LLM API 集成
把模型接进应用:调用、参数、可靠性。面试主线:接口形态、关键参数、生产级调用。
调用形态
from openai import OpenAI
client = OpenAI()
resp = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是客服助手"},
{"role": "user", "content": "怎么退款?"},
],
temperature=0.3,
max_tokens=1024,
)- 接口事实标准:OpenAI 兼容的 chat completions 格式(各厂商兼容,本地模型也支持)
- messages 角色:system(系统提示)、user(用户)、assistant(模型回复)、tool(工具结果)
- 流式:
stream=True拿增量(见流式输出篇)
关键参数
| 参数 | 作用 | 调优 |
|---|---|---|
| temperature | 随机性(0-2) | 事实任务 0-0.3,创意任务 0.7+ |
| max_tokens | 输出上限 | 防超长(成本控制) |
| top_p | 核采样 | 和 temperature 二选一调 |
| stop | 停止序列 | 结构化输出截断 |
| seed | 复现(部分支持) | 测试可复现 |
| response_format | JSON 模式 | 结构化输出 |
面试点:temperature 高 = 随机 = 幻觉风险高;事实场景(检索问答)用低温度。
可靠性工程
LLM API 是外部依赖,按分布式系统处理:
| 问题 | 对策 |
|---|---|
| 超时 | 连接/读取超时分开设,流式用读超时 |
| 限流(429) | 退避重试(见重试与幂等篇) |
| 5xx | 重试 + 熔断(见熔断篇) |
| 格式错误 | JSON 解析失败重试/修复(few-shot 给格式) |
| 内容截断 | max_tokens 不够 → 分段生成 |
| 成本失控 | 上限监控、按量告警 |
# 重试 + 超时模板
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1))
def call_llm(messages):
return client.chat.completions.create(
model="gpt-4o", messages=messages, timeout=30)面试追问
- API 调用格式? OpenAI 兼容 chat completions:messages 列表(system/user/assistant/tool)
- temperature 怎么调? 事实任务低(0-0.3),创意任务高。高温度幻觉风险大
- LLM API 会失败吗? 会:限流、超时、5xx、格式错。按外部依赖工程化处理(重试/熔断/兜底)
- 怎么保证 JSON 输出? response_format=json + few-shot 示例 + 解析失败重试
- max_tokens 截断怎么办? 检测 finish_reason,分段生成或提示精简