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

# LangChain

> Sage decisions and Levanto's LLMs in LangChain, in Python and TypeScript.

```bash Python theme={"theme":"github-light"}
pip install langchain-levanto
```

```bash TypeScript theme={"theme":"github-light"}
npm install @levanto/langchain @langchain/core @langchain/openai
```

It reads your key from `LEVANTO_API_KEY`.

## Decisions

```python Python theme={"theme":"github-light"}
from langchain_core.decisions import Choice, Noul, Score
from langchain_levanto import LevantoDecisionModel

sage = LevantoDecisionModel()
response = sage.invoke({
    "state": "I was charged twice. Please refund the duplicate today.",
    "questions": {
        "refund": Noul(instructions="Is the customer asking for money back?"),
        "team": Choice(
            instructions="Which team should handle this?",
            criteria={"billing": "Charges and refunds", "technical": "Bugs and outages"},
        ),
        "urgency": Score(instructions="How urgent is it?", criteria=["Can wait", "This week", "Today"]),
    },
})

response.nouls["refund"].noul      # 0.996
response.choices["team"].choice    # "billing"
response.scores["urgency"].score   # 1.99, from 0 to 2
```

```ts TypeScript theme={"theme":"github-light"}
import { LevantoDecisionModel } from '@levanto/langchain';

const sage = new LevantoDecisionModel();
const response = await sage.invoke({
  state: 'I was charged twice. Please refund the duplicate today.',
  questions: {
    refund: { type: 'noul', instructions: 'Is the customer asking for money back?' },
    team: { type: 'choice', instructions: 'Which team?', criteria: { billing: 'Charges and refunds', technical: 'Bugs and outages' } },
    urgency: { type: 'score', instructions: 'How urgent is it?', criteria: ['Can wait', 'This week', 'Today'] },
  },
});

response.nouls.refund.noul;    // 0.996
response.choices.team.choice;  // 'billing'
response.scores.urgency.score; // 1.99, from 0 to 2
```

The state can be text, JSON or a list of chat messages. Every answer comes back, so set your own threshold on the probability. To get `null` when Sage isn't sure, or to send images, call [`/decide`](https://docs.levanto.ai/decision-model/quickstart). Options: `reasoning`, `grounding` and `timeout`, as in the [SystemOne API](https://docs.levanto.ai/systemone.md).

## Guard an agent

LangChain's auto-mode middleware asks Sage, before each listed tool runs, whether the call is risky or wasn't asked for. Sage blocks it if so.

```python Python theme={"theme":"github-light"}
from langchain.agents import create_agent
from langchain.agents.middleware import AutoModeMiddleware

agent = create_agent(
    model,
    tools=[read_file, delete_file],
    middleware=[AutoModeMiddleware(tools=[delete_file], classifier=LevantoDecisionModel())],
)
```

```ts TypeScript theme={"theme":"github-light"}
import { autoModeMiddleware, createAgent } from 'langchain';

const agent = createAgent({
  model,
  tools: [readFile, deleteFile],
  middleware: [autoModeMiddleware({ tools: [deleteFile], classifier: new LevantoDecisionModel() })],
});
```

`ModelRouterMiddleware` (`modelRouterMiddleware` in TypeScript) takes Sage the same way, as its `classifier`, to pick a model per run.

## LLMs

```python Python theme={"theme":"github-light"}
from langchain_levanto import ChatLevanto

llm = ChatLevanto(target="economy")
reply = llm.invoke("Summarize this ticket in one sentence: ...")
reply.response_metadata["model_name"]  # the model that answered
```

```ts TypeScript theme={"theme":"github-light"}
import { ChatLevanto } from '@levanto/langchain';

const llm = new ChatLevanto({ target: 'economy' });
const reply = await llm.invoke('Summarize this ticket in one sentence: ...');
reply.response_metadata.model_name; // the model that answered
```

The model defaults to `auto`, which lets the [router](https://docs.levanto.ai/llms/routers.md) pick. Streaming, tools and structured output work as with `ChatOpenAI`. Source: [github.com/levantolabs/langchain-levanto](https://github.com/levantolabs/langchain-levanto).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.