CommunityEscrita e Ediçãogithub.com

Azure AI Projects SDK para .NET

SDK de alto nível para gerenciamento de projetos Azure AI Foundry em .NET, incluindo agentes, conexões, conjuntos de dados, implantações, avaliações e índices.

O que é Azure AI Projects SDK para .NET?

O SDK Azure.AI.Projects para .NET fornece uma interface de alto nível para operações em projetos Azure AI Foundry, como gerenciamento de agentes versionados, conexões com recursos, upload e gerenciamento de conjuntos de dados, implantações de modelos, avaliações e índices de busca. Ele suporta tanto agentes persistentes de baixo nível quanto agentes versionados com ferramentas como Code Interpreter, File Search, Bing Grounding e Azure AI Search. Utiliza `DefaultAzureCredential` para autenticação e exige a variável de ambiente `PROJECT_ENDPOINT`. Ideal para desenvolvedores .NET que desejam orquestrar fluxos de IA no ecossistema Azure de forma programática, com suporte a operações assíncronas e padrões de polling.

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-projects-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.Projects (.NET)

SDK de alto nível para operações em projetos Azure AI Foundry, incluindo agentes, conexões, conjuntos de dados, implantações, avaliações e índices.

Instalação

dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity

# Opcional: Para agentes versionados com extensões OpenAI
dotnet add package Azure.AI.Projects.OpenAI --prerelease

# Opcional: Para operações de agente de baixo nível
dotnet add package Azure.AI.Agents.Persistent --prerelease

Versões Atuais: GA v1.1.0, Preview v1.2.0-beta.5

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
CONNECTION_NAME=<your-connection-name>  # Opcional: nome da conexão do projeto
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>  # Opcional: nome da conexão do Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod  # Obrigatório apenas se DefaultAzureCredential for usado em produção

Autenticação

using Azure.Identity;
using Azure.AI.Projects;

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

Hierarquia do Cliente

AIProjectClient
├── Agents          → AIProjectAgentsOperations (agentes versionados)
├── Connections     → ConnectionsClient
├── Datasets        → DatasetsClient
├── Deployments     → DeploymentsClient
├── Evaluations     → EvaluationsClient
├── Evaluators      → EvaluatorsClient
├── Indexes         → IndexesClient
├── Telemetry       → AIProjectTelemetry
├── OpenAI          → ProjectOpenAIClient (preview)
└── GetPersistentAgentsClient() → PersistentAgentsClient

Fluxos de Trabalho Principais

1. Obter o Cliente de Agentes Persistentes

// Obtém o cliente de agentes de baixo nível a partir do cliente do projeto
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// Cria um agente
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Tutor de Matemática",
    instructions: "Você é um tutor pessoal de matemática.");

// Cria uma thread e executa
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Resolva 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);

// Polling até a conclusão
do
{
    await Task.Delay(500);
    run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

// Obtém as mensagens
await foreach (var msg in agentsClient.Messages.GetMessagesAsync(thread.Id))
{
    foreach (var content in msg.ContentItems)
    {
        if (content is MessageTextContent textContent)
            Console.WriteLine(textContent.Text);
    }
}

// Limpeza
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);

2. Agentes Versionados com Ferramentas (Preview)

using Azure.AI.Projects.OpenAI;

// Cria um agente com ferramenta de busca na web
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
    Instructions = "Você é um assistente útil que pode pesquisar na web",
    Tools = {
        ResponseTool.CreateWebSearchTool(
            userLocation: WebSearchToolLocation.CreateApproximateLocation(
                country: "US",
                city: "Seattle",
                region: "Washington"
            )
        ),
    }
};

AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
    agentName: "myAgent",
    options: new(agentDefinition));

// Obtém o cliente de respostas
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// Cria uma resposta
ResponseResult response = responseClient.CreateResponse("Qual é a previsão do tempo em Seattle?");
Console.WriteLine(response.GetOutputText());

// Limpeza
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

3. Conexões

// Lista todas as conexões
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
    Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}

// Obtém uma conexão específica
AIProjectConnection conn = projectClient.Connections.GetConnection(
    connectionName, 
    includeCredentials: true);

// Obtém a conexão padrão
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
    includeCredentials: false);

4. Implantações

// Lista todas as implantações
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
    Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}

// Filtra por editor
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
    Console.WriteLine(deployment.Name);
}

// Obtém uma implantação específica
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");

5. Conjuntos de Dados

