Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Met declaratieve agents kunt u agentconfiguratie definiëren met behulp van YAML- of JSON-bestanden in plaats van programmatische code te schrijven. Deze aanpak maakt het eenvoudiger om agents te definiëren, te wijzigen en te delen tussen teams.
Prerequisites
Als u declaratieve agents in C# wilt gebruiken, voegt u het Microsoft.Agents.AI.Declarative NuGet-pakket toe aan uw project, naast het chatclientpakket voor uw provider (bijvoorbeeld Azure.AI.OpenAI):
dotnet add package Microsoft.Agents.AI.Declarative --prerelease
dotnet add package Azure.AI.OpenAI
dotnet add package Azure.Identity
Het Microsoft.Agents.AI.Declarative-pakket biedt het type ChatClientPromptAgentFactory en de extensiemethode CreateFromYamlAsync op PromptAgentFactory die in de onderstaande voorbeelden worden gebruikt.
Een agent inline definiëren met YAML
U kunt de volledige YAML-specificatie definiëren als een tekenreeks rechtstreeks in uw code en vervolgens een AIAgent van deze specificatie maken met 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);
}
Waarschuwing
DefaultAzureCredential is handig voor ontwikkeling, maar vereist zorgvuldige overwegingen in de productieomgeving. Overweeg in productie een specifieke referentie te gebruiken (bijvoorbeeld ManagedIdentityCredential) om latentieproblemen, onbedoelde referentieprobing en potentiële beveiligingsrisico's van terugvalmechanismen te voorkomen.
Een agent laden vanuit een YAML-bestand
U kunt de YAML-definitie ook opslaan in een afzonderlijk bestand en deze tijdens runtime laden, zodat u de agentconfiguratie eenvoudiger kunt delen, versien en bewerken, onafhankelijk van uw code:
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
Als u declaratieve agents in Python wilt gebruiken, installeert u het pakket agent-framework-declarative naast het providerpakket voor uw chatclient (bijvoorbeeld agent-framework-foundry voor Microsoft Foundry of agent-framework-azure-ai voor Azure AI Foundry):
pip install agent-framework-declarative agent-framework-foundry --pre
Het agent-framework-declarative pakket bevat de AgentFactory klasse en de create_agent_from_yaml methoden die create_agent_from_yaml_path in de onderstaande voorbeelden worden gebruikt.
Een agent inline definiëren met YAML
U kunt de volledige YAML-specificatie rechtstreeks in uw code definiëren als een tekenreeks:
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())
Een agent laden vanuit een YAML-bestand
U kunt de YAML-definitie ook laden vanuit een bestand:
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())