Open History to see the last commit
1import { jsonModeSystemPrompt } from '@tanstack/ai-utils'
2import { OPENROUTER_JSON_OBJECT_ONLY_MODELS } from '../model-meta'
3import { openRouterModelIn, openRouterRoutedModels } from './model-ids'
4import type { TextOptions } from '@tanstack/ai'
5
6/**
7 * True when this OpenRouter call must send `json_object`. The caller set it
8 * in `modelOptions` (`responseFormat` or `text.format`), or a routed model
9 * (`model` with its `variant`, or `modelOptions.models`) has
10 * `response_format` and not `structured_outputs` in the catalog.
11 */
12export function openRouterUsesJsonObject(
13 model: string,
14 modelOptions: unknown,
15): boolean {
16 const record = (modelOptions ?? {}) as {
17 responseFormat?: { type?: unknown }
18 text?: { format?: { type?: unknown } }
19 }
20 if (
21 record.responseFormat?.type === 'json_object' ||
22 record.text?.format?.type === 'json_object'
23 ) {
24 return true
25 }
26 return openRouterRoutedModels(model, modelOptions).some((id) =>
27 openRouterModelIn(OPENROUTER_JSON_OBJECT_ONLY_MODELS, id),
28 )
29}
30
31/** Add the schema as a system prompt, because JSON mode does not send it. */
32export function withJsonModePrompt<
33 TProviderOptions extends Record<string, any>,
34>(
35 options: TextOptions<TProviderOptions>,
36 schema: unknown,
37): TextOptions<TProviderOptions> {
38 return {
39 ...options,
40 systemPrompts: [
41 ...(options.systemPrompts ?? []),
42 jsonModeSystemPrompt(schema),
43 ],
44 }
45}