Metadata-Version: 2.5
Name: raindrop-deep-agents
Version: 0.0.11
Summary: Raindrop integration for Deep Agents
Project-URL: Homepage, https://raindrop.ai
Project-URL: Documentation, https://docs.raindrop.ai
Author-email: Raindrop AI <sdk@raindrop.ai>
License-Expression: MIT
License-File: LICENSE
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: langchain-core>=0.3.0
Requires-Dist: raindrop-ai>=0.0.70
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: requests>=2.28; extra == 'dev'
Description-Content-Type: text/markdown

# raindrop-deep-agents

Raindrop integration for [Deep Agents](https://docs.langchain.com/oss/python/deepagents/overview) (Python). Pass a single LangChain callback handler and Raindrop captures every LLM call, tool invocation, chain step, and agent action — with full OpenTelemetry trace nesting linked to the resulting dashboard event.

## Installation

```bash
pip install raindrop-deep-agents deepagents langchain-core langchain-openai
```

> Works with both `wrapt < 2.0` and `wrapt >= 2.0`. The upstream `opentelemetry-instrumentation-langchain` package (latest 0.59.2) still calls `wrapt.wrap_function_wrapper(module="...", ...)` with the legacy `module=` keyword argument that wrapt 2.0 [renamed to `target=`](https://wrapt.readthedocs.io/en/latest/changes.html). Without a workaround the instrumentor crashes on activation and Traceloop silently swallows the error — traces never reach the dashboard while events keep working (tracked upstream at [traceloop/openllmetry#4009](https://github.com/traceloop/openllmetry/issues/4009) and [Arize-ai/openinference#2996](https://github.com/Arize-ai/openinference/issues/2996)). On import, this package installs a small backwards-compat shim (`raindrop_deep_agents/_wrapt_compat.py`) that translates `module=` → `target=` for any caller using wrapt 2.x; on wrapt 1.x the shim is a no-op. We can drop the shim once the upstream instrumentors migrate.

## Quick Start

```python
from raindrop_deep_agents import RaindropDeepAgents
from deepagents import create_deep_agent
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

raindrop = RaindropDeepAgents(
    api_key="rk_...",
    user_id="user-123",
    convo_id="session-abc",
)

llm = ChatOpenAI(model="gpt-4o-mini")
agent = create_deep_agent(model=llm, system_prompt="Be concise.")

result = agent.invoke(
    {"messages": [HumanMessage(content="Hello!")]},
    config={"callbacks": [raindrop.handler]},
)

raindrop.shutdown()
```

### Factory Function (alternative)

```python
from raindrop_deep_agents import create_raindrop_deep_agents

raindrop = create_raindrop_deep_agents(api_key="rk_...", user_id="user-123")
agent = create_deep_agent(model=llm)
agent.invoke(
    {"messages": [HumanMessage(content="Hello")]},
    config={"callbacks": [raindrop.handler]},
)
raindrop.shutdown()
```

## What Gets Captured

- **LLM calls** — model name, input, output, prompt + completion tokens, finish reason
- **Tool calls** — tool name, input arguments, output, duration as nested `TOOL_CALL` spans linked to the parent event (via `interaction.track_tool()`)
- **Chains** — root chain input/output captured as the canonical event (the user's question → final assistant reply)
- **Agent actions** — tool selection events captured during the agent loop
- **Errors** — exception type and message: on the event when the turn or any nested model call failed (no output only when the turn itself failed), on the tool span for a failed tool
- **Extended token categories** — cached tokens (`ai.usage.cached_tokens`) and reasoning tokens (`ai.usage.thoughts_tokens`) when available from the provider (e.g. OpenAI, Anthropic)
- **Finish reason** — captured as `ai.finish_reason` in event properties (`"stop"`, `"length"`, `"tool_calls"`, etc.)
- **Tags & metadata** — anything passed via LangChain `config={"tags": [...], "metadata": {...}}` is forwarded to event properties

**Key clashes.** If one of your properties (LangChain `tags` / `metadata`) has the same key as one the
wrapper derives itself, your value wins, whichever update carries it (a
debug-level log line names the key). The wrapper's own keys are `ai.*` (for
example `ai.usage.prompt_tokens`), `error`/`error.*` and `deep_agents.*`; avoid them
unless you mean to replace the wrapper's value.

## One event per turn

A turn (the outermost run your handler sees: the Deep Agents graph, or a bare
model call) is **one** Raindrop event, as in the TypeScript integration:

- Model calls inside the turn update that event. Its input and output are the
  root chain's (the user's question and the final reply; the last model call's
  output when the chain has none); its model and token usage are the **last** model call's.
- Tool calls are `TOOL_CALL` spans on the event, never events of their own;
  a tool that runs outside any turn is not sent (the standalone `ai_tool_call`
  events are gone). A failed tool is a failed span; the agent decides whether
  the turn fails.
- If a nested model call fails, the event carries its `error.type` /
  `error.message` (the most recent failure), even when a later call in the
  turn succeeds; the output is still the turn's last successful output. Only a
  failed turn (the outermost run itself fails) ends with the error and no
  output.
- Each model call's own input, output, model and token usage stay on a span
  for that call (a `task` span under the event, exported when `tracing_enabled`
  is on).

Earlier versions also sent every nested model call as a separate event and
summed token usage across calls on the root event.

Events that update only properties or usage need `raindrop-ai` 0.0.76 or later;
the turn's finishing update always carries the input, so it is sent on older
cores too.

## Projects

Route events to a specific [project](https://docs.raindrop.ai/platform/projects) by passing its slug as `project_id`:

```python
raindrop = RaindropDeepAgents(
    api_key="rk_...",
    project_id="support-prod",
)
```

`project_id` sets the `X-Raindrop-Project-Id` header on every event. Omit it (or pass `"default"`) to use your org's default **Production** project, which is the existing behavior. The same option is accepted by the `create_raindrop_deep_agents(...)` factory. Invalid slugs are ignored with a warning and no header is sent.

## Debug Mode

Enable verbose logging with `debug=True`:

```python
raindrop = RaindropDeepAgents(
    api_key="rk_...",
    debug=True,
)
```

## Identify Users

Associate events with a user after initialization:

```python
raindrop.identify("user-123", {"name": "Alice", "plan": "pro"})
```

## Track Signals

Send feedback, edits, or custom signals attached to a specific event:

```python
# After an agent.invoke(...), attach a feedback signal to the event
# that just shipped.  ``raindrop.last_event_id`` is the canonical
# event_id the handler emitted for the root chain — using it (rather
# than a freshly generated UUID) ensures the signal links to the real
# dashboard row instead of creating an orphan signal.
if raindrop.last_event_id:
    raindrop.track_signal(
        event_id=raindrop.last_event_id,
        name="thumbs_up",
        signal_type="feedback",
        sentiment="POSITIVE",
        comment="user liked the answer",
    )
```

## Updating the last event

`last_event_id` is the `event_id` of the most recently shipped root event.
Use it to attach a signal, or reopen the event with
`resume_interaction()` (defaults to `last_event_id`) and update it through the
core SDK's `Interaction`:

```python
interaction = raindrop.resume_interaction()
if interaction is not None:
    interaction.set_properties({"reviewed": True})
    interaction.finish()
```

Property-only updates need `raindrop-ai` 0.0.76 or newer; older core
versions drop an update that carries no input or output; the wrapper logs one warning when it resumes an event on such a core.

`last_event_id` is per wrapper instance; under concurrent calls it is whichever
event was captured last, so pass `event_id=` when you need to correlate
concurrent calls.

## Flushing and Shutdown

```python
raindrop.flush()     # flush pending events
raindrop.shutdown()  # flush + release resources (always call before process exit)
```

## API Reference

### `RaindropDeepAgents`

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `Optional[str]` | `None` | Raindrop API key. If `None`, telemetry shipping is disabled (a `UserWarning` is issued). |
| `user_id` | `Optional[str]` | `None` | Stamped on every event. Required to send: without it events are skipped, with one warning. |
| `convo_id` | `Optional[str]` | `None` | Conversation/session ID — events sharing this value are grouped on the dashboard. |
| `project_id` | `Optional[str]` | `None` | Route events to a specific [project](https://docs.raindrop.ai/platform/projects) (slug); omit for the default **Production** project. |
| `tracing_enabled` | `bool` | `True` | Enable distributed tracing (activates the LangChain OTel instrumentor). |
| `bypass_otel_for_tools` | `bool` | `True` | Bypass OTEL for tool spans — emits OTLP directly to `/v1/traces`. |
| `debug` | `bool` | `False` | Enable DEBUG-level logging. |

#### Methods

| Method | Description |
|--------|-------------|
| `handler` | Property — the LangChain callback handler. Pass into `config={"callbacks": [...]}` on `agent.invoke(...)`. |
| `last_event_id` | Property — `event_id` of the most recently shipped root event (or `None` if none has landed yet). Use this to attach a `track_signal` to the agent invocation you just ran without having to poll the dashboard API. |
| `resume_interaction(event_id=None)` | Reopen an event (default: `last_event_id`) as a core `Interaction` to update it (`set_properties`, `finish`, ...); `None` when there is nothing to resume. |
| `identify(user_id, traits)` | Identify a user with optional traits. |
| `track_signal(event_id, name, signal_type, ...)` | Track a feedback / edit / default signal against an event. |
| `flush()` | Flush all pending events to the Raindrop API. |
| `shutdown()` | Flush remaining events and release resources. |

## Async Support

The handler inherits from LangChain's `BaseCallbackHandler` and works with both synchronous and asynchronous Deep Agents invocations:

```python
result = await agent.ainvoke(
    {"messages": [HumanMessage(content="Hello")]},
    config={"callbacks": [raindrop.handler]},
)
```

## LangGraph Internals

Deep Agents is built on LangGraph. The handler keeps the outer `LangGraph` chain as the canonical root (so OTel association context is set before any span exists), and filters internal LangGraph nodes (`__start__`, `__end__`, `ChannelWrite`, `ChannelRead`, `Branch:*`, dunder names) so they don't pollute the dashboard.

## Tool catalog capture (`ai.prompt.tools`)

Every model span records the tools LangChain handed the provider for that call as `ai.prompt.tools`: an OTel string array, one JSON document per tool with `name`, `description` and the full JSON Schema as `inputSchema` (`{"type": "function", ...}`), or `{"type": "provider-defined", ...}` for provider-owned tools. The capture is **exact, per call**: `RaindropDeepAgentsHandler.on_chat_model_start` / `on_llm_start` receive `invocation_params["tools"]` (or the legacy `functions`), which is the list Deep Agents bound to the model: your registered tools plus the Deep Agents built-ins (`ls`, `read_file`, `write_file`, `edit_file`, `glob`, `grep`, `task`, ...). Those built-ins are in the list because the model really was given them on that call; this is not a catalog. The handler binds that list through the core's `prompt_tools_scope` mechanism for the duration of the model call and releases it in `on_llm_end` / `on_llm_error`, so the model span the OpenLLMetry LangChain instrumentor (or the OpenAI instrumentor under it) starts inside the call carries the attribute. A call whose `invocation_params` has no `tools` or `functions` records `[]`. Sync, async (`ainvoke`, the handler runs inline in the caller's task) and streaming calls are covered because the span starts inside the call.

Callback and instrumentor agree: the instrumentor writes the same list to `gen_ai.tool.definitions` (OpenLLMetry 0.62 emits that attribute, not `llm.request.functions.*`; `raindrop-ai` 0.0.70/0.0.71 do not rebuild `ai.prompt.tools` from it and 0.0.72 does; the wrapper binds the list itself so capture does not depend on the core version, and the bound list takes precedence). The callback's `invocation_params` is the source of truth; the test suite asserts both carry the same tools.

`RaindropDeepAgents(...)` enables the LangChain instrumentor (`instruments={Instruments.LANGCHAIN}`) whenever `tracing_enabled=True`, so model spans exist by default. With `tracing_enabled=False`, or a supplied `client=` built with `auto_instrument=False` and no instruments, there is no model span and nothing to carry the attribute.

Override:

```python
# Default for every model span this handler sees
rd = RaindropDeepAgents(api_key="...", user_id="u1", tools=[{"type": "function", "name": "get_weather", "inputSchema": {...}}])
handler = RaindropDeepAgentsHandler(user_id="u1", tools=[...])       # same option on the raw handler

# Per call, through LangChain config metadata (stripped from the event properties)
agent.invoke({"messages": [...]}, config={"callbacks": [handler], "metadata": {"raindrop_tools": [...]}})
```

The per-call value replaces the constructor default; the constructor default replaces the inferred list; `tools=[]` at either level records an empty catalog. An enclosing `raindrop.prompt_tools(...)` / `begin(..., tools=...)` scope is also treated as an override and is never shadowed by the inferred list.

Semantics shared with every Raindrop SDK:

- **Attribute absent**: the wrapper could not see the tool list (or there is no model span, see below).
- **`[]`**: the model had no tools.
- **Override replaces, never merges.** A `tools=` you pass wins over anything inferred; `tools=[]` records an empty catalog.
- **Content gate.** Tool definitions are prompt content. With `TRACELOOP_TRACE_CONTENT=false` nothing is recorded, overrides included.
- Malformed entries are skipped with a debug log; nothing here raises into your application.

Accepted shapes for `tools=`: canonical `{"type": "function", "name", "description", "inputSchema"}`, OpenAI `{"type": "function", "function": {...}}`, Anthropic `{"name", "description", "input_schema"}`, and `{"type": "provider-defined", "name", ...}`. The core normalises them; the JSON Schema is kept exactly as given.

Needs `raindrop-ai>=0.0.70`; on an older core the wrapper logs at debug and records nothing.

## User id

Every event needs a real user id: set `user_id=` on the wrapper. Without one (missing, blank, or a placeholder such as `"unknown"` or `"anonymous"`), the event is **not sent** and the wrapper logs one warning; it never raises. Updating an event you resumed with `resume_interaction(event_id=...)` needs no user id, since ingest keeps the one it stored.

## Model spans

With tracing on (the default), the wrapper records each model call in a turn as a span on the Raindrop client's tracing. The span carries:

- the model: `gen_ai.provider.name` (canonical name, such as `openai` or `amazon-bedrock`), `gen_ai.request.model` and `gen_ai.response.model`;
- the token usage the provider reports: `gen_ai.usage.input_tokens`, `output_tokens`, `cache_read_input_tokens`, `cache_write_input_tokens` and `reasoning_tokens`;
- the event it belongs to: `ai.telemetry.metadata.raindrop.eventId` and the `traceloop.association.properties.*` keys.

Token usage also stays on the event as `ai.usage.*` properties. When an OpenTelemetry auto-instrumentation already records the model calls (for example with `auto_instrument=True` on the client), the wrapper adds no span of its own, so a call is never counted twice.

## Known Limitations

- **Beta status** — API surface may change in minor releases.
- **Streaming** — Token-by-token streaming events are not captured individually; only the final aggregated response per LLM call is tracked.
- **Subagent isolation** — Each subagent invoked via the `task` tool fires its own callback chain. Events are correctly grouped by `convo_id`, but the parent–child trace relationship across subagents is best-effort.
- **OTel context propagation** — The LangChain instrumentor sometimes does not propagate `traceloop.association.properties.user_id` baggage to every span produced inside a LangGraph callback context. The dashboard still shows the trace under the correct event because the SDK records `trace_id` on the root event's properties — but filtering the global Traces page by `user_id` may not surface every relevant span. Tracked upstream at [traceloop/openllmetry#2271](https://github.com/traceloop/openllmetry/issues/2271).
- **Concurrent invocations on a shared handler** — A single `RaindropDeepAgents` instance keeps one in-flight OTel association context (`_interaction`) at a time. Running multiple `agent.invoke(...)` / `agent.ainvoke(...)` calls **concurrently with the same handler** (e.g. `await asyncio.gather(...)` inside one process) will let later invocations share or overwrite the earlier one's interaction, scrambling the linkage between events and traces. **Workaround**: instantiate one `RaindropDeepAgents` per concurrent request (cheap — it's just a wrapper around module-level SDK state). Sequential invocations on a single instance are fine and exercised by the e2e test suite.
- **Long chain inputs/outputs are truncated** — Chain-level input and output captured on the root event are truncated to ~8 KB to stay within the SDK's payload limits. Each model call's own input and output are on its span; only the event's summary is shortened. As of `0.0.2` the truncation is also enforced *during* serialization (cost proportional to the cap, not the payload — a multi-MB history or multi-modal content list can't stall the event loop inside a synchronous callback), with structured payloads marked `...[truncated by raindrop]`.
- **Python SDK feature surface** — The Raindrop Python SDK uses module-level functions and does not expose the TypeScript-only `EventShipper` / `TraceShipper` low-level APIs. Equivalent capability is exposed as top-level methods (`identify()`, `track_signal()`) on this class.

