appQQQ commited on
Commit
4bd952b
·
verified ·
1 Parent(s): 74feb32

chore: upload app/streaming/events.py

Browse files
Files changed (1) hide show
  1. app/streaming/events.py +84 -0
app/streaming/events.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AG-UI 兼容事件类型常量 + helper.
2
+
3
+ AG-UI 协议: https://docs.ag-ui.com (CopilotKit 提出, 2025 起逐步成为 agent UI 事件标准)
4
+
5
+ 我们的 9 类事件:
6
+ - thinking: Agent 推理过程 / 决策说明
7
+ - agent_step: 节点生命周期 (running / done / error)
8
+ - retrieval: 命中文档 ID + 分数
9
+ - tool_call: 工具调用详情
10
+ - token: LLM delta
11
+ - citation: 引用片段
12
+ - progress: 整体进度 0-100
13
+ - done: 结束
14
+ - error: 错误
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from typing import Any, Literal
20
+
21
+ # 事件类型常量 (防止拼写错)
22
+ EV_THINKING = "thinking"
23
+ EV_AGENT_STEP = "agent_step"
24
+ EV_RETRIEVAL = "retrieval"
25
+ EV_TOOL_CALL = "tool_call"
26
+ EV_TOKEN = "token"
27
+ EV_CITATION = "citation"
28
+ EV_PROGRESS = "progress"
29
+ EV_DONE = "done"
30
+ EV_ERROR = "error"
31
+
32
+ ALL_EVENTS: tuple[str, ...] = (
33
+ EV_THINKING, EV_AGENT_STEP, EV_RETRIEVAL, EV_TOOL_CALL,
34
+ EV_TOKEN, EV_CITATION, EV_PROGRESS, EV_DONE, EV_ERROR,
35
+ )
36
+
37
+
38
+ def sse_format(event: str, data: dict[str, Any]) -> str:
39
+ """格式化为标准 SSE 双行: `event: <type>\\ndata: <json>\\n\\n`."""
40
+ payload = json.dumps(data, ensure_ascii=False, default=str)
41
+ return f"event: {event}\ndata: {payload}\n\n"
42
+
43
+
44
+ def sse_heartbeat() -> str:
45
+ """保活注释, 避免代理超时. 不属于事件, 不会触发前端 listener."""
46
+ return ": keepalive\n\n"
47
+
48
+
49
+ def sse_done(usage: dict[str, int] | None = None, total_ms: int = 0) -> str:
50
+ return sse_format(EV_DONE, {"usage": usage or {}, "total_ms": total_ms})
51
+
52
+
53
+ def sse_error(
54
+ code: str,
55
+ message: str,
56
+ *,
57
+ retryable: bool = False,
58
+ detail: dict[str, Any] | None = None,
59
+ ) -> str:
60
+ return sse_format(
61
+ EV_ERROR,
62
+ {"code": code, "message": message, "retryable": retryable, "detail": detail or {}},
63
+ )
64
+
65
+
66
+ # 节点名常量 (在 LangGraph 里用到, 统一在此声明)
67
+ NODE_ROUTE = "route"
68
+ NODE_QUERY_REWRITE = "query_rewrite"
69
+ NODE_RETRIEVE = "retrieve"
70
+ NODE_RERANK = "rerank"
71
+ NODE_TOOL = "tool_executor"
72
+ NODE_ANSWER = "answer"
73
+ NODE_EVALUATE = "evaluate"
74
+
75
+ ALL_NODES: tuple[str, ...] = (
76
+ NODE_ROUTE, NODE_QUERY_REWRITE, NODE_RETRIEVE, NODE_RERANK,
77
+ NODE_TOOL, NODE_ANSWER, NODE_EVALUATE,
78
+ )
79
+
80
+
81
+ NodeName = Literal[
82
+ "route", "query_rewrite", "retrieve", "rerank",
83
+ "tool_executor", "answer", "evaluate",
84
+ ]