CommunityEscrita e Ediçãogithub.com

microsoft/azure-ai-agents-persistent-dotnet

SDK de baixo nível para criar e gerenciar agentes de IA persistentes com threads, mensagens, execuções e ferramentas, voltado para .NET.

O que é azure-ai-agents-persistent-dotnet?

Azure.AI.Agents.Persistent é um SDK .NET de baixo nível que permite criar, gerenciar e interagir com agentes de IA persistentes, incluindo operações CRUD de agentes, gerenciamento de threads de conversa, mensagens, execuções (runs) e streaming de respostas. Ele suporta ferramentas como interpretador de código, busca de arquivos, chamada de funções, ancoragem no Bing (Bing Grounding), busca no Azure AI Search, OpenAPI, Azure Functions, MCP, SharePoint e Microsoft Fabric. O SDK oferece tanto polling quanto streaming para consumir respostas do agente, e inclui tratamento de chamadas de função com submissão de saídas de ferramentas. A autenticação é feita via `DefaultAzureCredential` ou credenciais específicas do Azure Identity. Os principais tipos incluem `PersistentAgentsClient`, `PersistentAgent`, `PersistentAgentThread`, `ThreadRun`, entre outros. É útil para desenvolvedores .NET que precisam de controle fino sobre agentes de IA em aplicações Azure, com suporte a ambientes locais e de produção.

Funciona com~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 Escrita e Edição skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Azure.AI.Agents.Persistent (.NET)

SDK de baixo nível para criar e gerenciar agentes de IA persistentes com threads, mensagens, execuções e ferramentas.

Instalação

dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity

Versões Atuais: Estável v1.1.0, Pré-visualização v1.2.0-beta.8

Variáveis de Ambiente

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # Obrigatório: endpoint do projeto Azure AI
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # Obrigatório: nome da implantação do modelo
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # Obrigatório: ID do recurso de conexão Bing
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # Obrigatório: ID do recurso de conexão Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado em produção

Autenticação

using Azure.AI.Agents.Persistent;
using Azure.Identity;

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_específica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou use uma credencial específica diretamente em produção:
// Veja https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
PersistentAgentsClient client = new(projectEndpoint, credential);

Hierarquia do Cliente

PersistentAgentsClient
├── Administration  → Operações CRUD de agente
├── Threads         → Gerenciamento de threads
├── Messages        → Operações de mensagens
├── Runs            → Execução de runs e streaming
├── Files           → Upload/download de arquivos
└── VectorStores    → Gerenciamento de vector stores

Fluxo de Trabalho Principal

1. Criar Agente

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. Criar Thread e Mensagem

// Criar thread
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// Criar mensagem
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "I need to solve the equation `3x + 11 = 14`. Can you help me?"
);

3. Executar Agente (Polling)

// Criar run
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe."
);

// Polling até 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 mensagens
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. Resposta em Streaming

AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
    thread.Id, 
    agent.Id
);

await foreach (StreamingUpdate update in stream)
{
    if (update.UpdateKind == StreamingUpdateReason.RunCreated)
    {
        Console.WriteLine("--- Run iniciada! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- Run concluída! ---");
    }
}

5. Chamada de Função

// Definir ferramenta de função
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 })
);

// Criar agente com função
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Weather Bot",
    instructions: "You are a weather bot.",
    tools: [weatherTool]
);

// Lidar com chamadas de função durante 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)
            {
                // Executar função e obter 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. Busca de Arquivos com Vector Store

// Upload de arquivo
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
    filePath: "document.txt",
    purpose: PersistentAgentFilePurpose.Agents
);

// Criar vector store
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "my_vector_store"
);

// Criar recurso de busca de arquivos
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// Criar agente com busca de arquivos
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. Ancoragem no Bing (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: "Use Bing to answer questions about current events.",
    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: "Search the documentation index to answer questions.",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: new ToolResources { AzureAISearch = searchResource }
);

9. Limpeza

await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);

Ferramentas Disponíveis

FerramentaClasseFinalidade
Interpretador de CódigoCodeInterpreterToolDefinitionExecutar código Python, gerar visualizações
Busca de ArquivosFileSearchToolDefinitionPesquisar arquivos enviados via vector stores
Chamada de FunçãoFunctionToolDefinitionChamar funções personalizadas
Ancoragem no BingBingGroundingToolDefinitionPesquisa na web via Bing
Azure AI SearchAzureAISearchToolDefinitionPesquisar índices do Azure AI Search
OpenAPIOpenApiToolDefinitionChamar APIs externas via especificação OpenAPI
Azure FunctionsAzureFunctionToolDefinitionInvocar Azure Functions
MCPMCPToolDefinitionFerramentas do Model Context Protocol
SharePointSharepointToolDefinitionAcessar conteúdo do SharePoint
Microsoft FabricMicrosoftFabricToolDefinitionAcessar dados do Fabric

Tipos de Atualização de Streaming

Tipo de AtualizaçãoDescrição
StreamingUpdateReason.RunCreatedRun iniciada
StreamingUpdateReason.RunInProgressRun em processamento
StreamingUpdateReason.RunCompletedRun concluída
StreamingUpdateReason.RunFailedRun com erro
MessageContentUpdateFragmento de conteúdo de texto
RunStepUpdateMudança de status da etapa

Referência de Tipos Principais

TipoFinalidade
PersistentAgentsClientPonto de entrada principal
PersistentAgentAgente com modelo, instruções, ferramentas
PersistentAgentThreadThread de conversa
PersistentThreadMessageMensagem em thread
ThreadRunExecução do agente contra a thread
RunStatusEm fila, Em andamento, Requer ação, Concluído, Falhou
ToolResourcesRecursos de ferramentas combinados
ToolOutputResposta de chamada de função

Melhores Práticas

  1. Sempre descartar clientes — Use instruções using ou descarte explícito
  2. Fazer polling com atrasos apropriados — 500ms recomendado entre verificações de status
  3. Limpar recursos — Excluir threads e agentes quando terminar
  4. Lidar com todos os status de run — Verificar RequiresAction, Failed, Cancelled
  5. Usar streaming para UX em tempo real — Melhor experiência do usuário que polling
  6. Armazenar IDs, não objetos — Referenciar agentes/threads por ID
  7. Usar métodos assíncronos — Todas as operações devem ser assíncronas

Tratamento de Erros

using Azure;

try
{
    var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Recurso não encontrado");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erro: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

SDKs Relacionados

SDKFinalidadeInstalação
Azure.AI.Agents.PersistentAgentes de baixo nível (este SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.ProjectsCliente de projeto de alto níveldotnet add package Azure.AI.Projects

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Azure.AI.Agents.Persistent
Referência da APIhttps://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
Código Fonte no GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
Amostrashttps://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.

Habilidades Relacionadas