Files
aaronxu 4fb9532f5c 重构 AI 智能体课程:Markdown 化,新增 ReAct 模块与案例
- 按 Python 课件的章节式结构重组为 9 个部分、24 章
- 新增 ReAct 模块:原理与手写实现、LangGraph 实现、create_agent、5 个案例
- 补齐 RAG、LangGraph 工作流、多智能体、任务调度
- 新增 3 个项目实战与部署评估章节
- 统一 '学习目标 / 概念 / 代码 / 小结 / 练习' 结构
2026-10-28 05:08:00 +08:00

6.8 KiB
Raw Permalink Blame History

部署与评估

本章目标:把 Notebook 里的 Demo 变成能启动、能观测、能评估的服务。 前置知识:完成至少一个项目。 预计用时:70 分钟。

1. Demo 和服务的差距

Demo 服务
入口 一个 .py HTTP / Web
配置 写死在代码里 环境变量
错误 直接抛异常 兜底 + 日志
并发 单用户 多用户、线程隔离
质量 看着还行 有评估集和指标
成本 不管 有 token 统计和限流

2. 第一步:把核心逻辑抽出来

不管外面是 CLI、FastAPI 还是 Streamlit,核心都应该是一个纯函数:

# core.py
from dataclasses import dataclass
from langchain_core.messages import HumanMessage
from graph import assistant

@dataclass
class Reply:
    answer: str
    sources: list[dict]
    intent: str

def run_assistant(question: str, thread_id: str = "default") -> Reply:
    if not question or not question.strip():
        return Reply("请输入问题。", [], "empty")

    try:
        out = assistant.invoke(
            {"messages": [HumanMessage(question)]},
            config={"configurable": {"thread_id": thread_id}},
        )
        return Reply(
            answer=out["messages"][-1].content,
            sources=out.get("sources", []),
            intent=out.get("intent", "unknown"),
        )
    except Exception as e:
        return Reply(f"服务暂时不可用:{e}", [], "error")

这样 CLI / API / 测试都调用同一个入口,行为一致。

3. FastAPI 部署

# api.py
from fastapi import FastAPI
from pydantic import BaseModel
from core import run_assistant

app = FastAPI(title="学习助手 API")

class ChatRequest(BaseModel):
    question: str
    thread_id: str = "default"

class ChatResponse(BaseModel):
    answer: str
    sources: list[dict]
    intent: str

@app.get("/health")
def health():
    return {"status": "ok"}

@app.post("/chat", response_model=ChatResponse)
def chat(req: ChatRequest):
    r = run_assistant(req.question, req.thread_id)
    return ChatResponse(answer=r.answer, sources=r.sources, intent=r.intent)

启动:

uvicorn api:app --host 0.0.0.0 --port 8000

测试:

curl -X POST http://127.0.0.1:8000/chat \
  -H "Content-Type: application/json" \
  -d '{"question":"退款政策是什么?","thread_id":"u1"}'

三个工程细节:

细节 做法
超时 uvicorn --timeout-keep-alive 30,模型调用加 timeout
并发 每个请求独立 thread_id,避免串话
密钥 只从环境变量读,绝不写进镜像

4. Docker

FROM python:3.12-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt \
    -i https://pypi.tuna.tsinghua.edu.cn/simple

COPY . .

ENV PYTHONUNBUFFERED=1
EXPOSE 8000

CMD ["uvicorn", "api:app", "--host", "0.0.0.0", "--port", "8000"]
docker build -t study-assistant .
docker run -p 8000:8000 --env-file .env study-assistant

.dockerignore 记得排除 .env、.venv、chroma_db。

5. 日志:出问题能查

最少记录四个字段:

import logging, time

logger = logging.getLogger("assistant")

def run_with_log(question, thread_id):
    start = time.perf_counter()
    reply = run_assistant(question, thread_id)
    logger.info({
        "thread_id": thread_id,
        "intent": reply.intent,
        "question_len": len(question),
        "answer_len": len(reply.answer),
        "elapsed_ms": round((time.perf_counter() - start) * 1000),
    })
    return reply

生产环境建议加:trace_id、模型名、token 数、工具调用次数、是否命中兜底。

6. 评估:怎么证明它「好」

6.1 先建评估集

从真实问题里抽 30~50 条,覆盖:

类型 占比 例子
常规问题 50% 退款政策是什么
边界问题 20% 资料里没有的问题
多步问题 15% 查订单 + 算退款
拒答问题 10% 帮我写代码
多轮追问 5% 那要多久

6.2 三类指标

指标 怎么算 关注点
检索命中率 正确片段是否在 top-k RAG 质量
答案正确率 与标准答案比对(人评或 LLM 评) 生成质量
工具调用准确率 调用序列是否符合预期 Agent 质量
# eval.py
CASES = [
    {"q": "退款几天内可以申请", "must": "7 天", "intent": "qa"},
    {"q": "北京天气", "must": "晴", "intent": "tool"},
    {"q": "比特币支付", "must": "没有", "intent": "qa"},
]

def run_eval():
    ok = 0
    for c in CASES:
        r = run_assistant(c["q"])
        passed = c["must"] in r.answer and r.intent == c["intent"]
        ok += passed
        print(("✅" if passed else "❌"), c["q"], "|", r.intent, "|", r.answer[:60])
    print(f"通过率:{ok}/{len(CASES)}")

6.3 LLM 当裁判

JUDGE_PROMPT = """判断回答是否正确。

问题:{q}
标准答案要点:{must}
模型回答:{a}

只输出 JSON:{{"correct": true/false, "reason": "..."}}"""

注意:裁判也会有偏差,关键场景仍要人工抽检。

7. 成本与性能

优化 做法 效果
缓存 相同问题直接返回 省 token
限流 每用户每分钟 N 次 防滥用
小模型分流 简单问题用便宜模型 降成本
历史裁剪 只带最近 6 条 降 token
并行 无依赖的工具并行调用 降延迟

8. 上线检查清单

□ .env 不在镜像/仓库里
□ 有 /health 健康检查
□ 模型调用有 timeout 和重试
□ 工具异常有兜底,不会 500
□ 每个请求独立 thread_id
□ 日志包含 trace_id / 耗时 / 意图
□ 评估集能一键跑
□ 有单用户限流
□ 有成本上限告警
□ README 写清启动方式

9. 常见错误

现象 原因 解决
多人对话串台 共用 thread_id 按用户+会话生成
上线后 500 没捕获模型异常 try/except + 兜底话术
首屏很慢 同步调用 + 无流式 流式输出 + 超时
成本失控 历史全量重发 裁剪 + 摘要
评估不可复现 temperature 高 + 无固定集 设 0 + 固定评估集

10. 本章小结

  • 核心逻辑抽成纯函数,CLI/API/Web 共用;
  • FastAPI + Docker 是最小可交付形态;
  • 日志至少记:意图、耗时、长度、trace_id;
  • 评估集要覆盖常规、边界、多步、拒答、多轮;
  • 上线前按清单逐项检查。

11. 练习

  1. 给 /chat 加一个 stream=true 的流式接口;
  2. 用 SqliteSaver 替换内存检查点,重启后会话还在;
  3. 写 20 条评估用例,统计通过率并列出失败案例;
  4. 给 API 加一个简单的每分钟限流。