JavaScript SDK
安装
bash
npm install openaiNode.js 用法
javascript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.BEESAI_API_KEY,
baseURL: 'https://beesai.cn/v1',
});
async function main() {
const completion = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: '你好,BeesAI!' }],
});
console.log(completion.choices[0].message.content);
}
main();浏览器端用法(fetch)
⚠️ 安全提示:不要在前端暴露 API Key。建议通过后端代理调用。
javascript
async function chat(message) {
const response = await fetch('https://your-proxy.com/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
const data = await response.json();
return data.choices[0].message.content;
}流式输出
javascript
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: '写一首短诗' }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}