Communityライティング&編集github.com

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents 永続SDK ( .NET)。エージェント、スレッド、メッセージ、実行、ツールの管理を行う低レベルSDKです。エージェントのCRUD、会話スレッド、ストリーミング応答、関数呼び出し、ファイル検索、コードインタプリタをサポートします。トリガー: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET"。

azure-ai-agents-persistent-dotnet とは?

**Azure.AI.Agents.Persistent (.NET)** は、Azure AI サービス上で永続的な AI エージェントを作成、管理、実行するための低レベル .NET SDK です。この SDK は、エージェントの CRUD 操作、会話スレッドとメッセージの管理、同期的およびストリーミング形式でのエージェント実行、関数呼び出し、ファイル検索 (ベクトルストア連携)、コードインタプリタ、Bing グラウンディング、Azure AI Search、OpenAPI や Azure Functions などの外部ツール連携を包括的にサポートします。 このスキルは `PersistentAgentsClient` をエントリポイントとし、`Administration`、`Threads`、`Messages`、`Runs`、`Files`、`VectorStores` のサブクライアント階層を通じて各リソースを操作します。主なワークフローは、エージェントの作成 → スレッドとメッセージの作成 → 実行 (ポーリングまたはストリーミング) → 結果の取得 → リソースのクリーンアップ、という流れです。 **対応プラットフォーム**: .NET (Azure SDK for .NET) 上で動作し、Azure AI プロジェクト環境が必要です。認証には `DefaultAzureCredential` または特定の資格情報 (Managed Identity など) を使用します。 **利点**: 永続的なエージェントと会話スレッドを維持でき、複雑なマルチステップのタスクや、ユーザーとの継続的な対話を必要とするアプリケーションに最適です。低レベル API であるため、エージェントの実行状態 (キュー、進行中、アクション要求、完了、失敗) をきめ細かく制御でき、関数呼び出しの結果をエージェントにフィードバックするなどの高度なシナリオを実現します。ストリーミング応答によるリアルタイム UI や、`RequestFailedException` による堅牢なエラーハンドリングもサポートしています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-agents-persistent-dotnet

Installed? Explore more ライティング&編集 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Azure.AI.Agents.Persistent (.NET)

永続的な AI エージェント、スレッド、メッセージ、実行、ツールを作成および管理するための低レベル SDK です。

インストール

dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity

現在のバージョン: 安定版 v1.1.0、プレビュー版 v1.2.0-beta.8

環境変数

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # 必須: Azure AI プロジェクトエンドポイント
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # 必須: モデルデプロイ名
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # 必須: Bing 接続リソース ID
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # 必須: Azure AI Search 接続リソース ID
AZURE_TOKEN_CREDENTIALS=prod  # 必須: 本番環境で DefaultAzureCredential を使用する場合のみ

認証

using Azure.AI.Agents.Persistent;
using Azure.Identity;

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// ローカル開発: DefaultAzureCredential。本番環境: AZURE_TOKEN_CREDENTIALS=prod または AZURE_TOKEN_CREDENTIALS=<特定の資格情報> を設定
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// または、本番環境で特定の資格情報を直接使用:
// https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
PersistentAgentsClient client = new(projectEndpoint, credential);

クライアント階層

PersistentAgentsClient
├── Administration  → エージェントの CRUD 操作
├── Threads         → スレッド管理
├── Messages        → メッセージ操作
├── Runs            → 実行の実行とストリーミング
├── Files           → ファイルのアップロード/ダウンロード
└── VectorStores    → ベクトルストア管理

コアワークフロー

1. エージェントの作成

var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Math Tutor",
    instructions: "あなたは個人的な数学のチューターです。数学の質問に答えるためにコードを書いて実行してください。",
    tools: [new CodeInterpreterToolDefinition()]
);

2. スレッドとメッセージの作成

// スレッドを作成
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// メッセージを作成
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "方程式 `3x + 11 = 14` を解く必要があります。手伝ってくれますか?"
);

3. エージェントの実行 (ポーリング)

// 実行を作成
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "ユーザーを Jane Doe として扱ってください。"
);

// 完了するまでポーリング
 do
{
    await Task.Delay(TimeSpan.FromMilliseconds(500));
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

// メッセージを取得
await foreach (PersistentThreadMessage message in client.Messages.GetMessagesAsync(
    threadId: thread.Id, 
    order: ListSortOrder.Ascending))
{
    Console.Write($"{message.Role}: ");
    foreach (MessageContent content in message.ContentItems)
    {
        if (content is MessageTextContent textContent)
            Console.WriteLine(textContent.Text);
    }
}

4. ストリーミング応答

AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
    thread.Id, 
    agent.Id
);

await foreach (StreamingUpdate update in stream)
{
    if (update.UpdateKind == StreamingUpdateReason.RunCreated)
    {
        Console.WriteLine("--- 実行開始! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- 実行完了! ---");
    }
}

5. 関数呼び出し

// 関数ツールを定義
FunctionToolDefinition weatherTool = new(
    name: "getCurrentWeather",
    description: "指定された場所の現在の天気を取得します。",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Location = new { Type = "string", Description = "市と州 (例: San Francisco, CA)" },
            Unit = new { Type = "string", Enum = new[] { "c", "f" } }
        },
        Required = new[] { "location" }
    }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);

