GR

groq-reference-architecture

Implement production-grade architecture patterns for Groq, including request routing, caching, and fallback chains.

Install

mkdir -p .claude/skills/groq-reference-architecture && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/8499" && unzip -o skill.zip -d .claude/skills/groq-reference-architecture && rm skill.zip

Installs to .claude/skills/groq-reference-architecture

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.

Implement Groq reference architecture with model routing, streaming
67 charsno explicit “when” trigger
Advanced

Key capabilities

  • Implement model registry with specs
  • Route requests based on latency and cost
  • Wrap completions with middleware
  • Execute fallback chains on failure
  • Stream completions via async generators

How it works

It establishes a service layer using a model registry and router to map requirements to models. It wraps calls in middleware for caching and metrics, and implements a fallback chain for reliability.

Inputs & outputs

You give it
Request requirements and message history
You get back
Routed, cached, or streamed completion response

When to use groq-reference-architecture

  • Designing new Groq API integrations
  • Reviewing project structure for LLM apps
  • Implementing request routing by cost or latency
  • Setting up fallback chains for API reliability

About this skill

Groq Reference Architecture

Overview

Production architecture for applications built on Groq's LPU inference API. It covers four concerns that every serious Groq integration needs: routing requests to the right model by latency/capability/cost, a middleware band (cache, metrics, retry), a multi-provider fallback chain, and a streaming pipeline. The service layer built here is reusable across a chat UI, an API backend, a batch processor, or an agent.

The full layer diagram and how the pieces interact lives in references/architecture.md; the complete, copy-ready TypeScript for every layer is in references/implementation.md.

Prerequisites

  • Groq API key — create one at console.groq.com and export it as GROQ_API_KEY. The Groq SDK reads it from the environment; the client is constructed as new Groq({ apiKey: process.env.GROQ_API_KEY }). Never hardcode the key.
  • Runtime: Node.js 18+ (for performance.now() and native fetch).
  • Packages: groq-sdk and lru-cache (npm install groq-sdk lru-cache).
  • Optional backup provider: an OpenAI-compatible key if you extend the fallback chain beyond Groq's own models.

Instructions

Build the service layer in five ordered steps. Each step is one file under src/groq/. The router depends on the registry; the middleware and fallback depend on the client; the streaming pipeline stands alone. Full source for every step (verbatim) is in references/implementation.md.

  1. Model Registry (models.ts) — declare a ModelSpec for each model with its tier, context window, speed, cost, and capabilities. Skeleton:

    export const MODELS: Record<string, ModelSpec> = {
      "llama-3.1-8b-instant":     { tier: "speed",   /* fast, cheap */ },
      "llama-3.3-70b-versatile":  { tier: "quality", /* tools + JSON */ },
      "meta-llama/llama-4-scout-17b-16e-instruct": { tier: "vision" },
      "whisper-large-v3-turbo":   { tier: "audio" },
    };
    
  2. Model Router (router.ts) — selectModel(req) maps requirements (maxLatencyMs, needsVision, needsTools, costSensitive) to the cheapest model that satisfies them. Callers pass requirements, never hardcoded ids.

  3. Middleware (middleware.ts) — completionWithMiddleware() wraps each call with an LRU cache (deterministic requests only, temperature === 0), latency + token metrics, and a pluggable metrics sink.

  4. Fallback Chain (fallback.ts) — completionWithFallback() tries the primary model, drops to a model in a different rate-limit pool on 429/5xx, then returns a graceful-degradation payload instead of throwing.

  5. Streaming Pipeline (streaming.ts) — streamCompletion() is an async generator yielding { type: "token" | "done" | "error" } for real-time SSE UIs.

When applying this to an existing repo, Read the current src/ layout and Grep for direct groq.chat.completions.create calls to find code that should route through the middleware and fallback wrappers instead.

Integration Patterns

