微信小程序接入chatgpt智能问答

1,409 阅读2分钟

文章目录

  • 接入流程介绍
  • Api key的获取
  • chatGPT 接口调用以及python实例
  • 小程序端
  • 运行效果

接入流程介绍

在本文中,我们将介绍如何将 智能问答机器人ChatGPT 集成到您的微信小程序中,并使用自定义 API Key 进行访问。我们还将展示如何使用 Python 代码调用 OpenAI 接口,从而实现与 ChatGPT 的交互。

image.png

Api key的获取

首先需要去openai官网注册账号,注册账号后就会看到生成apikey的按钮了,直接生成一个复制出来即可。

chatGPT 接口调用以及python实例

接口请求地址是https://api.openai.com/v1/completions
我们需要在接口的请求头中加入Authorization: YOUR_API_KEY进行身份校验,YOUR_API_KEY即上一步中我们申请的内容。
POST请求如下参数

{
  "model": "text-davinci-003",
  "prompt": "Say this is a test",
  "max_tokens": 7,
  "temperature": 0,
  "top_p": 1,
  "n": 1,
  "stream": false,
  "logprobs": null,
  "stop": "\n"
}

prompt即我们的输入内容,其他参数说明官方文档都有,可以去查阅一下,这里不做过多说明。
有了这些我们就可以直接发起请求调用了。当然,官方还提供了openai的python库和node库。这里我们以Python为例展示下。


import openai

# Define OpenAI API key 
openai.api_key = "YOUR_API_KEY"

# Set up the model and prompt
model_engine = "text-davinci-003"
prompt = "Once upon a time, in a land far, far away, there was a princess who..."

# Generate a response
completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

response = completion.choices[0].text
print(response)

小程序端

由于openai的网络原因,所以我们要在自己的服务器启动接口调用服务。用腾讯云服务器的请求是发不出去的,所以这里建议有条件的可以自己搭建内网穿透,或者使用aws,google cloud等云服务。
这里为了使用方便,界面上提供了apikey的按钮,可以在输入框中输入自己的key后点击设置私有api,从而实现访问。因为当前免费接口只支持18$的额度。

<view class="container1" data-weui-theme="light">
  <view class="title">一颗程序树 智能问答</view>
  <view class="itemView">
    <view class="you">开始与ChatGPT的对话吧:</view>
    <input class="input1" type="text" name="content" placeholder="请输入你的问题或设置api" bindinput="getContent" value="{{content}}" />
    <view class="view_btn">
      <button class="loginBtn" type="primary" bindtap="loginBtnClick">发送</button>
      <button class="loginBtn" type="primary" bindtap="resetBtnClick">清除</button>
    </view>
    <view class="use-own-api">
      <button class="set-api-btn" bindtap="inputApi">设置私有API</button>
    </view>

  </view>
  <view wx:for="{{messages}}" wx:key="index" class="chat-messages">
    <view slot="title" class="d-flex align-items-center">
      <image class="avatar-image border-radius-lg" src="{{item.name=='chatgpt'?robotImg:userInfo.avatarUrl}}"></image>
    </view>
    <view class="chat-bubble">
      <text class="chat-name">{{item.name}} - {{item.currentDate}}</text>
      <text class="chat-content {{item.type}}" bindtap="copyContent" data-copied="{{item.content}}">{{item.content}}</text>
    </view>
  </view>
  <view class="bottom">
    <ad unit-id="adunit-fca6e9113418814f" style="position: relative; left: -1rpx; top: 423rpx"></ad>
  </view>

</view>