命令行里的程序怎么分享?发一个 .py 让人 python main.py?—— Web 服务把你的代码变成一个 URL。本周:FastAPI 后端 → 前端聊天页 → 对话记忆 → AI 结对开发方法论。M5 收官。
| 时间 | 环节 | 要点 |
|---|---|---|
| 0–10 | FastAPI 六行 | 路由=URL 与函数绑定;Pydantic 模型自动校验;/docs 自动文档 |
| 10–22 | 三种参数 | 路径/查询/请求体;async def——等 LLM 不阻塞 |
| 22–34 | 封装 /chat | 把 llm_chat 包成 POST 服务;health 检查端点 |
| 34–46 | 前端最小集 | HTML 三件套 + fetch + async/await;DOM 渲染回复 |
| 46–58 | 联调三坑 | CORS / 字段名 / 类型转换——各给排查口诀 |
| 58–70 | 动手练习 | 运行场:SessionManager 会话隔离 + 超限摘要 + clear |
| 70–80 | 对话记忆 | API 无状态——记忆是你传的 messages;Token 预算与摘要压缩 |
| 80–92 | 五步方法论 | 需求拆解→架构→增量生成→每步验证→调试;四条结对原则;协作日志 |
| 92–100 | M5 收官 | 零件集齐;下周项目启动 |
M5 收官:llm_chat + /chat + 前端页 + 记忆 = 完整 AI 应用的全部零件。
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class ChatRequest(BaseModel): # 请求体结构(自动校验)
message: str
@app.post("/chat") # 路由 = URL 与函数的绑定
async def chat(req: ChatRequest):
return {"reply": await call_llm(req.message)}
# 启动:uvicorn main:app --reload 然后打开 /docs 看自动文档
/chat/{id}、查询参数 ?model=x、请求体(POST JSON)async def:等 LLM 响应时不阻塞,单进程也能服务多个请求<div id="msgs"></div> <input id="inp"> <button onclick="send()">发送</button>
async function send() { // 和 Python 的 async/await 概念相同
const r = await fetch("/chat", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({message: inp.value})
});
const data = await r.json();
msgs.innerHTML += `<p>AI: ${data.reply}</p>`; // DOM 操作显示回复
}
reply,前端读 answer → undefined。对着接口文档逐字核对。深入阅读:M5 模块页 · FastAPI 实战 · 实战续