> ## Documentation Index
> Fetch the complete documentation index at: https://moonshotfactory.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain

> Automatically instrument LangChain chains, LLMs, and tools with zero-change integration using the AgentVista callback handler.

The `AgentVistaCallbackHandler` is a drop-in LangChain callback handler that produces AgentVista spans automatically — no manual SDK calls required. Attach it to any chain or agent via the `callbacks` argument and every chain execution, LLM call, and tool invocation is captured as a typed span.

The handler maps LangChain lifecycle events to AgentVista span types:

| LangChain callback                | Span type |
| --------------------------------- | --------- |
| `on_chain_start` / `on_chain_end` | `agent`   |
| `on_llm_start` / `on_llm_end`     | `llm`     |
| `on_tool_start` / `on_tool_end`   | `tool`    |

## Setup

<Steps>
  <Step title="Install the SDK">
    The LangChain adapter ships with the base `agentvista` package — no extras needed.

    ```bash theme={null}
    pip install agentvista
    ```

    You also need `langchain-core` installed for the handler to be active. If `langchain_core` is not available the handler imports without error but produces no output (silent no-op), so it is safe to include in any environment.

    ```bash theme={null}
    pip install langchain-core
    ```
  </Step>

  <Step title="Initialize AgentVista">
    Call `agentvista.init()` once at application startup.

    ```python theme={null}
    import agentvista

    agentvista.init(api_key="av_xxxxx")
    ```
  </Step>

  <Step title="Create the callback handler">
    ```python theme={null}
    from agentvista.adapters.langchain import AgentVistaCallbackHandler

    handler = AgentVistaCallbackHandler(agent_name="my-agent")
    ```

    `agent_name` labels the trace in the AgentVista dashboard. It defaults to `"langchain-agent"` if omitted.
  </Step>

  <Step title="Attach to your chain or agent">
    Pass `handler` in the `callbacks` list on any LangChain chain, LLM, or agent executor.

    ```python theme={null}
    chain = MyChain(..., callbacks=[handler])
    ```
  </Step>
</Steps>

## Usage example

<CodeGroup>
  ```python Standalone chain theme={null}
  from langchain_openai import ChatOpenAI
  from langchain_core.prompts import ChatPromptTemplate
  from langchain_core.output_parsers import StrOutputParser
  import agentvista
  from agentvista.adapters.langchain import AgentVistaCallbackHandler

  agentvista.init(api_key="av_xxxxx")
  handler = AgentVistaCallbackHandler(agent_name="support-bot")

  llm = ChatOpenAI(model="gpt-4.1")
  prompt = ChatPromptTemplate.from_messages([
      ("system", "You are a helpful support assistant."),
      ("human", "{question}"),
  ])
  chain = prompt | llm | StrOutputParser()

  # Pass the handler via the config dict or the callbacks argument
  result = chain.invoke(
      {"question": "How do I reset my password?"},
      config={"callbacks": [handler]},
  )
  print(result)
  ```

  ```python Inside an existing agentvista.run() trace theme={null}
  import agentvista
  from agentvista.adapters.langchain import AgentVistaCallbackHandler
  from langchain_anthropic import ChatAnthropic
  from langchain_core.prompts import ChatPromptTemplate
  from langchain_core.output_parsers import StrOutputParser

  agentvista.init(api_key="av_xxxxx")

  with agentvista.run("lead-qualifier") as r:
      handler = AgentVistaCallbackHandler(agent_name="lead-qualifier")

      llm = ChatAnthropic(model="claude-sonnet-4-6")
      prompt = ChatPromptTemplate.from_messages([
          ("human", "Qualify this lead: {lead_info}"),
      ])
      chain = prompt | llm | StrOutputParser()

      result = chain.invoke(
          {"lead_info": "Startup, 10 employees, interested in Pro plan"},
          config={"callbacks": [handler]},
      )

      qualified = "qualified" in result.lower()
      r.set_outcome(success=qualified, outcome="qualified" if qualified else "not-qualified")
  ```
</CodeGroup>

## How trace context works

The handler automatically manages trace context in two modes:

**Inside an existing `agentvista.run()` context** — the handler detects the active trace and appends child spans to it. Use this when you want to attach LangChain spans to a trace that you control, together with a call to `r.set_outcome()`.

**Standalone (no enclosing context)** — the handler auto-creates a trace when the outermost chain starts and flushes it when the outermost chain completes. You do not need to call `agentvista.run()` at all.

## What is captured per span

| Span type       | Input captured      | Output captured    | Extras                                  |
| --------------- | ------------------- | ------------------ | --------------------------------------- |
| `agent` (chain) | Chain input dict    | Chain output dict  | Chain class name                        |
| `llm`           | Prompt strings list | Generated text     | Model name, token counts when available |
| `tool`          | Tool input string   | Tool output string | Tool name                               |

Token counts (`input_tokens`, `output_tokens`, `total_tokens`) are extracted from `llm_output.token_usage` in the LangChain response when present.

<Note>
  The adapter is compatible with any `langchain_core`-based chain or agent. It uses the standard `BaseCallbackHandler` interface from `langchain_core.callbacks`, which is stable across LangChain v0.1 and v0.2+. Chains built with LangGraph or custom runnables that surface `on_chain_start`/`on_chain_end` callbacks are also supported.
</Note>
