文心一言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信息

你可能感兴趣的:(python,文心一言)