v0.3.2: Link Start! WebChat!手搓第一个WebChat模型

This commit is contained in:
guan
2026-10-09 17:37:58 +08:00
parent c5c78e5a0a
commit 521b676721
10 changed files with 435 additions and 48 deletions
+57 -29
View File
@@ -1,37 +1,65 @@
import httpx
"""AgentSeed 第三章:将命令行对话展示为一个最小的 Chat Web。"""
from pathlib import Path
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
base_url = "https://api.example.com/v1/messages"
api_key = "sk-xxxx"
model = "claude-fable-5"
system_prompt = "你是一只可爱活泼元气猫娘~ 说话末尾带喵~" # 设置模型的身份和行为
messages = [] # 保存本次对话的历史消息
system_prompt = "请用轻松、亲切、自然的语气交流,表达简洁,有幽默感。" # 设置模型的身份和行为
messages: list[dict[str, str]] = [] # 保存本次对话的历史消息
while True:
user_input = input("You> ")
BASE_DIR = Path(__file__).parent
MAX_TOKENS = 1024
messages.append({"role": "user", "content": user_input}) # 添加用户输入的消息到历史消息列表中
app = FastAPI(title="AgentSeed Chat")
response = httpx.post(
base_url,
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
},
json={
"model": model,
"max_tokens": 20, # 设置模型最多生成的 Token 数量
"system": system_prompt, # 设置模型的身份和行为
"messages": messages, # 历史消息列表
},
timeout=60,
)
class MessageRequest(BaseModel):
"""描述发送消息接口接收的请求体。"""
data = response.json()
assistant_message = "" # 初始化助手回复的消息
print("Assistant>", end=" ")
for block in data["content"]:
if block["type"] == "text":
assistant_message += block["text"] # 拼接助手回复的消息
print(block["text"], end="")
print()
messages.append({"role": "assistant", "content": assistant_message}) # 添加助手回复的消息到历史消息列表中
content: str = Field(min_length=1, max_length=2000)
@app.post("/api/messages")
def create_message(request: MessageRequest) -> dict[str, str]:
"""接收用户消息,调用模型,并保存模型回复。"""
messages.append({"role": "user", "content": request.content})
try:
response = httpx.post(
base_url,
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
},
json={
"model": model,
"max_tokens": MAX_TOKENS,
"system": system_prompt,
"messages": messages,
},
timeout=60,
)
response.raise_for_status()
data = response.json()
assistant_content = "".join(
block["text"]
for block in data["content"]
if block["type"] == "text"
)
except (httpx.HTTPError, KeyError, IndexError, TypeError, ValueError) as exc:
# 保留已经加入的用户消息,方便通过 GET 观察请求过程;本轮回复失败。
raise HTTPException(status_code=502, detail="模型服务调用失败") from exc
assistant_message = {"role": "assistant", "content": assistant_content}
messages.append(assistant_message)
return assistant_message
# 访问 / 时返回前端页面;API 路由定义在挂载静态目录之前。
app.mount("/", StaticFiles(directory=BASE_DIR / "static", html=True), name="static")