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