Skip to main content
OpenInference provides automatic instrumentation for LangChain4j applications, enabling you to trace LLM calls, model parameters, token usage, and more using OpenTelemetry.

Installation

Gradle

Add the following to your build.gradle:

Maven

Add the following to your pom.xml:

Requirements

  • Java 11 or higher
  • OpenTelemetry Java 1.49.0 or higher
  • LangChain4j 1.0.0 or higher

Quick Start

Automatic Instrumentation

Instrument your LangChain4j application with a single line of code:

Manual Instrumentation with Model Listener

For more control, register a model listener directly:

OpenTelemetry Setup

Basic Setup with Phoenix

With Authentication (Phoenix Cloud)

Configuration

Custom Trace Configuration

Control what information is captured in traces:

With Custom Tracer Provider

Complete Example

Here’s a complete example with tool calling:

Captured Trace Data

The instrumentation automatically captures:
  • LLM Model Information: Model name, provider (OpenAI, etc.)
  • Input Messages: User prompts, system messages, conversation history
  • Output Messages: Model responses, assistant messages
  • Invocation Parameters: Temperature, max tokens, top_p, etc.
  • Token Usage: Prompt tokens, completion tokens, total tokens
  • Tool Calls: Function names, arguments, and results
  • Timing Information: Request latency and duration
  • Error Information: Exceptions and error messages

Viewing Traces

Using Phoenix

  1. Start Phoenix locally:
  2. Run your instrumented application
  3. View traces at http://localhost:6006

Using Other Backends

OpenInference instrumentation works with any OpenTelemetry-compatible backend:
  • Jaeger: Change the OTLP endpoint to your Jaeger instance
  • Zipkin: Use the Zipkin exporter instead of OTLP
  • Cloud Providers: AWS X-Ray, Google Cloud Trace, Azure Monitor

Best Practices

  1. Initialize Once: Call LangChain4jInstrumentor.instrument() once at application startup
  2. Set Service Name: Always set a meaningful service.name in your OpenTelemetry resource
  3. Use Batch Processing: Use BatchSpanProcessor for better performance in production
  4. Handle Secrets: Never log API keys or sensitive data in traces
  5. Flush on Shutdown: Call tracerProvider.forceFlush() before application exit to ensure all spans are sent

Troubleshooting

No traces appearing

  • Verify OpenTelemetry is initialized before calling instrument()
  • Check that your OTLP endpoint is accessible
  • Ensure forceFlush() is called before application exit
  • Enable debug logging: System.setProperty("otel.logs.exporter", "console")

Duplicate instrumentation error

Solution: Only call LangChain4jInstrumentor.instrument() once per application lifecycle.

Missing token counts

Token counts are only available when the LLM provider returns usage metadata. Not all providers include this information.

Resources