File size: 11,058 Bytes
c198907 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 |
#!/usr/bin/env python
# coding: utf-8
# ## ChatGPT来了,更快的速度更低的价格
# In[ ]:
在第3讲里面. 通过colpletion接口, 实现一个聊天机器人
我们采用的是自己将整个对话拼接起来,将整个上下文都发送给 OpenAI的 Completion API 的方式。
因为 ChatGPT 的火热,OpenAI 放出了一个直接可以进行对话聊天的接口。
这个接口叫做 ChatCompletion,对应的模型叫做 gpt3.5-turbo,不但用起来更容易了,速度还快,而且价格也是我们之前使用的 text-davinci-003 的十分之一,
可谓是物美价廉了。
# In[ ]:
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?"}
]
)
# In[ ]:
需要传入的参数,从一段Prompt 变成了一个数组,数组的每个元素都有 role 和 content 两个字段
role 这个字段一共有三个角色可以选择,其中 system 代表系统,user 代表用户,而assistant 则代表 AI 的回答
# In[ ]:
当 role 是 system 的时候,content 里面的内容代表我们给 AI 的一个指令.是告诉AI 应该怎么回答用户的问题
比如我们希望 AI 都通过中文回答我们就可以在content 里面写 "你只能用中文回答"
而当 role 是 user 或者 assistant 的时候
content 里面的内容就代表用户和ai对话的内容
和我们第 03 讲里做的聊天机器人一样,你需要把历史上的对话一起发送给OpenAI 的接口,它才能有理解整个对话的上下文的能力。
# In[ ]:
# In[1]:
import openai
import os
OPENAI_API_KEY='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'
openai.api_key = OPENAI_API_KEY
# 封装了一个 Conversation 类
class Conversation:
# prompt 作为system 的 content,代表我们对这个聊天机器人的指令,
# num_of_round 代表每次向ChatGPT 发起请求的时候,保留过去几轮会话。
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})
#输入是一个 string 类型的 question,返回结果也是 string 类型的一条 message。
# 每次调用 ask 函数,都会向 ChatGPT 发起一个请求
# 在这个请求里,我们都会把最新的问题拼接到整个对话数组的最后,而在得到 ChatGPT 的回答之后也会把回答拼接上去。
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})
# 回答完之后,发现会话的轮数超过我们设置的 num_of_round,我们就去掉最前面的一轮会话
if len(self.messages) > self.num_of_round*2 + 1:
del self.messages[1:3]
return message
# In[2]:
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))
# In[3]:
question4 = "我问你的第一个问题是什么?"
print("User : %s" % question4)
print("Assistant : %s\n" % conv1.ask(question4))
# In[ ]:
如果我们重新再问一遍“我问你的第一个问题是什么”,你会发现回答变了。
上一轮已经是第四轮了,而我们设置记住的 num_of_round 是 3。
在上一轮的问题回答完了之后,第一轮的关于“你是谁”的问答,被我们从 ChatGPT 的对话历史里去掉了。
所以这个时候,它会告诉我们,第一个问题是“鱼香肉丝怎么做”。
# In[4]:
question5 = "我问你的第一个问题是什么?"
print("User : %s" % question5)
print("Assistant : %s\n" % conv1.ask(question5))
# In[ ]:
ChatGPT 的对话模型用起来很方便,但是也有一点需要注意。就是在这个需要传送大量上下文的情况下,这个费用会比你想象的高。
OpenAI 是通过模型处理的 Token 数量来收费的,但是要注意,这个收费是“双向收费”。
它是按照你发送给它的上下文,加上它返回给你的内容的总 Token 数来计算花费的 Token 数量的。
# In[ ]:
第一轮对话是只消耗了 100 个 Token,但是第二轮因为要把前面的上下文都发送出去,所以需要 200 个
# ### 通过API计算Token数量
# In[ ]:
第一种计算 Token 数量的方式,是从 API 返回的结果里面获取。我们修改一下刚才的Conversation 类,重新创建一个 Conversation2 类。
和之前只有一个不同,ask 函数除了返回回复的消息之外,还会返回这次请求消耗的 Token 数
# In[2]:
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
# In[6]:
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库计算Token数量
# In[ ]:
第二种方式,我们在上一讲用过,就是使用 Tiktoken 这个 Python 库,将文本分词,然后数一数 Token 的数量。
# In[3]:
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))
# In[ ]:
我们通过 API 获得了消耗的 Token 数,然后又通过 Tiktoken 分别计算了 System 的指示内
容、用户的问题和 AI 生成的回答,发现了两者还有小小的差异。这个是因为,我们没有计算
OpenAI 去拼接它们内部需要的格式的 Token 数量。很多时候,我们都需要通过 Tiktoken 预
先计算一下 Token 数量,避免提交的内容太多,导致 API 返回报错。
# In[8]:
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帮你快速搭建一个聊天界面
# In[ ]:
我们直接选用 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的教程
# In[5]:
get_ipython().run_line_magic('pip', 'install gradio')
# In[4]:
get_ipython().run_line_magic('pip', 'install --upgrade gradio')
# In[3]:
import gradio as gr
prompt = """你是一个中国厨师,用中文回答做菜的问题。你的回答需要满足以下要求:
1. 你的回答必须是中文
2. 回答限制在100个字以内"""
# 定义好了 system 这个系统角色的提示语,创建了一个 Conversation 对象。
conv = Conversation(prompt, 5)
# 通过 history 维护了整个会话的历史记录
def predict(input, history=[]):
history.append(input)
response = conv.ask(input)
history.append(response)
# 通过 responses,将用户和 AI 的对话分组
responses = [(u,b) for u,b in zip(history[::2], history[1::2])]
return responses, history
# 最后,我们通过一段 with 代码,创建了对应的聊天界面。Gradio 提供了一个现成的Chatbot 组件,我们只需要调用它,然后提供一个文本输入框就好了。
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()
# In[ ]:
|