280 lines
12 KiB
Python
280 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import FastAPI
|
|
|
|
from app.api.v1 import situational_awareness
|
|
from app.schemas.ai import SituationalAnalysisResponse
|
|
from app.services.ai import spatial_domain_agent
|
|
from app.services.ai.stream_turn import reset_stream_quota_ledger
|
|
from app.services.ai_client import AIProviderClient, get_ai_provider_client
|
|
|
|
|
|
def _parse_sse_text(raw: str) -> list[tuple[str, dict]]:
|
|
events: list[tuple[str, dict]] = []
|
|
for block in raw.replace("\r\n", "\n").split("\n\n"):
|
|
if not block.strip():
|
|
continue
|
|
ev_name = "message"
|
|
data_lines: list[str] = []
|
|
for line in block.split("\n"):
|
|
if line.startswith("event:"):
|
|
ev_name = line[6:].strip()
|
|
elif line.startswith("data:"):
|
|
data_lines.append(line[5:].lstrip())
|
|
if data_lines:
|
|
events.append((ev_name, json.loads("\n".join(data_lines))))
|
|
return events
|
|
|
|
|
|
class _StubDb:
|
|
pass
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_spatial_domain_agent_reads_content_attribute(monkeypatch):
|
|
class _FakeClient:
|
|
service_url = "http://aiprovider.test"
|
|
llm_config = {"provider": "minimax", "model": "MiniMax-M2.7"}
|
|
|
|
async def analyze(self, _req):
|
|
return SituationalAnalysisResponse(
|
|
provider="minimax",
|
|
model="MiniMax-M2.7",
|
|
content=json.dumps(
|
|
{
|
|
"domain": "global",
|
|
"subject_key": "global:test",
|
|
"title": "全球多图层态势",
|
|
"executive_assertion": "已成功读取大模型合成内容。",
|
|
"confirmed_facts": [{"statement": "全网多图层数据在线。", "evidence_ids": ["ev-global-1"]}],
|
|
"analytical_notes": [{"statement": "LLM 输出字段匹配成功。", "evidence_ids": ["ev-global-1"]}],
|
|
"open_gaps": ["示例口径边界。"],
|
|
"evidence_ids": ["ev-global-1"],
|
|
},
|
|
ensure_ascii=False,
|
|
),
|
|
)
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"available": True,
|
|
"domain_summaries": [],
|
|
"bgp_summary": {"active_count": 0},
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Snapshot"}},
|
|
"limitations": [],
|
|
}
|
|
|
|
monkeypatch.setattr(spatial_domain_agent, "query_global_situational_tool", fake_global_tool)
|
|
|
|
result = await spatial_domain_agent.investigate_spatial_domain(
|
|
_StubDb(),
|
|
domain="global",
|
|
question="分析全球态势",
|
|
persist=False,
|
|
ai_client=_FakeClient(),
|
|
)
|
|
|
|
assert result["generation_mode"] == "llm_verified"
|
|
assert result["payload"]["executive_assertion"] == "已成功读取大模型合成内容。"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_turn_adapts_between_configured_minimax_and_disabled_ai(monkeypatch):
|
|
reset_stream_quota_ledger()
|
|
|
|
async def fake_recent_news(*_args, **_kwargs):
|
|
return {
|
|
"domain": "news",
|
|
"available": True,
|
|
"count": 1,
|
|
"items": [{"id": "n1", "title": "全球海缆路由测试头条", "source": "Reuters", "region": "global"}],
|
|
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Planet News"}},
|
|
}
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
|
}
|
|
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
|
|
|
class _ConfiguredClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={
|
|
"provider": "minimax",
|
|
"provider_api": "anthropic-messages",
|
|
"base_url": "https://api.minimaxi.com/anthropic",
|
|
"api_key": "secret-key",
|
|
"model": "MiniMax-M2.7",
|
|
},
|
|
)
|
|
|
|
async def stream_analyze(self, payload, request_id=None):
|
|
assert payload.thinking == {"type": "enabled", "budget_tokens": 2048}
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
|
yield {"event": "reasoning", "delta": "先梳理新闻核心矛盾。"}
|
|
yield {"event": "text", "delta": "### 新闻深度分析\n\n- **要点**:供应链与光缆关注升温。"}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 42}}
|
|
|
|
class _DisabledClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={"provider": "disabled"},
|
|
)
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
|
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _ConfiguredClient()
|
|
|
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
|
# 1. Anonymous Earth/desktop caller uses MiniMax automatically when configured
|
|
res_ai = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
|
"domain": "news",
|
|
"news_context": {
|
|
"id": "n1",
|
|
"title": "全球海缆路由测试头条",
|
|
"summary": "测试新闻摘要",
|
|
"source": "Reuters",
|
|
"region": "全球",
|
|
},
|
|
},
|
|
)
|
|
assert res_ai.status_code == 200
|
|
assert "text/event-stream" in res_ai.headers["content-type"]
|
|
ai_events = _parse_sse_text(res_ai.text)
|
|
ai_names = [name for name, _ in ai_events]
|
|
assert ai_names == ["meta", "reasoning", "text", "done"]
|
|
assert ai_events[0][1]["ai_enabled"] is True
|
|
assert ai_events[0][1]["model"] == "MiniMax-M2.7"
|
|
assert ai_events[1][1]["delta"] == "先梳理新闻核心矛盾。"
|
|
assert "新闻深度分析" in ai_events[2][1]["delta"]
|
|
assert ai_events[3][1]["zero_token"] is False
|
|
assert ai_events[3][1]["generation_mode"] == "llm_verified"
|
|
assert ai_events[3][1]["model"] == "MiniMax-M2.7"
|
|
|
|
# 2. Switching provider to disabled adapts seamlessly back to deterministic baseline
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _DisabledClient()
|
|
res_no_ai = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "请深度分析这条新闻:「全球海缆路由测试头条」",
|
|
"domain": "news",
|
|
"news_context": {"id": "n1", "title": "全球海缆路由测试头条", "summary": "测试新闻摘要"},
|
|
},
|
|
)
|
|
assert res_no_ai.status_code == 200
|
|
no_ai_events = _parse_sse_text(res_no_ai.text)
|
|
assert no_ai_events[0][1]["ai_enabled"] is False
|
|
assert no_ai_events[0][1]["model"] is None
|
|
assert no_ai_events[-1][0] == "done"
|
|
assert no_ai_events[-1][1]["zero_token"] is True
|
|
assert no_ai_events[-1][1]["model"] is None
|
|
assert no_ai_events[-1][1]["generation_mode"] == "deterministic_baseline"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
|
|
reset_stream_quota_ledger()
|
|
|
|
async def fake_global_tool(*_args, **_kwargs):
|
|
return {
|
|
"domain": "global",
|
|
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
|
|
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
|
|
}
|
|
|
|
async def fake_recent_news(*_args, **_kwargs):
|
|
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
|
|
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
|
|
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
|
|
|
|
captured_analyze_reqs = []
|
|
captured_stream_reqs = []
|
|
|
|
class _CompactingClient(AIProviderClient):
|
|
def __init__(self):
|
|
super().__init__(
|
|
service_url="http://aiprovider.test",
|
|
llm_config={
|
|
"provider": "minimax",
|
|
"provider_api": "anthropic-messages",
|
|
"base_url": "https://api.minimaxi.com/anthropic",
|
|
"api_key": "secret-key",
|
|
"model": "MiniMax-M2.7",
|
|
},
|
|
)
|
|
|
|
async def analyze(self, payload, request_id=None):
|
|
captured_analyze_reqs.append(payload)
|
|
return SituationalAnalysisResponse(
|
|
provider="minimax",
|
|
model="MiniMax-M2.7",
|
|
content="<think>internal</think>前序关注中美算力与亚太海缆冗余,已核验 343 条骨干海缆。",
|
|
)
|
|
|
|
async def stream_analyze(self, payload, request_id=None):
|
|
captured_stream_reqs.append(payload)
|
|
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
|
|
yield {"event": "text", "delta": "结合前文 343 条海缆与您的亚太聚焦偏好,补充说明如下。"}
|
|
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 55}}
|
|
|
|
app = FastAPI()
|
|
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
|
|
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
|
|
app.dependency_overrides[get_ai_provider_client] = lambda: _CompactingClient()
|
|
|
|
long_history = []
|
|
for idx in range(1, 7):
|
|
long_history.append({"role": "user", "content": f"第 {idx} 轮提问"})
|
|
long_history.append({"role": "assistant", "content": f"<think>thought-{idx}</think>第 {idx} 轮结论"})
|
|
|
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
|
|
res = await client.post(
|
|
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
|
|
json={
|
|
"question": "基于前面总结继续追问亚太海缆脆弱点",
|
|
"domain": "global",
|
|
"history": long_history,
|
|
"memory_notes": ["优先给出亚太海缆冗余与算力口径边界"],
|
|
"pinned_summaries": ["GLOBAL · Rev.1: 全球综合态势"],
|
|
},
|
|
)
|
|
assert res.status_code == 200
|
|
events = _parse_sse_text(res.text)
|
|
meta_ev = events[0][1]
|
|
done_ev = events[-1][1]
|
|
|
|
assert meta_ev["compacted"] is True
|
|
assert "343 条骨干海缆" in meta_ev["conversation_summary"]
|
|
assert "<think>" not in meta_ev["conversation_summary"]
|
|
assert meta_ev["memory_used"] is True
|
|
assert done_ev["compacted"] is True
|
|
assert done_ev["conversation_summary"] == meta_ev["conversation_summary"]
|
|
|
|
assert len(captured_analyze_reqs) == 1
|
|
assert len(captured_stream_reqs) == 1
|
|
sent_payload = captured_stream_reqs[0]
|
|
# Recent window preserves latest 4 turns (8 messages), with <think> stripped
|
|
assert len(sent_payload.messages) == 8
|
|
assert sent_payload.messages[0].content == "第 3 轮提问"
|
|
assert sent_payload.messages[1].content == "第 3 轮结论"
|
|
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
|
|
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
|
|
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
|