sync update from LAN repo (source ji @ 85078a31)
This commit is contained in:
1 parent
5d6627af50
commit
e602d88695
864 files changed
+99150
-6346
No files matched your search
@@ -31,6 +31,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any
|
||||
|
||||
@@ -69,6 +70,52 @@ MAX_PARALLEL_AGENTS = 8
|
||||
# a long run of "!!!", which otherwise look non-empty to the UI.
|
||||
MIN_MEANINGFUL_CONTENT_CHARS = 20
|
||||
|
||||
# Long-running read-only skills can be silent while they wait on an upstream
|
||||
# service. Emit user-visible progress often enough to keep proxies and the UI
|
||||
# alive, and fail one seat instead of leaving the whole strategy page pending
|
||||
# forever when the upstream stream has truly stalled.
|
||||
PROGRESS_HEARTBEAT_SECONDS = 5.0
|
||||
AGENT_STREAM_IDLE_TIMEOUT_SECONDS = 180.0
|
||||
|
||||
_TOOL_PROGRESS_LABELS: dict[str, str] = {
|
||||
"search_skills": "正在搜索匹配技能",
|
||||
"skill_list": "正在查找可用技能",
|
||||
"skill_view": "正在读取技能说明",
|
||||
"llmwiki_search": "正在检索知识库",
|
||||
"web_search": "正在检索外部信息",
|
||||
"web_fetch": "正在读取外部资料",
|
||||
"knowledge_search": "正在检索知识资料",
|
||||
"read_file": "正在读取资料",
|
||||
"read_multiple_files": "正在读取多份资料",
|
||||
"ls": "正在查看资料目录",
|
||||
"glob": "正在查找相关资料",
|
||||
"grep": "正在筛选相关内容",
|
||||
}
|
||||
|
||||
|
||||
def _tool_progress_message(name: str, args: dict[str, Any]) -> str:
|
||||
base = _TOOL_PROGRESS_LABELS.get(name, f"正在执行 {name}" if name else "正在执行策略分析步骤")
|
||||
detail = next(
|
||||
(
|
||||
str(value).strip()
|
||||
for value in (
|
||||
args.get("query"),
|
||||
args.get("skill_name"),
|
||||
args.get("skill"),
|
||||
args.get("name"),
|
||||
args.get("path"),
|
||||
)
|
||||
if value is not None and str(value).strip()
|
||||
),
|
||||
"",
|
||||
)
|
||||
if not detail:
|
||||
return base
|
||||
compact = " ".join(detail.split())
|
||||
if len(compact) > 64:
|
||||
compact = f"{compact[:64]}…"
|
||||
return f"{base}:{compact}"
|
||||
|
||||
|
||||
def _has_substantive_content(content: str) -> bool:
|
||||
visible = visible_seat_text(content)
|
||||
@@ -496,15 +543,35 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
inline_thinking = InlineThinkTagFilter(allow_implicit_close=probe_implicit_close)
|
||||
reasoning_emitted = False
|
||||
done_sent = False
|
||||
started_at = time.monotonic()
|
||||
progress_message = "智能体正在分析任务"
|
||||
|
||||
async def _emit_progress_heartbeats() -> None:
|
||||
while not done_sent:
|
||||
await asyncio.sleep(PROGRESS_HEARTBEAT_SECONDS)
|
||||
# A terminal event may have been queued while this task was
|
||||
# sleeping. Never let a late heartbeat move a completed card
|
||||
# back into the running state on the frontend.
|
||||
if done_sent:
|
||||
return
|
||||
await queue.put(
|
||||
{
|
||||
"type": "agent_progress",
|
||||
"agent_id": agent_id,
|
||||
"message": progress_message,
|
||||
"elapsed_seconds": max(0, round(time.monotonic() - started_at)),
|
||||
}
|
||||
)
|
||||
|
||||
async def _emit_text_parts(text: str, provider_reasoning: str = "") -> None:
|
||||
nonlocal reasoning_emitted
|
||||
nonlocal progress_message, reasoning_emitted
|
||||
if text:
|
||||
raw_answer_buffer.append(text)
|
||||
visible_prelude = inline_thinking.confirm_visible_channel() if provider_reasoning else ""
|
||||
visible, inline_reasoning = inline_thinking.push_parts(text)
|
||||
reasoning = f"{provider_reasoning}{inline_reasoning}"
|
||||
if reasoning:
|
||||
progress_message = "正在分析并组织策略"
|
||||
reasoning_emitted = True
|
||||
await queue.put(
|
||||
{
|
||||
@@ -515,6 +582,7 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
)
|
||||
confirmed_visible = f"{visible_prelude}{visible}"
|
||||
if confirmed_visible:
|
||||
progress_message = "正在生成策略正文"
|
||||
buffer.append(confirmed_visible)
|
||||
await queue.put({"type": "delta", "agent_id": agent_id, "text": confirmed_visible})
|
||||
|
||||
@@ -541,6 +609,7 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
空 ``{}`` 占位、真实 args 走 tool_call_chunks 后到,过早发会把空 args 钉死。等累积出
|
||||
完整 args(synthetic)或终态全量 tool_calls(``allow_empty=True``)再发。
|
||||
"""
|
||||
nonlocal progress_message
|
||||
if not isinstance(tc, dict):
|
||||
return
|
||||
name = tc.get("name")
|
||||
@@ -555,14 +624,26 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
if key_id in emitted_tools:
|
||||
return
|
||||
emitted_tools.add(key_id)
|
||||
progress_message = _tool_progress_message(name, args)
|
||||
await queue.put({"type": "step", "agent_id": agent_id, "key": f"tool_calling:{name}", "label": name, "args": args})
|
||||
|
||||
heartbeat_task = asyncio.create_task(_emit_progress_heartbeats())
|
||||
try:
|
||||
thread_id = await _create_thread(client, base, headers, metadata=_ROUNDTABLE_THREAD_METADATA)
|
||||
gen = _run_one_agent( # 只禁文件写入,其余工具放开(保留步骤条)
|
||||
client, base, headers, agent_id, thread_id, new_message, model_name
|
||||
)
|
||||
async for chunk in gen:
|
||||
).__aiter__()
|
||||
while True:
|
||||
try:
|
||||
chunk = await asyncio.wait_for(
|
||||
anext(gen),
|
||||
timeout=AGENT_STREAM_IDLE_TIMEOUT_SECONDS,
|
||||
)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
except TimeoutError as exc:
|
||||
await gen.aclose()
|
||||
raise RuntimeError(f"智能体连续 {int(AGENT_STREAM_IDLE_TIMEOUT_SECONDS)} 秒没有返回进度,已停止本次执行,请重试") from exc
|
||||
if isinstance(chunk, dict):
|
||||
# 终态:先用最终 tool_calls(全量 args)补发漏掉的 step,再发收口/澄清。
|
||||
await _flush_text_filter()
|
||||
@@ -580,6 +661,7 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
}
|
||||
)
|
||||
if chunk.get("type") == "clarification":
|
||||
done_sent = True
|
||||
clar = chunk.get("clarification") or {}
|
||||
await queue.put(
|
||||
{
|
||||
@@ -590,8 +672,8 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
}
|
||||
)
|
||||
else:
|
||||
done_sent = True
|
||||
await queue.put({"type": "agent_done", "agent_id": agent_id, "content": final_content})
|
||||
done_sent = True
|
||||
continue
|
||||
line = chunk.strip() if isinstance(chunk, str) else ""
|
||||
if line.startswith("event:"):
|
||||
@@ -638,6 +720,7 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
raise RuntimeError(f"模型调用失败:{reason_text(failure_reason)}")
|
||||
if not _has_substantive_content(buffered_content):
|
||||
raise RuntimeError("智能体未生成有效正文,请重试或更换全局模型")
|
||||
done_sent = True
|
||||
await queue.put(
|
||||
{
|
||||
"type": "agent_done",
|
||||
@@ -649,6 +732,8 @@ async def run_parallel_agents_stream(request: Request, payload: dict = Body(...)
|
||||
logger.warning("[parallel-agents] %s failed: %r", agent_id, exc)
|
||||
await queue.put({"type": "agent_error", "agent_id": agent_id, "message": str(exc)})
|
||||
finally:
|
||||
heartbeat_task.cancel()
|
||||
await asyncio.gather(heartbeat_task, return_exceptions=True)
|
||||
await queue.put({"type": "__agent_end__", "agent_id": agent_id})
|
||||
|
||||
async def stream_generator() -> AsyncIterator[str]:
|
||||
|
||||
Reference in new issue
Block a user