Advertisement

千帆大模型|API调用

阅读量:

一、千帆大模型简介

二、操作步骤

APIdoc官方链接地址:APIdoc调用路径 - 千帆大模型平台 | 百度智能云官方文档

获取免费版 Yi-34B 智能聊天系统(当然有此需求时建议自行决定),具体调用 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('结束对话')
    
    
    
    
    python
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-18/JFQhZOYvES0RdXAMoWly3BPbDcew.png)

具体效果如下:

难于仅专注于技术本身而不去学习如何放大自身的技术能力以掌握更多资源的获取方法

全部评论 (0)

还没有任何评论哟~