把大模型接入代码所需的一切:覆盖目录中每个服务商的代码生成器、关键参数、生产环境最佳实践,以及在自己电脑上运行模型的指南。
生成集成代码
几乎所有服务商都提供相同的兼容 OpenAI 的 API:只有基础 URL、密钥和模型名称不同。选择服务商和选项,然后复制代码。
请把密钥存放在环境变量或 .env 文件中 —— 切勿写进前端代码或 Git 仓库。
环境变量
# .env (add .env to .gitignore — never commit it)
GROQ_API_KEY=your-key-here
# or, for the current shell session:
export GROQ_API_KEY="your-key-here"# pip install openai
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.groq.com/openai/v1",
api_key=os.environ["GROQ_API_KEY"],
timeout=60,
max_retries=3, # retries 429 / 5xx with exponential backoff
)
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": "你是一个简洁的助手。"},
{"role": "user", "content": "用一句话解释什么是 API。"},
],
temperature=0.7,
max_tokens=512,
)
print(response.choices[0].message.content)
print(response.usage) # prompt / completion tokens关键参数
这些参数适用于所有兼容 OpenAI 的 API。部分服务商会忽略或限制其中一些参数,请查阅其文档。
| 参数 | 作用 | 推荐取值 |
|---|---|---|
model | 模型标识,须与服务商公布的完全一致。 | 从目录页面或 GET /v1/models 复制。 |
messages | 对话:消息列表,每条消息包含角色(system、user、assistant)和内容。 | 把指令放在 system 消息中;多轮对话需重新发送历史记录。 |
temperature | 回答的随机程度(0 = 确定性,2 = 非常有创意)。 | 提取、代码或 JSON 用 0–0.3;聊天用 0.7;头脑风暴用 1 以上。 |
top_p | 核采样:只保留概率最高的令牌。 | 保持默认;temperature 和 top_p 只调其一。 |
max_tokens | 回答的最大长度(以令牌计)。 | 务必设置以控制成本和延迟;推理模型需要更多(1000 以上)。 |
stream | 逐个令牌发送回答(server-sent events)。 | 聊天界面建议开启:几百毫秒内即可看到第一个字。 |
stop | 遇到即停止生成的字符串。 | 适用于模板,例如 ["\n\n"]。 |
seed | 固定随机种子,使回答更可复现。 | 便于测试;并非所有服务商都保证支持。 |
response_format | 强制返回 JSON({"type": "json_object"})或 JSON Schema。 | 同时在提示词中要求 JSON,并校验结果。 |
tools | 模型可调用的函数(function calling)。 | 依赖前请在目录中确认“工具”功能。 |
最佳实践
- API 密钥只放在服务器端(环境变量、密钥管理服务):写在网页或移动应用中的密钥一定会被盗。
- 始终设置超时和 max_tokens:卡住的请求或无休止的回答都会浪费时间和金钱。
- 对 429(限流)和 5xx 错误使用指数退避重试;不要重试 400、401 或 403 错误。
- 免费额度低且经常变化:请准备切换到其他服务商或本地模型的后备方案。
- 交互界面请使用流式输出,并测量首个令牌时间 —— 目录为每个 API 显示该指标。
- 记录令牌用量(response.usage)以监控成本,并缓存相同的请求。
- 切勿把个人或机密数据发送给你未读过其条款的服务商;敏感数据优先使用本地模型。
指数退避重试
import random, time
from openai import OpenAI, RateLimitError, APIStatusError, APIConnectionError
def ask(client, model, messages, attempts=5):
"""Retries 429 / 5xx / network errors with exponential backoff and jitter."""
for i in range(attempts):
try:
return client.chat.completions.create(model=model, messages=messages)
except (RateLimitError, APIConnectionError) as e:
err = e
except APIStatusError as e:
if e.status_code < 500:
raise # 400 / 401 / 403 / 404: retrying will not help
err = e
time.sleep(min(30, 2 ** i) + random.random())
raise err在免费服务商之间切换 — Python
import os
from openai import OpenAI
# Free providers tried in order: if one is down or rate limited, the next one answers.
PROVIDERS = [
("https://api.groq.com/openai/v1", os.environ.get("GROQ_API_KEY"), "llama-3.3-70b-versatile"),
("https://api.cerebras.ai/v1", os.environ.get("CEREBRAS_API_KEY"), "llama3.1-8b"),
("https://openrouter.ai/api/v1", os.environ.get("OPENROUTER_API_KEY"), "openrouter/free"), # routes to an available free model
("http://localhost:11434/v1", "ollama", "qwen3:8b"), # local last resort
]
def ask(prompt):
errors = []
for base_url, key, model in PROVIDERS:
if not key:
continue
try:
client = OpenAI(base_url=base_url, api_key=key, timeout=30, max_retries=1)
r = client.chat.completions.create(model=model, messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
except Exception as e: # rate limit, outage, timeout…
errors.append(f"{base_url}: {e}")
raise RuntimeError("All providers failed:\n" + "\n".join(errors))在免费服务商之间切换 — JavaScript
import OpenAI from 'openai'
// Free providers tried in order: if one is down or rate limited, the next one answers.
const PROVIDERS = [
{ baseURL: 'https://api.groq.com/openai/v1', apiKey: process.env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' },
{ baseURL: 'https://api.cerebras.ai/v1', apiKey: process.env.CEREBRAS_API_KEY, model: 'llama3.1-8b' },
{ baseURL: 'http://localhost:11434/v1', apiKey: 'ollama', model: 'qwen3:8b' }, // local last resort
]
export async function ask(prompt) {
const errors = []
for (const { baseURL, apiKey, model } of PROVIDERS) {
if (!apiKey) continue
try {
const client = new OpenAI({ baseURL, apiKey, timeout: 30_000, maxRetries: 1 })
const r = await client.chat.completions.create({ model, messages: [{ role: 'user', content: prompt }] })
return r.choices[0].message.content
} catch (err) {
errors.push(`${baseURL}: ${err.message}`)
}
}
throw new Error(`All providers failed:\n${errors.join('\n')}`)
}在自己的电脑上运行大模型
本地模型免费、私密且可离线使用。能运行什么主要取决于显卡显存(VRAM)—— 在 Mac 上则取决于统一内存。
NVIDIA:可直接配合 Ollama、LM Studio、llama.cpp(CUDA)和 vLLM 使用。请安装较新的驱动,并用 nvidia-smi 检查。
经验法则:4 位量化下,每十亿参数约需 0.6 GB,另加 1–2 GB 用于上下文。8 GB 显存 ≈ 7–8B 模型,12 GB ≈ 14B,24 GB ≈ 32B。
| 模型 | 用途 | 下载大小 | 所需内存 | 在你的电脑上 |
|---|---|---|---|---|
Llama 3.2 1Bllama3.2:1b | 聊天 | ≈ 1.3 GB | 2.4 GB | |
Gemma 3 1Bgemma3:1b | 聊天 | ≈ 0.8 GB | 1.9 GB | |
Llama 3.2 3Bllama3.2:3b | 聊天 | ≈ 2 GB | 3.2 GB | |
Phi-4 miniphi4-mini | 聊天, 推理 | ≈ 2.5 GB | 3.7 GB | |
Qwen3 4Bqwen3:4b | 聊天, 推理 | ≈ 2.6 GB | 3.8 GB | |
Gemma 3 4Bgemma3:4b | 聊天, 视觉(图像) | ≈ 3.3 GB | 4.6 GB | |
Mistral 7Bmistral:7b | 聊天 | ≈ 4.1 GB | 5.4 GB | |
Qwen2.5-Coder 7Bqwen2.5-coder:7b | 编程 | ≈ 4.7 GB | 6.1 GB | |
Llama 3.1 8Bllama3.1:8b | 聊天 | ≈ 4.9 GB | 6.3 GB | |
Qwen2.5-VL 7Bqwen2.5vl:7b | 视觉(图像) | ≈ 6 GB | 7.5 GB | |
Qwen3 8Bqwen3:8b | 聊天, 推理, 编程 | ≈ 5.2 GB | 6.6 GB | |
DeepSeek-R1 8Bdeepseek-r1:8b | 推理 | ≈ 5.2 GB | 6.6 GB | |
Gemma 3 12Bgemma3:12b | 聊天, 视觉(图像) | ≈ 8.1 GB | 9.7 GB | |
Phi-4 14Bphi4:14b | 聊天, 推理 | ≈ 9.1 GB | 10.8 GB | |
Qwen3 14Bqwen3:14b | 聊天, 推理, 编程 | ≈ 9.3 GB | 11 GB | |
Qwen2.5-Coder 14Bqwen2.5-coder:14b | 编程 | ≈ 9 GB | 10.7 GB | |
DeepSeek-R1 14Bdeepseek-r1:14b | 推理 | ≈ 9 GB | 10.7 GB | |
gpt-oss 20Bgpt-oss:20b | 聊天, 推理, 编程 | ≈ 14 GB | 16.1 GB | |
Mistral Small 24Bmistral-small:24b | 聊天 | ≈ 14 GB | 16.1 GB | |
Gemma 3 27Bgemma3:27b | 聊天, 视觉(图像) | ≈ 17 GB | 19.4 GB | |
Qwen3 30B-A3Bqwen3:30b | 聊天, 推理 | ≈ 19 GB | 21.5 GB | |
Qwen3-Coder 30B-A3Bqwen3-coder:30b | 编程 | ≈ 19 GB | 21.5 GB | |
Qwen3 32Bqwen3:32b | 聊天, 推理, 编程 | ≈ 20 GB | 22.6 GB | |
Qwen2.5-Coder 32Bqwen2.5-coder:32b | 编程 | ≈ 20 GB | 22.6 GB | |
DeepSeek-R1 32Bdeepseek-r1:32b | 推理 | ≈ 20 GB | 22.6 GB | |
Llama 3.3 70Bllama3.3:70b | 聊天 | ≈ 43 GB | 47.4 GB | |
DeepSeek-R1 70Bdeepseek-r1:70b | 推理 | ≈ 43 GB | 47.4 GB | |
gpt-oss 120Bgpt-oss:120b | 聊天, 推理, 编程 | ≈ 65 GB | 71.2 GB |
大小为默认 4 位量化(Q4)的近似值。上下文越长需要的内存越多。确切大小见 ollama.com/library。 点击模型查看对应命令。
安装与运行
Ollama —— 最简单:一条命令即可下载并运行模型,并在 11434 端口提供兼容 OpenAI 的 API。
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# macOS
brew install ollama # or download the app from https://ollama.com/download
# Windows
winget install Ollama.OllamaQwen3 8B
ollama pull qwen3:8b
ollama run qwen3:8b
# check that it runs on the GPU (PROCESSOR column: "100% GPU")
ollama ps# Ollama exposes an OpenAI-compatible API on http://localhost:11434/v1
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "qwen3:8b", "messages": [{"role": "user", "content": "Hello"}]}'用与云端 API 相同的代码调用本地模型:在上方代码生成器中选择“Ollama”。
Docker(带 NVIDIA GPU 的 Ollama):
docker run -d --gpus=all -v ollama:/root/.ollama -p 127.0.0.1:11434:11434 --name ollama ollama/ollama
docker exec -it ollama ollama run qwen3:8bLM Studio —— 带图形界面的桌面应用:搜索模型、下载,然后启动本地服务器(端口 1234)。 lmstudio.ai
llama.cpp —— 大多数工具背后的轻量引擎:可完全控制量化、GPU 层数(-ngl)和上下文(-c)。
# macOS / Linux: brew install llama.cpp — Windows: winget install llama.cpp
# -ngl 99: all layers on the GPU (lower it if the model does not fit), -c: context size
llama-server -m ./model-Q4_K_M.gguf -ngl 99 -c 8192 --port 8080vLLM —— 适用于配备大显存 NVIDIA GPU、并发用户多的服务器(全精度权重:每十亿参数约 2 GB)。
pip install vllm
vllm serve Qwen/Qwen3-8B --max-model-len 8192 # OpenAI-compatible API on http://localhost:8000/v1安全:Ollama 默认只监听 localhost。没有反向代理和身份验证时,切勿把 11434 端口暴露到互联网。