Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dc54b8aa5 | ||
|
|
d5442136d9 |
@@ -0,0 +1,64 @@
|
||||
---
|
||||
name: integration-fastapi
|
||||
description: PostHog integration for FastAPI applications
|
||||
metadata:
|
||||
author: PostHog
|
||||
version: 1.29.1
|
||||
---
|
||||
|
||||
# PostHog integration for FastAPI
|
||||
|
||||
This skill helps you add PostHog analytics to FastAPI applications.
|
||||
|
||||
## Workflow
|
||||
|
||||
Follow these steps in order to complete the integration:
|
||||
|
||||
1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here**
|
||||
2. `references/2-edit.md` - PostHog Setup - Edit
|
||||
3. `references/3-revise.md` - PostHog Setup - Revise
|
||||
4. `references/4-conclude.md` - PostHog Setup - Conclusion
|
||||
|
||||
## Reference files
|
||||
|
||||
- `references/EXAMPLE.md` - FastAPI example project code
|
||||
- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan
|
||||
- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project
|
||||
- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation
|
||||
- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation
|
||||
- `references/python.md` - Python - docs
|
||||
- `references/identify-users.md` - Identify users - docs
|
||||
|
||||
The example project shows the target implementation pattern. Consult the documentation for API details.
|
||||
|
||||
## Key principles
|
||||
|
||||
- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them.
|
||||
- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code.
|
||||
- **Match the example**: Your implementation should follow the example project's patterns as closely as possible.
|
||||
|
||||
## Framework guidelines
|
||||
|
||||
- Initialize PostHog in the lifespan context manager on startup using posthog.api_key and posthog.host
|
||||
- Call posthog.flush() in the lifespan shutdown to ensure all events are sent before the app exits
|
||||
- Use Pydantic Settings with @lru_cache decorator on get_settings() for caching and easy test overrides
|
||||
- Use FastAPI dependency injection (Depends) for accessing current_user and settings in route handlers
|
||||
- Use the same context API pattern as Flask/Django (with new_context(), identify_context(user_id), then capture())
|
||||
- Remember that source code is available in the venv/site-packages directory
|
||||
- posthog is the Python SDK package name
|
||||
- Install dependencies with `pip install posthog` or `pip install -r requirements.txt` and do NOT use unquoted version specifiers like `>=` directly in shell commands
|
||||
- In CLIs and scripts: MUST call posthog.shutdown() before exit or all events are lost
|
||||
- Always use the Posthog() class constructor (instance-based API) instead of module-level posthog.api_key config
|
||||
- Always include enable_exception_autocapture=True in the Posthog() constructor to automatically track exceptions
|
||||
- NEVER send PII in capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content
|
||||
- PII belongs in identify() person properties, NOT in capture() event properties. Safe event properties are metadata like message_length, form_type, boolean flags.
|
||||
- Register posthog_client.shutdown with atexit.register() to ensure all events are flushed on exit
|
||||
- The Python SDK has NO identify() method — use posthog_client.set(distinct_id=user_id, properties={...}) to set person properties, or use identify_context(user_id) within a context
|
||||
|
||||
## Identifying users
|
||||
|
||||
Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation.
|
||||
|
||||
## Error tracking
|
||||
|
||||
Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: PostHog Setup - Begin
|
||||
description: Start the event tracking setup process by analyzing the project and creating an event tracking plan
|
||||
---
|
||||
|
||||
We're making an event tracking plan for this project.
|
||||
|
||||
This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report.
|
||||
|
||||
## Task list
|
||||
|
||||
As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty.
|
||||
|
||||
It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call.
|
||||
|
||||
Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context.
|
||||
|
||||
Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting.
|
||||
|
||||
From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents.
|
||||
|
||||
Look for opportunities to track client-side events.
|
||||
|
||||
**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like:
|
||||
|
||||
- Payment/checkout completion
|
||||
- Webhook handlers
|
||||
- Authentication endpoints
|
||||
|
||||
Do not skip server-side events - they capture actions that cannot be tracked client-side.
|
||||
|
||||
Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them.
|
||||
|
||||
Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel.
|
||||
|
||||
As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step.
|
||||
|
||||
## Status
|
||||
|
||||
Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in:
|
||||
|
||||
[STATUS] Checking project structure.
|
||||
|
||||
Status to report in this phase:
|
||||
|
||||
- Checking project structure
|
||||
- Verifying PostHog dependencies
|
||||
- Generating events based on project
|
||||
|
||||
## Abort statuses
|
||||
|
||||
If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you.
|
||||
|
||||
---
|
||||
|
||||
**Upon completion, continue with:** [2-edit.md](2-edit.md)
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: PostHog Setup - Edit
|
||||
description: Implement PostHog event tracking in the identified files, following best practices and the example project
|
||||
---
|
||||
|
||||
For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents.
|
||||
|
||||
Use environment variables for PostHog keys. Do not hardcode PostHog keys.
|
||||
|
||||
If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it.
|
||||
|
||||
For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach.
|
||||
|
||||
Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference.
|
||||
|
||||
Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant.
|
||||
|
||||
It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate.
|
||||
|
||||
You should also add PostHog exception capture error tracking to these files where relevant.
|
||||
|
||||
Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted.
|
||||
|
||||
Remember the documentation and example project resources you were provided at the beginning. Read them now.
|
||||
|
||||
## Status
|
||||
|
||||
Status to report in this phase:
|
||||
|
||||
- Inserting PostHog capture code
|
||||
- A status message for each file whose edits you are planning, including a high level summary of changes
|
||||
- A status message for each file you have edited
|
||||
|
||||
---
|
||||
|
||||
**Upon completion, continue with:** [3-revise.md](3-revise.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: PostHog Setup - Revise
|
||||
description: Review and fix any errors in the PostHog integration implementation
|
||||
---
|
||||
|
||||
Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents.
|
||||
|
||||
Ensure that any components created were actually used.
|
||||
|
||||
Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase.
|
||||
|
||||
## Status
|
||||
|
||||
Status to report in this phase:
|
||||
|
||||
- Finding and correcting errors
|
||||
- Report details of any errors you fix
|
||||
- Linting, building and prettying
|
||||
|
||||
---
|
||||
|
||||
**Upon completion, continue with:** [4-conclude.md](4-conclude.md)
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
title: PostHog Setup - Conclusion
|
||||
description: Review and fix any errors in the PostHog integration implementation
|
||||
---
|
||||
|
||||
Create a live PostHog dashboard named "Analytics basics (wizard)" from the events you just instrumented, then populate it with up to five insights — lead with the business-critical views: conversion funnels, churn events, and other key signals. Use the exact same event names as implemented in the code. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go.
|
||||
|
||||
## How to call PostHog MCP tools
|
||||
|
||||
The PostHog MCP server exposes a single `exec` tool. Every PostHog operation is driven by a CLI-style command string passed in its `command` parameter — the tool may be namespaced by the host (`mcp__posthog__exec`, `mcp__posthog-wizard__exec`), but the command grammar is the same. Tool names and schemas are not predictable, so discover and inspect before you call.
|
||||
|
||||
**Grammar** — run in this order:
|
||||
|
||||
```text
|
||||
exec({ "command": "search <regex>" }) # find tools by name/title/description; `tools` lists them all
|
||||
exec({ "command": "info <tool_name>" }) # REQUIRED before every call — description + input schema
|
||||
exec({ "command": "schema <tool_name> <field_path>" }) # drill into a field the schema flags with a `hint`
|
||||
exec({ "command": "call <tool_name> <json_input>" }) # run the tool
|
||||
```
|
||||
|
||||
Running `info <tool_name>` before `call <tool_name>` is mandatory, the same way you read a file before editing it. `info` returns the full schema for simple tools; for large ones it summarizes and attaches `hint` entries pointing at fields to drill into with `schema`. Dot-notation descends objects (`query.source`), array items (`series.0.properties`), and unions. Never guess the structure of a field that carries a hint — drill first.
|
||||
|
||||
Every PostHog tool goes through `exec` this way — there is no separate named tool to call directly. The inner tool names and JSON payloads below are what you pass to `call`.
|
||||
|
||||
**Errors** carry a suggestion and similar tool names — read it before retrying. If a name isn't found it may have been renamed; run `search <pattern>` or `tools` again to find the current one.
|
||||
|
||||
Create the parent dashboard first with `dashboard-create`, capture its returned `id`, then attach every insight to it via `dashboards: [<id>]`:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Analytics basics (wizard)",
|
||||
"description": "Key views for the events instrumented by the PostHog wizard.",
|
||||
"tags": ["wizard"]
|
||||
}
|
||||
```
|
||||
|
||||
When calling `insight-create`, use these known-good query shapes — they are verified against the MCP schema, and the common variations around them are rejected:
|
||||
|
||||
A trends insight with a breakdown (breakdowns go in `breakdownFilter.breakdowns`, an array — there is NO top-level `breakdown` field on `TrendsQuery`):
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Signups by plan (wizard)",
|
||||
"dashboards": [<dashboard id from dashboard-create>],
|
||||
"query": {
|
||||
"kind": "InsightVizNode",
|
||||
"source": {
|
||||
"kind": "TrendsQuery",
|
||||
"series": [{ "kind": "EventsNode", "event": "user_signed_up", "math": "total" }],
|
||||
"interval": "day",
|
||||
"dateRange": { "date_from": "-30d" },
|
||||
"breakdownFilter": { "breakdowns": [{ "type": "event", "property": "plan" }] },
|
||||
"trendsFilter": { "display": "ActionsBar" }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A conversion funnel (the window fields are camelCase and live INSIDE `funnelsFilter` — not at the top level of `FunnelsQuery`, and not snake_case):
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Signup funnel (wizard)",
|
||||
"dashboards": [<dashboard id from dashboard-create>],
|
||||
"query": {
|
||||
"kind": "InsightVizNode",
|
||||
"source": {
|
||||
"kind": "FunnelsQuery",
|
||||
"series": [
|
||||
{ "kind": "EventsNode", "event": "page_viewed" },
|
||||
{ "kind": "EventsNode", "event": "user_signed_up" }
|
||||
],
|
||||
"dateRange": { "date_from": "-30d" },
|
||||
"funnelsFilter": {
|
||||
"funnelVizType": "steps",
|
||||
"funnelOrderType": "ordered",
|
||||
"funnelWindowInterval": 14,
|
||||
"funnelWindowIntervalUnit": "day"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Valid `trendsFilter.display` values are `ActionsLineGraph`, `ActionsBar`, `ActionsAreaGraph`, `ActionsPie`, `ActionsStackedBar`, `BoldNumber`, and `ActionsTable` — names like `ActionsBarChart` or `ActionsBarGraph` are rejected. If an insight call is rejected anyway, fix the payload against these examples rather than retrying variations.
|
||||
|
||||
Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] <full https url>`. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped.
|
||||
|
||||
Search for a file called `.posthog-events.json` and read it for available events.
|
||||
|
||||
Do not spawn subagents.
|
||||
|
||||
Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format:
|
||||
|
||||
<wizard-report>
|
||||
# PostHog post-wizard report
|
||||
|
||||
The wizard has completed a deep integration of your project. [Detailed summary of changes]
|
||||
|
||||
[table of events/descriptions/files]
|
||||
|
||||
## Next steps
|
||||
|
||||
We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented:
|
||||
|
||||
[links]
|
||||
|
||||
## Verify before merging
|
||||
|
||||
[checklist]
|
||||
|
||||
### Agent skill
|
||||
|
||||
We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog.
|
||||
|
||||
</wizard-report>
|
||||
|
||||
For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each:
|
||||
|
||||
- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code."
|
||||
- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures."
|
||||
- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set."
|
||||
- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify."
|
||||
- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability."
|
||||
- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs."
|
||||
|
||||
Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two.
|
||||
|
||||
Upon completion, update `.posthog-events.json` so it matches the events you actually implemented, then remove it with your file tools. If removal is blocked or fails in your environment, leave the file in place and move on — the wizard host cleans it up after the run. Do not retry the removal or reach for shell commands to force it.
|
||||
|
||||
## Status
|
||||
|
||||
Status to report in this phase:
|
||||
|
||||
- Configured dashboard: [insert PostHog dashboard URL]
|
||||
- Created setup report: [insert full local file path]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,272 @@
|
||||
# Identify users - Docs
|
||||
|
||||
Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms.
|
||||
|
||||
This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument.
|
||||
|
||||
However, in the frontend of a [web](/docs/libraries/js/features.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/features.md#capturing-anonymous-events).
|
||||
|
||||
To link events to specific users, call `identify`:
|
||||
|
||||
PostHog AI
|
||||
|
||||
### Web
|
||||
|
||||
```javascript
|
||||
posthog.identify(
|
||||
'distinct_id', // Replace 'distinct_id' with your user's unique identifier
|
||||
{ email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties
|
||||
);
|
||||
```
|
||||
|
||||
### Android
|
||||
|
||||
```kotlin
|
||||
PostHog.identify(
|
||||
distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier
|
||||
// optional: set additional person properties
|
||||
userProperties = mapOf(
|
||||
"name" to "Max Hedgehog",
|
||||
"email" to "max@hedgehogmail.com"
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
### iOS
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier
|
||||
userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties
|
||||
```
|
||||
|
||||
### React Native
|
||||
|
||||
```jsx
|
||||
posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier
|
||||
email: 'max@hedgehogmail.com', // optional: set additional person properties
|
||||
name: 'Max Hedgehog'
|
||||
})
|
||||
```
|
||||
|
||||
### Dart
|
||||
|
||||
```dart
|
||||
await Posthog().identify(
|
||||
userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier
|
||||
userProperties: {
|
||||
'email': 'max@hedgehogmail.com', // optional: set additional person properties
|
||||
'name': 'Max Hedgehog',
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already.
|
||||
|
||||
Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed.
|
||||
|
||||
## How identify works
|
||||
|
||||
When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally.
|
||||
|
||||
Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions.
|
||||
|
||||
By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together.
|
||||
|
||||
Thus, all past and future events made with that anonymous ID are now associated with the distinct ID.
|
||||
|
||||
This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms.
|
||||
|
||||
Using identify in the backend
|
||||
|
||||
Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles.
|
||||
|
||||
## Best practices when using `identify`
|
||||
|
||||
### 1\. Call `identify` as soon as you're able to
|
||||
|
||||
In your frontend, you should call `identify` as soon as you're able to.
|
||||
|
||||
Typically, this is every time your **app loads** for the first time, and directly after your **users log in**.
|
||||
|
||||
This ensures that events sent during your users' sessions are correctly associated with them.
|
||||
|
||||
You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily.
|
||||
|
||||
If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls.
|
||||
|
||||
### 2\. Use unique strings for distinct IDs
|
||||
|
||||
If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are:
|
||||
|
||||
- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID.
|
||||
- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`.
|
||||
|
||||
PostHog also has built-in protections to stop the most common distinct ID mistakes.
|
||||
|
||||
### 3\. Reset after logout
|
||||
|
||||
If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user.
|
||||
|
||||
This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions.
|
||||
|
||||
**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.**
|
||||
|
||||
You can do that like so:
|
||||
|
||||
PostHog AI
|
||||
|
||||
### Web
|
||||
|
||||
```javascript
|
||||
posthog.reset()
|
||||
```
|
||||
|
||||
### iOS
|
||||
|
||||
```swift
|
||||
PostHogSDK.shared.reset()
|
||||
```
|
||||
|
||||
### Android
|
||||
|
||||
```kotlin
|
||||
PostHog.reset()
|
||||
```
|
||||
|
||||
### React Native
|
||||
|
||||
```jsx
|
||||
posthog.reset()
|
||||
```
|
||||
|
||||
### Dart
|
||||
|
||||
```dart
|
||||
await Posthog().reset();
|
||||
```
|
||||
|
||||
If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument:
|
||||
|
||||
Web
|
||||
|
||||
PostHog AI
|
||||
|
||||
```javascript
|
||||
posthog.reset(true)
|
||||
```
|
||||
|
||||
### 4\. Person profiles and properties
|
||||
|
||||
You'll notice that one of the parameters in the `identify` method is a `properties` object.
|
||||
|
||||
This enables you to set [person properties](/docs/product-analytics/person-properties.md).
|
||||
|
||||
Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date.
|
||||
|
||||
Person properties can also be set being adding a `$set` property to a event `capture` call.
|
||||
|
||||
See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices.
|
||||
|
||||
### 5\. Use deep links between platforms
|
||||
|
||||
We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in.
|
||||
|
||||
This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are:
|
||||
|
||||
- Onboarding and signup flows before authentication.
|
||||
- Unauthenticated web pages redirecting to authenticated mobile apps.
|
||||
- Authenticated web apps prompting an app download.
|
||||
|
||||
In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users.
|
||||
|
||||
1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog.
|
||||
2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters.
|
||||
3. When the user is redirected to the app, parse the deep link and handle the following cases:
|
||||
|
||||
- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/features.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person.
|
||||
- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID.
|
||||
|
||||
As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms.
|
||||
|
||||
Here's an example implementation for handling deep links from web to mobile:
|
||||
|
||||
PostHog AI
|
||||
|
||||
### iOS
|
||||
|
||||
```swift
|
||||
import PostHog
|
||||
class DeepLinkIdentityManager {
|
||||
static let shared = DeepLinkIdentityManager()
|
||||
// MARK: - Deep Link Received
|
||||
func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) {
|
||||
guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)?
|
||||
.queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else {
|
||||
return
|
||||
}
|
||||
if isAuthenticatedOnMobile {
|
||||
// The mobile app already knows the current user.
|
||||
// Alias the incoming web distinct ID to that user.
|
||||
PostHogSDK.shared.alias(webDistinctId)
|
||||
} else {
|
||||
// Reuse the web distinct ID until login on mobile.
|
||||
PostHogSDK.shared.identify(webDistinctId)
|
||||
}
|
||||
}
|
||||
// MARK: - Login/Signup
|
||||
func handleLogin(canonicalUserId: String) {
|
||||
// Switch from the web distinct ID (or a mobile anon ID)
|
||||
// to your canonical user ID.
|
||||
PostHogSDK.shared.identify(canonicalUserId)
|
||||
// Set user properties, track signup event, etc.
|
||||
}
|
||||
func handleLogout() {
|
||||
PostHogSDK.shared.reset()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Android
|
||||
|
||||
```kotlin
|
||||
import android.net.Uri
|
||||
import com.posthog.PostHog
|
||||
object DeepLinkIdentityManager {
|
||||
// Deep Link Received
|
||||
fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) {
|
||||
val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return
|
||||
if (isAuthenticatedOnMobile) {
|
||||
// The mobile app already knows the current user.
|
||||
// Alias the incoming web distinct ID to that user.
|
||||
PostHog.alias(webDistinctId)
|
||||
} else {
|
||||
// Reuse the web distinct ID until login on mobile.
|
||||
PostHog.identify(webDistinctId)
|
||||
}
|
||||
}
|
||||
// Login/Signup
|
||||
fun handleLogin(canonicalUserId: String) {
|
||||
// Switch from the web distinct ID (or a mobile anon ID)
|
||||
// to your canonical user ID.
|
||||
PostHog.identify(canonicalUserId)
|
||||
// Set user properties, track signup event, etc.
|
||||
}
|
||||
fun handleLogout() {
|
||||
PostHog.reset()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Identifying users docs](/docs/product-analytics/identify.md)
|
||||
- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing)
|
||||
- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md)
|
||||
|
||||
### Community questions
|
||||
|
||||
Ask a question
|
||||
|
||||
### Was this page useful?
|
||||
|
||||
HelpfulCould be better
|
||||
@@ -0,0 +1,898 @@
|
||||
# Python - Docs
|
||||
|
||||
The Python SDK makes it easy to capture events, evaluate feature flags, track errors, and more in your Python apps.
|
||||
|
||||
**Python 3.9 and lower**
|
||||
|
||||
Python 3.9 is no longer supported for PostHog Python SDK versions `7.x.x` and higher.
|
||||
|
||||
## Installation
|
||||
|
||||
Terminal
|
||||
|
||||
PostHog AI
|
||||
|
||||
```bash
|
||||
pip install posthog
|
||||
```
|
||||
|
||||
**Upgrading to v6**
|
||||
|
||||
Version `6.x` of the PostHog Python SDK introduces a new [contexts](/docs/libraries/python.md#contexts) API and breaking changes. If you're upgrading from `5.x` to `6.x`, read the [migration guide](/tutorials/python-v6-migration.md) first to learn more.
|
||||
|
||||
In your app, import the `posthog` library and set your project token and host **before** making any calls.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import Posthog
|
||||
posthog = Posthog('<ph_project_token>', host='https://us.i.posthog.com')
|
||||
```
|
||||
|
||||
> **Note:** As a rule of thumb, we do not recommend having API keys or tokens in plaintext. Setting it as an environment variable is best.
|
||||
|
||||
You can find your project token and instance address in the [project settings](https://app.posthog.com/project/settings) page in PostHog.
|
||||
|
||||
## Identifying users
|
||||
|
||||
> **Identifying users is required.** Backend events need a `distinct_id` to associate events with the correct user.
|
||||
>
|
||||
> In Python, you can do this through a context. All event captures in the same context will be tagged automatically with the correct `distinct_id`. Typically, you would set a fresh context and identify at the top of each route.
|
||||
>
|
||||
> Python
|
||||
>
|
||||
> PostHog AI
|
||||
>
|
||||
> ```python
|
||||
> from posthog import new_context, identify_context, capture
|
||||
> @app.get("/foo")
|
||||
> def foo(current_user: User = Depends(get_current_user)):
|
||||
> with new_context(): # Set context at the top of a route
|
||||
> identify_context(current_user.id)
|
||||
> capture("foo_viewed")
|
||||
> return {"status": "ok"}
|
||||
> ```
|
||||
|
||||
## Capturing events
|
||||
|
||||
You can send custom events using `capture`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
# Events captured with no context or explicit distinct_id are marked as personless and have an auto-generated distinct_id:
|
||||
posthog.capture('some-anon-event')
|
||||
from posthog import identify_context, new_context
|
||||
# Use contexts to manage user identification across multiple capture calls
|
||||
with new_context():
|
||||
identify_context('distinct_id_of_the_user')
|
||||
posthog.capture('user_signed_up')
|
||||
posthog.capture('user_logged_in')
|
||||
# You can also capture events with a specific distinct_id
|
||||
posthog.capture('some-custom-action', distinct_id='distinct_id_of_the_user')
|
||||
```
|
||||
|
||||
> **Tip:** We recommend using a `[object] [verb]` format for your event names, where `[object]` is the entity that the behavior relates to, and `[verb]` is the behavior itself. For example, `project created`, `user signed up`, or `invite sent`.
|
||||
|
||||
> **Tip:** You can define event schemas with typed properties and generate type-safe code using [schema management](/docs/product-analytics/schema-management.md).
|
||||
|
||||
### Setting event properties
|
||||
|
||||
Optionally, you can include additional information with the event by including a [properties](/docs/data/events.md#event-properties) object:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture(
|
||||
"user_signed_up",
|
||||
distinct_id="distinct_id_of_the_user",
|
||||
properties={
|
||||
"login_type": "email",
|
||||
"is_free_trial": "true"
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### Sending page views
|
||||
|
||||
If you're aiming for a backend-only implementation of PostHog and won't be capturing events from your frontend, you can send `pageviews` from your backend like so:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture('$pageview', distinct_id="distinct_id_of_the_user", properties={'$current_url': 'https://example.com'})
|
||||
```
|
||||
|
||||
## Person profiles and properties
|
||||
|
||||
The Python SDK captures identified events if the current context is identified or if you pass a distinct ID explicitly. These create [person profiles](/docs/data/persons.md). To set [person properties](/docs/data/user-properties.md) in these profiles, include them when capturing an event:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
# Passing a distinct id explicitly
|
||||
posthog.capture(
|
||||
'event_name',
|
||||
distinct_id='user-distinct-id',
|
||||
properties={
|
||||
'$set': {'name': 'Max Hedgehog'},
|
||||
'$set_once': {'initial_url': '/blog'}
|
||||
}
|
||||
)
|
||||
# Using contexts
|
||||
from posthog import new_context, identify_context
|
||||
with new_context():
|
||||
identify_context('user-distinct-id')
|
||||
posthog.capture('event_name')
|
||||
```
|
||||
|
||||
For more details on the difference between `$set` and `$set_once`, see our [person properties docs](/docs/data/user-properties.md#what-is-the-difference-between-set-and-set_once).
|
||||
|
||||
To capture [anonymous events](/docs/data/anonymous-vs-identified-events.md) without person profiles, set the event's `$process_person_profile` property to `False`. Events captured with no context or explicit distinct\_id are marked as personless, and will have an auto-generated distinct\_id:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture(
|
||||
event='event_name',
|
||||
properties={
|
||||
'$process_person_profile': False
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Alias
|
||||
|
||||
Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend.
|
||||
|
||||
In this case, you can use `alias` to assign another distinct ID to the same user.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.alias(previous_id='distinct_id', distinct_id='alias_id')
|
||||
```
|
||||
|
||||
We strongly recommend reading our docs on [alias](/docs/product-analytics/identify.md#alias-assigning-multiple-distinct-ids-to-the-same-user) to best understand how to correctly use this method.
|
||||
|
||||
## Contexts
|
||||
|
||||
The Python SDK uses nested contexts for managing state that's shared across events. Contexts are the recommended way to manage things like "which user is taking this action" (through `identify_context`), rather than manually passing user state through your apps stack.
|
||||
|
||||
When events (including exceptions) are captured in a context, the event uses the user [distinct ID](/docs/getting-started/identify-users.md), [session ID](/docs/data/sessions.md), and tags that are (optionally) set in the context. This is useful for adding properties to multiple events during a single user's interaction with your product.
|
||||
|
||||
You can enter a context using the `with` statement:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, tag, set_context_session, identify_context
|
||||
with new_context():
|
||||
tag("transaction_id", "abc123")
|
||||
tag("some_arbitrary_value", {"tags": "can be dicts"})
|
||||
# Sessions are UUIDv7 values and used to track a sequence of events that occur within a single user session
|
||||
# See https://posthog.com/docs/data/sessions
|
||||
set_context_session(session_id)
|
||||
# Setting the context-level distinct ID. See below for more details.
|
||||
identify_context(user_id)
|
||||
# This event is captured with the distinct ID, session ID, and tags set above
|
||||
posthog.capture("order_processed")
|
||||
```
|
||||
|
||||
Contexts are persisted across function calls. If you enter one and then call a function and capture an event in the called function, it uses the context tags and session ID set in the parent context:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, tag
|
||||
def some_function():
|
||||
# When called from `outer_function`, this event is captured with the property some-key="value-4"
|
||||
posthog.capture("order_processed")
|
||||
def outer_function():
|
||||
with new_context():
|
||||
tag("some-key", "value-4")
|
||||
some_function()
|
||||
```
|
||||
|
||||
Contexts are nested, so tags added to a parent context are inherited by child contexts. If you set the same tag in both a parent and child context, the child context's value overrides the parent's at event capture (but the parent context won't be affected). This nesting also applies to session IDs and distinct IDs.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, tag
|
||||
with new_context():
|
||||
tag("some-key", "value-1")
|
||||
tag("some-other-key", "another-value")
|
||||
with new_context():
|
||||
tag("some-key", "value-2")
|
||||
# This event is captured with some-key="value-2" and some-other-key="another-value"
|
||||
posthog.capture("order_processed")
|
||||
# This event is captured with some-key="value-1" and some-other-key="another-value"
|
||||
posthog.capture("order_processed")
|
||||
```
|
||||
|
||||
You can disable this nesting behavior by passing `fresh=True` to `new_context`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, tag
|
||||
with new_context(fresh=True):
|
||||
tag("some-key", "value-2")
|
||||
# This event only has the property some-key="value-2" from the fresh context
|
||||
posthog.capture("order_processed")
|
||||
```
|
||||
|
||||
> **Note:** Distinct IDs, session IDs, and properties passed directly to calls to `capture` and related functions override context state in the final event captured.
|
||||
|
||||
### Contexts and user identification
|
||||
|
||||
Contexts can be associated with a distinct ID by calling `posthog.identify_context`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import identify_context
|
||||
identify_context("distinct-id")
|
||||
```
|
||||
|
||||
Within a context associated with a distinct ID, all events captured are associated with that user. You can override the distinct ID for a specific event by passing a `distinct_id` argument to `capture`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, identify_context
|
||||
with new_context():
|
||||
identify_context("distinct-id")
|
||||
posthog.capture("order_processed") # will be associated with distinct-id
|
||||
posthog.capture("order_processed", distinct_id="another-distinct-id") # will be associated with another-distinct-id
|
||||
```
|
||||
|
||||
It's recommended to pass the currently active distinct ID from the frontend to the backend, using the `X-POSTHOG-DISTINCT-ID` header. If you're using our Django middleware, this is extracted and associated with the request handler context automatically.
|
||||
|
||||
You can read more about identifying users in the [user identification documentation](/docs/product-analytics/identify.md).
|
||||
|
||||
### Contexts and sessions
|
||||
|
||||
Contexts can be associated with a session ID by calling `posthog.set_context_session`. When linking backend events to frontend sessions, use the session ID from the frontend SDK (PostHog session IDs are UUIDv7 strings).
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, set_context_session
|
||||
with new_context():
|
||||
set_context_session(request.get_header("X-POSTHOG-SESSION-ID"))
|
||||
```
|
||||
|
||||
**Using PostHog on your frontend too?**
|
||||
|
||||
If you're using the PostHog JavaScript Web SDK on your frontend, it generates a session ID for you. Configure [`tracing_headers`](/docs/libraries/js/config.md#tracing-headers) for your backend hostname to add the session and distinct ID headers to browser requests automatically.
|
||||
|
||||
You need to extract the header in your request handler (if you're using our Django middleware integration, this happens automatically).
|
||||
|
||||
If you associate a context with a session, you'll be able to do things like:
|
||||
|
||||
- See backend events on the session timeline when viewing session replays
|
||||
- View session replays for users that triggered a backend exception in error tracking
|
||||
|
||||
You can read more about sessions in the [session tracking](/docs/data/sessions.md) documentation.
|
||||
|
||||
### Exception capture
|
||||
|
||||
By default exceptions raised within a context are captured and available in the [error tracking](/docs/error-tracking.md) dashboard. You can override this behavior by passing `capture_exceptions=False` to `new_context`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import new_context, tag
|
||||
with new_context(capture_exceptions=False):
|
||||
tag("transaction_id", "abc123")
|
||||
tag("some_arbitrary_value", {"tags": "can be dicts"})
|
||||
# This event will be captured with the tags set above
|
||||
posthog.capture("order_processed")
|
||||
# This exception will not be captured
|
||||
raise Exception("Order processing failed")
|
||||
```
|
||||
|
||||
### Decorating functions
|
||||
|
||||
The SDK exposes a function decorator. It takes the same `fresh` and `capture_exceptions` arguments as `new_context` and provides a handy way to mark a whole function as being in a new context. For example:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import scoped, identify_context
|
||||
@scoped(fresh=True)
|
||||
def process_order(user, order_id):
|
||||
identify_context(user.distinct_id)
|
||||
posthog.capture("order_processed") # Associated with the user
|
||||
raise Exception("Order processing failed") # This exception is also captured and associated with the user
|
||||
```
|
||||
|
||||
## Group analytics
|
||||
|
||||
Group analytics allows you to associate an event with a group (e.g. teams, organizations, etc.). Read the [Group Analytics](/docs/user-guides/group-analytics.md) guide for more information.
|
||||
|
||||
> **Note:** This is a paid feature and is not available on the open-source or free cloud plan. Learn more on our [pricing page](/pricing.md).
|
||||
|
||||
To capture an event and associate it with a group:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture('some_event', groups={'company': 'company_id_in_your_db'})
|
||||
```
|
||||
|
||||
To update properties on a group:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.group_identify('company', 'company_id_in_your_db', {
|
||||
'name': 'Awesome Inc.',
|
||||
'employees': 11
|
||||
})
|
||||
```
|
||||
|
||||
The `name` is a special property which is used in the PostHog UI for the name of the group. If you don't specify a `name` property, the group ID will be used instead.
|
||||
|
||||
## Feature flags
|
||||
|
||||
PostHog's [feature flags](/docs/feature-flags.md) enable you to safely deploy and roll back new features as well as target specific users and groups with them.
|
||||
|
||||
There are two steps to implement feature flags in Python:
|
||||
|
||||
### Step 1: Evaluate flags once
|
||||
|
||||
Call `posthog.evaluate_flags()` once for the user, then read values from the returned snapshot.
|
||||
|
||||
#### Boolean feature flags
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
flags = posthog.evaluate_flags("distinct_id_of_your_user")
|
||||
if flags.is_enabled("flag-key"):
|
||||
# Do something differently for this user
|
||||
# Optional: fetch the payload
|
||||
matched_flag_payload = flags.get_flag_payload("flag-key")
|
||||
```
|
||||
|
||||
#### Multivariate feature flags
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
flags = posthog.evaluate_flags("distinct_id_of_your_user")
|
||||
enabled_variant = flags.get_flag("flag-key")
|
||||
if enabled_variant == "variant-key": # replace "variant-key" with the key of your variant
|
||||
# Do something differently for this user
|
||||
# Optional: fetch the payload
|
||||
matched_flag_payload = flags.get_flag_payload("flag-key")
|
||||
```
|
||||
|
||||
`flags.get_flag()` returns the variant string for multivariate flags, `True` for enabled boolean flags, `False` for disabled flags, and `None` when the flag wasn't returned by the evaluation.
|
||||
|
||||
> **Note:** `posthog.feature_enabled()`, `posthog.get_feature_flag()`, `posthog.get_feature_flag_payload()`, and `posthog.capture(send_feature_flags=True)` still work during the migration period, but they're deprecated. Prefer `posthog.evaluate_flags()` for new code.
|
||||
|
||||
### Step 2: Include feature flag information when capturing events
|
||||
|
||||
If you want use your feature flag to breakdown or filter events in your [insights](/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event.
|
||||
|
||||
> **Note:** This step is only required for events captured using our server-side SDKs or [API](/docs/api.md).
|
||||
|
||||
There are two methods you can use to include feature flag information in your events:
|
||||
|
||||
#### Method 1: Pass the evaluated flags snapshot to `capture()`
|
||||
|
||||
Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
flags = posthog.evaluate_flags("distinct_id_of_your_user")
|
||||
if flags.is_enabled("flag-key"):
|
||||
# Do something differently for this user
|
||||
pass
|
||||
posthog.capture(
|
||||
"event_name",
|
||||
distinct_id="distinct_id_of_your_user",
|
||||
flags=flags,
|
||||
)
|
||||
```
|
||||
|
||||
By default, this attaches every flag in the snapshot using `$feature/<flag-key>` properties and `$active_feature_flags`.
|
||||
|
||||
To reduce event property bloat, pass a filtered snapshot:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
# Attach only flags accessed with is_enabled() or get_flag() before this call
|
||||
posthog.capture(
|
||||
"event_name",
|
||||
distinct_id="distinct_id_of_your_user",
|
||||
flags=flags.only_accessed(),
|
||||
)
|
||||
# Attach only specific flags
|
||||
posthog.capture(
|
||||
"event_name",
|
||||
distinct_id="distinct_id_of_your_user",
|
||||
flags=flags.only(["checkout-flow", "new-dashboard"]),
|
||||
)
|
||||
```
|
||||
|
||||
`only_accessed()` is order-dependent. If you call it before accessing any flags with `is_enabled()` or `get_flag()`, no feature flag properties are attached.
|
||||
|
||||
#### Method 2: Include the `$feature/feature_flag_name` property manually
|
||||
|
||||
In the event properties, include `$feature/feature_flag_name: variant_key`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture(
|
||||
"event_name",
|
||||
distinct_id="distinct_id_of_the_user",
|
||||
properties={
|
||||
# Replace feature-flag-key with your flag key and "variant-key" with the key of your variant
|
||||
"$feature/feature-flag-key": "variant-key",
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
### Evaluating only specific flags
|
||||
|
||||
By default, `posthog.evaluate_flags()` evaluates every flag for the user. If you only need a few flags, pass `flag_keys` to request only those flags:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
flags = posthog.evaluate_flags(
|
||||
"distinct_id_of_your_user",
|
||||
flag_keys=["checkout-flow", "new-dashboard"],
|
||||
)
|
||||
```
|
||||
|
||||
### Sending `$feature_flag_called` events
|
||||
|
||||
Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](/docs/product-analytics/insights.md) on the flag. With `posthog.evaluate_flags()`, the SDK sends this event when you call `flags.is_enabled()` or `flags.get_flag()` for a flag.
|
||||
|
||||
The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics.
|
||||
|
||||
`flags.get_flag_payload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `only_accessed()`.
|
||||
|
||||
### Advanced: Overriding server properties
|
||||
|
||||
Sometimes, you may want to evaluate feature flags using [person properties](/docs/product-analytics/person-properties.md), [groups](/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier.
|
||||
|
||||
You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server.
|
||||
|
||||
For example:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
flags = posthog.evaluate_flags(
|
||||
"distinct_id_of_the_user",
|
||||
person_properties={"property_name": "value"},
|
||||
groups={
|
||||
"your_group_type": "your_group_id",
|
||||
"another_group_type": "your_group_id",
|
||||
},
|
||||
group_properties={
|
||||
"your_group_type": {"group_property_name": "value"},
|
||||
"another_group_type": {"group_property_name": "value"},
|
||||
},
|
||||
)
|
||||
if flags.is_enabled("flag-key"):
|
||||
# Do something differently for this user
|
||||
```
|
||||
|
||||
### Overriding GeoIP properties
|
||||
|
||||
By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties.
|
||||
|
||||
You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location.
|
||||
|
||||
The following GeoIP properties can be overridden:
|
||||
|
||||
- `$geoip_country_code`
|
||||
- `$geoip_country_name`
|
||||
- `$geoip_city_name`
|
||||
- `$geoip_city_confidence`
|
||||
- `$geoip_continent_code`
|
||||
- `$geoip_continent_name`
|
||||
- `$geoip_latitude`
|
||||
- `$geoip_longitude`
|
||||
- `$geoip_postal_code`
|
||||
- `$geoip_subdivision_1_code`
|
||||
- `$geoip_subdivision_1_name`
|
||||
- `$geoip_subdivision_2_code`
|
||||
- `$geoip_subdivision_2_name`
|
||||
- `$geoip_subdivision_3_code`
|
||||
- `$geoip_subdivision_3_name`
|
||||
- `$geoip_time_zone`
|
||||
|
||||
Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags.
|
||||
|
||||
### Request timeout
|
||||
|
||||
You can configure the `feature_flags_request_timeout_seconds` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog = Posthog(
|
||||
"<ph_project_token>",
|
||||
host="https://us.i.posthog.com",
|
||||
feature_flags_request_timeout_seconds=3, # Time in seconds. Defaults to 3.
|
||||
)
|
||||
```
|
||||
|
||||
### Local evaluation
|
||||
|
||||
Evaluating feature flags requires making a request to PostHog for each flag. However, you can improve performance by evaluating flags locally. Instead of making a request for each flag, PostHog will periodically request and store feature flag definitions locally, enabling you to evaluate flags without making additional requests.
|
||||
|
||||
It is best practice to use local evaluation flags when possible, since this enables you to resolve flags faster and with fewer API calls.
|
||||
|
||||
For details on how to implement local evaluation, see our [local evaluation guide](/docs/feature-flags/local-evaluation.md).
|
||||
|
||||
#### Distributed environments
|
||||
|
||||
In multi-worker or edge environments, you can implement custom caching for flag definitions using Redis, Cloudflare KV, or other storage backends. This enables sharing definitions across workers and coordinating fetches. See our guide for [local evaluation in distributed environments](/docs/feature-flags/local-evaluation/distributed-environments?tab=Python.md) for details.
|
||||
|
||||
## Experiments (A/B tests)
|
||||
|
||||
Since [experiments](/docs/experiments/start-here.md) use feature flags, the code for running an experiment is very similar to the feature flags code:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
flags = posthog.evaluate_flags("user_distinct_id")
|
||||
variant = flags.get_flag("experiment-feature-flag-key")
|
||||
if variant == "variant-name":
|
||||
# Do something
|
||||
```
|
||||
|
||||
It's also possible to [run experiments without using feature flags](/docs/experiments/running-experiments-without-feature-flags.md).
|
||||
|
||||
## AI Observability
|
||||
|
||||
Our Python SDK includes a built-in AI Observability feature. It enables you to capture LLM usage, performance, and more. Check out our [analytics docs](/docs/ai-observability.md) for more details on setting it up.
|
||||
|
||||
## Error tracking
|
||||
|
||||
You can [autocapture exceptions](/docs/error-tracking/installation.md) by setting the `enable_exception_autocapture` argument to `True` when initializing the PostHog client.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from posthog import Posthog
|
||||
posthog = Posthog("<ph_project_token>", enable_exception_autocapture=True, ...)
|
||||
```
|
||||
|
||||
You can also manually capture exceptions using the `capture_exception` method:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture_exception(e, distinct_id='user_distinct_id', properties=additional_properties)
|
||||
```
|
||||
|
||||
Contexts automatically capture exceptions thrown inside them, unless disable it by passing `capture_exceptions=False` to `new_context()`.
|
||||
|
||||
### Code variables capture
|
||||
|
||||
The Python SDK can automatically capture the state of local variables when an exception occurs. This gives you a debugger-like view of your application state at the time of the error:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog = Posthog(
|
||||
"<ph_project_token>",
|
||||
enable_exception_autocapture=True,
|
||||
capture_exception_code_variables=True,
|
||||
)
|
||||
```
|
||||
|
||||
You can configure which variables are captured, masked, or ignored. See the [code variables documentation](/docs/error-tracking/code-variables/python.md) for detailed configuration options.
|
||||
|
||||
## GeoIP properties
|
||||
|
||||
Before posthog-python v3.0, we added GeoIP properties to all incoming events by default. We also used these properties for feature flag evaluation, based on the IP address of the request. This isn't ideal since they are created based on your server IP address, rather than the user's, leading to incorrect location resolution.
|
||||
|
||||
As of posthog-python v3.0, the default now is to disregard the server IP, not add the GeoIP properties, and not use the values for feature flag evaluations.
|
||||
|
||||
You can go back to previous behavior by doing setting the `disable_geoip` argument in your initialization to `False`:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog = Posthog('api_key', disable_geoip=False)
|
||||
```
|
||||
|
||||
The list of properties that this overrides:
|
||||
|
||||
1. `$geoip_city_name`
|
||||
2. `$geoip_country_name`
|
||||
3. `$geoip_country_code`
|
||||
4. `$geoip_continent_name`
|
||||
5. `$geoip_continent_code`
|
||||
6. `$geoip_postal_code`
|
||||
7. `$geoip_time_zone`
|
||||
|
||||
You can also explicitly chose to enable or disable GeoIP for a single capture request like so:
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.capture('test_event', disable_geoip=True|False)
|
||||
```
|
||||
|
||||
## Debug mode
|
||||
|
||||
If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening.
|
||||
|
||||
You can enable debug mode by setting the `debug` option to `True` in the `PostHog` object. This will enable verbose logs about the inner workings of the SDK.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
posthog.debug = True
|
||||
```
|
||||
|
||||
## Disabling requests during tests
|
||||
|
||||
You can disable requests during tests by setting the `disabled` option to `True` in the `PostHog` object. This means no events will be captured or no requests will be sent to PostHog.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
if settings.TEST:
|
||||
posthog.disabled = True
|
||||
```
|
||||
|
||||
## Connection configuration
|
||||
|
||||
The SDK uses HTTP connection pooling internally for better performance. These settings typically need not be changed, but in some environments, such as when running behind NAT gateways, pooled connections may be terminated non-gracefully, causing request failures.
|
||||
|
||||
You can configure connection behavior in several ways. The following settings should be called during initialization, before any API requests are made.
|
||||
|
||||
### Enable TCP keepalive
|
||||
|
||||
TCP keepalive probes help prevent idle connections from being dropped by network infrastructure. This is the recommended approach for most cases where idle connections are terminated.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
import posthog
|
||||
posthog.enable_keep_alive()
|
||||
```
|
||||
|
||||
This enables TCP keepalive with sensible defaults (60 second idle time, 60 second probe interval, 3 probes before timeout).
|
||||
|
||||
### Disable connection pooling
|
||||
|
||||
If you need each request to use a fresh connection, you can disable connection reuse entirely. This will incur additional overhead per request but may be desirable in some circumstances.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
import posthog
|
||||
posthog.disable_connection_reuse()
|
||||
```
|
||||
|
||||
### Custom HTTP socket options
|
||||
|
||||
For advanced use cases, you can configure arbitrary socket options on the underlying HTTP connection.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
import socket
|
||||
import posthog
|
||||
posthog.set_socket_options([
|
||||
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
|
||||
# Add additional socket options as needed
|
||||
])
|
||||
```
|
||||
|
||||
Pass `None` to `set_socket_options()` to reset to default behavior.
|
||||
|
||||
## Filtering or modifying events before sending
|
||||
|
||||
Use `before_send` to modify or drop events before they are queued for delivery. Return the modified event dictionary to send it, or `None` to drop it.
|
||||
|
||||
Python
|
||||
|
||||
PostHog AI
|
||||
|
||||
```python
|
||||
from typing import Any
|
||||
import posthog
|
||||
def scrub_pii(event: dict[str, Any]) -> dict[str, Any] | None:
|
||||
properties = event.get("properties", {})
|
||||
if "email" in properties:
|
||||
email = properties["email"]
|
||||
properties["email"] = f"***@{email.split('@', 1)[1]}" if "@" in email else "***"
|
||||
if event.get("event") == "test_event":
|
||||
return None
|
||||
return event
|
||||
client = posthog.Client(
|
||||
"<ph_project_api_key>",
|
||||
before_send=scrub_pii,
|
||||
)
|
||||
```
|
||||
|
||||
If your callback raises an exception, the SDK logs the error and continues with the original unmodified event.
|
||||
|
||||
## Historical migrations
|
||||
|
||||
You can use the Python or Node SDK to run [historical migrations](/docs/migrate.md) of data into PostHog. To do so, set the `historical_migration` option to `true` when initializing the client.
|
||||
|
||||
PostHog AI
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
from posthog import Posthog
|
||||
from datetime import datetime
|
||||
posthog = Posthog(
|
||||
'<ph_project_token>',
|
||||
host='https://us.i.posthog.com',
|
||||
debug=True,
|
||||
historical_migration=True
|
||||
)
|
||||
events = [
|
||||
{
|
||||
"event": "batched_event_name",
|
||||
"properties": {
|
||||
"distinct_id": "user_id",
|
||||
"timestamp": datetime.fromisoformat("2024-04-02T12:00:00")
|
||||
}
|
||||
},
|
||||
{
|
||||
"event": "batched_event_name",
|
||||
"properties": {
|
||||
"distinct_id": "used_id",
|
||||
"timestamp": datetime.fromisoformat("2024-04-02T12:00:00")
|
||||
}
|
||||
}
|
||||
]
|
||||
for event in events:
|
||||
posthog.capture(
|
||||
distinct_id=event["properties"]["distinct_id"],
|
||||
event=event["event"],
|
||||
properties=event["properties"],
|
||||
timestamp=event["properties"]["timestamp"],
|
||||
)
|
||||
```
|
||||
|
||||
### Node.js
|
||||
|
||||
```javascript
|
||||
import { PostHog } from 'posthog-node'
|
||||
const client = new PostHog(
|
||||
'<ph_project_token>',
|
||||
{
|
||||
host: 'https://us.i.posthog.com',
|
||||
historicalMigration: true
|
||||
}
|
||||
)
|
||||
client.debug()
|
||||
client.capture({
|
||||
event: "batched_event_name",
|
||||
distinctId: "user_id",
|
||||
properties: {},
|
||||
timestamp: "2024-04-03T12:00:00Z"
|
||||
})
|
||||
client.capture({
|
||||
event: "batched_event_name",
|
||||
distinctId: "user_id",
|
||||
properties: {},
|
||||
timestamp: "2024-04-03T13:00:00Z"
|
||||
})
|
||||
await client.shutdown()
|
||||
```
|
||||
|
||||
## Serverless environments (Render/Lambda/...)
|
||||
|
||||
By default, the library buffers events before sending them to the capture endpoint, for better performance. This can lead to lost events in serverless environments, if the Python process is terminated by the platform before the buffer is fully flushed. To avoid this, you can either:
|
||||
|
||||
- Ensure that `posthog.shutdown()` is called after processing every request by adding a middleware to your server. This allows `posthog.capture()` to remain asynchronous for better performance. `posthog.shutdown()` is blocking.
|
||||
- Enable the `sync_mode` option when initializing the client, so that all calls to `posthog.capture()` become synchronous.
|
||||
|
||||
## Django
|
||||
|
||||
See our [Django docs](/docs/libraries/django.md) for how to set up PostHog in Django. Our library includes a [contexts middleware](/docs/libraries/django.md#django-contexts-middleware) that can automatically capture distinct IDs, session IDs, and other properties you can set up with tags.
|
||||
|
||||
## Alternative name
|
||||
|
||||
As our open source project [PostHog](https://github.com/PostHog/posthog) shares the same module name, we created a special `posthoganalytics` package, mostly for internal use to avoid module collision. It is the exact same.
|
||||
|
||||
## Thank you
|
||||
|
||||
This library is largely based on the `analytics-python` package.
|
||||
|
||||
### Community questions
|
||||
|
||||
Ask a question
|
||||
|
||||
### Was this page useful?
|
||||
|
||||
HelpfulCould be better
|
||||
@@ -461,6 +461,12 @@ async def enqueue_batch_job(
|
||||
await _queue.put(job_id)
|
||||
|
||||
logger.info("Batch job %s enqueued: %s → %s", job_id, video.filename, lang_list)
|
||||
from core.analytics import capture as _ph_capture
|
||||
_ph_capture("batch_job_submitted", {
|
||||
"target_language_count": len(lang_list),
|
||||
"has_voice_id": bool(voice_id),
|
||||
"preserve_bg": preserve_bg,
|
||||
})
|
||||
return {"job_id": job_id, "status": "queued", "queue_position": _queue.qsize()}
|
||||
|
||||
|
||||
|
||||
@@ -307,6 +307,8 @@ async def dub_upload(
|
||||
_ingest_gen, job_id, job_dir,
|
||||
{"kind": "file", "path": video_path, "input_type": input_type}, filename,
|
||||
)
|
||||
from core.analytics import capture as _ph_capture
|
||||
_ph_capture("dub_project_started", {"source": "upload", "input_type": input_type})
|
||||
return JSONResponse(
|
||||
status_code=202,
|
||||
content={"job_id": job_id, "task_id": task_id, "filename": filename},
|
||||
@@ -357,6 +359,8 @@ async def dub_ingest_url(req: DubIngestUrlRequest):
|
||||
_ingest_gen, job_id, job_dir,
|
||||
source, None,
|
||||
)
|
||||
from core.analytics import capture as _ph_capture
|
||||
_ph_capture("dub_project_started", {"source": "url"})
|
||||
return JSONResponse(
|
||||
status_code=202,
|
||||
content={"job_id": job_id, "task_id": task_id, "filename": ""},
|
||||
|
||||
@@ -587,6 +587,12 @@ def select_engine(req: SelectEngineRequest):
|
||||
)
|
||||
prefs.set_("mlx_audio_model_id", req.model_id)
|
||||
prefs.set_(pref_key, req.backend_id)
|
||||
from core.analytics import capture as _ph_capture
|
||||
_ph_capture("engine_selected", {
|
||||
"family": req.family,
|
||||
"backend_id": req.backend_id,
|
||||
"routing_status": entry.get("routing_status", "cpu_only"),
|
||||
})
|
||||
return {
|
||||
"family": req.family,
|
||||
"active": module.active_backend_id(),
|
||||
|
||||
@@ -24,6 +24,7 @@ from services.model_manager import (
|
||||
from services.audio_io import _safe_torchaudio_save
|
||||
from core import event_bus
|
||||
from omnivoice.utils.voice_design import heal_design_instruct
|
||||
from core.analytics import capture as ph_capture
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger("omnivoice.generate")
|
||||
@@ -1265,6 +1266,16 @@ async def generate_speech(
|
||||
audio_filename = _meta["filename"]
|
||||
audio_dur = _meta["duration"]
|
||||
gen_time = _meta["gen_time"]
|
||||
ph_capture("speech_generated", {
|
||||
"engine_id": engine_id,
|
||||
"language": language or "auto",
|
||||
"duration_seconds": audio_dur,
|
||||
"gen_time_seconds": gen_time,
|
||||
"text_length": len(text),
|
||||
"has_profile": bool(resolved_profile_id),
|
||||
"effect_preset": effect_preset,
|
||||
"stream": False,
|
||||
})
|
||||
|
||||
buffer = io.BytesIO()
|
||||
_safe_torchaudio_save(buffer, audio_tensor, sample_rate, format="wav")
|
||||
@@ -1311,6 +1322,12 @@ async def generate_speech(
|
||||
except Exception as e:
|
||||
tb = traceback.format_exc()
|
||||
logger.error("Inference failed: %s\n%s", e, tb)
|
||||
ph_capture("generation_failed", {
|
||||
"engine_id": engine_id,
|
||||
"language": language or "auto",
|
||||
"text_length": len(text),
|
||||
"error_type": type(e).__name__,
|
||||
})
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=(
|
||||
|
||||
@@ -13,6 +13,7 @@ from core.config import VOICES_DIR, OUTPUTS_DIR
|
||||
from core import event_bus
|
||||
from core.personalities import get_personalities
|
||||
from omnivoice.utils.voice_design import heal_design_instruct, sanitize_instruct
|
||||
from core.analytics import capture as ph_capture
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -158,6 +159,7 @@ async def create_profile(
|
||||
os.remove(audio_path)
|
||||
raise
|
||||
event_bus.emit("profiles", {"action": "created", "id": profile_id})
|
||||
ph_capture("voice_profile_created", {"kind": kind, "language": language})
|
||||
return {"id": profile_id, "name": name, "kind": kind}
|
||||
|
||||
@router.get("/profiles/{profile_id}")
|
||||
@@ -384,6 +386,7 @@ async def lock_profile(
|
||||
(locked_filename, seed, ref_text, profile_id)
|
||||
)
|
||||
event_bus.emit("profiles", {"action": "locked", "id": profile_id})
|
||||
ph_capture("voice_profile_locked", {})
|
||||
return {"locked": True, "profile_id": profile_id, "locked_audio_path": locked_filename}
|
||||
|
||||
@router.post("/profiles/{profile_id}/unlock")
|
||||
@@ -529,4 +532,5 @@ def delete_profile(profile_id: str):
|
||||
conn.execute("UPDATE generation_history SET profile_id = NULL WHERE profile_id=?", (profile_id,))
|
||||
conn.execute("DELETE FROM voice_profiles WHERE id=?", (profile_id,))
|
||||
event_bus.emit("profiles", {"action": "deleted", "id": profile_id})
|
||||
ph_capture("voice_profile_deleted", {})
|
||||
return {"deleted": profile_id}
|
||||
|
||||
@@ -533,6 +533,8 @@ async def install_model(req: InstallModelRequest):
|
||||
# aggregator can sit below 100% even though every file landed.
|
||||
download_aggregator.complete(req.repo_id)
|
||||
logger.info("model install done: %s", req.repo_id)
|
||||
from core.analytics import capture as _ph_capture
|
||||
_ph_capture("model_installed", {"repo_id": req.repo_id})
|
||||
hf_progress.emit({
|
||||
"repo_id": req.repo_id,
|
||||
"filename": req.repo_id,
|
||||
|
||||
@@ -552,4 +552,6 @@ async def setup_warmup():
|
||||
logger.warning("setup/warmup: model load failed: %s", e)
|
||||
|
||||
loop.create_task(_do_warmup())
|
||||
from core.analytics import capture as _ph_capture
|
||||
_ph_capture("setup_completed", {})
|
||||
return {"status": "warmup_started"}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""PostHog analytics client singleton for OmniVoice Studio.
|
||||
|
||||
Provides a stable installation-scoped distinct_id (no user auth in this
|
||||
app), a lazy-initialized Posthog client, and thin helpers used by routers.
|
||||
All calls are best-effort — a disabled or uninitialized client is a no-op.
|
||||
"""
|
||||
import atexit
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
logger = logging.getLogger("omnivoice.analytics")
|
||||
|
||||
_posthog_client = None
|
||||
|
||||
|
||||
def get_posthog():
|
||||
"""Return the active Posthog client, or None if disabled/uninitialized."""
|
||||
return _posthog_client
|
||||
|
||||
|
||||
def setup_posthog() -> None:
|
||||
"""Initialize the PostHog client. Called once during lifespan startup."""
|
||||
global _posthog_client
|
||||
|
||||
if os.environ.get("POSTHOG_DISABLED", "").strip().lower() in ("1", "true", "yes", "on"):
|
||||
logger.info("PostHog analytics disabled (POSTHOG_DISABLED).")
|
||||
return
|
||||
|
||||
token = os.environ.get("POSTHOG_PROJECT_TOKEN", "")
|
||||
host = os.environ.get("POSTHOG_HOST", "https://eu.i.posthog.com")
|
||||
if not token:
|
||||
logger.info("PostHog analytics disabled (POSTHOG_PROJECT_TOKEN not set).")
|
||||
return
|
||||
|
||||
try:
|
||||
from posthog import Posthog
|
||||
_posthog_client = Posthog(
|
||||
token,
|
||||
host=host,
|
||||
enable_exception_autocapture=True,
|
||||
)
|
||||
atexit.register(_posthog_client.shutdown)
|
||||
logger.info("PostHog analytics initialized (host=%s).", host)
|
||||
except Exception as e:
|
||||
logger.warning("PostHog analytics failed to initialize: %s", e)
|
||||
|
||||
|
||||
def teardown_posthog() -> None:
|
||||
"""Flush all queued events before shutdown. Called in lifespan teardown."""
|
||||
global _posthog_client
|
||||
if _posthog_client is not None:
|
||||
try:
|
||||
_posthog_client.shutdown()
|
||||
except Exception as e:
|
||||
logger.debug("PostHog shutdown error (non-fatal): %s", e)
|
||||
_posthog_client = None
|
||||
|
||||
|
||||
def get_installation_id() -> str:
|
||||
"""Return a stable UUID for this installation.
|
||||
|
||||
Generated once and persisted to prefs.json so every backend restart
|
||||
maps to the same PostHog person — even without user authentication.
|
||||
"""
|
||||
from core.prefs import get, set_
|
||||
|
||||
_KEY = "installation_id"
|
||||
iid = get(_KEY)
|
||||
if not iid:
|
||||
iid = str(uuid.uuid4())
|
||||
try:
|
||||
set_(_KEY, iid)
|
||||
except Exception as e:
|
||||
logger.debug("Failed to persist installation_id (non-fatal): %s", e)
|
||||
return iid
|
||||
|
||||
|
||||
def capture(event: str, properties: dict | None = None) -> None:
|
||||
"""Capture a single event associated with this installation.
|
||||
|
||||
Uses the Posthog instance directly so the distinct_id is always explicit.
|
||||
Best-effort — never raises.
|
||||
"""
|
||||
client = get_posthog()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
iid = get_installation_id()
|
||||
client.capture(event, distinct_id=iid, properties=properties or {})
|
||||
except Exception as e:
|
||||
logger.debug("PostHog capture error (%s): %s", event, e)
|
||||
@@ -567,6 +567,9 @@ async def lifespan(app: FastAPI):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from core.analytics import setup_posthog
|
||||
setup_posthog()
|
||||
|
||||
init_db()
|
||||
# Network sharing is loopback-only by default; the PIN middleware stays
|
||||
# inert until enable() sets a PIN. Seed the (disabled) state so the
|
||||
@@ -741,6 +744,8 @@ async def lifespan(app: FastAPI):
|
||||
await close_http_client()
|
||||
except Exception:
|
||||
pass
|
||||
from core.analytics import teardown_posthog
|
||||
teardown_posthog()
|
||||
logger.info("Shutdown: done.")
|
||||
|
||||
|
||||
|
||||
@@ -167,6 +167,7 @@ dependencies = [
|
||||
# (services/text_normalization.py). Was already installed transitively;
|
||||
# promoted to a direct dependency because we now import it ourselves.
|
||||
"num2words>=0.5.14",
|
||||
"posthog>=7.22.1",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -439,6 +439,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backoff"
|
||||
version = "2.2.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/47/d7/5bbeb12c44d7c4f2fb5b56abce497eb5ed9f34d85701de869acedd602619/backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba", size = 17001, upload-time = "2022-10-05T19:19:32.061Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blis"
|
||||
version = "1.3.3"
|
||||
@@ -3230,6 +3239,7 @@ dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "openai" },
|
||||
{ name = "pedalboard" },
|
||||
{ name = "posthog" },
|
||||
{ name = "psutil" },
|
||||
{ name = "pyannote-audio" },
|
||||
{ name = "pydub" },
|
||||
@@ -3310,6 +3320,7 @@ requires-dist = [
|
||||
{ name = "numpy" },
|
||||
{ name = "openai", specifier = ">=1.40" },
|
||||
{ name = "pedalboard", specifier = ">=0.9.14" },
|
||||
{ name = "posthog", specifier = ">=7.22.1" },
|
||||
{ name = "psutil", specifier = ">=7.2.2" },
|
||||
{ name = "pyannote-audio", specifier = ">=3.3.2,<4.0" },
|
||||
{ name = "pydub" },
|
||||
@@ -3776,6 +3787,21 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/2d/d4bf65e47cea8ff2c794a600c4fd1273a7902f268757c531e0ee9f18aa58/pooch-1.9.0-py3-none-any.whl", hash = "sha256:f265597baa9f760d25ceb29d0beb8186c243d6607b0f60b83ecf14078dbc703b", size = 67175, upload-time = "2026-01-30T19:15:08.36Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "posthog"
|
||||
version = "7.22.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "backoff" },
|
||||
{ name = "distro" },
|
||||
{ name = "requests" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/33/7f/e728eae66e5b62d9a21d7291eeee82341077c6f30064a88cd762cf7fc07c/posthog-7.22.1.tar.gz", hash = "sha256:24650a64433c9735524bc8f41f53f160f691e913887293928528c720f132bc37", size = 330224, upload-time = "2026-07-10T14:37:58.16Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/27/52/5470b635d02b056afefac3c0998ef3005c23f25b7f94143e6a877a27e61a/posthog-7.22.1-py3-none-any.whl", hash = "sha256:7483e5f37b7a6263b9d1a5e68d947e6d9a526de1145c74374eeb330f0ba58d2e", size = 395904, upload-time = "2026-07-10T14:37:56.444Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "preshed"
|
||||
version = "3.0.13"
|
||||
|
||||
Reference in New Issue
Block a user