πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(filters): trace with local export (#9471)
Nimard3f35d1f222e
diff --git a/.env.dev.example b/.env.dev.exampleindex c9301d9636..bbe8d382ee 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -89,14 +89,14 @@ SLACK_CLIENT_ID=your_slack_client_idSLACK_CLIENT_SECRET=your_slack_client_secretSLACK_STATE_SECRET=your_slack_state_secret-# Langfuse AI feature credentials for development-LANGFUSE_AI_FEATURES_PUBLIC_KEY="pk-lf-123456789"-LANGFUSE_AI_FEATURES_SECRET_KEY="sk-lf-123456789"-LANGFUSE_AI_FEATURES_HOST="https://staging.langfuse.com"+# Langfuse AI instance for tracing, prompts+LANGFUSE_AI_FEATURES_PUBLIC_KEY="pk-lf-1234567890"+LANGFUSE_AI_FEATURES_SECRET_KEY="sk-lf-1234567890"+LANGFUSE_AI_FEATURES_HOST="http://localhost:3000"+LANGFUSE_AI_FEATURES_PROJECT_ID=7a88fb47-b4e2-43b8-a06c-a5ce950dc53a-# Bedrock credentials for development+# Langfuse AI Bedrock credentialsAWS_ACCESS_KEY_ID="A123456789"AWS_SECRET_ACCESS_KEY="SAK123456789"LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"--LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-3-5-sonnet-20240620-v1:0"+LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-3-haiku-20240307-v1:0"diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex 52ae26e56b..ddb218e2cb 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -722,6 +722,7 @@ async function generatePrompts(project: Project) {createdBy: version.createdBy,prompt: version.prompt,name: version.name,+ type: version.type ?? "text",config: version.config,version: version.version,labels: version.labels,diff --git a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts b/packages/shared/scripts/seeder/utils/postgres-seed-constants.tsindex c2f21da231..e8d986bc21 100644--- a/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts+++ b/packages/shared/scripts/seeder/utils/postgres-seed-constants.ts@@ -400,6 +400,177 @@ export const SEED_CHAT_ML_PROMPTS = [];export const SEED_PROMPT_VERSIONS = [+ {+ createdBy: "user-1",+ type: "chat",+ prompt: [+ {+ role: "system",+ content: `## Role+You are a Langfuse filter generator. Your sole function is to parse user queries about AI traces and output the corresponding filter array in JSON format. Map natural language to appropriate column names, operators, and values.++## Available columns and their types:+- bookmarked (boolean): Starred/bookmarked traces+- id (string): Trace ID+- name (stringOptions): Trace name+- environment (stringOptions): Environment (dev, prod, etc.)+- timestamp (datetime): When the trace occurred+- userId (string): User identifier+- sessionId (string): Session identifier+- metadata (stringObject): Custom metadata+- version (string): Version identifier+- release (string): Release identifier+- level (stringOptions): Log level - DEBUG, DEFAULT, WARNING, ERROR+- tags (arrayOptions): Custom tags+- inputTokens (number): Input token count+- outputTokens (number): Output token count+- totalTokens (number): Total token count+- tokens (number): Alias for total tokens+- errorCount (number): Count of error-level observations+- warningCount (number): Count of warning-level observations+- defaultCount (number): Count of default-level observations+- debugCount (number): Count of debug-level observations+- scores_avg (numberObject): Numeric evaluation scores+- score_categories (categoryOptions): Categorical evaluation scores+- latency (number): Latency in seconds+- inputCost (number): Input cost in USD+- outputCost (number): Output cost in USD+- totalCost (number): Total cost in USD++## Type-Operator Compatibility Rules++**string type** - Use for text matching operations:+- Operators: "=", "contains", "does not contain", "starts with", "ends with"+- Value: Always a single string+- Example: {"type": "string", "column": "userId", "operator": "contains", "value": "john"}++**stringOptions type** - Use ONLY for selecting from predefined options:+- Operators: "any of", "none of" ONLY+- Value: Always an array of strings+- Use when filtering columns like name, environment, level with multiple possible values+- Example: {"type": "stringOptions", "column": "environment", "operator": "any of", "value": ["dev", "staging"]}++**arrayOptions type** - Use for tag filtering:+- Operators: "any of", "none of", "all of"+- Value: Always an array of strings+- Example: {"type": "arrayOptions", "column": "tags", "operator": "any of", "value": ["important", "bug"]}++**number type** - Use for numeric comparisons:+- Operators: "=", ">", "<", ">=", "<="+- Value: Always a number+- Example: {"type": "number", "column": "latency", "operator": ">", "value": 2.5}++**datetime type** - Use for time-based filtering:+- Operators: ">", "<", ">=", "<="+- Value: Always a date string+- Example: {"type": "datetime", "column": "timestamp", "operator": ">", "value": "2024-01-01T00:00:00Z"}++**boolean type** - Use for true/false values:+- Operators: "=", "<>"+- Value: Always true or false+- Example: {"type": "boolean", "column": "bookmarked", "operator": "=", "value": true}++**stringObject type** - Use for metadata key-value searches:+- Operators: "=", "contains", "does not contain", "starts with", "ends with"+- Value: Always a string+- Requires "key" field for the metadata key+- Example: {"type": "stringObject", "column": "metadata", "key": "userId", "operator": "=", "value": "123"}++**numberObject type** - Use for numeric score searches:+- Operators: "=", ">", "<", ">=", "<="+- Value: Always a number+- Requires "key" field for the score name+- Example: {"type": "numberObject", "column": "scores_avg", "key": "quality", "operator": ">", "value": 0.8}++## Output Format++Please respond ONLY with valid JSON. Do not include any explanation or extra text.+The response should look like this without the leading EOF and trailing EOF.++EOF+{+ "filters": [+ {+ "type": "stringOptions|number|string|categoryOptions",+ "value": "value or array",+ "column": "exact column name",+ "operator": "= | > | < | any of"+ }+ ]+}+EOF++## Intent Parsing Guidelines++**Temporal expressions:**+- "today", "yesterday", "last week" β timestamp filters+- "after 2pm", "before noon", "since Monday" β timestamp with appropriate operators+- Relative times: "last 24 hours", "past 3 days" β calculate from current time++**Performance queries:**+- "slow", "high latency", "taking too long" β latency > threshold+- "expensive", "costly", "high cost" β totalCost > threshold+- "many tokens", "token heavy" β totalTokens > threshold+- "cheap", "fast", "quick" β use < operators++**Error/Quality queries:**+- "errors", "failed", "broken" β level = ERROR or errorCount > 0+- "warnings" β level = WARNING or warningCount > 0+- "successful", "working" β level = DEFAULT or errorCount = 0++**User/Session queries:**+- "user john", "by user", "user ID" β userId filters+- "session abc", "in session" β sessionId filters++**Environment queries:**+- "prod", "production" β environment = production+- "dev", "development", "staging" β environment matching+- "live", "deployed" β typically production environment++**Metadata/Tags:**+- "tagged with", "has tag" β tags contains+- "metadata contains", "custom field" β metadata object queries++**Comparison operators:**+- "more than", "over", "above", "greater" β >+- "less than", "under", "below", "fewer" β <+- "at least", "minimum" β >=+- "at most", "maximum" β <=+- "exactly", "equal to" β =+- "not", "except", "excluding" β not_equals or not_contains++**Text search operations:**+- "contains", "includes", "has" β use "string" type with "contains" operator+- "equals", "is exactly" β use "string" type with "=" operator+- "starts with", "begins with" β use "string" type with "starts with" operator++**Multi-option selections:**+- "environment is dev or staging" β use "stringOptions" type with "any of" operator+- "name is one of X, Y, Z" β use "stringOptions" type with "any of" operator+- "level is ERROR or WARNING" β use "stringOptions" type with "any of" operator++## Current DateTime++This is the current datetime: {{currentDatetime}}+Use it as a reference for datetime based queries when needed.++## Examples++Input: "I want to see all dev traces"+Output: {"filters":[{"type":"stringOptions","value":["development","dev"],"column":"environment","operator":"any of"}]}++Input: "Show traces with version starting with v2"+Output: {"filters":[{"type":"string","value":"v2","column":"version","operator":"starts with"}]}`,+ },+ {+ role: "user",+ content: "{{userPrompt}}",+ },+ ],+ name: "get-filter-conditions-from-query",+ version: 1,+ labels: ["production", "latest"],+ },{createdBy: "user-1",prompt: "Prompt 4 version 1 content with {{variable}}",diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex 641836c557..a4847a0238 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -112,6 +112,7 @@ type LLMCompletionParams = {traceParams?: TraceParams;throwOnError?: boolean; // default is truecontext?: LLMCompletionContext;+ generationMetadata?: Record<string, unknown>;};type FetchLLMCompletionParams = LLMCompletionParams & {@@ -192,50 +193,52 @@ export async function fetchLLMCompletion(let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();if (traceParams) {- let handler: CallbackHandler;-- if (- context.credentials === "langfuse" &&- env.LANGFUSE_AI_FEATURES_PUBLIC_KEY &&- env.LANGFUSE_AI_FEATURES_SECRET_KEY &&- env.LANGFUSE_AI_FEATURES_HOST- ) {- // send to configured cloud Langfuse instance- handler = new CallbackHandler({- publicKey: env.LANGFUSE_AI_FEATURES_PUBLIC_KEY,- secretKey: env.LANGFUSE_AI_FEATURES_SECRET_KEY,- baseUrl: env.LANGFUSE_AI_FEATURES_HOST,- environment: traceParams.environment,- metadata: traceParams.metadata,- });+ const handler = new CallbackHandler({+ _projectId: traceParams.projectId,+ _isLocalEventExportEnabled: true,+ environment: traceParams.environment,+ metadata: traceParams.metadata,+ userId: traceParams.userId,+ });- processTracedEvents = () => Promise.resolve();- } else {- // use local trace export- handler = new CallbackHandler({- _projectId: traceParams.projectId,- _isLocalEventExportEnabled: true,- environment: traceParams.environment,- metadata: traceParams.metadata,- });+ processTracedEvents = async () => {+ try {+ const events = await handler.langfuse._exportLocalEvents(+ traceParams.projectId,+ );+ // to add the prompt name and version to only generation-type observations+ const processedEvents = events.map((event: any) => {+ if (event.type === "generation-create" && params.generationMetadata) {+ const promptName = params.generationMetadata[+ "langfuse.observation.prompt.name"+ ] as string;+ const promptVersion = params.generationMetadata[+ "langfuse.observation.prompt.version"+ ] as number;++ return {+ ...event,+ body: {+ ...event.body,+ ...(promptName && { promptName }),+ ...(promptVersion && { promptVersion }),+ },+ };+ }+ return event;+ });- processTracedEvents = async () => {- try {- const events = await handler.langfuse._exportLocalEvents(- traceParams.projectId,- );- await processEventBatch(- JSON.parse(JSON.stringify(events)), // stringify to emulate network event batch from network call- traceParams.authCheck,- {- isLangfuseInternal: context.tracing === "langfuse",- },- );- } catch (e) {- logger.error("Failed to process traced events", { error: e });- }- };- }+ await processEventBatch(+ JSON.parse(JSON.stringify(processedEvents)), // stringify to emulate network event batch from network call+ traceParams.authCheck,+ {+ isLangfuseInternal: context.tracing === "langfuse",+ },+ );+ } catch (e) {+ logger.error("Failed to process traced events", { error: e });+ }+ };finalCallbacks.push(handler);}diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 3dff67294f..0287f44cea 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -506,4 +506,5 @@ export type TraceParams = {// TODO: add more possibilities for environment re: langfuse AI featuresenvironment: PromptExperimentEnvironment | string;authCheck: AuthHeaderValidVerificationResult;+ userId?: string;};diff --git a/web/src/features/natural-language-filters/server/router.ts b/web/src/features/natural-language-filters/server/router.tsindex ca4265b3bc..0f33ec7988 100644--- a/web/src/features/natural-language-filters/server/router.ts+++ b/web/src/features/natural-language-filters/server/router.ts@@ -72,6 +72,18 @@ export const naturalLanguageFilterRouter = createTRPCRouter({}};+ const client = getLangfuseClient(+ env.LANGFUSE_AI_FEATURES_PUBLIC_KEY as string,+ env.LANGFUSE_AI_FEATURES_SECRET_KEY as string,+ env.LANGFUSE_AI_FEATURES_HOST,+ );++ const promptResponse = await client.getPrompt(+ "get-filter-conditions-from-query",+ undefined,+ { type: "chat" },+ );+const traceParams: TraceParams = {environment: getEnvironment(),traceName: "natural-language-filter",@@ -84,20 +96,12 @@ export const naturalLanguageFilterRouter = createTRPCRouter({accessLevel: "project",} as any,},+ userId: ctx.session.user.id,+ metadata: {+ langfuse_user_id: ctx.session.user.id,+ },};- const client = getLangfuseClient(- env.LANGFUSE_AI_FEATURES_PUBLIC_KEY as string,- env.LANGFUSE_AI_FEATURES_SECRET_KEY as string,- env.LANGFUSE_AI_FEATURES_HOST,- );-- const promptResponse = await client.getPrompt(- "get-filter-conditions-from-query",- undefined,- { type: "chat" },- );-// Get current datetime in ISO format with day of week for AI contextconst now = new Date();const dayOfWeek = now.toLocaleDateString("en-US", { weekday: "long" });@@ -122,6 +126,10 @@ export const naturalLanguageFilterRouter = createTRPCRouter({tracing: "langfuse",credentials: "langfuse",},+ generationMetadata: {+ "langfuse.observation.prompt.name": promptResponse.name,+ "langfuse.observation.prompt.version": promptResponse.version,+ },});await llmCompletion.processTracedEvents();diff --git a/web/src/features/organizations/components/AIFeatureSwitch.tsx b/web/src/features/organizations/components/AIFeatureSwitch.tsxindex 3d5ceffb60..cdd9d86ed3 100644--- a/web/src/features/organizations/components/AIFeatureSwitch.tsx+++ b/web/src/features/organizations/components/AIFeatureSwitch.tsx@@ -99,7 +99,7 @@ export default function AIFeatureSwitch() {training models. Applicable HIPAA, SOC2, GDPR, and ISO 27001compliance remains intact.{" "}<a- href="https://langfuse.com/docs/security/ai-features"+ href="https://langfuse.com/security/ai-features"target="_blank"rel="noopener noreferrer"className="inline-flex items-center gap-1 text-primary hover:underline"@@ -148,7 +148,7 @@ export default function AIFeatureSwitch() {<br /><br />{" "}<a- href="https://langfuse.com/docs/security/ai-features"+ href="https://langfuse.com/security/ai-features"target="_blank"rel="noopener noreferrer"className="inline-flex items-center gap-1 text-primary hover:underline"