Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions backend/app/api/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@

logger = logging.getLogger(__name__)

from app.streaming.trace_api import router as trace_router

router = APIRouter()
router.include_router(trace_router)

_MANUAL_COMPACTION_MIN_USAGE_RATIO = 0.5

Expand Down Expand Up @@ -78,13 +81,19 @@ def _on_task_done(task: asyncio.Task[None], *, job: GenerationJob) -> None:

async def _run_with_semaphore(sm: StreamManager, job: GenerationJob, coro) -> None:
"""Run generation under the concurrency semaphore."""
job.trace._emit(job.trace.spans[job.trace.root_id])
queue_span = job.trace.start('生成任务排队', '调度', parent_id=job.trace.root_id)
try:
await asyncio.wait_for(sm._semaphore.acquire(), timeout=30)
except asyncio.TimeoutError:
job.trace.finish(queue_span, 'error')
job.trace.close('error')
coro.close()
job.publish(SSEEvent(AGENT_ERROR, {"error_message": "Server is busy. Please try again shortly."}))
job.complete()
return
try:
job.trace.finish(queue_span)
await coro
finally:
sm._semaphore.release()
Expand Down Expand Up @@ -431,13 +440,17 @@ async def event_generator():


@router.post("/chat/abort")
async def abort_generation(sm: StreamManagerDep, body: AbortRequest) -> dict:
async def abort_generation(sm: StreamManagerDep, body: AbortRequest, session_factory: SessionFactoryDep) -> dict:
"""Abort an active generation."""
job = sm.get_job(body.stream_id)
if job is None:
return {"status": "not_found"}
job.abort()
return {"status": "aborted"}
try:
await job.trace.persist(session_factory)
except Exception:
logger.warning('Failed to persist aborted execution trace', exc_info=True)
return {"status": "aborted", "execution_trace": job.trace.snapshot()}


@router.get("/chat/active")
Expand Down
70 changes: 69 additions & 1 deletion backend/app/mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,75 @@ async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> CallTool
"""Call a tool on the MCP server."""
if self._session is None:
raise RuntimeError(f"MCP server '{self.name}' is not connected")
return await self._session.call_tool(tool_name, arguments)
from app.streaming.trace import current_trace, safe_value
import json
active = current_trace()
if active is None:
return await self._session.call_tool(tool_name, arguments)
trace, parent = active
sent = trace.now()
anchor = None
uncertainty = None

def import_span(raw):
nonlocal anchor, uncertainty
if trace.completed:
return
if not isinstance(raw, dict) or not isinstance(raw.get('id'), str):
return
if anchor is None:
received = trace.now()
anchor = (sent + received) / 2
uncertainty = (received - sent) / 2
key = f'mcp-{parent}-{raw["id"][:64]}'
if len(trace.spans) >= 2000 and key not in trace.spans:
return
try:
start = max(0.0, float(raw['startMs']))
duration = max(0.0, float(raw['durationMs']))
import math
if not math.isfinite(start + duration):
return
except (KeyError, TypeError, ValueError):
return
span = {'id': key, 'parentId': f'mcp-{parent}-{raw["parentId"][:64]}' if raw.get('parentId') else parent,
'name': str(raw.get('name', 'MCP phase'))[:120], 'service': str(raw.get('service', self.name))[:60],
'kind': 'phase', 'startMs': anchor + start, 'durationMs': duration,
'status': raw.get('status') if raw.get('status') in {'ok', 'running', 'error', 'cancelled'} else 'incomplete',
'attributes': {**safe_value(raw.get('attributes') or {}),
'clock': 'remote monotonic; start aligned by first progress RTT midpoint',
'alignment_uncertainty_ms': uncertainty, 'connector': self.name}}
trace.spans[key] = span
trace._emit(span)

async def on_progress(progress, total, message):
if not message or len(message) > 30000:
return
try:
data = json.loads(message)
if data.get('type') == 'codata.trace.v1':
import_span(data.get('span'))
except (ValueError, TypeError, AttributeError):
return

result = await self._session.call_tool(tool_name, arguments, progress_callback=on_progress)
if trace.completed:
return result
meta = getattr(result, 'meta', None) or {}
remote = meta.get('codata_trace') or {}
if anchor is not None and isinstance(remote.get('duration_ms'), (int, float)):
corrected = max(sent, min(anchor, trace.now() - remote['duration_ms']))
shift = corrected - anchor
if shift:
for span in trace.spans.values():
if span['id'].startswith(f'mcp-{parent}-'):
span['startMs'] += shift
trace._emit(span)
anchor = corrected
# Final metadata reconciles missed notifications without duplicating spans.
for span in remote.get('spans', [])[:1000]:
import_span(span)
return result

