目录
0 前言
访问GPT_API的干货,见这篇blog:https://blog.csdn.net/m0_60121089/article/details/149104844?spm=1011.2415.3001.5331
1 聊天机器人
前置准备
import dotenv
from openai import OpenAI
# 加载环境变量
dotenv.load_dotenv('.env')
# 创建客户端
client = OpenAI()
单轮对话
chat_response = client.chat.completions.create(
# 模型
model="gpt-3.5-turbo",
# 消息
messages=[
# 角色扮演
{"role": "system","content": "You are a helpful assistant."},
# 用户消息
{"role": "user","content": "Say this is a test."}
],
# 流式输出
stream=True
)
for chunk in chat_response:
# 内容不为None就输出
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content,end='')
# 内容为None(也就是输出结束时)退出循环
else:
break
输出:
多轮对话
while True:
# 用户输入
user_input = input('User:')
# 用户输入为“quit”时退出while循环
if user_input == "quit":
break
chat_response = client.chat.completions.create(
# 模型
model="gpt-3.5-turbo",
# 消息
messages=[
# 角色扮演
{"role": "system","content": "You are a helpful assistant."},
# 用户消息
{"role": "user","content": user_input}
],
# 流式输出
stream=True
)
print('GPT:',end='')
for chunk in chat_response:
# 内容不为None就输出
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content,end='')
# 内容为None(也就是输出结束时)退出for循环
else:
break
print()
可见此时的聊天机器人没有存储对话历史,还不具备记忆功能。
存储对话历史
存储对话历史,让聊天机器人具备记忆功能。
# 对话历史
chat_history = [{"role": "system","content": "You are a helpful assistant."}]
while True:
# 用户输入
user_input = input('User:')
# 用户输入为“quit”时退出while循环
if user_input == "quit":
break
# 对话历史中添加用户消息
chat_history.append({"role": "user","content": user_input})
chat_response = client.chat.completions.create(
# 模型
model="gpt-3.5-turbo",
# 消息
messages=chat_history,
# 流式输出
stream=True
)
print('GPT:',end='')
# gpt回答
gpt_answer = ''
for chunk in chat_response:
# 内容不为None就输出
if chunk.choices[0].delta.content is not None:
# 流式输出的每部分内容
chunk_content = chunk.choices[0].delta.content
print(chunk_content,end='')
# 把流式输出的每部分内容累加起来,就是gpt回答
gpt_answer += chunk_content
# 内容为None(也就是输出结束时)退出for循环
else:
break
# 对话历史中添加gpt回答
chat_history.append({"role": "assistant","content": gpt_answer})
print()
完整代码
import dotenv
from openai import OpenAI
# 加载环境变量
dotenv.load_dotenv('.env')
# 创建客户端
client = OpenAI()
# 对话历史
chat_history = [{"role": "system","content": "You are a helpful assistant."}]
while True:
# 用户输入
user_input = input('User:')
# 用户输入为“quit”时退出while循环
if user_input == "quit":
break
# 对话历史中添加用户消息
chat_history.append({"role": "user","content": user_input})
chat_response = client.chat.completions.create(
# 模型
model="gpt-3.5-turbo",
# 消息
messages=chat_history,
# 流式输出
stream=True
)
print('GPT:',end='')
# gpt回答
gpt_answer = ''
for chunk in chat_response:
# 内容不为None就输出
if chunk.choices[0].delta.content is not None:
# 流式输出的每部分内容
chunk_content = chunk.choices[0].delta.content
print(chunk_content,end='')
# 把流式输出的每部分内容累加起来,就是gpt回答
gpt_answer += chunk_content
# 内容为None(也就是输出结束时)退出for循环
else:
break
# 对话历史中添加gpt回答
chat_history.append({"role": "assistant","content": gpt_answer})
print()
2 翻译助手
import dotenv
from openai import OpenAI
# 加载环境变量
dotenv.load_dotenv('.env')
# 创建客户端
client = OpenAI()
print('您好,我是您的翻译助手。有什么问题就问我吧。结束聊天对话请输入:quit')
while True:
# 用户输入
user_input = input('User:')
# 用户输入为“quit”时退出while循环
if user_input == "quit":
break
chat_response = client.chat.completions.create(
# 模型
model="gpt-3.5-turbo",
# 消息
messages=[
# 角色扮演
{"role": "system","content": "你是一个专业的中英翻译助手"},
# 用户消息
{"role": "user","content": user_input}
],
# 流式输出
stream=True
)
print('GPT:',end='')
for chunk in chat_response:
# 内容不为None就输出
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content,end='')
# 内容为None(也就是输出结束时)退出for循环
else:
break
print()
3 联网搜索
联网搜索可以获取最新的数据,防止大模型根据旧数据胡编乱造,缓解大模型幻觉问题。
使用联网搜索前,先准备好以下两步:
1. 获取SerpApi Key
访问SerpApi注册页面(https://serpapi.com/users/sign_up)进行注册并获取你的API密钥。
2. 安装必要的Python库
安装google-search-results库以便进行API调用。运行以下命令:
pip install google-search-results
import os
from openai import OpenAI
from serpapi import GoogleSearch
# 创建客户端
client = OpenAI(
base_url = os.environ.get("OPENAI_BASE_URL"),
api_key = os.environ.get("OPENAI_API_KEY")
)
def get_search_results(query):
# 参数
params = {
"q": query,
"api_key": os.environ.get("SERPAPI_API_KEY")
}
# 传参,进行搜索
search = GoogleSearch(params)
# 转换成字典形式
result = search.get_dict()
# 返回搜索结果
return result['organic_results'][0]['snippet']
def chat(query,model_name="gpt-3.5-turbo"):
prompt = get_search_results(query) + query
chat_response = client.chat.completions.create(
# 模型
model="gpt-3.5-turbo",
# 消息
messages=[
# 角色扮演
{"role": "system","content": "You are a helpful assistant."},
# 用户消息
{"role": "user","content": prompt}
],
# 流式输出
stream=True
)
for chunk in chat_response:
# 内容不为None就输出
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content,end='')
# 内容为None(也就是输出结束时)退出循环
else:
break
分析:
所以,传递给大模型的prompt,实际上是search_results + query,具体为:
2023年8月29日晚11点56分,易建联在其个人微博上宣布退役。 目录. 1 生平; 2 ... 最终火箭以91比83击败雄鹿,但两人的表现都不突出,姚明得到12分,而易建联则是在比赛中撞伤右肩 ...易建联是什么时候退役的?