Langfuse JS/TS SDKs
    Preparing search index...

    Specialized observation wrapper for tracking structured multi-step workflows and process chains.

    LangfuseChain is designed for observing sequential, parallel, or conditional workflow orchestration where multiple operations are coordinated to achieve a larger goal. It captures the flow of data between steps, manages dependencies, tracks progress through complex pipelines, and provides insights into workflow performance and reliability patterns.

    • Data Processing Pipelines: ETL processes, data transformation workflows
    • Business Process Automation: Order processing, approval workflows, document processing
    • LangChain Integration: LangChain chain execution and orchestration
    • RAG Pipelines: Document retrieval → context preparation → generation → post-processing
    • Multi-Model Workflows: Preprocessing → model inference → post-processing → validation
    • Content Production: Research → drafting → review → editing → publishing
    • Step Orchestration: Sequential, parallel, and conditional step execution tracking
    • Data Flow Management: Input/output tracking between pipeline steps
    • Dependency Resolution: Manages complex step dependencies and prerequisites
    • Progress Monitoring: Real-time workflow progress and completion status
    • Error Propagation: Handles failures, retries, and recovery across workflow steps
    • Performance Analytics: Bottleneck identification and optimization insights
    • Pipeline Setup: Workflow definition, step configuration, and dependency mapping
    • Sequential Execution: Step-by-step processing with state management
    • Parallel Processing: Concurrent step execution with synchronization
    • Conditional Logic: Dynamic branching based on intermediate results
    • Error Recovery: Failure handling, rollback, and alternative path execution
    • Result Aggregation: Combining outputs from multiple workflow branches
    // RAG processing chain
    const ragChain = startObservation('rag-chain', {
    input: {
    query: 'What is renewable energy?',
    steps: ['retrieval', 'generation']
    }
    }, { asType: 'chain' });

    // Step 1: Document retrieval
    const retrieval = ragChain.startObservation('document-retrieval', {
    input: { query: 'renewable energy' }
    }, { asType: 'retriever' });

    const docs = await vectorSearch('renewable energy');
    retrieval.update({ output: { documents: docs, count: docs.length } });
    retrieval.end();

    // Step 2: Generate response
    const generation = ragChain.startObservation('response-generation', {
    input: {
    query: 'What is renewable energy?',
    context: docs
    },
    model: 'gpt-4'
    }, { asType: 'generation' });

    const response = await llm.generate({
    prompt: buildPrompt('What is renewable energy?', docs)
    });

    generation.update({ output: response });
    generation.end();

    ragChain.update({
    output: {
    finalResponse: response,
    stepsCompleted: 2,
    documentsUsed: docs.length
    }
    });
    ragChain.end();

    Hierarchy

    • LangfuseBaseObservation
      • LangfuseChain
    Index

    Constructors

    • Parameters

      • params: LangfuseChainParams

      Returns LangfuseChain

    Properties

    id: string

    The span ID from the OpenTelemetry span context

    otelSpan: Span

    The underlying OpenTelemetry span

    traceId: string

    The trace ID from the OpenTelemetry span context

    The underlying OpenTelemetry span

    Accessors

    • get tracer(): Tracer

      Gets the Langfuse OpenTelemetry tracer instance

      Returns Tracer

    Methods

    • Ends the observation, marking it as complete.

      Parameters

      • OptionalendTime: TimeInput

        Optional end time, defaults to current time

      Returns void

    • 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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseGenerationAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "generation" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseGeneration

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "event" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseEvent

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "agent" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseAgent

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "tool" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseTool

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "chain" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseChain

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "retriever" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseRetriever

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "evaluator" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseEvaluator

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "guardrail" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseGuardrail

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • attributes: LangfuseGenerationAttributes

        Type-specific attributes (varies by observation type)

      • options: { asType: "embedding" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseEmbedding

      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.

      • Child observations automatically inherit the parent's trace ID and span context
      • Creates proper parent-child relationships in the trace structure
      • Enables distributed tracing across nested operations
      • Maintains correlation between related operations
      • Return type is automatically inferred from asType parameter
      • Attributes parameter is type-checked based on observation type
      • Compile-time validation prevents type mismatches
      • Full IntelliSense support for observation-specific attributes

      Parameters

      • name: string

        Descriptive name for the child observation

      • Optionalattributes: LangfuseSpanAttributes

        Type-specific attributes (varies by observation type)

      • Optionaloptions: { asType?: "span" }

        Configuration including observation type (defaults to 'span')

      Returns LangfuseSpan

      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();
    • Updates this chain observation with new attributes.

      Parameters

      Returns LangfuseChain

      This chain for method chaining

      chain.update({
      output: {
      stepsCompleted: 5,
      stepsSuccessful: 4,
      finalResult: processedData,
      pipelineEfficiency: 0.87
      },
      metadata: {
      bottleneckStep: 'data-validation',
      parallelizationOpportunities: ['step-2', 'step-3'],
      optimizationSuggestions: ['cache-intermediate-results']
      }
      });
    • Updates the parent trace with new attributes.

      This sets trace-level attributes that apply to the entire trace, not just this specific observation.

      Parameters

      Returns LangfuseChain

      This observation for method chaining