实现问答机器人,掌握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
    }
)

返回结果

posted @   王竹笙  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示