通过web页面调用openAI API

ChatGPT大火后,国内不少人开始测试使用,但openAI做了地域限制,在中国区当前是没法使用openai的,刚好手里有海外的机器资源和手机号,注册了下openai的帐号,通过调用其API,实现了Text completion功能的测试。

一、注册及调用

注册openai站点帐户(打开 https://openai.com/api/ 页,右上角sign up注册,注册需海外手机号短信验证),打开 beta.openai.com/account/api-keys 页面获取api-key信息 ,见下图:

openai-apikey

API调用测试,这里使用是text-davinci-003模型,其他GPT3模型可以参考文档:https://platform.openai.com/docs/models/gpt-3

python测试代码如下:

[root@ecs-668b mnt]# cat chatgpttest.py
import openai

openai.api_key = "your api key"

def generate_response(prompt):
    model_engine = "text-davinci-003"
    prompt = (f"{prompt}")

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

    message = completions.choices[0].text
    return message.strip()

prompt = input("Enter your question: ")
response = generate_response(prompt)

print(response)

注意这里openai模块需要安装,其会有pandas等模块依赖。

执行测试结果如下:

二、web封装调用

想要实现的效果:通过谷歌或百度一样的搜索框,输入查询关键字,返回openai 调用后返回的结果。具体代码如下:

// 实现的几个文件
(base) [root@ecs-668b chat]# tree
.
├── demaon.sh
├── main.py
└── templates
    ├── index.html
    └── result.html

1 directory, 4 files

//通过flask框架简单实现API的调用,并通过模板文件渲染结果
(base) [root@ecs-668b chat]# cat main.py
from flask import Flask,jsonify,render_template,render_template_string,request
import requests,json
import openai

openai.api_key = "your api key"

app = Flask(__name__,template_folder='./templates')
@app.route('/')
def index():
    return render_template("index.html")
@app.route('/chatgpt', methods=['POST'])

def chatgpt():
  q = request.form['question']
  print(str(q))
  response = generate_response(str(q))
  #return response
  return render_template("result.html", question=q,result=response)
def generate_response(prompt):
    model_engine = "text-davinci-003"

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

    message = completions.choices[0].text
    return message.strip()

if __name__ == '__main__':
   app.run("0.0.0.0",port=80)
(base) [root@ecs-668b chat]#

//首页模板文件,输出搜索框,将输入结果传给flask处理
(base) [root@ecs-668b chat]# cat templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<style type="text/css">
.container {
                width: 500px;
                height: 50px;
                margin: 100px auto;
            }

            .parent {
                width: 100%;
                height: 42px;
                top: 4px;
                position: relative;
            }

            .parent>input:first-of-type {
                /*输入框高度设置为40px, border占据2px,总高度为42px*/
                width: 380px;
                height: 40px;
                border: 1px solid #ccc;
                font-size: 16px;
                outline: none;
            }

            .parent>input:first-of-type:focus {
                border: 1px solid #317ef3;
                padding-left: 10px;
            }

            .parent>input:last-of-type {
                /*button按钮border并不占据外围大小,设置高度42px*/
                width: 100px;
                height: 44px;
                position: absolute;
                background: #317ef3;
                border: 1px solid #317ef3;
                color: #fff;
                font-size: 16px;
                outline: none;
            }
</style>
</head>
<body>
   <div class="container">
        <form action="/chatgpt" method="post" class="parent">
        <input type="search" name="question" placeholder="请输入问题">
        <input type="submit" id="search" value="查询">
        </form>
    </div>
</body>
</html>
(base) [root@ecs-668b chat]#

//返回查询结果页,并在本页可以继续查询
(base) [root@ecs-668b chat]# cat templates/result.html
<!DOCTYPE html>
<html>
<head>
<style>
div {
  background-color: lightgrey;
  width: 500px;
  border: 15px solid green;
  padding: 150px;
  margin: 10px auto;
}
</style>
</head>
<body>

<h2 align="center">ChatGPT查询</h2>

<p align="center">您的问题是:<font color="#FF0000"><strong> {{ question }} </strong></font>,chatGPT查询结果如下:</p>

<div align="center">
{{ result }}
</div>

        <form action="/chatgpt" method="post"  align="center">
        <input type="text" name="question" placeholder="继续问问题">
        <input type="submit" id="search" value="查询">
        </form>

</body>
</html>
(base) [root@ecs-668b chat]#

//守护进程,避免程序挂掉
(base) [root@ecs-668b chat]# cat demaon.sh
#!/usr/bin/env bash

while true;do
process_number=`pgrep  python|wc -l`
if [ $process_number -lt 1 ];then
        echo “process java is not running”
        cd /mnt/chat
        python main.py >>out.log &
        sleep 10
fi
echo check
sleep 10
done

我们来看下执行结果,发现问同一个问题时,使用中文问和英文问给出的结果是不同的,其对中文的分词理解感觉不够好(估计没有使用结巴分词这类中文分词分析)。

chinese word ask

同样的问题,换成英文去问时,结果如下:

english-word-ask

发现一个给出的结果是湖北,一个给出的是广东。(不知道他这个是根据常住人口还是实际归属人口返回的结果)。

三、总结

这里只使用了openai的一个模块下的某一个小的模型进行了测试,官方提供的模型如下:

Models Description
GPT-3 A set of models that can understand and generate natural language
Codex Limited beta A set of models that can understand and generate code, including translating natural language to code
Content filter A fine-tuned model that can detect whether text may be sensitive or unsafe

每个模型下面又对应了不同算法,想要了解每个的细节或进行测试,可以通过官方页面:https://platform.openai.com/docs/models/overview 获取更多信息。

对于一些应用示例也可以参考官方的功能示例页面:openai examples 进行查看。

最后:由于仅仅只是测试目的,当前ask.361way.com 测试完成后,已进行下架处理。需要体验的同学,也可以使用https://chatgpt.sbaliyun.com/ 站点进行测试,只不过界面有些不同,都是使用的官方API。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注