Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(traces): add more observation types (#8507)

Nimar78aa8fdd2625
diff --git a/CLAUDE.md b/CLAUDE.md
index 945e3a5173..8e09fc504f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -83,7 +83,8 @@ Depending on the file location (sync, async)
`web` related tests must go into the `web/src/__tests__/` folder.
```sh
pnpm test-sync --testPathPattern="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"
-pnpm test-async --testPathPattern="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"
+# For tests in the async folder:
+pnpm test -- --testPathPattern="$FILE_LOCATION_PATTERN" --testNamePattern="$TEST_NAME_PATTERN"
```
### Testing in the Worker Package
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d89e7c0d47..4e19606fe2 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -241,7 +241,7 @@ We're using Jest with in the `web` package. Therefore, if you want to provide an
There are three types of unit tests:
- `test-sync`
-- `test-async`
+- `test` (for async folder tests)
- `test-client`
To run a specific test, for example the test: `"should handle special characters in prompt names"` in `prompts.v2.servertest.ts`, run:
@@ -249,6 +249,8 @@ To run a specific test, for example the test: `"should handle special characters
```sh
cd web # or with --filter=web
pnpm test-sync --testPathPattern="prompts\.v2\.servertest" --testNamePattern="should handle special characters in prompt names"
+# for async folder tests:
+pnpm test -- --testPathPattern="observations-api" --testNamePattern="should fetch all observations"
```
To run all tests:
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.yml
index d480a1f5f6..87487778c1 100644
--- a/fern/apis/server/definition/ingestion.yml
+++ b/fern/apis/server/definition/ingestion.yml
@@ -145,6 +145,13 @@ types:
- SPAN
- GENERATION
- EVENT
+ - AGENT
+ - TOOL
+ - CHAIN
+ - RETRIEVER
+ - EVALUATOR
+ - EMBEDDING
+ - GUARDRAIL
IngestionUsage:
discriminated: false
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 6f65f1f704..0b36aae610 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -22,6 +22,13 @@ export const LegacyPrismaObservationType = {
SPAN: "SPAN",
EVENT: "EVENT",
GENERATION: "GENERATION",
+ AGENT: "AGENT",
+ TOOL: "TOOL",
+ CHAIN: "CHAIN",
+ RETRIEVER: "RETRIEVER",
+ EVALUATOR: "EVALUATOR",
+ EMBEDDING: "EMBEDDING",
+ GUARDRAIL: "GUARDRAIL",
} as const;
export type LegacyPrismaObservationType =
(typeof LegacyPrismaObservationType)[keyof typeof LegacyPrismaObservationType];
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 61d50ccc97..44f42d9e5e 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -368,7 +368,6 @@ model LegacyPrismaObservation {
version String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- // GENERATION ONLY
model String? // user-provided model attribute
internalModel String? @map("internal_model") // matched model.name that is matched at ingestion time, to be deprecated
internalModelId String? @map("internal_model_id") // matched model.id that is matched at ingestion time
@@ -409,6 +408,13 @@ enum LegacyPrismaObservationType {
SPAN
EVENT
GENERATION
+ AGENT
+ TOOL
+ CHAIN
+ RETRIEVER
+ EVALUATOR
+ EMBEDDING
+ GUARDRAIL
@@map("ObservationType")
}
diff --git a/packages/shared/scripts/seeder/utils/clickhouse-seed-constants.ts b/packages/shared/scripts/seeder/utils/clickhouse-seed-constants.ts
index 8ff8231ccb..b436ad2fee 100644
--- a/packages/shared/scripts/seeder/utils/clickhouse-seed-constants.ts
+++ b/packages/shared/scripts/seeder/utils/clickhouse-seed-constants.ts
@@ -95,3 +95,57 @@ export const REALISTIC_METADATA_EXAMPLES = [
},
{ file_type: "JSON", validation: "passed", schema_version: "v1.2" },
];
+
+export const REALISTIC_AGENT_NAMES = [
+ "AI-Coordinator",
+ "TaskManager",
+ "WorkflowOrchestrator",
+ "PlanningAgent",
+ "MultiStepAgent",
+ "SmartCoordinator",
+];
+
+export const REALISTIC_TOOL_NAMES = [
+ "WebSearchTool",
+ "CalculatorTool",
+ "WeatherForecastTool",
+ "EmailSenderTool",
+];
+
+export const REALISTIC_CHAIN_NAMES = [
+ "DataTransformationChain",
+ "ProcessingPipeline",
+ "TransformationChain",
+ "MultiStepProcess",
+];
+
+export const REALISTIC_RETRIEVER_NAMES = [
+ "DocumentRetriever",
+ "SemanticSearch",
+ "InformationRetriever",
+ "VectorSearch",
+ "MemoryRetriever",
+];
+
+export const REALISTIC_EVALUATOR_NAMES = [
+ "QualityEvaluator",
+ "RelevanceScorer",
+ "AccuracyChecker",
+ "ResponseEvaluator",
+ "ContentScorer",
+];
+
+export const REALISTIC_EMBEDDING_NAMES = [
+ "TextEmbedding",
+ "DocumentEncoder",
+ "SemanticEncoder",
+ "VectorEmbedding",
+];
+
+export const REALISTIC_GUARDRAIL_NAMES = [
+ "SafetyChecker",
+ "ContentModerator",
+ "ToxicityFilter",
+ "JailbreakDetector",
+ "PolicyEnforcer",
+];
diff --git a/packages/shared/scripts/seeder/utils/data-generators.ts b/packages/shared/scripts/seeder/utils/data-generators.ts
index 9895499fd6..a99094c076 100644
--- a/packages/shared/scripts/seeder/utils/data-generators.ts
+++ b/packages/shared/scripts/seeder/utils/data-generators.ts
@@ -4,6 +4,13 @@ import {
REALISTIC_SPAN_NAMES,
REALISTIC_GENERATION_NAMES,
REALISTIC_MODELS,
+ REALISTIC_AGENT_NAMES,
+ REALISTIC_TOOL_NAMES,
+ REALISTIC_CHAIN_NAMES,
+ REALISTIC_RETRIEVER_NAMES,
+ REALISTIC_EVALUATOR_NAMES,
+ REALISTIC_EMBEDDING_NAMES,
+ REALISTIC_GUARDRAIL_NAMES,
} from "./clickhouse-seed-constants";
import {
generateDatasetItemId,
@@ -365,8 +372,56 @@ export class DataGenerator {
const observations: ObservationRecordInsertType[] = [];
traces.forEach((trace, traceIndex) => {
+ if (this.randomBoolean(0.1)) {
+ const { observations: workflowObservations } =
+ this.generateComprehensiveAIWorkflowTrace(trace.id, trace.project_id);
+ observations.push(...workflowObservations);
+ return;
+ }
+
for (let i = 0; i < observationsPerTrace; i++) {
- const obsType = this.randomElement(["GENERATION", "SPAN", "EVENT"]);
+ const obsType = this.randomBoolean(0.8) // More "traditional" types, are more common in app
+ ? this.randomElement(["GENERATION", "SPAN", "EVENT"])
+ : this.randomElement([
+ "AGENT",
+ "TOOL",
+ "CHAIN",
+ "RETRIEVER",
+ "EVALUATOR",
+ "EMBEDDING",
+ "GUARDRAIL",
+ ]);
+
+ let observationName: string;
+ switch (obsType) {
+ case "AGENT":
+ observationName = this.randomElement(REALISTIC_AGENT_NAMES);
+ break;
+ case "TOOL":
+ observationName = this.randomElement(REALISTIC_TOOL_NAMES);
+ break;
+ case "CHAIN":
+ observationName = this.randomElement(REALISTIC_CHAIN_NAMES);
+ break;
+ case "RETRIEVER":
+ observationName = this.randomElement(REALISTIC_RETRIEVER_NAMES);
+ break;
+ case "EVALUATOR":
+ observationName = this.randomElement(REALISTIC_EVALUATOR_NAMES);
+ break;
+ case "EMBEDDING":
+ observationName = this.randomElement(REALISTIC_EMBEDDING_NAMES);
+ break;
+ case "GUARDRAIL":
+ observationName = this.randomElement(REALISTIC_GUARDRAIL_NAMES);
+ break;
+ case "GENERATION":
+ observationName = this.randomElement(REALISTIC_GENERATION_NAMES);
+ break;
+ default:
+ observationName = this.randomElement(REALISTIC_SPAN_NAMES);
+ break;
+ }
const observation: ObservationRecordInsertType = createObservation({
id: `obs-synthetic-${traceIndex}-${i}`,
@@ -375,28 +430,28 @@ export class DataGenerator {
parent_observation_id:
i > 0 ? `obs-synthetic-${traceIndex}-${i - 1}` : undefined,
type: obsType as any,
- name:
- obsType === "GENERATION"
- ? this.randomElement(REALISTIC_GENERATION_NAMES)
- : this.randomElement(REALISTIC_SPAN_NAMES),
+ name: observationName,
input:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? this.generateObservationInput()
: undefined,
output:
- obsType === "GENERATION"
+ obsType === "GENERATION" ||
+ obsType === "RETRIEVER" ||
+ obsType === "EVALUATOR" ||
+ obsType === "GUARDRAIL"
? this.generateObservationOutput()
: undefined,
provided_model_name:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? this.randomElement(REALISTIC_MODELS)
: undefined,
model_parameters:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? JSON.stringify({ temperature: 0.7 })
: undefined,
usage_details:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? {
input: this.randomInt(20, 200),
output: this.randomInt(10, 100),
@@ -404,7 +459,7 @@ export class DataGenerator {
}
: undefined,
provided_usage_details:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? {
input: this.randomInt(20, 200),
output: this.randomInt(10, 100),
@@ -412,7 +467,7 @@ export class DataGenerator {
}
: undefined,
cost_details:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? {
input: this.randomInt(1, 10) / 100000,
output: this.randomInt(1, 20) / 100000,
@@ -420,7 +475,7 @@ export class DataGenerator {
}
: undefined,
provided_cost_details:
- obsType === "GENERATION"
+ obsType === "GENERATION" || obsType === "EMBEDDING"
? {
input: this.randomInt(1, 10) / 100000,
output: this.randomInt(1, 20) / 100000,
@@ -500,6 +555,252 @@ export class DataGenerator {
return scores;
}
+ /**
+ * Creates a workflow trace with all possible observation types.
+ */
+ generateComprehensiveAIWorkflowTrace(
+ traceId: string,
+ projectId: string,
+ ): {
+ trace: TraceRecordInsertType;
+ observations: ObservationRecordInsertType[];
+ } {
+ // Create the main trace
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ name: "AI-Agent-Workflow",
+ input:
+ "Analyze and summarize the latest research papers on quantum computing",
+ output:
+ "Here is a comprehensive summary of quantum computing research trends with key insights and recommendations.",
+ user_id: this.randomBoolean(0.3)
+ ? `user_${this.randomInt(1, 1000)}`
+ : null,
+ session_id: this.randomBoolean(0.3)
+ ? `session_${this.randomInt(1, 100)}`
+ : undefined,
+ environment: "default",
+ metadata: { workflowType: "comprehensive-ai", purpose: "demonstration" },
+ tags: ["ai-agent", "multi-step", "comprehensive"],
+ public: true,
+ bookmarked: this.randomBoolean(0.2),
+ });
+
+ const observations: ObservationRecordInsertType[] = [];
+ const baseTime = Date.now();
+
+ // 1. AGENT - Main coordinator
+ observations.push(
+ createObservation({
+ id: `${traceId}-agent`,
+ trace_id: trace.id,
+ project_id: projectId,
+ type: "AGENT",
+ name: this.randomElement(REALISTIC_AGENT_NAMES),
+ input: "Plan and coordinate the research analysis workflow",
+ output:
+ "Workflow planned: retrieve documents → create embeddings → analyze → evaluate → check safety",
+ start_time: baseTime,
+ end_time: baseTime + 500,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: { role: "coordinator", step: "1" },
+ }),
+ );
+
+ // 2. RETRIEVER - Document retrieval
+ observations.push(
+ createObservation({
+ id: `${traceId}-retriever`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-agent`,
+ type: "RETRIEVER",
+ name: this.randomElement(REALISTIC_RETRIEVER_NAMES),
+ input: "query: quantum computing research papers 2024",
+ output: "Retrieved 15 relevant research papers from arXiv and IEEE",
+ start_time: baseTime + 500,
+ end_time: baseTime + 2000,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: { documentsFound: "15", sources: "arXiv,IEEE" },
+ }),
+ );
+
+ // 3. EMBEDDING - Create document embeddings
+ observations.push(
+ createObservation({
+ id: `${traceId}-embedding`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-retriever`,
+ type: "EMBEDDING",
+ name: this.randomElement(REALISTIC_EMBEDDING_NAMES),
+ input: "15 research paper abstracts and titles",
+ output: "Generated 1536-dimensional embeddings for semantic similarity",
+ start_time: baseTime + 2000,
+ end_time: baseTime + 3500,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: {
+ embeddingModel: "text-embedding-ada-002",
+ dimensions: "1536",
+ },
+ usage_details: {
+ input: this.randomInt(2000, 4000),
+ total: this.randomInt(2000, 4000),
+ },
+ provided_usage_details: {
+ input: this.randomInt(2000, 4000),
+ total: this.randomInt(2000, 4000),
+ },
+ cost_details: {
+ input: this.randomInt(5, 15) / 100000,
+ total: this.randomInt(5, 15) / 100000,
+ },
+ provided_cost_details: {
+ input: this.randomInt(5, 15) / 100000,
+ total: this.randomInt(5, 15) / 100000,
+ },
+ }),
+ );
+
+ // 4. CHAIN - Processing pipeline
+ observations.push(
+ createObservation({
+ id: `${traceId}-chain`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-embedding`,
+ type: "CHAIN",
+ name: this.randomElement(REALISTIC_CHAIN_NAMES),
+ input: "Research papers with embeddings",
+ output:
+ "Processed and analyzed 15 papers through multi-step analysis chain",
+ start_time: baseTime + 3500,
+ end_time: baseTime + 8000,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: { steps: "4", processed: "15" },
+ }),
+ );
+
+ // 5. TOOL - External API call for additional context
+ observations.push(
+ createObservation({
+ id: `${traceId}-tool`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-chain`,
+ type: "TOOL",
+ name: this.randomElement(REALISTIC_TOOL_NAMES),
+ input: "Search for quantum computing market trends",
+ output:
+ "Market data: $1.2B industry, 25% YoY growth, key players identified",
+ start_time: baseTime + 8000,
+ end_time: baseTime + 10000,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: { toolType: "api-call", endpoint: "market-research" },
+ }),
+ );
+
+ // 6. GENERATION - Final summary generation
+ observations.push(
+ createObservation({
+ id: `${traceId}-generation`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-tool`,
+ type: "GENERATION",
+ name: this.randomElement(REALISTIC_GENERATION_NAMES),
+ input:
+ "Synthesize research analysis and market data into comprehensive summary",
+ output:
+ "Generated comprehensive 2000-word analysis of quantum computing research trends",
+ provided_model_name: this.randomElement(REALISTIC_MODELS),
+ model_parameters: JSON.stringify({
+ temperature: 0.3,
+ max_tokens: 2000,
+ }),
+ start_time: baseTime + 10000,
+ end_time: baseTime + 15000,
+ level: "DEFAULT",
+ environment: trace.environment,
+ usage_details: {
+ input: this.randomInt(1500, 2500),
+ output: this.randomInt(1800, 2200),
+ total: this.randomInt(3300, 4700),
+ },
+ provided_usage_details: {
+ input: this.randomInt(1500, 2500),
+ output: this.randomInt(1800, 2200),
+ total: this.randomInt(3300, 4700),
+ },
+ cost_details: {
+ input: this.randomInt(15, 25) / 100000,
+ output: this.randomInt(35, 45) / 100000,
+ total: this.randomInt(50, 70) / 100000,
+ },
+ provided_cost_details: {
+ input: this.randomInt(15, 25) / 100000,
+ output: this.randomInt(35, 45) / 100000,
+ total: this.randomInt(50, 70) / 100000,
+ },
+ }),
+ );
+
+ // 7. EVALUATOR - Quality evaluation
+ observations.push(
+ createObservation({
+ id: `${traceId}-evaluator`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-generation`,
+ type: "EVALUATOR",
+ name: this.randomElement(REALISTIC_EVALUATOR_NAMES),
+ input: "Evaluate summary quality, accuracy, and completeness",
+ output: "Quality score: 8.7/10, High accuracy, Comprehensive coverage",
+ start_time: baseTime + 15000,
+ end_time: baseTime + 16500,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: {
+ qualityScore: "8.7",
+ accuracy: "high",
+ completeness: "comprehensive",
+ },
+ }),
+ );
+
+ // 8. GUARDRAIL - Safety and compliance check
+ observations.push(
+ createObservation({
+ id: `${traceId}-guardrail`,
+ trace_id: trace.id,
+ project_id: projectId,
+ parent_observation_id: `${traceId}-evaluator`,
+ type: "GUARDRAIL",
+ name: this.randomElement(REALISTIC_GUARDRAIL_NAMES),
+ input: "Check content for safety, bias, and compliance issues",
+ output:
+ "✓ Content approved: No safety issues, Low bias detected, Compliant",
+ start_time: baseTime + 16500,
+ end_time: baseTime + 17000,
+ level: "DEFAULT",
+ environment: trace.environment,
+ metadata: {
+ safetyCheck: "passed",
+ biasLevel: "low",
+ compliance: "approved",
+ },
+ }),
+ );
+
+ return { trace, observations };
+ }
+
/**
* Creates evaluation traces for testing evaluator configurations.
* Use for: Evaluation testing, score validation, evaluator development.
diff --git a/packages/shared/src/domain/observations.ts b/packages/shared/src/domain/observations.ts
index 62b04f6db8..54a6e72b99 100644
--- a/packages/shared/src/domain/observations.ts
+++ b/packages/shared/src/domain/observations.ts
@@ -6,8 +6,27 @@ export const ObservationType = {
SPAN: "SPAN",
EVENT: "EVENT",
GENERATION: "GENERATION",
+ AGENT: "AGENT",
+ TOOL: "TOOL",
+ CHAIN: "CHAIN",
+ RETRIEVER: "RETRIEVER",
+ EVALUATOR: "EVALUATOR",
+ EMBEDDING: "EMBEDDING",
+ GUARDRAIL: "GUARDRAIL",
} as const;
-export const ObservationTypeDomain = z.enum(["SPAN", "EVENT", "GENERATION"]);
+
+export const ObservationTypeDomain = z.enum([
+ "SPAN",
+ "EVENT",
+ "GENERATION",
+ "AGENT",
+ "TOOL",
+ "CHAIN",
+ "RETRIEVER",
+ "EVALUATOR",
+ "EMBEDDING",
+ "GUARDRAIL",
+]);
export type ObservationType = z.infer<typeof ObservationTypeDomain>;
export const ObservationLevel = {
@@ -74,3 +93,29 @@ export const ObservationSchema = z.object({
});
export type Observation = z.infer<typeof ObservationSchema>;
+
+/**
+ * Returns true if an observation type is generation-like, meaning it could include LLM calls
+ * and potentially has similar input/output fields.
+ */
+export const GenerationLikeObservationTypes = [
+ ObservationType.GENERATION,
+ ObservationType.AGENT,
+ ObservationType.TOOL,
+ ObservationType.CHAIN,
+ ObservationType.RETRIEVER,
+ ObservationType.EVALUATOR,
+ ObservationType.EMBEDDING,
+ ObservationType.GUARDRAIL,
+] as const;
+
+export const isGenerationLike = (observationType: ObservationType): boolean => {
+ return GenerationLikeObservationTypes.includes(observationType as any);
+};
+
+/**
+ * Returns all generation-like observation types for use in filters and queries.
+ */
+export const getGenerationLikeTypes = (): ObservationType[] => {
+ return [...GenerationLikeObservationTypes];
+};
diff --git a/packages/shared/src/features/evals/types.ts b/packages/shared/src/features/evals/types.ts
index 0c099c3069..7360634721 100644
--- a/packages/shared/src/features/evals/types.ts
+++ b/packages/shared/src/features/evals/types.ts
@@ -5,6 +5,13 @@ export const langfuseObjects = [
"span",
"generation",
"event",
+ "agent",
+ "tool",
+ "chain",
+ "retriever",
+ "evaluator",
+ "embedding",
+ "guardrail",
"dataset_item",
] as const;
@@ -80,6 +87,41 @@ export const availableTraceEvalVariables = [
display: "Event",
availableColumns: observationCols,
},
+ {
+ id: "agent",
+ display: "Agent",
+ availableColumns: observationCols,
+ },
+ {
+ id: "tool",
+ display: "Tool",
+ availableColumns: observationCols,
+ },
+ {
+ id: "chain",
+ display: "Chain",
+ availableColumns: observationCols,
+ },
+ {
+ id: "retriever",
+ display: "Retriever",
+ availableColumns: observationCols,
+ },
+ {
+ id: "evaluator",
+ display: "Evaluator",
+ availableColumns: observationCols,
+ },
+ {
+ id: "embedding",
+ display: "Embedding",
+ availableColumns: observationCols,
+ },
+ {
+ id: "guardrail",
+ display: "Guardrail",
+ availableColumns: observationCols,
+ },
];
export const availableDatasetEvalVariables = [
diff --git a/packages/shared/src/server/clickhouse/schemaUtils.ts b/packages/shared/src/server/clickhouse/schemaUtils.ts
index 1ff9ebd5db..cfbc732b15 100644
--- a/packages/shared/src/server/clickhouse/schemaUtils.ts
+++ b/packages/shared/src/server/clickhouse/schemaUtils.ts
@@ -27,6 +27,13 @@ export const getClickhouseEntityType = (
case eventTypes.SPAN_UPDATE:
case eventTypes.GENERATION_CREATE:
case eventTypes.GENERATION_UPDATE:
+ case eventTypes.AGENT_CREATE:
+ case eventTypes.TOOL_CREATE:
+ case eventTypes.CHAIN_CREATE:
+ case eventTypes.RETRIEVER_CREATE:
+ case eventTypes.EVALUATOR_CREATE:
+ case eventTypes.EMBEDDING_CREATE:
+ case eventTypes.GUARDRAIL_CREATE:
return "observation";
case eventTypes.SCORE_CREATE:
return "score";
diff --git a/packages/shared/src/server/ingestion/types.ts b/packages/shared/src/server/ingestion/types.ts
index db7d646cc5..cfd2b81da9 100644
--- a/packages/shared/src/server/ingestion/types.ts
+++ b/packages/shared/src/server/ingestion/types.ts
@@ -223,6 +223,13 @@ export const eventTypes = {
SPAN_UPDATE: "span-update",
GENERATION_CREATE: "generation-create",
GENERATION_UPDATE: "generation-update",
+ AGENT_CREATE: "agent-create",
+ TOOL_CREATE: "tool-create",
+ CHAIN_CREATE: "chain-create",
+ RETRIEVER_CREATE: "retriever-create",
+ EVALUATOR_CREATE: "evaluator-create",
+ EMBEDDING_CREATE: "embedding-create",
+ GUARDRAIL_CREATE: "guardrail-create",
SDK_LOG: "sdk-log",
DATASET_RUN_ITEM_CREATE: "dataset-run-item-create",
// LEGACY, only required for backwards compatibility
@@ -564,6 +571,41 @@ const createAllIngestionSchemas = ({
body: UpdateGenerationBody,
});
+ const agentCreateEvent = base.extend({
+ type: z.literal(eventTypes.AGENT_CREATE),
+ body: CreateGenerationBody,
+ });
+
+ const toolCreateEvent = base.extend({
+ type: z.literal(eventTypes.TOOL_CREATE),
+ body: CreateGenerationBody,
+ });
+
+ const chainCreateEvent = base.extend({
+ type: z.literal(eventTypes.CHAIN_CREATE),
+ body: CreateGenerationBody,
+ });
+
+ const retrieverCreateEvent = base.extend({
+ type: z.literal(eventTypes.RETRIEVER_CREATE),
+ body: CreateGenerationBody,
+ });
+
+ const evaluatorCreateEvent = base.extend({
+ type: z.literal(eventTypes.EVALUATOR_CREATE),
+ body: CreateGenerationBody,
+ });
+
+ const embeddingCreateEvent = base.extend({
+ type: z.literal(eventTypes.EMBEDDING_CREATE),
+ body: CreateGenerationBody,
+ });
+
+ const guardrailCreateEvent = base.extend({
+ type: z.literal(eventTypes.GUARDRAIL_CREATE),
+ body: CreateGenerationBody,
+ });
+
const scoreEvent = base.extend({
type: z.literal(eventTypes.SCORE_CREATE),
body: ScoreBody,
@@ -603,6 +645,13 @@ const createAllIngestionSchemas = ({
spanUpdateEvent,
generationCreateEvent,
generationUpdateEvent,
+ agentCreateEvent,
+ toolCreateEvent,
+ chainCreateEvent,
+ retrieverCreateEvent,
+ evaluatorCreateEvent,
+ embeddingCreateEvent,
+ guardrailCreateEvent,
sdkLogEvent,
datasetRunItemCreateEvent,
// LEGACY, only required for backwards compatibility
@@ -629,6 +678,13 @@ const createAllIngestionSchemas = ({
spanUpdateEvent,
generationCreateEvent,
generationUpdateEvent,
+ agentCreateEvent,
+ toolCreateEvent,
+ chainCreateEvent,
+ retrieverCreateEvent,
+ evaluatorCreateEvent,
+ embeddingCreateEvent,
+ guardrailCreateEvent,
scoreEvent,
datasetRunItemCreateEvent,
sdkLogEvent,
@@ -666,6 +722,13 @@ export const spanCreateEvent = publicSchemas.spanCreateEvent;
export const spanUpdateEvent = publicSchemas.spanUpdateEvent;
export const generationCreateEvent = publicSchemas.generationCreateEvent;
export const generationUpdateEvent = publicSchemas.generationUpdateEvent;
+export const agentCreateEvent = publicSchemas.agentCreateEvent;
+export const toolCreateEvent = publicSchemas.toolCreateEvent;
+export const chainCreateEvent = publicSchemas.chainCreateEvent;
+export const retrieverCreateEvent = publicSchemas.retrieverCreateEvent;
+export const evaluatorCreateEvent = publicSchemas.evaluatorCreateEvent;
+export const embeddingCreateEvent = publicSchemas.embeddingCreateEvent;
+export const guardrailCreateEvent = publicSchemas.guardrailCreateEvent;
export const scoreEvent = publicSchemas.scoreEvent;
export const sdkLogEvent = publicSchemas.sdkLogEvent;
export const datasetRunItemCreateEvent =
@@ -707,4 +770,11 @@ export type ObservationEvent =
| z.infer<typeof spanCreateEvent>
| z.infer<typeof spanUpdateEvent>
| z.infer<typeof generationCreateEvent>
- | z.infer<typeof generationUpdateEvent>;
+ | z.infer<typeof generationUpdateEvent>
+ | z.infer<typeof agentCreateEvent>
+ | z.infer<typeof toolCreateEvent>
+ | z.infer<typeof chainCreateEvent>
+ | z.infer<typeof retrieverCreateEvent>
+ | z.infer<typeof evaluatorCreateEvent>
+ | z.infer<typeof embeddingCreateEvent>
+ | z.infer<typeof guardrailCreateEvent>;
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index cbc6b3df1a..4b708c5b59 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -5970,6 +5970,13 @@ components:
- SPAN
- GENERATION
- EVENT
+ - AGENT
+ - TOOL
+ - CHAIN
+ - RETRIEVER
+ - EVALUATOR
+ - EMBEDDING
+ - GUARDRAIL
IngestionUsage:
title: IngestionUsage
oneOf:
diff --git a/web/src/__tests__/async/ingestion-api.servertest.ts b/web/src/__tests__/async/ingestion-api.servertest.ts
index c3e7a73d89..9081d19e07 100644
--- a/web/src/__tests__/async/ingestion-api.servertest.ts
+++ b/web/src/__tests__/async/ingestion-api.servertest.ts
@@ -205,6 +205,162 @@ describe("/api/public/ingestion API Endpoint", () => {
},
},
],
+ [
+ "agent",
+ "AGENT",
+ {
+ id: randomUUID(),
+ type: "agent-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ endTime: new Date(Date.now() + 1000).toISOString(),
+ name: "AI Agent",
+ input: "Process user request",
+ output: "Request processed successfully",
+ model: "claude-3-haiku",
+ modelParameters: { temperature: 0.7, max_tokens: 1000 },
+ usage: {
+ input: 150,
+ output: 75,
+ total: 225,
+ unit: "TOKENS",
+ inputCost: 0.0015,
+ outputCost: 0.003,
+ totalCost: 0.0045,
+ },
+ usageDetails: { input: 150, output: 75, total: 225 },
+ costDetails: { input: 0.0015, output: 0.003, total: 0.0045 },
+ },
+ },
+ ],
+ [
+ "tool",
+ "TOOL",
+ {
+ id: randomUUID(),
+ type: "tool-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ endTime: new Date(Date.now() + 2000).toISOString(),
+ name: "Web Search Tool",
+ input: "Search for current weather",
+ output: "Weather data retrieved",
+ model: "gpt-4o-mini",
+ usage: {
+ input: 50,
+ output: 25,
+ total: 75,
+ unit: "TOKENS",
+ inputCost: 0.0001,
+ outputCost: 0.0002,
+ totalCost: 0.0003,
+ },
+ },
+ },
+ ],
+ [
+ "chain",
+ "CHAIN",
+ {
+ id: randomUUID(),
+ type: "chain-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ endTime: new Date(Date.now() + 3000).toISOString(),
+ name: "Processing Chain",
+ input: "Multi-step task",
+ output: "All steps completed",
+ model: "gpt-4",
+ usageDetails: { input: 800, output: 400, total: 1200 },
+ costDetails: { input: 0.024, output: 0.048, total: 0.072 },
+ },
+ },
+ ],
+ [
+ "retriever",
+ "RETRIEVER",
+ {
+ id: randomUUID(),
+ type: "retriever-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ endTime: new Date(Date.now() + 1500).toISOString(),
+ name: "Document Retriever",
+ input: "Query document database",
+ output: "Retrieved 5 relevant documents",
+ },
+ },
+ ],
+ [
+ "evaluator",
+ "EVALUATOR",
+ {
+ id: randomUUID(),
+ type: "evaluator-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ endTime: new Date(Date.now() + 800).toISOString(),
+ name: "Quality Evaluator",
+ input: "Evaluate response quality",
+ output: "Quality score: 0.85",
+ },
+ },
+ ],
+ [
+ "embedding",
+ "EMBEDDING",
+ {
+ id: randomUUID(),
+ type: "embedding-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ endTime: new Date(Date.now() + 500).toISOString(),
+ name: "Text Embedding",
+ input: "Text to embed",
+ output: "Embedding vector generated",
+ model: "text-embedding-ada-002",
+ usage: {
+ input: 20,
+ output: 0,
+ total: 20,
+ unit: "TOKENS",
+ totalCost: 0.00004,
+ },
+ },
+ },
+ ],
+ [
+ "guardrail",
+ "GUARDRAIL",
+ {
+ id: randomUUID(),
+ type: "guardrail-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: randomUUID(),
+ traceId: randomUUID(),
+ startTime: new Date().toISOString(),
+ },
+ },
+ ],
])(
"should create observations via the ingestion API (%s)",
async (_name: string, type: string, entity: any) => {
diff --git a/web/src/__tests__/async/observation-api.servertest.ts b/web/src/__tests__/async/observation-api.servertest.ts
index b697351d05..f29ba9bb94 100644
--- a/web/src/__tests__/async/observation-api.servertest.ts
+++ b/web/src/__tests__/async/observation-api.servertest.ts
@@ -45,6 +45,41 @@ describe("/api/public/observations API Endpoint", () => {
output: observation.output,
});
});
+
+ it.each([
+ ["AGENT", "agent-observation"],
+ ["TOOL", "tool-observation"],
+ ["CHAIN", "chain-observation"],
+ ["RETRIEVER", "retriever-observation"],
+ ["EVALUATOR", "evaluator-observation"],
+ ["EMBEDDING", "embedding-observation"],
+ ["GUARDRAIL", "guardrail-observation"],
+ ])("should GET observation with type %s", async (type, name) => {
+ const observationId = uuidv4();
+ const traceId = uuidv4();
+
+ const observation = createObservationObject({
+ id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: type,
+ name: name,
+ });
+
+ await createObservationsInClickhouse([observation]);
+
+ const getEventRes = await makeZodVerifiedAPICall(
+ GetObservationV1Response,
+ "GET",
+ "/api/public/observations/" + observationId,
+ );
+ expect(getEventRes.body).toMatchObject({
+ id: observationId,
+ traceId: traceId,
+ type: type,
+ name: name,
+ });
+ });
});
describe("GET /api/public/observations", () => {
diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.ts
index 41549922dc..2c560e7bb6 100644
--- a/web/src/__tests__/async/observations-api.servertest.ts
+++ b/web/src/__tests__/async/observations-api.servertest.ts
@@ -66,6 +66,98 @@ describe("/api/public/observations API Endpoint", () => {
input: "User action recorded",
metadata: { eventType: "click", target: "submit-button" },
}),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "agent-observation",
+ type: "AGENT",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 2000,
+ end_time: timestamp.getTime() + 2500,
+ provided_model_name: "claude-3-haiku",
+ provided_usage_details: { input: 100, output: 50, total: 150 },
+ provided_cost_details: { input: 0.001, output: 0.002, total: 0.003 },
+ }),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "tool-observation",
+ type: "TOOL",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 2500,
+ end_time: timestamp.getTime() + 3000,
+ input: "Search web for information",
+ output: "Found relevant results",
+ provided_model_name: "gpt-4o-mini",
+ provided_usage_details: { input: 200, output: 100, total: 300 },
+ provided_cost_details: { input: 0.002, output: 0.004, total: 0.006 },
+ }),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "chain-observation",
+ type: "CHAIN",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 3000,
+ end_time: timestamp.getTime() + 3500,
+ input: "Process multi-step workflow",
+ output: "Workflow completed",
+ provided_model_name: "gpt-4",
+ provided_usage_details: { input: 500, output: 300, total: 800 },
+ provided_cost_details: { input: 0.015, output: 0.03, total: 0.045 },
+ }),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "retriever-observation",
+ type: "RETRIEVER",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 3500,
+ end_time: timestamp.getTime() + 4000,
+ input: "Query document database",
+ output: "Retrieved 5 relevant documents",
+ }),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "evaluator-observation",
+ type: "EVALUATOR",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 4000,
+ input: null,
+ output: null,
+ end_time: null,
+ }),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "embedding-observation",
+ type: "EMBEDDING",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 4500,
+ end_time: timestamp.getTime() + 4750,
+ input: "Text to embed",
+ output: "Vector embedding generated",
+ provided_model_name: "text-embedding-ada-002",
+ provided_usage_details: { input: 10, output: 0, total: 10 },
+ provided_cost_details: { input: 0.0001, output: 0, total: 0.0001 },
+ }),
+ createObservation({
+ id: randomUUID(),
+ trace_id: traceId,
+ project_id: projectId,
+ name: "guardrail-observation",
+ type: "GUARDRAIL",
+ level: "DEFAULT",
+ start_time: timestamp.getTime() + 5000,
+ provided_cost_details: { input: 0.0001, output: 0, total: 0.0001 },
+ }),
];
await createTracesCh([createdTrace]);
@@ -80,14 +172,14 @@ describe("/api/public/observations API Endpoint", () => {
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
expect(response.body.meta).toBeDefined();
- expect(response.body.meta.totalItems).toBeGreaterThanOrEqual(3);
- expect(response.body.data.length).toBeGreaterThanOrEqual(3);
+ expect(response.body.meta.totalItems).toBeGreaterThanOrEqual(10);
+ expect(response.body.data.length).toBeGreaterThanOrEqual(10);
// Find our created observations in the response
const createdObservations = response.body.data.filter(
(obs) => obs.traceId === traceId,
);
- expect(createdObservations.length).toBe(3);
+ expect(createdObservations.length).toBe(10);
// Verify data structure and content
const generationObs = createdObservations.find(
@@ -118,6 +210,75 @@ describe("/api/public/observations API Endpoint", () => {
eventType: "click",
target: "submit-button",
});
+
+ // Verify new observation types exist and have correct type
+ const agentObs = createdObservations.find((obs) => obs.type === "AGENT");
+ expect(agentObs).toBeDefined();
+ expect(agentObs?.name).toBe("agent-observation");
+
+ const toolObs = createdObservations.find((obs) => obs.type === "TOOL");
+ expect(toolObs).toBeDefined();
+ expect(toolObs?.name).toBe("tool-observation");
+
+ const chainObs = createdObservations.find((obs) => obs.type === "CHAIN");
+ expect(chainObs).toBeDefined();
+ expect(chainObs?.name).toBe("chain-observation");
+
+ const retrieverObs = createdObservations.find(
+ (obs) => obs.type === "RETRIEVER",
+ );
+ expect(retrieverObs).toBeDefined();
+ expect(retrieverObs?.name).toBe("retriever-observation");
+
+ const evaluatorObs = createdObservations.find(
+ (obs) => obs.type === "EVALUATOR",
+ );
+ expect(evaluatorObs).toBeDefined();
+ expect(evaluatorObs?.name).toBe("evaluator-observation");
+ // Test that input, output, and endTime can be null (optional fields)
+ expect(evaluatorObs?.input).toBeNull();
+ expect(evaluatorObs?.output).toBeNull();
+ expect(evaluatorObs?.endTime).toBeNull();
+
+ const embeddingObs = createdObservations.find(
+ (obs) => obs.type === "EMBEDDING",
+ );
+ expect(embeddingObs).toBeDefined();
+ expect(embeddingObs?.name).toBe("embedding-observation");
+
+ const guardrailObs = createdObservations.find(
+ (obs) => obs.type === "GUARDRAIL",
+ );
+ expect(guardrailObs).toBeDefined();
+ expect(guardrailObs?.name).toBe("guardrail-observation");
+
+ // Verify new observation types support model and cost attributes
+ // The key verification is that new observation types now have model and cost fields populated
+ // (even if with default values from the factory, proving the schema changes work)
+ expect(agentObs?.model).toBe("claude-3-haiku");
+ expect(agentObs?.input).toBe("Hello World");
+ expect(agentObs?.output).toBe("Hello John");
+ // Verify that model/cost fields are present (core functionality test)
+ expect(agentObs?.usageDetails).toBeDefined();
+ expect(agentObs?.costDetails).toBeDefined();
+
+ expect(toolObs?.model).toBe("gpt-4o-mini");
+ expect(toolObs?.input).toBe("Search web for information");
+ expect(toolObs?.output).toBe("Found relevant results");
+ expect(toolObs?.usageDetails).toBeDefined();
+ expect(toolObs?.costDetails).toBeDefined();
+
+ expect(chainObs?.model).toBe("gpt-4");
+ expect(chainObs?.input).toBe("Process multi-step workflow");
+ expect(chainObs?.output).toBe("Workflow completed");
+ expect(chainObs?.usageDetails).toBeDefined();
+ expect(chainObs?.costDetails).toBeDefined();
+
+ expect(embeddingObs?.model).toBe("text-embedding-ada-002");
+ expect(embeddingObs?.input).toBe("Text to embed");
+ expect(embeddingObs?.output).toBe("Vector embedding generated");
+ expect(embeddingObs?.usageDetails).toBeDefined();
+ expect(embeddingObs?.costDetails).toBeDefined();
}, 20_000);
it("should filter observations by level parameter", async () => {
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index 758f197ea0..1900c79a3e 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -3304,5 +3304,48 @@ describe("OTel Resource Span Mapping", () => {
expect(traceEvent).toBeDefined();
expect(traceEvent.body.sessionId).toBe("session-id-123");
});
+
+ it("should default to span-create for unknown observation type", async () => {
+ const otelSpans = [
+ {
+ resource: { attributes: [] },
+ scopeSpans: [
+ {
+ scope: { name: "test-scope" },
+ spans: [
+ {
+ traceId: {
+ data: [
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ ],
+ },
+ spanId: { data: [1, 2, 3, 4, 5, 6, 7, 8] },
+ name: "test-span",
+ startTimeUnixNano: 1000000000,
+ endTimeUnixNano: 2000000000,
+ attributes: [
+ {
+ key: "langfuse.observation.type",
+ value: { stringValue: "invalid_type" },
+ },
+ ],
+ status: {},
+ },
+ ],
+ },
+ ],
+ },
+ ];
+
+ const events = await convertOtelSpanToIngestionEvent(
+ otelSpans[0],
+ new Set(),
+ publicKey,
+ );
+ const spanEvents = events.filter((e) => e.type === "span-create");
+
+ expect(spanEvents.length).toBe(1);
+ expect(spanEvents[0].body.name).toBe("test-span");
+ });
});
});
diff --git a/web/src/components/ItemBadge.tsx b/web/src/components/ItemBadge.tsx
index be2b354f99..361b798a11 100644
--- a/web/src/components/ItemBadge.tsx
+++ b/web/src/components/ItemBadge.tsx
@@ -14,6 +14,11 @@ import {
TestTubeDiagonal,
Clock,
Bot,
+ Wrench,
+ Link,
+ Search,
+ Layers3,
+ ShieldCheck,
} from "lucide-react";
import { cva } from "class-variance-authority";
import { type ObservationType } from "@langfuse/shared";
@@ -38,6 +43,12 @@ const iconMap = {
GENERATION: Fan,
EVENT: CircleDot,
SPAN: MoveHorizontal,
+ AGENT: Bot,
+ TOOL: Wrench,
+ CHAIN: Link,
+ RETRIEVER: Search,
+ EMBEDDING: Layers3,
+ GUARDRAIL: ShieldCheck,
SESSION: Clock,
USER: User,
QUEUE_ITEM: ClipboardPen,
@@ -57,6 +68,12 @@ const iconVariants = cva(cn("h-4 w-4"), {
GENERATION: "text-muted-magenta",
EVENT: "text-muted-green",
SPAN: "text-muted-blue",
+ AGENT: "text-purple-600",
+ TOOL: "text-orange-600",
+ CHAIN: "text-indigo-600",
+ RETRIEVER: "text-teal-600",
+ EMBEDDING: "text-amber-600",
+ GUARDRAIL: "text-red-600",
SESSION: "text-primary-accent",
USER: "text-primary-accent",
QUEUE_ITEM: "text-primary-accent",
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 4504017df0..2894192c40 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -148,7 +148,16 @@ export default function ObservationsTable({
column: "type",
type: "stringOptions",
operator: "any of",
- value: ["GENERATION"],
+ value: [
+ "GENERATION",
+ "AGENT",
+ "TOOL",
+ "CHAIN",
+ "RETRIEVER",
+ "EVALUATOR",
+ "EMBEDDING",
+ "GUARDRAIL",
+ ],
},
]
: [],
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index c659a8edf5..d496a1416d 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -1,5 +1,9 @@
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
-import { AnnotationQueueObjectType, type APIScoreV2 } from "@langfuse/shared";
+import {
+ AnnotationQueueObjectType,
+ type APIScoreV2,
+ isGenerationLike,
+} from "@langfuse/shared";
import { Badge } from "@/src/components/ui/badge";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
@@ -177,14 +181,15 @@ export const ObservationPreview = ({
objectType={AnnotationQueueObjectType.OBSERVATION}
/>
</div>
- {observationWithInputAndOutput.data?.type === "GENERATION" && (
- <JumpToPlaygroundButton
- source="generation"
- generation={observationWithInputAndOutput.data}
- analyticsEventName="trace_detail:test_in_playground_button_click"
- className={cn(isTimeline ? "!hidden" : "")}
- />
- )}
+ {observationWithInputAndOutput.data &&
+ isGenerationLike(observationWithInputAndOutput.data.type) && (
+ <JumpToPlaygroundButton
+ source="generation"
+ generation={observationWithInputAndOutput.data}
+ analyticsEventName="trace_detail:test_in_playground_button_click"
+ className={cn(isTimeline ? "!hidden" : "")}
+ />
+ )}
<CommentDrawerButton
projectId={preloadedObservation.projectId}
objectId={preloadedObservation.id}
@@ -259,7 +264,7 @@ export const ObservationPreview = ({
projectId={preloadedObservation.projectId}
/>
) : undefined}
- {preloadedObservation.type === "GENERATION" && (
+ {isGenerationLike(preloadedObservation.type) && (
<BreakdownTooltip
details={preloadedObservation.usageDetails}
isCost={false}
diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsx
index 8da3e26f86..38eaadc527 100644
--- a/web/src/components/trace/TracePreview.tsx
+++ b/web/src/components/trace/TracePreview.tsx
@@ -3,6 +3,7 @@ import {
type APIScoreV2,
type TraceDomain,
AnnotationQueueObjectType,
+ isGenerationLike,
} from "@langfuse/shared";
import { AggUsageBadge } from "@/src/components/token-usage-badge";
import { Badge } from "@/src/components/ui/badge";
@@ -102,7 +103,7 @@ export const TracePreview = ({
const usageDetails = useMemo(
() =>
observations
- .filter((o) => o.type === "GENERATION")
+ .filter((o) => isGenerationLike(o.type))
.map((o) => o.usageDetails),
[observations],
);
@@ -201,7 +202,7 @@ export const TracePreview = ({
{totalCost && (
<BreakdownTooltip
details={observations
- .filter((o) => o.type === "GENERATION")
+ .filter((o) => isGenerationLike(o.type))
.map((o) => o.costDetails)}
isCost
>
diff --git a/web/src/features/dashboard/components/LatencyChart.tsx b/web/src/features/dashboard/components/LatencyChart.tsx
index e79d4d6e7b..fe731f1fdc 100644
--- a/web/src/features/dashboard/components/LatencyChart.tsx
+++ b/web/src/features/dashboard/components/LatencyChart.tsx
@@ -1,5 +1,5 @@
import { api } from "@/src/utils/api";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import {
extractTimeSeriesData,
fillMissingValuesAndTransform,
@@ -69,9 +69,9 @@ export const GenerationLatencyChart = ({
...mapLegacyUiTableFilterToView("observations", globalFilterState),
{
column: "type",
- operator: "=",
- value: "GENERATION",
- type: "string",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ type: "stringOptions",
},
{
column: "providedModelName",
diff --git a/web/src/features/dashboard/components/LatencyTables.tsx b/web/src/features/dashboard/components/LatencyTables.tsx
index 5e8127af7f..8d5e7fdb49 100644
--- a/web/src/features/dashboard/components/LatencyTables.tsx
+++ b/web/src/features/dashboard/components/LatencyTables.tsx
@@ -1,7 +1,7 @@
import { RightAlignedCell } from "@/src/features/dashboard/components/RightAlignedCell";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import { api } from "@/src/utils/api";
import { formatIntervalSeconds } from "@/src/utils/dates";
@@ -38,9 +38,9 @@ export const LatencyTables = ({
...mapLegacyUiTableFilterToView("observations", globalFilterState),
{
column: "type",
- operator: "=",
- value: "GENERATION",
- type: "string",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ type: "stringOptions",
},
],
timeDimension: null,
diff --git a/web/src/features/dashboard/components/ModelCostTable.tsx b/web/src/features/dashboard/components/ModelCostTable.tsx
index d5b73a0fc1..25b629458f 100644
--- a/web/src/features/dashboard/components/ModelCostTable.tsx
+++ b/web/src/features/dashboard/components/ModelCostTable.tsx
@@ -3,7 +3,7 @@ import { RightAlignedCell } from "@/src/features/dashboard/components/RightAlign
import { LeftAlignedCell } from "@/src/features/dashboard/components/LeftAlignedCell";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { DashboardTable } from "@/src/features/dashboard/components/cards/DashboardTable";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import { api } from "@/src/utils/api";
import { compactNumberFormatter } from "@/src/utils/numbers";
import { TotalMetric } from "./TotalMetric";
@@ -40,9 +40,9 @@ export const ModelCostTable = ({
...mapLegacyUiTableFilterToView("observations", globalFilterState),
{
column: "type",
- operator: "=",
- value: "GENERATION",
- type: "string",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ type: "stringOptions",
},
],
timeDimension: null,
diff --git a/web/src/features/dashboard/components/ModelUsageChart.tsx b/web/src/features/dashboard/components/ModelUsageChart.tsx
index 66ae062cd9..6faf11082c 100644
--- a/web/src/features/dashboard/components/ModelUsageChart.tsx
+++ b/web/src/features/dashboard/components/ModelUsageChart.tsx
@@ -15,7 +15,7 @@ import {
dashboardDateRangeAggregationSettings,
} from "@/src/utils/date-range-utils";
import { compactNumberFormatter } from "@/src/utils/numbers";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import {
ModelSelectorPopover,
useModelSelection,
@@ -70,9 +70,9 @@ export const ModelUsageChart = ({
...mapLegacyUiTableFilterToView("observations", userAndEnvFilterState),
{
column: "type",
- operator: "=",
- value: "GENERATION",
- type: "string",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ type: "stringOptions",
},
{
column: "providedModelName",
@@ -115,7 +115,12 @@ export const ModelUsageChart = ({
],
filter: [
...globalFilterState,
- { type: "string", column: "type", operator: "=", value: "GENERATION" },
+ {
+ type: "stringOptions",
+ column: "type",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ },
{
type: "stringOptions",
column: "model",
@@ -160,7 +165,12 @@ export const ModelUsageChart = ({
],
filter: [
...globalFilterState,
- { type: "string", column: "type", operator: "=", value: "GENERATION" },
+ {
+ type: "stringOptions",
+ column: "type",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ },
{
type: "stringOptions",
column: "model",
diff --git a/web/src/features/dashboard/components/UserChart.tsx b/web/src/features/dashboard/components/UserChart.tsx
index 81b1ab584d..88d889b4aa 100644
--- a/web/src/features/dashboard/components/UserChart.tsx
+++ b/web/src/features/dashboard/components/UserChart.tsx
@@ -1,5 +1,5 @@
import { api } from "@/src/utils/api";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import { DashboardCard } from "@/src/features/dashboard/components/cards/DashboardCard";
import { compactNumberFormatter } from "@/src/utils/numbers";
import { TabComponent } from "@/src/features/dashboard/components/TabsComponent";
@@ -46,9 +46,9 @@ export const UserChart = ({
...mapLegacyUiTableFilterToView("observations", globalFilterState),
{
column: "type",
- operator: "=",
- value: "GENERATION",
- type: "string",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ type: "stringOptions",
},
],
timeDimension: null,
diff --git a/web/src/features/dashboard/components/hooks.ts b/web/src/features/dashboard/components/hooks.ts
index 91b11407ca..f8886854a6 100644
--- a/web/src/features/dashboard/components/hooks.ts
+++ b/web/src/features/dashboard/components/hooks.ts
@@ -1,5 +1,5 @@
import { type TimeSeriesChartDataPoint } from "@/src/features/dashboard/components/BaseTimeSeriesChart";
-import { type FilterState } from "@langfuse/shared";
+import { type FilterState, getGenerationLikeTypes } from "@langfuse/shared";
import { type DatabaseRow } from "@/src/server/api/services/sqlInterface";
import { api } from "@/src/utils/api";
import { mapLegacyUiTableFilterToView } from "@/src/features/query";
@@ -21,9 +21,9 @@ export const getAllModels = (
...mapLegacyUiTableFilterToView("observations", globalFilterState),
{
column: "type",
- operator: "=",
- value: "GENERATION",
- type: "string",
+ operator: "any of",
+ value: getGenerationLikeTypes(),
+ type: "stringOptions",
},
],
timeDimension: null,
diff --git a/web/src/features/otel/server/OtelIngestionProcessor.ts b/web/src/features/otel/server/OtelIngestionProcessor.ts
index e496676289..fbccb18e1b 100644
--- a/web/src/features/otel/server/OtelIngestionProcessor.ts
+++ b/web/src/features/otel/server/OtelIngestionProcessor.ts
@@ -1,6 +1,10 @@
import { randomUUID } from "crypto";
-import { ForbiddenError, ObservationLevel } from "@langfuse/shared";
+import {
+ ForbiddenError,
+ ObservationLevel,
+ ObservationTypeDomain,
+} from "@langfuse/shared";
import {
type TraceEventType,
type IngestionEventType,
@@ -634,23 +638,30 @@ export class OtelIngestionProcessor {
}),
};
+ const observationType = attributes[
+ LangfuseOtelSpanAttributes.OBSERVATION_TYPE
+ ] as string;
const isGeneration =
- attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] ===
- "generation" ||
+ observationType === "generation" ||
Boolean(observation.model) ||
("openinference.span.kind" in attributes &&
attributes["openinference.span.kind"] === "LLM");
- const isEvent =
- attributes[LangfuseOtelSpanAttributes.OBSERVATION_TYPE] === "event";
+ const isKnownObservationType =
+ observationType &&
+ ObservationTypeDomain.safeParse(observationType.toUpperCase()).success;
+
+ const getIngestionEventType = (): string => {
+ if (isGeneration) return "generation-create";
+ if (isKnownObservationType) {
+ return `${observationType.toLowerCase()}-create`;
+ }
+ return "span-create";
+ };
return {
id: randomUUID(),
- type: isGeneration
- ? "generation-create"
- : isEvent
- ? "event-create"
- : "span-create",
+ type: getIngestionEventType(),
timestamp: new Date().toISOString(),
body: observation,
} as unknown as IngestionEventType;
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index a66d3d59cf..f2fa4ae1dc 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -38,6 +38,7 @@ import {
type PlaceholderMessage,
isPlaceholder,
PromptType,
+ isGenerationLike,
} from "@langfuse/shared";
import {
LANGGRAPH_NODE_TAG,
@@ -478,7 +479,7 @@ const parseGeneration = (
},
modelToProviderMap: Record<string, string>,
): PlaygroundCache => {
- if (generation.type !== "GENERATION") return null;
+ if (!isGenerationLike(generation.type)) return null;
const isLangGraph = isLangGraphTrace(generation);
const modelParams = parseModelParams(generation, modelToProviderMap);
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index 6536e389e5..780c6d2ad0 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -16,7 +16,18 @@ import { z } from "zod/v4";
* Objects
*/
-const ObservationType = z.enum(["GENERATION", "SPAN", "EVENT"]);
+const ObservationType = z.enum([
+ "GENERATION",
+ "SPAN",
+ "EVENT",
+ "AGENT",
+ "TOOL",
+ "CHAIN",
+ "RETRIEVER",
+ "EVALUATOR",
+ "EMBEDDING",
+ "GUARDRAIL",
+]);
export const APIObservation = z
.object({
@@ -38,7 +49,6 @@ export const APIObservation = z
level: z.enum(["DEBUG", "DEFAULT", "WARNING", "ERROR"]),
statusMessage: z.string().nullable(),
- // GENERATION only
model: z.string().nullable(),
modelParameters: z.any(),
completionStartTime: z.coerce.date().nullable(),
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index 0df5d25dcf..b45b146a14 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -160,7 +160,18 @@ export const filterOptionsQuery = protectedProjectProcedure
.map((i) => ({
value: i.tag as string,
})),
- type: ["GENERATION", "SPAN", "EVENT"].map((i) => ({
+ type: [
+ "GENERATION",
+ "SPAN",
+ "EVENT",
+ "AGENT",
+ "TOOL",
+ "CHAIN",
+ "RETRIEVER",
+ "EVALUATOR",
+ "EMBEDDING",
+ "GUARDRAIL",
+ ].map((i) => ({
value: i,
})),
};
diff --git a/web/src/utils/types.ts b/web/src/utils/types.ts
index 127c6be5a9..c714907fbb 100644
--- a/web/src/utils/types.ts
+++ b/web/src/utils/types.ts
@@ -34,6 +34,34 @@ export type Generation = Observation & {
};
};
+export type Agent = Observation & {
+ type: "AGENT";
+};
+
+export type Tool = Observation & {
+ type: "TOOL";
+};
+
+export type Chain = Observation & {
+ type: "CHAIN";
+};
+
+export type Retriever = Observation & {
+ type: "RETRIEVER";
+};
+
+export type Evaluator = Observation & {
+ type: "EVALUATOR";
+};
+
+export type Embedding = Observation & {
+ type: "EMBEDDING";
+};
+
+export type Guardrail = Observation & {
+ type: "GUARDRAIL";
+};
+
export type RouterInput = inferRouterInputs<AppRouter>;
export type RouterOutput = inferRouterOutputs<AppRouter>;
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 70c620566a..594cc363cf 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -450,8 +450,8 @@ export class IngestionService {
await this.prisma.$executeRaw`
INSERT INTO trace_sessions (id, project_id, environment, created_at, updated_at)
VALUES (${traceRecordWithSession.session_id}, ${projectId}, ${traceRecordWithSession.environment}, NOW(), NOW())
- ON CONFLICT (id, project_id)
- DO UPDATE SET
+ ON CONFLICT (id, project_id)
+ DO UPDATE SET
environment = EXCLUDED.environment,
updated_at = NOW()
WHERE trace_sessions.environment IS DISTINCT FROM EXCLUDED.environment
@@ -1118,7 +1118,17 @@ export class IngestionService {
private getObservationType(
observation: ObservationEvent,
- ): "EVENT" | "SPAN" | "GENERATION" {
+ ):
+ | "EVENT"
+ | "SPAN"
+ | "GENERATION"
+ | "AGENT"
+ | "TOOL"
+ | "CHAIN"
+ | "RETRIEVER"
+ | "EVALUATOR"
+ | "GUARDRAIL"
+ | "EMBEDDING" {
switch (observation.type) {
case eventTypes.OBSERVATION_CREATE:
case eventTypes.OBSERVATION_UPDATE:
@@ -1131,6 +1141,20 @@ export class IngestionService {
case eventTypes.GENERATION_CREATE:
case eventTypes.GENERATION_UPDATE:
return "GENERATION" as const;
+ case eventTypes.AGENT_CREATE:
+ return "AGENT" as const;
+ case eventTypes.TOOL_CREATE:
+ return "TOOL" as const;
+ case eventTypes.CHAIN_CREATE:
+ return "CHAIN" as const;
+ case eventTypes.RETRIEVER_CREATE:
+ return "RETRIEVER" as const;
+ case eventTypes.EVALUATOR_CREATE:
+ return "EVALUATOR" as const;
+ case eventTypes.EMBEDDING_CREATE:
+ return "EMBEDDING" as const;
+ case eventTypes.GUARDRAIL_CREATE:
+ return "GUARDRAIL" as const;
}
}