@charivo/llm 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/{chunk-N2ILPUIF.mjs → chunk-64OO6OAH.mjs} +16 -4
- package/dist/chunk-64OO6OAH.mjs.map +1 -0
- package/dist/gemini/index.js +14 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/index.mjs +1 -1
- package/dist/openai/index.js +14 -2
- package/dist/openai/index.js.map +1 -1
- package/dist/openai/index.mjs +1 -1
- package/dist/openclaw/index.js +14 -2
- package/dist/openclaw/index.js.map +1 -1
- package/dist/openclaw/index.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-N2ILPUIF.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -11,6 +11,10 @@ It wraps an `LLMClient` implementation from another package.
|
|
|
11
11
|
pnpm add @charivo/llm
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
+
Requires Node.js 22 or newer. This package depends on the `openai` SDK v7,
|
|
15
|
+
whose own `engines` field declares that floor, so it applies wherever
|
|
16
|
+
`@charivo/llm` is installed — not only when you import `@charivo/llm/openai`.
|
|
17
|
+
|
|
14
18
|
## Usage
|
|
15
19
|
|
|
16
20
|
```ts
|
|
@@ -69,7 +69,14 @@ function toLLMToolCall(raw) {
|
|
|
69
69
|
'LLM tool call is missing a non-empty string "id"'
|
|
70
70
|
);
|
|
71
71
|
}
|
|
72
|
-
const
|
|
72
|
+
const type = raw.type;
|
|
73
|
+
if (type !== void 0 && type !== "function") {
|
|
74
|
+
throw new CharivoProviderError(
|
|
75
|
+
`LLM tool call "${id}" has unsupported type "${String(type)}"; only "function" tool calls are supported`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
const fn = isPlainObject(raw.function) ? raw.function : {};
|
|
79
|
+
const name = fn.name;
|
|
73
80
|
if (typeof name !== "string" || name.length === 0) {
|
|
74
81
|
throw new CharivoProviderError(
|
|
75
82
|
`LLM tool call "${id}" is missing a non-empty string "function.name"`
|
|
@@ -78,10 +85,15 @@ function toLLMToolCall(raw) {
|
|
|
78
85
|
return {
|
|
79
86
|
id,
|
|
80
87
|
name,
|
|
81
|
-
arguments: parseToolArguments(name,
|
|
88
|
+
arguments: parseToolArguments(name, fn.arguments)
|
|
82
89
|
};
|
|
83
90
|
}
|
|
84
91
|
function parseToolArguments(name, rawArguments) {
|
|
92
|
+
if (typeof rawArguments !== "string") {
|
|
93
|
+
throw new CharivoProviderError(
|
|
94
|
+
`LLM tool call "${name}" has unparsable "function.arguments"`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
85
97
|
let parsed;
|
|
86
98
|
try {
|
|
87
99
|
parsed = JSON.parse(rawArguments);
|
|
@@ -103,5 +115,5 @@ function isPlainObject(value) {
|
|
|
103
115
|
}
|
|
104
116
|
|
|
105
117
|
export { toLLMToolResponse, toOpenAIChatMessages, toOpenAITools };
|
|
106
|
-
//# sourceMappingURL=chunk-
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
118
|
+
//# sourceMappingURL=chunk-64OO6OAH.mjs.map
|
|
119
|
+
//# sourceMappingURL=chunk-64OO6OAH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/openai-tool-format.ts"],"names":[],"mappings":";;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,UAAA;AAAA,UACtB,SAAS,OAAA,CAAQ;AAAA,SACnB;AAAA,MACF,KAAK,WAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,WAAA;AAAA,UACN,SAAS,OAAA,CAAQ,OAAA;AAAA,UACjB,GAAI,OAAA,CAAQ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AACzB,EAAA,IAAI,OAAO,iBAAiB,QAAA,EAAU;AACpC,IAAA,MAAM,IAAI,oBAAA;AAAA,MACR,kBAAkB,IAAI,CAAA,qCAAA;AAAA,KACxB;AAAA,EACF;AAEA,EAAA,IAAI,MAAA;AAEJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,YAAY,CAAA;AAAA,EAClC,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAI,oBAAA;AAAA,MACR,kBAAkB,IAAI,CAAA,qCAAA,CAAA;AAAA,MACtB,EAAE,KAAA,EAAO,KAAA,YAAiB,KAAA,GAAQ,QAAQ,MAAA;AAAU,KACtD;AAAA,EACF;AAEA,EAAA,IAAI,OAAO,WAAW,QAAA,IAAY,MAAA,KAAW,QAAQ,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,EAAG;AAC1E,IAAA,MAAM,IAAI,oBAAA;AAAA,MACR,kBAAkB,IAAI,CAAA,qDAAA;AAAA,KACxB;AAAA,EACF;AAEA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,cAAc,KAAA,EAAkD;AACvE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E","file":"chunk-64OO6OAH.mjs","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n // `ChatCompletionMessageToolCall` is a union of a function and a custom tool\n // call, and `type` is its discriminator. Only function calls map onto\n // `LLMToolCall`, so a custom call is rejected for what it is rather than for\n // the `function` member it was never going to carry.\n // A gateway that omits `type` altogether still reaches the `function` checks\n // below, which is how this parser behaved before the union existed. Only a\n // type that is present and names something else is refused.\n const type = raw.type;\n if (type !== undefined && type !== \"function\") {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" has unsupported type \"${String(type)}\"; only \"function\" tool calls are supported`,\n );\n }\n\n // Past the discriminator the member is still read as untrusted data: this\n // function's stance is that the SDK types promise more than a gateway\n // delivers, so the checks below stay authoritative.\n const fn: Record<string, unknown> = isPlainObject(raw.function)\n ? raw.function\n : {};\n\n const name = fn.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, fn.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: unknown,\n): Record<string, unknown> {\n if (typeof rawArguments !== \"string\") {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n );\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|
package/dist/gemini/index.js
CHANGED
|
@@ -76,7 +76,14 @@ function toLLMToolCall(raw) {
|
|
|
76
76
|
'LLM tool call is missing a non-empty string "id"'
|
|
77
77
|
);
|
|
78
78
|
}
|
|
79
|
-
const
|
|
79
|
+
const type = raw.type;
|
|
80
|
+
if (type !== void 0 && type !== "function") {
|
|
81
|
+
throw new core.CharivoProviderError(
|
|
82
|
+
`LLM tool call "${id}" has unsupported type "${String(type)}"; only "function" tool calls are supported`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const fn = isPlainObject(raw.function) ? raw.function : {};
|
|
86
|
+
const name = fn.name;
|
|
80
87
|
if (typeof name !== "string" || name.length === 0) {
|
|
81
88
|
throw new core.CharivoProviderError(
|
|
82
89
|
`LLM tool call "${id}" is missing a non-empty string "function.name"`
|
|
@@ -85,10 +92,15 @@ function toLLMToolCall(raw) {
|
|
|
85
92
|
return {
|
|
86
93
|
id,
|
|
87
94
|
name,
|
|
88
|
-
arguments: parseToolArguments(name,
|
|
95
|
+
arguments: parseToolArguments(name, fn.arguments)
|
|
89
96
|
};
|
|
90
97
|
}
|
|
91
98
|
function parseToolArguments(name, rawArguments) {
|
|
99
|
+
if (typeof rawArguments !== "string") {
|
|
100
|
+
throw new core.CharivoProviderError(
|
|
101
|
+
`LLM tool call "${name}" has unparsable "function.arguments"`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
92
104
|
let parsed;
|
|
93
105
|
try {
|
|
94
106
|
parsed = JSON.parse(rawArguments);
|
package/dist/gemini/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai-tool-format.ts","../../src/gemini/provider.ts","../../src/gemini/index.ts"],"names":["CharivoProviderError","CharivoStateError","OpenAI","toCharivoError","CharivoTimeoutError"],"mappings":";;;;;;;;;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,U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MAAA,UAAA,CAAW,KAAA,EAAM;AACjB,MAAA,MAAA,CAAO,IAAIC,wBAAA,CAAoB,cAAc,CAAC,CAAA;AAAA,IAChD,GAAG,kBAAkB,CAAA;AAAA,EACvB,CAAC,CAAA;AAED,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,QAAQ,IAAA,CAAK,CAAC,YAAY,UAAA,CAAW,MAAM,CAAA,EAAG,cAAc,CAAC,CAAA;AAAA,EAC5E,CAAA,SAAE;AACA,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,YAAA,CAAa,SAAS,CAAA;AAAA,IACxB;AAAA,EACF;AACF;;;AC7KA,IAAM,kBAAN,MAA2C;AAAA,EACjC,QAAA;AAAA,EAER,YAAY,MAAA,EAA+B;AAGzC,IAAA,IAAA,CAAK,WAAW,uBAAA,CAAwB;AAAA,MACtC,GAAG,MAAA;AAAA,MACH,uBAAA,EAAyB;AAAA,KAC1B,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,KAAK,QAAA,EAAyC;AAElD,IAAA,MAAM,gBAAA,GAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,iBAAiB,QAAQ,CAAA;AAEtE,IAAA,OAAO,gBAAA;AAAA,EACT;AAAA,EAEA,MAAM,aAAA,CACJ,QAAA,EACA,KAAA,EAC0B;AAC1B,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,yBAAA,CAA0B,QAAA,EAAU,KAAK,CAAA;AAAA,EAChE;AACF,CAAA;AAEO,SAAS,sBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,gBAAgB,MAAM,CAAA;AACnC","file":"index.js","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n const name = raw.function?.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, raw.function.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: string,\n): Record<string, unknown> {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n CharivoTimeoutError,\n LLMProvider,\n toCharivoError,\n type LLMMessage,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport {\n toLLMToolResponse,\n toOpenAIChatMessages,\n toOpenAITools,\n} from \"../openai-tool-format\";\n\nconst GEMINI_BASE_URL =\n \"https://generativelanguage.googleapis.com/v1beta/openai/\";\nconst DEFAULT_MODEL = \"gemini-3.5-flash-lite\";\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** Sent in place of the real thought signature Gemini returned; see `toGeminiChatMessages`. */\nconst THOUGHT_SIGNATURE_SKIP = \"skip_thought_signature_validator\";\n\nexport interface GeminiLLMConfig {\n apiKey: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n dangerouslyAllowBrowser?: boolean;\n}\n\ntype GeminiToolCall = OpenAI.ChatCompletionMessageToolCall & {\n extra_content?: { google: { thought_signature: string } };\n};\n\n/**\n * `toOpenAIChatMessages`'s output widened so an assistant tool-call message can\n * carry Gemini's `extra_content.google.thought_signature` on its first tool\n * call, a field `openai`'s `ChatCompletionMessageToolCall` type does not model.\n */\ntype GeminiChatMessage =\n | Exclude<\n OpenAI.ChatCompletionMessageParam,\n OpenAI.ChatCompletionAssistantMessageParam\n >\n | (Omit<OpenAI.ChatCompletionAssistantMessageParam, \"tool_calls\"> & {\n tool_calls?: GeminiToolCall[];\n });\n\n/**\n * Gemini 3 answers HTTP 400 (\"Function call is missing a thought_signature in\n * functionCall parts\") when a resent assistant `tool_calls` turn lacks the\n * `thought_signature` Gemini attached to its first call. `LLMToolCall` has no\n * field for the real signature Gemini returned, so this provider sends a\n * documented skip placeholder instead and loses reasoning continuity across\n * tool rounds.\n */\nexport class GeminiLLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature?: number;\n private maxTokens: number;\n\n constructor(config: GeminiLLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"Gemini LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.apiKey,\n baseURL: GEMINI_BASE_URL,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || DEFAULT_MODEL;\n this.temperature = config.temperature;\n this.maxTokens = config.maxTokens || 1000;\n }\n\n async generateResponse(messages: LLMMessage[]): Promise<string> {\n try {\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toGeminiChatMessages(messages),\n ...(this.temperature !== undefined\n ? { temperature: this.temperature }\n : {}),\n max_tokens: this.maxTokens,\n },\n { signal },\n ),\n `Gemini LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"Gemini LLM request failed\");\n }\n }\n\n async generateResponseWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n try {\n const openAITools = toOpenAITools(tools);\n\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toGeminiChatMessages(messages),\n ...(this.temperature !== undefined\n ? { temperature: this.temperature }\n : {}),\n max_tokens: this.maxTokens,\n ...(openAITools ? { tools: openAITools } : {}),\n },\n { signal },\n ),\n `Gemini LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return toLLMToolResponse(completion.choices[0]?.message);\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"Gemini LLM request failed\");\n }\n }\n}\n\nexport function createGeminiLLMProvider(\n config: GeminiLLMConfig,\n): GeminiLLMProvider {\n return new GeminiLLMProvider(config);\n}\n\n/**\n * Stamps the documented skip placeholder for `thought_signature` onto only\n * `tool_calls[0]` of each assistant tool-call message: Gemini attaches the real\n * signature to the first call of a parallel group, and every other message\n * (including `tool_calls[1..]`) is left as `toOpenAIChatMessages` produced it.\n */\nfunction toGeminiChatMessages(messages: LLMMessage[]): GeminiChatMessage[] {\n return toOpenAIChatMessages(messages).map((message) => {\n // `role: \"tool\"` messages pass through unchanged, with no `name` field: the\n // OpenAI-compatible endpoint resolves the function from `tool_call_id`\n // (verified across sequential and parallel tool rounds). `name` is a\n // requirement of the native `functionResponse` / Interactions surfaces, not this one.\n if (message.role !== \"assistant\" || !message.tool_calls?.length) {\n return message;\n }\n\n return {\n ...message,\n tool_calls: message.tool_calls.map((toolCall, index) =>\n index === 0\n ? {\n ...toolCall,\n extra_content: {\n google: { thought_signature: THOUGHT_SIGNATURE_SKIP },\n },\n }\n : toolCall,\n ),\n };\n });\n}\n\n/**\n * Aborts the underlying SDK request on timeout instead of only abandoning the\n * wrapper promise: the SDK stops waiting and stops retrying, and the aborted\n * request becomes a cancellation request to the server. Work Gemini already\n * accepted before the abort may still be billed.\n */\nasync function withTimeout<T>(\n makeRequest: (signal: AbortSignal) => Promise<T>,\n timeoutMessage: string,\n): Promise<T> {\n const controller = new AbortController();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const timeoutPromise = new Promise<T>((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new CharivoTimeoutError(timeoutMessage));\n }, REQUEST_TIMEOUT_MS);\n });\n\n try {\n return await Promise.race([makeRequest(controller.signal), timeoutPromise]);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n}\n","import type {\n LLMClient,\n LLMMessage,\n LLMToolResponse,\n ToolDefinition,\n} from \"@charivo/core\";\nimport {\n createGeminiLLMProvider,\n GeminiLLMConfig,\n GeminiLLMProvider,\n} from \"./provider\";\n\nexport {\n createGeminiLLMProvider,\n GeminiLLMProvider,\n type GeminiLLMConfig,\n} from \"./provider\";\n\n// Use GeminiLLMConfig directly\nexport type GeminiLLMClientConfig = GeminiLLMConfig;\n\n/**\n * Gemini LLM Client - Stateless client that wraps the Gemini provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The API key is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass GeminiLLMClient implements LLMClient {\n private provider: GeminiLLMProvider;\n\n constructor(config: GeminiLLMClientConfig) {\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createGeminiLLMProvider({\n ...config,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(messages: LLMMessage[]): Promise<string> {\n // Generate a response using the provider\n const assistantMessage = await this.provider.generateResponse(messages);\n\n return assistantMessage;\n }\n\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n return this.provider.generateResponseWithTools(messages, tools);\n }\n}\n\nexport function createGeminiLLMClient(\n config: GeminiLLMClientConfig,\n): LLMClient {\n return new GeminiLLMClient(config);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/openai-tool-format.ts","../../src/gemini/provider.ts","../../src/gemini/index.ts"],"names":["CharivoProviderError","CharivoStateError","OpenAI","toCharivoError","CharivoTimeoutError"],"mappings":";;;;;;;;;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,UAAA;AAAA,UACtB,SAAS,OAAA,CAAQ;AAAA,SACnB;AAAA,MACF,KAAK,WAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,WAAA;AAAA,UACN,SAAS,OAAA,CAAQ,OAAA;AAAA,UACjB,GAAI,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,UAAU,MAAA,GAAS,CAAA,GAChD,EAAE,UAAA,EAAY,QAAQ,SAAA,CAAU,GAAA,CAAI,gBAAgB,CAAA,KACpD;AAAC,SACP;AAAA,MACF,KAAK,QAAA;AAAA,MACL,KAAK,MAAA;AACH,QAAA,OAAO,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA;AAC1D,EACF,CAAC,CAAA;AACH;AAOO,SAAS,cACd,KAAA,EACyC;AACzC,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,MAAU;AAAA,IAC1B,IAAA,EAAM,UAAA;AAAA,IACN,QAAA,EAAU;AAAA,MACR,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,aAAa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IAAA,IAAI,SAAA,EAAW;AACb,MAAA,YAAA,CAAa,SAAS,CAAA;AAAA,IACxB;AAAA,EACF;AACF;;;AC7KA,IAAM,kBAAN,MAA2C;AAAA,EACjC,QAAA;AAAA,EAER,YAAY,MAAA,EAA+B;AAGzC,IAAA,IAAA,CAAK,WAAW,uBAAA,CAAwB;AAAA,MACtC,GAAG,MAAA;AAAA,MACH,uBAAA,EAAyB;AAAA,KAC1B,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,KAAK,QAAA,EAAyC;AAElD,IAAA,MAAM,gBAAA,GAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,iBAAiB,QAAQ,CAAA;AAEtE,IAAA,OAAO,gBAAA;AAAA,EACT;AAAA,EAEA,MAAM,aAAA,CACJ,QAAA,EACA,KAAA,EAC0B;AAC1B,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,yBAAA,CAA0B,QAAA,EAAU,KAAK,CAAA;AAAA,EAChE;AACF,CAAA;AAEO,SAAS,sBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,gBAAgB,MAAM,CAAA;AACnC","file":"index.js","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n // `ChatCompletionMessageToolCall` is a union of a function and a custom tool\n // call, and `type` is its discriminator. Only function calls map onto\n // `LLMToolCall`, so a custom call is rejected for what it is rather than for\n // the `function` member it was never going to carry.\n // A gateway that omits `type` altogether still reaches the `function` checks\n // below, which is how this parser behaved before the union existed. Only a\n // type that is present and names something else is refused.\n const type = raw.type;\n if (type !== undefined && type !== \"function\") {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" has unsupported type \"${String(type)}\"; only \"function\" tool calls are supported`,\n );\n }\n\n // Past the discriminator the member is still read as untrusted data: this\n // function's stance is that the SDK types promise more than a gateway\n // delivers, so the checks below stay authoritative.\n const fn: Record<string, unknown> = isPlainObject(raw.function)\n ? raw.function\n : {};\n\n const name = fn.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, fn.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: unknown,\n): Record<string, unknown> {\n if (typeof rawArguments !== \"string\") {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n );\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n CharivoTimeoutError,\n LLMProvider,\n toCharivoError,\n type LLMMessage,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport {\n toLLMToolResponse,\n toOpenAIChatMessages,\n toOpenAITools,\n} from \"../openai-tool-format\";\n\nconst GEMINI_BASE_URL =\n \"https://generativelanguage.googleapis.com/v1beta/openai/\";\nconst DEFAULT_MODEL = \"gemini-3.5-flash-lite\";\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n/** Sent in place of the real thought signature Gemini returned; see `toGeminiChatMessages`. */\nconst THOUGHT_SIGNATURE_SKIP = \"skip_thought_signature_validator\";\n\nexport interface GeminiLLMConfig {\n apiKey: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n dangerouslyAllowBrowser?: boolean;\n}\n\ntype GeminiToolCall = OpenAI.ChatCompletionMessageToolCall & {\n extra_content?: { google: { thought_signature: string } };\n};\n\n/**\n * `toOpenAIChatMessages`'s output widened so an assistant tool-call message can\n * carry Gemini's `extra_content.google.thought_signature` on its first tool\n * call, a field `openai`'s `ChatCompletionMessageToolCall` type does not model.\n */\ntype GeminiChatMessage =\n | Exclude<\n OpenAI.ChatCompletionMessageParam,\n OpenAI.ChatCompletionAssistantMessageParam\n >\n | (Omit<OpenAI.ChatCompletionAssistantMessageParam, \"tool_calls\"> & {\n tool_calls?: GeminiToolCall[];\n });\n\n/**\n * Gemini 3 answers HTTP 400 (\"Function call is missing a thought_signature in\n * functionCall parts\") when a resent assistant `tool_calls` turn lacks the\n * `thought_signature` Gemini attached to its first call. `LLMToolCall` has no\n * field for the real signature Gemini returned, so this provider sends a\n * documented skip placeholder instead and loses reasoning continuity across\n * tool rounds.\n */\nexport class GeminiLLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature?: number;\n private maxTokens: number;\n\n constructor(config: GeminiLLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"Gemini LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.apiKey,\n baseURL: GEMINI_BASE_URL,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || DEFAULT_MODEL;\n this.temperature = config.temperature;\n this.maxTokens = config.maxTokens || 1000;\n }\n\n async generateResponse(messages: LLMMessage[]): Promise<string> {\n try {\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toGeminiChatMessages(messages),\n ...(this.temperature !== undefined\n ? { temperature: this.temperature }\n : {}),\n max_tokens: this.maxTokens,\n },\n { signal },\n ),\n `Gemini LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"Gemini LLM request failed\");\n }\n }\n\n async generateResponseWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n try {\n const openAITools = toOpenAITools(tools);\n\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toGeminiChatMessages(messages),\n ...(this.temperature !== undefined\n ? { temperature: this.temperature }\n : {}),\n max_tokens: this.maxTokens,\n ...(openAITools ? { tools: openAITools } : {}),\n },\n { signal },\n ),\n `Gemini LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return toLLMToolResponse(completion.choices[0]?.message);\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"Gemini LLM request failed\");\n }\n }\n}\n\nexport function createGeminiLLMProvider(\n config: GeminiLLMConfig,\n): GeminiLLMProvider {\n return new GeminiLLMProvider(config);\n}\n\n/**\n * Stamps the documented skip placeholder for `thought_signature` onto only\n * `tool_calls[0]` of each assistant tool-call message: Gemini attaches the real\n * signature to the first call of a parallel group, and every other message\n * (including `tool_calls[1..]`) is left as `toOpenAIChatMessages` produced it.\n */\nfunction toGeminiChatMessages(messages: LLMMessage[]): GeminiChatMessage[] {\n return toOpenAIChatMessages(messages).map((message) => {\n // `role: \"tool\"` messages pass through unchanged, with no `name` field: the\n // OpenAI-compatible endpoint resolves the function from `tool_call_id`\n // (verified across sequential and parallel tool rounds). `name` is a\n // requirement of the native `functionResponse` / Interactions surfaces, not this one.\n if (message.role !== \"assistant\" || !message.tool_calls?.length) {\n return message;\n }\n\n return {\n ...message,\n tool_calls: message.tool_calls.map((toolCall, index) =>\n index === 0\n ? {\n ...toolCall,\n extra_content: {\n google: { thought_signature: THOUGHT_SIGNATURE_SKIP },\n },\n }\n : toolCall,\n ),\n };\n });\n}\n\n/**\n * Aborts the underlying SDK request on timeout instead of only abandoning the\n * wrapper promise: the SDK stops waiting and stops retrying, and the aborted\n * request becomes a cancellation request to the server. Work Gemini already\n * accepted before the abort may still be billed.\n */\nasync function withTimeout<T>(\n makeRequest: (signal: AbortSignal) => Promise<T>,\n timeoutMessage: string,\n): Promise<T> {\n const controller = new AbortController();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const timeoutPromise = new Promise<T>((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new CharivoTimeoutError(timeoutMessage));\n }, REQUEST_TIMEOUT_MS);\n });\n\n try {\n return await Promise.race([makeRequest(controller.signal), timeoutPromise]);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n}\n","import type {\n LLMClient,\n LLMMessage,\n LLMToolResponse,\n ToolDefinition,\n} from \"@charivo/core\";\nimport {\n createGeminiLLMProvider,\n GeminiLLMConfig,\n GeminiLLMProvider,\n} from \"./provider\";\n\nexport {\n createGeminiLLMProvider,\n GeminiLLMProvider,\n type GeminiLLMConfig,\n} from \"./provider\";\n\n// Use GeminiLLMConfig directly\nexport type GeminiLLMClientConfig = GeminiLLMConfig;\n\n/**\n * Gemini LLM Client - Stateless client that wraps the Gemini provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The API key is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass GeminiLLMClient implements LLMClient {\n private provider: GeminiLLMProvider;\n\n constructor(config: GeminiLLMClientConfig) {\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createGeminiLLMProvider({\n ...config,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(messages: LLMMessage[]): Promise<string> {\n // Generate a response using the provider\n const assistantMessage = await this.provider.generateResponse(messages);\n\n return assistantMessage;\n }\n\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n return this.provider.generateResponseWithTools(messages, tools);\n }\n}\n\nexport function createGeminiLLMClient(\n config: GeminiLLMClientConfig,\n): LLMClient {\n return new GeminiLLMClient(config);\n}\n"]}
|
package/dist/gemini/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { toOpenAITools, toLLMToolResponse, toOpenAIChatMessages } from '../chunk-
|
|
1
|
+
import { toOpenAITools, toLLMToolResponse, toOpenAIChatMessages } from '../chunk-64OO6OAH.mjs';
|
|
2
2
|
import OpenAI from 'openai';
|
|
3
3
|
import { CharivoStateError, toCharivoError, CharivoTimeoutError } from '@charivo/core';
|
|
4
4
|
|
package/dist/openai/index.js
CHANGED
|
@@ -76,7 +76,14 @@ function toLLMToolCall(raw) {
|
|
|
76
76
|
'LLM tool call is missing a non-empty string "id"'
|
|
77
77
|
);
|
|
78
78
|
}
|
|
79
|
-
const
|
|
79
|
+
const type = raw.type;
|
|
80
|
+
if (type !== void 0 && type !== "function") {
|
|
81
|
+
throw new core.CharivoProviderError(
|
|
82
|
+
`LLM tool call "${id}" has unsupported type "${String(type)}"; only "function" tool calls are supported`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const fn = isPlainObject(raw.function) ? raw.function : {};
|
|
86
|
+
const name = fn.name;
|
|
80
87
|
if (typeof name !== "string" || name.length === 0) {
|
|
81
88
|
throw new core.CharivoProviderError(
|
|
82
89
|
`LLM tool call "${id}" is missing a non-empty string "function.name"`
|
|
@@ -85,10 +92,15 @@ function toLLMToolCall(raw) {
|
|
|
85
92
|
return {
|
|
86
93
|
id,
|
|
87
94
|
name,
|
|
88
|
-
arguments: parseToolArguments(name,
|
|
95
|
+
arguments: parseToolArguments(name, fn.arguments)
|
|
89
96
|
};
|
|
90
97
|
}
|
|
91
98
|
function parseToolArguments(name, rawArguments) {
|
|
99
|
+
if (typeof rawArguments !== "string") {
|
|
100
|
+
throw new core.CharivoProviderError(
|
|
101
|
+
`LLM tool call "${name}" has unparsable "function.arguments"`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
92
104
|
let parsed;
|
|
93
105
|
try {
|
|
94
106
|
parsed = JSON.parse(rawArguments);
|
package/dist/openai/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai-tool-format.ts","../../src/openai/provider.ts","../../src/openai/index.ts"],"names":["CharivoProviderError","CharivoStateError","OpenAI","toCharivoError","CharivoTimeoutError"],"mappings":";;;;;;;;;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,UAAA;AAAA,UACtB,SAAS,OAAA,CAAQ;AAAA,SACnB;AAAA,MACF,KAAK,WAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,WAAA;AAAA,UACN,SAAS,OAAA,CAAQ,OAAA;AAAA,UACjB,GAAI,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,UAAU,MAAA,GAAS,CAAA,GAChD,EAAE,UAAA,EAAY,QAAQ,SAAA,CAAU,GAAA,CAAI,gBAAgB,CAAA,KACpD;AAAC,SACP;AAAA,MACF,KAAK,QAAA;AAAA,MACL,KAAK,MAAA;AACH,QAAA,OAAO,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA;AAC1D,EACF,CAAC,CAAA;AACH;AAOO,SAAS,cACd,KA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AChD,GAAG,kBAAkB,CAAA;AAAA,EACvB,CAAC,CAAA;AAED,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,QAAQ,IAAA,CAAK,CAAC,YAAY,UAAA,CAAW,MAAM,CAAA,EAAG,cAAc,CAAC,CAAA;AAAA,EAC5E,CAAA,SAAE;AACA,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,YAAA,CAAa,SAAS,CAAA;AAAA,IACxB;AAAA,EACF;AACF;;;ACxGA,IAAM,kBAAN,MAA2C;AAAA,EACjC,QAAA;AAAA,EAER,YAAY,MAAA,EAA+B;AAGzC,IAAA,IAAA,CAAK,WAAW,uBAAA,CAAwB;AAAA,MACtC,GAAG,MAAA;AAAA,MACH,uBAAA,EAAyB;AAAA,KAC1B,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,KAAK,QAAA,EAAyC;AAElD,IAAA,MAAM,gBAAA,GAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,iBAAiB,QAAQ,CAAA;AAEtE,IAAA,OAAO,gBAAA;AAAA,EACT;AAAA,EAEA,MAAM,aAAA,CACJ,QAAA,EACA,KAAA,EAC0B;AAC1B,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,yBAAA,CAA0B,QAAA,EAAU,KAAK,CAAA;AAAA,EAChE;AACF,CAAA;AAEO,SAAS,sBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,gBAAgB,MAAM,CAAA;AACnC","file":"index.js","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n const name = raw.function?.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, raw.function.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: string,\n): Record<string, unknown> {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n CharivoTimeoutError,\n LLMProvider,\n toCharivoError,\n type LLMMessage,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport {\n toLLMToolResponse,\n toOpenAIChatMessages,\n toOpenAITools,\n} from \"../openai-tool-format\";\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\nexport interface OpenAILLMConfig {\n apiKey: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n dangerouslyAllowBrowser?: boolean;\n}\n\nexport class OpenAILLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature: number;\n private maxTokens: number;\n\n constructor(config: OpenAILLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"OpenAI LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.apiKey,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || \"gpt-4.1-nano\";\n this.temperature = config.temperature || 0.7;\n this.maxTokens = config.maxTokens || 1000;\n }\n\n async generateResponse(messages: LLMMessage[]): Promise<string> {\n try {\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toOpenAIChatMessages(messages),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n },\n { signal },\n ),\n `OpenAI LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenAI LLM request failed\");\n }\n }\n\n async generateResponseWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n try {\n const openAITools = toOpenAITools(tools);\n\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toOpenAIChatMessages(messages),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n ...(openAITools ? { tools: openAITools } : {}),\n },\n { signal },\n ),\n `OpenAI LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return toLLMToolResponse(completion.choices[0]?.message);\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenAI LLM request failed\");\n }\n }\n}\n\nexport function createOpenAILLMProvider(\n config: OpenAILLMConfig,\n): OpenAILLMProvider {\n return new OpenAILLMProvider(config);\n}\n\n/**\n * Aborts the underlying SDK request on timeout instead of only abandoning the\n * wrapper promise: the SDK stops waiting and stops retrying, and the aborted\n * request becomes a cancellation request to the server. Work OpenAI already\n * accepted before the abort may still be billed.\n */\nasync function withTimeout<T>(\n makeRequest: (signal: AbortSignal) => Promise<T>,\n timeoutMessage: string,\n): Promise<T> {\n const controller = new AbortController();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const timeoutPromise = new Promise<T>((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new CharivoTimeoutError(timeoutMessage));\n }, REQUEST_TIMEOUT_MS);\n });\n\n try {\n return await Promise.race([makeRequest(controller.signal), timeoutPromise]);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n}\n","import type {\n LLMClient,\n LLMMessage,\n LLMToolResponse,\n ToolDefinition,\n} from \"@charivo/core\";\nimport {\n createOpenAILLMProvider,\n OpenAILLMConfig,\n OpenAILLMProvider,\n} from \"./provider\";\n\nexport {\n createOpenAILLMProvider,\n OpenAILLMProvider,\n type OpenAILLMConfig,\n} from \"./provider\";\n\n// Use OpenAILLMConfig directly\nexport type OpenAILLMClientConfig = OpenAILLMConfig;\n\n/**\n * OpenAI LLM Client - Stateless client that wraps the OpenAI provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The API key is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass OpenAILLMClient implements LLMClient {\n private provider: OpenAILLMProvider;\n\n constructor(config: OpenAILLMClientConfig) {\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createOpenAILLMProvider({\n ...config,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(messages: LLMMessage[]): Promise<string> {\n // Generate a response using the provider\n const assistantMessage = await this.provider.generateResponse(messages);\n\n return assistantMessage;\n }\n\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n return this.provider.generateResponseWithTools(messages, tools);\n }\n}\n\nexport function createOpenAILLMClient(\n config: OpenAILLMClientConfig,\n): LLMClient {\n return new OpenAILLMClient(config);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/openai-tool-format.ts","../../src/openai/provider.ts","../../src/openai/index.ts"],"names":["CharivoProviderError","CharivoStateError","OpenAI","toCharivoError","CharivoTimeoutError"],"mappings":";;;;;;;;;;AAcO,S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EACvB,CAAC,CAAA;AAED,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,QAAQ,IAAA,CAAK,CAAC,YAAY,UAAA,CAAW,MAAM,CAAA,EAAG,cAAc,CAAC,CAAA;AAAA,EAC5E,CAAA,SAAE;AACA,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,YAAA,CAAa,SAAS,CAAA;AAAA,IACxB;AAAA,EACF;AACF;;;ACxGA,IAAM,kBAAN,MAA2C;AAAA,EACjC,QAAA;AAAA,EAER,YAAY,MAAA,EAA+B;AAGzC,IAAA,IAAA,CAAK,WAAW,uBAAA,CAAwB;AAAA,MACtC,GAAG,MAAA;AAAA,MACH,uBAAA,EAAyB;AAAA,KAC1B,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,KAAK,QAAA,EAAyC;AAElD,IAAA,MAAM,gBAAA,GAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,iBAAiB,QAAQ,CAAA;AAEtE,IAAA,OAAO,gBAAA;AAAA,EACT;AAAA,EAEA,MAAM,aAAA,CACJ,QAAA,EACA,KAAA,EAC0B;AAC1B,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,yBAAA,CAA0B,QAAA,EAAU,KAAK,CAAA;AAAA,EAChE;AACF,CAAA;AAEO,SAAS,sBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,gBAAgB,MAAM,CAAA;AACnC","file":"index.js","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n // `ChatCompletionMessageToolCall` is a union of a function and a custom tool\n // call, and `type` is its discriminator. Only function calls map onto\n // `LLMToolCall`, so a custom call is rejected for what it is rather than for\n // the `function` member it was never going to carry.\n // A gateway that omits `type` altogether still reaches the `function` checks\n // below, which is how this parser behaved before the union existed. Only a\n // type that is present and names something else is refused.\n const type = raw.type;\n if (type !== undefined && type !== \"function\") {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" has unsupported type \"${String(type)}\"; only \"function\" tool calls are supported`,\n );\n }\n\n // Past the discriminator the member is still read as untrusted data: this\n // function's stance is that the SDK types promise more than a gateway\n // delivers, so the checks below stay authoritative.\n const fn: Record<string, unknown> = isPlainObject(raw.function)\n ? raw.function\n : {};\n\n const name = fn.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, fn.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: unknown,\n): Record<string, unknown> {\n if (typeof rawArguments !== \"string\") {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n );\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n CharivoTimeoutError,\n LLMProvider,\n toCharivoError,\n type LLMMessage,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport {\n toLLMToolResponse,\n toOpenAIChatMessages,\n toOpenAITools,\n} from \"../openai-tool-format\";\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\nexport interface OpenAILLMConfig {\n apiKey: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n dangerouslyAllowBrowser?: boolean;\n}\n\nexport class OpenAILLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature: number;\n private maxTokens: number;\n\n constructor(config: OpenAILLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"OpenAI LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.apiKey,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || \"gpt-4.1-nano\";\n this.temperature = config.temperature || 0.7;\n this.maxTokens = config.maxTokens || 1000;\n }\n\n async generateResponse(messages: LLMMessage[]): Promise<string> {\n try {\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toOpenAIChatMessages(messages),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n },\n { signal },\n ),\n `OpenAI LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenAI LLM request failed\");\n }\n }\n\n async generateResponseWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n try {\n const openAITools = toOpenAITools(tools);\n\n const completion = await withTimeout(\n (signal) =>\n this.openai.chat.completions.create(\n {\n model: this.model,\n messages: toOpenAIChatMessages(messages),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n ...(openAITools ? { tools: openAITools } : {}),\n },\n { signal },\n ),\n `OpenAI LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return toLLMToolResponse(completion.choices[0]?.message);\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenAI LLM request failed\");\n }\n }\n}\n\nexport function createOpenAILLMProvider(\n config: OpenAILLMConfig,\n): OpenAILLMProvider {\n return new OpenAILLMProvider(config);\n}\n\n/**\n * Aborts the underlying SDK request on timeout instead of only abandoning the\n * wrapper promise: the SDK stops waiting and stops retrying, and the aborted\n * request becomes a cancellation request to the server. Work OpenAI already\n * accepted before the abort may still be billed.\n */\nasync function withTimeout<T>(\n makeRequest: (signal: AbortSignal) => Promise<T>,\n timeoutMessage: string,\n): Promise<T> {\n const controller = new AbortController();\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const timeoutPromise = new Promise<T>((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new CharivoTimeoutError(timeoutMessage));\n }, REQUEST_TIMEOUT_MS);\n });\n\n try {\n return await Promise.race([makeRequest(controller.signal), timeoutPromise]);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n}\n","import type {\n LLMClient,\n LLMMessage,\n LLMToolResponse,\n ToolDefinition,\n} from \"@charivo/core\";\nimport {\n createOpenAILLMProvider,\n OpenAILLMConfig,\n OpenAILLMProvider,\n} from \"./provider\";\n\nexport {\n createOpenAILLMProvider,\n OpenAILLMProvider,\n type OpenAILLMConfig,\n} from \"./provider\";\n\n// Use OpenAILLMConfig directly\nexport type OpenAILLMClientConfig = OpenAILLMConfig;\n\n/**\n * OpenAI LLM Client - Stateless client that wraps the OpenAI provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The API key is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass OpenAILLMClient implements LLMClient {\n private provider: OpenAILLMProvider;\n\n constructor(config: OpenAILLMClientConfig) {\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createOpenAILLMProvider({\n ...config,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(messages: LLMMessage[]): Promise<string> {\n // Generate a response using the provider\n const assistantMessage = await this.provider.generateResponse(messages);\n\n return assistantMessage;\n }\n\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n return this.provider.generateResponseWithTools(messages, tools);\n }\n}\n\nexport function createOpenAILLMClient(\n config: OpenAILLMClientConfig,\n): LLMClient {\n return new OpenAILLMClient(config);\n}\n"]}
|
package/dist/openai/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { toOpenAIChatMessages, toOpenAITools, toLLMToolResponse } from '../chunk-
|
|
1
|
+
import { toOpenAIChatMessages, toOpenAITools, toLLMToolResponse } from '../chunk-64OO6OAH.mjs';
|
|
2
2
|
import OpenAI from 'openai';
|
|
3
3
|
import { CharivoStateError, toCharivoError, CharivoTimeoutError } from '@charivo/core';
|
|
4
4
|
|
package/dist/openclaw/index.js
CHANGED
|
@@ -76,7 +76,14 @@ function toLLMToolCall(raw) {
|
|
|
76
76
|
'LLM tool call is missing a non-empty string "id"'
|
|
77
77
|
);
|
|
78
78
|
}
|
|
79
|
-
const
|
|
79
|
+
const type = raw.type;
|
|
80
|
+
if (type !== void 0 && type !== "function") {
|
|
81
|
+
throw new core.CharivoProviderError(
|
|
82
|
+
`LLM tool call "${id}" has unsupported type "${String(type)}"; only "function" tool calls are supported`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const fn = isPlainObject(raw.function) ? raw.function : {};
|
|
86
|
+
const name = fn.name;
|
|
80
87
|
if (typeof name !== "string" || name.length === 0) {
|
|
81
88
|
throw new core.CharivoProviderError(
|
|
82
89
|
`LLM tool call "${id}" is missing a non-empty string "function.name"`
|
|
@@ -85,10 +92,15 @@ function toLLMToolCall(raw) {
|
|
|
85
92
|
return {
|
|
86
93
|
id,
|
|
87
94
|
name,
|
|
88
|
-
arguments: parseToolArguments(name,
|
|
95
|
+
arguments: parseToolArguments(name, fn.arguments)
|
|
89
96
|
};
|
|
90
97
|
}
|
|
91
98
|
function parseToolArguments(name, rawArguments) {
|
|
99
|
+
if (typeof rawArguments !== "string") {
|
|
100
|
+
throw new core.CharivoProviderError(
|
|
101
|
+
`LLM tool call "${name}" has unparsable "function.arguments"`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
92
104
|
let parsed;
|
|
93
105
|
try {
|
|
94
106
|
parsed = JSON.parse(rawArguments);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai-tool-format.ts","../../src/openclaw/provider.ts","../../src/openclaw/index.ts"],"names":["CharivoProviderError","CharivoStateError","OpenAI","toCharivoError"],"mappings":";;;;;;;;;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,UAAA;AAAA,UACtB,SAAS,OAAA,CAAQ;AAAA,SACnB;AAAA,MACF,KAAK,WAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,WAAA;AAAA,UACN,SAAS,OAAA,CAAQ,OAAA;AAAA,UACjB,GAAI,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,UAAU,MAAA,GAAS,CAAA,GAChD,EAAE,UAAA,EAAY,QAAQ,SAAA,CAAU,GAAA,CAAI,gBAAgB,CAAA,KACpD;AAAC,SACP;AAAA,MACF,KAAK,QAAA;AAAA,MACL,KAAK,MAAA;AACH,QAAA,OAAO,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA;AAC1D,EACF,CAAC,CAAA;AACH;AAOO,SAAS,cACd,KAAA,E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EAAU,KAAK,CAAA;AAAA,EAChE;AACF,CAAA;AAEO,SAAS,wBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,kBAAkB,MAAM,CAAA;AACrC","file":"index.js","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n const name = raw.function?.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, raw.function.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: string,\n): Record<string, unknown> {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n LLMProvider,\n toCharivoError,\n type LLMMessage,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport {\n toLLMToolResponse,\n toOpenAIChatMessages,\n toOpenAITools,\n} from \"../openai-tool-format\";\n\nexport interface OpenClawLLMConfig {\n token: string;\n baseURL?: string;\n /**\n * Target a specific agent on the gateway.\n * When omitted, the gateway's configured default agent handles the request.\n */\n agentId?: string;\n /**\n * Agent target, not a backend model name. The gateway resolves this to an\n * agent: `openclaw`, `openclaw/default`, or `openclaw/<agentId>`.\n *\n * @default \"openclaw/default\"\n */\n model?: string;\n temperature?: number;\n maxTokens?: number;\n /**\n * Pins the conversation to a server-side session on the gateway.\n *\n * The gateway keeps conversation state itself, but without an identifier it\n * opens a fresh session per request: nothing is persisted between turns and\n * each one strands a throwaway session. Sending this as the `user` field makes\n * the gateway derive a stable session key from it.\n *\n * When set, past turns are not resent — the gateway already holds them. The\n * system prompt is still sent every turn so the persona survives a dropped\n * session.\n *\n * Treat it as a conversation-scoped identifier (e.g. a UUID per conversation,\n * rotated when the user resets the chat). Rotating it is the only way to reset\n * the conversation; the gateway keeps the old transcript under the old key.\n */\n sessionKey?: string;\n dangerouslyAllowBrowser?: boolean;\n}\n\n/**\n * Deliberately has no request timeout, unlike the OpenAI and Gemini providers.\n * The gateway fronts an agent harness whose runs legitimately take minutes, so\n * any cap short enough to be useful against a hang would also cut off ordinary\n * work. Neither method takes an `AbortSignal`, so a caller can stop waiting on\n * the promise but cannot cancel the run behind it.\n */\nexport class OpenClawLLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature: number;\n private maxTokens: number;\n private sessionKey?: string;\n\n constructor(config: OpenClawLLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"OpenClaw LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.token,\n baseURL: config.baseURL || \"http://127.0.0.1:18789/v1\",\n defaultHeaders: config.agentId\n ? { \"x-openclaw-agent-id\": config.agentId }\n : undefined,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || \"openclaw/default\";\n this.temperature = config.temperature ?? 0.7;\n this.maxTokens = config.maxTokens || 1000;\n this.sessionKey = config.sessionKey;\n }\n\n async generateResponse(messages: LLMMessage[]): Promise<string> {\n try {\n const completion = await this.openai.chat.completions.create({\n model: this.model,\n messages: toOpenAIChatMessages(this.selectMessages(messages)),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n ...(this.sessionKey ? { user: this.sessionKey } : {}),\n });\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenClaw LLM request failed\");\n }\n }\n\n async generateResponseWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n try {\n const openAITools = toOpenAITools(tools);\n\n const completion = await this.openai.chat.completions.create({\n model: this.model,\n messages: toOpenAIChatMessages(this.selectMessages(messages)),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n ...(this.sessionKey ? { user: this.sessionKey } : {}),\n ...(openAITools ? { tools: openAITools } : {}),\n });\n\n return toLLMToolResponse(completion.choices[0]?.message);\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenClaw LLM request failed\");\n }\n }\n\n /**\n * With a pinned session the gateway already holds the past turns, and resending\n * them would flatten a duplicate copy of the history on top of its own. Keep the\n * system prompts (cheap persona insurance if the session was dropped) and only\n * what the gateway has not recorded yet:\n * - mid tool round, that is the trailing run of tool results (the gateway\n * generated the assistant tool-call turn that asked for them itself);\n * - otherwise, the latest turn.\n */\n private selectMessages<T extends { role: string }>(messages: T[]): T[] {\n const latest = messages[messages.length - 1];\n if (!this.sessionKey || !latest) {\n return messages;\n }\n\n const systemMessages = messages.filter((msg) => msg.role === \"system\");\n\n if (latest.role === \"tool\") {\n return [...systemMessages, ...trailingToolMessages(messages)];\n }\n\n return latest.role === \"system\"\n ? systemMessages\n : [...systemMessages, latest];\n }\n}\n\n/** The unbroken run of tool results at the end of the conversation. */\nfunction trailingToolMessages<T extends { role: string }>(messages: T[]): T[] {\n let start = messages.length;\n while (start > 0 && messages[start - 1]!.role === \"tool\") {\n start -= 1;\n }\n\n return messages.slice(start);\n}\n\nexport function createOpenClawLLMProvider(\n config: OpenClawLLMConfig,\n): OpenClawLLMProvider {\n return new OpenClawLLMProvider(config);\n}\n","import type {\n LLMClient,\n LLMMessage,\n LLMToolResponse,\n ToolDefinition,\n} from \"@charivo/core\";\nimport {\n createOpenClawLLMProvider,\n OpenClawLLMConfig,\n OpenClawLLMProvider,\n} from \"./provider\";\n\nexport {\n createOpenClawLLMProvider,\n OpenClawLLMProvider,\n type OpenClawLLMConfig,\n} from \"./provider\";\n\n// No `sessionKey` here, unlike the provider config. Pinning the gateway\n// session requires rotating it on reset, and this client is driven by\n// LLMManager, whose clearHistory()/character switch clear only local history and\n// cannot reach the client. A pinned session would survive that reset and silently\n// replay the old conversation. Server routes construct the provider themselves and\n// can rotate the key, so the option lives there instead.\nexport type OpenClawLLMClientConfig = Omit<OpenClawLLMConfig, \"sessionKey\">;\n\n/**\n * OpenClaw LLM Client - Stateless client that wraps the OpenClaw provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The token is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass OpenClawLLMClient implements LLMClient {\n private provider: OpenClawLLMProvider;\n\n constructor(config: OpenClawLLMClientConfig) {\n // Strip sessionKey at runtime too: an untyped JS caller can bypass the\n // Omit above and pass it anyway.\n const { sessionKey: _sessionKey, ...rest } = config as OpenClawLLMConfig;\n\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createOpenClawLLMProvider({\n ...rest,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(messages: LLMMessage[]): Promise<string> {\n return this.provider.generateResponse(messages);\n }\n\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n return this.provider.generateResponseWithTools(messages, tools);\n }\n}\n\nexport function createOpenClawLLMClient(\n config: OpenClawLLMClientConfig,\n): LLMClient {\n return new OpenClawLLMClient(config);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/openai-tool-format.ts","../../src/openclaw/provider.ts","../../src/openclaw/index.ts"],"names":["CharivoProviderError","CharivoStateError","OpenAI","toCharivoError"],"mappings":";;;;;;;;;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,UAAA;AAAA,UACtB,SAAS,OAAA,CAAQ;AAAA,SACnB;AAAA,MACF,KAAK,WAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,WAAA;AAAA,UACN,SAAS,OAAA,CAAQ,OAAA;AAAA,UACjB,GAAI,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,UAAU,MAAA,GAAS,CAAA,GAChD,EAAE,UAAA,EAAY,QAAQ,SAAA,CAAU,GAAA,CAAI,gBAAgB,CAAA,KACpD;AAAC,SACP;AAAA,MACF,KAAK,QAAA;AAAA,MACL,KAAK,MAAA;AACH,QAAA,OAAO,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA;AAC1D,EACF,CAAC,CAAA;AACH;AAOO,SAAS,cACd,KAAA,EACyC;AACzC,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACtB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,MAAU;AAAA,IAC1B,IAAA,EAAM,UAAA;AAAA,IACN,QAAA,EAAU;AAA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AA,KAC1B,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,KAAK,QAAA,EAAyC;AAClD,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,gBAAA,CAAiB,QAAQ,CAAA;AAAA,EAChD;AAAA,EAEA,MAAM,aAAA,CACJ,QAAA,EACA,KAAA,EAC0B;AAC1B,IAAA,OAAO,IAAA,CAAK,QAAA,CAAS,yBAAA,CAA0B,QAAA,EAAU,KAAK,CAAA;AAAA,EAChE;AACF,CAAA;AAEO,SAAS,wBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,kBAAkB,MAAM,CAAA;AACrC","file":"index.js","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n // `ChatCompletionMessageToolCall` is a union of a function and a custom tool\n // call, and `type` is its discriminator. Only function calls map onto\n // `LLMToolCall`, so a custom call is rejected for what it is rather than for\n // the `function` member it was never going to carry.\n // A gateway that omits `type` altogether still reaches the `function` checks\n // below, which is how this parser behaved before the union existed. Only a\n // type that is present and names something else is refused.\n const type = raw.type;\n if (type !== undefined && type !== \"function\") {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" has unsupported type \"${String(type)}\"; only \"function\" tool calls are supported`,\n );\n }\n\n // Past the discriminator the member is still read as untrusted data: this\n // function's stance is that the SDK types promise more than a gateway\n // delivers, so the checks below stay authoritative.\n const fn: Record<string, unknown> = isPlainObject(raw.function)\n ? raw.function\n : {};\n\n const name = fn.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, fn.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: unknown,\n): Record<string, unknown> {\n if (typeof rawArguments !== \"string\") {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n );\n }\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n LLMProvider,\n toCharivoError,\n type LLMMessage,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport {\n toLLMToolResponse,\n toOpenAIChatMessages,\n toOpenAITools,\n} from \"../openai-tool-format\";\n\nexport interface OpenClawLLMConfig {\n token: string;\n baseURL?: string;\n /**\n * Target a specific agent on the gateway.\n * When omitted, the gateway's configured default agent handles the request.\n */\n agentId?: string;\n /**\n * Agent target, not a backend model name. The gateway resolves this to an\n * agent: `openclaw`, `openclaw/default`, or `openclaw/<agentId>`.\n *\n * @default \"openclaw/default\"\n */\n model?: string;\n temperature?: number;\n maxTokens?: number;\n /**\n * Pins the conversation to a server-side session on the gateway.\n *\n * The gateway keeps conversation state itself, but without an identifier it\n * opens a fresh session per request: nothing is persisted between turns and\n * each one strands a throwaway session. Sending this as the `user` field makes\n * the gateway derive a stable session key from it.\n *\n * When set, past turns are not resent — the gateway already holds them. The\n * system prompt is still sent every turn so the persona survives a dropped\n * session.\n *\n * Treat it as a conversation-scoped identifier (e.g. a UUID per conversation,\n * rotated when the user resets the chat). Rotating it is the only way to reset\n * the conversation; the gateway keeps the old transcript under the old key.\n */\n sessionKey?: string;\n dangerouslyAllowBrowser?: boolean;\n}\n\n/**\n * Deliberately has no request timeout, unlike the OpenAI and Gemini providers.\n * The gateway fronts an agent harness whose runs legitimately take minutes, so\n * any cap short enough to be useful against a hang would also cut off ordinary\n * work. Neither method takes an `AbortSignal`, so a caller can stop waiting on\n * the promise but cannot cancel the run behind it.\n */\nexport class OpenClawLLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature: number;\n private maxTokens: number;\n private sessionKey?: string;\n\n constructor(config: OpenClawLLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"OpenClaw LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.token,\n baseURL: config.baseURL || \"http://127.0.0.1:18789/v1\",\n defaultHeaders: config.agentId\n ? { \"x-openclaw-agent-id\": config.agentId }\n : undefined,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || \"openclaw/default\";\n this.temperature = config.temperature ?? 0.7;\n this.maxTokens = config.maxTokens || 1000;\n this.sessionKey = config.sessionKey;\n }\n\n async generateResponse(messages: LLMMessage[]): Promise<string> {\n try {\n const completion = await this.openai.chat.completions.create({\n model: this.model,\n messages: toOpenAIChatMessages(this.selectMessages(messages)),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n ...(this.sessionKey ? { user: this.sessionKey } : {}),\n });\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenClaw LLM request failed\");\n }\n }\n\n async generateResponseWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n try {\n const openAITools = toOpenAITools(tools);\n\n const completion = await this.openai.chat.completions.create({\n model: this.model,\n messages: toOpenAIChatMessages(this.selectMessages(messages)),\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n ...(this.sessionKey ? { user: this.sessionKey } : {}),\n ...(openAITools ? { tools: openAITools } : {}),\n });\n\n return toLLMToolResponse(completion.choices[0]?.message);\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenClaw LLM request failed\");\n }\n }\n\n /**\n * With a pinned session the gateway already holds the past turns, and resending\n * them would flatten a duplicate copy of the history on top of its own. Keep the\n * system prompts (cheap persona insurance if the session was dropped) and only\n * what the gateway has not recorded yet:\n * - mid tool round, that is the trailing run of tool results (the gateway\n * generated the assistant tool-call turn that asked for them itself);\n * - otherwise, the latest turn.\n */\n private selectMessages<T extends { role: string }>(messages: T[]): T[] {\n const latest = messages[messages.length - 1];\n if (!this.sessionKey || !latest) {\n return messages;\n }\n\n const systemMessages = messages.filter((msg) => msg.role === \"system\");\n\n if (latest.role === \"tool\") {\n return [...systemMessages, ...trailingToolMessages(messages)];\n }\n\n return latest.role === \"system\"\n ? systemMessages\n : [...systemMessages, latest];\n }\n}\n\n/** The unbroken run of tool results at the end of the conversation. */\nfunction trailingToolMessages<T extends { role: string }>(messages: T[]): T[] {\n let start = messages.length;\n while (start > 0 && messages[start - 1]!.role === \"tool\") {\n start -= 1;\n }\n\n return messages.slice(start);\n}\n\nexport function createOpenClawLLMProvider(\n config: OpenClawLLMConfig,\n): OpenClawLLMProvider {\n return new OpenClawLLMProvider(config);\n}\n","import type {\n LLMClient,\n LLMMessage,\n LLMToolResponse,\n ToolDefinition,\n} from \"@charivo/core\";\nimport {\n createOpenClawLLMProvider,\n OpenClawLLMConfig,\n OpenClawLLMProvider,\n} from \"./provider\";\n\nexport {\n createOpenClawLLMProvider,\n OpenClawLLMProvider,\n type OpenClawLLMConfig,\n} from \"./provider\";\n\n// No `sessionKey` here, unlike the provider config. Pinning the gateway\n// session requires rotating it on reset, and this client is driven by\n// LLMManager, whose clearHistory()/character switch clear only local history and\n// cannot reach the client. A pinned session would survive that reset and silently\n// replay the old conversation. Server routes construct the provider themselves and\n// can rotate the key, so the option lives there instead.\nexport type OpenClawLLMClientConfig = Omit<OpenClawLLMConfig, \"sessionKey\">;\n\n/**\n * OpenClaw LLM Client - Stateless client that wraps the OpenClaw provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The token is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass OpenClawLLMClient implements LLMClient {\n private provider: OpenClawLLMProvider;\n\n constructor(config: OpenClawLLMClientConfig) {\n // Strip sessionKey at runtime too: an untyped JS caller can bypass the\n // Omit above and pass it anyway.\n const { sessionKey: _sessionKey, ...rest } = config as OpenClawLLMConfig;\n\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createOpenClawLLMProvider({\n ...rest,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(messages: LLMMessage[]): Promise<string> {\n return this.provider.generateResponse(messages);\n }\n\n async callWithTools(\n messages: LLMMessage[],\n tools: ToolDefinition[],\n ): Promise<LLMToolResponse> {\n return this.provider.generateResponseWithTools(messages, tools);\n }\n}\n\nexport function createOpenClawLLMClient(\n config: OpenClawLLMClientConfig,\n): LLMClient {\n return new OpenClawLLMClient(config);\n}\n"]}
|
package/dist/openclaw/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { toOpenAIChatMessages, toOpenAITools, toLLMToolResponse } from '../chunk-
|
|
1
|
+
import { toOpenAIChatMessages, toOpenAITools, toLLMToolResponse } from '../chunk-64OO6OAH.mjs';
|
|
2
2
|
import OpenAI from 'openai';
|
|
3
3
|
import { CharivoStateError, toCharivoError } from '@charivo/core';
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@charivo/llm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"description": "LLM manager and browser adapters for Charivo",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@charivo/core": "^0.36.0",
|
|
49
|
-
"openai": "^
|
|
49
|
+
"openai": "^7.10.0"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"tsup": "^8.5.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/openai-tool-format.ts"],"names":[],"mappings":";;;AAcO,SAAS,qBACd,QAAA,EACqC;AACrC,EAAA,OAAO,QAAA,CAAS,GAAA,CAAI,CAAC,OAAA,KAAY;AAC/B,IAAA,QAAQ,QAAQ,IAAA;AAAM,MACpB,KAAK,MAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,MAAA;AAAA,UACN,cAAc,OAAA,CAAQ,UAAA;AAAA,UACtB,SAAS,OAAA,CAAQ;AAAA,SACnB;AAAA,MACF,KAAK,WAAA;AACH,QAAA,OAAO;AAAA,UACL,IAAA,EAAM,WAAA;AAAA,UACN,SAAS,OAAA,CAAQ,OAAA;AAAA,UACjB,GAAI,OAAA,CAAQ,SAAA,IAAa,OAAA,CAAQ,UAAU,MAAA,GAAS,CAAA,GAChD,EAAE,UAAA,EAAY,QAAQ,SAAA,CAAU,GAAA,CAAI,gBAAgB,CAAA,KACpD;AAAC,SACP;AAAA,MACF,KAAK,QAAA;AAAA,MACL,KAAK,MAAA;AACH,QAAA,OAAO,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,OAAA,EAAS,QAAQ,OAAA,EAAQ;AAAA;AAC1D,EACF,CAAC,CAAA;AACH;AAOO,SAAS,cACd,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":"chunk-N2ILPUIF.mjs","sourcesContent":["/**\n * Mapping between the neutral LLM tool contracts and the OpenAI\n * chat.completions wire format. Shared by the OpenAI provider and the OpenClaw\n * gateway provider, which speaks the same API.\n */\nimport {\n CharivoProviderError,\n type LLMMessage,\n type LLMToolCall,\n type LLMToolResponse,\n type ToolDefinition,\n} from \"@charivo/core\";\nimport type OpenAI from \"openai\";\n\nexport function toOpenAIChatMessages(\n messages: LLMMessage[],\n): OpenAI.ChatCompletionMessageParam[] {\n return messages.map((message) => {\n switch (message.role) {\n case \"tool\":\n return {\n role: \"tool\",\n tool_call_id: message.toolCallId,\n content: message.content,\n };\n case \"assistant\":\n return {\n role: \"assistant\",\n content: message.content,\n ...(message.toolCalls && message.toolCalls.length > 0\n ? { tool_calls: message.toolCalls.map(toOpenAIToolCall) }\n : {}),\n };\n case \"system\":\n case \"user\":\n return { role: message.role, content: message.content };\n }\n });\n}\n\n/**\n * Returns undefined for an empty list so callers can spread the result and\n * leave the `tools` param out entirely: an empty array would still switch the\n * model into tool mode.\n */\nexport function toOpenAITools(\n tools: ToolDefinition[],\n): OpenAI.ChatCompletionTool[] | undefined {\n if (tools.length === 0) {\n return undefined;\n }\n\n return tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n}\n\n/**\n * Builds the neutral tool response from a completion message. Shared by the\n * OpenAI and OpenClaw providers, which both read from the same wire shape.\n */\nexport function toLLMToolResponse(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolResponse {\n const toolCalls = readToolCalls(message);\n\n return {\n content: message?.content ?? \"\",\n ...(toolCalls.length > 0 ? { toolCalls } : {}),\n };\n}\n\n/**\n * Read the tool calls off a completion message. The SDK types promise more than\n * the wire delivers - especially through a gateway - so every field is checked\n * before it reaches the neutral contract.\n */\nfunction readToolCalls(\n message: OpenAI.ChatCompletionMessage | undefined,\n): LLMToolCall[] {\n const rawToolCalls = message?.tool_calls;\n if (!rawToolCalls || rawToolCalls.length === 0) {\n return [];\n }\n\n return rawToolCalls.map(toLLMToolCall);\n}\n\nfunction toOpenAIToolCall(\n toolCall: LLMToolCall,\n): OpenAI.ChatCompletionMessageToolCall {\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.arguments),\n },\n };\n}\n\nfunction toLLMToolCall(raw: OpenAI.ChatCompletionMessageToolCall): LLMToolCall {\n if (!isPlainObject(raw)) {\n throw new CharivoProviderError(\"LLM tool call must be an object\");\n }\n\n const id = raw.id;\n if (typeof id !== \"string\" || id.length === 0) {\n throw new CharivoProviderError(\n 'LLM tool call is missing a non-empty string \"id\"',\n );\n }\n\n const name = raw.function?.name;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new CharivoProviderError(\n `LLM tool call \"${id}\" is missing a non-empty string \"function.name\"`,\n );\n }\n\n return {\n id,\n name,\n arguments: parseToolArguments(name, raw.function.arguments),\n };\n}\n\nfunction parseToolArguments(\n name: string,\n rawArguments: string,\n): Record<string, unknown> {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(rawArguments);\n } catch (error) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has unparsable \"function.arguments\"`,\n { cause: error instanceof Error ? error : undefined },\n );\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CharivoProviderError(\n `LLM tool call \"${name}\" has \"function.arguments\" that are not a JSON object`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"]}
|