Navigator
- 一、Python
- 1.1 最简单的单次问答
- 1.2 连续对话
- 1.3 GUI界面
首先简单说一下:调用openAI的模型,需要申请API key,用于鉴权和计费嘛。你注册之后有18美元体验金,3个月有效期。
更多信息可以看我上一篇文章,或者官网文档。
API key不能暴露于网络,否则要重新申请(不影响什么),比如你把你的含有key的代码同步到github仓库,很快这个key就失效了。
使用API请求后,完整的回复是这样的json结构数据:我们只需要解析出 choices 的 text 即可。其中 usage 显示了本次请求使用的token数量信息。
当你发现回答内容或格式不正确时,就可以打印全部恢复,看看问题出在什么地方。
You: hello
GPT-3: {
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"text": "\n\nHi there! How can I help you?"
}
],
"created": 1677321094,
"id": "cmpl-6nm7ywWcF6tQYhrKkPA6mOIvi9OEY",
"model": "text-davinci-003",
"object": "text_completion",
"usage": {
"completion_tokens": 11,
"prompt_tokens": 1,
"total_tokens": 12
}
}
此外,即使是GPT-3的API,使用的人也不少(毕竟chatGPT API没出来,不少人拿这个骗人),所以有时候并不会秒响应。
模型非常适合写文本以及算法类型的代码(毕竟用了github数十亿开源代码来训练),但回答内容的正确性需要用户判断(尽管大多数时间是可用、正确的)。
一、Python
1.1 最简单的单次问答
很简单,但不支持连续对话,你每一次都要把你的需求描述完整。
主要的请求如下:
response = openai.Completion.create(
model= self.model,
prompt=prompt,
temperature=0,
max_tokens=1500,
frequency_penalty=0.2,
presence_penalty=0.15,
)
直接打印就是完整的返回数据,我们只打印对话内容即可:
print(self.bot, response["choices"][0]["text"].strip())
完整代码:
import openai
openai.api_key = "你的key"
class Chat_bot:
def __init__(self,model):
self.user = "\nYou: "
self.bot = "GPT-3: "
self.model = model
def Generate(self):
while True:
prompt = input(self.user)
if prompt == 'exit':
break
else:
try:
response = openai.Completion.create(
model= self.model,
prompt=prompt,
temperature=0,
max_tokens=1500,
frequency_penalty=0.2,
presence_penalty=0.15,
)
print(self.bot, response["choices"][0]["text"].strip())
except Exception as exc:
print(exc)
if __name__ =='__main__':
bot = Chat_bot('text-davinci-003')
bot.Generate()
运行示例:
1.2 连续对话
先看效果:
实现方式:将最新几次的对话保存下来,作为prompt输入即可。这里最新取了5次对话,太大的话会超过token数量限制。
另外用变量将问答保存下来,待对话结束保存下来即可。
完整示例:
import openai
import time
from pathlib import Path
openai.api_key = "你的key"
class Chat_bot:
def __init__(self,model):
self.user = "\nYou: "
self.bot = "GPT-3: "
self.model = model
self.question_list = []
self.answer_list = []
self.text = ''
self.turns = []
self.last_result = ''
def dialogue_save(self):
timestamp = time.strftime("%Y%m%d-%H%M-%S", time.localtime())
file_name = 'output/Chat_' + timestamp + '.md'
f = Path(file_name)
f.parent.mkdir(parents=True, exist_ok=True)
with open(file_name, "w", encoding="utf-8") as f:
for q, a in zip(self.question_list, self.answer_list):
f.write(f"You: {q}\nGPT-3: {a}\n\n")
print("对话内容已保存到文件中: " + file_name)
def Generate(self):
print('\n请开始你们的对话,以exit结束。')
while True:
question = input(self.user)
self.question_list.append(question)
prompt = self.bot + self.text + self.user + question
if question == 'exit':
break
else:
try:
response = openai.Completion.create(
model= self.model,
prompt=prompt,
temperature=0,
max_tokens=1500,
frequency_penalty=0.2,
presence_penalty=0.15,
)
result = response["choices"][0]["text"].strip()
result = result[result.index('G'):]
self.answer_list.append(result)
self.last_result = result
self.turns += [question] + [result]
if len(self.turns) <= 10:
self.text = " ".join(self.turns)
else:
self.text = " ".join(self.turns[-10:])
print(result)
except Exception as exc:
print(exc)
self.dialogue_save()
if __name__ =='__main__':
bot = Chat_bot('text-davinci-003')
bot.Generate()
1.3 GUI界面
使用tkinter简单写一个,运行效果如下:
代码示例:
import openai
import tkinter as tk
openai.api_key = "你的key"
def window_set(root, width, height):
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 5)
root.geometry(size)
root.update()
root = tk.Tk()
root.title("OpenAI Text-Davinci-003")
sw=root.winfo_screenwidth()
sh=root.winfo_screenheight()
window_set(root,800,500)
root.resizable(False, False)
input_field = tk.Text(root,font=("SimSun", 12),wrap='word',bg='#A1CBD1')
input_field.place(x=0, y=0,width=700,height=50)
response_field = tk.Text(root,font=("SimSun", 12),bg='black',fg='orange',wrap='word')
response_field.place(x=0, y=50,width=800,height=450)
def send_input():
input_text = input_field.get("1.0",'end')
response_field.insert(tk.END, '\n\nYou:' + input_text)
response = openai.Completion.create(
model='text-davinci-003',
prompt=input_text,
temperature=0,
max_tokens=1500,
frequency_penalty=0.2,
presence_penalty=0.15,
)
result = response['choices'][0]['text'].strip()
response_field.insert(tk.END,'GPT-3:'+ result)
send_button = tk.Button(root, font=("SimSun", 12),text="发送", command=send_input,bg='#FCC09C')
send_button.place(x=700, y=0,width=100,height=50)
root.mainloop()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)