forked from linkong/planet
887 lines
38 KiB
Python
887 lines
38 KiB
Python
"""Adaptive SSE streaming turn orchestrator with thinking process, model attribution, and news context."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
from collections import defaultdict, deque
|
||
from collections.abc import AsyncIterator
|
||
from datetime import UTC, datetime, timedelta
|
||
import json
|
||
import os
|
||
from typing import Any
|
||
import uuid
|
||
|
||
from fastapi import HTTPException, Request, status
|
||
from sqlalchemy import select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
||
from app.core.logging import get_logger
|
||
from app.models.ai_workflow import AIWorkflow
|
||
from app.models.situational_assessment import InvestigationSession, WorkflowRun
|
||
from app.schemas.ai import ChatMessage, SituationalAnalysisRequest
|
||
from app.services.ai.access_policy import AccessContext
|
||
from app.services.ai.conversation_memory import (
|
||
compact_conversation_history,
|
||
sanitize_memory_notes,
|
||
sanitize_pinned_summaries,
|
||
)
|
||
from app.services.ai.dag_executor import run_workflow_dag_stream
|
||
from app.services.ai.thinking_sanitizer import prepare_situational_ai_call, strip_thinking_text
|
||
from app.services.ai.tool_registry import (
|
||
TimeBasis,
|
||
query_global_situational_tool,
|
||
query_recent_earth_news_tool,
|
||
)
|
||
from app.services.ai.scene_directives import (
|
||
INFLUENCE_ZONE_GUIDANCE as _INFLUENCE_ZONE_GUIDANCE,
|
||
consume_text_holding_scene_tag as _consume_text_holding_scene_tag,
|
||
extract_planet_scene_from_text,
|
||
)
|
||
from app.services.ai.workflow_evolver import schedule_post_run_evolution
|
||
from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows
|
||
from app.services.ai.workflow_runtime import (
|
||
ActiveRunHandle,
|
||
classify_turn_intent,
|
||
execute_session_turn,
|
||
register_active_run_handle,
|
||
unregister_active_run_handle,
|
||
)
|
||
from app.services.ai_client import AIProviderClient
|
||
from app.services.compute_lineage import (
|
||
build_revision_change_context,
|
||
is_revision_question,
|
||
)
|
||
|
||
logger = get_logger(__name__, service="ai_stream")
|
||
|
||
_STREAM_QUOTA_WINDOW: dict[str, deque[datetime]] = defaultdict(deque)
|
||
_GEOPOLITICAL_OR_NEWS_KEYWORDS = (
|
||
"国际局势",
|
||
"全球局势",
|
||
"地缘",
|
||
"新闻",
|
||
"报道",
|
||
"外交",
|
||
"冲突",
|
||
"制裁",
|
||
"关税",
|
||
"战争",
|
||
"和平",
|
||
"热点",
|
||
"geopolit",
|
||
"headline",
|
||
"news",
|
||
"international situation",
|
||
"world situation",
|
||
)
|
||
|
||
|
||
def reset_stream_quota_ledger() -> None:
|
||
"""Reset in-memory public stream rate limiter state (for deterministic tests)."""
|
||
_STREAM_QUOTA_WINDOW.clear()
|
||
|
||
|
||
def check_stream_quota(access: AccessContext) -> None:
|
||
"""Enforce bounded hourly quota on adaptive streaming AI turns across all access tiers."""
|
||
default_public_cap = int(os.getenv("PLANET_PUBLIC_AI_STREAM_HOURLY_QUOTA", "60"))
|
||
limit = access.hourly_paid_quota if access.hourly_paid_quota > 0 else default_public_cap
|
||
if limit <= 0:
|
||
return
|
||
|
||
now = datetime.now(UTC)
|
||
window_start = now - timedelta(hours=1)
|
||
dq = _STREAM_QUOTA_WINDOW[access.actor_key]
|
||
while dq and dq[0] < window_start:
|
||
dq.popleft()
|
||
if len(dq) >= limit:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||
detail=f"Hourly AI stream quota ({limit}) exceeded.",
|
||
)
|
||
dq.append(now)
|
||
|
||
|
||
def build_streaming_thinking_config(ai_client: AIProviderClient) -> dict[str, Any] | None:
|
||
"""Enable streamed reasoning tokens for MiniMax/Anthropic providers when streaming turns."""
|
||
llm_cfg = getattr(ai_client, "llm_config", None) or {}
|
||
provider = str(llm_cfg.get("provider") or "").strip().lower()
|
||
provider_api = str(llm_cfg.get("provider_api") or "").strip().lower()
|
||
model = str(llm_cfg.get("model") or "").strip().lower()
|
||
|
||
if "minimax-m3" in model:
|
||
return {"type": "adaptive", "effort": "medium"}
|
||
if provider == "minimax" or provider_api == "anthropic-messages" or "anthropic" in provider or "claude" in model:
|
||
return {"type": "enabled", "budget_tokens": 2048}
|
||
return None
|
||
|
||
|
||
def _is_geopolitical_or_news_question(
|
||
question: str,
|
||
*,
|
||
domain: str,
|
||
news_context: dict[str, Any] | None,
|
||
) -> bool:
|
||
if domain == "news" or news_context:
|
||
return True
|
||
q = (question or "").strip().lower()
|
||
return any(kw in q for kw in _GEOPOLITICAL_OR_NEWS_KEYWORDS)
|
||
|
||
|
||
def _format_sse(event: str, payload: dict[str, Any]) -> str:
|
||
return f"event: {event}\ndata: {json.dumps(payload, ensure_ascii=False, default=str)}\n\n"
|
||
|
||
|
||
def _build_news_fallback_markdown(
|
||
*,
|
||
question: str,
|
||
news_context: dict[str, Any] | None,
|
||
recent_news: dict[str, Any],
|
||
ai_configured: bool,
|
||
fallback_reason: str | None = None,
|
||
) -> str:
|
||
lines: list[str] = []
|
||
if news_context:
|
||
title = str(news_context.get("title") or "新闻速递").strip()
|
||
source = str(news_context.get("source") or "").strip()
|
||
region = str(news_context.get("region") or news_context.get("region_key") or "").strip()
|
||
published_at = str(news_context.get("published_at") or "").strip()
|
||
summary = str(news_context.get("summary") or "").strip()
|
||
lines.append(f"### 新闻焦点:{title}")
|
||
meta_parts = [p for p in (source, region, published_at) if p]
|
||
if meta_parts:
|
||
lines.append(f"- **来源与时间**:{' · '.join(meta_parts)}")
|
||
if summary:
|
||
lines.append(f"- **报道摘要**:{summary}")
|
||
else:
|
||
lines.append("### 全球局势与新闻态势速览")
|
||
if question:
|
||
lines.append(f"- **当前问题**:{question}")
|
||
|
||
items = list(recent_news.get("items") or [])
|
||
if items:
|
||
lines.append("")
|
||
lines.append("#### 近期关联动态")
|
||
for item in items[:5]:
|
||
item_title = str(item.get("title") or "").strip()
|
||
item_src = str(item.get("source") or "").strip()
|
||
item_reg = str(item.get("region") or "").strip()
|
||
if item_title:
|
||
meta = f"({item_src}{' · ' + item_reg if item_reg else ''})" if item_src else ""
|
||
lines.append(f"- {item_title}{meta}")
|
||
|
||
if not ai_configured:
|
||
lines.append("")
|
||
lines.append("> 当前后台尚未接入可用 AI 大模型,以上为内置新闻与遥测结构化汇总。")
|
||
elif fallback_reason:
|
||
lines.append("")
|
||
lines.append(f"> AI 流式生成暂时不可用({fallback_reason}),已自动回退为内置结构化汇总。")
|
||
return "\n".join(lines).strip()
|
||
|
||
|
||
def _build_news_analysis_request(
|
||
*,
|
||
question: str,
|
||
news_context: dict[str, Any] | None,
|
||
recent_news: dict[str, Any],
|
||
global_snapshot: dict[str, Any],
|
||
thinking_cfg: dict[str, Any] | None,
|
||
conversation_messages: list[ChatMessage] | None = None,
|
||
conversation_summary: str = "",
|
||
memory_notes: list[str] | None = None,
|
||
pinned_summaries: list[str] | None = None,
|
||
) -> SituationalAnalysisRequest:
|
||
context: dict[str, Any] = {
|
||
"focused_news": news_context or None,
|
||
"recent_news_headlines": (recent_news.get("items") or [])[:10],
|
||
"global_infrastructure_summary": global_snapshot.get("domain_summaries") or [],
|
||
}
|
||
if conversation_summary:
|
||
context["conversation_summary"] = conversation_summary
|
||
if memory_notes:
|
||
context["user_memory_notes"] = memory_notes
|
||
if pinned_summaries:
|
||
context["pinned_comparisons"] = pinned_summaries
|
||
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
|
||
return SituationalAnalysisRequest(
|
||
title="Planet 全球新闻与国际局势研判",
|
||
objective=(
|
||
f"用户提问:{question}\n\n"
|
||
"请结合多轮对话延续性与记忆备忘,直接使用中文(若用户用英文提问则用英文)输出结构清晰的 Markdown 深度分析,包括:\n"
|
||
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
|
||
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
|
||
"3. **后续重点观察信号与不确定边界**。\n"
|
||
"正文直接输出面向用户的 Markdown,不要把正文包在 JSON 里;若存在任何明确的地理国家、地区或海域影响范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
|
||
),
|
||
system_prompt=(
|
||
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
|
||
"如有前序对话与用户备忘录,请保持指代与口径延续。"
|
||
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。\n\n"
|
||
f"{_INFLUENCE_ZONE_GUIDANCE}"
|
||
),
|
||
context=context,
|
||
constraints=[
|
||
"Output clean user-facing Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
|
||
"Distinguish reported facts from analytical outlook.",
|
||
],
|
||
thinking=thinking_cfg,
|
||
messages=conversation_messages or [],
|
||
)
|
||
|
||
|
||
def _build_telemetry_stream_request(
|
||
*,
|
||
domain: str,
|
||
question: str,
|
||
base_answer_md: str,
|
||
evidence: dict[str, Any],
|
||
view_spec: dict[str, Any] | None,
|
||
recent_news: dict[str, Any] | None,
|
||
thinking_cfg: dict[str, Any] | None,
|
||
conversation_messages: list[ChatMessage] | None = None,
|
||
conversation_summary: str = "",
|
||
memory_notes: list[str] | None = None,
|
||
pinned_summaries: list[str] | None = None,
|
||
revision_context: dict[str, Any] | None = None,
|
||
) -> SituationalAnalysisRequest:
|
||
context: dict[str, Any] = {
|
||
"domain": domain,
|
||
"verified_baseline_summary": base_answer_md,
|
||
"evidence": evidence,
|
||
"view_headline": (view_spec or {}).get("headline"),
|
||
"publish_id": (view_spec or {}).get("publish_id"),
|
||
"mode": (view_spec or {}).get("mode"),
|
||
"focus_year": (view_spec or {}).get("focus_year"),
|
||
}
|
||
if revision_context:
|
||
context["revision_context"] = revision_context
|
||
if recent_news and recent_news.get("items"):
|
||
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
|
||
if conversation_summary:
|
||
context["conversation_summary"] = conversation_summary
|
||
if memory_notes:
|
||
context["user_memory_notes"] = memory_notes
|
||
if pinned_summaries:
|
||
context["pinned_comparisons"] = pinned_summaries
|
||
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
|
||
return SituationalAnalysisRequest(
|
||
title=f"Planet 态势参谋分析({domain})",
|
||
objective=(
|
||
f"用户问题:{question}\n\n"
|
||
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
|
||
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要把正文包在 JSON 对象里;"
|
||
"若涉及明确国家、地区或海域范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
|
||
),
|
||
system_prompt=(
|
||
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
|
||
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。\n\n"
|
||
f"{_INFLUENCE_ZONE_GUIDANCE}"
|
||
),
|
||
context=context,
|
||
constraints=[
|
||
"Output clean Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
|
||
"Do not invent telemetry counts or unverified outages outside context.",
|
||
],
|
||
thinking=thinking_cfg,
|
||
messages=conversation_messages or [],
|
||
)
|
||
|
||
|
||
async def stream_session_turn(
|
||
db: AsyncSession,
|
||
*,
|
||
request: Request | None,
|
||
session: InvestigationSession | None,
|
||
question: str,
|
||
context_override: dict[str, Any] | None,
|
||
news_context: dict[str, Any] | None,
|
||
access: AccessContext,
|
||
ai_client: AIProviderClient | None,
|
||
client_run_id: str | None = None,
|
||
issued_session_token: str | None = None,
|
||
history: list[dict[str, Any]] | None = None,
|
||
conversation_summary: str | None = None,
|
||
memory_notes: list[str] | None = None,
|
||
pinned_summaries: list[str] | None = None,
|
||
workflow_id: str | None = None,
|
||
targets: list[dict[str, Any]] | None = None,
|
||
) -> AsyncIterator[str]:
|
||
"""Adaptive SSE generator: streams real LLM + thinking when AI is configured, else grounded baseline."""
|
||
check_stream_quota(access)
|
||
|
||
session_id_val = str(session.id) if session is not None else "stateless"
|
||
run_id = client_run_id or f"run-{uuid.uuid4().hex[:12]}"
|
||
|
||
merged_ctx: dict[str, Any] = {}
|
||
if session is not None and isinstance(session.context_state, dict):
|
||
merged_ctx.update(session.context_state)
|
||
if context_override:
|
||
for k, v in context_override.items():
|
||
if v is not None:
|
||
merged_ctx[k] = v
|
||
if context_override.get("publish_id") and not context_override.get("as_of"):
|
||
merged_ctx["as_of"] = None
|
||
elif context_override.get("as_of") and not context_override.get("publish_id"):
|
||
merged_ctx["publish_id"] = None
|
||
|
||
raw_history = history if history else merged_ctx.get("recent_messages")
|
||
existing_summary = str(
|
||
conversation_summary
|
||
if conversation_summary is not None
|
||
else merged_ctx.get("conversation_summary") or ""
|
||
)
|
||
clean_memory_notes = sanitize_memory_notes(memory_notes)
|
||
clean_pinned_summaries = sanitize_pinned_summaries(
|
||
pinned_summaries
|
||
if pinned_summaries is not None
|
||
else [
|
||
f"{p.get('pin_id', 'PIN')}: {p.get('title', '')}"
|
||
for p in ((getattr(session, "pinned_items", None) or []) if session is not None else [])
|
||
if isinstance(p, dict) and p.get("title")
|
||
]
|
||
)
|
||
|
||
routed = classify_turn_intent(question, merged_ctx)
|
||
explicit_domain = str((context_override or {}).get("domain") or "").strip().lower()
|
||
domain = "news" if news_context or explicit_domain == "news" else str(routed.get("domain") or "global")
|
||
is_pure_view = bool(routed.get("is_pure_projection") or routed.get("auto_play_presentation"))
|
||
geo_or_news_query = _is_geopolitical_or_news_question(
|
||
question,
|
||
domain=domain,
|
||
news_context=news_context,
|
||
)
|
||
|
||
time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective"
|
||
cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at")
|
||
publish_id: str | None = merged_ctx.get("publish_id")
|
||
as_of: str | None = merged_ctx.get("as_of")
|
||
codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"])
|
||
visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {})
|
||
|
||
ai_ready = False
|
||
provider_name = ""
|
||
model_name = ""
|
||
if ai_client is not None:
|
||
ai_ready, provider_name, model_name = await ai_client.is_ready()
|
||
|
||
compaction = await compact_conversation_history(
|
||
raw_history,
|
||
existing_summary,
|
||
ai_client=ai_client,
|
||
ai_ready=ai_ready,
|
||
)
|
||
compacted_summary = str(compaction.get("summary") or "")
|
||
recent_history = list(compaction.get("recent_messages") or [])
|
||
compacted_flag = bool(compaction.get("compacted"))
|
||
memory_used_flag = bool(compacted_summary or recent_history or clean_memory_notes or clean_pinned_summaries)
|
||
|
||
if workflow_id:
|
||
wf_dict: dict[str, Any] | None = None
|
||
try:
|
||
await ensure_builtin_workflows(db)
|
||
wf_row = (
|
||
await db.execute(select(AIWorkflow).where(AIWorkflow.workflow_id == workflow_id))
|
||
).scalar_one_or_none()
|
||
if wf_row is not None:
|
||
wf_dict = wf_row.to_dict()
|
||
except Exception:
|
||
wf_dict = None
|
||
if wf_dict is None:
|
||
wf_dict = _fallback_workflow_dict(workflow_id)
|
||
|
||
if wf_dict is not None:
|
||
wf_started_at = datetime.now(UTC)
|
||
wf_trace: list[str] = []
|
||
wf_status = "completed"
|
||
wf_error = ""
|
||
wf_answer = ""
|
||
wf_model = str(model_name or "")
|
||
wf_provider = str(provider_name or "")
|
||
wf_revision = int(wf_dict.get("active_revision") or 1)
|
||
wf_scene_zones_count = 0
|
||
run_handle = register_active_run_handle(
|
||
ActiveRunHandle(
|
||
run_id=run_id,
|
||
session_id=session_id_val if session is not None else None,
|
||
actor_key=getattr(access, "actor_key", "anonymous"),
|
||
workflow_id=workflow_id,
|
||
access_tier=getattr(access, "access_tier", "public_zero_cost"),
|
||
question=question[:500],
|
||
started_at=wf_started_at,
|
||
)
|
||
)
|
||
try:
|
||
wf_earth_ctx: dict[str, Any] = {
|
||
**merged_ctx,
|
||
"domain": domain,
|
||
"selected_codes": codes,
|
||
"visible_layers": visible_layers,
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"publish_id": publish_id,
|
||
"as_of": as_of,
|
||
}
|
||
if news_context:
|
||
wf_earth_ctx["news_context"] = news_context
|
||
if clean_memory_notes:
|
||
wf_earth_ctx["user_memory_notes"] = clean_memory_notes
|
||
|
||
effective_client = ai_client
|
||
if ai_ready and ai_client is not None and type(ai_client) is AIProviderClient and ai_client.llm_config:
|
||
cur_max = int(ai_client.llm_config.get("max_tokens") or 0)
|
||
if cur_max < 3200:
|
||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
|
||
|
||
allow_external = getattr(access, "access_tier", "public_zero_cost") == "admin"
|
||
async for item in run_workflow_dag_stream(
|
||
db=db,
|
||
workflow=wf_dict,
|
||
question=question,
|
||
use_draft=False,
|
||
targets=targets,
|
||
earth_context=wf_earth_ctx,
|
||
history=recent_history,
|
||
ai_client=effective_client,
|
||
request=request,
|
||
run_id=run_id,
|
||
allow_external_tools=allow_external,
|
||
cancel_event=run_handle.cancel_event,
|
||
extra_meta={
|
||
"session_id": session_id_val,
|
||
"domain": domain,
|
||
"ai_enabled": ai_ready,
|
||
"provider": provider_name if ai_ready else None,
|
||
"model": model_name if ai_ready else None,
|
||
"compacted": compacted_flag,
|
||
"conversation_summary": compacted_summary,
|
||
"memory_used": memory_used_flag,
|
||
"context_state": {**merged_ctx, "domain": domain},
|
||
**({"session_token": issued_session_token} if issued_session_token else {}),
|
||
},
|
||
):
|
||
if run_handle.cancel_event.is_set() or (
|
||
request is not None and await request.is_disconnected()
|
||
):
|
||
wf_status = "cancelled"
|
||
break
|
||
ev_name = str(item.get("event") or "")
|
||
ev_data = dict(item.get("data") or {})
|
||
if ev_name == "node" and ev_data.get("status") == "completed":
|
||
nid = str(ev_data.get("node_id") or "")
|
||
if nid and nid not in wf_trace:
|
||
wf_trace.append(nid)
|
||
elif ev_name == "scene":
|
||
s_spec = ev_data.get("scene_spec")
|
||
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
|
||
wf_scene_zones_count = len(s_spec["influence_zones"])
|
||
elif ev_name == "done":
|
||
if run_handle.cancel_event.is_set():
|
||
wf_status = "cancelled"
|
||
break
|
||
if isinstance(ev_data.get("nodes"), list):
|
||
wf_trace = [str(n) for n in ev_data["nodes"] if n]
|
||
if ev_data.get("model"):
|
||
wf_model = str(ev_data["model"])
|
||
if ev_data.get("provider"):
|
||
wf_provider = str(ev_data["provider"])
|
||
s_spec = ev_data.get("scene_spec")
|
||
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
|
||
wf_scene_zones_count = len(s_spec["influence_zones"])
|
||
wf_answer = str(ev_data.get("answer_markdown") or "")
|
||
ev_data.setdefault("usage", {})
|
||
ev_data["compacted"] = compacted_flag
|
||
ev_data["conversation_summary"] = compacted_summary
|
||
ev_data["memory_used"] = memory_used_flag
|
||
if session is not None and isinstance(session.context_state, dict):
|
||
base_recent = list(session.context_state.get("recent_messages") or recent_history)
|
||
updated_recent = [*base_recent, {"role": "user", "content": question}]
|
||
if wf_answer:
|
||
updated_recent.append({"role": "assistant", "content": wf_answer[:1800]})
|
||
session.context_state = {
|
||
**session.context_state,
|
||
"conversation_summary": compacted_summary,
|
||
"recent_messages": updated_recent[-8:],
|
||
}
|
||
elif ev_name == "error":
|
||
wf_status = "failed"
|
||
wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error")
|
||
yield _format_sse(ev_name, ev_data)
|
||
if run_handle.cancel_event.is_set():
|
||
wf_status = "cancelled"
|
||
except asyncio.CancelledError:
|
||
wf_status = "cancelled"
|
||
raise
|
||
except Exception as exc:
|
||
wf_status = "failed"
|
||
wf_error = str(exc)
|
||
logger.warning_event(
|
||
"Bound Earth workflow DAG stream failed",
|
||
event="ai_stream.workflow_dag.failed",
|
||
context={"workflow_id": workflow_id, "run_id": run_id, "error": wf_error},
|
||
)
|
||
yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)})
|
||
finally:
|
||
unregister_active_run_handle(run_id)
|
||
try:
|
||
wf_completed_at = datetime.now(UTC)
|
||
wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000))
|
||
db.add(
|
||
WorkflowRun(
|
||
id=run_id,
|
||
session_id=session.id if session is not None else None,
|
||
workflow_id=workflow_id,
|
||
status=wf_status,
|
||
access_tier=getattr(access, "access_tier", "public_zero_cost"),
|
||
actor_key=getattr(access, "actor_key", "anonymous"),
|
||
question=question[:500],
|
||
input_params={
|
||
"domain": domain,
|
||
"targets_count": len(targets or []),
|
||
"source": "earth_copilot",
|
||
},
|
||
tool_trace=wf_trace,
|
||
budget_used={
|
||
"steps": len(wf_trace),
|
||
"model_used": wf_model,
|
||
"provider": wf_provider,
|
||
"latency_ms": wf_latency_ms,
|
||
"workflow_revision": wf_revision,
|
||
"scene_zones_count": wf_scene_zones_count,
|
||
},
|
||
error_message=wf_error[:500],
|
||
started_at=wf_started_at,
|
||
completed_at=wf_completed_at,
|
||
)
|
||
)
|
||
if hasattr(db, "commit"):
|
||
await db.commit()
|
||
schedule_post_run_evolution(workflow_id, run_id)
|
||
except Exception:
|
||
if hasattr(db, "rollback"):
|
||
try:
|
||
await db.rollback()
|
||
except Exception:
|
||
pass
|
||
return
|
||
|
||
view_spec: dict[str, Any] | None = None
|
||
scene_spec: dict[str, Any] | None = None
|
||
evidence: dict[str, Any] = {}
|
||
subject_key = "global"
|
||
revision = 1
|
||
base_answer_md = ""
|
||
context_state: dict[str, Any] = {**merged_ctx, "domain": domain}
|
||
recent_news: dict[str, Any] = {"items": [], "evidence": {}}
|
||
|
||
if news_context or domain == "news":
|
||
news_region = str((news_context or {}).get("region_key") or "").strip() or None
|
||
recent_news = await query_recent_earth_news_tool(db, region=news_region, limit=10)
|
||
global_snap = await query_global_situational_tool(
|
||
db,
|
||
selected_codes=codes,
|
||
visible_layers=visible_layers,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
)
|
||
evidence = {**(recent_news.get("evidence") or {}), **(global_snap.get("evidence") or {})}
|
||
if news_context and news_context.get("url"):
|
||
evidence["ev-news-focus"] = {
|
||
"id": "ev-news-focus",
|
||
"title": str(news_context.get("title") or "聚焦新闻"),
|
||
"publisher": str(news_context.get("source") or "Planet News"),
|
||
"url": str(news_context.get("url") or ""),
|
||
"published_at": str(news_context.get("published_at") or ""),
|
||
"locator": str(news_context.get("region") or news_context.get("region_key") or "news"),
|
||
}
|
||
subject_key = f"news:{(news_context or {}).get('id') or news_region or 'global'}"
|
||
base_answer_md = _build_news_fallback_markdown(
|
||
question=question,
|
||
news_context=news_context,
|
||
recent_news=recent_news,
|
||
ai_configured=ai_ready,
|
||
)
|
||
else:
|
||
base_turn = await execute_session_turn(
|
||
db,
|
||
session=session,
|
||
question=question,
|
||
context_override=context_override,
|
||
prefer_llm=False,
|
||
access=access,
|
||
ai_client=None,
|
||
client_run_id=None,
|
||
)
|
||
view_spec = base_turn.get("view_spec")
|
||
scene_spec = base_turn.get("scene_spec")
|
||
evidence = base_turn.get("evidence") or {}
|
||
subject_key = str(base_turn.get("subject_key") or domain)
|
||
revision = int(base_turn.get("revision") or 1)
|
||
base_answer_md = str((base_turn.get("reply") or {}).get("answer_markdown") or "")
|
||
if isinstance(base_turn.get("context_state"), dict):
|
||
context_state = base_turn["context_state"]
|
||
if domain == "global" and (geo_or_news_query or ai_ready):
|
||
recent_news = await query_recent_earth_news_tool(db, limit=10)
|
||
evidence = {**evidence, **(recent_news.get("evidence") or {})}
|
||
if geo_or_news_query and not is_pure_view:
|
||
# Conversational international/news questions should focus on the narrative, not a static bar chart.
|
||
view_spec = None
|
||
scene_spec = None
|
||
if not ai_ready:
|
||
base_answer_md = _build_news_fallback_markdown(
|
||
question=question,
|
||
news_context=None,
|
||
recent_news=recent_news,
|
||
ai_configured=False,
|
||
)
|
||
|
||
meta_payload: dict[str, Any] = {
|
||
"session_id": session_id_val,
|
||
"run_id": run_id,
|
||
"domain": domain,
|
||
"subject_key": subject_key,
|
||
"revision": revision,
|
||
"ai_enabled": ai_ready and not is_pure_view,
|
||
"provider": provider_name if (ai_ready and not is_pure_view) else None,
|
||
"model": model_name if (ai_ready and not is_pure_view) else None,
|
||
"compacted": compacted_flag,
|
||
"conversation_summary": compacted_summary,
|
||
"memory_used": memory_used_flag,
|
||
"view_spec": view_spec,
|
||
"scene_spec": scene_spec,
|
||
"evidence": evidence,
|
||
"context_state": context_state,
|
||
}
|
||
if issued_session_token:
|
||
meta_payload["session_token"] = issued_session_token
|
||
yield _format_sse("meta", meta_payload)
|
||
|
||
def _persist_session_memory(answer_text: str) -> None:
|
||
if session is None or not isinstance(session.context_state, dict):
|
||
return
|
||
base_recent = list(session.context_state.get("recent_messages") or recent_history)
|
||
updated_recent = [*base_recent, {"role": "user", "content": question}]
|
||
if answer_text:
|
||
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
|
||
session.context_state = {
|
||
**session.context_state,
|
||
"conversation_summary": compacted_summary,
|
||
"recent_messages": updated_recent[-8:],
|
||
}
|
||
|
||
if not ai_ready or is_pure_view or ai_client is None:
|
||
_persist_session_memory(base_answer_md)
|
||
if base_answer_md:
|
||
yield _format_sse("text", {"delta": base_answer_md})
|
||
yield _format_sse(
|
||
"done",
|
||
{
|
||
"status": "completed",
|
||
"generation_mode": "deterministic_baseline",
|
||
"zero_token": True,
|
||
"provider": None,
|
||
"model": None,
|
||
"usage": {},
|
||
"compacted": compacted_flag,
|
||
"conversation_summary": compacted_summary,
|
||
"memory_used": memory_used_flag,
|
||
"answer_markdown": base_answer_md,
|
||
"reasoning_markdown": "",
|
||
},
|
||
)
|
||
return
|
||
|
||
conversation_messages = [
|
||
ChatMessage(role=m["role"], content=m["content"]) for m in recent_history
|
||
]
|
||
thinking_cfg = build_streaming_thinking_config(ai_client)
|
||
effective_client = ai_client
|
||
current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0)
|
||
if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200:
|
||
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
|
||
revision_context: dict[str, Any] | None = None
|
||
if domain == "compute" and is_revision_question(question):
|
||
revision_context = await build_revision_change_context(
|
||
db,
|
||
publish_id=(view_spec or {}).get("publish_id") or publish_id,
|
||
redact=(getattr(access, "tier", "public_zero_cost") != "admin"),
|
||
)
|
||
analysis_req = (
|
||
_build_news_analysis_request(
|
||
question=question,
|
||
news_context=news_context,
|
||
recent_news=recent_news,
|
||
global_snapshot=await query_global_situational_tool(
|
||
db,
|
||
selected_codes=codes,
|
||
visible_layers=visible_layers,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
),
|
||
thinking_cfg=thinking_cfg,
|
||
conversation_messages=conversation_messages,
|
||
conversation_summary=compacted_summary,
|
||
memory_notes=clean_memory_notes,
|
||
pinned_summaries=clean_pinned_summaries,
|
||
)
|
||
if (news_context or domain == "news")
|
||
else _build_telemetry_stream_request(
|
||
domain=domain,
|
||
question=question,
|
||
base_answer_md=base_answer_md,
|
||
evidence=evidence,
|
||
view_spec=view_spec,
|
||
recent_news=recent_news if domain == "global" else None,
|
||
thinking_cfg=thinking_cfg,
|
||
conversation_messages=conversation_messages,
|
||
conversation_summary=compacted_summary,
|
||
memory_notes=clean_memory_notes,
|
||
pinned_summaries=clean_pinned_summaries,
|
||
revision_context=revision_context,
|
||
)
|
||
)
|
||
|
||
text_chunks: list[str] = []
|
||
reasoning_chunks: list[str] = []
|
||
pending_scene_tail = ""
|
||
resolved_provider = provider_name
|
||
resolved_model = model_name
|
||
final_usage: dict[str, Any] = {}
|
||
direct_run_handle = register_active_run_handle(
|
||
ActiveRunHandle(
|
||
run_id=run_id,
|
||
session_id=session_id_val if session is not None else None,
|
||
actor_key=getattr(access, "actor_key", "anonymous"),
|
||
workflow_id=f"stream.{domain}",
|
||
access_tier=getattr(access, "access_tier", "public_zero_cost"),
|
||
question=question[:500],
|
||
started_at=datetime.now(UTC),
|
||
)
|
||
)
|
||
|
||
try:
|
||
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
|
||
if direct_run_handle.cancel_event.is_set() or (
|
||
request is not None and await request.is_disconnected()
|
||
):
|
||
return
|
||
ev_type = str(ev.get("event") or "")
|
||
if ev_type == "start":
|
||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||
resolved_provider = ev["provider"]
|
||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||
resolved_model = ev["model"]
|
||
elif ev_type == "reasoning":
|
||
delta = ev.get("delta")
|
||
if isinstance(delta, str) and delta:
|
||
reasoning_chunks.append(delta)
|
||
yield _format_sse("reasoning", {"delta": delta})
|
||
elif ev_type == "text":
|
||
delta = ev.get("delta")
|
||
if isinstance(delta, str) and delta:
|
||
text_chunks.append(delta)
|
||
combined_buf = pending_scene_tail + delta
|
||
emit_chunk, pending_scene_tail = _consume_text_holding_scene_tag(combined_buf)
|
||
if emit_chunk:
|
||
yield _format_sse("text", {"delta": emit_chunk})
|
||
elif ev_type == "done":
|
||
if isinstance(ev.get("provider"), str) and ev["provider"]:
|
||
resolved_provider = ev["provider"]
|
||
if isinstance(ev.get("model"), str) and ev["model"]:
|
||
resolved_model = ev["model"]
|
||
if isinstance(ev.get("usage"), dict):
|
||
final_usage = ev["usage"]
|
||
elif ev_type == "error":
|
||
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
|
||
|
||
if direct_run_handle.cancel_event.is_set():
|
||
return
|
||
|
||
if pending_scene_tail:
|
||
cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail)
|
||
if cleaned_tail:
|
||
yield _format_sse("text", {"delta": cleaned_tail})
|
||
|
||
combined_text = "".join(text_chunks).strip()
|
||
if not combined_text:
|
||
raise RuntimeError("AI provider stream returned empty response")
|
||
|
||
clean_text, inline_thoughts = strip_thinking_text(combined_text)
|
||
clean_text, parsed_scene = extract_planet_scene_from_text(clean_text or combined_text)
|
||
combined_reasoning = "".join(reasoning_chunks).strip()
|
||
if inline_thoughts:
|
||
extra_thought = "\n\n".join(inline_thoughts)
|
||
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
|
||
|
||
final_answer_md = clean_text or combined_text
|
||
merged_scene_spec: dict[str, Any] | None = dict(scene_spec) if isinstance(scene_spec, dict) else None
|
||
if parsed_scene:
|
||
merged_scene_spec = {**(merged_scene_spec or {}), "domain": (merged_scene_spec or {}).get("domain") or domain, **parsed_scene}
|
||
|
||
_persist_session_memory(final_answer_md)
|
||
if hasattr(db, "commit"):
|
||
try:
|
||
await db.commit()
|
||
except Exception:
|
||
pass
|
||
|
||
if merged_scene_spec is not None and (merged_scene_spec.get("influence_zones") or parsed_scene):
|
||
yield _format_sse("scene", {"scene_spec": merged_scene_spec})
|
||
|
||
done_payload: dict[str, Any] = {
|
||
"status": "completed",
|
||
"generation_mode": "llm_verified",
|
||
"zero_token": False,
|
||
"provider": resolved_provider,
|
||
"model": resolved_model,
|
||
"usage": final_usage,
|
||
"compacted": compacted_flag,
|
||
"conversation_summary": compacted_summary,
|
||
"memory_used": memory_used_flag,
|
||
"answer_markdown": final_answer_md,
|
||
"reasoning_markdown": combined_reasoning,
|
||
}
|
||
if merged_scene_spec is not None:
|
||
done_payload["scene_spec"] = merged_scene_spec
|
||
|
||
yield _format_sse("done", done_payload)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"AI stream turn failed",
|
||
event="ai_stream.llm.fallback",
|
||
context={"domain": domain, "emitted_text": bool(text_chunks), "error": str(exc)},
|
||
)
|
||
if text_chunks:
|
||
yield _format_sse("error", {"detail": str(exc), "partial": True})
|
||
return
|
||
|
||
fallback_md = (
|
||
_build_news_fallback_markdown(
|
||
question=question,
|
||
news_context=news_context,
|
||
recent_news=recent_news,
|
||
ai_configured=True,
|
||
fallback_reason=str(exc),
|
||
)
|
||
if (news_context or domain == "news" or geo_or_news_query)
|
||
else f"{base_answer_md}\n\n> AI 流式研判暂时回退:{exc}".strip()
|
||
)
|
||
if fallback_md:
|
||
yield _format_sse("text", {"delta": fallback_md})
|
||
yield _format_sse(
|
||
"done",
|
||
{
|
||
"status": "completed",
|
||
"generation_mode": "deterministic_fallback",
|
||
"zero_token": True,
|
||
"provider": None,
|
||
"model": None,
|
||
"usage": {},
|
||
"answer_markdown": fallback_md,
|
||
"reasoning_markdown": "".join(reasoning_chunks).strip(),
|
||
"fallback_reason": str(exc),
|
||
},
|
||
)
|
||
finally:
|
||
unregister_active_run_handle(run_id)
|