CommunityRedacción y edicióngithub.com

microsoft/azure-ai-projects-dotnet

SDK de Azure AI Projects para .NET. Cliente de alto nivel para proyectos de Azure AI Foundry que incluye agentes, conexiones, conjuntos de datos, implementaciones, evaluaciones e índices.

¿Qué es azure-ai-projects-dotnet?

Este skill proporciona un SDK de alto nivel en C# para gestionar proyectos de Azure AI Foundry. Permite realizar operaciones completas como la creación de agentes versionados, la gestión de conexiones a recursos de Azure, la subida y consulta de conjuntos de datos, la administración de implementaciones de modelos, la ejecución de evaluaciones y el trabajo con índices de búsqueda. Soporta tanto autenticación local con `DefaultAzureCredential` como autenticación específica en producción. Incluye flujos de trabajo clave como la creación de agentes persistentes con polling para la finalización de ejecuciones, agentes versionados con herramientas (búsqueda web, interpretación de código, etc.), y la obtención de clientes de Azure OpenAI para completar chats. Se recomienda para desarrolladores .NET que necesiten orquestar y gestionar recursos de Azure AI Foundry de forma estructurada y programática.

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

SDK de alto nivel para operaciones de proyectos de Azure AI Foundry, incluyendo agentes, conexiones, conjuntos de datos, implementaciones, evaluaciones e índices.

Instalación

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

# Opcional: Para agentes versionados con extensiones de OpenAI
dotnet add package Azure.AI.Projects.OpenAI --prerelease

# Opcional: Para operaciones de agentes de bajo nivel
dotnet add package Azure.AI.Agents.Persistent --prerelease

Versiones actuales: GA v1.1.0, Preview v1.2.0-beta.5

Variables de Entorno

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # Obligatorio: Punto de conexión del proyecto Azure AI
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # Obligatorio: Nombre de la implementación del modelo
CONNECTION_NAME=<your-connection-name>  # Opcional: Nombre de la conexión del proyecto
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>  # Opcional: Nombre de la conexión de Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod  # Obligatorio solo si se usa DefaultAzureCredential en producción

Autenticación

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

var endpoint = 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();
AIProjectClient projectClient = new AIProjectClient(
    new Uri(endpoint), 
    credential);

Jerarquía del Cliente

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

Flujos de Trabajo Principales

1. Obtener el Cliente de Agentes Persistentes

// Obtener el cliente de agentes de bajo nivel desde el cliente del proyecto
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// Crear agente
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Tutor de Matemáticas",
    instructions: "Eres un tutor personal de matemáticas.");

// Crear hilo y ejecución
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Resuelve 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);

// Consultar hasta que finalice
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress)
{
    await Task.Delay(500);
    run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}

// Obtener mensajes
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);
    }
}

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

2. Agentes Versionados con Herramientas (Vista previa)

using Azure.AI.Projects.OpenAI;

// Crear agente con herramienta de búsqueda web
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
    Instructions = "Eres un asistente útil que puede buscar en la web",
    Tools = {
        ResponseTool.CreateWebSearchTool(
            userLocation: WebSearchToolLocation.CreateApproximateLocation(
                country: "US",
                city: "Seattle",
                region: "Washington"
            )
        ),
    }
};

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

// Obtener el cliente de respuestas
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// Crear respuesta
ResponseResult response = responseClient.CreateResponse("¿Cómo está el clima en Seattle?");
Console.WriteLine(response.GetOutputText());

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

3. Conexiones

// Listar todas las conexiones
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
    Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}

// Obtener una conexión específica
AIProjectConnection conn = projectClient.Connections.GetConnection(
    connectionName, 
    includeCredentials: true);

// Obtener la conexión predeterminada
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
    includeCredentials: false);

4. Implementaciones

// Listar todas las implementaciones
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
    Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}

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

// Obtener una implementación específica
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");

5. Conjuntos de Datos

// Subir un solo archivo
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "mi-conjunto",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// Subir una carpeta
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "mi-conjunto",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// Obtener conjunto de datos
AIProjectDataset dataset = projectClient.Datasets.GetDataset("mi-conjunto", "1.0");

