原生 API 实现的最小工具调用 Agent

import json

import requests

base_url = "https://api.siliconflow.cn/v1/chat/completions"
api_key = "sk-bhrvkxhvdhfhmt"
model_name = "Pro/zai-org/GLM-5.1"


def weather(city: str) -> str:
    """
    替换成真实的业务调用过程
    :param city:
    :return:
    """
    return f"{city}天气为晴天,25℃"

# tools 定义
tools = [{
    "type": "function",
    "function": {
        "name": "weather",
        "description": "查询城市的天气",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string"
                }
            }
        },
        "required": ["city"]
    }
}]
# tools 字典
func = {"weather": weather}


def agent(prompt: str):
    msgs = [{"role": "user", "content": prompt}]
    for i in range(8):
        print("msgs------>",json.dumps(msgs,ensure_ascii=False))
        response = requests.post(url=base_url,
                                 headers={"Authorization": f"Bearer {api_key}"},
                                 json={"model": model_name, "messages": msgs, "tools": tools})
        print(response.text)
        # 增加调用的消息
        msg = response.json()["choices"][0]["message"]
        msgs.append(msg)
        if not msg.get("tool_calls"):
            return msg["content"]
        #
        for tc in msg["tool_calls"]:
            # function calling  获取tools 然后解包参数再调用方法
            content = json.dumps(func[tc["function"]["name"]](**json.loads(tc["function"]["arguments"])),
                                 ensure_ascii=False)
            print("content--->", content)
            msgs.append(
                {
                    "role": "tool",
                    # 增加原tool消息ID 这个很重要
                    "tool_call_id": tc["id"],
                    "content": content
                }
            )


if __name__ == '__main__':
    agent("北京的天气怎么样?")
    # print(func["weather"](**json.loads("{\"city\": \"北京\"}")))
posted @ 2026-08-27 09:43  lyu6  阅读(4)  评论(0)    收藏  举报