# LangChain (Python, JS)

Point LangChain's chat and embedding models at eWest.

LangChain's OpenAI integration works with eWest once you change the base URL, in Python and in JavaScript. Chains, agents and LangGraph use the model like any other chat model.

## Setup

Install the integration packages (Python 3.10 or newer, or Node 22 or newer for JavaScript):

Python:

```bash
pip install langchain-openai langchain-anthropic
```

JavaScript:

```bash
npm install @langchain/openai @langchain/core
```

[Create an API key](https://ewest.ai/keys) and put it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). The examples read it from there; never put the key in browser code.

Create `ChatOpenAI` with the base URL `https://api.ewest.ai/v1` (`base_url` in Python, `configuration.baseURL` in JavaScript):

Python:

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="ewest/claude-haiku",
    base_url="https://api.ewest.ai/v1",
    api_key=os.environ["EWEST_KEY"],
    max_tokens=256,
)
```

JavaScript:

```javascript
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "ewest/claude-haiku",
  apiKey: process.env.EWEST_KEY,
  configuration: { baseURL: "https://api.ewest.ai/v1" },
  maxTokens: 256,
});

export default llm;
```

Prefer the Anthropic format for Claude models? `ChatAnthropic` works too. Its base URL is `https://api.ewest.ai` without `/v1`, because the Anthropic client adds the path itself.

Python:

```python
import os
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
    model="ewest/claude-haiku",
    base_url="https://api.ewest.ai",  # no /v1: the Anthropic client adds it
    api_key=os.environ["EWEST_KEY"],
    max_tokens=256,
)
print(llm.invoke("Say hello in one short sentence.").content)
```

## Choose a model

Use the full model ID, including the `ewest/` prefix. The table has good starting points; [Models](https://ewest.ai/docs/models) lists every model with its context window and limits, and `GET /v1/models` returns the models your key may use. Pass it as `model`.

| Use | Model ID |
| --- | --- |
| Fast and cheap chat, tools | `ewest/claude-haiku` |
| Stronger reasoning and coding | `ewest/claude-sonnet` |
| Long context (1M tokens), images, audio and video input | `ewest/gemini-flash` |
| Embeddings for search and RAG | `ewest/gemini-embedding` |

## Verify it works

A first request with `invoke`. It prints the answer and the token usage.

Python:

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="ewest/claude-haiku",
    base_url="https://api.ewest.ai/v1",
    api_key=os.environ["EWEST_KEY"],
    max_tokens=256,
)
reply = llm.invoke("Say hello in one short sentence.")
print(reply.content)
print(reply.usage_metadata)
```

JavaScript:

```javascript
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "ewest/claude-haiku",
  apiKey: process.env.EWEST_KEY,
  configuration: { baseURL: "https://api.ewest.ai/v1" },
  maxTokens: 256,
});
const reply = await llm.invoke("Say hello in one short sentence.");
console.log(reply.content);
console.log(reply.usage_metadata);
```

The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces).

## Streaming and tools

`stream` yields the answer in chunks. In Python, `stream_usage=True` adds token usage to the last chunk.

Python:

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="ewest/claude-haiku",
    base_url="https://api.ewest.ai/v1",
    api_key=os.environ["EWEST_KEY"],
    max_tokens=256,
    stream_usage=True,
)
for chunk in llm.stream("Write a haiku about the sea."):
    print(chunk.content, end="", flush=True)
print()
```

JavaScript:

```javascript
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "ewest/claude-haiku",
  apiKey: process.env.EWEST_KEY,
  configuration: { baseURL: "https://api.ewest.ai/v1" },
  maxTokens: 256,
});
for await (const chunk of await llm.stream("Write a haiku about the sea.")) process.stdout.write(String(chunk.content));
console.log();
```

Tools: describe them with `@tool` (Python) or `tool()` (JavaScript) and attach them with `bind_tools` / `bindTools`. The model returns `tool_calls`; run them and send the results back, or let a LangGraph agent do the loop.

Python:

```python
import os
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI


@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"18 C and cloudy in {city}"


llm = ChatOpenAI(
    model="ewest/claude-haiku",
    base_url="https://api.ewest.ai/v1",
    api_key=os.environ["EWEST_KEY"],
    max_tokens=256,
)
msg = llm.bind_tools([get_weather]).invoke("What is the weather in Yerevan?")
for call in msg.tool_calls:
    print(call["name"], call["args"])
    print(get_weather.invoke(call["args"]))
```

JavaScript:

```javascript
import { tool } from "@langchain/core/tools";
import { ChatOpenAI } from "@langchain/openai";
import { z } from "zod";

const getWeather = tool(async ({ city }) => `18 C and cloudy in ${city}`, {
  name: "get_weather",
  description: "Get the current weather for a city.",
  schema: z.object({ city: z.string() }),
});

const llm = new ChatOpenAI({
  model: "ewest/claude-haiku",
  apiKey: process.env.EWEST_KEY,
  configuration: { baseURL: "https://api.ewest.ai/v1" },
  maxTokens: 256,
});
const msg = await llm.bindTools([getWeather]).invoke("What is the weather in Yerevan?");
for (const call of msg.tool_calls ?? []) {
  console.log(call.name, call.args);
  const result = await getWeather.invoke(call); // a ToolMessage to send back to the model
  console.log(result.content);
}
```

Embeddings use `OpenAIEmbeddings` with the same base URL. In Python, set `check_embedding_ctx_length=False` so it sends plain text. This avoids sending token ids that non-OpenAI embedding models can't read.

Python:

```python
import os
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(
    model="ewest/gemini-embedding",
    base_url="https://api.ewest.ai/v1",
    api_key=os.environ["EWEST_KEY"],
    check_embedding_ctx_length=False,  # send text, not token ids
)
vector = embeddings.embed_query("How do I reset my password?")
print(len(vector))
```

JavaScript:

```javascript
import { OpenAIEmbeddings } from "@langchain/openai";

const embeddings = new OpenAIEmbeddings({
  model: "ewest/gemini-embedding",
  apiKey: process.env.EWEST_KEY,
  configuration: { baseURL: "https://api.ewest.ai/v1" },
});
const vector = await embeddings.embedQuery("How do I reset my password?");
console.log(vector.length);
```

## Troubleshooting

- **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-haiku`, not `claude-haiku`). Check the spelling against [Models](https://ewest.ai/docs/models).
- **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens, or turn reasoning off (below). This is a known limitation.
- **Follow-up turns forget the conversation:** on the Responses API, pass the earlier response's `id` as `previous_response_id` (conversations are stored by default), or send the full message history with every request; chat completions and Messages are always stateless. See [Responses](https://ewest.ai/docs/responses).
- **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console.

Turning reasoning off: pass `reasoning_effort="none"` to `ChatOpenAI`. Most chat models accept `none`; a few don't (their lowest is `low`) and answer 400 `unsupported_value`. Check the model's `reasoning_efforts` in `GET /v1/models/{id}` or the catalog. `use_responses_api=True` works as well; send the full message history each turn, or use `previous_response_id` (see [Responses](https://ewest.ai/docs/responses)).

Python:

```python
import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="ewest/gemini-flash",
    base_url="https://api.ewest.ai/v1",
    api_key=os.environ["EWEST_KEY"],
    max_tokens=256,
    reasoning_effort="none",  # answer without thinking first
)
print(llm.invoke("Say hello in one short sentence.").content)
```

Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting).

Source: https://ewest.ai/docs/guides/langchain
