Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(observability): add response feedback tracking to openapi (#1660)

yepper21854b5c58e8
diff --git a/bot/README.md b/bot/README.md
index 7fea0c448..c20b42642 100644
--- a/bot/README.md
+++ b/bot/README.md
@@ -431,6 +431,7 @@ vikingbot gateway
- Session and user tracking
- LLM call monitoring
- Token usage tracking
+- Feedback observability design: `bot/docs/vikingbot-feedback-observability-design.md`
</details>
diff --git a/bot/README_CN.md b/bot/README_CN.md
index 01679ea45..47ac40a51 100644
--- a/bot/README_CN.md
+++ b/bot/README_CN.md
@@ -425,6 +425,7 @@ vikingbot gateway
- Session 和 User 追踪
- LLM 调用监控
- Token 使用量追踪
+- 问答效果反馈观测方案:`bot/docs/vikingbot-feedback-observability-design.md`
</details>
@@ -596,4 +597,3 @@ which nodejs
| `ov chat --no-format` | 显示纯文本回复(无 Markdown) |
交互模式退出:`exit`、`quit`、`/exit`、`/quit`、`:q` 或 `Ctrl+D`。
-
diff --git a/bot/deploy/docker/deploy_langfuse.sh b/bot/deploy/docker/deploy_langfuse.sh
index 80dd0be77..5c762b85d 100755
--- a/bot/deploy/docker/deploy_langfuse.sh
+++ b/bot/deploy/docker/deploy_langfuse.sh
@@ -8,8 +8,17 @@ LANGFUSE_DIR="$SCRIPT_DIR/langfuse"
cd "$LANGFUSE_DIR"
+if docker compose version >/dev/null 2>&1; then
+ COMPOSE_CMD=(docker compose)
+elif command -v docker-compose >/dev/null 2>&1; then
+ COMPOSE_CMD=(docker-compose)
+else
+ echo "Error: neither 'docker compose' nor 'docker-compose' is available."
+ exit 1
+fi
+
echo "🚀 Starting Langfuse..."
-docker-compose up -d
+"${COMPOSE_CMD[@]}" up -d
echo ""
echo "✅ Langfuse deployed successfully!"
@@ -24,5 +33,5 @@ echo "🔑 API keys:"
echo " Public key: pk-lf-vikingbot-public-key-2026"
echo " Secret key: sk-lf-vikingbot-secret-key-2026"
echo ""
-echo "📝 To view logs: docker-compose -f $LANGFUSE_DIR/docker-compose.yml logs -f"
-echo "📝 To stop: docker-compose -f $LANGFUSE_DIR/docker-compose.yml down"
+echo "📝 To view logs: ${COMPOSE_CMD[*]} -f $LANGFUSE_DIR/docker-compose.yml logs -f"
+echo "📝 To stop: ${COMPOSE_CMD[*]} -f $LANGFUSE_DIR/docker-compose.yml down"
diff --git a/bot/docs/rfc-openviking-cli-ov-chat.md b/bot/docs/rfc-openviking-cli-ov-chat.md
index 8043329c5..47d2ac496 100644
--- a/bot/docs/rfc-openviking-cli-ov-chat.md
+++ b/bot/docs/rfc-openviking-cli-ov-chat.md
@@ -32,10 +32,10 @@ flowchart TB
subgraph Server["OpenViking Server<br/>(Python/FastAPI, Port 1933)"]
Auth["统一认证中间件<br/>Unified Auth"]
BotAPIProxy["Bot API Proxy<br/>(--with-bot)"]
- BotRouter["/api/v1/bot/*<br/>Router"]
+ BotRouter["/bot/v1/*<br/>Router"]
end
- subgraph Vikingbot["Vikingbot (Process 2, Port 18791)"]
+ subgraph Vikingbot["Vikingbot (Process 2, Port 18790)"]
subgraph Channels["Channels (BaseChannel 实现)"]
OC["OpenAPIChannel"]
FC["FeishuChannel<br/>(Webhook)"]
@@ -105,7 +105,7 @@ flowchart TB
DiscordClient["Discord Client"]
end
- CLI -->|"HTTP POST<br/>http://localhost:18791/chat"| OCEndpoints
+ CLI -->|"HTTP POST<br/>http://localhost:1933/bot/v1/chat"| OCEndpoints
FeishuApp -->|"Webhook POST<br/>/webhook/event"| FCEndpoints
DiscordClient -->|"WebSocket"| Discord
@@ -175,7 +175,7 @@ flowchart TB
- Support for session management and context building / 支持会话管理和上下文构建
**Architecture Position / 架构位置:**
-- Process 2 (Port 18791 default) / 进程2(默认端口 18791)
+- Process 2 (Port 18790 default) / 进程2(默认端口 18790)
- Receives proxied requests from OpenViking Server / 接收来自 OpenViking 服务器的代理请求
---
@@ -201,9 +201,9 @@ Channel → MessageBus.inbound → Agent Loop → MessageBus.outbound → Channe
| Method | Path | Description |
|--------|------|-------------|
-| GET | `/api/v1/bot/health` | Health check |
-| POST | `/api/v1/bot/chat` | Send message (non-streaming) |
-| POST | `/api/v1/bot/chat/stream` | Send message (streaming, SSE) |
+| GET | `/bot/v1/health` | Health check |
+| POST | `/bot/v1/chat` | Send message (non-streaming) |
+| POST | `/bot/v1/chat/stream` | Send message (streaming, SSE) |
### 4.2 Response Codes
@@ -225,8 +225,8 @@ openviking-server --with-bot
# Output:
# OpenViking HTTP Server is running on 127.0.0.1:1933
-# Bot API proxy enabled, forwarding to http://localhost:18791
-# [vikingbot] Starting gateway on port 18791...
+# Bot API proxy enabled, forwarding to http://127.0.0.1:18790
+# Starting vikingbot gateway...
```
**说明 / Note:**
@@ -248,17 +248,17 @@ ov chat
ov chat -m "Hello, bot!"
# Use custom endpoint
-VIKINGBOT_ENDPOINT=http://localhost:1933/api/v1/bot ov chat -m "Hello!"
+VIKINGBOT_ENDPOINT=http://localhost:1933/bot/v1 ov chat -m "Hello!"
```
### 5.3 Direct HTTP API usage / 直接 HTTP API 使用
```bash
# Health check
-curl http://localhost:1933/api/v1/bot/health
+curl http://localhost:1933/bot/v1/health
# Send a message
-curl -X POST http://localhost:1933/api/v1/bot/chat \
+curl -X POST http://localhost:1933/bot/v1/chat \
-H "Content-Type: application/json" \
-d '{
"message": "Hello!",
@@ -267,7 +267,7 @@ curl -X POST http://localhost:1933/api/v1/bot/chat \
}'
# Streaming response
-curl -X POST http://localhost:1933/api/v1/bot/chat/stream \
+curl -X POST http://localhost:1933/bot/v1/chat/stream \
-H "Content-Type: application/json" \
-d '{
"message": "Hello!",
@@ -293,7 +293,7 @@ Vikingbot 的配置项统一放在 `ov.conf` 的 `bot` 字段下:
"port": 1933,
"root_api_key": "your-api-key",
"with_bot": true,
- "bot_api_url": "http://localhost:18791"
+ "bot_api_url": "http://localhost:18790"
},
"bot": {
"agents": {
@@ -303,7 +303,7 @@ Vikingbot 的配置项统一放在 `ov.conf` 的 `bot` 字段下:
},
"gateway": {
"host": "127.0.0.1",
- "port": 18791,
+ "port": 18790,
"token": ""
},
"channels": [
diff --git a/bot/docs/vikingbot-feedback-observability-design.md b/bot/docs/vikingbot-feedback-observability-design.md
new file mode 100644
index 000000000..2b80eb0e6
--- /dev/null
+++ b/bot/docs/vikingbot-feedback-observability-design.md
@@ -0,0 +1,818 @@
+# Vikingbot 问答效果反馈观测方案设计
+
+**Author:** OpenViking Team
+**Status:** Revised Draft
+**Date:** 2026-04-30
+
+---
+
+## 1. 背景
+
+基于当前代码复核,vikingbot 现状更准确地说是“过程可观测”,而不是“结果可观测”。
+
+当前已经存在的能力包括:
+
+- `AgentLoop` 最终返回的 `OutboundMessage` 已携带 `time_cost`、`token_usage`、`iteration`、`tools_used_names`
+- bus 已支持 `REASONING`、`TOOL_CALL`、`TOOL_RESULT`、`ITERATION`、`NO_REPLY` 等过程事件
+- Langfuse 已接入 `session_id` / `user_id` 透传、LLM generation、tool span
+- session 以 JSONL 持久化历史消息,assistant 消息可保存 `token_usage` 与 `tools_used`
+
+但原方案的若干前提与当前实现已经有偏差,主要体现在:
+
+- Phase 1 已经补齐 `response_id`,并打通到 `OutboundMessage`、session JSONL、OpenAPI 返回体与 Langfuse metadata
+- Phase 2 当前工作树已经补齐显式反馈入口,OpenAPI 提供 `POST /bot/v1/feedback`
+- `response_completed` 与 `feedback_submitted` 已经进入实现范围;`response_outcome_evaluated` 仍然属于 Phase 3,但当前工作树已经落地最小规则版实现
+- session JSONL 目前不是面向分析的响应事实表,`time_cost`、`iteration`、`tools_used_names` 也没有以统一结构持久化到响应记录里
+- OpenAPI 当前只透出 `response`、`reasoning`、`tool_call`、`tool_result`,并未把 `ITERATION` 等过程事件完整暴露出来
+- Langfuse 当前写入的 generation metadata 已覆盖 `response_id`;`query_category`、`prompt_version`、`bot_version` 仍未稳定覆盖;Phase 3 outcome 当前通过 trace event 与 observation score 记录,而不是事后回写已结束 generation metadata
+- 代码中还没有稳定的 `query_category`、`prompt_version`、`bot_version` 字段来源,因此原方案里大量切片分析暂时没有数据基础
+
+### 1.1 截至 2026-04-30 的实现状态更新
+
+为避免后续讨论继续把“设计目标”误写成“当前能力”,这里先明确当前代码状态:
+
+1. Phase 1 已完成并已单独提交,`response_id` 已经贯通最终回答链路。
+2. Phase 2 当前实现已经包含 `POST /bot/v1/feedback`、`FeedbackRequest` / `FeedbackResponse`、`OutboundEventType.FEEDBACK_SUBMITTED`。
+3. 显式反馈当前采用最小化落地:反馈事件追加写入 session JSONL 的 `session.metadata["feedback_events"]`,而不是新建独立事实表。
+4. `feedback_submitted` 属于 analytics-only 事件,用户侧 channel 明确忽略该事件,避免把分析事件误发到用户可见通道。
+5. `response_outcome_evaluated` 仍然是 Phase 3 能力,但当前仅实现 analytics-only 的最小规则版,不应误写成完整离线评测体系。
+
+因此,这份方案需要从“直接建设完整反馈归因体系”调整为“三步走”:
+
+1. 先把一次回答变成可识别、可关联、可沉淀的结构化对象。
+2. 再补显式反馈闭环。
+3. 最后再做隐式结果判断、问题分类和版本归因。
+
+在这个调整后的前提下,现有信息仍然足以回答“系统有没有运行”“模型和工具有没有被调用”,但还不足以回答更关键的问题:
+
+1. 用户是否觉得这次回答有效。
+2. 回答是否真正解决了用户问题。
+3. 哪类问题效果差。
+4. 效果差是因为模型、工具、时延,还是对话策略。
+5. 改 prompt、改模型、改工具后,效果是否提升。
+
+本方案的目标是为 vikingbot 建立一套面向“问答效果反馈”的观测体系,形成从回答生成到用户反馈、再到问题归因的完整闭环,并且保证每一阶段都建立在当前代码已具备的事实基础上。
+
+---
+
+## 2. 设计目标
+
+### 2.1 目标
+
+本方案希望建立一套可持续使用的指标体系,用于衡量 vikingbot 的问答质量和用户体验。
+
+设计目标如下:
+
+1. 能稳定衡量单条回答和单个会话的效果。
+2. 能区分“模型回答差”“工具调用差”“执行太慢”等不同失败模式。
+3. 能支持按模型、渠道、问题类型、版本进行切片分析。
+4. 能与 Langfuse trace 关联,支持从坏样本回溯到具体执行链路。
+5. 能渐进式落地,先最小可用,再逐步增强。
+
+### 2.2 非目标
+
+本方案当前不追求以下目标:
+
+1. 不试图用单一指标替代所有人工判断。
+2. 不要求第一版就接入复杂的离线评测平台。
+3. 不要求所有指标都进入 Prometheus;部分更适合保存在业务事件或分析仓库中。
+4. 不要求完全依赖 Langfuse 完成所有聚合分析;Langfuse 更适合作为 trace 容器和样本诊断入口。
+
+---
+
+## 3. 核心问题与总体思路
+
+### 3.1 需要回答的核心问题
+
+该体系主要服务于以下五类问题:
+
+1. 用户觉得这次回答好不好。
+2. 这次回答是否一次性解决问题。
+3. 哪些问题类型和使用场景效果最差。
+4. 坏结果主要集中在哪个执行环节。
+5. 系统改动前后,效果是上升、持平还是回退。
+
+### 3.2 总体思路
+
+观测体系分为四层:
+
+1. 用户反馈层:看用户主观评价。
+2. 会话结果层:看问题是否被解决。
+3. 执行质量层:看耗时、工具、LLM 调用质量。
+4. 归因分析层:按模型、渠道、问题类型、版本等维度切片。
+
+核心链路如下:
+
+`一次回答 -> 用户反馈 -> 会话结果 -> trace 归因`
+
+换句话说,系统不能只采“过程”,也必须采“结果”。
+
+### 3.3 现状约束下的方案调整
+
+为了避免方案设计继续偏离当前实现,整体落地顺序调整为以下三层依赖:
+
+1. `response identity`:先给每次最终回答分配稳定的 `response_id`,并把它同时写入 `OutboundMessage`、session message、OpenAPI 返回体和 Langfuse metadata。
+2. `response facts`:再沉淀一条结构化 `response_completed` 事件,把当前已经能拿到的字段先稳定保存下来,例如 `session_id`、`user_id`、`time_cost`、`token_usage`、`iteration_count`、`tool_count`、`tools_used_names`、`finish_reason`。
+3. `feedback & outcome`:最后在 `response_id` 基础上补反馈事件与隐式结果判断,否则后续指标会缺少关联主键。
+
+这意味着:
+
+- 原方案中依赖 `query_category`、`prompt_version`、`bot_version` 的切片分析,需要从 MVP 下调到增强阶段
+- `good_answer_rate`、`one_turn_resolution_rate`、`reask_rate` 等结果指标,不适合作为第一批必须落地的线上指标
+- 第一阶段更应聚焦“把已有过程指标可靠地沉淀为响应事实”,而不是急于定义复杂的结果分数
+
+---
+
+## 4. 指标分层设计
+
+## 4.1 用户反馈层
+
+这层是问答效果评估的长期核心,但不应被当成 Phase 1 的落地前提。
+
+### 4.1.1 显式满意度指标
+
+建议定义以下指标:
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `feedback_coverage` | 有反馈回答数 / 总回答数 | 衡量样本覆盖率,避免只看好评率 |
+| `thumbs_up_rate` | 点赞回答数 / 有反馈回答数 | 基础正反馈指标 |
+| `thumbs_down_rate` | 点踩回答数 / 有反馈回答数 | 基础负反馈指标 |
+| `csat_score` | 用户评分均值 | 适用于 5 分制或 10 分制满意度 |
+| `dissatisfaction_reason_distribution` | 各类差评原因占比 | 用于定位主要失败模式 |
+
+差评原因建议最少支持以下标签:
+
+- `irrelevant`: 答非所问
+- `incorrect`: 信息错误
+- `incomplete`: 不够完整
+- `too_slow`: 太慢
+- `tool_failed`: 工具执行失败
+- `too_verbose`: 重复或啰嗦
+- `not_actionable`: 无法操作
+- `bad_format`: 格式不好
+
+### 4.1.2 反馈强度指标
+
+二元点赞不足以表达问题严重程度,因此建议增加:
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `strong_negative_rate` | 强负反馈数 / 有反馈回答数 | 例如“错误”或“无法完成任务”类差评 |
+| `recover_after_negative_rate` | 差评后被修复的比例 | 衡量 bot 的纠错与恢复能力 |
+
+---
+
+## 4.2 会话结果层
+
+这层用于回答“即便用户没点反馈,这次回答到底算不算成功”。
+
+### 4.2.1 单轮解决率
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `one_turn_resolution_rate` | 单轮解决回答数 / 总回答数 | 用户一次提问后 bot 第一次正式回答即解决问题 |
+
+可先使用以下代理信号:
+
+1. 用户显式好评。
+2. 回答后短时间内无追问且会话结束。
+3. 用户后续切换到新话题,而不是继续纠错或重问。
+
+### 4.2.2 重问率
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `reask_rate` | 回答后短时间内同主题再次提问的比例 | 是最重要的隐式失败信号之一 |
+
+重问信号可包括:
+
+- “不是这个意思”
+- “你没回答我的问题”
+- “重新回答”
+- “还是不对”
+- 同主题关键词在短时间内重复出现
+
+### 4.2.3 澄清和解决轮次
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `clarification_turn_rate` | 需要多轮澄清的会话占比 | 衡量首答命中程度 |
+| `avg_turns_to_resolution` | 从首次提问到解决的平均轮次 | 衡量整体问答效率 |
+
+### 4.2.4 放弃和无回复
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `no_reply_rate` | `NO_REPLY` 回答占比 | 衡量系统未回复情况 |
+| `abandonment_after_answer_rate` | 回答后用户直接离开的比例 | 用于识别体验断点 |
+
+---
+
+## 4.3 执行质量层
+
+这层用于回答“效果差的根因是什么”。
+
+### 4.3.1 响应效率指标
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `response_latency_ms_p50/p95/p99` | 端到端回答耗时分位数 | 核心体验指标 |
+| `first_tool_latency_ms` | 首次工具调用前耗时 | 用于识别前置 LLM 慢或工具规划慢 |
+| `end_to_end_time_cost` | 单条回答总耗时 | 可直接复用现有 `time_cost` |
+| `iteration_count_avg` | 平均迭代次数 | 反映 agent 复杂度和稳定性 |
+| `tool_count_avg` | 平均工具调用数 | 反映问题依赖工具程度 |
+
+### 4.3.2 LLM 质量代理指标
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `answer_length_avg` | 平均回答长度 | 用于识别过短或过长 |
+| `reasoning_present_rate` | 含 reasoning 的回答占比 | 适用于支持 reasoning 的模型 |
+| `tool_call_rate` | 触发工具调用的回答占比 | 看问题类型与工具依赖 |
+| `multi_iteration_rate` | `iteration > 1` 的回答占比 | 迭代过多通常意味着策略不稳 |
+| `max_iteration_hit_rate` | 达到最大迭代限制的比例 | 是重要失败信号 |
+
+### 4.3.3 工具执行质量指标
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `tool_success_rate` | 成功工具调用数 / 总工具调用数 | 总体工具稳定性 |
+| `tool_error_rate_by_name` | 按工具名统计的错误率 | 识别问题工具 |
+| `tool_timeout_rate_by_name` | 按工具名统计超时率 | 识别慢工具 |
+| `tool_result_used_rate` | 工具结果最终促成有效回答的比例 | 衡量工具有效性 |
+| `tool_waste_rate` | 工具被调用但对结果无帮助的比例 | 衡量无效执行 |
+
+### 4.3.4 成本质量比指标
+
+| 指标名 | 定义 | 说明 |
+| --- | --- | --- |
+| `tokens_per_positive_answer` | 总 token / 正反馈回答数 | 评估成本效率 |
+| `latency_per_positive_answer` | 总耗时 / 正反馈回答数 | 评估体验效率 |
+| `tool_calls_per_positive_answer` | 总工具数 / 正反馈回答数 | 看质量提升是否依赖复杂调用 |
+
+---
+
+## 4.4 归因分析层
+
+该层不是单独的一组指标,而是要求前面所有指标都支持按关键维度切片。
+
+建议将切片维度分成“当前阶段可稳定支持的”与“后续增强补齐的”。
+
+当前阶段优先支持:
+
+- `channel`
+- `chat_type`
+- `model`
+- `provider`
+- `session_type`
+- `tool_used`
+- `tool_name`
+- `language`
+- `user_segment`
+- `time_bucket`
+
+后续增强再补:
+
+- `query_category`
+- `prompt_version`
+- `bot_version`
+
+如果不支持这些维度切片,最终只能看到“整体效果一般”,但无法定位具体问题来源。这里尤其要避免把 `query_category`、`prompt_version`、`bot_version` 误写成当前已经稳定存在的字段来源。
+
+---
+
+## 5. 北极星指标与结果分级
+
+## 5.1 北极星指标
+
+考虑到当前实现尚无反馈入口、也无隐式 outcome 计算链路,北极星指标需要分阶段定义。
+
+### Phase 1 北极星指标
+
+如果第一阶段只能盯少量核心指标,建议优先使用以下五个:
+
+1. `response_completed_count`
+2. `response_latency_p95`
+3. `tool_success_rate`
+4. `max_iteration_hit_rate`
+5. `no_reply_rate`
+
+这五个指标都可以建立在当前代码已存在或只需极小补充的数据之上,能先回答“系统有没有稳定产出答案”。
+
+### Phase 2 北极星指标
+
+在 `response_id` 和反馈入口稳定后,再升级为以下五个:
+
+1. `good_answer_rate`
+2. `one_turn_resolution_rate`
+3. `reask_rate`
+4. `thumbs_down_rate`
+5. `response_latency_p95`
+
+其中 `good_answer_rate` 建议作为 Phase 2 之后的综合指标,定义如下:
+
+```text
+good_answer_rate =
+(显式正反馈回答数 + 隐式成功回答数) / 总回答数
+```
+
+隐式成功回答数可先使用以下判定:
+
+- 非 `NO_REPLY`
+- 非错误结束
+- 非最大迭代耗尽
+- 无短时间内重问
+- 无显式负反馈
+
+## 5.2 回答结果分级
+
+建议为每条最终回答打一个离散标签 `outcome_label`,而不是只做散乱的数值统计。
+
+建议标签如下:
+
+- `excellent`
+- `good`
+- `neutral`
+- `bad`
+- `failed`
+
+建议规则:
+
+| 标签 | 规则 |
+| --- | --- |
+| `excellent` | 有显式好评,且无后续重问 |
+| `good` | 无显式反馈,但单轮结束,无重问 |
+| `neutral` | 有继续追问,但最终解决 |
+| `bad` | 有差评,或短时间内重问/纠错 |
+| `failed` | 工具失败、LLM error、无回答、达到最大迭代仍未完成 |
+
+这样所有统计都可以统一以 `outcome_label` 为基础聚合。
+
+---
+
+## 6. 事件模型设计
+
+为了支撑上述指标,需要补充结构化事件。当前 vikingbot 已经有过程事件,但还缺少结果与反馈事件。
+
+这里建议把事件模型拆成“必须先落地”和“后续增强”两层,而不是一次性并列设计。
+
+### 6.0 当前已存在的过程事件
+
+当前代码里已经存在但尚未沉淀为分析事实表的过程事件包括:
+
+- `REASONING`
+- `TOOL_CALL`
+- `TOOL_RESULT`
+- `ITERATION`
+- `NO_REPLY`
+
+这些事件更适合用于在线流式展示和单次问题排查,不适合作为最终分析主表。后续新增事件应围绕“最终回答”来建立主键和关联关系。
+
+### 6.0.1 分阶段事件落地状态
+
+截至当前代码状态:
+
+1. Phase 1 已经落地 `response_completed` 相关主链路。
+2. Phase 2 当前工作树已经落地 `feedback_submitted` 与 `/bot/v1/feedback`。
+3. `response_outcome_evaluated` 已进入第三阶段实现,当前版本仅覆盖 session 历史加显式反馈的最小规则推导。
+
+## 6.1 `response_completed`
+
+该事件在最终回答产生时记录,是整套分析的主事实表。
+
+建议字段:
+
+| 字段名 | 说明 |
+| --- | --- |
+| `response_id` | 回答唯一 ID |
+| `trace_id` | 对应 Langfuse trace ID,如当前阶段难以稳定获取可先留空 |
+| `session_id` | 会话 ID |
+| `user_id` | 用户 ID |
+| `channel` | 渠道 |
+| `chat_type` | 单聊/群聊等,如当前阶段无统一来源可先从 channel metadata 推断 |
+| `model` | 模型名 |
+| `provider` | provider 名,如当前阶段无稳定字段可由 provider 配置推导 |
+| `message_id` | 原始消息 ID,如 channel 无该概念可为空 |
+| `time_cost_ms` | 端到端耗时 |
+| `prompt_tokens` | 输入 token |
+| `completion_tokens` | 输出 token |
+| `total_tokens` | 总 token |
+| `iteration_count` | 迭代次数 |
+| `tool_count` | 工具调用数 |
+| `tools_used_names` | 工具名列表 |
+| `finish_reason` | LLM 结束原因,如当前未显式透出则可先根据 provider 返回补齐 |
+| `has_reasoning` | 是否有 reasoning 内容;当前阶段也可先退化为“是否产生过 reasoning 事件” |
+| `response_length` | 回答长度 |
+| `query_category` | 问题分类,第二阶段再补 |
+| `prompt_version` | prompt 版本,第二阶段再补 |
+| `bot_version` | bot 版本,第二阶段再补 |
+
+其中当前阶段最低要求字段应收敛为:
+
+- `response_id`
+- `session_id`
+- `user_id`
+- `channel`
+- `time_cost_ms`
+- `prompt_tokens`
+- `completion_tokens`
+- `total_tokens`
+- `iteration_count`
+- `tool_count`
+- `tools_used_names`
+- `response_length`
+- `created_at`
+
+## 6.2 `feedback_submitted`
+
+该事件在用户提交点赞、点踩、评分或文字反馈时记录。
+
+该事件不应作为 MVP 前提。只有在 `response_id` 已经能从客户端拿到并可靠回传后,才值得接入。
+
+当前实现状态补充:
+
+1. OpenAPI 已提供 `POST /bot/v1/feedback`。
+2. 反馈按 `response_id` 回查 assistant message;找不到时返回 `404 Response not found`。
+3. 反馈会追加写入 session JSONL metadata 下的 `feedback_events`。
+4. 反馈会发布 `feedback_submitted` analytics 事件,但不会向用户侧 channel 透出。
+
+建议字段:
+
+| 字段名 | 说明 |
+| --- | --- |
+| `response_id` | 关联的回答 ID |
+| `session_id` | 会话 ID |
+| `user_id` | 用户 ID |
+| `feedback_type` | `thumb_up` / `thumb_down` / `rating` |
+| `feedback_score` | 数值评分 |
+| `feedback_reason` | 差评原因标签 |
+| `feedback_text` | 用户补充说明 |
+| `feedback_delay_sec` | 回答到反馈的间隔 |
+
+## 6.3 `response_outcome_evaluated`
+
+该事件由系统后处理产生,用于沉淀隐式结果判断。
+
+当前实现状态补充:
+
+1. 该事件已经以 analytics-only 方式落地,不会透传到用户可见 channel。
+2. 当前在两个时机触发:显式反馈写入时,以及新一轮 user turn 到来前对上一条 assistant response 做隐式评估时。
+3. 评估结果当前写入 session JSONL metadata 下的 `response_outcomes[response_id]`。
+4. 当前规则版优先使用显式 `thumb_up` / `thumb_down`,否则结合 10 分钟内 follow-up、后续 user turn 数和是否缺少反馈来推导 outcome。
+5. 当前实现是 Phase 3 的最小可用版本,不等同于完整离线 judge 或评审模型。
+
+该事件建议放在第三阶段持续增强,因为它依赖:
+
+- session 历史中能稳定关联 user / assistant 消息
+- `response_id` 已经绑定到 assistant 最终回答
+- 对“重问/纠错/切换话题/放弃”已有稳定规则
+
+建议字段:
+
+| 字段名 | 说明 |
+| --- | --- |
+| `response_id` | 回答 ID |
+| `resolved_in_one_turn` | 是否单轮解决 |
+| `reask_within_10m` | 10 分钟内是否重问 |
+| `clarification_turns` | 后续澄清轮次 |
+| `follow_up_without_feedback` | 是否出现 follow-up 且无显式反馈 |
+| `outcome_label` | 最终结果标签 |
+
+---
+
+## 7. Query 分类设计
+
+问答效果不能只看总体平均值,必须按问题类型分层。
+
+但结合当前实现,`query_category` 不应作为 Phase 1 前提,而应放到 Phase 2 之后补齐。
+
+第二阶段建议至少支持以下分类:
+
+- `general_qa`
+- `code_explanation`
+- `bug_diagnosis`
+- `file_operation`
+- `shell_execution`
+- `web_search`
+- `workflow_task`
+- `memory_or_profile`
+
+后续可以进一步扩展成更稳定的分类:
+
+- `factual`
+- `reasoning`
+- `retrieval_heavy`
+- `tool_heavy`
+- `multi_step`
+- `social_chitchat`
+
+分类来源可以按阶段逐步演进:
+
+1. 先使用规则或关键字分类,并明确这是增强能力而非现状能力。
+2. 再引入离线模型分类。
+3. 最终沉淀为稳定的业务问题 taxonomy。
+
+---
+
+## 8. 与 Langfuse 的集成设计
+
+Langfuse 适合作为 trace 容器、坏样本入口和链路诊断工具,但不建议把全部业务分析都压在 Langfuse 查询上。
+
+结合当前实现,需要先明确“已经有的”和“还没有的”。
+
+当前已经有:
+
+- `trace` 装饰器会透传 `session_id`、`user_id`
+- provider 会写入 LLM generation
+- tool registry 会写入 tool span,并附带 `success`、`duration_ms`
+
+当前还没有:
+
+- 统一写入 generation / trace 的 `query_category`
+- 统一写入 generation / trace 的 `prompt_version`、`bot_version`
+- 统一且完善的 outcome 聚合视图;当前已落地的是 trace event `response_outcome_evaluated` 与 observation score `response_outcome_label`
+
+## 8.1 Langfuse 中应承载的内容
+
+建议按三类承载信息,而不是把所有字段都塞进 generation metadata:
+
+1. trace / generation metadata:
+- `response_id`
+- `channel`
+- `chat_type`
+- `query_category`
+- `session_type`
+- `iteration_count`
+- `tool_count`
+- `tool_names`
+- `prompt_version`
+- `bot_version`
+
+2. outcome event:
+- `response_outcome_evaluated`
+
+3. outcome score:
+- `response_outcome_label`
+
+对于 Phase 3 当前实现,需要明确避免一种不准确表述:不要写成“在显式 feedback 之后把 `final_outcome_label` 回写到已结束 generation metadata”。真实落地方式是把 outcome 写到原 trace 下的 event,并把离散标签写到对应 observation score。
+
+其中建议的接入优先级是:
+
+1. 先补 `response_id`、`iteration_count`、`tool_count`、`tool_names`
+2. 再补 `query_category`
+3. Phase 3 outcome 统一使用 `response_outcome_evaluated` event + `response_outcome_label` score
+4. 最后再补 `prompt_version`、`bot_version`
+
+## 8.2 Langfuse score 建议
+
+建议将关键结果写入 Langfuse score,方便直接筛 trace:
+
+- `response_outcome_label`
+- `user_feedback_score`
+- `implicit_resolution_score`
+- `response_quality_score`
+- `tool_execution_score`
+- `latency_satisfaction_score`
+
+其中:
+
+- `response_outcome_label` 适合使用离散枚举值,例如 `positive_feedback`、`negative_feedback`、`reasked`、`resolved`
+- `user_feedback_score` 可取 `1 / 0 / -1`
+- `implicit_resolution_score` 可取 `1 / 0`
+- `response_quality_score` 可为综合分
+
+## 8.3 Langfuse 与分析仓库的关系
+
+建议职责分工如下:
+
+| 系统 | 职责 |
+| --- | --- |
+| Langfuse | trace 展示、样本回溯、执行链路诊断、坏案例筛选 |
+| 业务事件仓库 | 指标聚合、趋势分析、A/B 对比、报表与告警 |
+
+换句话说,Langfuse 用来回答“这条坏样本具体发生了什么”,而聚合分析系统用来回答“最近哪类问题整体变差了”。
+
+---
+
+## 9. Dashboard 与告警设计
+
+## 9.1 建议的三个 Dashboard
+
+Dashboard 同样需要分阶段理解:
+
+- Phase 1 先做“运行稳定性看板”和“执行诊断看板”
+- Phase 2 之后再补“业务效果看板”和“差评分析看板”
+
+### 9.1.1 业务效果看板
+
+该看板属于 Phase 2 及之后。
+
+建议展示:
+
+- `good_answer_rate`
+- `one_turn_resolution_rate`
+- `thumbs_down_rate`
+- `reask_rate`
+
+支持按以下维度切片:
+
+- 时间
+- 模型
+- channel
+- query_category
+
+### 9.1.2 执行诊断看板
+
+建议展示:
+
+- `response_latency_p95`
+- `tool_error_rate_by_name`
+- `max_iteration_hit_rate`
+- `response_completed_count`
+
+支持按以下维度切片:
+
+- provider
+- tool_name
+
+`prompt_version` 相关切片应放到后续增强阶段,前提是代码中已经有稳定字段来源。
+
+### 9.1.3 差评分析看板
+
+该看板同样属于 Phase 2 及之后。
+
+建议展示:
+
+- 差评原因分布
+- 差评样本 Top N
+- 差评 trace 中常见工具链
+- 差评 query_category 排名
+
+## 9.2 告警建议
+
+建议优先配置以下五类告警:
+
+1. `response_latency_p95` 超阈值
+2. `tool_success_rate` 突降
+3. `max_iteration_hit_rate` 突增
+4. `no_reply_rate` 突增
+5. `response_completed_count` 异常下降
+
+在 Phase 2 接入反馈后,再补:
+
+1. `thumbs_down_rate` 突增
+2. `good_answer_rate` 突降
+
+这些告警比单纯盯错误日志更接近真实用户体验变化。
+
+---
+
+## 10. 分阶段落地计划
+
+## 10.1 Phase 1: MVP
+
+第一阶段先做最小可用版本,目标是快速建立结构化响应事实闭环。
+
+建议优先落地:
+
+1. `response_id` 机制
+2. `response_completed` 事件
+3. 在 `OutboundMessage`、session message、OpenAPI 响应中透出 `response_id`
+4. Langfuse trace / generation metadata 关联 `response_id`
+5. 最小指标集
+
+MVP 指标集建议为:
+
+1. `response_completed_count`
+2. `response_latency_p95`
+3. `tool_success_rate`
+4. `tool_error_rate_by_name`
+5. `max_iteration_hit_rate`
+6. `no_reply_rate`
+7. `avg_iteration_count`
+8. `avg_tool_count`
+
+说明:第一阶段不再把 `feedback_coverage`、`thumbs_up_rate`、`thumbs_down_rate`、`good_answer_rate`、`one_turn_resolution_rate`、`reask_rate` 作为必须指标,因为它们当前没有数据入口或没有稳定计算依据。
+
+## 10.2 Phase 2: 增强归因能力
+
+第二阶段重点提升分析和归因能力。
+
+截至当前工作树,以下第 1、2 项已经进入实现状态,并且已经通过 `openviking-server --with-bot` 完成真实代理路径验证;后续重点应放在补充更系统的验证沉淀与指标消费,而不是把尚未完成的 Phase 3 能力提前写成已实现。
+
+建议增加:
+
+1. 点赞/点踩反馈入口与 `feedback_submitted` 事件
+2. OpenAPI 反馈接口或统一 feedback webhook
+3. query 分类
+4. `feedback_coverage`
+5. `thumbs_up_rate`
+6. `thumbs_down_rate`
+7. `negative_rate_by_query_category`
+8. `model_comparison_by_query_category`
+
+## 10.3 Phase 3: 离线评测与评审模型
+
+第三阶段再考虑引入隐式 outcome 判断与离线质量评审能力。
+
+截至当前工作树,`response_outcome_evaluated` 的最小规则版已经落地;后续重点从“是否实现”转为“规则是否足够稳健、指标如何消费、是否接入 judge”。
+
+建议先补:
+
+1. 增强 `response_outcome_evaluated` 后处理
+2. `one_turn_resolution_rate`
+3. `reask_rate`
+4. `good_answer_rate`
+5. `outcome_label`
+6. `recover_after_negative_rate`
+7. `tool_helpfulness_rate_by_name`
+8. `tokens_per_positive_answer`
+9. `latency_vs_feedback_correlation`
+
+建议引入 LLM-as-a-Judge,为每条回答提供辅助分数:
+
+- `relevance_score`
+- `correctness_score`
+- `completeness_score`
+- `actionability_score`
+- `tone_score`
+
+这一层只能作为辅助,不应替代真实用户反馈。
+
+---
+
+## 11. 与当前 vikingbot 架构的对应关系
+
+结合当前代码结构,建议的最小落点如下:
+
+1. 在 `vikingbot.bus.events.OutboundMessage` 增加 `response_id` 字段。
+2. 在 `AgentLoop._process_message` 生成最终 `OutboundMessage` 前创建 `response_id`。
+3. 在 `session.add_message("assistant", ...)` 时把 `response_id` 一并写入 JSONL 消息。
+4. 在 OpenAPI `ChatResponse` 与流式最终事件中返回 `response_id`,让客户端具备回传反馈的主键。
+5. 新增 `response_completed` 事件写入点,优先在 agent loop 最终回答落盘后触发。
+6. 在 Langfuse generation / tool span metadata 中写入 `response_id`、`iteration_count`、`tool_count`、`tool_names`。
+
+第二阶段再补:
+
+1. OpenAPI 反馈接口。
+2. channel 侧反馈事件接入。
+3. `feedback_submitted` 事件。
+4. `query_category`、`prompt_version`、`bot_version` 的字段来源。
+
+第三阶段再补:
+
+1. 基于 session 历史的 `response_outcome_evaluated` 后处理。
+2. 更稳健的 `outcome_label` 规则。
+3. 单轮解决、重问、放弃等隐式结果指标消费。
+
+因此,第一阶段无需大改 agent 主循环,但也不只是把“最终回答”和“后续反馈”关联起来,而是要先把“最终回答本身”沉淀成结构化、可关联、可复盘的响应事实。
+
+---
+
+## 12. 风险与注意事项
+
+### 12.1 反馈覆盖率不足
+
+如果用户反馈入口不明显,最终会导致显式反馈覆盖率过低。因此不能只依赖点赞/点踩,必须同时建设隐式成功指标。
+
+### 12.2 不能让高基数字段污染通用指标系统
+
+像 `session_id`、`user_id`、完整错误文本、完整问题文本,不适合直接进入高频指标标签。它们更适合存到事件系统或 trace metadata。
+
+### 12.3 LLM Judge 不能替代真实用户
+
+离线模型评分可以帮助排序和筛样本,但不能当成用户体验的真实代表。
+
+### 12.4 反馈体系要支持版本对比
+
+若没有 `prompt_version`、`bot_version`、`model` 等字段,后续几乎无法评估优化是否有效。
+
+### 12.5 不要把“设想中的字段”误当成“现有能力”
+
+本次复核发现,设计文档最容易偏离现状的地方,不在于指标定义本身,而在于把“应该有的字段”写成了“已经稳定存在的字段”。
+
+后续继续推进时需要遵守两个原则:
+
+1. 文档中的“当前已有能力”必须只写代码里已经稳定产出的字段和事件。
+2. 文档中的“建议字段”必须明确区分为 MVP 必需、第二阶段补齐、第三阶段增强,避免把实现顺序倒置。
+
+---
+
+## 13. 结论
+
+vikingbot 的问答效果反馈观测,不能只停留在 token、trace 和工具调用层面,必须建立从“执行过程”到“最终结果”的完整链路。
+
+本方案建议的主线是:
+
+1. 以 `response_completed` 为核心事实事件。
+2. 先建立响应事实,再叠加显式反馈和隐式结果。
+3. Phase 1 先用 `response_completed_count`、`response_latency_p95`、`tool_success_rate`、`max_iteration_hit_rate`、`no_reply_rate` 保障系统稳定性;Phase 2 之后再升级为效果类北极星指标组合。
+4. 通过 Langfuse trace + 业务事件聚合实现从趋势发现到坏样本回溯的闭环。
+
+最终目标不是“记录更多日志”,而是让团队能够明确回答:
+
+- 哪些回答真的好。
+- 哪些回答正在变差。
+- 为什么变差。
+- 改完以后是否真的变好。
diff --git a/bot/docs/vikingbot-langfuse-local-setup.md b/bot/docs/vikingbot-langfuse-local-setup.md
new file mode 100644
index 000000000..1b6244373
--- /dev/null
+++ b/bot/docs/vikingbot-langfuse-local-setup.md
@@ -0,0 +1,239 @@
+# Vikingbot Langfuse Local Setup
+
+**Author:** OpenViking Team
+**Status:** Draft
+**Date:** 2026-04-29
+
+---
+
+## 1. Purpose
+
+This document describes how to bring up a local Langfuse service for `vikingbot`, connect it through `openviking-server --with-bot`, and verify that traces are arriving.
+
+This guide is for local development and validation. It uses the repository's bundled Docker Compose deployment and the default local credentials baked into that deployment.
+
+---
+
+## 2. What You Get
+
+After setup completes, you should have:
+
+1. A local Langfuse UI at `http://localhost:3000`
+2. A working `bot.langfuse` configuration in `~/.openviking/ov.conf`
+3. `vikingbot` traces tied to your real bot traffic
+4. `response_id` visible in Langfuse metadata for Phase 1 validation
+
+---
+
+## 3. Prerequisites
+
+Before starting, make sure:
+
+1. Docker is installed and the daemon is running
+2. `docker compose` is available, or `docker-compose` is installed
+3. Your local OpenViking environment can start with `openviking-server --with-bot`
+4. Your bot already has a usable model configuration in `ov.conf`
+
+If Docker image pulls fail in your environment, fix Docker daemon network access or proxy settings before continuing.
+
+---
+
+## 4. Deploy Local Langfuse
+
+Run the bundled deployment script:
+
+```bash
+cd bot/deploy/docker
+./deploy_langfuse.sh
+```
+
+The script starts the Langfuse stack from `bot/deploy/docker/langfuse/docker-compose.yml`.
+
+Expected local endpoints and credentials:
+
+- Web UI: `http://localhost:3000`
+- Admin email: `[email protected]`
+- Admin password: `vikingbot-admin-password-2026`
+- Public key: `pk-lf-vikingbot-public-key-2026`
+- Secret key: `sk-lf-vikingbot-secret-key-2026`
+
+If the script succeeds, verify the containers are running:
+
+```bash
+docker compose -f bot/deploy/docker/langfuse/docker-compose.yml ps
+```
+
+If your machine only has `docker-compose`, use:
+
+```bash
+docker-compose -f bot/deploy/docker/langfuse/docker-compose.yml ps
+```
+
+---
+
+## 5. Install Langfuse Python Support
+
+`vikingbot` only sends Langfuse traces when the optional Langfuse dependency is installed.
+
+From the repository root, install it with:
+
+```bash
+uv pip install -e ".[bot,bot-langfuse]"
+```
+
+If your environment already has the main bot dependencies installed, the smaller install also works:
+
+```bash
+uv pip install -e ".[bot-langfuse]"
+```
+
+---
+
+## 6. Configure ov.conf
+
+Add the following to `~/.openviking/ov.conf`:
+
+```json
+{
+ "bot": {
+ "langfuse": {
+ "enabled": true,
+ "secret_key": "sk-lf-vikingbot-secret-key-2026",
+ "public_key": "pk-lf-vikingbot-public-key-2026",
+ "base_url": "http://localhost:3000"
+ }
+ }
+}
+```
+
+Key meaning:
+
+1. `secret_key`: server-side ingestion credential used by `vikingbot`
+2. `public_key`: paired project key stored alongside the secret key
+3. `base_url`: local Langfuse service address
+
+For local repository deployment, keep `base_url` as `http://localhost:3000`.
+
+---
+
+## 7. Restart OpenViking With Bot
+
+After updating `ov.conf`, restart the service path you actually use for validation:
+
+```bash
+openviking-server --with-bot
+```
+
+Expected startup behavior:
+
+1. OpenViking HTTP server listens on `127.0.0.1:1933`
+2. Bot API proxy is exposed at `/bot/v1`
+3. Internal `vikingbot gateway` starts automatically
+
+If Langfuse is enabled correctly, startup logs should indicate Langfuse is enabled with the configured base URL.
+
+---
+
+## 8. Verify End-to-End
+
+### 8.1 Check Bot Health
+
+```bash
+curl -sS http://127.0.0.1:1933/bot/v1/health
+```
+
+Expected result: HTTP 200.
+
+### 8.2 Send a Test Chat Request
+
+```bash
+curl -sS -X POST "http://127.0.0.1:1933/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "langfuse-local-verify-session",
+ "user_id": "langfuse-local-verify-user",
+ "message": "Please reply with one short sentence for Langfuse verification."
+ }'
+```
+
+Expected result:
+
+1. The top-level response contains `response_id`
+2. The final `response` event contains `data.response_id`
+3. Both values match
+
+### 8.3 Check Langfuse UI
+
+Open `http://localhost:3000` and sign in with:
+
+1. Email: `[email protected]`
+2. Password: `vikingbot-admin-password-2026`
+
+Find the trace generated by the test request and inspect the generation metadata.
+
+For Phase 1, verify:
+
+1. The trace exists for your request
+2. Generation metadata includes `response_id`
+3. Tool spans, if any, also include `response_id`
+4. `session_id` and `user_id` are attached to the trace
+
+### 8.4 Cross-Check Session Storage
+
+If you also want to verify persistence, inspect the session JSONL under the bot data directory. By default this is:
+
+```text
+~/.openviking/data/bot/sessions/
+```
+
+The assistant message for the request should include the same `response_id` you saw in the HTTP response and Langfuse.
+
+For the full Phase 1 verification checklist, see:
+
+- `bot/docs/vikingbot-phase1-validation-with-openviking-server.md`
+
+---
+
+## 9. Troubleshooting
+
+### 9.1 Langfuse UI Does Not Open
+
+Check whether the containers are up:
+
+```bash
+docker compose -f bot/deploy/docker/langfuse/docker-compose.yml ps
+```
+
+Then inspect logs:
+
+```bash
+docker compose -f bot/deploy/docker/langfuse/docker-compose.yml logs -f
+```
+
+If you use `docker-compose`, replace the command accordingly.
+
+### 9.2 No Traces Show Up in Langfuse
+
+Check the following first:
+
+1. `uv pip install -e ".[bot-langfuse]"` or `uv pip install -e ".[bot,bot-langfuse]"` has been run in the active environment
+2. `bot.langfuse.enabled` is `true` in `~/.openviking/ov.conf`
+3. `secret_key`, `public_key`, and `base_url` match the local deployment values
+4. `openviking-server --with-bot` was restarted after the config change
+
+### 9.3 Docker Pull Fails
+
+Typical causes are:
+
+1. The Docker daemon cannot reach upstream registries
+2. Your machine needs an outbound proxy for Docker
+3. A company network policy blocks anonymous registry access
+
+Resolve Docker connectivity first, then rerun the deployment script.
+
+---
+
+## 10. Related Docs
+
+- Feedback observability design: `bot/docs/vikingbot-feedback-observability-design.md`
+- Phase 1 validation: `bot/docs/vikingbot-phase1-validation-with-openviking-server.md`
diff --git a/bot/docs/vikingbot-phase1-validation-with-openviking-server.md b/bot/docs/vikingbot-phase1-validation-with-openviking-server.md
new file mode 100644
index 000000000..b0081b268
--- /dev/null
+++ b/bot/docs/vikingbot-phase1-validation-with-openviking-server.md
@@ -0,0 +1,381 @@
+# Vikingbot Phase 1 功能验证指南
+
+**Author:** OpenViking Team
+**Status:** Draft
+**Date:** 2026-04-29
+
+---
+
+## 1. 目的
+
+本文用于验证 Vikingbot feedback observability Phase 1 当前已经落地的能力,验证方式基于 `openviking-server --with-bot` 启动模式。
+
+本次 Phase 1 需要确认的核心点有四个:
+
+1. OpenAPI 返回中存在稳定的 `response_id`
+2. session JSONL 中 assistant message 持久化了 `response_id`
+3. Langfuse 的 generation / tool span metadata 中带有 `response_id`
+4. `response_completed` 没有暴露到用户侧 channel 或 OpenAPI 对外返回中
+
+---
+
+## 2. 适用范围
+
+本文适用于以下启动方式:
+
+```bash
+openviking-server --with-bot
+```
+
+在这种模式下:
+
+- OpenViking Server 对外监听 `1933`
+- 内部会自动启动 `vikingbot gateway`
+- Bot API 会通过 OpenViking Server 代理暴露在 `/bot/v1`
+
+因此本文所有 HTTP 验证请求都走:
+
+- `http://127.0.0.1:1933/bot/v1`
+
+而不是直接访问 `vikingbot gateway` 自身端口。
+
+---
+
+## 3. 前置条件
+
+开始前请确认:
+
+1. OpenViking 可以正常启动,并带上 `--with-bot`
+2. bot 已配置可用模型,能够正常回答问题
+3. 如果要验证 Langfuse,已经安装 `bot-langfuse` 依赖并在 `ov.conf` 中开启 Langfuse
+
+Langfuse 配置示例:
+
+```json
+{
+ "bot": {
+ "langfuse": {
+ "enabled": true,
+ "secret_key": "your-secret-key",
+ "public_key": "your-public-key",
+ "base_url": "http://localhost:3000"
+ }
+ }
+}
+```
+
+如果你修改了配置,需要重启:
+
+```bash
+openviking-server --with-bot
+```
+
+---
+
+## 4. 启动服务
+
+在一个终端中启动:
+
+```bash
+openviking-server --with-bot
+```
+
+预期日志中至少应看到类似内容:
+
+```text
+Bot API proxy enabled, forwarding to http://127.0.0.1:18790
+Starting vikingbot gateway...
+Vikingbot gateway started (PID: ...)
+OpenViking HTTP Server is running on 127.0.0.1:1933
+```
+
+如果这里启动失败,后面的验证都不成立,先解决启动问题。
+
+---
+
+## 5. 验证步骤
+
+### 5.1 健康检查
+
+先确认 Bot API 代理已经可访问:
+
+```bash
+curl -sS http://127.0.0.1:1933/bot/v1/health
+```
+
+预期返回 HTTP 200。
+
+如果这里失败,说明 `--with-bot` 没有生效,或者内部 bot gateway 没有成功启动。
+
+### 5.2 验证非流式返回包含 `response_id`
+
+发送一条最小请求:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:1933/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase1-verify-session",
+ "user_id": "phase1-verify-user",
+ "message": "请简单回复一句:验证 response_id"
+ }'
+```
+
+预期返回中至少包含以下结构:
+
+```json
+{
+ "session_id": "phase1-verify-session",
+ "response_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "message": "...",
+ "events": [
+ {
+ "type": "response",
+ "data": {
+ "content": "...",
+ "response_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ },
+ "timestamp": "..."
+ }
+ ]
+}
+```
+
+重点检查:
+
+1. 顶层有 `response_id`
+2. `events` 中最终 `type == "response"` 的事件里,`data.response_id` 存在
+3. 顶层 `response_id` 与 `events[*].data.response_id` 一致
+
+如果只看到 `message`,但没有 `response_id`,说明 Phase 1 的 API 贯通未生效。
+
+### 5.3 验证流式返回包含 `response_id`
+
+发送一条流式请求:
+
+```bash
+curl -N -X POST "http://127.0.0.1:1933/bot/v1/chat/stream" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase1-verify-stream",
+ "user_id": "phase1-verify-user",
+ "stream": true,
+ "message": "请简单回复一句:验证 stream response_id"
+ }'
+```
+
+预期 SSE 中最终 `response` 事件的数据类似:
+
+```json
+{
+ "type": "response",
+ "data": {
+ "content": "...",
+ "response_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ },
+ "timestamp": "..."
+}
+```
+
+重点检查:
+
+1. 流式最终 `response` 事件带有 `data.response_id`
+2. 没有额外出现 `response_completed` 事件
+
+### 5.4 验证 session JSONL 已写入 `response_id`
+
+Phase 1 当前会把 `response_id` 持久化到 assistant message 中。
+
+默认情况下,bot data 目录是:
+
+```text
+~/.openviking/data/bot
+```
+
+session 目录是:
+
+```text
+~/.openviking/data/bot/sessions
+```
+
+如果你在 `ov.conf` 中设置了 `storage.workspace`,则实际目录为:
+
+```text
+{storage.workspace}/bot/sessions
+```
+
+先搜索刚才的 session:
+
+```bash
+rg "phase1-verify-session|response_id" ~/.openviking/data/bot/sessions
+```
+
+也可以直接列出 session 文件:
+
+```bash
+ls ~/.openviking/data/bot/sessions
+```
+
+找到对应文件后,检查 assistant message,预期类似:
+
+```json
+{
+ "role": "assistant",
+ "content": "...",
+ "timestamp": "...",
+ "response_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
+ "token_usage": {
+ "prompt_tokens": 123,
+ "completion_tokens": 45,
+ "total_tokens": 168
+ }
+}
+```
+
+重点检查:
+
+1. `role == "assistant"` 的消息里有 `response_id`
+2. 该 `response_id` 与 HTTP 返回中的 `response_id` 一致
+
+如果 session 中没有 `response_id`,说明只有 API 层返回了该字段,但持久化链路未生效。
+
+### 5.5 验证 Langfuse generation metadata 包含 `response_id`
+
+这一步要求已经启用 Langfuse。
+
+完成第 5.2 步后,打开 Langfuse UI,找到刚才对应的 trace / generation,检查 metadata。
+
+预期至少包含:
+
+- `response_id`
+- `has_tools`
+- `finish_reason`
+
+重点检查:
+
+1. generation metadata 中存在 `response_id`
+2. Langfuse 中看到的 `response_id` 与 HTTP 返回一致
+
+### 5.6 验证 Langfuse tool span metadata 包含 `response_id`
+
+再发一条更容易触发工具的问题,例如:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:1933/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase1-verify-tool",
+ "user_id": "phase1-verify-user",
+ "message": "请查看当前工作区有哪些文件,并简短总结"
+ }'
+```
+
+然后在 Langfuse 中查看对应 tool span metadata。
+
+预期至少包含:
+
+- `response_id`
+- `duration_ms`
+- `success`
+
+重点检查:
+
+1. tool span metadata 中存在 `response_id`
+2. generation 与 tool span 使用的是同一个 `response_id`
+
+### 5.7 验证 `response_completed` 没有对外暴露
+
+`response_completed` 当前是内部分析事件,不应直接暴露给 OpenAPI 客户端,也不应出现在用户可见 channel 中。
+
+验证方式:
+
+1. 检查第 5.2 和 5.3 步的 HTTP 返回
+2. 确认返回事件中只包含以下类型:
+ - `response`
+ - `reasoning`
+ - `tool_call`
+ - `tool_result`
+3. 确认没有出现:
+ - `response_completed`
+
+如果你同时在使用 CLI chat、Email 或 Mochat 等用户侧 channel,也应确认:
+
+1. 用户只看到正常回答
+2. 没有额外空消息
+3. 没有出现 `response_completed` 或内部 JSON 数据
+
+说明:
+
+- 当前 `response_completed` 是通过内部 bus 发布的分析事件
+- 它不是 OpenAPI 对外契约的一部分
+- 因此本阶段的正确行为是“内部可用、外部不可见”
+
+---
+
+## 6. 通过标准
+
+如果以下条件全部满足,可以认为当前 Phase 1 实现已验证通过:
+
+1. `/bot/v1/chat` 返回顶层 `response_id`
+2. 最终 `response` 事件的 `data.response_id` 存在
+3. session JSONL 的 assistant message 中写入了 `response_id`
+4. Langfuse generation metadata 中存在 `response_id`
+5. 如果触发工具,Langfuse tool span metadata 中也存在 `response_id`
+6. OpenAPI 或用户侧 channel 没有暴露 `response_completed`
+
+---
+
+## 7. 常见问题
+
+### 7.1 `/bot/v1/health` 不通
+
+优先检查:
+
+1. 是否确实使用了 `openviking-server --with-bot`
+2. 启动日志中是否出现 `Bot API proxy enabled`
+3. 内部 bot gateway 是否启动成功
+4. 启动前是否已经有其他进程占用了 `18790`
+
+如果 `18790` 已经被单独运行的 `vikingbot` 或旧进程占用,`openviking-server --with-bot` 会直接拒绝启动,并输出类似错误:
+
+```text
+Error: vikingbot gateway port 18790 is already in use.
+ A previous process is still bound - refusing to start a duplicate.
+```
+
+### 7.2 API 能回答,但没有 `response_id`
+
+优先检查:
+
+1. 当前进程是否已经重启到包含 Phase 1 改动的新代码
+2. 是否命中了 `/bot/v1/chat` 的正常回答路径
+3. 是否不是旧版本服务还在占用端口
+
+### 7.3 session 文件里没有 `response_id`
+
+优先检查:
+
+1. 是否找错了 session 文件目录
+2. 是否配置了非默认 `storage.workspace`
+3. 是否实际看到的是历史旧 session 文件
+
+### 7.4 Langfuse 中看不到 `response_id`
+
+优先检查:
+
+1. 是否已安装 `bot-langfuse` 依赖
+2. `ov.conf` 中 `bot.langfuse.enabled` 是否为 `true`
+3. 是否已经重启服务
+4. 当前请求是否确实打到了启用 Langfuse 的 bot 进程
+
+---
+
+## 8. 最小验证闭环
+
+如果只想用最短时间确认核心链路,建议至少完成以下三步:
+
+1. 调用一次 `/bot/v1/chat` 并确认返回中有 `response_id`
+2. 在 session JSONL 中确认 assistant message 写入了相同的 `response_id`
+3. 确认 OpenAPI 对外返回中没有 `response_completed`
+
+这三步成功,说明 Phase 1 最核心的“response identity + response facts 基础链路”已经基本打通。
diff --git a/bot/docs/vikingbot-phase2-feedback-validation-with-openviking-server.md b/bot/docs/vikingbot-phase2-feedback-validation-with-openviking-server.md
new file mode 100644
index 000000000..63eed660e
--- /dev/null
+++ b/bot/docs/vikingbot-phase2-feedback-validation-with-openviking-server.md
@@ -0,0 +1,376 @@
+# Vikingbot Phase 2 反馈链路验证指南
+
+**Author:** OpenViking Team
+**Status:** Draft
+**Date:** 2026-04-30
+
+---
+
+## 1. 目的
+
+本文用于验证 Vikingbot feedback observability Phase 2 当前已经进入实现状态的显式反馈链路,重点覆盖:
+
+1. `POST /bot/v1/feedback` 可通过 OpenViking Server 代理路径访问
+2. 反馈请求能够按 `response_id` 关联到历史 assistant message
+3. feedback 事件会追加写入 session JSONL 的 `metadata.feedback_events`
+4. bus 会发布 analytics-only 的 `feedback_submitted` 事件
+5. `feedback_submitted` 不会泄漏到用户可见 channel
+
+本文优先采用 `openviking-server --with-bot` 的真实代理路径进行验证,而不是直接把 vikingbot gateway 端口当作主验证入口。
+
+---
+
+## 2. 适用范围
+
+本文适用于以下启动方式:
+
+```bash
+openviking-server --with-bot
+```
+
+在这种模式下:
+
+- OpenViking Server 对外监听业务端口
+- 内部自动启动 vikingbot gateway
+- Bot API 通过 OpenViking Server 代理暴露在 `/bot/v1`
+
+因此本文默认验证地址形如:
+
+- `http://127.0.0.1:<server-port>/bot/v1`
+
+本文不把 `http://127.0.0.1:18790` 视为主验证入口。
+
+---
+
+## 3. 当前已验证结论
+
+截至 2026-04-30,本轮已完成的验证分为三类。
+
+### 3.1 已通过的代码级验证
+
+已通过如下定向测试:
+
+```bash
+./.venv/bin/python -m pytest -o addopts='' bot/tests/test_openapi_auth.py -k feedback
+```
+
+结果:`3 passed`
+
+对应验证点:
+
+1. 成功提交 `/bot/v1/feedback` 时,返回 `accepted=true`
+2. 成功提交后,bus 中出现 `OutboundEventType.FEEDBACK_SUBMITTED`
+3. session JSONL metadata 中出现 `feedback_events[0]`
+4. 对不存在的 `response_id` 提交反馈时,返回 `404 Response not found`
+5. 当 OpenAPIChannel 持有过期 session cache,而 agent loop 已把 assistant response 写入磁盘时,`/feedback` 会重新加载 session,避免误报 `Response not found`
+
+### 3.2 已通过的运行时代理验证
+
+已通过 `openviking-server --with-bot` 验证代理健康检查:
+
+```bash
+curl -sS http://127.0.0.1:30300/bot/v1/health
+```
+
+返回结果表明:
+
+1. OpenViking Server 已成功代理 `/bot/v1`
+2. `--with-bot` 启动路径在当前环境可用
+
+### 3.3 已通过的真实 `/chat -> /feedback` 闭环验证
+
+本轮已经通过 `openviking-server --with-bot --config ov_conf/ov.conf` 完成真实代理路径闭环验证。
+
+前置条件:
+
+```bash
+OPENVIKING_CLI_CONFIG_FILE=ov_conf/ovcli.conf openviking-server --with-bot --config ov_conf/ov.conf
+```
+
+验证结果:
+
+1. `POST /bot/v1/chat` 能返回真实 `response_id`
+2. `POST /bot/v1/feedback` 能通过 OpenViking Server 代理路径成功提交有效反馈
+3. 对不存在的 `response_id` 提交反馈时,OpenViking Server 返回统一错误包裹,其中 message 为 `{"detail":"Response not found"}`
+4. `./data/bot/sessions/cli__default__phase2-feedback-session-3.jsonl` 的 metadata 已实际出现 `feedback_events`
+
+本轮真实验证样例:
+
+1. `/chat` 返回 `response_id=71283018f5e1416ab5f22b11eccd6176`
+2. `/feedback` 返回:
+
+```json
+{
+ "accepted": true,
+ "response_id": "71283018f5e1416ab5f22b11eccd6176",
+ "session_id": "phase2-feedback-session-3",
+ "feedback_type": "thumb_up",
+ "feedback_delay_sec": 9.228,
+ "timestamp": "2026-04-30T11:32:43.355564"
+}
+```
+
+3. session JSONL metadata 首行包含:
+
+```json
+{
+ "metadata": {
+ "feedback_events": [
+ {
+ "response_id": "71283018f5e1416ab5f22b11eccd6176",
+ "feedback_type": "thumb_up",
+ "feedback_text": "helpful",
+ "feedback_delay_sec": 9.228
+ }
+ ]
+ }
+}
+```
+
+---
+
+## 4. 本轮遇到并已解决的问题
+
+### 4.1 全局 CLI 配置污染真实聊天链路
+
+本机全局 `~/.openviking/ovcli.conf` 包含非法字段 `url44`:
+
+```text
+ValueError: Invalid CLI config in /home/yangshunyao/.openviking/ovcli.conf:
+Unknown config field 'ovcli.url44' (did you mean 'ovcli.url'?)
+```
+
+解决方式不是修改用户全局配置,而是在启动 `openviking-server --with-bot` 时显式传入 repo 内的 colocated CLI 配置:
+
+```bash
+OPENVIKING_CLI_CONFIG_FILE=ov_conf/ovcli.conf openviking-server --with-bot --config ov_conf/ov.conf
+```
+
+这样可以保证 bot 子进程以及 bot 内部 OpenViking client 都读取 `ov_conf/ovcli.conf`。
+
+### 4.2 OpenViking Server 代理层最初没有暴露 `/feedback`
+
+虽然 vikingbot gateway 已实现 `POST /bot/v1/feedback`,但 OpenViking Server 的 `openviking/server/routers/bot.py` 起初只代理:
+
+1. `/health`
+2. `/chat`
+3. `/chat/stream`
+
+因此通过 `http://127.0.0.1:30300/bot/v1/feedback` 访问时,只会得到 OpenViking Server 自己的 404。
+
+本轮已补齐代理层 `/feedback` 转发,并增加了对应回归测试。
+
+### 4.3 真实运行时存在 session stale-cache 问题
+
+真实闭环验证中还发现一个仅在运行时更容易触发的问题:
+
+1. OpenAPIChannel 自己维护一个 `SessionManager`
+2. agent loop 也维护自己的 `SessionManager`
+3. 如果一次过早的 `/feedback` 请求先把空 session 缓存进 OpenAPIChannel
+4. 后续 assistant response 虽然已经写入磁盘,OpenAPIChannel 仍可能继续读取自己那份过期内存缓存
+
+这会导致真实路径上错误返回 `Response not found`。
+
+本轮已在 `/feedback` handler 中补充“一次磁盘重载重试”,并增加定向回归测试覆盖该场景。
+
+---
+
+## 5. 推荐验证步骤
+
+### 5.1 启动服务
+
+```bash
+OPENVIKING_CLI_CONFIG_FILE=ov_conf/ovcli.conf openviking-server --with-bot --config ov_conf/ov.conf
+```
+
+预期日志至少包含类似内容:
+
+```text
+Bot API proxy enabled, forwarding to http://127.0.0.1:18790
+Starting vikingbot gateway...
+Vikingbot gateway started (PID: ...)
+OpenViking HTTP Server is running on 127.0.0.1:30300
+```
+
+### 5.2 先做健康检查
+
+```bash
+curl -sS http://127.0.0.1:30300/bot/v1/health
+```
+
+预期返回 HTTP 200。
+
+### 5.3 发送一条真实聊天请求
+
+在使用 repo 内 colocated `ovcli.conf` 启动后,发送:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase2-feedback-session",
+ "user_id": "phase2-feedback-user",
+ "message": "请简单回复一句:用于验证 feedback"
+ }'
+```
+
+预期返回中至少包含:
+
+```json
+{
+ "session_id": "phase2-feedback-session",
+ "response_id": "...",
+ "message": "..."
+}
+```
+
+### 5.4 提交显式反馈
+
+拿到上一步的 `response_id` 后,发送:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/feedback" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase2-feedback-session",
+ "response_id": "<response_id>",
+ "feedback_type": "thumb_up",
+ "feedback_text": "helpful"
+ }'
+```
+
+预期返回类似:
+
+```json
+{
+ "accepted": true,
+ "response_id": "<response_id>",
+ "session_id": "phase2-feedback-session",
+ "feedback_type": "thumb_up",
+ "feedback_delay_sec": 1.234,
+ "timestamp": "..."
+}
+```
+
+### 5.5 验证不存在的 `response_id` 返回 404
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/feedback" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase2-feedback-session",
+ "response_id": "missing-response",
+ "feedback_type": "thumb_down"
+ }'
+```
+
+bot gateway 侧预期返回 HTTP 404,OpenViking Server 当前会包一层统一错误格式,典型返回为:
+
+```json
+{
+ "status": "error",
+ "error": {
+ "code": "NOT_FOUND",
+ "message": "{\"detail\":\"Response not found\"}"
+ }
+}
+```
+
+### 5.6 检查 session JSONL 持久化
+
+默认情况下,session 文件位于:
+
+```text
+{storage.workspace}/bot/sessions
+```
+
+例如当前本地配置对应:
+
+```text
+./data/bot/sessions
+```
+
+找到对应 session 文件后,检查首行 metadata,预期包含:
+
+```json
+{
+ "metadata": {
+ "feedback_events": [
+ {
+ "response_id": "<response_id>",
+ "feedback_type": "thumb_up",
+ "feedback_text": "helpful"
+ }
+ ]
+ }
+}
+```
+
+### 5.7 检查 analytics 事件未泄漏到用户侧 channel
+
+当前实现约束是:
+
+1. bus 按 `channel_key` 分发,而不是按 `event_type` 分发
+2. `feedback_submitted` 仅作为 analytics-only 事件存在
+3. chat / email / mochat 等用户侧 channel 明确忽略该事件
+
+因此应确认:
+
+1. OpenAPI `/feedback` 返回体中没有额外暴露 `feedback_submitted` 事件流
+2. 用户侧 channel 不会把该 analytics 事件发送给终端用户
+
+---
+
+## 6. 排查建议
+
+### 6.1 `/bot/v1/health` 不通
+
+优先检查:
+
+1. 是否确实使用了 `openviking-server --with-bot`
+2. 服务端口是否与 `ov.conf` 中的 `server.port` 一致
+3. `18790` 是否被旧的 vikingbot 进程占用
+
+### 6.2 `/chat` 失败但 `/health` 正常
+
+优先检查 bot 日志文件,例如:
+
+```text
+{storage.workspace}/bot/logs/vikingbot.log
+```
+
+本轮实际遇到的排查示例是:
+
+```text
+Invalid CLI config in /home/yangshunyao/.openviking/ovcli.conf
+Unknown config field 'ovcli.url44'
+```
+
+这类问题会阻塞真实 agent 处理,但不代表 `/feedback` 的接口实现本身有问题。
+
+### 6.3 `/chat` 成功但 `/feedback` 直接返回框架 404
+
+优先检查 OpenViking Server 代理层是否真的暴露了 `/bot/v1/feedback`。
+
+如果日志里根本没有 bot gateway 收到 `POST /bot/v1/feedback`,而 HTTP 返回是通用 404,则通常不是 bot gateway 本身的问题,而是 server proxy 没有转发该路由。
+
+### 6.4 `/feedback` 命中 bot gateway 但仍返回 `Response not found`
+
+优先检查:
+
+1. `response_id` 是否确实来自同一 `session_id` 的 assistant response
+2. feedback 是否在 assistant response 写盘前就过早提交
+3. session 文件首行 metadata 与 assistant message 是否已持久化到同一个 `cli__default__<session>.jsonl`
+
+---
+
+## 7. 结论口径
+
+截至当前,Phase 2 应使用如下口径描述:
+
+1. `/bot/v1/feedback` 已实现
+2. 反馈成功、404 失败以及 stale-cache 重载路径已被定向测试验证
+3. `openviking-server --with-bot` 代理健康路径已验证可用
+4. 完整真实 `/chat -> /feedback` 闭环已在当前环境完成,并确认 session JSONL 会写入 `metadata.feedback_events`
+5. 为了走通首选运行路径,本轮额外补齐了 OpenViking Server 的 `/bot/v1/feedback` 代理路由
+6. `response_outcome_evaluated` 仍然不在 Phase 2 范围内
diff --git a/bot/docs/vikingbot-phase3-outcome-validation-with-openviking-server.md b/bot/docs/vikingbot-phase3-outcome-validation-with-openviking-server.md
new file mode 100644
index 000000000..f5a509f05
--- /dev/null
+++ b/bot/docs/vikingbot-phase3-outcome-validation-with-openviking-server.md
@@ -0,0 +1,437 @@
+# Vikingbot Phase 3 outcome 验证指南
+
+**Author:** OpenViking Team
+**Status:** Draft
+**Date:** 2026-04-30
+
+---
+
+## 1. 目的
+
+本文用于验证 Vikingbot feedback observability Phase 3 当前已落地的 response outcome 链路,重点覆盖:
+
+1. 历史 assistant response 能基于 session 上下文被评估为 `response_outcome_evaluated`
+2. 显式反馈能够驱动 outcome 落为 `positive_feedback` 或 `negative_feedback`
+3. 后续 user turn 能驱动上一条 assistant response 被隐式评估为 `reasked`
+4. session JSONL metadata 中会写入 `response_outcomes`
+5. Langfuse 中可看到与 outcome 对应的 trace event 和 observation score
+6. `response_outcome_evaluated` 作为 analytics-only 事件,不会泄漏到 OpenAPI 对外响应或用户可见 channel
+
+本阶段仍然是最小规则版 outcome evaluator,不是完整的离线 judge 或模型评审链路。
+
+---
+
+## 2. 适用范围
+
+本文适用于以下启动方式:
+
+```bash
+OPENVIKING_CLI_CONFIG_FILE=ov_conf/ovcli.conf openviking-server --with-bot --config ov_conf/ov.conf
+```
+
+在这种模式下:
+
+- OpenViking Server 对外监听业务端口
+- 内部自动启动 vikingbot gateway
+- Bot API 通过 OpenViking Server 代理暴露在 `/bot/v1`
+
+因此本文默认验证地址形如:
+
+- `http://127.0.0.1:30300/bot/v1`
+
+本文优先验证真实代理路径,而不是直接访问 `http://127.0.0.1:18790`。
+
+---
+
+## 3. 当前已验证结论
+
+截至 2026-04-30,本轮已完成的验证分为三类。
+
+### 3.1 已通过的代码级验证
+
+已通过如下定向测试:
+
+```bash
+./.venv/bin/python -m pytest -o addopts='' bot/tests/test_outcome_evaluator.py
+./.venv/bin/python -m pytest -o addopts='' bot/tests/test_agent_loop_outcome.py
+./.venv/bin/python -m pytest -o addopts='' bot/tests/test_langfuse_outcome_metadata.py
+./.venv/bin/python -m pytest -o addopts='' bot/tests/test_openapi_auth.py -k feedback
+```
+
+对应验证点:
+
+1. outcome evaluator 能产出 `resolved`
+2. 显式 `thumb_up` 能产出 `positive_feedback`
+3. 显式 `thumb_down` 能产出 `negative_feedback`
+4. 新 user turn 到来时,上一条 assistant response 能被评估为 `reasked`
+5. outcome 会写入 `session.metadata["response_outcomes"]`
+6. bus 会发布 `OutboundEventType.RESPONSE_OUTCOME_EVALUATED`
+7. Langfuse 能记录 `response_outcome_evaluated` event 与 `response_outcome_label` score
+
+### 3.2 已验证的对外契约约束
+
+当前实现已明确保证:
+
+1. `response_outcome_evaluated` 是 analytics-only 事件
+2. chat / email / mochat 等用户可见 channel 明确忽略该事件
+3. OpenAPI `/chat` 与 `/feedback` 对外返回中不会新增暴露 `response_outcome_evaluated` 事件流
+
+### 3.3 当前建议完成的真实链路闭环
+
+本阶段建议至少完成以下两个真实代理路径闭环:
+
+1. `/chat -> /feedback`,验证 outcome 为 `positive_feedback` 或 `negative_feedback`
+2. `/chat -> follow-up user turn`,验证上一条 assistant response outcome 为 `reasked`
+
+这两个闭环合起来,足以验证当前 Phase 3 最核心的“显式 + 隐式” outcome 评估链路。
+
+---
+
+## 4. 当前规则说明
+
+当前 Phase 3 使用最小规则版 evaluator,规则来源为:
+
+1. session message 历史
+2. `session.metadata["feedback_events"]`
+
+当前规则为:
+
+1. `thumb_down` -> `negative_feedback`
+2. `thumb_up` -> `positive_feedback`
+3. 无显式反馈,但 10 分钟内出现新的 user turn -> `reasked`
+4. 无后续 user turn -> `resolved`
+5. 有 follow-up 且无反馈 -> `follow_up_without_feedback`
+6. 其他情况 -> `follow_up`
+
+当前写入的 outcome payload 至少包含:
+
+- `response_id`
+- `resolved_in_one_turn`
+- `reask_within_10m`
+- `clarification_turns`
+- `follow_up_without_feedback`
+- `outcome_label`
+- `evaluated_at`
+- `evidence`
+
+---
+
+## 5. 推荐验证步骤
+
+### 5.1 启动服务
+
+```bash
+OPENVIKING_CLI_CONFIG_FILE=ov_conf/ovcli.conf openviking-server --with-bot --config ov_conf/ov.conf
+```
+
+预期日志至少包含类似内容:
+
+```text
+Bot API proxy enabled, forwarding to http://127.0.0.1:18790
+Starting vikingbot gateway...
+Vikingbot gateway started (PID: ...)
+OpenViking HTTP Server is running on 127.0.0.1:30300
+```
+
+### 5.2 健康检查
+
+```bash
+curl -sS http://127.0.0.1:30300/bot/v1/health
+```
+
+预期返回 HTTP 200。
+
+### 5.3 场景 A:显式反馈驱动 `positive_feedback`
+
+先发送一条真实聊天请求:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase3-outcome-feedback-session",
+ "user_id": "phase3-outcome-user",
+ "message": "请简单回复一句:用于验证 phase3 positive outcome"
+ }'
+```
+
+预期返回至少包含:
+
+```json
+{
+ "session_id": "phase3-outcome-feedback-session",
+ "response_id": "<response_id>",
+ "message": "..."
+}
+```
+
+拿到 `response_id` 后,提交显式反馈:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/feedback" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase3-outcome-feedback-session",
+ "response_id": "<response_id>",
+ "feedback_type": "thumb_up",
+ "feedback_text": "helpful"
+ }'
+```
+
+预期 `/feedback` 返回类似:
+
+```json
+{
+ "accepted": true,
+ "response_id": "<response_id>",
+ "session_id": "phase3-outcome-feedback-session",
+ "feedback_type": "thumb_up",
+ "feedback_delay_sec": 1.234,
+ "timestamp": "..."
+}
+```
+
+然后检查对应 session JSONL 首行 metadata,预期至少包含:
+
+```json
+{
+ "metadata": {
+ "feedback_events": [
+ {
+ "response_id": "<response_id>",
+ "feedback_type": "thumb_up",
+ "feedback_text": "helpful"
+ }
+ ],
+ "response_outcomes": {
+ "<response_id>": {
+ "response_id": "<response_id>",
+ "outcome_label": "positive_feedback",
+ "resolved_in_one_turn": true,
+ "reask_within_10m": false
+ }
+ }
+ }
+}
+```
+
+如需验证负向路径,可对另一条新 response 提交:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/feedback" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase3-outcome-feedback-session-neg",
+ "response_id": "<another_response_id>",
+ "feedback_type": "thumb_down",
+ "feedback_text": "not helpful"
+ }'
+```
+
+预期 `response_outcomes["<another_response_id>"].outcome_label == "negative_feedback"`。
+
+### 5.4 场景 B:后续 user turn 驱动 `reasked`
+
+先创建一条新的对话响应:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase3-outcome-reask-session",
+ "user_id": "phase3-outcome-user",
+ "message": "请简单回复一句:用于验证 phase3 reasked"
+ }'
+```
+
+记录返回中的 `response_id=<response_id_1>`。
+
+在 10 分钟内,对同一个 `session_id` 再发送一条 follow-up user message:
+
+```bash
+curl -sS -X POST "http://127.0.0.1:30300/bot/v1/chat" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "session_id": "phase3-outcome-reask-session",
+ "user_id": "phase3-outcome-user",
+ "message": "我还是没明白,请再解释一下"
+ }'
+```
+
+当前实现会在处理这条新 user turn 前,先评估上一条 assistant response 的 outcome。
+
+随后检查 session JSONL 首行 metadata,预期至少包含:
+
+```json
+{
+ "metadata": {
+ "response_outcomes": {
+ "<response_id_1>": {
+ "response_id": "<response_id_1>",
+ "outcome_label": "reasked",
+ "reask_within_10m": true,
+ "resolved_in_one_turn": false,
+ "clarification_turns": 1,
+ "follow_up_without_feedback": false
+ }
+ }
+ }
+}
+```
+
+这里的关键点不是第二次 `/chat` 的返回内容,而是上一条 response 的 outcome 是否已被持久化为 `reasked`。
+
+### 5.5 检查 Langfuse trace event 与 observation score
+
+这一步要求已启用 Langfuse。
+
+完成 5.3 或 5.4 后,在 Langfuse UI 中找到对应 trace / generation,重点检查:
+
+1. trace 下新增一个 event:`response_outcome_evaluated`
+2. 对应 generation / observation 下新增一个 score:`response_outcome_label`
+
+原因说明:
+
+1. Phase 3 outcome 往往发生在 `/chat` 请求结束之后
+2. Langfuse v3 中 generation 一旦结束,不适合再事后修改其 metadata
+3. 因此当前实现采用“event + score”记录 outcome,而不是回写已结束 generation 的 metadata
+
+预期至少包含:
+
+- trace event 名称:`response_outcome_evaluated`
+- score 名称:`response_outcome_label`
+- score 值:如 `positive_feedback`、`negative_feedback`、`reasked`
+
+对于显式正向反馈路径,典型 event 预期类似:
+
+```json
+{
+ "name": "response_outcome_evaluated",
+ "metadata": {
+ "response_id": "<response_id>",
+ "outcome_label": "positive_feedback",
+ "response_outcome_evaluated": {
+ "response_id": "<response_id>",
+ "outcome_label": "positive_feedback"
+ }
+ }
+}
+```
+
+对应 score 预期类似:
+
+```json
+{
+ "name": "response_outcome_label",
+ "value": "positive_feedback",
+ "data_type": "CATEGORICAL"
+}
+```
+
+对于 follow-up 路径,典型 event 预期类似:
+
+```json
+{
+ "name": "response_outcome_evaluated",
+ "metadata": {
+ "response_id": "<response_id_1>",
+ "outcome_label": "reasked",
+ "response_outcome_evaluated": {
+ "response_id": "<response_id_1>",
+ "outcome_label": "reasked",
+ "reask_within_10m": true
+ }
+ }
+}
+```
+
+对应 score 预期类似:
+
+```json
+{
+ "name": "response_outcome_label",
+ "value": "reasked",
+ "data_type": "CATEGORICAL"
+}
+```
+
+### 5.6 验证 analytics-only 事件未对外泄漏
+
+当前实现要求:
+
+1. `/bot/v1/chat` 正常返回用户可见回复
+2. `/bot/v1/feedback` 只返回 feedback ack
+3. `response_outcome_evaluated` 不应出现在 OpenAPI 对外响应体中
+4. chat / email / mochat 等用户可见 channel 不应向终端用户输出该 analytics 事件
+
+因此应确认:
+
+1. `/chat` 响应中没有新增 `response_outcome_evaluated` 事件对象
+2. `/feedback` 响应中只有 `accepted`、`response_id`、`session_id`、`feedback_type`、`feedback_delay_sec`、`timestamp` 等反馈确认字段
+3. 终端用户只能看到正常 assistant reply,而不会看到内部 outcome JSON
+
+---
+
+## 6. 通过标准
+
+如果以下条件全部满足,可以认为当前 Phase 3 最小实现验证通过:
+
+1. `/bot/v1/chat` 仍能稳定返回 `response_id`
+2. 对某条 response 提交 `thumb_up` 后,session JSONL `metadata.response_outcomes[response_id].outcome_label == "positive_feedback"`
+3. 对某条 response 提交 `thumb_down` 后,session JSONL `metadata.response_outcomes[response_id].outcome_label == "negative_feedback"`
+4. 在同一 session 中追加 follow-up user turn 后,上一条 response 的 outcome 被写为 `reasked`
+5. Langfuse trace 中可看到 `response_outcome_evaluated` event,且 observation 上可看到 `response_outcome_label` score
+6. OpenAPI 对外响应和用户可见 channel 中没有泄漏 `response_outcome_evaluated`
+
+---
+
+## 7. 排查建议
+
+### 7.1 `/bot/v1/health` 不通
+
+优先检查:
+
+1. 是否确实使用了 `openviking-server --with-bot`
+2. 服务端口是否与 `ov_conf/ov.conf` 中配置一致
+3. `18790` 是否被旧的 vikingbot 进程占用
+
+### 7.2 `/feedback` 成功,但 session 里没有 `response_outcomes`
+
+优先检查:
+
+1. 当前 `response_id` 是否确实来自同一 `session_id`
+2. session 首行 metadata 中是否已经写入 `feedback_events`
+3. 当前运行代码是否已包含 Phase 3 outcome evaluator 接入
+
+### 7.3 follow-up 后没有看到 `reasked`
+
+优先检查:
+
+1. follow-up 是否发送到了同一个 `session_id`
+2. 第一条 assistant message 是否已持久化且带有 `response_id`
+3. follow-up 与上一条 assistant response 的间隔是否明显超过 10 分钟
+4. 该 response 是否已经先被显式 `thumb_up` 或 `thumb_down` 覆盖为更强信号
+
+### 7.4 Langfuse 中看不到 outcome 记录
+
+优先检查:
+
+1. 是否已安装并启用 `bot-langfuse`
+2. `ov_conf/ov.conf` 中 Langfuse 配置是否生效
+3. 原始 generation metadata 中是否已有 `response_id`
+4. 是否在 trace 视图中查看了 event,而不是只盯着 generation metadata
+5. 是否在 observation / generation 详情中查看了 score
+6. outcome 是否已经成功写入 session JSONL 的 `metadata.response_outcomes`
+
+---
+
+## 8. 结论口径
+
+截至当前,Phase 3 应使用如下口径描述:
+
+1. `response_outcome_evaluated` 的最小规则版实现已落地
+2. outcome 可由显式 feedback 或后续 user turn 隐式推导
+3. 评估结果会写入 session JSONL 的 `metadata.response_outcomes`
+4. Langfuse 当前通过 trace event 和 observation score 记录 outcome,而不是事后回写已结束 generation 的 metadata
+5. 该事件目前仍是 analytics-only,不属于对外用户契约
+6. 当前实现可支撑后续更复杂的 judge / 打分链路,但当前版本尚不是完整评审系统
diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.py
new file mode 100644
index 000000000..c446eb4ed
--- /dev/null
+++ b/bot/tests/test_agent_loop_outcome.py
@@ -0,0 +1,122 @@
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+from vikingbot.agent.loop import AgentLoop
+from vikingbot.bus.events import InboundMessage, OutboundEventType
+from vikingbot.bus.queue import MessageBus
+from vikingbot.config.schema import Config, SessionKey
+from vikingbot.heartbeat.service import HEARTBEAT_METADATA_KEY
+from vikingbot.providers.base import LLMProvider
+
+
+class _FakeProvider(LLMProvider):
+ async def chat(self, *args, **kwargs): # pragma: no cover - should not be called
+ raise AssertionError("provider.chat should not be called in no-reply outcome test")
+
+ def get_default_model(self) -> str:
+ return "fake-model"
+
+
+class _FakeSubagentManager:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+
+async def test_agent_loop_evaluates_previous_response_outcome_before_new_user_turn(
+ temp_dir: Path, monkeypatch
+):
+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)
+ monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)
+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)
+
+ bus = MessageBus()
+ config = Config(storage_workspace=str(temp_dir))
+ loop = AgentLoop(
+ bus=bus,
+ provider=_FakeProvider(),
+ workspace=temp_dir / "workspace",
+ config=config,
+ )
+
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")
+ session = loop.sessions.get_or_create(session_key, skip_heartbeat=True)
+ session.add_message(
+ "assistant",
+ "hello",
+ sender_id="user-1",
+ response_id="resp-123",
+ timestamp="2026-04-30T00:00:00",
+ )
+ await loop.sessions.save(session)
+
+ response = await loop._process_message(
+ InboundMessage(
+ session_key=session_key,
+ sender_id="user-1",
+ content="that did not help",
+ need_reply=False,
+ timestamp=datetime.fromisoformat("2026-04-30T00:05:00"),
+ )
+ )
+
+ assert response is not None
+ assert response.event_type == OutboundEventType.NO_REPLY
+ assert bus.outbound_size == 1
+
+ outcome_event = await bus.consume_outbound()
+ assert outcome_event.event_type == OutboundEventType.RESPONSE_OUTCOME_EVALUATED
+ assert outcome_event.response_id == "resp-123"
+ assert outcome_event.metadata["response_outcome_evaluated"]["outcome_label"] == "reasked"
+ assert outcome_event.metadata["response_outcome_evaluated"]["reask_within_10m"] is True
+
+ persisted_session = loop.sessions.get_or_create(session_key, skip_heartbeat=True)
+ assert persisted_session.metadata["response_outcomes"]["resp-123"]["outcome_label"] == "reasked"
+
+
+async def test_agent_loop_ignores_heartbeat_when_evaluating_previous_response_outcome(
+ temp_dir: Path, monkeypatch
+):
+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)
+ monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)
+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)
+
+ bus = MessageBus()
+ config = Config(storage_workspace=str(temp_dir))
+ loop = AgentLoop(
+ bus=bus,
+ provider=_FakeProvider(),
+ workspace=temp_dir / "workspace",
+ config=config,
+ )
+
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")
+ session = loop.sessions.get_or_create(session_key, skip_heartbeat=False)
+ session.add_message(
+ "assistant",
+ "hello",
+ sender_id="user-1",
+ response_id="resp-123",
+ timestamp="2026-04-30T00:00:00",
+ )
+ await loop.sessions.save(session)
+
+ response = await loop._process_message(
+ InboundMessage(
+ session_key=session_key,
+ sender_id="user-1",
+ content="Read HEARTBEAT.md if needed",
+ need_reply=False,
+ timestamp=datetime.fromisoformat("2026-04-30T00:05:00"),
+ metadata={HEARTBEAT_METADATA_KEY: True},
+ )
+ )
+
+ assert response is not None
+ assert response.event_type == OutboundEventType.NO_REPLY
+ assert bus.outbound_size == 0
+
+ persisted_session = loop.sessions.get_or_create(session_key, skip_heartbeat=False)
+ assert "response_outcomes" not in persisted_session.metadata
diff --git a/bot/tests/test_langfuse_outcome_metadata.py b/bot/tests/test_langfuse_outcome_metadata.py
new file mode 100644
index 000000000..287bf3768
--- /dev/null
+++ b/bot/tests/test_langfuse_outcome_metadata.py
@@ -0,0 +1,105 @@
+from vikingbot.integrations.langfuse import LangfuseClient
+
+
+class _FakeGeneration:
+ def __init__(self, metadata=None):
+ self.metadata = metadata or {}
+ self.trace_id = "trace-123"
+ self.id = "obs-123"
+
+ def update(self, **kwargs):
+ if "metadata" in kwargs:
+ self.metadata = kwargs["metadata"]
+
+
+class _FakeGenerationWithoutMetadata:
+ def __init__(self):
+ self.updated_metadata = None
+ self.trace_id = "trace-456"
+ self.id = "obs-456"
+
+ def update(self, **kwargs):
+ self.updated_metadata = kwargs.get("metadata")
+
+
+class _FakeClient:
+ def __init__(self):
+ self.flush_calls = 0
+ self.events = []
+ self.scores = []
+
+ def flush(self):
+ self.flush_calls += 1
+
+ def create_event(self, **kwargs):
+ self.events.append(kwargs)
+
+ def create_score(self, **kwargs):
+ self.scores.append(kwargs)
+
+
+def test_langfuse_client_creates_event_and_score_for_outcome():
+ client = LangfuseClient.__new__(LangfuseClient)
+ client.enabled = True
+ client._client = _FakeClient()
+ client._observations_by_response_id = {}
+ client._metadata_by_response_id = {}
+ client._trace_context_by_response_id = {}
+
+ generation = _FakeGeneration(metadata={"response_id": "resp-123"})
+ client.register_generation("resp-123", generation, metadata={"response_id": "resp-123"})
+ client.update_generation_metadata("resp-123", {"finish_reason": "stop"})
+ client.update_response_outcome(
+ "resp-123",
+ "positive_feedback",
+ {"response_id": "resp-123", "outcome_label": "positive_feedback"},
+ )
+
+ assert client._trace_context_by_response_id["resp-123"]["trace_id"] == "trace-123"
+ assert client._trace_context_by_response_id["resp-123"]["observation_id"] == "obs-123"
+ assert client._client.events[0]["name"] == "response_outcome_evaluated"
+ assert client._client.events[0]["trace_context"] == {"trace_id": "trace-123"}
+ assert client._client.events[0]["metadata"]["response_id"] == "resp-123"
+ assert client._client.events[0]["metadata"]["finish_reason"] == "stop"
+ assert client._client.events[0]["metadata"]["outcome_label"] == "positive_feedback"
+ assert client._client.scores[0]["name"] == "response_outcome_label"
+ assert client._client.scores[0]["value"] == "positive_feedback"
+ assert client._client.scores[0]["trace_id"] == "trace-123"
+ assert client._client.scores[0]["observation_id"] == "obs-123"
+ assert client._client.scores[0]["metadata"]["response_id"] == "resp-123"
+ assert client._client.flush_calls == 1
+
+
+def test_langfuse_client_records_outcome_without_generation_metadata_attribute():
+ client = LangfuseClient.__new__(LangfuseClient)
+ client.enabled = True
+ client._client = _FakeClient()
+ client._observations_by_response_id = {}
+ client._metadata_by_response_id = {}
+ client._trace_context_by_response_id = {}
+
+ generation = _FakeGenerationWithoutMetadata()
+ client.register_generation(
+ "resp-456",
+ generation,
+ metadata={"response_id": "resp-456", "has_tools": False},
+ )
+ client.update_generation_metadata("resp-456", {"finish_reason": "stop"})
+ client.update_response_outcome(
+ "resp-456",
+ "reasked",
+ {
+ "response_id": "resp-456",
+ "outcome_label": "reasked",
+ "reask_within_10m": True,
+ },
+ )
+
+ assert client._client.events[0]["trace_context"] == {"trace_id": "trace-456"}
+ assert client._client.events[0]["metadata"]["response_id"] == "resp-456"
+ assert client._client.events[0]["metadata"]["has_tools"] is False
+ assert client._client.events[0]["metadata"]["finish_reason"] == "stop"
+ assert client._client.events[0]["metadata"]["outcome_label"] == "reasked"
+ assert client._client.scores[0]["observation_id"] == "obs-456"
+ assert client._client.scores[0]["metadata"]["reask_within_10m"] is True
+ assert client._client.flush_calls == 1
diff --git a/bot/tests/test_openapi_auth.py b/bot/tests/test_openapi_auth.py
index 5fe659010..4273b3592 100644
--- a/bot/tests/test_openapi_auth.py
+++ b/bot/tests/test_openapi_auth.py
@@ -2,6 +2,8 @@
# SPDX-License-Identifier: AGPL-3.0
"""Regression tests for OpenAPI HTTP auth requirements."""
+import asyncio
+import json
import tempfile
from pathlib import Path
from types import SimpleNamespace
@@ -9,10 +11,11 @@ from types import SimpleNamespace
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from vikingbot.bus.events import OutboundEventType, OutboundMessage
from vikingbot.bus.queue import MessageBus
-from vikingbot.channels.openapi import OpenAPIChannel, OpenAPIChannelConfig
+from vikingbot.channels.openapi import OpenAPIChannel, OpenAPIChannelConfig, PendingResponse
from vikingbot.channels.openapi_models import ChatResponse
-from vikingbot.config.schema import BotChannelConfig
+from vikingbot.config.schema import BotChannelConfig, SessionKey
@pytest.fixture
@@ -45,12 +48,15 @@ class TestOpenAPIAuth:
assert response.status_code == 200
- def test_chat_accepts_requests_when_api_key_not_configured(self, message_bus, temp_workspace, monkeypatch):
+ def test_chat_accepts_requests_when_api_key_not_configured(
+ self, message_bus, temp_workspace, monkeypatch
+ ):
channel = OpenAPIChannel(
OpenAPIChannelConfig(),
message_bus,
workspace_path=temp_workspace,
)
+
async def fake_handle_chat(request):
return ChatResponse(
session_id=request.session_id or "default", message="ok", events=None
@@ -105,7 +111,10 @@ class TestOpenAPIAuth:
response = client.post("/bot/v1/chat", json={"message": "hello"})
assert response.status_code == 503
- assert response.json()["detail"] == "OpenAPI gateway token is required when host is non-localhost"
+ assert (
+ response.json()["detail"]
+ == "OpenAPI gateway token is required when host is non-localhost"
+ )
def test_bot_channel_accepts_requests_without_channel_api_key(
self, message_bus, temp_workspace, monkeypatch
@@ -166,3 +175,214 @@ class TestOpenAPIAuth:
)
assert authorized.status_code == 200
assert authorized.json()["message"] == "ok:alpha"
+
+ @pytest.mark.asyncio
+ async def test_send_tracks_response_id_in_final_openapi_response(
+ self, message_bus, temp_workspace
+ ):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ pending = PendingResponse()
+ channel._pending["session-1"] = pending
+
+ await channel.send(
+ OutboundMessage(
+ session_key=SessionKey(type="cli", channel_id="default", chat_id="session-1"),
+ content="hello",
+ event_type=OutboundEventType.RESPONSE,
+ response_id="resp-123",
+ metadata={"relevant_memories": "memory"},
+ )
+ )
+
+ assert pending.final_content == "hello"
+ assert pending.response_id == "resp-123"
+ assert pending.relevant_memories == "memory"
+ assert len(pending.events) == 1
+ assert pending.events[0]["type"] == "response"
+ assert pending.events[0]["data"] == {"content": "hello", "response_id": "resp-123"}
+
+ def test_feedback_persists_event_and_emits_feedback_submitted(
+ self, message_bus, temp_workspace
+ ):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")
+ session = channel._session_manager.get_or_create(session_key)
+ session.add_message(
+ "assistant",
+ "hello",
+ sender_id="user-1",
+ response_id="resp-123",
+ timestamp="2026-04-30T00:00:00",
+ )
+ asyncio.run(channel._session_manager.save(session))
+
+ client = _make_client(channel)
+ response = client.post(
+ "/bot/v1/feedback",
+ json={
+ "session_id": "session-1",
+ "response_id": "resp-123",
+ "feedback_type": "thumb_up",
+ "feedback_text": "helpful",
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["accepted"] is True
+ assert body["response_id"] == "resp-123"
+ assert body["session_id"] == "session-1"
+ assert body["feedback_type"] == "thumb_up"
+ assert message_bus.outbound_size == 2
+
+ first_outbound = asyncio.run(message_bus.consume_outbound())
+ second_outbound = asyncio.run(message_bus.consume_outbound())
+ assert first_outbound.event_type == OutboundEventType.RESPONSE_OUTCOME_EVALUATED
+ assert first_outbound.response_id == "resp-123"
+ assert (
+ first_outbound.metadata["response_outcome_evaluated"]["outcome_label"]
+ == "positive_feedback"
+ )
+ assert second_outbound.event_type == OutboundEventType.FEEDBACK_SUBMITTED
+ assert second_outbound.response_id == "resp-123"
+ assert second_outbound.metadata["feedback_submitted"]["feedback_type"] == "thumb_up"
+ assert second_outbound.metadata["feedback_submitted"]["feedback_text"] == "helpful"
+
+ session_path = temp_workspace / "sessions" / "cli__default__session-1.jsonl"
+ lines = session_path.read_text(encoding="utf-8").splitlines()
+ metadata = json.loads(lines[0])
+ assert metadata["metadata"]["feedback_events"][0]["response_id"] == "resp-123"
+ assert metadata["metadata"]["feedback_events"][0]["feedback_type"] == "thumb_up"
+ assert (
+ metadata["metadata"]["response_outcomes"]["resp-123"]["outcome_label"]
+ == "positive_feedback"
+ )
+
+ def test_feedback_requires_existing_response(self, message_bus, temp_workspace):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ client = _make_client(channel)
+
+ response = client.post(
+ "/bot/v1/feedback",
+ json={
+ "session_id": "missing-session",
+ "response_id": "missing-response",
+ "feedback_type": "thumb_down",
+ },
+ )
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "Response not found"
+
+ def test_feedback_reloads_session_after_stale_cached_miss(self, message_bus, temp_workspace):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")
+
+ stale_session = channel._session_manager.get_or_create(session_key)
+ assert stale_session.messages == []
+
+ writer_manager = channel._session_manager.__class__(channel._session_manager.bot_data_path)
+ writer_session = writer_manager.get_or_create(session_key)
+ writer_session.add_message(
+ "assistant",
+ "hello",
+ sender_id="user-1",
+ response_id="resp-123",
+ timestamp="2026-04-30T00:00:00",
+ )
+ asyncio.run(writer_manager.save(writer_session))
+
+ client = _make_client(channel)
+ response = client.post(
+ "/bot/v1/feedback",
+ json={
+ "session_id": "session-1",
+ "response_id": "resp-123",
+ "feedback_type": "thumb_up",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["accepted"] is True
+
+ def test_feedback_preserves_messages_written_after_stale_cache_read(
+ self, message_bus, temp_workspace
+ ):
+ channel = OpenAPIChannel(
+ OpenAPIChannelConfig(),
+ message_bus,
+ workspace_path=temp_workspace,
+ )
+ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-1")
+
+ stale_session = channel._session_manager.get_or_create(session_key)
+ stale_session.add_message(
+ "assistant",
+ "hello",
+ sender_id="user-1",
+ response_id="resp-123",
+ timestamp="2026-04-30T00:00:00",
+ )
+ asyncio.run(channel._session_manager.save(stale_session))
+
+ writer_manager = channel._session_manager.__class__(channel._session_manager.bot_data_path)
+ writer_session = writer_manager.get_or_create(session_key)
+ writer_session.add_message(
+ "user",
+ "follow up",
+ sender_id="user-1",
+ timestamp="2026-04-30T00:01:00",
+ )
+ writer_session.add_message(
+ "assistant",
+ "new reply",
+ sender_id="user-1",
+ response_id="resp-456",
+ timestamp="2026-04-30T00:02:00",
+ )
+ asyncio.run(writer_manager.save(writer_session))
+
+ stale_session.metadata["local_only"] = True
+
+ client = _make_client(channel)
+ response = client.post(
+ "/bot/v1/feedback",
+ json={
+ "session_id": "session-1",
+ "response_id": "resp-123",
+ "feedback_type": "thumb_up",
+ },
+ )
+
+ assert response.status_code == 200
+
+ session_path = temp_workspace / "sessions" / "cli__default__session-1.jsonl"
+ lines = session_path.read_text(encoding="utf-8").splitlines()
+ metadata = json.loads(lines[0])
+ messages = [json.loads(line) for line in lines[1:]]
+
+ assert metadata["metadata"]["feedback_events"][0]["response_id"] == "resp-123"
+ assert "local_only" not in metadata["metadata"]
+ assert [
+ message.get("response_id") for message in messages if message["role"] == "assistant"
+ ] == [
+ "resp-123",
+ "resp-456",
+ ]
+ assert messages[-1]["content"] == "new reply"
diff --git a/bot/tests/test_outcome_evaluator.py b/bot/tests/test_outcome_evaluator.py
new file mode 100644
index 000000000..2cff446d0
--- /dev/null
+++ b/bot/tests/test_outcome_evaluator.py
@@ -0,0 +1,138 @@
+from datetime import datetime
+
+from vikingbot.observability.outcome import evaluate_response_outcome
+
+
+def test_evaluate_response_outcome_marks_resolved_without_follow_up():
+ evaluation = evaluate_response_outcome(
+ [
+ {
+ "role": "assistant",
+ "content": "hello",
+ "response_id": "resp-1",
+ "timestamp": "2026-04-30T00:00:00",
+ }
+ ],
+ "resp-1",
+ now=datetime.fromisoformat("2026-04-30T00:05:00"),
+ )
+
+ assert evaluation is not None
+ assert evaluation.outcome_label == "resolved"
+ assert evaluation.resolved_in_one_turn is True
+ assert evaluation.reask_within_10m is False
+ assert evaluation.clarification_turns == 0
+ assert evaluation.follow_up_without_feedback is False
+
+
+def test_evaluate_response_outcome_prefers_positive_feedback():
+ evaluation = evaluate_response_outcome(
+ [
+ {
+ "role": "assistant",
+ "content": "hello",
+ "response_id": "resp-1",
+ "timestamp": "2026-04-30T00:00:00",
+ },
+ {
+ "role": "user",
+ "content": "thanks",
+ "timestamp": "2026-04-30T00:01:00",
+ },
+ ],
+ "resp-1",
+ feedback_events=[
+ {
+ "response_id": "resp-1",
+ "feedback_type": "thumb_up",
+ }
+ ],
+ now=datetime.fromisoformat("2026-04-30T00:02:00"),
+ )
+
+ assert evaluation is not None
+ assert evaluation.outcome_label == "positive_feedback"
+ assert evaluation.resolved_in_one_turn is True
+ assert evaluation.reask_within_10m is False
+ assert evaluation.clarification_turns == 0
+ assert evaluation.follow_up_without_feedback is False
+
+
+def test_evaluate_response_outcome_marks_negative_feedback():
+ evaluation = evaluate_response_outcome(
+ [
+ {
+ "role": "assistant",
+ "content": "hello",
+ "response_id": "resp-1",
+ "timestamp": "2026-04-30T00:00:00",
+ }
+ ],
+ "resp-1",
+ feedback_events=[
+ {
+ "response_id": "resp-1",
+ "feedback_type": "thumb_down",
+ }
+ ],
+ now=datetime.fromisoformat("2026-04-30T00:02:00"),
+ )
+
+ assert evaluation is not None
+ assert evaluation.outcome_label == "negative_feedback"
+ assert evaluation.resolved_in_one_turn is False
+ assert evaluation.follow_up_without_feedback is False
+
+
+def test_evaluate_response_outcome_marks_reasked_within_window():
+ evaluation = evaluate_response_outcome(
+ [
+ {
+ "role": "assistant",
+ "content": "hello",
+ "response_id": "resp-1",
+ "timestamp": "2026-04-30T00:00:00",
+ },
+ {
+ "role": "user",
+ "content": "that did not help",
+ "timestamp": "2026-04-30T00:05:00",
+ },
+ ],
+ "resp-1",
+ now=datetime.fromisoformat("2026-04-30T00:06:00"),
+ )
+
+ assert evaluation is not None
+ assert evaluation.outcome_label == "reasked"
+ assert evaluation.resolved_in_one_turn is False
+ assert evaluation.reask_within_10m is True
+ assert evaluation.clarification_turns == 1
+ assert evaluation.follow_up_without_feedback is False
+
+
+def test_evaluate_response_outcome_marks_follow_up_without_feedback():
+ evaluation = evaluate_response_outcome(
+ [
+ {
+ "role": "assistant",
+ "content": "hello",
+ "response_id": "resp-1",
+ "timestamp": "2026-04-30T00:00:00",
+ },
+ {
+ "role": "user",
+ "content": "another question later",
+ "timestamp": "2026-04-30T00:20:00",
+ },
+ ],
+ "resp-1",
+ now=datetime.fromisoformat("2026-04-30T00:21:00"),
+ )
+
+ assert evaluation is not None
+ assert evaluation.outcome_label == "follow_up_without_feedback"
+ assert evaluation.resolved_in_one_turn is False
+ assert evaluation.reask_within_10m is False
+ assert evaluation.clarification_turns == 1
+ assert evaluation.follow_up_without_feedback is True
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index fbef7a38d..ab6d05324 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -6,6 +6,7 @@ import asyncio
import json
import re
import time
+import uuid
from contextlib import AsyncExitStack
from pathlib import Path
from typing import TYPE_CHECKING
@@ -24,11 +25,13 @@ from vikingbot.config.schema import BotMode, Config, SessionKey
from vikingbot.heartbeat.service import HEARTBEAT_METADATA_KEY, is_heartbeat_noop_response
from vikingbot.hooks import HookContext
from vikingbot.hooks.manager import hook_manager
+from vikingbot.integrations.langfuse import LangfuseClient
+from vikingbot.observability.outcome import evaluate_response_outcome, should_update_outcome
from vikingbot.providers.base import LLMProvider
from vikingbot.sandbox import SandboxManager
-from vikingbot.session.manager import SessionManager
+from vikingbot.session.manager import Session, SessionManager
from vikingbot.utils.helpers import cal_str_tokens
-from vikingbot.utils.tracing import trace
+from vikingbot.utils.tracing import set_response_id, trace
if TYPE_CHECKING:
from vikingbot.config.schema import ExecToolConfig
@@ -557,11 +560,13 @@ class AgentLoop:
# Debug mode handling
if self.config.mode == BotMode.DEBUG:
# In debug mode, only record message to session, no processing or reply
+ await self._evaluate_previous_response_outcome(session, msg)
session.add_message("user", msg.content, sender_id=msg.sender_id)
await self.sessions.save(session)
return None
if not msg.need_reply:
+ await self._evaluate_previous_response_outcome(session, msg)
session.add_message("user", msg.content, sender_id=msg.sender_id)
await self.sessions.save(session)
return OutboundMessage(
@@ -581,6 +586,8 @@ class AgentLoop:
# Run consolidation in background
await self._safe_consolidate_memory(session_clone, archive_all=False)
+ await self._evaluate_previous_response_outcome(session, msg)
+
if self.sandbox_manager:
message_workspace = self.sandbox_manager.get_workspace_path(session_key)
else:
@@ -611,14 +618,22 @@ class AgentLoop:
relevant_memories = message_context.latest_relevant_memories
# logger.info(f"New messages: {json.dumps(messages, indent=4)}")
- # Run agent loop
- final_content, final_reasoning_content, tools_used, token_usage, iteration = await self._run_agent_loop(
- messages=messages,
- session_key=session_key,
- publish_events=True,
- sender_id=msg.sender_id,
- ov_tools_enable=ov_tools_enable,
- )
+ # Run agent loop within a stable response identity for tracing/tool spans.
+ response_id = uuid.uuid4().hex
+ with set_response_id(response_id):
+ (
+ final_content,
+ final_reasoning_content,
+ tools_used,
+ token_usage,
+ iteration,
+ ) = await self._run_agent_loop(
+ messages=messages,
+ session_key=session_key,
+ publish_events=True,
+ sender_id=msg.sender_id,
+ ov_tools_enable=ov_tools_enable,
+ )
# Log response preview
preview = final_content[:300] + "..." if len(final_content) > 300 else final_content
@@ -630,6 +645,7 @@ class AgentLoop:
session.add_message(
"assistant",
final_content,
+ response_id=response_id,
tools_used=tools_used if tools_used else None,
token_usage=token_usage,
sender_id=msg.sender_id,
@@ -645,10 +661,31 @@ class AgentLoop:
response_metadata = dict(msg.metadata or {})
if relevant_memories is not None:
response_metadata["relevant_memories"] = relevant_memories
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ session_key=msg.session_key,
+ content="",
+ event_type=OutboundEventType.RESPONSE_COMPLETED,
+ response_id=response_id,
+ metadata={
+ "response_completed": {
+ "response_id": response_id,
+ "session_id": session_key.safe_name(),
+ "sender_id": msg.sender_id,
+ "content": final_content,
+ "token_usage": token_usage,
+ "time_cost": time_cost,
+ "iteration": iteration,
+ "tools_used_names": tools_used_names,
+ }
+ },
+ )
+ )
return OutboundMessage(
session_key=msg.session_key,
content=final_content,
metadata=response_metadata,
+ response_id=response_id,
token_usage=token_usage,
time_cost=time_cost,
iteration=iteration,
@@ -662,6 +699,57 @@ class AgentLoop:
except asyncio.CancelledError:
pass
+ async def _evaluate_previous_response_outcome(
+ self, session: Session, msg: InboundMessage
+ ) -> None:
+ """Evaluate the latest assistant response before appending a new user turn."""
+ if msg.metadata.get(HEARTBEAT_METADATA_KEY):
+ return
+
+ last_response = None
+ for message in reversed(session.messages):
+ if message.get("role") == "assistant" and message.get("response_id"):
+ last_response = message
+ break
+ if message.get("role") == "user":
+ break
+
+ if last_response is None:
+ return
+
+ response_id = last_response["response_id"]
+ evaluation = evaluate_response_outcome(
+ session.messages
+ + [{"role": "user", "content": msg.content, "timestamp": msg.timestamp.isoformat()}],
+ response_id,
+ feedback_events=session.metadata.get("feedback_events", []),
+ now=msg.timestamp,
+ )
+ if evaluation is None:
+ return
+
+ outcomes = session.metadata.setdefault("response_outcomes", {})
+ previous = outcomes.get(response_id)
+ if not should_update_outcome(previous, evaluation):
+ return
+
+ outcome_payload = evaluation.to_dict()
+ outcomes[response_id] = outcome_payload
+ LangfuseClient.get_instance().update_response_outcome(
+ response_id,
+ outcome_payload["outcome_label"],
+ outcome_payload,
+ )
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ session_key=msg.session_key,
+ content="",
+ event_type=OutboundEventType.RESPONSE_OUTCOME_EVALUATED,
+ response_id=response_id,
+ metadata={"response_outcome_evaluated": outcome_payload},
+ )
+ )
+
def _get_channel_config(self, session_key: SessionKey):
"""Get channel config for a session key.
@@ -714,7 +802,13 @@ class AgentLoop:
)
# Run agent loop (no events published)
- final_content, final_reasoning_content, tools_used, token_usage, iteration = await self._run_agent_loop(
+ (
+ final_content,
+ final_reasoning_content,
+ tools_used,
+ token_usage,
+ iteration,
+ ) = await self._run_agent_loop(
messages=messages,
session_key=msg.session_key,
publish_events=False,
diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.py
index 0f5235bd1..2d6d49e55 100644
--- a/bot/vikingbot/agent/memory.py
+++ b/bot/vikingbot/agent/memory.py
@@ -1,10 +1,11 @@
"""Memory system for persistent agent memory."""
import asyncio
+import time
from pathlib import Path
from typing import Any
+
from loguru import logger
-import time
from vikingbot.config.loader import load_config
from vikingbot.openviking_mount.ov_server import VikingClient
@@ -53,7 +54,6 @@ class MemoryStore:
for idx, memory in enumerate(filtered_memories, start=1):
uri = getattr(memory, "uri", "")
- abstract = getattr(memory, "abstract", "")
score = getattr(memory, "score", 0.0)
# First, try to build full memory with content
@@ -127,9 +127,9 @@ class MemoryStore:
config = load_config().ov_server
admin_user_id = config.admin_user_id
user_id = sender_id
- logger.info(f'workspace_id={workspace_id}')
- logger.info(f'user_id={user_id}')
- logger.info(f'admin_user_id={admin_user_id}')
+ logger.info(f"workspace_id={workspace_id}")
+ logger.info(f"user_id={user_id}")
+ logger.info(f"admin_user_id={admin_user_id}")
client = await VikingClient.create(agent_id=workspace_id)
result = await client.search_memory(
query=current_message, user_id=user_id, agent_user_id=admin_user_id, limit=30
@@ -141,14 +141,19 @@ class MemoryStore:
memory_list = []
memory_list.append(f"user_memory[{len(result['user_memory'])}]:")
- for i, mem in enumerate(result['user_memory']):
+ for i, mem in enumerate(result["user_memory"]):
memory_list.append(f"{i},{getattr(mem, 'uri', '')},{getattr(mem, 'score', 0)}")
- memory_list.append(f'agent_memory[{len(result['agent_memory'])}]:')
- for i, mem in enumerate(result['agent_memory']):
+ memory_list.append(f"agent_memory[{len(result['agent_memory'])}]:")
+ for i, mem in enumerate(result["agent_memory"]):
memory_list.append(f"{i},{getattr(mem, 'uri', '')},{getattr(mem, 'score', 0)}")
- logger.info(f"[RAW_MEMORIES]\n{'\n'.join(memory_list)}")
- user_memory = await self._parse_viking_memory(result["user_memory"], client, min_score=0.35)
- agent_memory = await self._parse_viking_memory(result["agent_memory"], client, min_score=0.35, max_chars=2000)
+ raw_memories_log = "\n".join(memory_list)
+ logger.info(f"[RAW_MEMORIES]\n{raw_memories_log}")
+ user_memory = await self._parse_viking_memory(
+ result["user_memory"], client, min_score=0.35
+ )
+ agent_memory = await self._parse_viking_memory(
+ result["agent_memory"], client, min_score=0.35, max_chars=2000
+ )
return f"### user memories:\n{user_memory}\n### agent memories:\n{agent_memory}"
except Exception as e:
logger.error(f"[READ_USER_MEMORY]: search error. {e}")
diff --git a/bot/vikingbot/agent/tools/registry.py b/bot/vikingbot/agent/tools/registry.py
index 1797ebce9..61e192db3 100644
--- a/bot/vikingbot/agent/tools/registry.py
+++ b/bot/vikingbot/agent/tools/registry.py
@@ -1,17 +1,17 @@
"""Tool registry for dynamic tool management."""
import time
+from typing import Any
from loguru import logger
-from typing import Any
-
from vikingbot.agent.tools.base import Tool, ToolContext
from vikingbot.config.schema import SessionKey
from vikingbot.hooks import HookContext
from vikingbot.hooks.manager import hook_manager
from vikingbot.integrations.langfuse import LangfuseClient
from vikingbot.sandbox.manager import SandboxManager
+from vikingbot.utils.tracing import get_current_response_id
class ToolRegistry:
@@ -163,12 +163,14 @@ class ToolRegistry:
tool_span = None
start_time = time.time()
result = None
+ response_id = get_current_response_id()
try:
if self.langfuse.enabled:
tool_ctx = self.langfuse.tool_call(
name=name,
input=params,
session_id=session_key.safe_name(),
+ metadata={"response_id": response_id} if response_id else None,
)
tool_span = tool_ctx.__enter__()
@@ -193,7 +195,10 @@ class ToolRegistry:
span=tool_span,
output=output_str,
success=execute_success,
- metadata={"duration_ms": duration_ms},
+ metadata={
+ "duration_ms": duration_ms,
+ **({"response_id": response_id} if response_id else {}),
+ },
)
if hasattr(tool_span, "__exit__"):
tool_span.__exit__(None, None, None)
diff --git a/bot/vikingbot/bus/events.py b/bot/vikingbot/bus/events.py
index 8d6493431..119d33290 100644
--- a/bot/vikingbot/bus/events.py
+++ b/bot/vikingbot/bus/events.py
@@ -17,6 +17,11 @@ class OutboundEventType(str, Enum):
REASONING = "reasoning" # Reasoning content
ITERATION = "iteration" # Iteration marker
NO_REPLY = "no_reply" # No reply required
+ RESPONSE_COMPLETED = "response_completed" # Analytics-only response fact
+ FEEDBACK_SUBMITTED = "feedback_submitted" # Analytics-only explicit feedback fact
+ RESPONSE_OUTCOME_EVALUATED = (
+ "response_outcome_evaluated" # Analytics-only implicit outcome fact
+ )
@dataclass
@@ -43,6 +48,7 @@ class OutboundMessage:
reply_to: str | None = None
media: list[str] = field(default_factory=list)
metadata: dict[str, Any] = field(default_factory=dict)
+ response_id: str | None = None
token_usage: dict[str, int] = field(default_factory=dict)
time_cost: float = field(default_factory=float)
iteration: int = field(default_factory=int)
diff --git a/bot/vikingbot/channels/chat.py b/bot/vikingbot/channels/chat.py
index d0fd6345e..80d50b32a 100644
--- a/bot/vikingbot/channels/chat.py
+++ b/bot/vikingbot/channels/chat.py
@@ -109,6 +109,12 @@ class ChatChannel(BaseChannel):
if len(content) > 150:
content = content[:150] + "..."
console.print(f" [dim]└─ Result: {content}[/dim]")
+ elif msg.event_type in (
+ OutboundEventType.RESPONSE_COMPLETED,
+ OutboundEventType.FEEDBACK_SUBMITTED,
+ OutboundEventType.RESPONSE_OUTCOME_EVALUATED,
+ ):
+ return
async def _run_interactive(self) -> None:
"""Run in interactive mode."""
diff --git a/bot/vikingbot/channels/email.py b/bot/vikingbot/channels/email.py
index 3dbd4e16d..8e5eaa4f1 100644
--- a/bot/vikingbot/channels/email.py
+++ b/bot/vikingbot/channels/email.py
@@ -16,7 +16,7 @@ from typing import Any
from loguru import logger
-from vikingbot.bus.events import OutboundMessage
+from vikingbot.bus.events import OutboundEventType, OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.base import BaseChannel
from vikingbot.config.schema import EmailChannelConfig
@@ -104,6 +104,13 @@ class EmailChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send email via SMTP."""
+ if msg.event_type in (
+ OutboundEventType.RESPONSE_COMPLETED,
+ OutboundEventType.FEEDBACK_SUBMITTED,
+ OutboundEventType.RESPONSE_OUTCOME_EVALUATED,
+ ):
+ return
+
if not self.config.consent_granted:
logger.warning("Skip email send: consent_granted is false")
return
diff --git a/bot/vikingbot/channels/mochat.py b/bot/vikingbot/channels/mochat.py
index 94800d807..d864a1d39 100644
--- a/bot/vikingbot/channels/mochat.py
+++ b/bot/vikingbot/channels/mochat.py
@@ -12,7 +12,7 @@ from typing import Any
import httpx
from loguru import logger
-from vikingbot.bus.events import OutboundMessage
+from vikingbot.bus.events import OutboundEventType, OutboundMessage
from vikingbot.bus.queue import MessageBus
from vikingbot.channels.base import BaseChannel
from vikingbot.config.schema import MochatChannelConfig
@@ -186,7 +186,7 @@ def resolve_was_mentioned(payload: dict[str, Any], agent_user_id: str) -> bool:
return f"<@{agent_user_id}>" in content or f"@{agent_user_id}" in content
-def resolve_require_mention(config: MochatConfig, session_id: str, group_id: str) -> bool:
+def resolve_require_mention(config: MochatChannelConfig, session_id: str, group_id: str) -> bool:
"""Resolve mention requirement for group/panel conversations."""
groups = config.groups or {}
for key in (group_id, session_id, "*"):
@@ -314,6 +314,13 @@ class MochatChannel(BaseChannel):
async def send(self, msg: OutboundMessage) -> None:
"""Send outbound message to session or panel."""
+ if msg.event_type in (
+ OutboundEventType.RESPONSE_COMPLETED,
+ OutboundEventType.FEEDBACK_SUBMITTED,
+ OutboundEventType.RESPONSE_OUTCOME_EVALUATED,
+ ):
+ return
+
if not self.config.claw_token:
logger.warning("Mochat claw_token missing, skip send")
return
diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.py
index e22b80a40..e0a0244f1 100644
--- a/bot/vikingbot/channels/openapi.py
+++ b/bot/vikingbot/channels/openapi.py
@@ -19,6 +19,8 @@ from vikingbot.channels.openapi_models import (
ChatResponse,
ChatStreamEvent,
EventType,
+ FeedbackRequest,
+ FeedbackResponse,
HealthResponse,
SessionCreateRequest,
SessionCreateResponse,
@@ -33,6 +35,9 @@ from vikingbot.config.schema import (
SessionKey,
requires_gateway_token,
)
+from vikingbot.integrations.langfuse import LangfuseClient
+from vikingbot.observability.outcome import evaluate_response_outcome, should_update_outcome
+from vikingbot.session.manager import SessionManager
class PendingResponse:
@@ -41,6 +46,7 @@ class PendingResponse:
def __init__(self):
self.events: List[Dict[str, Any]] = []
self.final_content: Optional[str] = None
+ self.response_id: Optional[str] = None
self.relevant_memories: Optional[str] = None
self.event = asyncio.Event()
self.stream_queue: asyncio.Queue[Optional[ChatStreamEvent]] = asyncio.Queue()
@@ -56,6 +62,10 @@ class PendingResponse:
self.final_content = content
self.event.set()
+ def set_response_id(self, response_id: str | None):
+ """Track the response ID for the final assistant response."""
+ self.response_id = response_id
+
async def close_stream(self):
"""Close the stream queue."""
await self.stream_queue.put(None)
@@ -105,6 +115,7 @@ class OpenAPIChannel(BaseChannel):
self._router: Optional[APIRouter] = None
self._app = app # External FastAPI app to register routes on
self._server: Optional[asyncio.Task] = None # Server task
+ self._session_manager = SessionManager(self._resolve_bot_data_path())
# Load BotChannel configurations immediately in constructor
# so that subscriptions are setup before ChannelManager starts
@@ -189,8 +200,12 @@ class OpenAPIChannel(BaseChannel):
msg.event_type == OutboundEventType.RESPONSE
or msg.event_type == OutboundEventType.NO_REPLY
):
+ pending.set_response_id(msg.response_id)
pending.relevant_memories = (msg.metadata or {}).get("relevant_memories")
- await pending.add_event("response", msg.content or "")
+ await pending.add_event(
+ "response",
+ {"content": msg.content or "", "response_id": msg.response_id},
+ )
pending.set_final(msg.content or "")
await pending.close_stream()
elif msg.event_type == OutboundEventType.REASONING:
@@ -211,8 +226,12 @@ class OpenAPIChannel(BaseChannel):
if msg.event_type == OutboundEventType.RESPONSE:
# Final response - add to stream first
+ pending.set_response_id(msg.response_id)
pending.relevant_memories = (msg.metadata or {}).get("relevant_memories")
- await pending.add_event("response", msg.content or "")
+ await pending.add_event(
+ "response",
+ {"content": msg.content or "", "response_id": msg.response_id},
+ )
pending.set_final(msg.content or "")
await pending.close_stream()
elif msg.event_type == OutboundEventType.REASONING:
@@ -228,13 +247,25 @@ class OpenAPIChannel(BaseChannel):
self._router = self._create_router()
return self._router
+ def _resolve_bot_data_path(self) -> Path:
+ """Resolve the bot data path used for session persistence."""
+ if self._global_config is not None and hasattr(self._global_config, "bot_data_path"):
+ return Path(self._global_config.bot_data_path)
+ if self.workspace_path is not None:
+ return (
+ self.workspace_path.parent
+ if self.workspace_path.name == "workspace"
+ else self.workspace_path
+ )
+ return Path("~/.openviking/data/bot").expanduser()
+
def _create_router(self) -> APIRouter:
"""Create the FastAPI router with all routes."""
router = APIRouter()
channel = self # Capture for closures
async def verify_api_key(
- x_gateway_token: Optional[str] = Header(None, alias="X-Gateway-Token")
+ x_gateway_token: Optional[str] = Header(None, alias="X-Gateway-Token"),
) -> bool:
"""Verify API key for privileged HTTP chat/session routes."""
gateway_token = ""
@@ -285,6 +316,14 @@ class OpenAPIChannel(BaseChannel):
request.stream = True
return await channel._handle_chat_stream(request)
+ @router.post("/feedback", response_model=FeedbackResponse)
+ async def submit_feedback(
+ request: FeedbackRequest,
+ authorized: bool = Depends(verify_api_key),
+ ):
+ """Submit explicit user feedback for a prior assistant response."""
+ return await channel._handle_feedback(request)
+
@router.get("/sessions", response_model=SessionListResponse)
async def list_sessions(
authorized: bool = Depends(verify_api_key),
@@ -455,6 +494,7 @@ class OpenAPIChannel(BaseChannel):
return ChatResponse(
session_id=session_id,
+ response_id=pending.response_id,
message=response_content,
events=pending.events if pending.events else None,
relevant_memories=pending.relevant_memories,
@@ -597,6 +637,7 @@ class OpenAPIChannel(BaseChannel):
return ChatResponse(
session_id=session_id,
+ response_id=pending.response_id,
message=response_content,
events=pending.events if pending.events else None,
relevant_memories=pending.relevant_memories,
@@ -685,6 +726,128 @@ class OpenAPIChannel(BaseChannel):
},
)
+ async def _handle_feedback(self, request: FeedbackRequest) -> FeedbackResponse:
+ """Persist explicit user feedback and emit an analytics event."""
+ session_key = self._get_feedback_session_key(request)
+ feedback_timestamp = datetime.now()
+
+ def apply_feedback(
+ session: Any,
+ ) -> tuple[dict[str, Any], float | None, Optional[dict[str, Any]]]:
+ response_message = self._find_response_message(session.messages, request.response_id)
+ if response_message is None:
+ raise HTTPException(status_code=404, detail="Response not found")
+
+ response_timestamp = self._parse_message_timestamp(response_message)
+ feedback_delay_sec = None
+ if response_timestamp is not None:
+ feedback_delay_sec = round(
+ (feedback_timestamp - response_timestamp).total_seconds(), 3
+ )
+
+ feedback_event = {
+ "response_id": request.response_id,
+ "session_id": request.session_id,
+ "user_id": request.user_id or response_message.get("sender_id"),
+ "feedback_type": request.feedback_type.value,
+ "feedback_score": request.feedback_score,
+ "feedback_reason": request.feedback_reason,
+ "feedback_text": request.feedback_text,
+ "feedback_delay_sec": feedback_delay_sec,
+ "channel": session_key.channel_key(),
+ "created_at": feedback_timestamp.isoformat(),
+ }
+ session.metadata.setdefault("feedback_events", []).append(feedback_event)
+ outcome_payload = self._build_outcome_payload(session, request.response_id)
+ return feedback_event, feedback_delay_sec, outcome_payload
+
+ session, feedback_update = await self._session_manager.update_session(
+ session_key, apply_feedback
+ )
+ feedback_event, feedback_delay_sec, outcome_payload = feedback_update
+ if outcome_payload is not None:
+ LangfuseClient.get_instance().update_response_outcome(
+ request.response_id,
+ outcome_payload["outcome_label"],
+ outcome_payload,
+ )
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ session_key=session_key,
+ content="",
+ event_type=OutboundEventType.RESPONSE_OUTCOME_EVALUATED,
+ response_id=request.response_id,
+ metadata={"response_outcome_evaluated": outcome_payload},
+ )
+ )
+
+ await self.bus.publish_outbound(
+ OutboundMessage(
+ session_key=session_key,
+ content="",
+ event_type=OutboundEventType.FEEDBACK_SUBMITTED,
+ response_id=request.response_id,
+ metadata={"feedback_submitted": feedback_event},
+ )
+ )
+
+ return FeedbackResponse(
+ accepted=True,
+ response_id=request.response_id,
+ session_id=request.session_id,
+ feedback_type=request.feedback_type,
+ feedback_delay_sec=feedback_delay_sec,
+ timestamp=feedback_timestamp,
+ )
+
+ def _get_feedback_session_key(self, request: FeedbackRequest) -> SessionKey:
+ """Resolve the persisted session key for a feedback request."""
+ if request.channel_id:
+ return SessionKey(
+ type="bot_api", channel_id=request.channel_id, chat_id=request.session_id
+ )
+ return SessionKey(
+ type="cli", channel_id=self.config.channel_id(), chat_id=request.session_id
+ )
+
+ @staticmethod
+ def _find_response_message(
+ messages: List[Dict[str, Any]], response_id: str
+ ) -> Optional[Dict[str, Any]]:
+ for message in reversed(messages):
+ if message.get("role") == "assistant" and message.get("response_id") == response_id:
+ return message
+ return None
+
+ @staticmethod
+ def _parse_message_timestamp(message: Dict[str, Any]) -> Optional[datetime]:
+ timestamp = message.get("timestamp")
+ if not isinstance(timestamp, str) or not timestamp:
+ return None
+ try:
+ return datetime.fromisoformat(timestamp)
+ except ValueError:
+ return None
+
+ def _build_outcome_payload(self, session: Any, response_id: str) -> Optional[dict[str, Any]]:
+ """Evaluate and persist the latest known outcome for a response."""
+ evaluation = evaluate_response_outcome(
+ session.messages,
+ response_id,
+ feedback_events=session.metadata.get("feedback_events", []),
+ )
+ if evaluation is None:
+ return None
+
+ outcomes = session.metadata.setdefault("response_outcomes", {})
+ previous = outcomes.get(response_id)
+ if not should_update_outcome(previous, evaluation):
+ return None
+
+ outcome_payload = evaluation.to_dict()
+ outcomes[response_id] = outcome_payload
+ return outcome_payload
+
def get_openapi_router(bus: MessageBus, config: Config) -> APIRouter:
"""
diff --git a/bot/vikingbot/channels/openapi_models.py b/bot/vikingbot/channels/openapi_models.py
index c33ff77b8..d95b27502 100644
--- a/bot/vikingbot/channels/openapi_models.py
+++ b/bot/vikingbot/channels/openapi_models.py
@@ -26,6 +26,14 @@ class EventType(str, Enum):
ITERATION = "iteration"
+class FeedbackType(str, Enum):
+ """Supported explicit feedback types."""
+
+ THUMB_UP = "thumb_up"
+ THUMB_DOWN = "thumb_down"
+ RATING = "rating"
+
+
class ChatMessage(BaseModel):
"""A single chat message."""
@@ -58,6 +66,7 @@ class ChatResponse(BaseModel):
"""Response from chat endpoint (non-streaming)."""
session_id: str = Field(..., description="Session ID")
+ response_id: Optional[str] = Field(default=None, description="Assistant response ID")
message: str = Field(..., description="Assistant's response message")
events: Optional[List[Dict[str, Any]]] = Field(
default=None, description="Intermediate events (thinking, tool calls)"
@@ -69,6 +78,36 @@ class ChatResponse(BaseModel):
timestamp: datetime = Field(default_factory=datetime.now, description="Response timestamp")
+class FeedbackRequest(BaseModel):
+ """Request body for explicit feedback submission."""
+
+ response_id: str = Field(..., description="Assistant response ID", min_length=1)
+ session_id: str = Field(..., description="Session ID", min_length=1)
+ user_id: Optional[str] = Field(default=None, description="User identifier (optional)")
+ feedback_type: FeedbackType = Field(..., description="Feedback type")
+ feedback_score: Optional[float] = Field(default=None, description="Numeric feedback score")
+ feedback_reason: Optional[str] = Field(default=None, description="Feedback reason label")
+ feedback_text: Optional[str] = Field(default=None, description="Free-form feedback text")
+ channel_id: Optional[str] = Field(
+ default=None,
+ description="Bot channel ID for multi-channel routing (optional)",
+ )
+
+
+class FeedbackResponse(BaseModel):
+ """Response from feedback endpoint."""
+
+ accepted: bool = Field(default=True, description="Whether feedback was accepted")
+ response_id: str = Field(..., description="Assistant response ID")
+ session_id: str = Field(..., description="Session ID")
+ feedback_type: FeedbackType = Field(..., description="Feedback type")
+ feedback_delay_sec: Optional[float] = Field(
+ default=None,
+ description="Delay between response creation and feedback submission",
+ )
+ timestamp: datetime = Field(default_factory=datetime.now, description="Feedback timestamp")
+
+
class ChatStreamEvent(BaseModel):
"""A single event in the chat stream (SSE)."""
diff --git a/bot/vikingbot/integrations/langfuse.py b/bot/vikingbot/integrations/langfuse.py
index 713bd5772..3361a831a 100644
--- a/bot/vikingbot/integrations/langfuse.py
+++ b/bot/vikingbot/integrations/langfuse.py
@@ -32,6 +32,9 @@ class LangfuseClient:
):
self._client = None
self.enabled = enabled
+ self._observations_by_response_id: dict[str, Any] = {}
+ self._metadata_by_response_id: dict[str, dict[str, Any]] = {}
+ self._trace_context_by_response_id: dict[str, dict[str, str]] = {}
if not self.enabled:
return
@@ -80,6 +83,72 @@ class LangfuseClient:
if self.enabled and self._client:
self._client.flush()
+ def register_generation(
+ self, response_id: str, generation: Any, metadata: dict[str, Any] | None = None
+ ) -> None:
+ """Keep a recent generation handle and metadata for later response outcome updates."""
+ if not response_id or generation is None:
+ return
+ self._observations_by_response_id[response_id] = generation
+ self._metadata_by_response_id[response_id] = dict(metadata or {})
+ trace_id = getattr(generation, "trace_id", None)
+ observation_id = getattr(generation, "id", None)
+ if trace_id and observation_id:
+ self._trace_context_by_response_id[response_id] = {
+ "trace_id": trace_id,
+ "observation_id": observation_id,
+ }
+ if len(self._observations_by_response_id) > 1000:
+ oldest_response_id = next(iter(self._observations_by_response_id))
+ self._observations_by_response_id.pop(oldest_response_id, None)
+ self._metadata_by_response_id.pop(oldest_response_id, None)
+ self._trace_context_by_response_id.pop(oldest_response_id, None)
+
+ def update_generation_metadata(self, response_id: str, metadata: dict[str, Any]) -> None:
+ """Merge provider-side generation metadata for later outcome updates."""
+ if not response_id or not metadata:
+ return
+ current = self._metadata_by_response_id.setdefault(response_id, {})
+ current.update(metadata)
+
+ def update_response_outcome(
+ self,
+ response_id: str,
+ outcome_label: str,
+ outcome_payload: dict[str, Any] | None = None,
+ ) -> None:
+ """Attach evaluated response outcome metadata to a tracked generation."""
+ if not self.enabled or not response_id:
+ return
+
+ trace_context = self._trace_context_by_response_id.get(response_id)
+ if trace_context is None or not self._client:
+ return
+
+ metadata = {"outcome_label": outcome_label}
+ if outcome_payload:
+ metadata["response_outcome_evaluated"] = outcome_payload
+
+ try:
+ combined_metadata = {**self._metadata_by_response_id.get(response_id, {}), **metadata}
+ self._metadata_by_response_id[response_id] = combined_metadata
+ self._client.create_event(
+ trace_context={"trace_id": trace_context["trace_id"]},
+ name="response_outcome_evaluated",
+ metadata=combined_metadata,
+ )
+ self._client.create_score(
+ name="response_outcome_label",
+ value=outcome_label,
+ trace_id=trace_context["trace_id"],
+ observation_id=trace_context["observation_id"],
+ data_type="CATEGORICAL",
+ metadata=outcome_payload,
+ )
+ self.flush()
+ except Exception as e:
+ logger.debug(f"Langfuse update response outcome error: {e}")
+
@contextmanager
def propagate_attributes(
self,
diff --git a/bot/vikingbot/observability/outcome.py b/bot/vikingbot/observability/outcome.py
new file mode 100644
index 000000000..7d14927d4
--- /dev/null
+++ b/bot/vikingbot/observability/outcome.py
@@ -0,0 +1,144 @@
+"""Outcome evaluation helpers for feedback observability Phase 3."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Any, Optional
+
+REASK_WINDOW = timedelta(minutes=10)
+
+
+@dataclass
+class OutcomeEvaluation:
+ """Structured outcome evaluation for a single assistant response."""
+
+ response_id: str
+ resolved_in_one_turn: bool
+ reask_within_10m: bool
+ clarification_turns: int
+ follow_up_without_feedback: bool
+ outcome_label: str
+ evaluated_at: str
+ evidence: dict[str, Any]
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "response_id": self.response_id,
+ "resolved_in_one_turn": self.resolved_in_one_turn,
+ "reask_within_10m": self.reask_within_10m,
+ "clarification_turns": self.clarification_turns,
+ "follow_up_without_feedback": self.follow_up_without_feedback,
+ "outcome_label": self.outcome_label,
+ "evaluated_at": self.evaluated_at,
+ "evidence": self.evidence,
+ }
+
+
+def evaluate_response_outcome(
+ messages: list[dict[str, Any]],
+ response_id: str,
+ *,
+ feedback_events: Optional[list[dict[str, Any]]] = None,
+ now: Optional[datetime] = None,
+) -> OutcomeEvaluation | None:
+ """Evaluate the best-known outcome for a response from session history."""
+ assistant_index = _find_response_index(messages, response_id)
+ if assistant_index is None:
+ return None
+
+ assistant_message = messages[assistant_index]
+ assistant_timestamp = _parse_timestamp(assistant_message)
+ if assistant_timestamp is None:
+ assistant_timestamp = now or datetime.now()
+
+ following_messages = messages[assistant_index + 1 :]
+ user_messages = [m for m in following_messages if m.get("role") == "user"]
+ clarification_turns = len(user_messages)
+
+ relevant_feedback = [
+ event for event in (feedback_events or []) if event.get("response_id") == response_id
+ ]
+ latest_feedback = relevant_feedback[-1] if relevant_feedback else None
+ feedback_type = latest_feedback.get("feedback_type") if latest_feedback else None
+
+ reask_within_10m = False
+ first_user_after_response = user_messages[0] if user_messages else None
+ if first_user_after_response is not None:
+ user_timestamp = _parse_timestamp(first_user_after_response)
+ if user_timestamp is None:
+ user_timestamp = now or datetime.now()
+ reask_within_10m = user_timestamp - assistant_timestamp <= REASK_WINDOW
+
+ resolved_in_one_turn = not user_messages
+ follow_up_without_feedback = bool(user_messages) and not relevant_feedback
+
+ if feedback_type == "thumb_down":
+ outcome_label = "negative_feedback"
+ resolved_in_one_turn = False
+ elif feedback_type == "thumb_up":
+ outcome_label = "positive_feedback"
+ resolved_in_one_turn = True
+ reask_within_10m = False
+ clarification_turns = 0
+ follow_up_without_feedback = False
+ elif reask_within_10m:
+ outcome_label = "reasked"
+ resolved_in_one_turn = False
+ follow_up_without_feedback = False
+ elif resolved_in_one_turn:
+ outcome_label = "resolved"
+ follow_up_without_feedback = False
+ elif follow_up_without_feedback:
+ outcome_label = "follow_up_without_feedback"
+ else:
+ outcome_label = "follow_up"
+
+ evaluated_at = (now or datetime.now()).isoformat()
+ return OutcomeEvaluation(
+ response_id=response_id,
+ resolved_in_one_turn=resolved_in_one_turn,
+ reask_within_10m=reask_within_10m,
+ clarification_turns=clarification_turns,
+ follow_up_without_feedback=follow_up_without_feedback,
+ outcome_label=outcome_label,
+ evaluated_at=evaluated_at,
+ evidence={
+ "feedback_type": feedback_type,
+ "user_follow_up_count": len(user_messages),
+ "assistant_index": assistant_index,
+ },
+ )
+
+
+def should_update_outcome(previous: Optional[dict[str, Any]], current: OutcomeEvaluation) -> bool:
+ """Check whether a newly derived outcome meaningfully changes stored state."""
+ if previous is None:
+ return True
+ return any(
+ previous.get(field) != getattr(current, field)
+ for field in (
+ "resolved_in_one_turn",
+ "reask_within_10m",
+ "clarification_turns",
+ "follow_up_without_feedback",
+ "outcome_label",
+ )
+ )
+
+
+def _find_response_index(messages: list[dict[str, Any]], response_id: str) -> Optional[int]:
+ for index, message in enumerate(messages):
+ if message.get("role") == "assistant" and message.get("response_id") == response_id:
+ return index
+ return None
+
+
+def _parse_timestamp(message: dict[str, Any]) -> Optional[datetime]:
+ timestamp = message.get("timestamp")
+ if not isinstance(timestamp, str) or not timestamp:
+ return None
+ try:
+ return datetime.fromisoformat(timestamp)
+ except ValueError:
+ return None
diff --git a/bot/vikingbot/providers/litellm_provider.py b/bot/vikingbot/providers/litellm_provider.py
index 5bca3627f..e3bd704e2 100644
--- a/bot/vikingbot/providers/litellm_provider.py
+++ b/bot/vikingbot/providers/litellm_provider.py
@@ -12,6 +12,7 @@ from vikingbot.integrations.langfuse import LangfuseClient
from vikingbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
from vikingbot.providers.registry import find_by_model, find_gateway
from vikingbot.utils.helpers import cal_str_tokens
+from vikingbot.utils.tracing import get_current_response_id
class LiteLLMProvider(LLMProvider):
@@ -222,6 +223,9 @@ class LiteLLMProvider(LLMProvider):
try:
if self.langfuse.enabled and self.langfuse._client:
metadata = {"has_tools": tools is not None}
+ response_id = get_current_response_id()
+ if response_id:
+ metadata["response_id"] = response_id
client = self.langfuse._client
# Use start_observation with generation type
if hasattr(client, "start_observation"):
@@ -232,6 +236,10 @@ class LiteLLMProvider(LLMProvider):
input=messages,
metadata=metadata,
)
+ if response_id:
+ self.langfuse.register_generation(
+ response_id, langfuse_observation, metadata=metadata
+ )
response = await acompletion(**kwargs)
llm_response = self._parse_response(response)
@@ -248,7 +256,14 @@ class LiteLLMProvider(LLMProvider):
# Update observation with output and usage
update_kwargs: dict[str, Any] = {
"output": output_text,
- "metadata": {"finish_reason": llm_response.finish_reason},
+ "metadata": {
+ "finish_reason": llm_response.finish_reason,
+ **(
+ {"response_id": get_current_response_id()}
+ if get_current_response_id()
+ else {}
+ ),
+ },
}
if llm_response.usage:
@@ -267,6 +282,13 @@ class LiteLLMProvider(LLMProvider):
update_kwargs["usage_details"] = usage_details
+ response_id = get_current_response_id()
+ if response_id:
+ self.langfuse.update_generation_metadata(
+ response_id,
+ update_kwargs.get("metadata", {}),
+ )
+
# Update the observation
if hasattr(langfuse_observation, "update"):
try:
@@ -294,7 +316,14 @@ class LiteLLMProvider(LLMProvider):
if hasattr(langfuse_observation, "update"):
langfuse_observation.update(
output=f"Error: {str(e)}",
- metadata={"error": str(e)},
+ metadata={
+ "error": str(e),
+ **(
+ {"response_id": get_current_response_id()}
+ if get_current_response_id()
+ else {}
+ ),
+ },
)
if hasattr(langfuse_observation, "end"):
langfuse_observation.end()
diff --git a/bot/vikingbot/providers/openai_compatible_provider.py b/bot/vikingbot/providers/openai_compatible_provider.py
index 7433d2f3a..ab89b14b4 100644
--- a/bot/vikingbot/providers/openai_compatible_provider.py
+++ b/bot/vikingbot/providers/openai_compatible_provider.py
@@ -9,12 +9,14 @@ Supports all LLM providers with OpenAI-compatible API endpoints, including:
import json
from typing import Any
-from openai import AsyncOpenAI
+
from loguru import logger
+from openai import AsyncOpenAI
from vikingbot.integrations.langfuse import LangfuseClient
from vikingbot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
from vikingbot.utils.helpers import cal_str_tokens
+from vikingbot.utils.tracing import get_current_response_id
class OpenAICompatibleProvider(LLMProvider):
@@ -148,6 +150,9 @@ class OpenAICompatibleProvider(LLMProvider):
try:
if self.langfuse.enabled and self.langfuse._client:
metadata = {"has_tools": tools is not None}
+ response_id = get_current_response_id()
+ if response_id:
+ metadata["response_id"] = response_id
client = self.langfuse._client
# Use start_observation with generation type
if hasattr(client, "start_observation"):
@@ -158,6 +163,10 @@ class OpenAICompatibleProvider(LLMProvider):
input=messages,
metadata=metadata,
)
+ if response_id:
+ self.langfuse.register_generation(
+ response_id, langfuse_observation, metadata=metadata
+ )
response = await self.client.chat.completions.create(**kwargs)
llm_response = self._parse_response(response)
@@ -174,7 +183,14 @@ class OpenAICompatibleProvider(LLMProvider):
# Update observation with output and usage
update_kwargs: dict[str, Any] = {
"output": output_text,
- "metadata": {"finish_reason": llm_response.finish_reason},
+ "metadata": {
+ "finish_reason": llm_response.finish_reason,
+ **(
+ {"response_id": get_current_response_id()}
+ if get_current_response_id()
+ else {}
+ ),
+ },
}
if llm_response.usage:
@@ -193,6 +209,13 @@ class OpenAICompatibleProvider(LLMProvider):
update_kwargs["usage_details"] = usage_details
+ response_id = get_current_response_id()
+ if response_id:
+ self.langfuse.update_generation_metadata(
+ response_id,
+ update_kwargs.get("metadata", {}),
+ )
+
# Update the observation
if hasattr(langfuse_observation, "update"):
try:
@@ -220,7 +243,14 @@ class OpenAICompatibleProvider(LLMProvider):
if hasattr(langfuse_observation, "update"):
langfuse_observation.update(
output=f"Error: {str(e)}",
- metadata={"error": str(e)},
+ metadata={
+ "error": str(e),
+ **(
+ {"response_id": get_current_response_id()}
+ if get_current_response_id()
+ else {}
+ ),
+ },
)
if hasattr(langfuse_observation, "end"):
langfuse_observation.end()
diff --git a/bot/vikingbot/session/manager.py b/bot/vikingbot/session/manager.py
index 1fa466c0b..bd3bb41b1 100644
--- a/bot/vikingbot/session/manager.py
+++ b/bot/vikingbot/session/manager.py
@@ -5,7 +5,7 @@ import json
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
-from typing import Any
+from typing import Any, Callable, TypeVar
from loguru import logger
@@ -14,6 +14,11 @@ from vikingbot.providers.registry import find_by_name
from vikingbot.sandbox.manager import SandboxManager
from vikingbot.utils.helpers import ensure_dir, ensure_non_empty_assistant_content
+T = TypeVar("T")
+
+
+_SESSION_LOCKS: dict[Path, asyncio.Lock] = {}
+
@dataclass
class Session:
@@ -30,7 +35,12 @@ class Session:
metadata: dict[str, Any] = field(default_factory=dict)
def add_message(
- self, role: str, content: str, sender_id: str | None = None, token_usage: dict[str, Any] = None, **kwargs: Any
+ self,
+ role: str,
+ content: str,
+ sender_id: str | None = None,
+ token_usage: dict[str, Any] = None,
+ **kwargs: Any,
) -> None:
"""Add a message to the session."""
msg = {"role": role, "content": content, "timestamp": datetime.now().isoformat(), **kwargs}
@@ -133,6 +143,14 @@ class SessionManager:
self._cache: dict[SessionKey, Session] = {}
self.sandbox_manager = sandbox_manager
+ def _get_lock(self, session_key: SessionKey) -> asyncio.Lock:
+ path = self._get_session_path(session_key)
+ lock = _SESSION_LOCKS.get(path)
+ if lock is None:
+ lock = asyncio.Lock()
+ _SESSION_LOCKS[path] = lock
+ return lock
+
def _get_session_path(self, session_key: SessionKey) -> Path:
return self.sessions_dir / f"{session_key.safe_name()}.jsonl"
@@ -232,6 +250,15 @@ class SessionManager:
async def save(self, session: Session) -> None:
"""Save a session to disk."""
+ async with self._get_lock(session.key):
+ latest = self._load(session.key)
+ if latest is not None:
+ session.created_at = latest.created_at
+ session.metadata = self._merge_metadata(latest.metadata, session.metadata)
+ self._save_unlocked(session)
+
+ def _save_unlocked(self, session: Session) -> None:
+ """Persist a session while holding the per-session lock."""
path = self._get_session_path(session.key)
with open(path, "w") as f:
@@ -251,6 +278,39 @@ class SessionManager:
self._cache[session.key] = session
+ async def update_session(
+ self,
+ session_key: SessionKey,
+ updater: Callable[[Session], T],
+ *,
+ skip_heartbeat: bool = False,
+ ) -> tuple[Session, T]:
+ """Reload, mutate, and persist a session under a shared lock."""
+ async with self._get_lock(session_key):
+ self._cache.pop(session_key, None)
+ session = self.get_or_create(session_key, skip_heartbeat=skip_heartbeat)
+ result = updater(session)
+ self._save_unlocked(session)
+ return session, result
+
+ @classmethod
+ def _merge_metadata(cls, base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
+ """Merge nested metadata dictionaries without dropping persisted keys."""
+ merged = dict(base)
+ for key, value in override.items():
+ if key not in merged:
+ merged[key] = value
+ continue
+
+ current = merged[key]
+ if isinstance(current, dict) and isinstance(value, dict):
+ merged[key] = cls._merge_metadata(current, value)
+ elif isinstance(current, list) and isinstance(value, list):
+ merged[key] = current + [item for item in value if item not in current]
+ else:
+ merged[key] = value
+ return merged
+
def delete(self, key: SessionKey) -> bool:
"""
Delete a session.
diff --git a/bot/vikingbot/utils/tracing.py b/bot/vikingbot/utils/tracing.py
index 948c30e9b..b9e239172 100644
--- a/bot/vikingbot/utils/tracing.py
+++ b/bot/vikingbot/utils/tracing.py
@@ -15,6 +15,7 @@ from loguru import logger
# Context variable to store current session ID
_session_id: ContextVar[str | None] = ContextVar("session_id", default=None)
+_response_id: ContextVar[str | None] = ContextVar("response_id", default=None)
T = TypeVar("T")
@@ -30,6 +31,11 @@ def get_current_session_id() -> str | None:
return _session_id.get()
+def get_current_response_id() -> str | None:
+ """Get the current response ID from context."""
+ return _response_id.get()
+
+
@contextmanager
def set_session_id(session_id: str | None) -> Generator[None, None, None]:
"""
@@ -50,6 +56,16 @@ def set_session_id(session_id: str | None) -> Generator[None, None, None]:
_session_id.reset(token)
+@contextmanager
+def set_response_id(response_id: str | None) -> Generator[None, None, None]:
+ """Set the response ID for the current context."""
+ token = _response_id.set(response_id)
+ try:
+ yield
+ finally:
+ _response_id.reset(token)
+
+
def trace(
name: str | None = None,
*,
@@ -170,7 +186,7 @@ def trace(
return await wrapped_func(*args, **kwargs)
else:
if not has_propagate:
- logger.warning(f"[LANGFUSE] propagate_attributes not available")
+ logger.warning("[LANGFUSE] propagate_attributes not available")
return await wrapped_func(*args, **kwargs)
else:
return await wrapped_func(*args, **kwargs)
diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.py
index 415d6ee09..7fa0228e2 100644
--- a/openviking/server/bootstrap.py
+++ b/openviking/server/bootstrap.py
@@ -20,7 +20,12 @@ from openviking.server.app import create_app
from openviking.server.config import load_server_config
from openviking_cli.utils.config import OPENVIKING_CONFIG_ENV
from openviking_cli.utils.config.config_loader import resolve_config_path
-from openviking_cli.utils.config.consts import DEFAULT_CONFIG_DIR, DEFAULT_OV_CONF
+from openviking_cli.utils.config.consts import (
+ DEFAULT_CONFIG_DIR,
+ DEFAULT_OV_CONF,
+ DEFAULT_OVCLI_CONF,
+ OPENVIKING_CLI_CONFIG_ENV,
+)
from openviking_cli.utils.logger import configure_uvicorn_logging
@@ -99,6 +104,25 @@ def _resolve_default_bot_log_dir(config_path: Optional[str]) -> str:
return str(default_log_dir)
+def _resolve_cli_config_for_bot(config_path: Optional[str]) -> Optional[str]:
+ """Resolve which ovcli.conf the vikingbot child process should use."""
+ explicit_cli_config = os.environ.get(OPENVIKING_CLI_CONFIG_ENV)
+ if explicit_cli_config:
+ return explicit_cli_config
+
+ resolved_ov_conf = resolve_config_path(config_path, OPENVIKING_CONFIG_ENV, DEFAULT_OV_CONF)
+ if resolved_ov_conf is not None:
+ colocated_cli_config = Path(resolved_ov_conf).resolve().parent / DEFAULT_OVCLI_CONF
+ if colocated_cli_config.exists():
+ return str(colocated_cli_config)
+
+ default_cli_config = DEFAULT_CONFIG_DIR / DEFAULT_OVCLI_CONF
+ if default_cli_config.exists():
+ return str(default_cli_config)
+
+ return None
+
+
def main():
"""Main entry point for openviking-server command."""
parser = argparse.ArgumentParser(
@@ -239,6 +263,7 @@ def main():
enable_bot_logging,
bot_log_dir,
bot_port,
+ config_path=args.config,
)
# Create and run server app
@@ -292,6 +317,7 @@ def _start_vikingbot_gateway(
enable_logging: bool,
log_dir: str,
port: int = VIKINGBOT_DEFAULT_PORT,
+ config_path: Optional[str] = None,
) -> Optional[BotProcess]:
"""Start vikingbot gateway as a subprocess."""
print("Starting vikingbot gateway...")
@@ -346,6 +372,9 @@ def _start_vikingbot_gateway(
try:
# Set environment to ensure it uses the same Python environment
env = os.environ.copy()
+ cli_config_path = _resolve_cli_config_for_bot(config_path)
+ if cli_config_path is not None:
+ env[OPENVIKING_CLI_CONFIG_ENV] = cli_config_path
process = subprocess.Popen(
vikingbot_cmd,
diff --git a/openviking/server/routers/bot.py b/openviking/server/routers/bot.py
index d16fef03f..167d47aac 100644
--- a/openviking/server/routers/bot.py
+++ b/openviking/server/routers/bot.py
@@ -24,6 +24,16 @@ BOT_API_URL: Optional[str] = None # e.g., "http://localhost:18791"
BOT_API_KEY: str = ""
+def _create_bot_proxy_client() -> httpx.AsyncClient:
+ """Create an internal client for loopback bot proxy calls.
+
+ These requests target the local vikingbot gateway started alongside the
+ server, so they should not inherit proxy settings from the shell
+ environment.
+ """
+ return httpx.AsyncClient(trust_env=False)
+
+
def set_bot_api_url(url: str) -> None:
"""Set the Bot API URL. Called by app.py when --with-bot is enabled."""
global BOT_API_URL
@@ -56,7 +66,7 @@ async def health_check(request: Request):
bot_url = get_bot_url()
try:
- async with httpx.AsyncClient() as client:
+ async with _create_bot_proxy_client() as client:
# Forward to Vikingbot OpenAPIChannel health endpoint
response = await client.get(
f"{bot_url}/bot/v1/health",
@@ -99,7 +109,7 @@ async def chat(
)
try:
- async with httpx.AsyncClient() as client:
+ async with _create_bot_proxy_client() as client:
# Build headers for bot gateway
headers = {"Content-Type": "application/json"}
if BOT_API_KEY:
@@ -134,6 +144,55 @@ async def chat(
)
[email protected]("/feedback")
+async def feedback(
+ request: Request,
+ _ctx: RequestContext = Depends(get_request_context),
+):
+ """Submit explicit user feedback to the bot gateway."""
+ bot_url = get_bot_url()
+
+ try:
+ body = await request.json()
+ except json.JSONDecodeError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Invalid JSON in request body",
+ )
+
+ try:
+ async with _create_bot_proxy_client() as client:
+ headers = {"Content-Type": "application/json"}
+ if BOT_API_KEY:
+ headers["X-Gateway-Token"] = BOT_API_KEY
+
+ response = await client.post(
+ f"{bot_url}/bot/v1/feedback",
+ json=body,
+ headers=headers,
+ timeout=30.0,
+ )
+ response.raise_for_status()
+ return response.json()
+ except httpx.RequestError as e:
+ logger.error(f"Failed to connect to bot service: {e}")
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Bot service unavailable: {str(e)}",
+ )
+ except httpx.HTTPStatusError as e:
+ logger.error(f"Bot service returned error: {e}")
+ if e.response.status_code < 500:
+ raise HTTPException(
+ status_code=e.response.status_code,
+ detail=e.response.text,
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"Bot service error: {e.response.text}",
+ )
+
+
@router.post("/chat/stream")
async def chat_stream(
request: Request,
@@ -157,7 +216,7 @@ async def chat_stream(
async def event_stream() -> AsyncGenerator[str, None]:
"""Generate SSE events from bot response stream."""
try:
- async with httpx.AsyncClient() as client:
+ async with _create_bot_proxy_client() as client:
# Build headers for bot gateway
headers = {"Content-Type": "application/json"}
if BOT_API_KEY:
diff --git a/tests/server/test_bot_proxy_auth.py b/tests/server/test_bot_proxy_auth.py
index b5855d1e6..ceb876d74 100644
--- a/tests/server/test_bot_proxy_auth.py
+++ b/tests/server/test_bot_proxy_auth.py
@@ -3,7 +3,14 @@
"""Regression tests for bot proxy endpoint auth enforcement."""
+from types import SimpleNamespace
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
import openviking.server.routers.bot as bot_router_module
+from openviking.server.identity import AuthMode
def test_set_bot_api_key_updates_module_state():
@@ -12,3 +19,65 @@ def test_set_bot_api_key_updates_module_state():
bot_router_module.set_bot_api_key("")
assert bot_router_module.BOT_API_KEY == ""
+
+
+async def test_create_bot_proxy_client_disables_env_proxy():
+ async with bot_router_module._create_bot_proxy_client() as client:
+ assert isinstance(client, httpx.AsyncClient)
+ assert client._trust_env is False
+
+
+async def test_feedback_proxy_forwards_request(monkeypatch):
+ forwarded = {}
+
+ class FakeResponse:
+ def __init__(self):
+ self.status_code = 200
+ self.text = '{"accepted": true}'
+
+ def raise_for_status(self):
+ return None
+
+ def json(self):
+ return {"accepted": True, "response_id": "resp-123"}
+
+ class FakeClient:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return None
+
+ async def post(self, url, json, headers, timeout):
+ forwarded["url"] = url
+ forwarded["json"] = json
+ forwarded["headers"] = headers
+ forwarded["timeout"] = timeout
+ return FakeResponse()
+
+ monkeypatch.setattr(bot_router_module, "BOT_API_URL", "http://127.0.0.1:18790")
+ monkeypatch.setattr(bot_router_module, "BOT_API_KEY", "gateway-secret")
+ monkeypatch.setattr(bot_router_module, "_create_bot_proxy_client", lambda: FakeClient())
+
+ app = FastAPI()
+ app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)
+ app.include_router(bot_router_module.router, prefix="/bot/v1")
+ transport = httpx.ASGITransport(app=app)
+
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.post(
+ "/bot/v1/feedback",
+ json={
+ "session_id": "session-1",
+ "response_id": "resp-123",
+ "feedback_type": "thumb_up",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"accepted": True, "response_id": "resp-123"}
+ assert forwarded["url"] == "http://127.0.0.1:18790/bot/v1/feedback"
+ assert forwarded["json"]["response_id"] == "resp-123"
+ assert forwarded["headers"]["X-Gateway-Token"] == "gateway-secret"
+ assert forwarded["timeout"] == 30.0
diff --git a/tests/unit/test_server_bootstrap_bot_gateway.py b/tests/unit/test_server_bootstrap_bot_gateway.py
index 19063fbd8..6eaa2b3bc 100644
--- a/tests/unit/test_server_bootstrap_bot_gateway.py
+++ b/tests/unit/test_server_bootstrap_bot_gateway.py
@@ -1,7 +1,9 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+
import openviking.server.bootstrap as bootstrap
+from openviking_cli.utils.config.consts import OPENVIKING_CLI_CONFIG_ENV
class _FakeProcess:
@@ -15,9 +17,11 @@ def test_start_vikingbot_gateway_forces_localhost_host(monkeypatch):
captured = {}
monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")
+ monkeypatch.delenv(OPENVIKING_CLI_CONFIG_ENV, raising=False)
def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):
captured["cmd"] = cmd
+ captured["env"] = env
return _FakeProcess()
monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)
@@ -39,9 +43,11 @@ def test_start_vikingbot_gateway_uses_custom_port(monkeypatch):
captured = {}
monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")
+ monkeypatch.delenv(OPENVIKING_CLI_CONFIG_ENV, raising=False)
def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):
captured["cmd"] = cmd
+ captured["env"] = env
return _FakeProcess()
monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)
@@ -56,3 +62,61 @@ def test_start_vikingbot_gateway_uses_custom_port(monkeypatch):
assert process is not None
assert captured["cmd"][captured["cmd"].index("--host") + 1] == "127.0.0.1"
assert captured["cmd"][captured["cmd"].index("--port") + 1] == "19990"
+
+
+def test_start_vikingbot_gateway_prefers_colocated_ovcli_conf(monkeypatch, tmp_path):
+ captured = {}
+ config_path = tmp_path / "ov.conf"
+ cli_config_path = tmp_path / "ovcli.conf"
+ config_path.write_text("{}", encoding="utf-8")
+ cli_config_path.write_text("{}", encoding="utf-8")
+
+ monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")
+
+ def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):
+ captured["cmd"] = cmd
+ captured["env"] = env
+ return _FakeProcess()
+
+ monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)
+ monkeypatch.setattr(bootstrap.time, "sleep", lambda _: None)
+ monkeypatch.delenv(OPENVIKING_CLI_CONFIG_ENV, raising=False)
+
+ process = bootstrap._start_vikingbot_gateway(
+ enable_logging=False,
+ log_dir="/tmp/logs",
+ config_path=str(config_path),
+ )
+
+ assert process is not None
+ assert captured["env"][OPENVIKING_CLI_CONFIG_ENV] == str(cli_config_path)
+
+
+def test_start_vikingbot_gateway_preserves_explicit_cli_config_env(monkeypatch, tmp_path):
+ captured = {}
+ config_path = tmp_path / "ov.conf"
+ colocated_cli_config = tmp_path / "ovcli.conf"
+ explicit_cli_config = tmp_path / "custom-ovcli.conf"
+ config_path.write_text("{}", encoding="utf-8")
+ colocated_cli_config.write_text("{}", encoding="utf-8")
+ explicit_cli_config.write_text("{}", encoding="utf-8")
+
+ monkeypatch.setattr(bootstrap.shutil, "which", lambda name: "/usr/bin/vikingbot")
+
+ def _fake_popen(cmd, stdout=None, stderr=None, text=None, env=None):
+ captured["cmd"] = cmd
+ captured["env"] = env
+ return _FakeProcess()
+
+ monkeypatch.setattr(bootstrap.subprocess, "Popen", _fake_popen)
+ monkeypatch.setattr(bootstrap.time, "sleep", lambda _: None)
+ monkeypatch.setenv(OPENVIKING_CLI_CONFIG_ENV, str(explicit_cli_config))
+
+ process = bootstrap._start_vikingbot_gateway(
+ enable_logging=False,
+ log_dir="/tmp/logs",
+ config_path=str(config_path),
+ )
+
+ assert process is not None
+ assert captured["env"][OPENVIKING_CLI_CONFIG_ENV] == str(explicit_cli_config)