# Anthropic SDK (Python, TS)

Call eWest with the official Anthropic libraries.

The official Anthropic libraries work with eWest's Messages API: `/v1/messages`, `/v1/messages/count_tokens` and `/v1/models`. Install with `pip install anthropic` or `npm install @anthropic-ai/sdk`.

## Setup

Set the base URL to `https://api.ewest.ai`, **without** `/v1`: the SDK adds `/v1/messages` itself. Pass your eWest key as the API key; eWest accepts it as `x-api-key` or `Authorization: Bearer`. Or set `ANTHROPIC_BASE_URL` and `ANTHROPIC_API_KEY` and create the client without arguments. `client.models.retrieve("ewest/claude-haiku")` is a free first check that the key and base URL work.

Python:

```python
import os
import anthropic

# No /v1 on the base URL: the SDK adds /v1/messages itself.
client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"])

# Looking up a model is free, and proves the key and base URL work.
print(client.models.retrieve("ewest/claude-haiku").id)

```

TypeScript:

```javascript
import Anthropic from "@anthropic-ai/sdk";

// No /v1 on the base URL: the SDK adds /v1/messages itself.
const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY });

// Looking up a model is free, and proves the key and base URL work.
console.log((await client.models.retrieve("ewest/claude-haiku")).id);

```

Shell:

```bash
# Or leave base_url / api_key out of the code: the SDKs read these.
export ANTHROPIC_BASE_URL=https://api.ewest.ai
export ANTHROPIC_API_KEY="$EWEST_KEY"
```

## Choose a model

`client.models.list()` returns the models your key may use. Claude models are `ewest/claude-opus`, `ewest/claude-sonnet` and `ewest/claude-haiku`, always with the `ewest/` prefix. `max_tokens` is required on every message, as in Anthropic's API.

Python:

```python
import os
import anthropic

# No /v1 on the base URL: the SDK adds /v1/messages itself.
client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"])

# Every model your key may call. Use the id as model=...
for model in client.models.list():
    print(model.id)

```

TypeScript:

```javascript
import Anthropic from "@anthropic-ai/sdk";

// No /v1 on the base URL: the SDK adds /v1/messages itself.
const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY });

// Every model your key may call. Use the id as model: ...
for await (const model of client.models.list()) console.log(model.id);

```

## Verify it works

A short message. Every response has an `x-request-id` header; paste it into the console under Requests to see the request ([trace IDs](https://ewest.ai/docs/traces)).

Python:

```python
import os
import anthropic

# No /v1 on the base URL: the SDK adds /v1/messages itself.
client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"])

message = client.messages.create(
    model="ewest/claude-haiku",
    max_tokens=512,
    messages=[{"role": "user", "content": "Say hello in five words."}],
)
print(message.content[0].text)

```

TypeScript:

```javascript
import Anthropic from "@anthropic-ai/sdk";

// No /v1 on the base URL: the SDK adds /v1/messages itself.
const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY });

const message = await client.messages.create({
  model: "ewest/claude-haiku",
  max_tokens: 512,
  messages: [{ role: "user", content: "Say hello in five words." }],
});
for (const block of message.content) if (block.type === "text") console.log(block.text);

```

## Streaming and tools

`messages.stream()` yields the text as it arrives. Tools use Anthropic's format (`input_schema`); the answer contains `tool_use` blocks, and you send each result back as a `tool_result` block in the next user message.

Python:

```python
import os
import anthropic

# No /v1 on the base URL: the SDK adds /v1/messages itself.
client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"])

# Streaming: print the answer as it arrives.
with client.messages.stream(
    model="ewest/claude-haiku",
    max_tokens=512,
    messages=[{"role": "user", "content": "Write one sentence about the sea."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
print()

# Tool calling: the model asks for get_weather, your code runs it.
message = client.messages.create(
    model="ewest/claude-haiku",
    max_tokens=512,
    tools=[{
        "name": "get_weather",
        "description": "Current weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    }],
    messages=[{"role": "user", "content": "What is the weather in Paris?"}],
)
for block in message.content:
    if block.type == "tool_use":
        print("tool call:", block.name, block.input)

```

TypeScript:

```javascript
import Anthropic from "@anthropic-ai/sdk";

// No /v1 on the base URL: the SDK adds /v1/messages itself.
const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY });

// Streaming: print the answer as it arrives.
const stream = client.messages.stream({
  model: "ewest/claude-haiku",
  max_tokens: 512,
  messages: [{ role: "user", content: "Write one sentence about the sea." }],
});
stream.on("text", (text) => process.stdout.write(text));
await stream.finalMessage();
console.log();

// Tool calling: the model asks for get_weather, your code runs it.
const message = await client.messages.create({
  model: "ewest/claude-haiku",
  max_tokens: 512,
  tools: [
    {
      name: "get_weather",
      description: "Current weather for a city",
      input_schema: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
    },
  ],
  messages: [{ role: "user", content: "What is the weather in Paris?" }],
});
for (const block of message.content) {
  if (block.type === "tool_use") console.log("tool call:", block.name, JSON.stringify(block.input));
}

```

## Troubleshooting

API errors raise `APIStatusError` with the status and body, in Anthropic's own error envelope (`{"type": "error", "error": {"type", "message"}}`), so the library's typed errors (`AuthenticationError`, `NotFoundError`, `RateLimitError`, ...) work as with Anthropic. The [Errors](https://ewest.ai/docs/errors#messages-envelope) page maps the types and explains each code.

- `404` on every request: the base URL ends in `/v1`. Use `https://api.ewest.ai`.
- `401`: the key is missing, mistyped or revoked. Copy it again from [API keys](https://ewest.ai/keys).
- `404` with `model_not_found`: the model name needs the `ewest/` prefix (`ewest/claude-haiku`, not `claude-haiku`) and must be in [Models](https://ewest.ai/docs/models).
- `403`: your key is not allowed to use that model; `402`: the key's budget is used up. See [Errors](https://ewest.ai/docs/errors).

Python:

```python
import os
import anthropic

# No /v1 on the base URL: the SDK adds /v1/messages itself.
client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"])

try:
    message = client.messages.create(
        model="ewest/claude-haiku",
        max_tokens=512,
        messages=[{"role": "user", "content": "Say hello in five words."}],
    )
    print(message.content[0].text)
except anthropic.APIStatusError as e:
    # 401 key, 402 budget, 403 model not allowed for this key, 404 unknown model id.
    print(e.status_code, e.body)
    print("trace:", e.response.headers.get("x-request-id"))

```

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

Source: https://ewest.ai/docs/guides/anthropic-sdk
