Skip to content

Commit 01b0ac6

Browse files
feat(anthropic)!: replace batch auto-instrumentation with explicit trace apis (#1200)
## Summary Removes Anthropic batch lifecycle auto-instrumentation and replaces it with explicit, spec-compliant Anthropic Message Batch tracing APIs modeled after the Braintrust JS SDK (`groq-batch` / `ai-sdk-batch`) and `batch-apis.md`. ### What changed & why 1. **Removed Anthropic batch auto-instrumentation (`py/src/braintrust/integrations/anthropic/tracing.py`)** - Deleted `Batches`, `AsyncBatches`, and the `batches` property overrides on `Messages` / `AsyncMessages`. - `client.messages.batches.create` / `results` and `client.beta.messages.batches.create` / `results` now pass through untouched under both `wrap_anthropic()` and `AnthropicIntegration.setup()`. - Deleted 6 now-unused `TestBatchesCreateSpans` cassettes across `latest`, `1.17.0`, and `0.48.0`. 2. **Added explicit Anthropic batch trace APIs (`py/src/braintrust/integrations/anthropic/batch.py`, exported from `braintrust.integrations.anthropic`)** - `start_anthropic_batch_trace(*, batch, requests) -> str | None` - `complete_anthropic_batch_trace(*, batch, results=None, context=None, requests=None) -> None` - `complete_anthropic_batch_trace_async(*, batch, results=None, context=None, requests=None) -> None` ```python from braintrust.integrations.anthropic import ( complete_anthropic_batch_trace, start_anthropic_batch_trace, ) batch = client.messages.batches.create(requests=requests) context = start_anthropic_batch_trace(batch=batch, requests=requests) # Later (including in a different process) once batch.processing_status == "ended": results = client.messages.batches.results(batch.id) complete_anthropic_batch_trace(batch=batch, results=results, context=context) ``` - **Span tree**: emits one parent `task` span (`anthropic.batch`) and one child `llm` span (`anthropic.messages.create`) per valid request via `start_span(..., set_current=False, internal={"initial_span_write_as_merge": True, ...})`, with deterministic span/row IDs (`anthropic:batch` and `anthropic:batch:request`) so start + collect merge idempotently without holding live spans in memory. - **Resumable bounded context**: versioned JSON string (`version=1`) storing only `batch_id`, `task` slug (with `propagated_event` stripped), `start_time`, `request_count`, and a SHA-256 digest of sorted `custom_id`s. - **Collect-only, streaming & privacy**: accepts JSONL strings/bytes, file-like streams, sync iterables, and async iterables; spools saved-context child updates via `tempfile.SpooledTemporaryFile` until `request_ids_digest` validates so invalid/unknown results emit zero stray rows without buffering large batches in RAM; enforces `provider_content_allowed` redaction on completion updates; supports collect-only mode when `requests` is supplied without prior start context. - **Terminal & partial-result handling**: keeps spans pending when `processing_status != "ended"` or results are incomplete, rejects duplicate/unknown `custom_id`s, clamps `end >= start`, and handles `succeeded`, `errored`, `canceled`, and `expired` outcomes. 3. **Tests & skill rule (`py/src/braintrust/integrations/anthropic/test_anthropic.py`, `.agents/skills/sdk-integrations/SKILL.md`)** - Replaced `TestBatchesCreateSpans` with 100% VCR-backed `TestAnthropicBatchTracing` across `latest`, `1.17.0`, and `0.48.0`, including newly recorded `errored` and `canceled` outcome cassettes. - Documented the rule in `.agents/skills/sdk-integrations/SKILL.md` that explicit provider batch helpers export from `braintrust.integrations.<provider>` rather than top-level `braintrust`. **Breaking change**: `messages.batches.create()` and `messages.batches.results()` are no longer auto-instrumented. Callers should switch to `start_anthropic_batch_trace()` and `complete_anthropic_batch_trace()` / `complete_anthropic_batch_trace_async()` from `braintrust.integrations.anthropic`. Link to Devin session: https://braintrust.devinenterprise.com/sessions/f12a57f6efe44a68b370bd5896079b41 Open in Devin Desktop: https://braintrust.devinenterprise.com/desktop/session/f12a57f6efe44a68b370bd5896079b41?variant=devin --------- Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 049b431 commit 01b0ac6

17 files changed

Lines changed: 8043 additions & 747 deletions

‎.agents/skills/sdk-integrations/SKILL.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ Declarative setup on the `BaseIntegration` subclass: `name`, `import_names`, `pa
8888
- Instrumentation failures (extraction, normalization) must never raise into the user's call path. But do not wrap `span.log(...)` / `span.set_attributes(...)` in try/except — they are boundary-safe.
8989
- Treat provider inputs/results/events/headers as untrusted. Don't mutate third-party objects.
9090
- Only instrument AI-generation-relevant ops (LLM calls, embeddings, tool exec, media gen, agent runs).
91+
- Explicit provider batch tracing helpers (`start_<provider>_batch_trace`, `complete_<provider>_batch_trace`, etc.) MUST be exported from `braintrust.integrations.<provider>` (not re-exported from top-level `py/src/braintrust/__init__.py`).
9192
- Do not over-serialize. `span.log` already runs `bt_safe_deep_copy` (pydantic, dataclasses, attachments). Log readable dicts/lists/scalars and materialized attachments; no JSON dumps/loads or recursive conversion in tracing code.
9293
- Every `llm` span has `metadata.model` and `metadata.provider` (whose pricing applies, not the framework name).
9394
- Before writing a usage mapper in a framework integration, check the underlying provider's `tracing.py` for a compatible parser. Reuse it when the payload shape matches, and verify reported usage details against the recording. For example, the OpenAI parser maps Responses `cache_write_tokens` to `prompt_cache_creation_tokens`.

‎py/src/braintrust/integrations/anthropic/__init__.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import warnings
22

3+
from .batch import (
4+
complete_anthropic_batch_trace,
5+
complete_anthropic_batch_trace_async,
6+
start_anthropic_batch_trace,
7+
)
38
from .integration import AnthropicIntegration
49
from .tracing import _wrap_anthropic
510

@@ -18,6 +23,9 @@ def wrap_anthropic_client(client):
1823

1924
__all__ = [
2025
"AnthropicIntegration",
26+
"complete_anthropic_batch_trace",
27+
"complete_anthropic_batch_trace_async",
28+
"start_anthropic_batch_trace",
2129
"wrap_anthropic",
2230
"wrap_anthropic_client",
2331
]

0 commit comments

Comments
 (0)