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

834
node_modules/@ai-sdk/anthropic/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,834 @@
# @ai-sdk/anthropic
## 1.2.12
### Patch Changes
- f64f4f0: feat (providers/anthropic): add claude v4 models
## 1.2.11
### Patch Changes
- Updated dependencies [d87b9d1]
- @ai-sdk/provider-utils@2.2.8
## 1.2.10
### Patch Changes
- Updated dependencies [beef951]
- @ai-sdk/provider@1.1.3
- @ai-sdk/provider-utils@2.2.7
## 1.2.9
### Patch Changes
- aeba38e: Add support for URL-based PDF documents in the Anthropic provider
## 1.2.8
### Patch Changes
- Updated dependencies [013faa8]
- @ai-sdk/provider@1.1.2
- @ai-sdk/provider-utils@2.2.6
## 1.2.7
### Patch Changes
- Updated dependencies [c21fa6d]
- @ai-sdk/provider-utils@2.2.5
- @ai-sdk/provider@1.1.1
## 1.2.6
### Patch Changes
- Updated dependencies [2c19b9a]
- @ai-sdk/provider-utils@2.2.4
## 1.2.5
### Patch Changes
- 292f543: fix (provider/google-vertex): fix anthropic support for image urls in messages
## 1.2.4
### Patch Changes
- Updated dependencies [28be004]
- @ai-sdk/provider-utils@2.2.3
## 1.2.3
### Patch Changes
- Updated dependencies [b01120e]
- @ai-sdk/provider-utils@2.2.2
## 1.2.2
### Patch Changes
- aeaa92b: feat (provider/anthropic): expose type for validating Anthropic responses provider options
## 1.2.1
### Patch Changes
- Updated dependencies [f10f0fa]
- @ai-sdk/provider-utils@2.2.1
## 1.2.0
### Minor Changes
- 5bc638d: AI SDK 4.2
### Patch Changes
- Updated dependencies [5bc638d]
- @ai-sdk/provider@1.1.0
- @ai-sdk/provider-utils@2.2.0
## 1.1.19
### Patch Changes
- Updated dependencies [d0c4659]
- @ai-sdk/provider-utils@2.1.15
## 1.1.18
### Patch Changes
- Updated dependencies [0bd5bc6]
- @ai-sdk/provider@1.0.12
- @ai-sdk/provider-utils@2.1.14
## 1.1.17
### Patch Changes
- Updated dependencies [2e1101a]
- @ai-sdk/provider@1.0.11
- @ai-sdk/provider-utils@2.1.13
## 1.1.16
### Patch Changes
- Updated dependencies [1531959]
- @ai-sdk/provider-utils@2.1.12
## 1.1.15
### Patch Changes
- e1d3d42: feat (ai): expose raw response body in generateText and generateObject
- Updated dependencies [e1d3d42]
- @ai-sdk/provider@1.0.10
- @ai-sdk/provider-utils@2.1.11
## 1.1.14
### Patch Changes
- 0e8b66c: feat (provider/anthropic): support image urls
## 1.1.13
### Patch Changes
- 3004b14: feat(provider/anthropic): add bash_20250124 and text_editor_20250124 tools
## 1.1.12
### Patch Changes
- b3e5a15: fix (provider/anthropic): add model setting to allow omitting reasoning content from model requests
## 1.1.11
### Patch Changes
- 00276ae: feat (provider/anthropic): update types for Anthropic computer_20250124 tool
- a4f8714: feat (provider/anthropic): update beta flag for sonnet-3-7 when using new computer-use tool
## 1.1.10
### Patch Changes
- ddf9740: feat (ai): add anthropic reasoning
- Updated dependencies [ddf9740]
- @ai-sdk/provider@1.0.9
- @ai-sdk/provider-utils@2.1.10
## 1.1.9
### Patch Changes
- Updated dependencies [2761f06]
- @ai-sdk/provider@1.0.8
- @ai-sdk/provider-utils@2.1.9
## 1.1.8
### Patch Changes
- Updated dependencies [2e898b4]
- @ai-sdk/provider-utils@2.1.8
## 1.1.7
### Patch Changes
- Updated dependencies [3ff4ef8]
- @ai-sdk/provider-utils@2.1.7
## 1.1.6
### Patch Changes
- Updated dependencies [d89c3b9]
- @ai-sdk/provider@1.0.7
- @ai-sdk/provider-utils@2.1.6
## 1.1.5
### Patch Changes
- Updated dependencies [3a602ca]
- @ai-sdk/provider-utils@2.1.5
## 1.1.4
### Patch Changes
- Updated dependencies [066206e]
- @ai-sdk/provider-utils@2.1.4
## 1.1.3
### Patch Changes
- Updated dependencies [39e5c1f]
- @ai-sdk/provider-utils@2.1.3
## 1.1.2
### Patch Changes
- Updated dependencies [ed012d2]
- Updated dependencies [3a58a2e]
- @ai-sdk/provider-utils@2.1.2
- @ai-sdk/provider@1.0.6
## 1.1.1
### Patch Changes
- 858f934: feat (provider/anthropic): default cache-control on and mark model setting deprecated
- b284e2c: feat (provider/google-vertex): support prompt caching for Anthropic Claude models
- Updated dependencies [e7a9ec9]
- Updated dependencies [0a699f1]
- @ai-sdk/provider-utils@2.1.1
- @ai-sdk/provider@1.0.5
## 1.1.0
### Minor Changes
- 62ba5ad: release: AI SDK 4.1
### Patch Changes
- Updated dependencies [62ba5ad]
- @ai-sdk/provider-utils@2.1.0
## 1.0.9
### Patch Changes
- Updated dependencies [00114c5]
- @ai-sdk/provider-utils@2.0.8
## 1.0.8
### Patch Changes
- Updated dependencies [90fb95a]
- Updated dependencies [e6dfef4]
- Updated dependencies [6636db6]
- @ai-sdk/provider-utils@2.0.7
## 1.0.7
### Patch Changes
- Updated dependencies [19a2ce7]
- Updated dependencies [19a2ce7]
- Updated dependencies [6337688]
- @ai-sdk/provider@1.0.4
- @ai-sdk/provider-utils@2.0.6
## 1.0.6
### Patch Changes
- 5ed5e45: chore (config): Use ts-library.json tsconfig for no-UI libs.
- Updated dependencies [5ed5e45]
- @ai-sdk/provider-utils@2.0.5
- @ai-sdk/provider@1.0.3
## 1.0.5
### Patch Changes
- Updated dependencies [09a9cab]
- @ai-sdk/provider@1.0.2
- @ai-sdk/provider-utils@2.0.4
## 1.0.4
### Patch Changes
- bcd892e: feat (provider/google-vertex): Add support for Anthropic models.
## 1.0.3
### Patch Changes
- Updated dependencies [0984f0b]
- @ai-sdk/provider-utils@2.0.3
## 1.0.2
### Patch Changes
- Updated dependencies [b446ae5]
- @ai-sdk/provider@1.0.1
- @ai-sdk/provider-utils@2.0.2
## 1.0.1
### Patch Changes
- Updated dependencies [c3ab5de]
- @ai-sdk/provider-utils@2.0.1
## 1.0.0
### Major Changes
- 66060f7: chore (release): bump major version to 4.0
- 0d3d3f5: chore (providers): remove baseUrl option
- 8ad0504: chore (provider/anthropic): remove Anthropic facade
- 2f6e8c0: chore (provider/anthropic): remove topK model setting
### Patch Changes
- Updated dependencies [b469a7e]
- Updated dependencies [dce4158]
- Updated dependencies [c0ddc24]
- Updated dependencies [b1da952]
- Updated dependencies [dce4158]
- Updated dependencies [8426f55]
- Updated dependencies [db46ce5]
- @ai-sdk/provider-utils@2.0.0
- @ai-sdk/provider@1.0.0
## 1.0.0-canary.4
### Major Changes
- 2f6e8c0: chore (provider/anthropic): remove topK model setting
## 1.0.0-canary.3
### Patch Changes
- Updated dependencies [8426f55]
- @ai-sdk/provider-utils@2.0.0-canary.3
## 1.0.0-canary.2
### Patch Changes
- Updated dependencies [dce4158]
- Updated dependencies [dce4158]
- @ai-sdk/provider-utils@2.0.0-canary.2
## 1.0.0-canary.1
### Major Changes
- 0d3d3f5: chore (providers): remove baseUrl option
- 8ad0504: chore (provider/anthropic): remove Anthropic facade
### Patch Changes
- Updated dependencies [b1da952]
- @ai-sdk/provider-utils@2.0.0-canary.1
## 1.0.0-canary.0
### Major Changes
- 66060f7: chore (release): bump major version to 4.0
### Patch Changes
- Updated dependencies [b469a7e]
- Updated dependencies [c0ddc24]
- Updated dependencies [db46ce5]
- @ai-sdk/provider-utils@2.0.0-canary.0
- @ai-sdk/provider@1.0.0-canary.0
## 0.0.56
### Patch Changes
- e6042b1: feat (provider/anthropic): add haiku 3.5 model ids
## 0.0.55
### Patch Changes
- ac380e3: fix (provider/anthropic): continuation mode with 3+ steps
## 0.0.54
### Patch Changes
- 4d2e53b: feat (provider/anthropic): pdf support
- c8afcb5: feat (provider/anthropic): allow using computer use and cache control at the same time
## 0.0.53
### Patch Changes
- 3b1b69a: feat (provider/anthropic): add computer use tools
- 3b1b69a: feat: provider-defined tools
- 8c222cd: feat (provider/anthropic): update model ids
- 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-utils@1.0.22
- @ai-sdk/provider@0.0.26
## 0.0.52
### Patch Changes
- b9b0d7b: feat (ai): access raw request body
- Updated dependencies [b9b0d7b]
- @ai-sdk/provider@0.0.25
- @ai-sdk/provider-utils@1.0.21
## 0.0.51
### Patch Changes
- Updated dependencies [d595d0d]
- @ai-sdk/provider@0.0.24
- @ai-sdk/provider-utils@1.0.20
## 0.0.50
### Patch Changes
- Updated dependencies [273f696]
- @ai-sdk/provider-utils@1.0.19
## 0.0.49
### Patch Changes
- 03313cd: feat (ai): expose response id, response model, response timestamp in telemetry and api
- 3be7c1c: fix (provider/anthropic): support prompt caching on assistant messages
- Updated dependencies [03313cd]
- Updated dependencies [3be7c1c]
- @ai-sdk/provider-utils@1.0.18
- @ai-sdk/provider@0.0.23
## 0.0.48
### Patch Changes
- 26515cb: feat (ai/provider): introduce ProviderV1 specification
- Updated dependencies [26515cb]
- @ai-sdk/provider@0.0.22
- @ai-sdk/provider-utils@1.0.17
## 0.0.47
### Patch Changes
- Updated dependencies [09f895f]
- @ai-sdk/provider-utils@1.0.16
## 0.0.46
### Patch Changes
- Updated dependencies [d67fa9c]
- @ai-sdk/provider-utils@1.0.15
## 0.0.45
### Patch Changes
- 95a53a3: chore (provider/anthropic): remove tool calls beta header
## 0.0.44
### Patch Changes
- Updated dependencies [f2c025e]
- @ai-sdk/provider@0.0.21
- @ai-sdk/provider-utils@1.0.14
## 0.0.43
### Patch Changes
- 6ac355e: feat (provider/anthropic): add cache control support
- Updated dependencies [6ac355e]
- @ai-sdk/provider@0.0.20
- @ai-sdk/provider-utils@1.0.13
## 0.0.42
### Patch Changes
- dd712ac: fix: use FetchFunction type to prevent self-reference
- Updated dependencies [dd712ac]
- @ai-sdk/provider-utils@1.0.12
## 0.0.41
### Patch Changes
- 89b18ca: fix (ai/provider): send finish reason 'unknown' by default
- Updated dependencies [dd4a0f5]
- @ai-sdk/provider@0.0.19
- @ai-sdk/provider-utils@1.0.11
## 0.0.40
### Patch Changes
- Updated dependencies [4bd27a9]
- Updated dependencies [845754b]
- @ai-sdk/provider-utils@1.0.10
- @ai-sdk/provider@0.0.18
## 0.0.39
### Patch Changes
- Updated dependencies [029af4c]
- @ai-sdk/provider@0.0.17
- @ai-sdk/provider-utils@1.0.9
## 0.0.38
### Patch Changes
- Updated dependencies [d58517b]
- @ai-sdk/provider@0.0.16
- @ai-sdk/provider-utils@1.0.8
## 0.0.37
### Patch Changes
- Updated dependencies [96aed25]
- @ai-sdk/provider@0.0.15
- @ai-sdk/provider-utils@1.0.7
## 0.0.36
### Patch Changes
- Updated dependencies [9614584]
- Updated dependencies [0762a22]
- @ai-sdk/provider-utils@1.0.6
## 0.0.35
### Patch Changes
- fe2128f0: feat (provider/anthropic): combine sequential assistant messages into one
## 0.0.34
### Patch Changes
- 7d0fd5a8: fix (provider/anthropic): handle error stream chunks
## 0.0.33
### Patch Changes
- a8d1c9e9: feat (ai/core): parallel image download
- Updated dependencies [a8d1c9e9]
- @ai-sdk/provider-utils@1.0.5
- @ai-sdk/provider@0.0.14
## 0.0.32
### Patch Changes
- Updated dependencies [4f88248f]
- @ai-sdk/provider-utils@1.0.4
## 0.0.31
### Patch Changes
- 2b9da0f0: feat (core): support stopSequences setting.
- a5b58845: feat (core): support topK setting
- 4aa8deb3: feat (provider): support responseFormat setting in provider api
- 13b27ec6: chore (ai/core): remove grammar mode
- Updated dependencies [2b9da0f0]
- Updated dependencies [a5b58845]
- Updated dependencies [4aa8deb3]
- Updated dependencies [13b27ec6]
- @ai-sdk/provider@0.0.13
- @ai-sdk/provider-utils@1.0.3
## 0.0.30
### Patch Changes
- 4c6b80f7: chore (provider/anthropic): improve object-tool mode
## 0.0.29
### Patch Changes
- Updated dependencies [b7290943]
- @ai-sdk/provider@0.0.12
- @ai-sdk/provider-utils@1.0.2
## 0.0.28
### Patch Changes
- Updated dependencies [d481729f]
- @ai-sdk/provider-utils@1.0.1
## 0.0.27
### Patch Changes
- 7e86b45e: fix (provider/anthropic): automatically trim trailing whitespace on pre-filled assistant responses
## 0.0.26
### Patch Changes
- 5edc6110: feat (ai/core): add custom request header support
- Updated dependencies [5edc6110]
- Updated dependencies [5edc6110]
- Updated dependencies [5edc6110]
- @ai-sdk/provider@0.0.11
- @ai-sdk/provider-utils@1.0.0
## 0.0.25
### Patch Changes
- 91dc4296: chore (@ai-sdk/anthropic): remove anthropic-beta header
## 0.0.24
### Patch Changes
- 04800838: fix (@ai-sdk/anthropic): combine tool and user messages, combine system messages
## 0.0.23
### Patch Changes
- Updated dependencies [02f6a088]
- @ai-sdk/provider-utils@0.0.16
## 0.0.22
### Patch Changes
- 0a22b05b: feat (@ai-sdk/anthropic): add claude-3.5-sonnet model
## 0.0.21
### Patch Changes
- Updated dependencies [85712895]
- Updated dependencies [85712895]
- @ai-sdk/provider-utils@0.0.15
## 0.0.20
### Patch Changes
- 4728c37f: feat (core): add text embedding model support to provider registry
- 7910ae84: feat (providers): support custom fetch implementations
- Updated dependencies [7910ae84]
- @ai-sdk/provider-utils@0.0.14
## 0.0.19
### Patch Changes
- Updated dependencies [102ca22f]
- @ai-sdk/provider@0.0.10
- @ai-sdk/provider-utils@0.0.13
## 0.0.18
### Patch Changes
- 09295e2e: feat (@ai-sdk/anthropic): automatically download image URLs
- Updated dependencies [09295e2e]
- Updated dependencies [09295e2e]
- Updated dependencies [043a5de2]
- @ai-sdk/provider@0.0.9
- @ai-sdk/provider-utils@0.0.12
## 0.0.17
### Patch Changes
- f39c0dd2: feat (provider): implement toolChoice support
- Updated dependencies [f39c0dd2]
- @ai-sdk/provider@0.0.8
- @ai-sdk/provider-utils@0.0.11
## 0.0.16
### Patch Changes
- 24683b72: fix (providers): Zod is required dependency
- Updated dependencies [8e780288]
- @ai-sdk/provider@0.0.7
- @ai-sdk/provider-utils@0.0.10
## 0.0.15
### Patch Changes
- Updated dependencies [6a50ac4]
- Updated dependencies [6a50ac4]
- @ai-sdk/provider@0.0.6
- @ai-sdk/provider-utils@0.0.9
## 0.0.14
### Patch Changes
- 06e3934: feat (provider/anthropic): streaming tool calls
## 0.0.13
### Patch Changes
- Updated dependencies [0f6bc4e]
- @ai-sdk/provider@0.0.5
- @ai-sdk/provider-utils@0.0.8
## 0.0.12
### Patch Changes
- Updated dependencies [325ca55]
- @ai-sdk/provider@0.0.4
- @ai-sdk/provider-utils@0.0.7
## 0.0.11
### Patch Changes
- 5b01c13: feat (ai/core): add system message support in messages list
## 0.0.10
### Patch Changes
- Updated dependencies [276f22b]
- @ai-sdk/provider-utils@0.0.6
## 0.0.9
### Patch Changes
- Updated dependencies [41d5736]
- @ai-sdk/provider@0.0.3
- @ai-sdk/provider-utils@0.0.5
## 0.0.8
### Patch Changes
- Updated dependencies [56ef84a]
- @ai-sdk/provider-utils@0.0.4
## 0.0.7
### Patch Changes
- 25f3350: ai/core: add support for getting raw response headers.
- Updated dependencies [d6431ae]
- Updated dependencies [25f3350]
- @ai-sdk/provider@0.0.2
- @ai-sdk/provider-utils@0.0.3
## 0.0.6
### 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-utils@0.0.2
- @ai-sdk/provider@0.0.1
## 0.0.5
### Patch Changes
- c6fc35b: Add custom header support.
## 0.0.4
### Patch Changes
- ab60b18: Simplified model construction by directly calling provider functions. Add create... functions to create provider instances.
## 0.0.3
### Patch Changes
- 587240b: Standardize providers to offer .chat() method
## 0.0.2
### Patch Changes
- 2bff460: Fix build for release.
## 0.0.1
### Patch Changes
- 7b8791d: Rename baseUrl to baseURL. Automatically remove trailing slashes.
- Updated dependencies [7b8791d]
- @ai-sdk/provider-utils@0.0.1

