groq-sdk-patterns
Provides standard patterns for using the Groq SDK with optimal performance and error handling.
Install
mkdir -p .claude/skills/groq-sdk-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8576" && unzip -o skill.zip -d .claude/skills/groq-sdk-patterns && rm skill.zipInstalls to .claude/skills/groq-sdk-patterns
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Apply production-ready Groq SDK patterns for TypeScript and Python.Key capabilities
- →Create a typed Groq client singleton with retry and timeout settings
- →Wrap Groq completions to return typed results including timing fields
- →Implement streaming with typed events for Groq responses
- →Handle Groq API errors and connection errors specifically
- →Apply exponential backoff with `retry-after` header for rate limits
- →Isolate API keys for multi-tenant applications using a client factory
How it works
The skill defines patterns for using the `groq-sdk` package, including client instantiation, response typing, streaming, and error handling, to account for Groq's specific behaviors.
Inputs & outputs
When to use groq-sdk-patterns
- →Implement Groq client singletons
- →Handle Groq rate limits
- →Integrate Groq in TypeScript projects
- →Integrate Groq in Python projects
About this skill
Groq SDK Patterns
Overview
Production patterns for the groq-sdk package. The Groq SDK mirrors the OpenAI SDK interface (chat.completions.create), so patterns feel familiar but must account for Groq-specific behavior: extreme speed (500+ tok/s), aggressive rate limits on free tier, and unique response metadata like queue_time and completion_time.
The full, copy-paste-ready implementations live in references/ so this file stays a fast map of the workflow. Read the summary here, then drill into the language file you need.
Prerequisites
groq-sdk(TypeScript) orgroq(Python) installedGROQ_API_KEYset in the environment- Understanding of async/await and error handling
- Familiarity with OpenAI SDK patterns (Groq is API-compatible)
Instructions
Build the integration in layers. Each step below is a one-line summary; the full typed implementation is in references/typescript-patterns.md (steps 1–5, 7) and references/python-patterns.md (step 6).
- Typed client singleton — one shared
Groqclient withmaxRetriesandtimeout, so the whole app reuses one connection pool and config. - Type-safe completion wrapper — return a typed result that surfaces Groq's unique timing fields (
queue_time,completion_time,total_time) and a computedtokensPerSec. - Streaming with typed events — an
AsyncGenerator<string>that yieldsdelta.contenttokens. - Error handling with Groq error types — branch on
Groq.APIError(429, 401, other) andGroq.APIConnectionError; rethrow the unknown. - Retry with exponential backoff — honor the
retry-afterheader on 429s, else jittered backoff. - Python patterns — sync
Groq(),AsyncGroq(), and streaming (see the Python reference). - Multi-tenant client factory — cache one client per tenant so API keys stay isolated.
The essential skeleton — a shared singleton every other pattern builds on:
// src/groq/client.ts
import Groq from "groq-sdk";
let _client: Groq | null = null;
export function getGroq(): Groq {
if (!_client) {
_client = new Groq({
apiKey: process.env.GROQ_API_KEY,
maxRetries: 3,
timeout: 30_000,
});
}
return _client;
}
Groq differs from OpenAI in a few details (package name, base URL, extra usage timing fields, error class names). The full comparison and error-handling matrix are in references/sdk-differences.md.
Output
Applying these patterns produces:
- A reusable
getGroq()client module and, for multi-tenant apps, agetClientForTenant()factory. - A
complete()wrapper returning a typedCompletionResult—content,model,tokens(prompt/completion/total), andtiming(queueMs,totalMs,tokensPerSec). - A
safeComplete()variant returning{ data, error }so callers never face an uncaught exception. - Streaming helpers that yield string tokens as they arrive.
Error Handling
| Pattern | Use Case | Benefit |
|---|---|---|
safeComplete wrapper | All API calls | Prevents uncaught exceptions |
withRetry | Rate-limited calls | Respects retry-after header |
| Typed error checking | instanceof Groq.APIError | Handles each status code specifically |
| Client singleton | App-wide usage | Single connection pool, consistent config |
- 429 (rate limited): read
err.headers["retry-after"]and wait that long before retrying; free tier hits this often. - 401 (bad key): surface a clear "Check GROQ_API_KEY" message — do not retry.
APIConnectionError: network issue reachingapi.groq.com; retry or fail fast per context.- Unknown errors: rethrow so they are not silently swallowed.
Full typed handlers: references/typescript-patterns.md (Step 4 and Step 5).
Examples
Non-streaming completion with timing metadata (full code in references/typescript-patterns.md, Step 2):
const result = await complete(
[{ role: "user", content: "Summarize Groq's speed advantage." }],
"llama-3.3-70b-versatile"
);
console.log(result.content);
console.log(`${result.timing.tokensPerSec.toFixed(0)} tok/s`);
Streaming tokens to stdout (full code in the TS reference, Step 3):
for await (const token of streamCompletion([{ role: "user", content: "Hello" }])) {
process.stdout.write(token);
}
Python one-liner (full sync/async/streaming in references/python-patterns.md):
from groq import Groq
client = Groq()
print(client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[{"role": "user", "content": "Hello"}],
).choices[0].message.content)
Resources
- Groq TypeScript SDK
- Groq API Reference
- Groq Error Codes
- references/typescript-patterns.md — full TS implementations (steps 1–5, 7)
- references/python-patterns.md — full Python implementations (step 6)
- references/sdk-differences.md — OpenAI-vs-Groq comparison and error matrix
Next Steps
Apply these patterns in groq-core-workflow-a for real-world chat completions, then wire safeComplete and withRetry into every call site so rate limits and network errors are handled consistently across the codebase.
When not to use it
- →When not using the `groq-sdk` package
- →When not integrating with the Groq API
Prerequisites
Limitations
- →Aggressive rate limits on free tier
- →Groq differs from OpenAI in package name, base URL, extra `usage` timing fields, error class names
How it compares
This approach provides specific patterns for Groq's unique timing fields and aggressive rate limits, unlike generic OpenAI SDK usage.
Compared to similar skills
groq-sdk-patterns side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| groq-sdk-patterns (this skill) | 0 | 27d | Review | Intermediate |
| stripe-integration | 48 | 2mo | No flags | Advanced |
| telegram-dev | 2 | 8mo | Review | Intermediate |
| build-smart-contracts | 0 | 6mo | Review | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by jeremylongshore
View all by jeremylongshore →You might also like
stripe-integration
wshobson
Implement Stripe payment processing for robust, PCI-compliant payment flows including checkout, subscriptions, and webhooks. Use when integrating Stripe payments, building subscription systems, or implementing secure checkout flows.
telegram-dev
2025Emma
Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。
build-smart-contracts
algorandfoundation
Build Algorand smart contracts using Algorand TypeScript (PuyaTs) or Algorand Python (PuyaPy). Use when creating new smart contracts from scratch, adding features or methods to existing contracts, understanding Algorand contract development patterns, or getting guidance on contract architecture. Str
assets
salazarsebas
Stellar Assets (classic) + trustlines + Stellar Asset Contract (SAC) bridge to Soroban. Covers asset issuance, distribution, authorization flags, clawback, regulated assets, trustline management, and the SAC interop layer that exposes classic assets as Soroban tokens. Use when tokenizing real-world
mcp-builder
anthropics
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
copilot-sdk
github
Build agentic applications with GitHub Copilot SDK. Use when embedding AI agents in apps, creating custom tools, implementing streaming responses, managing sessions, connecting to MCP servers, or creating custom agents. Triggers on Copilot SDK, GitHub SDK, agentic app, embed Copilot, programmable agent, MCP server, custom agent.