天天看點

chatgpt-api使用指南【node.js】

作者:新缸中之腦

chatgpt-api是 OpenAI ChatGPT 的非官方的 Node.js 包裝器。 包括 TS 類型定義。 chatgpt-api不再需要任何浏覽器破解——它使用洩露出來的OpenAI官方ChatGPT 在背景使用的模型。

chatgpt-api使用指南【node.js】
推薦:使用 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 問題或速率限制。

chatgpt-api使用指南【node.js】

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           
chatgpt-api使用指南【node.js】

運作倉庫中包含的顯示進度處理的示範程式:

npx tsx demos/demo-on-progress.ts           

上面這個示範使用 sendMessage可選的 onProgress 參數以接收中間結果,看起來就像 ChatGPT 正在“輸入”。

chatgpt-api使用指南【node.js】

運作倉庫中包含的多輪對話示範程式:

npx tsx demos/demo-conversation.ts           
chatgpt-api使用指南【node.js】

倉庫中的持久性示範展示了如何在 Redis 中存儲消息以實作持久化:

npx tsx demos/demo-conversation.ts           

任何 keyv 擴充卡都支援消息的持久化,如果你想使用不同的方式存儲/檢索消息,則可以進行覆寫。

請注意,需要持久化消息來記住目前 Node.js 程序範圍之外的先前對話的上下文,因為預設情況下,我們僅将消息存儲在記憶體中。

原文連結:http://www.bimant.com/blog/chatgpt-api-npm/

繼續閱讀