千帆大模型|API调用

一、千帆大模型简介

二、操作步骤

API使用文档官方链接:API调用流程 - 千帆大模型平台 | 百度智能云文档

选择免费的 Yi-34B-Chat进行测试(当然,有具体需求自主选择),具体调用API代码可点击右侧的API文档。

我把API代码拿过来之后进行修改,可以实现交互。

# -*- coding: utf-8 -*-
# @Time : 2024/4/11 20:11
# @Author : Tim
# @File : 千帆大模型API测试.py
# @Software : PyCharm


import requests
import json

Switch = True


# https://cloud.baidu.com/doc/WENXINWORKSHOP/s/vlpteyv3c      yi_34b_chat 程序说明文档
# 请求示例
def get_access_token():
    """
    使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
    """
    API_Key = '换成自己的'
    Secret_Key = '换成自己的'
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_Key}&client_secret={Secret_Key}"

    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():
    counter = 0
    global Switch
    while Switch:
        information =  {
            "messages": [],
            'stream': True
        }


        input_text = input('输入bye或者连续对话10次结束对话:>>')
        information['messages'].append({
            "role": "user",
            "content": input_text
        })

        if input_text=='bye' or counter>=10:
            Switch = False

        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?access_token=" + get_access_token()

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

        response = requests.request("POST", url, headers=headers, data=payload,stream = True)
        output = str()
        for line in response.iter_lines():
            data_str = line.decode("UTF-8")
            if data_str:  # 间隔输出空行 因此要判断是否为空
                json_str = data_str.replace('data:', '')
                json_out = json.loads(json_str)
                out = json_out.get('result')
                output += out
                print(out)


        information['messages'].append({
            "role": "assistant",
            "content": output
        }) # 把模型的输出再返回给模型 实现上下文连续对话
        counter +=1 # 对话次数+1

if __name__ == '__main__':
    main()
    print('结束对话')

具体效果如下:

感叹,技术人不能只痴迷于技术,还要懂如何放大自己的技术,获取更多的资源。

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值