GR

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.zip

Installs 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.
67 charsno explicit “when” trigger
Intermediate

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

You give it
Groq API key, messages, model, and optional client configuration
You get back
A typed `CompletionResult` with content, model, tokens, and timing data, or streamed tokens

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) or groq (Python) installed
  • GROQ_API_KEY set 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).

  1. Typed client singleton — one shared Groq client with maxRetries and timeout, so the whole app reuses one connection pool and config.
  2. Type-safe completion wrapper — return a typed result that surfaces Groq's unique timing fields (queue_time, completion_time, total_time) and a computed tokensPerSec.
  3. Streaming with typed events — an AsyncGenerator<string> that yields delta.content tokens.
  4. Error handling with Groq error types — branch on Groq.APIError (429, 401, other) and Groq.APIConnectionError; rethrow the unknown.
  5. Retry with exponential backoff — honor the retry-after header on 429s, else jittered backoff.
  6. Python patterns — sync Groq(), AsyncGroq(), and streaming (see the Python reference).
  7. 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, a getClientForTenant() factory.
  • A complete() wrapper returning a typed CompletionResultcontent, model, tokens (prompt/completion/total), and timing (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

PatternUse CaseBenefit
safeComplete wrapperAll API callsPrevents uncaught exceptions
withRetryRate-limited callsRespects retry-after header
Typed error checkinginstanceof Groq.APIErrorHandles each status code specifically
Client singletonApp-wide usageSingle 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 reaching api.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

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

`groq-sdk` (TypeScript) or `groq` (Python) installed`GROQ_API_KEY` set in the environmentUnderstanding of async/await and error handlingFamiliarity with OpenAI SDK patterns (Groq is API-compatible)

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.

SkillInstallsUpdatedSafetyDifficulty
groq-sdk-patterns (this skill)027dReviewIntermediate
stripe-integration482moNo flagsAdvanced
telegram-dev28moReviewIntermediate
build-smart-contracts06moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

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.

48165

telegram-dev

2025Emma

Telegram 生态开发全栈指南 - 涵盖 Bot API、Mini Apps (Web Apps)、MTProto 客户端开发。包括消息处理、支付、内联模式、Webhook、认证、存储、传感器 API 等完整开发资源。

232

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

00

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

00

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).

136215

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.

763

Search skills

Search the agent skills registry