PostHog

Sync PostHog LLM analytics generations and the user feedback tied to them into a dataset.

What syncs#

PostHog stores LLM calls as $ai_generation events grouped by $ai_trace_id. Each trace becomes one record, and any feedback event that carries the same $ai_trace_id (a thumbs survey response) becomes a score on it.

PostHoggrad record
$ai_trace_idid (the merge key for late feedback)
$ai_input / $ai_output_choicesmessages
survey sent with the same $ai_trace_idscores.thumbs from the survey's thumbs question (up = 1, down = 0); other numeric answers keep their value under their question ID; text answers aren't synced
$ai_session_idsession_id
$ai_modelmetadata.model
Your own event properties (model_version)metadata
distinct_idmetadata.user_id

Tag generations with the model and version#

The PostHog SDK wrappers capture $ai_generation for you. When you capture it yourself, add your own properties next to the $ai_* ones:

Python
from posthog import Posthog

posthog = Posthog("<ph_project_api_key>", host="https://us.i.posthog.com")

posthog.capture(
    distinct_id="user_7",
    event="$ai_generation",
    properties={
        "$ai_trace_id": trace_id,
        "$ai_model": "your-org/support-sft",
        "$ai_provider": "gradiated",
        "model_version": "v42",
    },
)

Send feedback from production#

PostHog collects LLM feedback as survey responses tied to the trace by $ai_trace_id. Create a thumbs survey from the trace's Feedback tab, then send the response (1 is thumbs up, 2 is thumbs down):

Python
posthog.capture(
    distinct_id="user_7",
    event="survey sent",
    properties={
        "$survey_id": survey_id,
        f"$survey_response_{question_id}": 1,
        "$ai_trace_id": trace_id,
    },
)

In React, the useThumbSurvey hook from @posthog/react sends the same event. Responses that arrive later are picked up by the next sync (see How syncing works).

Connect it to grad#

Store the key once as a workspace secret (it reads the value from stdin and never returns it), then add a source to a dataset. The schedule is a cron expression; leave it out to sync only when you ask.

Shell
grad secrets set posthog-prod   # paste a personal API key with Query Read

grad sources add posthog \
  --dataset support-prod \
  --host https://us.posthog.com \
  --secret posthog-prod \
  --project 12345 \
  --schedule "*/30 * * * *"

grad sources list
grad sources sync src_01J9X

How syncing works#

Each sync is incremental: it pulls traces added since the last sync, plus scores and corrections added to traces it already has, so feedback that arrives days later still counts. Records are matched by the provider's trace ID and the latest score wins. Traces younger than 10 minutes wait for the next sync, because providers take a few minutes to expose new data. New feedback events on any trace, however old, land with the next sync, and an event PostHog ingests late (up to an hour) is picked up within 15 minutes.

Syncs add dataset versions (a scheduled one at most every version_interval, 15 minutes by default; see Versions). Old versions never change, so a run keeps the exact data it pinned. If you edit old scores or change the mapping, grad sources sync src_01J9X --full (or source.sync(full=True)) rebuilds the dataset from the provider as a new version.

source.sync() returns the import job (call .wait() to block), or the sync already in progress; on the CLI, add --wait. A source syncs at most once a minute, and one that keeps failing backs off and then pauses; see When a sync fails.

A one-off grad import of an exported file is a snapshot: it never gets later feedback. Use a source for the feedback loop.

Filter what syncs#

Every source takes the shared filters, sample_rate and record caps. grad puts model ($ai_model), name ($ai_span_name), session_id, user_id (distinct_id), the environment and release properties, metadata (event properties) and from/to in the HogQL query; tags and version (custom properties) are matched after fetching.

Choose what to train on#

Records keep the provider's scores in scores and its model and version tags in metadata, so you can pick a slice before training. A filter runs on the server, costs nothing to re-run, and saves the slice as its own dataset:

Python
from grad import Grad

client = Grad()
good = client.datasets.get("support-prod").filter(
    scores={"thumbs": ">=1"},
    metadata={"version": "v42"},
    name="support-prod-v42-good",
)
print(good.count())

A router can use the raw dataset as is: it learns from every score, good and bad.

Keys and hosts#

  • Project (required): the numeric project id from Project settings, for example 12345.
  • Key: a personal API key with the Query Read permission for the project (grad reads events with the query API). The project API key you capture with can't read data. PostHog rate-limits that API, so grad paces itself at 40 queries a minute and the first sync of a large project can take a while.
  • Hosts: the app host, https://us.posthog.com (the default) or https://eu.posthog.com, not the i.posthog.com ingestion host; or your self-hosted PostHog URL. Hosts must be public https:// URLs; for a server on a private network, see Private hosts.

Private hosts#

Sync workers only call public https:// hosts, so a provider key can't be pointed at an internal service by mistake. To sync from a provider on your own network, list its address range in GRAD_SOURCES_EGRESS_ALLOW (comma-separated CIDRs, such as 10.20.0.0/16) on the import workers; plain http:// is then allowed to those addresses too. Store the key with that host too (grad secrets set NAME --allowed-host HOST, or allowed_hosts=[...]): a secret only goes to the public provider hosts unless it names others. On Helm, set it in workers.import.env and allow the range in networkPolicy.workerEgress (see Self-hosting).