Open History to see the last commit
1import type { ChatContentCacheControl } from '@openrouter/sdk/models'
2import type { JSONSchema, Tool } from '@tanstack/ai'
3
4export interface FunctionTool {
5 type: 'function'
6 function: {
7 name: string
8 description?: string
9 parameters: Record<string, unknown>
10 strict?: boolean
11 }
12 /**
13 * Anthropic-style prompt-cache breakpoint for the tool definition.
14 *
15 * The SDK accepts this camelCase field as a top-level sibling of `function`
16 * and remaps it to `cache_control` on the wire (its outbound Zod schema
17 * strips an unrecognized snake_case `cache_control`, so the field must be
18 * `cacheControl`). Forwarding it lets callers cache tool definitions through
19 * OpenRouter exactly as `@tanstack/ai-anthropic` does directly. Uses the
20 * SDK's `ChatContentCacheControl` type, matching `OpenRouterSystemPromptMetadata`.
21 */
22 cacheControl?: ChatContentCacheControl
23}
24
25/**
26 * Converts a standard Tool to OpenRouter FunctionTool format.
27 *
28 * Tool schemas are already converted to JSON Schema in the ai layer.
29 */
30export function convertFunctionToolToAdapterFormat(tool: Tool): FunctionTool {
31 // Tool schemas are already converted to JSON Schema in the ai layer
32 const inputSchema = (tool.inputSchema ?? {
33 type: 'object',
34 properties: {},
35 required: [],
36 }) as JSONSchema
37
38 // Forward an optional cache-control marker so OpenRouter can cache the tool
39 // definition (Anthropic prompt caching). Mirrors
40 // `convertCustomToolToAdapterFormat` in `@tanstack/ai-anthropic`. The SDK
41 // remaps `cacheControl` -> `cache_control` on the wire; a snake_case key is
42 // silently stripped by its outbound schema.
43 //
44 // `Tool.metadata` is `Record<string, any>`, so the field is already
45 // assignable here — the annotation narrows it without a cast.
46 const cacheControl: ChatContentCacheControl | null | undefined =
47 tool.metadata?.cacheControl
48
49 return {
50 type: 'function',
51 function: {
52 name: tool.name,
53 description: tool.description,
54 parameters: inputSchema,
55 // Sent explicitly for every model. Observed behaviour (#1542): with
56 // `strict` omitted, OpenAI models through OpenRouter treat the schema as
57 // strict, so every optional field becomes required.
58 strict: false,
59 },
60 // Only present when supplied — additive and non-breaking.
61 ...(cacheControl ? { cacheControl } : {}),
62 }
63}