Metadata-Version: 2.4
Name: originate-run-sdk
Version: 0.1.1
Summary: Backend SDK for Run, Originate's managed service: request metrics, calls to outside services, AI call telemetry, health, deploy and backup reports, policies and consent. No prompts, completions or request bodies ever leave the process.
Author: Originate, Inc.
License: Apache-2.0
Project-URL: Homepage, https://www.originatetech.com
Keywords: originate,run,monitoring,metrics,asgi,fastapi
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Framework :: FastAPI
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# originate-run-sdk

The Python backend SDK for Run, Originate's managed service. It reports what Originate needs to operate your application (request metrics, calls to outside services, AI call telemetry, health, deploys, backups, metered external calls, audit events) and reads the policies and consent decisions you configured in the Originate dashboard.

It never sends prompts, completions, request bodies, headers or user content. See "What is sent" below.

Python 3.9 or newer. No dependencies. A Node application uses `@originatedev/run-sdk`, which reports the same things.

## Install

```bash
pip install originate-run-sdk
```

## The server key

The SDK reports with the application's **server key**. It starts with `osk_` and it is a secret: it says that a report comes from your server.

1. In Originate, open the application's settings, then Run, then Backend SDK, and choose Create the server key (an administrator of the organization can). The same key serves every server of the application, the deploy step in your pipeline and the Originate server agent.
2. Put it in the server's environment as `ORIGINATE_RUN_SERVER_KEY`, the way you keep any other secret. Never commit it.

The SDK sends it as a bearer token over HTTPS, never in an address or a request body, and never writes it to a log. It refuses to send it over a connection that is not encrypted, except to the machine it runs on, and it never follows a redirect with it.

The key that starts with `opk_` is the public one in the website tag. The SDK does not accept it: anyone can read it in your pages.

## Init

```python
import os
import originate_run as run

run.init(
    release=os.environ.get("GIT_SHA"),   # or ORIGINATE_RUN_RELEASE
    service="api",                       # optional, when you run several processes
)
```

`init` reads the key from `ORIGINATE_RUN_SERVER_KEY`; pass `server_key=` to give it yourself. Other options: `api_base` (defaults to `https://api.platform.originatetech.com`, or `ORIGINATE_API_BASE`), `flush_interval` (seconds, 5), `heartbeat_interval` (seconds, 60; `0` sends none), `request_timeout` (seconds, 10), `on_error` (a function that receives each delivery problem), `disabled` (every call becomes a no-op).

`init()` returns the client and also makes it the module-level one, so the same functions work anywhere:

```python
import originate_run as run

run.track("order_placed", {"total_cents": 4200})
```

Before `init()` ran, calls are no-ops and nothing raises.

How it behaves in your process:

- **Nothing raises into your code.** A delivery problem goes to `on_error`; without one it is logged as a warning on the `originate_run` logger.
- **Nothing waits on the network in a request.** Reports are queued in memory and sent by one background thread. The exceptions are the calls that answer you: `deploy.report`, `backup.report`, `policy.check`, `consent.allows`, `heartbeat` and `flush`.
- **The thread never keeps the process alive**, and what is queued is sent when the process exits (one short attempt, so a slow network cannot hold the exit up). Call `run.shutdown()` from your own shutdown hook to send sooner.
- **Memory is bounded.** Queues drop their oldest rows on a long outage. Every delivery is tried three times with backoff; a refusal (4xx) is not retried.
- **Pre-forking servers work.** In a worker forked after `init()` (gunicorn with `--preload`), the SDK starts its thread again on the first report and sends only that worker's rows.

## Request metrics

Every response is counted per minute and per route (`METHOD route`), with 5xx errors and p50, p95 and p99 latency. Only the route template and timings are sent: no addresses with ids, no query strings, no headers.

### FastAPI, Starlette and other ASGI applications

```python
from fastapi import FastAPI
from originate_run.asgi import RunMiddleware

app = FastAPI()
app.add_middleware(RunMiddleware, ignore=["/health", "/static/*"])
```

The route is the framework's template (`/entries/{entry_id}`), with the prefix of a mounted sub-application. An address is never sent as it was typed:

- A response no route produced, such as a sign-in redirect from something in front of the router or a file from a static mount, is counted under one route, `(no route)`. Its address may hold an identifier, so it is not used.
- An address that matches no route and answers 404 is counted under `(not found)`, so a scanner walking made-up addresses does not become a thousand routes.
- A framework that never reports its routes (anything but FastAPI and Starlette today) has the path used instead, with UUIDs, numbers and long hex ids replaced by `:id`. An identifier of another shape (`/v/100-2403-121`) is not recognized, so with such a framework name the routes yourself with `run.metrics.record`, or pass `unrouted="group"`.

`unrouted` is `"auto"` by default (the behavior above); `"group"` and `"path"` force one or the other. Latency ends when the response is complete; background tasks that run afterwards are not counted.

