Source: https://wiki.niceai.dev/guide/clients/anthropic-sdk

# Anthropic SDK 接入自定义 API

在 Anthropic 官方 SDK 中把 `base_url`（Python）或 `baseURL`（TypeScript）设为 `https://api.niceai.dev`，**不加 `/v1`**，`api_key` 填 NiceAI 密钥即可。

## 准备工作

1. 在 NiceAI 控制台「[API 密钥](https://niceai.dev/keys)」页面创建密钥，分组选择 **Claude**。
2. 把密钥存到环境变量 `NICEAI_API_KEY`。

## 安装与调用

**-group**

```python [Python]
# pip install anthropic
import os
import anthropic

client = anthropic.Anthropic(
    base_url="https://api.niceai.dev",
    api_key=os.environ["NICEAI_API_KEY"],
)

msg = client.messages.create(
    model="<模型名，见模型广场>",
    max_tokens=1024,
    messages=[{"role": "user", "content": "你好"}],
)
print(msg.content[0].text)
```

```ts [TypeScript]
// npm install @anthropic-ai/sdk
import Anthropic from '@anthropic-ai/sdk'

const client = new Anthropic({
  baseURL: 'https://api.niceai.dev',
  apiKey: process.env.NICEAI_API_KEY,
})

const msg = await client.messages.create({
  model: '<模型名，见模型广场>',
  max_tokens: 1024,
  messages: [{ role: 'user', content: '你好' }],
})
console.log(msg.content)
```



## 用环境变量切换

SDK 也会读取 `ANTHROPIC_BASE_URL` 和 `ANTHROPIC_API_KEY`：

**-group**

```bash [macOS / Linux]
export ANTHROPIC_BASE_URL="https://api.niceai.dev"
export ANTHROPIC_API_KEY="你的 NiceAI 密钥"
```

```powershell [Windows PowerShell]
$env:ANTHROPIC_BASE_URL = "https://api.niceai.dev"
$env:ANTHROPIC_API_KEY = "你的 NiceAI 密钥"
```



## 更多用法

- 请求头和参数说明：[Anthropic Messages 接口](https://wiki.niceai.dev/guide/api/anthropic-messages)
- 流式输出：[流式输出（SSE）](https://wiki.niceai.dev/guide/api/streaming)
- 工具调用：[工具调用（Function Calling）](https://wiki.niceai.dev/guide/api/tools)
- 提示词缓存：`cache_control` 写法与官方一致，原理见 [提示词缓存是怎么省钱的](https://wiki.niceai.dev/guide/tech/prompt-caching)

## 常见问题

### 404？

`base_url` 不要加 `/v1`，SDK 会自己拼接 `/v1/messages`。详见 [接口地址要不要加 /v1](https://wiki.niceai.dev/guide/v1-404)。

### 401 或 403？

检查密钥是否完整、分组是否为 Claude。

## 下一步

- [OpenAI SDK 接入](https://wiki.niceai.dev/guide/clients/openai-sdk)
- [Claude Code 接入](https://wiki.niceai.dev/guide/claude-code)
