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

groq.md

286 lines9.5 KB

1---
2title: Groq
3id: groq-adapter
4order: 6
5description: "Use the fast Groq inference API in TanStack AI with @tanstack/ai-groq: low-latency chat with Llama, gpt-oss, Qwen, and Kimi, plus Whisper transcription and Orpheus speech."
6keywords:
7 - tanstack ai
8 - groq
9 - fast inference
10 - llama
11 - low latency
12 - adapter
13 - llm
14 - whisper
15 - transcription
16---
17​
18The Groq adapter calls Llama, gpt-oss, Qwen, and Kimi with low latency. It also calls Whisper for transcription and Orpheus for speech.
19​
20## 1. Install
21​
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23​
24react: @tanstack/ai-groq
25vue: @tanstack/ai-groq
26solid: @tanstack/ai-groq
27svelte: @tanstack/ai-groq
28preact: @tanstack/ai-groq
29angular: @tanstack/ai-groq
30vanilla: @tanstack/ai-groq
31octane: @tanstack/ai-groq
32​
33<!-- ::end:tabs -->
34​
35## 2. Set the API key
36​
37Put the key in the environment of your server:
38​
39```bash
40GROQ_API_KEY=gsk_...
41```
42​
43`groqText` and the other short factories read `GROQ_API_KEY`. To pass the key in code, use the `create*` factory of the same adapter:
44​
45```typescript
46import { createGroqText } from "@tanstack/ai-groq";
47​
48const adapter = createGroqText("openai/gpt-oss-120b", process.env.GROQ_API_KEY!);
49```
50​
51## 3. Stream a chat from the server
52​
53```typescript
54import {
55 chat,
56 chatParamsFromRequest,
57 toServerSentEventsResponse,
58} from "@tanstack/ai";
59import { groqText } from "@tanstack/ai-groq";
60​
61export async function POST(request: Request) {
62 const { messages, threadId, runId } = await chatParamsFromRequest(request);
63​
64 const stream = chat({
65 adapter: groqText("openai/gpt-oss-120b"),
66 messages,
67 threadId,
68 runId,
69 });
70​
71 return toServerSentEventsResponse(stream);
73```
74​
75## 4. Render the chat
76​
77The client is the same for every provider. Point `useChat` at your route:
78​
79```tsx
80import { useState } from "react";
81import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
82​
83export function Chat() {
84 const [input, setInput] = useState("");
85 const { messages, sendMessage } = useChat({
86 connection: fetchServerSentEvents("/api/chat"),
87 threadId: "support-chat",
88 });
89​
90 return (
91 <form
92 onSubmit={(event) => {
93 event.preventDefault();
94 sendMessage(input);
95 setInput("");
96 }}
97 >
98 {messages.map((message) => (
99 <p key={message.id}>
100 {message.parts
101 .map((part) => (part.type === "text" ? part.content : ""))
102 .join("")}
103 </p>
104 ))}
105 <input value={input} onChange={(event) => setInput(event.target.value)} />
106 </form>
107 );
109```
110​
111For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
112​
113You now have a streaming chat on Groq. [Tools](../tools/tools) and [Structured Outputs](../structured-outputs/overview) work the same as with every adapter. For the Groq details of both, see [Tool calls that Groq rejects](#tool-calls-that-groq-rejects) and [Structured output](#structured-output).
114​
115## Transcription
116​
117`groqTranscription` turns speech into text with Whisper:
118​
119```typescript
120import { generateTranscription } from "@tanstack/ai";
121import { groqTranscription } from "@tanstack/ai-groq";
122​
123const result = await generateTranscription({
124 adapter: groqTranscription("whisper-large-v3-turbo"),
125 audio: "https://example.com/recording.mp3",
126 language: "en",
127 threadId: "thread-1",
128});
129​
130console.log(result.text);
131​
132// verbose_json (the default) fills language, duration, and timestamped segments
133for (const segment of result.segments ?? []) {
134 console.log(`[${segment.start}s to ${segment.end}s] ${segment.text}`);
136```
137​
138- `audio` takes a `File`, a `Blob`, an `ArrayBuffer`, a base64 string, a data URL, or an `https://` URL. The adapter sends a URL to Groq as it is, with no new upload.
139- Models: `whisper-large-v3-turbo`, `whisper-large-v3`.
140- `responseFormat` takes `json`, `text`, or `verbose_json` (the default). Groq does not support `srt` or `vtt`.
141​
142See [Transcription](../media/transcription).
143​
144## Speech
145​
146`groqSpeech` turns text into speech with the Orpheus models:
147​
148```typescript
149import { generateSpeech } from "@tanstack/ai";
150import { groqSpeech } from "@tanstack/ai-groq";
151​
152const result = await generateSpeech({
153 adapter: groqSpeech("canopylabs/orpheus-v1-english"),
154 text: "Hello from Groq!",
155 threadId: "thread-1",
156 voice: "autumn",
157 format: "wav",
158});
159​
160console.log(result.audio); // Base64-encoded audio
161```
162​
163- Models: `canopylabs/orpheus-v1-english` and `canopylabs/orpheus-arabic-saudi`.
164- English voices: `autumn` (the default), `diana`, `hannah`, `austin`, `daniel`, `troy`.
165- Arabic voices: `fahad`, `sultan`, `lulwa`, `noura`.
166- Formats: `flac`, `mp3`, `mulaw`, `ogg`, and `wav` (the default). `modelOptions.sample_rate` sets the sample rate.
167​
168See [Text-to-Speech](../media/text-to-speech).
169​
170## Summarization
171​
172```typescript
173import { summarize } from "@tanstack/ai";
174import { groqSummarize } from "@tanstack/ai-groq";
175​
176const result = await summarize({
177 adapter: groqSummarize("llama-3.3-70b-versatile"),
178 text: "Your long text to summarize...",
179 threadId: "thread-1",
180 maxLength: 100,
181 style: "concise", // "concise" | "bullet-points" | "paragraph"
182});
183​
184console.log(result.summary);
185```
186​
187## No image generation
188​
189Groq does not make images. For images, use [OpenAI](./openai) or [Gemini](./gemini). Groq has no provider tools of its own. Define your tools with `toolDefinition()`.
190​
191## Models and options
192​
193### Model options
194​
195Provider options go in `modelOptions`. This includes the sampling options `temperature`, `top_p`, and `max_completion_tokens` (the token limit of Groq):
196​
197```typescript
198import { chat } from "@tanstack/ai";
199import { groqText } from "@tanstack/ai-groq";
200​
201const stream = chat({
202 adapter: groqText("llama-3.3-70b-versatile"),
203 messages: [{ role: "user", content: "Hello!" }],
204 threadId: "thread-1",
205 modelOptions: {
206 temperature: 0.7,
207 max_completion_tokens: 1024,
208 top_p: 0.9,
209 },
210});
211```
212​
213Sampling options do not go at the root of `chat()`. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
214​
215### Reasoning
216​
217Set how hard a reasoning model thinks with `reasoning` on `chat()`:
218​
219```typescript
220import { chat } from "@tanstack/ai";
221import { groqText } from "@tanstack/ai-groq";
222​
223const stream = chat({
224 adapter: groqText("openai/gpt-oss-120b"),
225 messages: [{ role: "user", content: "Hello!" }],
226 threadId: "thread-1",
227 reasoning: "medium",
228});
229```
230​
231It goes out as `reasoning_effort`:
232​
233- `openai/gpt-oss-120b`, `openai/gpt-oss-20b`, `openai/gpt-oss-safeguard-20b`: `low`, `medium`, `high`.
234- `qwen/qwen3-32b`: `off` (sent as `none`) and `high` (sent as `default`).
235​
236To pick how the thinking text comes back, set `reasoning_format` in `modelOptions`.
237​
238### Models
239​
240The package exports the full lists as `GROQ_CHAT_MODELS`, `GROQ_TRANSCRIPTION_MODELS`, and `GROQ_TTS_MODELS`.
241​
242| Group | Models |
243| --- | --- |
244| OpenAI gpt-oss | `openai/gpt-oss-120b` (reasoning), `openai/gpt-oss-20b`, `openai/gpt-oss-safeguard-20b` (safety-tuned) |
245| Meta Llama | `meta-llama/llama-4-maverick-17b-128e-instruct` (vision), `meta-llama/llama-4-scout-17b-16e-instruct`, `llama-3.3-70b-versatile` (128K context), `llama-3.1-8b-instant` |
246| Other | `qwen/qwen3-32b` (reasoning), `moonshotai/kimi-k2-instruct-0905` (256K context) |
247| Safety | `meta-llama/llama-guard-4-12b` (content moderation), `meta-llama/llama-prompt-guard-2-86m` and `meta-llama/llama-prompt-guard-2-22m` (prompt injection detection) |
248​
249`adapter.inputModalities` lists the input kinds of the selected model. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
250​
251## Advanced
252​
253### Configuration
254​
255```typescript
256import { createGroqText, type GroqTextConfig } from "@tanstack/ai-groq";
257​
258const config: Omit<GroqTextConfig, "apiKey"> = {
259 baseURL: "https://api.groq.com/openai/v1", // Optional, for custom endpoints
260};
261​
262const adapter = createGroqText("openai/gpt-oss-120b", process.env.GROQ_API_KEY!, config);
263```
264​
265Need a header on each request, or a log of each model call? This adapter supports [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call).
266​
267### Tool calls that Groq rejects
268​
269Groq can reject a tool call from the model with `tool_use_failed`. If the error has a tool call in `failed_generation` that the adapter can rebuild, the adapter does not run the call. It returns the provider error as the result of that tool. The agent loop can then repair the call on its next step. Other provider errors still end the run.
270​
271### Structured output
272​
273Some Groq models, for example `llama-3.3-70b-versatile`, reject strict JSON schema. For these models, `chat({ outputSchema })` sends `json_object` and adds your schema to the system prompt. Read [When strict JSON schema is rejected](../structured-outputs/overview.md#when-strict-json-schema-is-rejected).
274​
275### API reference
276​
277Each factory pair has the same shape. The short factory reads `GROQ_API_KEY` from the environment. The `create*` factory takes an explicit API key. Both take `model` as the first argument.
278​
279| Factories | Creates |
280| --- | --- |
281| `groqText(model, config?)` / `createGroqText(model, apiKey, config?)` | Chat adapter |
282| `groqSummarize(model, config?)` / `createGroqSummarize(model, apiKey, config?)` | Summarization adapter |
283| `groqTranscription(model, config?)` / `createGroqTranscription(model, apiKey, config?)` | Speech-to-text adapter |
284| `groqSpeech(model, config?)` / `createGroqSpeech(model, apiKey, config?)` | Text-to-speech adapter |
285​
286`config.baseURL` sets a custom base URL for the API requests. `adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know.