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

fal-chat-facts.ts

294 lines9.5 KB

1/**
2 * Chat facts for FAL's text endpoints, read from the endpoint's own OpenAPI
3 * request schema (models API, `expand=openapi-3.0`) and its listing
4 * description. Every FAL endpoint has its own request body, so nothing here
5 * is shared across rows. A router that takes a `model` field states no
6 * window, output cap, or reasoning config of its own: those stay null.
7 */
8import { extractEndpointSchemas } from '#/server/ingest/bundle.ts'
9import { walkRequestSchema } from './fact-sources.ts'
10import { tokenCount } from './model-facts.ts'
11import { SHARED_EFFORT_LEVELS } from './request-map.ts'
12import type { EffortLevelMap } from './request-map.ts'
13import type {
14 FactSource,
15 ModelFactSources,
16 ModelInfo,
17 ModelReasoning,
18 OpenApiDocument,
19} from './types.ts'
20​
21export type FalChatFacts = Pick<
22 ModelInfo,
23 | 'contextWindow'
24 | 'maxOutput'
25 | 'modalities'
26 | 'capabilities'
27 | 'reasoning'
28 | 'requestMap'
29 | 'factSources'
31​
32/** `256K context` in the listing description. The unit and word are required. */
33const CONTEXT = /\b(\d+(?:\.\d+)?[KkMm])[ \t]+context\b/g
34​
35/** FAL names media inputs `<medium>_url` or `<medium>_urls`. */
36const MEDIA_PROPERTY = /^(image|audio|video)_urls?$/
37​
38const MAX_OUTPUT_PROPERTIES = ['max_completion_tokens', 'max_tokens']
39​
40function isRecord(value: unknown): value is Record<string, unknown> {
41 return typeof value === 'object' && value !== null && !Array.isArray(value)
43​
44/** The node and its `anyOf` members: FAL wraps optional fields as `T | null`. */
45function variants(node: unknown): Array<Record<string, unknown>> {
46 if (!isRecord(node)) return []
47 const anyOf = Array.isArray(node.anyOf) ? node.anyOf.filter(isRecord) : []
48 return [node, ...anyOf]
50​
51function stringEnum(node: unknown): Array<string> | null {
52 const found = variants(node).filter((v) => Array.isArray(v.enum))
53 const only = found.length === 1 ? found[0]?.enum : null
54 return Array.isArray(only) &&
55 only.length > 0 &&
56 only.every((item): item is string => typeof item === 'string')
57 ? only
58 : null
60​
61/**
62 * Shared levels this enum actually names. Null when a value is not one of
63 * those levels, or when `high` is missing — "on" is effort high.
64 */
65function effortLevelMap(
66 accepted: ReadonlyArray<string>,
67): EffortLevelMap | null {
68 const shared = new Set<string>(SHARED_EFFORT_LEVELS)
69 if (!accepted.every((effort) => shared.has(effort))) return null
70 if (!accepted.includes('high')) return null
71 const has = (level: string): string | null =>
72 accepted.includes(level) ? level : null
73 return {
74 off: has('none') ?? has('off'),
75 minimal: has('minimal'),
76 low: has('low'),
77 medium: has('medium'),
78 high: 'high',
79 xhigh: has('xhigh'),
80 max: has('max'),
81 }
83​
84/**
85 * Wire map from this endpoint's own properties. A router's boolean
86 * `reasoning` only asks for the trace back; it is not a thinking body.
87 * No max-token field and no effort or think/no_think switch → null.
88 */
89function falRequestMap(
90 properties: Record<string, unknown>,
91): ModelInfo['requestMap'] {
92 const maxTokensField =
93 'max_completion_tokens' in properties
94 ? 'max_completion_tokens'
95 : 'max_tokens' in properties
96 ? 'max_tokens'
97 : null
98 const efforts = stringEnum(properties.reasoning_effort)
99 const thinking = stringEnum(properties.thinking)
100 const mode = stringEnum(properties.reasoning_mode)
101 let thinkingRequest: NonNullable<ModelInfo['requestMap']>['thinking'] = null
102 if (efforts?.includes('high') && thinking?.includes('enabled')) {
103 thinkingRequest = {
104 on: { thinking: 'enabled', reasoning_effort: 'high' },
105 off: thinking.includes('disabled') ? { thinking: 'disabled' } : null,
106 levels: effortLevelMap(efforts),
107 }
108 } else if (
109 !efforts &&
110 !thinking &&
111 [...(mode ?? [])].sort().join() === 'no_think,think'
112 ) {
113 thinkingRequest = {
114 on: { reasoning_mode: 'think' },
115 off: { reasoning_mode: 'no_think' },
116 levels: null,
117 }
118 }
119 const reasoningEffort = 'reasoning_effort' in properties ? true : null
120 if (
121 maxTokensField === null &&
122 thinkingRequest === null &&
123 reasoningEffort !== true
124 ) {
125 return null
126 }
127 return {
128 thinking: thinkingRequest,
129 maxTokensField,
130 developerRole: null,
131 replayReasoningContent: null,
132 store: null,
133 strictTools: null,
134 sessionAffinity: null,
135 cacheControl: null,
136 toolStream: null,
137 reasoningEffort,
138 }
140​
141function integerMaximum(node: unknown): number | null {
142 const found = variants(node).filter(
143 (v) => v.type === 'integer' && typeof v.maximum === 'number',
144 )
145 const maximum = found.length === 1 ? found[0]?.maximum : null
146 return typeof maximum === 'number' && Number.isInteger(maximum) && maximum > 0
147 ? maximum
148 : null
150​
151/** The one context size the description states, or null. */
152export function falDescriptionContextWindow(
153 description: string | undefined,
154): number | null {
155 const stated = new Set(
156 [...(description ?? '').matchAll(CONTEXT)].map((m) => tokenCount(m[1])),
157 )
158 const [only] = [...stated]
159 return stated.size === 1 && only != null && only > 0 ? only : null
161​
162/** The models API URL that returns one endpoint with its OpenAPI document. */
163export function falEndpointSpecUrl(listingUrl: string, rawId: string): string {
164 return `${listingUrl}?endpoint_id=${rawId}&expand=openapi-3.0`
166​
167export function falChatFacts(
168 model: {
169 endpoint_id: string
170 description?: string
171 openapi?: OpenApiDocument
172 },
173 listingUrl: string,
174): FalChatFacts {
175 const facts: FalChatFacts = {}
176 const sources: ModelFactSources = {}
177​
178 const contextWindow = falDescriptionContextWindow(model.description)
179 if (contextWindow !== null) {
180 facts.contextWindow = contextWindow
181 sources.contextWindow = {
182 derivation: 'listing',
183 sourceUrl: listingUrl,
184 path: 'metadata.description',
185 }
186 }
187​
188 const rawId = model.endpoint_id
189 // A spec fetched by `endpoint_id` can name its path by the app's internal
190 // alias (`/fal-ai/nemotron-…` for `nvidia/nemotron-…`), so take the
191 // document's one POST path instead of building it from the id.
192 const posts = Object.entries(model.openapi?.paths ?? {})
193 .filter(([, operations]) => operations.post !== undefined)
194 .map(([path]) => path)
195 const [postPath] = posts
196 const extracted =
197 model.openapi && posts.length === 1 && postPath !== undefined
198 ? extractEndpointSchemas(model.openapi, postPath, 'sibling-get')
199 : null
200 const input = extracted?.input
201 const properties = isRecord(input?.properties) ? input.properties : {}
202 if (Object.keys(properties).length > 0) {
203 const sourceUrl = falEndpointSpecUrl(listingUrl, rawId)
204 const source = (path: string): FactSource => ({
205 derivation: 'upstream-spec',
206 sourceUrl,
207 endpointId: rawId,
208 path,
209 })
210​
211 for (const name of MAX_OUTPUT_PROPERTIES) {
212 const maximum = integerMaximum(properties[name])
213 if (maximum === null) continue
214 facts.maxOutput = maximum
215 sources.maxOutput = source(`/properties/${name}/maximum`)
216 break
217 }
218​
219 // `thinking` must name `enabled`, or the enum is a shape we do not know.
220 const efforts = stringEnum(properties.reasoning_effort)
221 const thinking = stringEnum(properties.thinking)
222 // The endpoint's own on/off switch. Any other value set is not read.
223 const mode = stringEnum(properties.reasoning_mode)
224 let reasoning: ModelReasoning | null = null
225 if (efforts && thinking?.includes('enabled')) {
226 reasoning = {
227 mode: 'effort',
228 mandatory: !thinking.includes('disabled'),
229 efforts,
230 }
231 facts.reasoning = reasoning
232 sources.reasoning = source('/properties/reasoning_effort')
233 } else if (
234 !efforts &&
235 !thinking &&
236 [...(mode ?? [])].sort().join() === 'no_think,think'
237 ) {
238 reasoning = { mode: 'toggle', mandatory: false }
239 facts.reasoning = reasoning
240 sources.reasoning = source('/properties/reasoning_mode')
241 }
242​
243 // Text is named by `prompt`, never assumed.
244 if ('prompt' in properties) {
245 const media = Object.keys(properties)
246 .map((name) => MEDIA_PROPERTY.exec(name)?.[1])
247 .filter((medium) => medium !== undefined)
248 const output = extracted?.output?.properties
249 const emitsText =
250 isRecord(output) &&
251 isRecord(output.output) &&
252 output.output.type === 'string'
253 facts.modalities = {
254 input: ['text', ...new Set(media)],
255 output: emitsText ? ['text'] : [],
256 }
257 sources.modalities = source('/properties')
258 }
259​
260 // The router's boolean `reasoning` only asks for the trace in the
261 // answer. Keep the flag for rows whose reasoning config was read.
262 const walk = walkRequestSchema(input, {
263 derivation: 'upstream-spec',
264 endpointId: rawId,
265 sourceUrl,
266 })
267 const flags = (walk?.flags ?? []).filter(
268 (flag) => flag !== 'reasoning' || reasoning !== null,
269 )
270 facts.capabilities = flags
271 if (flags.length > 0) {
272 sources.capabilities = Object.fromEntries(
273 flags.map((flag) => [
274 flag,
275 walk?.sources.capabilities?.[flag] ?? source('/properties'),
276 ]),
277 )
278 }
279​
280 const requestMap = falRequestMap(properties)
281 if (requestMap) {
282 facts.requestMap = requestMap
283 const path = requestMap.maxTokensField
284 ? `/properties/${requestMap.maxTokensField}`
285 : requestMap.reasoningEffort
286 ? '/properties/reasoning_effort'
287 : '/properties/reasoning_mode'
288 sources.requestMap = source(path)
289 }
290 }
291​
292 if (Object.keys(sources).length > 0) facts.factSources = sources
293 return facts