Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

1111
node_modules/@ai-sdk/openai/CHANGELOG.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

13
node_modules/@ai-sdk/openai/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,13 @@
Copyright 2023 Vercel, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

36
node_modules/@ai-sdk/openai/README.md generated vendored Normal file
View File

@@ -0,0 +1,36 @@
# AI SDK - OpenAI Provider
The **[OpenAI provider](https://ai-sdk.dev/providers/ai-sdk-providers/openai)** for the [AI SDK](https://ai-sdk.dev/docs)
contains language model support for the OpenAI chat and completion APIs and embedding model support for the OpenAI embeddings API.
## Setup
The OpenAI provider is available in the `@ai-sdk/openai` module. You can install it with
```bash
npm i @ai-sdk/openai
```
## Provider Instance
You can import the default provider instance `openai` from `@ai-sdk/openai`:
```ts
import { openai } from '@ai-sdk/openai';
```
## Example
```ts
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
const { text } = await generateText({
model: openai('gpt-4-turbo'),
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});
```
## Documentation
Please check out the **[OpenAI provider documentation](https://ai-sdk.dev/providers/ai-sdk-providers/openai)** for more information.

342
node_modules/@ai-sdk/openai/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,342 @@
import { LanguageModelV1, ProviderV1, EmbeddingModelV1, ImageModelV1, TranscriptionModelV1, SpeechModelV1 } from '@ai-sdk/provider';
import { FetchFunction } from '@ai-sdk/provider-utils';
import { z } from 'zod';
type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
interface OpenAIChatSettings {
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
Whether to enable parallel function calling during tool use. Default to true.
*/
parallelToolCalls?: boolean;
/**
Whether to use structured outputs. Defaults to false.
When enabled, tool calls and object generation will be strict and follow the provided schema.
*/
structuredOutputs?: boolean;
/**
Whether to use legacy function calling. Defaults to false.
Required by some open source inference engines which do not support the `tools` API. May also
provide a workaround for `parallelToolCalls` resulting in the provider buffering tool calls,
which causes `streamObject` to be non-streaming.
Prefer setting `parallelToolCalls: false` over this option.
@deprecated this API is supported but deprecated by OpenAI.
*/
useLegacyFunctionCalling?: boolean;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
/**
Automatically download images and pass the image as data to the model.
OpenAI supports image URLs for public models, so this is only needed for
private models or when the images are not publicly accessible.
Defaults to `false`.
*/
downloadImages?: boolean;
/**
Simulates streaming by using a normal generate call and returning it as a stream.
Enable this if the model that you are using does not support streaming.
Defaults to `false`.
@deprecated Use `simulateStreamingMiddleware` instead.
*/
simulateStreaming?: boolean;
/**
Reasoning effort for reasoning models. Defaults to `medium`.
*/
reasoningEffort?: 'low' | 'medium' | 'high';
}
type OpenAICompletionModelId = 'gpt-3.5-turbo-instruct' | (string & {});
interface OpenAICompletionSettings {
/**
Echo back the prompt in addition to the completion.
*/
echo?: boolean;
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
The suffix that comes after a completion of inserted text.
*/
suffix?: string;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
type OpenAICompletionConfig = {
provider: string;
compatibility: 'strict' | 'compatible';
headers: () => Record<string, string | undefined>;
url: (options: {
modelId: string;
path: string;
}) => string;
fetch?: FetchFunction;
};
declare class OpenAICompletionLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode: undefined;
readonly modelId: OpenAICompletionModelId;
readonly settings: OpenAICompletionSettings;
private readonly config;
constructor(modelId: OpenAICompletionModelId, settings: OpenAICompletionSettings, config: OpenAICompletionConfig);
get provider(): string;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type OpenAIEmbeddingModelId = 'text-embedding-3-small' | 'text-embedding-3-large' | 'text-embedding-ada-002' | (string & {});
interface OpenAIEmbeddingSettings {
/**
Override the maximum number of embeddings per call.
*/
maxEmbeddingsPerCall?: number;
/**
Override the parallelism of embedding calls.
*/
supportsParallelCalls?: boolean;
/**
The number of dimensions the resulting output embeddings should have.
Only supported in text-embedding-3 and later models.
*/
dimensions?: number;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
type OpenAIImageModelId = 'gpt-image-1' | 'dall-e-3' | 'dall-e-2' | (string & {});
interface OpenAIImageSettings {
/**
Override the maximum number of images per call (default is dependent on the
model, or 1 for an unknown model).
*/
maxImagesPerCall?: number;
}
type OpenAITranscriptionModelId = 'whisper-1' | 'gpt-4o-mini-transcribe' | 'gpt-4o-transcribe' | (string & {});
type OpenAIResponsesModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
declare const WebSearchPreviewParameters: z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>;
declare function webSearchPreviewTool({ searchContextSize, userLocation, }?: {
searchContextSize?: 'low' | 'medium' | 'high';
userLocation?: {
type?: 'approximate';
city?: string;
region?: string;
country?: string;
timezone?: string;
};
}): {
type: 'provider-defined';
id: 'openai.web_search_preview';
args: {};
parameters: typeof WebSearchPreviewParameters;
};
declare const openaiTools: {
webSearchPreview: typeof webSearchPreviewTool;
};
type OpenAISpeechModelId = 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts' | (string & {});
interface OpenAIProvider extends ProviderV1 {
(modelId: 'gpt-3.5-turbo-instruct', settings?: OpenAICompletionSettings): OpenAICompletionLanguageModel;
(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): LanguageModelV1;
/**
Creates an OpenAI model for text generation.
*/
languageModel(modelId: 'gpt-3.5-turbo-instruct', settings?: OpenAICompletionSettings): OpenAICompletionLanguageModel;
languageModel(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): LanguageModelV1;
/**
Creates an OpenAI chat model for text generation.
*/
chat(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): LanguageModelV1;
/**
Creates an OpenAI responses API model for text generation.
*/
responses(modelId: OpenAIResponsesModelId): LanguageModelV1;
/**
Creates an OpenAI completion model for text generation.
*/
completion(modelId: OpenAICompletionModelId, settings?: OpenAICompletionSettings): LanguageModelV1;
/**
Creates a model for text embeddings.
*/
embedding(modelId: OpenAIEmbeddingModelId, settings?: OpenAIEmbeddingSettings): EmbeddingModelV1<string>;
/**
Creates a model for text embeddings.
@deprecated Use `textEmbeddingModel` instead.
*/
textEmbedding(modelId: OpenAIEmbeddingModelId, settings?: OpenAIEmbeddingSettings): EmbeddingModelV1<string>;
/**
Creates a model for text embeddings.
*/
textEmbeddingModel(modelId: OpenAIEmbeddingModelId, settings?: OpenAIEmbeddingSettings): EmbeddingModelV1<string>;
/**
Creates a model for image generation.
*/
image(modelId: OpenAIImageModelId, settings?: OpenAIImageSettings): ImageModelV1;
/**
Creates a model for image generation.
*/
imageModel(modelId: OpenAIImageModelId, settings?: OpenAIImageSettings): ImageModelV1;
/**
Creates a model for transcription.
*/
transcription(modelId: OpenAITranscriptionModelId): TranscriptionModelV1;
/**
Creates a model for speech generation.
*/
speech(modelId: OpenAISpeechModelId): SpeechModelV1;
/**
OpenAI-specific tools.
*/
tools: typeof openaiTools;
}
interface OpenAIProviderSettings {
/**
Base URL for the OpenAI API calls.
*/
baseURL?: string;
/**
API key for authenticating requests.
*/
apiKey?: string;
/**
OpenAI Organization.
*/
organization?: string;
/**
OpenAI project.
*/
project?: string;
/**
Custom headers to include in the requests.
*/
headers?: Record<string, string>;
/**
OpenAI compatibility mode. Should be set to `strict` when using the OpenAI API,
and `compatible` when using 3rd party providers. In `compatible` mode, newer
information such as streamOptions are not being sent. Defaults to 'compatible'.
*/
compatibility?: 'strict' | 'compatible';
/**
Provider name. Overrides the `openai` default name for 3rd party providers.
*/
name?: string;
/**
Custom fetch implementation. You can use it as a middleware to intercept requests,
or to provide a custom fetch implementation for e.g. testing.
*/
fetch?: FetchFunction;
}
/**
Create an OpenAI provider instance.
*/
declare function createOpenAI(options?: OpenAIProviderSettings): OpenAIProvider;
/**
Default OpenAI provider instance. It uses 'strict' compatibility mode.
*/
declare const openai: OpenAIProvider;
declare const openaiResponsesProviderOptionsSchema: z.ZodObject<{
metadata: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
parallelToolCalls: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
previousResponseId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
store: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
user: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningEffort: z.ZodOptional<z.ZodNullable<z.ZodString>>;
strictSchemas: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningSummary: z.ZodOptional<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
instructions?: string | null | undefined;
reasoningSummary?: string | null | undefined;
}, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
instructions?: string | null | undefined;
reasoningSummary?: string | null | undefined;
}>;
type OpenAIResponsesProviderOptions = z.infer<typeof openaiResponsesProviderOptionsSchema>;
export { type OpenAIProvider, type OpenAIProviderSettings, type OpenAIResponsesProviderOptions, createOpenAI, openai };

342
node_modules/@ai-sdk/openai/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,342 @@
import { LanguageModelV1, ProviderV1, EmbeddingModelV1, ImageModelV1, TranscriptionModelV1, SpeechModelV1 } from '@ai-sdk/provider';
import { FetchFunction } from '@ai-sdk/provider-utils';
import { z } from 'zod';
type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
interface OpenAIChatSettings {
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
Whether to enable parallel function calling during tool use. Default to true.
*/
parallelToolCalls?: boolean;
/**
Whether to use structured outputs. Defaults to false.
When enabled, tool calls and object generation will be strict and follow the provided schema.
*/
structuredOutputs?: boolean;
/**
Whether to use legacy function calling. Defaults to false.
Required by some open source inference engines which do not support the `tools` API. May also
provide a workaround for `parallelToolCalls` resulting in the provider buffering tool calls,
which causes `streamObject` to be non-streaming.
Prefer setting `parallelToolCalls: false` over this option.
@deprecated this API is supported but deprecated by OpenAI.
*/
useLegacyFunctionCalling?: boolean;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
/**
Automatically download images and pass the image as data to the model.
OpenAI supports image URLs for public models, so this is only needed for
private models or when the images are not publicly accessible.
Defaults to `false`.
*/
downloadImages?: boolean;
/**
Simulates streaming by using a normal generate call and returning it as a stream.
Enable this if the model that you are using does not support streaming.
Defaults to `false`.
@deprecated Use `simulateStreamingMiddleware` instead.
*/
simulateStreaming?: boolean;
/**
Reasoning effort for reasoning models. Defaults to `medium`.
*/
reasoningEffort?: 'low' | 'medium' | 'high';
}
type OpenAICompletionModelId = 'gpt-3.5-turbo-instruct' | (string & {});
interface OpenAICompletionSettings {
/**
Echo back the prompt in addition to the completion.
*/
echo?: boolean;
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
The suffix that comes after a completion of inserted text.
*/
suffix?: string;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
type OpenAICompletionConfig = {
provider: string;
compatibility: 'strict' | 'compatible';
headers: () => Record<string, string | undefined>;
url: (options: {
modelId: string;
path: string;
}) => string;
fetch?: FetchFunction;
};
declare class OpenAICompletionLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode: undefined;
readonly modelId: OpenAICompletionModelId;
readonly settings: OpenAICompletionSettings;
private readonly config;
constructor(modelId: OpenAICompletionModelId, settings: OpenAICompletionSettings, config: OpenAICompletionConfig);
get provider(): string;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type OpenAIEmbeddingModelId = 'text-embedding-3-small' | 'text-embedding-3-large' | 'text-embedding-ada-002' | (string & {});
interface OpenAIEmbeddingSettings {
/**
Override the maximum number of embeddings per call.
*/
maxEmbeddingsPerCall?: number;
/**
Override the parallelism of embedding calls.
*/
supportsParallelCalls?: boolean;
/**
The number of dimensions the resulting output embeddings should have.
Only supported in text-embedding-3 and later models.
*/
dimensions?: number;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
type OpenAIImageModelId = 'gpt-image-1' | 'dall-e-3' | 'dall-e-2' | (string & {});
interface OpenAIImageSettings {
/**
Override the maximum number of images per call (default is dependent on the
model, or 1 for an unknown model).
*/
maxImagesPerCall?: number;
}
type OpenAITranscriptionModelId = 'whisper-1' | 'gpt-4o-mini-transcribe' | 'gpt-4o-transcribe' | (string & {});
type OpenAIResponsesModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
declare const WebSearchPreviewParameters: z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>;
declare function webSearchPreviewTool({ searchContextSize, userLocation, }?: {
searchContextSize?: 'low' | 'medium' | 'high';
userLocation?: {
type?: 'approximate';
city?: string;
region?: string;
country?: string;
timezone?: string;
};
}): {
type: 'provider-defined';
id: 'openai.web_search_preview';
args: {};
parameters: typeof WebSearchPreviewParameters;
};
declare const openaiTools: {
webSearchPreview: typeof webSearchPreviewTool;
};
type OpenAISpeechModelId = 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts' | (string & {});
interface OpenAIProvider extends ProviderV1 {
(modelId: 'gpt-3.5-turbo-instruct', settings?: OpenAICompletionSettings): OpenAICompletionLanguageModel;
(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): LanguageModelV1;
/**
Creates an OpenAI model for text generation.
*/
languageModel(modelId: 'gpt-3.5-turbo-instruct', settings?: OpenAICompletionSettings): OpenAICompletionLanguageModel;
languageModel(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): LanguageModelV1;
/**
Creates an OpenAI chat model for text generation.
*/
chat(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): LanguageModelV1;
/**
Creates an OpenAI responses API model for text generation.
*/
responses(modelId: OpenAIResponsesModelId): LanguageModelV1;
/**
Creates an OpenAI completion model for text generation.
*/
completion(modelId: OpenAICompletionModelId, settings?: OpenAICompletionSettings): LanguageModelV1;
/**
Creates a model for text embeddings.
*/
embedding(modelId: OpenAIEmbeddingModelId, settings?: OpenAIEmbeddingSettings): EmbeddingModelV1<string>;
/**
Creates a model for text embeddings.
@deprecated Use `textEmbeddingModel` instead.
*/
textEmbedding(modelId: OpenAIEmbeddingModelId, settings?: OpenAIEmbeddingSettings): EmbeddingModelV1<string>;
/**
Creates a model for text embeddings.
*/
textEmbeddingModel(modelId: OpenAIEmbeddingModelId, settings?: OpenAIEmbeddingSettings): EmbeddingModelV1<string>;
/**
Creates a model for image generation.
*/
image(modelId: OpenAIImageModelId, settings?: OpenAIImageSettings): ImageModelV1;
/**
Creates a model for image generation.
*/
imageModel(modelId: OpenAIImageModelId, settings?: OpenAIImageSettings): ImageModelV1;
/**
Creates a model for transcription.
*/
transcription(modelId: OpenAITranscriptionModelId): TranscriptionModelV1;
/**
Creates a model for speech generation.
*/
speech(modelId: OpenAISpeechModelId): SpeechModelV1;
/**
OpenAI-specific tools.
*/
tools: typeof openaiTools;
}
interface OpenAIProviderSettings {
/**
Base URL for the OpenAI API calls.
*/
baseURL?: string;
/**
API key for authenticating requests.
*/
apiKey?: string;
/**
OpenAI Organization.
*/
organization?: string;
/**
OpenAI project.
*/
project?: string;
/**
Custom headers to include in the requests.
*/
headers?: Record<string, string>;
/**
OpenAI compatibility mode. Should be set to `strict` when using the OpenAI API,
and `compatible` when using 3rd party providers. In `compatible` mode, newer
information such as streamOptions are not being sent. Defaults to 'compatible'.
*/
compatibility?: 'strict' | 'compatible';
/**
Provider name. Overrides the `openai` default name for 3rd party providers.
*/
name?: string;
/**
Custom fetch implementation. You can use it as a middleware to intercept requests,
or to provide a custom fetch implementation for e.g. testing.
*/
fetch?: FetchFunction;
}
/**
Create an OpenAI provider instance.
*/
declare function createOpenAI(options?: OpenAIProviderSettings): OpenAIProvider;
/**
Default OpenAI provider instance. It uses 'strict' compatibility mode.
*/
declare const openai: OpenAIProvider;
declare const openaiResponsesProviderOptionsSchema: z.ZodObject<{
metadata: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
parallelToolCalls: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
previousResponseId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
store: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
user: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningEffort: z.ZodOptional<z.ZodNullable<z.ZodString>>;
strictSchemas: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningSummary: z.ZodOptional<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
instructions?: string | null | undefined;
reasoningSummary?: string | null | undefined;
}, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
instructions?: string | null | undefined;
reasoningSummary?: string | null | undefined;
}>;
type OpenAIResponsesProviderOptions = z.infer<typeof openaiResponsesProviderOptionsSchema>;
export { type OpenAIProvider, type OpenAIProviderSettings, type OpenAIResponsesProviderOptions, createOpenAI, openai };

2880
node_modules/@ai-sdk/openai/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@ai-sdk/openai/dist/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2913
node_modules/@ai-sdk/openai/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@ai-sdk/openai/dist/index.mjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

388
node_modules/@ai-sdk/openai/internal/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,388 @@
import { LanguageModelV1, EmbeddingModelV1, ImageModelV1, TranscriptionModelV1CallOptions, TranscriptionModelV1, SpeechModelV1 } from '@ai-sdk/provider';
import { FetchFunction } from '@ai-sdk/provider-utils';
import { z } from 'zod';
type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
interface OpenAIChatSettings {
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
Whether to enable parallel function calling during tool use. Default to true.
*/
parallelToolCalls?: boolean;
/**
Whether to use structured outputs. Defaults to false.
When enabled, tool calls and object generation will be strict and follow the provided schema.
*/
structuredOutputs?: boolean;
/**
Whether to use legacy function calling. Defaults to false.
Required by some open source inference engines which do not support the `tools` API. May also
provide a workaround for `parallelToolCalls` resulting in the provider buffering tool calls,
which causes `streamObject` to be non-streaming.
Prefer setting `parallelToolCalls: false` over this option.
@deprecated this API is supported but deprecated by OpenAI.
*/
useLegacyFunctionCalling?: boolean;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
/**
Automatically download images and pass the image as data to the model.
OpenAI supports image URLs for public models, so this is only needed for
private models or when the images are not publicly accessible.
Defaults to `false`.
*/
downloadImages?: boolean;
/**
Simulates streaming by using a normal generate call and returning it as a stream.
Enable this if the model that you are using does not support streaming.
Defaults to `false`.
@deprecated Use `simulateStreamingMiddleware` instead.
*/
simulateStreaming?: boolean;
/**
Reasoning effort for reasoning models. Defaults to `medium`.
*/
reasoningEffort?: 'low' | 'medium' | 'high';
}
type OpenAIChatConfig = {
provider: string;
compatibility: 'strict' | 'compatible';
headers: () => Record<string, string | undefined>;
url: (options: {
modelId: string;
path: string;
}) => string;
fetch?: FetchFunction;
};
declare class OpenAIChatLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly modelId: OpenAIChatModelId;
readonly settings: OpenAIChatSettings;
private readonly config;
constructor(modelId: OpenAIChatModelId, settings: OpenAIChatSettings, config: OpenAIChatConfig);
get supportsStructuredOutputs(): boolean;
get defaultObjectGenerationMode(): "tool" | "json";
get provider(): string;
get supportsImageUrls(): boolean;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type OpenAICompletionModelId = 'gpt-3.5-turbo-instruct' | (string & {});
interface OpenAICompletionSettings {
/**
Echo back the prompt in addition to the completion.
*/
echo?: boolean;
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
The suffix that comes after a completion of inserted text.
*/
suffix?: string;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
type OpenAICompletionConfig = {
provider: string;
compatibility: 'strict' | 'compatible';
headers: () => Record<string, string | undefined>;
url: (options: {
modelId: string;
path: string;
}) => string;
fetch?: FetchFunction;
};
declare class OpenAICompletionLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode: undefined;
readonly modelId: OpenAICompletionModelId;
readonly settings: OpenAICompletionSettings;
private readonly config;
constructor(modelId: OpenAICompletionModelId, settings: OpenAICompletionSettings, config: OpenAICompletionConfig);
get provider(): string;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type OpenAIConfig = {
provider: string;
url: (options: {
modelId: string;
path: string;
}) => string;
headers: () => Record<string, string | undefined>;
fetch?: FetchFunction;
generateId?: () => string;
};
type OpenAIEmbeddingModelId = 'text-embedding-3-small' | 'text-embedding-3-large' | 'text-embedding-ada-002' | (string & {});
interface OpenAIEmbeddingSettings {
/**
Override the maximum number of embeddings per call.
*/
maxEmbeddingsPerCall?: number;
/**
Override the parallelism of embedding calls.
*/
supportsParallelCalls?: boolean;
/**
The number of dimensions the resulting output embeddings should have.
Only supported in text-embedding-3 and later models.
*/
dimensions?: number;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
declare class OpenAIEmbeddingModel implements EmbeddingModelV1<string> {
readonly specificationVersion = "v1";
readonly modelId: OpenAIEmbeddingModelId;
private readonly config;
private readonly settings;
get provider(): string;
get maxEmbeddingsPerCall(): number;
get supportsParallelCalls(): boolean;
constructor(modelId: OpenAIEmbeddingModelId, settings: OpenAIEmbeddingSettings, config: OpenAIConfig);
doEmbed({ values, headers, abortSignal, }: Parameters<EmbeddingModelV1<string>['doEmbed']>[0]): Promise<Awaited<ReturnType<EmbeddingModelV1<string>['doEmbed']>>>;
}
type OpenAIImageModelId = 'gpt-image-1' | 'dall-e-3' | 'dall-e-2' | (string & {});
declare const modelMaxImagesPerCall: Record<OpenAIImageModelId, number>;
declare const hasDefaultResponseFormat: Set<string>;
interface OpenAIImageSettings {
/**
Override the maximum number of images per call (default is dependent on the
model, or 1 for an unknown model).
*/
maxImagesPerCall?: number;
}
interface OpenAIImageModelConfig extends OpenAIConfig {
_internal?: {
currentDate?: () => Date;
};
}
declare class OpenAIImageModel implements ImageModelV1 {
readonly modelId: OpenAIImageModelId;
private readonly settings;
private readonly config;
readonly specificationVersion = "v1";
get maxImagesPerCall(): number;
get provider(): string;
constructor(modelId: OpenAIImageModelId, settings: OpenAIImageSettings, config: OpenAIImageModelConfig);
doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, }: Parameters<ImageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<ImageModelV1['doGenerate']>>>;
}
type OpenAITranscriptionModelId = 'whisper-1' | 'gpt-4o-mini-transcribe' | 'gpt-4o-transcribe' | (string & {});
type OpenAITranscriptionModelOptions = {
/**
* Additional information to include in the transcription response.
*/
include?: string[];
/**
* The language of the input audio in ISO-639-1 format.
*/
language?: string;
/**
* An optional text to guide the model's style or continue a previous audio segment.
*/
prompt?: string;
/**
* The sampling temperature, between 0 and 1.
* @default 0
*/
temperature?: number;
/**
* The timestamp granularities to populate for this transcription.
* @default ['segment']
*/
timestamp_granularities?: Array<'word' | 'segment'>;
};
declare const openAIProviderOptionsSchema: z.ZodObject<{
include: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString, "many">>>;
language: z.ZodOptional<z.ZodNullable<z.ZodString>>;
prompt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
temperature: z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodNumber>>>;
timestampGranularities: z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodEnum<["word", "segment"]>, "many">>>>;
}, "strip", z.ZodTypeAny, {
temperature: number | null;
timestampGranularities: ("word" | "segment")[] | null;
prompt?: string | null | undefined;
include?: string[] | null | undefined;
language?: string | null | undefined;
}, {
prompt?: string | null | undefined;
temperature?: number | null | undefined;
include?: string[] | null | undefined;
language?: string | null | undefined;
timestampGranularities?: ("word" | "segment")[] | null | undefined;
}>;
type OpenAITranscriptionCallOptions = Omit<TranscriptionModelV1CallOptions, 'providerOptions'> & {
providerOptions?: {
openai?: z.infer<typeof openAIProviderOptionsSchema>;
};
};
interface OpenAITranscriptionModelConfig extends OpenAIConfig {
_internal?: {
currentDate?: () => Date;
};
}
declare class OpenAITranscriptionModel implements TranscriptionModelV1 {
readonly modelId: OpenAITranscriptionModelId;
private readonly config;
readonly specificationVersion = "v1";
get provider(): string;
constructor(modelId: OpenAITranscriptionModelId, config: OpenAITranscriptionModelConfig);
private getArgs;
doGenerate(options: OpenAITranscriptionCallOptions): Promise<Awaited<ReturnType<TranscriptionModelV1['doGenerate']>>>;
}
type OpenAISpeechModelId = 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts' | (string & {});
declare const OpenAIProviderOptionsSchema: z.ZodObject<{
instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;
speed: z.ZodOptional<z.ZodNullable<z.ZodDefault<z.ZodNumber>>>;
}, "strip", z.ZodTypeAny, {
instructions?: string | null | undefined;
speed?: number | null | undefined;
}, {
instructions?: string | null | undefined;
speed?: number | null | undefined;
}>;
type OpenAISpeechCallOptions = z.infer<typeof OpenAIProviderOptionsSchema>;
interface OpenAISpeechModelConfig extends OpenAIConfig {
_internal?: {
currentDate?: () => Date;
};
}
declare class OpenAISpeechModel implements SpeechModelV1 {
readonly modelId: OpenAISpeechModelId;
private readonly config;
readonly specificationVersion = "v1";
get provider(): string;
constructor(modelId: OpenAISpeechModelId, config: OpenAISpeechModelConfig);
private getArgs;
doGenerate(options: Parameters<SpeechModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<SpeechModelV1['doGenerate']>>>;
}
type OpenAIResponsesModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
declare class OpenAIResponsesLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode = "json";
readonly supportsStructuredOutputs = true;
readonly modelId: OpenAIResponsesModelId;
private readonly config;
constructor(modelId: OpenAIResponsesModelId, config: OpenAIConfig);
get provider(): string;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
declare const openaiResponsesProviderOptionsSchema: z.ZodObject<{
metadata: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
parallelToolCalls: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
previousResponseId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
store: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
user: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningEffort: z.ZodOptional<z.ZodNullable<z.ZodString>>;
strictSchemas: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningSummary: z.ZodOptional<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
instructions?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
reasoningSummary?: string | null | undefined;
}, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
instructions?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
reasoningSummary?: string | null | undefined;
}>;
type OpenAIResponsesProviderOptions = z.infer<typeof openaiResponsesProviderOptionsSchema>;
export { OpenAIChatLanguageModel, type OpenAIChatModelId, type OpenAIChatSettings, OpenAICompletionLanguageModel, type OpenAICompletionModelId, type OpenAICompletionSettings, OpenAIEmbeddingModel, type OpenAIEmbeddingModelId, type OpenAIEmbeddingSettings, OpenAIImageModel, type OpenAIImageModelId, type OpenAIImageSettings, OpenAIResponsesLanguageModel, type OpenAIResponsesProviderOptions, type OpenAISpeechCallOptions, OpenAISpeechModel, type OpenAISpeechModelId, type OpenAITranscriptionCallOptions, OpenAITranscriptionModel, type OpenAITranscriptionModelId, type OpenAITranscriptionModelOptions, hasDefaultResponseFormat, modelMaxImagesPerCall };

388
node_modules/@ai-sdk/openai/internal/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,388 @@
import { LanguageModelV1, EmbeddingModelV1, ImageModelV1, TranscriptionModelV1CallOptions, TranscriptionModelV1, SpeechModelV1 } from '@ai-sdk/provider';
import { FetchFunction } from '@ai-sdk/provider-utils';
import { z } from 'zod';
type OpenAIChatModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
interface OpenAIChatSettings {
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
Whether to enable parallel function calling during tool use. Default to true.
*/
parallelToolCalls?: boolean;
/**
Whether to use structured outputs. Defaults to false.
When enabled, tool calls and object generation will be strict and follow the provided schema.
*/
structuredOutputs?: boolean;
/**
Whether to use legacy function calling. Defaults to false.
Required by some open source inference engines which do not support the `tools` API. May also
provide a workaround for `parallelToolCalls` resulting in the provider buffering tool calls,
which causes `streamObject` to be non-streaming.
Prefer setting `parallelToolCalls: false` over this option.
@deprecated this API is supported but deprecated by OpenAI.
*/
useLegacyFunctionCalling?: boolean;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
/**
Automatically download images and pass the image as data to the model.
OpenAI supports image URLs for public models, so this is only needed for
private models or when the images are not publicly accessible.
Defaults to `false`.
*/
downloadImages?: boolean;
/**
Simulates streaming by using a normal generate call and returning it as a stream.
Enable this if the model that you are using does not support streaming.
Defaults to `false`.
@deprecated Use `simulateStreamingMiddleware` instead.
*/
simulateStreaming?: boolean;
/**
Reasoning effort for reasoning models. Defaults to `medium`.
*/
reasoningEffort?: 'low' | 'medium' | 'high';
}
type OpenAIChatConfig = {
provider: string;
compatibility: 'strict' | 'compatible';
headers: () => Record<string, string | undefined>;
url: (options: {
modelId: string;
path: string;
}) => string;
fetch?: FetchFunction;
};
declare class OpenAIChatLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly modelId: OpenAIChatModelId;
readonly settings: OpenAIChatSettings;
private readonly config;
constructor(modelId: OpenAIChatModelId, settings: OpenAIChatSettings, config: OpenAIChatConfig);
get supportsStructuredOutputs(): boolean;
get defaultObjectGenerationMode(): "tool" | "json";
get provider(): string;
get supportsImageUrls(): boolean;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type OpenAICompletionModelId = 'gpt-3.5-turbo-instruct' | (string & {});
interface OpenAICompletionSettings {
/**
Echo back the prompt in addition to the completion.
*/
echo?: boolean;
/**
Modify the likelihood of specified tokens appearing in the completion.
Accepts a JSON object that maps tokens (specified by their token ID in
the GPT tokenizer) to an associated bias value from -100 to 100. You
can use this tokenizer tool to convert text to token IDs. Mathematically,
the bias is added to the logits generated by the model prior to sampling.
The exact effect will vary per model, but values between -1 and 1 should
decrease or increase likelihood of selection; values like -100 or 100
should result in a ban or exclusive selection of the relevant token.
As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
token from being generated.
*/
logitBias?: Record<number, number>;
/**
Return the log probabilities of the tokens. Including logprobs will increase
the response size and can slow down response times. However, it can
be useful to better understand how the model is behaving.
Setting to true will return the log probabilities of the tokens that
were generated.
Setting to a number will return the log probabilities of the top n
tokens that were generated.
*/
logprobs?: boolean | number;
/**
The suffix that comes after a completion of inserted text.
*/
suffix?: string;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
type OpenAICompletionConfig = {
provider: string;
compatibility: 'strict' | 'compatible';
headers: () => Record<string, string | undefined>;
url: (options: {
modelId: string;
path: string;
}) => string;
fetch?: FetchFunction;
};
declare class OpenAICompletionLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode: undefined;
readonly modelId: OpenAICompletionModelId;
readonly settings: OpenAICompletionSettings;
private readonly config;
constructor(modelId: OpenAICompletionModelId, settings: OpenAICompletionSettings, config: OpenAICompletionConfig);
get provider(): string;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type OpenAIConfig = {
provider: string;
url: (options: {
modelId: string;
path: string;
}) => string;
headers: () => Record<string, string | undefined>;
fetch?: FetchFunction;
generateId?: () => string;
};
type OpenAIEmbeddingModelId = 'text-embedding-3-small' | 'text-embedding-3-large' | 'text-embedding-ada-002' | (string & {});
interface OpenAIEmbeddingSettings {
/**
Override the maximum number of embeddings per call.
*/
maxEmbeddingsPerCall?: number;
/**
Override the parallelism of embedding calls.
*/
supportsParallelCalls?: boolean;
/**
The number of dimensions the resulting output embeddings should have.
Only supported in text-embedding-3 and later models.
*/
dimensions?: number;
/**
A unique identifier representing your end-user, which can help OpenAI to
monitor and detect abuse. Learn more.
*/
user?: string;
}
declare class OpenAIEmbeddingModel implements EmbeddingModelV1<string> {
readonly specificationVersion = "v1";
readonly modelId: OpenAIEmbeddingModelId;
private readonly config;
private readonly settings;
get provider(): string;
get maxEmbeddingsPerCall(): number;
get supportsParallelCalls(): boolean;
constructor(modelId: OpenAIEmbeddingModelId, settings: OpenAIEmbeddingSettings, config: OpenAIConfig);
doEmbed({ values, headers, abortSignal, }: Parameters<EmbeddingModelV1<string>['doEmbed']>[0]): Promise<Awaited<ReturnType<EmbeddingModelV1<string>['doEmbed']>>>;
}
type OpenAIImageModelId = 'gpt-image-1' | 'dall-e-3' | 'dall-e-2' | (string & {});
declare const modelMaxImagesPerCall: Record<OpenAIImageModelId, number>;
declare const hasDefaultResponseFormat: Set<string>;
interface OpenAIImageSettings {
/**
Override the maximum number of images per call (default is dependent on the
model, or 1 for an unknown model).
*/
maxImagesPerCall?: number;
}
interface OpenAIImageModelConfig extends OpenAIConfig {
_internal?: {
currentDate?: () => Date;
};
}
declare class OpenAIImageModel implements ImageModelV1 {
readonly modelId: OpenAIImageModelId;
private readonly settings;
private readonly config;
readonly specificationVersion = "v1";
get maxImagesPerCall(): number;
get provider(): string;
constructor(modelId: OpenAIImageModelId, settings: OpenAIImageSettings, config: OpenAIImageModelConfig);
doGenerate({ prompt, n, size, aspectRatio, seed, providerOptions, headers, abortSignal, }: Parameters<ImageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<ImageModelV1['doGenerate']>>>;
}
type OpenAITranscriptionModelId = 'whisper-1' | 'gpt-4o-mini-transcribe' | 'gpt-4o-transcribe' | (string & {});
type OpenAITranscriptionModelOptions = {
/**
* Additional information to include in the transcription response.
*/
include?: string[];
/**
* The language of the input audio in ISO-639-1 format.
*/
language?: string;
/**
* An optional text to guide the model's style or continue a previous audio segment.
*/
prompt?: string;
/**
* The sampling temperature, between 0 and 1.
* @default 0
*/
temperature?: number;
/**
* The timestamp granularities to populate for this transcription.
* @default ['segment']
*/
timestamp_granularities?: Array<'word' | 'segment'>;
};
declare const openAIProviderOptionsSchema: z.ZodObject<{
include: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodString, "many">>>;
language: z.ZodOptional<z.ZodNullable<z.ZodString>>;
prompt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
temperature: z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodNumber>>>;
timestampGranularities: z.ZodDefault<z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodEnum<["word", "segment"]>, "many">>>>;
}, "strip", z.ZodTypeAny, {
temperature: number | null;
timestampGranularities: ("word" | "segment")[] | null;
prompt?: string | null | undefined;
include?: string[] | null | undefined;
language?: string | null | undefined;
}, {
prompt?: string | null | undefined;
temperature?: number | null | undefined;
include?: string[] | null | undefined;
language?: string | null | undefined;
timestampGranularities?: ("word" | "segment")[] | null | undefined;
}>;
type OpenAITranscriptionCallOptions = Omit<TranscriptionModelV1CallOptions, 'providerOptions'> & {
providerOptions?: {
openai?: z.infer<typeof openAIProviderOptionsSchema>;
};
};
interface OpenAITranscriptionModelConfig extends OpenAIConfig {
_internal?: {
currentDate?: () => Date;
};
}
declare class OpenAITranscriptionModel implements TranscriptionModelV1 {
readonly modelId: OpenAITranscriptionModelId;
private readonly config;
readonly specificationVersion = "v1";
get provider(): string;
constructor(modelId: OpenAITranscriptionModelId, config: OpenAITranscriptionModelConfig);
private getArgs;
doGenerate(options: OpenAITranscriptionCallOptions): Promise<Awaited<ReturnType<TranscriptionModelV1['doGenerate']>>>;
}
type OpenAISpeechModelId = 'tts-1' | 'tts-1-hd' | 'gpt-4o-mini-tts' | (string & {});
declare const OpenAIProviderOptionsSchema: z.ZodObject<{
instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;
speed: z.ZodOptional<z.ZodNullable<z.ZodDefault<z.ZodNumber>>>;
}, "strip", z.ZodTypeAny, {
instructions?: string | null | undefined;
speed?: number | null | undefined;
}, {
instructions?: string | null | undefined;
speed?: number | null | undefined;
}>;
type OpenAISpeechCallOptions = z.infer<typeof OpenAIProviderOptionsSchema>;
interface OpenAISpeechModelConfig extends OpenAIConfig {
_internal?: {
currentDate?: () => Date;
};
}
declare class OpenAISpeechModel implements SpeechModelV1 {
readonly modelId: OpenAISpeechModelId;
private readonly config;
readonly specificationVersion = "v1";
get provider(): string;
constructor(modelId: OpenAISpeechModelId, config: OpenAISpeechModelConfig);
private getArgs;
doGenerate(options: Parameters<SpeechModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<SpeechModelV1['doGenerate']>>>;
}
type OpenAIResponsesModelId = 'o1' | 'o1-2024-12-17' | 'o1-mini' | 'o1-mini-2024-09-12' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o3-mini' | 'o3-mini-2025-01-31' | 'o3' | 'o3-2025-04-16' | 'o4-mini' | 'o4-mini-2025-04-16' | 'gpt-5' | 'gpt-5-2025-08-07' | 'gpt-5-mini' | 'gpt-5-mini-2025-08-07' | 'gpt-5-nano' | 'gpt-5-nano-2025-08-07' | 'gpt-5-chat-latest' | 'gpt-4.1' | 'gpt-4.1-2025-04-14' | 'gpt-4.1-mini' | 'gpt-4.1-mini-2025-04-14' | 'gpt-4.1-nano' | 'gpt-4.1-nano-2025-04-14' | 'gpt-4o' | 'gpt-4o-2024-05-13' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-11-20' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-search-preview' | 'gpt-4o-search-preview-2025-03-11' | 'gpt-4o-mini-search-preview' | 'gpt-4o-mini-search-preview-2025-03-11' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-turbo-preview' | 'gpt-4-0125-preview' | 'gpt-4-1106-preview' | 'gpt-4' | 'gpt-4-0613' | 'gpt-4.5-preview' | 'gpt-4.5-preview-2025-02-27' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-1106' | 'chatgpt-4o-latest' | (string & {});
declare class OpenAIResponsesLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode = "json";
readonly supportsStructuredOutputs = true;
readonly modelId: OpenAIResponsesModelId;
private readonly config;
constructor(modelId: OpenAIResponsesModelId, config: OpenAIConfig);
get provider(): string;
private getArgs;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
declare const openaiResponsesProviderOptionsSchema: z.ZodObject<{
metadata: z.ZodOptional<z.ZodNullable<z.ZodAny>>;
parallelToolCalls: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
previousResponseId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
store: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
user: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningEffort: z.ZodOptional<z.ZodNullable<z.ZodString>>;
strictSchemas: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
instructions: z.ZodOptional<z.ZodNullable<z.ZodString>>;
reasoningSummary: z.ZodOptional<z.ZodNullable<z.ZodString>>;
}, "strip", z.ZodTypeAny, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
instructions?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
reasoningSummary?: string | null | undefined;
}, {
user?: string | null | undefined;
store?: boolean | null | undefined;
metadata?: any;
reasoningEffort?: string | null | undefined;
instructions?: string | null | undefined;
parallelToolCalls?: boolean | null | undefined;
previousResponseId?: string | null | undefined;
strictSchemas?: boolean | null | undefined;
reasoningSummary?: string | null | undefined;
}>;
type OpenAIResponsesProviderOptions = z.infer<typeof openaiResponsesProviderOptionsSchema>;
export { OpenAIChatLanguageModel, type OpenAIChatModelId, type OpenAIChatSettings, OpenAICompletionLanguageModel, type OpenAICompletionModelId, type OpenAICompletionSettings, OpenAIEmbeddingModel, type OpenAIEmbeddingModelId, type OpenAIEmbeddingSettings, OpenAIImageModel, type OpenAIImageModelId, type OpenAIImageSettings, OpenAIResponsesLanguageModel, type OpenAIResponsesProviderOptions, type OpenAISpeechCallOptions, OpenAISpeechModel, type OpenAISpeechModelId, type OpenAITranscriptionCallOptions, OpenAITranscriptionModel, type OpenAITranscriptionModelId, type OpenAITranscriptionModelOptions, hasDefaultResponseFormat, modelMaxImagesPerCall };

2770
node_modules/@ai-sdk/openai/internal/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

2793
node_modules/@ai-sdk/openai/internal/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,565 @@
# @ai-sdk/provider-utils
## 2.2.8
### Patch Changes
- d87b9d1: fix(provider-utils): fix SSE parser bug (CRLF)
## 2.2.7
### Patch Changes
- Updated dependencies [beef951]
- @ai-sdk/provider@1.1.3
## 2.2.6
### Patch Changes
- Updated dependencies [013faa8]
- @ai-sdk/provider@1.1.2
## 2.2.5
### Patch Changes
- c21fa6d: feat: add transcription with experimental_transcribe
- Updated dependencies [c21fa6d]
- @ai-sdk/provider@1.1.1
## 2.2.4
### Patch Changes
- 2c19b9a: feat(provider-utils): add TestServerCall#requestCredentials
## 2.2.3
### Patch Changes
- 28be004: chore (provider-utils): add error method to TestStreamController
## 2.2.2
### Patch Changes
- b01120e: chore (provider-utils): update unified test server
## 2.2.1
### Patch Changes
- f10f0fa: fix (provider-utils): improve event source stream parsing performance
## 2.2.0
### Minor Changes
- 5bc638d: AI SDK 4.2
### Patch Changes
- Updated dependencies [5bc638d]
- @ai-sdk/provider@1.1.0
## 2.1.15
### Patch Changes
- d0c4659: feat (provider-utils): parseProviderOptions function
## 2.1.14
### Patch Changes
- Updated dependencies [0bd5bc6]
- @ai-sdk/provider@1.0.12
## 2.1.13
### Patch Changes
- Updated dependencies [2e1101a]
- @ai-sdk/provider@1.0.11
## 2.1.12
### Patch Changes
- 1531959: feat (provider-utils): add readable-stream to unified test server
## 2.1.11
### Patch Changes
- Updated dependencies [e1d3d42]
- @ai-sdk/provider@1.0.10
## 2.1.10
### Patch Changes
- Updated dependencies [ddf9740]
- @ai-sdk/provider@1.0.9
## 2.1.9
### Patch Changes
- Updated dependencies [2761f06]
- @ai-sdk/provider@1.0.8
## 2.1.8
### Patch Changes
- 2e898b4: chore (ai): move mockId test helper into provider utils
## 2.1.7
### Patch Changes
- 3ff4ef8: feat (provider-utils): export removeUndefinedEntries for working with e.g. headers
## 2.1.6
### Patch Changes
- Updated dependencies [d89c3b9]
- @ai-sdk/provider@1.0.7
## 2.1.5
### Patch Changes
- 3a602ca: chore (core): rename CoreTool to Tool
## 2.1.4
### Patch Changes
- 066206e: feat (provider-utils): move delay to provider-utils from ai
## 2.1.3
### Patch Changes
- 39e5c1f: feat (provider-utils): add getFromApi and response handlers for binary responses and status-code errors
## 2.1.2
### Patch Changes
- ed012d2: feat (provider): add metadata extraction mechanism to openai-compatible providers
- Updated dependencies [3a58a2e]
- @ai-sdk/provider@1.0.6
## 2.1.1
### Patch Changes
- e7a9ec9: feat (provider-utils): include raw value in json parse results
- Updated dependencies [0a699f1]
- @ai-sdk/provider@1.0.5
## 2.1.0
### Minor Changes
- 62ba5ad: release: AI SDK 4.1
## 2.0.8
### Patch Changes
- 00114c5: feat: expose IDGenerator and createIdGenerator
## 2.0.7
### Patch Changes
- 90fb95a: chore (provider-utils): switch to unified test server
- e6dfef4: feat (provider/fireworks): Support add'l image models.
- 6636db6: feat (provider-utils): add unified test server
## 2.0.6
### Patch Changes
- 19a2ce7: feat (provider/fireworks): Add image model support.
- 6337688: feat: change image generation errors to warnings
- Updated dependencies [19a2ce7]
- Updated dependencies [6337688]
- @ai-sdk/provider@1.0.4
## 2.0.5
### Patch Changes
- 5ed5e45: chore (config): Use ts-library.json tsconfig for no-UI libs.
- Updated dependencies [5ed5e45]
- @ai-sdk/provider@1.0.3
## 2.0.4
### Patch Changes
- Updated dependencies [09a9cab]
- @ai-sdk/provider@1.0.2
## 2.0.3
### Patch Changes
- 0984f0b: feat (provider-utils): Add resolvable type and utility routine.
## 2.0.2
### Patch Changes
- Updated dependencies [b446ae5]
- @ai-sdk/provider@1.0.1
## 2.0.1
### Patch Changes
- c3ab5de: fix (provider-utils): downgrade nanoid and secure-json-parse (ESM compatibility)
## 2.0.0
### Major Changes
- b469a7e: chore: remove isXXXError methods
- b1da952: chore (provider-utils): remove convertStreamToArray
- 8426f55: chore (ai):increase id generator default size from 7 to 16.
- db46ce5: chore (provider-utils): remove isParseableJson export
### Patch Changes
- dce4158: chore (dependencies): update eventsource-parser to 3.0.0
- dce4158: chore (dependencies): update nanoid to 5.0.8
- Updated dependencies [b469a7e]
- Updated dependencies [c0ddc24]
- @ai-sdk/provider@1.0.0
## 2.0.0-canary.3
### Major Changes
- 8426f55: chore (ai):increase id generator default size from 7 to 16.
## 2.0.0-canary.2
### Patch Changes
- dce4158: chore (dependencies): update eventsource-parser to 3.0.0
- dce4158: chore (dependencies): update nanoid to 5.0.8
## 2.0.0-canary.1
### Major Changes
- b1da952: chore (provider-utils): remove convertStreamToArray
## 2.0.0-canary.0
### Major Changes
- b469a7e: chore: remove isXXXError methods
- db46ce5: chore (provider-utils): remove isParseableJson export
### Patch Changes
- Updated dependencies [b469a7e]
- Updated dependencies [c0ddc24]
- @ai-sdk/provider@1.0.0-canary.0
## 1.0.22
### Patch Changes
- aa98cdb: chore: more flexible dependency versioning
- 7b937c5: feat (provider-utils): improve id generator robustness
- 811a317: feat (ai/core): multi-part tool results (incl. images)
- Updated dependencies [aa98cdb]
- Updated dependencies [1486128]
- Updated dependencies [7b937c5]
- Updated dependencies [3b1b69a]
- Updated dependencies [811a317]
- @ai-sdk/provider@0.0.26
## 1.0.21
### Patch Changes
- Updated dependencies [b9b0d7b]
- @ai-sdk/provider@0.0.25
## 1.0.20
### Patch Changes
- Updated dependencies [d595d0d]
- @ai-sdk/provider@0.0.24
## 1.0.19
### Patch Changes
- 273f696: fix (ai/provider-utils): expose size argument in generateId
## 1.0.18
### Patch Changes
- 03313cd: feat (ai): expose response id, response model, response timestamp in telemetry and api
- Updated dependencies [03313cd]
- Updated dependencies [3be7c1c]
- @ai-sdk/provider@0.0.23
## 1.0.17
### Patch Changes
- Updated dependencies [26515cb]
- @ai-sdk/provider@0.0.22
## 1.0.16
### Patch Changes
- 09f895f: feat (ai/core): no-schema output for generateObject / streamObject
## 1.0.15
### Patch Changes
- d67fa9c: feat (provider/amazon-bedrock): add support for session tokens
## 1.0.14
### Patch Changes
- Updated dependencies [f2c025e]
- @ai-sdk/provider@0.0.21
## 1.0.13
### Patch Changes
- Updated dependencies [6ac355e]
- @ai-sdk/provider@0.0.20
## 1.0.12
### Patch Changes
- dd712ac: fix: use FetchFunction type to prevent self-reference
## 1.0.11
### Patch Changes
- Updated dependencies [dd4a0f5]
- @ai-sdk/provider@0.0.19
## 1.0.10
### Patch Changes
- 4bd27a9: chore (ai/provider): refactor type validation
- 845754b: fix (ai/provider): fix atob/btoa execution on cloudflare edge workers
- Updated dependencies [4bd27a9]
- @ai-sdk/provider@0.0.18
## 1.0.9
### Patch Changes
- Updated dependencies [029af4c]
- @ai-sdk/provider@0.0.17
## 1.0.8
### Patch Changes
- Updated dependencies [d58517b]
- @ai-sdk/provider@0.0.16
## 1.0.7
### Patch Changes
- Updated dependencies [96aed25]
- @ai-sdk/provider@0.0.15
## 1.0.6
### Patch Changes
- 9614584: fix (ai/core): use Symbol.for
- 0762a22: feat (ai/core): support zod transformers in generateObject & streamObject
## 1.0.5
### Patch Changes
- a8d1c9e9: feat (ai/core): parallel image download
- Updated dependencies [a8d1c9e9]
- @ai-sdk/provider@0.0.14
## 1.0.4
### Patch Changes
- 4f88248f: feat (core): support json schema
## 1.0.3
### Patch Changes
- Updated dependencies [2b9da0f0]
- Updated dependencies [a5b58845]
- Updated dependencies [4aa8deb3]
- Updated dependencies [13b27ec6]
- @ai-sdk/provider@0.0.13
## 1.0.2
### Patch Changes
- Updated dependencies [b7290943]
- @ai-sdk/provider@0.0.12
## 1.0.1
### Patch Changes
- d481729f: fix (ai/provider-utils): generalize to Error (DomException not always available)
## 1.0.0
### Major Changes
- 5edc6110: feat (provider-utils): change getRequestHeader() test helper to return Record (breaking change)
### Patch Changes
- 5edc6110: feat (provider-utils): add combineHeaders helper
- Updated dependencies [5edc6110]
- @ai-sdk/provider@0.0.11
## 0.0.16
### Patch Changes
- 02f6a088: feat (provider-utils): add convertArrayToAsyncIterable test helper
## 0.0.15
### Patch Changes
- 85712895: feat (@ai-sdk/provider-utils): add createJsonStreamResponseHandler
- 85712895: chore (@ai-sdk/provider-utils): move test helper to provider utils
## 0.0.14
### Patch Changes
- 7910ae84: feat (providers): support custom fetch implementations
## 0.0.13
### Patch Changes
- Updated dependencies [102ca22f]
- @ai-sdk/provider@0.0.10
## 0.0.12
### Patch Changes
- 09295e2e: feat (@ai-sdk/provider-utils): add download helper
- 043a5de2: fix (provider-utils): rename to isParsableJson
- Updated dependencies [09295e2e]
- @ai-sdk/provider@0.0.9
## 0.0.11
### Patch Changes
- Updated dependencies [f39c0dd2]
- @ai-sdk/provider@0.0.8
## 0.0.10
### Patch Changes
- Updated dependencies [8e780288]
- @ai-sdk/provider@0.0.7
## 0.0.9
### Patch Changes
- 6a50ac4: feat (provider-utils): add loadSetting and convertAsyncGeneratorToReadableStream helpers
- Updated dependencies [6a50ac4]
- @ai-sdk/provider@0.0.6
## 0.0.8
### Patch Changes
- Updated dependencies [0f6bc4e]
- @ai-sdk/provider@0.0.5
## 0.0.7
### Patch Changes
- Updated dependencies [325ca55]
- @ai-sdk/provider@0.0.4
## 0.0.6
### Patch Changes
- 276f22b: fix (ai/provider): improve request error handling
## 0.0.5
### Patch Changes
- Updated dependencies [41d5736]
- @ai-sdk/provider@0.0.3
## 0.0.4
### Patch Changes
- 56ef84a: ai/core: fix abort handling in transformation stream
## 0.0.3
### Patch Changes
- 25f3350: ai/core: add support for getting raw response headers.
- Updated dependencies [d6431ae]
- Updated dependencies [25f3350]
- @ai-sdk/provider@0.0.2
## 0.0.2
### Patch Changes
- eb150a6: ai/core: remove scaling of setting values (breaking change). If you were using the temperature, frequency penalty, or presence penalty settings, you need to update the providers and adjust the setting values.
- Updated dependencies [eb150a6]
- @ai-sdk/provider@0.0.1
## 0.0.1
### Patch Changes
- 7b8791d: Rename baseUrl to baseURL. Automatically remove trailing slashes.

View File

@@ -0,0 +1,13 @@
Copyright 2023 Vercel, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1 @@
# AI SDK - Provider Implementation Utilities

View File

@@ -0,0 +1,379 @@
import { JSONValue, JSONParseError, TypeValidationError, APICallError } from '@ai-sdk/provider';
import { z, ZodSchema } from 'zod';
declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
/**
* Converts an AsyncIterator to a ReadableStream.
*
* @template T - The type of elements produced by the AsyncIterator.
* @param { <T>} iterator - The AsyncIterator to convert.
* @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.
*/
declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
/**
* Creates a Promise that resolves after a specified delay
* @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.
* @returns A Promise that resolves after the specified delay
*/
declare function delay(delayInMs?: number | null): Promise<void>;
type EventSourceChunk = {
event: string | undefined;
data: string;
id?: string;
retry?: number;
};
declare function createEventSourceParserStream(): TransformStream<string, EventSourceChunk>;
/**
Extracts the headers from a response object and returns them as a key-value object.
@param response - The response object to extract headers from.
@returns The headers as a key-value object.
*/
declare function extractResponseHeaders(response: Response): Record<string, string>;
/**
* Fetch function type (standardizes the version of fetch used).
*/
type FetchFunction = typeof globalThis.fetch;
/**
Creates an ID generator.
The total length of the ID is the sum of the prefix, separator, and random part length.
Non-secure.
@param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
@param prefix - The prefix of the ID to generate. Default: ''.
@param separator - The separator between the prefix and the random part of the ID. Default: '-'.
@param size - The size of the random part of the ID to generate. Default: 16.
*/
declare const createIdGenerator: ({ prefix, size: defaultSize, alphabet, separator, }?: {
prefix?: string;
separator?: string;
size?: number;
alphabet?: string;
}) => ((size?: number) => string);
/**
A function that generates an ID.
*/
type IDGenerator = () => string;
/**
Generates a 16-character random string to use for IDs. Not secure.
@param size - The size of the ID to generate. Default: 16.
*/
declare const generateId: (size?: number) => string;
declare function getErrorMessage(error: unknown | undefined): string;
/**
* Used to mark validator functions so we can support both Zod and custom schemas.
*/
declare const validatorSymbol: unique symbol;
type ValidationResult<OBJECT> = {
success: true;
value: OBJECT;
} | {
success: false;
error: Error;
};
type Validator<OBJECT = unknown> = {
/**
* Used to mark validator functions so we can support both Zod and custom schemas.
*/
[validatorSymbol]: true;
/**
* Optional. Validates that the structure of a value matches this schema,
* and returns a typed version of the value if it does.
*/
readonly validate?: (value: unknown) => ValidationResult<OBJECT>;
};
/**
* Create a validator.
*
* @param validate A validation function for the schema.
*/
declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT>)): Validator<OBJECT>;
declare function isValidator(value: unknown): value is Validator;
declare function asValidator<OBJECT>(value: Validator<OBJECT> | z.Schema<OBJECT, z.ZodTypeDef, any>): Validator<OBJECT>;
declare function zodValidator<OBJECT>(zodSchema: z.Schema<OBJECT, z.ZodTypeDef, any>): Validator<OBJECT>;
/**
* Parses a JSON string into an unknown object.
*
* @param text - The JSON string to parse.
* @returns {JSONValue} - The parsed JSON object.
*/
declare function parseJSON(options: {
text: string;
schema?: undefined;
}): JSONValue;
/**
* Parses a JSON string into a strongly-typed object using the provided schema.
*
* @template T - The type of the object to parse the JSON into.
* @param {string} text - The JSON string to parse.
* @param {Validator<T>} schema - The schema to use for parsing the JSON.
* @returns {T} - The parsed object.
*/
declare function parseJSON<T>(options: {
text: string;
schema: ZodSchema<T> | Validator<T>;
}): T;
type ParseResult<T> = {
success: true;
value: T;
rawValue: unknown;
} | {
success: false;
error: JSONParseError | TypeValidationError;
};
/**
* Safely parses a JSON string and returns the result as an object of type `unknown`.
*
* @param text - The JSON string to parse.
* @returns {object} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
*/
declare function safeParseJSON(options: {
text: string;
schema?: undefined;
}): ParseResult<JSONValue>;
/**
* Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
*
* @template T - The type of the object to parse the JSON into.
* @param {string} text - The JSON string to parse.
* @param {Validator<T>} schema - The schema to use for parsing the JSON.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
declare function safeParseJSON<T>(options: {
text: string;
schema: ZodSchema<T> | Validator<T>;
}): ParseResult<T>;
declare function isParsableJson(input: string): boolean;
type ResponseHandler<RETURN_TYPE> = (options: {
url: string;
requestBodyValues: unknown;
response: Response;
}) => PromiseLike<{
value: RETURN_TYPE;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
errorSchema: ZodSchema<T>;
errorToMessage: (error: T) => string;
isRetryable?: (response: Response, error?: T) => boolean;
}) => ResponseHandler<APICallError>;
declare const createEventSourceResponseHandler: <T>(chunkSchema: ZodSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
declare const createJsonResponseHandler: <T>(responseSchema: ZodSchema<T>) => ResponseHandler<T>;
declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
failedResponseHandler: ResponseHandler<Error>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare function isAbortError(error: unknown): error is Error;
declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName, description, }: {
apiKey: string | undefined;
environmentVariableName: string;
apiKeyParameterName?: string;
description: string;
}): string;
/**
* Loads an optional `string` setting from the environment or a parameter.
*
* @param settingValue - The setting value.
* @param environmentVariableName - The environment variable name.
* @returns The setting value.
*/
declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
settingValue: string | undefined;
environmentVariableName: string;
}): string | undefined;
/**
* Loads a `string` setting from the environment or a parameter.
*
* @param settingValue - The setting value.
* @param environmentVariableName - The environment variable name.
* @param settingName - The setting name.
* @param description - The description of the setting.
* @returns The setting value.
*/
declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
settingValue: string | undefined;
environmentVariableName: string;
settingName: string;
description: string;
}): string;
declare function parseProviderOptions<T>({ provider, providerOptions, schema, }: {
provider: string;
providerOptions: Record<string, unknown> | undefined;
schema: z.ZodSchema<T>;
}): T | undefined;
declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
body: unknown;
failedResponseHandler: ResponseHandler<APICallError>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare const postFormDataToApi: <T>({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
formData: FormData;
failedResponseHandler: ResponseHandler<APICallError>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
body: {
content: string | FormData | Uint8Array;
values: unknown;
};
failedResponseHandler: ResponseHandler<Error>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
/**
* Removes entries from a record where the value is null or undefined.
* @param record - The input object whose entries may be null or undefined.
* @returns A new object containing only entries with non-null and non-undefined values.
*/
declare function removeUndefinedEntries<T>(record: Record<string, T | undefined>): Record<string, T>;
type Resolvable<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
/**
* Resolves a value that could be a raw value, a Promise, a function returning a value,
* or a function returning a Promise.
*/
declare function resolve<T>(value: Resolvable<T>): Promise<T>;
declare function convertBase64ToUint8Array(base64String: string): Uint8Array;
declare function convertUint8ArrayToBase64(array: Uint8Array): string;
/**
* Validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @returns {T} - The typed object.
*/
declare function validateTypes<T>({ value, schema: inputSchema, }: {
value: unknown;
schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
}): T;
/**
* Safely validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The JSON object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
declare function safeValidateTypes<T>({ value, schema, }: {
value: unknown;
schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
}): {
success: true;
value: T;
} | {
success: false;
error: TypeValidationError;
};
declare function withoutTrailingSlash(url: string | undefined): string | undefined;
/**
Typed tool call that is returned by generateText and streamText.
It contains the tool call ID, the tool name, and the tool arguments.
*/
interface ToolCall<NAME extends string, ARGS> {
/**
ID of the tool call. This ID is used to match the tool call with the tool result.
*/
toolCallId: string;
/**
Name of the tool that is being called.
*/
toolName: NAME;
/**
Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
*/
args: ARGS;
}
/**
* @deprecated Use `ToolCall` instead.
*/
type CoreToolCall<NAME extends string, ARGS> = ToolCall<NAME, ARGS>;
/**
Typed tool result that is returned by `generateText` and `streamText`.
It contains the tool call ID, the tool name, the tool arguments, and the tool result.
*/
interface ToolResult<NAME extends string, ARGS, RESULT> {
/**
ID of the tool call. This ID is used to match the tool call with the tool result.
*/
toolCallId: string;
/**
Name of the tool that was called.
*/
toolName: NAME;
/**
Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
*/
args: ARGS;
/**
Result of the tool call. This is the result of the tool's execution.
*/
result: RESULT;
}
/**
* @deprecated Use `ToolResult` instead.
*/
type CoreToolResult<NAME extends string, ARGS, RESULT> = ToolResult<NAME, ARGS, RESULT>;
export { type CoreToolCall, type CoreToolResult, type EventSourceChunk, type FetchFunction, type IDGenerator, type ParseResult, type Resolvable, type ResponseHandler, type ToolCall, type ToolResult, type ValidationResult, type Validator, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceParserStream, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createStatusCodeErrorResponseHandler, delay, extractResponseHeaders, generateId, getErrorMessage, getFromApi, isAbortError, isParsableJson, isValidator, loadApiKey, loadOptionalSetting, loadSetting, parseJSON, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, validateTypes, validator, validatorSymbol, withoutTrailingSlash, zodValidator };

View File

@@ -0,0 +1,379 @@
import { JSONValue, JSONParseError, TypeValidationError, APICallError } from '@ai-sdk/provider';
import { z, ZodSchema } from 'zod';
declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
/**
* Converts an AsyncIterator to a ReadableStream.
*
* @template T - The type of elements produced by the AsyncIterator.
* @param { <T>} iterator - The AsyncIterator to convert.
* @returns {ReadableStream<T>} - A ReadableStream that provides the same data as the AsyncIterator.
*/
declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
/**
* Creates a Promise that resolves after a specified delay
* @param delayInMs - The delay duration in milliseconds. If null or undefined, resolves immediately.
* @returns A Promise that resolves after the specified delay
*/
declare function delay(delayInMs?: number | null): Promise<void>;
type EventSourceChunk = {
event: string | undefined;
data: string;
id?: string;
retry?: number;
};
declare function createEventSourceParserStream(): TransformStream<string, EventSourceChunk>;
/**
Extracts the headers from a response object and returns them as a key-value object.
@param response - The response object to extract headers from.
@returns The headers as a key-value object.
*/
declare function extractResponseHeaders(response: Response): Record<string, string>;
/**
* Fetch function type (standardizes the version of fetch used).
*/
type FetchFunction = typeof globalThis.fetch;
/**
Creates an ID generator.
The total length of the ID is the sum of the prefix, separator, and random part length.
Non-secure.
@param alphabet - The alphabet to use for the ID. Default: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
@param prefix - The prefix of the ID to generate. Default: ''.
@param separator - The separator between the prefix and the random part of the ID. Default: '-'.
@param size - The size of the random part of the ID to generate. Default: 16.
*/
declare const createIdGenerator: ({ prefix, size: defaultSize, alphabet, separator, }?: {
prefix?: string;
separator?: string;
size?: number;
alphabet?: string;
}) => ((size?: number) => string);
/**
A function that generates an ID.
*/
type IDGenerator = () => string;
/**
Generates a 16-character random string to use for IDs. Not secure.
@param size - The size of the ID to generate. Default: 16.
*/
declare const generateId: (size?: number) => string;
declare function getErrorMessage(error: unknown | undefined): string;
/**
* Used to mark validator functions so we can support both Zod and custom schemas.
*/
declare const validatorSymbol: unique symbol;
type ValidationResult<OBJECT> = {
success: true;
value: OBJECT;
} | {
success: false;
error: Error;
};
type Validator<OBJECT = unknown> = {
/**
* Used to mark validator functions so we can support both Zod and custom schemas.
*/
[validatorSymbol]: true;
/**
* Optional. Validates that the structure of a value matches this schema,
* and returns a typed version of the value if it does.
*/
readonly validate?: (value: unknown) => ValidationResult<OBJECT>;
};
/**
* Create a validator.
*
* @param validate A validation function for the schema.
*/
declare function validator<OBJECT>(validate?: undefined | ((value: unknown) => ValidationResult<OBJECT>)): Validator<OBJECT>;
declare function isValidator(value: unknown): value is Validator;
declare function asValidator<OBJECT>(value: Validator<OBJECT> | z.Schema<OBJECT, z.ZodTypeDef, any>): Validator<OBJECT>;
declare function zodValidator<OBJECT>(zodSchema: z.Schema<OBJECT, z.ZodTypeDef, any>): Validator<OBJECT>;
/**
* Parses a JSON string into an unknown object.
*
* @param text - The JSON string to parse.
* @returns {JSONValue} - The parsed JSON object.
*/
declare function parseJSON(options: {
text: string;
schema?: undefined;
}): JSONValue;
/**
* Parses a JSON string into a strongly-typed object using the provided schema.
*
* @template T - The type of the object to parse the JSON into.
* @param {string} text - The JSON string to parse.
* @param {Validator<T>} schema - The schema to use for parsing the JSON.
* @returns {T} - The parsed object.
*/
declare function parseJSON<T>(options: {
text: string;
schema: ZodSchema<T> | Validator<T>;
}): T;
type ParseResult<T> = {
success: true;
value: T;
rawValue: unknown;
} | {
success: false;
error: JSONParseError | TypeValidationError;
};
/**
* Safely parses a JSON string and returns the result as an object of type `unknown`.
*
* @param text - The JSON string to parse.
* @returns {object} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.
*/
declare function safeParseJSON(options: {
text: string;
schema?: undefined;
}): ParseResult<JSONValue>;
/**
* Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
*
* @template T - The type of the object to parse the JSON into.
* @param {string} text - The JSON string to parse.
* @param {Validator<T>} schema - The schema to use for parsing the JSON.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
declare function safeParseJSON<T>(options: {
text: string;
schema: ZodSchema<T> | Validator<T>;
}): ParseResult<T>;
declare function isParsableJson(input: string): boolean;
type ResponseHandler<RETURN_TYPE> = (options: {
url: string;
requestBodyValues: unknown;
response: Response;
}) => PromiseLike<{
value: RETURN_TYPE;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare const createJsonErrorResponseHandler: <T>({ errorSchema, errorToMessage, isRetryable, }: {
errorSchema: ZodSchema<T>;
errorToMessage: (error: T) => string;
isRetryable?: (response: Response, error?: T) => boolean;
}) => ResponseHandler<APICallError>;
declare const createEventSourceResponseHandler: <T>(chunkSchema: ZodSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
declare const createJsonStreamResponseHandler: <T>(chunkSchema: ZodSchema<T>) => ResponseHandler<ReadableStream<ParseResult<T>>>;
declare const createJsonResponseHandler: <T>(responseSchema: ZodSchema<T>) => ResponseHandler<T>;
declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
failedResponseHandler: ResponseHandler<Error>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare function isAbortError(error: unknown): error is Error;
declare function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName, description, }: {
apiKey: string | undefined;
environmentVariableName: string;
apiKeyParameterName?: string;
description: string;
}): string;
/**
* Loads an optional `string` setting from the environment or a parameter.
*
* @param settingValue - The setting value.
* @param environmentVariableName - The environment variable name.
* @returns The setting value.
*/
declare function loadOptionalSetting({ settingValue, environmentVariableName, }: {
settingValue: string | undefined;
environmentVariableName: string;
}): string | undefined;
/**
* Loads a `string` setting from the environment or a parameter.
*
* @param settingValue - The setting value.
* @param environmentVariableName - The environment variable name.
* @param settingName - The setting name.
* @param description - The description of the setting.
* @returns The setting value.
*/
declare function loadSetting({ settingValue, environmentVariableName, settingName, description, }: {
settingValue: string | undefined;
environmentVariableName: string;
settingName: string;
description: string;
}): string;
declare function parseProviderOptions<T>({ provider, providerOptions, schema, }: {
provider: string;
providerOptions: Record<string, unknown> | undefined;
schema: z.ZodSchema<T>;
}): T | undefined;
declare const postJsonToApi: <T>({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
body: unknown;
failedResponseHandler: ResponseHandler<APICallError>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare const postFormDataToApi: <T>({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
formData: FormData;
failedResponseHandler: ResponseHandler<APICallError>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
url: string;
headers?: Record<string, string | undefined>;
body: {
content: string | FormData | Uint8Array;
values: unknown;
};
failedResponseHandler: ResponseHandler<Error>;
successfulResponseHandler: ResponseHandler<T>;
abortSignal?: AbortSignal;
fetch?: FetchFunction;
}) => Promise<{
value: T;
rawValue?: unknown;
responseHeaders?: Record<string, string>;
}>;
/**
* Removes entries from a record where the value is null or undefined.
* @param record - The input object whose entries may be null or undefined.
* @returns A new object containing only entries with non-null and non-undefined values.
*/
declare function removeUndefinedEntries<T>(record: Record<string, T | undefined>): Record<string, T>;
type Resolvable<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
/**
* Resolves a value that could be a raw value, a Promise, a function returning a value,
* or a function returning a Promise.
*/
declare function resolve<T>(value: Resolvable<T>): Promise<T>;
declare function convertBase64ToUint8Array(base64String: string): Uint8Array;
declare function convertUint8ArrayToBase64(array: Uint8Array): string;
/**
* Validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @returns {T} - The typed object.
*/
declare function validateTypes<T>({ value, schema: inputSchema, }: {
value: unknown;
schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
}): T;
/**
* Safely validates the types of an unknown object using a schema and
* return a strongly-typed object.
*
* @template T - The type of the object to validate.
* @param {string} options.value - The JSON object to validate.
* @param {Validator<T>} options.schema - The schema to use for validating the JSON.
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
*/
declare function safeValidateTypes<T>({ value, schema, }: {
value: unknown;
schema: z.Schema<T, z.ZodTypeDef, any> | Validator<T>;
}): {
success: true;
value: T;
} | {
success: false;
error: TypeValidationError;
};
declare function withoutTrailingSlash(url: string | undefined): string | undefined;
/**
Typed tool call that is returned by generateText and streamText.
It contains the tool call ID, the tool name, and the tool arguments.
*/
interface ToolCall<NAME extends string, ARGS> {
/**
ID of the tool call. This ID is used to match the tool call with the tool result.
*/
toolCallId: string;
/**
Name of the tool that is being called.
*/
toolName: NAME;
/**
Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
*/
args: ARGS;
}
/**
* @deprecated Use `ToolCall` instead.
*/
type CoreToolCall<NAME extends string, ARGS> = ToolCall<NAME, ARGS>;
/**
Typed tool result that is returned by `generateText` and `streamText`.
It contains the tool call ID, the tool name, the tool arguments, and the tool result.
*/
interface ToolResult<NAME extends string, ARGS, RESULT> {
/**
ID of the tool call. This ID is used to match the tool call with the tool result.
*/
toolCallId: string;
/**
Name of the tool that was called.
*/
toolName: NAME;
/**
Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
*/
args: ARGS;
/**
Result of the tool call. This is the result of the tool's execution.
*/
result: RESULT;
}
/**
* @deprecated Use `ToolResult` instead.
*/
type CoreToolResult<NAME extends string, ARGS, RESULT> = ToolResult<NAME, ARGS, RESULT>;
export { type CoreToolCall, type CoreToolResult, type EventSourceChunk, type FetchFunction, type IDGenerator, type ParseResult, type Resolvable, type ResponseHandler, type ToolCall, type ToolResult, type ValidationResult, type Validator, asValidator, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceParserStream, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createJsonStreamResponseHandler, createStatusCodeErrorResponseHandler, delay, extractResponseHeaders, generateId, getErrorMessage, getFromApi, isAbortError, isParsableJson, isValidator, loadApiKey, loadOptionalSetting, loadSetting, parseJSON, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, validateTypes, validator, validatorSymbol, withoutTrailingSlash, zodValidator };

View File

@@ -0,0 +1,944 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
asValidator: () => asValidator,
combineHeaders: () => combineHeaders,
convertAsyncIteratorToReadableStream: () => convertAsyncIteratorToReadableStream,
convertBase64ToUint8Array: () => convertBase64ToUint8Array,
convertUint8ArrayToBase64: () => convertUint8ArrayToBase64,
createBinaryResponseHandler: () => createBinaryResponseHandler,
createEventSourceParserStream: () => createEventSourceParserStream,
createEventSourceResponseHandler: () => createEventSourceResponseHandler,
createIdGenerator: () => createIdGenerator,
createJsonErrorResponseHandler: () => createJsonErrorResponseHandler,
createJsonResponseHandler: () => createJsonResponseHandler,
createJsonStreamResponseHandler: () => createJsonStreamResponseHandler,
createStatusCodeErrorResponseHandler: () => createStatusCodeErrorResponseHandler,
delay: () => delay,
extractResponseHeaders: () => extractResponseHeaders,
generateId: () => generateId,
getErrorMessage: () => getErrorMessage,
getFromApi: () => getFromApi,
isAbortError: () => isAbortError,
isParsableJson: () => isParsableJson,
isValidator: () => isValidator,
loadApiKey: () => loadApiKey,
loadOptionalSetting: () => loadOptionalSetting,
loadSetting: () => loadSetting,
parseJSON: () => parseJSON,
parseProviderOptions: () => parseProviderOptions,
postFormDataToApi: () => postFormDataToApi,
postJsonToApi: () => postJsonToApi,
postToApi: () => postToApi,
removeUndefinedEntries: () => removeUndefinedEntries,
resolve: () => resolve,
safeParseJSON: () => safeParseJSON,
safeValidateTypes: () => safeValidateTypes,
validateTypes: () => validateTypes,
validator: () => validator,
validatorSymbol: () => validatorSymbol,
withoutTrailingSlash: () => withoutTrailingSlash,
zodValidator: () => zodValidator
});
module.exports = __toCommonJS(src_exports);
// src/combine-headers.ts
function combineHeaders(...headers) {
return headers.reduce(
(combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders != null ? currentHeaders : {}
}),
{}
);
}
// src/convert-async-iterator-to-readable-stream.ts
function convertAsyncIteratorToReadableStream(iterator) {
return new ReadableStream({
/**
* Called when the consumer wants to pull more data from the stream.
*
* @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
* @returns {Promise<void>}
*/
async pull(controller) {
try {
const { value, done } = await iterator.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
},
/**
* Called when the consumer cancels the stream.
*/
cancel() {
}
});
}
// src/delay.ts
async function delay(delayInMs) {
return delayInMs == null ? Promise.resolve() : new Promise((resolve2) => setTimeout(resolve2, delayInMs));
}
// src/event-source-parser-stream.ts
function createEventSourceParserStream() {
let buffer = "";
let event = void 0;
let data = [];
let lastEventId = void 0;
let retry = void 0;
function parseLine(line, controller) {
if (line === "") {
dispatchEvent(controller);
return;
}
if (line.startsWith(":")) {
return;
}
const colonIndex = line.indexOf(":");
if (colonIndex === -1) {
handleField(line, "");
return;
}
const field = line.slice(0, colonIndex);
const valueStart = colonIndex + 1;
const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart);
handleField(field, value);
}
function dispatchEvent(controller) {
if (data.length > 0) {
controller.enqueue({
event,
data: data.join("\n"),
id: lastEventId,
retry
});
data = [];
event = void 0;
retry = void 0;
}
}
function handleField(field, value) {
switch (field) {
case "event":
event = value;
break;
case "data":
data.push(value);
break;
case "id":
lastEventId = value;
break;
case "retry":
const parsedRetry = parseInt(value, 10);
if (!isNaN(parsedRetry)) {
retry = parsedRetry;
}
break;
}
}
return new TransformStream({
transform(chunk, controller) {
const { lines, incompleteLine } = splitLines(buffer, chunk);
buffer = incompleteLine;
for (let i = 0; i < lines.length; i++) {
parseLine(lines[i], controller);
}
},
flush(controller) {
parseLine(buffer, controller);
dispatchEvent(controller);
}
});
}
function splitLines(buffer, chunk) {
const lines = [];
let currentLine = buffer;
for (let i = 0; i < chunk.length; ) {
const char = chunk[i++];
if (char === "\n") {
lines.push(currentLine);
currentLine = "";
} else if (char === "\r") {
lines.push(currentLine);
currentLine = "";
if (chunk[i] === "\n") {
i++;
}
} else {
currentLine += char;
}
}
return { lines, incompleteLine: currentLine };
}
// src/extract-response-headers.ts
function extractResponseHeaders(response) {
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
return headers;
}
// src/generate-id.ts
var import_provider = require("@ai-sdk/provider");
var import_non_secure = require("nanoid/non-secure");
var createIdGenerator = ({
prefix,
size: defaultSize = 16,
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
separator = "-"
} = {}) => {
const generator = (0, import_non_secure.customAlphabet)(alphabet, defaultSize);
if (prefix == null) {
return generator;
}
if (alphabet.includes(separator)) {
throw new import_provider.InvalidArgumentError({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
}
return (size) => `${prefix}${separator}${generator(size)}`;
};
var generateId = createIdGenerator();
// src/get-error-message.ts
function getErrorMessage(error) {
if (error == null) {
return "unknown error";
}
if (typeof error === "string") {
return error;
}
if (error instanceof Error) {
return error.message;
}
return JSON.stringify(error);
}
// src/get-from-api.ts
var import_provider2 = require("@ai-sdk/provider");
// src/remove-undefined-entries.ts
function removeUndefinedEntries(record) {
return Object.fromEntries(
Object.entries(record).filter(([_key, value]) => value != null)
);
}
// src/is-abort-error.ts
function isAbortError(error) {
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
}
// src/get-from-api.ts
var getOriginalFetch = () => globalThis.fetch;
var getFromApi = async ({
url,
headers = {},
successfulResponseHandler,
failedResponseHandler,
abortSignal,
fetch = getOriginalFetch()
}) => {
try {
const response = await fetch(url, {
method: "GET",
headers: removeUndefinedEntries(headers),
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError(error) || import_provider2.APICallError.isInstance(error)) {
throw error;
}
throw new import_provider2.APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || import_provider2.APICallError.isInstance(error)) {
throw error;
}
}
throw new import_provider2.APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
if (isAbortError(error)) {
throw error;
}
if (error instanceof TypeError && error.message === "fetch failed") {
const cause = error.cause;
if (cause != null) {
throw new import_provider2.APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
isRetryable: true,
requestBodyValues: {}
});
}
}
throw error;
}
};
// src/load-api-key.ts
var import_provider3 = require("@ai-sdk/provider");
function loadApiKey({
apiKey,
environmentVariableName,
apiKeyParameterName = "apiKey",
description
}) {
if (typeof apiKey === "string") {
return apiKey;
}
if (apiKey != null) {
throw new import_provider3.LoadAPIKeyError({
message: `${description} API key must be a string.`
});
}
if (typeof process === "undefined") {
throw new import_provider3.LoadAPIKeyError({
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
});
}
apiKey = process.env[environmentVariableName];
if (apiKey == null) {
throw new import_provider3.LoadAPIKeyError({
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
});
}
if (typeof apiKey !== "string") {
throw new import_provider3.LoadAPIKeyError({
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
});
}
return apiKey;
}
// src/load-optional-setting.ts
function loadOptionalSetting({
settingValue,
environmentVariableName
}) {
if (typeof settingValue === "string") {
return settingValue;
}
if (settingValue != null || typeof process === "undefined") {
return void 0;
}
settingValue = process.env[environmentVariableName];
if (settingValue == null || typeof settingValue !== "string") {
return void 0;
}
return settingValue;
}
// src/load-setting.ts
var import_provider4 = require("@ai-sdk/provider");
function loadSetting({
settingValue,
environmentVariableName,
settingName,
description
}) {
if (typeof settingValue === "string") {
return settingValue;
}
if (settingValue != null) {
throw new import_provider4.LoadSettingError({
message: `${description} setting must be a string.`
});
}
if (typeof process === "undefined") {
throw new import_provider4.LoadSettingError({
message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`
});
}
settingValue = process.env[environmentVariableName];
if (settingValue == null) {
throw new import_provider4.LoadSettingError({
message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`
});
}
if (typeof settingValue !== "string") {
throw new import_provider4.LoadSettingError({
message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
});
}
return settingValue;
}
// src/parse-json.ts
var import_provider6 = require("@ai-sdk/provider");
var import_secure_json_parse = __toESM(require("secure-json-parse"));
// src/validate-types.ts
var import_provider5 = require("@ai-sdk/provider");
// src/validator.ts
var validatorSymbol = Symbol.for("vercel.ai.validator");
function validator(validate) {
return { [validatorSymbol]: true, validate };
}
function isValidator(value) {
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
}
function asValidator(value) {
return isValidator(value) ? value : zodValidator(value);
}
function zodValidator(zodSchema) {
return validator((value) => {
const result = zodSchema.safeParse(value);
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
});
}
// src/validate-types.ts
function validateTypes({
value,
schema: inputSchema
}) {
const result = safeValidateTypes({ value, schema: inputSchema });
if (!result.success) {
throw import_provider5.TypeValidationError.wrap({ value, cause: result.error });
}
return result.value;
}
function safeValidateTypes({
value,
schema
}) {
const validator2 = asValidator(schema);
try {
if (validator2.validate == null) {
return { success: true, value };
}
const result = validator2.validate(value);
if (result.success) {
return result;
}
return {
success: false,
error: import_provider5.TypeValidationError.wrap({ value, cause: result.error })
};
} catch (error) {
return {
success: false,
error: import_provider5.TypeValidationError.wrap({ value, cause: error })
};
}
}
// src/parse-json.ts
function parseJSON({
text,
schema
}) {
try {
const value = import_secure_json_parse.default.parse(text);
if (schema == null) {
return value;
}
return validateTypes({ value, schema });
} catch (error) {
if (import_provider6.JSONParseError.isInstance(error) || import_provider6.TypeValidationError.isInstance(error)) {
throw error;
}
throw new import_provider6.JSONParseError({ text, cause: error });
}
}
function safeParseJSON({
text,
schema
}) {
try {
const value = import_secure_json_parse.default.parse(text);
if (schema == null) {
return { success: true, value, rawValue: value };
}
const validationResult = safeValidateTypes({ value, schema });
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
} catch (error) {
return {
success: false,
error: import_provider6.JSONParseError.isInstance(error) ? error : new import_provider6.JSONParseError({ text, cause: error })
};
}
}
function isParsableJson(input) {
try {
import_secure_json_parse.default.parse(input);
return true;
} catch (e) {
return false;
}
}
// src/parse-provider-options.ts
var import_provider7 = require("@ai-sdk/provider");
function parseProviderOptions({
provider,
providerOptions,
schema
}) {
if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
return void 0;
}
const parsedProviderOptions = safeValidateTypes({
value: providerOptions[provider],
schema
});
if (!parsedProviderOptions.success) {
throw new import_provider7.InvalidArgumentError({
argument: "providerOptions",
message: `invalid ${provider} provider options`,
cause: parsedProviderOptions.error
});
}
return parsedProviderOptions.value;
}
// src/post-to-api.ts
var import_provider8 = require("@ai-sdk/provider");
var getOriginalFetch2 = () => globalThis.fetch;
var postJsonToApi = async ({
url,
headers,
body,
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
}) => postToApi({
url,
headers: {
"Content-Type": "application/json",
...headers
},
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postFormDataToApi = async ({
url,
headers,
formData,
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
}) => postToApi({
url,
headers,
body: {
content: formData,
values: Object.fromEntries(formData.entries())
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postToApi = async ({
url,
headers = {},
body,
successfulResponseHandler,
failedResponseHandler,
abortSignal,
fetch = getOriginalFetch2()
}) => {
try {
const response = await fetch(url, {
method: "POST",
headers: removeUndefinedEntries(headers),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError(error) || import_provider8.APICallError.isInstance(error)) {
throw error;
}
throw new import_provider8.APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || import_provider8.APICallError.isInstance(error)) {
throw error;
}
}
throw new import_provider8.APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
if (isAbortError(error)) {
throw error;
}
if (error instanceof TypeError && error.message === "fetch failed") {
const cause = error.cause;
if (cause != null) {
throw new import_provider8.APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues: body.values,
isRetryable: true
// retry when network error
});
}
}
throw error;
}
};
// src/resolve.ts
async function resolve(value) {
if (typeof value === "function") {
value = value();
}
return Promise.resolve(value);
}
// src/response-handler.ts
var import_provider9 = require("@ai-sdk/provider");
var createJsonErrorResponseHandler = ({
errorSchema,
errorToMessage,
isRetryable
}) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const responseHeaders = extractResponseHeaders(response);
if (responseBody.trim() === "") {
return {
responseHeaders,
value: new import_provider9.APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
try {
const parsedError = parseJSON({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new import_provider9.APICallError({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
})
};
} catch (parseError) {
return {
responseHeaders,
value: new import_provider9.APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
};
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) {
throw new import_provider9.EmptyResponseBodyError({});
}
return {
responseHeaders,
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
new TransformStream({
transform({ data }, controller) {
if (data === "[DONE]") {
return;
}
controller.enqueue(
safeParseJSON({
text: data,
schema: chunkSchema
})
);
}
})
)
};
};
var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) {
throw new import_provider9.EmptyResponseBodyError({});
}
let buffer = "";
return {
responseHeaders,
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
new TransformStream({
transform(chunkText, controller) {
if (chunkText.endsWith("\n")) {
controller.enqueue(
safeParseJSON({
text: buffer + chunkText,
schema: chunkSchema
})
);
buffer = "";
} else {
buffer += chunkText;
}
}
})
)
};
};
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const parsedResult = safeParseJSON({
text: responseBody,
schema: responseSchema
});
const responseHeaders = extractResponseHeaders(response);
if (!parsedResult.success) {
throw new import_provider9.APICallError({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
}
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
if (!response.body) {
throw new import_provider9.APICallError({
message: "Response body is empty",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0
});
}
try {
const buffer = await response.arrayBuffer();
return {
responseHeaders,
value: new Uint8Array(buffer)
};
} catch (error) {
throw new import_provider9.APICallError({
message: "Failed to read response as array buffer",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0,
cause: error
});
}
};
var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
const responseBody = await response.text();
return {
responseHeaders,
value: new import_provider9.APICallError({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody
})
};
};
// src/uint8-utils.ts
var { btoa, atob } = globalThis;
function convertBase64ToUint8Array(base64String) {
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
const latin1string = atob(base64Url);
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
}
function convertUint8ArrayToBase64(array) {
let latin1string = "";
for (let i = 0; i < array.length; i++) {
latin1string += String.fromCodePoint(array[i]);
}
return btoa(latin1string);
}
// src/without-trailing-slash.ts
function withoutTrailingSlash(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
asValidator,
combineHeaders,
convertAsyncIteratorToReadableStream,
convertBase64ToUint8Array,
convertUint8ArrayToBase64,
createBinaryResponseHandler,
createEventSourceParserStream,
createEventSourceResponseHandler,
createIdGenerator,
createJsonErrorResponseHandler,
createJsonResponseHandler,
createJsonStreamResponseHandler,
createStatusCodeErrorResponseHandler,
delay,
extractResponseHeaders,
generateId,
getErrorMessage,
getFromApi,
isAbortError,
isParsableJson,
isValidator,
loadApiKey,
loadOptionalSetting,
loadSetting,
parseJSON,
parseProviderOptions,
postFormDataToApi,
postJsonToApi,
postToApi,
removeUndefinedEntries,
resolve,
safeParseJSON,
safeValidateTypes,
validateTypes,
validator,
validatorSymbol,
withoutTrailingSlash,
zodValidator
});
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,873 @@
// src/combine-headers.ts
function combineHeaders(...headers) {
return headers.reduce(
(combinedHeaders, currentHeaders) => ({
...combinedHeaders,
...currentHeaders != null ? currentHeaders : {}
}),
{}
);
}
// src/convert-async-iterator-to-readable-stream.ts
function convertAsyncIteratorToReadableStream(iterator) {
return new ReadableStream({
/**
* Called when the consumer wants to pull more data from the stream.
*
* @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream.
* @returns {Promise<void>}
*/
async pull(controller) {
try {
const { value, done } = await iterator.next();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
},
/**
* Called when the consumer cancels the stream.
*/
cancel() {
}
});
}
// src/delay.ts
async function delay(delayInMs) {
return delayInMs == null ? Promise.resolve() : new Promise((resolve2) => setTimeout(resolve2, delayInMs));
}
// src/event-source-parser-stream.ts
function createEventSourceParserStream() {
let buffer = "";
let event = void 0;
let data = [];
let lastEventId = void 0;
let retry = void 0;
function parseLine(line, controller) {
if (line === "") {
dispatchEvent(controller);
return;
}
if (line.startsWith(":")) {
return;
}
const colonIndex = line.indexOf(":");
if (colonIndex === -1) {
handleField(line, "");
return;
}
const field = line.slice(0, colonIndex);
const valueStart = colonIndex + 1;
const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart);
handleField(field, value);
}
function dispatchEvent(controller) {
if (data.length > 0) {
controller.enqueue({
event,
data: data.join("\n"),
id: lastEventId,
retry
});
data = [];
event = void 0;
retry = void 0;
}
}
function handleField(field, value) {
switch (field) {
case "event":
event = value;
break;
case "data":
data.push(value);
break;
case "id":
lastEventId = value;
break;
case "retry":
const parsedRetry = parseInt(value, 10);
if (!isNaN(parsedRetry)) {
retry = parsedRetry;
}
break;
}
}
return new TransformStream({
transform(chunk, controller) {
const { lines, incompleteLine } = splitLines(buffer, chunk);
buffer = incompleteLine;
for (let i = 0; i < lines.length; i++) {
parseLine(lines[i], controller);
}
},
flush(controller) {
parseLine(buffer, controller);
dispatchEvent(controller);
}
});
}
function splitLines(buffer, chunk) {
const lines = [];
let currentLine = buffer;
for (let i = 0; i < chunk.length; ) {
const char = chunk[i++];
if (char === "\n") {
lines.push(currentLine);
currentLine = "";
} else if (char === "\r") {
lines.push(currentLine);
currentLine = "";
if (chunk[i] === "\n") {
i++;
}
} else {
currentLine += char;
}
}
return { lines, incompleteLine: currentLine };
}
// src/extract-response-headers.ts
function extractResponseHeaders(response) {
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
return headers;
}
// src/generate-id.ts
import { InvalidArgumentError } from "@ai-sdk/provider";
import { customAlphabet } from "nanoid/non-secure";
var createIdGenerator = ({
prefix,
size: defaultSize = 16,
alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
separator = "-"
} = {}) => {
const generator = customAlphabet(alphabet, defaultSize);
if (prefix == null) {
return generator;
}
if (alphabet.includes(separator)) {
throw new InvalidArgumentError({
argument: "separator",
message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
});
}
return (size) => `${prefix}${separator}${generator(size)}`;
};
var generateId = createIdGenerator();
// src/get-error-message.ts
function getErrorMessage(error) {
if (error == null) {
return "unknown error";
}
if (typeof error === "string") {
return error;
}
if (error instanceof Error) {
return error.message;
}
return JSON.stringify(error);
}
// src/get-from-api.ts
import { APICallError } from "@ai-sdk/provider";
// src/remove-undefined-entries.ts
function removeUndefinedEntries(record) {
return Object.fromEntries(
Object.entries(record).filter(([_key, value]) => value != null)
);
}
// src/is-abort-error.ts
function isAbortError(error) {
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
}
// src/get-from-api.ts
var getOriginalFetch = () => globalThis.fetch;
var getFromApi = async ({
url,
headers = {},
successfulResponseHandler,
failedResponseHandler,
abortSignal,
fetch = getOriginalFetch()
}) => {
try {
const response = await fetch(url, {
method: "GET",
headers: removeUndefinedEntries(headers),
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (isAbortError(error) || APICallError.isInstance(error)) {
throw error;
}
throw new APICallError({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: {}
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError.isInstance(error)) {
throw error;
}
}
throw new APICallError({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: {}
});
}
} catch (error) {
if (isAbortError(error)) {
throw error;
}
if (error instanceof TypeError && error.message === "fetch failed") {
const cause = error.cause;
if (cause != null) {
throw new APICallError({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
isRetryable: true,
requestBodyValues: {}
});
}
}
throw error;
}
};
// src/load-api-key.ts
import { LoadAPIKeyError } from "@ai-sdk/provider";
function loadApiKey({
apiKey,
environmentVariableName,
apiKeyParameterName = "apiKey",
description
}) {
if (typeof apiKey === "string") {
return apiKey;
}
if (apiKey != null) {
throw new LoadAPIKeyError({
message: `${description} API key must be a string.`
});
}
if (typeof process === "undefined") {
throw new LoadAPIKeyError({
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
});
}
apiKey = process.env[environmentVariableName];
if (apiKey == null) {
throw new LoadAPIKeyError({
message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
});
}
if (typeof apiKey !== "string") {
throw new LoadAPIKeyError({
message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
});
}
return apiKey;
}
// src/load-optional-setting.ts
function loadOptionalSetting({
settingValue,
environmentVariableName
}) {
if (typeof settingValue === "string") {
return settingValue;
}
if (settingValue != null || typeof process === "undefined") {
return void 0;
}
settingValue = process.env[environmentVariableName];
if (settingValue == null || typeof settingValue !== "string") {
return void 0;
}
return settingValue;
}
// src/load-setting.ts
import { LoadSettingError } from "@ai-sdk/provider";
function loadSetting({
settingValue,
environmentVariableName,
settingName,
description
}) {
if (typeof settingValue === "string") {
return settingValue;
}
if (settingValue != null) {
throw new LoadSettingError({
message: `${description} setting must be a string.`
});
}
if (typeof process === "undefined") {
throw new LoadSettingError({
message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.`
});
}
settingValue = process.env[environmentVariableName];
if (settingValue == null) {
throw new LoadSettingError({
message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.`
});
}
if (typeof settingValue !== "string") {
throw new LoadSettingError({
message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
});
}
return settingValue;
}
// src/parse-json.ts
import {
JSONParseError,
TypeValidationError as TypeValidationError2
} from "@ai-sdk/provider";
import SecureJSON from "secure-json-parse";
// src/validate-types.ts
import { TypeValidationError } from "@ai-sdk/provider";
// src/validator.ts
var validatorSymbol = Symbol.for("vercel.ai.validator");
function validator(validate) {
return { [validatorSymbol]: true, validate };
}
function isValidator(value) {
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
}
function asValidator(value) {
return isValidator(value) ? value : zodValidator(value);
}
function zodValidator(zodSchema) {
return validator((value) => {
const result = zodSchema.safeParse(value);
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
});
}
// src/validate-types.ts
function validateTypes({
value,
schema: inputSchema
}) {
const result = safeValidateTypes({ value, schema: inputSchema });
if (!result.success) {
throw TypeValidationError.wrap({ value, cause: result.error });
}
return result.value;
}
function safeValidateTypes({
value,
schema
}) {
const validator2 = asValidator(schema);
try {
if (validator2.validate == null) {
return { success: true, value };
}
const result = validator2.validate(value);
if (result.success) {
return result;
}
return {
success: false,
error: TypeValidationError.wrap({ value, cause: result.error })
};
} catch (error) {
return {
success: false,
error: TypeValidationError.wrap({ value, cause: error })
};
}
}
// src/parse-json.ts
function parseJSON({
text,
schema
}) {
try {
const value = SecureJSON.parse(text);
if (schema == null) {
return value;
}
return validateTypes({ value, schema });
} catch (error) {
if (JSONParseError.isInstance(error) || TypeValidationError2.isInstance(error)) {
throw error;
}
throw new JSONParseError({ text, cause: error });
}
}
function safeParseJSON({
text,
schema
}) {
try {
const value = SecureJSON.parse(text);
if (schema == null) {
return { success: true, value, rawValue: value };
}
const validationResult = safeValidateTypes({ value, schema });
return validationResult.success ? { ...validationResult, rawValue: value } : validationResult;
} catch (error) {
return {
success: false,
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
};
}
}
function isParsableJson(input) {
try {
SecureJSON.parse(input);
return true;
} catch (e) {
return false;
}
}
// src/parse-provider-options.ts
import { InvalidArgumentError as InvalidArgumentError2 } from "@ai-sdk/provider";
function parseProviderOptions({
provider,
providerOptions,
schema
}) {
if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) {
return void 0;
}
const parsedProviderOptions = safeValidateTypes({
value: providerOptions[provider],
schema
});
if (!parsedProviderOptions.success) {
throw new InvalidArgumentError2({
argument: "providerOptions",
message: `invalid ${provider} provider options`,
cause: parsedProviderOptions.error
});
}
return parsedProviderOptions.value;
}
// src/post-to-api.ts
import { APICallError as APICallError2 } from "@ai-sdk/provider";
var getOriginalFetch2 = () => globalThis.fetch;
var postJsonToApi = async ({
url,
headers,
body,
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
}) => postToApi({
url,
headers: {
"Content-Type": "application/json",
...headers
},
body: {
content: JSON.stringify(body),
values: body
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postFormDataToApi = async ({
url,
headers,
formData,
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
}) => postToApi({
url,
headers,
body: {
content: formData,
values: Object.fromEntries(formData.entries())
},
failedResponseHandler,
successfulResponseHandler,
abortSignal,
fetch
});
var postToApi = async ({
url,
headers = {},
body,
successfulResponseHandler,
failedResponseHandler,
abortSignal,
fetch = getOriginalFetch2()
}) => {
try {
const response = await fetch(url, {
method: "POST",
headers: removeUndefinedEntries(headers),
body: body.content,
signal: abortSignal
});
const responseHeaders = extractResponseHeaders(response);
if (!response.ok) {
let errorInformation;
try {
errorInformation = await failedResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (isAbortError(error) || APICallError2.isInstance(error)) {
throw error;
}
throw new APICallError2({
message: "Failed to process error response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
throw errorInformation.value;
}
try {
return await successfulResponseHandler({
response,
url,
requestBodyValues: body.values
});
} catch (error) {
if (error instanceof Error) {
if (isAbortError(error) || APICallError2.isInstance(error)) {
throw error;
}
}
throw new APICallError2({
message: "Failed to process successful response",
cause: error,
statusCode: response.status,
url,
responseHeaders,
requestBodyValues: body.values
});
}
} catch (error) {
if (isAbortError(error)) {
throw error;
}
if (error instanceof TypeError && error.message === "fetch failed") {
const cause = error.cause;
if (cause != null) {
throw new APICallError2({
message: `Cannot connect to API: ${cause.message}`,
cause,
url,
requestBodyValues: body.values,
isRetryable: true
// retry when network error
});
}
}
throw error;
}
};
// src/resolve.ts
async function resolve(value) {
if (typeof value === "function") {
value = value();
}
return Promise.resolve(value);
}
// src/response-handler.ts
import { APICallError as APICallError3, EmptyResponseBodyError } from "@ai-sdk/provider";
var createJsonErrorResponseHandler = ({
errorSchema,
errorToMessage,
isRetryable
}) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const responseHeaders = extractResponseHeaders(response);
if (responseBody.trim() === "") {
return {
responseHeaders,
value: new APICallError3({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
try {
const parsedError = parseJSON({
text: responseBody,
schema: errorSchema
});
return {
responseHeaders,
value: new APICallError3({
message: errorToMessage(parsedError),
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
data: parsedError,
isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
})
};
} catch (parseError) {
return {
responseHeaders,
value: new APICallError3({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody,
isRetryable: isRetryable == null ? void 0 : isRetryable(response)
})
};
}
};
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) {
throw new EmptyResponseBodyError({});
}
return {
responseHeaders,
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough(
new TransformStream({
transform({ data }, controller) {
if (data === "[DONE]") {
return;
}
controller.enqueue(
safeParseJSON({
text: data,
schema: chunkSchema
})
);
}
})
)
};
};
var createJsonStreamResponseHandler = (chunkSchema) => async ({ response }) => {
const responseHeaders = extractResponseHeaders(response);
if (response.body == null) {
throw new EmptyResponseBodyError({});
}
let buffer = "";
return {
responseHeaders,
value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(
new TransformStream({
transform(chunkText, controller) {
if (chunkText.endsWith("\n")) {
controller.enqueue(
safeParseJSON({
text: buffer + chunkText,
schema: chunkSchema
})
);
buffer = "";
} else {
buffer += chunkText;
}
}
})
)
};
};
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
const responseBody = await response.text();
const parsedResult = safeParseJSON({
text: responseBody,
schema: responseSchema
});
const responseHeaders = extractResponseHeaders(response);
if (!parsedResult.success) {
throw new APICallError3({
message: "Invalid JSON response",
cause: parsedResult.error,
statusCode: response.status,
responseHeaders,
responseBody,
url,
requestBodyValues
});
}
return {
responseHeaders,
value: parsedResult.value,
rawValue: parsedResult.rawValue
};
};
var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
if (!response.body) {
throw new APICallError3({
message: "Response body is empty",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0
});
}
try {
const buffer = await response.arrayBuffer();
return {
responseHeaders,
value: new Uint8Array(buffer)
};
} catch (error) {
throw new APICallError3({
message: "Failed to read response as array buffer",
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody: void 0,
cause: error
});
}
};
var createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => {
const responseHeaders = extractResponseHeaders(response);
const responseBody = await response.text();
return {
responseHeaders,
value: new APICallError3({
message: response.statusText,
url,
requestBodyValues,
statusCode: response.status,
responseHeaders,
responseBody
})
};
};
// src/uint8-utils.ts
var { btoa, atob } = globalThis;
function convertBase64ToUint8Array(base64String) {
const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
const latin1string = atob(base64Url);
return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
}
function convertUint8ArrayToBase64(array) {
let latin1string = "";
for (let i = 0; i < array.length; i++) {
latin1string += String.fromCodePoint(array[i]);
}
return btoa(latin1string);
}
// src/without-trailing-slash.ts
function withoutTrailingSlash(url) {
return url == null ? void 0 : url.replace(/\/$/, "");
}
export {
asValidator,
combineHeaders,
convertAsyncIteratorToReadableStream,
convertBase64ToUint8Array,
convertUint8ArrayToBase64,
createBinaryResponseHandler,
createEventSourceParserStream,
createEventSourceResponseHandler,
createIdGenerator,
createJsonErrorResponseHandler,
createJsonResponseHandler,
createJsonStreamResponseHandler,
createStatusCodeErrorResponseHandler,
delay,
extractResponseHeaders,
generateId,
getErrorMessage,
getFromApi,
isAbortError,
isParsableJson,
isValidator,
loadApiKey,
loadOptionalSetting,
loadSetting,
parseJSON,
parseProviderOptions,
postFormDataToApi,
postJsonToApi,
postToApi,
removeUndefinedEntries,
resolve,
safeParseJSON,
safeValidateTypes,
validateTypes,
validator,
validatorSymbol,
withoutTrailingSlash,
zodValidator
};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,72 @@
{
"name": "@ai-sdk/provider-utils",
"version": "2.2.8",
"license": "Apache-2.0",
"sideEffects": false,
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist/**/*",
"test/dist/**/*",
"CHANGELOG.md"
],
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./test": {
"types": "./test/dist/index.d.ts",
"import": "./test/dist/index.mjs",
"module": "./test/dist/index.mjs",
"require": "./test/dist/index.js"
}
},
"dependencies": {
"@ai-sdk/provider": "1.1.3",
"nanoid": "^3.3.8",
"secure-json-parse": "^2.7.0"
},
"devDependencies": {
"@types/node": "20.17.24",
"msw": "2.7.0",
"tsup": "^8",
"typescript": "5.6.3",
"zod": "3.23.8",
"@vercel/ai-tsconfig": "0.0.0"
},
"peerDependencies": {
"zod": "^3.23.8"
},
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
},
"homepage": "https://ai-sdk.dev/docs",
"repository": {
"type": "git",
"url": "git+https://github.com/vercel/ai.git"
},
"bugs": {
"url": "https://github.com/vercel/ai/issues"
},
"keywords": [
"ai"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"clean": "rm -rf dist && rm -rf test/dist",
"lint": "eslint \"./**/*.ts*\"",
"type-check": "tsc --noEmit",
"prettier-check": "prettier --check \"./**/*.ts*\"",
"test": "pnpm test:node && pnpm test:edge",
"test:edge": "vitest --config vitest.edge.config.js --run",
"test:node": "vitest --config vitest.node.config.js --run"
}
}

View File

@@ -0,0 +1,45 @@
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
var __accessCheck = (obj, member, msg) => {
if (!member.has(obj))
throw TypeError("Cannot " + msg);
};
var __privateGet = (obj, member, getter) => {
__accessCheck(obj, member, "read from private field");
return getter ? getter.call(obj) : member.get(obj);
};
var __privateAdd = (obj, member, value) => {
if (member.has(obj))
throw TypeError("Cannot add the same private member more than once");
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
};
var __privateSet = (obj, member, value, setter) => {
__accessCheck(obj, member, "write to private field");
setter ? setter.call(obj, value) : member.set(obj, value);
return value;
};
var __privateMethod = (obj, member, method) => {
__accessCheck(obj, member, "access private method");
return method;
};
export {
__require,
__publicField,
__privateGet,
__privateAdd,
__privateSet,
__privateMethod
};
//# sourceMappingURL=chunk-D6YTI3O5.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,162 @@
import { SetupServer } from 'msw/node';
import { JsonBodyType } from 'msw';
declare function convertArrayToAsyncIterable<T>(values: T[]): AsyncIterable<T>;
declare function convertArrayToReadableStream<T>(values: T[]): ReadableStream<T>;
declare function convertAsyncIterableToArray<T>(iterable: AsyncIterable<T>): Promise<T[]>;
declare function convertReadableStreamToArray<T>(stream: ReadableStream<T>): Promise<T[]>;
declare function convertResponseStreamToArray(response: Response): Promise<string[]>;
/**
* @deprecated Use createTestServer instead
*/
declare class JsonTestServer {
readonly server: SetupServer;
responseHeaders: Record<string, string>;
responseBodyJson: any;
request: Request | undefined;
/**
* @deprecated Use createTestServer instead
*/
constructor(url: string);
getRequestBodyJson(): Promise<any>;
getRequestHeaders(): Promise<Record<string, string>>;
getRequestUrlSearchParams(): Promise<URLSearchParams>;
getRequestUrl(): Promise<string>;
setupTestEnvironment(): void;
}
declare function mockId({ prefix, }?: {
prefix?: string;
}): () => string;
/**
* @deprecated Use createTestServer instead
*/
declare class StreamingTestServer {
readonly server: SetupServer;
responseHeaders: Record<string, string>;
responseChunks: any[];
request: Request | undefined;
/**
* @deprecated Use createTestServer instead
*/
constructor(url: string);
getRequestBodyJson(): Promise<any>;
getRequestHeaders(): Promise<Record<string, string>>;
getRequestUrlSearchParams(): Promise<URLSearchParams>;
setupTestEnvironment(): void;
}
type TestServerJsonBodyType = JsonBodyType;
type TestServerResponse = {
url: string;
headers?: Record<string, string>;
} & ({
type: 'json-value';
content: TestServerJsonBodyType;
} | {
type: 'stream-values';
content: Array<string>;
} | {
type: 'controlled-stream';
id?: string;
} | {
type: 'error';
status: number;
content?: string;
});
declare class TestServerCall$1 {
private request;
constructor(request: Request);
getRequestBodyJson(): Promise<any>;
getRequestCredentials(): RequestCredentials;
getRequestHeaders(): Record<string, string>;
getRequestUrlSearchParams(): URLSearchParams;
}
declare function withTestServer(responses: Array<TestServerResponse> | TestServerResponse, testFunction: (options: {
calls: () => Array<TestServerCall$1>;
call: (index: number) => TestServerCall$1;
getStreamController: (id: string) => ReadableStreamDefaultController<string>;
streamController: ReadableStreamDefaultController<string>;
}) => Promise<void>): () => Promise<void>;
declare function describeWithTestServer(description: string, responses: Array<TestServerResponse> | TestServerResponse, testFunction: (options: {
calls: () => Array<TestServerCall$1>;
call: (index: number) => TestServerCall$1;
getStreamController: (id: string) => ReadableStreamDefaultController<string>;
streamController: ReadableStreamDefaultController<string>;
}) => void): void;
type UrlResponse = {
type: 'json-value';
headers?: Record<string, string>;
body: JsonBodyType;
} | {
type: 'stream-chunks';
headers?: Record<string, string>;
chunks: Array<string>;
} | {
type: 'binary';
headers?: Record<string, string>;
body: Buffer;
} | {
type: 'empty';
headers?: Record<string, string>;
status?: number;
} | {
type: 'error';
headers?: Record<string, string>;
status?: number;
body?: string;
} | {
type: 'controlled-stream';
headers?: Record<string, string>;
controller: TestResponseController;
} | undefined;
type UrlResponseParameter = UrlResponse | UrlResponse[] | ((options: {
callNumber: number;
}) => UrlResponse);
type UrlHandler = {
response: UrlResponseParameter;
};
type UrlHandlers<URLS extends {
[url: string]: {
response?: UrlResponseParameter;
};
}> = {
[url in keyof URLS]: UrlHandler;
};
declare class TestServerCall {
private request;
constructor(request: Request);
get requestBody(): Promise<any>;
get requestBodyMultipart(): Promise<Record<string, any>> | null;
get requestCredentials(): RequestCredentials;
get requestHeaders(): Record<string, string>;
get requestUrlSearchParams(): URLSearchParams;
get requestUrl(): string;
get requestMethod(): string;
}
declare function createTestServer<URLS extends {
[url: string]: {
response?: UrlResponseParameter;
};
}>(routes: URLS): {
urls: UrlHandlers<URLS>;
calls: TestServerCall[];
};
declare class TestResponseController {
private readonly transformStream;
private readonly writer;
constructor();
get stream(): ReadableStream;
write(chunk: string): Promise<void>;
error(error: Error): Promise<void>;
close(): Promise<void>;
}
export { JsonTestServer, StreamingTestServer, TestResponseController, type TestServerJsonBodyType, type TestServerResponse, type UrlHandler, type UrlHandlers, type UrlResponse, convertArrayToAsyncIterable, convertArrayToReadableStream, convertAsyncIterableToArray, convertReadableStreamToArray, convertResponseStreamToArray, createTestServer, describeWithTestServer, mockId, withTestServer };

View File

@@ -0,0 +1,162 @@
import { SetupServer } from 'msw/node';
import { JsonBodyType } from 'msw';
declare function convertArrayToAsyncIterable<T>(values: T[]): AsyncIterable<T>;
declare function convertArrayToReadableStream<T>(values: T[]): ReadableStream<T>;
declare function convertAsyncIterableToArray<T>(iterable: AsyncIterable<T>): Promise<T[]>;
declare function convertReadableStreamToArray<T>(stream: ReadableStream<T>): Promise<T[]>;
declare function convertResponseStreamToArray(response: Response): Promise<string[]>;
/**
* @deprecated Use createTestServer instead
*/
declare class JsonTestServer {
readonly server: SetupServer;
responseHeaders: Record<string, string>;
responseBodyJson: any;
request: Request | undefined;
/**
* @deprecated Use createTestServer instead
*/
constructor(url: string);
getRequestBodyJson(): Promise<any>;
getRequestHeaders(): Promise<Record<string, string>>;
getRequestUrlSearchParams(): Promise<URLSearchParams>;
getRequestUrl(): Promise<string>;
setupTestEnvironment(): void;
}
declare function mockId({ prefix, }?: {
prefix?: string;
}): () => string;
/**
* @deprecated Use createTestServer instead
*/
declare class StreamingTestServer {
readonly server: SetupServer;
responseHeaders: Record<string, string>;
responseChunks: any[];
request: Request | undefined;
/**
* @deprecated Use createTestServer instead
*/
constructor(url: string);
getRequestBodyJson(): Promise<any>;
getRequestHeaders(): Promise<Record<string, string>>;
getRequestUrlSearchParams(): Promise<URLSearchParams>;
setupTestEnvironment(): void;
}
type TestServerJsonBodyType = JsonBodyType;
type TestServerResponse = {
url: string;
headers?: Record<string, string>;
} & ({
type: 'json-value';
content: TestServerJsonBodyType;
} | {
type: 'stream-values';
content: Array<string>;
} | {
type: 'controlled-stream';
id?: string;
} | {
type: 'error';
status: number;
content?: string;
});
declare class TestServerCall$1 {
private request;
constructor(request: Request);
getRequestBodyJson(): Promise<any>;
getRequestCredentials(): RequestCredentials;
getRequestHeaders(): Record<string, string>;
getRequestUrlSearchParams(): URLSearchParams;
}
declare function withTestServer(responses: Array<TestServerResponse> | TestServerResponse, testFunction: (options: {
calls: () => Array<TestServerCall$1>;
call: (index: number) => TestServerCall$1;
getStreamController: (id: string) => ReadableStreamDefaultController<string>;
streamController: ReadableStreamDefaultController<string>;
}) => Promise<void>): () => Promise<void>;
declare function describeWithTestServer(description: string, responses: Array<TestServerResponse> | TestServerResponse, testFunction: (options: {
calls: () => Array<TestServerCall$1>;
call: (index: number) => TestServerCall$1;
getStreamController: (id: string) => ReadableStreamDefaultController<string>;
streamController: ReadableStreamDefaultController<string>;
}) => void): void;
type UrlResponse = {
type: 'json-value';
headers?: Record<string, string>;
body: JsonBodyType;
} | {
type: 'stream-chunks';
headers?: Record<string, string>;
chunks: Array<string>;
} | {
type: 'binary';
headers?: Record<string, string>;
body: Buffer;
} | {
type: 'empty';
headers?: Record<string, string>;
status?: number;
} | {
type: 'error';
headers?: Record<string, string>;
status?: number;
body?: string;
} | {
type: 'controlled-stream';
headers?: Record<string, string>;
controller: TestResponseController;
} | undefined;
type UrlResponseParameter = UrlResponse | UrlResponse[] | ((options: {
callNumber: number;
}) => UrlResponse);
type UrlHandler = {
response: UrlResponseParameter;
};
type UrlHandlers<URLS extends {
[url: string]: {
response?: UrlResponseParameter;
};
}> = {
[url in keyof URLS]: UrlHandler;
};
declare class TestServerCall {
private request;
constructor(request: Request);
get requestBody(): Promise<any>;
get requestBodyMultipart(): Promise<Record<string, any>> | null;
get requestCredentials(): RequestCredentials;
get requestHeaders(): Record<string, string>;
get requestUrlSearchParams(): URLSearchParams;
get requestUrl(): string;
get requestMethod(): string;
}
declare function createTestServer<URLS extends {
[url: string]: {
response?: UrlResponseParameter;
};
}>(routes: URLS): {
urls: UrlHandlers<URLS>;
calls: TestServerCall[];
};
declare class TestResponseController {
private readonly transformStream;
private readonly writer;
constructor();
get stream(): ReadableStream;
write(chunk: string): Promise<void>;
error(error: Error): Promise<void>;
close(): Promise<void>;
}
export { JsonTestServer, StreamingTestServer, TestResponseController, type TestServerJsonBodyType, type TestServerResponse, type UrlHandler, type UrlHandlers, type UrlResponse, convertArrayToAsyncIterable, convertArrayToReadableStream, convertAsyncIterableToArray, convertReadableStreamToArray, convertResponseStreamToArray, createTestServer, describeWithTestServer, mockId, withTestServer };

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

71
node_modules/@ai-sdk/openai/package.json generated vendored Normal file
View File

@@ -0,0 +1,71 @@
{
"name": "@ai-sdk/openai",
"version": "1.3.24",
"license": "Apache-2.0",
"sideEffects": false,
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist/**/*",
"internal/dist/**/*",
"CHANGELOG.md"
],
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./internal": {
"types": "./internal/dist/index.d.ts",
"import": "./internal/dist/index.mjs",
"module": "./internal/dist/index.mjs",
"require": "./internal/dist/index.js"
}
},
"dependencies": {
"@ai-sdk/provider": "1.1.3",
"@ai-sdk/provider-utils": "2.2.8"
},
"devDependencies": {
"@types/node": "20.17.24",
"tsup": "^8",
"typescript": "5.6.3",
"zod": "3.23.8",
"@vercel/ai-tsconfig": "0.0.0"
},
"peerDependencies": {
"zod": "^3.0.0"
},
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
},
"homepage": "https://ai-sdk.dev/docs",
"repository": {
"type": "git",
"url": "git+https://github.com/vercel/ai.git"
},
"bugs": {
"url": "https://github.com/vercel/ai/issues"
},
"keywords": [
"ai"
],
"scripts": {
"build": "tsup",
"build:watch": "tsup --watch",
"clean": "rm -rf dist && rm -rf internal/dist",
"lint": "eslint \"./**/*.ts*\"",
"type-check": "tsc --noEmit",
"prettier-check": "prettier --check \"./**/*.ts*\"",
"test": "pnpm test:node && pnpm test:edge",
"test:edge": "vitest --config vitest.edge.config.js --run",
"test:node": "vitest --config vitest.node.config.js --run",
"test:node:watch": "vitest --config vitest.node.config.js --watch"
}
}