该Python代码简单演示了如何使用火山引擎的ARK SDK实现一个具备工具调用能力的对话系统。示例包含天气查询和数学计算两个工具功能,通过多轮对话处理机制实现用户提问"查看惠州温度并计算加5后的值"。代码首先测试本地工具函数(模拟天气API和四则运算),然后与ARK模型交互,自动调用相应工具完成请求。程序展示了工具定义、函数实现、多轮对话处理等关键环节,可作为智能对话系统开发的参考模板。

from volcenginesdkarkruntime import Ark
from volcenginesdkarkruntime.types.chat import ChatCompletion
import json
import os

'''
pip install --upgrade volcengine-python-sdk[ark]
pip install --upgrade arkitect
'''

# 从环境变量获取认证信息(推荐方式)
api_key = os.getenv("VOLC_API_KEY", "替换为自己的")  # 替换为实际API_KEY
region = os.getenv("VOLC_REGION", "cn-north-1")

# 初始化客户端
client = Ark(
    api_key=api_key,
    region=region
)

# 对话历史
messages = [
    {"role": "user", "content": "帮我看一下惠州的今天的温度,然后计算一下该温度值加5等于多少度"}
]

# 工具定义(天气查询+数学计算)
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "获取指定地点的实时天气信息",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "地点名称,例如北京、上海"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["摄氏度", "华氏度"],
                        "description": "温度单位"
                    }
                },
                "required": ["location"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "执行加、减、乘、除数学运算",
            "parameters": {
                "type": "object",
                "properties": {
                    "operation": {
                        "type": "string",
                        "enum": ["加", "减", "乘", "除"],
                        "description": "运算类型"
                    },
                    "a": {
                        "type": "number",
                        "description": "第一个数字"
                    },
                    "b": {
                        "type": "number",
                        "description": "第二个数字"
                    }
                },
                "required": ["operation", "a", "b"]
            }
        }
    }
]


# 工具函数实现
def get_current_weather(location: str, unit: str = "摄氏度") -> str:
    """模拟天气查询结果(实际需对接天气API)"""
    return f"{location}今天天气晴朗,温度25{unit},湿度60%,微风。"


def calculate(operation: str, a: float, b: float) -> str:
    """执行数学运算并返回结果"""
    if operation == "加":
        return f"{a} + {b} = {a + b}"
    elif operation == "减":
        return f"{a} - {b} = {a - b}"
    elif operation == "乘":
        return f"{a} × {b} = {a * b}"
    elif operation == "除":
        if b == 0:
            return "错误:除数不能为零"
        return f"{a} ÷ {b} = {a / b}"
    else:
        return f"不支持的运算:{operation}"


# 多轮对话处理
def process_conversation():
    """处理多轮对话及工具调用"""
    print("\n=== 开始对话 ===")
    print(f"用户提问: {messages[0]['content']}\n")

    while True:
        try:
            # 调用模型API
            completion: ChatCompletion = client.chat.completions.create(
                model="doubao-pro-32k-241215",
                messages=messages,
                tools=tools
            )

            resp_msg = completion.choices[0].message
            print(f"模型回复: {resp_msg.content}")

            # 检查是否需要继续调用工具
            if completion.choices[0].finish_reason != "tool_calls":
                break

            # 记录模型回复并处理工具调用
            messages.append(resp_msg.model_dump())
            tool_calls = resp_msg.tool_calls
            print("---------------")
            print(tool_calls)
            for tool_call in tool_calls:
                tool_name = tool_call.function.name
                args = json.loads(tool_call.function.arguments)

                if tool_name == "get_current_weather":
                    # 处理天气查询
                    result = get_current_weather(**args)
                    print(f"工具调用: {tool_name}({args}) -> {result}")
                    messages.append({
                        "role": "tool",
                        "content": result,
                        "tool_call_id": tool_call.id
                    })

                elif tool_name == "calculate":
                    # 处理数学计算
                    result = calculate(**args)
                    print(f"工具调用: {tool_name}({args}) -> {result}")
                    messages.append({
                        "role": "tool",
                        "content": result,
                        "tool_call_id": tool_call.id
                    })

        except Exception as e:
            print(f"错误发生: {str(e)}")
            break


# 独立测试工具函数(非API调用)
def test_tools():
    """本地测试工具函数逻辑"""
    print("\n=== 工具函数测试 ===")
    # 天气查询测试
    print(get_current_weather("广州"))
    print(get_current_weather("纽约", "华氏度"))

    # 数学计算测试
    print(calculate("加", 123, 456))
    print(calculate("减", 999, 123))
    print(calculate("乘", 78, 12))
    print(calculate("除", 100, 4))
    print(calculate("除", 50, 0))  # 除零错误演示


# 主程序
if __name__ == "__main__":
    # 先测试工具函数
    test_tools()
    # 再执行对话流程
    process_conversation()

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