chatgpt-api 是一款针对 OpenAI ChatGPT 的非官方 Node.js 封装库,内置 TypeScript 类型定义。它摆脱了对浏览器破解的依赖,直接利用泄露出的 OpenAI 官方 ChatGPT 后台模型进行交互。

推荐:使用 NSDT场景设计器 快速搭建 3D场景。
✨你可以使用它开始构建由 ChatGPT 支持的项目,例如聊天机器人、网站等…
import { ChatGPTAPI } from 'chatgpt'
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY
})
const res = await api.sendMessage('Hello World!')
console.log(res.text)
建议升级至 chatgpt@latest(至少 v4.0.0)。相较于旧版,新版本更加轻量且稳定,同时解决了 IP 限制和速率控制的问题。

1、安装chatgpt-api
确保运行环境为 node >= 18 以原生支持 fetch(若使用 node >= 14 需额外安装 fetch polyfill)。
通过以下命令安装 chatgpt-api:
npm install chatgpt
2、chatgpt-api使用方法
首先注册并获取 OpenAI API 密钥,将其存储于环境变量中。
以下是简单的一次性对话示例:
import { ChatGPTAPI } from 'chatgpt'
async function example() {
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY
})
const res = await api.sendMessage('Hello World!')
console.log(res.text)
}
若需进行持续多轮对话,需传递 parentMessageid 和 conversationid:
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
// send a message and wait for the response
let res = await api.sendMessage('What is OpenAI?')
console.log(res.text)
// send a follow-up
res = await api.sendMessage('Can you expand on that?', {
conversationId: res.conversationId,
parentMessageId: res.id
})
console.log(res.text)
// send another follow-up
res = await api.sendMessage('What were we talking about?', {
conversationId: res.conversationId,
parentMessageId: res.id
})
console.log(res.text)
可通过 onProgress 处理程序实现流式响应:
const res = await api.sendMessage('Write a 500 word essay on frogs.', {
// print the partial response as the AI is "typing"
onProgress: (partialResponse) => console.log(partialResponse.text)
})
// print the full text at the end
console.log(res.text)
也可使用 timeoutMs 选项设置超时:
// timeout after 2 minutes (which will also abort the underlying HTTP request)
const response = await api.sendMessage(
'write me a really really long essay on frogs',
{
timeoutMs: 2 * 60 * 1000
}
)
如需查看发送至 OpenAI 完成 API 的详细信息,可在 ChatGPT API 构造函数中设置 debug: true 选项:
const api = new ChatGPTAPI({
apiKey: process.env.OPENAI_API_KEY,
debug: true
})
注意此处使用了反向工程得到的 promptPrefix 和 promptSuffix。你可以通过 sendMessage 的选项自定义这些参数:
const res = await api.sendMessage('what is the answer to the universe?', {
promptPrefix: `You are ChatGPT, a large language model trained by OpenAI. You answer as concisely as possible for each response (e.g. don't be verbose). It is very important that you answer as concisely as possible, so please remember this. If you are generating a list, do not have too many items. Keep the number of items short.
Current date: ${new Date().toISOString()}\n\n`
})
系统会自动将先前消息附加到提示词中,并尝试优化可用 token(默认为 4096)。
在 CommonJS 环境中可使用动态导入:
async function example() {
// To use ESM in CommonJS, you can use a dynamic import
const { ChatGPTAPI } = await import('chatgpt')
const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY })
const res = await api.sendMessage('Hello World!')
console.log(res.text)
}
完整的使用文档可在此处查看。
3、使用演示程序
要运行包含的演示:
- 克隆此仓库
- 安装 node.js 依赖
- 在 .env 中设置 OPENAI_API_KEY
运行仓库中包含的基本演示程序:
npx tsx demos/demo.ts

运行仓库中包含的显示进度处理的演示程序:
npx tsx demos/demo-on-progress.ts
上述演示使用 sendMessage 可选的 onProgress 参数接收中间结果,模拟 ChatGPT “输入”效果。

运行仓库中包含的多轮对话演示程序:
npx tsx demos/demo-conversation.ts

仓库中的持久性演示展示了如何在 Redis 中存储消息以实现持久化:
npx tsx demos/demo-conversation.ts
任何 keyv 适配器均支持消息持久化,如需不同存储/检索方式可进行覆盖。
请注意,默认情况下消息仅存储在内存中。若需记住当前 Node.js 进程范围之外的先前对话上下文,必须启用消息持久化。
到此这篇关于chatgpt-api使用指南【官方泄露版】的文章就介绍到这了,更多相关chatgpt-api使用内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!