工具允许代理调用自定义函数,例如提取天气数据、查询数据库或调用 API。
在添加工具之前,请查看 工具审批安全最佳做法 ,以确定哪些操作需要人工确认。
将工具定义为具有 [Description] 属性的任何方法:
using System.ComponentModel;
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
=> $"The weather in {location} is cloudy with a high of 15°C.";
使用工具创建代理:
using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant.",
tools: [AIFunctionFactory.Create(GetWeather)]);
Warning
DefaultAzureCredential 对于开发来说很方便,但在生产中需要仔细考虑。 在生产环境中,请考虑使用特定凭据(例如), ManagedIdentityCredential以避免延迟问题、意外凭据探测以及回退机制的潜在安全风险。
在合适的时候,代理会自动调用您的工具。
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Tip
有关完整的可运行示例应用程序,请参阅 此处 。
完整示例使用 @tool 修饰器定义一个工具,使用该工具创建一个代理,并运行该代理:
import asyncio
from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
# This read-only sample tool can run without approval.
@tool(approval_mode="never_require")
def get_weather(location: str) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
async def main() -> None:
agent = Agent(
client=FoundryChatClient(
project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
model="gpt-6-luna",
credential=AzureCliCredential(),
),
instructions="Use the weather tool to answer questions.",
tools=[get_weather],
)
print(await agent.run("What's the weather like in Seattle?"))
if __name__ == "__main__":
asyncio.run(main())
Tip
请查看完整示例以获取完整的可运行文件。
使用 functool 定义工具:
import (
"context"
"fmt"
"github.com/microsoft/agent-framework-go/tool"
"github.com/microsoft/agent-framework-go/tool/functool"
)
var weatherTool = functool.MustNew(functool.Config{
Name: "weather",
Description: "Get the current weather for a given location",
}, func(_ context.Context, location string) (string, error) {
return fmt.Sprintf("The weather in %s is cloudy with a high of 15°C.", location), nil
})
使用工具创建代理:
a := foundryprovider.NewAgent(
endpoint,
token,
foundryprovider.ModelDeployment(model),
foundryprovider.AgentConfig{
Instructions: "You are a helpful assistant",
Config: agent.Config{
Tools: []tool.Tool{weatherTool},
},
},
)
在合适的时候,代理会自动调用您的工具。
resp, err := a.RunText(ctx, "What is the weather like in Amsterdam?").Collect()
fmt.Println(resp, err)
Tip
请查看完整示例以获取完整的可运行文件。
后续步骤
更深入: