LangChain Integration

Lucidic integrates seamlessly with LangChain agents and chains — no need to rewrite your code or restructure your logic.

How It Works

When you use providers=["langchain"] with Lucidic:
  • LangChain LLM calls are automatically instrumented using OpenTelemetry
  • Events are automatically created for every LLM call - no manual event creation needed
  • No need to manually attach handlers in most cases
  • All LLM usage is captured as Lucidic Events, grouped under the correct Step
  • If no step exists when an LLM call occurs, one is automatically created
This means you get full observability into your agent’s reasoning — with minimal setup.

Example

import lucidicai as lai
from langchain_openai import ChatOpenAI

# Just initialize - that's it!
lai.init(providers=["langchain"])

llm = ChatOpenAI(model="gpt-4")

# Steps and events are automatically created
response = llm.invoke("Hello!")

# Session auto-ends when script exits

Streaming Example

import lucidicai as lai
from langchain_openai import ChatOpenAI

lai.init(providers=["langchain"])

llm = ChatOpenAI(model="gpt-4")

# Streaming responses are also tracked automatically
for chunk in llm.stream("Tell me a story"):
    print(chunk.content, end="")

Explicit Step Management

import lucidicai as lai
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage

lai.init(
    session_name="langchain_research",
    providers=["langchain"]  # API key and agent ID from env vars
)

llm = ChatOpenAI(model="gpt-4")

lai.create_step(state="Research", goal="Generate research ideas")

# All LLM calls are automatically tracked as events within this step
response = llm.invoke([
    SystemMessage(content="You are a research assistant."),
    HumanMessage(content="What are 5 important areas in climate science?")
])

response = llm.invoke([
    HumanMessage(content="What methodologies are used to study each area?")
])

lai.end_step()

What Gets Captured

For every LangChain LLM call, we automatically capture:
  • Input: your messages/prompt to the LLM
  • Model: the LLM model used (e.g. gpt-4, claude-3)
  • Output: the LLM response (including streaming)
  • Token usage: input and output tokens
  • Cost: calculated based on token usage and model pricing
  • Chain context: which chain or agent made the call
  • Tool usage: any tools invoked by the agent

Agent Example

import lucidicai as lai
from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent, AgentExecutor
from langchain.tools import Tool
from langchain_core.prompts import PromptTemplate

lai.init(
    session_name="langchain_agent",
    providers=["langchain"]
)

# Define tools
tools = [
    Tool(
        name="Calculator",
        func=lambda x: eval(x),
        description="Useful for math calculations"
    )
]

# Create agent
llm = ChatOpenAI(model="gpt-4")
prompt = PromptTemplate.from_template("You are a helpful assistant. {input}")
agent = create_react_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools)

lai.create_step(state="Ready", goal="Solve math problem")

# All LLM calls within the agent are automatically tracked!
result = executor.invoke({"input": "What is 25 * 4 + 10?"})

lai.end_step()

Complex Agent Handler (Optional)

For some complex agent setups, you may need to manually attach a handler:
from lucidicai.telemetry.otel_handlers import OTelLangChainHandler

# Get the handler from the SDK
handler = lai.Client().get_provider("langchain")

# Manually attach to your agent if needed
if hasattr(agent, 'callbacks'):
    agent.callbacks.append(handler)
In most cases, automatic instrumentation will work without manual attachment.

Notes

  • Requires LangChain packages installed (langchain, langchain-openai, etc.)
  • Works with all LangChain LLMs, chains, and agents
  • Automatic instrumentation handles most use cases
  • If no step exists when an LLM call is made, Lucidic automatically creates one
  • Both sync and async operations are supported
  • Tool calls and chain execution are tracked as separate events