# LangChain

> Use LangChain with AnyRouter by pointing ChatOpenAI at one endpoint, in Python or TypeScript.


# Use LangChain with AnyRouter

AnyRouter is OpenAI-compatible, so keep LangChain's OpenAI integration and change the base URL, key and model id. Create an `sk-ar-` key in the [dashboard](https://anyrouter.dev/dashboard/keys) and export it as `ANYROUTER_API_KEY`.

::::tabs

:::tab{label="Python"}
```bash
pip install langchain-openai
```

```python
import os
from langchain_openai import ChatOpenAI

chat = ChatOpenAI(
    base_url="https://anyrouter.dev/api/v1",
    api_key=os.environ["ANYROUTER_API_KEY"],
    model="anyrouter/free",
)

response = chat.invoke("What is a fallback route? Answer in one sentence.")
print(response.response_metadata.get("model_name"))  # the model that served it
print(response.content)
```
:::

:::tab{label="TypeScript"}
```bash
npm install @langchain/openai @langchain/core
```

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

const chat = new ChatOpenAI({
  model: "anyrouter/free",
  apiKey: process.env.ANYROUTER_API_KEY,
  configuration: { baseURL: "https://anyrouter.dev/api/v1" },
})

const response = await chat.invoke("Explain DNS load balancing in one sentence.")
console.log(response.response_metadata.model_name) // the model that served it
console.log(response.content)
```
:::

::::

Requests also appear in [Logs](https://anyrouter.dev/dashboard/logs).

## Model ids

- `anyrouter/free` routes to a healthy free model, no credits. Needs Go ($2/mo, or free when you donate one working provider key to the shared Pool); no daily cap. See [Free Tier](/features/free-tier).
- `anyrouter/auto` picks from the full catalog.
- Any `provider/model` id from the [catalog](https://anyrouter.dev/models) pins one model.

Own provider keys (BYOK) deduct no credits: see [Get a provider API key](/guides/byok-provider-keys) and [BYOK](/features/byok).

## Troubleshooting

| Symptom | Fix |
|---|---|
| 401 | Key must start with `sk-ar-` and be passed as `api_key` (Python) or `apiKey` (TypeScript). |
| 404 model not found | Use a full id such as `anyrouter/free` or `z-ai/glm-4.7-flash`, not a bare model name. |


## Related

- [OpenAI SDK](/docs/guides/openai-sdk.md)
- [Vercel AI SDK](/docs/guides/vercel-ai-sdk.md)
- [LlamaIndex](/docs/guides/llamaindex.md)
- [Chat Completions API](/docs/api-reference/chat-completions.md)
- [Free Tier](/docs/features/free-tier.md)
- [Bring Your Own Key (BYOK)](/docs/features/byok.md)
