Groq API Python 教程:比 ChatGPT 快 10 倍的免费 LLM 推理

Dev.to ML 2026-07-11T09:11:59.712242

Groq 提供比 OpenAI 快 10 倍的免费 LLM 推理。以下是使用方法。

为什么选择 Groq?

安装

pip install httpx

基础对话

import httpx
import os

GROQ_KEY = os.getenv("GROQ_API_KEY")  # 在 console.groq.com 免费获取

def chat(prompt: str, model: str = "llama-3.3-70b-versatile") -> str:
    with httpx.Client() as client:
        r = client.post(
            "https://api.groq.com/openai/v1/chat/completions",
            headers={"Authorization": f"Bearer {GROQ_KEY}"},
            json={
                "model": model,
                "messages": [{"role": "user", "content": prompt}],
                "max_tokens": 1000,
                "temperature": 0.7,
            },
            timeout=30,
        )
    return r.json()["choices"][0]["message"]["content"]

# 测试
response = chat("用三句话解释 Python 装饰器")
print(response)

异步版本(适用于 API)

import httpx
import asyncio

async def async_chat(prompt: str) -> str:
    async with httpx.AsyncClient() as client:
        r = await client.post(
            "https://api.groq.com/openai/v1/chat/completions",
            headers={"Authorization": f"Bearer {os.getenv('GROQ_API_KEY')}"},
            json={
                "model": "llama-3.1-8b-instant",
                "messages": [{"role": "user", "content": prompt}],
            },
            timeout=30,
        )
    return r.json()["choices"][0]["message"]["content"]

# 同时运行多个提示词
async def main():
    prompts = [
        "什么是 Python?",
        "解释 async/await",
        "2024 年最佳 Python 库",
    ]
    results = await asyncio.gather(*[async_chat(p) for p in prompts])
    for prompt, result in zip(prompts, results):
        print(f"问: {prompt}\n答: {result[:100]}...\n")

asyncio.run(main())

可用模型

模型 速度 上下文窗口 最佳用途
llama-3.3-70b-versatile 128K 通用任务
llama-3.1-8b-instant 最快 128K 简单任务
gemma2-9b-it 8K 代码生成
mixtral-8x7b-32768 中等 32K 复杂推理

速率限制(免费版)

对于大多数项目来说,这基本上是无限的!

查看原文