## Application Git metadata

`RaindropDeepAgents(...)` and `create_raindrop_deep_agents(...)` accept the keyword-only `app_git` option. It defaults to `True`: explicit Raindrop Git environment or deployment context is applied immediately, and the base SDK may perform one bounded background local-Git lookup from the process working directory. Event capture, flush, and shutdown never wait for that lookup. Pass `False` to disable enrichment, or pass an `AppGitOptions` mapping with `commit_sha`, `commit_dirty`, `branch`, `source_directory`, `detect_branch`, and/or `auto_detect`. Automatic branch discovery remains opt-in through `detect_branch=True` (or `RAINDROP_GIT_DETECT_BRANCH=true`).

For an ordinary in-process application, the process working directory is treated as the application-under-test checkout. A remote, coding, workflow, or observer process must not rely on its own checkout: pass `app_git=False`, provide explicit revision values, or set `source_directory` to the actual application checkout. Canonical per-operation properties remain authoritative. When supplying `client=`, configure `app_git` while constructing that `Raindrop` client; the supplied client is authoritative and the wrapper's `app_git` argument does not reconfigure it.

Release order is deliberate: first publish the base SDK feature, then publish the wrapper feature release with its minimum dependency coordinated to that base release. The existing `raindrop-ai` lower bound remains compatible, but application Git metadata is unavailable on an older core and must not be claimed complete until the base is upgraded. Until coordination assigns a released version, the wrapper checks for an explicit base `app_git` parameter and omits the option when unsupported. Explicit non-default configuration is debug-logged and omitted. Unsupported `app_git` is determined by signature inspection before construction, not by retrying initialization after a `TypeError`; Git configuration adds no initialization attempts and does not change any existing framework-specific initialization fallback.

