@ai-sdk/openai-compatible 3.0.84 → 3.0.86
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 +36 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +111 -14
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +3 -1
- package/dist/internal/index.d.ts.map +1 -1
- package/dist/internal/index.js +9 -3
- package/dist/internal/index.js.map +1 -1
- package/docs/index.mdx +47 -0
- package/package.json +3 -3
- package/src/chat/convert-to-openai-compatible-chat-messages.ts +8 -0
- package/src/chat/map-openai-compatible-finish-reason.ts +5 -1
- package/src/chat/openai-compatible-chat-language-model.ts +72 -7
- package/src/embedding/openai-compatible-embedding-model.ts +9 -2
- package/src/image/openai-compatible-image-model.ts +3 -1
- package/src/openai-compatible-model-catalog.ts +143 -0
package/dist/internal/index.d.ts
CHANGED
|
@@ -95,7 +95,9 @@ export declare function convertOpenAICompatibleChatUsage(usage: {
|
|
|
95
95
|
} | undefined | null): LanguageModelV4Usage;
|
|
96
96
|
//#endregion
|
|
97
97
|
//#region src/chat/map-openai-compatible-finish-reason.d.ts
|
|
98
|
-
export declare function mapOpenAICompatibleFinishReason(finishReason: string | null | undefined
|
|
98
|
+
export declare function mapOpenAICompatibleFinishReason(finishReason: string | null | undefined, { hasRefusal }?: {
|
|
99
|
+
hasRefusal?: boolean;
|
|
100
|
+
}): LanguageModelV4FinishReason['unified'];
|
|
99
101
|
//#endregion
|
|
100
102
|
//#region src/chat/get-response-metadata.d.ts
|
|
101
103
|
export declare function getResponseMetadata({ id, model, created }: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/chat/openai-compatible-api-types.ts","../../src/chat/convert-to-openai-compatible-chat-messages.ts","../../src/chat/convert-openai-compatible-chat-usage.ts","../../src/chat/map-openai-compatible-finish-reason.ts","../../src/chat/get-response-metadata.ts","../../src/chat/openai-compatible-prepare-tools.ts","../../src/openai-compatible-error.ts","../../src/chat/openai-compatible-metadata-extractor.ts","../../src/chat/openai-compatible-chat-language-model.ts"],"mappings":";;;;KAEY,6BAA6B,MAAM;KAEnC,0BACR,gCACA,8BACA,mCACA;KAIC,WAAW,aAAa,eAE3B,YAAY,cAAc,IAAI;UAGf,sCAAsC;EACrD;EACA;;UAGe,oCAAoC,WAAW;EAC9D;EACA,kBAAkB,MAAM;;KAGd,8BACR,kCACA,mCACA,mCACA,wCACA;UAEa,wCAAwC;EACvD;EACA;;UAGe,yCAAyC;EACxD;EACA;IAAa;;;UAIE,yCAAyC;EACxD;EACA;IAAa;;;UAIE,8CAA8C;EAC7D;EACA;IAAe;IAAc;;;UAGd,wCAAwC;EACvD;EACA;IAAQ;IAAkB;;IAAwB;;;UAGnC,yCAAyC,WAAW;EACnE;EACA;EACA;EACA,aAAa,MAAM;;UAGJ,wCAAwC;EACvD;EACA;EACA;IACE;IACA;;;;;;EAMF;IACE;MACE;;;;UAKW,oCAAoC;EACnD;EACA,kBAAkB,MAAM;EACxB;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/chat/openai-compatible-api-types.ts","../../src/chat/convert-to-openai-compatible-chat-messages.ts","../../src/chat/convert-openai-compatible-chat-usage.ts","../../src/chat/map-openai-compatible-finish-reason.ts","../../src/chat/get-response-metadata.ts","../../src/chat/openai-compatible-prepare-tools.ts","../../src/openai-compatible-error.ts","../../src/chat/openai-compatible-metadata-extractor.ts","../../src/chat/openai-compatible-chat-language-model.ts"],"mappings":";;;;KAEY,6BAA6B,MAAM;KAEnC,0BACR,gCACA,8BACA,mCACA;KAIC,WAAW,aAAa,eAE3B,YAAY,cAAc,IAAI;UAGf,sCAAsC;EACrD;EACA;;UAGe,oCAAoC,WAAW;EAC9D;EACA,kBAAkB,MAAM;;KAGd,8BACR,kCACA,mCACA,mCACA,wCACA;UAEa,wCAAwC;EACvD;EACA;;UAG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package/dist/internal/index.js
CHANGED
|
@@ -29,7 +29,13 @@ function convertToOpenAICompatibleContentPart(part, provider) {
|
|
|
29
29
|
}) },
|
|
30
30
|
...partMetadata
|
|
31
31
|
};
|
|
32
|
-
case "text":
|
|
32
|
+
case "text":
|
|
33
|
+
if (getTopLevelMediaType(part.mediaType) === "text") return {
|
|
34
|
+
type: "text",
|
|
35
|
+
text: part.data.text,
|
|
36
|
+
...partMetadata
|
|
37
|
+
};
|
|
38
|
+
throw new UnsupportedFunctionalityError({ functionality: "text file parts" });
|
|
33
39
|
case "url":
|
|
34
40
|
case "data": {
|
|
35
41
|
const topLevel = getTopLevelMediaType(part.mediaType);
|
|
@@ -216,9 +222,9 @@ function convertOpenAICompatibleChatUsage(usage) {
|
|
|
216
222
|
}
|
|
217
223
|
//#endregion
|
|
218
224
|
//#region src/chat/map-openai-compatible-finish-reason.ts
|
|
219
|
-
function mapOpenAICompatibleFinishReason(finishReason) {
|
|
225
|
+
function mapOpenAICompatibleFinishReason(finishReason, { hasRefusal = false } = {}) {
|
|
220
226
|
switch (finishReason) {
|
|
221
|
-
case "stop": return "stop";
|
|
227
|
+
case "stop": return hasRefusal ? "content-filter" : "stop";
|
|
222
228
|
case "length": return "length";
|
|
223
229
|
case "content_filter": return "content-filter";
|
|
224
230
|
case "function_call":
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_exhaustiveCheck","_exhaustiveCheck"],"sources":["../../src/chat/convert-to-openai-compatible-chat-messages.ts","../../src/chat/convert-openai-compatible-chat-usage.ts","../../src/chat/map-openai-compatible-finish-reason.ts","../../src/chat/get-response-metadata.ts","../../src/chat/openai-compatible-prepare-tools.ts"],"sourcesContent":["import {\n UnsupportedFunctionalityError,\n type LanguageModelV4FilePart,\n type LanguageModelV4Prompt,\n type LanguageModelV4TextPart,\n type LanguageModelV4ToolResultOutput,\n type SharedV4ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n OpenAICompatibleChatPrompt,\n OpenAICompatibleContentPart,\n} from './openai-compatible-api-types';\nimport {\n secureJsonParse,\n stringifyWithBigIntAndCycles,\n convertBase64ToUint8Array,\n convertToBase64,\n getTopLevelMediaType,\n resolveFullMediaType,\n resolveProviderReference,\n} from '@ai-sdk/provider-utils';\n\nfunction getOpenAIMetadata(message: {\n providerOptions?: SharedV4ProviderMetadata;\n}) {\n return message?.providerOptions?.openaiCompatible ?? {};\n}\n\nfunction getAudioFormat(mediaType: string): 'wav' | 'mp3' | null {\n switch (mediaType) {\n case 'audio/wav':\n return 'wav';\n case 'audio/mp3':\n case 'audio/mpeg':\n return 'mp3';\n default:\n return null;\n }\n}\n\nfunction convertToOpenAICompatibleContentPart(\n part: LanguageModelV4TextPart | LanguageModelV4FilePart,\n provider: string,\n): OpenAICompatibleContentPart {\n const partMetadata = getOpenAIMetadata(part);\n\n switch (part.type) {\n case 'text': {\n return { type: 'text', text: part.text, ...partMetadata };\n }\n case 'file': {\n switch (part.data.type) {\n case 'reference': {\n return {\n type: 'file',\n file: {\n file_id: resolveProviderReference({\n reference: part.data.reference,\n provider,\n }),\n },\n ...partMetadata,\n };\n }\n case 'text': {\n throw new UnsupportedFunctionalityError({\n functionality: 'text file parts',\n });\n }\n case 'url':\n case 'data': {\n const topLevel = getTopLevelMediaType(part.mediaType);\n\n if (topLevel === 'image') {\n return {\n type: 'image_url',\n image_url: {\n url:\n part.data.type === 'url'\n ? part.data.url.toString()\n : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'video') {\n return {\n type: 'video_url',\n video_url: {\n url:\n part.data.type === 'url'\n ? part.data.url.toString()\n : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'audio') {\n if (part.data.type === 'url') {\n throw new UnsupportedFunctionalityError({\n functionality: 'audio file parts with URLs',\n });\n }\n\n const fullMediaType = resolveFullMediaType({ part });\n const format = getAudioFormat(fullMediaType);\n if (format === null) {\n throw new UnsupportedFunctionalityError({\n functionality: `audio media type ${fullMediaType}`,\n });\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n data: convertToBase64(part.data.data),\n format,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'application') {\n if (part.data.type === 'url') {\n throw new UnsupportedFunctionalityError({\n functionality: 'PDF file parts with URLs',\n });\n }\n\n const fullMediaType = resolveFullMediaType({ part });\n if (fullMediaType !== 'application/pdf') {\n throw new UnsupportedFunctionalityError({\n functionality: `file part media type ${fullMediaType}`,\n });\n }\n\n return {\n type: 'file',\n file: {\n filename: part.filename ?? 'document.pdf',\n file_data: `data:application/pdf;base64,${convertToBase64(part.data.data)}`,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'text') {\n const textContent =\n part.data.type === 'url'\n ? part.data.url.toString()\n : typeof part.data.data === 'string'\n ? new TextDecoder().decode(\n convertBase64ToUint8Array(part.data.data),\n )\n : new TextDecoder().decode(part.data.data);\n\n return {\n type: 'text',\n text: textContent,\n ...partMetadata,\n };\n }\n\n throw new UnsupportedFunctionalityError({\n functionality: `file part media type ${part.mediaType}`,\n });\n }\n }\n }\n }\n}\n\nfunction convertToolContentPart(\n part: Extract<\n LanguageModelV4ToolResultOutput,\n { type: 'content' }\n >['value'][number],\n provider: string,\n): OpenAICompatibleContentPart {\n if (part.type === 'custom') {\n throw new UnsupportedFunctionalityError({\n functionality: 'custom tool content parts',\n });\n }\n\n return convertToOpenAICompatibleContentPart(part, provider);\n}\n\nfunction serializeToolCallArguments(input: unknown): string {\n if (typeof input === 'string') {\n try {\n secureJsonParse(input);\n return input;\n } catch {\n return JSON.stringify(input);\n }\n }\n return stringifyWithBigIntAndCycles(input);\n}\n\nexport function convertToOpenAICompatibleChatMessages(\n prompt: LanguageModelV4Prompt,\n {\n provider = 'openaiCompatible',\n providerOptionsKey = 'google',\n supportsMultiPartToolContent = false,\n }: {\n provider?: string;\n providerOptionsKey?: string;\n supportsMultiPartToolContent?: boolean;\n } = {},\n): OpenAICompatibleChatPrompt {\n const messages: OpenAICompatibleChatPrompt = [];\n for (const { role, content, ...message } of prompt) {\n const metadata = getOpenAIMetadata({ ...message });\n switch (role) {\n case 'system': {\n messages.push({ role: 'system', content, ...metadata });\n break;\n }\n\n case 'user': {\n if (content.length === 1 && content[0].type === 'text') {\n messages.push({\n role: 'user',\n content: content[0].text,\n ...getOpenAIMetadata(content[0]),\n });\n break;\n }\n\n messages.push({\n role: 'user',\n content: content.map(part =>\n convertToOpenAICompatibleContentPart(part, provider),\n ),\n ...metadata,\n });\n\n break;\n }\n\n case 'assistant': {\n let text = '';\n let reasoning = '';\n const toolCalls: Array<{\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n extra_content?: {\n google?: {\n thought_signature?: string;\n };\n };\n }> = [];\n\n for (const part of content) {\n const partMetadata = getOpenAIMetadata(part);\n switch (part.type) {\n case 'text': {\n text += part.text;\n break;\n }\n case 'reasoning': {\n reasoning += part.text;\n break;\n }\n case 'tool-call': {\n // TODO: thoughtSignature should be abstracted once we add support for other providers\n const thoughtSignature =\n part.providerOptions?.[providerOptionsKey]?.thoughtSignature ??\n part.providerOptions?.google?.thoughtSignature;\n toolCalls.push({\n id: part.toolCallId,\n type: 'function',\n function: {\n name: part.toolName,\n arguments: serializeToolCallArguments(part.input),\n },\n ...partMetadata,\n // Include extra_content for Google Gemini thought signatures\n ...(thoughtSignature\n ? {\n extra_content: {\n google: {\n thought_signature: String(thoughtSignature),\n },\n },\n }\n : {}),\n });\n break;\n }\n }\n }\n\n messages.push({\n role: 'assistant',\n content: toolCalls.length > 0 ? text || null : text,\n ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n ...metadata,\n });\n\n break;\n }\n\n case 'tool': {\n for (const toolResponse of content) {\n if (toolResponse.type === 'tool-approval-response') {\n continue;\n }\n\n const output = toolResponse.output;\n\n let contentValue: string | Array<OpenAICompatibleContentPart>;\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 = stringifyWithBigIntAndCycles(output.value);\n break;\n case 'content':\n contentValue = supportsMultiPartToolContent\n ? output.value.map(part =>\n convertToolContentPart(part, provider),\n )\n : stringifyWithBigIntAndCycles(output.value);\n break;\n }\n\n const toolResponseMetadata = getOpenAIMetadata(toolResponse);\n messages.push({\n role: 'tool',\n tool_call_id: toolResponse.toolCallId,\n content: contentValue,\n ...toolResponseMetadata,\n });\n }\n break;\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n\n return messages;\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\nimport { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';\n\nexport function convertOpenAICompatibleChatUsage(\n usage:\n | {\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n prompt_tokens_details?: {\n cached_tokens?: number | null;\n } | null;\n completion_tokens_details?: {\n reasoning_tokens?: number | null;\n } | null;\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 = usage.prompt_tokens_details?.cached_tokens ?? 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 type { LanguageModelV4FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAICompatibleFinishReason(\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 'function_call':\n case 'tool_calls':\n return 'tool-calls';\n default:\n return 'other';\n }\n}\n","import { createLanguageModelResponseMetadata } from '@ai-sdk/provider-utils';\n\nexport function getResponseMetadata({\n id,\n model,\n created,\n}: {\n id?: string | null;\n model?: string | null;\n created?: number | null;\n}) {\n return createLanguageModelResponseMetadata({\n id,\n model,\n // Some OpenAI-compatible providers use 0 as a placeholder timestamp.\n created: created || undefined,\n });\n}\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nexport function prepareTools({\n tools,\n toolChoice,\n}: {\n tools: LanguageModelV4CallOptions['tools'];\n toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n}): {\n tools:\n | undefined\n | Array<{\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n strict?: boolean;\n };\n }>;\n toolChoice:\n | { type: 'function'; function: { name: string } }\n | 'auto'\n | 'none'\n | 'required'\n | undefined;\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 openaiCompatTools: Array<{\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n strict?: boolean;\n };\n }> = [];\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 openaiCompatTools.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: openaiCompatTools, 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: openaiCompatTools, toolChoice: type, toolWarnings };\n case 'tool':\n return {\n tools: openaiCompatTools,\n toolChoice: {\n type: 'function',\n function: { name: toolChoice.toolName },\n },\n toolWarnings,\n };\n default: {\n const _exhaustiveCheck: never = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`,\n });\n }\n }\n}\n"],"mappings":";;;AAsBA,SAAS,kBAAkB,SAExB;CACD,OAAO,SAAS,iBAAiB,oBAAoB,CAAC;AACxD;AAEA,SAAS,eAAe,WAAyC;CAC/D,QAAQ,WAAR;EACE,KAAK,aACH,OAAO;EACT,KAAK;EACL,KAAK,cACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,SAAS,qCACP,MACA,UAC6B;CAC7B,MAAM,eAAe,kBAAkB,IAAI;CAE3C,QAAQ,KAAK,MAAb;EACE,KAAK,QACH,OAAO;GAAE,MAAM;GAAQ,MAAM,KAAK;GAAM,GAAG;EAAa;EAE1D,KAAK,QACH,QAAQ,KAAK,KAAK,MAAlB;GACE,KAAK,aACH,OAAO;IACL,MAAM;IACN,MAAM,EACJ,SAAS,yBAAyB;KAChC,WAAW,KAAK,KAAK;KACrB;IACF,CAAC,EACH;IACA,GAAG;GACL;GAEF,KAAK,QACH,MAAM,IAAI,8BAA8B,EACtC,eAAe,kBACjB,CAAC;GAEH,KAAK;GACL,KAAK,QAAQ;IACX,MAAM,WAAW,qBAAqB,KAAK,SAAS;IAEpD,IAAI,aAAa,SACf,OAAO;KACL,MAAM;KACN,WAAW,EACT,KACE,KAAK,KAAK,SAAS,QACf,KAAK,KAAK,IAAI,SAAS,IACvB,QAAQ,qBAAqB,EAAE,KAAK,CAAC,EAAE,UAAU,gBAAgB,KAAK,KAAK,IAAI,IACvF;KACA,GAAG;IACL;IAGF,IAAI,aAAa,SACf,OAAO;KACL,MAAM;KACN,WAAW,EACT,KACE,K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OAAO;GAAE,OAAO;GAAmB,YAAY;GAAM;EAAa;EACpE,KAAK,QACH,OAAO;GACL,OAAO;GACP,YAAY;IACV,MAAM;IACN,UAAU,EAAE,MAAM,WAAW,SAAS;GACxC;GACA;EACF;EACF,SAEE,MAAM,IAAI,8BAA8B,EACtC,eAAe,qBAAqBC,OACtC,CAAC;CAEL;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_exhaustiveCheck","_exhaustiveCheck"],"sources":["../../src/chat/convert-to-openai-compatible-chat-messages.ts","../../src/chat/convert-openai-compatible-chat-usage.ts","../../src/chat/map-openai-compatible-finish-reason.ts","../../src/chat/get-response-metadata.ts","../../src/chat/openai-compatible-prepare-tools.ts"],"sourcesContent":["import {\n UnsupportedFunctionalityError,\n type LanguageModelV4FilePart,\n type LanguageModelV4Prompt,\n type LanguageModelV4TextPart,\n type LanguageModelV4ToolResultOutput,\n type SharedV4ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n OpenAICompatibleChatPrompt,\n OpenAICompatibleContentPart,\n} from './openai-compatible-api-types';\nimport {\n secureJsonParse,\n stringifyWithBigIntAndCycles,\n convertBase64ToUint8Array,\n convertToBase64,\n getTopLevelMediaType,\n resolveFullMediaType,\n resolveProviderReference,\n} from '@ai-sdk/provider-utils';\n\nfunction getOpenAIMetadata(message: {\n providerOptions?: SharedV4ProviderMetadata;\n}) {\n return message?.providerOptions?.openaiCompatible ?? {};\n}\n\nfunction getAudioFormat(mediaType: string): 'wav' | 'mp3' | null {\n switch (mediaType) {\n case 'audio/wav':\n return 'wav';\n case 'audio/mp3':\n case 'audio/mpeg':\n return 'mp3';\n default:\n return null;\n }\n}\n\nfunction convertToOpenAICompatibleContentPart(\n part: LanguageModelV4TextPart | LanguageModelV4FilePart,\n provider: string,\n): OpenAICompatibleContentPart {\n const partMetadata = getOpenAIMetadata(part);\n\n switch (part.type) {\n case 'text': {\n return { type: 'text', text: part.text, ...partMetadata };\n }\n case 'file': {\n switch (part.data.type) {\n case 'reference': {\n return {\n type: 'file',\n file: {\n file_id: resolveProviderReference({\n reference: part.data.reference,\n provider,\n }),\n },\n ...partMetadata,\n };\n }\n case 'text': {\n if (getTopLevelMediaType(part.mediaType) === 'text') {\n return {\n type: 'text',\n text: part.data.text,\n ...partMetadata,\n };\n }\n\n throw new UnsupportedFunctionalityError({\n functionality: 'text file parts',\n });\n }\n case 'url':\n case 'data': {\n const topLevel = getTopLevelMediaType(part.mediaType);\n\n if (topLevel === 'image') {\n return {\n type: 'image_url',\n image_url: {\n url:\n part.data.type === 'url'\n ? part.data.url.toString()\n : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'video') {\n return {\n type: 'video_url',\n video_url: {\n url:\n part.data.type === 'url'\n ? part.data.url.toString()\n : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'audio') {\n if (part.data.type === 'url') {\n throw new UnsupportedFunctionalityError({\n functionality: 'audio file parts with URLs',\n });\n }\n\n const fullMediaType = resolveFullMediaType({ part });\n const format = getAudioFormat(fullMediaType);\n if (format === null) {\n throw new UnsupportedFunctionalityError({\n functionality: `audio media type ${fullMediaType}`,\n });\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n data: convertToBase64(part.data.data),\n format,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'application') {\n if (part.data.type === 'url') {\n throw new UnsupportedFunctionalityError({\n functionality: 'PDF file parts with URLs',\n });\n }\n\n const fullMediaType = resolveFullMediaType({ part });\n if (fullMediaType !== 'application/pdf') {\n throw new UnsupportedFunctionalityError({\n functionality: `file part media type ${fullMediaType}`,\n });\n }\n\n return {\n type: 'file',\n file: {\n filename: part.filename ?? 'document.pdf',\n file_data: `data:application/pdf;base64,${convertToBase64(part.data.data)}`,\n },\n ...partMetadata,\n };\n }\n\n if (topLevel === 'text') {\n const textContent =\n part.data.type === 'url'\n ? part.data.url.toString()\n : typeof part.data.data === 'string'\n ? new TextDecoder().decode(\n convertBase64ToUint8Array(part.data.data),\n )\n : new TextDecoder().decode(part.data.data);\n\n return {\n type: 'text',\n text: textContent,\n ...partMetadata,\n };\n }\n\n throw new UnsupportedFunctionalityError({\n functionality: `file part media type ${part.mediaType}`,\n });\n }\n }\n }\n }\n}\n\nfunction convertToolContentPart(\n part: Extract<\n LanguageModelV4ToolResultOutput,\n { type: 'content' }\n >['value'][number],\n provider: string,\n): OpenAICompatibleContentPart {\n if (part.type === 'custom') {\n throw new UnsupportedFunctionalityError({\n functionality: 'custom tool content parts',\n });\n }\n\n return convertToOpenAICompatibleContentPart(part, provider);\n}\n\nfunction serializeToolCallArguments(input: unknown): string {\n if (typeof input === 'string') {\n try {\n secureJsonParse(input);\n return input;\n } catch {\n return JSON.stringify(input);\n }\n }\n return stringifyWithBigIntAndCycles(input);\n}\n\nexport function convertToOpenAICompatibleChatMessages(\n prompt: LanguageModelV4Prompt,\n {\n provider = 'openaiCompatible',\n providerOptionsKey = 'google',\n supportsMultiPartToolContent = false,\n }: {\n provider?: string;\n providerOptionsKey?: string;\n supportsMultiPartToolContent?: boolean;\n } = {},\n): OpenAICompatibleChatPrompt {\n const messages: OpenAICompatibleChatPrompt = [];\n for (const { role, content, ...message } of prompt) {\n const metadata = getOpenAIMetadata({ ...message });\n switch (role) {\n case 'system': {\n messages.push({ role: 'system', content, ...metadata });\n break;\n }\n\n case 'user': {\n if (content.length === 1 && content[0].type === 'text') {\n messages.push({\n role: 'user',\n content: content[0].text,\n ...getOpenAIMetadata(content[0]),\n });\n break;\n }\n\n messages.push({\n role: 'user',\n content: content.map(part =>\n convertToOpenAICompatibleContentPart(part, provider),\n ),\n ...metadata,\n });\n\n break;\n }\n\n case 'assistant': {\n let text = '';\n let reasoning = '';\n const toolCalls: Array<{\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n extra_content?: {\n google?: {\n thought_signature?: string;\n };\n };\n }> = [];\n\n for (const part of content) {\n const partMetadata = getOpenAIMetadata(part);\n switch (part.type) {\n case 'text': {\n text += part.text;\n break;\n }\n case 'reasoning': {\n reasoning += part.text;\n break;\n }\n case 'tool-call': {\n // TODO: thoughtSignature should be abstracted once we add support for other providers\n const thoughtSignature =\n part.providerOptions?.[providerOptionsKey]?.thoughtSignature ??\n part.providerOptions?.google?.thoughtSignature;\n toolCalls.push({\n id: part.toolCallId,\n type: 'function',\n function: {\n name: part.toolName,\n arguments: serializeToolCallArguments(part.input),\n },\n ...partMetadata,\n // Include extra_content for Google Gemini thought signatures\n ...(thoughtSignature\n ? {\n extra_content: {\n google: {\n thought_signature: String(thoughtSignature),\n },\n },\n }\n : {}),\n });\n break;\n }\n }\n }\n\n messages.push({\n role: 'assistant',\n content: toolCalls.length > 0 ? text || null : text,\n ...(reasoning.length > 0 ? { reasoning_content: reasoning } : {}),\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n ...metadata,\n });\n\n break;\n }\n\n case 'tool': {\n for (const toolResponse of content) {\n if (toolResponse.type === 'tool-approval-response') {\n continue;\n }\n\n const output = toolResponse.output;\n\n let contentValue: string | Array<OpenAICompatibleContentPart>;\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 = stringifyWithBigIntAndCycles(output.value);\n break;\n case 'content':\n contentValue = supportsMultiPartToolContent\n ? output.value.map(part =>\n convertToolContentPart(part, provider),\n )\n : stringifyWithBigIntAndCycles(output.value);\n break;\n }\n\n const toolResponseMetadata = getOpenAIMetadata(toolResponse);\n messages.push({\n role: 'tool',\n tool_call_id: toolResponse.toolCallId,\n content: contentValue,\n ...toolResponseMetadata,\n });\n }\n break;\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new Error(`Unsupported role: ${_exhaustiveCheck}`);\n }\n }\n }\n\n return messages;\n}\n","import type { LanguageModelV4Usage } from '@ai-sdk/provider';\nimport { createNullLanguageModelUsage } from '@ai-sdk/provider-utils';\n\nexport function convertOpenAICompatibleChatUsage(\n usage:\n | {\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n prompt_tokens_details?: {\n cached_tokens?: number | null;\n } | null;\n completion_tokens_details?: {\n reasoning_tokens?: number | null;\n } | null;\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 = usage.prompt_tokens_details?.cached_tokens ?? 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 type { LanguageModelV4FinishReason } from '@ai-sdk/provider';\n\nexport function mapOpenAICompatibleFinishReason(\n finishReason: string | null | undefined,\n // flag that checks if the model refused to answer:\n { hasRefusal = false }: { hasRefusal?: boolean } = {},\n): LanguageModelV4FinishReason['unified'] {\n switch (finishReason) {\n case 'stop':\n // OpenAI reports a completed response for refusals, so the refusal is\n // the reason the response ended:\n return hasRefusal ? 'content-filter' : 'stop';\n case 'length':\n return 'length';\n case 'content_filter':\n return 'content-filter';\n case 'function_call':\n case 'tool_calls':\n return 'tool-calls';\n default:\n return 'other';\n }\n}\n","import { createLanguageModelResponseMetadata } from '@ai-sdk/provider-utils';\n\nexport function getResponseMetadata({\n id,\n model,\n created,\n}: {\n id?: string | null;\n model?: string | null;\n created?: number | null;\n}) {\n return createLanguageModelResponseMetadata({\n id,\n model,\n // Some OpenAI-compatible providers use 0 as a placeholder timestamp.\n created: created || undefined,\n });\n}\n","import {\n UnsupportedFunctionalityError,\n type LanguageModelV4CallOptions,\n type SharedV4Warning,\n} from '@ai-sdk/provider';\nexport function prepareTools({\n tools,\n toolChoice,\n}: {\n tools: LanguageModelV4CallOptions['tools'];\n toolChoice?: LanguageModelV4CallOptions['toolChoice'];\n}): {\n tools:\n | undefined\n | Array<{\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n strict?: boolean;\n };\n }>;\n toolChoice:\n | { type: 'function'; function: { name: string } }\n | 'auto'\n | 'none'\n | 'required'\n | undefined;\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 openaiCompatTools: Array<{\n type: 'function';\n function: {\n name: string;\n description: string | undefined;\n parameters: unknown;\n strict?: boolean;\n };\n }> = [];\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 openaiCompatTools.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: openaiCompatTools, 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: openaiCompatTools, toolChoice: type, toolWarnings };\n case 'tool':\n return {\n tools: openaiCompatTools,\n toolChoice: {\n type: 'function',\n function: { name: toolChoice.toolName },\n },\n toolWarnings,\n };\n default: {\n const _exhaustiveCheck: never = type;\n throw new UnsupportedFunctionalityError({\n functionality: `tool choice type: ${_exhaustiveCheck}`,\n });\n }\n }\n}\n"],"mappings":";;;AAsBA,SAAS,kBAAkB,SAExB;CACD,OAAO,SAAS,iBAAiB,oBAAoB,CAAC;AACxD;AAEA,SAAS,eAAe,WAAyC;CAC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@ -155,6 +155,28 @@ Only enable `supportsMultiPartToolContent` when the provider accepts content
|
|
|
155
155
|
arrays for messages with the `tool` role. The default stringifies multi-part
|
|
156
156
|
tool results for compatibility with the OpenAI Chat Completions API.
|
|
157
157
|
|
|
158
|
+
### Refusals
|
|
159
|
+
|
|
160
|
+
Some OpenAI-compatible providers, including OpenAI itself, can return a
|
|
161
|
+
`refusal` instead of content when the model declines a request. The refusal
|
|
162
|
+
explanation is surfaced as text in both `generateText` and `streamText`. When a
|
|
163
|
+
non-empty refusal is received and the provider reports a `stop` finish reason,
|
|
164
|
+
the finish reason is `content-filter`:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
const { text, finishReason } = await generateText({
|
|
168
|
+
model: provider('model-id'),
|
|
169
|
+
prompt: '...',
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
if (finishReason === 'content-filter') {
|
|
173
|
+
// `text` contains the model's refusal explanation
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
When a response contains both content and a refusal, the content text is emitted
|
|
178
|
+
first, followed by the refusal text.
|
|
179
|
+
|
|
158
180
|
### Example
|
|
159
181
|
|
|
160
182
|
You can use provider language models to generate text with the `generateText` function:
|
|
@@ -772,3 +794,28 @@ console.log(providerMetadata.myProvider.customMetrics);
|
|
|
772
794
|
```
|
|
773
795
|
|
|
774
796
|
This allows you to access provider-specific information while maintaining a consistent interface across different providers.
|
|
797
|
+
|
|
798
|
+
## Provider Option Reference
|
|
799
|
+
|
|
800
|
+
The following option definitions are generated from the provider catalog.
|
|
801
|
+
|
|
802
|
+
{/* model-capabilities:openai-compatible-provider-options:start */}
|
|
803
|
+
|
|
804
|
+
| Operation | Option | Description |
|
|
805
|
+
| --------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
806
|
+
| language | `user` | A unique identifier representing your end-user, which can help providers to monitor and detect abuse. |
|
|
807
|
+
| language | `reasoningEffort` | Reasoning effort for reasoning models. Defaults to `medium`. Set to `null` to send `"reasoning_effort": null`, for providers that treat an explicit `null` differently from an omitted field. |
|
|
808
|
+
| language | `textVerbosity` | Controls the verbosity of the generated text. Defaults to `medium`. |
|
|
809
|
+
| language | `strictJsonSchema` | Whether to use strict JSON schema validation. When true, the model uses constrained decoding to guarantee schema compliance. Only used when the provider supports structured outputs and a schema is provided. |
|
|
810
|
+
| language | `echo` | Echo back the prompt in addition to the completion. |
|
|
811
|
+
| language | `logitBias` | Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. |
|
|
812
|
+
| language | `suffix` | The suffix that comes after a completion of inserted text. |
|
|
813
|
+
| embedding | `dimensions` | The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. |
|
|
814
|
+
| embedding | `user` | A unique identifier representing your end-user, which can help providers to monitor and detect abuse. |
|
|
815
|
+
| image | `size` | Dimensions of the generated image. Supported values depend on the provider and model. |
|
|
816
|
+
| image | `quality` | Quality of the generated image. Supported values depend on the provider and model. |
|
|
817
|
+
| image | `output_format` | File format of the generated image. Supported values depend on the provider and model. |
|
|
818
|
+
| image | `output_compression` | Compression level for JPEG and WebP images. |
|
|
819
|
+
| image | `background` | Background behavior for the generated image. Supported values depend on the provider and model. |
|
|
820
|
+
|
|
821
|
+
{/* model-capabilities:openai-compatible-provider-options:end */}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/openai-compatible",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.86",
|
|
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.36",
|
|
39
|
+
"@ai-sdk/provider-utils": "5.0.75"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@ai-sdk/test-server": "2.0.4",
|
|
@@ -63,6 +63,14 @@ function convertToOpenAICompatibleContentPart(
|
|
|
63
63
|
};
|
|
64
64
|
}
|
|
65
65
|
case 'text': {
|
|
66
|
+
if (getTopLevelMediaType(part.mediaType) === 'text') {
|
|
67
|
+
return {
|
|
68
|
+
type: 'text',
|
|
69
|
+
text: part.data.text,
|
|
70
|
+
...partMetadata,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
66
74
|
throw new UnsupportedFunctionalityError({
|
|
67
75
|
functionality: 'text file parts',
|
|
68
76
|
});
|
|
@@ -2,10 +2,14 @@ import type { LanguageModelV4FinishReason } from '@ai-sdk/provider';
|
|
|
2
2
|
|
|
3
3
|
export function mapOpenAICompatibleFinishReason(
|
|
4
4
|
finishReason: string | null | undefined,
|
|
5
|
+
// flag that checks if the model refused to answer:
|
|
6
|
+
{ hasRefusal = false }: { hasRefusal?: boolean } = {},
|
|
5
7
|
): LanguageModelV4FinishReason['unified'] {
|
|
6
8
|
switch (finishReason) {
|
|
7
9
|
case 'stop':
|
|
8
|
-
|
|
10
|
+
// OpenAI reports a completed response for refusals, so the refusal is
|
|
11
|
+
// the reason the response ended:
|
|
12
|
+
return hasRefusal ? 'content-filter' : 'stop';
|
|
9
13
|
case 'length':
|
|
10
14
|
return 'length';
|
|
11
15
|
case 'content_filter':
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { openaiCompatibleRequestDefaults } from '../openai-compatible-model-catalog';
|
|
1
2
|
import {
|
|
2
3
|
InvalidResponseDataError,
|
|
3
4
|
type APICallError,
|
|
@@ -169,7 +170,9 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
169
170
|
);
|
|
170
171
|
this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure);
|
|
171
172
|
|
|
172
|
-
this.supportsStructuredOutputs =
|
|
173
|
+
this.supportsStructuredOutputs =
|
|
174
|
+
config.supportsStructuredOutputs ??
|
|
175
|
+
openaiCompatibleRequestDefaults.language.supportsStructuredOutputs;
|
|
173
176
|
}
|
|
174
177
|
|
|
175
178
|
get provider(): string {
|
|
@@ -352,7 +355,11 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
352
355
|
...(reasoningEffort !== undefined
|
|
353
356
|
? { reasoning_effort: reasoningEffort }
|
|
354
357
|
: {}),
|
|
355
|
-
|
|
358
|
+
// an unset textVerbosity must not overwrite a raw `verbosity`
|
|
359
|
+
// passed through provider options:
|
|
360
|
+
...(compatibleOptions.textVerbosity !== undefined
|
|
361
|
+
? { verbosity: compatibleOptions.textVerbosity }
|
|
362
|
+
: {}),
|
|
356
363
|
|
|
357
364
|
// messages:
|
|
358
365
|
messages: convertToOpenAICompatibleChatMessages(prompt, {
|
|
@@ -422,6 +429,16 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
422
429
|
|
|
423
430
|
content.push(...convertOpenAICompatibleContent(choice.message.content));
|
|
424
431
|
|
|
432
|
+
// When the model refuses to answer, the API returns the refusal in
|
|
433
|
+
// `refusal` and sets `content` to null, so surface it as text instead of
|
|
434
|
+
// dropping it. Content and refusal are both returned when the model
|
|
435
|
+
// refuses after answering, so keep both:
|
|
436
|
+
const refusal = choice.message.refusal;
|
|
437
|
+
const hasRefusal = refusal != null && refusal.length > 0;
|
|
438
|
+
if (hasRefusal) {
|
|
439
|
+
content.push({ type: 'text', text: refusal });
|
|
440
|
+
}
|
|
441
|
+
|
|
425
442
|
// tool calls:
|
|
426
443
|
if (choice.message.tool_calls != null) {
|
|
427
444
|
for (const toolCall of choice.message.tool_calls) {
|
|
@@ -464,7 +481,9 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
464
481
|
return {
|
|
465
482
|
content,
|
|
466
483
|
finishReason: {
|
|
467
|
-
unified: mapOpenAICompatibleFinishReason(choice.finish_reason
|
|
484
|
+
unified: mapOpenAICompatibleFinishReason(choice.finish_reason, {
|
|
485
|
+
hasRefusal,
|
|
486
|
+
}),
|
|
468
487
|
raw: choice.finish_reason ?? undefined,
|
|
469
488
|
},
|
|
470
489
|
usage: this.convertUsage(responseBody.usage),
|
|
@@ -582,12 +601,14 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
582
601
|
};
|
|
583
602
|
|
|
584
603
|
let finishReason: LanguageModelV4FinishReason | undefined;
|
|
604
|
+
let rawFinishReason: string | undefined = undefined;
|
|
585
605
|
let usage:
|
|
586
606
|
| z.infer<ReturnType<typeof openaiCompatibleTokenUsageSchema>>
|
|
587
607
|
| undefined = undefined;
|
|
588
608
|
let metadataExtracted = false;
|
|
589
609
|
let isActiveReasoning = false;
|
|
590
610
|
let isActiveText = false;
|
|
611
|
+
let hasRefusal = false;
|
|
591
612
|
const convertUsage = (
|
|
592
613
|
usage: z.infer<ReturnType<typeof openaiCompatibleTokenUsageSchema>>,
|
|
593
614
|
) => this.convertUsage(usage);
|
|
@@ -627,6 +648,7 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
627
648
|
// handle failed chunk parsing / validation:
|
|
628
649
|
if (!chunk.success) {
|
|
629
650
|
finishReason = { unified: 'error', raw: undefined };
|
|
651
|
+
rawFinishReason = undefined;
|
|
630
652
|
controller.enqueue({ type: 'error', error: chunk.error });
|
|
631
653
|
return;
|
|
632
654
|
}
|
|
@@ -636,6 +658,7 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
636
658
|
// handle error chunks:
|
|
637
659
|
if ('error' in chunk.value) {
|
|
638
660
|
finishReason = { unified: 'error', raw: undefined };
|
|
661
|
+
rawFinishReason = undefined;
|
|
639
662
|
controller.enqueue({
|
|
640
663
|
type: 'error',
|
|
641
664
|
error: chunk.value.error,
|
|
@@ -669,11 +692,13 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
669
692
|
|
|
670
693
|
const choice = value.choices[0];
|
|
671
694
|
|
|
695
|
+
// store the raw finish reason and map it in `flush`, after all
|
|
696
|
+
// chunks have been read: many OpenAI-compatible servers send the
|
|
697
|
+
// last delta (which can contain a refusal) in the same chunk as
|
|
698
|
+
// the finish reason, and a refusal turns `stop` into
|
|
699
|
+
// `content-filter`:
|
|
672
700
|
if (choice?.finish_reason != null) {
|
|
673
|
-
|
|
674
|
-
unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
|
|
675
|
-
raw: choice.finish_reason ?? undefined,
|
|
676
|
-
};
|
|
701
|
+
rawFinishReason = choice.finish_reason;
|
|
677
702
|
}
|
|
678
703
|
|
|
679
704
|
if (choice?.delta == null) {
|
|
@@ -740,6 +765,16 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
740
765
|
}
|
|
741
766
|
}
|
|
742
767
|
|
|
768
|
+
// When the model refuses to answer, the API streams the refusal in
|
|
769
|
+
// `refusal` instead of `content`. Content and refusal deltas can
|
|
770
|
+
// both occur, so append each to the same text part instead of
|
|
771
|
+
// dropping one:
|
|
772
|
+
const refusal = delta.refusal;
|
|
773
|
+
if (refusal != null && refusal.length > 0) {
|
|
774
|
+
hasRefusal = true;
|
|
775
|
+
enqueueTextDelta(refusal);
|
|
776
|
+
}
|
|
777
|
+
|
|
743
778
|
if (delta.tool_calls != null && delta.tool_calls.length > 0) {
|
|
744
779
|
// end active reasoning block before tool calls start
|
|
745
780
|
if (isActiveReasoning) {
|
|
@@ -779,6 +814,18 @@ export class OpenAICompatibleChatLanguageModel implements LanguageModelV4 {
|
|
|
779
814
|
|
|
780
815
|
toolCallTracker.flush();
|
|
781
816
|
|
|
817
|
+
// map the stored finish reason now that all deltas (including
|
|
818
|
+
// refusals that arrived in the same chunk as the finish reason)
|
|
819
|
+
// have been read:
|
|
820
|
+
if (rawFinishReason != null) {
|
|
821
|
+
finishReason = {
|
|
822
|
+
unified: mapOpenAICompatibleFinishReason(rawFinishReason, {
|
|
823
|
+
hasRefusal,
|
|
824
|
+
}),
|
|
825
|
+
raw: rawFinishReason,
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
|
|
782
829
|
if (finishReason == null) {
|
|
783
830
|
finishReason = { unified: 'error', raw: undefined };
|
|
784
831
|
controller.enqueue({
|
|
@@ -914,6 +961,15 @@ const OpenAICompatibleChatResponseSchema = lazySchema(() =>
|
|
|
914
961
|
message: z.object({
|
|
915
962
|
role: z.literal('assistant').nullish(),
|
|
916
963
|
content: openAICompatibleContentSchema(),
|
|
964
|
+
// set instead of `content` when the model refuses to answer. Some
|
|
965
|
+
// OpenAI-compatible servers send non-string values (e.g. `false`),
|
|
966
|
+
// which are ignored instead of failing the whole response:
|
|
967
|
+
refusal: z
|
|
968
|
+
.unknown()
|
|
969
|
+
.nullish()
|
|
970
|
+
.transform(value =>
|
|
971
|
+
typeof value === 'string' ? value : undefined,
|
|
972
|
+
),
|
|
917
973
|
reasoning_content: z.string().nullish(),
|
|
918
974
|
reasoning: z.string().nullish(),
|
|
919
975
|
tool_calls: z
|
|
@@ -957,6 +1013,15 @@ const chunkBaseSchema = () =>
|
|
|
957
1013
|
.object({
|
|
958
1014
|
role: z.enum(['assistant', '']).nullish(),
|
|
959
1015
|
content: openAICompatibleContentSchema(),
|
|
1016
|
+
// set instead of `content` when the model refuses to answer. Some
|
|
1017
|
+
// OpenAI-compatible servers send non-string values (e.g. `false`),
|
|
1018
|
+
// which are ignored instead of failing the whole response:
|
|
1019
|
+
refusal: z
|
|
1020
|
+
.unknown()
|
|
1021
|
+
.nullish()
|
|
1022
|
+
.transform(value =>
|
|
1023
|
+
typeof value === 'string' ? value : undefined,
|
|
1024
|
+
),
|
|
960
1025
|
// Most openai-compatible models set `reasoning_content`, but some
|
|
961
1026
|
// providers serving `gpt-oss` set `reasoning`. See #7866
|
|
962
1027
|
reasoning_content: z.string().nullish(),
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { openaiCompatibleRequestDefaults } from '../openai-compatible-model-catalog';
|
|
1
2
|
import {
|
|
2
3
|
TooManyEmbeddingValuesForCallError,
|
|
3
4
|
type EmbeddingModelV4,
|
|
@@ -58,11 +59,17 @@ export class OpenAICompatibleEmbeddingModel implements EmbeddingModelV4 {
|
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
get maxEmbeddingsPerCall(): number {
|
|
61
|
-
return
|
|
62
|
+
return (
|
|
63
|
+
this.config.maxEmbeddingsPerCall ??
|
|
64
|
+
openaiCompatibleRequestDefaults.embedding.maxEmbeddingsPerCall
|
|
65
|
+
);
|
|
62
66
|
}
|
|
63
67
|
|
|
64
68
|
get supportsParallelCalls(): boolean {
|
|
65
|
-
return
|
|
69
|
+
return (
|
|
70
|
+
this.config.supportsParallelCalls ??
|
|
71
|
+
openaiCompatibleRequestDefaults.embedding.supportsParallelCalls
|
|
72
|
+
);
|
|
66
73
|
}
|
|
67
74
|
|
|
68
75
|
static [WORKFLOW_SERIALIZE](model: OpenAICompatibleEmbeddingModel) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { openaiCompatibleRequestDefaults } from '../openai-compatible-model-catalog';
|
|
1
2
|
import {
|
|
2
3
|
InvalidResponseDataError,
|
|
3
4
|
type ImageModelV4,
|
|
@@ -52,7 +53,8 @@ export type OpenAICompatibleImageModelConfig = {
|
|
|
52
53
|
|
|
53
54
|
export class OpenAICompatibleImageModel implements ImageModelV4 {
|
|
54
55
|
readonly specificationVersion = 'v4';
|
|
55
|
-
readonly maxImagesPerCall =
|
|
56
|
+
readonly maxImagesPerCall =
|
|
57
|
+
openaiCompatibleRequestDefaults.image.maxImagesPerCall;
|
|
56
58
|
readonly supportsFileInputs = undefined;
|
|
57
59
|
readonly supportsMaskInputs = undefined;
|
|
58
60
|
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ModelEntry,
|
|
3
|
+
ProviderOptionDefinition,
|
|
4
|
+
ProviderOptionDefinitions,
|
|
5
|
+
} from '@ai-sdk/provider';
|
|
6
|
+
import type { OpenAICompatibleLanguageModelChatOptions } from './chat/openai-compatible-chat-language-model-options';
|
|
7
|
+
import type { OpenAICompatibleLanguageModelCompletionOptions } from './completion/openai-compatible-completion-language-model-options';
|
|
8
|
+
import type { OpenAICompatibleEmbeddingModelOptions } from './embedding/openai-compatible-embedding-model-options';
|
|
9
|
+
import type { OpenAICompatibleImageModelOptions } from './image/openai-compatible-image-model-options';
|
|
10
|
+
|
|
11
|
+
/** Options are declared by the adapter; support depends on the configured backend. */
|
|
12
|
+
export const openaiCompatibleProviderOptions = {
|
|
13
|
+
language: {
|
|
14
|
+
user: {
|
|
15
|
+
description:
|
|
16
|
+
'A unique identifier representing your end-user, which can help providers to monitor and detect abuse.',
|
|
17
|
+
},
|
|
18
|
+
reasoningEffort: {
|
|
19
|
+
description:
|
|
20
|
+
'Reasoning effort for reasoning models. Defaults to `medium`. Set to `null` to send `"reasoning_effort": null`, for providers that treat an explicit `null` differently from an omitted field.',
|
|
21
|
+
},
|
|
22
|
+
textVerbosity: {
|
|
23
|
+
description:
|
|
24
|
+
'Controls the verbosity of the generated text. Defaults to `medium`.',
|
|
25
|
+
},
|
|
26
|
+
strictJsonSchema: {
|
|
27
|
+
description:
|
|
28
|
+
'Whether to use strict JSON schema validation. When true, the model uses constrained decoding to guarantee schema compliance. Only used when the provider supports structured outputs and a schema is provided.',
|
|
29
|
+
},
|
|
30
|
+
echo: {
|
|
31
|
+
description: 'Echo back the prompt in addition to the completion.',
|
|
32
|
+
},
|
|
33
|
+
logitBias: {
|
|
34
|
+
description:
|
|
35
|
+
'Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100.',
|
|
36
|
+
},
|
|
37
|
+
suffix: {
|
|
38
|
+
description: 'The suffix that comes after a completion of inserted text.',
|
|
39
|
+
},
|
|
40
|
+
} satisfies Record<
|
|
41
|
+
| keyof OpenAICompatibleLanguageModelChatOptions
|
|
42
|
+
| keyof OpenAICompatibleLanguageModelCompletionOptions,
|
|
43
|
+
ProviderOptionDefinition
|
|
44
|
+
>,
|
|
45
|
+
embedding: {
|
|
46
|
+
dimensions: {
|
|
47
|
+
description:
|
|
48
|
+
'The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.',
|
|
49
|
+
},
|
|
50
|
+
user: {
|
|
51
|
+
description:
|
|
52
|
+
'A unique identifier representing your end-user, which can help providers to monitor and detect abuse.',
|
|
53
|
+
},
|
|
54
|
+
} satisfies Record<
|
|
55
|
+
keyof OpenAICompatibleEmbeddingModelOptions,
|
|
56
|
+
ProviderOptionDefinition
|
|
57
|
+
>,
|
|
58
|
+
image: {
|
|
59
|
+
size: {
|
|
60
|
+
description:
|
|
61
|
+
'Dimensions of the generated image. Supported values depend on the provider and model.',
|
|
62
|
+
},
|
|
63
|
+
quality: {
|
|
64
|
+
description:
|
|
65
|
+
'Quality of the generated image. Supported values depend on the provider and model.',
|
|
66
|
+
},
|
|
67
|
+
output_format: {
|
|
68
|
+
description:
|
|
69
|
+
'File format of the generated image. Supported values depend on the provider and model.',
|
|
70
|
+
},
|
|
71
|
+
output_compression: {
|
|
72
|
+
description: 'Compression level for JPEG and WebP images.',
|
|
73
|
+
},
|
|
74
|
+
background: {
|
|
75
|
+
description:
|
|
76
|
+
'Background behavior for the generated image. Supported values depend on the provider and model.',
|
|
77
|
+
},
|
|
78
|
+
} satisfies Record<
|
|
79
|
+
keyof OpenAICompatibleImageModelOptions,
|
|
80
|
+
ProviderOptionDefinition
|
|
81
|
+
>,
|
|
82
|
+
} as const satisfies ProviderOptionDefinitions;
|
|
83
|
+
|
|
84
|
+
export const openaiCompatibleRequestDefaults = {
|
|
85
|
+
embedding: { maxEmbeddingsPerCall: 2048, supportsParallelCalls: true },
|
|
86
|
+
image: { maxImagesPerCall: 10 },
|
|
87
|
+
language: { supportsStructuredOutputs: false },
|
|
88
|
+
} as const;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* This protocol accepts arbitrary model IDs. Undeclared backend capabilities
|
|
92
|
+
* remain unknown; a protocol name does not identify a hosted model inventory.
|
|
93
|
+
*/
|
|
94
|
+
export function getOpenAICompatibleModelEntry(_modelId: string) {
|
|
95
|
+
return {
|
|
96
|
+
capabilities: {
|
|
97
|
+
language: {
|
|
98
|
+
inputs: { image: 'unknown', audio: 'unknown' },
|
|
99
|
+
objectGeneration: 'unknown',
|
|
100
|
+
tools: { usage: 'unknown', streaming: 'unknown' },
|
|
101
|
+
reasoning: { support: 'unknown' },
|
|
102
|
+
sampling: {
|
|
103
|
+
temperature: 'unknown',
|
|
104
|
+
topP: 'unknown',
|
|
105
|
+
logprobs: 'unknown',
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
image: {
|
|
109
|
+
sizes: { description: 'Depends on the configured backend and model.' },
|
|
110
|
+
fileInput: 'unknown',
|
|
111
|
+
maskInput: 'unknown',
|
|
112
|
+
maxImagesPerCall:
|
|
113
|
+
openaiCompatibleRequestDefaults.image.maxImagesPerCall,
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
providerOptions: {
|
|
117
|
+
language: Object.fromEntries(
|
|
118
|
+
Object.keys(openaiCompatibleProviderOptions.language).map(key => [
|
|
119
|
+
key,
|
|
120
|
+
'unknown' as const,
|
|
121
|
+
]),
|
|
122
|
+
),
|
|
123
|
+
embedding: Object.fromEntries(
|
|
124
|
+
Object.keys(openaiCompatibleProviderOptions.embedding).map(key => [
|
|
125
|
+
key,
|
|
126
|
+
'unknown' as const,
|
|
127
|
+
]),
|
|
128
|
+
),
|
|
129
|
+
image: Object.fromEntries(
|
|
130
|
+
Object.keys(openaiCompatibleProviderOptions.image).map(key => [
|
|
131
|
+
key,
|
|
132
|
+
'unknown' as const,
|
|
133
|
+
]),
|
|
134
|
+
),
|
|
135
|
+
},
|
|
136
|
+
requestConfig: openaiCompatibleRequestDefaults,
|
|
137
|
+
} satisfies ModelEntry<typeof openaiCompatibleRequestDefaults>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** An arbitrary configured model; this adapter does not own a hosted inventory. */
|
|
141
|
+
export const openaiCompatibleModelCatalog = {
|
|
142
|
+
'*': getOpenAICompatibleModelEntry('*'),
|
|
143
|
+
};
|