Merk
Tilgang til denne siden krever autorisasjon. Du kan prøve å logge på eller endre kataloger.
Tilgang til denne siden krever autorisasjon. Du kan prøve å endre kataloger.
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.OpenAI;
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 AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential())
.GetChatClient(deploymentName)
.AsAIAgent(instructions: "You are a helpful assistant.", tools: [AIFunctionFactory.Create(GetWeather)]);
The agent will automatically call your tool when relevant:
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Tip
See the full sample for the complete runnable file.
Define a tool with the @tool decorator:
# NOTE: approval_mode="never_require" is for sample brevity.
# Use "always_require" in production for user confirmation before tool execution.
@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."
Create an agent with the tool:
agent = client.as_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent. Use the get_weather tool to answer questions.",
tools=get_weather,
)
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