步驟二:新增工具

工具讓你的客服人員呼叫自訂功能——例如取得天氣資料、查詢資料庫或呼叫 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

完整範例可執行檔案請參閱 完整範例 。

下一步

深入探討: