Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(tracing): add Tracer.oneshot() for instrumented one-shot LLM calls

xf gong90533c689e6b
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index cca2171..7a70fdc 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -30,6 +30,57 @@ from cubepi.tracing.schema import SCHEMA_URL, SCOPE_NAME
if TYPE_CHECKING:
from cubepi.agent.agent import Agent
+ from cubepi.providers.base import BaseProvider, Message, Model
+
+
+class _OneShotSession:
+ """Returned by :meth:`Tracer.oneshot` to issue a single traced LLM call.
+
+ The session's provider listeners are live for the lifetime of the
+ ``async with tracer.oneshot(...)`` block. Call :meth:`generate` once
+ inside that block to run the LLM and get the response text.
+ """
+
+ def __init__(
+ self,
+ provider: "BaseProvider",
+ model: "Model",
+ run: Any,
+ ) -> None:
+ self._provider = provider
+ self._model = model
+ self._run = run
+
+ async def generate(
+ self,
+ *,
+ system: str,
+ messages: "list[Message]",
+ max_output_tokens: int,
+ ) -> str:
+ """Run one non-tool-using completion and return the full text.
+
+ The provider listeners wired by :meth:`Tracer.oneshot` will record
+ a ``chat`` child span covering this call automatically.
+ """
+ # Seed transcript so record_content captures input messages.
+ self._run.transcript = list(messages)
+
+ model = self._model.model_copy(update={"max_tokens": max_output_tokens})
+ stream = await self._provider.stream(
+ model=model,
+ messages=messages,
+ system_prompt=system,
+ )
+ parts: list[str] = []
+ async for evt in stream:
+ if evt.type == "text_delta" and evt.delta:
+ parts.append(evt.delta)
+ elif evt.type == "error":
+ raise RuntimeError(evt.error_message or "oneshot generation failed")
+ elif evt.type == "done":
+ break
+ return "".join(parts)
class Tracer:
@@ -331,6 +382,136 @@ class Tracer:
except BaseException:
pass
+ @contextlib.asynccontextmanager
+ async def oneshot(
+ self,
+ *,
+ provider: "BaseProvider",
+ model: "Model",
+ operation: str = "oneshot",
+ metadata: "dict[str, str | int | float | bool] | None" = None,
+ record_content: bool | None = None,
+ ) -> AsyncIterator["_OneShotSession"]:
+ """Instrumented one-shot LLM call that produces a trace without a full Agent.
+
+ Creates an ``invoke_agent`` root span (so the ``cubepi trace`` CLI
+ indexes it alongside normal agent runs) and wires the provider's
+ listeners for the duration of the block, producing a ``chat`` child
+ span automatically when :meth:`_OneShotSession.generate` is called.
+
+ ``metadata`` keys are stamped as ``cubepi.metadata.<key>`` attributes on
+ the root span and are queryable with
+ ``cubepi trace ls --meta <key>=<value>``.
+
+ ``operation`` is recorded as ``cubepi.oneshot.operation`` to let
+ callers filter one-shot traces from agent runs in dashboards.
+
+ Example::
+
+ async with tracer.oneshot(
+ provider=provider,
+ model=model,
+ operation="consolidate_memory",
+ metadata={"conversation_id": conv_id, "user_id": user_id},
+ ) as session:
+ text = await session.generate(
+ system=SYSTEM_PROMPT,
+ messages=[UserMessage(...)],
+ max_output_tokens=1500,
+ )
+ """
+ from opentelemetry.trace import SpanKind
+
+ from cubepi.providers.base import BaseProvider as _BaseProvider
+ from cubepi.tracing.recorder import Recorder, _RunState, _active_run
+ from cubepi.tracing.schema import (
+ CUBEPI_RUN_ID,
+ GEN_AI_OPERATION_NAME,
+ GEN_AI_PROVIDER_NAME,
+ OP_INVOKE_AGENT,
+ SPAN_NAME_INVOKE_AGENT,
+ )
+
+ do_record = record_content if record_content is not None else self._record_content
+ run_id = str(uuid.uuid4())
+
+ root_attrs: dict[str, Any] = {
+ GEN_AI_OPERATION_NAME: OP_INVOKE_AGENT,
+ CUBEPI_RUN_ID: run_id,
+ GEN_AI_PROVIDER_NAME: "cubepi",
+ "cubepi.oneshot.operation": operation,
+ }
+ for k, v in (metadata or {}).items():
+ try:
+ root_attrs[f"cubepi.metadata.{k}"] = v
+ except (TypeError, ValueError):
+ pass
+
+ root_span = self._otel_tracer.start_span(
+ name=SPAN_NAME_INVOKE_AGENT,
+ kind=SpanKind.INTERNAL,
+ attributes=root_attrs,
+ )
+
+ # _RunState with turn_span = root_span so chat spans nest directly
+ # under the root (no cubepi.turn wrapper — one-shot has no loop).
+ run = _RunState(
+ run_id=run_id,
+ agent_span=root_span,
+ turn_span=root_span,
+ )
+
+ # Minimal Recorder to handle the 3 provider lifecycle listeners.
+ # We don't subscribe agent events — there's no agent loop.
+ recorder = Recorder(
+ self,
+ record_content=do_record,
+ record_stream=self._record_stream,
+ stream_dir=self._stream_dir,
+ redact=self._redact,
+ )
+ recorder._run = run
+
+ detachers: list[Callable[[], None]] = []
+ if isinstance(provider, _BaseProvider):
+ try:
+ detachers.append(
+ provider.subscribe_request(recorder._on_provider_request)
+ )
+ detachers.append(
+ provider.subscribe_chunk(recorder._on_provider_chunk)
+ )
+ detachers.append(
+ provider.subscribe_response(recorder._on_provider_response)
+ )
+ except BaseException:
+ root_span.end()
+ raise
+
+ # Set the per-task active-run gate so provider listeners recognise
+ # calls that belong to this oneshot session.
+ token = _active_run.set(run)
+ try:
+ yield _OneShotSession(provider=provider, model=model, run=run)
+ finally:
+ _active_run.reset(token)
+ for d in detachers:
+ try:
+ d()
+ except Exception:
+ pass
+ recorder._run = None
+ root_span.end()
+ # Best-effort flush — tracing must never break the caller's work.
+ try:
+ import asyncio
+
+ asyncio.get_running_loop().create_task(
+ self.force_flush(timeout_seconds=5.0)
+ )
+ except RuntimeError:
+ pass
+
async def __aenter__(self) -> "Tracer":
return self
diff --git a/skills/cubepi-trace/SKILL.md b/skills/cubepi-trace/SKILL.md
index 0179914..f91623f 100644
--- a/skills/cubepi-trace/SKILL.md
+++ b/skills/cubepi-trace/SKILL.md
@@ -20,6 +20,9 @@ token/cache counts. Reach for this **before** guessing at a bug.
`error`.
- Token / cache / cost numbers look wrong.
- You just need to understand the agent's actual trajectory for a given input.
+- A background LLM call (e.g. memory consolidation via `Tracer.oneshot()`) isn't
+ behaving as expected — oneshot calls produce `invoke_agent` spans too and are
+ searchable by metadata.
## Prerequisites (one-time)
@@ -120,6 +123,52 @@ uv run cubepi trace stats --by model --meta user_id=usr_9
uv run cubepi trace ls --show-meta conversation_id,user_id
```
+## Tracing one-shot LLM calls (`Tracer.oneshot`)
+
+`Tracer.oneshot()` instruments a single prompt→text LLM call (no agent loop)
+and writes it as a full `invoke_agent` trace. Cubebox uses this for background
+tasks like memory consolidation. The span tree is flat — no `cubepi.turn`
+wrapper since there's no loop:
+
+```
+trace
+└── invoke_agent 820ms [0x3f2a1b...]
+ └── chat deepseek-v3 815ms tok 3200/180 [0x9c45d2...]
+```
+
+The root span carries:
+- `cubepi.oneshot.operation` — the operation name (e.g. `"consolidate_memory"`)
+- `cubepi.metadata.*` — caller-supplied metadata (e.g. `conversation_id`)
+
+Find oneshot traces by operation or conversation:
+
+```bash
+# All consolidation runs
+uv run cubepi trace ls --meta cubepi.oneshot.operation=consolidate_memory
+
+# Oneshot traces for a specific conversation (alongside its agent runs)
+uv run cubepi trace ls --meta conversation_id=conv-1fwZQ8u3ZDukx3
+
+# Stats on consolidation token usage
+uv run cubepi trace stats --by model --meta cubepi.oneshot.operation=consolidate_memory
+```
+
+Cubebox wires this in `run_manager.py`; the consolidation pass calls:
+
+```python
+async with tracer.oneshot(
+ provider=provider,
+ model=model,
+ operation="consolidate_memory",
+ metadata={"conversation_id": conv_id, "user_id": user_id},
+) as session:
+ raw = await session.generate(
+ system=CONSOLIDATION_SYSTEM,
+ messages=[UserMessage(...)],
+ max_output_tokens=1500,
+ )
+```
+
## Replaying a failing LLM call (`trace convert`)
When the span tree + content aren't enough and you need to replay the exact API
diff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.py
new file mode 100644
index 0000000..533b179
--- /dev/null
+++ b/tests/tracing/test_oneshot.py
@@ -0,0 +1,224 @@
+"""Tests for Tracer.oneshot() — instrumented one-shot LLM calls."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from opentelemetry.sdk.trace import ReadableSpan
+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+from cubepi.providers.base import Model, TextContent, UserMessage
+from cubepi.providers.faux import FauxProvider, faux_assistant_message
+from cubepi.tracing import Tracer
+from cubepi.tracing.tracer import _OneShotSession
+
+
+MODEL = Model(id="faux-1", provider="faux")
+
+
+class InMemoryExporter(SpanExporter):
+ def __init__(self) -> None:
+ self.spans: list[ReadableSpan] = []
+
+ def export(self, spans: Any) -> SpanExportResult:
+ self.spans.extend(spans)
+ return SpanExportResult.SUCCESS
+
+ def shutdown(self) -> None:
+ pass
+
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ return True
+
+
+def _make_tracer(*, record_content: bool = False) -> tuple[Tracer, InMemoryExporter]:
+ exporter = InMemoryExporter()
+ tracer = Tracer(
+ exporters=[exporter],
+ record_content=record_content,
+ atexit_flush=False,
+ )
+ return tracer, exporter
+
+
+def _spans_by_name(spans: list[ReadableSpan]) -> dict[str, ReadableSpan]:
+ result: dict[str, ReadableSpan] = {}
+ for s in spans:
+ result[s.name] = s
+ return result
+
+
+async def test_oneshot_session_type() -> None:
+ provider = FauxProvider()
+ tracer, _ = _make_tracer()
+ async with tracer.oneshot(provider=provider, model=MODEL) as session:
+ assert isinstance(session, _OneShotSession)
+ await tracer.shutdown()
+
+
+async def test_oneshot_produces_root_and_chat_spans() -> None:
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("hello world")])
+ tracer, exporter = _make_tracer()
+
+ async with tracer.oneshot(
+ provider=provider,
+ model=MODEL,
+ operation="test_op",
+ metadata={"conversation_id": "conv-123", "user_id": "usr-456"},
+ ) as session:
+ text = await session.generate(
+ system="You are helpful.",
+ messages=[UserMessage(content=[TextContent(text="hi")])],
+ max_output_tokens=100,
+ )
+
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ assert text == "hello world"
+
+ by_name = _spans_by_name(exporter.spans)
+ assert "invoke_agent" in by_name, f"spans: {[s.name for s in exporter.spans]}"
+ assert f"chat {MODEL.id}" in by_name
+
+ root = by_name["invoke_agent"]
+ attrs = dict(root.attributes or {})
+ assert attrs.get("gen_ai.operation.name") == "invoke_agent"
+ assert attrs.get("cubepi.oneshot.operation") == "test_op"
+ assert attrs.get("cubepi.metadata.conversation_id") == "conv-123"
+ assert attrs.get("cubepi.metadata.user_id") == "usr-456"
+ assert "cubepi.run_id" in attrs
+
+ chat = by_name[f"chat {MODEL.id}"]
+ # chat span must be a child of root
+ assert chat.parent is not None
+ assert chat.parent.span_id == root.context.span_id
+
+ # token counts recorded
+ chat_attrs = dict(chat.attributes or {})
+ assert "gen_ai.usage.input_tokens" in chat_attrs
+ assert "gen_ai.usage.output_tokens" in chat_attrs
+
+
+async def test_oneshot_metadata_on_root_span() -> None:
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("ok")])
+ tracer, exporter = _make_tracer()
+
+ async with tracer.oneshot(
+ provider=provider,
+ model=MODEL,
+ operation="consolidate_memory",
+ metadata={"conversation_id": "conv-abc"},
+ ) as session:
+ await session.generate(
+ system="sys",
+ messages=[UserMessage(content=[TextContent(text="x")])],
+ max_output_tokens=50,
+ )
+
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ roots = [s for s in exporter.spans if s.name == "invoke_agent"]
+ assert len(roots) == 1
+ attrs = dict(roots[0].attributes or {})
+ assert attrs["cubepi.oneshot.operation"] == "consolidate_memory"
+ assert attrs["cubepi.metadata.conversation_id"] == "conv-abc"
+
+
+async def test_oneshot_no_metadata_ok() -> None:
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("result")])
+ tracer, exporter = _make_tracer()
+
+ async with tracer.oneshot(provider=provider, model=MODEL) as session:
+ text = await session.generate(
+ system="sys",
+ messages=[UserMessage(content=[TextContent(text="q")])],
+ max_output_tokens=10,
+ )
+
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ assert text == "result"
+ assert any(s.name == "invoke_agent" for s in exporter.spans)
+
+
+async def test_oneshot_record_content_captures_messages() -> None:
+ provider = FauxProvider()
+ provider.append_responses([faux_assistant_message("answer")])
+ tracer, exporter = _make_tracer(record_content=True)
+
+ async with tracer.oneshot(
+ provider=provider,
+ model=MODEL,
+ record_content=True,
+ ) as session:
+ await session.generate(
+ system="be helpful",
+ messages=[UserMessage(content=[TextContent(text="question")])],
+ max_output_tokens=50,
+ )
+
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ chat_spans = [s for s in exporter.spans if s.name.startswith("chat")]
+ assert chat_spans, "expected a chat span"
+ attrs = dict(chat_spans[0].attributes or {})
+ # With record_content=True the system instructions are recorded on the chat span
+ assert "gen_ai.system_instructions" in attrs
+
+
+async def test_oneshot_does_not_interfere_with_concurrent_agent() -> None:
+ """Oneshot's active-run gate must not bleed into a concurrent Agent run."""
+ import asyncio
+
+ from cubepi.agent.agent import Agent
+
+ provider = FauxProvider()
+ # Push responses for both agent and oneshot
+ provider.append_responses([faux_assistant_message("agent reply")])
+ provider.append_responses([faux_assistant_message("oneshot reply")])
+
+ tracer, exporter = _make_tracer()
+ agent = Agent(provider=provider, model=MODEL, system_prompt="sys")
+ detach = tracer.attach(agent)
+
+ # Run agent and oneshot concurrently
+ async def run_agent() -> str:
+ await agent.prompt("agent question")
+ return str(agent.state.messages[-1].content[0].text) # type: ignore[index]
+
+ async def run_oneshot() -> str:
+ async with tracer.oneshot(provider=provider, model=MODEL) as session:
+ return await session.generate(
+ system="sys",
+ messages=[UserMessage(content=[TextContent(text="oneshot q")])],
+ max_output_tokens=50,
+ )
+
+ agent_result, oneshot_result = await asyncio.gather(run_agent(), run_oneshot())
+
+ result = detach()
+ if result is not None:
+ await result
+ await tracer.force_flush()
+ await tracer.shutdown()
+
+ assert "agent reply" in agent_result or "oneshot reply" in agent_result
+ assert "agent reply" in oneshot_result or "oneshot reply" in oneshot_result
+
+ # Both runs should produce an invoke_agent span
+ roots = [s for s in exporter.spans if s.name == "invoke_agent"]
+ assert len(roots) == 2