@ai-sdk/deepseek 3.0.75 → 3.0.77
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/CHANGELOG.md +31 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -11
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +2 -2
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +3 -6
- package/dist/internal/index.js.map +1 -1
- package/docs/30-deepseek.mdx +5 -6
- package/package.json +3 -3
- package/src/chat/deepseek-chat-language-model.ts +12 -11
- package/src/deepseek-provider.ts +16 -11
- package/src/files/deepseek-files.ts +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["deepseekLanguageModelChatOptions","deepseekMessageProviderOptions","deepseekAssistantMessageProviderOptions","deepseekAssistantMessageProviderOptions","deepseekLanguageModelChatOptions"],"sources":["../../src/chat/deepseek-chat-language-model-options.ts","../../src/chat/deepseek-file-part-options.ts","../../src/chat/is-deepseek-v4-model.ts","../../src/chat/convert-to-deepseek-chat-messages.ts","../../src/chat/convert-to-deepseek-usage.ts","../../src/chat/deepseek-chat-api-types.ts","../../src/chat/deepseek-prepare-tools.ts","../../src/chat/map-deepseek-finish-reason.ts","../../src/chat/deepseek-chat-language-model.ts","../../src/internal/index.ts"],"sourcesContent":["import {\n type InferSchema,\n lazySchema,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://api-docs.deepseek.com/quick_start/pricing\nexport type DeepSeekChatModelId =\n | 'deepseek-flash'\n | 'deepseek-v4-flash'\n | 'deepseek-v4-pro'\n | 'deepseek-v4-flash-vision-exp'\n // Retired aliases remain assignable through the string escape hatch, but are\n // intentionally omitted from first-class editor suggestions.\n | (string & {});\n\nfunction createDeepseekChatOptionsSchema() {\n return z.object({\n /**\n * Whether to return log probabilities for generated tokens.\n */\n logprobs: z.boolean().optional(),\n\n /**\n * Number of most likely tokens to return at each token position.\n *\n * Setting this option automatically enables `logprobs`.\n */\n topLogprobs: z.number().int().min(0).max(20).optional(),\n\n /**\n * An opaque identifier for the end user. DeepSeek uses this identifier for\n * content-safety tracing and request isolation.\n *\n * Must contain only ASCII letters, numbers, underscores, and hyphens, and\n * must be at most 512 characters long.\n */\n userId: z\n .string()\n .regex(/^[a-zA-Z0-9_-]+$/, 'userId must match /^[a-zA-Z0-9_-]+$/')\n .max(512, 'userId must be at most 512 characters long')\n .optional(),\n\n /**\n * Type of thinking to use. Defaults to `enabled`.\n */\n thinking: z\n .object({\n // `adaptive` is accepted at runtime for backwards compatibility and\n // mapped to `enabled`, but is intentionally excluded from the exported\n // provider options type.\n type: z.enum(['adaptive', 'enabled', 'disabled']).optional(),\n })\n .optional(),\n\n /**\n * Controls the thinking strength for DeepSeek V4 reasoning models.\n */\n // `medium` and `xhigh` are accepted at runtime for backwards compatibility\n // and mapped to canonical DeepSeek values, but are intentionally excluded\n // from the exported provider options type.\n reasoningEffort: z\n .enum(['low', 'medium', 'high', 'xhigh', 'max'])\n .optional(),\n\n /**\n * Whether to use strict JSON schema validation for structured outputs.\n * Only applies when the serving endpoint supports JSON schema response\n * formats (e.g. Azure). Defaults to `true`.\n */\n strictJsonSchema: z.boolean().optional(),\n });\n}\n\nlet chatOptionsSchema:\n | ReturnType<typeof createDeepseekChatOptionsSchema>\n | undefined;\n\nexport function getDeepseekChatOptionsSchema() {\n return (chatOptionsSchema ??= createDeepseekChatOptionsSchema());\n}\n\nexport const deepseekLanguageModelChatOptions = lazySchema(() =>\n zodSchema(getDeepseekChatOptionsSchema()),\n);\n\nexport type DeepSeekLanguageModelChatOptions = {\n /**\n * Whether to return log probabilities for generated tokens.\n */\n logprobs?: boolean;\n\n /**\n * Number of most likely tokens to return at each token position.\n *\n * Setting this option automatically enables `logprobs`.\n */\n topLogprobs?: number;\n\n /**\n * An opaque identifier for the end user. DeepSeek uses this identifier for\n * content-safety tracing and request isolation.\n *\n * Must contain only ASCII letters, numbers, underscores, and hyphens, and\n * must be at most 512 characters long.\n */\n userId?: string;\n\n /**\n * Controls whether thinking mode is enabled. Defaults to `enabled`.\n */\n thinking?: {\n type?: 'enabled' | 'disabled';\n };\n\n /**\n * Controls the thinking strength for DeepSeek V4 reasoning models.\n */\n reasoningEffort?: 'low' | 'high' | 'max';\n\n /**\n * Whether to use strict JSON schema validation for structured outputs.\n * Only applies when the serving endpoint supports JSON schema response\n * formats (e.g. Azure). Defaults to `true`.\n */\n strictJsonSchema?: boolean;\n};\n\nfunction createDeepseekMessageOptionsSchema() {\n return z.object({\n /**\n * The name of the participant represented by the message.\n *\n * Supported on system, user, and assistant messages.\n */\n name: z.string().optional(),\n });\n}\n\nlet messageOptionsSchema:\n | ReturnType<typeof createDeepseekMessageOptionsSchema>\n | undefined;\n\nexport function getDeepseekMessageOptionsSchema() {\n return (messageOptionsSchema ??= createDeepseekMessageOptionsSchema());\n}\n\nexport const deepseekMessageProviderOptions = lazySchema(() =>\n zodSchema(getDeepseekMessageOptionsSchema()),\n);\n\nexport type DeepSeekMessageProviderOptions = InferSchema<\n typeof deepseekMessageProviderOptions\n>;\n\nfunction createDeepseekAssistantMessageOptionsSchema() {\n return getDeepseekMessageOptionsSchema().extend({\n /**\n * Whether the assistant message content is a prefix that DeepSeek should\n * continue. This beta feature is only supported on the final assistant\n * message when using a beta base URL.\n */\n prefix: z.literal(true).optional(),\n });\n}\n\nlet assistantMessageOptionsSchema:\n | ReturnType<typeof createDeepseekAssistantMessageOptionsSchema>\n | undefined;\n\nexport function getDeepseekAssistantMessageOptionsSchema() {\n return (assistantMessageOptionsSchema ??=\n createDeepseekAssistantMessageOptionsSchema());\n}\n\nexport const deepseekAssistantMessageProviderOptions = lazySchema(() =>\n zodSchema(getDeepseekAssistantMessageOptionsSchema()),\n);\n\nexport type DeepSeekAssistantMessageProviderOptions = InferSchema<\n typeof deepseekAssistantMessageProviderOptions\n>;\n","import {\n type InferSchema,\n lazySchema,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const deepseekFilePartProviderOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * Controls how DeepSeek processes an image sent as an `image_url` part.\n *\n * @see https://api-docs.deepseek.com/api/create-chat-completion/\n */\n imageDetail: z.enum(['low', 'high', 'original', 'auto']).optional(),\n\n /**\n * Sends inline image data as a DeepSeek `file` part using `file_data`\n * instead of an `image_url` data URL. When set, the file part's filename\n * is preserved.\n *\n * This option only applies to inline image data. It cannot be combined\n * with `imageDetail`.\n */\n fileData: z.literal(true).optional(),\n }),\n ),\n);\n\nexport type DeepSeekFilePartProviderOptions = InferSchema<\n typeof deepseekFilePartProviderOptions\n>;\n","/**\n * Whether a model id uses DeepSeek V4-or-newer behavior (thinking mode on by\n * default, `reasoning_content` required on every assistant turn).\n *\n * DeepSeek publishes V4 models under both versioned ids (`deepseek-v4-pro`,\n * `deepseek-v4-flash-*`) and unversioned aliases (`deepseek-flash`, currently\n * serving V4.1 Flash). Known legacy aliases and pre-V4 version IDs retain\n * their previous behavior; unrecognized IDs inherit the current protocol.\n */\nexport function isDeepSeekV4Model(modelId: string): boolean {\n return !/(^|[/.])deepseek-(?:chat|reasoner|v[1-3](?:\\.\\d+)?)(?=[-/:.]|$)/.test(\n modelId,\n );\n}\n","import {\n InvalidPromptError,\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type LanguageModelV4FilePart,\n type LanguageModelV4Prompt,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n convertToBase64,\n getTopLevelMediaType,\n parseProviderOptions,\n resolveFullMediaType,\n resolveProviderReference,\n} from '@ai-sdk/provider-utils';\nimport type {\n DeepSeekChatPrompt,\n DeepSeekContentPart,\n DeepSeekToolMessage,\n} from './deepseek-chat-api-types';\nimport { deepseekFilePartProviderOptions } from './deepseek-file-part-options';\nimport { deepseekAssistantMessageProviderOptions } from './deepseek-chat-language-model-options';\nimport { isDeepSeekV4Model } from './is-deepseek-v4-model';\n\nconst supportedImageMediaTypes = new Set([\n 'image/gif',\n 'image/jpeg',\n 'image/jpg',\n 'image/png',\n 'image/webp',\n]);\n\nfunction resolveDeepSeekImageMediaType(part: LanguageModelV4FilePart): string {\n const resolvedMediaType = resolveFullMediaType({ part });\n\n if (!supportedImageMediaTypes.has(resolvedMediaType)) {\n throw new UnsupportedFunctionalityError({\n functionality: `DeepSeek image media type ${resolvedMediaType}`,\n message: 'DeepSeek supports JPEG, PNG, GIF, and WebP image inputs.',\n });\n }\n\n return resolvedMediaType;\n}\n\nfunction validateDeepSeekImageUrl({\n url,\n prompt,\n}: {\n url: string;\n prompt: LanguageModelV4Prompt;\n}): void {\n if (url.length > 8192) {\n throw new InvalidPromptError({\n prompt,\n message: 'DeepSeek image URLs must not exceed 8192 characters.',\n });\n }\n}\n\nexport async function convertToDeepSeekChatMessages({\n prompt,\n responseFormat,\n modelId,\n providerOptionsName = 'deepseek',\n supportsAssistantPrefixCompletion = false,\n supportsStructuredOutputs = false,\n}: {\n prompt: LanguageModelV4Prompt;\n responseFormat: LanguageModelV4CallOptions['responseFormat'];\n modelId: string;\n providerOptionsName?: string;\n supportsAssistantPrefixCompletion?: boolean;\n supportsStructuredOutputs?: boolean;\n}): Promise<{\n messages: DeepSeekChatPrompt;\n warnings: Array<SharedV4Warning>;\n}> {\n const isDeepSeekV4 = isDeepSeekV4Model(modelId);\n const messages: DeepSeekChatPrompt = [];\n const warnings: Array<SharedV4Warning> = [];\n\n // Inject system message if response format is JSON\n if (responseFormat?.type === 'json') {\n if (responseFormat.schema == null) {\n messages.push({\n role: 'system',\n content: 'Return JSON.',\n });\n } else if (!supportsStructuredOutputs) {\n messages.push({\n role: 'system',\n content:\n 'Return JSON that conforms to the following schema: ' +\n JSON.stringify(responseFormat.schema),\n });\n warnings.push({\n type: 'compatibility',\n feature: 'responseFormat JSON schema',\n details: 'JSON response schema is injected into the system message.',\n });\n }\n }\n\n // TODO use findLastIndex once we use ES2023\n let lastUserMessageIndex = -1;\n for (let i = prompt.length - 1; i >= 0; i--) {\n if (prompt[i].role === 'user') {\n lastUserMessageIndex = i;\n break;\n }\n }\n\n let index = -1;\n for (const { role, content, providerOptions } of prompt) {\n index++;\n\n // The assistant schema extends the common message schema, so one parse\n // validates names for every role and the assistant-only prefix option.\n const deepseekMessageOptions = await parseProviderOptions({\n provider: providerOptionsName,\n providerOptions,\n schema: deepseekAssistantMessageProviderOptions,\n });\n\n if (deepseekMessageOptions?.prefix === true && role !== 'assistant') {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek assistant prefix completion requires `prefix: true` on an assistant message.',\n });\n }\n\n switch (role) {\n case 'system': {\n messages.push({\n role: 'system',\n content,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n });\n break;\n }\n\n case 'user': {\n const hasImagePart = content.some(\n part =>\n part.type === 'file' &&\n (part.data.type === 'reference' ||\n part.data.type === 'url' ||\n part.data.type === 'data') &&\n getTopLevelMediaType(part.mediaType) === 'image',\n );\n\n if (!hasImagePart) {\n let userContent = '';\n for (const part of content) {\n if (part.type === 'text') {\n userContent += part.text;\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `user message part type: ${part.type}`,\n });\n }\n }\n\n messages.push({\n role: 'user',\n content: userContent,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n });\n break;\n }\n\n const userContent: Array<DeepSeekContentPart> = [];\n for (const part of content) {\n if (part.type === 'text') {\n userContent.push({ type: 'text', text: part.text });\n } else if (\n part.type === 'file' &&\n getTopLevelMediaType(part.mediaType) === 'image'\n ) {\n const filePartOptions = await parseProviderOptions({\n provider: providerOptionsName,\n providerOptions: part.providerOptions,\n schema: deepseekFilePartProviderOptions,\n });\n\n if (part.data.type === 'reference') {\n userContent.push({\n type: 'file',\n file_id: resolveProviderReference({\n reference: part.data.reference,\n provider: 'deepseek',\n }),\n });\n } else if (part.data.type === 'url' || part.data.type === 'data') {\n const resolvedMediaType = resolveDeepSeekImageMediaType(part);\n\n if (part.data.type === 'url') {\n const url = part.data.url.toString();\n\n validateDeepSeekImageUrl({ url, prompt });\n\n if (filePartOptions?.fileData === true) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek `fileData` image parts require inline data, not a URL.',\n });\n }\n\n userContent.push({\n type: 'image_url',\n image_url: {\n url,\n ...(filePartOptions?.imageDetail != null && {\n detail: filePartOptions.imageDetail,\n }),\n },\n });\n } else {\n const dataUrl = `data:${\n resolvedMediaType === 'image/jpg'\n ? 'image/jpeg'\n : resolvedMediaType\n };base64,${convertToBase64(part.data.data)}`;\n\n if (filePartOptions?.fileData === true) {\n if (filePartOptions.imageDetail != null) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek `imageDetail` cannot be combined with `fileData`.',\n });\n }\n\n userContent.push({\n type: 'file',\n file_data: dataUrl,\n ...(part.filename != null && { filename: part.filename }),\n });\n } else {\n userContent.push({\n type: 'image_url',\n image_url: {\n url: dataUrl,\n ...(filePartOptions?.imageDetail != null && {\n detail: filePartOptions.imageDetail,\n }),\n },\n });\n }\n }\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `user message part type: ${part.type}`,\n });\n }\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `user message part type: ${part.type}`,\n });\n }\n }\n\n messages.push({\n role: 'user',\n content: userContent,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n });\n\n break;\n }\n case 'assistant': {\n if (deepseekMessageOptions?.prefix === true) {\n if (index !== prompt.length - 1) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek assistant prefix completion requires the prefixed assistant message to be the final message.',\n });\n }\n\n if (!supportsAssistantPrefixCompletion) {\n throw new UnsupportedFunctionalityError({\n functionality: 'DeepSeek assistant prefix completion',\n message:\n 'DeepSeek assistant prefix completion requires a beta base URL ending in `/beta`.',\n });\n }\n }\n\n let text = '';\n let reasoning: string | undefined;\n\n const toolCalls: Array<{\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n }> = [];\n\n for (const part of content) {\n switch (part.type) {\n case 'text': {\n text += part.text;\n break;\n }\n case 'reasoning': {\n // R1 must not receive prior reasoning; V4 requires it.\n if (index <= lastUserMessageIndex && !isDeepSeekV4) {\n break;\n }\n\n if (reasoning == null) {\n reasoning = part.text;\n } else {\n reasoning += part.text;\n }\n break;\n }\n case 'tool-call': {\n toolCalls.push({\n id: part.toolCallId,\n type: 'function',\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input),\n },\n });\n break;\n }\n }\n }\n\n // V4 demands the field on every assistant turn — back-fill an empty\n // string when the source message had no reasoning part at all.\n messages.push({\n role: 'assistant',\n content: text,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n ...(deepseekMessageOptions?.prefix === true && {\n prefix: true,\n }),\n reasoning_content: reasoning ?? (isDeepSeekV4 ? '' : undefined),\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n });\n\n break;\n }\n\n case 'tool': {\n if (deepseekMessageOptions?.name != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'message name on tool messages',\n });\n }\n\n for (const toolResponse of content) {\n if (toolResponse.type === 'tool-approval-response') {\n continue;\n }\n const output = toolResponse.output;\n\n let contentValue: DeepSeekToolMessage['content'];\n switch (output.type) {\n case 'text':\n case 'error-text':\n contentValue = output.value;\n break;\n case 'execution-denied':\n contentValue = output.reason ?? 'Tool call execution denied.';\n break;\n case 'json':\n case 'error-json':\n contentValue = JSON.stringify(output.value);\n break;\n case 'content': {\n const hasImagePart = output.value.some(\n part =>\n part.type === 'file' &&\n (part.data.type === 'reference' ||\n part.data.type === 'url' ||\n part.data.type === 'data') &&\n getTopLevelMediaType(part.mediaType) === 'image',\n );\n\n if (!hasImagePart) {\n contentValue = JSON.stringify(output.value);\n break;\n }\n\n contentValue = [];\n for (const part of output.value) {\n if (part.type === 'text') {\n contentValue.push({ type: 'text', text: part.text });\n } else if (\n part.type === 'file' &&\n (part.data.type === 'reference' ||\n part.data.type === 'url' ||\n part.data.type === 'data') &&\n getTopLevelMediaType(part.mediaType) === 'image'\n ) {\n if (part.data.type === 'reference') {\n contentValue.push({\n type: 'file',\n file_id: resolveProviderReference({\n reference: part.data.reference,\n provider: 'deepseek',\n }),\n });\n continue;\n }\n\n const filePartOptions = await parseProviderOptions({\n provider: providerOptionsName,\n providerOptions: part.providerOptions,\n schema: deepseekFilePartProviderOptions,\n });\n const resolvedMediaType = resolveDeepSeekImageMediaType(part);\n let url: string;\n\n if (part.data.type === 'url') {\n url = part.data.url.toString();\n validateDeepSeekImageUrl({ url, prompt });\n } else {\n url = `data:${\n resolvedMediaType === 'image/jpg'\n ? 'image/jpeg'\n : resolvedMediaType\n };base64,${convertToBase64(part.data.data)}`;\n }\n\n contentValue.push({\n type: 'image_url',\n image_url: {\n url,\n ...(filePartOptions?.imageDetail != null && {\n detail: filePartOptions.imageDetail,\n }),\n },\n });\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `tool result content part type: ${part.type}`,\n });\n }\n }\n break;\n }\n }\n\n messages.push({\n role: 'tool',\n tool_call_id: toolResponse.toolCallId,\n content: contentValue,\n });\n }\n break;\n }\n\n default: {\n warnings.push({\n type: 'unsupported',\n feature: `message role: ${role}`,\n });\n break;\n }\n }\n }\n\n return { messages, warnings };\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\nimport { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';\n\nexport function convertDeepSeekUsage(\n usage:\n | {\n prompt_tokens?: number | null | undefined;\n completion_tokens?: number | null | undefined;\n prompt_cache_hit_tokens?: number | null | undefined;\n prompt_tokens_details?:\n | {\n cached_tokens?: number | null | undefined;\n }\n | null\n | undefined;\n completion_tokens_details?:\n | {\n reasoning_tokens?: number | null | undefined;\n }\n | null\n | undefined;\n }\n | undefined\n | null,\n): LanguageModelV4Usage {\n if (usage == null) {\n return createNullLanguageModelUsage();\n }\n\n const promptTokens = usage.prompt_tokens ?? 0;\n const completionTokens = usage.completion_tokens ?? 0;\n const cacheReadTokens =\n usage.prompt_cache_hit_tokens ??\n usage.prompt_tokens_details?.cached_tokens ??\n 0;\n const reasoningTokens =\n usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: completionTokens,\n text: Math.max(0, completionTokens - reasoningTokens),\n reasoning: reasoningTokens,\n },\n raw: usage,\n };\n}\n","import {\n type InferSchema,\n lazySchema,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type DeepSeekChatPrompt = Array<DeepSeekMessage>;\n\nexport type DeepSeekMessage =\n | DeepSeekSystemMessage\n | DeepSeekUserMessage\n | DeepSeekAssistantMessage\n | DeepSeekToolMessage;\n\nexport interface DeepSeekSystemMessage {\n role: 'system';\n content: string;\n name?: string;\n}\n\nexport interface DeepSeekUserMessage {\n role: 'user';\n content: string | Array<DeepSeekContentPart>;\n name?: string;\n}\n\nexport type DeepSeekContentPart =\n | DeepSeekContentPartText\n | DeepSeekContentPartImage\n | DeepSeekContentPartFile;\n\nexport interface DeepSeekContentPartText {\n type: 'text';\n text: string;\n}\n\nexport interface DeepSeekContentPartImage {\n type: 'image_url';\n image_url: {\n url: string;\n detail?: 'low' | 'high' | 'original' | 'auto';\n };\n}\n\nexport type DeepSeekContentPartFile =\n | {\n type: 'file';\n file_id: string;\n }\n | {\n type: 'file';\n file_data: string;\n filename?: string;\n };\n\nexport interface DeepSeekAssistantMessage {\n role: 'assistant';\n content?: string | null;\n name?: string;\n prefix?: true;\n reasoning_content?: string;\n tool_calls?: Array<DeepSeekMessageToolCall>;\n}\n\nexport interface DeepSeekMessageToolCall {\n type: 'function';\n id: string;\n function: {\n arguments: string;\n name: string;\n };\n}\n\nexport interface DeepSeekToolMessage {\n role: 'tool';\n content: string | Array<DeepSeekContentPart>;\n tool_call_id: string;\n}\n\nexport interface DeepSeekFunctionTool {\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n strict?: boolean;\n };\n}\n\nexport type DeepSeekToolChoice =\n | { type: 'function'; function: { name: string } }\n | 'auto'\n | 'none'\n | 'required'\n | undefined;\n\n// Loose, nested objects included: the parsed value is returned as `usage.raw`.\nfunction createTokenUsageSchema() {\n return z\n .looseObject({\n prompt_tokens: z.number().nullish(),\n completion_tokens: z.number().nullish(),\n prompt_cache_hit_tokens: z.number().nullish(),\n prompt_cache_miss_tokens: z.number().nullish(),\n total_tokens: z.number().nullish(),\n prompt_tokens_details: z\n .looseObject({\n cached_tokens: z.number().nullish(),\n })\n .nullish(),\n completion_tokens_details: z\n .looseObject({\n reasoning_tokens: z.number().nullish(),\n })\n .nullish(),\n })\n .nullish();\n}\n\nlet tokenUsageSchema: ReturnType<typeof createTokenUsageSchema> | undefined;\n\nfunction getTokenUsageSchema() {\n return (tokenUsageSchema ??= createTokenUsageSchema());\n}\n\nexport type DeepSeekChatTokenUsage = z.infer<\n ReturnType<typeof getTokenUsageSchema>\n>;\n\nfunction createDeepSeekErrorSchema() {\n return z.object({\n error: z.object({\n message: z.string(),\n type: z.string().nullish(),\n param: z.any().nullish(),\n code: z.union([z.string(), z.number()]).nullish(),\n }),\n });\n}\n\nlet errorSchema: ReturnType<typeof createDeepSeekErrorSchema> | undefined;\n\nfunction getDeepSeekErrorSchema() {\n return (errorSchema ??= createDeepSeekErrorSchema());\n}\n\nexport const deepSeekErrorSchema = lazySchema(() =>\n zodSchema(getDeepSeekErrorSchema()),\n);\n\nexport type DeepSeekErrorData = InferSchema<typeof deepSeekErrorSchema>;\n\nfunction createDeepseekChatLogprobsSchema() {\n const deepseekChatLogprobSchema = z.object({\n token: z.string(),\n logprob: z.number(),\n bytes: z.array(z.number()).nullable(),\n top_logprobs: z.array(\n z.object({\n token: z.string(),\n logprob: z.number(),\n bytes: z.array(z.number()).nullable(),\n }),\n ),\n });\n\n return z\n .object({\n content: z.array(deepseekChatLogprobSchema).nullish(),\n reasoning_content: z.array(deepseekChatLogprobSchema).nullish(),\n })\n .nullish();\n}\n\nlet logprobsSchema:\n | ReturnType<typeof createDeepseekChatLogprobsSchema>\n | undefined;\n\nfunction getDeepseekChatLogprobsSchema() {\n return (logprobsSchema ??= createDeepseekChatLogprobsSchema());\n}\n\nexport type DeepSeekChatLogprob = NonNullable<\n NonNullable<\n z.infer<ReturnType<typeof getDeepseekChatLogprobsSchema>>\n >['content']\n>[number];\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const deepseekChatResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string().nullish(),\n created: z.number().nullish(),\n model: z.string().nullish(),\n object: z.literal('chat.completion').nullish(),\n system_fingerprint: z.string().nullish(),\n choices: z.array(\n z.object({\n index: z.number().nullish(),\n message: z.object({\n role: z.literal('assistant').nullish(),\n content: z.string().nullish(),\n reasoning_content: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n id: z.string().nullish(),\n type: z.literal('function').nullish(),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n }),\n )\n .nullish(),\n }),\n logprobs: getDeepseekChatLogprobsSchema(),\n finish_reason: z.string().nullish(),\n }),\n ),\n usage: getTokenUsageSchema(),\n }),\n ),\n);\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const deepseekChatChunkSchema = lazySchema(() =>\n zodSchema(\n z.union([\n z.object({\n id: z.string().nullish(),\n created: z.number().nullish(),\n model: z.string().nullish(),\n object: z.literal('chat.completion.chunk').nullish(),\n system_fingerprint: z.string().nullish(),\n choices: z.array(\n z.object({\n index: z.number().nullish(),\n delta: z\n .object({\n role: z.enum(['assistant']).nullish(),\n content: z.string().nullish(),\n reasoning_content: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n index: z.number(),\n id: z.string().nullish(),\n type: z.literal('function').nullish(),\n function: z.object({\n name: z.string().nullish(),\n arguments: z.string().nullish(),\n }),\n }),\n )\n .nullish(),\n })\n .nullish(),\n logprobs: getDeepseekChatLogprobsSchema(),\n finish_reason: z.string().nullish(),\n }),\n ),\n usage: getTokenUsageSchema(),\n }),\n getDeepSeekErrorSchema(),\n ]),\n ),\n);\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport type {\n DeepSeekFunctionTool,\n DeepSeekToolChoice,\n} from './deepseek-chat-api-types';\n\nexport function prepareTools({\n tools,\n toolChoice,\n supportsStrictToolCalls,\n}: {\n tools: LanguageModelV4CallOptions['tools'];\n toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n supportsStrictToolCalls?: boolean;\n}): {\n tools: undefined | Array<DeepSeekFunctionTool>;\n toolChoice: DeepSeekToolChoice;\n toolWarnings: SharedV4Warning[];\n} {\n // when the tools array is empty, change it to undefined to prevent errors:\n tools = tools?.length ? tools : undefined;\n\n const toolWarnings: SharedV4Warning[] = [];\n\n if (tools == null) {\n return { tools: undefined, toolChoice: undefined, toolWarnings };\n }\n\n const functionTools = tools.filter(tool => tool.type === 'function');\n const hasStrictTool = functionTools.some(tool => tool.strict === true);\n\n if (hasStrictTool && supportsStrictToolCalls === false) {\n throw new UnsupportedFunctionalityError({\n functionality: 'DeepSeek strict tool calls',\n message:\n 'DeepSeek strict tool calls require a beta base URL ending in `/beta`.',\n });\n }\n\n if (\n hasStrictTool &&\n supportsStrictToolCalls === true &&\n functionTools.some(tool => tool.strict !== true)\n ) {\n throw new UnsupportedFunctionalityError({\n functionality: 'mixed DeepSeek strict and non-strict tool calls',\n message:\n 'DeepSeek strict mode requires every function tool in the request to set `strict: true`.',\n });\n }\n\n const deepseekTools: Array<DeepSeekFunctionTool> = [];\n\n for (const tool of tools) {\n if (tool.type === 'provider') {\n toolWarnings.push({\n type: 'unsupported',\n feature: `provider-defined tool ${tool.id}`,\n });\n } else {\n deepseekTools.push({\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...(tool.strict != null ? { strict: tool.strict } : {}),\n },\n });\n }\n }\n\n if (toolChoice == null) {\n return { tools: deepseekTools, toolChoice: undefined, toolWarnings };\n }\n\n const type = toolChoice?.type;\n\n switch (type) {\n case 'auto':\n case 'none':\n case 'required':\n return { tools: deepseekTools, toolChoice: type, toolWarnings };\n case 'tool':\n return {\n tools: deepseekTools,\n toolChoice: {\n type: 'function',\n function: { name: toolChoice.toolName },\n },\n toolWarnings,\n };\n default: {\n return {\n tools: deepseekTools,\n toolChoice: undefined,\n toolWarnings: [\n ...toolWarnings,\n {\n type: 'unsupported',\n feature: `tool choice type: ${type}`,\n },\n ],\n };\n }\n }\n}\n","import type { LanguageModelV4FinishReason } from '@ai-sdk/provider';\n\nexport function mapDeepSeekFinishReason(\n finishReason: string | null | undefined,\n): LanguageModelV4FinishReason['unified'] {\n switch (finishReason) {\n case 'stop':\n return 'stop';\n case 'length':\n return 'length';\n case 'content_filter':\n return 'content-filter';\n case 'tool_calls':\n return 'tool-calls';\n case 'insufficient_system_resource':\n return 'error';\n default:\n return 'other';\n }\n}\n","import {\n InvalidResponseDataError,\n type APICallError,\n type LanguageModelV4,\n type LanguageModelV4CallOptions,\n type LanguageModelV4Content,\n type LanguageModelV4FinishReason,\n type LanguageModelV4GenerateResult,\n type LanguageModelV4StreamPart,\n type LanguageModelV4StreamResult,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n createProviderStreamError,\n generateId,\n isCustomReasoning,\n mapReasoningToProviderEffort,\n parseProviderOptions,\n postJsonToApi,\n serializeModelOptions,\n StreamingToolCallTracker,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n type FetchFunction,\n type InferSchema,\n type ParseResult,\n type ResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { convertToDeepSeekChatMessages } from './convert-to-deepseek-chat-messages';\nimport { convertDeepSeekUsage } from './convert-to-deepseek-usage';\nimport {\n deepseekChatChunkSchema,\n deepseekChatResponseSchema,\n deepSeekErrorSchema,\n type DeepSeekChatLogprob,\n type DeepSeekChatTokenUsage,\n} from './deepseek-chat-api-types';\nimport {\n deepseekLanguageModelChatOptions,\n type DeepSeekChatModelId,\n} from './deepseek-chat-language-model-options';\nimport { prepareTools } from './deepseek-prepare-tools';\nimport { getResponseMetadata } from './get-response-metadata';\nimport { isDeepSeekV4Model } from './is-deepseek-v4-model';\nimport { mapDeepSeekFinishReason } from './map-deepseek-finish-reason';\n\nexport type DeepSeekChatConfig = {\n provider: string;\n headers?: () => Record<string, string | undefined>;\n url: (options: { modelId: string; path: string }) => string;\n fetch?: FetchFunction;\n supportsAssistantPrefixCompletion?: boolean;\n supportsStrictToolCalls?: boolean;\n supportsPenaltySampling?: boolean;\n supportsThinking?: boolean;\n supportsStructuredOutputs?: boolean;\n};\n\nfunction createDeepSeekStreamError(\n error: {\n message: string;\n type?: string | null;\n code?: string | number | null;\n },\n data: unknown,\n) {\n const metadata = getDeepSeekStreamErrorMetadata(error);\n\n return createProviderStreamError({\n message: error.message,\n type: error.type ?? undefined,\n code: error.code ?? undefined,\n ...metadata,\n data,\n });\n}\n\nfunction getDeepSeekStreamErrorMetadata(error: {\n type?: string | null;\n code?: string | number | null;\n}): {\n statusCode?: number;\n isRetryable?: boolean;\n} {\n if (\n error.code === 'insufficient_quota' ||\n error.type === 'insufficient_quota'\n ) {\n return { statusCode: 429, isRetryable: false };\n }\n\n const explicitStatusCode = getHttpStatusCode(error.code);\n if (explicitStatusCode != null) {\n return {\n statusCode: explicitStatusCode,\n isRetryable: isRetryableStatusCode(explicitStatusCode),\n };\n }\n\n for (const discriminator of [error.code, error.type]) {\n switch (discriminator) {\n case 'rate_limit_exceeded':\n case 'rate_limit_error':\n return { statusCode: 429, isRetryable: true };\n case 'server_error':\n case 'api_error':\n case 'internal_server_error':\n return { statusCode: 500, isRetryable: true };\n case 'overloaded_error':\n case 'service_unavailable':\n return { statusCode: 503, isRetryable: true };\n case 'timeout':\n case 'timeout_error':\n return { statusCode: 504, isRetryable: true };\n case 'authentication_error':\n case 'invalid_api_key':\n return { statusCode: 401, isRetryable: false };\n case 'permission_error':\n return { statusCode: 403, isRetryable: false };\n case 'not_found_error':\n case 'model_not_found':\n return { statusCode: 404, isRetryable: false };\n case 'bad_request':\n case 'context_length_exceeded':\n case 'invalid_request_error':\n return { statusCode: 400, isRetryable: false };\n }\n }\n\n return {};\n}\n\nfunction getHttpStatusCode(value: unknown): number | undefined {\n const statusCode =\n typeof value === 'string' && /^\\d{3}$/.test(value) ? Number(value) : value;\n\n return typeof statusCode === 'number' &&\n Number.isInteger(statusCode) &&\n statusCode >= 400 &&\n statusCode <= 599\n ? statusCode\n : undefined;\n}\n\nfunction isRetryableStatusCode(statusCode: number): boolean {\n return (\n statusCode === 408 ||\n statusCode === 409 ||\n statusCode === 429 ||\n statusCode >= 500\n );\n}\n\nfunction mapDeepSeekProviderReasoningEffort({\n reasoningEffort,\n warnings,\n}: {\n reasoningEffort: 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n warnings: SharedV4Warning[];\n}): 'low' | 'high' | 'max' {\n const mapped =\n reasoningEffort === 'medium'\n ? 'high'\n : reasoningEffort === 'xhigh'\n ? 'max'\n : reasoningEffort;\n\n if (mapped !== reasoningEffort) {\n warnings.push({\n type: 'compatibility',\n feature: 'reasoningEffort',\n details: `reasoningEffort \"${reasoningEffort}\" is not a canonical DeepSeek value. mapped to \"${mapped}\".`,\n });\n }\n\n return mapped;\n}\n\nexport class DeepSeekChatLanguageModel implements LanguageModelV4 {\n readonly specificationVersion = 'v4';\n\n readonly modelId: DeepSeekChatModelId;\n\n readonly supportedUrls = {\n 'image/*': [/^https?:\\/\\/.*$/],\n };\n\n private readonly config: DeepSeekChatConfig;\n private readonly failedResponseHandler: ResponseHandler<APICallError>;\n\n static [WORKFLOW_SERIALIZE](model: DeepSeekChatLanguageModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: DeepSeekChatModelId;\n config: DeepSeekChatConfig;\n }) {\n return new DeepSeekChatLanguageModel(options.modelId, options.config);\n }\n\n constructor(modelId: DeepSeekChatModelId, config: DeepSeekChatConfig) {\n this.modelId = modelId;\n this.config = config;\n\n this.failedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: deepSeekErrorSchema,\n errorToMessage: (error: InferSchema<typeof deepSeekErrorSchema>) =>\n error.error.message,\n });\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n private get providerOptionsName(): string {\n return this.config.provider.split('.')[0].trim();\n }\n\n private async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n reasoning,\n providerOptions,\n stopSequences,\n responseFormat,\n seed,\n toolChoice,\n tools,\n }: LanguageModelV4CallOptions) {\n const deepseekOptions =\n (await parseProviderOptions({\n provider: this.providerOptionsName,\n providerOptions,\n schema: deepseekLanguageModelChatOptions,\n })) ?? {};\n\n const supportsStructuredOutputs =\n this.config.supportsStructuredOutputs === true;\n const supportsPenaltySampling =\n this.config.supportsPenaltySampling === true;\n\n const { messages, warnings } = await convertToDeepSeekChatMessages({\n prompt,\n responseFormat,\n modelId: this.modelId,\n providerOptionsName: this.providerOptionsName,\n supportsAssistantPrefixCompletion:\n this.config.supportsAssistantPrefixCompletion,\n supportsStructuredOutputs,\n });\n const allWarnings: SharedV4Warning[] = [...warnings];\n\n if (topK != null) {\n allWarnings.push({ type: 'unsupported', feature: 'topK' });\n }\n\n if (seed != null) {\n allWarnings.push({ type: 'unsupported', feature: 'seed' });\n }\n\n if (!supportsPenaltySampling && frequencyPenalty != null) {\n allWarnings.push({\n type: 'deprecated',\n setting: 'frequencyPenalty',\n message:\n 'frequencyPenalty is deprecated by DeepSeek and has been omitted. Remove frequencyPenalty from the request.',\n });\n }\n\n if (!supportsPenaltySampling && presencePenalty != null) {\n allWarnings.push({\n type: 'deprecated',\n setting: 'presencePenalty',\n message:\n 'presencePenalty is deprecated by DeepSeek and has been omitted. Remove presencePenalty from the request.',\n });\n }\n\n const {\n tools: deepseekTools,\n toolChoice: deepseekToolChoices,\n toolWarnings,\n } = prepareTools({\n tools,\n toolChoice,\n supportsStrictToolCalls: this.config.supportsStrictToolCalls,\n });\n\n const thinkingType = deepseekOptions.thinking?.type;\n if (thinkingType === 'adaptive') {\n allWarnings.push({\n type: 'compatibility',\n feature: 'thinking.type',\n details:\n 'thinking.type \"adaptive\" is not a canonical DeepSeek value. mapped to \"enabled\".',\n });\n }\n\n const thinking =\n this.config.supportsThinking === false\n ? undefined\n : thinkingType != null\n ? { type: thinkingType === 'adaptive' ? 'enabled' : thinkingType }\n : isCustomReasoning(reasoning)\n ? { type: reasoning === 'none' ? 'disabled' : 'enabled' }\n : undefined;\n\n const isThinkingEnabled =\n this.config.supportsThinking !== false &&\n thinking?.type !== 'disabled' &&\n (thinking != null ||\n this.modelId === 'deepseek-reasoner' ||\n isDeepSeekV4Model(this.modelId));\n\n if (isThinkingEnabled && temperature != null) {\n allWarnings.push({\n type: 'unsupported',\n feature: 'temperature',\n details:\n \"temperature has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use temperature.\",\n });\n }\n\n if (isThinkingEnabled && topP != null) {\n allWarnings.push({\n type: 'unsupported',\n feature: 'topP',\n details:\n \"topP has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use topP.\",\n });\n }\n\n const reasoningEffort =\n deepseekOptions.reasoningEffort != null\n ? mapDeepSeekProviderReasoningEffort({\n reasoningEffort: deepseekOptions.reasoningEffort,\n warnings: allWarnings,\n })\n : isCustomReasoning(reasoning) && reasoning !== 'none'\n ? mapReasoningToProviderEffort({\n reasoning,\n effortMap: {\n minimal: 'low',\n low: 'low',\n medium: 'high',\n high: 'high',\n xhigh: 'max',\n max: 'max',\n },\n warnings: allWarnings,\n })\n : undefined;\n\n return {\n args: {\n model: this.modelId,\n ...((deepseekOptions.logprobs === true ||\n deepseekOptions.topLogprobs != null) && { logprobs: true }),\n ...(deepseekOptions.topLogprobs != null && {\n top_logprobs: deepseekOptions.topLogprobs,\n }),\n max_tokens: maxOutputTokens,\n temperature: isThinkingEnabled ? undefined : temperature,\n top_p: isThinkingEnabled ? undefined : topP,\n frequency_penalty: supportsPenaltySampling\n ? frequencyPenalty\n : undefined,\n presence_penalty: supportsPenaltySampling ? presencePenalty : undefined,\n response_format:\n responseFormat?.type === 'json'\n ? supportsStructuredOutputs && responseFormat.schema != null\n ? {\n type: 'json_schema',\n json_schema: {\n schema: responseFormat.schema,\n strict: deepseekOptions.strictJsonSchema ?? true,\n name: responseFormat.name ?? 'response',\n description: responseFormat.description,\n },\n }\n : { type: 'json_object' }\n : undefined,\n stop: stopSequences,\n messages,\n tools: deepseekTools,\n tool_choice: deepseekToolChoices,\n thinking,\n ...(deepseekOptions.userId != null && {\n user_id: deepseekOptions.userId,\n }),\n ...(thinking?.type !== 'disabled' &&\n reasoningEffort != null && {\n reasoning_effort: reasoningEffort,\n }),\n },\n warnings: [...allWarnings, ...toolWarnings],\n };\n }\n\n async doGenerate(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4GenerateResult> {\n const { args, warnings } = await this.getArgs({ ...options });\n\n const {\n responseHeaders,\n value: responseBody,\n rawValue: rawResponse,\n } = await postJsonToApi({\n url: this.config.url({\n path: '/chat/completions',\n modelId: this.modelId,\n }),\n headers: combineHeaders(this.config.headers?.(), options.headers),\n body: args,\n failedResponseHandler: this.failedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n deepseekChatResponseSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const choice = responseBody.choices[0];\n if (choice == null) {\n throw new InvalidResponseDataError({\n data: rawResponse,\n message: 'Response did not contain any choices.',\n });\n }\n\n const content: Array<LanguageModelV4Content> = [];\n\n // reasoning content (before text):\n const reasoning = choice.message.reasoning_content;\n if (reasoning != null && reasoning.length > 0) {\n content.push({\n type: 'reasoning',\n text: reasoning,\n });\n }\n\n // tool calls:\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: 'tool-call',\n toolCallId: toolCall.id || generateId(),\n toolName: toolCall.function.name,\n input: toolCall.function.arguments!,\n });\n }\n }\n\n // text content:\n const text = choice.message.content;\n if (text != null && text.length > 0) {\n content.push({ type: 'text', text });\n }\n\n return {\n content,\n finishReason: {\n unified: mapDeepSeekFinishReason(choice.finish_reason),\n raw: choice.finish_reason ?? undefined,\n },\n usage: convertDeepSeekUsage(responseBody.usage),\n providerMetadata: {\n [this.providerOptionsName]: {\n promptCacheHitTokens: responseBody.usage?.prompt_cache_hit_tokens,\n promptCacheMissTokens: responseBody.usage?.prompt_cache_miss_tokens,\n ...(responseBody.object != null && {\n responseObject: responseBody.object,\n }),\n ...(choice.index != null && { choiceIndex: choice.index }),\n ...(choice.message.role != null && {\n messageRole: choice.message.role,\n }),\n ...(choice.message.tool_calls != null && {\n toolCallTypes: choice.message.tool_calls\n .map(toolCall => toolCall.type)\n .filter(type => type != null),\n }),\n ...(choice.logprobs != null && { logprobs: choice.logprobs }),\n ...(responseBody.system_fingerprint != null && {\n systemFingerprint: responseBody.system_fingerprint,\n }),\n },\n },\n request: { body: args },\n response: {\n ...getResponseMetadata(responseBody),\n headers: responseHeaders,\n body: rawResponse,\n },\n warnings,\n };\n }\n\n async doStream(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4StreamResult> {\n const { args, warnings } = await this.getArgs({ ...options });\n\n const body = {\n ...args,\n stream: true,\n stream_options: { include_usage: true },\n };\n\n const { responseHeaders, value: response } = await postJsonToApi({\n url: this.config.url({\n path: '/chat/completions',\n modelId: this.modelId,\n }),\n headers: combineHeaders(this.config.headers?.(), options.headers),\n body,\n failedResponseHandler: this.failedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n deepseekChatChunkSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n let toolCallTracker: StreamingToolCallTracker;\n\n // A clean end without the provider's completion signal is interrupted.\n let finishReason: LanguageModelV4FinishReason = {\n unified: 'interrupted',\n raw: undefined,\n };\n let usage: DeepSeekChatTokenUsage | undefined = undefined;\n let systemFingerprint: string | undefined = undefined;\n let isFirstChunk = true;\n const providerOptionsName = this.providerOptionsName;\n let isActiveReasoning = false;\n let isActiveText = false;\n let responseObject: 'chat.completion.chunk' | undefined;\n let choiceIndex: number | undefined;\n let messageRole: 'assistant' | undefined;\n const toolCallTypes = new Map<number, 'function'>();\n const contentLogprobs: DeepSeekChatLogprob[] = [];\n const reasoningLogprobs: DeepSeekChatLogprob[] = [];\n\n return {\n stream: response.pipeThrough(\n new TransformStream<\n ParseResult<InferSchema<typeof deepseekChatChunkSchema>>,\n LanguageModelV4StreamPart\n >({\n start(controller) {\n toolCallTracker = new StreamingToolCallTracker(controller, {\n generateId,\n });\n controller.enqueue({ type: 'stream-start', warnings });\n },\n\n transform(chunk, controller) {\n // Emit raw chunk if requested (before anything else)\n if (options.includeRawChunks) {\n controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n }\n\n // handle failed chunk parsing / validation:\n if (!chunk.success) {\n finishReason = { unified: 'error', raw: undefined };\n controller.enqueue({ type: 'error', error: chunk.error });\n return;\n }\n const value = chunk.value;\n\n // handle error chunks:\n if ('error' in value) {\n finishReason = { unified: 'error', raw: undefined };\n controller.enqueue({\n type: 'error',\n error: createDeepSeekStreamError(value.error, value),\n });\n return;\n }\n\n if (isFirstChunk) {\n isFirstChunk = false;\n\n controller.enqueue({\n type: 'response-metadata',\n ...getResponseMetadata(value),\n });\n }\n\n if (value.usage != null) {\n usage = value.usage;\n }\n\n if (value.object != null) {\n responseObject = value.object;\n }\n\n // The fingerprint is repeated on stream chunks; keep the latest\n // non-null value in case it changes during the response.\n if (value.system_fingerprint != null) {\n systemFingerprint = value.system_fingerprint;\n }\n\n const choice = value.choices[0];\n\n if (choice?.index != null) {\n choiceIndex = choice.index;\n }\n\n if (choice?.finish_reason != null) {\n finishReason = {\n unified: mapDeepSeekFinishReason(choice.finish_reason),\n raw: choice.finish_reason,\n };\n }\n\n if (choice?.logprobs?.content != null) {\n contentLogprobs.push(...choice.logprobs.content);\n }\n\n if (choice?.logprobs?.reasoning_content != null) {\n reasoningLogprobs.push(...choice.logprobs.reasoning_content);\n }\n\n if (choice?.delta == null) {\n return;\n }\n\n const delta = choice.delta;\n\n if (delta.role != null) {\n messageRole = delta.role;\n }\n\n // enqueue reasoning before text deltas:\n const reasoningContent = delta.reasoning_content;\n if (reasoningContent) {\n if (!isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-start',\n id: 'reasoning-0',\n });\n isActiveReasoning = true;\n }\n\n controller.enqueue({\n type: 'reasoning-delta',\n id: 'reasoning-0',\n delta: reasoningContent,\n });\n }\n\n if (delta.content) {\n if (!isActiveText) {\n controller.enqueue({ type: 'text-start', id: 'txt-0' });\n isActiveText = true;\n }\n\n // end reasoning when text starts:\n if (isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-end',\n id: 'reasoning-0',\n });\n isActiveReasoning = false;\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: 'txt-0',\n delta: delta.content,\n });\n }\n\n if (delta.tool_calls != null && delta.tool_calls.length > 0) {\n // end reasoning when tool calls start:\n if (isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-end',\n id: 'reasoning-0',\n });\n isActiveReasoning = false;\n }\n\n for (const toolCallDelta of delta.tool_calls) {\n if (toolCallDelta.type != null) {\n toolCallTypes.set(toolCallDelta.index, toolCallDelta.type);\n }\n toolCallTracker.processDelta(toolCallDelta);\n }\n }\n },\n\n flush(controller) {\n if (isActiveReasoning) {\n controller.enqueue({ type: 'reasoning-end', id: 'reasoning-0' });\n }\n\n if (isActiveText) {\n controller.enqueue({ type: 'text-end', id: 'txt-0' });\n }\n\n toolCallTracker.flush();\n\n controller.enqueue({\n type: 'finish',\n finishReason,\n usage: convertDeepSeekUsage(usage),\n providerMetadata: {\n [providerOptionsName]: {\n promptCacheHitTokens:\n usage?.prompt_cache_hit_tokens ?? undefined,\n promptCacheMissTokens:\n usage?.prompt_cache_miss_tokens ?? undefined,\n ...(responseObject != null && { responseObject }),\n ...(choiceIndex != null && { choiceIndex }),\n ...(messageRole != null && { messageRole }),\n ...(toolCallTypes.size > 0 && {\n toolCallTypes: [...toolCallTypes.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, type]) => type),\n }),\n ...((contentLogprobs.length > 0 ||\n reasoningLogprobs.length > 0) && {\n logprobs: {\n ...(contentLogprobs.length > 0 && {\n content: contentLogprobs,\n }),\n ...(reasoningLogprobs.length > 0 && {\n reasoning_content: reasoningLogprobs,\n }),\n },\n }),\n ...(systemFingerprint != null && { systemFingerprint }),\n },\n },\n });\n },\n }),\n ),\n request: { body },\n response: { headers: responseHeaders },\n };\n }\n}\n","import {\n getDeepseekAssistantMessageOptionsSchema,\n getDeepseekChatOptionsSchema,\n getDeepseekMessageOptionsSchema,\n} from '../chat/deepseek-chat-language-model-options';\n\nexport * from '../chat/deepseek-chat-language-model';\nexport type {\n DeepSeekAssistantMessageProviderOptions,\n DeepSeekChatModelId,\n DeepSeekLanguageModelChatOptions,\n DeepSeekMessageProviderOptions,\n} from '../chat/deepseek-chat-language-model-options';\n\n// Preserve the Zod object exports for consumers of the internal entry point.\nexport const deepseekLanguageModelChatOptions = getDeepseekChatOptionsSchema();\nexport const deepseekMessageProviderOptions = getDeepseekMessageOptionsSchema();\nexport const deepseekAssistantMessageProviderOptions =\n getDeepseekAssistantMessageOptionsSchema();\n"],"mappings":";;;;AAiBA,SAAS,kCAAkC;CACzC,OAAO,EAAE,OAAO;;;;EAId,UAAU,EAAE,QAAQ,CAAC,CAAC,SAAS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ACF;IACF;IAEA,MAAM,YAAY;KAChB,IAAI,mBACF,WAAW,QAAQ;MAAE,MAAM;MAAiB,IAAI;KAAc,CAAC;KAGjE,IAAI,cACF,WAAW,QAAQ;MAAE,MAAM;MAAY,IAAI;KAAQ,CAAC;KAGtD,gBAAgB,MAAM;KAEtB,WAAW,QAAQ;MACjB,MAAM;MACN;MACA,OAAO,qBAAqB,KAAK;MACjC,kBAAkB,GACf,sBAAsB;OACrB,sBACE,OAAO,2BAA2B,KAAA;OACpC,uBACE,OAAO,4BAA4B,KAAA;OACrC,GAAI,kBAAkB,QAAQ,EAAE,eAAe;OAC/C,GAAI,eAAe,QAAQ,EAAE,YAAY;OACzC,GAAI,eAAe,QAAQ,EAAE,YAAY;OACzC,GAAI,cAAc,OAAO,KAAK,EAC5B,eAAe,CAAC,GAAG,cAAc,QAAQ,CAAC,CAAC,CACxC,MAAM,CAAC,OAAO,CAAC,WAAW,OAAO,KAAK,CAAC,CACvC,KAAK,GAAG,UAAU,IAAI,EAC3B;OACA,IAAK,gBAAgB,SAAS,KAC5B,kBAAkB,SAAS,MAAM,EACjC,UAAU;QACR,GAAI,gBAAgB,SAAS,KAAK,EAChC,SAAS,gBACX;QACA,GAAI,kBAAkB,SAAS,KAAK,EAClC,mBAAmB,kBACrB;OACF,EACF;OACA,GAAI,qBAAqB,QAAQ,EAAE,kBAAkB;MACvD,EACF;KACF,CAAC;IACH;GACF,CAAC,CACH;GACA,SAAS,EAAE,KAAK;GAChB,UAAU,EAAE,SAAS,gBAAgB;EACvC;CACF;AACF;;;ACzuBA,MAAa,mCAAmC,6BAA6B;AAC7E,MAAa,iCAAiC,gCAAgC;AAC9E,MAAa,0CACX,yCAAyC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["deepseekLanguageModelChatOptions","deepseekMessageProviderOptions","deepseekAssistantMessageProviderOptions","deepseekAssistantMessageProviderOptions","deepseekLanguageModelChatOptions"],"sources":["../../src/chat/deepseek-chat-language-model-options.ts","../../src/chat/deepseek-file-part-options.ts","../../src/chat/is-deepseek-v4-model.ts","../../src/chat/convert-to-deepseek-chat-messages.ts","../../src/chat/convert-to-deepseek-usage.ts","../../src/chat/deepseek-chat-api-types.ts","../../src/chat/deepseek-prepare-tools.ts","../../src/chat/map-deepseek-finish-reason.ts","../../src/chat/deepseek-chat-language-model.ts","../../src/internal/index.ts"],"sourcesContent":["import {\n type InferSchema,\n lazySchema,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// https://api-docs.deepseek.com/quick_start/pricing\nexport type DeepSeekChatModelId =\n | 'deepseek-flash'\n | 'deepseek-v4-flash'\n | 'deepseek-v4-pro'\n | 'deepseek-v4-flash-vision-exp'\n // Retired aliases remain assignable through the string escape hatch, but are\n // intentionally omitted from first-class editor suggestions.\n | (string & {});\n\nfunction createDeepseekChatOptionsSchema() {\n return z.object({\n /**\n * Whether to return log probabilities for generated tokens.\n */\n logprobs: z.boolean().optional(),\n\n /**\n * Number of most likely tokens to return at each token position.\n *\n * Setting this option automatically enables `logprobs`.\n */\n topLogprobs: z.number().int().min(0).max(20).optional(),\n\n /**\n * An opaque identifier for the end user. DeepSeek uses this identifier for\n * content-safety tracing and request isolation.\n *\n * Must contain only ASCII letters, numbers, underscores, and hyphens, and\n * must be at most 512 characters long.\n */\n userId: z\n .string()\n .regex(/^[a-zA-Z0-9_-]+$/, 'userId must match /^[a-zA-Z0-9_-]+$/')\n .max(512, 'userId must be at most 512 characters long')\n .optional(),\n\n /**\n * Type of thinking to use. Defaults to `enabled`.\n */\n thinking: z\n .object({\n // `adaptive` is accepted at runtime for backwards compatibility and\n // mapped to `enabled`, but is intentionally excluded from the exported\n // provider options type.\n type: z.enum(['adaptive', 'enabled', 'disabled']).optional(),\n })\n .optional(),\n\n /**\n * Controls the thinking strength for DeepSeek V4 reasoning models.\n */\n // `medium` and `xhigh` are accepted at runtime for backwards compatibility\n // and mapped to canonical DeepSeek values, but are intentionally excluded\n // from the exported provider options type.\n reasoningEffort: z\n .enum(['low', 'medium', 'high', 'xhigh', 'max'])\n .optional(),\n\n /**\n * Whether to use strict JSON schema validation for structured outputs.\n * Only applies when the serving endpoint supports JSON schema response\n * formats (e.g. Azure). Defaults to `true`.\n */\n strictJsonSchema: z.boolean().optional(),\n });\n}\n\nlet chatOptionsSchema:\n | ReturnType<typeof createDeepseekChatOptionsSchema>\n | undefined;\n\nexport function getDeepseekChatOptionsSchema() {\n return (chatOptionsSchema ??= createDeepseekChatOptionsSchema());\n}\n\nexport const deepseekLanguageModelChatOptions = lazySchema(() =>\n zodSchema(getDeepseekChatOptionsSchema()),\n);\n\nexport type DeepSeekLanguageModelChatOptions = {\n /**\n * Whether to return log probabilities for generated tokens.\n */\n logprobs?: boolean;\n\n /**\n * Number of most likely tokens to return at each token position.\n *\n * Setting this option automatically enables `logprobs`.\n */\n topLogprobs?: number;\n\n /**\n * An opaque identifier for the end user. DeepSeek uses this identifier for\n * content-safety tracing and request isolation.\n *\n * Must contain only ASCII letters, numbers, underscores, and hyphens, and\n * must be at most 512 characters long.\n */\n userId?: string;\n\n /**\n * Controls whether thinking mode is enabled. Defaults to `enabled`.\n */\n thinking?: {\n type?: 'enabled' | 'disabled';\n };\n\n /**\n * Controls the thinking strength for DeepSeek V4 reasoning models.\n */\n reasoningEffort?: 'low' | 'high' | 'max';\n\n /**\n * Whether to use strict JSON schema validation for structured outputs.\n * Only applies when the serving endpoint supports JSON schema response\n * formats (e.g. Azure). Defaults to `true`.\n */\n strictJsonSchema?: boolean;\n};\n\nfunction createDeepseekMessageOptionsSchema() {\n return z.object({\n /**\n * The name of the participant represented by the message.\n *\n * Supported on system, user, and assistant messages.\n */\n name: z.string().optional(),\n });\n}\n\nlet messageOptionsSchema:\n | ReturnType<typeof createDeepseekMessageOptionsSchema>\n | undefined;\n\nexport function getDeepseekMessageOptionsSchema() {\n return (messageOptionsSchema ??= createDeepseekMessageOptionsSchema());\n}\n\nexport const deepseekMessageProviderOptions = lazySchema(() =>\n zodSchema(getDeepseekMessageOptionsSchema()),\n);\n\nexport type DeepSeekMessageProviderOptions = InferSchema<\n typeof deepseekMessageProviderOptions\n>;\n\nfunction createDeepseekAssistantMessageOptionsSchema() {\n return getDeepseekMessageOptionsSchema().extend({\n /**\n * Whether the assistant message content is a prefix that DeepSeek should\n * continue. This beta feature is only supported on the final assistant\n * message when using a beta base URL.\n */\n prefix: z.literal(true).optional(),\n });\n}\n\nlet assistantMessageOptionsSchema:\n | ReturnType<typeof createDeepseekAssistantMessageOptionsSchema>\n | undefined;\n\nexport function getDeepseekAssistantMessageOptionsSchema() {\n return (assistantMessageOptionsSchema ??=\n createDeepseekAssistantMessageOptionsSchema());\n}\n\nexport const deepseekAssistantMessageProviderOptions = lazySchema(() =>\n zodSchema(getDeepseekAssistantMessageOptionsSchema()),\n);\n\nexport type DeepSeekAssistantMessageProviderOptions = InferSchema<\n typeof deepseekAssistantMessageProviderOptions\n>;\n","import {\n type InferSchema,\n lazySchema,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const deepseekFilePartProviderOptions = lazySchema(() =>\n zodSchema(\n z.object({\n /**\n * Controls how DeepSeek processes an image sent as an `image_url` part.\n *\n * @see https://api-docs.deepseek.com/api/create-chat-completion/\n */\n imageDetail: z.enum(['low', 'high', 'original', 'auto']).optional(),\n\n /**\n * Sends inline image data as a DeepSeek `file` part using `file_data`\n * instead of an `image_url` data URL. When set, the file part's filename\n * is preserved.\n *\n * This option only applies to inline image data. It cannot be combined\n * with `imageDetail`.\n */\n fileData: z.literal(true).optional(),\n }),\n ),\n);\n\nexport type DeepSeekFilePartProviderOptions = InferSchema<\n typeof deepseekFilePartProviderOptions\n>;\n","/**\n * Whether a model id uses DeepSeek V4-or-newer behavior (thinking mode on by\n * default, `reasoning_content` required on every assistant turn).\n *\n * DeepSeek publishes V4 models under both versioned ids (`deepseek-v4-pro`,\n * `deepseek-v4-flash-*`) and unversioned aliases (`deepseek-flash`, currently\n * serving V4.1 Flash). Known legacy aliases and pre-V4 version IDs retain\n * their previous behavior; unrecognized IDs inherit the current protocol.\n */\nexport function isDeepSeekV4Model(modelId: string): boolean {\n return !/(^|[/.])deepseek-(?:chat|reasoner|v[1-3](?:\\.\\d+)?)(?=[-/:.]|$)/.test(\n modelId,\n );\n}\n","import {\n InvalidPromptError,\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type LanguageModelV4FilePart,\n type LanguageModelV4Prompt,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n convertToBase64,\n getTopLevelMediaType,\n parseProviderOptions,\n resolveFullMediaType,\n resolveProviderReference,\n} from '@ai-sdk/provider-utils';\nimport type {\n DeepSeekChatPrompt,\n DeepSeekContentPart,\n DeepSeekToolMessage,\n} from './deepseek-chat-api-types';\nimport { deepseekFilePartProviderOptions } from './deepseek-file-part-options';\nimport { deepseekAssistantMessageProviderOptions } from './deepseek-chat-language-model-options';\nimport { isDeepSeekV4Model } from './is-deepseek-v4-model';\n\nconst supportedImageMediaTypes = new Set([\n 'image/gif',\n 'image/jpeg',\n 'image/jpg',\n 'image/png',\n 'image/webp',\n]);\n\nfunction resolveDeepSeekImageMediaType(part: LanguageModelV4FilePart): string {\n const resolvedMediaType = resolveFullMediaType({ part });\n\n if (!supportedImageMediaTypes.has(resolvedMediaType)) {\n throw new UnsupportedFunctionalityError({\n functionality: `DeepSeek image media type ${resolvedMediaType}`,\n message: 'DeepSeek supports JPEG, PNG, GIF, and WebP image inputs.',\n });\n }\n\n return resolvedMediaType;\n}\n\nfunction validateDeepSeekImageUrl({\n url,\n prompt,\n}: {\n url: string;\n prompt: LanguageModelV4Prompt;\n}): void {\n if (url.length > 8192) {\n throw new InvalidPromptError({\n prompt,\n message: 'DeepSeek image URLs must not exceed 8192 characters.',\n });\n }\n}\n\nexport async function convertToDeepSeekChatMessages({\n prompt,\n responseFormat,\n modelId,\n providerOptionsName = 'deepseek',\n supportsAssistantPrefixCompletion = false,\n supportsStructuredOutputs = false,\n}: {\n prompt: LanguageModelV4Prompt;\n responseFormat: LanguageModelV4CallOptions['responseFormat'];\n modelId: string;\n providerOptionsName?: string;\n supportsAssistantPrefixCompletion?: boolean;\n supportsStructuredOutputs?: boolean;\n}): Promise<{\n messages: DeepSeekChatPrompt;\n warnings: Array<SharedV4Warning>;\n}> {\n const isDeepSeekV4 = isDeepSeekV4Model(modelId);\n const messages: DeepSeekChatPrompt = [];\n const warnings: Array<SharedV4Warning> = [];\n\n // Inject system message if response format is JSON\n if (responseFormat?.type === 'json') {\n if (responseFormat.schema == null) {\n messages.push({\n role: 'system',\n content: 'Return JSON.',\n });\n } else if (!supportsStructuredOutputs) {\n messages.push({\n role: 'system',\n content:\n 'Return JSON that conforms to the following schema: ' +\n JSON.stringify(responseFormat.schema),\n });\n warnings.push({\n type: 'compatibility',\n feature: 'responseFormat JSON schema',\n details: 'JSON response schema is injected into the system message.',\n });\n }\n }\n\n // TODO use findLastIndex once we use ES2023\n let lastUserMessageIndex = -1;\n for (let i = prompt.length - 1; i >= 0; i--) {\n if (prompt[i].role === 'user') {\n lastUserMessageIndex = i;\n break;\n }\n }\n\n let index = -1;\n for (const { role, content, providerOptions } of prompt) {\n index++;\n\n // The assistant schema extends the common message schema, so one parse\n // validates names for every role and the assistant-only prefix option.\n const deepseekMessageOptions = await parseProviderOptions({\n provider: providerOptionsName,\n providerOptions,\n schema: deepseekAssistantMessageProviderOptions,\n });\n\n if (deepseekMessageOptions?.prefix === true && role !== 'assistant') {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek assistant prefix completion requires `prefix: true` on an assistant message.',\n });\n }\n\n switch (role) {\n case 'system': {\n messages.push({\n role: 'system',\n content,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n });\n break;\n }\n\n case 'user': {\n const hasImagePart = content.some(\n part =>\n part.type === 'file' &&\n (part.data.type === 'reference' ||\n part.data.type === 'url' ||\n part.data.type === 'data') &&\n getTopLevelMediaType(part.mediaType) === 'image',\n );\n\n if (!hasImagePart) {\n let userContent = '';\n for (const part of content) {\n if (part.type === 'text') {\n userContent += part.text;\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `user message part type: ${part.type}`,\n });\n }\n }\n\n messages.push({\n role: 'user',\n content: userContent,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n });\n break;\n }\n\n const userContent: Array<DeepSeekContentPart> = [];\n for (const part of content) {\n if (part.type === 'text') {\n userContent.push({ type: 'text', text: part.text });\n } else if (\n part.type === 'file' &&\n getTopLevelMediaType(part.mediaType) === 'image'\n ) {\n const filePartOptions = await parseProviderOptions({\n provider: providerOptionsName,\n providerOptions: part.providerOptions,\n schema: deepseekFilePartProviderOptions,\n });\n\n if (part.data.type === 'reference') {\n userContent.push({\n type: 'file',\n file_id: resolveProviderReference({\n reference: part.data.reference,\n provider: 'deepseek',\n }),\n });\n } else if (part.data.type === 'url' || part.data.type === 'data') {\n const resolvedMediaType = resolveDeepSeekImageMediaType(part);\n\n if (part.data.type === 'url') {\n const url = part.data.url.toString();\n\n validateDeepSeekImageUrl({ url, prompt });\n\n if (filePartOptions?.fileData === true) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek `fileData` image parts require inline data, not a URL.',\n });\n }\n\n userContent.push({\n type: 'image_url',\n image_url: {\n url,\n ...(filePartOptions?.imageDetail != null && {\n detail: filePartOptions.imageDetail,\n }),\n },\n });\n } else {\n const dataUrl = `data:${\n resolvedMediaType === 'image/jpg'\n ? 'image/jpeg'\n : resolvedMediaType\n };base64,${convertToBase64(part.data.data)}`;\n\n if (filePartOptions?.fileData === true) {\n if (filePartOptions.imageDetail != null) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek `imageDetail` cannot be combined with `fileData`.',\n });\n }\n\n userContent.push({\n type: 'file',\n file_data: dataUrl,\n ...(part.filename != null && { filename: part.filename }),\n });\n } else {\n userContent.push({\n type: 'image_url',\n image_url: {\n url: dataUrl,\n ...(filePartOptions?.imageDetail != null && {\n detail: filePartOptions.imageDetail,\n }),\n },\n });\n }\n }\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `user message part type: ${part.type}`,\n });\n }\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `user message part type: ${part.type}`,\n });\n }\n }\n\n messages.push({\n role: 'user',\n content: userContent,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n });\n\n break;\n }\n case 'assistant': {\n if (deepseekMessageOptions?.prefix === true) {\n if (index !== prompt.length - 1) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'DeepSeek assistant prefix completion requires the prefixed assistant message to be the final message.',\n });\n }\n\n if (!supportsAssistantPrefixCompletion) {\n throw new UnsupportedFunctionalityError({\n functionality: 'DeepSeek assistant prefix completion',\n message:\n 'DeepSeek assistant prefix completion requires a beta base URL ending in `/beta`.',\n });\n }\n }\n\n let text = '';\n let reasoning: string | undefined;\n\n const toolCalls: Array<{\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n }> = [];\n\n for (const part of content) {\n switch (part.type) {\n case 'text': {\n text += part.text;\n break;\n }\n case 'reasoning': {\n // R1 must not receive prior reasoning; V4 requires it.\n if (index <= lastUserMessageIndex && !isDeepSeekV4) {\n break;\n }\n\n if (reasoning == null) {\n reasoning = part.text;\n } else {\n reasoning += part.text;\n }\n break;\n }\n case 'tool-call': {\n toolCalls.push({\n id: part.toolCallId,\n type: 'function',\n function: {\n name: part.toolName,\n arguments: JSON.stringify(part.input),\n },\n });\n break;\n }\n }\n }\n\n // V4 demands the field on every assistant turn — back-fill an empty\n // string when the source message had no reasoning part at all.\n messages.push({\n role: 'assistant',\n content: text,\n ...(deepseekMessageOptions?.name != null && {\n name: deepseekMessageOptions.name,\n }),\n ...(deepseekMessageOptions?.prefix === true && {\n prefix: true,\n }),\n reasoning_content: reasoning ?? (isDeepSeekV4 ? '' : undefined),\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n });\n\n break;\n }\n\n case 'tool': {\n if (deepseekMessageOptions?.name != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'message name on tool messages',\n });\n }\n\n for (const toolResponse of content) {\n if (toolResponse.type === 'tool-approval-response') {\n continue;\n }\n const output = toolResponse.output;\n\n let contentValue: DeepSeekToolMessage['content'];\n switch (output.type) {\n case 'text':\n case 'error-text':\n contentValue = output.value;\n break;\n case 'execution-denied':\n contentValue = output.reason ?? 'Tool call execution denied.';\n break;\n case 'json':\n case 'error-json':\n contentValue = JSON.stringify(output.value);\n break;\n case 'content': {\n const hasImagePart = output.value.some(\n part =>\n part.type === 'file' &&\n (part.data.type === 'reference' ||\n part.data.type === 'url' ||\n part.data.type === 'data') &&\n getTopLevelMediaType(part.mediaType) === 'image',\n );\n\n if (!hasImagePart) {\n contentValue = JSON.stringify(output.value);\n break;\n }\n\n contentValue = [];\n for (const part of output.value) {\n if (part.type === 'text') {\n contentValue.push({ type: 'text', text: part.text });\n } else if (\n part.type === 'file' &&\n (part.data.type === 'reference' ||\n part.data.type === 'url' ||\n part.data.type === 'data') &&\n getTopLevelMediaType(part.mediaType) === 'image'\n ) {\n if (part.data.type === 'reference') {\n contentValue.push({\n type: 'file',\n file_id: resolveProviderReference({\n reference: part.data.reference,\n provider: 'deepseek',\n }),\n });\n continue;\n }\n\n const filePartOptions = await parseProviderOptions({\n provider: providerOptionsName,\n providerOptions: part.providerOptions,\n schema: deepseekFilePartProviderOptions,\n });\n const resolvedMediaType = resolveDeepSeekImageMediaType(part);\n let url: string;\n\n if (part.data.type === 'url') {\n url = part.data.url.toString();\n validateDeepSeekImageUrl({ url, prompt });\n } else {\n url = `data:${\n resolvedMediaType === 'image/jpg'\n ? 'image/jpeg'\n : resolvedMediaType\n };base64,${convertToBase64(part.data.data)}`;\n }\n\n contentValue.push({\n type: 'image_url',\n image_url: {\n url,\n ...(filePartOptions?.imageDetail != null && {\n detail: filePartOptions.imageDetail,\n }),\n },\n });\n } else {\n warnings.push({\n type: 'unsupported',\n feature: `tool result content part type: ${part.type}`,\n });\n }\n }\n break;\n }\n }\n\n messages.push({\n role: 'tool',\n tool_call_id: toolResponse.toolCallId,\n content: contentValue,\n });\n }\n break;\n }\n\n default: {\n warnings.push({\n type: 'unsupported',\n feature: `message role: ${role}`,\n });\n break;\n }\n }\n }\n\n return { messages, warnings };\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\nimport { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';\n\nexport function convertDeepSeekUsage(\n usage:\n | {\n prompt_tokens?: number | null | undefined;\n completion_tokens?: number | null | undefined;\n prompt_cache_hit_tokens?: number | null | undefined;\n prompt_tokens_details?:\n | {\n cached_tokens?: number | null | undefined;\n }\n | null\n | undefined;\n completion_tokens_details?:\n | {\n reasoning_tokens?: number | null | undefined;\n }\n | null\n | undefined;\n }\n | undefined\n | null,\n): LanguageModelV4Usage {\n if (usage == null) {\n return createNullLanguageModelUsage();\n }\n\n const promptTokens = usage.prompt_tokens ?? 0;\n const completionTokens = usage.completion_tokens ?? 0;\n const cacheReadTokens =\n usage.prompt_cache_hit_tokens ??\n usage.prompt_tokens_details?.cached_tokens ??\n 0;\n const reasoningTokens =\n usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: completionTokens,\n text: Math.max(0, completionTokens - reasoningTokens),\n reasoning: reasoningTokens,\n },\n raw: usage,\n };\n}\n","import {\n type InferSchema,\n lazySchema,\n zodSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport type DeepSeekChatPrompt = Array<DeepSeekMessage>;\n\nexport type DeepSeekMessage =\n | DeepSeekSystemMessage\n | DeepSeekUserMessage\n | DeepSeekAssistantMessage\n | DeepSeekToolMessage;\n\nexport interface DeepSeekSystemMessage {\n role: 'system';\n content: string;\n name?: string;\n}\n\nexport interface DeepSeekUserMessage {\n role: 'user';\n content: string | Array<DeepSeekContentPart>;\n name?: string;\n}\n\nexport type DeepSeekContentPart =\n | DeepSeekContentPartText\n | DeepSeekContentPartImage\n | DeepSeekContentPartFile;\n\nexport interface DeepSeekContentPartText {\n type: 'text';\n text: string;\n}\n\nexport interface DeepSeekContentPartImage {\n type: 'image_url';\n image_url: {\n url: string;\n detail?: 'low' | 'high' | 'original' | 'auto';\n };\n}\n\nexport type DeepSeekContentPartFile =\n | {\n type: 'file';\n file_id: string;\n }\n | {\n type: 'file';\n file_data: string;\n filename?: string;\n };\n\nexport interface DeepSeekAssistantMessage {\n role: 'assistant';\n content?: string | null;\n name?: string;\n prefix?: true;\n reasoning_content?: string;\n tool_calls?: Array<DeepSeekMessageToolCall>;\n}\n\nexport interface DeepSeekMessageToolCall {\n type: 'function';\n id: string;\n function: {\n arguments: string;\n name: string;\n };\n}\n\nexport interface DeepSeekToolMessage {\n role: 'tool';\n content: string | Array<DeepSeekContentPart>;\n tool_call_id: string;\n}\n\nexport interface DeepSeekFunctionTool {\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n strict?: boolean;\n };\n}\n\nexport type DeepSeekToolChoice =\n | { type: 'function'; function: { name: string } }\n | 'auto'\n | 'none'\n | 'required'\n | undefined;\n\n// Loose, nested objects included: the parsed value is returned as `usage.raw`.\nfunction createTokenUsageSchema() {\n return z\n .looseObject({\n prompt_tokens: z.number().nullish(),\n completion_tokens: z.number().nullish(),\n prompt_cache_hit_tokens: z.number().nullish(),\n prompt_cache_miss_tokens: z.number().nullish(),\n total_tokens: z.number().nullish(),\n prompt_tokens_details: z\n .looseObject({\n cached_tokens: z.number().nullish(),\n })\n .nullish(),\n completion_tokens_details: z\n .looseObject({\n reasoning_tokens: z.number().nullish(),\n })\n .nullish(),\n })\n .nullish();\n}\n\nlet tokenUsageSchema: ReturnType<typeof createTokenUsageSchema> | undefined;\n\nfunction getTokenUsageSchema() {\n return (tokenUsageSchema ??= createTokenUsageSchema());\n}\n\nexport type DeepSeekChatTokenUsage = z.infer<\n ReturnType<typeof getTokenUsageSchema>\n>;\n\nfunction createDeepSeekErrorSchema() {\n return z.object({\n error: z.object({\n message: z.string(),\n type: z.string().nullish(),\n param: z.any().nullish(),\n code: z.union([z.string(), z.number()]).nullish(),\n }),\n });\n}\n\nlet errorSchema: ReturnType<typeof createDeepSeekErrorSchema> | undefined;\n\nfunction getDeepSeekErrorSchema() {\n return (errorSchema ??= createDeepSeekErrorSchema());\n}\n\nexport const deepSeekErrorSchema = lazySchema(() =>\n zodSchema(getDeepSeekErrorSchema()),\n);\n\nexport type DeepSeekErrorData = InferSchema<typeof deepSeekErrorSchema>;\n\nfunction createDeepseekChatLogprobsSchema() {\n const deepseekChatLogprobSchema = z.object({\n token: z.string(),\n logprob: z.number(),\n bytes: z.array(z.number()).nullable(),\n top_logprobs: z.array(\n z.object({\n token: z.string(),\n logprob: z.number(),\n bytes: z.array(z.number()).nullable(),\n }),\n ),\n });\n\n return z\n .object({\n content: z.array(deepseekChatLogprobSchema).nullish(),\n reasoning_content: z.array(deepseekChatLogprobSchema).nullish(),\n })\n .nullish();\n}\n\nlet logprobsSchema:\n | ReturnType<typeof createDeepseekChatLogprobsSchema>\n | undefined;\n\nfunction getDeepseekChatLogprobsSchema() {\n return (logprobsSchema ??= createDeepseekChatLogprobsSchema());\n}\n\nexport type DeepSeekChatLogprob = NonNullable<\n NonNullable<\n z.infer<ReturnType<typeof getDeepseekChatLogprobsSchema>>\n >['content']\n>[number];\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const deepseekChatResponseSchema = lazySchema(() =>\n zodSchema(\n z.object({\n id: z.string().nullish(),\n created: z.number().nullish(),\n model: z.string().nullish(),\n object: z.literal('chat.completion').nullish(),\n system_fingerprint: z.string().nullish(),\n choices: z.array(\n z.object({\n index: z.number().nullish(),\n message: z.object({\n role: z.literal('assistant').nullish(),\n content: z.string().nullish(),\n reasoning_content: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n id: z.string().nullish(),\n type: z.literal('function').nullish(),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n }),\n )\n .nullish(),\n }),\n logprobs: getDeepseekChatLogprobsSchema(),\n finish_reason: z.string().nullish(),\n }),\n ),\n usage: getTokenUsageSchema(),\n }),\n ),\n);\n\n// limited version of the schema, focussed on what is needed for the implementation\n// this approach limits breakages when the API changes and increases efficiency\nexport const deepseekChatChunkSchema = lazySchema(() =>\n zodSchema(\n z.union([\n z.object({\n id: z.string().nullish(),\n created: z.number().nullish(),\n model: z.string().nullish(),\n object: z.literal('chat.completion.chunk').nullish(),\n system_fingerprint: z.string().nullish(),\n choices: z.array(\n z.object({\n index: z.number().nullish(),\n delta: z\n .object({\n role: z.enum(['assistant']).nullish(),\n content: z.string().nullish(),\n reasoning_content: z.string().nullish(),\n tool_calls: z\n .array(\n z.object({\n index: z.number(),\n id: z.string().nullish(),\n type: z.literal('function').nullish(),\n function: z.object({\n name: z.string().nullish(),\n arguments: z.string().nullish(),\n }),\n }),\n )\n .nullish(),\n })\n .nullish(),\n logprobs: getDeepseekChatLogprobsSchema(),\n finish_reason: z.string().nullish(),\n }),\n ),\n usage: getTokenUsageSchema(),\n }),\n getDeepSeekErrorSchema(),\n ]),\n ),\n);\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport type {\n DeepSeekFunctionTool,\n DeepSeekToolChoice,\n} from './deepseek-chat-api-types';\n\nexport function prepareTools({\n tools,\n toolChoice,\n supportsStrictToolCalls,\n}: {\n tools: LanguageModelV4CallOptions['tools'];\n toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n supportsStrictToolCalls?: boolean;\n}): {\n tools: undefined | Array<DeepSeekFunctionTool>;\n toolChoice: DeepSeekToolChoice;\n toolWarnings: SharedV4Warning[];\n} {\n // when the tools array is empty, change it to undefined to prevent errors:\n tools = tools?.length ? tools : undefined;\n\n const toolWarnings: SharedV4Warning[] = [];\n\n if (tools == null) {\n return { tools: undefined, toolChoice: undefined, toolWarnings };\n }\n\n const functionTools = tools.filter(tool => tool.type === 'function');\n const hasStrictTool = functionTools.some(tool => tool.strict === true);\n\n if (hasStrictTool && supportsStrictToolCalls === false) {\n throw new UnsupportedFunctionalityError({\n functionality: 'DeepSeek strict tool calls',\n message:\n 'DeepSeek strict tool calls require a beta base URL ending in `/beta`.',\n });\n }\n\n if (\n hasStrictTool &&\n supportsStrictToolCalls === true &&\n functionTools.some(tool => tool.strict !== true)\n ) {\n throw new UnsupportedFunctionalityError({\n functionality: 'mixed DeepSeek strict and non-strict tool calls',\n message:\n 'DeepSeek strict mode requires every function tool in the request to set `strict: true`.',\n });\n }\n\n const deepseekTools: Array<DeepSeekFunctionTool> = [];\n\n for (const tool of tools) {\n if (tool.type === 'provider') {\n toolWarnings.push({\n type: 'unsupported',\n feature: `provider-defined tool ${tool.id}`,\n });\n } else {\n deepseekTools.push({\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n ...(tool.strict != null ? { strict: tool.strict } : {}),\n },\n });\n }\n }\n\n if (toolChoice == null) {\n return { tools: deepseekTools, toolChoice: undefined, toolWarnings };\n }\n\n const type = toolChoice?.type;\n\n switch (type) {\n case 'auto':\n case 'none':\n case 'required':\n return { tools: deepseekTools, toolChoice: type, toolWarnings };\n case 'tool':\n return {\n tools: deepseekTools,\n toolChoice: {\n type: 'function',\n function: { name: toolChoice.toolName },\n },\n toolWarnings,\n };\n default: {\n return {\n tools: deepseekTools,\n toolChoice: undefined,\n toolWarnings: [\n ...toolWarnings,\n {\n type: 'unsupported',\n feature: `tool choice type: ${type}`,\n },\n ],\n };\n }\n }\n}\n","import type { LanguageModelV4FinishReason } from '@ai-sdk/provider';\n\nexport function mapDeepSeekFinishReason(\n finishReason: string | null | undefined,\n): LanguageModelV4FinishReason['unified'] {\n switch (finishReason) {\n case 'stop':\n return 'stop';\n case 'length':\n return 'length';\n case 'content_filter':\n return 'content-filter';\n case 'tool_calls':\n return 'tool-calls';\n case 'insufficient_system_resource':\n return 'error';\n default:\n return 'other';\n }\n}\n","import {\n InvalidResponseDataError,\n type APICallError,\n type LanguageModelV4,\n type LanguageModelV4CallOptions,\n type LanguageModelV4Content,\n type LanguageModelV4FinishReason,\n type LanguageModelV4GenerateResult,\n type LanguageModelV4StreamPart,\n type LanguageModelV4StreamResult,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n type Resolvable,\n resolve,\n combineHeaders,\n createEventSourceResponseHandler,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n createProviderStreamError,\n generateId,\n isCustomReasoning,\n mapReasoningToProviderEffort,\n parseProviderOptions,\n postJsonToApi,\n serializeModelOptions,\n StreamingToolCallTracker,\n WORKFLOW_SERIALIZE,\n WORKFLOW_DESERIALIZE,\n type FetchFunction,\n type InferSchema,\n type ParseResult,\n type ResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { convertToDeepSeekChatMessages } from './convert-to-deepseek-chat-messages';\nimport { convertDeepSeekUsage } from './convert-to-deepseek-usage';\nimport {\n deepseekChatChunkSchema,\n deepseekChatResponseSchema,\n deepSeekErrorSchema,\n type DeepSeekChatLogprob,\n type DeepSeekChatTokenUsage,\n} from './deepseek-chat-api-types';\nimport {\n deepseekLanguageModelChatOptions,\n type DeepSeekChatModelId,\n} from './deepseek-chat-language-model-options';\nimport { prepareTools } from './deepseek-prepare-tools';\nimport { getResponseMetadata } from './get-response-metadata';\nimport { isDeepSeekV4Model } from './is-deepseek-v4-model';\nimport { mapDeepSeekFinishReason } from './map-deepseek-finish-reason';\n\nexport type DeepSeekChatConfig = {\n provider: string;\n headers?: Resolvable<Record<string, string | undefined>>;\n url: (options: { modelId: string; path: string }) => string;\n fetch?: FetchFunction;\n supportsAssistantPrefixCompletion?: boolean;\n supportsStrictToolCalls?: boolean;\n supportsPenaltySampling?: boolean;\n supportsThinking?: boolean;\n supportsStructuredOutputs?: boolean;\n};\n\nfunction createDeepSeekStreamError(\n error: {\n message: string;\n type?: string | null;\n code?: string | number | null;\n },\n data: unknown,\n) {\n const metadata = getDeepSeekStreamErrorMetadata(error);\n\n return createProviderStreamError({\n message: error.message,\n type: error.type ?? undefined,\n code: error.code ?? undefined,\n ...metadata,\n data,\n });\n}\n\nfunction getDeepSeekStreamErrorMetadata(error: {\n type?: string | null;\n code?: string | number | null;\n}): {\n statusCode?: number;\n isRetryable?: boolean;\n} {\n if (\n error.code === 'insufficient_quota' ||\n error.type === 'insufficient_quota'\n ) {\n return { statusCode: 429, isRetryable: false };\n }\n\n const explicitStatusCode = getHttpStatusCode(error.code);\n if (explicitStatusCode != null) {\n return {\n statusCode: explicitStatusCode,\n isRetryable: isRetryableStatusCode(explicitStatusCode),\n };\n }\n\n for (const discriminator of [error.code, error.type]) {\n switch (discriminator) {\n case 'rate_limit_exceeded':\n case 'rate_limit_error':\n return { statusCode: 429, isRetryable: true };\n case 'server_error':\n case 'api_error':\n case 'internal_server_error':\n return { statusCode: 500, isRetryable: true };\n case 'overloaded_error':\n case 'service_unavailable':\n return { statusCode: 503, isRetryable: true };\n case 'timeout':\n case 'timeout_error':\n return { statusCode: 504, isRetryable: true };\n case 'authentication_error':\n case 'invalid_api_key':\n return { statusCode: 401, isRetryable: false };\n case 'permission_error':\n return { statusCode: 403, isRetryable: false };\n case 'not_found_error':\n case 'model_not_found':\n return { statusCode: 404, isRetryable: false };\n case 'bad_request':\n case 'context_length_exceeded':\n case 'invalid_request_error':\n return { statusCode: 400, isRetryable: false };\n }\n }\n\n return {};\n}\n\nfunction getHttpStatusCode(value: unknown): number | undefined {\n const statusCode =\n typeof value === 'string' && /^\\d{3}$/.test(value) ? Number(value) : value;\n\n return typeof statusCode === 'number' &&\n Number.isInteger(statusCode) &&\n statusCode >= 400 &&\n statusCode <= 599\n ? statusCode\n : undefined;\n}\n\nfunction isRetryableStatusCode(statusCode: number): boolean {\n return (\n statusCode === 408 ||\n statusCode === 409 ||\n statusCode === 429 ||\n statusCode >= 500\n );\n}\n\nfunction mapDeepSeekProviderReasoningEffort({\n reasoningEffort,\n warnings,\n}: {\n reasoningEffort: 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n warnings: SharedV4Warning[];\n}): 'low' | 'high' | 'max' {\n const mapped =\n reasoningEffort === 'medium'\n ? 'high'\n : reasoningEffort === 'xhigh'\n ? 'max'\n : reasoningEffort;\n\n if (mapped !== reasoningEffort) {\n warnings.push({\n type: 'compatibility',\n feature: 'reasoningEffort',\n details: `reasoningEffort \"${reasoningEffort}\" is not a canonical DeepSeek value. mapped to \"${mapped}\".`,\n });\n }\n\n return mapped;\n}\n\nexport class DeepSeekChatLanguageModel implements LanguageModelV4 {\n readonly specificationVersion = 'v4';\n\n readonly modelId: DeepSeekChatModelId;\n\n readonly supportedUrls = {\n 'image/*': [/^https?:\\/\\/.*$/],\n };\n\n private readonly config: DeepSeekChatConfig;\n private readonly failedResponseHandler: ResponseHandler<APICallError>;\n\n static [WORKFLOW_SERIALIZE](model: DeepSeekChatLanguageModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: DeepSeekChatModelId;\n config: DeepSeekChatConfig;\n }) {\n return new DeepSeekChatLanguageModel(options.modelId, options.config);\n }\n\n constructor(modelId: DeepSeekChatModelId, config: DeepSeekChatConfig) {\n this.modelId = modelId;\n this.config = config;\n\n this.failedResponseHandler = createJsonErrorResponseHandler({\n errorSchema: deepSeekErrorSchema,\n errorToMessage: (error: InferSchema<typeof deepSeekErrorSchema>) =>\n error.error.message,\n });\n }\n\n get provider(): string {\n return this.config.provider;\n }\n\n private get providerOptionsName(): string {\n return this.config.provider.split('.')[0].trim();\n }\n\n private async getArgs({\n prompt,\n maxOutputTokens,\n temperature,\n topP,\n topK,\n frequencyPenalty,\n presencePenalty,\n reasoning,\n providerOptions,\n stopSequences,\n responseFormat,\n seed,\n toolChoice,\n tools,\n }: LanguageModelV4CallOptions) {\n const deepseekOptions =\n (await parseProviderOptions({\n provider: this.providerOptionsName,\n providerOptions,\n schema: deepseekLanguageModelChatOptions,\n })) ?? {};\n\n const supportsStructuredOutputs =\n this.config.supportsStructuredOutputs === true;\n const supportsPenaltySampling =\n this.config.supportsPenaltySampling === true;\n\n const { messages, warnings } = await convertToDeepSeekChatMessages({\n prompt,\n responseFormat,\n modelId: this.modelId,\n providerOptionsName: this.providerOptionsName,\n supportsAssistantPrefixCompletion:\n this.config.supportsAssistantPrefixCompletion,\n supportsStructuredOutputs,\n });\n const allWarnings: SharedV4Warning[] = [...warnings];\n\n if (topK != null) {\n allWarnings.push({ type: 'unsupported', feature: 'topK' });\n }\n\n if (seed != null) {\n allWarnings.push({ type: 'unsupported', feature: 'seed' });\n }\n\n if (!supportsPenaltySampling && frequencyPenalty != null) {\n allWarnings.push({\n type: 'deprecated',\n setting: 'frequencyPenalty',\n message:\n 'frequencyPenalty is deprecated by DeepSeek and has been omitted. Remove frequencyPenalty from the request.',\n });\n }\n\n if (!supportsPenaltySampling && presencePenalty != null) {\n allWarnings.push({\n type: 'deprecated',\n setting: 'presencePenalty',\n message:\n 'presencePenalty is deprecated by DeepSeek and has been omitted. Remove presencePenalty from the request.',\n });\n }\n\n const {\n tools: deepseekTools,\n toolChoice: deepseekToolChoices,\n toolWarnings,\n } = prepareTools({\n tools,\n toolChoice,\n supportsStrictToolCalls: this.config.supportsStrictToolCalls,\n });\n\n const thinkingType = deepseekOptions.thinking?.type;\n if (thinkingType === 'adaptive') {\n allWarnings.push({\n type: 'compatibility',\n feature: 'thinking.type',\n details:\n 'thinking.type \"adaptive\" is not a canonical DeepSeek value. mapped to \"enabled\".',\n });\n }\n\n const thinking =\n this.config.supportsThinking === false\n ? undefined\n : thinkingType != null\n ? { type: thinkingType === 'adaptive' ? 'enabled' : thinkingType }\n : isCustomReasoning(reasoning)\n ? { type: reasoning === 'none' ? 'disabled' : 'enabled' }\n : undefined;\n\n const isThinkingEnabled =\n this.config.supportsThinking !== false &&\n thinking?.type !== 'disabled' &&\n (thinking != null ||\n this.modelId === 'deepseek-reasoner' ||\n isDeepSeekV4Model(this.modelId));\n\n if (isThinkingEnabled && temperature != null) {\n allWarnings.push({\n type: 'unsupported',\n feature: 'temperature',\n details:\n \"temperature has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use temperature.\",\n });\n }\n\n if (isThinkingEnabled && topP != null) {\n allWarnings.push({\n type: 'unsupported',\n feature: 'topP',\n details:\n \"topP has no effect when DeepSeek thinking is enabled. Set providerOptions.deepseek.thinking.type to 'disabled' to use topP.\",\n });\n }\n\n const reasoningEffort =\n deepseekOptions.reasoningEffort != null\n ? mapDeepSeekProviderReasoningEffort({\n reasoningEffort: deepseekOptions.reasoningEffort,\n warnings: allWarnings,\n })\n : isCustomReasoning(reasoning) && reasoning !== 'none'\n ? mapReasoningToProviderEffort({\n reasoning,\n effortMap: { low: 'low', high: 'high', max: 'max' },\n warnings: allWarnings,\n })\n : undefined;\n\n return {\n args: {\n model: this.modelId,\n ...((deepseekOptions.logprobs === true ||\n deepseekOptions.topLogprobs != null) && { logprobs: true }),\n ...(deepseekOptions.topLogprobs != null && {\n top_logprobs: deepseekOptions.topLogprobs,\n }),\n max_tokens: maxOutputTokens,\n temperature: isThinkingEnabled ? undefined : temperature,\n top_p: isThinkingEnabled ? undefined : topP,\n frequency_penalty: supportsPenaltySampling\n ? frequencyPenalty\n : undefined,\n presence_penalty: supportsPenaltySampling ? presencePenalty : undefined,\n response_format:\n responseFormat?.type === 'json'\n ? supportsStructuredOutputs && responseFormat.schema != null\n ? {\n type: 'json_schema',\n json_schema: {\n schema: responseFormat.schema,\n strict: deepseekOptions.strictJsonSchema ?? true,\n name: responseFormat.name ?? 'response',\n description: responseFormat.description,\n },\n }\n : { type: 'json_object' }\n : undefined,\n stop: stopSequences,\n messages,\n tools: deepseekTools,\n tool_choice: deepseekToolChoices,\n thinking,\n ...(deepseekOptions.userId != null && {\n user_id: deepseekOptions.userId,\n }),\n ...(thinking?.type !== 'disabled' &&\n reasoningEffort != null && {\n reasoning_effort: reasoningEffort,\n }),\n },\n warnings: [...allWarnings, ...toolWarnings],\n };\n }\n\n async doGenerate(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4GenerateResult> {\n const { args, warnings } = await this.getArgs({ ...options });\n\n const {\n responseHeaders,\n value: responseBody,\n rawValue: rawResponse,\n } = await postJsonToApi({\n url: this.config.url({\n path: '/chat/completions',\n modelId: this.modelId,\n }),\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n body: args,\n failedResponseHandler: this.failedResponseHandler,\n successfulResponseHandler: createJsonResponseHandler(\n deepseekChatResponseSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n const choice = responseBody.choices[0];\n if (choice == null) {\n throw new InvalidResponseDataError({\n data: rawResponse,\n message: 'Response did not contain any choices.',\n });\n }\n\n const content: Array<LanguageModelV4Content> = [];\n\n // reasoning content (before text):\n const reasoning = choice.message.reasoning_content;\n if (reasoning != null && reasoning.length > 0) {\n content.push({\n type: 'reasoning',\n text: reasoning,\n });\n }\n\n // tool calls:\n if (choice.message.tool_calls != null) {\n for (const toolCall of choice.message.tool_calls) {\n content.push({\n type: 'tool-call',\n toolCallId: toolCall.id || generateId(),\n toolName: toolCall.function.name,\n input: toolCall.function.arguments!,\n });\n }\n }\n\n // text content:\n const text = choice.message.content;\n if (text != null && text.length > 0) {\n content.push({ type: 'text', text });\n }\n\n return {\n content,\n finishReason: {\n unified: mapDeepSeekFinishReason(choice.finish_reason),\n raw: choice.finish_reason ?? undefined,\n },\n usage: convertDeepSeekUsage(responseBody.usage),\n providerMetadata: {\n [this.providerOptionsName]: {\n promptCacheHitTokens: responseBody.usage?.prompt_cache_hit_tokens,\n promptCacheMissTokens: responseBody.usage?.prompt_cache_miss_tokens,\n ...(responseBody.object != null && {\n responseObject: responseBody.object,\n }),\n ...(choice.index != null && { choiceIndex: choice.index }),\n ...(choice.message.role != null && {\n messageRole: choice.message.role,\n }),\n ...(choice.message.tool_calls != null && {\n toolCallTypes: choice.message.tool_calls\n .map(toolCall => toolCall.type)\n .filter(type => type != null),\n }),\n ...(choice.logprobs != null && { logprobs: choice.logprobs }),\n ...(responseBody.system_fingerprint != null && {\n systemFingerprint: responseBody.system_fingerprint,\n }),\n },\n },\n request: { body: args },\n response: {\n ...getResponseMetadata(responseBody),\n headers: responseHeaders,\n body: rawResponse,\n },\n warnings,\n };\n }\n\n async doStream(\n options: LanguageModelV4CallOptions,\n ): Promise<LanguageModelV4StreamResult> {\n const { args, warnings } = await this.getArgs({ ...options });\n\n const body = {\n ...args,\n stream: true,\n stream_options: { include_usage: true },\n };\n\n const { responseHeaders, value: response } = await postJsonToApi({\n url: this.config.url({\n path: '/chat/completions',\n modelId: this.modelId,\n }),\n headers: combineHeaders(\n await resolve(this.config.headers),\n options.headers,\n ),\n body,\n failedResponseHandler: this.failedResponseHandler,\n successfulResponseHandler: createEventSourceResponseHandler(\n deepseekChatChunkSchema,\n ),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n let toolCallTracker: StreamingToolCallTracker;\n\n // A clean end without the provider's completion signal is interrupted.\n let finishReason: LanguageModelV4FinishReason = {\n unified: 'interrupted',\n raw: undefined,\n };\n let usage: DeepSeekChatTokenUsage | undefined = undefined;\n let systemFingerprint: string | undefined = undefined;\n let isFirstChunk = true;\n const providerOptionsName = this.providerOptionsName;\n let isActiveReasoning = false;\n let isActiveText = false;\n let responseObject: 'chat.completion.chunk' | undefined;\n let choiceIndex: number | undefined;\n let messageRole: 'assistant' | undefined;\n const toolCallTypes = new Map<number, 'function'>();\n const contentLogprobs: DeepSeekChatLogprob[] = [];\n const reasoningLogprobs: DeepSeekChatLogprob[] = [];\n\n return {\n stream: response.pipeThrough(\n new TransformStream<\n ParseResult<InferSchema<typeof deepseekChatChunkSchema>>,\n LanguageModelV4StreamPart\n >({\n start(controller) {\n toolCallTracker = new StreamingToolCallTracker(controller, {\n generateId,\n });\n controller.enqueue({ type: 'stream-start', warnings });\n },\n\n transform(chunk, controller) {\n // Emit raw chunk if requested (before anything else)\n if (options.includeRawChunks) {\n controller.enqueue({ type: 'raw', rawValue: chunk.rawValue });\n }\n\n // handle failed chunk parsing / validation:\n if (!chunk.success) {\n finishReason = { unified: 'error', raw: undefined };\n controller.enqueue({ type: 'error', error: chunk.error });\n return;\n }\n const value = chunk.value;\n\n // handle error chunks:\n if ('error' in value) {\n finishReason = { unified: 'error', raw: undefined };\n controller.enqueue({\n type: 'error',\n error: createDeepSeekStreamError(value.error, value),\n });\n return;\n }\n\n if (isFirstChunk) {\n isFirstChunk = false;\n\n controller.enqueue({\n type: 'response-metadata',\n ...getResponseMetadata(value),\n });\n }\n\n if (value.usage != null) {\n usage = value.usage;\n }\n\n if (value.object != null) {\n responseObject = value.object;\n }\n\n // The fingerprint is repeated on stream chunks; keep the latest\n // non-null value in case it changes during the response.\n if (value.system_fingerprint != null) {\n systemFingerprint = value.system_fingerprint;\n }\n\n const choice = value.choices[0];\n\n if (choice?.index != null) {\n choiceIndex = choice.index;\n }\n\n if (choice?.finish_reason != null) {\n finishReason = {\n unified: mapDeepSeekFinishReason(choice.finish_reason),\n raw: choice.finish_reason,\n };\n }\n\n if (choice?.logprobs?.content != null) {\n contentLogprobs.push(...choice.logprobs.content);\n }\n\n if (choice?.logprobs?.reasoning_content != null) {\n reasoningLogprobs.push(...choice.logprobs.reasoning_content);\n }\n\n if (choice?.delta == null) {\n return;\n }\n\n const delta = choice.delta;\n\n if (delta.role != null) {\n messageRole = delta.role;\n }\n\n // enqueue reasoning before text deltas:\n const reasoningContent = delta.reasoning_content;\n if (reasoningContent) {\n if (!isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-start',\n id: 'reasoning-0',\n });\n isActiveReasoning = true;\n }\n\n controller.enqueue({\n type: 'reasoning-delta',\n id: 'reasoning-0',\n delta: reasoningContent,\n });\n }\n\n if (delta.content) {\n if (!isActiveText) {\n controller.enqueue({ type: 'text-start', id: 'txt-0' });\n isActiveText = true;\n }\n\n // end reasoning when text starts:\n if (isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-end',\n id: 'reasoning-0',\n });\n isActiveReasoning = false;\n }\n\n controller.enqueue({\n type: 'text-delta',\n id: 'txt-0',\n delta: delta.content,\n });\n }\n\n if (delta.tool_calls != null && delta.tool_calls.length > 0) {\n // end reasoning when tool calls start:\n if (isActiveReasoning) {\n controller.enqueue({\n type: 'reasoning-end',\n id: 'reasoning-0',\n });\n isActiveReasoning = false;\n }\n\n for (const toolCallDelta of delta.tool_calls) {\n if (toolCallDelta.type != null) {\n toolCallTypes.set(toolCallDelta.index, toolCallDelta.type);\n }\n toolCallTracker.processDelta(toolCallDelta);\n }\n }\n },\n\n flush(controller) {\n if (isActiveReasoning) {\n controller.enqueue({ type: 'reasoning-end', id: 'reasoning-0' });\n }\n\n if (isActiveText) {\n controller.enqueue({ type: 'text-end', id: 'txt-0' });\n }\n\n toolCallTracker.flush();\n\n controller.enqueue({\n type: 'finish',\n finishReason,\n usage: convertDeepSeekUsage(usage),\n providerMetadata: {\n [providerOptionsName]: {\n promptCacheHitTokens:\n usage?.prompt_cache_hit_tokens ?? undefined,\n promptCacheMissTokens:\n usage?.prompt_cache_miss_tokens ?? undefined,\n ...(responseObject != null && { responseObject }),\n ...(choiceIndex != null && { choiceIndex }),\n ...(messageRole != null && { messageRole }),\n ...(toolCallTypes.size > 0 && {\n toolCallTypes: [...toolCallTypes.entries()]\n .sort(([left], [right]) => left - right)\n .map(([, type]) => type),\n }),\n ...((contentLogprobs.length > 0 ||\n reasoningLogprobs.length > 0) && {\n logprobs: {\n ...(contentLogprobs.length > 0 && {\n content: contentLogprobs,\n }),\n ...(reasoningLogprobs.length > 0 && {\n reasoning_content: reasoningLogprobs,\n }),\n },\n }),\n ...(systemFingerprint != null && { systemFingerprint }),\n },\n },\n });\n },\n }),\n ),\n request: { body },\n response: { headers: responseHeaders },\n };\n }\n}\n","import {\n getDeepseekAssistantMessageOptionsSchema,\n getDeepseekChatOptionsSchema,\n getDeepseekMessageOptionsSchema,\n} from '../chat/deepseek-chat-language-model-options';\n\nexport * from '../chat/deepseek-chat-language-model';\nexport type {\n DeepSeekAssistantMessageProviderOptions,\n DeepSeekChatModelId,\n DeepSeekLanguageModelChatOptions,\n DeepSeekMessageProviderOptions,\n} from '../chat/deepseek-chat-language-model-options';\n\n// Preserve the Zod object exports for consumers of the internal entry point.\nexport const deepseekLanguageModelChatOptions = getDeepseekChatOptionsSchema();\nexport const deepseekMessageProviderOptions = getDeepseekMessageOptionsSchema();\nexport const deepseekAssistantMessageProviderOptions =\n getDeepseekAssistantMessageOptionsSchema();\n"],"mappings":";;;;AAiBA,SAAS,kCAAkC;CACzC,OAAO,EAAE,OAAO;;;;EAId,UAAU,EAAE,QAAQ,CAAC,CAAC,SAAS;;;;;;EAO/B,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS;;;;;;;;EAStD,QAAQ,EACL,OAAO,CAAC,CACR,MAAM,oBAAoB,sCAAsC,CAAC,CACjE,IAAI,KAAK,4CAA4C,CAAC,CACtD,SAAS;;;;EAKZ,UAAU,EACP,OAAO,EAIN,MAAM,EAAE,KAAK;GAAC;GAAY;GAAW;EAAU,CAAC,CAAC,CAAC,SAAS,EAC7D,CAAC,CAAC,CACD,SAAS;;;;EAQZ,iBAAiB,EACd,KAAK;GAAC;GAAO;GAAU;GAAQ;GAAS;EAAK,CAAC,CAAC,CAC/C,SAAS;;;;;;EAOZ,kBAAkB,EAAE,QAAQ,CAAC,CAAC,SAAS;CACzC,CAAC;AACH;AAEA,IAAI;AAIJ,SAAgB,+BAA+B;CAC7C,OAAQ,sBAAsB,gCAAgC;AAChE;AAEA,MAAaA,qCAAmC,iBAC9C,UAAU,6BAA6B,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AS,KAC5B,kBAAkB,SAAS,MAAM,EACjC,UAAU;QACR,GAAI,gBAAgB,SAAS,KAAK,EAChC,SAAS,gBACX;QACA,GAAI,kBAAkB,SAAS,KAAK,EAClC,mBAAmB,kBACrB;OACF,EACF;OACA,GAAI,qBAAqB,QAAQ,EAAE,kBAAkB;MACvD,EACF;KACF,CAAC;IACH;GACF,CAAC,CACH;GACA,SAAS,EAAE,KAAK;GAChB,UAAU,EAAE,SAAS,gBAAgB;EACvC;CACF;AACF;;;AC1uBA,MAAa,mCAAmC,6BAA6B;AAC7E,MAAa,iCAAiC,gCAAgC;AAC9E,MAAa,0CACX,yCAAyC"}
|
package/docs/30-deepseek.mdx
CHANGED
|
@@ -84,11 +84,14 @@ You can use the following optional settings to customize the DeepSeek provider i
|
|
|
84
84
|
Use a different URL prefix for API calls.
|
|
85
85
|
The default prefix is `https://api.deepseek.com`.
|
|
86
86
|
|
|
87
|
-
- **apiKey**
|
|
87
|
+
- **apiKey** _string | PromiseLike<string> | (() => string | PromiseLike<string>)_
|
|
88
88
|
|
|
89
89
|
API key that is being sent using the `Authorization` header. It defaults to
|
|
90
90
|
the `DEEPSEEK_API_KEY` environment variable.
|
|
91
91
|
|
|
92
|
+
A function is called before each request and may return a promise. Use it to
|
|
93
|
+
supply refreshed credentials; a promise value resolves to the same key each time.
|
|
94
|
+
|
|
92
95
|
- **headers** _Record<string,string>_
|
|
93
96
|
|
|
94
97
|
Custom headers to include in the requests.
|
|
@@ -153,11 +156,7 @@ The following optional provider options are available for DeepSeek models:
|
|
|
153
156
|
|
|
154
157
|
- `reasoningEffort` _'low' | 'high' | 'max'_
|
|
155
158
|
|
|
156
|
-
Optional. Controls thinking strength for DeepSeek V4 reasoning models.
|
|
157
|
-
using the top-level `reasoning` setting, `minimal` is sent as `low`,
|
|
158
|
-
`medium` is sent as `high`, `xhigh` is sent as `max`, and `max` is sent
|
|
159
|
-
directly. A compatibility warning is returned whenever the requested value
|
|
160
|
-
is mapped.
|
|
159
|
+
Optional. Controls thinking strength for DeepSeek V4 reasoning models.
|
|
161
160
|
|
|
162
161
|
For backwards compatibility, legacy provider options supplied at runtime are
|
|
163
162
|
also mapped to documented values: `thinking.type: 'adaptive'` becomes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/deepseek",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.77",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -35,8 +35,8 @@
|
|
|
35
35
|
}
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@ai-sdk/provider": "4.0.
|
|
39
|
-
"@ai-sdk/provider-utils": "5.0.
|
|
38
|
+
"@ai-sdk/provider": "4.0.35",
|
|
39
|
+
"@ai-sdk/provider-utils": "5.0.72"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@ai-sdk/test-server": "2.0.4",
|
|
@@ -11,6 +11,8 @@ import {
|
|
|
11
11
|
type SharedV4Warning,
|
|
12
12
|
} from '@ai-sdk/provider';
|
|
13
13
|
import {
|
|
14
|
+
type Resolvable,
|
|
15
|
+
resolve,
|
|
14
16
|
combineHeaders,
|
|
15
17
|
createEventSourceResponseHandler,
|
|
16
18
|
createJsonErrorResponseHandler,
|
|
@@ -50,7 +52,7 @@ import { mapDeepSeekFinishReason } from './map-deepseek-finish-reason';
|
|
|
50
52
|
|
|
51
53
|
export type DeepSeekChatConfig = {
|
|
52
54
|
provider: string;
|
|
53
|
-
headers?:
|
|
55
|
+
headers?: Resolvable<Record<string, string | undefined>>;
|
|
54
56
|
url: (options: { modelId: string; path: string }) => string;
|
|
55
57
|
fetch?: FetchFunction;
|
|
56
58
|
supportsAssistantPrefixCompletion?: boolean;
|
|
@@ -353,14 +355,7 @@ export class DeepSeekChatLanguageModel implements LanguageModelV4 {
|
|
|
353
355
|
: isCustomReasoning(reasoning) && reasoning !== 'none'
|
|
354
356
|
? mapReasoningToProviderEffort({
|
|
355
357
|
reasoning,
|
|
356
|
-
effortMap: {
|
|
357
|
-
minimal: 'low',
|
|
358
|
-
low: 'low',
|
|
359
|
-
medium: 'high',
|
|
360
|
-
high: 'high',
|
|
361
|
-
xhigh: 'max',
|
|
362
|
-
max: 'max',
|
|
363
|
-
},
|
|
358
|
+
effortMap: { low: 'low', high: 'high', max: 'max' },
|
|
364
359
|
warnings: allWarnings,
|
|
365
360
|
})
|
|
366
361
|
: undefined;
|
|
@@ -425,7 +420,10 @@ export class DeepSeekChatLanguageModel implements LanguageModelV4 {
|
|
|
425
420
|
path: '/chat/completions',
|
|
426
421
|
modelId: this.modelId,
|
|
427
422
|
}),
|
|
428
|
-
headers: combineHeaders(
|
|
423
|
+
headers: combineHeaders(
|
|
424
|
+
await resolve(this.config.headers),
|
|
425
|
+
options.headers,
|
|
426
|
+
),
|
|
429
427
|
body: args,
|
|
430
428
|
failedResponseHandler: this.failedResponseHandler,
|
|
431
429
|
successfulResponseHandler: createJsonResponseHandler(
|
|
@@ -527,7 +525,10 @@ export class DeepSeekChatLanguageModel implements LanguageModelV4 {
|
|
|
527
525
|
path: '/chat/completions',
|
|
528
526
|
modelId: this.modelId,
|
|
529
527
|
}),
|
|
530
|
-
headers: combineHeaders(
|
|
528
|
+
headers: combineHeaders(
|
|
529
|
+
await resolve(this.config.headers),
|
|
530
|
+
options.headers,
|
|
531
|
+
),
|
|
531
532
|
body,
|
|
532
533
|
failedResponseHandler: this.failedResponseHandler,
|
|
533
534
|
successfulResponseHandler: createEventSourceResponseHandler(
|
package/src/deepseek-provider.ts
CHANGED
|
@@ -5,6 +5,8 @@ import {
|
|
|
5
5
|
type ProviderV4,
|
|
6
6
|
} from '@ai-sdk/provider';
|
|
7
7
|
import {
|
|
8
|
+
type Resolvable,
|
|
9
|
+
resolveWith,
|
|
8
10
|
loadApiKey,
|
|
9
11
|
withoutTrailingSlash,
|
|
10
12
|
withUserAgentSuffix,
|
|
@@ -18,8 +20,9 @@ import { VERSION } from './version';
|
|
|
18
20
|
export interface DeepSeekProviderSettings {
|
|
19
21
|
/**
|
|
20
22
|
* DeepSeek API key.
|
|
23
|
+
* A function is called before each request and may return a promise.
|
|
21
24
|
*/
|
|
22
|
-
apiKey?: string
|
|
25
|
+
apiKey?: Resolvable<string>;
|
|
23
26
|
|
|
24
27
|
/**
|
|
25
28
|
* Base URL for the API calls.
|
|
@@ -73,16 +76,18 @@ export function createDeepSeek(
|
|
|
73
76
|
'https://api.deepseek.com';
|
|
74
77
|
|
|
75
78
|
const getHeaders = () =>
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
79
|
+
resolveWith(options.apiKey, apiKey =>
|
|
80
|
+
withUserAgentSuffix(
|
|
81
|
+
{
|
|
82
|
+
Authorization: `Bearer ${loadApiKey({
|
|
83
|
+
apiKey,
|
|
84
|
+
environmentVariableName: 'DEEPSEEK_API_KEY',
|
|
85
|
+
description: 'DeepSeek API key',
|
|
86
|
+
})}`,
|
|
87
|
+
...options.headers,
|
|
88
|
+
},
|
|
89
|
+
`ai-sdk-deepseek/${VERSION}`,
|
|
90
|
+
),
|
|
86
91
|
);
|
|
87
92
|
|
|
88
93
|
const createLanguageModel = (modelId: DeepSeekChatModelId) => {
|
|
@@ -5,6 +5,8 @@ import {
|
|
|
5
5
|
type FilesV4UploadFileResult,
|
|
6
6
|
} from '@ai-sdk/provider';
|
|
7
7
|
import {
|
|
8
|
+
type Resolvable,
|
|
9
|
+
resolve,
|
|
8
10
|
combineHeaders,
|
|
9
11
|
convertInlineFileDataToUint8Array,
|
|
10
12
|
createJsonErrorResponseHandler,
|
|
@@ -25,7 +27,7 @@ import {
|
|
|
25
27
|
interface DeepSeekFilesConfig {
|
|
26
28
|
provider: string;
|
|
27
29
|
baseURL: string;
|
|
28
|
-
headers:
|
|
30
|
+
headers: Resolvable<Record<string, string | undefined>>;
|
|
29
31
|
fetch?: FetchFunction;
|
|
30
32
|
}
|
|
31
33
|
|
|
@@ -111,7 +113,7 @@ export class DeepSeekFiles implements FilesV4 {
|
|
|
111
113
|
|
|
112
114
|
const { value: response } = await postFormDataToApi({
|
|
113
115
|
url: `${this.config.baseURL}/files`,
|
|
114
|
-
headers: combineHeaders(this.config.headers
|
|
116
|
+
headers: combineHeaders(await resolve(this.config.headers), headers),
|
|
115
117
|
formData,
|
|
116
118
|
failedResponseHandler: deepSeekFailedResponseHandler,
|
|
117
119
|
successfulResponseHandler: createJsonResponseHandler(
|