Metadata-Version: 2.5
Name: dataframer-journey
Version: 1.0.0
Summary: Automatic journey_id propagation for DataFramer — inbound extraction, outbound header injection, Langfuse and LangSmith trace stamping
Project-URL: Repository, https://github.com/aimonlabs/dataframer-journey-py
License: Copyright (c) 2026 AIMon Labs, Inc. All rights reserved.
        
        Permission is granted to use this software solely for the purpose of
        integrating with and sending data to the DataFramer service, whether
        directly or as part of a licensed application.
        
        Redistribution, resale, sublicensing, reverse engineering, or creation
        of derivative works based on this software, in whole or in part, is
        not permitted without the prior written permission of AIMon Labs, Inc.,
        except as expressly permitted under a separate written agreement.
License-File: LICENSE
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# dataframer-journey

Automatic `journey_id` propagation for [DataFramer](https://dataframer.ai) user-signal stitching. One line per service; after that the journey id flows browser → service → service → trace without anyone threading it by hand.

**Full documentation:** [Link AI Traces to Journeys](https://www.dataframer.ai/docs/user-signals/link-traces) — journey id semantics, framework setup, and trace stamping details; [Send Events from Backend](https://www.dataframer.ai/docs/user-signals/backend-events) — sending events from your server.

> **New to DataFramer?** It's an AI Workflow Intelligence Platform — once journeys are stitched, see the full timeline of user actions, traces, agents, and events, then turn every accuracy fix into reusable business context.
> [Start free →](https://app.dataframer.ai/?screen=signup&utm_source=pypi&utm_medium=readme&utm_campaign=oss)

## Install

```
pip install dataframer-journey
```

Zero runtime dependencies. Hooks apply only to libraries you already have (`requests`, `httpx`, `langfuse`, `langsmith`).

## Usage

**FastAPI / Starlette:**

```python
from dataframer_journey import instrument

app = FastAPI()
instrument(app)
```

**Django** — call `instrument()` at the end of `settings.py` and add the middleware, above `django-cors-headers`' `CorsMiddleware` if you use it:

```python
MIDDLEWARE = [
    'dataframer_journey.django.JourneyIdMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    ...,
]

import dataframer_journey
dataframer_journey.instrument()
```

That's it. From then on:

- **Inbound**: the journey id is read off each incoming request (`baggage` header → `X-Journey-Id` header → `df_journey_id` cookie set by `@dataframer/signals`) into request-scoped context.
- **Outbound**: outgoing `requests`/`httpx` calls to your own services carry it to the next service (both `X-Journey-Id` and W3C `baggage`, so it also rides existing OpenTelemetry propagation). By default that means private addresses only: localhost, private IPs, single-label names and `*.internal` / `*.local` / Kubernetes `*.svc` hostnames. List your public services with `instrument(propagate_to=['https://agents.acme.com'])`. Third parties such as LLM vendors never receive it, not even when one of your services redirects to them. Explicitly-set headers are never overwritten.
- **Celery**: a task queued during the request carries the id in its message headers, and the worker runs it inside the journey, so its traces are stamped and the tasks it queues carry the id on. Call `instrument()` in the worker process too.
- **Traces**: every Langfuse trace and every LangSmith run created during the request gets `metadata.journey_id` (and a `journey:<id>` tag) stamped automatically. Metadata you set on the trace or run yourself is kept; an explicit `journey_id` there wins.

**Other non-HTTP entry points** (other queue consumers, scheduled jobs, raw `ThreadPoolExecutor` or `run_in_executor` work, WebSocket handlers): take the id from the payload yourself —

```python
from dataframer_journey import with_journey, get_journey_id

with with_journey(payload["journey_id"]):
    ...  # traces created here are stamped; outbound calls carry the id
```

**Events from your backend** (an order completed, a refund issued): send them with the same write key the browser uses. Inside a request or a `with_journey` block, the event joins that journey —

```python
from dataframer_journey import Signals

signals = Signals(write_key=os.environ['DATAFRAMER_WRITE_KEY'])
signals.track('OrderCompleted', {'order_id': order.id, 'total': 42.5}, user_id=user.email)
```

Events go out in the background, in batches, and are retried while DataFramer is busy or unreachable. An event the server keeps failing on is dropped after five tries, with a warning in the log, so it never holds up the events behind it. Pass `journey_id=` for work outside a request, and call `signals.flush()` before a short-lived process such as a serverless function returns. It waits up to 30 seconds, or the `timeout=` you pass, and returns `False` if some events are still unsent.

**Already using PostHog?** Its browser library can send its session id to your API: set `tracing_headers: ['api.acme.com']` in `posthog.init`. Then read that header as the journey id —

```python
instrument(app, journey_headers=['X-POSTHOG-SESSION-ID'])
```

Traces get the PostHog session id, which every PostHog event also carries as `$session_id`, so DataFramer can link your PostHog events to them (in DataFramer, set the link mode to match `properties.$session_id` on events with `metadata.journey_id` on traces). PostHog also sends `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-WINDOW-ID`; if your API is on another origin, its CORS settings must allow all three. PostHog loads this part of its library shortly after the page starts, so the first requests on a page may carry no header.

## Notes

- Langfuse SDK v2, v3 (3.9.0 or newer), v4 and v5 are supported, through the v2 `trace()` method or the OpenTelemetry-based `propagate_attributes()` scope. Langfuse 3.0–3.8 has no such scope: the library logs a warning and does not stamp; upgrade.
- LangSmith is supported (tested with 0.3.45 and 0.14.0) via its `tracing_context()` scope: `@traceable` functions, `trace()` blocks, wrapped OpenAI clients, and LangChain/LangGraph runs all pick it up.
- At start, `instrument()` logs one `INFO` line on the `dataframer_journey` logger naming the tracing SDKs it stamps and the HTTP clients that carry the id.
- Signals showing as unmatched? Set the `dataframer_journey` logger to `DEBUG`: it names every request that arrived without a journey id and, on Langfuse v2, every trace created outside one.
- Traces are stamped only while the request or `with_journey` block is running; a span or run started from a background task after the request ends carries no id.
- The browser side is [`@dataframer/signals`](https://www.npmjs.com/package/@dataframer/signals), which generates the journey id and sends it on requests to your API.
- CORS: if your frontend and API are on different origins, the browser must be allowed to send the `X-Journey-Id` header. The middleware allows it by itself, for the origins your CORS setup already allows; it never allows a new origin. On Django it must sit above `django-cors-headers`' `CorsMiddleware`, and logs a warning when it does not. Allow the header yourself when your CORS is answered before the app (nginx, an API gateway, a CDN) or on an API this library does not run in. Same-origin setups need nothing.
