Facet
All docs

LangChain — Integration Guide

Step-by-step developer guide for instrumenting a LangChain application.

LangChain Integration Guide (Developer)

This is the complete, step-by-step guide for a developer instrumenting a real LangChain application with ADG. The adapter has been validated against two independent, real-world open-source applications — not just internal test applications — see "Real-world validation" below for what that means in practice and why it matters to you.

For the conceptual question "which of my own objects/calls should become a Trace vs. an Activity vs. an Artifact vs. a Resource?" — relevant if your app does anything LangChain doesn't already structure for you — see the Ontology Mapping Decision Guide first. This guide assumes you already know the answer and shows the LangChain-specific mechanics of acting on it.


1. The one-line integration

If your code already calls a LangChain Runnable — a chain, an AgentExecutor, a chat model, a retriever, anything with .invoke()/.ainvoke() — the entire integration is:

from adg.adapters.langchain import instrument_callbacks

result = chain.invoke(
    my_input,
    config={"callbacks": instrument_callbacks()},
)

That's it. instrument_callbacks() returns a list containing one ADGCallbackHandler — a real langchain_core.callbacks. BaseCallbackHandler subclass — wired with ADG's default transport (console by default; your platform contact can help configure REST/production transport). No wrapping, no subclassing, no changes to your chain's own structure. This is the same config={"callbacks": [...]} mechanism every LangChain Runnable already accepts natively — nothing ADG-specific about how you attach it, only what you attach.

Every on_chain_start/on_chain_end, on_llm_start/on_llm_end, on_tool_start/on_tool_end, and on_retriever_start/ on_retriever_end event your chain fires becomes a Trace/Activity/ Artifact/Resource automatically — see §3 below for exactly how each maps.

Async code

Use ainvoke/astream exactly the same way — the adapter is a real AsyncCallbackHandler and supports both sync and async call paths, including streaming (astream still fires a complete on_llm_end with the fully-assembled response, confirmed during real-world validation — see §5).

Customizing what gets captured

All the same optional parameters every other ADG adapter supports are available on instrument_callbacks(...):

from pathlib import Path
from adg.adapters.langchain import instrument_callbacks
from adg.artifact_types import load_artifact_type_mapping

artifact_type_mapping = load_artifact_type_mapping(
    Path(__file__).parent / "artifact_types.toml"
)

handlers = instrument_callbacks(
    artifact_type_mapper=artifact_type_mapping,  # or a callable
)

result = await chain.ainvoke(
    my_input, config={"callbacks": handlers}
)

See the Artifact Type Mapping guide for the full artifact_types.toml format — this classifies your chain's own outcome Artifacts (e.g. "this chain's final output is a DECISION") without ADG ever guessing at your business semantics itself.


2. Zero-code instrumentation

If you cannot or do not want to add instrument_callbacks() to your own source at all, LangChain is one of the frameworks ADG's zero-code sitecustomize shim supports — environment variables only, no source change. Set:

export ADG_ZERO_CODE_FRAMEWORKS=langchain   # or omit to patch all known frameworks

and put ADG's zero-code shim directory on PYTHONPATH, same as the LangGraph/Semantic Kernel zero-code paths. Your platform contact can walk you through the full environment-variable reference table.


3. How LangChain's events map onto the ontology

LangChain callback Ontology entity Notes
Outermost Runnable/AgentExecutor/chain's invoke()/ainvoke() call Trace Opened on the outermost on_chain_start with no enclosing parent run; closed on its matching on_chain_end/error.
Nested on_chain_start/on_chain_end (sub-chains, RunnableSequence steps) Activity One Activity per nested chain step, correctly parented via LangChain's own run_id/parent_run_id.
on_llm_start/on_chat_model_start ... on_llm_end Activity (if no enclosing chain Activity exists, one is synthesized) + Resource (the model itself) + Artifact (the completion) A standalone llm.invoke(...) call with no enclosing chain still gets a full Trace/Activity/Artifact/Resource sequence — never silently dropped for lacking a parent chain.
on_tool_start/on_tool_end Activity + Resource ("tool"-typed) + Artifact (single-key, named after the tool) Proven against a real multi-tool AgentExecutor in our own validation suite.
on_agent_action Activity ("agent_action:<tool_name>") One per agent decision, nested inside the Trace the top-level AgentExecutor.invoke(...) opened.
on_retriever_start/on_retriever_end Activity + Resource ("vector_store"/retriever-typed) + Artifact (retrieved documents) See §5 for a real-world caveat: not every retrieval-shaped app actually fires these.
Final chain/agent return value TraceFinalStateCaptured The Trace's own final state — whatever shape your chain actually returned, never reshaped.
Any exception during a chain/LLM/tool call *Failed event (TraceFailed/ActivityFailed) str(exception) only — the adapter never inspects exception internals beyond that.

