Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
As ferramentas permitem que seu agente chame funções personalizadas , como buscar dados meteorológicos, consultar um banco de dados ou chamar uma API.
Antes de adicionar ferramentas, examine as práticas recomendadas de segurança de aprovação da ferramenta para decidir quais operações precisam de confirmação humana.
Defina uma ferramenta como qualquer método com um [Description] atributo:
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.";
Crie um agente com a ferramenta:
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)]);
Aviso
DefaultAzureCredential é conveniente para o desenvolvimento, mas requer uma consideração cuidadosa na produção. Em produção, considere o uso de uma credencial específica (por exemplo, ManagedIdentityCredential) para evitar problemas de latência, investigação de credenciais não intencionais e possíveis riscos de segurança de mecanismos de fallback.
O agente chamará automaticamente sua ferramenta quando relevante:
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Tip
Veja aqui um aplicativo de exemplo executável completo.
O exemplo completo define uma ferramenta com o @tool decorador, cria um agente com a ferramenta e executa o agente:
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
Consulte o exemplo completo do arquivo executável completo.
Definir uma ferramenta usando 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
})
Crie um agente com a ferramenta:
a := foundryprovider.NewAgent(
endpoint,
token,
foundryprovider.ModelDeployment(model),
foundryprovider.AgentConfig{
Instructions: "You are a helpful assistant",
Config: agent.Config{
Tools: []tool.Tool{weatherTool},
},
},
)
O agente chamará automaticamente sua ferramenta quando relevante:
resp, err := a.RunText(ctx, "What is the weather like in Amsterdam?").Collect()
fmt.Println(resp, err)
Tip
Consulte o exemplo completo do arquivo executável completo.
Próximas Etapas
Vá mais fundo:
- Visão geral das ferramentas – saiba mais sobre todos os tipos de ferramentas disponíveis
- Ferramentas de função – padrões avançados de ferramenta de função
- Aprovação de ferramenta – interação humana para chamadas de ferramenta