> ## Documentation Index
> Fetch the complete documentation index at: https://docs.arouter.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js / TypeScript

> 透過 OpenAI、Anthropic 或 ARouter Node.js SDK 使用 ARouter。

## OpenAI SDK

[OpenAI Node.js SDK](https://github.com/openai/openai-node) 可直接使用。

### 安裝

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install openai
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add openai
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add openai
    ```
  </Tab>
</Tabs>

### 基礎用法

```typescript theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.arouter.ai/v1",
  apiKey: "lr_live_xxxx",
});

const response = await client.chat.completions.create({
  model: "openai/gpt-5.4",
  messages: [{ role: "user", content: "Hello!" }],
});
console.log(response.choices[0].message.content);
```

### 多 Provider

```typescript theme={null}
// 透過 OpenAI SDK 使用 Anthropic
const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4.6",
  messages: [{ role: "user", content: "Hello!" }],
});

// 透過 OpenAI SDK 使用 DeepSeek
const response = await client.chat.completions.create({
  model: "deepseek/deepseek-v3.2",
  messages: [{ role: "user", content: "Hello!" }],
});
```

### 串流輸出

```typescript theme={null}
const stream = await client.chat.completions.create({
  model: "openai/gpt-5.4",
  messages: [{ role: "user", content: "寫一首詩。" }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) process.stdout.write(content);
}
```

***

## Anthropic SDK

[Anthropic Node.js SDK](https://github.com/anthropics/anthropic-sdk-typescript) 可原生使用。

### 安裝

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @anthropic-ai/sdk
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @anthropic-ai/sdk
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @anthropic-ai/sdk
    ```
  </Tab>
</Tabs>

### 基礎用法

```typescript theme={null}
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  baseURL: "https://api.arouter.ai",
  apiKey: "lr_live_xxxx",
});

const message = await client.messages.create({
  model: "claude-sonnet-4.6",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Hello!" }],
});
console.log(message.content[0].text);
```

### 串流輸出

```typescript theme={null}
const stream = client.messages.stream({
  model: "claude-sonnet-4.6",
  max_tokens: 1024,
  messages: [{ role: "user", content: "告訴我一個故事。" }],
});

for await (const event of stream) {
  if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
    process.stdout.write(event.delta.text);
  }
}
```

***

## ARouter SDK

官方 `@arouter/sdk` 提供 key 管理和用量追蹤等額外功能。

### 安裝

<Tabs>
  <Tab title="npm">
    ```bash theme={null}
    npm install @arouter/sdk
    ```
  </Tab>

  <Tab title="yarn">
    ```bash theme={null}
    yarn add @arouter/sdk
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash theme={null}
    pnpm add @arouter/sdk
    ```
  </Tab>
</Tabs>

### 對話補全

```typescript theme={null}
import { ARouter } from "@arouter/sdk";

const router = new ARouter({
  apiKey: "lr_live_xxxx",
  baseURL: "https://api.arouter.ai",
});

const response = await router.chatCompletion({
  model: "openai/gpt-5.4",
  messages: [{ role: "user", content: "Hello!" }],
});
console.log(response.choices[0].message.content);
```

### 串流輸出

```typescript theme={null}
const stream = await router.chatCompletionStream({
  model: "openai/gpt-5.4",
  messages: [{ role: "user", content: "寫一首俳句。" }],
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) process.stdout.write(content);
}
```

### Key 管理

使用管理密鑰（`lr_mgmt_`）建立和管理 API key。

```typescript theme={null}
const mgmt = new ARouter({
  apiKey: "lr_mgmt_xxxx",
  baseURL: "https://api.arouter.ai",
});

const key = await mgmt.createKey({
  name: "backend-service",
  allowed_providers: ["openai", "anthropic"],
  limit: 150,
  limit_reset: "monthly",
});
console.log("API Key:", key.key);

const keys = await mgmt.listKeys();
console.log("Keys:", keys.data);

await mgmt.updateKey(key.data.hash, { disabled: true });

await mgmt.deleteKey(key.data.hash);
```

### 錢包 JWT + x402 支付

擁有加密錢包的 AI 代理可透過 SIWx 驗證身分，並透過 x402 支付積分。
SDK 會快取錢包 JWT，並將其作為後續請求的 Bearer token。

#### EVM（Base）

```typescript theme={null}
import { ARouter, withX402EvmPayment } from "@arouter/sdk";
import { privateKeyToAccount } from "viem/accounts";

const signer = privateKeyToAccount(process.env.EVM_PRIVATE_KEY as `0x${string}`);

const client = withX402EvmPayment(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  signer,
);

const response = await client.chatCompletion({
  model: "openai/gpt-5.4",
  messages: [{ role: "user", content: "Hello" }],
});
```

#### Solana

```typescript theme={null}
import { ARouter, withX402SolanaPayment } from "@arouter/sdk";

const client = withX402SolanaPayment(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  solanaSigner,
  { address: solanaAddress, signMessage: (msg) => signEd25519(msg) },
);
```

#### 僅 SIWx（不自動支付）

```typescript theme={null}
import { ARouter, withSIWxAuth } from "@arouter/sdk";

const client = await withSIWxAuth(
  new ARouter({ baseURL: "https://api.arouter.ai", apiKey: "" }),
  { address: "0xYourAddress", signMessage: (msg) => signer.signMessage({ message: msg }) },
);
```

完整協議流程請參見 [x402 支付指南](/zh-Hant/guides/x402-payments)。
