ai 3.1.0-canary.3 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.d.mts +982 -24
- package/dist/index.d.ts +982 -24
- package/dist/index.js +1748 -175
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1723 -174
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -31
- package/prompts/dist/index.d.mts +13 -1
- package/prompts/dist/index.d.ts +13 -1
- package/prompts/dist/index.js +13 -0
- package/prompts/dist/index.js.map +1 -1
- package/prompts/dist/index.mjs +12 -0
- package/prompts/dist/index.mjs.map +1 -1
- package/react/dist/index.d.mts +27 -6
- package/react/dist/index.d.ts +31 -8
- package/react/dist/index.js +155 -141
- package/react/dist/index.js.map +1 -1
- package/react/dist/index.mjs +154 -141
- package/react/dist/index.mjs.map +1 -1
- package/react/dist/index.server.d.mts +4 -2
- package/react/dist/index.server.d.ts +4 -2
- package/react/dist/index.server.js.map +1 -1
- package/react/dist/index.server.mjs.map +1 -1
- package/rsc/dist/index.d.ts +385 -20
- package/rsc/dist/rsc-client.d.mts +1 -1
- package/rsc/dist/rsc-client.mjs +2 -0
- package/rsc/dist/rsc-client.mjs.map +1 -1
- package/rsc/dist/rsc-server.d.mts +367 -20
- package/rsc/dist/rsc-server.mjs +676 -35
- package/rsc/dist/rsc-server.mjs.map +1 -1
- package/rsc/dist/rsc-shared.d.mts +24 -9
- package/rsc/dist/rsc-shared.mjs +98 -4
- package/rsc/dist/rsc-shared.mjs.map +1 -1
- package/solid/dist/index.d.mts +7 -3
- package/solid/dist/index.d.ts +7 -3
- package/solid/dist/index.js +106 -107
- package/solid/dist/index.js.map +1 -1
- package/solid/dist/index.mjs +106 -107
- package/solid/dist/index.mjs.map +1 -1
- package/svelte/dist/index.d.mts +7 -3
- package/svelte/dist/index.d.ts +7 -3
- package/svelte/dist/index.js +109 -109
- package/svelte/dist/index.js.map +1 -1
- package/svelte/dist/index.mjs +109 -109
- package/svelte/dist/index.mjs.map +1 -1
- package/vue/dist/index.d.mts +7 -3
- package/vue/dist/index.d.ts +7 -3
- package/vue/dist/index.js +106 -107
- package/vue/dist/index.js.map +1 -1
- package/vue/dist/index.mjs +106 -107
- package/vue/dist/index.mjs.map +1 -1
- package/ai-model-specification/dist/index.d.mts +0 -606
- package/ai-model-specification/dist/index.d.ts +0 -606
- package/ai-model-specification/dist/index.js +0 -617
- package/ai-model-specification/dist/index.js.map +0 -1
- package/ai-model-specification/dist/index.mjs +0 -560
- package/ai-model-specification/dist/index.mjs.map +0 -1
- package/core/dist/index.d.mts +0 -590
- package/core/dist/index.d.ts +0 -590
- package/core/dist/index.js +0 -1528
- package/core/dist/index.js.map +0 -1
- package/core/dist/index.mjs +0 -1481
- package/core/dist/index.mjs.map +0 -1
- package/provider/dist/index.d.mts +0 -429
- package/provider/dist/index.d.ts +0 -429
- package/provider/dist/index.js +0 -1194
- package/provider/dist/index.js.map +0 -1
- package/provider/dist/index.mjs +0 -1158
- package/provider/dist/index.mjs.map +0 -1
package/core/dist/index.mjs.map
DELETED
@@ -1 +0,0 @@
|
|
1
|
-
{"version":3,"sources":["../generate-object/generate-object.ts","../../ai-model-specification/errors/ai-invalid-argument-error.ts","../../ai-model-specification/util/get-error-message.ts","../../ai-model-specification/errors/json-parse-error.ts","../../ai-model-specification/errors/no-object-generated-error.ts","../../ai-model-specification/errors/retry-error.ts","../../ai-model-specification/errors/type-validation-error.ts","../../ai-model-specification/util/parse-json.ts","../../ai-model-specification/util/validate-types.ts","../../ai-model-specification/util/uint8-utils.ts","../generate-text/token-usage.ts","../prompt/data-content.ts","../prompt/convert-to-language-model-prompt.ts","../prompt/get-input-format.ts","../prompt/validate-call-settings.ts","../util/delay.ts","../util/retry-with-exponential-backoff.ts","../generate-object/inject-json-schema-into-system.ts","../generate-object/stream-object.ts","../util/is-deep-equal-data.ts","../util/parse-partial-json.ts","../util/fix-json.ts","../generate-text/generate-text.ts","../generate-text/tool-call.ts","../generate-text/stream-text.ts","../generate-text/run-tools-transformation.ts","../tool/tool.ts"],"sourcesContent":["import { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\nimport {\n LanguageModelV1,\n LanguageModelV1FinishReason,\n NoTextGeneratedError,\n safeParseJSON,\n} from '../../ai-model-specification';\nimport { TokenUsage, calculateTokenUsage } from '../generate-text/token-usage';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { getInputFormat } from '../prompt/get-input-format';\nimport { Prompt } from '../prompt/prompt';\nimport { validateCallSettings } from '../prompt/validate-call-settings';\nimport { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff';\nimport { injectJsonSchemaIntoSystem } from './inject-json-schema-into-system';\n\n/**\n * Generate a structured, typed object using a language model.\n */\nexport async function generateObject<T>({\n model,\n schema,\n mode,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n ...settings\n}: CallSettings &\n Prompt & {\n model: LanguageModelV1;\n schema: z.Schema<T>;\n mode?: 'auto' | 'json' | 'tool' | 'grammar';\n }): Promise<GenerateObjectResult<T>> {\n const retry = retryWithExponentialBackoff({ maxRetries });\n const jsonSchema = zodToJsonSchema(schema);\n\n // use the default provider mode when the mode is set to 'auto' or unspecified\n if (mode === 'auto' || mode == null) {\n mode = model.defaultObjectGenerationMode;\n }\n\n let result: string;\n let finishReason: LanguageModelV1FinishReason;\n let usage: Parameters<typeof calculateTokenUsage>[0];\n\n switch (mode) {\n case 'json': {\n const generateResult = await retry(() =>\n model.doGenerate({\n mode: { type: 'object-json' },\n ...validateCallSettings(settings),\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({\n system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),\n prompt,\n messages,\n }),\n abortSignal,\n }),\n );\n\n if (generateResult.text === undefined) {\n throw new NoTextGeneratedError();\n }\n\n result = generateResult.text;\n finishReason = generateResult.finishReason;\n usage = generateResult.usage;\n\n break;\n }\n\n case 'grammar': {\n const generateResult = await retry(() =>\n model.doGenerate({\n mode: { type: 'object-grammar', schema: jsonSchema },\n ...settings,\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({\n system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),\n prompt,\n messages,\n }),\n abortSignal,\n }),\n );\n\n if (generateResult.text === undefined) {\n throw new NoTextGeneratedError();\n }\n\n result = generateResult.text;\n finishReason = generateResult.finishReason;\n usage = generateResult.usage;\n\n break;\n }\n\n case 'tool': {\n const generateResult = await retry(() =>\n model.doGenerate({\n mode: {\n type: 'object-tool',\n tool: {\n type: 'function',\n name: 'json',\n description: 'Respond with a JSON object.',\n parameters: jsonSchema,\n },\n },\n ...settings,\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({ system, prompt, messages }),\n abortSignal,\n }),\n );\n\n const functionArgs = generateResult.toolCalls?.[0]?.args;\n\n if (functionArgs === undefined) {\n throw new NoTextGeneratedError();\n }\n\n result = functionArgs;\n finishReason = generateResult.finishReason;\n usage = generateResult.usage;\n\n break;\n }\n\n case undefined: {\n throw new Error('Model does not have a default object generation mode.');\n }\n\n default: {\n const _exhaustiveCheck: never = mode;\n throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);\n }\n }\n\n const parseResult = safeParseJSON({ text: result, schema });\n\n if (!parseResult.success) {\n throw parseResult.error;\n }\n\n return new GenerateObjectResult({\n object: parseResult.value,\n finishReason,\n usage: calculateTokenUsage(usage),\n });\n}\n\nexport class GenerateObjectResult<T> {\n readonly object: T;\n readonly finishReason: LanguageModelV1FinishReason;\n readonly usage: TokenUsage;\n\n constructor(options: {\n object: T;\n finishReason: LanguageModelV1FinishReason;\n usage: TokenUsage;\n }) {\n this.object = options.object;\n this.finishReason = options.finishReason;\n this.usage = options.usage;\n }\n}\n","export class AI_InvalidArgumentError extends Error {\n readonly parameter: string;\n readonly value: unknown;\n // readonly learnMore =\n // 'https://sdk.vercel.com/docs/ai/errors/ai_invalid_argument_error';\n\n constructor({\n parameter,\n value,\n message,\n }: {\n parameter: string;\n value: unknown;\n message: string;\n }) {\n super(`Invalid argument for parameter ${parameter}: ${message}`);\n\n this.name = 'AI_InvalidArgumentError';\n\n this.parameter = parameter;\n this.value = value;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n stack: this.stack,\n\n parameter: this.parameter,\n value: this.value,\n };\n }\n}\n","export function getErrorMessage(error: unknown | undefined) {\n if (error == null) {\n return 'unknown error';\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return JSON.stringify(error);\n}\n","import { getErrorMessage } from '../util/get-error-message';\n\nexport class JSONParseError extends Error {\n // note: property order determines debugging output\n readonly text: string;\n readonly cause: unknown;\n\n constructor({ text, cause }: { text: string; cause: unknown }) {\n super(\n `JSON parsing failed: ` +\n `Text: ${text}.\\n` +\n `Error message: ${getErrorMessage(cause)}`,\n );\n\n this.name = 'JSONParseError';\n\n this.cause = cause;\n this.text = text;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n cause: this.cause,\n stack: this.stack,\n\n valueText: this.text,\n };\n }\n}\n","export class NoTextGeneratedError extends Error {\n readonly cause: unknown;\n\n constructor() {\n super(`No text generated.`);\n\n this.name = 'NoTextGeneratedError';\n }\n\n toJSON() {\n return {\n name: this.name,\n cause: this.cause,\n message: this.message,\n stack: this.stack,\n };\n }\n}\n","export type RetryErrorReason =\n | 'maxRetriesExceeded'\n | 'errorNotRetryable'\n | 'abort';\n\nexport class RetryError extends Error {\n // note: property order determines debugging output\n readonly reason: RetryErrorReason;\n readonly lastError: unknown;\n readonly errors: Array<unknown>;\n\n constructor({\n message,\n reason,\n errors,\n }: {\n message: string;\n reason: RetryErrorReason;\n errors: Array<unknown>;\n }) {\n super(message);\n\n this.name = 'RetryError';\n this.reason = reason;\n this.errors = errors;\n\n // separate our last error to make debugging via log easier:\n this.lastError = errors[errors.length - 1];\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n reason: this.reason,\n lastError: this.lastError,\n errors: this.errors,\n };\n }\n}\n","import { getErrorMessage } from '../util/get-error-message';\n\nexport class TypeValidationError extends Error {\n readonly value: unknown;\n readonly cause: unknown;\n\n constructor({ value, cause }: { value: unknown; cause: unknown }) {\n super(\n `Type validation failed: ` +\n `Value: ${JSON.stringify(value)}.\\n` +\n `Error message: ${getErrorMessage(cause)}`,\n );\n\n this.name = 'TypeValidationError';\n\n this.cause = cause;\n this.value = value;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n cause: this.cause,\n stack: this.stack,\n\n value: this.value,\n };\n }\n}\n","import SecureJSON from 'secure-json-parse';\nimport { ZodSchema } from 'zod';\nimport { JSONParseError } from '../errors/json-parse-error';\nimport { TypeValidationError } from '../errors/type-validation-error';\nimport { safeValidateTypes, validateTypes } from './validate-types';\n\n/**\n * Parses a JSON string into an unknown object.\n *\n * @param text - The JSON string to parse.\n * @returns {unknown} - The parsed JSON object.\n */\nexport function parseJSON({ text }: { text: string }): unknown;\n/**\n * Parses a JSON string into a strongly-typed object using the provided schema.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Schema<T>} schema - The schema to use for parsing the JSON.\n * @returns {T} - The parsed object.\n */\nexport function parseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema: ZodSchema<T>;\n}): T;\nexport function parseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema?: ZodSchema<T>;\n}): T {\n try {\n const value = SecureJSON.parse(text);\n\n if (schema == null) {\n return value;\n }\n\n return validateTypes({ value, schema });\n } catch (error) {\n if (\n error instanceof JSONParseError ||\n error instanceof TypeValidationError\n ) {\n throw error;\n }\n\n throw new JSONParseError({ text, cause: error });\n }\n}\n\n/**\n * Safely parses a JSON string and returns the result as an object of type `unknown`.\n *\n * @param text - The JSON string to parse.\n * @returns {object} Either an object with `success: true` and the parsed data, or an object with `success: false` and the error that occurred.\n */\nexport function safeParseJSON({\n text,\n}: {\n text: string;\n}):\n | { success: true; value: unknown }\n | { success: false; error: JSONParseError | TypeValidationError };\n/**\n * Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.\n *\n * @template T - The type of the object to parse the JSON into.\n * @param {string} text - The JSON string to parse.\n * @param {Schema<T>} schema - The schema to use for parsing the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport function safeParseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema: ZodSchema<T>;\n}):\n | { success: true; value: T }\n | { success: false; error: JSONParseError | TypeValidationError };\nexport function safeParseJSON<T>({\n text,\n schema,\n}: {\n text: string;\n schema?: ZodSchema<T>;\n}):\n | { success: true; value: T }\n | { success: false; error: JSONParseError | TypeValidationError } {\n try {\n const value = SecureJSON.parse(text);\n\n if (schema == null) {\n return {\n success: true,\n value: value as T,\n };\n }\n\n return safeValidateTypes({ value, schema });\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof JSONParseError\n ? error\n : new JSONParseError({ text, cause: error }),\n };\n }\n}\n\nexport function isParseableJson(input: string): boolean {\n try {\n SecureJSON.parse(input);\n return true;\n } catch {\n return false;\n }\n}\n","import { ZodSchema } from 'zod';\nimport { TypeValidationError } from '../errors/type-validation-error';\n\n/**\n * Validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The object to validate.\n * @param {Schema<T>} options.schema - The schema to use for validating the JSON.\n * @returns {T} - The typed object.\n */\nexport function validateTypes<T>({\n value,\n schema,\n}: {\n value: unknown;\n schema: ZodSchema<T>;\n}): T {\n try {\n return schema.parse(value);\n } catch (error) {\n throw new TypeValidationError({ value, cause: error });\n }\n}\n\n/**\n * Safely validates the types of an unknown object using a schema and\n * return a strongly-typed object.\n *\n * @template T - The type of the object to validate.\n * @param {string} options.value - The JSON object to validate.\n * @param {Schema<T>} options.schema - The schema to use for validating the JSON.\n * @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.\n */\nexport function safeValidateTypes<T>({\n value,\n schema,\n}: {\n value: unknown;\n schema: ZodSchema<T>;\n}):\n | { success: true; value: T }\n | { success: false; error: TypeValidationError } {\n try {\n const validationResult = schema.safeParse(value);\n\n if (validationResult.success) {\n return {\n success: true,\n value: validationResult.data,\n };\n }\n\n return {\n success: false,\n error: new TypeValidationError({\n value,\n cause: validationResult.error,\n }),\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof TypeValidationError\n ? error\n : new TypeValidationError({ value, cause: error }),\n };\n }\n}\n","export function convertBase64ToUint8Array(base64String: string) {\n const base64Url = base64String.replace(/-/g, '+').replace(/_/g, '/');\n const latin1string = globalThis.atob(base64Url);\n return Uint8Array.from(latin1string, byte => byte.codePointAt(0)!);\n}\n\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n let latin1string = '';\n for (const value of array) {\n latin1string += String.fromCodePoint(value);\n }\n return globalThis.btoa(latin1string);\n}\n","export type TokenUsage = {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n};\n\nexport function calculateTokenUsage(usage: {\n promptTokens: number;\n completionTokens: number;\n}): TokenUsage {\n return {\n promptTokens: usage.promptTokens,\n completionTokens: usage.completionTokens,\n totalTokens: usage.promptTokens + usage.completionTokens,\n };\n}\n","import {\n convertBase64ToUint8Array,\n convertUint8ArrayToBase64,\n} from '../../ai-model-specification';\n\n/**\n * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.\n */\nexport type DataContent = string | Uint8Array | ArrayBuffer | Buffer;\n\nexport function convertDataContentToBase64String(content: DataContent): string {\n if (typeof content === 'string') {\n return content;\n }\n\n if (content instanceof ArrayBuffer) {\n return convertUint8ArrayToBase64(new Uint8Array(content));\n }\n\n return convertUint8ArrayToBase64(content);\n}\n\nexport function convertDataContentToUint8Array(\n content: DataContent,\n): Uint8Array {\n if (content instanceof Uint8Array) {\n return content;\n }\n\n if (typeof content === 'string') {\n return convertBase64ToUint8Array(content);\n }\n\n if (content instanceof ArrayBuffer) {\n return new Uint8Array(content);\n }\n\n throw new Error(\n `Invalid data content. Expected a string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n );\n}\n","import {\n LanguageModelV1ImagePart,\n LanguageModelV1Message,\n LanguageModelV1Prompt,\n LanguageModelV1TextPart,\n} from '../../ai-model-specification';\nimport { convertDataContentToUint8Array } from './data-content';\nimport { Prompt } from './prompt';\n\nexport function convertToLanguageModelPrompt({\n system,\n prompt,\n messages,\n}: Prompt): LanguageModelV1Prompt {\n if (prompt == null && messages == null) {\n throw new Error('prompt or messages must be defined');\n }\n\n if (prompt != null && messages != null) {\n throw new Error('prompt and messages cannot be defined at the same time');\n }\n\n const languageModelMessages: LanguageModelV1Prompt = [];\n\n if (system != null) {\n languageModelMessages.push({ role: 'system', content: system });\n }\n\n if (typeof prompt === 'string') {\n languageModelMessages.push({\n role: 'user',\n content: [{ type: 'text', text: prompt }],\n });\n } else {\n messages = messages!; // it's not null because of the check above\n\n languageModelMessages.push(\n ...messages.map((message): LanguageModelV1Message => {\n switch (message.role) {\n case 'user': {\n if (typeof message.content === 'string') {\n return {\n role: 'user',\n content: [{ type: 'text', text: message.content }],\n };\n }\n\n return {\n role: 'user',\n content: message.content.map(\n (part): LanguageModelV1TextPart | LanguageModelV1ImagePart => {\n switch (part.type) {\n case 'text': {\n return part;\n }\n\n case 'image': {\n return {\n type: 'image',\n image:\n part.image instanceof URL\n ? part.image\n : convertDataContentToUint8Array(part.image),\n mimeType: part.mimeType,\n };\n }\n }\n },\n ),\n };\n }\n\n case 'assistant': {\n if (typeof message.content === 'string') {\n return {\n role: 'assistant',\n content: [{ type: 'text', text: message.content }],\n };\n }\n\n return { role: 'assistant', content: message.content };\n }\n\n case 'tool': {\n return message;\n }\n }\n }),\n );\n }\n\n return languageModelMessages;\n}\n","import { Prompt } from './prompt';\n\nexport function getInputFormat({\n prompt,\n messages,\n}: Prompt): 'prompt' | 'messages' {\n if (prompt == null && messages == null) {\n throw new Error('prompt or messages must be defined');\n }\n\n if (prompt != null && messages != null) {\n throw new Error('prompt and messages cannot be defined at the same time');\n }\n\n return prompt != null ? 'prompt' : 'messages';\n}\n","import { CallSettings } from './call-settings';\nimport { AI_InvalidArgumentError } from '../../ai-model-specification';\n\nexport function validateCallSettings(settings: CallSettings): CallSettings {\n if (settings.maxTokens != null) {\n if (!Number.isInteger(settings.maxTokens)) {\n throw new AI_InvalidArgumentError({\n parameter: 'maxTokens',\n value: settings.maxTokens,\n message: 'maxTokens must be an integer',\n });\n }\n\n if (settings.maxTokens < 1) {\n throw new AI_InvalidArgumentError({\n parameter: 'maxTokens',\n value: settings.maxTokens,\n message: 'maxTokens must be >= 1',\n });\n }\n }\n\n if (settings.temperature != null) {\n if (typeof settings.temperature !== 'number') {\n throw new AI_InvalidArgumentError({\n parameter: 'temperature',\n value: settings.temperature,\n message: 'temperature must be a number',\n });\n }\n\n if (settings.temperature < 0 || settings.temperature > 1) {\n throw new AI_InvalidArgumentError({\n parameter: 'temperature',\n value: settings.temperature,\n message: 'temperature must be between 0 and 1 (inclusive)',\n });\n }\n }\n\n if (settings.topP != null) {\n if (typeof settings.topP !== 'number') {\n throw new AI_InvalidArgumentError({\n parameter: 'topP',\n value: settings.topP,\n message: 'topP must be a number',\n });\n }\n\n if (settings.topP < 0 || settings.topP > 1) {\n throw new AI_InvalidArgumentError({\n parameter: 'topP',\n value: settings.topP,\n message: 'topP must be between 0 and 1 (inclusive)',\n });\n }\n }\n\n if (settings.presencePenalty != null) {\n if (typeof settings.presencePenalty !== 'number') {\n throw new AI_InvalidArgumentError({\n parameter: 'presencePenalty',\n value: settings.presencePenalty,\n message: 'presencePenalty must be a number',\n });\n }\n\n if (settings.presencePenalty < -1 || settings.presencePenalty > 1) {\n throw new AI_InvalidArgumentError({\n parameter: 'presencePenalty',\n value: settings.presencePenalty,\n message: 'presencePenalty must be between -1 and 1 (inclusive)',\n });\n }\n }\n\n if (settings.frequencyPenalty != null) {\n if (typeof settings.frequencyPenalty !== 'number') {\n throw new AI_InvalidArgumentError({\n parameter: 'frequencyPenalty',\n value: settings.frequencyPenalty,\n message: 'frequencyPenalty must be a number',\n });\n }\n\n if (settings.frequencyPenalty < -1 || settings.frequencyPenalty > 1) {\n throw new AI_InvalidArgumentError({\n parameter: 'frequencyPenalty',\n value: settings.frequencyPenalty,\n message: 'frequencyPenalty must be between -1 and 1 (inclusive)',\n });\n }\n }\n\n if (settings.seed != null) {\n if (!Number.isInteger(settings.seed)) {\n throw new AI_InvalidArgumentError({\n parameter: 'seed',\n value: settings.seed,\n message: 'seed must be an integer',\n });\n }\n }\n\n return settings;\n}\n","export async function delay(delayInMs: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delayInMs));\n}\n","import { RetryError, getErrorMessage } from '../../ai-model-specification';\nimport { delay } from './delay';\n\nexport type RetryFunction = <OUTPUT>(\n fn: () => PromiseLike<OUTPUT>,\n) => PromiseLike<OUTPUT>;\n\n/**\n * The `retryWithExponentialBackoff` strategy retries a failed API call with an exponential backoff.\n * You can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoff =\n ({\n maxRetries = 2,\n initialDelayInMs = 2000,\n backoffFactor = 2,\n } = {}): RetryFunction =>\n async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>\n _retryWithExponentialBackoff(f, {\n maxRetries,\n delayInMs: initialDelayInMs,\n backoffFactor,\n });\n\nasync function _retryWithExponentialBackoff<OUTPUT>(\n f: () => PromiseLike<OUTPUT>,\n {\n maxRetries,\n delayInMs,\n backoffFactor,\n }: { maxRetries: number; delayInMs: number; backoffFactor: number },\n errors: unknown[] = [],\n): Promise<OUTPUT> {\n try {\n return await f();\n } catch (error) {\n if (maxRetries === 0) {\n throw error; // don't wrap the error when retries are disabled\n }\n\n const errorMessage = getErrorMessage(error);\n const newErrors = [...errors, error];\n const tryNumber = newErrors.length;\n\n if (tryNumber > maxRetries) {\n throw new RetryError({\n message: `Failed after ${tryNumber} tries. Last error: ${errorMessage}`,\n reason: 'maxRetriesExceeded',\n errors: newErrors,\n });\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw error;\n }\n\n if (\n // deal with bundling duplication by using names\n error.name === 'ApiCallError' &&\n (error as any).isRetryable === true &&\n tryNumber <= maxRetries\n ) {\n await delay(delayInMs);\n return _retryWithExponentialBackoff(\n f,\n { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },\n newErrors,\n );\n }\n }\n\n throw new RetryError({\n message: `Failed after ${tryNumber} tries with non-retryable error: '${errorMessage}'`,\n reason: 'errorNotRetryable',\n errors: newErrors,\n });\n }\n}\n","const DEFAULT_SCHEMA_PREFIX = 'JSON schema:';\nconst DEFAULT_SCHEMA_SUFFIX =\n 'You MUST answer with a JSON object that matches the JSON schema above.';\n\nexport function injectJsonSchemaIntoSystem({\n system,\n schema,\n schemaPrefix = DEFAULT_SCHEMA_PREFIX,\n schemaSuffix = DEFAULT_SCHEMA_SUFFIX,\n}: {\n system?: string;\n schema: Record<string, unknown>;\n schemaPrefix?: string;\n schemaSuffix?: string;\n}): string {\n return [\n system,\n system != null ? '' : null, // add a newline if system is not null\n schemaPrefix,\n JSON.stringify(schema),\n schemaSuffix,\n ]\n .filter(line => line != null)\n .join('\\n');\n}\n","import { PartialDeep } from 'type-fest';\nimport { z } from 'zod';\nimport zodToJsonSchema from 'zod-to-json-schema';\nimport {\n LanguageModelV1,\n LanguageModelV1StreamPart,\n} from '../../ai-model-specification/index';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { getInputFormat } from '../prompt/get-input-format';\nimport { Prompt } from '../prompt/prompt';\nimport { validateCallSettings } from '../prompt/validate-call-settings';\nimport { isDeepEqualData } from '../util/is-deep-equal-data';\nimport { parsePartialJson } from '../util/parse-partial-json';\nimport { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff';\nimport { injectJsonSchemaIntoSystem } from './inject-json-schema-into-system';\n\n/**\n * Stream an object as a partial object stream.\n */\nexport async function streamObject<T>({\n model,\n schema,\n mode,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n ...settings\n}: CallSettings &\n Prompt & {\n model: LanguageModelV1;\n schema: z.Schema<T>;\n mode?: 'auto' | 'json' | 'tool' | 'grammar';\n }): Promise<StreamObjectResult<T>> {\n const retry = retryWithExponentialBackoff({ maxRetries });\n const jsonSchema = zodToJsonSchema(schema);\n\n let modelStream: ReadableStream<string | ErrorStreamPart>;\n\n // use the default provider mode when the mode is set to 'auto' or unspecified\n if (mode === 'auto' || mode == null) {\n mode = model.defaultObjectGenerationMode;\n }\n\n switch (mode) {\n case 'json': {\n const { stream, warnings } = await retry(() =>\n model.doStream({\n mode: { type: 'object-json' },\n ...validateCallSettings(settings),\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({\n system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),\n prompt,\n messages,\n }),\n abortSignal,\n }),\n );\n\n // TODO remove duplication\n modelStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV1StreamPart,\n string | ErrorStreamPart\n >({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'text-delta':\n controller.enqueue(chunk.textDelta);\n break;\n case 'error':\n controller.enqueue(chunk);\n break;\n }\n },\n }),\n );\n\n break;\n }\n\n case 'grammar': {\n const { stream, warnings } = await retry(() =>\n model.doStream({\n mode: { type: 'object-grammar', schema: jsonSchema },\n ...settings,\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({\n system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),\n prompt,\n messages,\n }),\n abortSignal,\n }),\n );\n\n // TODO remove duplication\n modelStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV1StreamPart,\n string | ErrorStreamPart\n >({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'text-delta':\n controller.enqueue(chunk.textDelta);\n break;\n case 'error':\n controller.enqueue(chunk);\n break;\n }\n },\n }),\n );\n\n break;\n }\n\n case 'tool': {\n const { stream, warnings } = await retry(() =>\n model.doStream({\n mode: {\n type: 'object-tool',\n tool: {\n type: 'function',\n name: 'json',\n description: 'Respond with a JSON object.',\n parameters: jsonSchema,\n },\n },\n ...settings,\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({ system, prompt, messages }),\n abortSignal,\n }),\n );\n\n modelStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV1StreamPart,\n string | ErrorStreamPart\n >({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'tool-call-delta':\n controller.enqueue(chunk.argsTextDelta);\n break;\n case 'error':\n controller.enqueue(chunk);\n break;\n }\n },\n }),\n );\n\n break;\n }\n\n case undefined: {\n throw new Error('Model does not have a default object generation mode.');\n }\n\n default: {\n const _exhaustiveCheck: never = mode;\n throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);\n }\n }\n\n return new StreamObjectResult(modelStream);\n}\n\nexport class StreamObjectResult<T> {\n readonly objectStream: AsyncIterable<\n PartialDeep<T, { recurseIntoArrays: true }>\n >;\n\n constructor(modelStream: ReadableStream<string | ErrorStreamPart>) {\n let accumulatedText = '';\n let latestObject: PartialDeep<T, { recurseIntoArrays: true }> | undefined =\n undefined;\n\n this.objectStream = {\n [Symbol.asyncIterator](): AsyncIterator<\n PartialDeep<T, { recurseIntoArrays: true }>\n > {\n const reader = modelStream.getReader();\n return {\n next: async () => {\n // loops until a text delta is found or the stream is finished:\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n return { value: null, done: true };\n }\n\n if (typeof value === 'string') {\n accumulatedText += value;\n\n const currentObject = parsePartialJson(\n accumulatedText,\n ) as PartialDeep<T, { recurseIntoArrays: true }>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n return { value: currentObject, done: false };\n }\n }\n\n // TODO handle error parts\n }\n },\n };\n },\n };\n }\n}\n\nexport type ErrorStreamPart = { type: 'error'; error: unknown };\n","/**\n * Performs a deep-equal comparison of two parsed JSON objects.\n *\n * @param {any} obj1 - The first object to compare.\n * @param {any} obj2 - The second object to compare.\n * @returns {boolean} - Returns true if the two objects are deeply equal, false otherwise.\n */\nexport function isDeepEqualData(obj1: any, obj2: any): boolean {\n // Check for strict equality first\n if (obj1 === obj2) return true;\n\n // Check if either is null or undefined\n if (obj1 == null || obj2 == null) return false;\n\n // Check if both are objects\n if (typeof obj1 !== 'object' && typeof obj2 !== 'object')\n return obj1 === obj2;\n\n // If they are not strictly equal, they both need to be Objects\n if (obj1.constructor !== obj2.constructor) return false;\n\n // Special handling for Date objects\n if (obj1 instanceof Date && obj2 instanceof Date) {\n return obj1.getTime() === obj2.getTime();\n }\n\n // Handle arrays: compare length and then perform a recursive deep comparison on each item\n if (Array.isArray(obj1)) {\n if (obj1.length !== obj2.length) return false;\n for (let i = 0; i < obj1.length; i++) {\n if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n }\n return true; // All array elements matched\n }\n\n // Compare the set of keys in each object\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) return false;\n\n // Check each key-value pair recursively\n for (const key of keys1) {\n if (!keys2.includes(key)) return false;\n if (!isDeepEqualData(obj1[key], obj2[key])) return false;\n }\n\n return true; // All keys and values matched\n}\n","import SecureJSON from 'secure-json-parse';\nimport { fixJson } from './fix-json';\n\nexport function parsePartialJson(\n jsonText: string | undefined,\n): unknown | undefined {\n if (jsonText == null) {\n return undefined;\n }\n\n try {\n // first attempt a regular JSON parse:\n return SecureJSON.parse(jsonText);\n } catch (ignored) {\n try {\n // then try to fix the partial JSON and parse it:\n const fixedJsonText = fixJson(jsonText);\n return SecureJSON.parse(fixedJsonText);\n } catch (ignored) {\n // ignored\n }\n }\n\n return undefined;\n}\n","type State =\n | 'ROOT'\n | 'FINISH'\n | 'INSIDE_STRING'\n | 'INSIDE_STRING_ESCAPE'\n | 'INSIDE_LITERAL'\n | 'INSIDE_NUMBER'\n | 'INSIDE_OBJECT_START'\n | 'INSIDE_OBJECT_KEY'\n | 'INSIDE_OBJECT_AFTER_KEY'\n | 'INSIDE_OBJECT_BEFORE_VALUE'\n | 'INSIDE_OBJECT_AFTER_VALUE'\n | 'INSIDE_OBJECT_AFTER_COMMA'\n | 'INSIDE_ARRAY_START'\n | 'INSIDE_ARRAY_AFTER_VALUE'\n | 'INSIDE_ARRAY_AFTER_COMMA';\n\n// Implemented as a scanner with additional fixing\n// that performs a single linear time scan pass over the partial JSON.\n//\n// The states should ideally match relevant states from the JSON spec:\n// https://www.json.org/json-en.html\n//\n// Please note that invalid JSON is not considered/covered, because it\n// is assumed that the resulting JSON will be processed by a standard\n// JSON parser that will detect any invalid JSON.\nexport function fixJson(input: string): string {\n const stack: State[] = ['ROOT'];\n let lastValidIndex = -1;\n let literalStart: number | null = null;\n\n function processValueStart(char: string, i: number, swapState: State) {\n {\n switch (char) {\n case '\"': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_STRING');\n break;\n }\n\n case 'f':\n case 't':\n case 'n': {\n lastValidIndex = i;\n literalStart = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_LITERAL');\n break;\n }\n\n case '-': {\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_NUMBER');\n break;\n }\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_NUMBER');\n break;\n }\n\n case '{': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_OBJECT_START');\n break;\n }\n\n case '[': {\n lastValidIndex = i;\n stack.pop();\n stack.push(swapState);\n stack.push('INSIDE_ARRAY_START');\n break;\n }\n }\n }\n }\n\n function processAfterObjectValue(char: string, i: number) {\n switch (char) {\n case ',': {\n stack.pop();\n stack.push('INSIDE_OBJECT_AFTER_COMMA');\n break;\n }\n case '}': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n }\n\n function processAfterArrayValue(char: string, i: number) {\n switch (char) {\n case ',': {\n stack.pop();\n stack.push('INSIDE_ARRAY_AFTER_COMMA');\n break;\n }\n case ']': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n }\n }\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n const currentState = stack[stack.length - 1];\n\n switch (currentState) {\n case 'ROOT':\n processValueStart(char, i, 'FINISH');\n break;\n\n case 'INSIDE_OBJECT_START': {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push('INSIDE_OBJECT_KEY');\n break;\n }\n case '}': {\n stack.pop();\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_AFTER_COMMA': {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push('INSIDE_OBJECT_KEY');\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_KEY': {\n switch (char) {\n case '\"': {\n stack.pop();\n stack.push('INSIDE_OBJECT_AFTER_KEY');\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_AFTER_KEY': {\n switch (char) {\n case ':': {\n stack.pop();\n stack.push('INSIDE_OBJECT_BEFORE_VALUE');\n\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_OBJECT_BEFORE_VALUE': {\n processValueStart(char, i, 'INSIDE_OBJECT_AFTER_VALUE');\n break;\n }\n\n case 'INSIDE_OBJECT_AFTER_VALUE': {\n processAfterObjectValue(char, i);\n break;\n }\n\n case 'INSIDE_STRING': {\n switch (char) {\n case '\"': {\n stack.pop();\n lastValidIndex = i;\n break;\n }\n\n case '\\\\': {\n stack.push('INSIDE_STRING_ESCAPE');\n break;\n }\n\n default: {\n lastValidIndex = i;\n }\n }\n\n break;\n }\n\n case 'INSIDE_ARRAY_START': {\n switch (char) {\n case ']': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n\n default: {\n lastValidIndex = i;\n processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n break;\n }\n }\n break;\n }\n\n case 'INSIDE_ARRAY_AFTER_VALUE': {\n switch (char) {\n case ',': {\n stack.pop();\n stack.push('INSIDE_ARRAY_AFTER_COMMA');\n break;\n }\n\n case ']': {\n lastValidIndex = i;\n stack.pop();\n break;\n }\n\n default: {\n lastValidIndex = i;\n break;\n }\n }\n\n break;\n }\n\n case 'INSIDE_ARRAY_AFTER_COMMA': {\n processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE');\n break;\n }\n\n case 'INSIDE_STRING_ESCAPE': {\n stack.pop();\n lastValidIndex = i;\n\n break;\n }\n\n case 'INSIDE_NUMBER': {\n switch (char) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9': {\n lastValidIndex = i;\n break;\n }\n\n case 'e':\n case 'E':\n case '-':\n case '.': {\n break;\n }\n\n case ',': {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n processAfterArrayValue(char, i);\n }\n\n if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n processAfterObjectValue(char, i);\n }\n\n break;\n }\n\n case '}': {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n processAfterObjectValue(char, i);\n }\n\n break;\n }\n\n case ']': {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n processAfterArrayValue(char, i);\n }\n\n break;\n }\n\n default: {\n stack.pop();\n break;\n }\n }\n\n break;\n }\n\n case 'INSIDE_LITERAL': {\n const partialLiteral = input.substring(literalStart!, i + 1);\n\n if (\n !'false'.startsWith(partialLiteral) &&\n !'true'.startsWith(partialLiteral) &&\n !'null'.startsWith(partialLiteral)\n ) {\n stack.pop();\n\n if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {\n processAfterObjectValue(char, i);\n } else if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {\n processAfterArrayValue(char, i);\n }\n } else {\n lastValidIndex = i;\n }\n\n break;\n }\n }\n }\n\n let result = input.slice(0, lastValidIndex + 1);\n\n for (let i = stack.length - 1; i >= 0; i--) {\n const state = stack[i];\n\n switch (state) {\n case 'INSIDE_STRING': {\n result += '\"';\n break;\n }\n\n case 'INSIDE_OBJECT_KEY':\n case 'INSIDE_OBJECT_AFTER_KEY':\n case 'INSIDE_OBJECT_AFTER_COMMA':\n case 'INSIDE_OBJECT_START':\n case 'INSIDE_OBJECT_BEFORE_VALUE':\n case 'INSIDE_OBJECT_AFTER_VALUE': {\n result += '}';\n break;\n }\n\n case 'INSIDE_ARRAY_START':\n case 'INSIDE_ARRAY_AFTER_COMMA':\n case 'INSIDE_ARRAY_AFTER_VALUE': {\n result += ']';\n break;\n }\n\n case 'INSIDE_LITERAL': {\n const partialLiteral = input.substring(literalStart!, input.length);\n\n if ('true'.startsWith(partialLiteral)) {\n result += 'true'.slice(partialLiteral.length);\n } else if ('false'.startsWith(partialLiteral)) {\n result += 'false'.slice(partialLiteral.length);\n } else if ('null'.startsWith(partialLiteral)) {\n result += 'null'.slice(partialLiteral.length);\n }\n }\n }\n }\n\n return result;\n}\n","import zodToJsonSchema from 'zod-to-json-schema';\nimport {\n LanguageModelV1,\n LanguageModelV1FinishReason,\n} from '../../ai-model-specification';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { getInputFormat } from '../prompt/get-input-format';\nimport { Prompt } from '../prompt/prompt';\nimport { validateCallSettings } from '../prompt/validate-call-settings';\nimport { Tool } from '../tool/tool';\nimport { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff';\nimport { TokenUsage, calculateTokenUsage } from './token-usage';\nimport { ToToolCallArray, parseToolCall } from './tool-call';\nimport { ToToolResultArray } from './tool-result';\n\n/**\n * Generate a text and call tools using a language model.\n */\nexport async function generateText<TOOLS extends Record<string, Tool>>({\n model,\n tools,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n ...settings\n}: CallSettings &\n Prompt & {\n model: LanguageModelV1;\n tools?: TOOLS;\n }): Promise<GenerateTextResult<TOOLS>> {\n const retry = retryWithExponentialBackoff({ maxRetries });\n const modelResponse = await retry(() =>\n model.doGenerate({\n mode: {\n type: 'regular',\n tools:\n tools == null\n ? undefined\n : Object.entries(tools).map(([name, tool]) => ({\n type: 'function',\n name,\n description: tool.description,\n parameters: zodToJsonSchema(tool.parameters),\n })),\n },\n ...validateCallSettings(settings),\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({\n system,\n prompt,\n messages,\n }),\n abortSignal,\n }),\n );\n\n // parse tool calls:\n const toolCalls: ToToolCallArray<TOOLS> = [];\n for (const modelToolCall of modelResponse.toolCalls ?? []) {\n toolCalls.push(parseToolCall({ toolCall: modelToolCall, tools }));\n }\n\n // execute tools:\n const toolResults =\n tools == null ? [] : await executeTools({ toolCalls, tools });\n\n return new GenerateTextResult({\n // Always return a string so that the caller doesn't have to check for undefined.\n // If they need to check if the model did not return any text,\n // they can check the length of the string:\n text: modelResponse.text ?? '',\n toolCalls,\n toolResults,\n finishReason: modelResponse.finishReason,\n usage: calculateTokenUsage(modelResponse.usage),\n });\n}\n\nasync function executeTools<TOOLS extends Record<string, Tool>>({\n toolCalls,\n tools,\n}: {\n toolCalls: ToToolCallArray<TOOLS>;\n tools: TOOLS;\n}): Promise<ToToolResultArray<TOOLS>> {\n const toolResults = await Promise.all(\n toolCalls.map(async toolCall => {\n const tool = tools[toolCall.toolName];\n\n if (tool?.execute == null) {\n return undefined;\n }\n\n const result = await tool.execute(toolCall.args);\n\n return {\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n args: toolCall.args,\n result,\n } as ToToolResultArray<TOOLS>[number];\n }),\n );\n\n return toolResults.filter(\n (result): result is NonNullable<typeof result> => result != null,\n );\n}\n\nexport class GenerateTextResult<TOOLS extends Record<string, Tool>> {\n readonly text: string;\n readonly toolCalls: ToToolCallArray<TOOLS>;\n readonly toolResults: ToToolResultArray<TOOLS>;\n readonly finishReason: LanguageModelV1FinishReason;\n readonly usage: TokenUsage;\n\n constructor(options: {\n text: string;\n toolCalls: ToToolCallArray<TOOLS>;\n toolResults: ToToolResultArray<TOOLS>;\n finishReason: LanguageModelV1FinishReason;\n usage: TokenUsage;\n }) {\n this.text = options.text;\n this.toolCalls = options.toolCalls;\n this.toolResults = options.toolResults;\n this.finishReason = options.finishReason;\n this.usage = options.usage;\n }\n}\n","import { ValueOf } from 'type-fest';\nimport { z } from 'zod';\nimport {\n LanguageModelV1FunctionToolCall,\n safeParseJSON,\n} from '../../ai-model-specification/index';\nimport { Tool } from '../tool';\n\nexport interface ToolCall<NAME extends string, ARGS> {\n toolCallId: string;\n toolName: NAME;\n args: ARGS;\n}\n\n// transforms the tools into a tool call union\nexport type ToToolCall<TOOLS extends Record<string, Tool>> = ValueOf<{\n [NAME in keyof TOOLS]: {\n toolCallId: string;\n toolName: NAME & string;\n args: z.infer<TOOLS[NAME]['parameters']>;\n };\n}>;\n\nexport type ToToolCallArray<TOOLS extends Record<string, Tool>> = Array<\n ToToolCall<TOOLS>\n>;\n\nexport function parseToolCall<TOOLS extends Record<string, Tool>>({\n toolCall,\n tools,\n}: {\n toolCall: LanguageModelV1FunctionToolCall;\n tools?: TOOLS;\n}): ToToolCall<TOOLS> {\n const toolName = toolCall.toolName as keyof TOOLS & string;\n\n if (tools == null) {\n // TODO add dedicated error to list of errors (NoSuchToolError)\n throw new Error(`Tool not found: ${toolName}`);\n }\n\n const tool = tools[toolName];\n\n // TODO add dedicated error to list of errors (NoSuchToolError)\n if (tool == null) {\n throw new Error(`Tool not found: ${toolName}`);\n }\n\n const parseResult = safeParseJSON({\n text: toolCall.args,\n schema: tool.parameters,\n });\n\n // TODO dedicate tool call error (InvalidToolArgumentsError)\n if (parseResult.success === false) {\n throw new Error(\n `Tool call ${toolName} has invalid arguments: ${parseResult.error}`,\n );\n }\n\n // TODO should have typesafe tool call arguments\n const toolArgs = parseResult.value;\n\n return {\n toolCallId: toolCall.toolCallId,\n toolName,\n args: toolArgs,\n };\n}\n","import zodToJsonSchema from 'zod-to-json-schema';\nimport { LanguageModelV1 } from '../../ai-model-specification/index';\nimport { CallSettings } from '../prompt/call-settings';\nimport { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';\nimport { getInputFormat } from '../prompt/get-input-format';\nimport { Prompt } from '../prompt/prompt';\nimport { validateCallSettings } from '../prompt/validate-call-settings';\nimport { Tool } from '../tool';\nimport { retryWithExponentialBackoff } from '../util/retry-with-exponential-backoff';\nimport { runToolsTransformation } from './run-tools-transformation';\nimport { ToToolCall } from './tool-call';\nimport { ToToolResult } from './tool-result';\n\n/**\n * Stream text generated by a language model.\n */\nexport async function streamText<TOOLS extends Record<string, Tool>>({\n model,\n tools,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n ...settings\n}: CallSettings &\n Prompt & {\n model: LanguageModelV1;\n tools?: TOOLS;\n }): Promise<StreamTextResult<TOOLS>> {\n const retry = retryWithExponentialBackoff({ maxRetries });\n const { stream, warnings } = await retry(() =>\n model.doStream({\n mode: {\n type: 'regular',\n tools:\n tools == null\n ? undefined\n : Object.entries(tools).map(([name, tool]) => ({\n type: 'function',\n name,\n description: tool.description,\n parameters: zodToJsonSchema(tool.parameters),\n })),\n },\n ...validateCallSettings(settings),\n inputFormat: getInputFormat({ prompt, messages }),\n prompt: convertToLanguageModelPrompt({\n system,\n prompt,\n messages,\n }),\n abortSignal,\n }),\n );\n\n const toolStream = runToolsTransformation({\n tools,\n generatorStream: stream,\n });\n\n return new StreamTextResult(toolStream);\n}\n\nexport type TextStreamPart<TOOLS extends Record<string, Tool>> =\n | {\n type: 'text-delta';\n textDelta: string;\n }\n | ({\n type: 'tool-call';\n } & ToToolCall<TOOLS>)\n | {\n type: 'error';\n error: unknown;\n }\n | ({\n type: 'tool-result';\n } & ToToolResult<TOOLS>);\n\nexport class StreamTextResult<TOOLS extends Record<string, Tool>> {\n private readonly rootStream: ReadableStream<TextStreamPart<TOOLS>>;\n\n readonly textStream: AsyncIterable<string>;\n\n readonly fullStream: AsyncIterable<TextStreamPart<TOOLS>>;\n\n constructor(stream: ReadableStream<TextStreamPart<TOOLS>>) {\n this.rootStream = stream;\n\n this.textStream = {\n [Symbol.asyncIterator](): AsyncIterator<string> {\n const reader = stream.getReader();\n return {\n next: async () => {\n // loops until a text delta is found or the stream is finished:\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n return { value: null, done: true };\n }\n\n if (value.type === 'text-delta') {\n // do not stream empty text deltas:\n if (value.textDelta.length > 0) {\n return { value: value.textDelta, done: false };\n }\n }\n\n if (value.type === 'error') {\n // TODO log / store errors\n console.error('Error:', value.error);\n }\n }\n },\n };\n },\n };\n\n this.fullStream = {\n [Symbol.asyncIterator](): AsyncIterator<TextStreamPart<TOOLS>> {\n const reader = stream.getReader();\n return {\n next: async () => {\n // loops until a valid delta is found or the stream is finished:\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n return { value: null, done: true };\n }\n\n if (value.type === 'text-delta') {\n // do not stream empty text deltas:\n if (value.textDelta.length > 0) {\n return { value, done: false };\n }\n } else {\n return { value, done: false };\n }\n }\n },\n };\n },\n };\n }\n}\n","import { nanoid } from 'nanoid';\nimport { LanguageModelV1StreamPart } from '../../ai-model-specification/index';\nimport { Tool } from '../tool';\nimport { TextStreamPart } from './stream-text';\nimport { parseToolCall } from './tool-call';\n\nexport function runToolsTransformation<TOOLS extends Record<string, Tool>>({\n tools,\n generatorStream,\n}: {\n tools?: TOOLS;\n generatorStream: ReadableStream<LanguageModelV1StreamPart>;\n}): ReadableStream<TextStreamPart<TOOLS>> {\n let canClose = false;\n const outstandingToolCalls = new Set<string>();\n\n // tool results stream\n let toolResultsStreamController: ReadableStreamDefaultController<\n TextStreamPart<TOOLS>\n > | null = null;\n const toolResultsStream = new ReadableStream<TextStreamPart<TOOLS>>({\n start(controller) {\n toolResultsStreamController = controller;\n },\n });\n\n // forward stream\n const forwardStream = new TransformStream<\n LanguageModelV1StreamPart,\n TextStreamPart<TOOLS>\n >({\n transform(\n chunk: LanguageModelV1StreamPart,\n controller: TransformStreamDefaultController<TextStreamPart<TOOLS>>,\n ) {\n const chunkType = chunk.type;\n\n switch (chunkType) {\n // forward:\n case 'text-delta':\n case 'error': {\n controller.enqueue(chunk);\n break;\n }\n\n // process\n case 'tool-call': {\n const toolName = chunk.toolName as keyof TOOLS & string;\n\n if (tools == null) {\n // TODO add dedicated error to list of errors (NoSuchToolError)\n toolResultsStreamController!.enqueue({\n type: 'error',\n error: `Tool ${chunk.toolName} not found (no tools provided)`,\n });\n break;\n }\n\n const tool = tools[toolName];\n\n if (tool == null) {\n // TODO add dedicated error to list of errors (NoSuchToolError)\n toolResultsStreamController!.enqueue({\n type: 'error',\n error: `Tool ${chunk.toolName} not found`,\n });\n\n break;\n }\n\n // TODO try catch or safe parse\n const toolCall = parseToolCall({\n toolCall: chunk,\n tools,\n });\n\n // TODO dedicate tool call error (InvalidToolArgumentsError)\n // toolResultsStreamController!.enqueue({\n // type: 'error',\n // error: `Tool call ${toolName} has invalid arguments: ${parseResult.error}`,\n // });\n\n controller.enqueue({\n type: 'tool-call',\n ...toolCall,\n });\n\n if (tool.execute != null) {\n const toolExecutionId = nanoid(); // use our own id to guarantee uniqueness\n outstandingToolCalls.add(toolExecutionId);\n\n // Note: we don't await the tool execution here, because we want to process\n // the next chunk as soon as possible. This is important for the case where\n // the tool execution takes a long time.\n tool.execute(toolCall.args).then(\n (result: any) => {\n toolResultsStreamController!.enqueue({\n type: 'tool-result',\n ...toolCall,\n result,\n } as any);\n\n outstandingToolCalls.delete(toolExecutionId);\n\n // close the tool results controller if no more outstanding tool calls\n if (canClose && outstandingToolCalls.size === 0) {\n toolResultsStreamController!.close();\n }\n },\n (error: any) => {\n toolResultsStreamController!.enqueue({\n type: 'error',\n error,\n });\n\n outstandingToolCalls.delete(toolExecutionId);\n\n // close the tool results controller if no more outstanding tool calls\n if (canClose && outstandingToolCalls.size === 0) {\n toolResultsStreamController!.close();\n }\n },\n );\n }\n\n break;\n }\n\n // ignore\n case 'finish-metadata':\n case 'tool-call-delta': {\n break;\n }\n\n default: {\n const _exhaustiveCheck: never = chunkType;\n throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);\n }\n }\n },\n\n flush() {\n canClose = true;\n\n if (outstandingToolCalls.size === 0) {\n toolResultsStreamController!.close();\n }\n },\n });\n\n // combine the generator stream and the tool results stream\n return new ReadableStream<TextStreamPart<TOOLS>>({\n async start(controller) {\n generatorStream.pipeThrough(forwardStream).pipeTo(\n new WritableStream({\n write(chunk) {\n controller.enqueue(chunk);\n },\n close() {\n // the generator stream controller is automatically closed when it's consumed\n },\n }),\n );\n\n toolResultsStream.pipeTo(\n new WritableStream({\n write(chunk) {\n controller.enqueue(chunk);\n },\n close() {\n controller.close();\n },\n }),\n );\n },\n });\n}\n","import { z } from 'zod';\n\n/**\n * A tool contains the description and the schema of the input that the tool expects.\n * This enables the language model to generate the input.\n *\n * The tool can also contain an optional execute function for the actual execution function of the tool.\n */\nexport interface Tool<PARAMETERS extends z.ZodTypeAny = any, RESULT = any> {\n /**\n * A optional description of what the tool does. Will be used by the language model to decide whether to use the tool.\n */\n description?: string;\n\n /**\n * The schema of the input that the tool expects. The language model will use this to generate the input.\n * Use descriptions to make the input understandable for the language model.\n */\n parameters: PARAMETERS;\n\n /**\n * An optional execute function for the actual execution function of the tool.\n * If not provided, the tool will not be executed automatically.\n */\n execute?: (args: z.infer<PARAMETERS>) => PromiseLike<RESULT>;\n}\n\n/**\n * Helper function for inferring the execute args of a tool.\n */\n// Note: special type inference is needed for the execute function args to make sure they are inferred correctly.\nexport function tool<PARAMETERS extends z.ZodTypeAny, RESULT>(\n tool: Tool<PARAMETERS, RESULT> & {\n execute: (args: z.infer<PARAMETERS>) => PromiseLike<RESULT>;\n },\n): Tool<PARAMETERS, RESULT> & {\n execute: (args: z.infer<PARAMETERS>) => PromiseLike<RESULT>;\n};\nexport function tool<PARAMETERS extends z.ZodTypeAny, RESULT>(\n tool: Tool<PARAMETERS, RESULT> & {\n execute?: undefined;\n },\n): Tool<PARAMETERS, RESULT> & {\n execute: undefined;\n};\nexport function tool<PARAMETERS extends z.ZodTypeAny, RESULT = any>(\n tool: Tool<PARAMETERS, RESULT>,\n): Tool<PARAMETERS, RESULT> {\n return tool;\n}\n"],"mappings":";AACA,OAAO,qBAAqB;;;ACDrB,IAAM,0BAAN,cAAsC,MAAM;AAAA;AAAA;AAAA,EAMjD,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAIG;AACD,UAAM,kCAAkC,SAAS,KAAK,OAAO,EAAE;AAE/D,SAAK,OAAO;AAEZ,SAAK,YAAY;AACjB,SAAK,QAAQ;AAAA,EACf;AAAA,EAEA,SAAS;AACP,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,OAAO,KAAK;AAAA,MAEZ,WAAW,KAAK;AAAA,MAChB,OAAO,KAAK;AAAA,IACd;AAAA,EACF;AACF;;;ACjCO,SAAS,gBAAgB,OAA4B;AAC1D,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,MAAI,iBAAiB,OAAO;AAC1B,WAAO,MAAM;AAAA,EACf;AAEA,SAAO,KAAK,UAAU,KAAK;AAC7B;;;ACZO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAKxC,YAAY,EAAE,MAAM,MAAM,GAAqC;AAC7D;AAAA,MACE,8BACW,IAAI;AAAA,iBACK,gBAAgB,KAAK,CAAC;AAAA,IAC5C;AAEA,SAAK,OAAO;AAEZ,SAAK,QAA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;AAE/B,oBAAI,MAAM,UAAU,SAAS,GAAG;AAC9B,yBAAO,EAAE,OAAO,MAAM,WAAW,MAAM,MAAM;AAAA,gBAC/C;AAAA,cACF;AAEA,kBAAI,MAAM,SAAS,SAAS;AAE1B,wBAAQ,MAAM,UAAU,MAAM,KAAK;AAAA,cACrC;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,SAAK,aAAa;AAAA,MAChB,CAAC,OAAO,aAAa,IAA0C;AAC7D,cAAM,SAAS,OAAO,UAAU;AAChC,eAAO;AAAA,UACL,MAAM,YAAY;AAEhB,mBAAO,MAAM;AACX,oBAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,kBAAI,MAAM;AACR,uBAAO,EAAE,OAAO,MAAM,MAAM,KAAK;AAAA,cACnC;AAEA,kBAAI,MAAM,SAAS,cAAc;AAE/B,oBAAI,MAAM,UAAU,SAAS,GAAG;AAC9B,yBAAO,EAAE,OAAO,MAAM,MAAM;AAAA,gBAC9B;AAAA,cACF,OAAO;AACL,uBAAO,EAAE,OAAO,MAAM,MAAM;AAAA,cAC9B;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AEtGO,SAAS,KACdE,OAC0B;AAC1B,SAAOA;AACT;","names":["zodToJsonSchema","SecureJSON","SecureJSON","ignored","zodToJsonSchema","zodToJsonSchema","tool","tool","zodToJsonSchema","zodToJsonSchema","tool","tool","zodToJsonSchema","tool"]}
|
@@ -1,429 +0,0 @@
|
|
1
|
-
type JsonSchema = Record<string, unknown>;
|
2
|
-
|
3
|
-
type LanguageModelV1CallSettings = {
|
4
|
-
/**
|
5
|
-
* Maximum number of tokens to generate.
|
6
|
-
*/
|
7
|
-
maxTokens?: number;
|
8
|
-
/**
|
9
|
-
* Temperature setting. This is a number between 0 (almost no randomness) and
|
10
|
-
* 1 (very random).
|
11
|
-
*
|
12
|
-
* Different LLM providers have different temperature
|
13
|
-
* scales, so they'd need to map it (without mapping, the same temperature has
|
14
|
-
* different effects on different models). The provider can also chose to map
|
15
|
-
* this to topP, potentially even using a custom setting on their model.
|
16
|
-
*
|
17
|
-
* Note: This is an example of a setting that requires a clear specification of
|
18
|
-
* the semantics.
|
19
|
-
*/
|
20
|
-
temperature?: number;
|
21
|
-
/**
|
22
|
-
* Nucleus sampling. This is a number between 0 and 1.
|
23
|
-
*
|
24
|
-
* E.g. 0.1 would mean that only tokens with the top 10% probability mass
|
25
|
-
* are considered.
|
26
|
-
*
|
27
|
-
* It is recommended to set either `temperature` or `topP`, but not both.
|
28
|
-
*/
|
29
|
-
topP?: number;
|
30
|
-
/**
|
31
|
-
* Presence penalty setting. It affects the likelihood of the model to
|
32
|
-
* repeat information that is already in the prompt.
|
33
|
-
*
|
34
|
-
* The presence penalty is a number between -1 (increase repetition)
|
35
|
-
* and 1 (maximum penalty, decrease repetition). 0 means no penalty.
|
36
|
-
*/
|
37
|
-
presencePenalty?: number;
|
38
|
-
/**
|
39
|
-
* Frequency penalty setting. It affects the likelihood of the model
|
40
|
-
* to repeatedly use the same words or phrases.
|
41
|
-
*
|
42
|
-
* The frequency penalty is a number between -1 (increase repetition)
|
43
|
-
* and 1 (maximum penalty, decrease repetition). 0 means no penalty.
|
44
|
-
*/
|
45
|
-
frequencyPenalty?: number;
|
46
|
-
/**
|
47
|
-
* The seed (integer) to use for random sampling. If set and supported
|
48
|
-
* by the model, calls will generate deterministic results.
|
49
|
-
*/
|
50
|
-
seed?: number;
|
51
|
-
/**
|
52
|
-
* Abort signal for cancelling the operation.
|
53
|
-
*/
|
54
|
-
abortSignal?: AbortSignal;
|
55
|
-
};
|
56
|
-
|
57
|
-
/**
|
58
|
-
* A tool has a name, a description, and a set of parameters.
|
59
|
-
*
|
60
|
-
* Note: this is **not** the user-facing tool definition. The AI SDK methods will
|
61
|
-
* map the user-facing tool definitions to this format.
|
62
|
-
*/
|
63
|
-
type LanguageModelV1FunctionTool = {
|
64
|
-
/**
|
65
|
-
* The type of the tool. Only functions for now, but this gives us room to
|
66
|
-
* add more specific tool types in the future and use a discriminated union.
|
67
|
-
*/
|
68
|
-
type: 'function';
|
69
|
-
/**
|
70
|
-
* The name of the tool. Unique within this model call.
|
71
|
-
*/
|
72
|
-
name: string;
|
73
|
-
description?: string;
|
74
|
-
parameters: JsonSchema;
|
75
|
-
};
|
76
|
-
|
77
|
-
/**
|
78
|
-
* A prompt is a list of messages.
|
79
|
-
*
|
80
|
-
* Note: Not all models and prompt formats support multi-modal inputs and
|
81
|
-
* tool calls. The validation happens at runtime.
|
82
|
-
*
|
83
|
-
* Note: This is not a user-facing prompt. The AI SDK methods will map the
|
84
|
-
* user-facing prompt types such as chat or instruction prompts to this format.
|
85
|
-
*/
|
86
|
-
type LanguageModelV1Prompt = Array<LanguageModelV1Message>;
|
87
|
-
type LanguageModelV1Message = {
|
88
|
-
role: 'system';
|
89
|
-
content: string;
|
90
|
-
} | {
|
91
|
-
role: 'user';
|
92
|
-
content: Array<LanguageModelV1TextPart | LanguageModelV1ImagePart>;
|
93
|
-
} | {
|
94
|
-
role: 'assistant';
|
95
|
-
content: Array<LanguageModelV1TextPart | LanguageModelV1ToolCallPart>;
|
96
|
-
} | {
|
97
|
-
role: 'tool';
|
98
|
-
content: Array<LanguageModelV1ToolResultPart>;
|
99
|
-
};
|
100
|
-
interface LanguageModelV1TextPart {
|
101
|
-
type: 'text';
|
102
|
-
/**
|
103
|
-
* The text content.
|
104
|
-
*/
|
105
|
-
text: string;
|
106
|
-
}
|
107
|
-
interface LanguageModelV1ImagePart {
|
108
|
-
type: 'image';
|
109
|
-
/**
|
110
|
-
* Image data as a Uint8Array (e.g. from a Blob or Buffer) or a URL.
|
111
|
-
*/
|
112
|
-
image: Uint8Array | URL;
|
113
|
-
/**
|
114
|
-
* Optional mime type of the image.
|
115
|
-
*/
|
116
|
-
mimeType?: string;
|
117
|
-
}
|
118
|
-
interface LanguageModelV1ToolCallPart {
|
119
|
-
type: 'tool-call';
|
120
|
-
toolCallId: string;
|
121
|
-
toolName: string;
|
122
|
-
args: unknown;
|
123
|
-
}
|
124
|
-
interface LanguageModelV1ToolResultPart {
|
125
|
-
type: 'tool-result';
|
126
|
-
toolCallId: string;
|
127
|
-
toolName: string;
|
128
|
-
result: unknown;
|
129
|
-
}
|
130
|
-
|
131
|
-
type LanguageModelV1CallOptions = LanguageModelV1CallSettings & {
|
132
|
-
/**
|
133
|
-
* Whether the user provided the input as messages or as
|
134
|
-
* a prompt. This can help guide non-chat models in the
|
135
|
-
* expansion, bc different expansions can be needed for
|
136
|
-
* chat/non-chat use cases.
|
137
|
-
*/
|
138
|
-
inputFormat: 'messages' | 'prompt';
|
139
|
-
/**
|
140
|
-
* The mode affects the behavior of the language model. It is required to
|
141
|
-
* support provider-independent streaming and generation of structured objects.
|
142
|
-
* The model can take this information and e.g. configure json mode, the correct
|
143
|
-
* low level grammar, etc. It can also be used to optimize the efficiency of the
|
144
|
-
* streaming, e.g. tool-delta stream parts are only needed in the
|
145
|
-
* object-tool mode.
|
146
|
-
*/
|
147
|
-
mode: {
|
148
|
-
type: 'regular';
|
149
|
-
tools?: Array<LanguageModelV1FunctionTool>;
|
150
|
-
} | {
|
151
|
-
type: 'object-json';
|
152
|
-
} | {
|
153
|
-
type: 'object-grammar';
|
154
|
-
schema: JsonSchema;
|
155
|
-
} | {
|
156
|
-
type: 'object-tool';
|
157
|
-
tool: LanguageModelV1FunctionTool;
|
158
|
-
};
|
159
|
-
/**
|
160
|
-
* A language mode prompt is a standardized prompt type.
|
161
|
-
*
|
162
|
-
* Note: This is **not** the user-facing prompt. The AI SDK methods will map the
|
163
|
-
* user-facing prompt types such as chat or instruction prompts to this format.
|
164
|
-
* That approach allows us to evolve the user facing prompts without breaking
|
165
|
-
* the language model interface.
|
166
|
-
*/
|
167
|
-
prompt: LanguageModelV1Prompt;
|
168
|
-
};
|
169
|
-
|
170
|
-
/**
|
171
|
-
* Warning from the model provider for this call. The call will proceed, but e.g.
|
172
|
-
* some settings might not be supported, which can lead to suboptimal results.
|
173
|
-
*/
|
174
|
-
type LanguageModelV1CallWarning = {
|
175
|
-
type: 'unsupported-setting';
|
176
|
-
setting: keyof LanguageModelV1CallSettings;
|
177
|
-
} | {
|
178
|
-
type: 'other';
|
179
|
-
message: string;
|
180
|
-
};
|
181
|
-
|
182
|
-
type LanguageModelV1FinishReason = 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other';
|
183
|
-
|
184
|
-
type LanguageModelV1FunctionToolCall = {
|
185
|
-
toolCallType: 'function';
|
186
|
-
toolCallId: string;
|
187
|
-
toolName: string;
|
188
|
-
/**
|
189
|
-
* Stringified JSON object with the tool call arguments. Must match the
|
190
|
-
* parameters schema of the tool.
|
191
|
-
*/
|
192
|
-
args: string;
|
193
|
-
};
|
194
|
-
|
195
|
-
type LanguageModelV1 = {
|
196
|
-
/**
|
197
|
-
* The language model must specify which language model interface
|
198
|
-
* version it implements. This will allow us to evolve the language
|
199
|
-
* model interface and retain backwards compatibility. The different
|
200
|
-
* implementation versions can be handled as a discriminated union
|
201
|
-
* on our side.
|
202
|
-
*/
|
203
|
-
readonly specificationVersion: 'v1';
|
204
|
-
/**
|
205
|
-
* Name of the provider for logging purposes.
|
206
|
-
*/
|
207
|
-
readonly provider: string;
|
208
|
-
/**
|
209
|
-
* Provider-specific model ID for logging purposes.
|
210
|
-
*/
|
211
|
-
readonly modelId: string;
|
212
|
-
/**
|
213
|
-
* Default object generation mode that should be used with this model when
|
214
|
-
* no mode is specified. Should be the mode with the best results for this
|
215
|
-
* model. `undefined` can be returned if object generation is not supported.
|
216
|
-
*
|
217
|
-
* This is needed to generate the best objects possible w/o requiring the
|
218
|
-
* user to explicitly specify the object generation mode.
|
219
|
-
*/
|
220
|
-
readonly defaultObjectGenerationMode: 'json' | 'tool' | 'grammar' | undefined;
|
221
|
-
/**
|
222
|
-
* Generates a language model output (non-streaming).
|
223
|
-
*
|
224
|
-
* Naming: "do" prefix to prevent accidental direct usage of the method
|
225
|
-
* by the user.
|
226
|
-
*/
|
227
|
-
doGenerate(options: LanguageModelV1CallOptions): PromiseLike<{
|
228
|
-
/**
|
229
|
-
* Text that the model has generated. Can be undefined if the model
|
230
|
-
* has only generated tool calls.
|
231
|
-
*/
|
232
|
-
text?: string;
|
233
|
-
/**
|
234
|
-
* Tool calls that the model has generated. Can be undefined if the
|
235
|
-
* model has only generated text.
|
236
|
-
*/
|
237
|
-
toolCalls?: Array<LanguageModelV1FunctionToolCall>;
|
238
|
-
/**
|
239
|
-
* Finish reason.
|
240
|
-
*/
|
241
|
-
finishReason: LanguageModelV1FinishReason;
|
242
|
-
/**
|
243
|
-
* Usage information.
|
244
|
-
*/
|
245
|
-
usage: {
|
246
|
-
promptTokens: number;
|
247
|
-
completionTokens: number;
|
248
|
-
};
|
249
|
-
/**
|
250
|
-
* Raw prompt and setting information for observability provider integration.
|
251
|
-
*/
|
252
|
-
rawCall: {
|
253
|
-
/**
|
254
|
-
* Raw prompt after expansion and conversion to the format that the
|
255
|
-
* provider uses to send the information to their API.
|
256
|
-
*/
|
257
|
-
rawPrompt: unknown;
|
258
|
-
/**
|
259
|
-
* Raw settings that are used for the API call. Includes provider-specific
|
260
|
-
* settings.
|
261
|
-
*/
|
262
|
-
rawSettings: Record<string, unknown>;
|
263
|
-
};
|
264
|
-
warnings?: LanguageModelV1CallWarning[];
|
265
|
-
}>;
|
266
|
-
/**
|
267
|
-
* Generates a language model output (streaming).
|
268
|
-
*
|
269
|
-
* Naming: "do" prefix to prevent accidental direct usage of the method
|
270
|
-
* by the user.
|
271
|
-
*
|
272
|
-
* @return A stream of higher-level language model output parts.
|
273
|
-
*/
|
274
|
-
doStream(options: LanguageModelV1CallOptions): PromiseLike<{
|
275
|
-
stream: ReadableStream<LanguageModelV1StreamPart>;
|
276
|
-
/**
|
277
|
-
* Raw prompt and setting information for observability provider integration.
|
278
|
-
*/
|
279
|
-
rawCall: {
|
280
|
-
/**
|
281
|
-
* Raw prompt after expansion and conversion to the format that the
|
282
|
-
* provider uses to send the information to their API.
|
283
|
-
*/
|
284
|
-
rawPrompt: unknown;
|
285
|
-
/**
|
286
|
-
* Raw settings that are used for the API call. Includes provider-specific
|
287
|
-
* settings.
|
288
|
-
*/
|
289
|
-
rawSettings: Record<string, unknown>;
|
290
|
-
};
|
291
|
-
warnings?: LanguageModelV1CallWarning[];
|
292
|
-
}>;
|
293
|
-
};
|
294
|
-
type LanguageModelV1StreamPart = {
|
295
|
-
type: 'text-delta';
|
296
|
-
textDelta: string;
|
297
|
-
} | ({
|
298
|
-
type: 'tool-call';
|
299
|
-
} & LanguageModelV1FunctionToolCall) | {
|
300
|
-
type: 'tool-call-delta';
|
301
|
-
toolCallId: string;
|
302
|
-
toolName: string;
|
303
|
-
argsTextDelta: string;
|
304
|
-
} | {
|
305
|
-
type: 'finish-metadata';
|
306
|
-
finishReason: LanguageModelV1FinishReason;
|
307
|
-
usage: {
|
308
|
-
promptTokens: number;
|
309
|
-
completionTokens: number;
|
310
|
-
};
|
311
|
-
} | {
|
312
|
-
type: 'error';
|
313
|
-
error: unknown;
|
314
|
-
};
|
315
|
-
|
316
|
-
type OpenAIChatModelId = 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-0125-preview' | 'gpt-4-vision-preview' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0301' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-16k-0613' | (string & {});
|
317
|
-
interface OpenAIChatSettings {
|
318
|
-
/**
|
319
|
-
* Modify the likelihood of specified tokens appearing in the completion.
|
320
|
-
*
|
321
|
-
* Accepts a JSON object that maps tokens (specified by their token ID in
|
322
|
-
* the GPT tokenizer) to an associated bias value from -100 to 100. You
|
323
|
-
* can use this tokenizer tool to convert text to token IDs. Mathematically,
|
324
|
-
* the bias is added to the logits generated by the model prior to sampling.
|
325
|
-
* The exact effect will vary per model, but values between -1 and 1 should
|
326
|
-
* decrease or increase likelihood of selection; values like -100 or 100
|
327
|
-
* should result in a ban or exclusive selection of the relevant token.
|
328
|
-
*
|
329
|
-
* As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
|
330
|
-
* token from being generated.
|
331
|
-
*/
|
332
|
-
logitBias?: Record<number, number>;
|
333
|
-
/**
|
334
|
-
* A unique identifier representing your end-user, which can help OpenAI to
|
335
|
-
* monitor and detect abuse. Learn more.
|
336
|
-
*/
|
337
|
-
user?: string;
|
338
|
-
}
|
339
|
-
|
340
|
-
type OpenAIChatConfig = {
|
341
|
-
provider: string;
|
342
|
-
baseUrl: string;
|
343
|
-
headers: () => Record<string, string | undefined>;
|
344
|
-
};
|
345
|
-
declare class OpenAIChatLanguageModel implements LanguageModelV1 {
|
346
|
-
readonly specificationVersion = "v1";
|
347
|
-
readonly defaultObjectGenerationMode = "tool";
|
348
|
-
readonly modelId: OpenAIChatModelId;
|
349
|
-
readonly settings: OpenAIChatSettings;
|
350
|
-
private readonly config;
|
351
|
-
constructor(modelId: OpenAIChatModelId, settings: OpenAIChatSettings, config: OpenAIChatConfig);
|
352
|
-
get provider(): string;
|
353
|
-
private getArgs;
|
354
|
-
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
|
355
|
-
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
|
356
|
-
}
|
357
|
-
|
358
|
-
type OpenAICompletionModelId = 'gpt-3.5-turbo-instruct' | (string & {});
|
359
|
-
interface OpenAICompletionSettings {
|
360
|
-
/**
|
361
|
-
* Echo back the prompt in addition to the completion
|
362
|
-
*/
|
363
|
-
echo?: boolean;
|
364
|
-
/**
|
365
|
-
* Modify the likelihood of specified tokens appearing in the completion.
|
366
|
-
*
|
367
|
-
* Accepts a JSON object that maps tokens (specified by their token ID in
|
368
|
-
* the GPT tokenizer) to an associated bias value from -100 to 100. You
|
369
|
-
* can use this tokenizer tool to convert text to token IDs. Mathematically,
|
370
|
-
* the bias is added to the logits generated by the model prior to sampling.
|
371
|
-
* The exact effect will vary per model, but values between -1 and 1 should
|
372
|
-
* decrease or increase likelihood of selection; values like -100 or 100
|
373
|
-
* should result in a ban or exclusive selection of the relevant token.
|
374
|
-
*
|
375
|
-
* As an example, you can pass {"50256": -100} to prevent the <|endoftext|>
|
376
|
-
* token from being generated.
|
377
|
-
*/
|
378
|
-
logitBias?: Record<number, number>;
|
379
|
-
/**
|
380
|
-
* The suffix that comes after a completion of inserted text.
|
381
|
-
*/
|
382
|
-
suffix?: string;
|
383
|
-
/**
|
384
|
-
* A unique identifier representing your end-user, which can help OpenAI to
|
385
|
-
* monitor and detect abuse. Learn more.
|
386
|
-
*/
|
387
|
-
user?: string;
|
388
|
-
}
|
389
|
-
|
390
|
-
type OpenAICompletionConfig = {
|
391
|
-
provider: string;
|
392
|
-
baseUrl: string;
|
393
|
-
headers: () => Record<string, string | undefined>;
|
394
|
-
};
|
395
|
-
declare class OpenAICompletionLanguageModel implements LanguageModelV1 {
|
396
|
-
readonly specificationVersion = "v1";
|
397
|
-
readonly defaultObjectGenerationMode: undefined;
|
398
|
-
readonly modelId: OpenAICompletionModelId;
|
399
|
-
readonly settings: OpenAICompletionSettings;
|
400
|
-
private readonly config;
|
401
|
-
constructor(modelId: OpenAICompletionModelId, settings: OpenAICompletionSettings, config: OpenAICompletionConfig);
|
402
|
-
get provider(): string;
|
403
|
-
private getArgs;
|
404
|
-
doGenerate(options: Parameters<LanguageModelV1['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doGenerate']>>>;
|
405
|
-
doStream(options: Parameters<LanguageModelV1['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV1['doStream']>>>;
|
406
|
-
}
|
407
|
-
|
408
|
-
/**
|
409
|
-
* OpenAI provider.
|
410
|
-
*/
|
411
|
-
declare class OpenAI {
|
412
|
-
readonly baseUrl?: string;
|
413
|
-
readonly apiKey?: string;
|
414
|
-
readonly organization?: string;
|
415
|
-
constructor(options?: {
|
416
|
-
baseUrl?: string;
|
417
|
-
apiKey?: string;
|
418
|
-
organization?: string;
|
419
|
-
});
|
420
|
-
private get baseConfig();
|
421
|
-
chat(modelId: OpenAIChatModelId, settings?: OpenAIChatSettings): OpenAIChatLanguageModel;
|
422
|
-
completion(modelId: OpenAICompletionModelId, settings?: OpenAICompletionSettings): OpenAICompletionLanguageModel;
|
423
|
-
}
|
424
|
-
/**
|
425
|
-
* Default OpenAI provider instance.
|
426
|
-
*/
|
427
|
-
declare const openai: OpenAI;
|
428
|
-
|
429
|
-
export { OpenAI, openai };
|