The span ID from the OpenTelemetry span context
ReadonlyotelThe underlying OpenTelemetry span
The trace ID from the OpenTelemetry span context
ReadonlytypeThe underlying OpenTelemetry span
ProtectedtracerGets the Langfuse OpenTelemetry tracer instance
Ends the observation, marking it as complete.
OptionalendTime: TimeInputOptional end time, defaults to current time
Make the trace this observation belongs to publicly accessible via its URL.
When a trace is published, anyone with the trace link can view the full trace without needing to be logged in to Langfuse. This action cannot be undone programmatically - once any span in a trace is published, the entire trace becomes public.
The observation instance for method chaining
Set trace-level input and output for the trace this observation belongs to.
Input and output data to associate with the trace
The observation instance for method chaining
This is a legacy method for backward compatibility with Langfuse platform features that still rely on trace-level input/output (e.g., legacy LLM-as-a-judge evaluators). It will be removed in a future major version.
For setting other trace attributes (userId, sessionId, metadata, tags, version), use propagateAttributes instead.
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Type-specific attributes (varies by observation type)
Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Creates a new child observation within this observation's context with full type safety.
This method enables hierarchical tracing by creating child observations that inherit
the parent's trace context. It supports all observation types with automatic TypeScript
type inference based on the asType parameter, ensuring compile-time safety for
attributes and return types.
asType parameterDescriptive name for the child observation
Optionalattributes: LangfuseSpanAttributesType-specific attributes (varies by observation type)
Optionaloptions: { asType?: "span" }Configuration including observation type (defaults to 'span')
Strongly-typed observation instance based on asType
// Within any observation (span, generation, agent, etc.)
const parentObservation = startObservation('ai-workflow');
// Create child span (default)
const dataProcessing = parentObservation.startObservation('data-processing', {
input: { userId: '123', dataSize: 1024 },
metadata: { processor: 'fast-lane', version: '2.1' }
}); // Returns LangfuseSpan
// Create child generation with full LLM attributes
const llmCall = parentObservation.startObservation('openai-gpt-4', {
input: [{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'user', content: 'Explain machine learning' }],
model: 'gpt-4-turbo',
modelParameters: {
temperature: 0.7,
maxTokens: 500,
topP: 1.0
},
metadata: { priority: 'high', timeout: 30000 }
}, { asType: 'generation' }); // Returns LangfuseGeneration
// Create child agent for complex reasoning
const reasoningAgent = parentObservation.startObservation('reasoning-agent', {
input: {
task: 'Analyze market trends',
context: 'Q4 2024 financial data'
},
metadata: {
model: 'gpt-4',
tools: ['calculator', 'web-search', 'data-analysis'],
maxIterations: 5
}
}, { asType: 'agent' }); // Returns LangfuseAgent
// Create child tool for external API calls
const apiCall = reasoningAgent.startObservation('market-data-api', {
input: {
endpoint: '/market/trends',
params: { symbol: 'AAPL', period: '1Y' }
},
metadata: {
provider: 'alpha-vantage',
rateLimit: 5,
timeout: 10000
}
}, { asType: 'tool' }); // Returns LangfuseTool
// Create child retriever for document search
const docSearch = parentObservation.startObservation('document-retrieval', {
input: {
query: 'sustainable energy solutions',
filters: { year: '2024', category: 'research' },
topK: 10
},
metadata: {
vectorStore: 'pinecone',
embeddingModel: 'text-embedding-ada-002',
similarity: 'cosine'
}
}, { asType: 'retriever' }); // Returns LangfuseRetriever
// Create child evaluator for quality assessment
const qualityCheck = parentObservation.startObservation('response-evaluator', {
input: {
response: llmCall.output?.content,
reference: 'Expected high-quality explanation',
criteria: ['accuracy', 'clarity', 'completeness']
},
metadata: {
evaluator: 'custom-bert-scorer',
threshold: 0.8,
metrics: ['bleu', 'rouge', 'semantic-similarity']
}
}, { asType: 'evaluator' }); // Returns LangfuseEvaluator
// Create child guardrail for safety checking
const safetyCheck = parentObservation.startObservation('content-guardrail', {
input: {
text: llmCall.output?.content,
policies: ['no-harmful-content', 'no-personal-info', 'professional-tone']
},
metadata: {
guardrailVersion: 'v2.1',
strictMode: true,
confidence: 0.95
}
}, { asType: 'guardrail' }); // Returns LangfuseGuardrail
// Create child embedding for vector generation
const textEmbedding = parentObservation.startObservation('text-embedder', {
input: {
texts: ['Document summary', 'Key insights', 'Conclusions'],
batchSize: 3
},
model: 'text-embedding-ada-002',
metadata: {
dimensions: 1536,
normalization: 'l2',
purpose: 'semantic-search'
}
}, { asType: 'embedding' }); // Returns LangfuseEmbedding
// Create child event for point-in-time logging
const userAction = parentObservation.startObservation('user-interaction', {
input: {
action: 'button-click',
element: 'generate-report',
timestamp: new Date().toISOString()
},
level: 'DEFAULT',
metadata: {
sessionId: 'sess_123',
userId: 'user_456',
browser: 'Chrome 120.0'
}
}, { asType: 'event' }); // Returns LangfuseEvent (auto-ended)
// Chain operations - each child inherits context
dataProcessing.update({ output: { processed: true, records: 1000 } });
dataProcessing.end();
llmCall.update({
output: { role: 'assistant', content: 'Machine learning is...' },
usageDetails: { promptTokens: 25, completionTokens: 150 }
});
llmCall.end();
parentObservation.update({
output: {
workflowCompleted: true,
childOperations: 8,
totalDuration: Date.now() - startTime
}
});
parentObservation.end();
Specialized observation wrapper for tracking LLM interactions, AI model calls, and text generation.
LangfuseGeneration is purpose-built for observing AI model interactions, providing rich metadata capture for prompts, completions, model parameters, token usage, and costs. It's the go-to observation type for any operation involving language models, chat APIs, completion APIs, or other generative AI services.
Primary Use Cases
Key Features
Generation-Specific Attributes
model: Model identifier (e.g., 'gpt-4-turbo', 'claude-3-sonnet')modelParameters: Temperature, max tokens, top-p, frequency penaltyinput: Prompt or message array for the modeloutput: Model response, completion, or generated contentusageDetails: Token consumption (prompt, completion, total)costDetails: Financial cost breakdown and pricingprompt: Structured prompt object with name, version, variablesExample
See
{ asType: 'generation' }- Factory function{ asType: 'generation' }- Function-scoped generation