chatGPT二次开发调用方法

编程知识 更新时间:2023-04-25 15:05:57

       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传给sendMessageasconversationIdparentMessageId

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的能力构建一个新应用程序,可以结合于各行各业,提高效率。

 

更多推荐

chatGPT二次开发调用方法

本文发布于:2023-04-19 09:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/2b81c63489efd51a96ab3fdf867ef6a8.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   chatGPT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 87588文章数
  • 20129阅读数
  • 0评论数