# LangChain

Use LangChain with Boundless through ChatOpenAI: install, base URL and key, streaming and a tool call.


LangChain reaches Boundless through `ChatOpenAI`, which speaks chat completions.

## Install

```bash
pip install langchain-openai
npm install @langchain/openai @langchain/core zod
```

## Base URL and key

```bash
export BOUNDLESS_API_KEY="paste-your-key-here"
```

Name a model with the ID from the [models table](https://inference.boundless.network/docs/models).

## Make a request

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="deepseek/deepseek-v4.1-flash-1017",
    api_key=os.environ["BOUNDLESS_API_KEY"],
    base_url="https://api.inference.boundless.network/v1",
)

message = llm.invoke("Say hello")
print(message.content)
print(message.usage_metadata)
```

```typescript
import { ChatOpenAI } from "@langchain/openai"

const llm = new ChatOpenAI({
  model: "deepseek/deepseek-v4.1-flash-1017",
  apiKey: process.env.BOUNDLESS_API_KEY,
  configuration: { baseURL: "https://api.inference.boundless.network/v1" },
})

const message = await llm.invoke("Say hello")
console.log(message.content)
console.log(message.usage_metadata)
```

## Stream the reply

```python
for chunk in llm.stream("Say hello"):
    print(chunk.content, end="", flush=True)
```

```typescript
for await (const chunk of await llm.stream("Say hello")) {
  process.stdout.write(String(chunk.content))
}
```

## Call a tool

```python
from langchain_core.tools import tool

@tool
def add(a: int, b: int) -> int:
    """Add two integers."""
    return a + b

llm_with_tools = ChatOpenAI(
    model="deepseek/deepseek-v4.1-flash",
    api_key=os.environ["BOUNDLESS_API_KEY"],
    base_url="https://api.inference.boundless.network/v1",
    max_tokens=1024,
).bind_tools([add])

message = llm_with_tools.invoke("What is 20 + 22? Use the add tool.")
print(message.tool_calls)
```

`message.tool_calls` holds the name and parsed arguments. Run the tool and send a `ToolMessage` back to continue. [Tool calling](https://inference.boundless.network/docs/tool-calling) shows the loop on the raw API.

## Known differences

- `ChatOpenAI` is built for OpenAI. Fields that only OpenAI defines are not guaranteed to work. Stay with chat completions.
- Not every model supports tools. `GET /v1/model/info` lists the capability flags.
- Credits that run out return `402` with `budget_exceeded`. Rate limits return `429`, which LangChain retries by default. See [Errors](https://inference.boundless.network/docs/errors).
- A reasoning model spends `max_tokens` on thinking too. See [Reasoning](https://inference.boundless.network/docs/reasoning).
- To use the Messages API instead, use the [Anthropic SDK](https://inference.boundless.network/docs/sdk-anthropic) or `langchain-anthropic` with `base_url` set to the gateway root.