13
node_modules/@ai-sdk/anthropic/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.

35
node_modules/@ai-sdk/anthropic/README.md generated vendored Normal file
View File

@@ -0,0 +1,35 @@
# AI SDK - Anthropic Provider
The **[Anthropic provider](https://ai-sdk.dev/providers/ai-sdk-providers/anthropic)** for the [AI SDK](https://ai-sdk.dev/docs) contains language model support for the [Anthropic Messages API](https://docs.anthropic.com/claude/reference/messages_post).
## Setup
The Anthropic provider is available in the `@ai-sdk/anthropic` module. You can install it with
```
npm i @ai-sdk/anthropic
```
## Provider Instance
You can import the default provider instance `anthropic` from `@ai-sdk/anthropic`:
```ts
import { anthropic } from '@ai-sdk/anthropic';
```
## Example
```ts
import { anthropic } from '@ai-sdk/anthropic';
import { generateText } from 'ai';
const { text } = await generateText({
model: anthropic('claude-3-haiku-20240307'),
prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});
```
## Documentation
Please check out the **[Anthropic provider documentation](https://ai-sdk.dev/providers/ai-sdk-providers/anthropic)** for more information.

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

@@ -0,0 +1,496 @@
import { z } from 'zod';
import { ProviderV1, LanguageModelV1 } from '@ai-sdk/provider';
import { FetchFunction } from '@ai-sdk/provider-utils';
type AnthropicMessagesModelId = 'claude-4-opus-20250514' | 'claude-4-sonnet-20250514' | 'claude-3-7-sonnet-20250219' | 'claude-3-5-sonnet-latest' | 'claude-3-5-sonnet-20241022' | 'claude-3-5-sonnet-20240620' | 'claude-3-5-haiku-latest' | 'claude-3-5-haiku-20241022' | 'claude-3-opus-latest' | 'claude-3-opus-20240229' | 'claude-3-sonnet-20240229' | 'claude-3-haiku-20240307' | (string & {});
interface AnthropicMessagesSettings {
/**
Enable Anthropic cache control. This will allow you to use provider-specific
`cacheControl` metadata.
@deprecated cache control is now enabled by default (meaning you are able to
optionally mark content for caching) and this setting is no longer needed.
*/
cacheControl?: boolean;
/**
Include reasoning content in requests sent to the model. Defaults to `true`.
If you are experiencing issues with the model handling requests involving
reasoning content, you can set this to `false` to omit them from the request.
*/
sendReasoning?: boolean;
}
declare const anthropicProviderOptionsSchema: z.ZodObject<{
thinking: z.ZodOptional<z.ZodObject<{
type: z.ZodUnion<[z.ZodLiteral<"enabled">, z.ZodLiteral<"disabled">]>;
budgetTokens: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
}, {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
thinking?: {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
} | undefined;
}, {
thinking?: {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
} | undefined;
}>;
type AnthropicProviderOptions = z.infer<typeof anthropicProviderOptionsSchema>;
type ExecuteFunction<PARAMETERS, RESULT> = undefined | ((args: PARAMETERS, options: {
abortSignal?: AbortSignal;
}) => Promise<RESULT>);
type ToolResultContent = Array<{
type: 'text';
text: string;
} | {
type: 'image';
data: string;
mimeType?: string;
}>;
declare const Bash20241022Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20241022';
args: {};
parameters: typeof Bash20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Bash20250124Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20250124';
args: {};
parameters: typeof Bash20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20241022Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20241022';
args: {};
parameters: typeof TextEditor20241022Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20250124Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20250124';
args: {};
parameters: typeof TextEditor20250124Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20241022Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "type", "mouse_move", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "screenshot", "cursor_position"]>;
coordinate: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20241022<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* The action to perform. The available actions are:
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_click`: Click the left mouse button.
* - `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button.
* - `middle_click`: Click the middle mouse button.
* - `double_click`: Double-click the left mouse button.
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'type' | 'mouse_move' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'screenshot' | 'cursor_position';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: number[];
/**
* Required only by `action=type` and `action=key`.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20241022';
args: {};
parameters: typeof Computer20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20250124Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "hold_key", "type", "cursor_position", "mouse_move", "left_mouse_down", "left_mouse_up", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "triple_click", "scroll", "wait", "screenshot"]>;
coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
duration: z.ZodOptional<z.ZodNumber>;
scroll_amount: z.ZodOptional<z.ZodNumber>;
scroll_direction: z.ZodOptional<z.ZodEnum<["up", "down", "left", "right"]>>;
start_coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20250124<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `hold_key`: Hold down a key or multiple keys for a specified duration (in seconds). Supports the same syntax as `key`.
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_mouse_down`: Press the left mouse button.
* - `left_mouse_up`: Release the left mouse button.
* - `left_click`: Click the left mouse button at the specified (x, y) pixel coordinate on the screen. You can also include a key combination to hold down while clicking using the `text` parameter.
* - `left_click_drag`: Click and drag the cursor from `start_coordinate` to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button at the specified (x, y) pixel coordinate on the screen.
* - `middle_click`: Click the middle mouse button at the specified (x, y) pixel coordinate on the screen.
* - `double_click`: Double-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `triple_click`: Triple-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `scroll`: Scroll the screen in a specified direction by a specified amount of clicks of the scroll wheel, at the specified (x, y) pixel coordinate. DO NOT use PageUp/PageDown to scroll.
* - `wait`: Wait for a specified duration (in seconds).
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'hold_key' | 'type' | 'cursor_position' | 'mouse_move' | 'left_mouse_down' | 'left_mouse_up' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'triple_click' | 'scroll' | 'wait' | 'screenshot';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: [number, number];
/**
* The duration to hold the key down for. Required only by `action=hold_key` and `action=wait`.
*/
duration?: number;
/**
* The number of 'clicks' to scroll. Required only by `action=scroll`.
*/
scroll_amount?: number;
/**
* The direction to scroll the screen. Required only by `action=scroll`.
*/
scroll_direction?: 'up' | 'down' | 'left' | 'right';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to start the drag from. Required only by `action=left_click_drag`.
*/
start_coordinate?: [number, number];
/**
* Required only by `action=type`, `action=key`, and `action=hold_key`. Can also be used by click or scroll actions to hold down keys while clicking or scrolling.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20250124';
args: {};
parameters: typeof Computer20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const anthropicTools: {
bash_20241022: typeof bashTool_20241022;
bash_20250124: typeof bashTool_20250124;
textEditor_20241022: typeof textEditorTool_20241022;
textEditor_20250124: typeof textEditorTool_20250124;
computer_20241022: typeof computerTool_20241022;
computer_20250124: typeof computerTool_20250124;
};
interface AnthropicProvider extends ProviderV1 {
/**
Creates a model for text generation.
*/
(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
Creates a model for text generation.
*/
languageModel(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
@deprecated Use `.languageModel()` instead.
*/
chat(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
@deprecated Use `.languageModel()` instead.
*/
messages(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
Anthropic-specific computer use tool.
*/
tools: typeof anthropicTools;
}
interface AnthropicProviderSettings {
/**
Use a different URL prefix for API calls, e.g. to use proxy servers.
The default prefix is `https://api.anthropic.com/v1`.
*/
baseURL?: string;
/**
API key that is being send using the `x-api-key` header.
It defaults to the `ANTHROPIC_API_KEY` environment variable.
*/
apiKey?: string;
/**
Custom headers to include in the requests.
*/
headers?: Record<string, 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;
generateId?: () => string;
}
/**
Create an Anthropic provider instance.
*/
declare function createAnthropic(options?: AnthropicProviderSettings): AnthropicProvider;
/**
Default Anthropic provider instance.
*/
declare const anthropic: AnthropicProvider;
export { type AnthropicProvider, type AnthropicProviderOptions, type AnthropicProviderSettings, anthropic, createAnthropic };

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

@@ -0,0 +1,496 @@
import { z } from 'zod';
import { ProviderV1, LanguageModelV1 } from '@ai-sdk/provider';
import { FetchFunction } from '@ai-sdk/provider-utils';
type AnthropicMessagesModelId = 'claude-4-opus-20250514' | 'claude-4-sonnet-20250514' | 'claude-3-7-sonnet-20250219' | 'claude-3-5-sonnet-latest' | 'claude-3-5-sonnet-20241022' | 'claude-3-5-sonnet-20240620' | 'claude-3-5-haiku-latest' | 'claude-3-5-haiku-20241022' | 'claude-3-opus-latest' | 'claude-3-opus-20240229' | 'claude-3-sonnet-20240229' | 'claude-3-haiku-20240307' | (string & {});
interface AnthropicMessagesSettings {
/**
Enable Anthropic cache control. This will allow you to use provider-specific
`cacheControl` metadata.
@deprecated cache control is now enabled by default (meaning you are able to
optionally mark content for caching) and this setting is no longer needed.
*/
cacheControl?: boolean;
/**
Include reasoning content in requests sent to the model. Defaults to `true`.
If you are experiencing issues with the model handling requests involving
reasoning content, you can set this to `false` to omit them from the request.
*/
sendReasoning?: boolean;
}
declare const anthropicProviderOptionsSchema: z.ZodObject<{
thinking: z.ZodOptional<z.ZodObject<{
type: z.ZodUnion<[z.ZodLiteral<"enabled">, z.ZodLiteral<"disabled">]>;
budgetTokens: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
}, {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
}>>;
}, "strip", z.ZodTypeAny, {
thinking?: {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
} | undefined;
}, {
thinking?: {
type: "enabled" | "disabled";
budgetTokens?: number | undefined;
} | undefined;
}>;
type AnthropicProviderOptions = z.infer<typeof anthropicProviderOptionsSchema>;
type ExecuteFunction<PARAMETERS, RESULT> = undefined | ((args: PARAMETERS, options: {
abortSignal?: AbortSignal;
}) => Promise<RESULT>);
type ToolResultContent = Array<{
type: 'text';
text: string;
} | {
type: 'image';
data: string;
mimeType?: string;
}>;
declare const Bash20241022Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20241022';
args: {};
parameters: typeof Bash20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Bash20250124Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20250124';
args: {};
parameters: typeof Bash20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20241022Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20241022';
args: {};
parameters: typeof TextEditor20241022Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20250124Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20250124';
args: {};
parameters: typeof TextEditor20250124Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20241022Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "type", "mouse_move", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "screenshot", "cursor_position"]>;
coordinate: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20241022<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* The action to perform. The available actions are:
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_click`: Click the left mouse button.
* - `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button.
* - `middle_click`: Click the middle mouse button.
* - `double_click`: Double-click the left mouse button.
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'type' | 'mouse_move' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'screenshot' | 'cursor_position';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: number[];
/**
* Required only by `action=type` and `action=key`.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20241022';
args: {};
parameters: typeof Computer20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20250124Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "hold_key", "type", "cursor_position", "mouse_move", "left_mouse_down", "left_mouse_up", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "triple_click", "scroll", "wait", "screenshot"]>;
coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
duration: z.ZodOptional<z.ZodNumber>;
scroll_amount: z.ZodOptional<z.ZodNumber>;
scroll_direction: z.ZodOptional<z.ZodEnum<["up", "down", "left", "right"]>>;
start_coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20250124<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `hold_key`: Hold down a key or multiple keys for a specified duration (in seconds). Supports the same syntax as `key`.
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_mouse_down`: Press the left mouse button.
* - `left_mouse_up`: Release the left mouse button.
* - `left_click`: Click the left mouse button at the specified (x, y) pixel coordinate on the screen. You can also include a key combination to hold down while clicking using the `text` parameter.
* - `left_click_drag`: Click and drag the cursor from `start_coordinate` to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button at the specified (x, y) pixel coordinate on the screen.
* - `middle_click`: Click the middle mouse button at the specified (x, y) pixel coordinate on the screen.
* - `double_click`: Double-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `triple_click`: Triple-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `scroll`: Scroll the screen in a specified direction by a specified amount of clicks of the scroll wheel, at the specified (x, y) pixel coordinate. DO NOT use PageUp/PageDown to scroll.
* - `wait`: Wait for a specified duration (in seconds).
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'hold_key' | 'type' | 'cursor_position' | 'mouse_move' | 'left_mouse_down' | 'left_mouse_up' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'triple_click' | 'scroll' | 'wait' | 'screenshot';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: [number, number];
/**
* The duration to hold the key down for. Required only by `action=hold_key` and `action=wait`.
*/
duration?: number;
/**
* The number of 'clicks' to scroll. Required only by `action=scroll`.
*/
scroll_amount?: number;
/**
* The direction to scroll the screen. Required only by `action=scroll`.
*/
scroll_direction?: 'up' | 'down' | 'left' | 'right';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to start the drag from. Required only by `action=left_click_drag`.
*/
start_coordinate?: [number, number];
/**
* Required only by `action=type`, `action=key`, and `action=hold_key`. Can also be used by click or scroll actions to hold down keys while clicking or scrolling.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20250124';
args: {};
parameters: typeof Computer20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const anthropicTools: {
bash_20241022: typeof bashTool_20241022;
bash_20250124: typeof bashTool_20250124;
textEditor_20241022: typeof textEditorTool_20241022;
textEditor_20250124: typeof textEditorTool_20250124;
computer_20241022: typeof computerTool_20241022;
computer_20250124: typeof computerTool_20250124;
};
interface AnthropicProvider extends ProviderV1 {
/**
Creates a model for text generation.
*/
(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
Creates a model for text generation.
*/
languageModel(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
@deprecated Use `.languageModel()` instead.
*/
chat(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
@deprecated Use `.languageModel()` instead.
*/
messages(modelId: AnthropicMessagesModelId, settings?: AnthropicMessagesSettings): LanguageModelV1;
/**
Anthropic-specific computer use tool.
*/
tools: typeof anthropicTools;
}
interface AnthropicProviderSettings {
/**
Use a different URL prefix for API calls, e.g. to use proxy servers.
The default prefix is `https://api.anthropic.com/v1`.
*/
baseURL?: string;
/**
API key that is being send using the `x-api-key` header.
It defaults to the `ANTHROPIC_API_KEY` environment variable.
*/
apiKey?: string;
/**
Custom headers to include in the requests.
*/
headers?: Record<string, 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;
generateId?: () => string;
}
/**
Create an Anthropic provider instance.
*/
declare function createAnthropic(options?: AnthropicProviderSettings): AnthropicProvider;
/**
Default Anthropic provider instance.
*/
declare const anthropic: AnthropicProvider;
export { type AnthropicProvider, type AnthropicProviderOptions, type AnthropicProviderSettings, anthropic, createAnthropic };

1201
node_modules/@ai-sdk/anthropic/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

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

File diff suppressed because one or more lines are too long

1191
node_modules/@ai-sdk/anthropic/dist/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,446 @@
import { LanguageModelV1 } from '@ai-sdk/provider';
import { Resolvable, FetchFunction } from '@ai-sdk/provider-utils';
import { z } from 'zod';
type AnthropicMessagesModelId = 'claude-4-opus-20250514' | 'claude-4-sonnet-20250514' | 'claude-3-7-sonnet-20250219' | 'claude-3-5-sonnet-latest' | 'claude-3-5-sonnet-20241022' | 'claude-3-5-sonnet-20240620' | 'claude-3-5-haiku-latest' | 'claude-3-5-haiku-20241022' | 'claude-3-opus-latest' | 'claude-3-opus-20240229' | 'claude-3-sonnet-20240229' | 'claude-3-haiku-20240307' | (string & {});
interface AnthropicMessagesSettings {
/**
Enable Anthropic cache control. This will allow you to use provider-specific
`cacheControl` metadata.
@deprecated cache control is now enabled by default (meaning you are able to
optionally mark content for caching) and this setting is no longer needed.
*/
cacheControl?: boolean;
/**
Include reasoning content in requests sent to the model. Defaults to `true`.
If you are experiencing issues with the model handling requests involving
reasoning content, you can set this to `false` to omit them from the request.
*/
sendReasoning?: boolean;
}
type AnthropicMessagesConfig = {
provider: string;
baseURL: string;
headers: Resolvable<Record<string, string | undefined>>;
supportsImageUrls: boolean;
fetch?: FetchFunction;
buildRequestUrl?: (baseURL: string, isStreaming: boolean) => string;
transformRequestBody?: (args: Record<string, any>) => Record<string, any>;
};
declare class AnthropicMessagesLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode = "tool";
readonly modelId: AnthropicMessagesModelId;
readonly settings: AnthropicMessagesSettings;
private readonly config;
constructor(modelId: AnthropicMessagesModelId, settings: AnthropicMessagesSettings, config: AnthropicMessagesConfig);
supportsUrl(url: URL): boolean;
get provider(): string;
get supportsImageUrls(): boolean;
private getArgs;
private getHeaders;
private buildRequestUrl;
private transformRequestBody;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type ExecuteFunction<PARAMETERS, RESULT> = undefined | ((args: PARAMETERS, options: {
abortSignal?: AbortSignal;
}) => Promise<RESULT>);
type ToolResultContent = Array<{
type: 'text';
text: string;
} | {
type: 'image';
data: string;
mimeType?: string;
}>;
declare const Bash20241022Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20241022';
args: {};
parameters: typeof Bash20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Bash20250124Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20250124';
args: {};
parameters: typeof Bash20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20241022Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20241022';
args: {};
parameters: typeof TextEditor20241022Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20250124Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20250124';
args: {};
parameters: typeof TextEditor20250124Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20241022Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "type", "mouse_move", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "screenshot", "cursor_position"]>;
coordinate: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20241022<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* The action to perform. The available actions are:
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_click`: Click the left mouse button.
* - `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button.
* - `middle_click`: Click the middle mouse button.
* - `double_click`: Double-click the left mouse button.
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'type' | 'mouse_move' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'screenshot' | 'cursor_position';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: number[];
/**
* Required only by `action=type` and `action=key`.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20241022';
args: {};
parameters: typeof Computer20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20250124Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "hold_key", "type", "cursor_position", "mouse_move", "left_mouse_down", "left_mouse_up", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "triple_click", "scroll", "wait", "screenshot"]>;
coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
duration: z.ZodOptional<z.ZodNumber>;
scroll_amount: z.ZodOptional<z.ZodNumber>;
scroll_direction: z.ZodOptional<z.ZodEnum<["up", "down", "left", "right"]>>;
start_coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20250124<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `hold_key`: Hold down a key or multiple keys for a specified duration (in seconds). Supports the same syntax as `key`.
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_mouse_down`: Press the left mouse button.
* - `left_mouse_up`: Release the left mouse button.
* - `left_click`: Click the left mouse button at the specified (x, y) pixel coordinate on the screen. You can also include a key combination to hold down while clicking using the `text` parameter.
* - `left_click_drag`: Click and drag the cursor from `start_coordinate` to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button at the specified (x, y) pixel coordinate on the screen.
* - `middle_click`: Click the middle mouse button at the specified (x, y) pixel coordinate on the screen.
* - `double_click`: Double-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `triple_click`: Triple-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `scroll`: Scroll the screen in a specified direction by a specified amount of clicks of the scroll wheel, at the specified (x, y) pixel coordinate. DO NOT use PageUp/PageDown to scroll.
* - `wait`: Wait for a specified duration (in seconds).
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'hold_key' | 'type' | 'cursor_position' | 'mouse_move' | 'left_mouse_down' | 'left_mouse_up' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'triple_click' | 'scroll' | 'wait' | 'screenshot';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: [number, number];
/**
* The duration to hold the key down for. Required only by `action=hold_key` and `action=wait`.
*/
duration?: number;
/**
* The number of 'clicks' to scroll. Required only by `action=scroll`.
*/
scroll_amount?: number;
/**
* The direction to scroll the screen. Required only by `action=scroll`.
*/
scroll_direction?: 'up' | 'down' | 'left' | 'right';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to start the drag from. Required only by `action=left_click_drag`.
*/
start_coordinate?: [number, number];
/**
* Required only by `action=type`, `action=key`, and `action=hold_key`. Can also be used by click or scroll actions to hold down keys while clicking or scrolling.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20250124';
args: {};
parameters: typeof Computer20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const anthropicTools: {
bash_20241022: typeof bashTool_20241022;
bash_20250124: typeof bashTool_20250124;
textEditor_20241022: typeof textEditorTool_20241022;
textEditor_20250124: typeof textEditorTool_20250124;
computer_20241022: typeof computerTool_20241022;
computer_20250124: typeof computerTool_20250124;
};
export { AnthropicMessagesLanguageModel, type AnthropicMessagesModelId, type AnthropicMessagesSettings, anthropicTools };

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

@@ -0,0 +1,446 @@
import { LanguageModelV1 } from '@ai-sdk/provider';
import { Resolvable, FetchFunction } from '@ai-sdk/provider-utils';
import { z } from 'zod';
type AnthropicMessagesModelId = 'claude-4-opus-20250514' | 'claude-4-sonnet-20250514' | 'claude-3-7-sonnet-20250219' | 'claude-3-5-sonnet-latest' | 'claude-3-5-sonnet-20241022' | 'claude-3-5-sonnet-20240620' | 'claude-3-5-haiku-latest' | 'claude-3-5-haiku-20241022' | 'claude-3-opus-latest' | 'claude-3-opus-20240229' | 'claude-3-sonnet-20240229' | 'claude-3-haiku-20240307' | (string & {});
interface AnthropicMessagesSettings {
/**
Enable Anthropic cache control. This will allow you to use provider-specific
`cacheControl` metadata.
@deprecated cache control is now enabled by default (meaning you are able to
optionally mark content for caching) and this setting is no longer needed.
*/
cacheControl?: boolean;
/**
Include reasoning content in requests sent to the model. Defaults to `true`.
If you are experiencing issues with the model handling requests involving
reasoning content, you can set this to `false` to omit them from the request.
*/
sendReasoning?: boolean;
}
type AnthropicMessagesConfig = {
provider: string;
baseURL: string;
headers: Resolvable<Record<string, string | undefined>>;
supportsImageUrls: boolean;
fetch?: FetchFunction;
buildRequestUrl?: (baseURL: string, isStreaming: boolean) => string;
transformRequestBody?: (args: Record<string, any>) => Record<string, any>;
};
declare class AnthropicMessagesLanguageModel implements LanguageModelV1 {
readonly specificationVersion = "v1";
readonly defaultObjectGenerationMode = "tool";
readonly modelId: AnthropicMessagesModelId;
readonly settings: AnthropicMessagesSettings;
private readonly config;
constructor(modelId: AnthropicMessagesModelId, settings: AnthropicMessagesSettings, config: AnthropicMessagesConfig);
supportsUrl(url: URL): boolean;
get provider(): string;
get supportsImageUrls(): boolean;
private getArgs;
private getHeaders;
private buildRequestUrl;
private transformRequestBody;
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
}
type ExecuteFunction<PARAMETERS, RESULT> = undefined | ((args: PARAMETERS, options: {
abortSignal?: AbortSignal;
}) => Promise<RESULT>);
type ToolResultContent = Array<{
type: 'text';
text: string;
} | {
type: 'image';
data: string;
mimeType?: string;
}>;
declare const Bash20241022Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20241022';
args: {};
parameters: typeof Bash20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Bash20250124Parameters: z.ZodObject<{
command: z.ZodString;
restart: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
command: string;
restart?: boolean | undefined;
}, {
command: string;
restart?: boolean | undefined;
}>;
/**
* Creates a tool for running a bash command. Must have name "bash".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function bashTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The bash command to run. Required unless the tool is being restarted.
*/
command: string;
/**
* Specifying true will restart this tool. Otherwise, leave this unspecified.
*/
restart?: boolean;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.bash_20250124';
args: {};
parameters: typeof Bash20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Bash20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20241022Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20241022<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20241022';
args: {};
parameters: typeof TextEditor20241022Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const TextEditor20250124Parameters: z.ZodObject<{
command: z.ZodEnum<["view", "create", "str_replace", "insert", "undo_edit"]>;
path: z.ZodString;
file_text: z.ZodOptional<z.ZodString>;
insert_line: z.ZodOptional<z.ZodNumber>;
new_str: z.ZodOptional<z.ZodString>;
old_str: z.ZodOptional<z.ZodString>;
view_range: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
}, "strip", z.ZodTypeAny, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}, {
path: string;
command: "view" | "create" | "str_replace" | "insert" | "undo_edit";
file_text?: string | undefined;
insert_line?: number | undefined;
new_str?: string | undefined;
old_str?: string | undefined;
view_range?: number[] | undefined;
}>;
/**
* Creates a tool for editing text. Must have name "str_replace_editor".
*
* Image results are supported.
*
* @param execute - The function to execute the tool. Optional.
*/
declare function textEditorTool_20250124<RESULT>(options?: {
execute?: ExecuteFunction<{
/**
* The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.
*/
command: 'view' | 'create' | 'str_replace' | 'insert' | 'undo_edit';
/**
* Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.
*/
path: string;
/**
* Required parameter of `create` command, with the content of the file to be created.
*/
file_text?: string;
/**
* Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.
*/
insert_line?: number;
/**
* Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.
*/
new_str?: string;
/**
* Required parameter of `str_replace` command containing the string in `path` to replace.
*/
old_str?: string;
/**
* Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.
*/
view_range?: number[];
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.text_editor_20250124';
args: {};
parameters: typeof TextEditor20250124Parameters;
execute: ExecuteFunction<z.infer<typeof TextEditor20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20241022Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "type", "mouse_move", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "screenshot", "cursor_position"]>;
coordinate: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position";
text?: string | undefined;
coordinate?: number[] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20241022<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* The action to perform. The available actions are:
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_click`: Click the left mouse button.
* - `left_click_drag`: Click and drag the cursor to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button.
* - `middle_click`: Click the middle mouse button.
* - `double_click`: Double-click the left mouse button.
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'type' | 'mouse_move' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'screenshot' | 'cursor_position';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: number[];
/**
* Required only by `action=type` and `action=key`.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20241022';
args: {};
parameters: typeof Computer20241022Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20241022Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const Computer20250124Parameters: z.ZodObject<{
action: z.ZodEnum<["key", "hold_key", "type", "cursor_position", "mouse_move", "left_mouse_down", "left_mouse_up", "left_click", "left_click_drag", "right_click", "middle_click", "double_click", "triple_click", "scroll", "wait", "screenshot"]>;
coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
duration: z.ZodOptional<z.ZodNumber>;
scroll_amount: z.ZodOptional<z.ZodNumber>;
scroll_direction: z.ZodOptional<z.ZodEnum<["up", "down", "left", "right"]>>;
start_coordinate: z.ZodOptional<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
text: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}, {
action: "type" | "key" | "mouse_move" | "left_click" | "left_click_drag" | "right_click" | "middle_click" | "double_click" | "screenshot" | "cursor_position" | "hold_key" | "left_mouse_down" | "left_mouse_up" | "triple_click" | "scroll" | "wait";
text?: string | undefined;
coordinate?: [number, number] | undefined;
duration?: number | undefined;
scroll_amount?: number | undefined;
scroll_direction?: "up" | "down" | "left" | "right" | undefined;
start_coordinate?: [number, number] | undefined;
}>;
/**
* Creates a tool for executing actions on a computer. Must have name "computer".
*
* Image results are supported.
*
* @param displayWidthPx - The width of the display being controlled by the model in pixels.
* @param displayHeightPx - The height of the display being controlled by the model in pixels.
* @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
* @param execute - The function to execute the tool. Optional.
*/
declare function computerTool_20250124<RESULT>(options: {
displayWidthPx: number;
displayHeightPx: number;
displayNumber?: number;
execute?: ExecuteFunction<{
/**
* - `key`: Press a key or key-combination on the keyboard.
* - This supports xdotool's `key` syntax.
* - Examples: "a", "Return", "alt+Tab", "ctrl+s", "Up", "KP_0" (for the numpad 0 key).
* - `hold_key`: Hold down a key or multiple keys for a specified duration (in seconds). Supports the same syntax as `key`.
* - `type`: Type a string of text on the keyboard.
* - `cursor_position`: Get the current (x, y) pixel coordinate of the cursor on the screen.
* - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on the screen.
* - `left_mouse_down`: Press the left mouse button.
* - `left_mouse_up`: Release the left mouse button.
* - `left_click`: Click the left mouse button at the specified (x, y) pixel coordinate on the screen. You can also include a key combination to hold down while clicking using the `text` parameter.
* - `left_click_drag`: Click and drag the cursor from `start_coordinate` to a specified (x, y) pixel coordinate on the screen.
* - `right_click`: Click the right mouse button at the specified (x, y) pixel coordinate on the screen.
* - `middle_click`: Click the middle mouse button at the specified (x, y) pixel coordinate on the screen.
* - `double_click`: Double-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `triple_click`: Triple-click the left mouse button at the specified (x, y) pixel coordinate on the screen.
* - `scroll`: Scroll the screen in a specified direction by a specified amount of clicks of the scroll wheel, at the specified (x, y) pixel coordinate. DO NOT use PageUp/PageDown to scroll.
* - `wait`: Wait for a specified duration (in seconds).
* - `screenshot`: Take a screenshot of the screen.
*/
action: 'key' | 'hold_key' | 'type' | 'cursor_position' | 'mouse_move' | 'left_mouse_down' | 'left_mouse_up' | 'left_click' | 'left_click_drag' | 'right_click' | 'middle_click' | 'double_click' | 'triple_click' | 'scroll' | 'wait' | 'screenshot';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to move the mouse to. Required only by `action=mouse_move` and `action=left_click_drag`.
*/
coordinate?: [number, number];
/**
* The duration to hold the key down for. Required only by `action=hold_key` and `action=wait`.
*/
duration?: number;
/**
* The number of 'clicks' to scroll. Required only by `action=scroll`.
*/
scroll_amount?: number;
/**
* The direction to scroll the screen. Required only by `action=scroll`.
*/
scroll_direction?: 'up' | 'down' | 'left' | 'right';
/**
* (x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates to start the drag from. Required only by `action=left_click_drag`.
*/
start_coordinate?: [number, number];
/**
* Required only by `action=type`, `action=key`, and `action=hold_key`. Can also be used by click or scroll actions to hold down keys while clicking or scrolling.
*/
text?: string;
}, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
}): {
type: 'provider-defined';
id: 'anthropic.computer_20250124';
args: {};
parameters: typeof Computer20250124Parameters;
execute: ExecuteFunction<z.infer<typeof Computer20250124Parameters>, RESULT>;
experimental_toToolResultContent?: (result: RESULT) => ToolResultContent;
};
declare const anthropicTools: {
bash_20241022: typeof bashTool_20241022;
bash_20250124: typeof bashTool_20250124;
textEditor_20241022: typeof textEditorTool_20241022;
textEditor_20250124: typeof textEditorTool_20250124;
computer_20241022: typeof computerTool_20241022;
computer_20250124: typeof computerTool_20250124;
};
export { AnthropicMessagesLanguageModel, type AnthropicMessagesModelId, type AnthropicMessagesSettings, anthropicTools };

1158
node_modules/@ai-sdk/anthropic/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

1143
node_modules/@ai-sdk/anthropic/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

70
node_modules/@ai-sdk/anthropic/package.json generated vendored Normal file
View File

@@ -0,0 +1,70 @@
{
"name": "@ai-sdk/anthropic",
"version": "1.2.12",
"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"
}
}