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

# JavaScript SDK

> 在 Node.js 中使用官方 OpenAI JavaScript SDK 调用 Yelu Chat、Responses 与流式输出。

官方 OpenAI JavaScript/TypeScript SDK 只需修改 API Key 与 Base URL 即可使用 Yelu。SDK 应运行在可信服务端，而不是浏览器 Bundle 中。

## 安装

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npm install openai
```

## 配置客户端

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.YELU_API_KEY,
  baseURL: 'https://api.yelu.ai/v1',
  timeout: 60_000,
  maxRetries: 2,
});
```

## Chat Completions

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const completion = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [
    { role: 'system', content: '回答简洁。' },
    { role: 'user', content: '解释向量搜索。' },
  ],
  max_completion_tokens: 200,
});
console.log(completion.choices[0].message.content);
console.log(completion.usage);
```

## Responses

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await client.responses.create({
  model: 'gpt-4o-mini',
  instructions: '面向软件工程师回答。',
  input: '什么是背压？',
  max_output_tokens: 200,
});
console.log(response.output_text);
```

## 流式输出

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const stream = await client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: '写一段简短发布说明。' }],
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}
```

## 错误处理

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
try {
  await client.models.list();
} catch (error) {
  if (error instanceof OpenAI.AuthenticationError) console.error('检查 YELU_API_KEY');
  else if (error instanceof OpenAI.RateLimitError) console.error('退避后再重试');
  else if (error instanceof OpenAI.APIConnectionError) console.error('网络或 TLS 失败', error.cause);
  else if (error instanceof OpenAI.APIError) console.error(error.status, error.code, error.message);
  else throw error;
}
```

<Warning>即使 SDK 可以被浏览器工具打包，也不要把 Yelu Key 发送给用户。浏览器应调用你自己的已鉴权后端。</Warning>
