LLM智能体工具调用原理

alt text

测试环境

被加数.txt文件内容

2

加数.txt文件内容

1

工具列表示例(截取部分)

[
  {
    "type": "function",
    "function": {
      "name": "edit",
      "description": "Replace old with new in file (old must be unique unless all=true)",
      "parameters": {
        "type": "object",
        "properties": {
          "path": {
            "type": "string"
          },
          "old": {
            "type": "string"
          },
          "new": {
            "type": "string"
          },
          "all": {
            "type": "boolean"
          }
        },
        "required": [
          "path",
          "old",
          "new"
        ]
      }
    }
  },
]

LLM节点调用(OpenAI兼容接口)

# 调用API
response = self.client.chat.completions.create(
    model=self.model,
    messages=[{"role": "system", "content": self.system_prompt}]
    + self.messages,
    tools=self.tools,
    tool_choice="auto",
    stream=stream,
)

第一轮

alt text

{
  "id": "chatcmpl-3111d54f-45eb-9bea-8a4e-1813bac62f9b",
  "object": "chat.completion",
  "created": 1772106543,
  "model": "qwen3.5-plus",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "",
        "tool_calls": [
          {
            "id": "call_7adf7a6935924e84b8f9726e",
            "type": "function",
            "function": {
              "name": "read",
              "arguments": "{\"path\": \"被加数.txt\"}"
            }
          },
          {
            "id": "call_669d0d02ad5f48c2a2073986",
            "type": "function",
            "function": {
              "name": "read",
              "arguments": "{\"path\": \"加数.txt\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

第二轮

alt text

{
  "id": "chatcmpl-93aedd25-7a56-9827-9837-d37142ab349b",
  "object": "chat.completion",
  "created": 1772106544,
  "model": "qwen3.5-plus",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "被加数是 2,加数是 1,结果是 3。我将把结果写入 答案.txt。\n</think>\n\n",
        "tool_calls": [
          {
            "id": "call_d97a09ce53c5441888da2331",
            "type": "function",
            "function": {
              "name": "write",
              "arguments": "{\"path\": \"答案.txt\", \"content\": \"3\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

第三轮

alt text

{
  "id": "chatcmpl-d3c05ff1-b30f-9d5b-a51e-fe59faf44437",
  "object": "chat.completion",
  "created": 1772106546,
  "model": "qwen3.5-plus",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "已完成。被加数 2 加上加数 1 等于 3,结果已写入 答案.txt。",
        "tool_calls": []
      },
      "finish_reason": "stop"
    }
  ]
}