Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Fix streaming trace emission on cancel/error and improve trace writer shutdown (#9973)
Sarah Wooders807604edf61a
diff --git a/letta/adapters/letta_llm_stream_adapter.py b/letta/adapters/letta_llm_stream_adapter.pyindex 85229d826..b04763dca 100644--- a/letta/adapters/letta_llm_stream_adapter.py+++ b/letta/adapters/letta_llm_stream_adapter.py@@ -1,5 +1,6 @@from __future__ import annotations+import asynciofrom typing import AsyncGeneratorfrom letta.adapters.letta_llm_adapter import LettaLLMAdapter@@ -129,25 +130,6 @@ class LettaLLMStreamAdapter(LettaLLMAdapter):# Start the streaming request (map provider errors to common LLMError types)try:stream = await self.llm_client.stream_async(request_data, self.llm_config)- except Exception as e:- self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()- latency_ms = int((self.llm_request_finish_timestamp_ns - request_start_ns) / 1_000_000)- await self.llm_client.log_provider_trace_async(- request_data=request_data,- response_json=None,- llm_config=self.llm_config,- latency_ms=latency_ms,- error_msg=str(e),- error_type=type(e).__name__,- )- raise self.llm_client.handle_llm_error(e, llm_config=self.llm_config)-- # Process the stream and yield chunks immediately for TTFT- # Wrap in error handling to convert provider errors to common LLMError types- try:- async for chunk in self.interface.process(stream): # TODO: add ttft span- # Yield each chunk immediately as it arrives- yield chunkexcept Exception as e:self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()latency_ms = int((self.llm_request_finish_timestamp_ns - request_start_ns) / 1_000_000)@@ -163,28 +145,65 @@ class LettaLLMStreamAdapter(LettaLLMAdapter):raiseraise self.llm_client.handle_llm_error(e, llm_config=self.llm_config)- # After streaming completes, extract the accumulated data- self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()+ stream_started = True- # Extract tool call from the interfacetry:- self.tool_call = self.interface.get_tool_call_object()- except ValueError:- # No tool call, handle upstream- self.tool_call = None+ # Process the stream and yield chunks immediately for TTFT+ # Wrap in error handling to convert provider errors to common LLMError types+ try:+ async for chunk in self.interface.process(stream): # TODO: add ttft span+ # Yield each chunk immediately as it arrives+ yield chunk+ except BaseException as e:+ self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()+ latency_ms = int((self.llm_request_finish_timestamp_ns - request_start_ns) / 1_000_000)+ await self.llm_client.log_provider_trace_async(+ request_data=request_data,+ response_json=None,+ llm_config=self.llm_config,+ latency_ms=latency_ms,+ error_msg=str(e),+ error_type=type(e).__name__,+ )+ if isinstance(e, asyncio.CancelledError):+ raise+ if isinstance(e, LLMError):+ raise+ raise self.llm_client.handle_llm_error(e, llm_config=self.llm_config)+ else:+ # After streaming completes, extract the accumulated data+ self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()+ finally:+ if not stream_started:+ return++ if self.llm_request_finish_timestamp_ns is None:+ self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()++ # Extract best-effort request results for trace logging+ try:+ self.tool_call = self.interface.get_tool_call_object()+ except Exception:+ self.tool_call = None- # Extract reasoning content from the interface- self.reasoning_content = self.interface.get_reasoning_content()+ try:+ self.reasoning_content = self.interface.get_reasoning_content()+ except Exception:+ self.reasoning_content = []- # Extract usage statistics from the streaming interface- self.usage = self.interface.get_usage_statistics()- self.usage.step_count = 1+ try:+ self.usage = self.interface.get_usage_statistics()+ except Exception:+ pass+ self.usage.step_count = 1- # Store any additional data from the interface- self.message_id = self.interface.letta_message_id+ try:+ self.message_id = self.interface.letta_message_id+ except Exception:+ self.message_id = None- # Log request and response data- self.log_provider_trace(step_id=step_id, actor=actor)+ # Log request and response data+ self.log_provider_trace(step_id=step_id, actor=actor)def supports_token_streaming(self) -> bool:return Truediff --git a/letta/adapters/simple_llm_stream_adapter.py b/letta/adapters/simple_llm_stream_adapter.pyindex f917341fb..901810b6d 100644--- a/letta/adapters/simple_llm_stream_adapter.py+++ b/letta/adapters/simple_llm_stream_adapter.py@@ -1,4 +1,5 @@-from typing import AsyncGenerator, List+import asyncio+from typing import AsyncGeneratorfrom letta.adapters.letta_llm_stream_adapter import LettaLLMStreamAdapterfrom letta.errors import LLMError@@ -13,7 +14,6 @@ from letta.llm_api.openai_client import OpenAIClientfrom letta.otel.tracing import log_attributes, safe_json_dumps, trace_methodfrom letta.schemas.enums import ProviderTypefrom letta.schemas.letta_message import LettaMessage-from letta.schemas.letta_message_content import LettaMessageContentUnionfrom letta.schemas.provider_trace import ProviderTracefrom letta.schemas.user import Userfrom letta.server.rest_api.streaming_response import get_cancellation_event_for_run@@ -166,67 +166,89 @@ class SimpleLLMStreamAdapter(LettaLLMStreamAdapter):raiseraise self.llm_client.handle_llm_error(e, llm_config=self.llm_config)- # Process the stream and yield chunks immediately for TTFT+ stream_started = True+try:- async for chunk in self.interface.process(stream): # TODO: add ttft span- # Yield each chunk immediately as it arrives- yield chunk- except Exception as e:- self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()- latency_ms = int((self.llm_request_finish_timestamp_ns - request_start_ns) / 1_000_000)- await self.llm_client.log_provider_trace_async(- request_data=request_data,- response_json=None,- llm_config=self.llm_config,- latency_ms=latency_ms,- error_msg=str(e),- error_type=type(e).__name__,- )- if isinstance(e, LLMError):- raise- raise self.llm_client.handle_llm_error(e, llm_config=self.llm_config)+ # Process the stream and yield chunks immediately for TTFT+ try:+ async for chunk in self.interface.process(stream): # TODO: add ttft span+ # Yield each chunk immediately as it arrives+ yield chunk+ except BaseException as e:+ self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()+ latency_ms = int((self.llm_request_finish_timestamp_ns - request_start_ns) / 1_000_000)+ await self.llm_client.log_provider_trace_async(+ request_data=request_data,+ response_json=None,+ llm_config=self.llm_config,+ latency_ms=latency_ms,+ error_msg=str(e),+ error_type=type(e).__name__,+ )+ if isinstance(e, asyncio.CancelledError):+ raise+ if isinstance(e, LLMError):+ raise+ raise self.llm_client.handle_llm_error(e, llm_config=self.llm_config)+ else:+ # After streaming completes, extract the accumulated data+ self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()+ finally:+ if not stream_started:+ return- # After streaming completes, extract the accumulated data- self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()+ if self.llm_request_finish_timestamp_ns is None:+ self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns()- # extract tool calls from interface (supports both single and parallel calls)- self.tool_calls = self._extract_tool_calls()- # preserve legacy single-call field for existing consumers- self.tool_call = self.tool_calls[-1] if self.tool_calls else None+ # extract tool calls from interface (supports both single and parallel calls)+ try:+ self.tool_calls = self._extract_tool_calls()+ except Exception:+ self.tool_calls = []+ self.tool_call = self.tool_calls[-1] if self.tool_calls else None- # Extract reasoning content from the interface- # TODO this should probably just be called "content"?- # self.reasoning_content = self.interface.get_reasoning_content()+ # Extract reasoning content from the interface+ # TODO this should probably just be called "content"?+ # self.reasoning_content = self.interface.get_reasoning_content()- # Extract all content parts- self.content: List[LettaMessageContentUnion] = self.interface.get_content()+ # Extract all content parts+ try:+ self.content = self.interface.get_content()+ except Exception:+ self.content = []- # Extract usage statistics from the interface- # Each interface implements get_usage_statistics() with provider-specific logic- self.usage = self.interface.get_usage_statistics()- self.usage.step_count = 1+ # Extract usage statistics from the interface+ # Each interface implements get_usage_statistics() with provider-specific logic+ try:+ self.usage = self.interface.get_usage_statistics()+ except Exception:+ pass+ self.usage.step_count = 1- # Store any additional data from the interface- self.message_id = self.interface.letta_message_id+ # Store any additional data from the interface+ try:+ self.message_id = self.interface.letta_message_id+ except Exception:+ self.message_id = None- # Populate finish_reason for downstream continuation logic.- # In Responses streaming, max_output_tokens is expressed via incomplete_details.reason.- if hasattr(self.interface, "final_response") and self.interface.final_response is not None:- resp = self.interface.final_response- incomplete_details = getattr(resp, "incomplete_details", None)- incomplete_reason = getattr(incomplete_details, "reason", None) if incomplete_details else None- if incomplete_reason == "max_output_tokens":- self._finish_reason = "length"- elif incomplete_reason == "content_filter":- self._finish_reason = "content_filter"- elif incomplete_reason is not None:- # Unknown incomplete reason — preserve it as-is for diagnostics- self._finish_reason = incomplete_reason- elif getattr(resp, "status", None) == "completed":- self._finish_reason = "stop"+ # Populate finish_reason for downstream continuation logic.+ # In Responses streaming, max_output_tokens is expressed via incomplete_details.reason.+ if hasattr(self.interface, "final_response") and self.interface.final_response is not None:+ resp = self.interface.final_response+ incomplete_details = getattr(resp, "incomplete_details", None)+ incomplete_reason = getattr(incomplete_details, "reason", None) if incomplete_details else None+ if incomplete_reason == "max_output_tokens":+ self._finish_reason = "length"+ elif incomplete_reason == "content_filter":+ self._finish_reason = "content_filter"+ elif incomplete_reason is not None:+ # Unknown incomplete reason — preserve it as-is for diagnostics+ self._finish_reason = incomplete_reason+ elif getattr(resp, "status", None) == "completed":+ self._finish_reason = "stop"- # Log request and response data- self.log_provider_trace(step_id=step_id, actor=actor)+ # Log request and response data+ self.log_provider_trace(step_id=step_id, actor=actor)@trace_methoddef log_provider_trace(self, step_id: str | None, actor: User | None) -> None:diff --git a/letta/services/llm_trace_writer.py b/letta/services/llm_trace_writer.pyindex e4c0282b6..e81a1ed16 100644--- a/letta/services/llm_trace_writer.py+++ b/letta/services/llm_trace_writer.py@@ -162,12 +162,30 @@ class LLMTraceWriter:logger.warning(f"LLMTraceWriter: Retry {attempt + 1}/{MAX_RETRIES}, backoff {backoff}s: {e}")await asyncio.sleep(backoff)else:- logger.error(f"LLMTraceWriter: Dropping trace after {MAX_RETRIES} retries: {e}")+ logger.warning(+ "LLMTraceWriter: Dropping trace after %s retries for model=%s step_id=%s: %s",+ MAX_RETRIES,+ trace.model,+ trace.step_id,+ e,+ )async def shutdown_async(self) -> None:"""Gracefully shutdown the writer."""self._shutdown = True+ # Ensure any background write tasks complete before closing the client.+ pending_tasks = [task for task in _background_tasks if not task.done()]+ if pending_tasks:+ logger.warning(+ "LLMTraceWriter: Flushing %s pending trace write task(s) during shutdown",+ len(pending_tasks),+ )+ flush_results = await asyncio.gather(*pending_tasks, return_exceptions=True)+ for result in flush_results:+ if isinstance(result, Exception):+ logger.warning(f"LLMTraceWriter: Background trace write task failed during shutdown: {result}")+# Close clientif self._client:try:@@ -185,6 +203,21 @@ class LLMTraceWriter:self._shutdown = True+ try:+ asyncio.run(self.shutdown_async())+ except Exception as e:+ logger.warning(f"LLMTraceWriter: Async shutdown during atexit failed: {e}")++ if self._client:+ try:+ self._client.close()+ except Exception as inner_error:+ logger.warning(f"LLMTraceWriter: Error closing client during atexit sync fallback: {inner_error}")+ self._client = None+ else:+ return++ # If running inside an active event loop, close only the client as a fallback.if self._client:try:self._client.close()