// 関数を持つエージェントを作成
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Weather Bot",
    instructions: "あなたは天気ボットです。",
    tools: [weatherTool]
);

// ポーリング中に関数呼び出しを処理
 do
{
    await Task.Delay(500);
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);

    if (run.Status == RunStatus.RequiresAction 
        && run.RequiredAction is SubmitToolOutputsAction submitAction)
    {
        List<ToolOutput> outputs = [];
        foreach (RequiredToolCall toolCall in submitAction.ToolCalls)
        {
            if (toolCall is RequiredFunctionToolCall funcCall)
            {
                // 関数を実行して結果を取得
                string result = ExecuteFunction(funcCall.Name, funcCall.Arguments);
                outputs.Add(new ToolOutput(toolCall, result));
            }
        }
        run = await client.Runs.SubmitToolOutputsToRunAsync(run, outputs, toolApprovals: null);
    }
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

6. ベクトルストアを使用したファイル検索

// ファイルをアップロード
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
    filePath: "document.txt",
    purpose: PersistentAgentFilePurpose.Agents
);

// ベクトルストアを作成
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "my_vector_store"
);

// ファイル検索リソースを作成
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// ファイル検索を持つエージェントを作成
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Document Assistant",
    instructions: "あなたはユーザーがドキュメント内の情報を見つけるのを助けます。",
    tools: [new FileSearchToolDefinition()],
    toolResources: new ToolResources { FileSearch = fileSearchResource }
);

7. Bing グラウンディング

var bingConnectionId = Environment.GetEnvironmentVariable("AZURE_BING_CONNECTION_ID");

BingGroundingToolDefinition bingTool = new(
    new BingGroundingSearchToolParameters(
        [new BingGroundingSearchConfiguration(bingConnectionId)]
    )
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Search Agent",
    instructions: "Bing を使用して現在のイベントに関する質問に答えてください。",
    tools: [bingTool]
);

8. Azure AI Search

AzureAISearchToolResource searchResource = new(
    connectionId: searchConnectionId,
    indexName: "my_index",
    topK: 5,
    filter: "category eq 'documentation'",
    queryType: AzureAISearchQueryType.Simple
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Search Agent",
    instructions: "ドキュメントインデックスを検索して質問に答えてください。",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: new ToolResources { AzureAISearch = searchResource }
);

9. クリーンアップ

await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);

利用可能なツール

ツールクラス目的
コードインタプリタCodeInterpreterToolDefinitionPython コードの実行、可視化の生成
ファイル検索FileSearchToolDefinitionベクトルストアを介してアップロードされたファイルを検索
関数呼び出しFunctionToolDefinitionカスタム関数の呼び出し
Bing グラウンディングBingGroundingToolDefinitionBing による Web 検索
Azure AI SearchAzureAISearchToolDefinitionAzure AI Search インデックスの検索
OpenAPIOpenApiToolDefinitionOpenAPI 仕様による外部 API の呼び出し
Azure FunctionsAzureFunctionToolDefinitionAzure Functions の呼び出し
MCPMCPToolDefinitionModel Context Protocol ツール
SharePointSharepointToolDefinitionSharePoint コンテンツへのアクセス
Microsoft FabricMicrosoftFabricToolDefinitionFabric データへのアクセス

ストリーミング更新の種類

更新の種類説明
StreamingUpdateReason.RunCreated実行が開始されました
StreamingUpdateReason.RunInProgress実行が処理中です
StreamingUpdateReason.RunCompleted実行が完了しました
StreamingUpdateReason.RunFailed実行でエラーが発生しました
MessageContentUpdateテキストコンテンツのチャンク
RunStepUpdateステップの状態変更

主要な型のリファレンス

型目的
PersistentAgentsClientメインのエントリポイント
PersistentAgentモデル、指示、ツールを持つエージェント
PersistentAgentThread会話スレッド
PersistentThreadMessageスレッド内のメッセージ
ThreadRunスレッドに対するエージェントの実行
RunStatusQueued、InProgress、RequiresAction、Completed、Failed
ToolResourcesツールリソースの組み合わせ
ToolOutput関数呼び出しの応答

ベストプラクティス

  1. 常にクライアントを破棄する — using ステートメントまたは明示的な破棄を使用
  2. 適切な遅延でポーリングする — ステータスチェック間は 500ms を推奨
  3. リソースをクリーンアップする — 使用後はスレッドとエージェントを削除
  4. すべての実行ステータスを処理する — RequiresAction、Failed、Cancelled をチェック
  5. リアルタイム UX にはストリーミングを使用する — ポーリングよりも優れたユーザー体験
  6. オブジェクトではなく ID を保存する — エージェント/スレッドは ID で参照
  7. 非同期メソッドを使用する — すべての操作は非同期で行うべき

エラーハンドリング

using Azure;

try
{
    var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("リソースが見つかりません");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"エラー: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

関連 SDK

SDK目的インストール
Azure.AI.Agents.Persistent低レベルエージェント (この SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects高レベルプロジェクトクライアントdotnet add package Azure.AI.Projects

参考リンク

リソースURL
NuGet パッケージhttps://www.nuget.org/packages/Azure.AI.Agents.Persistent
API リファレンスhttps://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
GitHub ソースhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
サンプルhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

関連スキル