mcpField
G
groq-api

groq-api

github.com/diskd-ai开发0199 次安装41 周前更新
代码仓库

关于 groq-api

groq-api 是使用 Groq LLM 推理服务构建应用的技能,面向 Python 和 TypeScript/JavaScript 开发者。内容涵盖聊天补全、音频与图像处理、结构化输出、工具调用和批处理等 API 用法。

主要功能

  1. 01Python 与 TypeScript/JavaScript SDK
  2. 02流式聊天补全
  3. 03JSON 与结构化输出
  4. 04图像理解及 OCR
  5. 05语音转录、翻译与合成
  6. 06批处理和提示缓存

适用场景

  1. 01在应用中实现 LLM 聊天
  2. 02从图像提取文本和数据
  3. 03构建语音转录或合成流程
  4. 04批量处理 API 请求

MCP 相关

文档说明可通过 Responses API 连接第三方 MCP 服务,以使用其工具。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/diskd-ai/groq-api --skill groq-api

安装后在 Claude Code 中输入/groq-api确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.gitignore
README.md
references/
sdk.md
audio.md
prompt-caching.md
structured-outputs.md
models.md
moderation.md
reasoning.md
tool-use.md
api-reference.md
vision.md

详细介绍

Groq API

使用 Groq 的超高速大模型推理(300-1000+ tokens/sec)构建应用。

快速入门

安装
# Python
pip install groq

# TypeScript/JavaScript
npm install groq-sdk
环境设置
export GROQ_API_KEY=<your-api-key>
基本聊天补全

Python:

from groq import Groq

client = Groq()  # Uses GROQ_API_KEY env var

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)

TypeScript:

import Groq from "groq-sdk";

const client = new Groq();

const response = await client.chat.completions.create({
    model: "llama-3.3-70b-versatile",
    messages: [{ role: "user", content: "Hello" }],
});
console.log(response.choices[0].message.content);

模型选择

用例模型备注
快速且便宜llama-3.1-8b-instant最适合简单任务
均衡llama-3.3-70b-versatile质量与成本平衡
最高质量openai/gpt-oss-120b内置工具 + 推理
Agenticgroq/compound网页搜索 + 代码执行
推理openai/gpt-oss-20b快速推理(low/med/high)
视觉/OCRllama-4-scout-17b-16e-instruct图像理解
音频 STTwhisper-large-v3-turbo转录
TTSplayai-tts文本转语音

完整模型列表和定价请参阅 references/models.md。

常见模式

流式响应
stream = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
系统消息
response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello"}
    ]
)
异步客户端(Python)
import asyncio
from groq import AsyncGroq

async def main():
    client = AsyncGroq()
    response = await client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[{"role": "user", "content": "Hello"}]
    )
    return response.choices[0].message.content

print(asyncio.run(main()))
JSON 模式
response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "List 3 colors as JSON array"}],
    response_format={"type": "json_object"}
)
结构化输出(JSON Schema)

强制输出符合某个架构。提供两种模式:

模式保证模型
strict: true100% 符合架构openai/gpt-oss-20b、openai/gpt-oss-120b
strict: false尽力符合架构所有受支持的模型

严格模式(保证符合):

response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "Extract: John is 30 years old"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"}
                },
                "required": ["name", "age"],
                "additionalProperties": False
            }
        }
    }
)

使用 Pydantic:

from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int

response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "Extract: John is 30"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": Person.model_json_schema()
        }
    }
)
person = Person.model_validate(json.loads(response.choices[0].message.content))

有关架构要求、验证库和示例,请参阅 references/structured-outputs.md。

音频

转录(语音转文本)
with open("audio.mp3", "rb") as f:
    transcription = client.audio.transcriptions.create(
        model="whisper-large-v3-turbo",
        file=f,
        language="en",  # Optional: ISO-639-1 code
        response_format="verbose_json",  # json, text, verbose_json
        timestamp_granularities=["word", "segment"]
    )
print(transcription.text)
翻译(为英语)
with open("french_audio.mp3", "rb") as f:
    translation = client.audio.translations.create(
        model="whisper-large-v3",
        file=f
    )
print(translation.text)  # English text
文本转语音
response = client.audio.speech.create(
    model="playai-tts",
    input="Hello, world!",
    voice="Fritz-PlayAI",
    response_format="wav",  # flac, mp3, mulaw, ogg, wav
    speed=1.0  # 0.5 to 5
)
response.write_to_file("output.wav")

视觉

使用 Llama 4 多模态模型处理图像。每个请求最多支持 5 张图像。

模型: meta-llama/llama-4-scout-17b-16e-instruct(更快)、meta-llama/llama-4-maverick-17b-128e-instruct(质量更高)

URL 中的图像
response = client.chat.completions.create(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
        ]
    }]
)
本地图像(Base64)
import base64

def encode_image(path: str) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")

response = client.chat.completions.create(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Describe this image"},
            {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image('photo.jpg')}"}}
        ]
    }]
)
OCR / 将数据提取为 JSON
response = client.chat.completions.create(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Extract all text and data as JSON"},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}
        ]
    }],
    response_format={"type": "json_object"}
)