`ignore` takes whole paths, prefixes ending in `*`, and compiled regular expressions. Leave out static files and health probes.

### Flask, Django and other WSGI applications

```python
from originate_run.wsgi import RunWSGIMiddleware

app.wsgi_app = RunWSGIMiddleware(app.wsgi_app, ignore=["/health"])    # Flask
application = RunWSGIMiddleware(get_wsgi_application())               # Django, in wsgi.py
```

WSGI does not say which route matched, so the path is used with UUIDs, numbers and long hex ids replaced by `:id`. An identifier of another shape (`/v/100-2403-121`) is not recognized and would be sent as part of the route: when your addresses hold such identifiers, pass `route=`, a function that takes the WSGI environ and returns the template or `None`.

### Anything else

```python
run.metrics.record("GET", "/users/{user_id}", 200, duration_ms, True)   # True: already a template
```

## Outside services

Time the calls your application makes to the services it depends on (its database, its file storage, another API), and Originate shows how each one is going next to what the vendor reports about itself: how many calls, how many failed, how slow.

```python
# Around a call. An exception passes through untouched and counts as a failure.
with run.dependency.time("postgres"):
    rows = conn.execute(sql).fetchall()

# As a decorator, on plain and async functions. `failed` judges a call that returns instead of raising.
@run.dependency.time("billing-api", failed=lambda response: response.status_code >= 500)
def charge(order): ...

# Or record it yourself: name, milliseconds, whether it worked.
run.dependency.record("resend", 182, True)
```

Inside a `with` block, `call.fail()` marks the call as failed without an exception (`with run.dependency.time("drive") as call:`). `async with` works too.

To cover every call made through `requests` or `httpx` in one line, time them by host. Calls to hosts of vendors Originate recognizes (Anthropic, OpenAI, Resend, SendGrid, Stripe, Supabase, Slack, Hugging Face and others, see `KNOWN_VENDOR_HOSTS`) are timed under the vendor's name; add your own hosts by name. A response with a 5xx status or a 429, and a call that raises, count as failed.

```python
run.dependency.instrument_requests(hosts={"www.googleapis.com": "google_workspace", "billing.internal.example.com": "billing-api"})
run.dependency.instrument_httpx()      # sync and async clients
```

Call them after `init()`. Each returns a function that undoes it. A host name starting with a dot matches every subdomain. Only the host, the status code and the duration are read: never the path, the query string, headers or bodies.

A name is a short lower case token (letters, digits, dot, dash, underscore, 40 at most); use a vendor's name where there is one (`neon`, `resend`, `anthropic`) so the row also carries that vendor's status. Calls are added up per minute and sent with the other batches. A database driver (psycopg, SQLAlchemy) is timed with `dependency.time()` around the query, or in the driver's own hook.

## Events, metering and audit

```python
run.track("order_placed", {"total_cents": 4200, "channel": "web"}, account_id="acct_123", session_id="sess_9")

run.meter("twilio_sms", 1, "message", cost_usd=0.0079)                       # an external_call event
run.meter("deepgram", 2.5, "minute", cost_usd=0.0108, props={"tier": "nova"})

run.audit.log("export_requested", "account:acct_123", {"by": "admin:42"})    # an audit_event
```

Event names are lower snake case (`^[a-z][a-z0-9_]{1,63}$`). Properties are dimensions, not content: strings, numbers, booleans and `None`; anything else is serialized to JSON and truncated. Never put emails, names or message text in properties.

## AI calls

```python
run.ai.record(
    provider="google",
    model="gemini-2.5-flash",
    operation="generate_content",
    input_tokens=1200,
    cached_tokens=0,
    output_tokens=310,
    duration_ms=840,
    finish_reason="STOP",
    feature="lead_summary",
    account_id="acct_123",          # your own id, never an email
)
```

All arguments: `provider`, `model`, `operation` (`chat` by default), `input_tokens`, `cached_tokens`, `output_tokens`, `duration_ms`, `ttft_ms`, `finish_reason`, `error_type`, `cost_usd`, `feature`, `account_id`, `source`, `guardrail_mode`, `guardrail_decision`, `guardrail_categories`, `batch`, `schema_version`, `occurred_at`. There is no argument for a prompt or a completion.

This version has no wrappers for the OpenAI and Anthropic clients: record each call from the usage the response carries.

## Health

```python
run.health.register("postgres", lambda: conn.execute("select 1") is not None)
run.health.register("drive", check_drive, critical=False)

@app.get("/health")
def health():
    status_code, body = run.health.handler()
    return JSONResponse(body, status_code=status_code)
```

A check returns `True` or nothing (ok), `False` (down), a status (`"ok"`, `"degraded"`, `"down"`) or `{"status": ..., "detail": ...}`; an exception or a timeout (3 seconds by default, `timeout=`) counts as down. It may be an `async` function. A critical check (the default) that is down takes the service down (HTTP 503); one that is not critical degrades it. The body is `{"status", "checks", "release", "service", "uptimeSeconds"}`.

