mcpField
A
azure-ai-projects-dotnet

azure-ai-projects-dotnet

github.com/sickn33開発48.7k60 回インストール今日更新
リポジトリ

azure-ai-projects-dotnet について

Azure AI Foundry プロジェクトを操作する .NET SDK 向けスキルで、エージェントの構築やプロジェクトリソースの管理を行う開発者向けです。エージェント、接続、データセット、デプロイ、インデックス、評価を扱い、MCP ツール定義も含みます。

主な機能

  1. 01永続型およびバージョン付きエージェントの作成と管理
  2. 02プロジェクト接続とモデルデプロイの一覧
  3. 03データセットのアップロードとインデックス管理
  4. 04評価の設定と実行
  5. 05MCP を含むエージェントツールの利用

活用シーン

  1. 01Azure AI プロジェクトでのエージェント構築
  2. 02プロジェクト接続とデプロイの確認
  3. 03データセットと検索インデックスの準備
  4. 04モデルやエージェントの結果評価

MCP 対応

利用可能なエージェントツールに MCPToolDefinition が含まれます。エージェント定義で MCP ツールを Azure AI Foundry プロジェクトの操作に利用できます。

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-projects-dotnet

インストール後、Claude Code で/azure-ai-projects-dotnetを入力して読み込まれたか確認します。

詳細

Azure.AI.Projects (.NET)

エージェント、接続、データセット、デプロイ、評価、インデックスなど、Azure AI Foundry プロジェクトの操作に対応する高レベル SDK です。

インストール

dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity

# Optional: For versioned agents with OpenAI extensions
dotnet add package Azure.AI.Projects.OpenAI --prerelease

# Optional: For low-level agent operations
dotnet add package Azure.AI.Agents.Persistent --prerelease

現行バージョン:GA v1.1.0、プレビュー v1.2.0-beta.5

環境変数

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>
MODEL_DEPLOYMENT_NAME=gpt-4o-mini
CONNECTION_NAME=<your-connection-name>
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>

認証

using Azure.Identity;
using Azure.AI.Projects;

var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
AIProjectClient projectClient = new AIProjectClient(
    new Uri(endpoint), 
    new DefaultAzureCredential());

クライアント階層

AIProjectClient
├── Agents          → AIProjectAgentsOperations (versioned agents)
├── Connections     → ConnectionsClient
├── Datasets        → DatasetsClient
├── Deployments     → DeploymentsClient
├── Evaluations     → EvaluationsClient
├── Evaluators      → EvaluatorsClient
├── Indexes         → IndexesClient
├── Telemetry       → AIProjectTelemetry
├── OpenAI          → ProjectOpenAIClient (preview)
└── GetPersistentAgentsClient() → PersistentAgentsClient

コアワークフロー

以下のスニペットは GA とプレビューの両方の API を対象としています。互換性のあるパッケージバージョンを固定し、組み合わせて使用する前に、リンク先の SDK サンプルでシグネチャを確認してください。プロジェクトのエンドポイント、テナント、デプロイ、予算、およびアップロードが許可されたデータを確認してください。エージェントの実行や評価では、課金が発生したり、外部ツールが呼び出されたりする場合があります。すべてのポーリングにキャンセルまたは期限を設定し、Completed と Failed/Cancelled/RequiresAction を区別してください。正常に完了した場合にのみ、出力を確認してください。クリーンアップでは、この実行で作成したリソースのみを削除してください。必要な証拠を保存したうえで finally ブロックを使用し、サンプルの終了時にユーザー所有のリソースを削除しないでください。

1. 永続エージェントのクライアントを取得する
// Get low-level agents client from project client
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// Create agent
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Math Tutor",
    instructions: "You are a personal math tutor.");

// Create thread and run
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Solve 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);

// Poll for completion
do
{
    await Task.Delay(500);
    run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

// Get messages
await foreach (var msg in agentsClient.Messages.GetMessagesAsync(thread.Id))
{
    foreach (var content in msg.ContentItems)
    {
        if (content is MessageTextContent textContent)
            Console.WriteLine(textContent.Text);
    }
}

// Cleanup
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
2. ツールを使用するバージョン管理されたエージェント(プレビュー)
using Azure.AI.Projects.OpenAI;

// Create agent with web search tool
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
    Instructions = "You are a helpful assistant that can search the web",
    Tools = {
        ResponseTool.CreateWebSearchTool(
            userLocation: WebSearchToolLocation.CreateApproximateLocation(
                country: "US",
                city: "Seattle",
                region: "Washington"
            )
        ),
    }
};

AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
    agentName: "myAgent",
    options: new(agentDefinition));