This table is the LangChain-specific instance of the same ontology every other adapter (LangGraph, Semantic Kernel) maps onto.


4. Two integration patterns, depending on your app's shape

Pattern A: your app already composes LCEL Runnables

If your app's orchestration is itself a composed RunnableSequence/ RunnableLambda/AgentExecutor chain (the common case), §1 above is the entire integration. Nothing else is needed.

Pattern B: your app calls LangChain chat models imperatively, from plain Python functions

Some real applications (this was discovered, not assumed, during real-world validation — see §5) never compose a single top-level Runnable at all. Instead, ordinary async def functions call one or more independent LangChain chat models directly (self.llm.ainvoke(messages)), possibly concurrently (asyncio.gather), with no config/callbacks parameter threaded through from any public entrypoint.

For this shape, wrap your own top-level entrypoint call in a plain RunnableLambda, and pass config={"callbacks": [...]} to that call — LangChain's own ambient RunnableConfig propagation (a contextvars.ContextVar, the same mechanism LangSmith's implicit tracing_v2_enabled() relies on) automatically threads your callback handler through every nested, unguarded .ainvoke() call underneath, including calls made concurrently under asyncio.gather:

from langchain_core.runnables import RunnableLambda
from adg.adapters.langchain import instrument_callbacks

async def _run(_):
    return await my_app.do_the_real_work(user_input)

handlers = instrument_callbacks()
result = await RunnableLambda(_run).ainvoke(
    None, config={"callbacks": handlers}
)

No monkeypatching of your own application's internals, and no changes to ADG's own adapter code are needed for this pattern — confirmed directly against a real production-grade application (see §5).

A known rough edge inherent to this pattern, not to ADG: if your own application's public API (like gpt-researcher's GPTResearcher.conduct_research()/.write_report()) has no config/ callbacks parameter of its own, you cannot attach per-call tags/metadata the way a native Runnable caller could — only the one outer RunnableLambda wrapping shown above. If you own that code, consider exposing a config/callbacks passthrough on your own public methods, the same way any native LangChain Runnable caller already gets for free.

Pattern C: a third-party framework built on LangChain with its own pluggable tracing abstraction

Some LangChain-based frameworks (Langflow's lfx execution engine is the real-world example validated here) expose their own tracer-plugin abstraction rather than a bare Runnable call site. For this shape, implement that framework's tracer interface and have it return instrument_callbacks()'s handler(s) from whatever method the framework calls to attach LangChain callbacks (for Langflow, this is an ADGTracingService subclassing lfx's own BaseTracingService, registered via lfx's own ServiceManager.register_service_class). No changes to ADG's own adapter code are needed for this pattern either.


5. Real-world validation: what this adapter was actually proven against

Beyond our own internal test applications, the adapter was validated against two independent, genuinely popular, actively-maintained open-source applications — deliberately chosen to prove the adapter against code nobody on this project wrote, in shapes this project didn't design for in advance:

  1. assafelovic/gpt-researcher (~22k★, PyPI gpt-researcher, genuinely built on langchain>=1.0/ langgraph) — Pattern B above (imperative chat-model calls, no composed Runnable). Stress-tested: concurrent asyncio.gather runs (zero cross-talk between concurrent traces, confirmed directly), streaming, non-dict chain state, exception paths.
  2. langflow-ai/langflow (156k★, via its standalone lfx execution engine) — Pattern C above (tracer-plugin-driven attachment, a materially different mechanism from Pattern B's ambient propagation). Stress-tested: a real multi-component flow (ChatInput→PromptComponent→ LanguageModelComponent→ChatOutput, mirroring Langflow's own "Basic Prompting" starter flow), concurrent runs sharing one singleton tracing-service instance.

Result: zero changes to ADG's own adapter code were needed for either validation. This is strong evidence the adapter generalizes beyond our own internal test applications — not a guarantee that your app's particular shape has zero surprises, but real precedent for two materially different real-world integration shapes (imperative Pattern B vs. tracer-plugin Pattern C) both working with no adapter changes.

One honest caveat: neither validation exercised a real retriever (on_retriever_start/on_retriever_end) against a real vector store — gpt-researcher's own retriever layer turned out to be its own plain-Python interface, unrelated to LangChain's retriever callbacks, and neither validation wired a real embeddings-backed retriever. If your app does, the mapping in §3's table is implemented and covered by our own test suite, but has not yet been proven against a real-world retrieval-heavy application the way the rest of this table has.


6. Where to go next

  • The Ontology Mapping Decision Guide — how to decide ontology boundaries for anything LangChain doesn't already structure for you.
  • The Artifact Type Mapping guide — classifying your chain's own outcome Artifacts.
  • The Field Mapping guide — vocabulary normalization (mapping your own field names onto canonical projection fields).
  • Your Facet platform contact — production transport, monitoring, and scaling guidance for LangChain-sourced traces.