Node.js 调用示例
本页面提供 Node.js 调用 51API 的完整示例。
环境准备
安装依赖
bash
npm install openai1
bash
yarn add openai1
bash
pnpm add openai1
配置 API Key
推荐使用环境变量存储 API Key:
bash
export NEWAPI_API_KEY="sk-你的密钥"1
bash
set NEWAPI_API_KEY=sk-你的密钥1
powershell
$env:NEWAPI_API_KEY="sk-你的密钥"1
方式一:使用 OpenAI SDK(推荐)
基础对话
javascript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
async function chat() {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: '你是一个有帮助的助手。' },
{ role: 'user', content: '你好!' }
]
});
console.log(response.choices[0].message.content);
}
chat();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
javascript
const OpenAI = require('openai');
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
async function chat() {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: '你是一个有帮助的助手。' },
{ role: 'user', content: '你好!' }
]
});
console.log(response.choices[0].message.content);
}
chat();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
流式输出
javascript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
async function streamChat() {
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: '讲一个简短的故事' }],
stream: true
});
process.stdout.write('AI: ');
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
console.log(); // 换行
}
streamChat();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
多轮对话
javascript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
// 保存对话历史
const messages = [
{ role: 'system', content: '你是一个友好的助手。' }
];
async function chat(userInput) {
// 添加用户消息
messages.push({ role: 'user', content: userInput });
// 发送请求
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: messages
});
// 获取回复
const reply = response.choices[0].message.content;
// 保存到历史
messages.push({ role: 'assistant', content: reply });
return reply;
}
// 多轮对话示例
async function main() {
console.log('AI:', await chat('我叫小明'));
console.log('AI:', await chat('我刚才说我叫什么?'));
}
main();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
方式二:使用 fetch API
适合不想安装额外依赖的场景。
基础请求
javascript
const API_KEY = process.env.NEWAPI_API_KEY;
const API_URL = 'https://www.51api.org/v1/chat/completions';
async function chat(message) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }]
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
// 使用示例
chat('你好!').then(console.log).catch(console.error);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
流式请求
javascript
const API_KEY = process.env.NEWAPI_API_KEY;
const API_URL = 'https://www.51api.org/v1/chat/completions';
async function streamChat(message) {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'gpt-4o',
messages: [{ role: 'user', content: message }],
stream: true
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
process.stdout.write('AI: ');
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data:')) {
const data = line.slice(5).trim();
if (data === '[DONE]') break;
try {
const json = JSON.parse(data);
const content = json.choices[0]?.delta?.content || '';
process.stdout.write(content);
} catch (e) {
// 忽略解析错误
}
}
}
}
console.log(); // 换行
}
streamChat('讲个笑话');1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
方式三:使用 axios
javascript
import axios from 'axios';
const API_KEY = process.env.NEWAPI_API_KEY;
const API_URL = 'https://www.51api.org/v1/chat/completions';
async function chat(message) {
const response = await axios.post(API_URL, {
model: 'gpt-4o',
messages: [{ role: 'user', content: message }]
}, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
}
});
return response.data.choices[0].message.content;
}
// 使用示例
chat('你好!').then(console.log).catch(console.error);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
高级示例:Express API 服务
创建一个简单的 API 服务,转发请求到 51API。
javascript
import express from 'express';
import OpenAI from 'openai';
const app = express();
app.use(express.json());
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
// 普通对话接口
app.post('/api/chat', async (req, res) => {
try {
const { message, model = 'gpt-4o' } = req.body;
const response = await client.chat.completions.create({
model,
messages: [{ role: 'user', content: message }]
});
res.json({
success: true,
reply: response.choices[0].message.content,
usage: response.usage
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// 流式对话接口
app.post('/api/chat/stream', async (req, res) => {
try {
const { message, model = 'gpt-4o' } = req.body;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const stream = await client.chat.completions.create({
model,
messages: [{ role: 'user', content: message }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
if (content) {
res.write(`data: ${JSON.stringify({ content })}\n\n`);
}
}
res.write('data: [DONE]\n\n');
res.end();
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
图片分析示例
javascript
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
async function analyzeImage(imageUrl) {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: '这张图片里有什么?' },
{
type: 'image_url',
image_url: { url: imageUrl }
}
]
}
],
max_tokens: 300
});
return response.choices[0].message.content;
}
// 使用示例
analyzeImage('https://example.com/image.jpg')
.then(console.log)
.catch(console.error);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
TypeScript 支持
OpenAI SDK 原生支持 TypeScript:
typescript
import OpenAI from 'openai';
import type { ChatCompletionMessageParam } from 'openai/resources/chat';
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1'
});
async function chat(messages: ChatCompletionMessageParam[]): Promise<string> {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages
});
return response.choices[0].message.content || '';
}
// 使用示例
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: '你是一个助手' },
{ role: 'user', content: '你好!' }
];
chat(messages).then(console.log);1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
常见问题
报错 "ECONNREFUSED" 或连接超时
- 检查网络连接
- 确认 API 地址正确:
https://www.51api.org/v1 - 尝试增加超时时间:
javascript
const client = new OpenAI({
apiKey: process.env.NEWAPI_API_KEY,
baseURL: 'https://www.51api.org/v1',
timeout: 60000 // 60 秒超时
});1
2
3
4
5
2
3
4
5
报错 "Model not found"
检查你的令牌分组是否正确。详见 常见问题。
其他问题
查看 完整常见问题
