: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): add code snippets for fetching prompts to usage tab (#69600)
Juraj Majerikacf5537f2d9f
diff --git a/products/ai_observability/frontend/prompts/llmPromptLogic.ts b/products/ai_observability/frontend/prompts/llmPromptLogic.tsindex 1234d9f77d2c..eeaf54b4b44a 100644--- a/products/ai_observability/frontend/prompts/llmPromptLogic.ts+++ b/products/ai_observability/frontend/prompts/llmPromptLogic.ts@@ -91,6 +91,8 @@ export interface PublishConflict {latestVersion: number | null}+export type PromptSnippetLanguage = 'python' | 'node'+async function fetchResolvedPrompt(promptName: string,params?: { version?: number; offset?: number; before_version?: number; limit?: number }@@ -168,6 +170,7 @@ export const llmPromptLogic = kea<llmPromptLogicType>([openPublishReview: true,closePublishReview: true,setVersionDescription: (versionDescription: string) => ({ versionDescription }),+ setSnippetLanguage: (snippetLanguage: PromptSnippetLanguage) => ({ snippetLanguage }),}),reducers(({ props }) => ({@@ -259,6 +262,12 @@ export const llmPromptLogic = kea<llmPromptLogicType>([setMode: () => '',},],+ snippetLanguage: [+ 'python' as PromptSnippetLanguage,+ {+ setSnippetLanguage: (_, { snippetLanguage }) => snippetLanguage,+ },+ ],})),loaders(({ props }) => ({diff --git a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx b/products/ai_observability/frontend/prompts/promptSceneComponents.tsxindex ca055c874e1a..e6704ae01c72 100644--- a/products/ai_observability/frontend/prompts/promptSceneComponents.tsx+++ b/products/ai_observability/frontend/prompts/promptSceneComponents.tsx@@ -3,9 +3,19 @@ import { combineUrl } from 'kea-router'import { lazy, Suspense, useRef } from 'react'import { IconColumns, IconMarkdown, IconMarkdownFilled } from '@posthog/icons'-import { LemonBanner, LemonButton, LemonModal, LemonSelect, LemonTag, LemonTextArea, Link } from '@posthog/lemon-ui'+import {+ LemonBanner,+ LemonButton,+ LemonModal,+ LemonSelect,+ LemonTabs,+ LemonTag,+ LemonTextArea,+ Link,+} from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { dayjs } from 'lib/dayjs'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonInput } from 'lib/lemon-ui/LemonInput'@@ -13,6 +23,7 @@ import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'+import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { DataTable } from '~/queries/nodes/DataTable/DataTable'@@ -386,12 +397,111 @@ export function PromptRelatedTraces(): JSX.Element {)}+function extractPromptVariables(promptText: string): string[] {+ const matches = promptText.match(/\{\{([^}]+)\}\}/g)+ return matches ? [...new Set(matches.map((match) => match.slice(2, -2).trim()))] : []+}++function buildPythonSnippet(promptName: string, host: string, projectApiKey: string, variables: string[]): string {+ const compileLines = variables.length+ ? `\nsystem_prompt = prompts.compile(result.prompt, {${variables.map((v) => `${JSON.stringify(v)}: '...'`).join(', ')}})`+ : ''+ return `from posthog import Posthog+from posthog.ai.prompts import Prompts++posthog = Posthog(+ '${projectApiKey}',+ host='${host}',+ personal_api_key='<personal_api_key>', # scope: llm_prompt:read+)+prompts = Prompts(posthog)++result = prompts.get(${JSON.stringify(promptName)}, with_metadata=True, fallback='You are a helpful assistant.')${compileLines}+# result.name / result.version -> send as $ai_prompt_name / $ai_prompt_version on your LLM events`+}++function buildNodeSnippet(promptName: string, host: string, projectApiKey: string, variables: string[]): string {+ const compileLines = variables.length+ ? `\nconst systemPrompt = prompts.compile(result.prompt, {${variables.map((v) => ` ${JSON.stringify(v)}: '...'`).join(',')} })`+ : ''+ return `import { Prompts } from '@posthog/ai'+import { PostHog } from 'posthog-node'++const posthog = new PostHog('${projectApiKey}', {+ host: '${host}',+ personalApiKey: '<personal_api_key>', // scope: llm_prompt:read+})+const prompts = new Prompts({ posthog })++const result = await prompts.get(${JSON.stringify(promptName)}, { fallback: 'You are a helpful assistant.' })${compileLines}+// result.name / result.version -> send as $ai_prompt_name / $ai_prompt_version on your LLM events`+}++export function PromptCodeSnippets({ prompt }: { prompt: LLMPrompt }): JSX.Element {+ const { snippetLanguage } = useValues(llmPromptLogic)+ const { setSnippetLanguage } = useActions(llmPromptLogic)+ const { currentTeam } = useValues(teamLogic)++ const host = window.location.origin+ const projectApiKey = currentTeam?.api_token ?? '<project_api_key>'+ const variables = extractPromptVariables(prompt.prompt)++ return (+ <div className="mb-6" data-attr="llma-prompt-code-snippets">+ <div className="mb-2 flex items-center justify-between gap-2">+ <div>+ <b>Use this prompt in your code</b>+ <div className="text-secondary text-sm">+ Fetch the latest version at runtime — publish new versions without deploying.+ </div>+ </div>+ <LemonButton+ type="secondary"+ size="small"+ to="https://posthog.com/docs/prompt-management"+ targetBlank+ data-attr="llma-prompt-snippet-docs-link"+ >+ Read the docs+ </LemonButton>+ </div>+ <LemonTabs+ activeKey={snippetLanguage}+ onChange={(key) => setSnippetLanguage(key)}+ size="small"+ tabs={[+ {+ key: 'python' as const,+ label: 'Python',+ content: (+ <CodeSnippet language={Language.Python}>+ {buildPythonSnippet(prompt.name, host, projectApiKey, variables)}+ </CodeSnippet>+ ),+ },+ {+ key: 'node' as const,+ label: 'Node.js',+ content: (+ <CodeSnippet language={Language.JavaScript}>+ {buildNodeSnippet(prompt.name, host, projectApiKey, variables)}+ </CodeSnippet>+ ),+ },+ ]}+ />+ </div>+ )+}+export function PromptUsage({ prompt }: { prompt: LLMPrompt }): JSX.Element {const { promptUsageLogQuery, promptUsageTrendQuery, analyticsScope } = useValues(llmPromptLogic)const { setAnalyticsScope } = useActions(llmPromptLogic)return (<div data-attr="llma-prompt-usage-container">+ <PromptCodeSnippets prompt={prompt} />+<LemonBanner type="info" className="mb-4">During the beta period, each prompt fetch is currently charged as a Product analytics event. See the{' '}<Link to="https://posthog.com/pricing" target="_blank">