有关多图像、图像工具使用和多轮对话,请参阅 references/vision.md。

工具使用

有关工具调用模式和示例,请参阅 references/tool-use.md。

快速示例:

import json

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather for a location",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"]
        }
    }
}]

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Weather in Paris?"}],
    tools=tools
)

if response.choices[0].message.tool_calls:
    for tc in response.choices[0].message.tool_calls:
        args = json.loads(tc.function.arguments)
        # Execute function and continue conversation

内置工具(Agentic)

使用 groq/compound 或 openai/gpt-oss-120b 执行内置网页搜索和代码:

response = client.chat.completions.create(
    model="groq/compound",
    messages=[{"role": "user", "content": "Search for latest Python news"}]
)
# Model automatically uses web search

MCP(远程工具)

连接第三方 MCP 服务,以使用 Stripe、GitHub、网页抓取等工具。请使用 Responses API:

import openai

client = openai.OpenAI(
    api_key=os.environ.get("GROQ_API_KEY"),
    base_url="https://api.groq.com/openai/v1"
)

response = client.responses.create(
    model="openai/gpt-oss-120b",
    input="What models are trending on Huggingface?",
    tools=[{
        "type": "mcp",
        "server_label": "Huggingface",
        "server_url": "https://huggingface.co/mcp"
    }]
)

有关 MCP 配置和常用服务,请参阅 references/tool-use.md。

推理模型

控制模型如何思考复杂问题。

模型: openai/gpt-oss-20b、openai/gpt-oss-120b(low/medium/high)、qwen/qwen3-32b(none/default)

带推理力度设置的 GPT-OSS
response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "How many r's in strawberry?"}],
    reasoning_effort="high",  # low, medium, high
    temperature=0.6,
    max_completion_tokens=1024
)

print(response.choices[0].message.content)
print("Reasoning:", response.choices[0].message.reasoning)
带解析推理的 Qwen3
response = client.chat.completions.create(
    model="qwen/qwen3-32b",
    messages=[{"role": "user", "content": "Solve: x + 5 = 12"}],
    reasoning_format="parsed"  # raw, parsed, hidden
)

print("Answer:", response.choices[0].message.content)
print("Reasoning:", response.choices[0].message.reasoning)
隐藏推理(GPT-OSS)
response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "What is 15% of 80?"}],
    include_reasoning=False  # Hide reasoning in response
)

有关流式处理、推理时的工具使用和最佳实践,请参阅 references/reasoning.md。

批处理

用于高容量异步处理(完成时间窗口为 24h-7d):

# 1. Create JSONL file with requests
# 2. Upload file
# 3. Create batch
batch = client.batches.create(
    input_file_id=file_id,
    endpoint="/v1/chat/completions",
    completion_window="24h"
)

# 4. Check status
batch = client.batches.retrieve(batch.id)
if batch.status == "completed":
    results = client.files.content(batch.output_file_id)

有关批处理 API 的完整详情,请参阅 references/api-reference.md。

提示缓存

自动将重复提示前缀的延迟和成本降低 50%。无需更改代码。

支持的模型: moonshotai/kimi-k2-instruct-0905、openai/gpt-oss-20b、openai/gpt-oss-120b、openai/gpt-oss-safeguard-20b

工作原理:

  • 将静态内容(系统提示词、工具、示例)放在开头
  • 将动态内容(用户查询)放在末尾
  • 缓存会自动匹配前缀并应用 50% 折扣
  • 缓存闲置 2 小时后过期

跟踪缓存用量:

response = client.chat.completions.create(
    model="moonshotai/kimi-k2-instruct-0905",
    messages=[{"role": "system", "content": large_system_prompt}, ...]
)

cached = response.usage.prompt_tokens_details.cached_tokens
print(f"Cached tokens: {cached}")  # 50% discount applied to these

有关优化策略和示例,请参阅 references/prompt-caching.md。

内容审核

使用安全防护模型检测并过滤有害内容。

Llama Guard 4

通用内容安全分类。返回 safe 或 unsafe\nSX(类别代码)。

response = client.chat.completions.create(
    model="meta-llama/Llama-Guard-4-12B",
    messages=[{"role": "user", "content": user_input}]
)

if response.choices[0].message.content.startswith("unsafe"):
    # Block or handle unsafe content
    pass
GPT-OSS Safeguard 20B

使用自定义策略检测提示词注入。返回结构化 JSON。

response = client.chat.completions.create(
    model="openai/gpt-oss-safeguard-20b",
    messages=[
        {"role": "system", "content": injection_detection_policy},
        {"role": "user", "content": user_input}
    ]
)
# Returns: {"violation": 1, "category": "Direct Override", "rationale": "..."}

完整策略、有害内容分类体系和集成模式请参阅 references/moderation.md。

错误处理

from groq import Groq, RateLimitError, APIConnectionError, APIStatusError

client = Groq()

try:
    response = client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    # Wait and retry with exponential backoff
    pass
except APIConnectionError:
    # Network issue
    pass
except APIStatusError as e:
    # API error (check e.status_code)
    pass

完整的音频 API 参考(包括文件处理、元数据字段和提示词编写指南)请参阅 references/audio.md。

资源

评论

支持 Markdown