// Faz upload de um único arquivo
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "meu-dataset",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// Faz upload de uma pasta
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "meu-dataset",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// Obtém um dataset
AIProjectDataset dataset = projectClient.Datasets.GetDataset("meu-dataset", "1.0");

// Exclui um dataset
projectClient.Datasets.Delete("meu-dataset", "1.0");

6. Índices

// Cria um índice do Azure AI Search
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Índice de Exemplo"
};

searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
    name: "meu-indice",
    version: "1.0",
    index: searchIndex);

// Lista índices
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
    Console.WriteLine(index.Name);
}

// Exclui um índice
projectClient.Indexes.Delete(name: "meu-indice", version: "1.0");

7. Avaliações

// Cria configuração de avaliação
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));

// Cria avaliação
Evaluation evaluation = new Evaluation(
    data: new InputDataset("<dataset_id>"),
    evaluators: new Dictionary<string, EvaluatorConfiguration> 
    { 
        { "relevance", evaluatorConfig } 
    }
)
{
    DisplayName = "Avaliação de Exemplo"
};

// Executa avaliação
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);

// Obtém avaliação
Evaluation getResult = projectClient.Evaluations.Get(result.Name);

// Lista avaliações
foreach (var eval in projectClient.Evaluations.GetAll())
{
    Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}

8. Obter Cliente de Chat do Azure OpenAI

using Azure.AI.OpenAI;
using OpenAI.Chat;

ClientConnection connection = projectClient.GetConnection(typeof(AzureOpenAIClient).FullName!);

if (!connection.TryGetLocatorAsUri(out Uri uri) || uri is null)
    throw new InvalidOperationException("URI inválida.");

uri = new Uri($"https://{uri.Host}");

AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");

ChatCompletion result = chatClient.CompleteChat("Liste todas as cores do arco-íris");
Console.WriteLine(result.Content[0].Text);

Ferramentas de Agente Disponíveis

FerramentaClassePropósito
Interpretador de CódigoCodeInterpreterToolDefinitionExecutar código Python
Pesquisa de ArquivosFileSearchToolDefinitionPesquisar arquivos enviados
Chamada de FunçãoFunctionToolDefinitionChamar funções personalizadas
Base do BingBingGroundingToolDefinitionPesquisa na web via Bing
Azure AI SearchAzureAISearchToolDefinitionPesquisar índices do Azure AI
OpenAPIOpenApiToolDefinitionChamar APIs externas
Azure FunctionsAzureFunctionToolDefinitionInvocar Azure Functions
MCPMCPToolDefinitionFerramentas de Protocolo de Contexto de Modelo

Referência de Tipos Principais

TipoPropósito
AIProjectClientPonto de entrada principal
PersistentAgentsClientOperações de agente de baixo nível
PromptAgentDefinitionDefinição de agente versionado
AgentVersionInstância de agente versionado
AIProjectConnectionConexão com recurso Azure
AIProjectDeploymentInformações de implantação do modelo
AIProjectDatasetMetadados do conjunto de dados
AIProjectIndexMetadados do índice de busca
EvaluationConfiguração e resultados de avaliação

Melhores Práticas

  1. Use DefaultAzureCredential para autenticação em produção
  2. Use métodos assíncronos (*Async) para todas as operações de E/S
  3. Faça polling com atrasos adequados (500ms recomendado) ao aguardar execuções
  4. Limpe os recursos — exclua threads, agentes e arquivos quando terminar
  5. Use agentes versionados (via Azure.AI.Projects.OpenAI) para cenários de produção
  6. Armazene IDs de conexão em vez de nomes para configurações de ferramentas
  7. Use includeCredentials: true apenas quando as credenciais forem necessárias
  8. Lide com paginação — use AsyncPageable<T> para operações de listagem

Tratamento de Erros

using Azure;

try
{
    var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erro: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

SDKs Relacionados

SDKPropósitoInstalação
Azure.AI.ProjectsCliente de projeto de alto nível (este SDK)dotnet add package Azure.AI.Projects
Azure.AI.Agents.PersistentOperações de agente de baixo níveldotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAIAgentes versionados com OpenAIdotnet add package Azure.AI.Projects.OpenAI

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Azure.AI.Projects
Referência da APIhttps://learn.microsoft.com/dotnet/api/azure.ai.projects
Código Fonte no GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects
Exemploshttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects/samples

Individual skills in this repo

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

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

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