Ai开放平台的消息Tpye怎么用 ? 含代码demo

173 阅读2分钟

Tool tpye

ChatCompletions-文本生成--火山方舟大模型服务平台-火山引擎

image.png

下面是一个具体的示例

第一次请求

  • 定义function的一些元信息+描述
  • 发起第一次请求
  • 当平台识别到方法的必要调用,会给后端一个特殊的字段

d'tool_calls': [{'function': {'arguments': '{"location": "北京"}', 'name': > > 'get_current_weather'}


后续请求

  • 一般的上下文使用assistant即可,就能实现一个会话中的上下文
  • assistant 用来做引导,使用"tool_calls"参数,后续必须使用tool message的回应前面的assistant

代码demo

import requests
import json
import subprocess

# 设置API的URL
url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"

# 设置请求头,包含授权信息(这里假设你已经获取到有效的API Key并替换下面的示例值)
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer 42c"
}

# 定义可调用的工具(添加了获取活动建议的新工具函数)
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "获取指定城市的天气信息",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                    "description": "城市,如:北京",
                    },
                },
                "required": ["location"],
            },
        },
    },
]

# 构造请求体
data = {
    "model": "ep-20241222201739-69mgv",
    "messages": [
        {
            "role": "system",
            "content": "使用系统提供的tool"
        },
        {
            "role": "user",
            "content": "现在北京的天气是什么"
        },



# ---------->    'tool_calls': [{'function': {'arguments': '{"location": "北京"}', 'name': 'get_current_weather'}, 'id': 'call_o6enstd6abyaeydruscwza', 'type': 'function'}] 
        # 反射本地调用
        ##  根据平台的回调地址 继续请求 
        ### 解析出id  结合assistant+tool_calls   在tool中添加本地程序的回应  继续请求
        # {
        #     "role": "assistant",
        #     "content": "现在北京的天气是什么",
        #     "tool_calls": [
        #         {
        #             "id": "call_5ydwdadwwd",
        #             "type": "function",
        #             "function": {
        #                 "name": "get_current_weather",
        #                 "arguments": json.dumps({"location": "北京"})
        #             }
        #         }
        #     ]
        # },
        # {
        #     "role": "tool",
        #     "content": "晴天",
        #     "tool_call_id": "call_5ydwdadwwd"
        # }
    ],
    "tools": tools
}

# 发送POST请求
response = requests.post(url, headers=headers, data=json.dumps(data))

# 获取并解析响应内容
response_dict = json.loads(response.content.decode('utf-8'))

print(response_dict)

# 定义函数,这里模拟通过subprocess执行获取天气信息的操作   
##   通过OOP反射等技术调用这个方法
def get_current_weather(location):
    try:
        return "晴天"
    except subprocess.CalledProcessError as e:
        return f"请求出错: e"

验证

第一次

image.png


通过oop的反射等机制本地程序调用,构建后续请求

  • id没有特殊含义

image.png

结果改变

image.png