CommunityRedacción y edicióngithub.com

microsoft/azure-ai-agents-persistent-dotnet

SDK de bajo nivel para .NET que permite crear y gestionar agentes de IA persistentes, incluyendo hilos de conversación, mensajes, ejecuciones y herramientas.

¿Qué es azure-ai-agents-persistent-dotnet?

Azure AI Agents Persistent SDK para .NET es una biblioteca de bajo nivel diseñada para crear y gestionar agentes de IA persistentes en la plataforma Azure. Este SDK permite realizar operaciones CRUD completas sobre agentes, gestionar hilos de conversación, mensajes y ejecuciones, además de admitir respuestas en streaming, llamadas a funciones (function calling), búsqueda en archivos y un intérprete de código integrado. Está pensado para desarrolladores .NET que necesiten integrar agentes de IA en sus aplicaciones con control detallado sobre el ciclo de vida y las interacciones. La autenticación se realiza mediante Azure Identity (DefaultAzureCredential o credenciales específicas como ManagedIdentityCredential) y requiere configurar variables de entorno como PROJECT_ENDPOINT y MODEL_DEPLOYMENT_NAME. El flujo típico incluye crear un agente, un hilo y mensajes, ejecutar el agente (ya sea por sondeo o streaming) y opcionalmente gestionar llamadas a funciones. Es compatible con herramientas como CodeInterpreterToolDefinition y FunctionToolDefinition, y permite almacenar archivos en vector stores para búsqueda semántica. Su uso es ideal para aplicaciones que necesitan agentes de IA conversacionales con persistencia y capacidades avanzadas.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-agents-persistent-dotnet

Installed? Explore more Redacción y edición skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Azure.AI.Agents.Persistent (.NET)

SDK de bajo nivel para crear y gestionar agentes de IA persistentes con hilos, 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://<resource>.services.ai.azure.com/api/projects/<project>  # Obligatorio: punto de conexión del proyecto de Azure AI
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # Obligatorio: nombre del despliegue del modelo
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # Obligatorio: ID del recurso de conexión de Bing
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # Obligatorio: ID del recurso de conexión de Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod  # Obligatorio solo si se usa 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: establecer AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credencial_específica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// O usar una credencial específica directamente en producción:
// Ver 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
├── Administration  → Operaciones CRUD de agente
├── Threads         → Gestión de hilos
├── Messages        → Operaciones de mensajes
├── Runs            → Ejecución y transmisión de ejecuciones
├── Files           → Carga/descarga de archivos
└── VectorStores    → 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 de matemáticas personal. Escribe y ejecuta código para responder preguntas de matemáticas.",
    tools: [new CodeInterpreterToolDefinition()]
);

