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

json-object-mode.ts

34 lines1.1 KB

1import { jsonModeSystemPrompt } from '@tanstack/ai-utils'
2import type { TextOptions } from '@tanstack/ai'
3​
4/** Caller set JSON mode on a Chat Completions or Responses body. */
5export function explicitJsonObject(modelOptions: unknown): boolean {
6 if (modelOptions == null || typeof modelOptions !== 'object') return false
7 if ('response_format' in modelOptions) {
8 const format = (modelOptions as { response_format?: { type?: unknown } })
9 .response_format
10 if (format?.type === 'json_object') return true
11 }
12 if ('text' in modelOptions) {
13 const text = (modelOptions as { text?: { format?: { type?: unknown } } })
14 .text
15 if (text?.format?.type === 'json_object') return true
16 }
17 return false
19​
20/** Add the schema as a system prompt, because JSON mode does not send it. */
21export function withJsonModePrompt<
22 TProviderOptions extends Record<string, any>,
23>(
24 options: TextOptions<TProviderOptions>,
25 schema: unknown,
26): TextOptions<TProviderOptions> {
27 return {
28 ...options,
29 systemPrompts: [
30 ...(options.systemPrompts ?? []),
31 jsonModeSystemPrompt(schema),
32 ],
33 }