文心一言API 多轮对话流式调用 可调整历史消息数

# -*- coding: utf-8 -*-
import requests
import json

history_baidu  = []
max_history_number = 6


def get_access_token():
    url = ("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ID"
           "&client_secret=SECRET")

    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")


def main():
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + get_access_token()
    if len(history_baidu) <= max_history_number * 2:
        history_baidu.append({
            "role": "user",
            "content": input("请输入问题:\n")
        })
    else:
        history_baidu.pop(0)
        history_baidu.append({
            "role": "user",
            "content": input("请输入问题:\n")
        })

    payload = json.dumps({
        "messages": history_baidu,
        "stream": True
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload, stream=True)

    whole_sentence = ""
    for line in response.iter_lines():
        string_data = line.decode('utf-8')
        if '{' in string_data and 'result' in string_data:
            start_index = string_data.index('{')
            end_index = string_data.rindex('}') + 1
            dict_string = string_data[start_index:end_index]
            dict_data = json.loads(dict_string)
            print(dict_data['result'], end='')
            whole_sentence += dict_data['result']
    if len(history_baidu) <= max_history_number * 2:
        history_baidu.append({
            "role": "assistant",
            "content": whole_sentence
        })
    else:
        history_baidu.pop(0)
        history_baidu.append({
            "role": "assistant",
            "content": whole_sentence
        })
    print("\n")


if __name__ == '__main__':
    while (True):
        main()

需要替换url里ID和SECRET为自己的api信息

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值