Azure.AI.Projects (.NET)
用於 Azure AI Foundry 專案操作的高階 SDK,包含代理程式、連線、資料集、部署、評估與索引。
安裝
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
目前版本:正式版 v1.1.0,預覽版 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>
AZURE_TOKEN_CREDENTIALS=prod
驗證
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);
用戶端階層
AIProjectClient
├── Agents → AIProjectAgentsOperations (版本化代理程式)
├── Connections → ConnectionsClient
├── Datasets → DatasetsClient
├── Deployments → DeploymentsClient
├── Evaluations → EvaluationsClient
├── Evaluators → EvaluatorsClient
├── Indexes → IndexesClient
├── Telemetry → AIProjectTelemetry
├── OpenAI → ProjectOpenAIClient (預覽版)
└── GetPersistentAgentsClient() → PersistentAgentsClient
核心工作流程
1. 取得不固定代理程式用戶端
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Math Tutor",
instructions: "你是一位個人數學家教。");
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "解出 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);
do
{
await Task.Delay(500);
run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
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. 版本化代理程式與工具(預覽版)
using Azure.AI.Projects.OpenAI;
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
Instructions = "你是一位可以搜尋網路的實用助理",
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("西雅圖的天氣如何?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. 連線
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. 部署
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. 資料集
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "my-dataset",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "my-dataset",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");
projectClient.Datasets.Delete("my-dataset", "1.0");
6. 索引
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "範例索引"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "my-index",
version: "1.0",
index: searchIndex);
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
Console.WriteLine(index.Name);
}
projectClient.Indexes.Delete(name: "my-index", version: "1.0");
7. 評估
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 = "範例評估"
};
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. 取得 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。");
uri = new Uri($"https://{uri.Host}");
AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");
ChatCompletion result = chatClient.CompleteChat("列出所有彩虹的顏色");
Console.WriteLine(result.Content[0].Text);
可用的代理程式工具
| 工具 | 類別 | 用途 |
|---|
| Code Interpreter | CodeInterpreterToolDefinition | 執行 Python 程式碼 |
| File Search | FileSearchToolDefinition | 搜尋已上傳的檔案 |
| Function Calling | FunctionToolDefinition | 呼叫自訂函式 |
| Bing Grounding | BingGroundingToolDefinition | 透過 Bing 進行網路搜尋 |
| Azure AI Search | AzureAISearchToolDefinition | 搜尋 Azure AI 索引 |
| OpenAPI | OpenApiToolDefinition | 呼叫外部 API |
| Azure Functions | AzureFunctionToolDefinition | 叫用 Azure Functions |
| MCP | MCPToolDefinition | 模型上下文協定工具 |
重要類型參考
| 類型 | 用途 |
|---|
AIProjectClient | 主要進入點 |
PersistentAgentsClient | 低階代理程式操作 |
PromptAgentDefinition | 版本化代理程式定義 |
AgentVersion | 版本化代理程式實例 |
AIProjectConnection | Azure 資源連線 |
AIProjectDeployment | 模型部署資訊 |
AIProjectDataset | 資料集中繼資料 |
AIProjectIndex | 搜尋索引中繼資料 |
Evaluation | 評估設定與結果 |
最佳實務
- 使用
DefaultAzureCredential 進行實際生產環境驗證
- 使用非同步方法 (
*Async) 進行所有 I/O 操作
- 使用適當延遲進行輪詢(建議 500 毫秒)等待執行完成
- 清理資源 — 完成後刪除執行緒、代理程式與檔案
- 使用版本化代理程式(透過
Azure.AI.Projects.OpenAI)處理實際生產環境情境
- 儲存連線 ID 而非名稱,用於工具設定
- 僅在需要時使用
includeCredentials: true
- 處理分頁 — 使用
AsyncPageable<T> 處理列出操作
錯誤處理
using Azure;
try
{
var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"錯誤:{ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
相關 SDK
| SDK | 用途 | 安裝方式 |
|---|
Azure.AI.Projects | 高階專案用戶端(此 SDK) | dotnet add package Azure.AI.Projects |
Azure.AI.Agents.Persistent | 低階代理程式操作 | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects.OpenAI | 搭配 OpenAI 的版本化代理程式 | dotnet add package Azure.AI.Projects.OpenAI |
參考連結