Appearance
智能体工具使用模式
点击上方图片可观看原课程视频。
工具是智能体扩展能力的核心。借助工具,智能体不再局限于单一输出,而是可以执行计算、检索外部数据、调用业务接口等多类操作。本节聚焦“工具使用”设计模式,解释智能体如何合理调用工具完成目标。
本节要回答的问题
- 什么是工具使用设计模式?
- 适用于哪些场景?
- 实现该模式需要哪些构件?
- 在打造可信智能体时,应注意哪些特殊考量?
学习目标
学完本节后,你将能够:
- 定义工具使用设计模式及其作用。
- 判断该模式适用的典型场景。
- 了解实现该模式所需的关键组件。
- 识别在使用工具时确保可信与安全的关键因素。
工具使用设计模式是什么
工具使用设计模式强调为大型语言模型(LLM)提供调用外部工具的能力。工具通常是可执行的代码,可以是简单函数(如计算器)或第三方 API(如股票、天气查询)。当模型根据提示决定执行某项任务时,会触发对应的函数调用。
典型应用场景
借助工具,智能体可以完成多样任务,常见场景包括:
- 动态信息检索:调用数据库或 API 获取最新数据,例如查询 SQLite、获取股价或天气。
- 代码执行与解释:运行脚本以解决数学问题、生成报告或模拟数据。
- 流程自动化:整合任务调度、邮件服务或数据流水线,自动执行多步骤任务。
- 客户支持:访问 CRM、工单系统或知识库,为用户解决问题。
- 内容生成与编辑:调用语法检查、摘要或内容安全工具辅助创作。
实现该模式需要的构件
要让智能体顺利调用工具,通常需要以下组件:
- 函数/工具 Schema:描述工具名称、用途、参数及返回值,便于模型选择合适工具并构造正确的调用。
- 执行逻辑:根据用户意图和上下文决定何时调用工具,可能包含规划器、路由或条件分支。
- 消息处理体系:管理用户输入、模型响应、工具调用与返回结果之间的对话流程。
- 工具集成框架:负责连接各类工具,无论是本地函数还是外部服务。
- 错误处理与校验:处理执行失败、参数校验与意外响应。
- 状态管理:维护多轮对话中的上下文、历史调用与持久化数据。
函数/工具调用机制
函数调用是 LLM 与工具交互的核心。当模型收到用户请求后,会把描述所有可用函数的 schema 作为参考,选择最适合的函数并返回名称与参数。宿主程序随后执行该函数,将结果回传给模型,再生成最终回答。
以下示例展示了如何让模型调度一个“获取当前时间”的函数。
python
# 摘自官方示例,演示模型如何返回函数调用
response_message = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
temperature=0.2,
)
print("Model's response:")
print(response_message)bash
Model's response:
ChatCompletionMessage(... tool_calls=[ChatCompletionMessageToolCall(... name='get_current_time' ...)])随后执行函数:
python
def get_current_time(location):
"""Get the current time for a given location"""
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
return json.dumps({"location": location, "current_time": "unknown"})python
# 处理模型的 tool_calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(location=function_args.get("location"))
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
print(final_response.choices[0].message.content)从零实现函数调用较为繁琐,因此 Lesson 02 中提到的智能体框架往往提供现成组件,帮助我们专注业务逻辑。
不同框架中的工具使用示例
Semantic Kernel
Semantic Kernel 面向 .NET、Python、Java 开发者开源,能够自动序列化函数及参数,并处理模型与代码之间的往返通信。框架内亦提供文件检索、代码解释器等现成工具。
函数调用流程示意:

在 Semantic Kernel 中,工具被称为插件。我们可以将前述 get_current_time 封装成一个插件:
python
from semantic_kernel.functions import kernel_function
class GetCurrentTimePlugin:
async def __init__(self, location):
self.location = location
@kernel_function(description="Get the current time for a given location")
def get_current_time(location: str = ""):
...python
from semantic_kernel import Kernel
kernel = Kernel()
get_current_time_plugin = GetCurrentTimePlugin(location)
kernel.add_plugin(get_current_time_plugin)Azure AI Agent Service
Azure AI Agent Service 提供托管式的智能体开发与部署能力,包含自动函数调用、会话线程、以及 Bing、Azure AI Search、Azure Functions 等内建工具。可将这些工具组合为 toolset,由服务端根据用户需求自动选择。
示例:构建一个分析销售数据的会话智能体。

python
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from fetch_sales_data_functions import fetch_sales_data_using_sqlite_query
from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query)
toolset = ToolSet()
toolset.add(fetch_data_function)
code_interpreter = CodeInterpreterTool()
toolset = ToolSet()
toolset.add(code_interpreter)
agent = project_client.agents.create_agent(
model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent",
toolset=toolset
)可信落地的注意事项
当智能体动态生成 SQL 时,需格外关注安全,例如防止 SQL 注入或恶意操作。常见做法包括:
- 为数据库配置只读权限,限制应用仅执行 SELECT。
- 在企业环境中,将生产数据抽取到只读的数据仓库,以获得更安全、性能更优的查询体验。
- 在受控环境中运行应用,确保工具调用不会越权。
更多交流渠道
欢迎加入 Azure AI Foundry Discord,与其他学习者交流工具使用经验。
延伸资源
- https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/
- https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop
- https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions
- https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py
- https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html
