Groq API Python 教程:比 ChatGPT 快 10 倍的免费 LLM 推理
Groq 提供比 OpenAI 快 10 倍的免费 LLM 推理。以下是使用方法。
为什么选择 Groq?
- ⚡ 每秒 500+ 个 token(GPT-4 约 50 个)
- 🆓 免费额度:每天 14,400 次请求
- 🔑 获取密钥:console.groq.com
安装
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 | 复杂推理 |
速率限制(免费版)
- 每天 14,400 次请求
- 每分钟 1,000 次请求
- 每分钟 6,000 个 token
对于大多数项目来说,这基本上是无限的!