Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

function-tool.ts

58 lines2.1 KB

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 }
11 /**
12 * Anthropic-style prompt-cache breakpoint for the tool definition.
13 *
14 * The SDK accepts this camelCase field as a top-level sibling of `function`
15 * and remaps it to `cache_control` on the wire (its outbound Zod schema
16 * strips an unrecognized snake_case `cache_control`, so the field must be
17 * `cacheControl`). Forwarding it lets callers cache tool definitions through
18 * OpenRouter exactly as `@tanstack/ai-anthropic` does directly. Uses the
19 * SDK's `ChatContentCacheControl` type, matching `OpenRouterSystemPromptMetadata`.
20 */
21 cacheControl?: ChatContentCacheControl
23​
24/**
25 * Converts a standard Tool to OpenRouter FunctionTool format.
26 *
27 * Tool schemas are already converted to JSON Schema in the ai layer.
28 */
29export function convertFunctionToolToAdapterFormat(tool: Tool): FunctionTool {
30 // Tool schemas are already converted to JSON Schema in the ai layer
31 const inputSchema = (tool.inputSchema ?? {
32 type: 'object',
33 properties: {},
34 required: [],
35 }) as JSONSchema
36​
37 // Forward an optional cache-control marker so OpenRouter can cache the tool
38 // definition (Anthropic prompt caching). Mirrors
39 // `convertCustomToolToAdapterFormat` in `@tanstack/ai-anthropic`. The SDK
40 // remaps `cacheControl` -> `cache_control` on the wire; a snake_case key is
41 // silently stripped by its outbound schema.
42 //
43 // `Tool.metadata` is `Record<string, any>`, so the field is already
44 // assignable here — the annotation narrows it without a cast.
45 const cacheControl: ChatContentCacheControl | null | undefined =
46 tool.metadata?.cacheControl
47​
48 return {
49 type: 'function',
50 function: {
51 name: tool.name,
52 description: tool.description,
53 parameters: inputSchema,
54 },
55 // Only present when supplied — additive and non-breaking.
56 ...(cacheControl ? { cacheControl } : {}),
57 }