azure-ai-agents-persistent-dotnet
microsoft/skills
Создавайте и управляйте постоянными агентами ИИ с помощью потоков, сообщений, циклов выполнения и инструментов с использованием Azure AI Agents SDK для .NET.
...Расширить всеAzure.AI.Agents.Persistent (.NET)
Низкоуровневый 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
AZURE_AI_SEARCH_CONNECTION_ID= # Обязательно: идентификатор ресурса подключения к Azure AI Search
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 с агентами
├── Потоки → Управление потоками
├── Сообщения → Операции с сообщениями
├── Запуски → Выполнение и потоковая передача запусков
├── Файлы → Загрузка/скачивание файлов
└── 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: "Пожалуйста, обращайтесь к пользователю как к Джейн Доу."
);
// Ожидание завершения
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. Вызов функции
// Определение инструмента-функции
FunctionToolDefinition weatherTool = new(
name: "getCurrentWeather",
description: "Получает текущую погоду в указанном месте.",
parameters: BinaryData.FromObjectAsJson(new
{
Type = "object",
Properties = new
{
Location = new { Type = "string", Description = "Город и штат, например, Сан-Франциско, Калифорния" },
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 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);
Доступные инструменты
| Инструмент | Класс | Назначение |
|---|---|---|
| Интерпретатор кода | Определение инструмента CodeInterpreterTool |
Выполнение кода Python, создание визуализаций |
| Поиск файлов | FileSearchToolDefinition |
Поиск загруженных файлов через векторные хранилища |
| Вызов функции | Определение инструмента «Функция» |
Вызов пользовательских функций |
| Bing Grounding | BingGroundingToolDefinition |
Веб-поиск через Bing |
| Поиск с помощью Azure AI | AzureAISearchToolDefinition |
Поиск в индексах Azure AI Search |
| OpenAPI | OpenApiToolDefinition |
Вызов внешних API через спецификацию OpenAPI |
| Azure Functions | Определение инструмента AzureFunctionTool |
Вызов функций Azure |
| MCP | MCPToolDefinition |
Инструменты протокола Model Context Protocol |
| SharePoint | SharepointToolDefinition |
Доступ к контенту SharePoint |
| Microsoft Fabric | Определение инструмента Microsoft Fabric |
Доступ к данным Fabric |
Типы потоковых обновлений
| Тип обновления | Описание |
|---|---|
Причина потокового обновления. Запуск создан |
Запуск начат |
StreamingUpdateReason.RunInProgress |
Обработка запуска |
StreamingUpdateReason.RunCompleted |
Запуск завершен |
Причина обновления потока.Запуск_не_удался |
Ошибка при выполнении |
MessageContentUpdate |
Блок текстового содержимого |
RunStepUpdate |
Изменение статуса шага |
Справочник типов ключей
| Тип | Назначение |
|---|---|
PersistentAgentsClient |
Основная точка входа |
PersistentAgent |
Агент с моделью, инструкциями и инструментами |
Поток агента PersistentAgent |
Поток разговора |
PersistentThreadMessage |
Сообщение в потоке |
ThreadRun |
Выполнение агента в потоке |
RunStatus |
В очереди, В процессе, Требует действия, Завершено, Сбой |
Ресурсы инструмента |
Объединённые ресурсы инструмента |
ToolOutput |
Ответ на вызов функции |
Рекомендации
- Всегда освобождайте клиенты — используйте оператор
usingили явное освобождение - Опрашивайте с соответствующими задержками — рекомендуется 500 мс между проверками состояния
- Очищайте ресурсы — удаляйте потоки и агенты по завершении работы
- Обрабатывайте все состояния выполнения — проверяйте наличие состояний
«RequiresAction»,«Failed»и«Cancelled» - Используйте потоковую передачу для обеспечения пользовательского опыта в реальном времени — это обеспечивает лучший пользовательский опыт, чем опрос
- Храните идентификаторы, а не объекты — ссылайтесь на агенты и потоки по идентификаторам
- Используйте асинхронные методы — все операции должны быть асинхронными
Обработка ошибок
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
Копировать





Дом