## Standard options and flush results

When the wrapper builds its own client, it accepts the core SDK's standard
options by the same names and passes them on:

```python
raindrop = RaindropDeepAgents(
    api_key="rk_...",
    user_id="user-123",
    redact_pii=True,        # local PII redaction of event input/output
    flush_timeout=5,        # seconds; deadline for flush() and shutdown()
    debug=True,             # also raises the core SDK's log verbosity
    max_queue_size=5_000,   # any other option `Raindrop(...)` declares
)

result = raindrop.flush()   # the core's FlushResult; safe to ignore
```

- An option the installed `raindrop-ai` does not support is ignored with a
  debug log, never an error. `flush_timeout` and the `FlushResult` return
  value need `raindrop-ai` 0.0.76 or later; on older releases `flush()` and
  `shutdown()` return `None`.
- With `client=` (a `Raindrop` you built), configure these options on that
  client; the wrapper ignores them (debug log).
- `flush()` and `shutdown()` never raise. The result is truthy when
  everything was delivered, and reports `pending`, `dropped` and `timed_out`.

## Testing

```bash
cd packages/deep-agents-python
pip install -e ".[dev]"
python -m pytest tests/test_handler.py -v   # unit tests (no external services)
```

End-to-end behavior is verified by the cross-SDK **conformance harness**. This
package ships a thin conformance driver at
[`conformance/driver.py`](conformance/driver.py) that maps the shared scenario
corpus onto the wrapper's public API; known gaps are tracked as ticket-linked
entries in [`conformance/failures.txt`](conformance/failures.txt). The **fault
lane** runs on every PR touching `packages/*-python/**`
(`.github/workflows/conformance-wrappers-python.yml`) against a local capture
server; the **prod lane** verifies delivery by reading back through the public
[Query API](https://docs.raindrop.ai/api-reference/overview). The harness is
pinned by commit SHA (`HARNESS_REF`). See the harness docs:
[HOW-IT-WORKS](https://github.com/invisible-tools/raindrop-sdk-harness/blob/main/docs/HOW-IT-WORKS.md) ·
[AGENTS](https://github.com/invisible-tools/raindrop-sdk-harness/blob/main/AGENTS.md) ·
[README](https://github.com/invisible-tools/raindrop-sdk-harness/blob/main/README.md).

See [`examples/deep-agents-python-basic/`](../../examples/deep-agents-python-basic) for a runnable end-to-end example with a tool call, `identify()`, and `track_signal()`.
