Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(docs): update docs to match SDK use over OTel (#75976)

Marco Gancitanoad80a393819b
diff --git a/docs/onboarding/ai-observability/_snippets/openai-compatible.tsx b/docs/onboarding/ai-observability/_snippets/openai-compatible.tsx
new file mode 100644
index 000000000000..3fbf5911c23b
--- /dev/null
+++ b/docs/onboarding/ai-observability/_snippets/openai-compatible.tsx
@@ -0,0 +1,264 @@
+import { OnboardingComponentsContext } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
+
+import { StepDefinition } from '../../steps'
+
+export interface OpenAICompatibleConfig {
+ /** Display name, e.g. 'DeepSeek' */
+ label: string
+ /** Example-repo slug, e.g. 'deepseek' */
+ slug: string
+ /** e.g. 'https://api.deepseek.com' */
+ baseUrl: string
+ /** e.g. '<deepseek_api_key>' */
+ apiKeyPlaceholder: string
+ /** e.g. 'deepseek-chat' */
+ defaultModel: string
+}
+
+export const getOpenAICompatibleSteps = (
+ ctx: OnboardingComponentsContext,
+ config: OpenAICompatibleConfig
+): StepDefinition[] => {
+ const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
+
+ const NotableGenerationProperties = snippets?.NotableGenerationProperties
+
+ return [
+ {
+ title: 'Install dependencies',
+ badge: 'required',
+ content: (
+ <>
+ <CalloutBox type="info" icon="IconInfo" title="Full working examples">
+ <Markdown>
+ {dedent`
+ See the complete
+ [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-${config.slug}) and
+ [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-${config.slug})
+ examples on GitHub.
+ `}
+ </Markdown>
+ </CalloutBox>
+
+ <Markdown>Install the PostHog SDK and the OpenAI SDK.</Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'bash',
+ file: 'Python',
+ code: dedent`
+ pip install posthog openai
+ `,
+ },
+ {
+ language: 'bash',
+ file: 'Node',
+ code: dedent`
+ npm install @posthog/ai posthog-node openai
+ `,
+ },
+ ]}
+ />
+ </>
+ ),
+ },
+ {
+ title: 'Configure PostHog',
+ badge: 'required',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ Create a PostHog client, then swap in PostHog's OpenAI wrapper, pointed at ${config.label}.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ from posthog import Posthog
+ from posthog.ai.openai import OpenAI
+ import time, uuid, json
+
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
+
+ client = OpenAI(
+ base_url="${config.baseUrl}",
+ api_key="${config.apiKeyPlaceholder}",
+ posthog_client=posthog,
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ import { OpenAI } from '@posthog/ai/openai'
+ import { PostHog } from 'posthog-node'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new OpenAI({
+ baseURL: '${config.baseUrl}',
+ apiKey: '${config.apiKeyPlaceholder}',
+ posthog,
+ })
+ `,
+ },
+ ]}
+ />
+ </>
+ ),
+ },
+ {
+ title: `Call ${config.label}`,
+ badge: 'required',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ When you use the wrapped client to call ${config.label}, PostHog automatically captures
+ an \`$ai_generation\` event.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ trace_id = str(uuid.uuid4())
+
+ response = client.chat.completions.create(
+ model="${config.defaultModel}",
+ messages=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ "$ai_provider": "${config.slug}",
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ const traceId = crypto.randomUUID()
+
+ const response = await client.chat.completions.create({
+ model: '${config.defaultModel}',
+ messages: [{ role: 'user', content: "What's the weather in Paris?" }],
+ tools,
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ $ai_provider: '${config.slug}',
+ },
+ })
+ `,
+ },
+ ]}
+ />
+
+ <Blockquote>
+ <Markdown>
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
+ events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
+ </Markdown>
+ </Blockquote>
+
+ <Markdown>
+ {dedent`
+ You can expect captured \`$ai_generation\` events to have the following properties:
+ `}
+ </Markdown>
+
+ {NotableGenerationProperties && <NotableGenerationProperties />}
+ </>
+ ),
+ },
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool
+ calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for call in response.choices[0].message.tool_calls or []:
+ start = time.time()
+ result = run_tool(call.function.name, json.loads(call.function.arguments))
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": call.function.name,
+ "$ai_input_state": call.function.arguments,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const call of response.choices[0].message.tool_calls ?? []) {
+ const start = Date.now()
+ const result = await runTool(call.function.name, JSON.parse(call.function.arguments))
+
+ posthog.capture({
+ distinctId: 'user_123',
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: 'conversation-abc',
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: call.function.name,
+ $ai_input_state: call.function.arguments,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
+ ]
+}
diff --git a/docs/onboarding/ai-observability/anthropic.tsx b/docs/onboarding/ai-observability/anthropic.tsx
index f4aa871d7815..835ecac799a7 100644
--- a/docs/onboarding/ai-observability/anthropic.tsx
+++ b/docs/onboarding/ai-observability/anthropic.tsx
@@ -18,18 +18,11 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
See the complete
[Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-anthropic) and
[Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-anthropic)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-anthropic)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-anthropic)
- examples.
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <Markdown>
- Install the OpenTelemetry SDK, the Anthropic instrumentation, and the Anthropic SDK.
- </Markdown>
+ <Markdown>Install the PostHog SDK and the Anthropic SDK.</Markdown>
<CodeBlock
blocks={[
@@ -37,14 +30,14 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'bash',
file: 'Python',
code: dedent`
- pip install anthropic opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-anthropic
+ pip install posthog anthropic
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install @anthropic-ai/sdk @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @traceloop/instrumentation-anthropic
+ npm install @posthog/ai posthog-node @anthropic-ai/sdk
`,
},
]}
@@ -53,13 +46,14 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument Anthropic SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client, then swap in PostHog's Anthropic wrapper.
+ `}
</Markdown>
<CodeBlock
@@ -68,54 +62,31 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.anthropic import AnthropicInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
+ from posthog import Posthog
+ from posthog.ai.anthropic import Anthropic
+ import time, uuid
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
- AnthropicInstrumentor().instrument()
+ client = Anthropic(
+ api_key="sk-ant-api...",
+ posthog_client=posthog,
+ )
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { AnthropicInstrumentation } from '@traceloop/instrumentation-anthropic'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new AnthropicInstrumentation()],
+ import { Anthropic } from '@posthog/ai/anthropic'
+ import { PostHog } from 'posthog-node'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new Anthropic({
+ apiKey: 'sk-ant-api...',
+ posthog,
})
- sdk.start()
`,
},
]}
@@ -129,8 +100,10 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
content: (
<>
<Markdown>
- Now, when you use the Anthropic SDK to call LLMs, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
+ {dedent`
+ When you use the wrapped client to call Anthropic, PostHog automatically captures an
+ \`$ai_generation\` event.
+ `}
</Markdown>
<CodeBlock
@@ -139,36 +112,38 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'python',
file: 'Python',
code: dedent`
- import anthropic
-
- client = anthropic.Anthropic(api_key="sk-ant-api...")
+ trace_id = str(uuid.uuid4())
response = client.messages.create(
- model="claude-sonnet-4-20250514",
+ model="claude-sonnet-4-5",
max_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
+ messages=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ },
)
-
- print(response.content[0].text)
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import Anthropic from '@anthropic-ai/sdk'
-
- const client = new Anthropic({ apiKey: 'sk-ant-api...' })
+ const traceId = crypto.randomUUID()
const response = await client.messages.create({
- model: 'claude-sonnet-4-20250514',
+ model: 'claude-sonnet-4-5',
max_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
+ messages: [{ role: 'user', content: "What's the weather in Paris?" }],
+ tools,
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ },
})
-
- console.log(response.content[0].text)
`,
},
]}
@@ -176,15 +151,8 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
<Blockquote>
<Markdown>
- **Note:** This also works with the `AsyncAnthropic` client as well as `AnthropicBedrock`,
- `AnthropicVertex`, and the async versions of those.
- </Markdown>
- </Blockquote>
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
</Blockquote>
@@ -199,6 +167,84 @@ export const getAnthropicSteps = (ctx: OnboardingComponentsContext): StepDefinit
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool
+ calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for block in response.content:
+ if block.type != "tool_use":
+ continue
+
+ start = time.time()
+ result = run_tool(block.name, block.input)
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": block.name,
+ "$ai_input_state": block.input,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const block of response.content) {
+ if (block.type !== 'tool_use') continue
+
+ const start = Date.now()
+ const result = await runTool(block.name, block.input)
+
+ posthog.capture({
+ distinctId: 'user_123',
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: 'conversation-abc',
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: block.name,
+ $ai_input_state: block.input,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
]
}
diff --git a/docs/onboarding/ai-observability/autogen.tsx b/docs/onboarding/ai-observability/autogen.tsx
index 78a9ca02f334..6e5e64dd9e8f 100644
--- a/docs/onboarding/ai-observability/autogen.tsx
+++ b/docs/onboarding/ai-observability/autogen.tsx
@@ -17,8 +17,8 @@ export const getAutoGenSteps = (ctx: OnboardingComponentsContext): StepDefinitio
<Markdown>
See the complete [Python
example](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-autogen)
- on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
- wrapper
+ on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see this example
+ instead: [Python wrapper
example](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-autogen).
</Markdown>
</CalloutBox>
diff --git a/docs/onboarding/ai-observability/azure-openai.tsx b/docs/onboarding/ai-observability/azure-openai.tsx
index 5fc0f83e7c83..79a750bac02d 100644
--- a/docs/onboarding/ai-observability/azure-openai.tsx
+++ b/docs/onboarding/ai-observability/azure-openai.tsx
@@ -16,19 +16,14 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
<CalloutBox type="info" icon="IconInfo" title="Full working examples">
<Markdown>
See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-azure-openai)
+ [Node.js](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-azure-openai)
and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-azure-openai)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-azure-openai)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-azure-openai)
- examples.
+ [Python](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-azure-openai)
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
+ <Markdown>Install the PostHog SDK and the OpenAI SDK.</Markdown>
<CodeBlock
blocks={[
@@ -36,14 +31,14 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
language: 'bash',
file: 'Python',
code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
+ pip install posthog openai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
+ npm install @posthog/ai posthog-node openai
`,
},
]}
@@ -52,13 +47,14 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client, then swap in PostHog's Azure OpenAI wrapper.
+ `}
</Markdown>
<CodeBlock
@@ -67,54 +63,35 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
+ from posthog import Posthog
+ from posthog.ai.openai import AzureOpenAI
+ import time, uuid, json
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
- OpenAIInstrumentor().instrument()
+ client = AzureOpenAI(
+ api_key="<azure_openai_api_key>",
+ api_version="2024-10-21",
+ azure_endpoint="https://<your-resource>.openai.azure.com",
+ posthog_client=posthog,
+ )
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
+ import { AzureOpenAI } from '@posthog/ai/openai'
+ import { PostHog } from 'posthog-node'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new AzureOpenAI({
+ apiKey: '<azure_openai_api_key>',
+ apiVersion: '2024-10-21',
+ endpoint: 'https://<your-resource>.openai.azure.com',
+ posthog,
})
- sdk.start()
`,
},
]}
@@ -128,8 +105,10 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
content: (
<>
<Markdown>
- Now, when you call Azure OpenAI, PostHog automatically captures `$ai_generation` events via the
- OpenTelemetry instrumentation.
+ {dedent`
+ When you use the wrapped client to call Azure OpenAI, PostHog automatically captures an
+ \`$ai_generation\` event.
+ `}
</Markdown>
<CodeBlock
@@ -138,42 +117,38 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
language: 'python',
file: 'Python',
code: dedent`
- import openai
+ trace_id = str(uuid.uuid4())
- client = openai.AzureOpenAI(
- api_key="<azure_openai_api_key>",
- api_version="2024-10-21",
- azure_endpoint="https://<your-resource>.openai.azure.com",
- )
-
- response = client.chat.completions.create(
+ response = client.responses.create(
model="<your-deployment-name>",
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
+ input=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ "$ai_provider": "azure",
+ },
)
-
- print(response.choices[0].message.content)
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { AzureOpenAI } from 'openai'
+ const traceId = crypto.randomUUID()
- const client = new AzureOpenAI({
- apiKey: '<azure_openai_api_key>',
- apiVersion: '2024-10-21',
- endpoint: 'https://<your-resource>.openai.azure.com',
- })
-
- const response = await client.chat.completions.create({
+ const response = await client.responses.create({
model: '<your-deployment-name>',
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
+ input: [{ role: 'user', content: "What's the weather in Paris?" }],
+ tools,
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ $ai_provider: 'azure',
+ },
})
-
- console.log(response.choices[0].message.content)
`,
},
]}
@@ -181,8 +156,8 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
<Blockquote>
<Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
</Blockquote>
@@ -197,6 +172,84 @@ export const getAzureOpenAISteps = (ctx: OnboardingComponentsContext): StepDefin
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool
+ calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for item in response.output:
+ if item.type != "function_call":
+ continue
+
+ start = time.time()
+ result = run_tool(item.name, json.loads(item.arguments))
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": item.name,
+ "$ai_input_state": item.arguments,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const item of response.output) {
+ if (item.type !== 'function_call') continue
+
+ const start = Date.now()
+ const result = await runTool(item.name, JSON.parse(item.arguments))
+
+ posthog.capture({
+ distinctId: 'user_123',
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: 'conversation-abc',
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: item.name,
+ $ai_input_state: item.arguments,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
]
}
diff --git a/docs/onboarding/ai-observability/cerebras.tsx b/docs/onboarding/ai-observability/cerebras.tsx
index dba6528f8d02..1c6d81a76c2d 100644
--- a/docs/onboarding/ai-observability/cerebras.tsx
+++ b/docs/onboarding/ai-observability/cerebras.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getCerebrasSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-cerebras) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-cerebras)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-cerebras)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-cerebras)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Cerebras',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Cerebras, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.cerebras.ai/v1",
- api_key="<cerebras_api_key>",
- )
-
- response = client.chat.completions.create(
- model="llama-3.3-70b",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.cerebras.ai/v1',
- apiKey: '<cerebras_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'llama-3.3-70b',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getCerebrasSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Cerebras',
+ slug: 'cerebras',
+ baseUrl: 'https://api.cerebras.ai/v1',
+ apiKeyPlaceholder: '<cerebras_api_key>',
+ defaultModel: 'llama-3.3-70b',
+ })
export const CerebrasInstallation = createInstallation(getCerebrasSteps)
diff --git a/docs/onboarding/ai-observability/claude-agent-sdk.tsx b/docs/onboarding/ai-observability/claude-agent-sdk.tsx
index 933b32e788e9..7b2a6c0cc94d 100644
--- a/docs/onboarding/ai-observability/claude-agent-sdk.tsx
+++ b/docs/onboarding/ai-observability/claude-agent-sdk.tsx
@@ -59,10 +59,13 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
content: (
<>
<Markdown>
- Initialize PostHog with your project token and host from [your project
- settings](https://app.posthog.com/settings/project), then use the PostHog `query()` wrapper as a
- drop-in replacement for `claude_agent_sdk.query()`. This automatically captures
- `$ai_generation`, `$ai_span`, and `$ai_trace` events.
+ {dedent`
+ Initialize PostHog with your project token and host from [your project
+ settings](https://app.posthog.com/settings/project). Then use the PostHog \`query()\`
+ wrapper as a drop-in replacement for \`claude_agent_sdk.query()\`. This automatically
+ captures \`$ai_generation\`, \`$ai_span\`, and \`$ai_trace\` events, including a span
+ for each tool the agent uses, such as \`Bash\` below.
+ `}
</Markdown>
<CodeBlock
@@ -81,16 +84,17 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
async def main():
options = ClaudeAgentOptions(
max_turns=5,
- permission_mode="plan",
+ allowed_tools=["Read", "Glob", "Grep"],
+ cwd="/path/to/your/project",
)
async for message in query(
- prompt="Tell me a fun fact about hedgehogs",
+ prompt="Read the README and summarize this project",
options=options,
posthog_client=posthog,
posthog_distinct_id="user_123", # optional
posthog_trace_id="trace_123", # optional
- posthog_properties={"conversation_id": "abc123"}, # optional
+ posthog_properties={"conversation_id": "abc123", "$ai_session_id": "conversation-abc"}, # optional
posthog_groups={"company": "company_id_in_your_db"}, # optional
posthog_privacy_mode=False, # optional
):
@@ -105,8 +109,9 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
<Markdown>
{dedent`
**Notes:**
- - All original messages are yielded unchanged — the wrapper is fully transparent.
- - If you want to capture LLM events anonymously, **don't** pass a distinct ID. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
+ - The wrapper yields all original messages unchanged, fully transparent to your code.
+ - Pass \`$ai_session_id\` in \`posthog_properties\` to group every generation, span, and trace from a call into one PostHog session.
+ - If you want to capture LLM events anonymously, **do not** pass a distinct ID. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
`}
</Markdown>
</Blockquote>
@@ -163,11 +168,11 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
`}
/>
- <Markdown>
- {dedent`
- You can override any PostHog parameter per-query:
+ <Markdown>You can override any PostHog parameter per-query:</Markdown>
- \`\`\`python
+ <CodeBlock
+ language="python"
+ code={dedent`
async for msg in ph.query(
prompt="...",
options=options,
@@ -175,9 +180,8 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
posthog_properties={"extra": "data"},
):
...
- \`\`\`
`}
- </Markdown>
+ />
</>
),
},
@@ -187,52 +191,36 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
content: (
<>
<Markdown>
- PostHog captures the full trace hierarchy for multi-turn agent conversations with tool calls.
- Each tool use is captured as an `$ai_span` event linked to its parent generation.
+ {dedent`
+ The recommended example above already runs a tool-using query, and \`max_turns\` lets
+ Claude take more than one internal turn before it replies. Inspect the message stream
+ to see each turn and tool call as they happen.
+ `}
</Markdown>
<CodeBlock
language="python"
code={dedent`
- import asyncio
- from posthog import Posthog
- from posthog.ai.claude_agent_sdk import query
- from claude_agent_sdk import ClaudeAgentOptions, AssistantMessage, TextBlock, ToolUseBlock
+ from claude_agent_sdk import AssistantMessage, TextBlock, ToolUseBlock
- posthog = Posthog(
- "<ph_project_token>",
- host="<ph_client_api_host>"
- )
-
- options = ClaudeAgentOptions(
- max_turns=10,
- allowed_tools=["Read", "Glob", "Grep", "Bash"],
- permission_mode="bypassPermissions",
- cwd="/path/to/your/project",
- )
-
- async def main():
- async for message in query(
- prompt="Read the README and summarize this project",
- options=options,
- posthog_client=posthog,
- posthog_distinct_id="user_123",
- ):
- if isinstance(message, AssistantMessage):
- for block in message.content:
- if isinstance(block, TextBlock):
- print(block.text)
- elif isinstance(block, ToolUseBlock):
- print(f"Tool: {block.name}")
-
- asyncio.run(main())
- posthog.shutdown()
+ async for message in query(
+ prompt="Read the README and summarize this project",
+ options=options,
+ posthog_client=posthog,
+ posthog_distinct_id="user_123",
+ ):
+ if isinstance(message, AssistantMessage):
+ for block in message.content:
+ if isinstance(block, TextBlock):
+ print(block.text)
+ elif isinstance(block, ToolUseBlock):
+ print(f"Tool: {block.name}")
`}
/>
<Markdown>
{dedent`
- This captures:
+ Across the whole query, PostHog captures:
- \`$ai_generation\` events for each LLM turn (with token counts, cost, and cache metrics)
- \`$ai_span\` events for each tool use (Read, Glob, Grep, Bash, etc.)
- An \`$ai_trace\` event grouping the entire conversation with total cost and latency
@@ -293,7 +281,9 @@ export const getClaudeAgentSDKSteps = (ctx: OnboardingComponentsContext): StepDe
<Markdown>
{dedent`
- Each \`receive_response()\` cycle emits \`$ai_generation\` events for that turn. When the client disconnects (exiting the \`async with\` block), a single \`$ai_trace\` event is emitted covering the entire session with aggregate latency.
+ Each \`receive_response()\` cycle emits \`$ai_generation\` events for that turn. When the
+ client disconnects, exiting the \`async with\` block, it emits a single \`$ai_trace\`
+ event covering the entire session with aggregate latency.
`}
</Markdown>
</>
diff --git a/docs/onboarding/ai-observability/cloudflare-ai-gateway.tsx b/docs/onboarding/ai-observability/cloudflare-ai-gateway.tsx
index ad44803db13a..0675d4d95d56 100644
--- a/docs/onboarding/ai-observability/cloudflare-ai-gateway.tsx
+++ b/docs/onboarding/ai-observability/cloudflare-ai-gateway.tsx
@@ -23,7 +23,7 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
</Markdown>
</CalloutBox>
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
+ <Markdown>Install the PostHog SDK and the OpenAI SDK.</Markdown>
<CodeBlock
blocks={[
@@ -31,14 +31,14 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
language: 'bash',
file: 'Python',
code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
+ pip install posthog openai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
+ npm install @posthog/ai posthog-node openai
`,
},
]}
@@ -47,13 +47,15 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client, then swap in PostHog's OpenAI wrapper, pointed at your
+ Cloudflare AI Gateway endpoint.
+ `}
</Markdown>
<CodeBlock
@@ -62,54 +64,39 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
+ from posthog import Posthog
+ from posthog.ai.openai import OpenAI
+ import time, uuid, json
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
- OpenAIInstrumentor().instrument()
+ client = OpenAI(
+ base_url="https://gateway.ai.cloudflare.com/v1/<account_id>/<gateway_id>/compat",
+ api_key="<openai_api_key>",
+ default_headers={
+ "cf-aig-authorization": "Bearer <cf_aig_token>",
+ },
+ posthog_client=posthog,
+ )
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
+ import { OpenAI } from '@posthog/ai/openai'
+ import { PostHog } from 'posthog-node'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new OpenAI({
+ baseURL: 'https://gateway.ai.cloudflare.com/v1/<account_id>/<gateway_id>/compat',
+ apiKey: '<openai_api_key>',
+ defaultHeaders: {
+ 'cf-aig-authorization': 'Bearer <cf_aig_token>',
+ },
+ posthog,
})
- sdk.start()
`,
},
]}
@@ -124,11 +111,8 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
<>
<Markdown>
{dedent`
- Cloudflare AI Gateway exposes an OpenAI-compatible \`compat\` endpoint at
- \`https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/compat\`. Point the OpenAI SDK at
- this URL with your upstream provider key (e.g. your OpenAI key) and pass your AI Gateway token via
- the \`cf-aig-authorization\` header. Specify models as \`provider/model-id\` (for example
- \`openai/gpt-5-mini\` or \`anthropic/claude-sonnet-4-5\`).
+ When you use the wrapped client to call Cloudflare AI Gateway, PostHog automatically
+ captures an \`$ai_generation\` event.
`}
</Markdown>
@@ -138,48 +122,40 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
language: 'python',
file: 'Python',
code: dedent`
- import openai
-
- client = openai.OpenAI(
- api_key="<openai_api_key>",
- default_headers={
- "cf-aig-authorization": "Bearer <cf_aig_token>",
- },
- base_url="https://gateway.ai.cloudflare.com/v1/<account_id>/<gateway_id>/compat",
- )
+ trace_id = str(uuid.uuid4())
response = client.chat.completions.create(
model="openai/gpt-5-mini",
max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
+ messages=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ "$ai_provider": "cloudflare",
+ },
)
-
- print(response.choices[0].message.content)
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- apiKey: '<openai_api_key>',
- defaultHeaders: {
- 'cf-aig-authorization': 'Bearer <cf_aig_token>',
- },
- baseURL: 'https://gateway.ai.cloudflare.com/v1/<account_id>/<gateway_id>/compat',
- })
+ const traceId = crypto.randomUUID()
const response = await client.chat.completions.create({
model: 'openai/gpt-5-mini',
max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
+ messages: [{ role: 'user', content: "What's the weather in Paris?" }],
+ tools,
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ $ai_provider: 'cloudflare',
+ },
})
-
- console.log(response.choices[0].message.content)
`,
},
]}
@@ -187,9 +163,9 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
<Blockquote>
<Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
+ events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
</Blockquote>
@@ -203,6 +179,79 @@ export const getCloudflareAIGatewaySteps = (ctx: OnboardingComponentsContext): S
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool
+ calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for call in response.choices[0].message.tool_calls or []:
+ start = time.time()
+ result = run_tool(call.function.name, json.loads(call.function.arguments))
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": call.function.name,
+ "$ai_input_state": call.function.arguments,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const call of response.choices[0].message.tool_calls ?? []) {
+ const start = Date.now()
+ const result = await runTool(call.function.name, JSON.parse(call.function.arguments))
+
+ posthog.capture({
+ distinctId,
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: sessionId,
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: call.function.name,
+ $ai_input_state: call.function.arguments,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
]
}
diff --git a/docs/onboarding/ai-observability/cohere.tsx b/docs/onboarding/ai-observability/cohere.tsx
index e9de7de84ed7..f720c301f05a 100644
--- a/docs/onboarding/ai-observability/cohere.tsx
+++ b/docs/onboarding/ai-observability/cohere.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getCohereSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-cohere) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-cohere)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-cohere) and
- [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-cohere)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Cohere',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Cohere, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.cohere.ai/compatibility/v1",
- api_key="<cohere_api_key>",
- )
-
- response = client.chat.completions.create(
- model="command-a-03-2025",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.cohere.ai/compatibility/v1',
- apiKey: '<cohere_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'command-a-03-2025',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getCohereSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Cohere',
+ slug: 'cohere',
+ baseUrl: 'https://api.cohere.ai/compatibility/v1',
+ apiKeyPlaceholder: '<cohere_api_key>',
+ defaultModel: 'command-a-03-2025',
+ })
export const CohereInstallation = createInstallation(getCohereSteps)
diff --git a/docs/onboarding/ai-observability/crewai.tsx b/docs/onboarding/ai-observability/crewai.tsx
index f7594d856516..25d63a9bec7f 100644
--- a/docs/onboarding/ai-observability/crewai.tsx
+++ b/docs/onboarding/ai-observability/crewai.tsx
@@ -62,7 +62,7 @@ export const getCrewAISteps = (ctx: OnboardingComponentsContext): StepDefinition
code={dedent`
import os
import litellm
- from crewai import Agent, Task, Crew
+ from crewai import Agent, Task, Crew, LLM
# Set PostHog environment variables
os.environ["POSTHOG_API_KEY"] = "<ph_project_token>"
@@ -76,9 +76,10 @@ export const getCrewAISteps = (ctx: OnboardingComponentsContext): StepDefinition
<CalloutBox type="fyi" icon="IconInfo" title="How this works">
<Markdown>
- CrewAI uses LiteLLM under the hood for LLM provider access. By configuring PostHog as a
- LiteLLM callback, all LLM calls made through CrewAI are automatically captured as
- `$ai_generation` events without proxying your calls.
+ CrewAI can route LLM calls either through its own provider clients or through LiteLLM.
+ PostHog hooks into LiteLLM's callback system, so you need `is_litellm=True` on the `LLM` you
+ pass to your agents. With it, PostHog captures every call as an `$ai_generation` event,
+ without proxying your calls.
</Markdown>
</CalloutBox>
</>
@@ -90,30 +91,74 @@ export const getCrewAISteps = (ctx: OnboardingComponentsContext): StepDefinition
content: (
<>
<Markdown>
- Run your CrewAI agents as normal. PostHog automatically captures generation events for each LLM
- call.
+ {dedent`
+ Run your CrewAI agents as normal. PostHog automatically captures an \`$ai_generation\`
+ event for each LLM call. LiteLLM's callback does not see the tools your agents call.
+ Capture a tool's own execution as a span from inside the tool itself instead, as
+ \`my_tool\` does below.
+ `}
</Markdown>
<CodeBlock
language="python"
code={dedent`
+ from posthog import Posthog
+ from crewai.tools import tool
+ import time, uuid
+
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
+
+ trace_id = str(uuid.uuid4())
+
+ @tool
+ def my_tool(query: str) -> str:
+ """Describe what your tool does."""
+ start = time.time()
+ result = run_tool(query)
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": "my_tool",
+ "$ai_input_state": {"query": query},
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ return result
+
+ # is_litellm=True routes calls through LiteLLM so the PostHog
+ # callback fires. Without it, CrewAI uses its own provider client
+ # and no events are captured.
+ llm = LLM(
+ model="gpt-4o-mini",
+ is_litellm=True,
+ metadata={
+ "user_id": "user_123",
+ "$ai_session_id": "conversation-abc",
+ "$ai_trace_id": trace_id,
+ },
+ )
+
researcher = Agent(
role="Researcher",
- goal="Find interesting facts about hedgehogs",
+ goal="Find the weather in a city",
backstory="You are an expert wildlife researcher.",
+ llm=llm,
+ tools=[my_tool],
)
task = Task(
- description="Research three fun facts about hedgehogs.",
- expected_output="A list of three fun facts.",
+ description="Find the weather in Paris.",
+ expected_output="The weather in Paris.",
agent=researcher,
)
- crew = Crew(
- agents=[researcher],
- tasks=[task],
- )
-
+ crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
print(result)
`}
diff --git a/docs/onboarding/ai-observability/dedalus.tsx b/docs/onboarding/ai-observability/dedalus.tsx
index 99aa88ef62ed..04317e87c043 100644
--- a/docs/onboarding/ai-observability/dedalus.tsx
+++ b/docs/onboarding/ai-observability/dedalus.tsx
@@ -1,198 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getDedalusSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="fyi" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-dedalus) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-dedalus)
- examples on GitHub.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Dedalus Labs',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Dedalus Labs exposes an OpenAI-compatible endpoint at `https://api.dedaluslabs.ai/v1`, so you
- can route the standard OpenAI SDK at it. Models are specified as `provider/model-id`, for
- example `openai/gpt-5-mini` or `anthropic/claude-sonnet-4-5`.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.dedaluslabs.ai/v1",
- api_key="<dedalus_api_key>",
- )
-
- response = client.chat.completions.create(
- model="openai/gpt-5-mini",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.dedaluslabs.ai/v1',
- apiKey: '<dedalus_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'openai/gpt-5-mini',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getDedalusSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Dedalus Labs',
+ slug: 'dedalus',
+ baseUrl: 'https://api.dedaluslabs.ai/v1',
+ apiKeyPlaceholder: '<dedalus_api_key>',
+ defaultModel: 'openai/gpt-5-mini',
+ })
export const DedalusInstallation = createInstallation(getDedalusSteps)
diff --git a/docs/onboarding/ai-observability/deepseek.tsx b/docs/onboarding/ai-observability/deepseek.tsx
index cff3b44d9b13..e5cb8d139b3e 100644
--- a/docs/onboarding/ai-observability/deepseek.tsx
+++ b/docs/onboarding/ai-observability/deepseek.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getDeepSeekSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-deepseek) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-deepseek)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-deepseek)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-deepseek)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call DeepSeek',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call DeepSeek, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.deepseek.com",
- api_key="<deepseek_api_key>",
- )
-
- response = client.chat.completions.create(
- model="deepseek-chat",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.deepseek.com',
- apiKey: '<deepseek_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'deepseek-chat',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getDeepSeekSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'DeepSeek',
+ slug: 'deepseek',
+ baseUrl: 'https://api.deepseek.com',
+ apiKeyPlaceholder: '<deepseek_api_key>',
+ defaultModel: 'deepseek-chat',
+ })
export const DeepSeekInstallation = createInstallation(getDeepSeekSteps)
diff --git a/docs/onboarding/ai-observability/dspy.tsx b/docs/onboarding/ai-observability/dspy.tsx
index 17538c6f2cd3..10448f0d2175 100644
--- a/docs/onboarding/ai-observability/dspy.tsx
+++ b/docs/onboarding/ai-observability/dspy.tsx
@@ -73,7 +73,14 @@ export const getDSPySteps = (ctx: OnboardingComponentsContext): StepDefinition[]
litellm.failure_callback = ["posthog"]
# Configure DSPy to use an LLM
- lm = dspy.LM("openai/gpt-5-mini", api_key="your_openai_api_key")
+ lm = dspy.LM(
+ "openai/gpt-5-mini",
+ api_key="your_openai_api_key",
+ metadata={
+ "user_id": "user_123", # Maps to PostHog distinct_id
+ "$ai_session_id": "conversation-abc", # Groups calls into one session
+ },
+ )
dspy.configure(lm=lm)
`}
/>
@@ -94,25 +101,42 @@ export const getDSPySteps = (ctx: OnboardingComponentsContext): StepDefinition[]
content: (
<>
<Markdown>
- Use DSPy as normal. PostHog automatically captures an `$ai_generation` event for each LLM call
- made through LiteLLM.
+ {dedent`
+ Use DSPy as normal. PostHog automatically captures an \`$ai_generation\` event for each
+ LLM call made through LiteLLM.
+ `}
</Markdown>
<CodeBlock
language="python"
code={dedent`
+ from posthog import Posthog
+ import time, uuid
+
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
+
+ trace_id = str(uuid.uuid4())
+
+ lm = dspy.LM(
+ "openai/gpt-5-mini",
+ api_key="your_openai_api_key",
+ metadata={
+ "user_id": "user_123",
+ "$ai_session_id": "conversation-abc",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ dspy.configure(lm=lm)
+
+
# Define a simple signature
class QA(dspy.Signature):
"""Answer the question."""
question: str = dspy.InputField()
answer: str = dspy.OutputField()
- # Create and run a module
predictor = dspy.Predict(QA)
- result = predictor(
- question="What is a fun fact about hedgehogs?"
- )
-
+ result = predictor(question="What's a fun fact about hedgehogs?")
print(result.answer)
`}
/>
@@ -127,6 +151,52 @@ export const getDSPySteps = (ctx: OnboardingComponentsContext): StepDefinition[]
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ Capture tool calls as a span yourself, as the example below does before calling \`predictor\`.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ language="python"
+ code={dedent`
+ # retrieve() is your existing retrieval setup
+ start = time.time()
+ context = retrieve("hedgehog facts")
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": "retrieve",
+ "$ai_input_state": "hedgehog facts",
+ "$ai_output_state": context,
+ "$ai_latency": time.time() - start,
+ },
+ )
+
+ question = f"Using this context, answer what a fun fact about hedgehogs is: {context}"
+ result = predictor(question=question)
+ `}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
]
}
diff --git a/docs/onboarding/ai-observability/eve.tsx b/docs/onboarding/ai-observability/eve.tsx
index a496060eb9f1..b5514e352fce 100644
--- a/docs/onboarding/ai-observability/eve.tsx
+++ b/docs/onboarding/ai-observability/eve.tsx
@@ -3,7 +3,7 @@ import { OnboardingComponentsContext, createInstallation } from 'scenes/onboardi
import { StepDefinition } from '../steps'
export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { Blockquote, CalloutBox, CodeBlock, Markdown, dedent, snippets } = ctx
+ const { Blockquote, CodeBlock, Markdown, dedent, snippets } = ctx
const NotableGenerationProperties = snippets?.NotableGenerationProperties
@@ -103,16 +103,6 @@ export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[]
`}
/>
- <CalloutBox type="fyi" icon="IconInfo" title="How this works">
- <Markdown>
- Eve emits Vercel AI SDK OpenTelemetry spans. `PostHogTraceExporter` sends the AI spans to
- PostHog's OTLP ingestion endpoint. `SimpleSpanProcessor` starts exporting each span when it
- ends instead of waiting for a background batch, so export does not depend on a background
- timer in Vercel Workflow. PostHog keeps the trace hierarchy, identifies the framework as
- Eve, and groups turns using `eve.session.id`.
- </Markdown>
- </CalloutBox>
-
<Blockquote>
<Markdown>
**Note:** To capture LLM events anonymously, omit the `events` handler. See our docs on
@@ -121,14 +111,6 @@ export const getEveSteps = (ctx: OnboardingComponentsContext): StepDefinition[]
</Markdown>
</Blockquote>
- <Blockquote>
- <Markdown>
- **Data capture:** Eve records full message history and model outputs by default. Set
- `recordInputs: false` or `recordOutputs: false` in `defineInstrumentation` if you do not
- want that data included in exported spans.
- </Markdown>
- </Blockquote>
-
<Markdown>
{dedent`
You can expect captured \`$ai_generation\` events to have the following properties:
diff --git a/docs/onboarding/ai-observability/fireworks-ai.tsx b/docs/onboarding/ai-observability/fireworks-ai.tsx
index 7c78a0a81cf5..617089cefcff 100644
--- a/docs/onboarding/ai-observability/fireworks-ai.tsx
+++ b/docs/onboarding/ai-observability/fireworks-ai.tsx
@@ -1,203 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getFireworksAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-fireworks-ai)
- and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-fireworks-ai)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-fireworks-ai)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-fireworks-ai)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Fireworks AI',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Fireworks AI, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.fireworks.ai/inference/v1",
- api_key="<fireworks_api_key>",
- )
-
- response = client.chat.completions.create(
- model="accounts/fireworks/models/llama-v3p3-70b-instruct",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.fireworks.ai/inference/v1',
- apiKey: '<fireworks_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'accounts/fireworks/models/llama-v3p3-70b-instruct',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getFireworksAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Fireworks AI',
+ slug: 'fireworks-ai',
+ baseUrl: 'https://api.fireworks.ai/inference/v1',
+ apiKeyPlaceholder: '<fireworks_api_key>',
+ defaultModel: 'accounts/fireworks/models/llama-v3p3-70b-instruct',
+ })
export const FireworksAIInstallation = createInstallation(getFireworksAISteps)
diff --git a/docs/onboarding/ai-observability/google.tsx b/docs/onboarding/ai-observability/google.tsx
index 75cf68ffd8af..1097af45947b 100644
--- a/docs/onboarding/ai-observability/google.tsx
+++ b/docs/onboarding/ai-observability/google.tsx
@@ -17,18 +17,11 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
See the complete
[Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-gemini) and
[Python](https://github.com/PostHog/posthog-python/tree/main/examples/example-ai-gemini)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-gemini) and
- [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/0fdbc2e9/examples/example-ai-gemini)
- examples.
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <Markdown>
- Install the OpenTelemetry SDK, the Google Gen AI instrumentation, and the Google Gen AI SDK.
- </Markdown>
+ <Markdown>Install the PostHog SDK and the Google Gen AI SDK.</Markdown>
<CodeBlock
blocks={[
@@ -36,14 +29,14 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
language: 'bash',
file: 'Python',
code: dedent`
- pip install google-genai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-google-generativeai
+ pip install posthog google-genai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install @google/genai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @traceloop/instrumentation-google-generativeai
+ npm install @posthog/ai posthog-node @google/genai
`,
},
]}
@@ -52,13 +45,14 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument Google Gen AI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client, then swap in PostHog's Google Gen AI wrapper.
+ `}
</Markdown>
<CodeBlock
@@ -67,54 +61,32 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.google_generativeai import GoogleGenerativeAiInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
+ from posthog import Posthog
+ from posthog.ai.gemini import Client
+ import time, uuid
+ from google.genai import types
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
- GoogleGenerativeAiInstrumentor().instrument()
+ client = Client(
+ api_key="your_gemini_api_key",
+ posthog_client=posthog,
+ )
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { GenAIInstrumentation } from '@traceloop/instrumentation-google-generativeai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new GenAIInstrumentation()],
+ import { GoogleGenAI } from '@posthog/ai/gemini'
+ import { PostHog } from 'posthog-node'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new GoogleGenAI({
+ apiKey: 'your_gemini_api_key',
+ posthog,
})
- sdk.start()
`,
},
]}
@@ -128,8 +100,10 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
content: (
<>
<Markdown>
- Now, when you use the Google Gen AI SDK to call Gemini, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
+ {dedent`
+ When you use the wrapped client to call Gemini, PostHog automatically captures an
+ \`$ai_generation\` event.
+ `}
</Markdown>
<CodeBlock
@@ -138,32 +112,36 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
language: 'python',
file: 'Python',
code: dedent`
- from google import genai
-
- client = genai.Client(api_key="your_gemini_api_key")
+ trace_id = str(uuid.uuid4())
response = client.models.generate_content(
model="gemini-2.5-flash",
- contents=[{"role": "user", "parts": [{"text": "Tell me a fun fact about hedgehogs"}]}],
+ contents=[{"role": "user", "parts": [{"text": "What's the weather in Paris?"}]}],
+ config=types.GenerateContentConfig(tools=tools),
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ },
)
-
- print(response.text)
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { GoogleGenAI } from '@google/genai'
-
- const client = new GoogleGenAI({ apiKey: 'your_gemini_api_key' })
+ const traceId = crypto.randomUUID()
const response = await client.models.generateContent({
model: 'gemini-2.5-flash',
- contents: 'Tell me a fun fact about hedgehogs',
+ contents: "What's the weather in Paris?",
+ config: { tools },
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ },
})
-
- console.log(response.text)
`,
},
]}
@@ -171,16 +149,8 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
<Blockquote>
<Markdown>
- {dedent`
- **Note:** This integration also works with Vertex AI via Google Cloud Platform. Initialize the Google Gen AI client with \`vertexai=True, project=..., location=...\` (Python) or \`{ vertexai: true, project: '...', location: '...' }\` (Node) and the OpenTelemetry instrumentation will capture those calls the same way.
- `}
- </Markdown>
- </Blockquote>
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
</Blockquote>
@@ -195,14 +165,87 @@ export const getGoogleSteps = (ctx: OnboardingComponentsContext): StepDefinition
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool
+ calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for call in response.function_calls or []:
+ start = time.time()
+ result = run_tool(call.name, call.args)
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": call.name,
+ "$ai_input_state": call.args,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const call of response.functionCalls ?? []) {
+ const start = Date.now()
+ const result = await runTool(call.name, call.args)
+
+ posthog.capture({
+ distinctId: 'user_123',
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: 'conversation-abc',
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: call.name,
+ $ai_input_state: call.args,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
{
title: 'Capture embeddings',
badge: 'optional',
content: (
<>
<Markdown>
- PostHog can also capture embedding generations as `$ai_embedding` events. The OpenTelemetry
- instrumentation automatically captures these when you use the `embed_content` API:
+ PostHog can also capture embedding generations as `$ai_embedding` events. The wrapped client
+ captures these automatically when you use the `embed_content` API:
</Markdown>
<CodeBlock
diff --git a/docs/onboarding/ai-observability/groq.tsx b/docs/onboarding/ai-observability/groq.tsx
index 3f44969757e2..e97f41792a5e 100644
--- a/docs/onboarding/ai-observability/groq.tsx
+++ b/docs/onboarding/ai-observability/groq.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getGroqSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-groq) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-groq)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-groq) and
- [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-groq)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Groq',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Groq, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.groq.com/openai/v1",
- api_key="<groq_api_key>",
- )
-
- response = client.chat.completions.create(
- model="llama-3.3-70b-versatile",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.groq.com/openai/v1',
- apiKey: '<groq_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'llama-3.3-70b-versatile',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getGroqSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Groq',
+ slug: 'groq',
+ baseUrl: 'https://api.groq.com/openai/v1',
+ apiKeyPlaceholder: '<groq_api_key>',
+ defaultModel: 'llama-3.3-70b-versatile',
+ })
export const GroqInstallation = createInstallation(getGroqSteps)
diff --git a/docs/onboarding/ai-observability/helicone.tsx b/docs/onboarding/ai-observability/helicone.tsx
index e8e4f523a812..8d73099b2054 100644
--- a/docs/onboarding/ai-observability/helicone.tsx
+++ b/docs/onboarding/ai-observability/helicone.tsx
@@ -1,208 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getHeliconeSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-helicone) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-helicone)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-helicone)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-helicone)
- examples.
- </Markdown>
- </CalloutBox>
-
- <CalloutBox type="fyi" icon="IconInfo" title="About Helicone">
- <Markdown>
- Helicone is an open-source AI gateway that provides access to 100+ LLM providers through an
- OpenAI-compatible interface. The Helicone API key handles authentication and routing to your
- chosen model provider.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Helicone',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you call Helicone with the OpenAI SDK, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://ai-gateway.helicone.ai/",
- api_key="<helicone_api_key>",
- )
-
- response = client.chat.completions.create(
- model="gpt-5-mini",
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://ai-gateway.helicone.ai/',
- apiKey: '<helicone_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'gpt-5-mini',
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getHeliconeSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Helicone',
+ slug: 'helicone',
+ baseUrl: 'https://ai-gateway.helicone.ai/',
+ apiKeyPlaceholder: '<helicone_api_key>',
+ defaultModel: 'gpt-5-mini',
+ })
export const HeliconeInstallation = createInstallation(getHeliconeSteps)
diff --git a/docs/onboarding/ai-observability/hugging-face.tsx b/docs/onboarding/ai-observability/hugging-face.tsx
index 873ca1ff64ac..38258a7e0d52 100644
--- a/docs/onboarding/ai-observability/hugging-face.tsx
+++ b/docs/onboarding/ai-observability/hugging-face.tsx
@@ -1,203 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getHuggingFaceSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-hugging-face)
- and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-hugging-face)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-hugging-face)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-hugging-face)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Hugging Face',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Hugging Face, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://router.huggingface.co/v1/",
- api_key="<huggingface_api_key>",
- )
-
- response = client.chat.completions.create(
- model="meta-llama/Llama-3.3-70B-Instruct",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://router.huggingface.co/v1/',
- apiKey: '<huggingface_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'meta-llama/Llama-3.3-70B-Instruct',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getHuggingFaceSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Hugging Face',
+ slug: 'hugging-face',
+ baseUrl: 'https://router.huggingface.co/v1/',
+ apiKeyPlaceholder: '<huggingface_api_key>',
+ defaultModel: 'meta-llama/Llama-3.3-70B-Instruct',
+ })
export const HuggingFaceInstallation = createInstallation(getHuggingFaceSteps)
diff --git a/docs/onboarding/ai-observability/instructor.tsx b/docs/onboarding/ai-observability/instructor.tsx
index 037a954375bd..4e7e125e460c 100644
--- a/docs/onboarding/ai-observability/instructor.tsx
+++ b/docs/onboarding/ai-observability/instructor.tsx
@@ -19,12 +19,12 @@ export const getInstructorSteps = (ctx: OnboardingComponentsContext): StepDefini
[Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-instructor)
and
[Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-instructor)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
+ examples on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry: see the
+ [Node.js
wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-instructor)
and [Python
wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-instructor)
- examples.
+ examples instead.
</Markdown>
</CalloutBox>
diff --git a/docs/onboarding/ai-observability/langchain.tsx b/docs/onboarding/ai-observability/langchain.tsx
index 4586cab00448..7c3e4abb3f94 100644
--- a/docs/onboarding/ai-observability/langchain.tsx
+++ b/docs/onboarding/ai-observability/langchain.tsx
@@ -18,18 +18,11 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
See the complete
[Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-langchain) and
[Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-langchain)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-langchain)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-langchain)
- examples.
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <Markdown>
- Install the OpenTelemetry SDK, the LangChain instrumentation, and LangChain with OpenAI.
- </Markdown>
+ <Markdown>Install the PostHog SDK and LangChain with OpenAI.</Markdown>
<CodeBlock
blocks={[
@@ -37,14 +30,14 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'bash',
file: 'Python',
code: dedent`
- pip install langchain langchain-core langchain-openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-langchain
+ pip install posthog "langchain>=1.0" langchain-core langchain-openai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install langchain @langchain/core @langchain/openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @traceloop/instrumentation-langchain
+ npm install posthog-node @posthog/ai langchain@^1.0 @langchain/core @langchain/openai zod
`,
},
]}
@@ -53,13 +46,15 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument LangChain calls and export traces to PostHog. PostHog
- converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client once, then build a callback handler for each request or
+ conversation. \`distinct_id\` ties each call to a user, and \`$ai_session_id\` groups calls in one conversation.
+ `}
</Markdown>
<CodeBlock
@@ -68,58 +63,47 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.langchain import LangchainInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ from posthog import Posthog
+ from posthog.ai.langchain import CallbackHandler
- LangchainInstrumentor().instrument()
- `,
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
+
+ def create_handler(user_id: str, session_id: str) -> CallbackHandler:
+ return CallbackHandler(
+ client=posthog,
+ distinct_id=user_id,
+ properties={"$ai_session_id": session_id},
+ )
+ `,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { LangChainInstrumentation } from '@traceloop/instrumentation-langchain'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new LangChainInstrumentation()],
- })
- sdk.start()
- `,
+ import { PostHog } from 'posthog-node'
+ import { LangChainCallbackHandler } from '@posthog/ai/langchain'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ function createHandler(userId: string, sessionId: string): LangChainCallbackHandler {
+ return new LangChainCallbackHandler({
+ client: posthog,
+ distinctId: userId,
+ properties: { $ai_session_id: sessionId },
+ })
+ }
+ `,
},
]}
/>
+
+ <Blockquote>
+ <Markdown>
+ **Note:** If you want to capture LLM events anonymously, omit `distinct_id`/`distinctId`
+ when constructing the handler. See our docs on [anonymous vs identified
+ events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
+ </Markdown>
+ </Blockquote>
</>
),
},
@@ -129,8 +113,9 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
content: (
<>
<Markdown>
- Use LangChain as normal. The OpenTelemetry instrumentation automatically captures
- `$ai_generation` events for each LLM call — no callback handlers needed.
+ {dedent`
+ Build your agent once and build the handler on each turn to track the relevant sessions. Traces, generations, and spans (tool calls) are automatically captured.
+ `}
</Markdown>
<CodeBlock
@@ -140,19 +125,26 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
file: 'Python',
code: dedent`
from langchain_openai import ChatOpenAI
- from langchain_core.prompts import ChatPromptTemplate
+ from langchain_core.tools import tool
+ from langchain.agents import create_agent
- prompt = ChatPromptTemplate.from_messages([
- ("system", "You are a helpful assistant."),
- ("user", "{input}")
- ])
+ @tool
+ def get_weather(city: str) -> str:
+ """Get the weather for a given city."""
+ return f"It's always sunny in {city}!"
model = ChatOpenAI(openai_api_key="your_openai_api_key")
- chain = prompt | model
+ agent = create_agent(model, tools=[get_weather])
- response = chain.invoke({"input": "Tell me a joke about programming"})
+ def ask(user_input: str, user_id: str, conversation_id: str) -> str:
+ handler = create_handler(user_id=user_id, session_id=conversation_id)
+ result = agent.invoke(
+ {"messages": [{"role": "user", "content": user_input}]},
+ config={"callbacks": [handler]},
+ )
+ return result["messages"][-1].content
- print(response.content)
+ ask("What's the weather in Paris?", "user_123", "conversation-abc")
`,
},
{
@@ -160,19 +152,34 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
file: 'Node',
code: dedent`
import { ChatOpenAI } from '@langchain/openai'
- import { ChatPromptTemplate } from '@langchain/core/prompts'
-
- const prompt = ChatPromptTemplate.fromMessages([
- ["system", "You are a helpful assistant."],
- ["user", "{input}"]
- ])
+ import { tool } from '@langchain/core/tools'
+ import { createAgent } from 'langchain'
+ import { z } from 'zod'
+
+ const getWeather = tool(
+ (input) => \`It's always sunny in \${input.city}!\`,
+ {
+ name: 'get_weather',
+ description: 'Get the weather for a given city',
+ schema: z.object({
+ city: z.string().describe('The city to get the weather for'),
+ }),
+ }
+ )
- const model = new ChatOpenAI({ apiKey: "your_openai_api_key" })
- const chain = prompt.pipe(model)
+ const model = new ChatOpenAI({ apiKey: 'your_openai_api_key' })
+ const agent = createAgent({ model, tools: [getWeather] })
- const response = await chain.invoke({ input: "Tell me a joke about programming" })
+ async function ask(userInput: string, userId: string, conversationId: string): Promise<string> {
+ const handler = createHandler(userId, conversationId)
+ const result = await agent.invoke(
+ { messages: [{ role: 'user', content: userInput }] },
+ { callbacks: [handler] }
+ )
+ return result.messages[result.messages.length - 1].content
+ }
- console.log(response.content)
+ await ask("What's the weather in Paris?", 'user_123', 'conversation-abc')
`,
},
]}
@@ -180,9 +187,13 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
<Blockquote>
<Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
+ {dedent`
+ **Using LangChain 0.x?** LangChain built agents with \`AgentExecutor\` before 1.0.
+ Everything else on this page is the same on either version, including the handler
+ and the properties it sets. See LangChain's
+ [migration guide](https://docs.langchain.com/oss/python/migrate/langchain-v1) to move
+ to \`create_agent\`.
+ `}
</Markdown>
</Blockquote>
@@ -193,7 +204,12 @@ export const getLangChainSteps = (ctx: OnboardingComponentsContext): StepDefinit
{NotableGenerationProperties && <NotableGenerationProperties />}
<Markdown>
- It also automatically creates a trace hierarchy based on how LangChain components are nested.
+ {dedent`
+ The handler also builds a trace hierarchy automatically based on how you structure your
+ agent. Pass the same \`$ai_session_id\` to every handler you construct for a
+ conversation, to group its calls into one session. Pass \`trace_id\`/\`traceId\` too, to
+ control the top-level trace ID instead of letting PostHog generate one.
+ `}
</Markdown>
</>
),
diff --git a/docs/onboarding/ai-observability/langgraph.tsx b/docs/onboarding/ai-observability/langgraph.tsx
index 1931e1393050..5d2518e4f8d8 100644
--- a/docs/onboarding/ai-observability/langgraph.tsx
+++ b/docs/onboarding/ai-observability/langgraph.tsx
@@ -18,18 +18,11 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
See the complete
[Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-langgraph) and
[Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-langgraph)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-langgraph)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-langgraph)
- examples.
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <Markdown>
- Install the OpenTelemetry SDK, the LangChain instrumentation, and LangGraph with OpenAI.
- </Markdown>
+ <Markdown>Install the PostHog SDK and LangGraph with OpenAI.</Markdown>
<CodeBlock
blocks={[
@@ -37,14 +30,14 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'bash',
file: 'Python',
code: dedent`
- pip install langgraph langchain-core langchain-openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-langchain
+ pip install posthog langgraph langchain-core langchain-openai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install @langchain/langgraph @langchain/openai @langchain/core zod @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @traceloop/instrumentation-langchain
+ npm install posthog-node @posthog/ai @langchain/langgraph @langchain/openai @langchain/core zod
`,
},
]}
@@ -53,14 +46,15 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument LangChain calls and export traces to PostHog.
- LangGraph is built on LangChain, so the same instrumentation captures all LLM calls. PostHog
- converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client once, then build a callback handler for each request or
+ conversation. \`distinct_id\` ties each call to a user, and \`$ai_session_id\` groups calls in one conversation.
+ `}
</Markdown>
<CodeBlock
@@ -69,58 +63,47 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.langchain import LangchainInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ from posthog import Posthog
+ from posthog.ai.langchain import CallbackHandler
- LangchainInstrumentor().instrument()
- `,
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
+
+ def create_handler(user_id: str, session_id: str) -> CallbackHandler:
+ return CallbackHandler(
+ client=posthog,
+ distinct_id=user_id,
+ properties={"$ai_session_id": session_id},
+ )
+ `,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { LangChainInstrumentation } from '@traceloop/instrumentation-langchain'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new LangChainInstrumentation()],
- })
- sdk.start()
- `,
+ import { PostHog } from 'posthog-node'
+ import { LangChainCallbackHandler } from '@posthog/ai/langchain'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ function createHandler(userId: string, sessionId: string): LangChainCallbackHandler {
+ return new LangChainCallbackHandler({
+ client: posthog,
+ distinctId: userId,
+ properties: { $ai_session_id: sessionId },
+ })
+ }
+ `,
},
]}
/>
+
+ <Blockquote>
+ <Markdown>
+ **Note:** If you want to capture LLM events anonymously, omit `distinct_id`/`distinctId`
+ when constructing the handler. See our docs on [anonymous vs identified
+ events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
+ </Markdown>
+ </Blockquote>
</>
),
},
@@ -130,8 +113,12 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
content: (
<>
<Markdown>
- Use LangGraph as normal. The OpenTelemetry instrumentation automatically captures
- `$ai_generation` events for each LLM call — no callback handlers needed.
+ {dedent`
+ Attach the handler through \`config\` when you invoke the graph, inside the function
+ that handles a turn. Because \`create_react_agent\` runs the turn as a single root
+ run, PostHog nests each tool call as an \`$ai_span\` under the trace automatically,
+ with real latency.
+ `}
</Markdown>
<CodeBlock
@@ -152,21 +139,25 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
model = ChatOpenAI(api_key="your_openai_api_key")
agent = create_react_agent(model, tools=[get_weather])
- result = agent.invoke(
- {"messages": [{"role": "user", "content": "What's the weather in Paris?"}]}
- )
+ def ask(user_input: str, user_id: str, conversation_id: str) -> str:
+ handler = create_handler(user_id=user_id, session_id=conversation_id)
+ result = agent.invoke(
+ {"messages": [{"role": "user", "content": user_input}]},
+ config={"callbacks": [handler]},
+ )
+ return result["messages"][-1].content
- print(result["messages"][-1].content)
+ print(ask("What's the weather in Paris?", "user_123", "conversation-abc"))
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { createReactAgent } from '@langchain/langgraph/prebuilt';
- import { ChatOpenAI } from '@langchain/openai';
- import { tool } from '@langchain/core/tools';
- import { z } from 'zod';
+ import { createReactAgent } from '@langchain/langgraph/prebuilt'
+ import { ChatOpenAI } from '@langchain/openai'
+ import { tool } from '@langchain/core/tools'
+ import { z } from 'zod'
const getWeather = tool(
(input) => \`It's always sunny in \${input.city}!\`,
@@ -177,36 +168,40 @@ export const getLangGraphSteps = (ctx: OnboardingComponentsContext): StepDefinit
city: z.string().describe('The city to get the weather for'),
}),
}
- );
+ )
- const model = new ChatOpenAI({ apiKey: 'your_openai_api_key' });
- const agent = createReactAgent({ llm: model, tools: [getWeather] });
+ const model = new ChatOpenAI({ apiKey: 'your_openai_api_key' })
+ const agent = createReactAgent({ model, tools: [getWeather] })
- const result = await agent.invoke(
- { messages: [{ role: 'user', content: "What's the weather in Paris?" }] }
- );
+ async function ask(userInput: string, userId: string, conversationId: string): Promise<string> {
+ const handler = createHandler(userId, conversationId)
+ const result = await agent.invoke(
+ { messages: [{ role: 'user', content: userInput }] },
+ { callbacks: [handler] }
+ )
+ return result.messages[result.messages.length - 1].content
+ }
- console.log(result.messages[result.messages.length - 1].content);
+ console.log(await ask("What's the weather in Paris?", 'user_123', 'conversation-abc'))
`,
},
]}
/>
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
+ <Markdown>
+ PostHog automatically captures an `$ai_generation` event along with these properties:
+ </Markdown>
+
+ {NotableGenerationProperties && <NotableGenerationProperties />}
<Markdown>
{dedent`
- PostHog automatically captures \`$ai_generation\` events and creates a trace hierarchy based on how LangGraph components are nested. You can expect captured events to have the following properties:
+ The handler also builds a trace hierarchy automatically based on how you structure
+ your graph. Pass the same \`$ai_session_id\` to every handler you construct for a
+ conversation, to group its calls into one session. Pass \`trace_id\`/\`traceId\`
+ too, to control the top-level trace ID instead of letting PostHog generate one.
`}
</Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
</>
),
},
diff --git a/docs/onboarding/ai-observability/litellm.tsx b/docs/onboarding/ai-observability/litellm.tsx
index 7d1bce00e9a0..063eaff3305d 100644
--- a/docs/onboarding/ai-observability/litellm.tsx
+++ b/docs/onboarding/ai-observability/litellm.tsx
@@ -13,8 +13,8 @@ export const getLiteLLMSteps = (ctx: OnboardingComponentsContext): StepDefinitio
content: (
<Blockquote>
<Markdown>
- **Note:** LiteLLM can be used as a Python SDK or as a proxy server. PostHog observability
- requires LiteLLM version 1.77.3 or higher.
+ **Note:** Use LiteLLM as a Python SDK or as a proxy server. PostHog observability requires
+ LiteLLM version 1.77.3 or higher.
</Markdown>
</Blockquote>
),
@@ -110,8 +110,11 @@ export const getLiteLLMSteps = (ctx: OnboardingComponentsContext): StepDefinitio
content: (
<>
<Markdown>
- Now, when you use LiteLLM to call various LLM providers, PostHog automatically captures an
- `$ai_generation` event.
+ {dedent`
+ When you use LiteLLM to call an LLM provider, PostHog automatically captures an
+ \`$ai_generation\` event. Identity and trace data travel through \`metadata\`, since
+ LiteLLM has no dedicated \`posthog_trace_id\` parameter.
+ `}
</Markdown>
<CodeBlock
@@ -120,18 +123,24 @@ export const getLiteLLMSteps = (ctx: OnboardingComponentsContext): StepDefinitio
language: 'python',
file: 'SDK',
code: dedent`
+ from posthog import Posthog
+ import time, uuid, json
+
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
+
+ trace_id = str(uuid.uuid4())
+
response = litellm.completion(
model="gpt-5-mini",
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
+ messages=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
metadata={
- "user_id": "user_123", # Maps to PostHog distinct_id
- "company": "company_id_in_your_db" # Custom property
- }
+ "user_id": "user_123", # Maps to PostHog distinct_id
+ "company": "company_id_in_your_db", # Custom property
+ "$ai_session_id": "conversation-abc",
+ "$ai_trace_id": trace_id,
+ },
)
-
- print(response.choices[0].message.content)
`,
},
{
@@ -151,7 +160,8 @@ export const getLiteLLMSteps = (ctx: OnboardingComponentsContext): StepDefinitio
],
"metadata": {
"user_id": "user_123",
- "company": "company_id_in_your_db" # Custom property
+ "company": "company_id_in_your_db", # Custom property
+ "$ai_session_id": "conversation-abc" # Groups calls into one session
}
}'
`,
@@ -165,7 +175,9 @@ export const getLiteLLMSteps = (ctx: OnboardingComponentsContext): StepDefinitio
**Notes:**
- This works with streaming responses by setting \`stream=True\`.
- To disable logging for specific requests, add \`{"no-log": true}\` to metadata.
- - If you want to capture LLM events anonymously, **don't** pass a \`user_id\` in metadata.
+ - Pass \`$ai_session_id\` in metadata to group calls from the same conversation into
+ one PostHog session.
+ - If you want to capture LLM events anonymously, **do not** pass a \`user_id\` in metadata.
See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
`}
@@ -182,6 +194,50 @@ export const getLiteLLMSteps = (ctx: OnboardingComponentsContext): StepDefinitio
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ Capture each tool call as a span yourself, as the example below does right after the
+ generation that triggered it.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ language="python"
+ code={dedent`
+ for call in response.choices[0].message.tool_calls or []:
+ start = time.time()
+ result = run_tool(call.function.name, json.loads(call.function.arguments))
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": call.function.name,
+ "$ai_input_state": call.function.arguments,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
{
title: 'Capture embeddings',
badge: 'optional',
diff --git a/docs/onboarding/ai-observability/llamaindex.tsx b/docs/onboarding/ai-observability/llamaindex.tsx
index a7e6802720d7..d7b4b81f5f14 100644
--- a/docs/onboarding/ai-observability/llamaindex.tsx
+++ b/docs/onboarding/ai-observability/llamaindex.tsx
@@ -17,8 +17,8 @@ export const getLlamaIndexSteps = (ctx: OnboardingComponentsContext): StepDefini
<Markdown>
See the complete [Python
example](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-llamaindex)
- on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
- wrapper
+ on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see this example
+ instead: [Python wrapper
example](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-llamaindex).
</Markdown>
</CalloutBox>
@@ -30,7 +30,7 @@ export const getLlamaIndexSteps = (ctx: OnboardingComponentsContext): StepDefini
<CodeBlock
language="bash"
code={dedent`
- pip install llama-index llama-index-llms-openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-llamaindex
+ pip install llama-index llama-index-llms-openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
`}
/>
</>
@@ -53,7 +53,7 @@ export const getLlamaIndexSteps = (ctx: OnboardingComponentsContext): StepDefini
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.llamaindex import LlamaIndexInstrumentor
+ from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
resource = Resource(attributes={
SERVICE_NAME: "my-app",
@@ -70,9 +70,18 @@ export const getLlamaIndexSteps = (ctx: OnboardingComponentsContext): StepDefini
)
trace.set_tracer_provider(provider)
- LlamaIndexInstrumentor().instrument()
+ OpenAIInstrumentor().instrument()
`}
/>
+
+ <CalloutBox type="fyi" icon="IconInfo" title="What gets captured">
+ <Markdown>
+ This instruments the OpenAI calls LlamaIndex makes underneath, so you get one
+ `$ai_generation` per LLM call. Retrieval and query-engine steps are not captured as spans.
+ To record those, capture `$ai_span` events yourself with a shared `$ai_trace_id`. See
+ [manual capture](https://posthog.com/docs/ai-observability/installation/manual-capture).
+ </Markdown>
+ </CalloutBox>
</>
),
},
diff --git a/docs/onboarding/ai-observability/manual.tsx b/docs/onboarding/ai-observability/manual.tsx
index 03e183b4e980..b1e7d82de990 100644
--- a/docs/onboarding/ai-observability/manual.tsx
+++ b/docs/onboarding/ai-observability/manual.tsx
@@ -25,9 +25,11 @@ export const getManualSteps = (ctx: OnboardingComponentsContext): StepDefinition
content: (
<>
<Markdown>
- If you're using a different server-side SDK or prefer to use the API, you can manually capture
- the data by calling the `capture` method or using the [capture
- API](https://posthog.com/docs/api/capture).
+ {dedent`
+ If you use a different server-side SDK, or prefer to use the API, capture the data
+ manually. Call the \`capture\` method, or use the [capture
+ API](https://posthog.com/docs/api/capture).
+ `}
</Markdown>
<Tab.Group tabs={languages.map((l) => l.label)}>
diff --git a/docs/onboarding/ai-observability/mirascope.tsx b/docs/onboarding/ai-observability/mirascope.tsx
index e98d49a1401f..d94be63731e2 100644
--- a/docs/onboarding/ai-observability/mirascope.tsx
+++ b/docs/onboarding/ai-observability/mirascope.tsx
@@ -17,7 +17,7 @@ export const getMirascopeSteps = (ctx: OnboardingComponentsContext): StepDefinit
<Markdown>
See the complete [Python
example](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-mirascope)
- on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
+ on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
wrapper
example](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-mirascope).
</Markdown>
@@ -87,17 +87,31 @@ export const getMirascopeSteps = (ctx: OnboardingComponentsContext): StepDefinit
<CodeBlock
language="python"
code={dedent`
- from mirascope.core import openai, prompt_template
+ from mirascope import llm
- @openai.call("gpt-4o-mini")
- @prompt_template("Tell me a fun fact about {topic}")
- def fun_fact(topic: str): ...
+ # Route OpenAI calls through chat.completions. Mirascope defaults to the
+ # Responses API, which the OpenTelemetry instrumentation does not cover.
+ llm.register_provider("openai:completions")
+
+ @llm.call("openai/gpt-4o-mini")
+ def fun_fact(topic: str) -> str:
+ return f"Tell me a fun fact about {topic}"
response = fun_fact("hedgehogs")
- print(response.content)
+ print(response.text())
`}
/>
+ <CalloutBox type="caution" icon="IconWarning" title="Use the completions provider">
+ <Markdown>
+ `opentelemetry-instrumentation-openai-v2` instruments `chat.completions` and `embeddings`
+ only. Mirascope v2 uses the OpenAI Responses API by default, which produces no spans.
+ `llm.register_provider("openai:completions")` switches it to `chat.completions`, so the
+ instrumentation captures the calls. This page targets Mirascope 2.x. The `mirascope.core`
+ API was v1 and no longer exists.
+ </Markdown>
+ </CalloutBox>
+
<Blockquote>
<Markdown>
**Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
diff --git a/docs/onboarding/ai-observability/mistral.tsx b/docs/onboarding/ai-observability/mistral.tsx
index 1986534bea75..5984915951dd 100644
--- a/docs/onboarding/ai-observability/mistral.tsx
+++ b/docs/onboarding/ai-observability/mistral.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getMistralSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-mistral) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-mistral)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-mistral)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-mistral)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Mistral',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Mistral, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.mistral.ai/v1",
- api_key="<mistral_api_key>",
- )
-
- response = client.chat.completions.create(
- model="mistral-large-latest",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.mistral.ai/v1',
- apiKey: '<mistral_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'mistral-large-latest',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getMistralSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Mistral',
+ slug: 'mistral',
+ baseUrl: 'https://api.mistral.ai/v1',
+ apiKeyPlaceholder: '<mistral_api_key>',
+ defaultModel: 'mistral-large-latest',
+ })
export const MistralInstallation = createInstallation(getMistralSteps)
diff --git a/docs/onboarding/ai-observability/ollama.tsx b/docs/onboarding/ai-observability/ollama.tsx
index 9661a6a22863..e1243d127326 100644
--- a/docs/onboarding/ai-observability/ollama.tsx
+++ b/docs/onboarding/ai-observability/ollama.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getOllamaSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-ollama) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-ollama)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-ollama) and
- [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-ollama)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Ollama',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Ollama, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="http://localhost:11434/v1",
- api_key="ollama",
- )
-
- response = client.chat.completions.create(
- model="llama3.2",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'http://localhost:11434/v1',
- apiKey: 'ollama',
- })
-
- const response = await client.chat.completions.create({
- model: 'llama3.2',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getOllamaSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Ollama',
+ slug: 'ollama',
+ baseUrl: 'http://localhost:11434/v1',
+ apiKeyPlaceholder: 'ollama',
+ defaultModel: 'llama3.2',
+ })
export const OllamaInstallation = createInstallation(getOllamaSteps)
diff --git a/docs/onboarding/ai-observability/openai-agents.tsx b/docs/onboarding/ai-observability/openai-agents.tsx
index 555b553da677..1c55fa84a899 100644
--- a/docs/onboarding/ai-observability/openai-agents.tsx
+++ b/docs/onboarding/ai-observability/openai-agents.tsx
@@ -60,7 +60,7 @@ export const getOpenAIAgentsSteps = (ctx: OnboardingComponentsContext): StepDefi
<>
<Markdown>
Initialize PostHog with your project token and host from [your project
- settings](https://app.posthog.com/settings/project), then call `instrument()` to register
+ settings](https://app.posthog.com/settings/project). Then call `instrument()` to register
PostHog tracing with the OpenAI Agents SDK. This automatically captures all agent traces, spans,
and LLM generations.
</Markdown>
@@ -88,7 +88,7 @@ export const getOpenAIAgentsSteps = (ctx: OnboardingComponentsContext): StepDefi
<Blockquote>
<Markdown>
- **Note:** If you want to capture LLM events anonymously, **don't** pass a distinct ID to
+ **Note:** If you want to capture LLM events anonymously, **do not** pass a distinct ID to
`instrument()`. See our docs on [anonymous vs identified
events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
@@ -102,21 +102,34 @@ export const getOpenAIAgentsSteps = (ctx: OnboardingComponentsContext): StepDefi
content: (
<>
<Markdown>
- Run your OpenAI agents as normal. PostHog automatically captures `$ai_generation` events for LLM
- calls and `$ai_span` events for agent execution, tool calls, and handoffs.
+ {dedent`
+ Run your OpenAI agents as normal. PostHog automatically captures \`$ai_generation\`
+ events for LLM calls and \`$ai_span\` events for agent execution, tool calls, and
+ handoffs. The example below defines a tool and lets the agent call it.
+ `}
</Markdown>
<CodeBlock
language="python"
code={dedent`
- from agents import Agent, Runner
+ from agents import Agent, Runner, RunConfig, function_tool
+
+ @function_tool
+ def get_weather(city: str) -> str:
+ """Get the weather for a city."""
+ return f"The weather in {city} is sunny, 72F"
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
+ tools=[get_weather],
)
- result = Runner.run_sync(agent, "Tell me a fun fact about hedgehogs")
+ result = Runner.run_sync(
+ agent,
+ "What's the weather in Paris?",
+ run_config=RunConfig(group_id="conversation-abc"),
+ )
print(result.final_output)
`}
/>
@@ -137,8 +150,10 @@ export const getOpenAIAgentsSteps = (ctx: OnboardingComponentsContext): StepDefi
content: (
<>
<Markdown>
- PostHog captures the full trace hierarchy for complex agent workflows including handoffs and
- tool calls.
+ {dedent`
+ PostHog captures the full trace hierarchy for complex agent workflows, including
+ handoffs between multiple agents.
+ `}
</Markdown>
<CodeBlock
@@ -176,6 +191,13 @@ export const getOpenAIAgentsSteps = (ctx: OnboardingComponentsContext): StepDefi
- Generation spans for all LLM calls
`}
</Markdown>
+
+ <Markdown>
+ {dedent`
+ As with the single-agent example above, PostHog captures every span in that list
+ automatically. You write no extra code for the handoff itself.
+ `}
+ </Markdown>
</>
),
},
diff --git a/docs/onboarding/ai-observability/openai.tsx b/docs/onboarding/ai-observability/openai.tsx
index e7ae26f6a885..f1c95a21b67c 100644
--- a/docs/onboarding/ai-observability/openai.tsx
+++ b/docs/onboarding/ai-observability/openai.tsx
@@ -18,16 +18,11 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
See the complete
[Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-openai) and
[Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-openai)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-openai) and
- [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-openai)
- examples.
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
+ <Markdown>Install the PostHog SDK and the OpenAI SDK.</Markdown>
<CodeBlock
blocks={[
@@ -35,14 +30,14 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
language: 'bash',
file: 'Python',
code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
+ pip install posthog openai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
+ npm install @posthog/ai posthog-node openai
`,
},
]}
@@ -51,13 +46,14 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client, then swap in PostHog's OpenAI wrapper.
+ `}
</Markdown>
<CodeBlock
@@ -66,54 +62,31 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
+ from posthog import Posthog
+ from posthog.ai.openai import OpenAI
+ import time, uuid, json
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
- OpenAIInstrumentor().instrument()
+ client = OpenAI(
+ api_key="your_openai_api_key",
+ posthog_client=posthog,
+ )
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
+ import { OpenAI } from '@posthog/ai/openai'
+ import { PostHog } from 'posthog-node'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new OpenAI({
+ apiKey: 'your_openai_api_key',
+ posthog,
})
- sdk.start()
`,
},
]}
@@ -127,8 +100,10 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
content: (
<>
<Markdown>
- Now, when you use the OpenAI SDK to call OpenAI, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
+ {dedent`
+ When you use the wrapped client to call OpenAI, PostHog automatically captures an
+ \`$ai_generation\` event.
+ `}
</Markdown>
<CodeBlock
@@ -137,38 +112,36 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
language: 'python',
file: 'Python',
code: dedent`
- import openai
-
- client = openai.OpenAI(
- api_key="your_openai_api_key",
- )
+ trace_id = str(uuid.uuid4())
response = client.responses.create(
model="gpt-5-mini",
- input=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
+ input=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ },
)
-
- print(response.output_text)
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- apiKey: 'your_openai_api_key',
- })
+ const traceId = crypto.randomUUID()
const response = await client.responses.create({
model: 'gpt-5-mini',
- input: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
+ input: [{ role: 'user', content: "What's the weather in Paris?" }],
+ tools,
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ },
})
-
- console.log(response.output_text)
`,
},
]}
@@ -176,8 +149,8 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
<Blockquote>
<Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
</Blockquote>
@@ -192,14 +165,91 @@ export const getOpenAISteps = (ctx: OnboardingComponentsContext): StepDefinition
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for item in response.output:
+ if item.type != "function_call":
+ continue
+
+ start = time.time()
+ result = run_tool(item.name, json.loads(item.arguments))
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": item.name,
+ "$ai_input_state": item.arguments,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const item of response.output) {
+ if (item.type !== 'function_call') continue
+
+ const start = Date.now()
+ const result = await runTool(item.name, JSON.parse(item.arguments))
+
+ posthog.capture({
+ distinctId: 'user_123',
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: 'conversation-abc',
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: item.name,
+ $ai_input_state: item.arguments,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
{
title: 'Capture embeddings',
badge: 'optional',
content: (
<>
<Markdown>
- PostHog can also capture embedding generations as `$ai_embedding` events. The OpenTelemetry
- instrumentation automatically captures these when you use the embeddings API:
+ PostHog can also capture embedding generations as `$ai_embedding` events. The wrapped client
+ captures these automatically when you use the embeddings API:
</Markdown>
<CodeBlock
diff --git a/docs/onboarding/ai-observability/openrouter.tsx b/docs/onboarding/ai-observability/openrouter.tsx
index e0ce9518c4e2..6edb4c11f2bc 100644
--- a/docs/onboarding/ai-observability/openrouter.tsx
+++ b/docs/onboarding/ai-observability/openrouter.tsx
@@ -1,203 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getOpenRouterSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-openrouter)
- and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-openrouter)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-openrouter)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-openrouter)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call OpenRouter',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call OpenRouter, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://openrouter.ai/api/v1",
- api_key="<openrouter_api_key>",
- )
-
- response = client.chat.completions.create(
- model="gpt-5-mini",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://openrouter.ai/api/v1',
- apiKey: '<openrouter_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'gpt-5-mini',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getOpenRouterSteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'OpenRouter',
+ slug: 'openrouter',
+ baseUrl: 'https://openrouter.ai/api/v1',
+ apiKeyPlaceholder: '<openrouter_api_key>',
+ defaultModel: 'gpt-5-mini',
+ })
export const OpenRouterInstallation = createInstallation(getOpenRouterSteps)
diff --git a/docs/onboarding/ai-observability/opentelemetry.tsx b/docs/onboarding/ai-observability/opentelemetry.tsx
index 247e8bdc3d9c..3df2e02079ab 100644
--- a/docs/onboarding/ai-observability/opentelemetry.tsx
+++ b/docs/onboarding/ai-observability/opentelemetry.tsx
@@ -120,16 +120,6 @@ export const getOpenTelemetrySteps = (ctx: OnboardingComponentsContext): StepDef
},
]}
/>
-
- <Markdown>
- {dedent`
- PostHog identifies each event using the \`posthog.distinct_id\` attribute on the OpenTelemetry
- **Resource** (with \`user.id\` as a fallback, then a random UUID if neither is set). Because
- the Resource applies to every span in a batched export, you only need to set the distinct ID
- once — there's no need for a \`BaggageSpanProcessor\` or per-span propagation. Any other
- Resource or span attributes pass through as event properties.
- `}
- </Markdown>
</>
),
},
diff --git a/docs/onboarding/ai-observability/perplexity.tsx b/docs/onboarding/ai-observability/perplexity.tsx
index c00ae8b81afc..4b46f59320a7 100644
--- a/docs/onboarding/ai-observability/perplexity.tsx
+++ b/docs/onboarding/ai-observability/perplexity.tsx
@@ -1,203 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getPerplexitySteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-perplexity)
- and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-perplexity)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-perplexity)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-perplexity)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Perplexity',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Perplexity, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.perplexity.ai",
- api_key="<perplexity_api_key>",
- )
-
- response = client.chat.completions.create(
- model="sonar",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.perplexity.ai',
- apiKey: '<perplexity_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'sonar',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getPerplexitySteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Perplexity',
+ slug: 'perplexity',
+ baseUrl: 'https://api.perplexity.ai',
+ apiKeyPlaceholder: '<perplexity_api_key>',
+ defaultModel: 'sonar',
+ })
export const PerplexityInstallation = createInstallation(getPerplexitySteps)
diff --git a/docs/onboarding/ai-observability/portkey.tsx b/docs/onboarding/ai-observability/portkey.tsx
index 66bf24ea6098..3e16f8f276d9 100644
--- a/docs/onboarding/ai-observability/portkey.tsx
+++ b/docs/onboarding/ai-observability/portkey.tsx
@@ -16,26 +16,14 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
<CalloutBox type="info" icon="IconInfo" title="Full working examples">
<Markdown>
See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-portkey) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-portkey)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-portkey)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-portkey)
- examples.
+ [Node.js](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-portkey)
+ and
+ [Python](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-portkey)
+ examples on GitHub.
</Markdown>
</CalloutBox>
- <CalloutBox type="fyi" icon="IconInfo" title="About Portkey">
- <Markdown>
- Portkey acts as an AI gateway that routes requests to 250+ LLM providers. The model string
- format (`@integration-slug/model`) determines which provider to use, where the slug is the
- name you chose when setting up the integration in Portkey.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
+ <Markdown>Install the PostHog SDK, the OpenAI SDK, and the Portkey SDK.</Markdown>
<CodeBlock
blocks={[
@@ -43,14 +31,14 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
language: 'bash',
file: 'Python',
code: dedent`
- pip install openai portkey-ai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
+ pip install posthog openai portkey-ai
`,
},
{
language: 'bash',
file: 'Node',
code: dedent`
- npm install openai portkey-ai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
+ npm install @posthog/ai posthog-node openai portkey-ai
`,
},
]}
@@ -59,13 +47,15 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
),
},
{
- title: 'Set up OpenTelemetry tracing',
+ title: 'Configure PostHog',
badge: 'required',
content: (
<>
<Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
+ {dedent`
+ Create a PostHog client, then swap in PostHog's OpenAI wrapper, pointed at Portkey's
+ gateway URL.
+ `}
</Markdown>
<CodeBlock
@@ -74,54 +64,35 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
language: 'python',
file: 'Python',
code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
+ from posthog import Posthog
+ from posthog.ai.openai import OpenAI
+ from portkey_ai import PORTKEY_GATEWAY_URL
+ import time, uuid, json
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
+ posthog = Posthog("<ph_project_token>", host="<ph_client_api_host>")
- OpenAIInstrumentor().instrument()
+ client = OpenAI(
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="<portkey_api_key>",
+ posthog_client=posthog,
+ )
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
+ import { OpenAI } from '@posthog/ai/openai'
+ import { PostHog } from 'posthog-node'
+ import { PORTKEY_GATEWAY_URL } from 'portkey-ai'
+
+ const posthog = new PostHog('<ph_project_token>', { host: '<ph_client_api_host>' })
+
+ const client = new OpenAI({
+ baseURL: PORTKEY_GATEWAY_URL,
+ apiKey: '<portkey_api_key>',
+ posthog,
})
- sdk.start()
`,
},
]}
@@ -135,8 +106,10 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
content: (
<>
<Markdown>
- Now, when you call Portkey with the OpenAI SDK, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
+ {dedent`
+ When you use the wrapped client to call Portkey, PostHog automatically captures an
+ \`$ai_generation\` event.
+ `}
</Markdown>
<CodeBlock
@@ -145,42 +118,38 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
language: 'python',
file: 'Python',
code: dedent`
- import openai
- from portkey_ai import PORTKEY_GATEWAY_URL
-
- client = openai.OpenAI(
- base_url=PORTKEY_GATEWAY_URL,
- api_key="<portkey_api_key>",
- )
+ trace_id = str(uuid.uuid4())
response = client.chat.completions.create(
model="@<integration-slug>/gpt-5-mini",
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
+ messages=[{"role": "user", "content": "What's the weather in Paris?"}],
+ tools=tools,
+ posthog_distinct_id="user_123",
+ posthog_trace_id=trace_id,
+ posthog_properties={
+ "$ai_session_id": "conversation-abc",
+ "$ai_provider": "portkey",
+ },
)
-
- print(response.choices[0].message.content)
`,
},
{
language: 'typescript',
file: 'Node',
code: dedent`
- import OpenAI from 'openai'
- import { PORTKEY_GATEWAY_URL } from 'portkey-ai'
-
- const client = new OpenAI({
- baseURL: PORTKEY_GATEWAY_URL,
- apiKey: '<portkey_api_key>',
- })
+ const traceId = crypto.randomUUID()
const response = await client.chat.completions.create({
model: '@<integration-slug>/gpt-5-mini',
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
+ messages: [{ role: 'user', content: "What's the weather in Paris?" }],
+ tools,
+ posthogDistinctId: 'user_123',
+ posthogTraceId: traceId,
+ posthogProperties: {
+ $ai_session_id: 'conversation-abc',
+ $ai_provider: 'portkey',
+ },
})
-
- console.log(response.choices[0].message.content)
`,
},
]}
@@ -188,8 +157,8 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
<Blockquote>
<Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
+ **Note:** If you want to capture LLM events anonymously, omit `posthog_distinct_id` from the
+ call. See our docs on [anonymous vs identified
events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
</Markdown>
</Blockquote>
@@ -204,6 +173,79 @@ export const getPortkeySteps = (ctx: OnboardingComponentsContext): StepDefinitio
</>
),
},
+ {
+ title: 'Capture tool calls as spans',
+ badge: 'optional',
+ content: (
+ <>
+ <Markdown>
+ {dedent`
+ For standard responses, the posthog client captures it as a generation. For all tool
+ calls, you must manually capture them as \`$ai_span\` events.
+ `}
+ </Markdown>
+
+ <CodeBlock
+ blocks={[
+ {
+ language: 'python',
+ file: 'Python',
+ code: dedent`
+ for call in response.choices[0].message.tool_calls or []:
+ start = time.time()
+ result = run_tool(call.function.name, json.loads(call.function.arguments))
+
+ posthog.capture(
+ distinct_id="user_123",
+ event="$ai_span",
+ properties={
+ "$ai_trace_id": trace_id,
+ "$ai_session_id": "conversation-abc",
+ "$ai_span_id": str(uuid.uuid4()),
+ "$ai_span_name": call.function.name,
+ "$ai_input_state": call.function.arguments,
+ "$ai_output_state": result,
+ "$ai_latency": time.time() - start,
+ },
+ )
+ `,
+ },
+ {
+ language: 'typescript',
+ file: 'Node',
+ code: dedent`
+ for (const call of response.choices[0].message.tool_calls ?? []) {
+ const start = Date.now()
+ const result = await runTool(call.function.name, JSON.parse(call.function.arguments))
+
+ posthog.capture({
+ distinctId: 'user_123',
+ event: '$ai_span',
+ properties: {
+ $ai_trace_id: traceId,
+ $ai_session_id: 'conversation-abc',
+ $ai_span_id: crypto.randomUUID(),
+ $ai_span_name: call.function.name,
+ $ai_input_state: call.function.arguments,
+ $ai_output_state: result,
+ $ai_latency: (Date.now() - start) / 1000,
+ },
+ })
+ }
+ `,
+ },
+ ]}
+ />
+
+ <Markdown>
+ {dedent`
+ See [spans](https://posthog.com/docs/ai-observability/spans) for the full list of span
+ properties.
+ `}
+ </Markdown>
+ </>
+ ),
+ },
]
}
diff --git a/docs/onboarding/ai-observability/pydantic-ai.tsx b/docs/onboarding/ai-observability/pydantic-ai.tsx
index bbccc0120e0c..67061ed24af6 100644
--- a/docs/onboarding/ai-observability/pydantic-ai.tsx
+++ b/docs/onboarding/ai-observability/pydantic-ai.tsx
@@ -17,7 +17,7 @@ export const getPydanticAISteps = (ctx: OnboardingComponentsContext): StepDefini
<Markdown>
See the complete [Python
example](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-pydantic-ai)
- on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
+ on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
wrapper
example](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-pydantic-ai).
</Markdown>
diff --git a/docs/onboarding/ai-observability/semantic-kernel.tsx b/docs/onboarding/ai-observability/semantic-kernel.tsx
index 7517726d9aff..6d1c4cf5f530 100644
--- a/docs/onboarding/ai-observability/semantic-kernel.tsx
+++ b/docs/onboarding/ai-observability/semantic-kernel.tsx
@@ -17,8 +17,8 @@ export const getSemanticKernelSteps = (ctx: OnboardingComponentsContext): StepDe
<Markdown>
See the complete [Python
example](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-semantic-kernel)
- on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
- wrapper
+ on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see this example
+ instead: [Python wrapper
example](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-semantic-kernel).
</Markdown>
</CalloutBox>
diff --git a/docs/onboarding/ai-observability/smolagents.tsx b/docs/onboarding/ai-observability/smolagents.tsx
index d052a20053e0..571cbdbe05dd 100644
--- a/docs/onboarding/ai-observability/smolagents.tsx
+++ b/docs/onboarding/ai-observability/smolagents.tsx
@@ -17,7 +17,7 @@ export const getSmolagentsSteps = (ctx: OnboardingComponentsContext): StepDefini
<Markdown>
See the complete [Python
example](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-smolagents)
- on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
+ on GitHub. If you use the PostHog SDK wrapper instead of OpenTelemetry, see the [Python
wrapper
example](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-smolagents).
</Markdown>
diff --git a/docs/onboarding/ai-observability/together-ai.tsx b/docs/onboarding/ai-observability/together-ai.tsx
index 429914dbda2a..0078ee3b2c08 100644
--- a/docs/onboarding/ai-observability/together-ai.tsx
+++ b/docs/onboarding/ai-observability/together-ai.tsx
@@ -1,203 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getTogetherAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-together-ai)
- and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-together-ai)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-together-ai)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-together-ai)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Together AI',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call Together AI, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.together.xyz/v1",
- api_key="<together_api_key>",
- )
-
- response = client.chat.completions.create(
- model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.together.xyz/v1',
- apiKey: '<together_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- {dedent`
- **Note:** If you want to capture LLM events anonymously, omit the \`posthog.distinct_id\` resource attribute. See our docs on [anonymous vs identified events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- `}
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getTogetherAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Together AI',
+ slug: 'together-ai',
+ baseUrl: 'https://api.together.xyz/v1',
+ apiKeyPlaceholder: '<together_api_key>',
+ defaultModel: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',
+ })
export const TogetherAIInstallation = createInstallation(getTogetherAISteps)
diff --git a/docs/onboarding/ai-observability/vercel-ai-gateway.tsx b/docs/onboarding/ai-observability/vercel-ai-gateway.tsx
index 91f2f1f65da1..3e52b6583d68 100644
--- a/docs/onboarding/ai-observability/vercel-ai-gateway.tsx
+++ b/docs/onboarding/ai-observability/vercel-ai-gateway.tsx
@@ -1,208 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getVercelAIGatewaySteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-vercel-ai-gateway)
- and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-vercel-ai-gateway)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-vercel-ai-gateway)
- and [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-vercel-ai-gateway)
- examples.
- </Markdown>
- </CalloutBox>
-
- <CalloutBox type="fyi" icon="IconInfo" title="About Vercel AI Gateway">
- <Markdown>
- Vercel AI Gateway provides a unified OpenAI-compatible API for accessing multiple LLM
- providers. It handles routing, caching, and rate limiting for your AI requests.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call Vercel AI Gateway',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you call Vercel AI Gateway with the OpenAI SDK, PostHog automatically captures
- `$ai_generation` events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://ai-gateway.vercel.sh/v1",
- api_key="<your_api_key>",
- )
-
- response = client.chat.completions.create(
- model="gpt-5-mini",
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://ai-gateway.vercel.sh/v1',
- apiKey: '<your_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'gpt-5-mini',
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getVercelAIGatewaySteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'Vercel AI Gateway',
+ slug: 'vercel-ai-gateway',
+ baseUrl: 'https://ai-gateway.vercel.sh/v1',
+ apiKeyPlaceholder: '<your_api_key>',
+ defaultModel: 'gpt-5-mini',
+ })
export const VercelAIGatewayInstallation = createInstallation(getVercelAIGatewaySteps)
diff --git a/docs/onboarding/ai-observability/vercel-ai.tsx b/docs/onboarding/ai-observability/vercel-ai.tsx
index 88068f1c2314..adf3f45aec6d 100644
--- a/docs/onboarding/ai-observability/vercel-ai.tsx
+++ b/docs/onboarding/ai-observability/vercel-ai.tsx
@@ -13,12 +13,15 @@ export const getVercelAISteps = (ctx: OnboardingComponentsContext): StepDefiniti
badge: 'required',
content: (
<>
- <Markdown>Install the PostHog AI package, the Vercel AI SDK, and the OpenTelemetry SDK.</Markdown>
+ <Markdown>
+ Install the PostHog AI package, the Vercel AI SDK, the OpenTelemetry SDK, and Zod for defining
+ tool schemas.
+ </Markdown>
<CodeBlock
language="bash"
code={dedent`
- npm install @posthog/ai @ai-sdk/openai ai @opentelemetry/sdk-node @opentelemetry/resources
+ npm install @posthog/ai @ai-sdk/openai ai @opentelemetry/sdk-node @opentelemetry/resources zod
`}
/>
</>
@@ -65,25 +68,38 @@ export const getVercelAISteps = (ctx: OnboardingComponentsContext): StepDefiniti
content: (
<>
<Markdown>
- Pass `experimental_telemetry` to your Vercel AI SDK calls. The `posthog_distinct_id` metadata
- field links events to a specific user in PostHog.
+ {dedent`
+ Pass \`experimental_telemetry\` to your Vercel AI SDK calls. The \`posthog_distinct_id\`
+ metadata field links events to a specific user in PostHog. Define \`tools\` the same way
+ you always would, with an \`execute\` function, as \`get_weather\` does below.
+ `}
</Markdown>
<CodeBlock
language="typescript"
code={dedent`
- import { generateText } from 'ai'
+ import { generateText, tool, stepCountIs } from 'ai'
import { openai } from '@ai-sdk/openai'
+ import { z } from 'zod'
const result = await generateText({
model: openai('gpt-5-mini'),
- prompt: 'Tell me a fun fact about hedgehogs.',
+ prompt: "What's the weather in Paris?",
+ tools: {
+ get_weather: tool({
+ description: 'Get the weather for a city',
+ inputSchema: z.object({ city: z.string() }),
+ execute: async ({ city }) => \`It's always sunny in \${city}!\`,
+ }),
+ },
+ stopWhen: stepCountIs(5), // let the model see the tool result and respond
experimental_telemetry: {
isEnabled: true,
functionId: 'my-ai-function',
metadata: {
posthog_distinct_id: 'user_123', // optional
posthog_environment: 'production', // custom property: sets "environment" on the event
+ $ai_session_id: 'conversation-abc', // optional: groups calls into one session
},
},
})
@@ -103,9 +119,9 @@ export const getVercelAISteps = (ctx: OnboardingComponentsContext): StepDefiniti
<Blockquote>
<Markdown>
**Custom properties:** Prefix any telemetry metadata field with `posthog_` to attach it to
- the `$ai_generation` event as a custom property. The prefix is stripped, so
+ the `$ai_generation` event as a custom property. PostHog strips the prefix, so
`posthog_environment` becomes an `environment` property you can filter and break down by.
- Other metadata fields aren't captured.
+ PostHog does not capture other metadata fields.
</Markdown>
</Blockquote>
diff --git a/docs/onboarding/ai-observability/xai.tsx b/docs/onboarding/ai-observability/xai.tsx
index 4e60ab64c8f0..aaf019e2302b 100644
--- a/docs/onboarding/ai-observability/xai.tsx
+++ b/docs/onboarding/ai-observability/xai.tsx
@@ -1,202 +1,15 @@
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'
import { StepDefinition } from '../steps'
-
-export const getXAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
- const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx
-
- const NotableGenerationProperties = snippets?.NotableGenerationProperties
-
- return [
- {
- title: 'Install dependencies',
- badge: 'required',
- content: (
- <>
- <CalloutBox type="info" icon="IconInfo" title="Full working examples">
- <Markdown>
- See the complete
- [Node.js](https://github.com/PostHog/posthog-js/tree/main/examples/example-ai-xai) and
- [Python](https://github.com/PostHog/posthog-python/tree/master/examples/example-ai-xai)
- examples on GitHub. If you're using the PostHog SDK wrapper instead of OpenTelemetry, see
- the [Node.js
- wrapper](https://github.com/PostHog/posthog-js/tree/e08ff1be/examples/example-ai-xai) and
- [Python
- wrapper](https://github.com/PostHog/posthog-python/tree/7223c52/examples/example-ai-xai)
- examples.
- </Markdown>
- </CalloutBox>
-
- <Markdown>Install the OpenTelemetry SDK, the OpenAI instrumentation, and the OpenAI SDK.</Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'bash',
- file: 'Python',
- code: dedent`
- pip install openai opentelemetry-sdk "posthog[otel]" opentelemetry-instrumentation-openai-v2
- `,
- },
- {
- language: 'bash',
- file: 'Node',
- code: dedent`
- npm install openai @posthog/ai @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/instrumentation-openai
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Set up OpenTelemetry tracing',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Configure OpenTelemetry to auto-instrument OpenAI SDK calls and export traces to PostHog.
- PostHog converts `gen_ai.*` spans into `$ai_generation` events automatically.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- from opentelemetry import trace
- from opentelemetry.sdk.trace import TracerProvider
- from opentelemetry.sdk.resources import Resource, SERVICE_NAME
- from posthog.ai.otel import PostHogSpanProcessor
- from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
-
- resource = Resource(attributes={
- SERVICE_NAME: "my-app",
- "posthog.distinct_id": "user_123", # optional: identifies the user in PostHog
- "foo": "bar", # custom properties are passed through
- })
-
- provider = TracerProvider(resource=resource)
- provider.add_span_processor(
- PostHogSpanProcessor(
- api_key="<ph_project_token>",
- host="<ph_client_api_host>",
- )
- )
- trace.set_tracer_provider(provider)
-
- OpenAIInstrumentor().instrument()
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import { NodeSDK } from '@opentelemetry/sdk-node'
- import { resourceFromAttributes } from '@opentelemetry/resources'
- import { PostHogSpanProcessor } from '@posthog/ai/otel'
- import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai'
-
- const sdk = new NodeSDK({
- resource: resourceFromAttributes({
- 'service.name': 'my-app',
- 'posthog.distinct_id': 'user_123', // optional: identifies the user in PostHog
- foo: 'bar', // custom properties are passed through
- }),
- spanProcessors: [
- new PostHogSpanProcessor({
- apiKey: '<ph_project_token>',
- host: '<ph_client_api_host>',
- }),
- ],
- instrumentations: [new OpenAIInstrumentation()],
- })
- sdk.start()
- `,
- },
- ]}
- />
- </>
- ),
- },
- {
- title: 'Call xAI',
- badge: 'required',
- content: (
- <>
- <Markdown>
- Now, when you use the OpenAI SDK to call xAI, PostHog automatically captures `$ai_generation`
- events via the OpenTelemetry instrumentation.
- </Markdown>
-
- <CodeBlock
- blocks={[
- {
- language: 'python',
- file: 'Python',
- code: dedent`
- import openai
-
- client = openai.OpenAI(
- base_url="https://api.x.ai/v1",
- api_key="<xai_api_key>",
- )
-
- response = client.chat.completions.create(
- model="grok-3",
- max_completion_tokens=1024,
- messages=[
- {"role": "user", "content": "Tell me a fun fact about hedgehogs"}
- ],
- )
-
- print(response.choices[0].message.content)
- `,
- },
- {
- language: 'typescript',
- file: 'Node',
- code: dedent`
- import OpenAI from 'openai'
-
- const client = new OpenAI({
- baseURL: 'https://api.x.ai/v1',
- apiKey: '<xai_api_key>',
- })
-
- const response = await client.chat.completions.create({
- model: 'grok-3',
- max_completion_tokens: 1024,
- messages: [{ role: 'user', content: 'Tell me a fun fact about hedgehogs' }],
- })
-
- console.log(response.choices[0].message.content)
- `,
- },
- ]}
- />
-
- <Blockquote>
- <Markdown>
- **Note:** If you want to capture LLM events anonymously, omit the `posthog.distinct_id`
- resource attribute. See our docs on [anonymous vs identified
- events](https://posthog.com/docs/data/anonymous-vs-identified-events) to learn more.
- </Markdown>
- </Blockquote>
-
- <Markdown>
- {dedent`
- You can expect captured \`$ai_generation\` events to have the following properties:
- `}
- </Markdown>
-
- {NotableGenerationProperties && <NotableGenerationProperties />}
- </>
- ),
- },
- ]
-}
+import { getOpenAICompatibleSteps } from './_snippets/openai-compatible'
+
+export const getXAISteps = (ctx: OnboardingComponentsContext): StepDefinition[] =>
+ getOpenAICompatibleSteps(ctx, {
+ label: 'xAI',
+ slug: 'xai',
+ baseUrl: 'https://api.x.ai/v1',
+ apiKeyPlaceholder: '<xai_api_key>',
+ defaultModel: 'grok-3',
+ })
export const XAIInstallation = createInstallation(getXAISteps)