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

text.ts

151 lines4.9 KB

1import OpenAI from 'openai'
2import { OpenAIBaseChatCompletionsTextAdapter } from '@tanstack/openai-base'
3import {
4 LLMGATEWAY_MODEL_INPUT_MODALITIES,
5 LLMGATEWAY_MODEL_REASONING,
6} from '../model-meta'
7import {
8 getLLMGatewayApiKeyFromEnv,
9 withLLMGatewayDefaults,
10} from '../utils/client'
11import type { Modality } from '@tanstack/ai'
12import type {
13 LLMGatewayChatModelToolCapabilitiesByName,
14 LLMGatewayModelId,
15 LLMGatewayModelReasoningByName,
16 ResolveInputModalities,
17 ResolveProviderOptions,
18} from '../model-meta'
19import type { LLMGatewayMessageMetadataByModality } from '../message-types'
20import type { LLMGatewayClientConfig } from '../utils/client'
21import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
22​
23/**
24 * The reasoning levels of a model, for `chat({ reasoning })`. This API has
25 * no token budget field, so no model takes `budgetTokens` here. `never`:
26 * the model does not reason.
27 */
28type ResolveReasoning<TModel extends string> =
29 TModel extends keyof LLMGatewayModelReasoningByName
30 ? {
31 levels: LLMGatewayModelReasoningByName[TModel]['levels']
32 budget: false
33 }
34 : never
35​
36type ResolveToolCapabilities<TModel extends string> =
37 TModel extends keyof LLMGatewayChatModelToolCapabilitiesByName
38 ? NonNullable<LLMGatewayChatModelToolCapabilitiesByName[TModel]>
39 : readonly []
40​
41/**
42 * Configuration for LLM Gateway text adapter
43 */
44export interface LLMGatewayTextConfig
45 extends LLMGatewayClientConfig, OpenAIBaseTextAdapterOptions {}
46​
47/**
48 * Re-export of the public provider options type
49 */
50export type { ExternalTextProviderOptions as LLMGatewayTextProviderOptions } from '../text/text-provider-options'
51​
52/**
53 * LLM Gateway Text (Chat) Adapter
54 *
55 * Tree-shakeable adapter for LLM Gateway chat/text completion. LLM Gateway
56 * exposes one OpenAI-compatible Chat Completions endpoint that routes to
57 * hundreds of models across many providers, so the adapter drives it with
58 * the OpenAI SDK via a `baseURL` override (the same pattern as `ai-grok`
59 * and `ai-groq`).
60 *
61 * Model ids are open-ended: curated ids get per-model type metadata, and
62 * any other id from https://llmgateway.io/models works with text-only
63 * defaults. A `provider/model` id (e.g. `openai/gpt-5.5`) pins routing to
64 * that provider; a bare id lets the gateway pick.
65 */
66export class LLMGatewayTextAdapter<
67 TModel extends LLMGatewayModelId,
68 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
69 TInputModalities extends ReadonlyArray<Modality> =
70 ResolveInputModalities<TModel>,
71 TToolCapabilities extends ReadonlyArray<string> =
72 ResolveToolCapabilities<TModel>,
73> extends OpenAIBaseChatCompletionsTextAdapter<
74 TModel,
75 TProviderOptions,
76 TInputModalities,
77 LLMGatewayMessageMetadataByModality,
78 TToolCapabilities,
79 ResolveReasoning<TModel>
80> {
81 override readonly kind = 'text' as const
82 override readonly name = 'llmgateway' as const
83 override readonly inputModalities =
84 LLMGATEWAY_MODEL_INPUT_MODALITIES[this.model]
85​
86 constructor(config: LLMGatewayTextConfig, model: TModel) {
87 super(
88 model,
89 'llmgateway',
90 new OpenAI(withLLMGatewayDefaults(config)),
91 config,
92 )
93 }
94​
95 protected override modelReasoning(model: string) {
96 return LLMGATEWAY_MODEL_REASONING[model]
97 }
98​
99 /**
100 * Surfaces reasoning deltas during streaming. LLM Gateway normalizes
101 * upstream reasoning output to `delta.reasoning_content` on the OpenAI
102 * Chat Completions wire format (the DeepSeek-style field most
103 * OpenAI-compatible providers emit); some routed providers emit
104 * `delta.reasoning` instead, so both are read.
105 */
106 protected override extractReasoning(
107 chunk: OpenAI.Chat.Completions.ChatCompletionChunk,
108 ): { text: string } | undefined {
109 const delta = chunk.choices?.[0]?.delta as
110 | { reasoning?: unknown; reasoning_content?: unknown }
111 | undefined
112 const raw = delta?.reasoning_content ?? delta?.reasoning
113 if (typeof raw === 'string' && raw.length > 0) {
114 return { text: raw }
115 }
116 return undefined
117 }
119​
120/**
121 * Creates an LLM Gateway text adapter with explicit API key.
122 *
123 * @example
124 * ```typescript
125 * const adapter = createLLMGatewayText('gpt-5.6-terra', "llmgtwy_...");
126 * ```
127 */
128export function createLLMGatewayText<TModel extends LLMGatewayModelId>(
129 model: TModel,
130 apiKey: string,
131 config?: Omit<LLMGatewayTextConfig, 'apiKey'>,
132): LLMGatewayTextAdapter<TModel> {
133 return new LLMGatewayTextAdapter({ apiKey, ...config }, model)
135​
136/**
137 * Creates an LLM Gateway text adapter with API key from
138 * `LLM_GATEWAY_API_KEY`.
139 *
140 * @example
141 * ```typescript
142 * const adapter = llmGatewayText('gpt-5.6-terra');
143 * ```
144 */
145export function llmGatewayText<TModel extends LLMGatewayModelId>(
146 model: TModel,
147 config?: Omit<LLMGatewayTextConfig, 'apiKey'>,
148): LLMGatewayTextAdapter<TModel> {
149 const apiKey = getLLMGatewayApiKeyFromEnv()
150 return createLLMGatewayText(model, apiKey, config)