2. Crear hilo y 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`. ¿Puedes ayudarme?"
);

3. Ejecutar agente (sondeo)

// Crear ejecución
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "Por favor, dirígete al usuario como Juan Pérez."
);

// Sondeo hasta completar
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 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. Respuesta en streaming

AsyncCollectionResult<StreamingUpdate> 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

// Definir herramienta de función
FunctionToolDefinition weatherTool = new(
    name: "obtenerClimaActual",
    description: "Obtiene el clima actual en una ubicación.",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Ubicacion = new { Type = "string", Description = "Ciudad y estado, ej. San Francisco, CA" },
            Unidad = new { Type = "string", Enum = new[] { "c", "f" } }
        },
        Required = new[] { "ubicacion" }
    }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);

// Crear agente con función
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Bot del clima",
    instructions: "Eres un bot del clima.",
    tools: [weatherTool]
);

// Manejar 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 is SubmitToolOutputsAction submitAction)
    {
        List<ToolOutput> outputs = [];
        foreach (RequiredToolCall toolCall in submitAction.ToolCalls)
        {
            if (toolCall is RequiredFunctionToolCall funcCall)
            {
                // Ejecutar función y obtener resultado
                string result = EjecutarFuncion(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 almacén vectorial

// Subir archivo
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
    filePath: "documento.txt",
    purpose: PersistentAgentFilePurpose.Agents
);

// Crear almacén vectorial
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "mi_almacen_vectorial"
);

// Crear recurso de búsqueda de archivos
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// Crear agente con búsqueda de archivos
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Asistente de documentos",
    instructions: "Ayudas a los usuarios a encontrar información en 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: "Agente de búsqueda",
    instructions: "Usa Bing para responder preguntas sobre eventos actuales.",
    tools: [bingTool]
);

8. Azure AI Search

AzureAISearchToolResource searchResource = new(
    connectionId: searchConnectionId,
    indexName: "mi_indice",
    topK: 5,
    filter: "category eq 'documentation'",
    queryType: AzureAISearchQueryType.Simple
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Agente de búsqueda",
    instructions: "Busca en el índice de documentación para responder 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

HerramientaClasePropósito
Intérprete de códigoCodeInterpreterToolDefinitionEjecutar código Python, generar visualizaciones
Búsqueda de archivosFileSearchToolDefinitionBuscar en archivos subidos mediante almacenes vectoriales
Llamada a funcionesFunctionToolDefinitionLlamar funciones personalizadas
Bing GroundingBingGroundingToolDefinitionBúsqueda web mediante Bing
Azure AI SearchAzureAISearchToolDefinitionBuscar en índices de Azure AI Search
OpenAPIOpenApiToolDefinitionLlamar APIs externas mediante especificación OpenAPI
Azure FunctionsAzureFunctionToolDefinitionInvocar Azure Functions
MCPMCPToolDefinitionHerramientas del Protocolo de Contexto de Modelo
SharePointSharepointToolDefinitionAcceder a contenido de SharePoint
Microsoft FabricMicrosoftFabricToolDefinitionAcceder a datos de Fabric

Tipos de actualización en streaming

Tipo de actualizaciónDescripción
StreamingUpdateReason.RunCreatedEjecución iniciada
StreamingUpdateReason.RunInProgressEjecución en proceso
StreamingUpdateReason.RunCompletedEjecución finalizada
StreamingUpdateReason.RunFailedEjecución con error
MessageContentUpdateFragmento de contenido de texto
RunStepUpdateCambio de estado del paso

Referencia de tipos clave

TipoPropósito
PersistentAgentsClientPunto de entrada principal
PersistentAgentAgente con modelo, instrucciones, herramientas
PersistentAgentThreadHilo de conversación
PersistentThreadMessageMensaje en un hilo
ThreadRunEjecución del agente contra un hilo
RunStatusEn cola, en progreso, requiere acción, completado, fallido
ToolResourcesRecursos combinados de herramientas
ToolOutputRespuesta de llamada a función

Buenas prácticas

  1. Desechar siempre los clientes — Usar instrucciones using o eliminación explícita
  2. Sondear con retrasos adecuados — Se recomiendan 500 ms entre comprobaciones de estado
  3. Limpiar recursos — Eliminar hilos y agentes al terminar
  4. Manejar todos los estados de ejecución — Verificar RequiresAction, Failed, Cancelled
  5. Usar streaming para UX en tiempo real — Mejor experiencia de usuario que el sondeo
  6. Almacenar IDs, no objetos — Referenciar agentes/hilos por ID
  7. Usar métodos asíncronos — Todas las operaciones deben ser asíncronas

Manejo 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}");
}

SDKs relacionados

SDKPropósitoInstalación
Azure.AI.Agents.PersistentAgentes de bajo nivel (este SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.ProjectsCliente de proyecto de alto niveldotnet add package Azure.AI.Projects

Enlaces de referencia

RecursoURL
Paquete NuGethttps://www.nuget.org/packages/Azure.AI.Agents.Persistent
Referencia de APIhttps://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
Código fuente en GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
Ejemploshttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

Skills relacionados