// Get response client
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// Create response
ResponseResult response = responseClient.CreateResponse("What's the weather in Seattle?");
Console.WriteLine(response.GetOutputText());

// Cleanup
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. 接続
// List all connections
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
    Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}

// Get specific connection
AIProjectConnection conn = projectClient.Connections.GetConnection(
    connectionName, 
    includeCredentials: false);

// Get default connection
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
    includeCredentials: false);
4. デプロイ
// List all deployments
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
    Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}

// Filter by publisher
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
    Console.WriteLine(deployment.Name);
}

// Get specific deployment
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
5. データセット
// Upload single file
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "my-dataset",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// Upload folder
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "my-dataset",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// Get dataset
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");

// Delete dataset
projectClient.Datasets.Delete("my-dataset", "1.0");
6. インデックス
// Create Azure AI Search index
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Sample Index"
};

searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
    name: "my-index",
    version: "1.0",
    index: searchIndex);

// List indexes
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
    Console.WriteLine(index.Name);
}

// Delete index
projectClient.Indexes.Delete(name: "my-index", version: "1.0");
7. 評価
// Create evaluation configuration
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));

// Create evaluation
Evaluation evaluation = new Evaluation(
    data: new InputDataset("<dataset_id>"),
    evaluators: new Dictionary<string, EvaluatorConfiguration> 
    { 
        { "relevance", evaluatorConfig } 
    }
)
{
    DisplayName = "Sample Evaluation"
};

// Run evaluation
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);

// Get evaluation
Evaluation getResult = projectClient.Evaluations.Get(result.Name);

// List evaluations
foreach (var eval in projectClient.Evaluations.GetAll())
{
    Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}
8. Azure OpenAI チャットクライアントを取得する
using Azure.AI.OpenAI;
using OpenAI.Chat;

ClientConnection connection = projectClient.GetConnection(typeof(AzureOpenAIClient).FullName!);

if (!connection.TryGetLocatorAsUri(out Uri uri) || uri is null)
    throw new InvalidOperationException("Invalid URI.");

uri = new Uri($"https://{uri.Host}");

AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");

ChatCompletion result = chatClient.CompleteChat("List all rainbow colors");
Console.WriteLine(result.Content[0].Text);

利用可能なエージェントツール

ツールクラス用途
コードインタープリターCodeInterpreterToolDefinitionPython コードを実行
ファイル検索FileSearchToolDefinitionアップロードしたファイルを検索
関数呼び出しFunctionToolDefinitionカスタム関数を呼び出す
Bing グラウンディングBingGroundingToolDefinitionBing を使ったウェブ検索
Azure AI SearchAzureAISearchToolDefinitionAzure AI インデックスを検索
OpenAPIOpenApiToolDefinition外部 API を呼び出す
Azure FunctionsAzureFunctionToolDefinitionAzure Functions を呼び出す
MCPMCPToolDefinitionModel Context Protocol ツール

主要な型のリファレンス

型用途
AIProjectClientメインのエントリーポイント
PersistentAgentsClient低レベルのエージェント操作
PromptAgentDefinitionバージョン管理されたエージェント定義
AgentVersionバージョン管理されたエージェントインスタンス
AIProjectConnectionAzure リソースへの接続
AIProjectDeploymentモデルのデプロイ情報
AIProjectDatasetデータセットのメタデータ
AIProjectIndex検索インデックスのメタデータ
Evaluation評価の構成と結果

ベストプラクティス

  1. 本番環境の認証には DefaultAzureCredential を使用する
  2. すべての I/O 操作には非同期メソッド(*Async)を使用する
  3. 実行の完了を待つ際は、適切な間隔(推奨は 500ms)でポーリングする
  4. リソースをクリーンアップする — 完了したらスレッド、エージェント、ファイルを削除する
  5. 本番環境ではバージョン管理されたエージェント(Azure.AI.Projects.OpenAI 経由)を使用する
  6. ツール構成では名前ではなく接続 ID を保存する
  7. includeCredentials: true は認証情報が必要な場合にのみ使用する
  8. ページネーションを処理する — 一覧取得操作には AsyncPageable<T> を使用する

エラー処理

using Azure;

try
{
    var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

関連 SDK

SDK用途インストール
Azure.AI.Projects高レベルのプロジェクトクライアント(この SDK)dotnet add package Azure.AI.Projects
Azure.AI.Agents.Persistent低レベルのエージェント操作dotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAIOpenAI を使用するバージョン管理されたエージェントdotnet add package Azure.AI.Projects.OpenAI

参考リンク

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

使用する場面

このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記のスコープに明確に一致する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、専門家によるレビューの代替として扱わないでください。
  • 必要な入力、権限、安全境界、成功基準が欠けている場合は、作業を中断して確認を求めてください。

コメント