|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
在第3讲里面. 通过colpletion接口, 实现一个聊天机器人 |
|
我们采用的是自己将整个对话拼接起来,将整个上下文都发送给 OpenAI的 Completion API 的方式。 |
|
因为 ChatGPT 的火热,OpenAI 放出了一个直接可以进行对话聊天的接口。 |
|
这个接口叫做 ChatCompletion,对应的模型叫做 gpt3.5-turbo,不但用起来更容易了,速度还快,而且价格也是我们之前使用的 text-davinci-003 的十分之一, |
|
可谓是物美价廉了。 |
|
|
|
|
|
|
|
|
|
|
|
import openai |
|
openai.ChatCompletion.create( |
|
model="gpt-3.5-turbo", |
|
messages=[ |
|
{"role": "system", "content": "You are a helpful assistant."}, |
|
{"role": "user", "content": "Who won the world series in 2020?"}, |
|
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, |
|
{"role": "user", "content": "Where was it played?"} |
|
] |
|
) |
|
|
|
|
|
|
|
|
|
|
|
需要传入的参数,从一段Prompt 变成了一个数组,数组的每个元素都有 role 和 content 两个字段 |
|
role 这个字段一共有三个角色可以选择,其中 system 代表系统,user 代表用户,而assistant 则代表 AI 的回答 |
|
|
|
|
|
|
|
|
|
|
|
当 role 是 system 的时候,content 里面的内容代表我们给 AI 的一个指令.是告诉AI 应该怎么回答用户的问题 |
|
比如我们希望 AI 都通过中文回答我们就可以在content 里面写 "你只能用中文回答" |
|
|
|
而当 role 是 user 或者 assistant 的时候 |
|
content 里面的内容就代表用户和ai对话的内容 |
|
和我们第 03 讲里做的聊天机器人一样,你需要把历史上的对话一起发送给OpenAI 的接口,它才能有理解整个对话的上下文的能力。 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import openai |
|
import os |
|
|
|
OPENAI_API_KEY='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' |
|
openai.api_key = OPENAI_API_KEY |
|
|
|
class Conversation: |
|
|
|
|
|
def __init__(self, prompt, num_of_round): |
|
self.prompt = prompt |
|
self.num_of_round = num_of_round |
|
self.messages = [] |
|
self.messages.append({"role": "system", "content": self.prompt}) |
|
|
|
|
|
|
|
|
|
def ask(self, question): |
|
try: |
|
self.messages.append( {"role": "user", "content": question}) |
|
response = openai.ChatCompletion.create( |
|
model="gpt-3.5-turbo", |
|
messages=self.messages, |
|
temperature=0.5, |
|
max_tokens=2048, |
|
top_p=1, |
|
) |
|
except Exception as e: |
|
print(e) |
|
return e |
|
|
|
message = response["choices"][0]["message"]["content"] |
|
self.messages.append({"role": "assistant", "content": message}) |
|
|
|
if len(self.messages) > self.num_of_round*2 + 1: |
|
del self.messages[1:3] |
|
return message |
|
|
|
|
|
|
|
|
|
|
|
prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求: |
|
1. 你的回答必须是中文 |
|
2. 回答限制在100个字以内""" |
|
conv1 = Conversation(prompt, 3) |
|
question1 = "你是谁?" |
|
print("User : %s" % question1) |
|
print("Assistant : %s\n" % conv1.ask(question1)) |
|
|
|
question2 = "请问鱼香肉丝怎么做?" |
|
print("User : %s" % question2) |
|
print("Assistant : %s\n" % conv1.ask(question2)) |
|
|
|
question3 = "那蚝油牛肉呢?" |
|
print("User : %s" % question3) |
|
print("Assistant : %s\n" % conv1.ask(question3)) |
|
|
|
|
|
|
|
|
|
|
|
question4 = "我问你的第一个问题是什么?" |
|
print("User : %s" % question4) |
|
print("Assistant : %s\n" % conv1.ask(question4)) |
|
|
|
|
|
|
|
|
|
|
|
如果我们重新再问一遍“我问你的第一个问题是什么”,你会发现回答变了。 |
|
上一轮已经是第四轮了,而我们设置记住的 num_of_round 是 3。 |
|
在上一轮的问题回答完了之后,第一轮的关于“你是谁”的问答,被我们从 ChatGPT 的对话历史里去掉了。 |
|
所以这个时候,它会告诉我们,第一个问题是“鱼香肉丝怎么做”。 |
|
|
|
|
|
|
|
|
|
|
|
question5 = "我问你的第一个问题是什么?" |
|
print("User : %s" % question5) |
|
print("Assistant : %s\n" % conv1.ask(question5)) |
|
|
|
|
|
|
|
|
|
|
|
ChatGPT 的对话模型用起来很方便,但是也有一点需要注意。就是在这个需要传送大量上下文的情况下,这个费用会比你想象的高。 |
|
OpenAI 是通过模型处理的 Token 数量来收费的,但是要注意,这个收费是“双向收费”。 |
|
它是按照你发送给它的上下文,加上它返回给你的内容的总 Token 数来计算花费的 Token 数量的。 |
|
|
|
|
|
|
|
|
|
|
|
第一轮对话是只消耗了 100 个 Token,但是第二轮因为要把前面的上下文都发送出去,所以需要 200 个 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
第一种计算 Token 数量的方式,是从 API 返回的结果里面获取。我们修改一下刚才的Conversation 类,重新创建一个 Conversation2 类。 |
|
和之前只有一个不同,ask 函数除了返回回复的消息之外,还会返回这次请求消耗的 Token 数 |
|
|
|
|
|
|
|
|
|
|
|
class Conversation2: |
|
def __init__(self, prompt, num_of_round): |
|
self.prompt = prompt |
|
self.num_of_round = num_of_round |
|
self.messages = [] |
|
self.messages.append({"role": "system", "content": self.prompt}) |
|
|
|
def ask(self, question): |
|
try: |
|
self.messages.append( {"role": "user", "content": question}) |
|
response = openai.ChatCompletion.create( |
|
model="gpt-3.5-turbo", |
|
messages=self.messages, |
|
temperature=0.5, |
|
max_tokens=2048, |
|
top_p=1, |
|
) |
|
except Exception as e: |
|
print(e) |
|
return e |
|
|
|
message = response["choices"][0]["message"]["content"] |
|
num_of_tokens = response['usage']['total_tokens'] |
|
self.messages.append({"role": "assistant", "content": message}) |
|
|
|
if len(self.messages) > self.num_of_round*2 + 1: |
|
del self.messages[1:3] |
|
return message, num_of_tokens |
|
|
|
|
|
|
|
|
|
|
|
conv2 = Conversation2(prompt, 3) |
|
questions = [question1, question2, question3, question4, question5] |
|
for question in questions: |
|
answer, num_of_tokens = conv2.ask(question) |
|
print("询问 {%s} 消耗的token数量是 : %d" % (question, num_of_tokens)) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
第二种方式,我们在上一讲用过,就是使用 Tiktoken 这个 Python 库,将文本分词,然后数一数 Token 的数量。 |
|
|
|
|
|
|
|
|
|
|
|
import tiktoken |
|
encoding = tiktoken.get_encoding("cl100k_base") |
|
|
|
conv2 = Conversation2(prompt, 3) |
|
question1 = "你是谁?" |
|
answer1, num_of_tokens = conv2.ask(question1) |
|
print("总共消耗的token数量是 : %d" % (num_of_tokens)) |
|
|
|
prompt_count = len(encoding.encode(prompt)) |
|
question1_count = len(encoding.encode(question1)) |
|
answer1_count = len(encoding.encode(answer1)) |
|
total_count = prompt_count + question1_count + answer1_count |
|
print("Prompt消耗 %d Token, 问题消耗 %d Token,回答消耗 %d Token,总共消耗 %d Token" % (prompt_count, question1_count, answer1_count, total_count)) |
|
|
|
|
|
|
|
|
|
|
|
我们通过 API 获得了消耗的 Token 数,然后又通过 Tiktoken 分别计算了 System 的指示内 |
|
容、用户的问题和 AI 生成的回答,发现了两者还有小小的差异。这个是因为,我们没有计算 |
|
OpenAI 去拼接它们内部需要的格式的 Token 数量。很多时候,我们都需要通过 Tiktoken 预 |
|
先计算一下 Token 数量,避免提交的内容太多,导致 API 返回报错。 |
|
|
|
|
|
|
|
|
|
|
|
system_start_count = len(encoding.encode("<|im_start|>system\n")) |
|
print(encoding.encode("<|im_start|>system\n")) |
|
end_count = len(encoding.encode("<|im_end|>\n")) |
|
print(encoding.encode("<|im_end|>\n")) |
|
user_start_count = len(encoding.encode("<|im_start|>user\n")) |
|
print(encoding.encode("<|im_start|>user\n")) |
|
assistant_start_count = len(encoding.encode("<|im_start|>assistant\n")) |
|
print(encoding.encode("<|im_start|>assistant\n")) |
|
|
|
total_mark_count = system_start_count + user_start_count + assistant_start_count + end_count*2 |
|
print("系统拼接的标记消耗 %d Token" % total_mark_count) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
我们直接选用 Gradio 这个 Python 库来开发这个聊天机器人的界面,因为它有这样几个好处。 |
|
1,我们现有的代码都是用 Python 实现的,你不需要再去学习 JavaScript、TypeScript 以及相关的前端框架了 |
|
2,Gradio 渲染出来的界面可以直接在 Jupyter Notebook 里面显示出来,对于不了解技术的同学,也不再需要解决其他环境搭建的问题。 |
|
3,Gradio 这个公司,已经被目前最大的开源机器学习模型社区 HuggingFace 收购了。你可以免费把 Gradio 的应用部署到 HuggingFace 上。 |
|
|
|
https://www.gradio.app/guides/creating-a-custom-chatbot-with-blocks Gradio官方也有用其他开源预训练模型创建Chatbot的教程 |
|
|
|
|
|
|
|
|
|
|
|
get_ipython().run_line_magic('pip', 'install gradio') |
|
|
|
|
|
|
|
|
|
|
|
get_ipython().run_line_magic('pip', 'install --upgrade gradio') |
|
|
|
|
|
|
|
|
|
|
|
import gradio as gr |
|
prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求: |
|
1. 你的回答必须是中文 |
|
2. 回答限制在100个字以内""" |
|
|
|
conv = Conversation(prompt, 5) |
|
|
|
|
|
def predict(input, history=[]): |
|
history.append(input) |
|
response = conv.ask(input) |
|
history.append(response) |
|
|
|
responses = [(u,b) for u,b in zip(history[::2], history[1::2])] |
|
return responses, history |
|
|
|
|
|
with gr.Blocks(css="#chatbot{height:350px} .overflow-y-auto{height:500px}") as demo: |
|
chatbot = gr.Chatbot(elem_id="chatbot") |
|
state = gr.State([]) |
|
|
|
with gr.Row(): |
|
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False) |
|
|
|
txt.submit(predict, [txt, state], [chatbot, state]) |
|
|
|
demo.launch() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|