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
dotnet add package Azure.AI.Projects.OpenAI --prerelease
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>
MODEL_DEPLOYMENT_NAME=gpt-4o-mini
CONNECTION_NAME=<your-connection-name>
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>
AZURE_TOKEN_CREDENTIALS=prod
Autenticación
using Azure.Identity;
using Azure.AI.Projects;
var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
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
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Tutor de Matemáticas",
instructions: "Eres un tutor personal de matemáticas.");
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);
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress)
{
await Task.Delay(500);
run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
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);
}
}
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
2. Agentes Versionados con Herramientas (Vista previa)
using Azure.AI.Projects.OpenAI;
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));
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse("¿Cómo está el clima en Seattle?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. Conexiones
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}
AIProjectConnection conn = projectClient.Connections.GetConnection(
connectionName,
includeCredentials: true);
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
includeCredentials: false);
4. Implementaciones
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
Console.WriteLine(deployment.Name);
}
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
5. Conjuntos de Datos
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "mi-conjunto",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "mi-conjunto",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
AIProjectDataset dataset = projectClient.Datasets.GetDataset("mi-conjunto", "1.0");
projectClient.Datasets.Delete("mi-conjunto", "1.0");
6. Índices
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "Índice de ejemplo"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "mi-índice",
version: "1.0",
index: searchIndex);
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
Console.WriteLine(index.Name);
}
projectClient.Indexes.Delete(name: "mi-índice", version: "1.0");
7. Evaluaciones
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));
Evaluation evaluation = new Evaluation(
data: new InputDataset("<dataset_id>"),
evaluators: new Dictionary<string, EvaluatorConfiguration>
{
{ "relevance", evaluatorConfig }
}
)
{
DisplayName = "Evaluación de Ejemplo"
};
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);
Evaluation getResult = projectClient.Evaluations.Get(result.Name);
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
| Herramienta | Clase | Propósito |
|---|
| Intérprete de código | CodeInterpreterToolDefinition | Ejecutar código Python |
| Búsqueda de archivos | FileSearchToolDefinition | Buscar archivos subidos |
| Llamada a funciones | FunctionToolDefinition | Llamar funciones personalizadas |
| Bing Grounding | BingGroundingToolDefinition | Búsqueda web mediante Bing |
| Azure AI Search | AzureAISearchToolDefinition | Buscar índices de Azure AI |
| OpenAPI | OpenApiToolDefinition | Llamar APIs externas |
| Azure Functions | AzureFunctionToolDefinition | Invocar Azure Functions |
| MCP | MCPToolDefinition | Herramientas del Protocolo de Contexto de Modelo |
Referencia de Tipos Clave
| Tipo | Propósito |
|---|
AIProjectClient | Punto de entrada principal |
PersistentAgentsClient | Operaciones de agentes de bajo nivel |
PromptAgentDefinition | Definición de agente versionado |
AgentVersion | Instancia de agente versionado |
AIProjectConnection | Conexión a recurso de Azure |
AIProjectDeployment | Información de implementación de modelo |
AIProjectDataset | Metadatos del conjunto de datos |
AIProjectIndex | Metadatos del índice de búsqueda |
Evaluation | Configuración y resultados de evaluación |
Buenas Prácticas
- Usar
DefaultAzureCredential para la autenticación en producción
- Usar métodos asíncronos (
*Async) para todas las operaciones de E/S
- Consultar con demoras adecuadas (se recomiendan 500 ms) al esperar ejecuciones
- Limpiar recursos — eliminar hilos, agentes y archivos cuando se termine
- Usar agentes versionados (a través de
Azure.AI.Projects.OpenAI) para escenarios de producción
- Almacenar IDs de conexión en lugar de nombres para configuraciones de herramientas
- Usar
includeCredentials: true solo cuando se necesiten credenciales
- 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
| SDK | Propósito | Instalación |
|---|
Azure.AI.Projects | Cliente de proyecto de alto nivel (este SDK) | dotnet add package Azure.AI.Projects |
Azure.AI.Agents.Persistent | Operaciones de agentes de bajo nivel | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects.OpenAI | Agentes versionados con OpenAI | dotnet add package Azure.AI.Projects.OpenAI |
Enlaces de Referencia