实现问答机器人,掌握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
分类:
AI大模型
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?