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

# Node.js 基础对话

> Node.js 使用 openai 包接入 Crazyrouter

> 更新日期：2026-06-06

## 安装

```bash theme={null}
npm install openai
```

## 基础对话

```javascript theme={null}
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-xxx',
  baseURL: 'https://api.crazyrouter.com/v1',
});

async function main() {
  const response = await client.chat.completions.create({
    model: 'gpt-5.5',
    messages: [
      { role: 'system', content: '你是一个有帮助的助手。' },
      { role: 'user', content: '用一句话解释什么是 Node.js' },
    ],
  });

  console.log(response.choices[0].message.content);
}

main();
```

## 流式输出

```javascript theme={null}
async function streamChat() {
  const stream = await client.chat.completions.create({
    model: 'gpt-5.5',
    messages: [{ role: 'user', content: '写一首关于编程的诗' }],
    stream: true,
  });

  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content || '';
    process.stdout.write(content);
  }
  console.log();
}

streamChat();
```

## 连续对话

```javascript theme={null}
const messages = [
  { role: 'system', content: '你是一个 JavaScript 专家。' },
];

async function chat(userInput) {
  messages.push({ role: 'user', content: userInput });

  const response = await client.chat.completions.create({
    model: 'gpt-5.5',
    messages,
  });

  const reply = response.choices[0].message.content;
  messages.push({ role: 'assistant', content: reply });
  return reply;
}

async function main() {
  console.log(await chat('什么是 Promise？'));
  console.log(await chat('和 async/await 有什么区别？'));
}

main();
```

## CommonJS 用法

```javascript theme={null}
const OpenAI = require('openai');

const client = new OpenAI({
  apiKey: 'sk-xxx',
  baseURL: 'https://api.crazyrouter.com/v1',
});

client.chat.completions
  .create({
    model: 'gpt-5.5',
    messages: [{ role: 'user', content: '你好' }],
  })
  .then((res) => console.log(res.choices[0].message.content));
```

<Note>
  以上示例默认使用 2026 年 3 月 23 日已在生产环境实测成功的 `gpt-5.5`。如果你需要切换模型，优先改成同样已验证的 `claude-opus-4-8` 或 `gemini-3.1-pro`，再根据场景继续扩展。
</Note>
