Open History to see the last commit
1/**
2 * Chat facts the Fireworks inference listing does not carry.
3 *
4 * Standard and Fast prices are sku amounts on
5 * `GET /v1/serverless/models`. Priority is a separate serving mode.
6 * A row with no mode (FireRouter `auto`) names no single rate. When the
7 * pricing page's Standard cell matches, that page stays the source; the
8 * API fills ids the page omits. A disagreement drops that id.
9 *
10 * Reasoning and the shared chat request fields come from
11 * `text-completion.openapi.yaml`. A family that prose does not name gets
12 * the shared request map and no reasoning object.
13 */
14import { compileTokenCard } from '@modelschemas/rate-card'
15
16import { tagDocsFacts } from './fact-sources.ts'
17import { FIREWORKS_PRICING_URL } from './fireworks-pricing.ts'
18import type {
19 FireworksPricingDoc,
20 FireworksRates,
21} from './fireworks-pricing.ts'
22import { assertParsed } from './model-facts.ts'
23import type { cachedDocs } from './model-facts.ts'
24import type {
25 ChatRequestMap,
26 EffortLevelMap,
27 SharedEffortLevel,
28 ThinkingRequest,
29} from './request-map.ts'
30import {
31 fetchOpenApi,
32 fetchText,
33 reasoningViolation,
34 sha256Text,
35} from './types.ts'
36import type { ModelFactSources, ModelInfo, ModelReasoning } from './types.ts'
37
38export const FIREWORKS_SPEC_URL =
39 'https://docs.fireworks.ai/text-completion.openapi.yaml'
40export const FIREWORKS_SERVERLESS_URL =
41 'https://api.fireworks.ai/v1/serverless/models'
42
43const LLM_INPUT = 'LLM input tokens (uncached)'
44const LLM_CACHED = 'LLM input tokens (cached)'
45const LLM_OUTPUT = 'LLM output tokens'
46const PER_MILLION = '1M tokens'
47
48const EFFORT_WORDS = [
49 'none',
50 'low',
51 'medium',
52 'high',
53 'xhigh',
54 'max',
55 'adaptive',
56] as const
57
58/** Backtick tokens that are request values, not model ids. */
59const NOT_A_MODEL = new Set<string>([...EFFORT_WORDS, 'true', 'false'])
60
61export interface FireworksFamily {
62 tokens: Array<string>
63 reasoning: ModelReasoning
64 thinking: ThinkingRequest
65}
66
67export interface FireworksSharedRequest {
68 maxTokensField: 'max_completion_tokens' | 'max_tokens' | null
69 developerRole: boolean | null
70 replayReasoningContent: boolean | null
71 sessionAffinity: boolean | null
72}
73
74export interface FireworksChatSpec {
75 families: Array<FireworksFamily>
76 shared: FireworksSharedRequest
77}
78
79export interface FireworksServerlessDoc {
80 rates: Record<string, FireworksRates>
81 context: Record<string, number>
82 hash: string
83 extractedAt: string
84}
85
86export interface FireworksPriced {
87 rates: FireworksRates
88 sourceUrl: string
89 sourceHash: string
90 extractedAt: string
91}
92
93interface ServerlessRow {
94 id: string
95 mode: string | null
96 usage: string
97 pricing: unknown
98 context: number | null
99}
100
101function asRecord(value: unknown): Record<string, unknown> | null {
102 if (typeof value !== 'object' || value === null || Array.isArray(value)) {
103 return null
104 }
105 return value as Record<string, unknown>
106}
107
108function schema(spec: unknown, name: string): Record<string, unknown> | null {
109 const root = asRecord(spec)
110 const components = asRecord(root?.components)
111 const schemas = asRecord(components?.schemas)
112 return asRecord(schemas?.[name])
113}
114
115function properties(
116 node: Record<string, unknown> | null,
117): Record<string, unknown> | null {
118 return asRecord(node?.properties)
119}
120
121function descriptionOf(node: unknown): string {
122 const record = asRecord(node)
123 return typeof record?.description === 'string' ? record.description : ''
124}
125
126function fireworksSlug(name: string): string {
127 return name
128 .trim()
129 .toLowerCase()
130 .replace(/&/g, ' ')
131 .replace(/\./g, 'p')
132 .replace(/[^a-z0-9]+/g, '-')
133 .replace(/^-+|-+$/g, '')
134}
135
136/** Markdown wraps `'none'` as a code span. The quotes are the value. */
137function prose(body: string): string {
138 return body.replace(/`/g, '')
139}
140
141function quotedEfforts(body: string): Array<string> {
142 const found = new Set<string>()
143 for (const match of prose(body).matchAll(/'([a-z]+)'/g)) {
144 const word = match[1]
145 if (word && (EFFORT_WORDS as ReadonlyArray<string>).includes(word)) {
146 found.add(word)
147 }
148 }
149 return EFFORT_WORDS.filter((word) => found.has(word))
150}
151
152function levelsFor(efforts: ReadonlyArray<string>): EffortLevelMap {
153 const accepted = new Set(efforts)
154 const value = (level: SharedEffortLevel): string | null => {
155 if (level === 'off') return accepted.has('none') ? 'none' : null
156 if (level === 'minimal') return accepted.has('minimal') ? 'minimal' : null
157 return accepted.has(level) ? level : null
158 }
159 return {
160 off: value('off'),
161 minimal: value('minimal'),
162 low: value('low'),
163 medium: value('medium'),
164 high: value('high'),
165 xhigh: value('xhigh'),
166 max: value('max'),
167 }
168}
169
170function effortFamily(
171 body: string,
172 mandatory: boolean,
173): Omit<FireworksFamily, 'tokens'> | null {
174 const quoted = quotedEfforts(body)
175 const efforts = mandatory ? quoted.filter((word) => word !== 'none') : quoted
176 const positive = efforts.filter((word) => word !== 'none')
177 const on = positive.includes('high') ? 'high' : positive[0]
178 if (!on || positive.length === 0) return null
179 return {
180 reasoning: { mode: 'effort', mandatory, efforts },
181 thinking: {
182 on: { reasoning_effort: on },
183 off: efforts.includes('none') ? { reasoning_effort: 'none' } : null,
184 levels: levelsFor(efforts),
185 },
186 }
187}
188
189/**
190 * The bullet's own words decide the mode. Binary on/off is a toggle.
191 * A bullet that rejects `'none'` cannot be turned off. A bullet that says
192 * thinking can be disabled is effort, and the quoted levels are the
193 * accepted strings (a promoted level is still accepted).
194 */
195function classifyBullet(body: string): Omit<FireworksFamily, 'tokens'> | null {
196 const text = prose(body)
197 if (/binary on\/off/i.test(text)) {
198 return {
199 reasoning: { mode: 'toggle', mandatory: false },
200 thinking: {
201 on: { reasoning_effort: true },
202 off: { reasoning_effort: 'none' },
203 levels: null,
204 },
205 }
206 }
207 const noneRejected =
208 /always on/i.test(text) ||
209 /does not support\s+'none'/i.test(text) ||
210 /'none'[^.]{0,120}rejected/i.test(text)
211 if (noneRejected) return effortFamily(body, true)
212 if (/to disable|disables thinking|disables reasoning/i.test(text)) {
213 return effortFamily(body, false)
214 }
215 return null
216}
217
218function tokensFrom(heading: string, body: string): Array<string> {
219 const pieces = heading.split(/[(),/]/).map(fireworksSlug)
220 const ticks = [...body.matchAll(/`([a-z0-9]+(?:-[a-z0-9]+)*)`/g)].flatMap(
221 (match) => (match[1] ? [match[1]] : []),
222 )
223 const tokens: Array<string> = []
224 const add = (token: string) => {
225 if (!token || NOT_A_MODEL.has(token) || tokens.includes(token)) return
226 tokens.push(token)
227 }
228 for (const token of pieces) add(token)
229 // Rejected effort names (`minimal`, `ultra`) are backticked too. The
230 // conversation styles this spec names all include a digit.
231 for (const token of ticks) {
232 if (token.includes('no-thinking') || !/\d/.test(token)) continue
233 add(token)
234 }
235 return tokens
236}
237
238function familiesFrom(description: string): Array<FireworksFamily> {
239 const marker = description.indexOf('Model-specific behavior:')
240 if (marker < 0) return []
241 const section = description.slice(marker)
242 const families: Array<FireworksFamily> = []
243 const bullets = section.matchAll(
244 /\n-\s+\*\*([^*]+)\*\*:\s*([\s\S]*?)(?=\n-\s+\*\*|$)/g,
245 )
246 for (const match of bullets) {
247 const heading = match[1]?.trim()
248 const body = match[2]?.trim()
249 if (!heading || !body) continue
250 const classified = classifyBullet(body)
251 if (!classified || reasoningViolation(classified.reasoning)) continue
252 const tokens = tokensFrom(heading, body)
253 if (tokens.length === 0) continue
254 families.push({ tokens, ...classified })
255 }
256 return families
257}
258
259/** MiniMax M3 is not a model-specific bullet. Its schema says adaptive. */
260function adaptiveFamily(
261 spec: unknown,
262 description: string,
263 families: ReadonlyArray<FireworksFamily>,
264): FireworksFamily | null {
265 const about = descriptionOf(schema(spec, 'ThinkingConfigAdaptive'))
266 const named = /MiniMax M3/.exec(about)
267 if (!named || !/adaptive/i.test(about)) return null
268 if (!/'adaptive' is supported only by MiniMax M3/.test(prose(description))) {
269 return null
270 }
271 const token = fireworksSlug(named[0])
272 if (families.some((family) => family.tokens.includes(token))) return null
273 return {
274 tokens: [token],
275 reasoning: { mode: 'adaptive', mandatory: null, efforts: ['adaptive'] },
276 thinking: {
277 on: { thinking: { type: 'adaptive' } },
278 off: null,
279 levels: null,
280 },
281 }
282}
283
284function sharedRequest(
285 spec: unknown,
286 props: Record<string, unknown>,
287): FireworksSharedRequest {
288 const hasMax = 'max_tokens' in props
289 const hasCompletion = 'max_completion_tokens' in props
290 const alias = /alias for max_tokens/i.test(
291 descriptionOf(props.max_completion_tokens),
292 )
293 let maxTokensField: FireworksSharedRequest['maxTokensField'] = null
294 if (hasMax && alias) maxTokensField = 'max_tokens'
295 else if (hasMax && !hasCompletion) maxTokensField = 'max_tokens'
296 else if (hasCompletion && !hasMax) maxTokensField = 'max_completion_tokens'
297
298 const message = properties(schema(spec, 'ChatMessage'))
299 const roles = [
300 ...descriptionOf(message?.role).matchAll(/`([a-z]+)`/g),
301 ].flatMap((match) => (match[1] ? [match[1]] : []))
302 return {
303 maxTokensField,
304 developerRole: roles.length === 0 ? null : roles.includes('developer'),
305 replayReasoningContent:
306 message !== null && 'reasoning_content' in message ? true : null,
307 sessionAffinity: /session affinity/i.test(
308 descriptionOf(props.prompt_cache_key),
309 )
310 ? true
311 : null,
312 }
313}
314
315export function parseFireworksChatSpec(spec: unknown): FireworksChatSpec {
316 const request = schema(spec, 'ChatCompletionRequest')
317 const props = properties(request)
318 if (!request || !props) {
319 throw new Error('fireworks chat spec: ChatCompletionRequest is missing')
320 }
321 const description = descriptionOf(props.reasoning_effort)
322 const families = familiesFrom(description)
323 const adaptive = adaptiveFamily(spec, description, families)
324 if (adaptive) families.push(adaptive)
325 if (families.length === 0) {
326 throw new Error('fireworks chat spec: parsed 0 reasoning families')
327 }
328 return { families, shared: sharedRequest(spec, props) }
329}
330
331function tokenMatches(slug: string, token: string): boolean {
332 return (
333 slug === token || slug.startsWith(`${token}-`) || token.endsWith(`-${slug}`)
334 )
335}
336
337/** Longest style or heading token wins. The id used is the last path segment. */
338export function matchFireworksFamily(
339 rawId: string,
340 families: ReadonlyArray<FireworksFamily>,
341): FireworksFamily | null {
342 const slash = rawId.lastIndexOf('/')
343 const slug = (slash === -1 ? rawId : rawId.slice(slash + 1)).toLowerCase()
344 let best: { family: FireworksFamily; length: number } | null = null
345 for (const family of families) {
346 for (const token of family.tokens) {
347 if (!tokenMatches(slug, token)) continue
348 if (best && token.length <= best.length) continue
349 best = { family, length: token.length }
350 }
351 }
352 return best?.family ?? null
353}
354
355export function fireworksRequestMap(
356 shared: FireworksSharedRequest,
357 family: FireworksFamily | null,
358): ChatRequestMap {
359 return {
360 thinking: family?.thinking ?? null,
361 maxTokensField: shared.maxTokensField,
362 developerRole: shared.developerRole,
363 replayReasoningContent: shared.replayReasoningContent,
364 store: null,
365 strictTools: null,
366 sessionAffinity: shared.sessionAffinity,
367 cacheControl: null,
368 toolStream: null,
369 reasoningEffort: family ? true : null,
370 }
371}
372
373function serverlessRows(body: unknown): Array<ServerlessRow> {
374 const root = asRecord(body)
375 const data = Array.isArray(body) ? body : root?.data
376 if (!Array.isArray(data)) {
377 throw new Error('fireworks serverless models: unreadable response')
378 }
379 const rows: Array<ServerlessRow> = []
380 for (const item of data) {
381 const record = asRecord(item)
382 if (!record || typeof record.id !== 'string' || record.id.length === 0) {
383 continue
384 }
385 const mode = record.serverless_mode
386 const context = record.context_length
387 rows.push({
388 id: record.id,
389 mode: typeof mode === 'string' ? mode : null,
390 usage:
391 typeof record.usage_identifier === 'string'
392 ? record.usage_identifier
393 : '',
394 pricing: record.pricing,
395 context:
396 typeof context === 'number' && Number.isInteger(context) && context > 0
397 ? context
398 : null,
399 })
400 }
401 return rows
402}
403
404/** Fast prices `usage_identifier`. Standard prices that id, or else `id`. */
405function billedId(row: ServerlessRow): string | null {
406 if (row.mode === 'fast') return row.usage.length > 0 ? row.usage : null
407 if (row.mode === 'standard') return row.usage.length > 0 ? row.usage : row.id
408 return null
409}
410
411function money(value: unknown): number | null {
412 if (typeof value !== 'number' && typeof value !== 'string') return null
413 if (typeof value === 'string' && value.trim() === '') return null
414 const amount = typeof value === 'number' ? value : Number(value)
415 if (!Number.isFinite(amount) || amount < 0) return null
416 return amount
417}
418
419function skuAmount(pricing: Array<unknown>, sku: string): number | null {
420 const hits = pricing.filter((item) => asRecord(item)?.sku === sku)
421 if (hits.length !== 1) return null
422 const row = asRecord(hits[0])
423 if (!row || row.unit !== PER_MILLION) return null
424 return money(row.amount)
425}
426
427function llmRates(pricing: unknown): FireworksRates | null {
428 if (!Array.isArray(pricing)) return null
429 const input = skuAmount(pricing, LLM_INPUT)
430 const cacheRead = skuAmount(pricing, LLM_CACHED)
431 const output = skuAmount(pricing, LLM_OUTPUT)
432 if (input === null || cacheRead === null || output === null) return null
433 return { input, cacheRead, output }
434}
435
436function sameRates(left: FireworksRates, right: FireworksRates): boolean {
437 return (
438 left.input === right.input &&
439 left.cacheRead === right.cacheRead &&
440 left.output === right.output
441 )
442}
443
444/**
445 * Priority and modeless rows are skipped. Embedding-only skus are not a
446 * chat card. Two billed ids with different amounts are dropped.
447 */
448export function parseFireworksServerless(body: unknown): {
449 rates: Map<string, FireworksRates>
450 context: Map<string, number>
451} {
452 const rates = new Map<string, FireworksRates>()
453 const dropped = new Set<string>()
454 const context = new Map<string, number>()
455 const contextDropped = new Set<string>()
456 for (const row of serverlessRows(body)) {
457 const id = billedId(row)
458 if (!id) continue
459 const price = llmRates(row.pricing)
460 if (price) {
461 const prior = rates.get(id)
462 if (dropped.has(id) || (prior && !sameRates(prior, price))) {
463 rates.delete(id)
464 dropped.add(id)
465 } else if (!prior) {
466 rates.set(id, price)
467 }
468 }
469 if (row.context !== null) {
470 const prior = context.get(id)
471 if (
472 contextDropped.has(id) ||
473 (prior !== undefined && prior !== row.context)
474 ) {
475 context.delete(id)
476 contextDropped.add(id)
477 } else if (prior === undefined) {
478 context.set(id, row.context)
479 }
480 }
481 }
482 return { rates, context }
483}
484
485export function loadFireworksServerless(
486 kv: KVNamespace | undefined,
487 cached: typeof cachedDocs,
488 apiKey: string,
489): Promise<FireworksServerlessDoc> {
490 return cached(kv, FIREWORKS_SERVERLESS_URL, async () => {
491 const text = await fetchText(FIREWORKS_SERVERLESS_URL, {
492 headers: { Authorization: `Bearer ${apiKey}` },
493 })
494 const parsed: unknown = JSON.parse(text)
495 const rows = parseFireworksServerless(parsed)
496 assertParsed(rows.rates, 'fireworks serverless models')
497 return {
498 rates: Object.fromEntries(rows.rates),
499 context: Object.fromEntries(rows.context),
500 hash: await sha256Text(text),
501 extractedAt: new Date().toISOString(),
502 }
503 })
504}
505
506export function loadFireworksChatSpec(
507 kv: KVNamespace | undefined,
508 cached: typeof cachedDocs,
509): Promise<FireworksChatSpec & { hash: string }> {
510 return cached(kv, FIREWORKS_SPEC_URL, async () => {
511 const { spec, hash } = await fetchOpenApi(FIREWORKS_SPEC_URL)
512 return { ...parseFireworksChatSpec(spec), hash }
513 })
514}
515
516export function mergeFireworksRates(
517 markdown: FireworksPricingDoc | null,
518 serverless: FireworksServerlessDoc | null,
519): Record<string, FireworksPriced> | null {
520 if (!markdown && !serverless) return null
521 const prices: Record<string, FireworksPriced> = {}
522 const ids = new Set([
523 ...Object.keys(markdown?.rates ?? {}),
524 ...Object.keys(serverless?.rates ?? {}),
525 ])
526 for (const id of ids) {
527 const page = markdown?.rates[id]
528 const api = serverless?.rates[id]
529 if (page && api && !sameRates(page, api)) continue
530 if (page) {
531 prices[id] = {
532 rates: page,
533 sourceUrl: FIREWORKS_PRICING_URL,
534 sourceHash: markdown.hash,
535 extractedAt: markdown.extractedAt,
536 }
537 continue
538 }
539 if (api) {
540 prices[id] = {
541 rates: api,
542 sourceUrl: FIREWORKS_SERVERLESS_URL,
543 sourceHash: serverless.hash,
544 extractedAt: serverless.extractedAt,
545 }
546 }
547 }
548 return prices
549}
550
551function capabilityList(value: unknown): Array<string> {
552 if (!Array.isArray(value)) return []
553 return value.filter((item): item is string => typeof item === 'string')
554}
555
556const REASONING_PATH =
557 'components/schemas/ChatCompletionRequest/properties/reasoning_effort/description'
558
559export function applyFireworksDocs(
560 model: ModelInfo,
561 input: {
562 prices: Record<string, FireworksPriced> | null
563 context: Record<string, number>
564 contextHash: string | null
565 chat: (FireworksChatSpec & { hash: string }) | null
566 },
567): Partial<ModelInfo> {
568 const patch: Partial<ModelInfo> = {}
569 const sources: ModelFactSources = {}
570 const absent: NonNullable<ModelInfo['absent']> = {}
571 if (input.prices === null) {
572 absent.pricing = 'unavailable'
573 } else {
574 const row = input.prices[model.rawId]
575 if (row) {
576 const pricing = compileTokenCard(
577 {
578 input_tokens: row.rates.input / 1e6,
579 output_tokens: row.rates.output / 1e6,
580 cache_read_tokens: row.rates.cacheRead / 1e6,
581 },
582 [],
583 {
584 url: row.sourceUrl,
585 hash: row.sourceHash,
586 extractedAt: row.extractedAt,
587 },
588 )
589 if (pricing) {
590 patch.pricing = pricing
591 Object.assign(
592 sources,
593 tagDocsFacts({ pricing }, row.sourceUrl, row.sourceHash),
594 )
595 }
596 }
597 }
598 const context = input.context[model.rawId]
599 if (model.contextWindow == null && context !== undefined) {
600 patch.contextWindow = context
601 sources.contextWindow = {
602 derivation: 'listing',
603 sourceUrl: FIREWORKS_SERVERLESS_URL,
604 ...(input.contextHash ? { sourceHash: input.contextHash } : {}),
605 path: 'context_length',
606 }
607 }
608 if (model.activity === 'chat') {
609 if (!input.chat) {
610 absent.reasoning = 'unavailable'
611 absent.requestMap = 'unavailable'
612 } else {
613 const family = matchFireworksFamily(model.rawId, input.chat.families)
614 patch.requestMap = fireworksRequestMap(input.chat.shared, family)
615 if (family) {
616 patch.reasoning = family.reasoning
617 if (Array.isArray(model.capabilities) || model.capabilities == null) {
618 const caps = capabilityList(model.capabilities)
619 if (!caps.includes('reasoning')) caps.push('reasoning')
620 patch.capabilities = caps
621 }
622 const source = {
623 derivation: 'docs-derived' as const,
624 sourceUrl: FIREWORKS_SPEC_URL,
625 sourceHash: input.chat.hash,
626 path: REASONING_PATH,
627 }
628 sources.reasoning = source
629 sources.capabilities = { reasoning: source }
630 }
631 }
632 }
633 if (
634 sources.pricing ||
635 sources.contextWindow ||
636 sources.reasoning ||
637 sources.capabilities
638 ) {
639 patch.factSources = sources
640 }
641 if (Object.keys(absent).length > 0) {
642 patch.absent = { ...model.absent, ...absent }
643 }
644 return patch
645}