文章目录
- 一、安装 Node.js 22+
- 二、初始化项目与安装依赖
-
- 1. 新建项目文件夹,终端进入目录,执行初始化命令:
- 2. 安装核心依赖:
- 三、基础配置(关键步骤)
-
- 1. 配置 OpenAI 库
- 2. 配置 Vercel AI SDK
- 四、运行测试
一、安装 Node.js 22+
二、初始化项目与安装依赖
1. 新建项目文件夹,终端进入目录,执行初始化命令:
npm init -y # 快速生成 package.json
2. 安装核心依赖:
# OpenAI Node.js 库(官方最新版)
npm install openai@latest
# Vercel AI SDK(含基础工具链)
npm install ai@latest
三、基础配置(关键步骤)
1. 配置 OpenAI 库
- 在项目根目录创建 .env 文件,添加 API 密钥(需提前在 OpenAI 官网获取):
OPENAI_API_KEY=your-api-key-here # 替换为真实密钥
- 基础使用示例(创建 index.js):
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// 测试调用(示例:生成文本)
async function testOpenAI() {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: "Hello World" }]
});
console.log(response.choices[0].message.content);
}
testOpenAI();
2. 配置 Vercel AI SDK
- 无需额外密钥配置(依赖 OpenAI 密钥),基础流式调用示例(修改 index.js):
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
async function testVercelAI() {
const result = await streamText({
model: openai('gpt-3.5-turbo'),
prompt: "Hello World"
});
// 流式输出结果
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}
}
testVercelAI();
四、运行测试
"scripts": { "start": "node -r dotenv/config index.js" }
完整的项目目录结构 和 调试常见报错


