Raindrop Python SDK
The official Python SDK for Raindrop AI — track AI events, collect user signals, and instrument LLM applications with OpenTelemetry-based tracing.
No write key yet? Agents can create one now, without a browser: run npx -y create-raindrop --org-name '<project name>' and give the user the claim link. Steps, including a plain HTTP call without Node: raindrop.ai/auth.md.
Installation
pip install raindrop-ai
Requires Python 3.10+
Quick Start
import raindrop.analytics as raindrop
raindrop.init(api_key="your-api-key", tracing_enabled=True)
# Track an AI event
raindrop.track_ai(
user_id="user-123",
event="chat-completion",
model="gpt-4",
input="What is the weather?",
output="It's sunny and 72°F.",
convo_id="conv-456",
)
Evals
Replay local agents against datasets, use hosted or local evaluators, and save
results in Raindrop. Python accepts the same manifests as the UI and JavaScript.
See Evals in Python for setup, pytest, and examples.
Application Git provenance
The SDK reports the application-under-test commit on events and owning spans
as raindrop.app.commit_sha. When known it also reports
raindrop.app.commit_dirty; branch reporting is opt-in. This is application
Git metadata, not the raindrop-ai package version, and it does not rewrite
release or SDK identity fields.
By default, explicit Raindrop environment values are read once at client
initialization and a local Git lookup is attempted once on a bounded daemon
thread. Event and span calls never run Git or wait for discovery; an operation
that starts before discovery finishes keeps an empty metadata snapshot.
Automatic sources are selected without combining identities. A nonempty
source_directory or RAINDROP_GIT_SOURCE_DIRECTORY explicitly names the
application repository and takes priority over ambient deployment and CI
metadata, with no fallback if that repository cannot be read. Otherwise,
marked Vercel, Railway, or Heroku deployment metadata is preferred, then the
current directory's local Git repository, then marked CI metadata from GitHub
Actions, GitLab CI, Buildkite, or CircleCI. Generic unmarked CI variables are
ignored. Source directories are resolved to an absolute path when the client
is initialized. Automatic SHAs must be full 40- or 64-character hex; dirty
state and branch are omitted unless a bounded final HEAD check confirms they
describe the reported commit.
Local Git lookup requires nonblocking pipe support and is skipped on Windows
with Python earlier than 3.12. Explicit app_git values and supported
deployment or CI environment sources remain available on those runtimes.
from raindrop import AppGitOptions, Raindrop
git_options: AppGitOptions = {
"source_directory": "/srv/my-application",
"detect_branch": True,
}
rd = Raindrop(api_key="...", app_git=git_options)
# Disable all application-Git enrichment.
rd_without_git = Raindrop(api_key="...", app_git=False)
The same app_git option is accepted by raindrop.analytics.init(). Explicit
commit_sha, commit_dirty, and branch values may be supplied in the
mapping. Existing canonical operation properties always win, including null,
empty, or invalid values:
rd.track_ai(
user_id="user-123",
event="chat-completion",
input="hello",
properties={"raindrop.app.commit_sha": supplied_revision},
)
Git contexts are bounded by max_queue_size (10,000 by default). Completed
operations free their entries. If simultaneously active partial operations
overflow that bound, new IDs omit client/default Git context until the client
is recreated; explicit per-operation properties still work. Small custom queue
limits reach this boundary sooner. This fail-closed behavior prevents an
overflowed operation from acquiring a different revision midway through its
lifetime and does not block or fail the agent's execution.
Track a plain, non-AI event through the same local queue and batched
events/track transport:
raindrop.track(
user_id="user-123",
event="cache-hit",
properties={"region": "us-east-1", "tags": ["hot", "shared"]},
event_id="event-456", # optional; generated when omitted
timestamp="2026-07-13T18:00:00Z",
attachments=[
raindrop.Attachment(type="text", value="cached response", role="output")
],
)
Plain events have no conversation association — there is no convo_id
parameter. To group events into a conversation, use track_ai / begin
(partials), which carry convo_id on the AI-data branch.
Instance-based clients (multiple projects in one process)
raindrop.Raindrop is the instance-shaped counterpart of the module API —
the same shape as the JS (new Raindrop({...})), Go, Rust, and Java SDKs.
Each instance owns its configuration and event pipeline, so one service can
route different agents to different projects concurrently:
from raindrop import Raindrop
rd_support = Raindrop(api_key=KEY, project_id="support-agent", tracing_enabled=True)
rd_billing = Raindrop(api_key=KEY, project_id="billing-agent", tracing_enabled=True)
# Everything hangs off the instance — same method names as the module API.
rd_support.track(user_id="u1", event="session-started", properties={"plan": "pro"})
interaction = rd_billing.begin(user_id="u1", event="billing-chat", input="...")
interaction.track_tool(name="invoice_lookup", input=..., output=...)
interaction.finish(output="...")
rd_support.track_ai(user_id="u1", event="support-chat", input="q", output="a")
rd_support.track_signal(event_id=..., name="thumbs_up")
Create instances once at startup and reuse them (see
example/fastapi_multi_project.py for a two-agent FastAPI app). Manual
events (track_ai, begin/finish, signals, identify) ship on each
instance's own connections with its own headers — fully isolated per
instance. The module-level API keeps working unchanged; it is simply the
default, process-wide instance of the same machinery.
rd.track_ai_partial(event) streams an incremental track_ai patch (a
PartialTrackAIEvent) into that instance's own buffers — the per-instance
counterpart used by integration wrappers that emit partial events. Its
read-only rd.write_key property exposes the key backing the instance
(e.g. to compare whether two clients are equivalent) without reaching into
internals.
Tracing with multiple instances
OpenTelemetry tracing is a process singleton (one tracer provider, one
exporter, global auto-instrumentation). The first instance constructed with
tracing_enabled=True initializes it; later tracing instances share it.
Span routing is per-span: begin() binds the current request/task to its
client's project until the matching finish() (which restores the
previous binding — abandoned interactions release theirs when garbage
collected), and every span started while bound carries a
raindrop.project_id attribute that the ingest boundary routes on. For
LLM/library calls made outside an interaction, scope them explicitly:
with rd_billing.as_current():
openai_client.chat.completions.create(...) # spans route to billing-agent
Two limitations, by design:
- One tracing key/org per process. Instances created with a different
api_key than the pipeline owner's get a constructor warning, and from
that point the export guard only ships spans positively attributed to the
owner: the foreign client's spans and any unattributed spans (emitted
outside begin()/as_current()) are dropped at export — nothing can
ride the wrong org's credential. Single-key processes are unaffected
(spans stay byte-identical). Manual events always route correctly. Run a
second org's tracing in its own process.
interaction.track_tool() with bypass_otel_for_tools=True skips the
shared pipeline entirely and ships on the instance's own connection —
those spans route per instance with no caveats.
Payload size limits
As of 0.0.52, text fields (ai input/output, tool span I/O, LLM span
content) are capped at 1,000,000 characters per field by default and
truncated with a ...[truncated by raindrop] marker. Fields up to 1M chars
— i.e. everything the ingest API accepts today — round-trip unchanged. The
cap is enforced before (or during) serialization, so oversized payloads cost
the cap — not the payload — on your calling thread, and a single capped
ASCII field still fits under the 1 MB event-level ingest limit. Tune it via:
raindrop.init(api_key="...", max_text_field_chars=250_000) # process-wide default
# Instance clients cap themselves only (never other clients or the default):
rd = Raindrop(api_key="...", max_text_field_chars=100_000)
A stricter OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT env var is still honored
for span content. All outbound HTTP carries finite timeouts, and the atexit
shutdown flush runs under a 10s deadline so a dead network can never wedge
your process exit.
Projects
If your org has a single project, you don't need to do anything — events go to
the default Production project automatically. When you have more than one
project, route events to a specific one by passing its slug as project_id to
init(). When set, every outbound request attaches an
X-Raindrop-Project-Id: <slug> header so events land under the named project
instead of the org default:
raindrop.init(api_key="your-api-key", project_id="my-project")
The header is attached to every channel — manual events (track_ai,
identify, track_signal, partial events, direct tool/trace POSTs), the
local Workshop mirror, and auto-instrumented OpenTelemetry spans exported via
Traceloop — so all telemetry routes to the same project.
Slugs must match ^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$ (lowercase
alphanumerics and dashes, not starting or ending with a dash). Invalid values
are logged as a warning and ignored — no exception is raised and no header is
sent. Omitting project_id (or passing "default") is fully backward
compatible: events fall back to your org's default Production project.
Interactions
Use begin() and finish() for multi-step AI workflows:
interaction = raindrop.begin(
user_id="user-123",
event="agent-run",
input="Search for weather data",
convo_id="conv-456",
)
# Update incrementally
interaction.set_property("region", "us-east")
interaction.add_attachments([
raindrop.Attachment(type="code", value="print('hello')", language="python")
])
# Complete the interaction
interaction.finish(output="Found weather data for NYC")
Tool Definitions
Pass tools= to begin() (or raindrop.interaction(..., tools=[...]), interaction.set_tools([...]), or the raindrop.prompt_tools([...]) context manager) to record the tool list the model was offered. Every model-call span started inside the interaction gets ai.prompt.tools set to that list — one JSON string per tool in the canonical {"type": "function", "name", "description", "inputSchema"} shape — replacing anything the instrumentation captured. OpenAI ({"type": "function", "function": {...}}) and Anthropic ({"name", "description", "input_schema"}) tool dicts are accepted and normalised; {"type": "provider-defined", "id", "name", "args"} records a provider-owned tool as-is, and tools=[] records that the model had no tools. Non-model spans are never stamped.
interaction = raindrop.begin(
user_id="user-123",
event="agent-run",
input="What's the weather?",
tools=[
{
"type": "function",
"name": "get_weather",
"description": "Look up the current weather",
"inputSchema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}
],
)
A span counts as a model call when it carries llm.request.type, gen_ai.request.model, llm.request.model or OpenInference's llm.model_name. Without an override, ai.prompt.tools is rebuilt at export time from the tool list the OpenLLMetry instrumentations record on model spans: gen_ai.tool.definitions (one JSON string, written by OpenLLMetry 0.54.0+ for Anthropic and 0.55.0+ for OpenAI/LangChain) or the older llm.request.functions.{i}.name/.description/.parameters attributes. SDK 0.0.72+ mirrors both shapes, consulting llm.request.functions.* first, and records nothing when the attribute is not valid JSON. Both the implicit capture and the override follow the content-capture setting, so TRACELOOP_TRACE_CONTENT=false never records the attribute.
When the list you pass is a catalog rather than the exact per-request list — an agent framework's tool registry that may overstate what one model call received — mark it with source on the raindrop.prompt_tools([...], source="...") context manager. The same model spans then also carry ai.prompt.tools.source (a string such as "agno.agent.tools"), under the same content gate, so consumers can tell a catalog from exact capture. begin(tools=...), interaction.set_tools([...]) and prompt_tools([...]) without source are explicit overrides and never carry ai.prompt.tools.source, including when they run inside a source-marked scope. Lists mirrored from the instrumentation attributes are exact per-request capture and carry no source marker either.
with raindrop.prompt_tools(agent_tool_catalog, source="agno.agent.tools"):
agent.run("What's the weather?")
Resuming Interactions
Access the current interaction from nested functions:
@raindrop.tool("sentiment_analyzer")
def analyze_sentiment(text: str):
interaction = raindrop.resume_interaction()
interaction.set_property("sentiment", "positive")
return {"sentiment": "positive"}
Continue an event begun in another process (a queue worker, a later request) by its id. Nothing is sent by the call itself. Pass user_id, convo_id and event_name if you have them: every later update and the finish for that event carry them.
interaction = raindrop.resume_interaction(
event_id, user_id="user-123", convo_id="convo-456", event_name="chat"
)
interaction.finish(output="Here is the summary.")
Without a user_id the updates are still sent and Raindrop keeps the user it already has for the event; the SDK logs a warning saying so. A blank user_id (or "null" / "undefined") counts as no user id.
Decorators
Instrument functions with automatic span creation:
@raindrop.interaction("my_workflow")
def run_workflow():
...
@raindrop.task("process_data")
def process():
...
@raindrop.tool("search")
def search(query: str):
...
Spans
Context Managers
with raindrop.task_span("process_data"):
result = do_processing()
with raindrop.tool_span("web_search"):
results = search(query)
Manual Spans
For async or distributed operations where you need explicit control:
span = raindrop.start_span(kind="tool", name="async_search")
span.record_input({"query": "weather"})
# ... later, when the result arrives
span.record_output({"result": "sunny"})
span.end()
Retroactive Tool Logging
Log tool calls after they complete, without wrapping them in spans:
interaction = raindrop.begin(user_id="user-123", event="agent-run")
interaction.track_tool(
name="web_search",
input={"query": "weather in NYC"},
output={"results": ["Sunny, 72°F"]},
duration_ms=150,
)
interaction.track_tool(
name="database_query",
input={"query": "SELECT * FROM users"},
duration_ms=50,
error=ConnectionError("Connection timeout"),
)
interaction.finish(output="Done")
Signals
Track user feedback on AI outputs: