azure-ai-agents-persistent-dotnet
microsoft/skills
Crea y gestiona agentes de IA persistentes con subprocesos, mensajes, ejecuciones y herramientas mediante el SDK de Azure AI Agents para .NET.
...Expandir todoAzure.AI.Agents.Persistent (.NET)
SDK de bajo nivel para crear y gestionar agentes de IA persistentes con subprocesos, mensajes, ejecuciones y herramientas.
Instalación
dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity
Versiones actuales: Estable v1.1.0, Vista previa v1.2.0-beta.8
Variables de entorno
PROJECT_ENDPOINT=https://.services.ai.azure.com/api/projects/ # Obligatorio: punto final del proyecto de Azure AI
MODEL_DEPLOYMENT_NAME=gpt-4o-mini # Obligatorio: nombre de la implementación del modelo
AZURE_BING_CONNECTION_ID= # Obligatorio: ID del recurso de conexión de Bing
AZURE_AI_SEARCH_CONNECTION_ID= # Obligatorio: ID del recurso de conexión de Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod # Obligatorio solo si se utiliza DefaultAzureCredential en producción
Autenticación
using Azure.AI.Agents.Persistent;
using Azure.Identity;
var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// Desarrollo local: DefaultAzureCredential. Producción: establece AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
// O bien, utiliza una credencial específica directamente en producción:
// Consulta https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
PersistentAgentsClient client = new(projectEndpoint, credential);
Jerarquía del cliente
PersistentAgentsClient
├── Administración → Operaciones CRUD de agentes
├── Hilos → Gestión de hilos
├── Mensajes → Operaciones con mensajes
├── Ejecuciones → Ejecución y transmisión de ejecuciones
├── Archivos → Carga y descarga de archivos
└── Almacénes vectoriales → Gestión de almacenes vectoriales
Flujo de trabajo principal
1. Crear agente
var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Tutor de matemáticas",
instructions: "Eres un tutor personal de matemáticas. Escribe y ejecuta código para responder a preguntas de matemáticas.",
tools: [new CodeInterpreterToolDefinition()]
);
2. Crear un hilo y un mensaje
// Crear hilo
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();
// Crear mensaje
await client.Messages.CreateMessageAsync(
thread.Id,
MessageRole.User,
"Necesito resolver la ecuación `3x + 11 = 14`. ¿Me puedes ayudar?"
);
3. Ejecutar el agente (sondeo)
// Crear ejecución
ThreadRun run = await client.Runs.CreateRunAsync(
thread.Id,
agent.Id,
additionalInstructions: "Por favor, dirígete a la usuaria como Jane Doe."
);
// Comprobar si se ha completado
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);
// Recuperar mensajes
await foreach (PersistentThreadMessage mensaje 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. Respuesta en streaming
AsyncCollectionResult stream = client.Runs.CreateRunStreamingAsync(
thread.Id,
agent.Id
);
await foreach (StreamingUpdate update in stream)
{
if (update.UpdateKind == StreamingUpdateReason.RunCreated)
{
Console.WriteLine("--- ¡Ejecución iniciada! ---");
}
else if (update is MessageContentUpdate contentUpdate)
{
Console.Write(contentUpdate.Text);
}
else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
{
Console.WriteLine("\n--- ¡Ejecución completada! ---");
}
}
5. Llamada a funciones
// Definición de la herramienta de función
FunctionToolDefinition weatherTool = new(
name: "getCurrentWeather",
description: "Obtiene el tiempo actual en una ubicación.",
parámetros: BinaryData.FromObjectAsJson(new
{
Type = "object",
Properties = new
{
Location = new { Type = "string", Description = "Ciudad y estado, p. ej., San Francisco, CA" },
Unit = new { Type = "string", Enum = new[] { "c", "f" } }
},
Required = new[] { "location" }
}, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);
// Crear agente con función
PersistentAgent agente = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Weather Bot",
instructions: "Eres un bot meteorológico.",
tools: [weatherTool]
);
// Gestionar las llamadas a funciones durante el sondeo
do
{
await Task.Delay(500);
run = await client.Runs.GetRunAsync(thread.Id, run.Id);
if (run.Status == RunStatus.RequiresAction
&& run.RequiredAction es SubmitToolOutputsAction submitAction)
{
List outputs = [];
foreach (RequiredToolCall toolCall in submitAction.ToolCalls)
{
if (toolCall es RequiredFunctionToolCall funcCall)
{
// Ejecutar la función y obtener el resultado
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. Búsqueda de archivos con Vector Store
// Subir archivo
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
filePath: "document.txt",
purpose: PersistentAgentFilePurpose.Agents
);
// Crear almacén vectorial
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
fileIds: [file.Id],
name: "my_vector_store"
);
// Crear recurso de búsqueda de archivos
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);
// Crear un agente con búsqueda de archivos
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Document Assistant",
instructions: "Ayudas a los usuarios a encontrar información en los documentos.",
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: "Utiliza Bing para responder a preguntas sobre temas de actualidad.",
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: "Busca en el índice de documentación para responder a las preguntas.",
tools: [new AzureAISearchToolDefinition()],
toolResources: new ToolResources { AzureAISearch = searchResource }
);
9. Limpieza
await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);
Herramientas disponibles
| Herramienta | Clase | Finalidad |
|---|---|---|
| Intérprete de código | CodeInterpreterToolDefinition |
Ejecutar código Python, generar visualizaciones |
| Búsqueda de archivos | FileSearchToolDefinition |
Buscar archivos cargados en almacenes vectoriales |
| Llamada a funciones | Definición de la herramienta de funciones |
Llamada a funciones personalizadas |
| Bing Grounding | BingGroundingToolDefinition |
Búsqueda web a través de Bing |
| Búsqueda con Azure AI | AzureAISearchToolDefinition |
Búsqueda en los índices de Azure AI Search |
| OpenAPI | OpenApiToolDefinition |
Llamar a API externas mediante la especificación OpenAPI |
| Azure Functions | AzureFunctionToolDefinition |
Invocar Azure Functions |
| MCP | MCPToolDefinition |
Herramientas del Protocolo de contexto de modelo |
| SharePoint | SharepointToolDefinition |
Acceder al contenido de SharePoint |
| Microsoft Fabric | Definición de herramienta de Microsoft Fabric |
Acceder a datos de Fabric |
Tipos de actualización en streaming
| Tipo de actualización | Descripción |
|---|---|
StreamingUpdateReason.RunCreated |
Ejecución iniciada |
StreamingUpdateReason.RunInProgress |
Procesamiento de la ejecución |
StreamingUpdateReason.RunCompleted |
Ejecución finalizada |
Motivo de actualización de streaming. Ejecución fallida |
Error en la ejecución |
MessageContentUpdate |
Bloque de contenido de texto |
Actualización de paso de ejecución |
Cambio de estado del paso |
Referencia de tipos de clave
| Tipo | Finalidad |
|---|---|
PersistentAgentsClient |
Punto de entrada principal |
PersistentAgent |
Agente con modelo, instrucciones y herramientas |
PersistentAgentThread |
Hilo de conversación |
Mensaje del hilo persistente |
Mensaje en el hilo |
ThreadRun |
Ejecución del agente en el hilo |
Estado de ejecución |
En cola, En curso, Requiere acción, Completado, Fallido |
Recursos de la herramienta |
Recursos combinados de la herramienta |
Salida de la herramienta |
Respuesta a la llamada de función |
Buenas prácticas
- Cerrar siempre los clientes: utiliza sentencias
«using»o el cierre explícito - Realice sondeos con los retrasos adecuados: se recomienda un intervalo de 500 ms entre comprobaciones de estado
- Limpia los recursos: elimina los subprocesos y los agentes cuando hayas terminado
- Gestiona todos los estados de ejecución: comprueba si hay
«RequiresAction»,«Failed»o«Cancelled» - Utiliza la transmisión en tiempo real para una mejorexperiencia de usuario — Ofrece una mejor experiencia de usuario que el sondeo
- Almacena identificadores, no objetos — Haz referencia a los agentes y subprocesos por su identificador
- Utilizar métodos asíncronos — Todas las operaciones deben ser asíncronas
Gestión de errores
using Azure;
try
{
var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
Console.WriteLine("Recurso no encontrado");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
SDK relacionados
| SDK | Finalidad | Instalación |
|---|---|---|
Azure.AI.Agents.Persistent |
Agentes de bajo nivel (este SDK) | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects |
Cliente de proyecto de alto nivel | dotnet add package Azure.AI.Projects |
Enlaces de referencia
| Recurso | URL |
|---|---|
| Paquete NuGet | https://www.nuget.org/packages/Azure.AI.Agents.Persistent |
| Referencia de la API | https://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent |
| Código fuente en GitHub | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent |
| Ejemplos | 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 |
Todos los archivos
0 archivosInstalar azure-ai-agents-persistent-dotnet
Descarga y descomprime los archivos de habilidades en tu directorio .claude/skills/.
Descargar ZIPClona el repositorio y copia los archivos de la habilidad a tu proyecto.
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
Copiar





Hogar
