
项目整体架构前端网页浏览器 --【HTTP/WebSocket】-- FastAPI 后端Python --【HTTPJSON】-- DeepSeek 开放 API 打包工具Docker 数据格式全程 JSON 能力普通问答 WebSocket 流式输出模拟 AI 逐字打字效果智能体必备选用DeepSeek注册简单新用户送免费额度适合学习开发第一步申请 DeepSeek API 密钥免费测试额度打开官网https://platform.deepseek.com/注册账号完成实名认证必须左侧菜单栏 →API Keys创建新密钥复制sk-xxxxxxxx⚠️妥善保存只放在后端代码绝对不能丢到前端网页环境清单你需要安装本地电脑Python3.10Git可选Docker Desktop第二步创建项目文件夹plaintextai_agent_demo/ ├── main.py # FastAPI后端核心 ├── .env # 存放你的API密钥不要上传git ├── Dockerfile # Docker打包配置 └── static/ └── index.html # 前端网页页面1. .env 文件envDEEPSEEK_API_KEYsk_你刚才复制的密钥 DEEPSEEK_URLhttps://api.deepseek.com/v1/chat/completions2. main.py 后端代码python运行import os import json import requests from dotenv import load_dotenv from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles load_dotenv() app FastAPI(title简易AI智能体) app.mount(/static, StaticFiles(directorystatic), namestatic) API_KEY os.getenv(DEEPSEEK_API_KEY) API_URL os.getenv(DEEPSEEK_URL) # 返回聊天网页 app.get(/, response_classHTMLResponse) async def get_html(): with open(static/index.html, r, encodingutf-8) as f: return f.read() # HTTP普通接口一次性返回全部回答 app.post(/chat) async def chat(message: dict): user_msg message.get(content) payload { model: deepseek-chat, messages: [{role: user, content: user_msg}], stream: False } headers {Authorization: fBearer {API_KEY}, Content-Type: application/json} resp requests.post(API_URL, jsonpayload, headersheaders) return resp.json() # WebSocket接口流式逐字输出智能体流式对话核心 app.websocket(/ws) async def ws_chat(websocket: WebSocket): await websocket.accept() try: while True: data await websocket.receive_text() user_msg json.loads(data)[content] payload { model: deepseek-chat, messages: [{role: user, content: user_msg}], stream: True } headers {Authorization: fBearer {API_KEY}, Content-Type: application/json} response requests.post(API_URL, jsonpayload, headersheaders, streamTrue) for line in response.iter_lines(): if line and line.startswith(bdata: ): text line.decode(utf-8)[6:] if text [DONE]: break chunk json.loads(text) content chunk[choices][0][delta].get(content, ) await websocket.send_text(json.dumps({content: content})) except WebSocketDisconnect: print(客户端断开连接) if __name__ __main__: import uvicorn uvicorn.run(main:app, host0.0.0.0, port8000)3. static/index.html 前端页面html预览!DOCTYPE html html head meta charsetUTF-8 title简易AI智能体/title /head body div idmsgBox stylewidth:600px;height:400px;border:1px solid #ccc;overflow:auto;padding:10px;/div input idinputText stylewidth:520px;margin-top:10px; placeholder输入消息 button onclicksendMessage()发送/button script const ws new WebSocket(ws://${location.host}/ws); const msgBox document.getElementById(msgBox); const input document.getElementById(inputText); let aiBlock; ws.onmessage function (ev) { const data JSON.parse(ev.data); aiBlock.innerText data.content; } function sendMessage() { const text input.value.trim(); if (!text) return; msgBox.innerHTML div用户${text}/div; aiBlock document.createElement(div); aiBlock.innerHTML AI; msgBox.appendChild(aiBlock); ws.send(JSON.stringify({content:text})); input.value ; } /script /body /html4. Dockerfile打包镜像使用 Docker 部署dockerfileFROM python:3.11-slim WORKDIR /app COPY . . RUN pip install fastapi uvicorn python-dotenv requests EXPOSE 8000 CMD [uvicorn, main:app, --host, 0.0.0.0, --port, 8000]第三步本地直接运行测试不使用 Docker新建虚拟环境可选安装依赖bashpip install fastapi uvicorn python-dotenv requests在项目根目录执行bashpython main.py浏览器访问 http://127.0.0.1:8000 ✅ 此时网页通过 WebSocket 连接后端后端用 HTTPJSON 调用 DeepSeek 大模型 API第四步使用 Docker 打包运行构建镜像bashdocker build -t ai-agent-demo .启动容器bashdocker run -p 8000:8000 --env-file .env ai-agent-demo整套项目对应你学习的知识点JSON前后端通信、调用大模型 API 全部使用 json 传输数据HTTP/chat 接口、后端请求 DeepSeek 接口都是 HTTP 协议WebSocket/ws 实现实时流式对话长连接双向通信FastAPI搭建后端服务Docker项目容器化打包方便部署LLM 调用流程后端转发请求调用大模型 API重要学习拓展方向后续智能体升级增加记忆功能保存历史对话上下文增加 Function Calling工具调用真正实现 AI 智能体增加 RAG 知识库优化前端界面常见避坑提醒API 密钥只放在.env不要提交到 Git前端不能直接调用 DeepSeek 接口防止密钥泄露免费额度用完后需要充值仅适合学习使用streamTrue 流式输出依靠 SSE配合 WebSocket 实现打字效果使用智谱 GLM-4-Flashmain里面的payload { model: deepseek-chat, # 这里把 deepseek-chat 修改成 glm-4-flash messages: [{role: user, content: user_msg}], stream: True }完整替换下面这份无缩进错误的 main.py全部覆盖保存python运行import os import json import requests from dotenv import load_dotenv from fastapi import FastAPI, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles load_dotenv() app FastAPI(title简易AI智能体) app.mount(/static, StaticFiles(directorystatic), namestatic) API_KEY os.getenv(ZHIPU_API_KEY) API_URL os.getenv(ZHIPU_URL) app.get(/, response_classHTMLResponse) async def get_html(): with open(static/index.html, r, encodingutf-8) as f: return f.read() app.post(/chat) async def chat(message: dict): user_msg message.get(content) payload { model: glm-4-flash, messages: [{role: user, content: user_msg}], stream: False } headers {Authorization: fBearer {API_KEY}, Content-Type: application/json} resp requests.post(API_URL, jsonpayload, headersheaders) return resp.json() app.websocket(/ws) async def ws_chat(websocket: WebSocket): await websocket.accept() try: while True: data await websocket.receive_text() user_msg json.loads(data)[content] payload { model: glm-4-flash, messages: [{role: user, content: user_msg}], stream: True } headers {Authorization: fBearer {API_KEY}, Content-Type: application/json} response requests.post(API_URL, jsonpayload, headersheaders, streamTrue) for line in response.iter_lines(): if line: line_str line.decode(utf-8) if line_str.startswith(data: ): text line_str[6:] if text [DONE]: break chunk json.loads(text) content chunk[choices][0][delta].get(content, ) await websocket.send_text(json.dumps({content: content})) except WebSocketDisconnect: print(客户端断开连接) if __name__ __main__: import uvicorn uvicorn.run(main:app, host0.0.0.0, port8000)警告信息plaintextWARNING: No supported WebSocket library detected. Please use pip install uvicorn[standard], or install websockets or wsproto manually.uvicorn 缺少 WebSocket 依赖库无法处理 ws 连接直接导致 /ws 接口失效、返回 404和 Python 社区版无关单纯缺少依赖包。解决方案在虚拟环境内执行当前终端已经激活.venv直接运行安装命令bashpip install uvicorn[standard]