chatGPT二次开发调用方法

ChatGPT 官方还没有正式公开 API,但是目前国内很多人使用各种方案来调用chatGPT,开发AI工具,用于获取客户或者订阅收费盈利。

下面是其中一种方案:

在 OpenAI 官网注册账号并获取 API Key。然后通过 pip 安装 OpenAI 库:

pip install openai

创建代码

通过调用 OpenAI API 来实现与 ChatGPT 的交互:

import openai

# 设置 API Key
openai.api_key = "your_api_key"

# 设置请求参数
model_engine = "text-davinci-002"
prompt = "如何用 Python 玩转 ChatGPT"

completions = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

# 获取 ChatGPT 的回复
message = completions.choices[0].text
print(message)

运行代码,观察 ChatGPT的响应:

另一种方案是通过无头浏览器获取session的方式编程调用ChatGPT接口

注册一个OpenAI账号,然后Node开发环境Node.js >= 18。这个是 OpenAI 围绕 ChatGPT 的Node.js 包装程序。

您可以使用它开始构建由 ChatGPT 支持的项目,例如聊天机器人、网站等...


12 月 11 日,OpenAI 添加了 Cloudflare 保护,这使得访问非官方 API 变得更加困难。

为了规避这些保护措施,我们添加了一个完全自动化的基于浏览器的解决方案,它在后台使用 Puppeteer 和 CAPTCHA 破解器。🔥

安装

npm install chatgpt puppeteer

puppeteer是一个可选的对等依赖项,用于通过 自动绕过 Cloudflare 保护getOpenAIAuth。主要的 API 包装器fetch直接使用。

用法

import { ChatGPTAPIBrowser } from chatgpt

async function example() {
  // use puppeteer to bypass cloudflare (headful because of captchas)
  const api = new ChatGPTAPIBrowser({
    email: process.env.OPENAI_EMAIL,//openAI账号
    password: process.env.OPENAI_PASSWORD//密码
  })

  await api.initSession()

  const result = await api.sendMessage(Hello World!)
  console.log(result.response)
}

ChatGPT 响应的格式默认为 markdown。如果你想使用纯文本,你可以使用:

const api = new ChatGPTAPIBrowser({ email, password, markdown: false })

如果要跟踪对话,在result对象中使用conversationIdand ,分别messageId传给sendMessageasconversationId和parentMessageId。

const api = new ChatGPTAPIBrowser({ email, password })
await api.initSession()

// send a message and wait for the response
let res = await api.sendMessage(What is OpenAI?)
console.log(res.response)

// send a follow-up
res = await api.sendMessage(Can you expand on that?, {
  conversationId: res.conversationId,
  parentMessageId: res.messageId
})
console.log(res.response)

// send another follow-up
// send a follow-up
res = await api.sendMessage(What were we talking about?, {
  conversationId: res.conversationId,
  parentMessageId: res.messageId
})
console.log(res.response)

有时,ChatGPT 会在开始响应之前挂起很长一段时间。这可能是由于速率限制,也可能是由于 OpenAI 的服务器过载。

为了缓解这些问题,您可以像这样添加超时:

// timeout after 2 minutes (which will also abort the underlying HTTP request)
const response = await api.sendMessage(this is a timeout test, {
  timeoutMs: 2 * 60 * 1000
})

代理问题

目前该库暂不支持设置代理,所以没法在国内主机运行,只能在国外VPS上部署。

以上两种方案目前都验证过可以实现利用chatGPT的能力构建一个新应用程序,可以结合于各行各业,提高效率。

经验分享 程序员 微信小程序 职场和发展