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.

10.3 KB
Raw Blame
import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'

import { PROSE_LANGUAGE, StepDefinition } from '../steps'
import { getOtelRequestContextStep } from './_snippets/otel-request-context'

export const getAWSBedrockSteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {
    const { CodeBlock, CalloutBox, Markdown, Blockquote, dedent, snippets } = ctx

    const NotableGenerationProperties = snippets?.NotableGenerationProperties

    return [
        {
            title: 'Install dependencies',
            badge: 'required',
            content: (
                <>
                    <Markdown>
                        Install the OpenTelemetry SDK, OTLP exporter, and the AWS SDK instrumentation for your language.
                    </Markdown>

                    <CodeBlock
                        blocks={[
                            {
                                language: 'bash',
                                file: 'Python',
                                code: dedent`
                                    pip install boto3 opentelemetry-instrumentation-botocore opentelemetry-sdk "posthog[otel]"
                                `,
                            },
                            {
                                language: 'bash',
                                file: 'Node',
                                code: dedent`
                                    npm install @aws-sdk/client-bedrock-runtime @opentelemetry/instrumentation-aws-sdk @opentelemetry/sdk-node @opentelemetry/resources @posthog/ai
                                `,
                            },
                            {
                                language: PROSE_LANGUAGE,
                                file: 'Go',
                                code: "There are no Go instrumentation libraries for the AWS SDK yet. Register PostHog's span processor and set the `gen_ai.*` attributes on a span around each Bedrock call, as shown in the Go tab of the [OpenTelemetry integration](https://posthog.com/docs/ai-observability/installation/opentelemetry).",
                            },
                        ]}
                    />
                </>
            ),
        },
        {
            title: 'Set up the OpenTelemetry exporter',
            badge: 'required',
            content: (
                <>
                    <Markdown>
                        Configure the OpenTelemetry SDK to export traces to PostHog's OTLP ingestion endpoint. 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.botocore import BotocoreInstrumentor

                                    resource = Resource(attributes={
                                        SERVICE_NAME: "my-ai-app",
                                    })

                                    provider = TracerProvider(resource=resource)
                                    provider.add_span_processor(
                                        PostHogSpanProcessor(
                                            api_key="<ph_project_token>",
                                            host="<ph_client_api_host>",
                                        )
                                    )
                                    trace.set_tracer_provider(provider)

                                    BotocoreInstrumentor().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 { AwsInstrumentation } from '@opentelemetry/instrumentation-aws-sdk'

                                    const sdk = new NodeSDK({
                                      resource: resourceFromAttributes({
                                        'service.name': 'my-ai-app',
                                      }),
                                      spanProcessors: [
                                        new PostHogSpanProcessor({
                                          projectToken: '<ph_project_token>',
                                          host: '<ph_client_api_host>',
                                        }),
                                      ],
                                      instrumentations: [new AwsInstrumentation()],
                                    })
                                    sdk.start()
                                `,
                            },
                        ]}
                    />
                </>
            ),
        },
        {
            title: 'Call Bedrock',
            badge: 'required',
            content: (
                <>
                    <Markdown>
                        Make Bedrock API calls as normal. The instrumentation automatically captures `gen_ai.*` spans
                        for Converse, ConverseStream, InvokeModel, and InvokeModelWithResponseStream operations.
                    </Markdown>

                    <CodeBlock
                        blocks={[
                            {
                                language: 'python',
                                file: 'Python',
                                code: dedent`
                                    import boto3

                                    client = boto3.client("bedrock-runtime", region_name="us-east-1")

                                    response = client.converse(
                                        modelId="openai.gpt-oss-20b-1:0",
                                        messages=[
                                            {
                                                "role": "user",
                                                "content": [{"text": "Tell me a fun fact about hedgehogs."}],
                                            }
                                        ],
                                    )

                                    for block in response["output"]["message"]["content"]:
                                        if "text" in block:
                                            print(block["text"])
                                            break
                                `,
                            },
                            {
                                language: 'typescript',
                                file: 'Node',
                                code: dedent`
                                    // The AWS SDK must be imported after sdk.start() so the
                                    // instrumentation can patch it.
                                    const {
                                      BedrockRuntimeClient,
                                      ConverseCommand,
                                    } = await import('@aws-sdk/client-bedrock-runtime')

                                    const client = new BedrockRuntimeClient({ region: 'us-east-1' })

                                    const response = await client.send(
                                      new ConverseCommand({
                                        modelId: 'openai.gpt-oss-20b-1:0',
                                        messages: [
                                          {
                                            role: 'user',
                                            content: [{ text: 'Tell me a fun fact about hedgehogs.' }],
                                          },
                                        ],
                                      })
                                    )

                                    const textBlock = response.output?.message?.content?.find((b) => 'text' in b)
                                    console.log(textBlock?.text)

                                    await sdk.shutdown()
                                `,
                            },
                        ]}
                    />

                    <CalloutBox type="fyi" icon="IconInfo" title="Supported models">
                        <Markdown>
                            The instrumentation emits `gen_ai.*` spans for **Amazon Titan**, **Amazon Nova**, and
                            **Anthropic Claude** models. Tool call instrumentation is available for Amazon Nova and
                            Anthropic Claude 3+.
                        </Markdown>
                    </CalloutBox>

                    <Blockquote>
                        <Markdown>
                            **Note:** To capture LLM events anonymously, omit the `posthog.distinct_id` resource
                            attribute and don't set a distinct ID in the PostHog context. 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 />}
                </>
            ),
        },
        getOtelRequestContextStep(ctx, { languages: ['Python', 'Node'] }),
    ]
}

export const AWSBedrockInstallation = createInstallation(getAWSBedrockSteps)