`handler()` runs the checks and waits for them, so in FastAPI declare the endpoint with `def` (it then runs off the event loop), or call it with `await asyncio.to_thread(run.health.handler)`.

The same results ride on every heartbeat, which is sent at init and then every `heartbeat_interval`, so Originate sees your dependencies without probing them. A check named like one of the application's components in Originate (one that has no probe of its own) sets that component's state.

## Deploy reports

From code:

```python
run.deploy.report(version="1.4.0", commit=os.environ.get("GIT_SHA"), summary="Checkout fixes", pr_url=pr_url, deployer="github-actions", outcome="success")
```

From a pipeline or a deploy script, without touching the application:

```bash
ORIGINATE_RUN_SERVER_KEY=osk_... python -m originate_run deploy --version 1.4.0 --commit "$GIT_SHA" --summary "Checkout fixes" --deployer deploy-script --outcome success
```

The installed command `originate-run` is the same thing. It exits with 0 when the report was accepted.

Each report becomes a change record. A report whose version matches a release already prepared in Originate marks that release as shipped.

A deploy report says that a version went live. It is not how a release is created:

- Send one only from the pipeline that performed the deploy, after the deploy. A report for a deploy that did not happen records one that did.
- A report whose version matches no prepared release is still recorded, as a release that has already shipped and was not announced. It holds only the fields above, with no summary for customers, no tickets, no highlights and no approval, and a shipped release cannot be deleted.
- To prepare a release (name, summary, tickets, highlights, approval), use the Originate connector (the `release_get`, `release_update` and `release_highlight` tools of the Originate MCP server) or the Releases page of the application in the dashboard. An agent asked to "create a release" that has no connector should say so and stop, not send a deploy report.

## Backup reports

Run never takes backups. It records that yours happened, and works out from the reports how much data a failure could lose and how long a restore takes.

```python
run.backup.report("Primary database", size_bytes=18_500_000_000, duration_seconds=312)
run.backup.report("Primary database", kind="restore_test", status="ok", duration_seconds=840)
```

From the backup script or cron job:

```bash
python -m originate_run backup --datastore "Primary database" --status ok --size-bytes 18500000000
```

`kind` is `backup` (the default) or `restore_test`; `status` is `ok` (the default), `failed` or `partial`; `taken_at` defaults to now.

## Policies and consent

```python
decision = run.policy.check(data_classes=["pii"], purpose="marketing", region="eu", feature="newsletter")
# {"allowed": ..., "effect": "allow" | "deny" | "mask" | None, "policy_key": ..., "reason": ...}

answer = run.consent.allows("analytics", account.id)
# {"allowed": ..., "reason": "implicit" | "granted" | "withdrawn" | "unknown" | "no_policy" | "unavailable"}
```

Policies are the ones you manage in the dashboard. A policy matches when every dimension its rule lists intersects the input; deny wins over mask, mask over allow; no matching policy allows. The subject id passed to `consent.allows` is SHA-256 hashed before it leaves the process. Results are cached for five minutes; `run.policy.refresh()` clears the cache.

Both read over the network when the cache is cold, so in an `async` handler call them with `asyncio.to_thread`. An application that is not on Run gets `{"allowed": True, "reason": "no_policy"}`. When the answer cannot be read the reason is `unavailable`: allowed for `policy.check` (fail open on your own rules), not allowed for `consent.allows` (fail closed on a person's choice).

## Short-lived processes

A script, a cron job or a task worker that ends soon after its work should send before it ends:

```python
run.init(flush_interval=0, heartbeat_interval=0)   # no background thread
do_the_work()
run.flush(all=True)                                # sends everything, the minute in progress included; never raises
```

## What is sent, and what is not

Sent:

- Request metrics: route template, method, count, 5xx count, latency percentiles, per minute.
- Calls to outside services: the name you gave or the vendor a host belongs to, count, failed count, latency percentiles, per minute.
- AI calls: provider, model, operation, token counts, duration, time to first token, finish reason, error type, feature, your account id when you pass one.
- Events: the name, timestamp, your account and session ids when you pass them, and the properties you give.
- Heartbeats: SDK version, release, service name, health status per check (not the detail).
- Deploy and backup reports: what you put in them.

Never sent: prompts, completions, messages, request or response bodies, headers, cookies, IP addresses, emails, full addresses with ids. The middleware drops query strings and ids, and the `requests` and `httpx` timing reads the host and the status code only.

## Development

Changes per version are in [CHANGELOG.md](CHANGELOG.md). The tests use the standard library only:

```bash
python3 -m unittest discover -s tests -t tests
```

## License

Apache-2.0. Copyright 2026 Originate, Inc. See [LICENSE](LICENSE).
