Azure.AI.Agents.Persistent (.NET)
用于创建和管理持久化 AI 代理的低级 SDK,支持线程、消息、运行和工具操作。
安装
dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity
当前版本:稳定版 v1.1.0,预览版 v1.2.0-beta.8
环境变量
PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>
MODEL_DEPLOYMENT_NAME=gpt-4o-mini
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>
AZURE_TOKEN_CREDENTIALS=prod
身份验证
using Azure.AI.Agents.Persistent;
using Azure.Identity;
var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
PersistentAgentsClient client = new(projectEndpoint, credential);
客户端层次结构
PersistentAgentsClient
├── Administration → 代理 CRUD 操作
├── Threads → 线程管理
├── Messages → 消息操作
├── Runs → 运行执行和流式传输
├── Files → 文件上传/下载
└── VectorStores → 向量存储管理
核心工作流
1. 创建代理
var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "Math Tutor",
instructions: "你是一名个人数学导师。编写并运行代码来回答数学问题。",
tools: [new CodeInterpreterToolDefinition()]
);
2. 创建线程和消息
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();
await client.Messages.CreateMessageAsync(
thread.Id,
MessageRole.User,
"我需要解方程 `3x + 11 = 14`。你能帮我吗?"
);
3. 运行代理(轮询)
ThreadRun run = await client.Runs.CreateRunAsync(
thread.Id,
agent.Id,
additionalInstructions: "请称呼用户为 Jane Doe。"
);
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
run = await client.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
await foreach (PersistentThreadMessage message in client.Messages.GetMessagesAsync(
threadId: thread.Id,
order: ListSortOrder.Ascending))
{
Console.Write($"{message.Role}: ");
foreach (MessageContent content in message.ContentItems)
{
if (content is MessageTextContent textContent)
Console.WriteLine(textContent.Text);
}
}
4. 流式响应
AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
thread.Id,
agent.Id
);
await foreach (StreamingUpdate update in stream)
{
if (update.UpdateKind == StreamingUpdateReason.RunCreated)
{
Console.WriteLine("--- 运行开始! ---");
}
else if (update is MessageContentUpdate contentUpdate)
{
Console.Write(contentUpdate.Text);
}
else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
{
Console.WriteLine("\n--- 运行完成! ---");
}
}
5. 函数调用
FunctionToolDefinition weatherTool = new(
name: "getCurrentWeather",
description: "获取某个地点的当前天气。",
parameters: BinaryData.FromObjectAsJson(new
{
Type = "object",
Properties = new
{
Location = new { Type = "string", Description = "城市和州,例如 San Francisco, CA" },
Unit = new { Type = "string", Enum = new[] { "c", "f" } }
},
Required = new[] { "location" }
}, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "天气机器人",
instructions: "你是一个天气机器人。",
tools: [weatherTool]
);
do
{
await Task.Delay(500);
run = await client.Runs.GetRunAsync(thread.Id, run.Id);
if (run.Status == RunStatus.RequiresAction
&& run.RequiredAction is SubmitToolOutputsAction submitAction)
{
List<ToolOutput> outputs = [];
foreach (RequiredToolCall toolCall in submitAction.ToolCalls)
{
if (toolCall is RequiredFunctionToolCall funcCall)
{
string result = ExecuteFunction(funcCall.Name, funcCall.Arguments);
outputs.Add(new ToolOutput(toolCall, result));
}
}
run = await client.Runs.SubmitToolOutputsToRunAsync(run, outputs, toolApprovals: null);
}
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
6. 使用向量存储进行文件搜索
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
filePath: "document.txt",
purpose: PersistentAgentFilePurpose.Agents
);
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
fileIds: [file.Id],
name: "my_vector_store"
);
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "文档助手",
instructions: "你帮助用户在文档中查找信息。",
tools: [new FileSearchToolDefinition()],
toolResources: new ToolResources { FileSearch = fileSearchResource }
);
7. Bing 接地
var bingConnectionId = Environment.GetEnvironmentVariable("AZURE_BING_CONNECTION_ID");
BingGroundingToolDefinition bingTool = new(
new BingGroundingSearchToolParameters(
[new BingGroundingSearchConfiguration(bingConnectionId)]
)
);
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "搜索代理",
instructions: "使用 Bing 回答有关时事的问题。",
tools: [bingTool]
);
8. Azure AI 搜索
AzureAISearchToolResource searchResource = new(
connectionId: searchConnectionId,
indexName: "my_index",
topK: 5,
filter: "category eq 'documentation'",
queryType: AzureAISearchQueryType.Simple
);
PersistentAgent agent = await client.Administration.CreateAgentAsync(
model: modelDeploymentName,
name: "搜索代理",
instructions: "搜索文档索引以回答问题。",
tools: [new AzureAISearchToolDefinition()],
toolResources: new ToolResources { AzureAISearch = searchResource }
);
9. 清理
await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);
可用工具
| 工具 | 类 | 用途 |
|---|
| 代码解释器 | CodeInterpreterToolDefinition | 执行 Python 代码,生成可视化 |
| 文件搜索 | FileSearchToolDefinition | 通过向量存储搜索上传的文件 |
| 函数调用 | FunctionToolDefinition | 调用自定义函数 |
| Bing 接地 | BingGroundingToolDefinition | 通过 Bing 进行网络搜索 |
| Azure AI 搜索 | AzureAISearchToolDefinition | 搜索 Azure AI 搜索索引 |
| OpenAPI | OpenApiToolDefinition | 通过 OpenAPI 规范调用外部 API |
| Azure Functions | AzureFunctionToolDefinition | 调用 Azure Functions |
| MCP | MCPToolDefinition | 模型上下文协议工具 |
| SharePoint | SharepointToolDefinition | 访问 SharePoint 内容 |
| Microsoft Fabric | MicrosoftFabricToolDefinition | 访问 Fabric 数据 |
流式更新类型
| 更新类型 | 描述 |
|---|
StreamingUpdateReason.RunCreated | 运行开始 |
StreamingUpdateReason.RunInProgress | 运行处理中 |
StreamingUpdateReason.RunCompleted | 运行完成 |
StreamingUpdateReason.RunFailed | 运行出错 |
MessageContentUpdate | 文本内容块 |
RunStepUpdate | 步骤状态更改 |
关键类型参考
| 类型 | 用途 |
|---|
PersistentAgentsClient | 主入口点 |
PersistentAgent | 包含模型、指令、工具的代理 |
PersistentAgentThread | 会话线程 |
PersistentThreadMessage | 线程中的消息 |
ThreadRun | 代理针对线程的执行 |
RunStatus | Queued、InProgress、RequiresAction、Completed、Failed |
ToolResources | 组合工具资源 |
ToolOutput | 函数调用响应 |
最佳实践
- 始终释放客户端 — 使用 using 语句或显式释放
- 使用适当的延迟进行轮询 — 建议状态检查间隔为 500ms
- 清理资源 — 完成后删除线程和代理
- 处理所有运行状态 — 检查 RequiresAction、Failed、Cancelled
- 使用流式传输以获得实时用户体验 — 比轮询更好的用户体验
- 存储 ID 而非对象 — 通过 ID 引用代理/线程
- 使用异步方法 — 所有操作都应异步
错误处理
using Azure;
try
{
var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
Console.WriteLine("未找到资源");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"错误:{ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
相关 SDK
| SDK | 用途 | 安装 |
|---|
Azure.AI.Agents.Persistent | 低级代理(本 SDK) | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects | 高级项目客户端 | dotnet add package Azure.AI.Projects |
参考链接