PatternWhen to UseGroq Feature
Direct completionSimple request/responsechat.completions.create
Streaming SSEReal-time chat UIstream: true
Tool callingAgent with function executiontools parameter
JSON extractionStructured data from textresponse_format: json_object
Batch processingHigh-volume document processingQueue + rate limiting
Audio transcriptionVoice inputaudio.transcriptions.create
Vision analysisImage understandingLlama 4 Scout/Maverick

Output

Applying this skill produces a src/groq/ service layer with six files (client.ts, models.ts, router.ts, middleware.ts, fallback.ts, streaming.ts) plus the service and API layers that consume it. At runtime you get:

  • Routed completionsselectModel() returns a ModelSpec; callers never hardcode a model id, so cost/latency policy lives in one place.
  • Cached deterministic responses — repeated temperature: 0 calls return from the LRU cache instead of re-billing the API.
  • Resilient callscompletionWithFallback() returns a valid completion shape even when Groq is rate-limited, never surfacing a raw 429 to the user.
  • Streamed tokensstreamCompletion() yields { type, content } events for SSE, with a terminal done or error event.
  • Metrics — every call emits { model, latencyMs, tokens, cached } to your metrics sink (Prometheus, Datadog, or console.log by default).

Error Handling

IssueCauseSolution
429 on primary modelRPM/TPM exceededFall back to different model
High latencyWrong model tierRoute to 8b-instant for latency-critical paths
Context overflowInput > 128K tokensTruncate or chunk input
Vision errorsWrong model for imagesUse Llama 4 Scout full model path
GROQ_API_KEY undefinedEnv var not exportedExport the key before starting the process

Examples

A latency-critical chat turn routes to the speed tier and returns one completion:

const model = selectModel({ maxLatencyMs: 80, costSensitive: true });
// → llama-3.1-8b-instant
const res = await completionWithMiddleware(groq, model.id, messages);

Streaming a UI consumes the async generator token-by-token:

for await (const event of streamCompletion(groq, messages)) {
  if (event.type === "token") process.stdout.write(event.content!);
}

Four fully worked examples — latency-critical, quality-with-fallback, streaming, and vision routing — are in references/examples.md.

Resources

Next Steps

For multi-environment deployment, see the groq-multi-env-setup skill, which extends this service layer with per-environment configuration and secrets handling.

When not to use it

  • Simple scripts without complex routing needs
  • Environments lacking Node.js 18+ features

Prerequisites

Groq API keyNode.js 18+groq-sdklru-cache

Limitations

  • Requires manual maintenance of model registry
  • Fallback chain depends on availability of secondary providers

How it compares

It replaces direct API calls with a structured service layer that abstracts model selection and error handling.

Compared to similar skills

groq-reference-architecture side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
groq-reference-architecture (this skill)026dReviewAdvanced
mcp-builder1363moReviewAdvanced
langchain-architecture82moReviewIntermediate
nodejs-backend-patterns122moNo flagsIntermediate

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

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

langchain-architecture

wshobson

Design LLM applications using the LangChain framework with agents, memory, and tool integration patterns. Use when building LangChain applications, implementing AI agents, or creating complex LLM workflows.

899

nodejs-backend-patterns

wshobson

Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.

1246

backend-architect

sickn33

Expert backend architect specializing in scalable API design, microservices architecture, and distributed systems. Masters REST/GraphQL/gRPC APIs, event-driven architectures, service mesh patterns, and modern backend frameworks. Handles service boundary definition, inter-service communication, resilience patterns, and observability. Use PROACTIVELY when creating new backend services or APIs.

1014

apollo-reference-architecture

jeremylongshore

Implement Apollo.io reference architecture. Use when designing Apollo integrations, establishing patterns, or building production-grade sales intelligence systems. Trigger with phrases like "apollo architecture", "apollo system design", "apollo integration patterns", "apollo best practices architecture".

11

customerio-reference-architecture

jeremylongshore

Implement Customer.io reference architecture. Use when designing integrations, planning architecture, or implementing enterprise patterns. Trigger with phrases like "customer.io architecture", "customer.io design", "customer.io enterprise", "customer.io integration pattern".

10

Search skills

Search the agent skills registry