宣言型エージェントを使用すると、プログラムコードを記述する代わりに、YAML または JSON ファイルを使用してエージェント構成を定義できます。 このアプローチにより、エージェントはチーム間で簡単に定義、変更、共有できるようになります。
前提条件
C# で宣言型エージェントを使用するには、Microsoft.Agents.AI.Declarative NuGet パッケージを、プロバイダーのチャット クライアント パッケージと共にプロジェクトに追加します (たとえば、Azure.AI.OpenAI)。
dotnet add package Microsoft.Agents.AI.Declarative --prerelease
dotnet add package Azure.AI.OpenAI
dotnet add package Azure.Identity
Microsoft.Agents.AI.Declarative パッケージは、ChatClientPromptAgentFactory 型と、次の例で使用する PromptAgentFactory の CreateFromYamlAsync 拡張メソッドを提供します。
YAML を使用してエージェントをインラインで定義する
完全な YAML 仕様をコード内で直接文字列として定義し、ChatClientPromptAgentFactoryを使用してそこからAIAgentを作成できます。
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);
}
Warnung
DefaultAzureCredential は開発には便利ですが、運用環境では慎重に考慮する必要があります。 運用環境では、待機時間の問題、意図しない資格情報のプローブ、フォールバック メカニズムによる潜在的なセキュリティ リスクを回避するために、特定の資格情報 ( ManagedIdentityCredential など) を使用することを検討してください。
YAML ファイルからエージェントを読み込む
また、YAML 定義を別のファイルに格納し、実行時に読み込むこともできます。これにより、コードとは別にエージェント構成の共有、バージョン管理、編集が容易になります。
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."));
前提条件
Pythonで宣言型エージェントを使用するには、チャット クライアントのプロバイダー パッケージと共に agent-framework-declarative パッケージをインストールします (たとえば、Microsoft Foundry の場合は agent-framework-foundry、Azure AI Foundry の場合は agent-framework-azure-ai)。
pip install agent-framework-declarative agent-framework-foundry --pre
agent-framework-declarative パッケージには、次の例で使用するAgentFactory クラスとcreate_agent_from_yamlメソッドとcreate_agent_from_yaml_path メソッドが用意されています。
YAML を使用してエージェントをインラインで定義する
完全な YAML 仕様は、コード内で直接文字列として定義できます。
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())
YAML ファイルからエージェントを読み込む
ファイルから YAML 定義を読み込むこともできます。
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())