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

# LangChain and LangGraph

> Add Silmaril callbacks to LangChain models and LangGraph applications in TypeScript or Python.

## Prerequisites

Install and initialize the [TypeScript SDK](/docs/sdk/typescript#initialize) or [Python SDK](/docs/sdk/python#initialize). The examples use that client as `fw`. Set `OPENAI_API_KEY` for the OpenAI model examples.

## Add the callback handler

<Tabs>
  <Tab title="TypeScript">
    ```bash theme={"theme":"github-light-default"}
    npm install @langchain/core @langchain/openai
    ```

    ```typescript theme={"theme":"github-light-default"}
    import { ChatOpenAI } from "@langchain/openai"

    const handler = await fw.asLangChainHandler()
    const model = new ChatOpenAI({ callbacks: [handler] })

    await model.invoke("Hello")
    ```

    LangGraph.js can use the same LangChain callback handler through graph invocation config.

    ```typescript theme={"theme":"github-light-default"}
    const handler = await fw.asLangChainHandler()

    await graph.invoke(state, {
      callbacks: [handler],
    })
    ```

    `graph` and `state` belong to the LangGraph application. Shadow-mode overrides for this handler are on the [TypeScript SDK page](/docs/sdk/typescript#shadow-mode).
  </Tab>

  <Tab title="Python">
    ```sh theme={"theme":"github-light-default"}
    pip install "silmaril-security-sdk[langchain]==0.6.1" langchain-openai
    ```

    ```python theme={"theme":"github-light-default"}
    from langchain_openai import ChatOpenAI

    handler = fw.as_langchain_handler()
    model = ChatOpenAI(callbacks=[handler])

    model.invoke("Hello")
    ```

    LangGraph can pass the same callback handler through runnable config.

    ```python theme={"theme":"github-light-default"}
    handler = fw.as_langchain_handler()

    graph.invoke(
        state,
        config={"callbacks": [handler]},
    )
    ```

    `fw` is the [Python client](/docs/sdk/python#initialize). `graph` and `state` belong to the LangGraph application. Direct Python calls raise `FirewallBlockedException` in enforcement mode. See [Python errors](/docs/sdk/python#errors).
  </Tab>
</Tabs>

## Expected result

The callback handler inspects supported model and tool lifecycle events. Pass the handler to every model or graph call you intend to protect. In shadow mode, would-block calls continue. When enforcing, handle the SDK's block exception at the application boundary.

* [LangChain documentation](https://docs.langchain.com/)
* [LangGraph documentation](https://docs.langchain.com/oss/python/langgraph/overview)