def tool_id(self, tool_name: str) -> str:
"""Generate a unique tool ID for a tool from this server."""
Expand Down
8 changes: 8 additions & 0 deletions backend/app/provider/openai_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,9 @@ async def stream_chat(
tool_call_accumulators: dict[int, dict[str, Any]] = {}
had_any_content = False # Track whether the stream produced any content

from app.streaming.trace import ProviderTiming
timing = ProviderTiming()
timing_status = 'ok'
try:
stream = await self._client.chat.completions.create(**kwargs)
async for chunk in stream:
Expand All @@ -201,6 +204,8 @@ async def stream_chat(
getattr(delta, "reasoning_content", None)
or getattr(delta, "reasoning", None)
)
if reasoning_text or delta.content or delta.tool_calls:
timing.first_token()
if reasoning_text:
had_any_content = True
yield StreamChunk(type="reasoning-delta", data={"text": reasoning_text})
Expand Down Expand Up @@ -289,8 +294,11 @@ async def stream_chat(
)

except Exception as e:
timing_status = 'error'
logger.error("Stream error for model %s: %s", model, e, exc_info=True)
yield StreamChunk(type="error", data={"message": str(e)})
finally:
timing.finish(timing_status)

def _build_messages(
self,
Expand Down
63 changes: 49 additions & 14 deletions backend/app/session/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
from __future__ import annotations

from typing import Any, AsyncIterator
from contextlib import nullcontext

from app.provider.base import BaseProvider
from app.schemas.agent import AgentInfo
from app.schemas.provider import StreamChunk
from app.tool.registry import ToolRegistry
from app.streaming.trace import trace_span


async def stream_llm(
Expand All @@ -30,6 +32,7 @@ async def stream_llm(
exclude_tools: set[str] | None = None,
discovered_tools: set[str] | None = None,
response_format: dict[str, Any] | None = None,
trace_attributes: dict[str, Any] | None = None,
) -> AsyncIterator[StreamChunk]:
"""Unified LLM streaming call.

Expand All @@ -38,18 +41,50 @@ async def stream_llm(
most providers do not support both simultaneously.
"""
# Resolve tool specs for this agent; disable when structured output is requested
tool_specs = None if response_format else tool_registry.to_openai_specs(
agent, exclude=exclude_tools, discovered=discovered_tools,
from app.streaming.trace import current_trace
import time
attrs = {'model': model_id, 'provider': provider.id, **(trace_attributes or {})}
active = current_trace()
if active and attrs.get('attempt', 1) > 1:
previous = [s for s in active[0].spans.values() if s['kind'] == 'model' and s['attributes'].get('message_id') == attrs.get('message_id')]
if previous:
attrs['retry_of'] = previous[-1]['id']
trace = active[0] if active else None
model_id_span = trace.start('模型响应 / 参数准备', '模型', kind='model', parent_id=active[1], attributes=attrs) if active else ''
# Do not hold a ContextVar token across an async-generator yield: early
# cancellation may close that generator from a different asyncio context.
with trace.bind(model_id_span) if trace else nullcontext():
with trace_span('本地准备与工具协议装配', '调度'):
tool_specs = None if response_format else tool_registry.to_openai_specs(
agent, exclude=exclude_tools, discovered=discovered_tools,
)
stream = provider.stream_chat(
model_id, messages, system=system_prompt, tools=tool_specs if tool_specs else None,
temperature=agent.temperature, max_tokens=max_tokens, extra_body=extra_body,
response_format=response_format,
)

async for chunk in provider.stream_chat(
model_id,
messages,
system=system_prompt,
tools=tool_specs if tool_specs else None,
temperature=agent.temperature,
max_tokens=max_tokens,
extra_body=extra_body,
response_format=response_format,
):
yield chunk
wait_ms = 0.0
status = 'ok'
try:
while True:
started = time.perf_counter_ns()
try:
with trace.bind(model_id_span) if trace else nullcontext():
chunk = await anext(stream)
except StopAsyncIteration:
break
finally:
wait_ms += (time.perf_counter_ns() - started) / 1_000_000
if chunk.type == 'error':
status = 'error'
if trace and chunk.type == 'tool-call':
chunk.data['_trace_model_span_id'] = model_id_span
yield chunk
except BaseException:
status = 'cancelled'
raise
finally:
await stream.aclose()
if trace:
trace.finish(model_id_span, status, provider_await_ms=wait_ms,
duration_note='总跨度含流消费 / 本地调度等待,provider_await_ms 为等待提供商分块累计,不能当独立连续跨度')
24 changes: 23 additions & 1 deletion backend/app/session/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ async def run_generation(
"""
from app.session.prompt import SessionPrompt

job.trace._emit(job.trace.spans[job.trace.root_id])
try:
prompt = SessionPrompt(
job,
Expand All @@ -414,7 +415,8 @@ async def run_generation(
index_manager=index_manager,
skip_user_message=skip_user_message,
)
await prompt.run()
with job.trace.bind():
await prompt.run()
except IntegrityError:
# Session was deleted while generation was in-flight — notify frontend
# so it can exit the generating state, then stop.
Expand All @@ -423,14 +425,26 @@ async def run_generation(
job.session_id,
job.stream_id,
)
job.trace.close('cancelled')
job.publish(SSEEvent(DONE, {
"session_id": job.session_id,
"finish_reason": "aborted",
}))
except Exception:
logger.exception("Generation error for stream %s", job.stream_id)
job.trace.close('error')
try:
await job.trace.persist(session_factory)
except Exception:
logger.warning('Failed to persist failed trace', exc_info=True)
job.publish(SSEEvent(AGENT_ERROR, {"error_message": "An internal error occurred. Please try again."}))
finally:
if not job.trace.completed:
job.trace.close('cancelled' if job.abort_event.is_set() else 'error')
try:
await job.trace.persist(session_factory)
except Exception:
logger.warning('Failed to persist execution trace', exc_info=True)
try:
from app.tool.builtin.todo import clear_in_progress_todos

Expand Down Expand Up @@ -567,6 +581,7 @@ async def process(self) -> Literal["continue", "stop", "compact"]:
exclude_tools=_exclude_tools,
discovered_tools=sp.discovered_tools,
response_format=sp.request.format,
trace_attributes={'step': sp.step, 'attempt': attempt + 1, 'message_id': self._assistant_msg_id},
):
if job.abort_event.is_set():
break
Expand Down Expand Up @@ -698,6 +713,7 @@ async def process(self) -> Literal["continue", "stop", "compact"]:
"tool": _tool.id, "call_id": _ci,
"arguments": _ta, "session_id": job.session_id,
"message_id": self._assistant_msg_id,
"time_start": datetime.datetime.now(datetime.timezone.utc).isoformat(),
}))

# Build context
Expand Down Expand Up @@ -734,6 +750,8 @@ async def process(self) -> Literal["continue", "stop", "compact"]:
tool_name=_tool.id, tool_args=_ta,
call_id=_ci, ctx=_ctx,
timeout=_cfg().tool_timeout,
producer_span_id=str(_tc.get('_trace_model_span_id', '')),
retry_of_call_id=_tc.get('retry_of_call_id'),
))
_exec_metadata[_exec_index] = {
"tool_part_id": _tpid,
Expand Down Expand Up @@ -1092,6 +1110,8 @@ async def process(self) -> Literal["continue", "stop", "compact"]:
"output": result.output[:500] if result.output else "",
"title": result.title,
"metadata": result.metadata,
"time_start": exec_result.time_start,
"time_end": exec_result.time_end,
},
)
)
Expand Down Expand Up @@ -1193,6 +1213,8 @@ async def process(self) -> Literal["continue", "stop", "compact"]:
"output": persist_output,
"title": result.title,
"metadata": result.metadata,
"time_start": exec_result.time_start,
"time_end": exec_result.time_end,
},
},
)
Expand Down
11 changes: 10 additions & 1 deletion backend/app/session/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,9 @@ def system_prompt(self) -> str | list[dict[str, Any]]:

async def run(self) -> None:
"""Main entry point: setup → loop → post-loop."""
await self._setup()
from app.streaming.trace import trace_span
with trace_span('会话校验与上下文装配', '调度'):
await self._setup()
await self._loop()
await self._post_loop()

Expand Down Expand Up @@ -772,10 +774,12 @@ async def _loop(self) -> None:
"agent": self.agent.name,
"model_id": self.model_id,
"provider_id": self.provider.id,
"trace_id": self.job.stream_id,
},
)
self.assistant_msg_id = assistant_msg.id
self.generation_message_ids.append(assistant_msg.id)
self.job.trace.message_ids.append(assistant_msg.id)

# Execute one LLM step — processor handles streaming + tool dispatch
processor: SessionProcessor = SessionProcessor(
Expand Down Expand Up @@ -1215,6 +1219,11 @@ async def _post_loop(self) -> None:
logger.warning("Analysis memory queue submission failed", exc_info=True)

# Publish DONE to unlock the frontend UI.
self.job.trace.close('cancelled' if self.job.abort_event.is_set() else 'error' if self.finish_reason == 'error' else 'ok')
try:
await self.job.trace.persist(self.session_factory)
except Exception:
logger.warning('Failed to persist execution trace', exc_info=True)
self.job.publish(
SSEEvent(
DONE,
Expand Down
Loading
Loading