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

text.ts

262 lines8.0 KB

1import OpenAI from 'openai'
2import { OpenAIBaseChatCompletionsTextAdapter } from '@tanstack/openai-base'
3import {
4 GROQ_MODEL_INPUT_MODALITIES,
5 GROQ_MODEL_REASONING,
6 groqModelPrefersJsonObject,
7} from '../model-meta'
8import { getGroqApiKeyFromEnv, withGroqDefaults } from '../utils/client'
9import { makeGroqStructuredOutputCompatibleWithMap } from '../utils/schema-converter'
10import type { Modality, TextOptions } from '@tanstack/ai'
11import type {
12 GROQ_CHAT_MODELS,
13 GroqChatModelToolCapabilitiesByName,
14 GroqModelReasoningByName,
15 ResolveInputModalities,
16 ResolveProviderOptions,
17} from '../model-meta'
18import type { GroqMessageMetadataByModality } from '../message-types'
19import type { GroqClientConfig } from '../utils/client'
20import type { OpenAIBaseTextAdapterOptions } from '@tanstack/openai-base'
21​
22/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */
23type ResolveReasoning<TModel extends string> =
24 TModel extends keyof GroqModelReasoningByName
25 ? GroqModelReasoningByName[TModel]
26 : never
27​
28type ResolveToolCapabilities<TModel extends string> =
29 TModel extends keyof GroqChatModelToolCapabilitiesByName
30 ? NonNullable<GroqChatModelToolCapabilitiesByName[TModel]>
31 : readonly []
32​
33/**
34 * Configuration for Groq text adapter
35 */
36export interface GroqTextConfig
37 extends GroqClientConfig, OpenAIBaseTextAdapterOptions {}
38​
39/**
40 * Re-export of the public provider options type
41 */
42export type { ExternalTextProviderOptions as GroqTextProviderOptions } from '../text/text-provider-options'
43​
44/**
45 * Groq Text (Chat) Adapter
46 *
47 * Tree-shakeable adapter for Groq chat/text completion. Groq exposes an
48 * OpenAI-compatible Chat Completions endpoint at `/openai/v1`, so we drive
49 * it with the OpenAI SDK via a `baseURL` override (the same pattern as
50 * `ai-grok`).
51 *
52 * Quirk: when usage is present on a stream, Groq historically delivered it
53 * under `chunk.x_groq.usage` rather than `chunk.usage`. The override below
54 * promotes it to the standard location so the base's RUN_FINISHED usage
55 * accounting works unchanged.
56 */
57export class GroqTextAdapter<
58 TModel extends (typeof GROQ_CHAT_MODELS)[number],
59 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
60 TInputModalities extends ReadonlyArray<Modality> =
61 ResolveInputModalities<TModel>,
62 TToolCapabilities extends ReadonlyArray<string> =
63 ResolveToolCapabilities<TModel>,
64> extends OpenAIBaseChatCompletionsTextAdapter<
65 TModel,
66 TProviderOptions,
67 TInputModalities,
68 GroqMessageMetadataByModality,
69 TToolCapabilities,
70 ResolveReasoning<TModel>
71> {
72 override readonly kind = 'text' as const
73 override readonly name = 'groq' as const
74 override readonly inputModalities = GROQ_MODEL_INPUT_MODALITIES[this.model]
75​
76 constructor(config: GroqTextConfig, model: TModel) {
77 super(model, 'groq', new OpenAI(withGroqDefaults(config)), config)
78 }
79​
80 protected override modelReasoning(model: string) {
81 return GROQ_MODEL_REASONING[model]
82 }
83​
84 protected override extractRejectedToolCall(
85 rawEvent: unknown,
86 fallbackMessage: string,
87 ):
88 | {
89 toolName: string
90 arguments: string
91 input?: unknown
92 error: string
93 }
94 | undefined {
95 if (
96 !isRecord(rawEvent) ||
97 rawEvent.code !== 'tool_use_failed' ||
98 typeof rawEvent.failed_generation !== 'string'
99 ) {
100 return undefined
101 }
102​
103 let failedGeneration: unknown
104 try {
105 failedGeneration = JSON.parse(rawEvent.failed_generation)
106 } catch {
107 return undefined
108 }
109 if (
110 !isRecord(failedGeneration) ||
111 typeof failedGeneration.name !== 'string' ||
112 failedGeneration.name.trim().length === 0
113 ) {
114 return undefined
115 }
116​
117 const rawArguments = failedGeneration.arguments
118 let argumentsJson: string
119 let input: unknown
120 if (typeof rawArguments === 'string') {
121 argumentsJson = rawArguments
122 try {
123 const parsed: unknown = JSON.parse(rawArguments)
124 if (isRecord(parsed)) input = parsed
125 } catch {
126 // The provider-rejected call remains non-executable with its raw input.
127 }
128 } else if (isRecord(rawArguments)) {
129 argumentsJson = JSON.stringify(rawArguments)
130 input = rawArguments
131 } else {
132 return undefined
133 }
134​
135 return {
136 toolName: failedGeneration.name,
137 arguments: argumentsJson,
138 ...(input !== undefined && { input }),
139 error:
140 typeof rawEvent.message === 'string' && rawEvent.message.length > 0
141 ? rawEvent.message
142 : fallbackMessage,
143 }
144 }
145​
146 protected override makeStructuredOutputCompatibleWithMap(
147 schema: Record<string, any>,
148 originalRequired?: Array<string>,
149 ) {
150 return makeGroqStructuredOutputCompatibleWithMap(schema, originalRequired)
151 }
152​
153 protected override async *processStreamChunks(
154 stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,
155 options: TextOptions,
156 aguiState: {
157 runId: string
158 threadId: string
159 messageId: string
160 hasEmittedRunStarted: boolean
161 },
162 ) {
163 yield* super.processStreamChunks(
164 promoteGroqUsage(stream),
165 options,
166 aguiState,
167 )
168 }
169​
170 /**
171 * Surfaces Groq's reasoning deltas during streaming structured output.
172 * Groq emits `delta.reasoning` (or legacy `delta.reasoning_content`) on
173 * reasoning models when the caller sets `reasoning_format: 'parsed'` in
174 * modelOptions. The base's chatStream and structuredOutputStream both
175 * route reasoning through this hook.
176 */
177 protected override extractReasoning(
178 chunk: OpenAI.Chat.Completions.ChatCompletionChunk,
179 ): { text: string } | undefined {
180 const delta = chunk.choices?.[0]?.delta as
181 | { reasoning?: unknown; reasoning_content?: unknown }
182 | undefined
183 const raw = delta?.reasoning ?? delta?.reasoning_content
184 if (typeof raw === 'string' && raw.length > 0) {
185 return { text: raw }
186 }
187 return undefined
188 }
189​
190 /**
191 * Groq's API rejects `response_format: json_schema` together with `tools`
192 * + `stream` (returns 400 — see Groq Structured Outputs docs:
193 * "Streaming and tool use are not currently supported with Structured
194 * Outputs."). Force the engine onto the legacy finalization path even
195 * though the OpenAI Chat Completions base would otherwise opt in.
196 */
197 override supportsCombinedToolsAndSchema(): boolean {
198 return false
199 }
200​
201 protected override modelPrefersJsonObject(model: string): boolean {
202 return groqModelPrefersJsonObject(model)
203 }
205​
206function isRecord(value: unknown): value is Record<string, unknown> {
207 return typeof value === 'object' && value !== null && !Array.isArray(value)
209​
210/**
211 * Promotes Groq's non-standard `x_groq.usage` to the standard `chunk.usage`
212 * slot the base reads. Pass-through for chunks that already carry usage at
213 * the documented location.
214 */
215async function* promoteGroqUsage(
216 stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,
217): AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk> {
218 for await (const chunk of stream) {
219 const groqChunk = chunk as typeof chunk & {
220 x_groq?: { usage?: OpenAI.Chat.Completions.ChatCompletionChunk['usage'] }
221 }
222 if (!chunk.usage && groqChunk.x_groq?.usage) {
223 yield { ...chunk, usage: groqChunk.x_groq.usage }
224 } else {
225 yield chunk
226 }
227 }
229​
230/**
231 * Creates a Groq text adapter with explicit API key.
232 *
233 * @example
234 * ```typescript
235 * const adapter = createGroqText('llama-3.3-70b-versatile', "gsk_...");
236 * ```
237 */
238export function createGroqText<
239 TModel extends (typeof GROQ_CHAT_MODELS)[number],
240>(
241 model: TModel,
242 apiKey: string,
243 config?: Omit<GroqTextConfig, 'apiKey'>,
244): GroqTextAdapter<TModel> {
245 return new GroqTextAdapter({ apiKey, ...config }, model)
247​
248/**
249 * Creates a Groq text adapter with API key from `GROQ_API_KEY`.
250 *
251 * @example
252 * ```typescript
253 * const adapter = groqText('llama-3.3-70b-versatile');
254 * ```
255 */
256export function groqText<TModel extends (typeof GROQ_CHAT_MODELS)[number]>(
257 model: TModel,
258 config?: Omit<GroqTextConfig, 'apiKey'>,
259): GroqTextAdapter<TModel> {
260 const apiKey = getGroqApiKeyFromEnv()
261 return createGroqText(model, apiKey, config)