From 9d2762a4f1801753f3d0d555a23cb46385c41bdb Mon Sep 17 00:00:00 2001 From: akinolur <126256260+akinolur@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:44:17 +0200 Subject: [PATCH] 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 --- docs/cli-reference.md | 2 +- docs/configuration.md | 6 +- .../configure-langfuse-observability.md | 8 +- docs/provider-cookbook.md | 6 +- docs/troubleshooting.md | 2 +- nanobot/providers/openai_codex_provider.py | 215 +++++++-- nanobot/providers/openai_responses/backend.py | 10 +- nanobot/providers/openai_responses/state.py | 8 + pyproject.toml | 2 +- tests/channels/test_channel_plugins.py | 2 +- tests/providers/test_openai_codex_langfuse.py | 456 ++++++++++++++++++ .../providers/test_openai_codex_websocket.py | 110 ++++- 12 files changed, 761 insertions(+), 66 deletions(-) create mode 100644 tests/providers/test_openai_codex_langfuse.py diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 65c3ea8c0..346902562 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -294,7 +294,7 @@ The `plugins` command name is retained for compatibility, but these entries are | `api` | Dependencies required by the OpenAI-compatible `nanobot serve` process | | `azure` | Azure identity support for Azure-hosted models | | `bedrock` | AWS Bedrock model provider support | -| `langfuse` | Langfuse tracing support for OpenAI-compatible providers | +| `langfuse` | Langfuse tracing support for OpenAI-compatible providers and the Codex OAuth provider | | `olostep` | Olostep web search provider support | | A channel name such as `telegram` or `slack` | The connector package and saved channel enablement | diff --git a/docs/configuration.md b/docs/configuration.md index 9d6fd385f..fcaac4ac8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -212,7 +212,7 @@ Internal variables such as `NANOBOT_RESTART_*` and `NANOBOT_PATH_*` are set by n ## Langfuse Observability -nanobot can trace OpenAI-compatible provider calls through Langfuse's OpenAI SDK wrapper. This is configured with environment variables, not `config.json`. +nanobot can trace OpenAI-compatible provider calls through Langfuse's OpenAI SDK wrapper, and Codex OAuth provider calls through Langfuse's native Python SDK. This is configured with environment variables, not `config.json`. Install the optional package in the same Python environment that runs nanobot: @@ -236,11 +236,11 @@ $env:LANGFUSE_PUBLIC_KEY = "pk-lf-..." $env:LANGFUSE_BASE_URL = "https://cloud.langfuse.com" ``` -When `LANGFUSE_SECRET_KEY` is set and the `langfuse` package is installed, nanobot uses `langfuse.openai.AsyncOpenAI` for OpenAI-compatible providers so model requests are sent to Langfuse in the background. If the secret key is set but `langfuse` is missing, nanobot logs a warning and falls back to the regular OpenAI client. +When `LANGFUSE_SECRET_KEY` is set and the `langfuse` package is installed, nanobot uses `langfuse.openai.AsyncOpenAI` for OpenAI-compatible providers so model requests are sent to Langfuse in the background. If the secret key is set but `langfuse` is missing, nanobot logs a warning and falls back to the regular OpenAI client. The Codex OAuth provider (`openai_codex`) uses the same `LANGFUSE_SECRET_KEY` check but logs each request through Langfuse's native SDK directly, since Codex does not use the OpenAI Python SDK client. Use the Langfuse region or self-hosted URL that matches your project. The [Langfuse OpenAI SDK docs](https://langfuse.com/integrations/model-providers/openai-py) use `LANGFUSE_BASE_URL` for cloud regions and self-hosted instances. -Tracing covers the providers that go through nanobot's OpenAI-compatible client path. Native providers that do not use that client may not produce Langfuse OpenAI-wrapper traces. +Tracing covers the providers that go through nanobot's OpenAI-compatible client path, plus the Codex OAuth provider (`openai_codex`) via Langfuse's native SDK. Other native providers that do not use either path may not produce Langfuse traces. ## Providers diff --git a/docs/guides/configure-langfuse-observability.md b/docs/guides/configure-langfuse-observability.md index d167af788..e5e985d71 100644 --- a/docs/guides/configure-langfuse-observability.md +++ b/docs/guides/configure-langfuse-observability.md @@ -1,6 +1,6 @@ # How to Configure Langfuse Observability for nanobot -nanobot can trace supported OpenAI-compatible provider calls through Langfuse's OpenAI SDK wrapper. +nanobot can trace supported OpenAI-compatible provider calls through Langfuse's OpenAI SDK wrapper, and Codex OAuth provider calls through Langfuse's native Python SDK. ## What you will build @@ -22,6 +22,8 @@ Install Langfuse: nanobot plugins enable langfuse ``` +nanobot uses Langfuse Python SDK 4.7 or later in the 4.x series. Tracing supports Langfuse Cloud and self-hosted Langfuse 3.63.0 or later. The SDK enables real-time ingestion on Langfuse v4 automatically; see [Langfuse compatibility](https://langfuse.com/docs/compatibility). + ## Minimal working example Set credentials before starting nanobot: @@ -47,7 +49,7 @@ nanobot agent -m "Hello!" - Langfuse is configured with environment variables, not `config.json`. - Start services from an environment that exports the same variables. - Add tracing after the provider works; it should not be the first setup step. -- Native providers that do not use the OpenAI-compatible client path may not produce Langfuse OpenAI-wrapper traces. +- Native providers other than Codex OAuth that do not use the OpenAI-compatible client path may not produce Langfuse traces. ## Security notes @@ -58,7 +60,7 @@ nanobot agent -m "Hello!" ## Troubleshooting - If no traces appear, confirm the service process sees the environment variables. -- Confirm the provider path is OpenAI-compatible. +- Confirm the provider path is OpenAI-compatible or the Codex OAuth provider. - Run one local `nanobot agent -m "Hello!"` call before debugging service logs. ## Related nanobot docs diff --git a/docs/provider-cookbook.md b/docs/provider-cookbook.md index c88ef77b0..fcece98c3 100644 --- a/docs/provider-cookbook.md +++ b/docs/provider-cookbook.md @@ -608,7 +608,7 @@ Keep fallback candidates realistic. If the local fallback has a smaller context ## Recipe: Langfuse Tracing -This recipe applies after the agent works and you want observability for OpenAI-compatible provider calls. +This recipe applies after the agent works and you want observability for OpenAI-compatible provider calls, or for the Codex OAuth provider. Install the optional package in the same Python environment that runs nanobot: @@ -634,7 +634,7 @@ $env:LANGFUSE_BASE_URL = "https://cloud.langfuse.com" nanobot agent -m "Hello!" ``` -Langfuse is not a model provider in `config.json`. It is configured through environment variables and traces supported OpenAI-compatible provider calls. Native providers that do not use that client path may not produce Langfuse OpenAI-wrapper traces. +Langfuse is not a model provider in `config.json`. It is configured through environment variables and traces supported OpenAI-compatible provider calls, plus Codex OAuth provider calls via Langfuse's native SDK. Other native providers that do not use either path may not produce Langfuse traces. ## Recipe: Switch Models at Runtime @@ -687,7 +687,7 @@ In chat: | `model not found` | The model ID does not belong to the selected provider or gateway | Compare `modelPresets..provider` and `modelPresets..model` | | `connection refused` | Local server is not running or `apiBase` has the wrong port/path | Run `curl /models` | | `provider not found` | Provider name is misspelled or uses the config key instead of registry name | Use names such as `openrouter`, `openai`, `anthropic`, `ollama`, `vllm`, `lm_studio` | -| Langfuse shows no traces | Env vars are missing, `langfuse` is not installed in the active Python environment, or the provider path is native | Run `python -m pip show langfuse` and restart nanobot from the same environment | +| Langfuse shows no traces | Env vars are missing, `langfuse` is not installed in the active Python environment, or the provider path is a native provider other than Codex OAuth | Run `python -m pip show langfuse` and restart nanobot from the same environment | ## Next References diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index a6cfe7848..a1b74ba05 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -192,7 +192,7 @@ Langfuse tracing is optional and controlled by environment variables. | `LANGFUSE_SECRET_KEY is set but langfuse is not installed` | Install `langfuse` in the same Python environment that runs nanobot, then restart the process. | | No traces appear | Set `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, and `LANGFUSE_BASE_URL` before starting nanobot. | | Wrong Langfuse project or region | Check that the key pair and `LANGFUSE_BASE_URL` come from the same Langfuse project/region. | -| Only some providers trace | Langfuse tracing applies to OpenAI-compatible provider calls; native providers may not use that client path. | +| Only some providers trace | Langfuse tracing applies to OpenAI-compatible provider calls and the Codex OAuth provider; other native providers may not use either client path. | See [`configuration.md#langfuse-observability`](./configuration.md#langfuse-observability) for setup commands. diff --git a/nanobot/providers/openai_codex_provider.py b/nanobot/providers/openai_codex_provider.py index 4f91cd8d9..a65052943 100644 --- a/nanobot/providers/openai_codex_provider.py +++ b/nanobot/providers/openai_codex_provider.py @@ -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 ) diff --git a/nanobot/providers/openai_responses/backend.py b/nanobot/providers/openai_responses/backend.py index 4cea9dddd..a5ddf6cb5 100644 --- a/nanobot/providers/openai_responses/backend.py +++ b/nanobot/providers/openai_responses/backend.py @@ -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, diff --git a/nanobot/providers/openai_responses/state.py b/nanobot/providers/openai_responses/state.py index 5835add7e..96fd488f7 100644 --- a/nanobot/providers/openai_responses/state.py +++ b/nanobot/providers/openai_responses/state.py @@ -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, diff --git a/pyproject.toml b/pyproject.toml index b0eab77e5..1e11fd46a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -86,7 +86,7 @@ documents = [ "python-pptx>=1.0.0,<2.0.0", ] langfuse = [ - "langfuse>=3.0.0,<4.0.0", + "langfuse>=4.7.0,<5.0.0", ] pdf = [ # Compatibility extra: PDF reading is bundled since v0.2.3. diff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.py index 6f27dd4f5..439bbd18c 100644 --- a/tests/channels/test_channel_plugins.py +++ b/tests/channels/test_channel_plugins.py @@ -2670,7 +2670,7 @@ def test_optional_dependency_metadata_for_enable(): "python-pptx>=1.0.0,<2.0.0", ] assert deps["pdf"] == ["pypdf>=5.0.0,<6.0.0"] - assert deps["langfuse"] == ["langfuse>=3.0.0,<4.0.0"] + assert deps["langfuse"] == ["langfuse>=4.7.0,<5.0.0"] assert deps["olostep"] == ["olostep>=0.1.0; python_version < '3.14'"] expected_olostep_args = [] if sys.version_info >= (3, 14) else ["olostep>=0.1.0"] assert optional_features.install_args_for_extra("olostep", deps["olostep"]) == ( diff --git a/tests/providers/test_openai_codex_langfuse.py b/tests/providers/test_openai_codex_langfuse.py new file mode 100644 index 000000000..d2b2c96f0 --- /dev/null +++ b/tests/providers/test_openai_codex_langfuse.py @@ -0,0 +1,456 @@ +import asyncio +import sys +import types +from importlib.machinery import ModuleSpec +from types import SimpleNamespace +from typing import Any + +import pytest + +import nanobot.providers.base as provider_base +from nanobot.providers.openai_codex_provider import OpenAICodexProvider, _CodexHTTPError +from nanobot.providers.openai_responses import build_responses_state + +LANGFUSE_MISSING_WARNING = ( + "LANGFUSE_SECRET_KEY is set but langfuse is not installed; " + "run `nanobot plugins enable langfuse` to enable tracing" +) + + +def _mock_codex_token(monkeypatch: pytest.MonkeyPatch) -> None: + def fake_token(**_kwargs): + return SimpleNamespace(account_id="acct", access="token") + + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider.get_codex_token", + fake_token, + ) + + +class _WarningCaptureLogger: + def __init__(self) -> None: + self.calls: list[tuple[str, tuple[Any, ...]]] = [] + + def warning(self, *args: Any, **kwargs: Any) -> None: + self.calls.append((args[0], args[1:])) + + def exception(self, message: str, *args: Any, **kwargs: Any) -> None: + raise AssertionError("Codex diagnostics must not log exception tracebacks") + + +def _capture_codex_warnings(monkeypatch: pytest.MonkeyPatch) -> _WarningCaptureLogger: + capture = _WarningCaptureLogger() + monkeypatch.setattr("nanobot.providers.openai_codex_provider.logger", capture) + return capture + + +class _FakeGeneration: + def __init__(self, start_kwargs: dict[str, Any]) -> None: + self.start_kwargs = start_kwargs + self.update_calls: list[dict[str, Any]] = [] + self.end_calls = 0 + + def update(self, **kwargs: Any) -> None: + self.update_calls.append(kwargs) + + def end(self) -> None: + self.end_calls += 1 + + +def _install_fake_langfuse(monkeypatch: pytest.MonkeyPatch, start_observation) -> None: + """Insert a fake ``langfuse`` module so ``from langfuse import get_client`` resolves.""" + fake_module = types.ModuleType("langfuse") + fake_module.__spec__ = ModuleSpec("langfuse", loader=None) + fake_module.get_client = lambda: SimpleNamespace(start_observation=start_observation) # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "langfuse", fake_module) + + +@pytest.fixture +def generations(monkeypatch): + monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret") + _mock_codex_token(monkeypatch) + generations: list[_FakeGeneration] = [] + + def start_observation(**kwargs: Any) -> _FakeGeneration: + gen = _FakeGeneration(kwargs) + generations.append(gen) + return gen + + _install_fake_langfuse(monkeypatch, start_observation) + return generations + + +async def _fake_request_success(*_args, **_kwargs) -> provider_base.LLMResponse: + return provider_base.LLMResponse( + content="hello", + usage=provider_base.LLMUsage.reported(input_tokens=1, output_tokens=2, total_tokens=3), + ) + + +async def test_codex_langfuse_missing_package_warns_and_call_still_succeeds(monkeypatch) -> None: + monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret") + monkeypatch.setattr("importlib.util.find_spec", lambda name: None) + capture = _capture_codex_warnings(monkeypatch) + _mock_codex_token(monkeypatch) + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", _fake_request_success + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.content == "hello" + assert capture.calls == [(LANGFUSE_MISSING_WARNING, ())] + + +async def test_codex_langfuse_disabled_when_env_var_unset(monkeypatch) -> None: + monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False) + capture = _capture_codex_warnings(monkeypatch) + _mock_codex_token(monkeypatch) + find_spec_calls: list[str] = [] + monkeypatch.setattr( + "importlib.util.find_spec", + lambda name: find_spec_calls.append(name), + ) + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", _fake_request_success + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.content == "hello" + assert capture.calls == [] + assert find_spec_calls == [] # short-circuited before ever checking the package + + +@pytest.mark.parametrize( + ("cache_counts", "expected_usage_details"), + [ + ({}, {"input": 100, "output": 20, "total": 120}), + ( + {"cache_read_tokens": 0}, + {"input": 100, "output": 20, "total": 120, "input_cached_tokens": 0}, + ), + ( + {"cache_read_tokens": 80}, + {"input": 20, "output": 20, "total": 120, "input_cached_tokens": 80}, + ), + ( + {"cache_write_tokens": 20}, + {"input": 80, "output": 20, "total": 120, "input_cache_creation": 20}, + ), + ], + ids=["unreported-cache", "zero-cache", "cache-read", "cache-write"], +) +async def test_codex_langfuse_success_records_generation_with_expected_fields( + monkeypatch, generations, cache_counts, expected_usage_details, +) -> None: + async def fake_request(*_args, **_kwargs): + return provider_base.LLMResponse( + content="hello", + usage=provider_base.LLMUsage.reported( + input_tokens=100, output_tokens=20, total_tokens=120, **cache_counts, + ), + ) + + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", fake_request + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.content == "hello" + assert len(generations) == 1 + gen = generations[0] + assert gen.start_kwargs["name"] == "codex_request" + assert gen.start_kwargs["as_type"] == "generation" + assert gen.start_kwargs["model"] == "gpt-5.6-sol" + assert gen.update_calls[-1]["output"] == "hello" + assert gen.update_calls[-1]["usage_details"] == expected_usage_details + assert gen.end_calls == 1 + + +async def test_codex_langfuse_error_records_generation_and_original_error_still_returned( + monkeypatch, generations, +) -> None: + async def fake_request_error(*_args, **_kwargs): + raise _CodexHTTPError("boom", status_code=500) + + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", fake_request_error + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.finish_reason == "error" + assert result.error_status_code == 500 + assert len(generations) == 1 + gen = generations[0] + assert gen.update_calls[-1]["level"] == "ERROR" + assert gen.update_calls[-1]["status_message"] == result.content + assert gen.end_calls == 1 + + +async def test_codex_langfuse_tracing_failure_does_not_break_codex_call(monkeypatch) -> None: + monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret") + _mock_codex_token(monkeypatch) + capture = _capture_codex_warnings(monkeypatch) + + def broken_start_observation(**_kwargs: Any): + raise RuntimeError("langfuse backend unreachable") + + _install_fake_langfuse(monkeypatch, broken_start_observation) + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", _fake_request_success + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.content == "hello" + assert len(capture.calls) == 1 + message, _args = capture.calls[0] + assert "Langfuse tracing failed for Codex request" in message + + +async def test_codex_langfuse_generation_still_ends_when_update_raises(monkeypatch, generations) -> None: + capture = _capture_codex_warnings(monkeypatch) + + def fail_update(self, **_kwargs): + raise RuntimeError("langfuse update failed") + + monkeypatch.setattr(_FakeGeneration, "update", fail_update) + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", _fake_request_success + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.content == "hello" + assert len(generations) == 1 + gen = generations[0] + assert gen.end_calls == 1 + assert len(capture.calls) == 1 + assert "Langfuse tracing failed for Codex request" in capture.calls[0][0] + + +async def test_codex_langfuse_generation_ends_on_cancellation(monkeypatch, generations) -> None: + async def fake_request_cancelled(*_args, **_kwargs): + raise asyncio.CancelledError() + + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", fake_request_cancelled + ) + + provider = OpenAICodexProvider() + with pytest.raises(asyncio.CancelledError): + await provider.chat([{"role": "user", "content": "hi"}]) + + assert len(generations) == 1 + gen = generations[0] + assert gen.end_calls == 1 + assert gen.update_calls == [] # no output/usage known - nothing to attach + + +async def test_codex_langfuse_traces_each_request_during_native_compaction(monkeypatch, generations) -> None: + provider = OpenAICodexProvider(default_model="openai-codex/gpt-5.6-sol") + state_provider = provider._responses_state_provider() + state = build_responses_state( + provider=state_provider, + model="gpt-5.6-sol", + input_items=[{"type": "message", "role": "user", "content": "old question"}], + output_items=[ + {"type": "reasoning", "encrypted_content": "old opaque reasoning"}, + { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": "old answer"}], + }, + ], + usage=provider_base.LLMUsage.reported(input_tokens=90, output_tokens=5, total_tokens=95), + ) + + async def fake_request( + url, headers, body, verify, proxy=None, on_content_delta=None, + on_thinking_delta=None, on_tool_call_delta=None, + ): + _ = url, headers, verify, proxy, on_content_delta, on_thinking_delta, on_tool_call_delta + if body["input"][-1].get("type") == "compaction_trigger": + compact_item = {"type": "compaction", "encrypted_content": "compacted opaque state"} + return provider_base.LLMResponse( + content=None, + provider_state=build_responses_state( + provider=state_provider, + model="gpt-5.6-sol", + input_items=body["input"], + output_items=[compact_item], + usage=provider_base.LLMUsage.reported(input_tokens=95, output_tokens=2, total_tokens=97), + ), + ) + return provider_base.LLMResponse( + content="done", + usage=provider_base.LLMUsage.reported(input_tokens=5, output_tokens=1, total_tokens=6), + ) + + monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request) + + response = await provider.chat_with_retry( + [ + {"role": "system", "content": "system"}, + {"role": "user", "content": "new question"}, + ], + max_tokens=5, + provider_context=provider_base.ProviderCallContext( + conversation_state=state.with_pending_messages([ + {"role": "user", "content": "new question"}, + ]), + context_window_tokens=100, + ), + ) + + assert response.content == "done" + assert len(generations) == 2 + assert generations[0].start_kwargs["name"] == "codex_compaction" + assert generations[1].start_kwargs["name"] == "codex_request" + assert [gen.end_calls for gen in generations] == [1, 1] + assert generations[1].update_calls[-1]["output"] == "done" + + +async def test_codex_langfuse_detection_failure_does_not_break_codex_call(monkeypatch) -> None: + monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret") + _mock_codex_token(monkeypatch) + capture = _capture_codex_warnings(monkeypatch) + + def broken_find_spec(name: str): + raise ValueError("corrupt module cache") + + monkeypatch.setattr("importlib.util.find_spec", broken_find_spec) + monkeypatch.setattr( + "nanobot.providers.openai_codex_provider._request_codex", _fake_request_success + ) + + provider = OpenAICodexProvider() + result = await provider.chat([{"role": "user", "content": "hi"}]) + + assert result.content == "hello" + assert len(capture.calls) == 1 + assert "Langfuse tracing failed for Codex request" in capture.calls[0][0] + + +async def test_codex_langfuse_traces_the_actual_wire_body_not_the_prenormalized_one( + monkeypatch, generations, +) -> None: + + provider = OpenAICodexProvider( + default_model="openai-codex/gpt-5.6-sol", + extra_body={"model": "openai-codex/override-model"}, + ) + state = build_responses_state( + provider=provider._responses_state_provider(), + model="gpt-5.6-sol", + input_items=[{ + "id": "msg_user", + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "Check the weather"}], + }], + output_items=[ + { + "id": "rs_reasoning", + "type": "reasoning", + "encrypted_content": "opaque reasoning", + "summary": [], + }, + { + "id": "fc_read", + "type": "function_call", + "call_id": "call_read", + "name": "read_file", + "arguments": '{"path":"weather/SKILL.md"}', + "status": "completed", + }, + ], + ) + sent_bodies: list[dict[str, Any]] = [] + + async def fake_request( + url, headers, body, verify, proxy=None, on_content_delta=None, + on_thinking_delta=None, on_tool_call_delta=None, + ): + sent_bodies.append(body) + return provider_base.LLMResponse(content="done") + + monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request) + + await provider.chat( + [{"role": "user", "content": "Check the weather"}], + provider_context=provider_base.ProviderCallContext( + conversation_state=state.with_pending_messages([{ + "role": "tool", + "tool_call_id": "call_read|fc_read", + "content": "weather skill contents", + }]), + ), + ) + + assert len(sent_bodies) == 1 + wire_body = sent_bodies[0] + assert all("id" not in item for item in wire_body["input"]) + assert len(generations) == 1 + gen = generations[0] + assert gen.start_kwargs["model"] == "override-model" + assert gen.start_kwargs["input"]["input"] == wire_body["input"] + assert all("id" not in item for item in gen.start_kwargs["input"]["input"]) + + +async def test_codex_langfuse_records_rejected_compaction_as_error(monkeypatch, generations) -> None: + """A transport-successful compaction with no usable item must not trace as a success.""" + provider = OpenAICodexProvider(default_model="openai-codex/gpt-5.6-sol") + state = build_responses_state( + provider=provider._responses_state_provider(), + model="gpt-5.6-sol", + input_items=[{"type": "message", "role": "user", "content": "old question"}], + output_items=[ + { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": "old answer"}], + }, + ], + usage=provider_base.LLMUsage.reported(input_tokens=90, output_tokens=5, total_tokens=95), + ) + + async def fake_request( + url, headers, body, verify, proxy=None, on_content_delta=None, + on_thinking_delta=None, on_tool_call_delta=None, + ): + if body["input"][-1].get("type") == "compaction_trigger": + return provider_base.LLMResponse(content=None) + return provider_base.LLMResponse(content="done") + + monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request) + + response = await provider.chat_with_retry( + [ + {"role": "system", "content": "system"}, + {"role": "user", "content": "new question"}, + ], + max_tokens=5, + provider_context=provider_base.ProviderCallContext( + conversation_state=state.with_pending_messages([ + {"role": "user", "content": "new question"}, + ]), + context_window_tokens=100, + ), + ) + + assert response.content == "done" # falls back to the uncompacted request + assert len(generations) == 2 + compaction_gen = generations[0] + assert compaction_gen.start_kwargs["name"] == "codex_compaction" + assert compaction_gen.update_calls[-1]["level"] == "ERROR" + assert compaction_gen.end_calls == 1 diff --git a/tests/providers/test_openai_codex_websocket.py b/tests/providers/test_openai_codex_websocket.py index 441db785d..f9cc6b7ad 100644 --- a/tests/providers/test_openai_codex_websocket.py +++ b/tests/providers/test_openai_codex_websocket.py @@ -8,7 +8,10 @@ import hashlib import io import json import random +import subprocess +import sys from dataclasses import dataclass, field, replace +from textwrap import dedent from types import SimpleNamespace from typing import Any @@ -35,7 +38,7 @@ class _Peer: closed: asyncio.Event = field(default_factory=asyncio.Event) -def _events(response_id: str, output: list[dict[str, Any]] | None = None): +def _events(response_id: str, output: list[dict[str, Any]] | None = None, *, usage=None): if output is None: output = [{ "type": "message", "id": f"msg_{response_id}", "role": "assistant", @@ -49,13 +52,13 @@ def _events(response_id: str, output: list[dict[str, Any]] | None = None): events.append({"type": "response.output_item.done", "output_index": index, "item": item}) events.append({"type": "response.completed", "response": { "id": response_id, "status": "completed", "output": output, - "usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15}, + "usage": usage if usage is not None else {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15}, }}) return events -async def _complete(peer: _Peer, response_id: str, output=None): - for event in _events(response_id, output): +async def _complete(peer: _Peer, response_id: str, output=None, *, usage=None): + for event in _events(response_id, output, usage=usage): await peer.socket.send_json(event) @@ -68,16 +71,17 @@ class _ResponsesServer: self.reject_upgrade = False self.upgrade_status = 426 self.upgrade_headers = [] + self.usage = None self.respond = self._respond async def _respond(self, peer, _body): - await _complete(peer, f"resp_{len(self.requests)}") + await _complete(peer, f"resp_{len(self.requests)}", usage=self.usage) async def handle(self, request): if request.method == "POST": body = await request.json() self.http_requests.append(body) - data = "".join(f"data: {json.dumps(event)}\n\n" for event in _events("resp_http")) + data = "".join(f"data: {json.dumps(event)}\n\n" for event in _events("resp_http", usage=self.usage)) return web.Response(text=data, content_type="text/event-stream") self.upgrade_attempts += 1 if self.reject_upgrade: @@ -140,6 +144,100 @@ def _context(result: LLMResponse | None = None, pending=None, session="session-a return ProviderCallContext(session_id=session, conversation_state=state, **kwargs) +@pytest.mark.parametrize("reject_upgrade", [False, True], ids=["websocket", "sse-fallback"]) +async def test_codex_exports_langfuse_usage(codex_peer, reject_upgrade): + pytest.importorskip("langfuse") + from importlib.metadata import version + + from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest + + import nanobot.providers.openai_codex_provider as codex + + _, server, _ = codex_peer + server.reject_upgrade = reject_upgrade + server.usage = { + "input_tokens": 100, "output_tokens": 20, "total_tokens": 120, + "input_tokens_details": {"cached_tokens": 80}, + } + spans = [] + sdk_versions = [] + + async def collect(request): + sdk_versions.append(request.headers.get("x-langfuse-sdk-version")) + exported = ExportTraceServiceRequest.FromString(await request.read()) + for resource in exported.resource_spans: + for scope in resource.scope_spans: + spans.extend(scope.spans) + return web.Response(body=b"", content_type="application/x-protobuf") + + app = web.Application() + app.router.add_post("/api/public/otel/v1/traces", collect) + runner = web.AppRunner(app) + await runner.setup() + try: + await web.TCPSite(runner, "127.0.0.1", 0).start() + langfuse_url = f"http://127.0.0.1:{runner.addresses[0][1]}" + # Isolate the SDK's global client and export threads from the test process. + script = dedent(''' + import asyncio + import os + import sys + from types import SimpleNamespace + + from langfuse import Langfuse + import nanobot.providers.openai_codex_provider as codex + from nanobot.providers.base import ProviderCallContext + + os.environ.pop("OTEL_EXPORTER_OTLP_HEADERS", None) + os.environ.pop("OTEL_EXPORTER_OTLP_TRACES_HEADERS", None) + client = Langfuse( + public_key="pk-local", secret_key="sk-local", base_url=sys.argv[2], + tracing_enabled=True, + ) + os.environ["LANGFUSE_SECRET_KEY"] = "sk-local" + codex.DEFAULT_CODEX_URL = sys.argv[1] + codex.get_codex_token = lambda **_: SimpleNamespace(account_id="acct", access="token") + + async def run(): + provider = codex.OpenAICodexProvider(default_model="gpt-5.4") + try: + result = await provider.chat( + [{"role": "user", "content": "hello"}], + provider_context=ProviderCallContext(session_id="langfuse-test"), + ) + assert result.content == "answer" + finally: + await provider.aclose() + + try: + asyncio.run(run()) + finally: + client.shutdown() + ''') + completed = await asyncio.to_thread( + subprocess.run, [sys.executable, "-c", script, codex.DEFAULT_CODEX_URL, langfuse_url], + capture_output=True, text=True, timeout=30, + ) + assert completed.returncode == 0, completed.stdout + completed.stderr + finally: + await runner.cleanup() + + assert len(server.requests) == int(not reject_upgrade) + assert len(server.http_requests) == int(reject_upgrade) + assert sdk_versions == [version("langfuse")] + assert len(spans) == 1 + span = spans[0] + attributes = {item.key: item.value.string_value for item in span.attributes} + assert span.name == "codex_request" + assert span.end_time_unix_nano >= span.start_time_unix_nano > 0 + assert attributes["langfuse.observation.type"] == "generation" + assert attributes["langfuse.observation.model.name"] == "gpt-5.4" + assert attributes["langfuse.observation.output"] == "answer" + assert json.loads(attributes["langfuse.observation.usage_details"]) == { + "input": 20, "output": 20, "total": 120, "input_cached_tokens": 80, + } + + async def test_gateway_continues_image_then_pdf_attachment_turn(codex_peer, tmp_path): provider, server, _ = codex_peer image = tmp_path / "image.png"