实现问答机器人,掌握OpenAI(zhupuai )接口使用---1
stream api
from openai import OpenAI
client = OpenAI(
# This is the default and can be omitted
api_key="sk-T1SC0pSurmOOhsdGu3P9WnHv5pDEhaz6GeMyENMfnsuKOQs",
base_url="https://api.openai-proxy.com/v1")
re_stream = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": "Say this is a test"
}
],
stream=True
)
print(re_stream.choices[0].message.content)
# 返回数据
for chunk in re_stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="") # end="" 空字符串,打印的结果就不会换行了。
实现多次对话。并实现历史对话记忆。
此次项目开发改为 zhupuai 大模型。
from zhipuai import ZhipuAI
client = ZhipuAI(api_key="fde24905ae3c5af19145593f767cdfde.NlFmUfz3SqkJmrh",)
# 定义一个空的数组
chat_history = []
while True:
user_input = input('User:')
if user_input == 'quit':
break
# 把用户输入内容赋值
chat_history.append({
'role': 'user',
'content': user_input})
re_stream = client.chat.completions.create(
model='glm-4',
messages=chat_history,
stream=True,
)
print(chat_history)
print('AI: ', end='') # 打印AI,对话内容
model_response = '' # 用于存储大模型返回的完整内容
for chunk in re_stream:
if chunk.choices[0].delta.content:
chunk_content = chunk.choices[0].delta.content
print(chunk_content, end='')
model_response += chunk_content #
chat_history.append(
{
"role": "assistant", #assistant 大模型的回复的内容
"content": model_response
}
)
返回结果
本文来自博客园,作者:王竹笙,转载请注明原文链接:https://www.cnblogs.com/edeny/p/18628319