azure-ai-agents-persistent-dotnet
microsoft/skills
Azure AI Agents SDK for .NET を使用して、スレッド、メッセージ、実行、およびツールを活用し、永続的な 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://.services.ai.azure.com/api/projects/ # 必須: Azure AI プロジェクトのエンドポイント
MODEL_DEPLOYMENT_NAME=gpt-4o-mini # 必須: モデル展開名
AZURE_BING_CONNECTION_ID= # 必須: Bing 接続リソース ID
AZURE_AI_SEARCH_CONNECTION_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
├── 管理 → エージェントの CRUD 操作
├── スレッド → スレッド管理
├── メッセージ → メッセージ操作
├── 実行 → 実行およびストリーミング
├── ファイル → ファイルのアップロード/ダウンロード
└── ベクトルストア → ベクトルストアの管理
主要なワークフロー
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 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. 関数の呼び出し
// 関数ツール tool を定義
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: "You are a weather bot.",
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 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 Grounding
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);
利用可能なツール
| ツール | クラス | 目的 |
|---|---|---|
| コードインタープリタ | CodeInterpreterToolDefinition |
Pythonコードを実行し、可視化を生成する |
| ファイル検索 | FileSearchToolDefinition |
ベクトルストア経由でアップロードされたファイルを検索 |
| 関数呼び出し | FunctionToolDefinition |
カスタム関数の呼び出し |
| Bing Grounding | BingGroundingToolDefinition |
Bing による Web 検索 |
| Azure AI Search | AzureAISearchToolDefinition |
Azure AI Search インデックスの検索 |
| OpenAPI | OpenApiToolDefinition |
OpenAPI仕様を介して外部APIを呼び出す |
| Azure Functions | AzureFunctionToolDefinition |
Azure Functionsの呼び出し |
| MCP | MCPToolDefinition |
モデルコンテキストプロトコル ツール |
| SharePoint | SharePointToolDefinition |
SharePoint コンテンツへのアクセス |
| Microsoft Fabric | MicrosoftFabricToolDefinition |
Fabric データへのアクセス |
ストリーミング更新の種類
| 更新タイプ | 説明 |
|---|---|
StreamingUpdateReason.RunCreated |
実行が開始されました |
StreamingUpdateReason.RunInProgress |
実行中 |
StreamingUpdateReason.RunCompleted |
実行が完了しました |
StreamingUpdateReason.RunFailed |
実行中にエラーが発生しました |
MessageContentUpdate |
テキストコンテンツのチャンク |
RunStepUpdate |
ステップステータスの変更 |
キー・タイプのリファレンス
| タイプ | 目的 |
|---|---|
PersistentAgentsClient |
メインエントリポイント |
PersistentAgent |
モデル、手順、ツールを備えたエージェント |
PersistentAgentThread |
会話スレッド |
PersistentThreadMessage |
スレッド内のメッセージ |
スレッドの実行 |
スレッドに対するエージェントの実行 |
実行ステータス |
キュー入り、進行中、アクションが必要、完了、失敗 |
ToolResources |
統合されたツールリソース |
ToolOutput |
関数呼び出しの応答 |
ベストプラクティス
- クライアントは常に破棄すること— `
using` ステートメントまたは明示的な破棄を使用する - 適切な遅延を置いてポーリングを行う— ステータスチェックの間隔は500msを推奨
- リソースのクリーンアップ— 処理完了時にスレッドとエージェントを削除する
- すべての実行ステータスを処理する— `
RequiresAction`、`Failed`、`Cancelled` を確認する - リアルタイムのUXにはストリーミングを使用する— ポーリングよりも優れたユーザー体験が得られる
- オブジェクトではなくIDを保存する— エージェントやスレッドはIDで参照する
- 非同期メソッドを使用する— すべての操作は非同期であるべき
エラー処理
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 |
---
name: azure-ai-agents-persistent-dotnet
description: Create and manage persistent AI agents with threads, messages, runs, and tools using the Azure AI Agents SDK for .NET.
license: MIT
---
# Azure.AI.Agents.Persistent (.NET)
Low-level SDK for creating and managing persistent AI agents with threads, messages, runs, and tools.
## Installation
```bash
dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity
```
**Current Versions**: Stable v1.1.0, Preview v1.2.0-beta.8
## Environment Variables
```bash
PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project> # Required: Azure AI project endpoint
MODEL_DEPLOYMENT_NAME=gpt-4o-mini # Required: model deployment name
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id> # Required: Bing connection resource ID
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id> # Required: Azure AI Search connection resource ID
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```
## Authentication
```csharp
using Azure.AI.Agents.Persistent;
using Azure.Identity;
var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
PersistentAgentsClient client = new(projectEndpoint, credential);
```
## Client Hierarchy
```
PersistentAgentsClient
├── Administration → Agent CRUD operations
├── Threads → Thread management
├── Messages → Message operations
├── Runs → Run execution and streaming
├── Files → File upload/download
└── VectorStores → Vector store management
```
## Core Workflow
### 1. Create Agent
```csharp
var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Math Tutor",
instructions: "You are a personal math tutor. Write and run code to answer math questions.",
tools: [new CodeInterpreterToolDefinition()]
);
```
### 2. Create Thread and Message
```csharp
// Create thread
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();
// Create message
await client.Messages.CreateMessageAsync(
thread.Id,
MessageRole.User,
"I need to solve the equation `3x + 11 = 14`. Can you help me?"
);
```
### 3. Run Agent (Polling)
```csharp
// Create run
ThreadRun run = await client.Runs.CreateRunAsync(
thread.Id,
agent.Id,
additionalInstructions: "Please address the user as Jane Doe."
);
// Poll for completion
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);
// Retrieve messages
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. Streaming Response
```csharp
AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
thread.Id,
agent.Id
);
await foreach (StreamingUpdate update in stream)
{
if (update.UpdateKind == StreamingUpdateReason.RunCreated)
{
Console.WriteLine("--- Run started! ---");
}
else if (update is MessageContentUpdate contentUpdate)
{
Console.Write(contentUpdate.Text);
}
else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
{
Console.WriteLine("\n--- Run completed! ---");
}
}
```
### 5. Function Calling
```csharp
// Define function tool
FunctionToolDefinition weatherTool = new(
name: "getCurrentWeather",
description: "Gets the current weather at a location.",
parameters: BinaryData.FromObjectAsJson(new
{
Type = "object",
Properties = new
{
Location = new { Type = "string", Description = "City and state, e.g. San Francisco, CA" },
Unit = new { Type = "string", Enum = new[] { "c", "f" } }
},
Required = new[] { "location" }
}, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);
// Create agent with function
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Weather Bot",
instructions: "You are a weather bot.",
tools: [weatherTool]
);
// Handle function calls during polling
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)
{
// Execute function and get result
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. File Search with Vector Store
```csharp
// Upload file
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
filePath: "document.txt",
purpose: PersistentAgentFilePurpose.Agents
);
// Create vector store
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
fileIds: [file.Id],
name: "my_vector_store"
);
// Create file search resource
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);
// Create agent with file search
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Document Assistant",
instructions: "You help users find information in documents.",
tools: [new FileSearchToolDefinition()],
toolResources: new ToolResources { FileSearch = fileSearchResource }
);
```
### 7. Bing Grounding
```csharp
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: "Use Bing to answer questions about current events.",
tools: [bingTool]
);
```
### 8. Azure AI Search
```csharp
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: "Search the documentation index to answer questions.",
tools: [new AzureAISearchToolDefinition()],
toolResources: new ToolResources { AzureAISearch = searchResource }
);
```
### 9. Cleanup
```csharp
await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);
```
## Available Tools
| Tool | Class | Purpose |
|------|-------|---------|
| Code Interpreter | `CodeInterpreterToolDefinition` | Execute Python code, generate visualizations |
| File Search | `FileSearchToolDefinition` | Search uploaded files via vector stores |
| Function Calling | `FunctionToolDefinition` | Call custom functions |
| Bing Grounding | `BingGroundingToolDefinition` | Web search via Bing |
| Azure AI Search | `AzureAISearchToolDefinition` | Search Azure AI Search indexes |
| OpenAPI | `OpenApiToolDefinition` | Call external APIs via OpenAPI spec |
| Azure Functions | `AzureFunctionToolDefinition` | Invoke Azure Functions |
| MCP | `MCPToolDefinition` | Model Context Protocol tools |
| SharePoint | `SharepointToolDefinition` | Access SharePoint content |
| Microsoft Fabric | `MicrosoftFabricToolDefinition` | Access Fabric data |
## Streaming Update Types
| Update Type | Description |
|-------------|-------------|
| `StreamingUpdateReason.RunCreated` | Run started |
| `StreamingUpdateReason.RunInProgress` | Run processing |
| `StreamingUpdateReason.RunCompleted` | Run finished |
| `StreamingUpdateReason.RunFailed` | Run errored |
| `MessageContentUpdate` | Text content chunk |
| `RunStepUpdate` | Step status change |
## Key Types Reference
| Type | Purpose |
|------|---------|
| `PersistentAgentsClient` | Main entry point |
| `PersistentAgent` | Agent with model, instructions, tools |
| `PersistentAgentThread` | Conversation thread |
| `PersistentThreadMessage` | Message in thread |
| `ThreadRun` | Execution of agent against thread |
| `RunStatus` | Queued, InProgress, RequiresAction, Completed, Failed |
| `ToolResources` | Combined tool resources |
| `ToolOutput` | Function call response |
## Best Practices
1. **Always dispose clients** — Use `using` statements or explicit disposal
2. **Poll with appropriate delays** — 500ms recommended between status checks
3. **Clean up resources** — Delete threads and agents when done
4. **Handle all run statuses** — Check for `RequiresAction`, `Failed`, `Cancelled`
5. **Use streaming for real-time UX** — Better user experience than polling
6. **Store IDs not objects** — Reference agents/threads by ID
7. **Use async methods** — All operations should be async
## Error Handling
```csharp
using Azure;
try
{
var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
Console.WriteLine("Resource not found");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
```
## Related SDKs
| SDK | Purpose | Install |
|-----|---------|---------|
| `Azure.AI.Agents.Persistent` | Low-level agents (this SDK) | `dotnet add package Azure.AI.Agents.Persistent` |
| `Azure.AI.Projects` | High-level project client | `dotnet add package Azure.AI.Projects` |
## Reference Links
| Resource | URL |
|----------|-----|
| NuGet Package | https://www.nuget.org/packages/Azure.AI.Agents.Persistent |
| API Reference | https://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent |
| Samples | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples |
すべてのファイル
0件のファイルazure-ai-agents-persistent-dotnetをインストール
スキルファイルをダウンロードし、.claude/skills/ ディレクトリに解凍してください。
ZIPをダウンロードリポジトリをクローンし、スキルファイルをプロジェクトにコピーしてください。
git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-agents-persistent-dotnet # Copy SKILL.md to your .claude/skills/ directory
コピー





家
