@tensorpass/aiconnect 0.1.5 → 0.1.7
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/dist/attachments/attachmentPolicy.d.ts +31 -0
- package/dist/attachments/attachmentPolicy.js +72 -0
- package/dist/attachments/attachmentPolicy.js.map +1 -0
- package/dist/attachments/imagePrep.d.ts +13 -0
- package/dist/attachments/imagePrep.js +70 -0
- package/dist/attachments/imagePrep.js.map +1 -0
- package/dist/attachments/index.d.ts +5 -0
- package/dist/attachments/index.js +6 -0
- package/dist/attachments/index.js.map +1 -0
- package/dist/attachments/pdfModule.d.ts +1 -0
- package/dist/attachments/pdfModule.js +9 -0
- package/dist/attachments/pdfModule.js.map +1 -0
- package/dist/attachments/pdfPrep.d.ts +6 -0
- package/dist/attachments/pdfPrep.js +63 -0
- package/dist/attachments/pdfPrep.js.map +1 -0
- package/dist/attachments/preparedAttachment.d.ts +18 -0
- package/dist/attachments/preparedAttachment.js +52 -0
- package/dist/attachments/preparedAttachment.js.map +1 -0
- package/dist/chatContent.d.ts +7 -1
- package/dist/chatContent.js +29 -2
- package/dist/chatContent.js.map +1 -1
- package/dist/client.js +10 -0
- package/dist/client.js.map +1 -1
- package/dist/connectionState.d.ts +4 -1
- package/dist/connectionState.js.map +1 -1
- package/dist/dictation.d.ts +21 -0
- package/dist/dictation.js +7 -0
- package/dist/dictation.js.map +1 -0
- package/dist/guards/answerGuard.js +1 -1
- package/dist/guards/answerGuard.js.map +1 -1
- package/dist/guards/chatGuard.d.ts +2 -2
- package/dist/guards/chatGuard.js +38 -12
- package/dist/guards/chatGuard.js.map +1 -1
- package/dist/guards/envelopes.d.ts +1 -0
- package/dist/guards/envelopes.js +8 -0
- package/dist/guards/envelopes.js.map +1 -1
- package/dist/guards/index.d.ts +3 -3
- package/dist/guards/index.js +3 -3
- package/dist/guards/index.js.map +1 -1
- package/dist/guards/policy.d.ts +2 -0
- package/dist/guards/policy.js +1 -0
- package/dist/guards/policy.js.map +1 -1
- package/dist/guards/questionGuard.d.ts +2 -0
- package/dist/guards/questionGuard.js +38 -5
- package/dist/guards/questionGuard.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/toolLoop.js +1 -2
- package/dist/toolLoop.js.map +1 -1
- package/dist/types.d.ts +13 -1
- package/dist/types.js.map +1 -1
- package/dist/walletProvider.d.ts +2 -0
- package/dist/walletProvider.js.map +1 -1
- package/dist/webAccounts/openAiWire.js +12 -6
- package/dist/webAccounts/openAiWire.js.map +1 -1
- package/dist/wireProtocols/anthropicMessages.js +18 -3
- package/dist/wireProtocols/anthropicMessages.js.map +1 -1
- package/dist/wireProtocols/geminiContents.js +11 -7
- package/dist/wireProtocols/geminiContents.js.map +1 -1
- package/dist/wireProtocols/openAiChat.js +4 -1
- package/dist/wireProtocols/openAiChat.js.map +1 -1
- package/dist/wireProtocols/openAiResponses.js +4 -1
- package/dist/wireProtocols/openAiResponses.js.map +1 -1
- package/dist/wireProtocols/wireProtocol.d.ts +2 -1
- package/dist/wireProtocols/wireProtocol.js +13 -1
- package/dist/wireProtocols/wireProtocol.js.map +1 -1
- package/package.json +7 -2
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// order, and each result answers the first open call of its name.
|
|
6
6
|
import { textOf } from "../chatContent.js";
|
|
7
7
|
import { WalletRequestError } from "../walletProvider.js";
|
|
8
|
-
import { EMPTY_PARAMETERS, unsupported, userContent } from "./wireProtocol.js";
|
|
8
|
+
import { EMPTY_PARAMETERS, filePart, unsupported, userContent } from "./wireProtocol.js";
|
|
9
9
|
const FINISH_REASONS = {
|
|
10
10
|
stop: 'STOP',
|
|
11
11
|
toolCalls: 'STOP',
|
|
@@ -43,19 +43,23 @@ function jsonSchemaOf(schema) {
|
|
|
43
43
|
}
|
|
44
44
|
return converted;
|
|
45
45
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
46
|
+
// An image, or a PDF or a text file given inline. A file Gemini fetches by its address is an image.
|
|
47
|
+
function mediaPart(mimeType, url, name) {
|
|
48
|
+
if (mimeType?.startsWith('image/')) {
|
|
49
|
+
return { type: 'image', url };
|
|
49
50
|
}
|
|
50
|
-
|
|
51
|
+
if (url.startsWith('data:')) {
|
|
52
|
+
return filePart(url, name);
|
|
53
|
+
}
|
|
54
|
+
throw unsupported(`${mimeType ?? 'untyped'} files`);
|
|
51
55
|
}
|
|
52
56
|
function partOf(part) {
|
|
53
57
|
if (typeof part.text === 'string') {
|
|
54
58
|
return { type: 'text', text: part.text };
|
|
55
59
|
}
|
|
56
60
|
if (part.inlineData) {
|
|
57
|
-
const { mimeType, data } = part.inlineData;
|
|
58
|
-
return mediaPart(mimeType, `data:${mimeType};base64,${data}
|
|
61
|
+
const { mimeType, data, displayName } = part.inlineData;
|
|
62
|
+
return mediaPart(mimeType, `data:${mimeType};base64,${data}`, displayName);
|
|
59
63
|
}
|
|
60
64
|
if (part.fileData) {
|
|
61
65
|
return mediaPart(part.fileData.mimeType, part.fileData.fileUri);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geminiContents.js","sourceRoot":"","sources":["../../src/wireProtocols/geminiContents.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,mGAAmG;AACnG,4FAA4F;AAC5F,gGAAgG;AAChG,kEAAkE;AAElE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAoD/E,MAAM,cAAc,GAAiC;IACnD,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,MAAM;IACjB,MAAM,EAAE,YAAY;IACpB,aAAa,EAAE,QAAQ;CACxB,CAAC;AAEF,MAAM,UAAU,GAA+B,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MA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E,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;IACjF,OAAO,KAAK,CAAC,OAAO,EAAE,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACzD,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,UAAU,EAAE,EAAE,CAAC;AACxH,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC","sourcesContent":["// The Gemini `generateContent` protocol, as Google's Gen AI SDK and the Vercel AI SDK's `google()`\n// models speak it. The path says whether to stream (`:streamGenerateContent`). Streamed answers go\n// as plain data events of the same response shape; the last one carries the tool calls, the\n// finish reason and the token counts. Gemini may leave tool call ids out: calls then get one in\n// order, and each result answers the first open call of its name.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ToolCall, ToolChoice, ToolDefinition, Usage,\n} from '../types.ts';\nimport { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport { EMPTY_PARAMETERS, unsupported, userContent } from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WirePart {\n text?: string;\n thought?: boolean;\n inlineData?: { mimeType: string; data: string };\n fileData?: { mimeType?: string; fileUri: string };\n functionCall?: { id?: string; name: string; args?: Record<string, unknown> };\n functionResponse?: { id?: string; name: string; response?: unknown };\n}\n\ninterface WireContent {\n role?: string;\n parts?: WirePart[];\n}\n\ninterface FunctionDeclaration {\n name: string;\n description?: string;\n parameters?: JsonSchema;\n parametersJsonSchema?: JsonSchema;\n}\n\ninterface WireTool {\n functionDeclarations?: FunctionDeclaration[];\n}\n\ninterface GenerateBody {\n contents?: WireContent[];\n systemInstruction?: string | WireContent;\n tools?: WireTool | WireTool[];\n toolConfig?: { functionCallingConfig?: { mode?: string; allowedFunctionNames?: string[] } };\n generationConfig?: {\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n candidateCount?: number;\n responseMimeType?: string;\n responseSchema?: JsonSchema;\n responseJsonSchema?: JsonSchema;\n };\n}\n\n// The conversation being read, with the tool calls still waiting for their result.\ninterface Reading {\n messages: ChatMessage[];\n open: ToolCall[];\n calls: number;\n}\n\nconst FINISH_REASONS: Record<FinishReason, string> = {\n stop: 'STOP',\n toolCalls: 'STOP',\n length: 'MAX_TOKENS',\n contentFilter: 'SAFETY',\n};\n\nconst TOOL_MODES: Record<string, ToolChoice> = { AUTO: 'auto', NONE: 'none', ANY: 'required', VALIDATED: 'auto' };\n\nconst GOOGLE_STATUSES: Record<number, string> = {\n 400: 'INVALID_ARGUMENT',\n 401: 'UNAUTHENTICATED',\n 403: 'PERMISSION_DENIED',\n 404: 'NOT_FOUND',\n 429: 'RESOURCE_EXHAUSTED',\n 503: 'UNAVAILABLE',\n};\n\n// Gemini's OpenAPI style schema as JSON Schema: lower case types, `nullable` as a null type, and\n// no `propertyOrdering`, which other providers refuse.\nfunction jsonSchemaOf(schema: JsonSchema): JsonSchema {\n const converted: JsonSchema = { ...schema };\n delete converted.propertyOrdering;\n delete converted.nullable;\n if (typeof schema.type === 'string') {\n const type = schema.type.toLowerCase();\n converted.type = schema.nullable ? [type, 'null'] : type;\n }\n if (schema.properties) {\n const properties = Object.entries(schema.properties as Record<string, JsonSchema>);\n converted.properties = Object.fromEntries(properties.map(([name, value]) => [name, jsonSchemaOf(value)]));\n }\n if (schema.items) {\n converted.items = jsonSchemaOf(schema.items as JsonSchema);\n }\n if (Array.isArray(schema.anyOf)) {\n converted.anyOf = (schema.anyOf as JsonSchema[]).map(jsonSchemaOf);\n }\n return converted;\n}\n\nfunction mediaPart(mimeType: string | undefined, url: string): ContentPart {\n if (!mimeType?.startsWith('image/')) {\n throw unsupported(`${mimeType ?? 'untyped'} files`);\n }\n return { type: 'image', url };\n}\n\nfunction partOf(part: WirePart): ContentPart {\n if (typeof part.text === 'string') {\n return { type: 'text', text: part.text };\n }\n if (part.inlineData) {\n const { mimeType, data } = part.inlineData;\n return mediaPart(mimeType, `data:${mimeType};base64,${data}`);\n }\n if (part.fileData) {\n return mediaPart(part.fileData.mimeType, part.fileData.fileUri);\n }\n throw unsupported(`the ${Object.keys(part).join(', ')} part`);\n}\n\nfunction readModel(reading: Reading, parts: WirePart[]): void {\n const toolCalls: ToolCall[] = parts.filter((part) => part.functionCall).map((part) => {\n const { id, name, args } = part.functionCall!;\n reading.calls += 1;\n return { id: id ?? `call_${reading.calls}`, name, arguments: args ?? {} };\n });\n reading.open.push(...toolCalls);\n const content = textOf(parts.filter((part) => !part.functionCall).map(partOf));\n reading.messages.push({ role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) });\n}\n\nfunction answeredCall(reading: Reading, response: NonNullable<WirePart['functionResponse']>): ToolCall {\n const index = reading.open.findIndex((call) => (response.id ? call.id === response.id : call.name === response.name));\n if (index < 0) {\n throw new WalletRequestError(`A function response answers ${response.name}, which no open call made`, 400);\n }\n return reading.open.splice(index, 1)[0];\n}\n\nfunction readUser(reading: Reading, parts: WirePart[]): void {\n for (const part of parts.filter((candidate) => candidate.functionResponse)) {\n const call = answeredCall(reading, part.functionResponse!);\n const content = JSON.stringify(part.functionResponse!.response ?? {});\n reading.messages.push({ role: 'tool', toolCallId: call.id, name: call.name, content });\n }\n const rest = parts.filter((part) => !part.functionResponse).map(partOf);\n if (rest.length) {\n reading.messages.push({ role: 'user', content: userContent(rest) });\n }\n}\n\n// Thought parts hold the provider's own reasoning, which another account cannot read.\nfunction readMessages(body: GenerateBody): ChatMessage[] {\n const reading: Reading = { messages: [], open: [], calls: 0 };\n const system = typeof body.systemInstruction === 'string'\n ? body.systemInstruction\n : textOf((body.systemInstruction?.parts ?? []).map(partOf));\n if (system) {\n reading.messages.push({ role: 'system', content: system });\n }\n for (const content of body.contents ?? []) {\n const parts = (content.parts ?? []).filter((part) => !part.thought);\n if (content.role === 'model') {\n readModel(reading, parts);\n } else {\n readUser(reading, parts);\n }\n }\n return reading.messages;\n}\n\nfunction readTools(tools: GenerateBody['tools']): ToolDefinition[] | undefined {\n if (!tools) {\n return undefined;\n }\n return [tools].flat().flatMap((tool) => {\n if (!tool.functionDeclarations) {\n throw unsupported(`the ${Object.keys(tool).join(', ')} tool`);\n }\n return tool.functionDeclarations.map(({ name, description = '', parameters, parametersJsonSchema }) => ({\n name,\n description,\n inputSchema: parametersJsonSchema ?? (parameters ? jsonSchemaOf(parameters) : EMPTY_PARAMETERS),\n }));\n });\n}\n\nfunction readToolChoice(config: GenerateBody['toolConfig']): ToolChoice | undefined {\n const calling = config?.functionCallingConfig;\n const names = calling?.allowedFunctionNames ?? [];\n if (calling?.mode === 'ANY' && names.length === 1) {\n return { name: names[0] };\n }\n return calling?.mode ? TOOL_MODES[calling.mode] : undefined;\n}\n\nfunction read(raw: Record<string, unknown>, url: URL): WireRequest {\n const body = raw as GenerateBody;\n const generation = body.generationConfig ?? {};\n if ((generation.candidateCount ?? 1) > 1) {\n throw unsupported('several candidates per request');\n }\n const { responseJsonSchema, responseSchema } = generation;\n const schema = responseJsonSchema ?? (responseSchema ? jsonSchemaOf(responseSchema) : undefined);\n const json = generation.responseMimeType === 'application/json';\n return {\n request: {\n messages: readMessages(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: generation.maxOutputTokens,\n temperature: generation.temperature,\n topP: generation.topP,\n stop: generation.stopSequences,\n toolChoice: readToolChoice(body.toolConfig),\n responseFormat: json ? { type: 'json', schema } : undefined,\n },\n },\n stream: /:streamGenerateContent$/i.test(url.pathname),\n };\n}\n\nfunction usageMetadata(usage: Usage | undefined) {\n if (!usage) {\n return undefined;\n }\n return {\n promptTokenCount: usage.inputTokens,\n candidatesTokenCount: usage.outputTokens,\n totalTokenCount: usage.inputTokens + usage.outputTokens,\n cachedContentTokenCount: usage.cachedInputTokens,\n };\n}\n\nfunction callParts(calls: ToolCall[] = []): WirePart[] {\n return calls.map((call) => ({ functionCall: { id: call.id, name: call.name, args: call.arguments } }));\n}\n\nfunction chunk(context: AnswerContext, model: string, parts: WirePart[], response?: ChatResponse) {\n const finish = response ? { finishReason: FINISH_REASONS[response.finishReason] } : {};\n return {\n candidates: [{ content: { role: 'model', parts }, index: 0, ...finish }],\n usageMetadata: usageMetadata(response?.usage),\n modelVersion: model,\n responseId: context.id,\n };\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const { model } = await answer.started;\n for await (const text of answer.texts()) {\n write.send(chunk(context, model, [{ text }]));\n }\n const response = await answer.result;\n write.send(chunk(context, response.model, callParts(response.message.toolCalls), response));\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n const { content, toolCalls } = response.message;\n const parts = [...(content ? [{ text: content }] : []), ...callParts(toolCalls)];\n return chunk(context, response.model, parts, response);\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { code: error.status, message: error.message, status: GOOGLE_STATUSES[error.status] ?? 'INTERNAL' } };\n}\n\nexport const geminiContents: WireProtocol = { read, stream, body, error: errorBody };\n"]}
|
|
1
|
+
{"version":3,"file":"geminiContents.js","sourceRoot":"","sources":["../../src/wireProtocols/geminiContents.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,mGAAmG;AACnG,4FAA4F;AAC5F,gGAAgG;AAChG,kEAAkE;AAElE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAI3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,m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,OAAO,EAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC9F,CAAC;AAED,SAAS,IAAI,CAAC,QAAsB,EAAE,OAAsB;IAC1D,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC,OAAO,CAAC;IAChD,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;IACjF,OAAO,KAAK,CAAC,OAAO,EAAE,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACzD,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,UAAU,EAAE,EAAE,CAAC;AACxH,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAiB,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC","sourcesContent":["// The Gemini `generateContent` protocol, as Google's Gen AI SDK and the Vercel AI SDK's `google()`\n// models speak it. The path says whether to stream (`:streamGenerateContent`). Streamed answers go\n// as plain data events of the same response shape; the last one carries the tool calls, the\n// finish reason and the token counts. Gemini may leave tool call ids out: calls then get one in\n// order, and each result answers the first open call of its name.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ToolCall, ToolChoice, ToolDefinition, Usage,\n} from '../types.ts';\nimport { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport { EMPTY_PARAMETERS, filePart, unsupported, userContent } from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WirePart {\n text?: string;\n thought?: boolean;\n inlineData?: { mimeType: string; data: string; displayName?: string };\n fileData?: { mimeType?: string; fileUri: string };\n functionCall?: { id?: string; name: string; args?: Record<string, unknown> };\n functionResponse?: { id?: string; name: string; response?: unknown };\n}\n\ninterface WireContent {\n role?: string;\n parts?: WirePart[];\n}\n\ninterface FunctionDeclaration {\n name: string;\n description?: string;\n parameters?: JsonSchema;\n parametersJsonSchema?: JsonSchema;\n}\n\ninterface WireTool {\n functionDeclarations?: FunctionDeclaration[];\n}\n\ninterface GenerateBody {\n contents?: WireContent[];\n systemInstruction?: string | WireContent;\n tools?: WireTool | WireTool[];\n toolConfig?: { functionCallingConfig?: { mode?: string; allowedFunctionNames?: string[] } };\n generationConfig?: {\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n candidateCount?: number;\n responseMimeType?: string;\n responseSchema?: JsonSchema;\n responseJsonSchema?: JsonSchema;\n };\n}\n\n// The conversation being read, with the tool calls still waiting for their result.\ninterface Reading {\n messages: ChatMessage[];\n open: ToolCall[];\n calls: number;\n}\n\nconst FINISH_REASONS: Record<FinishReason, string> = {\n stop: 'STOP',\n toolCalls: 'STOP',\n length: 'MAX_TOKENS',\n contentFilter: 'SAFETY',\n};\n\nconst TOOL_MODES: Record<string, ToolChoice> = { AUTO: 'auto', NONE: 'none', ANY: 'required', VALIDATED: 'auto' };\n\nconst GOOGLE_STATUSES: Record<number, string> = {\n 400: 'INVALID_ARGUMENT',\n 401: 'UNAUTHENTICATED',\n 403: 'PERMISSION_DENIED',\n 404: 'NOT_FOUND',\n 429: 'RESOURCE_EXHAUSTED',\n 503: 'UNAVAILABLE',\n};\n\n// Gemini's OpenAPI style schema as JSON Schema: lower case types, `nullable` as a null type, and\n// no `propertyOrdering`, which other providers refuse.\nfunction jsonSchemaOf(schema: JsonSchema): JsonSchema {\n const converted: JsonSchema = { ...schema };\n delete converted.propertyOrdering;\n delete converted.nullable;\n if (typeof schema.type === 'string') {\n const type = schema.type.toLowerCase();\n converted.type = schema.nullable ? [type, 'null'] : type;\n }\n if (schema.properties) {\n const properties = Object.entries(schema.properties as Record<string, JsonSchema>);\n converted.properties = Object.fromEntries(properties.map(([name, value]) => [name, jsonSchemaOf(value)]));\n }\n if (schema.items) {\n converted.items = jsonSchemaOf(schema.items as JsonSchema);\n }\n if (Array.isArray(schema.anyOf)) {\n converted.anyOf = (schema.anyOf as JsonSchema[]).map(jsonSchemaOf);\n }\n return converted;\n}\n\n// An image, or a PDF or a text file given inline. A file Gemini fetches by its address is an image.\nfunction mediaPart(mimeType: string | undefined, url: string, name?: string): ContentPart {\n if (mimeType?.startsWith('image/')) {\n return { type: 'image', url };\n }\n if (url.startsWith('data:')) {\n return filePart(url, name);\n }\n throw unsupported(`${mimeType ?? 'untyped'} files`);\n}\n\nfunction partOf(part: WirePart): ContentPart {\n if (typeof part.text === 'string') {\n return { type: 'text', text: part.text };\n }\n if (part.inlineData) {\n const { mimeType, data, displayName } = part.inlineData;\n return mediaPart(mimeType, `data:${mimeType};base64,${data}`, displayName);\n }\n if (part.fileData) {\n return mediaPart(part.fileData.mimeType, part.fileData.fileUri);\n }\n throw unsupported(`the ${Object.keys(part).join(', ')} part`);\n}\n\nfunction readModel(reading: Reading, parts: WirePart[]): void {\n const toolCalls: ToolCall[] = parts.filter((part) => part.functionCall).map((part) => {\n const { id, name, args } = part.functionCall!;\n reading.calls += 1;\n return { id: id ?? `call_${reading.calls}`, name, arguments: args ?? {} };\n });\n reading.open.push(...toolCalls);\n const content = textOf(parts.filter((part) => !part.functionCall).map(partOf));\n reading.messages.push({ role: 'assistant', content, ...(toolCalls.length ? { toolCalls } : {}) });\n}\n\nfunction answeredCall(reading: Reading, response: NonNullable<WirePart['functionResponse']>): ToolCall {\n const index = reading.open.findIndex((call) => (response.id ? call.id === response.id : call.name === response.name));\n if (index < 0) {\n throw new WalletRequestError(`A function response answers ${response.name}, which no open call made`, 400);\n }\n return reading.open.splice(index, 1)[0];\n}\n\nfunction readUser(reading: Reading, parts: WirePart[]): void {\n for (const part of parts.filter((candidate) => candidate.functionResponse)) {\n const call = answeredCall(reading, part.functionResponse!);\n const content = JSON.stringify(part.functionResponse!.response ?? {});\n reading.messages.push({ role: 'tool', toolCallId: call.id, name: call.name, content });\n }\n const rest = parts.filter((part) => !part.functionResponse).map(partOf);\n if (rest.length) {\n reading.messages.push({ role: 'user', content: userContent(rest) });\n }\n}\n\n// Thought parts hold the provider's own reasoning, which another account cannot read.\nfunction readMessages(body: GenerateBody): ChatMessage[] {\n const reading: Reading = { messages: [], open: [], calls: 0 };\n const system = typeof body.systemInstruction === 'string'\n ? body.systemInstruction\n : textOf((body.systemInstruction?.parts ?? []).map(partOf));\n if (system) {\n reading.messages.push({ role: 'system', content: system });\n }\n for (const content of body.contents ?? []) {\n const parts = (content.parts ?? []).filter((part) => !part.thought);\n if (content.role === 'model') {\n readModel(reading, parts);\n } else {\n readUser(reading, parts);\n }\n }\n return reading.messages;\n}\n\nfunction readTools(tools: GenerateBody['tools']): ToolDefinition[] | undefined {\n if (!tools) {\n return undefined;\n }\n return [tools].flat().flatMap((tool) => {\n if (!tool.functionDeclarations) {\n throw unsupported(`the ${Object.keys(tool).join(', ')} tool`);\n }\n return tool.functionDeclarations.map(({ name, description = '', parameters, parametersJsonSchema }) => ({\n name,\n description,\n inputSchema: parametersJsonSchema ?? (parameters ? jsonSchemaOf(parameters) : EMPTY_PARAMETERS),\n }));\n });\n}\n\nfunction readToolChoice(config: GenerateBody['toolConfig']): ToolChoice | undefined {\n const calling = config?.functionCallingConfig;\n const names = calling?.allowedFunctionNames ?? [];\n if (calling?.mode === 'ANY' && names.length === 1) {\n return { name: names[0] };\n }\n return calling?.mode ? TOOL_MODES[calling.mode] : undefined;\n}\n\nfunction read(raw: Record<string, unknown>, url: URL): WireRequest {\n const body = raw as GenerateBody;\n const generation = body.generationConfig ?? {};\n if ((generation.candidateCount ?? 1) > 1) {\n throw unsupported('several candidates per request');\n }\n const { responseJsonSchema, responseSchema } = generation;\n const schema = responseJsonSchema ?? (responseSchema ? jsonSchemaOf(responseSchema) : undefined);\n const json = generation.responseMimeType === 'application/json';\n return {\n request: {\n messages: readMessages(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: generation.maxOutputTokens,\n temperature: generation.temperature,\n topP: generation.topP,\n stop: generation.stopSequences,\n toolChoice: readToolChoice(body.toolConfig),\n responseFormat: json ? { type: 'json', schema } : undefined,\n },\n },\n stream: /:streamGenerateContent$/i.test(url.pathname),\n };\n}\n\nfunction usageMetadata(usage: Usage | undefined) {\n if (!usage) {\n return undefined;\n }\n return {\n promptTokenCount: usage.inputTokens,\n candidatesTokenCount: usage.outputTokens,\n totalTokenCount: usage.inputTokens + usage.outputTokens,\n cachedContentTokenCount: usage.cachedInputTokens,\n };\n}\n\nfunction callParts(calls: ToolCall[] = []): WirePart[] {\n return calls.map((call) => ({ functionCall: { id: call.id, name: call.name, args: call.arguments } }));\n}\n\nfunction chunk(context: AnswerContext, model: string, parts: WirePart[], response?: ChatResponse) {\n const finish = response ? { finishReason: FINISH_REASONS[response.finishReason] } : {};\n return {\n candidates: [{ content: { role: 'model', parts }, index: 0, ...finish }],\n usageMetadata: usageMetadata(response?.usage),\n modelVersion: model,\n responseId: context.id,\n };\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const { model } = await answer.started;\n for await (const text of answer.texts()) {\n write.send(chunk(context, model, [{ text }]));\n }\n const response = await answer.result;\n write.send(chunk(context, response.model, callParts(response.message.toolCalls), response));\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n const { content, toolCalls } = response.message;\n const parts = [...(content ? [{ text: content }] : []), ...callParts(toolCalls)];\n return chunk(context, response.model, parts, response);\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { code: error.status, message: error.message, status: GOOGLE_STATUSES[error.status] ?? 'INTERNAL' } };\n}\n\nexport const geminiContents: WireProtocol = { read, stream, body, error: errorBody };\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// the Vercel AI SDK's `openai.chat()` speak it. Streamed answers go as `chat.completion.chunk`
|
|
3
3
|
// events ending with `[DONE]`; tool calls and the finish reason come on the last chunks.
|
|
4
4
|
import { textOf } from "../chatContent.js";
|
|
5
|
-
import { EMPTY_PARAMETERS, errorType, parseToolArguments, toolNameOf, unsupported, userContent, } from "./wireProtocol.js";
|
|
5
|
+
import { EMPTY_PARAMETERS, errorType, filePart, parseToolArguments, toolNameOf, unsupported, userContent, } from "./wireProtocol.js";
|
|
6
6
|
const FINISH_REASONS = {
|
|
7
7
|
stop: 'stop',
|
|
8
8
|
length: 'length',
|
|
@@ -19,6 +19,9 @@ function partOf(part) {
|
|
|
19
19
|
if (part.type === 'image_url' && part.image_url) {
|
|
20
20
|
return { type: 'image', url: typeof part.image_url === 'string' ? part.image_url : part.image_url.url };
|
|
21
21
|
}
|
|
22
|
+
if (part.type === 'file' && part.file) {
|
|
23
|
+
return filePart(part.file.file_data, part.file.filename);
|
|
24
|
+
}
|
|
22
25
|
throw unsupported(`${part.type} content`);
|
|
23
26
|
}
|
|
24
27
|
function partsOf(content) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openAiChat.js","sourceRoot":"","sources":["../../src/wireProtocols/openAiChat.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,+FAA+F;AAC/F,yFAAyF;AAEzF,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQ3C,OAAO,EACL,gBAAgB,EAAE,SAAS,EAAE,kBAAkB,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,GACtF,MAAM,mBAAmB,CAAC;AA+C3B,MAAM,cAAc,GAAiC;IACnD,IAA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O,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE;gBACtG,aAAa,EAAE,cAAc,CAAC,YAAY,CAAC;gBAC3C,QAAQ,EAAE,IAAI;aACf,CAAC;QACF,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;KAC5C,CAAC;AACJ,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;AACvG,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAiB;IACtC,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,KAAK,EAAE,SAAS;IAChB,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;CACrD,CAAC","sourcesContent":["// The OpenAI chat completions protocol, as the OpenAI SDK, LangChain's ChatOpenAI, LlamaIndex and\n// the Vercel AI SDK's `openai.chat()` speak it. Streamed answers go as `chat.completion.chunk`\n// events ending with `[DONE]`; tool calls and the finish reason come on the last chunks.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport {\n EMPTY_PARAMETERS, errorType, parseToolArguments, toolNameOf, unsupported, userContent,\n} from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WirePart {\n type: string;\n text?: string;\n refusal?: string;\n image_url?: string | { url: string };\n}\n\ninterface WireToolCall {\n id: string;\n function: { name: string; arguments?: string };\n}\n\ninterface WireMessage {\n role: string;\n content?: string | WirePart[] | null;\n tool_calls?: WireToolCall[];\n tool_call_id?: string;\n}\n\ninterface WireTool {\n type: string;\n function?: { name: string; description?: string; parameters?: JsonSchema };\n}\n\ninterface WireFormat {\n type: string;\n json_schema?: { name?: string; schema?: JsonSchema; strict?: boolean };\n}\n\ninterface ChatBody {\n messages?: WireMessage[];\n tools?: WireTool[];\n tool_choice?: string | { function: { name: string } };\n response_format?: WireFormat;\n max_tokens?: number;\n max_completion_tokens?: number;\n temperature?: number;\n top_p?: number;\n stop?: string | string[];\n n?: number;\n stream?: boolean;\n stream_options?: { include_usage?: boolean };\n}\n\nconst FINISH_REASONS: Record<FinishReason, string> = {\n stop: 'stop',\n length: 'length',\n toolCalls: 'tool_calls',\n contentFilter: 'content_filter',\n};\n\nfunction partOf(part: WirePart): ContentPart {\n if (part.type === 'text') {\n return { type: 'text', text: part.text ?? '' };\n }\n if (part.type === 'refusal') {\n return { type: 'text', text: part.refusal ?? '' };\n }\n if (part.type === 'image_url' && part.image_url) {\n return { type: 'image', url: typeof part.image_url === 'string' ? part.image_url : part.image_url.url };\n }\n throw unsupported(`${part.type} content`);\n}\n\nfunction partsOf(content: WireMessage['content']): ContentPart[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).map(partOf);\n}\n\nfunction assistantMessage(message: WireMessage, names: Map<string, string>): ChatMessage {\n const toolCalls: ToolCall[] = (message.tool_calls ?? []).map((call) => ({\n id: call.id, name: call.function.name, arguments: parseToolArguments(call.function.arguments),\n }));\n toolCalls.forEach((call) => names.set(call.id, call.name));\n return { role: 'assistant', content: textOf(partsOf(message.content)), ...(toolCalls.length ? { toolCalls } : {}) };\n}\n\nfunction readMessages(messages: WireMessage[]): ChatMessage[] {\n const names = new Map<string, string>();\n return messages.map((message): ChatMessage => {\n switch (message.role) {\n case 'system':\n case 'developer':\n return { role: 'system', content: textOf(partsOf(message.content)) };\n case 'user':\n return { role: 'user', content: userContent(partsOf(message.content)) };\n case 'assistant':\n return assistantMessage(message, names);\n case 'tool': {\n const toolCallId = message.tool_call_id ?? '';\n const content = textOf(partsOf(message.content));\n return { role: 'tool', toolCallId, name: toolNameOf(names, toolCallId), content };\n }\n default:\n throw unsupported(`${message.role} messages`);\n }\n });\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type !== 'function' || !tool.function) {\n throw unsupported(`${tool.type} tools`);\n }\n const { name, description = '', parameters = EMPTY_PARAMETERS } = tool.function;\n return { name, description, inputSchema: parameters };\n });\n}\n\nfunction readToolChoice(choice: ChatBody['tool_choice']): ToolChoice | undefined {\n return typeof choice === 'object' ? { name: choice.function.name } : choice as ToolChoice | undefined;\n}\n\nfunction readFormat(format?: WireFormat): ResponseFormat | undefined {\n if (!format || format.type === 'text') {\n return undefined;\n }\n return { type: 'json', ...format.json_schema };\n}\n\nfunction read(body: Record<string, unknown>): WireRequest {\n const chat = body as ChatBody;\n if ((chat.n ?? 1) > 1) {\n throw unsupported('several choices per request');\n }\n return {\n request: {\n messages: readMessages(chat.messages ?? []),\n tools: readTools(chat.tools),\n options: {\n maxTokens: chat.max_completion_tokens ?? chat.max_tokens,\n temperature: chat.temperature,\n topP: chat.top_p,\n stop: typeof chat.stop === 'string' ? [chat.stop] : chat.stop,\n toolChoice: readToolChoice(chat.tool_choice),\n responseFormat: readFormat(chat.response_format),\n },\n },\n stream: chat.stream === true,\n includeUsage: chat.stream_options?.include_usage === true,\n };\n}\n\nfunction wireUsage(usage: Usage) {\n return {\n prompt_tokens: usage.inputTokens,\n completion_tokens: usage.outputTokens,\n total_tokens: usage.inputTokens + usage.outputTokens,\n prompt_tokens_details: { cached_tokens: usage.cachedInputTokens },\n };\n}\n\nfunction wireToolCall(call: ToolCall) {\n return { id: call.id, type: 'function', function: { name: call.name, arguments: JSON.stringify(call.arguments) } };\n}\n\nfunction chunk(context: AnswerContext, model: string, delta: Record<string, unknown>, finish: string | null = null) {\n return {\n id: `chatcmpl-${context.id}`,\n object: 'chat.completion.chunk',\n created: context.created,\n model,\n choices: [{ index: 0, delta, finish_reason: finish, logprobs: null }],\n };\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const answering = (await answer.started).model;\n write.send(chunk(context, answering, { role: 'assistant', content: '' }));\n for await (const text of answer.texts()) {\n write.send(chunk(context, answering, { content: text }));\n }\n const { message, finishReason, model, usage } = await answer.result;\n // One chunk per call, as OpenAI streams them.\n (message.toolCalls ?? []).forEach((call, index) => {\n write.send(chunk(context, model, { tool_calls: [{ index, ...wireToolCall(call) }] }));\n });\n write.send(chunk(context, model, {}, FINISH_REASONS[finishReason]));\n if (context.wire.includeUsage && usage) {\n write.send({ ...chunk(context, model, {}), choices: [], usage: wireUsage(usage) });\n }\n write.send('[DONE]');\n}\n\nfunction body({ message, finishReason, model, usage }: ChatResponse, context: AnswerContext) {\n const toolCalls = message.toolCalls?.length ? message.toolCalls.map(wireToolCall) : undefined;\n return {\n id: `chatcmpl-${context.id}`,\n object: 'chat.completion',\n created: context.created,\n model,\n choices: [{\n index: 0,\n message: { role: 'assistant', content: message.content || null, refusal: null, tool_calls: toolCalls },\n finish_reason: FINISH_REASONS[finishReason],\n logprobs: null,\n }],\n usage: usage ? wireUsage(usage) : undefined,\n };\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { message: error.message, type: errorType(error.status), param: null, code: null } };\n}\n\nexport const openAiChat: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({ data: errorBody(error) }),\n};\n"]}
|
|
1
|
+
{"version":3,"file":"openAiChat.js","sourceRoot":"","sources":["../../src/wireProtocols/openAiChat.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,+FAA+F;AAC/F,yFAAyF;AAEzF,OAAO,EAAE,MAAM,EAAE,M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M,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9F,OAAO;QACL,EAAE,EAAE,YAAY,OAAO,CAAC,EAAE,EAAE;QAC5B,MAAM,EAAE,iBAAiB;QACzB,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,KAAK;QACL,OAAO,EAAE,CAAC;gBACR,KAAK,EAAE,CAAC;gBACR,OAAO,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE;gBACtG,aAAa,EAAE,cAAc,CAAC,YAAY,CAAC;gBAC3C,QAAQ,EAAE,IAAI;aACf,CAAC;QACF,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS;KAC5C,CAAC;AACJ,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;AACvG,CAAC;AAED,MAAM,CAAC,MAAM,UAAU,GAAiB;IACtC,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,KAAK,EAAE,SAAS;IAChB,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;CACrD,CAAC","sourcesContent":["// The OpenAI chat completions protocol, as the OpenAI SDK, LangChain's ChatOpenAI, LlamaIndex and\n// the Vercel AI SDK's `openai.chat()` speak it. Streamed answers go as `chat.completion.chunk`\n// events ending with `[DONE]`; tool calls and the finish reason come on the last chunks.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n ChatMessage, ChatResponse, ContentPart, FinishReason, JsonSchema, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport {\n EMPTY_PARAMETERS, errorType, filePart, parseToolArguments, toolNameOf, unsupported, userContent,\n} from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface WirePart {\n type: string;\n text?: string;\n refusal?: string;\n image_url?: string | { url: string };\n file?: { file_data?: string; filename?: string; file_id?: string };\n}\n\ninterface WireToolCall {\n id: string;\n function: { name: string; arguments?: string };\n}\n\ninterface WireMessage {\n role: string;\n content?: string | WirePart[] | null;\n tool_calls?: WireToolCall[];\n tool_call_id?: string;\n}\n\ninterface WireTool {\n type: string;\n function?: { name: string; description?: string; parameters?: JsonSchema };\n}\n\ninterface WireFormat {\n type: string;\n json_schema?: { name?: string; schema?: JsonSchema; strict?: boolean };\n}\n\ninterface ChatBody {\n messages?: WireMessage[];\n tools?: WireTool[];\n tool_choice?: string | { function: { name: string } };\n response_format?: WireFormat;\n max_tokens?: number;\n max_completion_tokens?: number;\n temperature?: number;\n top_p?: number;\n stop?: string | string[];\n n?: number;\n stream?: boolean;\n stream_options?: { include_usage?: boolean };\n}\n\nconst FINISH_REASONS: Record<FinishReason, string> = {\n stop: 'stop',\n length: 'length',\n toolCalls: 'tool_calls',\n contentFilter: 'content_filter',\n};\n\nfunction partOf(part: WirePart): ContentPart {\n if (part.type === 'text') {\n return { type: 'text', text: part.text ?? '' };\n }\n if (part.type === 'refusal') {\n return { type: 'text', text: part.refusal ?? '' };\n }\n if (part.type === 'image_url' && part.image_url) {\n return { type: 'image', url: typeof part.image_url === 'string' ? part.image_url : part.image_url.url };\n }\n if (part.type === 'file' && part.file) {\n return filePart(part.file.file_data, part.file.filename);\n }\n throw unsupported(`${part.type} content`);\n}\n\nfunction partsOf(content: WireMessage['content']): ContentPart[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).map(partOf);\n}\n\nfunction assistantMessage(message: WireMessage, names: Map<string, string>): ChatMessage {\n const toolCalls: ToolCall[] = (message.tool_calls ?? []).map((call) => ({\n id: call.id, name: call.function.name, arguments: parseToolArguments(call.function.arguments),\n }));\n toolCalls.forEach((call) => names.set(call.id, call.name));\n return { role: 'assistant', content: textOf(partsOf(message.content)), ...(toolCalls.length ? { toolCalls } : {}) };\n}\n\nfunction readMessages(messages: WireMessage[]): ChatMessage[] {\n const names = new Map<string, string>();\n return messages.map((message): ChatMessage => {\n switch (message.role) {\n case 'system':\n case 'developer':\n return { role: 'system', content: textOf(partsOf(message.content)) };\n case 'user':\n return { role: 'user', content: userContent(partsOf(message.content)) };\n case 'assistant':\n return assistantMessage(message, names);\n case 'tool': {\n const toolCallId = message.tool_call_id ?? '';\n const content = textOf(partsOf(message.content));\n return { role: 'tool', toolCallId, name: toolNameOf(names, toolCallId), content };\n }\n default:\n throw unsupported(`${message.role} messages`);\n }\n });\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type !== 'function' || !tool.function) {\n throw unsupported(`${tool.type} tools`);\n }\n const { name, description = '', parameters = EMPTY_PARAMETERS } = tool.function;\n return { name, description, inputSchema: parameters };\n });\n}\n\nfunction readToolChoice(choice: ChatBody['tool_choice']): ToolChoice | undefined {\n return typeof choice === 'object' ? { name: choice.function.name } : choice as ToolChoice | undefined;\n}\n\nfunction readFormat(format?: WireFormat): ResponseFormat | undefined {\n if (!format || format.type === 'text') {\n return undefined;\n }\n return { type: 'json', ...format.json_schema };\n}\n\nfunction read(body: Record<string, unknown>): WireRequest {\n const chat = body as ChatBody;\n if ((chat.n ?? 1) > 1) {\n throw unsupported('several choices per request');\n }\n return {\n request: {\n messages: readMessages(chat.messages ?? []),\n tools: readTools(chat.tools),\n options: {\n maxTokens: chat.max_completion_tokens ?? chat.max_tokens,\n temperature: chat.temperature,\n topP: chat.top_p,\n stop: typeof chat.stop === 'string' ? [chat.stop] : chat.stop,\n toolChoice: readToolChoice(chat.tool_choice),\n responseFormat: readFormat(chat.response_format),\n },\n },\n stream: chat.stream === true,\n includeUsage: chat.stream_options?.include_usage === true,\n };\n}\n\nfunction wireUsage(usage: Usage) {\n return {\n prompt_tokens: usage.inputTokens,\n completion_tokens: usage.outputTokens,\n total_tokens: usage.inputTokens + usage.outputTokens,\n prompt_tokens_details: { cached_tokens: usage.cachedInputTokens },\n };\n}\n\nfunction wireToolCall(call: ToolCall) {\n return { id: call.id, type: 'function', function: { name: call.name, arguments: JSON.stringify(call.arguments) } };\n}\n\nfunction chunk(context: AnswerContext, model: string, delta: Record<string, unknown>, finish: string | null = null) {\n return {\n id: `chatcmpl-${context.id}`,\n object: 'chat.completion.chunk',\n created: context.created,\n model,\n choices: [{ index: 0, delta, finish_reason: finish, logprobs: null }],\n };\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const answering = (await answer.started).model;\n write.send(chunk(context, answering, { role: 'assistant', content: '' }));\n for await (const text of answer.texts()) {\n write.send(chunk(context, answering, { content: text }));\n }\n const { message, finishReason, model, usage } = await answer.result;\n // One chunk per call, as OpenAI streams them.\n (message.toolCalls ?? []).forEach((call, index) => {\n write.send(chunk(context, model, { tool_calls: [{ index, ...wireToolCall(call) }] }));\n });\n write.send(chunk(context, model, {}, FINISH_REASONS[finishReason]));\n if (context.wire.includeUsage && usage) {\n write.send({ ...chunk(context, model, {}), choices: [], usage: wireUsage(usage) });\n }\n write.send('[DONE]');\n}\n\nfunction body({ message, finishReason, model, usage }: ChatResponse, context: AnswerContext) {\n const toolCalls = message.toolCalls?.length ? message.toolCalls.map(wireToolCall) : undefined;\n return {\n id: `chatcmpl-${context.id}`,\n object: 'chat.completion',\n created: context.created,\n model,\n choices: [{\n index: 0,\n message: { role: 'assistant', content: message.content || null, refusal: null, tool_calls: toolCalls },\n finish_reason: FINISH_REASONS[finishReason],\n logprobs: null,\n }],\n usage: usage ? wireUsage(usage) : undefined,\n };\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { message: error.message, type: errorType(error.status), param: null, code: null } };\n}\n\nexport const openAiChat: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({ data: errorBody(error) }),\n};\n"]}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// whole input. Streamed answers go as typed events: the message item and its text deltas, one item
|
|
4
4
|
// per tool call, then `response.completed` with the usage.
|
|
5
5
|
import { textOf } from "../chatContent.js";
|
|
6
|
-
import { EMPTY_PARAMETERS, errorType, parseToolArguments, toolNameOf, unsupported, userContent, } from "./wireProtocol.js";
|
|
6
|
+
import { EMPTY_PARAMETERS, errorType, filePart, parseToolArguments, toolNameOf, unsupported, userContent, } from "./wireProtocol.js";
|
|
7
7
|
function partOf(part) {
|
|
8
8
|
if (part.type === 'input_text' || part.type === 'output_text') {
|
|
9
9
|
return { type: 'text', text: part.text ?? '' };
|
|
@@ -14,6 +14,9 @@ function partOf(part) {
|
|
|
14
14
|
if (part.type === 'input_image' && part.image_url) {
|
|
15
15
|
return { type: 'image', url: part.image_url };
|
|
16
16
|
}
|
|
17
|
+
if (part.type === 'input_file') {
|
|
18
|
+
return filePart(part.file_data, part.filename);
|
|
19
|
+
}
|
|
17
20
|
throw unsupported(`${part.type} content`);
|
|
18
21
|
}
|
|
19
22
|
function partsOf(content) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openAiResponses.js","sourceRoot":"","sources":["../../src/wireProtocols/openAiResponses.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,+FAA+F;AAC/F,mGAAmG;AACnG,2DAA2D;AAE3D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQ3C,OAAO,EACL,gBAAg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,CAAC;IAChG,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,qBAAqB,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;AACzG,CAAC;AAED,SAAS,IAAI,CAAC,QAAsB,EAAE,OAAsB;IAC1D,OAAO,cAAc,CAAC,OAAO,EAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,EAAE,WAAW,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC;AAC3F,CAAC;AAED,SAAS,SAAS,CAAC,KAAyB;IAC1C,OAAO,EAAE,KAAK,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;AACvG,CAAC;AAED,MAAM,CAAC,MAAM,eAAe,GAAiB;IAC3C,IAAI;IACJ,MAAM;IACN,IAAI;IACJ,KAAK,EAAE,SAAS;IAChB,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACvB,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE;QAC3F,KAAK,EAAE,OAAO;KACf,CAAC;CACH,CAAC","sourcesContent":["// The OpenAI Responses protocol, the default path of the Vercel AI SDK's `openai()` models and of\n// the OpenAI SDK's `responses` API. The wallet keeps no conversation, so a request carries its\n// whole input. Streamed answers go as typed events: the message item and its text deltas, one item\n// per tool call, then `response.completed` with the usage.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n AssistantMessage, ChatMessage, ChatResponse, ContentPart, JsonSchema, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport {\n EMPTY_PARAMETERS, errorType, parseToolArguments, toolNameOf, unsupported, userContent,\n} from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface InputPart {\n type: string;\n text?: string;\n refusal?: string;\n image_url?: string;\n}\n\ninterface InputItem {\n type?: string;\n role?: string;\n content?: string | InputPart[];\n call_id?: string;\n name?: string;\n arguments?: string;\n output?: string | InputPart[];\n}\n\ninterface WireTool {\n type: string;\n name?: string;\n description?: string;\n parameters?: JsonSchema;\n}\n\ninterface ResponsesBody {\n input?: string | InputItem[];\n instructions?: string;\n tools?: WireTool[];\n tool_choice?: string | { type: string; name?: string };\n text?: { format?: { type: string; name?: string; schema?: JsonSchema; strict?: boolean } };\n max_output_tokens?: number;\n temperature?: number;\n top_p?: number;\n previous_response_id?: string;\n stream?: boolean;\n}\n\n// The conversation being read, with the name of each tool call for the results that answer it.\ninterface Reading {\n messages: ChatMessage[];\n names: Map<string, string>;\n}\n\nfunction partOf(part: InputPart): ContentPart {\n if (part.type === 'input_text' || part.type === 'output_text') {\n return { type: 'text', text: part.text ?? '' };\n }\n if (part.type === 'refusal') {\n return { type: 'text', text: part.refusal ?? '' };\n }\n if (part.type === 'input_image' && part.image_url) {\n return { type: 'image', url: part.image_url };\n }\n throw unsupported(`${part.type} content`);\n}\n\nfunction partsOf(content: string | InputPart[] | undefined): ContentPart[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).map(partOf);\n}\n\n// A function call joins the assistant turn just before it, as the provider produced them together.\nfunction readFunctionCall({ messages, names }: Reading, item: InputItem): void {\n const call: ToolCall = {\n id: item.call_id ?? '', name: item.name ?? '', arguments: parseToolArguments(item.arguments),\n };\n names.set(call.id, call.name);\n const last = messages.at(-1);\n if (last?.role === 'assistant') {\n last.toolCalls = [...(last.toolCalls ?? []), call];\n } else {\n messages.push({ role: 'assistant', content: '', toolCalls: [call] });\n }\n}\n\nfunction readMessage(item: InputItem): ChatMessage {\n const parts = partsOf(item.content);\n switch (item.role) {\n case 'system':\n case 'developer':\n return { role: 'system', content: textOf(parts) };\n case 'user':\n return { role: 'user', content: userContent(parts) };\n case 'assistant':\n return { role: 'assistant', content: textOf(parts) } satisfies AssistantMessage;\n default:\n throw unsupported(`${item.role} messages`);\n }\n}\n\n// Reasoning items hold the provider's own thinking, which another account cannot read.\nfunction readItem(reading: Reading, item: InputItem): void {\n if (item.type === 'function_call') {\n readFunctionCall(reading, item);\n } else if (item.type === 'function_call_output') {\n const toolCallId = item.call_id ?? '';\n const content = textOf(partsOf(item.output));\n reading.messages.push({ role: 'tool', toolCallId, name: toolNameOf(reading.names, toolCallId), content });\n } else if (item.type === undefined || item.type === 'message') {\n reading.messages.push(readMessage(item));\n } else if (item.type !== 'reasoning') {\n throw unsupported(`${item.type} input items`);\n }\n}\n\nfunction readInput(body: ResponsesBody): ChatMessage[] {\n const reading: Reading = { messages: [], names: new Map() };\n if (body.instructions) {\n reading.messages.push({ role: 'system', content: body.instructions });\n }\n const items = typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : body.input ?? [];\n items.forEach((item) => readItem(reading, item));\n return reading.messages;\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type !== 'function' || !tool.name) {\n throw unsupported(`${tool.type} tools`);\n }\n return { name: tool.name, description: tool.description ?? '', inputSchema: tool.parameters ?? EMPTY_PARAMETERS };\n });\n}\n\nfunction readToolChoice(choice: ResponsesBody['tool_choice']): ToolChoice | undefined {\n if (typeof choice !== 'object') {\n return choice as ToolChoice | undefined;\n }\n if (choice.type !== 'function' || !choice.name) {\n throw unsupported(`a ${choice.type} tool choice`);\n }\n return { name: choice.name };\n}\n\nfunction readFormat(format: NonNullable<ResponsesBody['text']>['format']): ResponseFormat | undefined {\n if (!format || format.type === 'text') {\n return undefined;\n }\n return { type: 'json', name: format.name, schema: format.schema, strict: format.strict };\n}\n\nfunction read(raw: Record<string, unknown>): WireRequest {\n const body = raw as ResponsesBody;\n if (body.previous_response_id) {\n throw unsupported('previous_response_id: send the whole conversation, AI Wallet keeps none');\n }\n return {\n request: {\n messages: readInput(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: body.max_output_tokens,\n temperature: body.temperature,\n topP: body.top_p,\n toolChoice: readToolChoice(body.tool_choice),\n responseFormat: readFormat(body.text?.format),\n },\n },\n stream: body.stream === true,\n };\n}\n\nfunction messageItem(id: string, text: string) {\n return {\n id, type: 'message', status: 'completed', role: 'assistant',\n content: [{ type: 'output_text', text, annotations: [] }],\n };\n}\n\nfunction functionCallItem(call: ToolCall) {\n return {\n id: `fc_${call.id}`, type: 'function_call', status: 'completed',\n call_id: call.id, name: call.name, arguments: JSON.stringify(call.arguments),\n };\n}\n\nfunction wireUsage(usage: Usage | undefined) {\n if (!usage) {\n return null;\n }\n const { inputTokens, outputTokens, cachedInputTokens } = usage;\n return {\n input_tokens: inputTokens,\n input_tokens_details: { cached_tokens: cachedInputTokens },\n output_tokens: outputTokens,\n total_tokens: inputTokens + outputTokens,\n };\n}\n\nfunction responseObject(context: AnswerContext, model: string, response?: ChatResponse, output: unknown[] = []) {\n const incomplete = response?.finishReason === 'length' || response?.finishReason === 'contentFilter';\n const reason = response?.finishReason === 'length' ? 'max_output_tokens' : 'content_filter';\n return {\n id: `resp_${context.id}`,\n object: 'response',\n created_at: context.created,\n status: response ? (incomplete ? 'incomplete' : 'completed') : 'in_progress',\n model,\n output,\n error: null,\n incomplete_details: incomplete ? { reason } : null,\n usage: wireUsage(response?.usage),\n };\n}\n\nfunction outputItems(context: AnswerContext, { message }: ChatResponse) {\n const text = message.content ? [messageItem(`msg_${context.id}`, message.content)] : [];\n return [...text, ...(message.toolCalls ?? []).map(functionCallItem)];\n}\n\n// Each event carries its type and a sequence number, as the provider numbers them.\nfunction eventSender(write: EventWriter) {\n let sequence = 0;\n return (type: string, fields: Record<string, unknown>) => {\n write.send({ type, sequence_number: sequence, ...fields }, type);\n sequence += 1;\n };\n}\n\nfunction writeMessageEnd(send: ReturnType<typeof eventSender>, id: string, text: string): void {\n const part = { type: 'output_text', text, annotations: [] };\n send('response.output_text.done', { item_id: id, output_index: 0, content_index: 0, text, logprobs: [] });\n send('response.content_part.done', { item_id: id, output_index: 0, content_index: 0, part });\n send('response.output_item.done', { output_index: 0, item: messageItem(id, text) });\n}\n\nfunction writeFunctionCall(send: ReturnType<typeof eventSender>, call: ToolCall, index: number): void {\n const item = functionCallItem(call);\n send('response.output_item.added', { output_index: index, item: { ...item, status: 'in_progress', arguments: '' } });\n send('response.function_call_arguments.delta', { item_id: item.id, output_index: index, delta: item.arguments });\n send('response.function_call_arguments.done', { item_id: item.id, output_index: index, arguments: item.arguments });\n send('response.output_item.done', { output_index: index, item });\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const send = eventSender(write);\n const id = `msg_${context.id}`;\n send('response.created', { response: responseObject(context, (await answer.started).model) });\n let streamed = false;\n for await (const delta of answer.texts()) {\n if (!streamed) {\n const part = { type: 'output_text', text: '', annotations: [] };\n const item = { ...messageItem(id, ''), status: 'in_progress', content: [] };\n send('response.output_item.added', { output_index: 0, item });\n send('response.content_part.added', { item_id: id, output_index: 0, content_index: 0, part });\n streamed = true;\n }\n send('response.output_text.delta', { item_id: id, output_index: 0, content_index: 0, delta, logprobs: [] });\n }\n const response = await answer.result;\n if (streamed) {\n writeMessageEnd(send, id, response.message.content);\n }\n const offset = streamed ? 1 : 0;\n (response.message.toolCalls ?? []).forEach((call, index) => writeFunctionCall(send, call, index + offset));\n const final = responseObject(context, response.model, response, outputItems(context, response));\n send(final.status === 'completed' ? 'response.completed' : 'response.incomplete', { response: final });\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n return responseObject(context, response.model, response, outputItems(context, response));\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { message: error.message, type: errorType(error.status), param: null, code: null } };\n}\n\nexport const openAiResponses: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({\n data: { type: 'error', code: errorType(error.status), message: error.message, param: null },\n event: 'error',\n }),\n};\n"]}
|
|
1
|
+
{"version":3,"file":"openAiResponses.js","sourceRoot":"","sources":["../../src/wireProtocols/openAiResponses.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,+FAA+F;AAC/F,mGAAmG;AACnG,2DAA2D;AAE3D,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAQ3C,OAAO,EACL,gBAAgB,EAAE,SAAS,EAAE,QAAQ,EAAE,kBAAkB,EAAE,UAAU,EAAE,WAAW,EAAE,WAAW,GAChG,MAAM,mBAAmB,CAAC;AAgD3B,SAAS,MAAM,CAAC,IAAe;IAC7B,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,IAAI,IAAI,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;QAC9D,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,EAAE,EAAE,CAAC;IACjD,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC5B,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,IAAI,EAAE,EAAE,CAAC;IACpD,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,KAAK,aAAa,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;QAClD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;IAChD,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;I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AI;IACJ,KAAK,EAAE,SAAS;IAChB,WAAW,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACvB,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE;QAC3F,KAAK,EAAE,OAAO;KACf,CAAC;CACH,CAAC","sourcesContent":["// The OpenAI Responses protocol, the default path of the Vercel AI SDK's `openai()` models and of\n// the OpenAI SDK's `responses` API. The wallet keeps no conversation, so a request carries its\n// whole input. Streamed answers go as typed events: the message item and its text deltas, one item\n// per tool call, then `response.completed` with the usage.\n\nimport { textOf } from '../chatContent.ts';\nimport type {\n AssistantMessage, ChatMessage, ChatResponse, ContentPart, JsonSchema, ResponseFormat, ToolCall, ToolChoice,\n ToolDefinition, Usage,\n} from '../types.ts';\nimport type { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\nimport {\n EMPTY_PARAMETERS, errorType, filePart, parseToolArguments, toolNameOf, unsupported, userContent,\n} from './wireProtocol.ts';\nimport type { AnswerContext, WireProtocol, WireRequest } from './wireProtocol.ts';\n\ninterface InputPart {\n type: string;\n text?: string;\n refusal?: string;\n image_url?: string;\n file_data?: string;\n filename?: string;\n}\n\ninterface InputItem {\n type?: string;\n role?: string;\n content?: string | InputPart[];\n call_id?: string;\n name?: string;\n arguments?: string;\n output?: string | InputPart[];\n}\n\ninterface WireTool {\n type: string;\n name?: string;\n description?: string;\n parameters?: JsonSchema;\n}\n\ninterface ResponsesBody {\n input?: string | InputItem[];\n instructions?: string;\n tools?: WireTool[];\n tool_choice?: string | { type: string; name?: string };\n text?: { format?: { type: string; name?: string; schema?: JsonSchema; strict?: boolean } };\n max_output_tokens?: number;\n temperature?: number;\n top_p?: number;\n previous_response_id?: string;\n stream?: boolean;\n}\n\n// The conversation being read, with the name of each tool call for the results that answer it.\ninterface Reading {\n messages: ChatMessage[];\n names: Map<string, string>;\n}\n\nfunction partOf(part: InputPart): ContentPart {\n if (part.type === 'input_text' || part.type === 'output_text') {\n return { type: 'text', text: part.text ?? '' };\n }\n if (part.type === 'refusal') {\n return { type: 'text', text: part.refusal ?? '' };\n }\n if (part.type === 'input_image' && part.image_url) {\n return { type: 'image', url: part.image_url };\n }\n if (part.type === 'input_file') {\n return filePart(part.file_data, part.filename);\n }\n throw unsupported(`${part.type} content`);\n}\n\nfunction partsOf(content: string | InputPart[] | undefined): ContentPart[] {\n if (typeof content === 'string') {\n return content ? [{ type: 'text', text: content }] : [];\n }\n return (content ?? []).map(partOf);\n}\n\n// A function call joins the assistant turn just before it, as the provider produced them together.\nfunction readFunctionCall({ messages, names }: Reading, item: InputItem): void {\n const call: ToolCall = {\n id: item.call_id ?? '', name: item.name ?? '', arguments: parseToolArguments(item.arguments),\n };\n names.set(call.id, call.name);\n const last = messages.at(-1);\n if (last?.role === 'assistant') {\n last.toolCalls = [...(last.toolCalls ?? []), call];\n } else {\n messages.push({ role: 'assistant', content: '', toolCalls: [call] });\n }\n}\n\nfunction readMessage(item: InputItem): ChatMessage {\n const parts = partsOf(item.content);\n switch (item.role) {\n case 'system':\n case 'developer':\n return { role: 'system', content: textOf(parts) };\n case 'user':\n return { role: 'user', content: userContent(parts) };\n case 'assistant':\n return { role: 'assistant', content: textOf(parts) } satisfies AssistantMessage;\n default:\n throw unsupported(`${item.role} messages`);\n }\n}\n\n// Reasoning items hold the provider's own thinking, which another account cannot read.\nfunction readItem(reading: Reading, item: InputItem): void {\n if (item.type === 'function_call') {\n readFunctionCall(reading, item);\n } else if (item.type === 'function_call_output') {\n const toolCallId = item.call_id ?? '';\n const content = textOf(partsOf(item.output));\n reading.messages.push({ role: 'tool', toolCallId, name: toolNameOf(reading.names, toolCallId), content });\n } else if (item.type === undefined || item.type === 'message') {\n reading.messages.push(readMessage(item));\n } else if (item.type !== 'reasoning') {\n throw unsupported(`${item.type} input items`);\n }\n}\n\nfunction readInput(body: ResponsesBody): ChatMessage[] {\n const reading: Reading = { messages: [], names: new Map() };\n if (body.instructions) {\n reading.messages.push({ role: 'system', content: body.instructions });\n }\n const items = typeof body.input === 'string' ? [{ role: 'user', content: body.input }] : body.input ?? [];\n items.forEach((item) => readItem(reading, item));\n return reading.messages;\n}\n\nfunction readTools(tools?: WireTool[]): ToolDefinition[] | undefined {\n return tools?.map((tool) => {\n if (tool.type !== 'function' || !tool.name) {\n throw unsupported(`${tool.type} tools`);\n }\n return { name: tool.name, description: tool.description ?? '', inputSchema: tool.parameters ?? EMPTY_PARAMETERS };\n });\n}\n\nfunction readToolChoice(choice: ResponsesBody['tool_choice']): ToolChoice | undefined {\n if (typeof choice !== 'object') {\n return choice as ToolChoice | undefined;\n }\n if (choice.type !== 'function' || !choice.name) {\n throw unsupported(`a ${choice.type} tool choice`);\n }\n return { name: choice.name };\n}\n\nfunction readFormat(format: NonNullable<ResponsesBody['text']>['format']): ResponseFormat | undefined {\n if (!format || format.type === 'text') {\n return undefined;\n }\n return { type: 'json', name: format.name, schema: format.schema, strict: format.strict };\n}\n\nfunction read(raw: Record<string, unknown>): WireRequest {\n const body = raw as ResponsesBody;\n if (body.previous_response_id) {\n throw unsupported('previous_response_id: send the whole conversation, AI Wallet keeps none');\n }\n return {\n request: {\n messages: readInput(body),\n tools: readTools(body.tools),\n options: {\n maxTokens: body.max_output_tokens,\n temperature: body.temperature,\n topP: body.top_p,\n toolChoice: readToolChoice(body.tool_choice),\n responseFormat: readFormat(body.text?.format),\n },\n },\n stream: body.stream === true,\n };\n}\n\nfunction messageItem(id: string, text: string) {\n return {\n id, type: 'message', status: 'completed', role: 'assistant',\n content: [{ type: 'output_text', text, annotations: [] }],\n };\n}\n\nfunction functionCallItem(call: ToolCall) {\n return {\n id: `fc_${call.id}`, type: 'function_call', status: 'completed',\n call_id: call.id, name: call.name, arguments: JSON.stringify(call.arguments),\n };\n}\n\nfunction wireUsage(usage: Usage | undefined) {\n if (!usage) {\n return null;\n }\n const { inputTokens, outputTokens, cachedInputTokens } = usage;\n return {\n input_tokens: inputTokens,\n input_tokens_details: { cached_tokens: cachedInputTokens },\n output_tokens: outputTokens,\n total_tokens: inputTokens + outputTokens,\n };\n}\n\nfunction responseObject(context: AnswerContext, model: string, response?: ChatResponse, output: unknown[] = []) {\n const incomplete = response?.finishReason === 'length' || response?.finishReason === 'contentFilter';\n const reason = response?.finishReason === 'length' ? 'max_output_tokens' : 'content_filter';\n return {\n id: `resp_${context.id}`,\n object: 'response',\n created_at: context.created,\n status: response ? (incomplete ? 'incomplete' : 'completed') : 'in_progress',\n model,\n output,\n error: null,\n incomplete_details: incomplete ? { reason } : null,\n usage: wireUsage(response?.usage),\n };\n}\n\nfunction outputItems(context: AnswerContext, { message }: ChatResponse) {\n const text = message.content ? [messageItem(`msg_${context.id}`, message.content)] : [];\n return [...text, ...(message.toolCalls ?? []).map(functionCallItem)];\n}\n\n// Each event carries its type and a sequence number, as the provider numbers them.\nfunction eventSender(write: EventWriter) {\n let sequence = 0;\n return (type: string, fields: Record<string, unknown>) => {\n write.send({ type, sequence_number: sequence, ...fields }, type);\n sequence += 1;\n };\n}\n\nfunction writeMessageEnd(send: ReturnType<typeof eventSender>, id: string, text: string): void {\n const part = { type: 'output_text', text, annotations: [] };\n send('response.output_text.done', { item_id: id, output_index: 0, content_index: 0, text, logprobs: [] });\n send('response.content_part.done', { item_id: id, output_index: 0, content_index: 0, part });\n send('response.output_item.done', { output_index: 0, item: messageItem(id, text) });\n}\n\nfunction writeFunctionCall(send: ReturnType<typeof eventSender>, call: ToolCall, index: number): void {\n const item = functionCallItem(call);\n send('response.output_item.added', { output_index: index, item: { ...item, status: 'in_progress', arguments: '' } });\n send('response.function_call_arguments.delta', { item_id: item.id, output_index: index, delta: item.arguments });\n send('response.function_call_arguments.done', { item_id: item.id, output_index: index, arguments: item.arguments });\n send('response.output_item.done', { output_index: index, item });\n}\n\nasync function stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void> {\n const send = eventSender(write);\n const id = `msg_${context.id}`;\n send('response.created', { response: responseObject(context, (await answer.started).model) });\n let streamed = false;\n for await (const delta of answer.texts()) {\n if (!streamed) {\n const part = { type: 'output_text', text: '', annotations: [] };\n const item = { ...messageItem(id, ''), status: 'in_progress', content: [] };\n send('response.output_item.added', { output_index: 0, item });\n send('response.content_part.added', { item_id: id, output_index: 0, content_index: 0, part });\n streamed = true;\n }\n send('response.output_text.delta', { item_id: id, output_index: 0, content_index: 0, delta, logprobs: [] });\n }\n const response = await answer.result;\n if (streamed) {\n writeMessageEnd(send, id, response.message.content);\n }\n const offset = streamed ? 1 : 0;\n (response.message.toolCalls ?? []).forEach((call, index) => writeFunctionCall(send, call, index + offset));\n const final = responseObject(context, response.model, response, outputItems(context, response));\n send(final.status === 'completed' ? 'response.completed' : 'response.incomplete', { response: final });\n}\n\nfunction body(response: ChatResponse, context: AnswerContext) {\n return responseObject(context, response.model, response, outputItems(context, response));\n}\n\nfunction errorBody(error: WalletRequestError) {\n return { error: { message: error.message, type: errorType(error.status), param: null, code: null } };\n}\n\nexport const openAiResponses: WireProtocol = {\n read,\n stream,\n body,\n error: errorBody,\n streamError: (error) => ({\n data: { type: 'error', code: errorType(error.status), message: error.message, param: null },\n event: 'error',\n }),\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ChatRequest, ChatResponse, ContentPart, JsonSchema } from '../types.ts';
|
|
1
|
+
import type { ChatRequest, ChatResponse, ContentPart, FilePart, JsonSchema } from '../types.ts';
|
|
2
2
|
import { WalletRequestError } from '../walletProvider.ts';
|
|
3
3
|
import type { EventWriter } from './eventStream.ts';
|
|
4
4
|
import type { WalletAnswer } from './walletAnswer.ts';
|
|
@@ -26,6 +26,7 @@ export interface WireProtocol {
|
|
|
26
26
|
export declare const EMPTY_PARAMETERS: JsonSchema;
|
|
27
27
|
export declare function errorType(status: number): string;
|
|
28
28
|
export declare function unsupported(what: string): WalletRequestError;
|
|
29
|
+
export declare function filePart(url: string | undefined, name: string | undefined): FilePart;
|
|
29
30
|
export declare function userContent(parts: ContentPart[]): string | ContentPart[];
|
|
30
31
|
export declare function parseToolArguments(raw: string | undefined): Record<string, unknown>;
|
|
31
32
|
export declare function toolNameOf(names: Map<string, string>, callId: string): string;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// What every protocol an AI SDK speaks provides to `AiConnect.fetch`: reading the SDK's request
|
|
2
2
|
// into the wallet's chat format, and writing the wallet's answer back the way the provider's own
|
|
3
3
|
// servers write it, streamed or whole, with errors in the provider's shape.
|
|
4
|
+
import { inlineData, isTextFile, PDF_TYPE } from "../chatContent.js";
|
|
4
5
|
import { WalletRequestError } from "../walletProvider.js";
|
|
5
6
|
// A function the SDK declares without parameters takes an empty object.
|
|
6
7
|
export const EMPTY_PARAMETERS = { type: 'object', properties: {} };
|
|
@@ -18,7 +19,18 @@ export function errorType(status) {
|
|
|
18
19
|
export function unsupported(what) {
|
|
19
20
|
return new WalletRequestError(`AI Wallet does not take ${what}`, 400);
|
|
20
21
|
}
|
|
21
|
-
// A
|
|
22
|
+
// A file an SDK attached as a `data:` URL: a PDF or a text file, the files the chat format carries.
|
|
23
|
+
export function filePart(url, name) {
|
|
24
|
+
const inline = url ? inlineData(url) : null;
|
|
25
|
+
if (!url || !inline) {
|
|
26
|
+
throw unsupported('files given by address or by id');
|
|
27
|
+
}
|
|
28
|
+
if (inline.mediaType !== PDF_TYPE && !isTextFile(inline.mediaType)) {
|
|
29
|
+
throw unsupported(`${inline.mediaType} files`);
|
|
30
|
+
}
|
|
31
|
+
return { type: 'file', url, name: name || 'attachment' };
|
|
32
|
+
}
|
|
33
|
+
// A single text stays a string; images, files or several parts stay parts.
|
|
22
34
|
export function userContent(parts) {
|
|
23
35
|
return parts.length === 1 && parts[0].type === 'text' ? parts[0].text : parts;
|
|
24
36
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wireProtocol.js","sourceRoot":"","sources":["../../src/wireProtocols/wireProtocol.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,iGAAiG;AACjG,4EAA4E;
|
|
1
|
+
{"version":3,"file":"wireProtocol.js","sourceRoot":"","sources":["../../src/wireProtocols/wireProtocol.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,iGAAiG;AACjG,4EAA4E;AAE5E,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAErE,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAiC1D,wEAAwE;AACxE,MAAM,CAAC,MAAM,gBAAgB,GAAe,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;AAE/E,MAAM,WAAW,GAA2B;IAC1C,GAAG,EAAE,uBAAuB;IAC5B,GAAG,EAAE,sBAAsB;IAC3B,GAAG,EAAE,kBAAkB;IACvB,GAAG,EAAE,iBAAiB;IACtB,GAAG,EAAE,kBAAkB;CACxB,CAAC;AAEF,yDAAyD;AACzD,MAAM,UAAU,SAAS,CAAC,MAAc;IACtC,OAAO,WAAW,CAAC,MAAM,CAAC,IAAI,WAAW,CAAC;AAC5C,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,IAAI,kBAAkB,CAAC,2BAA2B,IAAI,EAAE,EAAE,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,oGAAoG;AACpG,MAAM,UAAU,QAAQ,CAAC,GAAuB,EAAE,IAAwB;IACxE,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC5C,IAAI,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;QACpB,MAAM,WAAW,CAAC,iCAAiC,CAAC,CAAC;IACvD,CAAC;IACD,IAAI,MAAM,CAAC,SAAS,KA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chat format, and writing the wallet's answer back the way the provider's own\n// servers write it, streamed or whole, with errors in the provider's shape.\n\nimport { inlineData, isTextFile, PDF_TYPE } from '../chatContent.ts';\nimport type { ChatRequest, ChatResponse, ContentPart, FilePart, JsonSchema } from '../types.ts';\nimport { WalletRequestError } from '../walletProvider.ts';\nimport type { EventWriter } from './eventStream.ts';\nimport type { WalletAnswer } from './walletAnswer.ts';\n\nexport interface WireRequest {\n request: Pick<ChatRequest, 'messages' | 'tools' | 'options'>;\n stream: boolean;\n // OpenAI streams the usage only to a request that asks for it.\n includeUsage?: boolean;\n}\n\n// The answer being written: its id, its creation time in seconds and the request it answers. A\n// stream reads the model that answers from the answer's start.\nexport interface AnswerContext {\n id: string;\n created: number;\n wire: WireRequest;\n}\n\nexport interface StreamError {\n data: unknown;\n event?: string;\n}\n\nexport interface WireProtocol {\n read(body: Record<string, unknown>, url: URL): WireRequest;\n stream(answer: WalletAnswer, write: EventWriter, context: AnswerContext): Promise<void>;\n body(response: ChatResponse, context: AnswerContext): unknown;\n error(error: WalletRequestError): unknown;\n // How the protocol reports a failure after the stream started; without it the stream breaks.\n streamError?(error: WalletRequestError): StreamError;\n}\n\n// A function the SDK declares without parameters takes an empty object.\nexport const EMPTY_PARAMETERS: JsonSchema = { type: 'object', properties: {} };\n\nconst ERROR_TYPES: Record<number, string> = {\n 400: 'invalid_request_error',\n 401: 'authentication_error',\n 403: 'permission_error',\n 404: 'not_found_error',\n 429: 'rate_limit_error',\n};\n\n// The error type OpenAI and Anthropic name for a status.\nexport function errorType(status: number): string {\n return ERROR_TYPES[status] ?? 'api_error';\n}\n\nexport function unsupported(what: string): WalletRequestError {\n return new WalletRequestError(`AI Wallet does not take ${what}`, 400);\n}\n\n// A file an SDK attached as a `data:` URL: a PDF or a text file, the files the chat format carries.\nexport function filePart(url: string | undefined, name: string | undefined): FilePart {\n const inline = url ? inlineData(url) : null;\n if (!url || !inline) {\n throw unsupported('files given by address or by id');\n }\n if (inline.mediaType !== PDF_TYPE && !isTextFile(inline.mediaType)) {\n throw unsupported(`${inline.mediaType} files`);\n }\n return { type: 'file', url, name: name || 'attachment' };\n}\n\n// A single text stays a string; images, files or several parts stay parts.\nexport function userContent(parts: ContentPart[]): string | ContentPart[] {\n return parts.length === 1 && parts[0].type === 'text' ? parts[0].text : parts;\n}\n\nexport function parseToolArguments(raw: string | undefined): Record<string, unknown> {\n if (!raw?.trim()) {\n return {};\n }\n try {\n return JSON.parse(raw) as Record<string, unknown>;\n } catch {\n throw new WalletRequestError(`Tool call arguments are not JSON: ${raw.slice(0, 100)}`, 400);\n }\n}\n\n// The name of the tool a result answers, read from the call earlier in the conversation.\nexport function toolNameOf(names: Map<string, string>, callId: string): string {\n const name = names.get(callId);\n if (!name) {\n throw new WalletRequestError(`A tool result answers ${callId}, which no earlier tool call made`, 400);\n }\n return name;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tensorpass/aiconnect",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "Headless SDK: connect a visitor's own AI account and run the site's tools with it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -18,6 +18,10 @@
|
|
|
18
18
|
"types": "./dist/guards/index.d.ts",
|
|
19
19
|
"default": "./dist/guards/index.js"
|
|
20
20
|
},
|
|
21
|
+
"./attachments": {
|
|
22
|
+
"types": "./dist/attachments/index.d.ts",
|
|
23
|
+
"default": "./dist/attachments/index.js"
|
|
24
|
+
},
|
|
21
25
|
"./callback": {
|
|
22
26
|
"types": "./dist/callback.d.ts",
|
|
23
27
|
"default": "./dist/callback.js"
|
|
@@ -36,7 +40,8 @@
|
|
|
36
40
|
"build": "rm -rf dist tsconfig.tsbuildinfo tsconfig.cli.tsbuildinfo && tsc -b tsconfig.json tsconfig.cli.json"
|
|
37
41
|
},
|
|
38
42
|
"dependencies": {
|
|
39
|
-
"@modelcontextprotocol/client": "^2.4.0"
|
|
43
|
+
"@modelcontextprotocol/client": "^2.4.0",
|
|
44
|
+
"pdfjs-dist": "^6.5.438"
|
|
40
45
|
},
|
|
41
46
|
"devDependencies": {
|
|
42
47
|
"@ai-sdk/anthropic": "^4.0.99",
|