Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
Los agentes declarativos permiten definir la configuración del agente mediante archivos YAML o JSON en lugar de escribir código mediante programación. Este enfoque facilita la definición, modificación y uso compartido de agentes entre equipos.
Prerequisites
Para usar agentes declarativos en C#, agregue el paquete NuGet Microsoft.Agents.AI.Declarative al proyecto, junto con el paquete de cliente de chat para el proveedor (por ejemplo, Azure.AI.OpenAI):
dotnet add package Microsoft.Agents.AI.Declarative --prerelease
dotnet add package Azure.AI.OpenAI
dotnet add package Azure.Identity
El paquete Microsoft.Agents.AI.Declarative proporciona el tipo ChatClientPromptAgentFactory y el método de extensión CreateFromYamlAsync en PromptAgentFactory usado en los ejemplos siguientes.
Definición de un agente en línea con YAML
Puede definir la especificación DE YAML completa como una cadena directamente en el código y, a continuación, crear una AIAgent a partir de ella con ChatClientPromptAgentFactory:
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("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
// Create the chat client
IChatClient chatClient = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsIChatClient();
// Define the agent using a YAML definition.
var yamlDefinition =
"""
kind: Prompt
name: Assistant
description: Helpful assistant
instructions: You are a helpful assistant. You answer questions in the language specified by the user. You return your answers in a JSON format.
model:
options:
temperature: 0.9
topP: 0.95
outputSchema:
properties:
language:
type: string
required: true
description: The language of the answer.
answer:
type: string
required: true
description: The answer text.
""";
// Create the agent from the YAML definition.
var agentFactory = new ChatClientPromptAgentFactory(chatClient);
var agent = await agentFactory.CreateFromYamlAsync(yamlDefinition);
// Invoke the agent and output the text result.
Console.WriteLine(await agent!.RunAsync("Tell me a joke about a pirate in English."));
// Invoke the agent with streaming support.
await foreach (var update in agent!.RunStreamingAsync("Tell me a joke about a pirate in French."))
{
Console.WriteLine(update);
}
Advertencia
DefaultAzureCredential es conveniente para el desarrollo, pero requiere una consideración cuidadosa en producción. En producción, considere usar una credencial específica (por ejemplo, ManagedIdentityCredential) para evitar problemas de latencia, sondeos de credenciales no deseados y posibles riesgos de seguridad de los mecanismos de respaldo.
Cargar un agente desde un archivo YAML
También puede almacenar la definición de YAML en un archivo independiente y cargarla en tiempo de ejecución, lo que facilita el uso compartido, la versión y la edición de la configuración del agente independientemente del código:
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("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
// Create the chat client.
IChatClient chatClient = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsIChatClient();
// Read the YAML agent definition from a file.
var yamlFilePath = "agent.yaml";
var yamlDefinition = await File.ReadAllTextAsync(yamlFilePath);
// Create the agent from the YAML definition.
var agentFactory = new ChatClientPromptAgentFactory(chatClient);
var agent = await agentFactory.CreateFromYamlAsync(yamlDefinition);
// Invoke the agent and output the text result.
Console.WriteLine(await agent!.RunAsync("Tell me a joke about a pirate in English."));
Prerequisites
Para usar agentes declarativos en Python, instale el paquete /agent-framework-declarative junto con el paquete de proveedor para el cliente de chat (por ejemplo, agent-framework-foundry para Microsoft Foundry o agent-framework-azure-ai para Fundición de IA de Azure):
pip install agent-framework-declarative agent-framework-foundry --pre
El agent-framework-declarative paquete proporciona la AgentFactory clase y los create_agent_from_yaml métodos y create_agent_from_yaml_path usados en los ejemplos siguientes.
Definición de un agente en línea con YAML
Puede definir la especificación completa de YAML como una cadena directamente en el código:
import asyncio
from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential
async def main():
"""Create an agent from an inline YAML definition and run it."""
yaml_definition = """kind: Prompt
name: DiagnosticAgent
displayName: Diagnostic Assistant
instructions: Specialized diagnostic and issue detection agent for systems with critical error protocol and automatic handoff capabilities
description: An agent that performs diagnostics on systems and can escalate issues when critical errors are detected.
model:
id: =Env.AZURE_OPENAI_MODEL
connection:
kind: remote
endpoint: =Env.FOUNDRY_PROJECT_ENDPOINT
"""
async with (
AzureCliCredential() as credential,
AgentFactory(client_kwargs={"credential": credential}).create_agent_from_yaml(yaml_definition) as agent,
):
response = await agent.run("What can you do for me?")
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())
Cargar un agente desde un archivo YAML
También puede cargar la definición de YAML desde un archivo:
import asyncio
from pathlib import Path
from agent_framework.declarative import AgentFactory
from azure.identity.aio import AzureCliCredential
async def main():
"""Create an agent from a declarative YAML file and run it."""
yaml_path = Path(__file__).parent / "agent-config.yaml"
async with (
AzureCliCredential() as credential,
AgentFactory(client_kwargs={"credential": credential}).create_agent_from_yaml_path(yaml_path) as agent,
):
response = await agent.run("Why is the sky blue?")
print("Agent response:", response.text)
if __name__ == "__main__":
asyncio.run(main())