Files
ai-kefu-admin/app/engine/routes/chat_rest.py
T
浅念 49e2b476f5 fix: 配置接线审查修复(push数值哨兵化/恒真测试修正/哨兵防漂移/种子映射消双路径)
Important-1: push 数值字段(timeout/max_attempts/retry_backoff_base)
出厂默认改 None 哨兵(与 ai.model 同款),resolve_push_settings 对 None
回退 env——根治 truthy 出厂默认永久遮住 env 覆盖;恒真测试修正(env 数值
patch 成 7.5/5/2.0 与出厂区分)+租户显式数值优先断言;ai.provider 遮
env 的边界记入 docstring。Minor-2: 出厂 model 哨兵与 DEFAULT_CONFIG
一致性测试 + defaults.py 双源注释(model/rate_limit_per_hour)。
Minor-4: allowed_seed_keys → context_seed_map(返回映射,单一取值路径)。
Minor-6/7/3/8: WS 配置冻结时机注释/name_to_region 查表序注释改准确/
chat_rest limit 0 语义注释/resolver None 路径仅供测试注释。404 全绿。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-12 21:57:57 +08:00

161 lines
6.4 KiB
Python

"""REST shell for the HESUPIPE app (non-streaming, JSON-in/JSON-out).
These routes wrap `ConversationManager`, shared with the existing `/ws/chat`
widget path. The app uses HTTP because it lacks a WebSocket client and is fine
with a 3-8s "AI is typing" affordance covering the round trip.
Red lines (see spec):
- WS path (`app/api/routes/chat.py`) shares `ConversationManager` with these
routes; both paths stay drift-free.
- `context` seeding is conditional + whitelist (handled in
`ConversationManager.create_conversation`; Task 9 起白名单 =
租户 config.engine.context_seed_keys——jiancai product_*/auto vehicle_*).
- The message route consumes `stream_process_message`; lead email is
triggered inside `ConversationManager` when contact info is detected
(contact-driven-lead-email plan).
"""
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select
from app.engine.models import ConversationSource, ConversationStatus, Message
from app.engine.routes.runtime import get_runtime
from app.engine.services.conversation import ConversationManager
from app.engine.services.rate_limit import DEFAULT_MAX
from app.engine.services.rate_limit import check as rate_check
router = APIRouter(prefix="/api/chat", tags=["chat-rest"])
class SessionRequest(BaseModel):
session_id: str | None = None
context: dict | None = None
client_info: dict | None = None
@router.post("/session")
async def chat_session(req: SessionRequest, request: Request):
"""Resume an active conversation by session_id, or create a new app one.
`context` flows into `create_conversation` where it is whitelisted into
`raw_info` (only when non-None). `client_info` is stored for analytics only
(ip/ua/device-id/lang) and never fed to the AI prompt.
"""
# 服务端 XFF 优先于客户端自报 ip(客户端自报可伪造,可伪造面最小)
xf = request.headers.get("x-forwarded-for", "").split(",")[0].strip()
client_info = dict(req.client_info or {})
if xf:
client_info["ip"] = xf
# Task 5b: 租户运行时经 state/默认租户兜底解析(过渡期无中间件);
# manager 由装配线从 runtime 造(db 会话 + runtime 引用)
runtime = get_runtime(request)
async with runtime.session_factory() as db:
manager = ConversationManager(db, runtime=runtime)
if req.session_id:
conv = await manager.get_by_session(req.session_id)
if conv and conv.status == ConversationStatus.active:
return {
"session_id": conv.session_id,
"is_new": False,
"ended": False,
}
conv = await manager.create_conversation(
source=ConversationSource.app,
client_info=client_info,
context=req.context,
)
return {
"session_id": conv.session_id,
"is_new": True,
"ended": False,
}
@router.get("/{session_id}/messages")
async def chat_history(session_id: str, request: Request):
"""Public history endpoint for session replay. App-source only, to narrow
the read surface; an unknown or non-app session yields 404.
"""
runtime = get_runtime(request)
async with runtime.session_factory() as db:
manager = ConversationManager(db, runtime=runtime)
conv = await manager.get_by_session(session_id)
if not conv or conv.source != ConversationSource.app:
raise HTTPException(status_code=404, detail="session not found")
result = await db.execute(
select(Message)
.where(Message.conversation_id == conv.id)
.order_by(Message.created_at)
)
msgs = result.scalars().all()
return [
{
"role": m.role.value,
"content": m.content,
"created_at": m.created_at.isoformat(),
}
for m in msgs
]
class MessageRequest(BaseModel):
session_id: str
content: str
@router.post("/message")
async def chat_message(req: MessageRequest, request: Request):
"""Process one app turn: stream-collect the AI reply, then evaluate.
🔴 Consumes `stream_process_message` so the REST path shares one code
path with the WS widget and never drifts. Lead email is triggered inside
`ConversationManager` when contact info is detected
(contact-driven-lead-email plan) — this route carries no email logic.
A light in-memory rate limit (per tenant + ip + X-Device-Id, rolling 1h)
guards GLM spend; only this route is throttled. Task 9: 桶键加租户维度
(两租户同出口 IP 不互挤配额),上限读租户 config.engine.rate_limit_per_hour
(默认 30,与出厂一致)。
"""
runtime = get_runtime(request)
ip = request.client.host if request.client else ""
dev = request.headers.get("X-Device-Id", "")
engine_cfg = runtime.config.data.get("engine") or {}
# 类型与 0 语义由 Phase 2 配置校验统一(当前: 空/0 回退 DEFAULT_MAX)
limit = engine_cfg.get("rate_limit_per_hour") or DEFAULT_MAX
if not rate_check(runtime.config.slug, ip, dev, max_requests=limit):
raise HTTPException(status_code=429, detail="rate limit exceeded")
async with runtime.session_factory() as db:
manager = ConversationManager(db, runtime=runtime)
conv = await manager.get_by_session(req.session_id)
if not conv:
raise HTTPException(status_code=404, detail="session not found")
if conv.status != ConversationStatus.active:
raise HTTPException(status_code=409, detail="conversation ended")
reply_parts: list[str] = []
ended = False
intent_level = "pending"
async for event in manager.stream_process_message(
req.session_id, req.content
):
t = event.get("type")
if t == "stream_chunk":
reply_parts.append(event.get("content", ""))
elif t == "evaluated":
ended = bool(event.get("ended"))
intent_level = event.get("intent_level", "pending")
elif t == "error":
msg = event.get("message", "error")
raise HTTPException(
status_code=409 if "ended" in msg else 404, detail=msg
)
return {
"reply": "".join(reply_parts),
"ended": ended,
"intent_level": intent_level,
}