feat(provider): langfuse tracing for codex (#5520)

* feat: trace Codex requests via Langfuse native SDK

Codex has no OpenAI SDK client for Langfuse's usual swap trick, so
log one generation per request through langfuse's native SDK
instead. Tracing failures never affect the returned Codex response.

* docs: note Codex Langfuse tracing support

* fix: trace every Codex request, close every generation

- Move the Langfuse generation inside _send so the compaction
  sub-request gets its own trace too, not just the main request.
- Derive traced model/input from the wire body (post extra_body
  override, post response-item-ID stripping) instead of the
  pre-normalized one.
- Wrap package detection in the same try/except as the SDK call, so
  a broken find_spec() can't turn a valid Codex request into an error.
- Make generation finalization idempotent and cancellation-safe via
  try/except/else/finally, so update() failures or a cancelled
  request no longer leave a generation open.
- Add tests for compaction tracing, update() failures, and
  cancellation.

* docs: fix cli-reference.md langfuse plugin row

* fix: don't trace a rejected compaction as success

- Add a validate hook to _send so a transport-successful compaction
  reply with no usable item traces as an error, not a success.
- Add regression tests for a find_spec() failure, for the traced
  model/input matching the actual wire body (extra_body override,
  ID-stripped replayed items), and for the rejected-compaction case.

* fix: convert LLMUsage to dict for Langfuse usage_details

LLMResponse.usage is now the LLMUsage dataclass upstream, not a
plain dict - Langfuse's usage_details param needs the latter.

* fix: satisfy basedpyright strict on compaction items

* fix(providers): normalize Codex Langfuse cache usage

* fix(providers): migrate Langfuse tracing to SDK 4

---------

Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
akinolurandchengyongru authored and GitHub committed 2026-10-16 00:44:17 +08:00
1 parent a148eabc9f
commit 9d2762a4f1
12 files changed
+761 -66

No files matched your search

+176 -39
View File
@@ -6,7 +6,9 @@ from __future__ import annotations
import asyncio
import hashlib
import importlib.util
import json
import os
import re
import ssl
from collections.abc import Awaitable, Callable
@@ -23,6 +25,7 @@ from nanobot.providers.base import (
CONTEXT_SAFETY_BUFFER,
LLMProvider,
LLMResponse,
LLMUsage,
ProviderCallContext,
ProviderConversationState,
)
@@ -38,7 +41,10 @@ from nanobot.providers.openai_responses import (
ResponsesWebSocketOptions,
responses_state_matches,
)
from nanobot.providers.openai_responses.state import without_response_item_ids
from nanobot.providers.openai_responses.state import (
responses_compaction_items,
without_response_item_ids,
)
from nanobot.providers.openai_responses.websocket import ResponsesWebSocketError
from nanobot.providers.registry import ProviderModelSpec, find_by_name
from nanobot.utils.helpers import estimate_prompt_tokens
@@ -50,6 +56,114 @@ OPENAI_CODEX_CATALOG_CLIENT_VERSION = "99.99.99"
DEFAULT_ORIGINATOR = "nanobot"
_LANGFUSE_TRACE_WARNING = "Langfuse tracing failed for Codex request: {}"
def _usage_details(usage: LLMUsage | None) -> dict[str, int] | None:
"""Split inclusive input usage into Langfuse's exclusive token buckets."""
if usage is None:
return None
cached_tokens = (usage.cache_read_tokens or 0) + (usage.cache_write_tokens or 0)
details = {
"input": usage.input_tokens - cached_tokens,
"output": usage.output_tokens,
"total": usage.total_tokens,
}
if usage.cache_read_tokens is not None:
details["input_cached_tokens"] = usage.cache_read_tokens
if usage.cache_write_tokens is not None:
details["input_cache_creation"] = usage.cache_write_tokens
return details
class _CodexGenerationTracer:
"""Best-effort Langfuse updates; the request owns generation closure."""
def __init__(self, generation: Any | None) -> None:
self._generation = generation
def record_success(self, result: LLMResponse) -> None:
output: Any = result.content
if result.tool_calls:
output = {
"content": result.content,
"tool_calls": [
{"name": call.name, "arguments": call.arguments} for call in result.tool_calls
],
}
self._update(output=output, usage_details=_usage_details(result.usage))
def record_error(self, response: LLMResponse) -> None:
self._update(
output=response.content,
level="ERROR",
status_message=response.content,
)
def _update(self, **kwargs: Any) -> None:
generation = self._generation
filtered = {k: v for k, v in kwargs.items() if v is not None}
if generation is None or not filtered:
return
try:
generation.update(**filtered)
except Exception as exc:
logger.warning(_LANGFUSE_TRACE_WARNING, exc)
def close(self) -> None:
generation = self._generation
if generation is None:
return
try:
generation.end()
except Exception as exc:
logger.warning(_LANGFUSE_TRACE_WARNING, exc)
def _start_codex_langfuse_generation(
*,
name: str,
model: str,
body: dict[str, Any],
) -> _CodexGenerationTracer:
"""Start a Langfuse generation for a Codex request, or a no-op tracer.
Detection and the SDK call share one try/except so a broken
``find_spec`` can't fail the Codex request itself.
"""
try:
if os.environ.get("LANGFUSE_SECRET_KEY") and importlib.util.find_spec("langfuse"):
from langfuse import get_client
langfuse = get_client()
generation = langfuse.start_observation(
name=name,
as_type="generation",
model=model,
input={
"instructions": body.get("instructions"),
"input": body.get("input"),
"tools": body.get("tools"),
},
model_parameters={
key: body[key]
for key in ("reasoning", "tool_choice", "text", "parallel_tool_calls")
if key in body
},
)
return _CodexGenerationTracer(generation)
if os.environ.get("LANGFUSE_SECRET_KEY"):
logger.warning(
"LANGFUSE_SECRET_KEY is set but langfuse is not installed; "
"run `nanobot plugins enable langfuse` to enable tracing"
)
return _CodexGenerationTracer(None)
except Exception as exc:
logger.warning(_LANGFUSE_TRACE_WARNING, exc)
return _CodexGenerationTracer(None)
class OpenAICodexProvider(LLMProvider):
"""Use Codex OAuth to call the Responses API."""
@@ -176,52 +290,75 @@ class OpenAICodexProvider(LLMProvider):
request_body: dict[str, Any],
*,
emit_deltas: bool,
trace_name: str,
validate: Callable[[LLMResponse], object] | None = None,
) -> LLMResponse:
wire_body = await prepare_inline_images(without_response_item_ids(request_body))
if session_id:
websocket_result = await self._responses.websocket_request(
session_id, DEFAULT_CODEX_URL, headers, wire_body,
provider=self._responses_state_provider(),
verify=self._ssl_context(verify=True), proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
if websocket_result is not None:
return websocket_result
tracer = _start_codex_langfuse_generation(
name=trace_name,
model=_strip_model_prefix(str(wire_body.get("model") or model)),
body=wire_body,
)
try:
return await _request_codex(
DEFAULT_CODEX_URL,
headers,
wire_body,
verify=self._ssl_context(verify=True),
proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
result = None
if session_id:
result = await self._responses.websocket_request(
session_id, DEFAULT_CODEX_URL, headers, wire_body,
provider=self._responses_state_provider(),
verify=self._ssl_context(verify=True), proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
if result is None:
try:
result = await _request_codex(
DEFAULT_CODEX_URL,
headers,
wire_body,
verify=self._ssl_context(verify=True),
proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
except Exception as exc:
if "CERTIFICATE_VERIFY_FAILED" not in str(exc):
raise
logger.warning(
"SSL verification failed for Codex API; retrying with verify=False"
)
result = await _request_codex(
DEFAULT_CODEX_URL,
headers,
wire_body,
verify=self._ssl_context(verify=False),
proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
if validate is not None:
validate(result)
except Exception as exc:
if "CERTIFICATE_VERIFY_FAILED" not in str(exc):
raise
logger.warning(
"SSL verification failed for Codex API; retrying with verify=False"
)
return await _request_codex(
DEFAULT_CODEX_URL,
headers,
wire_body,
verify=self._ssl_context(verify=False),
proxy=self.proxy,
on_content_delta=on_content_delta if emit_deltas else None,
on_thinking_delta=on_thinking_delta if emit_deltas else None,
on_tool_call_delta=on_tool_call_delta if emit_deltas else None,
)
tracer.record_error(_codex_error_response(exc))
raise
else:
tracer.record_success(result)
return result
finally:
tracer.close()
if self.supports_native_compaction(model) and replayed and sanitized_state is not None:
stage = "codex_compaction"
async def send_compaction(request: dict[str, Any]) -> LLMResponse:
return await _send(request, emit_deltas=False)
return await _send(
request,
emit_deltas=False,
trace_name="codex_compaction",
validate=responses_compaction_items,
)
native_compaction_state = await self._responses.compact_before_request(
body, state=sanitized_state,
@@ -249,7 +386,7 @@ class OpenAICodexProvider(LLMProvider):
preserve_provider_state_on_error=True,
)
stage = "codex_request"
result = await _send(body, emit_deltas=True)
result = await _send(body, emit_deltas=True, trace_name="codex_request")
result.provider_compaction_applied = (
result.provider_compaction_applied or native_compaction_applied
)
@@ -36,6 +36,7 @@ from nanobot.providers.openai_responses.state import (
is_compaction_compatibility_error,
prepare_responses_input,
resolve_compact_threshold,
responses_compaction_items,
responses_state_context_tokens,
responses_state_items,
)
@@ -173,14 +174,7 @@ class ResponsesBackend:
history, delta = split_compaction_input(history, items[len(history):])
try:
compacted = await send({**body, "input": [*history, {"type": "compaction_trigger"}]})
compact_items = (
responses_state_items(compacted.provider_state)
if compacted.provider_state is not None else None
)
if not compact_items or compact_items[-1].get("type") not in {
"compaction", "compaction_summary", "context_compaction",
}:
raise RuntimeError("Responses compaction returned no compaction item")
compact_items = responses_compaction_items(compacted)
body["input"] = [*retained_compaction_messages(history), *compact_items, *delta]
return build_responses_compaction_state(
provider=provider, model=model, output_items=compact_items,
@@ -171,6 +171,14 @@ def responses_state_context_tokens(state: ProviderConversationState) -> int:
return max(0, value)
def responses_compaction_items(result: LLMResponse) -> list[dict[str, Any]]:
"""Return replay items ending at a valid trigger-compaction boundary."""
items = responses_state_items(result.provider_state) if result.provider_state is not None else None
if not items or items[-1].get("type") not in _COMPACTION_ITEM_TYPES:
raise RuntimeError("Responses compaction returned no compaction item")
return items
def resolve_compact_threshold(
context_window_tokens: int | None,
max_output_tokens: int,