You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跨模块用FunctionTool时Azure AI Agent报Toolset不可用错误

Azure AI Agents跨模块使用ToolSet报错问题解决

问题场景

将多个自定义函数通过FunctionTool包装后加入ToolSet,在tools.py中定义该ToolSet,在main.py中导入并创建代理时,运行线程出现错误:ValueError: Toolset is not available in the client。但将代码合并到单个文件时可正常运行,已确认ToolSet导入正确、依赖与环境变量配置无误、ToolSet和FunctionTool构造正确。


1. 跨模块定义ToolSet报错的原因

  • 序列化/反序列化不匹配:Azure AI Agents的ToolSet跨模块导入时,工具的模块路径会被标记为tools(而非主模块),导致客户端无法将序列化后的工具元信息与当前上下文的工具实例关联,单个文件中工具和代理同属一个命名空间,不存在路径匹配问题。
  • 初始化时机错位:若tools.py中提前创建ToolSet实例,而main.py中的客户端实例在工具集之后初始化,会导致工具集未被正确注册到客户端上下文。
  • 实例唯一性冲突:跨模块导入过程中可能意外生成多个ToolSet或客户端实例,代理使用的工具集与客户端绑定的工具集并非同一实例,引发可用性校验失败。

2. 正确跨模块使用ToolSet的方法

方法一:延迟工具集创建,绑定客户端上下文

不在tools.py中提前实例化ToolSet,而是定义创建工具集的函数,待main.py中客户端初始化完成后再调用:

# tools.py
from azure.ai.agents import FunctionTool

def custom_func1():
    # 自定义函数逻辑
    return "func1 result"

def custom_func2():
    # 自定义函数逻辑
    return "func2 result"

def create_tool_set():
    tool1 = FunctionTool.from_function(custom_func1)
    tool2 = FunctionTool.from_function(custom_func2)
    return [tool1, tool2]
# main.py
from azure.ai.agents import Agent, AgentClient
from tools import create_tool_set

# 先初始化客户端
client = AgentClient(
    endpoint="YOUR_ENDPOINT",
    credential="YOUR_CREDENTIAL",
    agent_resource_id="YOUR_AGENT_ID"
)
# 创建工具集并关联代理
tools = create_tool_set()
agent = Agent(tools=tools, client=client)

方法二:显式指定工具模块路径

创建FunctionTool时通过module_name参数指定模块名,确保客户端能识别跨模块工具:

# tools.py
from azure.ai.agents import FunctionTool

def custom_func1():
    return "func1 result"

def custom_func2():
    return "func2 result"

tool1 = FunctionTool.from_function(custom_func1, module_name="tools")
tool2 = FunctionTool.from_function(custom_func2, module_name="tools")
tool_set = [tool1, tool2]
# main.py
from azure.ai.agents import Agent, AgentClient
from tools import tool_set

client = AgentClient(...)
agent = Agent(tools=tool_set, client=client)

方法三:统一客户端实例作用域

在main.py中初始化客户端后,传递给tools.py用于工具集注册,确保工具集与代理使用同一客户端:

# main.py
from azure.ai.agents import AgentClient
# 初始化客户端并全局导出
client = AgentClient(...)
# tools.py
from azure.ai.agents import FunctionTool
from main import client

def custom_func1():
    return "func1 result"

tool1 = FunctionTool.from_function(custom_func1)
tool_set = [tool1]
# 将工具集注册到客户端
client.register_tools(tool_set)
# main.py
from azure.ai.agents import Agent
from tools import tool_set

agent = Agent(tools=tool_set, client=client)

内容的提问来源于stack exchange,提问作者Ipshita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:27:41