mcpField
A
azure-ai-projects-dotnet

azure-ai-projects-dotnet

github.com/sickn33开发48.7k60 次安装今天更新
代码仓库

关于 azure-ai-projects-dotnet

面向 .NET 开发者的 Azure AI Foundry 项目操作 SDK 技能,适用于构建 Agent 和管理项目资源。客户端涵盖 Agent、连接、数据集、部署、索引和评估,并包含 MCP 工具定义。

主要功能

  1. 01创建和管理持久型及版本化 Agent
  2. 02列出项目连接和模型部署
  3. 03上传数据集并管理索引
  4. 04配置和运行评估
  5. 05使用包括 MCP 在内的 Agent 工具

适用场景

  1. 01在 Azure AI 项目中构建 Agent
  2. 02检查项目连接和部署
  3. 03准备数据集与搜索索引
  4. 04评估模型或 Agent 的结果

MCP 相关

SDK 将 MCPToolDefinition 列为可用的 Agent 工具。Agent 定义可在 Azure AI Foundry 项目操作中使用 MCP 工具。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-projects-dotnet

安装后在 Claude Code 中输入/azure-ai-projects-dotnet确认已加载。

详细介绍

Azure.AI.Projects(.NET)

用于 Azure AI Foundry 项目操作的高级 SDK,涵盖 Agent、连接、数据集、部署、评估和索引。

安装

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

# Optional: For versioned agents with OpenAI extensions
dotnet add package Azure.AI.Projects.OpenAI --prerelease

# Optional: For low-level agent operations
dotnet add package Azure.AI.Agents.Persistent --prerelease

当前版本:GA v1.1.0,Preview v1.2.0-beta.5

环境变量

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>

身份验证

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

var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
AIProjectClient projectClient = new AIProjectClient(
    new Uri(endpoint), 
    new DefaultAzureCredential());

客户端层级

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

核心工作流

以下代码片段涉及 GA 和 Preview 版本的功能;请锁定兼容的软件包版本,并在组合使用前核对链接的 SDK 示例中的签名。确认项目终结点、租户、部署、预算和允许上传的数据。Agent 运行和评估可能会产生费用或调用外部工具。为每次轮询添加取消机制和截止时间,区分 Completed、Failed、Cancelled 和 RequiresAction 状态,并仅在成功完成后检查输出。清理操作只删除本次运行创建的资源;保留所需证据后,在 finally 代码块中执行清理,切勿仅因示例结束就删除用户拥有的资源。

1. 获取持久化 Agent 客户端
// Get low-level agents client from project client
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// Create agent
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Math Tutor",
    instructions: "You are a personal math tutor.");

// Create thread and run
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Solve 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);

// Poll for completion
do
{
    await Task.Delay(500);
    run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

// Get messages
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);
    }
}

// Cleanup
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
2. 带工具的版本化 Agent(Preview)
using Azure.AI.Projects.OpenAI;

// Create agent with web search tool
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
    Instructions = "You are a helpful assistant that can search the web",
    Tools = {
        ResponseTool.CreateWebSearchTool(
            userLocation: WebSearchToolLocation.CreateApproximateLocation(
                country: "US",
                city: "Seattle",
                region: "Washington"
            )
        ),
    }
};

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

// Get response client
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// Create response
ResponseResult response = responseClient.CreateResponse("What's the weather in Seattle?");
Console.WriteLine(response.GetOutputText());

// Cleanup
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. 连接
// List all connections
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
    Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}

// Get specific connection
AIProjectConnection conn = projectClient.Connections.GetConnection(
    connectionName, 
    includeCredentials: false);

// Get default connection
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
    includeCredentials: false);
4. 部署
// List all deployments
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
    Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}

// Filter by publisher
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
    Console.WriteLine(deployment.Name);
}

// Get specific deployment
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
5. 数据集
// Upload single file
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "my-dataset",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// Upload folder
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "my-dataset",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// Get dataset
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");

// Delete dataset
projectClient.Datasets.Delete("my-dataset", "1.0");
6. 索引
// Create Azure AI Search index
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Sample Index"
};

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

// List indexes
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
    Console.WriteLine(index.Name);
}

// Delete index
projectClient.Indexes.Delete(name: "my-index", version: "1.0");
7. 评估
// Create evaluation configuration
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));

// Create evaluation
Evaluation evaluation = new Evaluation(
    data: new InputDataset("<dataset_id>"),
    evaluators: new Dictionary<string, EvaluatorConfiguration> 
    { 
        { "relevance", evaluatorConfig } 
    }
)
{
    DisplayName = "Sample Evaluation"
};

// Run evaluation
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);

// Get evaluation
Evaluation getResult = projectClient.Evaluations.Get(result.Name);

// List evaluations
foreach (var eval in projectClient.Evaluations.GetAll())
{
    Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}
8. 获取 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("Invalid URI.");

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

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

ChatCompletion result = chatClient.CompleteChat("List all rainbow colors");
Console.WriteLine(result.Content[0].Text);

可用的 Agent 工具

工具类用途
代码解释器CodeInterpreterToolDefinition执行 Python 代码
文件搜索FileSearchToolDefinition搜索已上传的文件
函数调用FunctionToolDefinition调用自定义函数
Bing GroundingBingGroundingToolDefinition通过 Bing 搜索网页
Azure AI SearchAzureAISearchToolDefinition搜索 Azure AI 索引
OpenAPIOpenApiToolDefinition调用外部 API
Azure FunctionsAzureFunctionToolDefinition调用 Azure Functions
MCPMCPToolDefinitionModel Context Protocol 工具

关键类型参考

类型用途
AIProjectClient主入口
PersistentAgentsClient底层 Agent 操作
PromptAgentDefinition版本化 Agent 定义
AgentVersion版本化 Agent 实例
AIProjectConnection与 Azure 资源的连接
AIProjectDeployment模型部署信息
AIProjectDataset数据集元数据
AIProjectIndex搜索索引元数据
Evaluation评估配置和结果

最佳实践

  1. 在生产环境身份验证中使用 DefaultAzureCredential
  2. 所有 I/O 操作均使用异步方法(*Async)
  3. 等待运行完成时采用适当的轮询间隔(建议 500ms)
  4. 清理资源——完成后删除线程、Agent 和文件
  5. 在生产场景中使用版本化 Agent(通过 Azure.AI.Projects.OpenAI)
  6. 工具配置中存储连接 ID,而不是名称
  7. 仅在需要凭据时使用 includeCredentials: true
  8. 处理分页——使用 AsyncPageable<T> 执行列表操作

错误处理

using Azure;

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

相关 SDK

SDK用途安装
Azure.AI.Projects高级项目客户端(此 SDK)dotnet add package Azure.AI.Projects
Azure.AI.Agents.Persistent底层 Agent 操作dotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAI使用 OpenAI 的版本化 Agentdotnet add package Azure.AI.Projects.OpenAI

参考链接

资源URL
NuGet 包https://www.nuget.org/packages/Azure.AI.Projects
API 参考https://learn.microsoft.com/dotnet/api/azure.ai.projects
GitHub 源码https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects
示例https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects/samples

适用场景

此技能适用于执行概述中描述的工作流或操作。

限制

  • 仅当任务明确符合上述范围时,才使用此技能。
  • 不要将输出视为特定环境验证、测试或专家评审的替代品。
  • 如果缺少必需的输入、权限、安全边界或成功标准,请停止并请求澄清。

评论

支持 Markdown