// Eliminar conjunto de datos
projectClient.Datasets.Delete("mi-conjunto", "1.0");

6. Índices

// Crear índice de Azure AI Search
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Índice de ejemplo"
};

searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
    name: "mi-índice",
    version: "1.0",
    index: searchIndex);

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

// Eliminar índice
projectClient.Indexes.Delete(name: "mi-índice", version: "1.0");

7. Evaluaciones

// Crear configuración de evaluación
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));

// Crear evaluación
Evaluation evaluation = new Evaluation(
    data: new InputDataset("<dataset_id>"),
    evaluators: new Dictionary<string, EvaluatorConfiguration> 
    { 
        { "relevance", evaluatorConfig } 
    }
)
{
    DisplayName = "Evaluación de Ejemplo"
};

// Ejecutar evaluación
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);

// Obtener evaluación
Evaluation getResult = projectClient.Evaluations.Get(result.Name);

// Listar evaluaciones
foreach (var eval in projectClient.Evaluations.GetAll())
{
    Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}

8. Obtener el Cliente de Chat de 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 no válido.");

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

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

ChatCompletion result = chatClient.CompleteChat("Enumera todos los colores del arcoíris");
Console.WriteLine(result.Content[0].Text);

Herramientas Disponibles para Agentes

HerramientaClasePropósito
Intérprete de códigoCodeInterpreterToolDefinitionEjecutar código Python
Búsqueda de archivosFileSearchToolDefinitionBuscar archivos subidos
Llamada a funcionesFunctionToolDefinitionLlamar funciones personalizadas
Bing GroundingBingGroundingToolDefinitionBúsqueda web mediante Bing
Azure AI SearchAzureAISearchToolDefinitionBuscar índices de Azure AI
OpenAPIOpenApiToolDefinitionLlamar APIs externas
Azure FunctionsAzureFunctionToolDefinitionInvocar Azure Functions
MCPMCPToolDefinitionHerramientas del Protocolo de Contexto de Modelo

Referencia de Tipos Clave

TipoPropósito
AIProjectClientPunto de entrada principal
PersistentAgentsClientOperaciones de agentes de bajo nivel
PromptAgentDefinitionDefinición de agente versionado
AgentVersionInstancia de agente versionado
AIProjectConnectionConexión a recurso de Azure
AIProjectDeploymentInformación de implementación de modelo
AIProjectDatasetMetadatos del conjunto de datos
AIProjectIndexMetadatos del índice de búsqueda
EvaluationConfiguración y resultados de evaluación

Buenas Prácticas

  1. Usar DefaultAzureCredential para la autenticación en producción
  2. Usar métodos asíncronos (*Async) para todas las operaciones de E/S
  3. Consultar con demoras adecuadas (se recomiendan 500 ms) al esperar ejecuciones
  4. Limpiar recursos — eliminar hilos, agentes y archivos cuando se termine
  5. Usar agentes versionados (a través de Azure.AI.Projects.OpenAI) para escenarios de producción
  6. Almacenar IDs de conexión en lugar de nombres para configuraciones de herramientas
  7. Usar includeCredentials: true solo cuando se necesiten credenciales
  8. Manejar paginación — usar AsyncPageable<T> para operaciones de listado

Manejo de Errores

using Azure;

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

SDKs Relacionados

SDKPropósitoInstalación
Azure.AI.ProjectsCliente de proyecto de alto nivel (este SDK)dotnet add package Azure.AI.Projects
Azure.AI.Agents.PersistentOperaciones de agentes de bajo niveldotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAIAgentes versionados con OpenAIdotnet add package Azure.AI.Projects.OpenAI

Enlaces de Referencia

RecursoURL
Paquete NuGethttps://www.nuget.org/packages/Azure.AI.Projects
Referencia de APIhttps://learn.microsoft.com/dotnet/api/azure.ai.projects
Código fuente en GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects
Ejemploshttps://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.

Skills relacionados