Azure.AI.Projects (.NET)
Azure AI Foundryプロジェクト操作のための高レベルSDK。エージェント、接続、データセット、デプロイ、評価、インデックスを含みます。
インストール
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity
dotnet add package Azure.AI.Projects.OpenAI --prerelease
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>
AZURE_TOKEN_CREDENTIALS=prod
認証
using Azure.Identity;
using Azure.AI.Projects;
var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
AIProjectClient projectClient = new AIProjectClient(
new Uri(endpoint),
credential);
クライアント階層
AIProjectClient
├── Agents → AIProjectAgentsOperations (バージョン管理エージェント)
├── Connections → ConnectionsClient
├── Datasets → DatasetsClient
├── Deployments → DeploymentsClient
├── Evaluations → EvaluationsClient
├── Evaluators → EvaluatorsClient
├── Indexes → IndexesClient
├── Telemetry → AIProjectTelemetry
├── OpenAI → ProjectOpenAIClient (プレビュー)
└── GetPersistentAgentsClient() → PersistentAgentsClient
コアワークフロー
1. 永続エージェントクライアントの取得
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Math Tutor",
instructions: "あなたは個人向け数学チューターです。");
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "3x + 11 = 14 を解いてください");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);
do
{
await Task.Delay(500);
run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
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);
}
}
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
2. ツールを使用したバージョン管理エージェント(プレビュー)
using Azure.AI.Projects.OpenAI;
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
Instructions = "あなたはWeb検索ができる便利なアシスタントです",
Tools = {
ResponseTool.CreateWebSearchTool(
userLocation: WebSearchToolLocation.CreateApproximateLocation(
country: "US",
city: "Seattle",
region: "Washington"
)
),
}
};
AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
agentName: "myAgent",
options: new(agentDefinition));
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse("シアトルの天気は?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. 接続
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}
AIProjectConnection conn = projectClient.Connections.GetConnection(
connectionName,
includeCredentials: true);
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
includeCredentials: false);
4. デプロイ
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
Console.WriteLine(deployment.Name);
}
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
5. データセット
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "my-dataset",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "my-dataset",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");
projectClient.Datasets.Delete("my-dataset", "1.0");
6. インデックス
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "サンプルインデックス"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "my-index",
version: "1.0",
index: searchIndex);
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
Console.WriteLine(index.Name);
}
projectClient.Indexes.Delete(name: "my-index", version: "1.0");
7. 評価
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));
Evaluation evaluation = new Evaluation(
data: new InputDataset("<dataset_id>"),
evaluators: new Dictionary<string, EvaluatorConfiguration>
{
{ "relevance", evaluatorConfig }
}
)
{
DisplayName = "サンプル評価"
};
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);
Evaluation getResult = projectClient.Evaluations.Get(result.Name);
foreach (var eval in projectClient.Evaluations.GetAll())
{
Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}
8. Azure OpenAI Chatクライアントの取得
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("無効な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("虹の色をすべてリストアップしてください");
Console.WriteLine(result.Content[0].Text);
利用可能なエージェントツール
| ツール | クラス | 目的 |
|---|
| Code Interpreter | CodeInterpreterToolDefinition | Pythonコードの実行 |
| File Search | FileSearchToolDefinition | アップロードされたファイルの検索 |
| Function Calling | FunctionToolDefinition | カスタム関数の呼び出し |
| Bing Grounding | BingGroundingToolDefinition | BingによるWeb検索 |
| Azure AI Search | AzureAISearchToolDefinition | Azure AIインデックスの検索 |
| OpenAPI | OpenApiToolDefinition | 外部APIの呼び出し |
| Azure Functions | AzureFunctionToolDefinition | Azure Functionsの呼び出し |
| MCP | MCPToolDefinition | Model Context Protocolツール |
主要型リファレンス
| 型 | 目的 |
|---|
AIProjectClient | メインエントリポイント |
PersistentAgentsClient | 低レベルエージェント操作 |
PromptAgentDefinition | バージョン管理エージェント定義 |
AgentVersion | バージョン管理エージェントインスタンス |
AIProjectConnection | Azureリソースへの接続 |
AIProjectDeployment | モデルデプロイ情報 |
AIProjectDataset | データセットメタデータ |
AIProjectIndex | 検索インデックスメタデータ |
Evaluation | 評価設定と結果 |
ベストプラクティス
DefaultAzureCredentialを使用して本番認証を行う
- 非同期メソッド(
*Async)をすべてのI/O操作に使用する
- 適切な遅延でポーリング(500ms推奨)して実行完了を待つ
- リソースをクリーンアップ — スレッド、エージェント、ファイルは使用後に削除
- バージョン管理エージェントを(
Azure.AI.Projects.OpenAI経由で)本番シナリオに使用
- 接続IDを保存(名前ではなく)してツール設定に使用
includeCredentials: true は資格情報が必要な場合のみ使用
- ページネーションを処理 — リスト操作には
AsyncPageable<T>を使用
エラーハンドリング
using Azure;
try
{
var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"エラー: {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.OpenAI | OpenAIを使用したバージョン管理エージェント | dotnet add package Azure.AI.Projects.OpenAI |
参考リンク