Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
chore: add more tracing to logging middleware (#8175)
jnjpngca0c2a53704e
diff --git a/letta/otel/tracing.py b/letta/otel/tracing.pyindex d86a2230a..68217f58e 100644--- a/letta/otel/tracing.py+++ b/letta/otel/tracing.py@@ -54,9 +54,7 @@ async def _trace_request_middleware(request: Request, call_next):span.set_attribute("entry.timestamp_ms", int(entry_time * 1000))try:- # This span captures all downstream middleware (CORS, RequestId, Logging) + handler- with tracer.start_as_current_span("middleware.chain"):- response = await call_next(request)+ response = await call_next(request)# Update span name with route pattern after FastAPI has matched the routeroute = request.scope.get("route")@@ -81,36 +79,38 @@ async def _update_trace_attributes(request: Request):if not span:return- # Update span name with route pattern- route = request.scope.get("route")- if route and hasattr(route, "path"):- span.update_name(f"{request.method} {route.path}")-- # Add request info- span.set_attribute("http.method", request.method)- span.set_attribute("http.url", str(request.url))-- # Add path params- for key, value in request.path_params.items():- span.set_attribute(f"http.{key}", value)-- # Add the following headers to span if available- header_attributes = {- "user_id": "user.id",- "x-organization-id": "organization.id",- "x-project-id": "project.id",- "x-agent-id": "agent.id",- "x-template-id": "template.id",- "x-base-template-id": "base_template.id",- "user-agent": "client",- "x-stainless-package-version": "sdk.version",- "x-stainless-lang": "sdk.language",- "x-letta-source": "source",- }- for header_key, span_key in header_attributes.items():- header_value = request.headers.get(header_key)- if header_value:- span.set_attribute(span_key, header_value)+ # Wrap attribute-setting work in a span to measure time before body parsing+ with tracer.start_as_current_span("trace.set_attributes"):+ # Update span name with route pattern+ route = request.scope.get("route")+ if route and hasattr(route, "path"):+ span.update_name(f"{request.method} {route.path}")++ # Add request info+ span.set_attribute("http.method", request.method)+ span.set_attribute("http.url", str(request.url))++ # Add path params+ for key, value in request.path_params.items():+ span.set_attribute(f"http.{key}", value)++ # Add the following headers to span if available+ header_attributes = {+ "user_id": "user.id",+ "x-organization-id": "organization.id",+ "x-project-id": "project.id",+ "x-agent-id": "agent.id",+ "x-template-id": "template.id",+ "x-base-template-id": "base_template.id",+ "user-agent": "client",+ "x-stainless-package-version": "sdk.version",+ "x-stainless-lang": "sdk.language",+ "x-letta-source": "source",+ }+ for header_key, span_key in header_attributes.items():+ header_value = request.headers.get(header_key)+ if header_value:+ span.set_attribute(span_key, header_value)# Add request body if availabletry:diff --git a/letta/server/rest_api/dependencies.py b/letta/server/rest_api/dependencies.pyindex 8f94b06a8..1cc1d02f4 100644--- a/letta/server/rest_api/dependencies.py+++ b/letta/server/rest_api/dependencies.py@@ -3,6 +3,8 @@ from typing import TYPE_CHECKING, Optionalfrom fastapi import Headerfrom pydantic import BaseModel+from letta.otel.tracing import tracer+if TYPE_CHECKING:from letta.server.server import SyncServer@@ -39,25 +41,27 @@ def get_headers(modal_sandbox: Optional[str] = Header(None, alias="X-Experimental-Modal-Sandbox"),) -> HeaderParams:"""Dependency injection function to extract common headers from requests."""- return HeaderParams(- actor_id=actor_id,- user_agent=user_agent,- project_id=project_id,- letta_source=letta_source,- sdk_version=sdk_version,- experimental_params=ExperimentalParams(- message_async=(message_async == "true") if message_async else None,- letta_v1_agent=(letta_v1_agent == "true") if letta_v1_agent else None,- letta_v1_agent_message_async=(letta_v1_agent_message_async == "true") if letta_v1_agent_message_async else None,- modal_sandbox=(modal_sandbox == "true") if modal_sandbox else None,- ),- )+ with tracer.start_as_current_span("dependency.get_headers"):+ return HeaderParams(+ actor_id=actor_id,+ user_agent=user_agent,+ project_id=project_id,+ letta_source=letta_source,+ sdk_version=sdk_version,+ experimental_params=ExperimentalParams(+ message_async=(message_async == "true") if message_async else None,+ letta_v1_agent=(letta_v1_agent == "true") if letta_v1_agent else None,+ letta_v1_agent_message_async=(letta_v1_agent_message_async == "true") if letta_v1_agent_message_async else None,+ modal_sandbox=(modal_sandbox == "true") if modal_sandbox else None,+ ),+ )# TODO: why does this double up the interface?async def get_letta_server() -> "SyncServer":- # Check if a global server is already instantiated- from letta.server.rest_api.app import server+ with tracer.start_as_current_span("dependency.get_letta_server"):+ # Check if a global server is already instantiated+ from letta.server.rest_api.app import server- # assert isinstance(server, SyncServer)- return server+ # assert isinstance(server, SyncServer)+ return serverdiff --git a/letta/server/rest_api/middleware/logging.py b/letta/server/rest_api/middleware/logging.pyindex 5caa043d1..16c33f7cc 100644--- a/letta/server/rest_api/middleware/logging.py+++ b/letta/server/rest_api/middleware/logging.py@@ -36,90 +36,90 @@ class LoggingMiddleware(BaseHTTPMiddleware):with tracer.start_as_current_span("middleware.logging"):# Extract and set log contextcontext = {}-- # Headers- actor_id = request.headers.get("user_id")- if actor_id:- context["actor_id"] = actor_id-- project_id = request.headers.get("x-project-id")- if project_id:- context["project_id"] = project_id-- org_id = request.headers.get("x-organization-id")- if org_id:- context["org_id"] = org_id-- user_agent = request.headers.get("x-agent-id")- if user_agent:- context["agent_id"] = user_agent-- run_id_header = request.headers.get("x-run-id") or request.headers.get("run-id")- if run_id_header:- context["run_id"] = run_id_header-- path = request.url.path- path_parts = [p for p in path.split("/") if p]-- # Path- matched_parts = set()- for part in path_parts:- if part in matched_parts:- continue-- for primitive_type in PrimitiveType:- prefix = primitive_type.value- pattern = PRIMITIVE_ID_PATTERNS.get(prefix)-- if pattern and pattern.match(part):- context_key = f"{primitive_type.name.lower()}_id"-- if primitive_type == PrimitiveType.ORGANIZATION:- context_key = "org_id"- elif primitive_type == PrimitiveType.USER:- context_key = "user_id"-- context[context_key] = part- matched_parts.add(part)- break-- # Query Parameters- for param_value in request.query_params.values():- if param_value in matched_parts:- continue-- for primitive_type in PrimitiveType:- prefix = primitive_type.value- pattern = PRIMITIVE_ID_PATTERNS.get(prefix)-- if pattern and pattern.match(param_value):- context_key = f"{primitive_type.name.lower()}_id"-- if primitive_type == PrimitiveType.ORGANIZATION:- context_key = "org_id"- elif primitive_type == PrimitiveType.USER:- context_key = "user_id"-- # Only set if not already set from path (path takes precedence over query params)- # Query params can overwrite headers, but path values take precedence- if context_key not in context:- context[context_key] = param_value- matched_parts.add(param_value)- break-- if context:- update_log_context(**context)-- logger.debug(- f"Incoming request: {request.method} {request.url.path}",- extra={- "method": request.method,- "url": str(request.url),- "path": request.url.path,- "query_params": dict(request.query_params),- "client_host": request.client.host if request.client else None,- },- )+ with tracer.start_as_current_span("middleware.logging.context"):+ # Headers+ actor_id = request.headers.get("user_id")+ if actor_id:+ context["actor_id"] = actor_id++ project_id = request.headers.get("x-project-id")+ if project_id:+ context["project_id"] = project_id++ org_id = request.headers.get("x-organization-id")+ if org_id:+ context["org_id"] = org_id++ user_agent = request.headers.get("x-agent-id")+ if user_agent:+ context["agent_id"] = user_agent++ run_id_header = request.headers.get("x-run-id") or request.headers.get("run-id")+ if run_id_header:+ context["run_id"] = run_id_header++ path = request.url.path+ path_parts = [p for p in path.split("/") if p]++ # Path+ matched_parts = set()+ for part in path_parts:+ if part in matched_parts:+ continue++ for primitive_type in PrimitiveType:+ prefix = primitive_type.value+ pattern = PRIMITIVE_ID_PATTERNS.get(prefix)++ if pattern and pattern.match(part):+ context_key = f"{primitive_type.name.lower()}_id"++ if primitive_type == PrimitiveType.ORGANIZATION:+ context_key = "org_id"+ elif primitive_type == PrimitiveType.USER:+ context_key = "user_id"++ context[context_key] = part+ matched_parts.add(part)+ break++ # Query Parameters+ for param_value in request.query_params.values():+ if param_value in matched_parts:+ continue++ for primitive_type in PrimitiveType:+ prefix = primitive_type.value+ pattern = PRIMITIVE_ID_PATTERNS.get(prefix)++ if pattern and pattern.match(param_value):+ context_key = f"{primitive_type.name.lower()}_id"++ if primitive_type == PrimitiveType.ORGANIZATION:+ context_key = "org_id"+ elif primitive_type == PrimitiveType.USER:+ context_key = "user_id"++ # Only set if not already set from path (path takes precedence over query params)+ # Query params can overwrite headers, but path values take precedence+ if context_key not in context:+ context[context_key] = param_value+ matched_parts.add(param_value)+ break++ if context:+ update_log_context(**context)++ logger.debug(+ f"Incoming request: {request.method} {request.url.path}",+ extra={+ "method": request.method,+ "url": str(request.url),+ "path": request.url.path,+ "query_params": dict(request.query_params),+ "client_host": request.client.host if request.client else None,+ },+ )response = await call_next(request)return responsediff --git a/letta/server/rest_api/middleware/request_id.py b/letta/server/rest_api/middleware/request_id.pyindex 70fd2cbb4..9e51bbcf5 100644--- a/letta/server/rest_api/middleware/request_id.py+++ b/letta/server/rest_api/middleware/request_id.py@@ -63,4 +63,4 @@ class RequestIdMiddleware:# This is accessible via request.state.request_id throughout the request lifecyclerequest.state.request_id = request_id- await self.app(scope, receive, send)+ await self.app(scope, receive, send)