Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Tools let your agent call custom functions — like fetching weather data, querying a database, or calling an API.
Define a tool as any method with a [Description] attribute:
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.";
Create an agent with the tool:
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 is convenient for development but requires careful consideration in production. In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
The agent will automatically call your tool when relevant:
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Tip
See here for a full runnable sample application.
The complete sample defines a tool with the @tool decorator, creates an agent with the tool, and runs the agent:
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from random import randint
from typing import Annotated
from agent_framework import Agent, tool
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
from pydantic import Field
"""
Add Tools — Give your agent a function tool
This sample shows how to define a function tool with the @tool decorator
and wire it into an agent so the model can call it.
"""
# <define_tool>
# NOTE: approval_mode="never_require" is for sample brevity.
# Use "always_require" in production for user confirmation before tool execution.
# For tools processing untrusted external data or performing privileged operations,
# review the Agent Safety guidance at
# https://learn.microsoft.com/en-us/agent-framework/concepts/agents/safety
# and see samples/02-agents/security/email_security_example.py for SecureAgentConfig
# and quarantined_llm defense patterns.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
# </define_tool>
async def main() -> None:
client = FoundryChatClient(
project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
model="gpt-4o",
credential=AzureCliCredential(),
)
# <create_agent_with_tools>
agent = Agent(
client=client,
name="WeatherAgent",
instructions="You are a helpful weather agent. Use the get_weather tool to answer questions.",
tools=[get_weather],
)
# </create_agent_with_tools>
# <run_agent>
result = await agent.run("What's the weather like in Seattle?")
print(f"Agent: {result}")
# </run_agent>
if __name__ == "__main__":
asyncio.run(main())
Tip
See the full sample for the complete runnable file.
Define a tool using 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
})
Create an agent with the tool:
a := foundryprovider.NewAgent(
endpoint,
token,
foundryprovider.ModelDeployment(model),
foundryprovider.AgentConfig{
Instructions: "You are a helpful assistant",
Config: agent.Config{
Tools: []tool.Tool{weatherTool},
},
},
)
The agent will automatically call your tool when relevant:
resp, err := a.RunText(ctx, "What is the weather like in Amsterdam?").Collect()
fmt.Println(resp, err)
Tip
See the full sample for the complete runnable file.
Next steps
Go deeper:
- Tools overview — learn about all available tool types
- Function tools — advanced function tool patterns
- Tool approval — human-in-the-loop for tool calls