Node.js AI 开发实战
# Node.js AI 开发实战 - 构建 AI Web 应用
---
一、环境准备
安装 Node.js
访问 Node.js 官网 下载 LTS 版本。
创建项目
mkdir ai-app cd ai-app npm init -y npm install express openai
---
二、基础 API 调用
OpenAI SDK
import OpenAI from 'openai';const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
async function chat(message) { const response = await client.chat.completions.create({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: message }] }); return response.choices[0].message.content; }
流式输出
async function chatStream(message) {
const stream = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: message }],
stream: true
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0].delta.content || '');
}
}
---
三、构建 API 服务
Express 服务
import express from 'express';const app = express(); app.use(express.json());
app.post('/chat', async (req, res) => { const { message } = req.body; const reply = await chat(message); res.json({ reply }); });
app.listen(3000, () => { console.log('AI API running on port 3000'); });
流式 API
app.post('/chat/stream', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
const stream = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: req.body.message }],
stream: true
});
for await (const chunk of stream) {
res.write(data: ${JSON.stringify(chunk)}\n\n);
}
res.end();
});
---
四、实战案例
1. 文档问答
async function answerQuestion(doc, question) {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 参考文档:${doc} },
{ role: 'user', content: question }
]
});
return response.choices[0].message.content;
}
2. 图片分析
async function analyzeImage(imageUrl, question) {
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{
role: 'user',
content: [
{ type: 'text', text: question },
{ type: 'image_url', image_url: { url: imageUrl } }
]
}]
});
return response.choices[0].message.content;
}
---
五、部署
PM2 部署
npm install -g pm2 pm2 start app.js --name ai-api pm2 save pm2 startup
---
作者:廖万里
本文链接:https://www.kkkliao.cn/?id=672 转载需授权!
版权声明:本文由廖万里的博客发布,如需转载请注明出处。



手机流量卡
免费领卡
号卡合伙人
产品服务
关于本站
