Metadata-Version: 2.5
Name: apphelm
Version: 0.6.0
Summary: Official Python server SDK for Apphelm: events, identify, fail-closed feature flags, errors and tracing.
Project-URL: Homepage, https://apphelm.dev
Project-URL: Documentation, https://apphelm.dev/docs
Author-email: SansaVision <support@sansavision.com>
License-Expression: LicenseRef-Proprietary
License-File: LICENSE
Keywords: analytics,apphelm,error-monitoring,feature-flags,tracing
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# Apphelm Python SDK

The official Python client for [Apphelm](https://apphelm.dev), for server-side code: product
events, identify, alias and groups, fail-closed feature flags, error and message reporting, cron check-ins and
tracing. One module, standard library only, Python 3.10 or later.

```bash
pip install apphelm
```

Use a server API key (`ahl_…`) from your Apphelm workspace and keep it secret. Never ship it in
a browser or mobile app.

```py
import os
from apphelm import Apphelm

apphelm = Apphelm(api_key=os.environ["APPHELM_API_KEY"])

# A product event for one person.
apphelm.capture("org_…", "prd_…", distinct_id=customer.id, event_name="invoice_sent")

# Feature flags fail closed: any network, timeout or API error evaluates to False.
if apphelm.is_enabled("new-checkout", customer.id, product_id="prd_…"):
    render_new_checkout()
variant = apphelm.get_feature_flag("org_…", "prd_…", "pricing-test", customer.id)  # variant, True or False
```

## LLM analytics

`apphelm_llm` (in the same package, standard library only) records the calls your server makes to its own model provider as PostHog-compatible `$ai_*` events. AppHelm never calls a model: the wrappers sit around your existing OpenAI or Anthropic client, sync or async, and send AppHelm what happened.

```py
from apphelm_llm import wrap_openai, wrap_anthropic, capture_ai_generation, capture_ai_feedback, capture_ai_metric, flush

client = wrap_openai(OpenAI(), apphelm, "org_…", "prd_…", distinct_id=user.id)
client.chat.completions.create(model="gpt-5-mini", messages=messages, apphelm={"trace_id": request_id})

claude = wrap_anthropic(AsyncAnthropic(), apphelm, "org_…", "prd_…", distinct_id=user.id)
await claude.messages.create(model="claude-haiku-4-5", max_tokens=512, messages=messages, stream=True)

capture_ai_generation(apphelm, "org_…", "prd_…", model="llama-3.3-70b", provider="self-hosted", distinct_id=user.id, input_tokens=812, output_tokens=96, latency_seconds=0.64)
capture_ai_feedback(apphelm, "org_…", "prd_…", trace_id=request_id, text="That fixed it", distinct_id=user.id)
```

- `wrap_openai` records `chat.completions.create`, `responses.create` and `embeddings.create`; `wrap_anthropic` records `messages.create`. Streams are recorded when they end.
- Prompts and completions are sent only with `capture_content=True` (on the wrapper, or `apphelm={"capture_content": True}` per call), bounded to 20,000 characters of JSON per field.
- Events go on a background thread; call `flush()` before a short-lived process exits, or pass `sync=True`. A failed send goes to `on_error` and never into your code; a failed model call is recorded and re-raised.
- Run its tests with `python3 -m unittest test_apphelm_llm`.

See [LLM analytics](https://apphelm.dev/docs#sdk) for the event contract and how cost is worked out.

## Identify, alias and groups

These send the same events as every other Apphelm SDK (`$identify`, `$create_alias`,
`$groupidentify`, `$groups`; see docs/SDK.md "Identity").

```py
# At sign-in. anon_distinct_id is the id the person had before (an anonymous browser or device id
# you forwarded): their earlier events then count for them. traits are sent as $set.
apphelm.identify("org_…", "prd_…", distinct_id=account.id, traits={"plan": "builder"},
                 anon_distinct_id=request.cookies.get("anon_id"), set_once={"signup_source": "ads"})

# Link another id of the same person (an id from an older system, say) to this one.
apphelm.alias("org_…", "prd_…", distinct_id=account.id, alias=legacy_id)

# Group properties. The group type "account" is the account Node group() names; any other type
# is its own account. name and plan fill the account's name and plan.
apphelm.group("org_…", "prd_…", "company", company.id, {"name": company.name, "plan": "scale"})

# Attach an event to its groups.
apphelm.capture("org_…", "prd_…", distinct_id=account.id, event_name="report_exported", groups={"company": company.id})
```

- An earlier id is linked one way, earlier → identified. It is never linked when it already
  belongs to another identified person: two identified customers are never merged
  automatically, and the pair goes to the identity review queue instead.
- `traits` and `set_once` become customer traits under your customer model, consent and plan
  limits, recorded as product-event, system-observed provenance (`set_once` only fills traits
  the customer has none of yet). Trait keys must be lowercase letters, digits and `_`;
  credential and special-category keys are left out.
- For explicit provenance, pass `trait_sources`, one entry per trait. The call is then sent as
  `apphelm.identify`, and a trait without a matching source (or a source without a trait) raises
  `ValueError` before anything is sent, because the API would reject it:

```py
apphelm.identify("org_…", "prd_…", account.id, traits={"plan": "builder"},
                 trait_sources={"plan": {"sourceType": "auth", "sourceId": "session", "verification": "integration_verified"}})
```

`external_user_id=` still works as another name for `distinct_id`.

## Errors and messages

```py
try:
    charge(order)
except Exception as error:
    apphelm.capture_exception("org_…", "prd_…", error, release=os.environ.get("RELEASE"),
                              environment="production", tags={"route": "/charges"}, user_id=account.id)

# Report uncaught exceptions (main thread and other threads) as unhandled issues.
# The previous hooks still run, so the traceback prints and the process exits as before.
restore = apphelm.capture_unhandled("org_…", "prd_…", release=os.environ.get("RELEASE"), environment="production")

apphelm.capture_message("org_…", "prd_…", "Payment provider fell back to retries", level="warning")
```

Tracebacks are scrubbed of email addresses, keys and query strings before they are sent, and
`user_id` is sent only as a hash. Pass `before_send=` to the constructor to change or drop
exceptions and messages: return the properties (changed or not), or `None` to drop the event. A
hook that raises drops the event.

## Tracing

```py
# Continue the caller's trace (from the browser or another service), or start a new one.
with apphelm.start_transaction("org_…", "prd_…", "POST /charges", traceparent=request.headers.get("traceparent")) as tx:
    with tx.start_span("db.query", "select order"):
        ...
```

`Apphelm(api_key, traces_sample_rate=0.2)` keeps a share of new transactions; a transaction that
continues an incoming `traceparent` keeps the caller's sampling decision.

## Cron check-ins

```py
apphelm.check_in("prd_…", monitor="nightly-export", status="ok", duration_ms=5400)
```

## Errors from the client

Failed requests raise `ApphelmError` with `status` and `code`. Flag checks (`is_enabled`,
`get_feature_flag`) never raise for a failed request; they return `False`.

## Licence

Proprietary. See `LICENSE`: use requires an active Apphelm service agreement.

Releasing this package: `docs/SDK-RELEASING.md` in the Apphelm repository.
