|
Add this skill
npx mdskills install sickn33/azure-ai-agents-persistent-dotnetComprehensive SDK reference with clear code examples and full workflow coverage
1---2name: azure-ai-agents-persistent-dotnet3description: |4 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".5package: Azure.AI.Agents.Persistent6---78# Azure.AI.Agents.Persistent (.NET)910Low-level SDK for creating and managing persistent AI agents with threads, messages, runs, and tools.1112## Installation1314```bash15dotnet add package Azure.AI.Agents.Persistent --prerelease16dotnet add package Azure.Identity17```1819**Current Versions**: Stable v1.1.0, Preview v1.2.0-beta.82021## Environment Variables2223```bash24PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>25MODEL_DEPLOYMENT_NAME=gpt-4o-mini26AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>27AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>28```2930## Authentication3132```csharp33using Azure.AI.Agents.Persistent;34using Azure.Identity;3536var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");37PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());38```3940## Client Hierarchy4142```43PersistentAgentsClient44├── Administration → Agent CRUD operations45├── Threads → Thread management46├── Messages → Message operations47├── Runs → Run execution and streaming48├── Files → File upload/download49└── VectorStores → Vector store management50```5152## Core Workflow5354### 1. Create Agent5556```csharp57var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");5859PersistentAgent agent = await client.Administration.CreateAgentAsync(60 model: modelDeploymentName,61 name: "Math Tutor",62 instructions: "You are a personal math tutor. Write and run code to answer math questions.",63 tools: [new CodeInterpreterToolDefinition()]64);65```6667### 2. Create Thread and Message6869```csharp70// Create thread71PersistentAgentThread thread = await client.Threads.CreateThreadAsync();7273// Create message74await client.Messages.CreateMessageAsync(75 thread.Id,76 MessageRole.User,77 "I need to solve the equation `3x + 11 = 14`. Can you help me?"78);79```8081### 3. Run Agent (Polling)8283```csharp84// Create run85ThreadRun run = await client.Runs.CreateRunAsync(86 thread.Id,87 agent.Id,88 additionalInstructions: "Please address the user as Jane Doe."89);9091// Poll for completion92do93{94 await Task.Delay(TimeSpan.FromMilliseconds(500));95 run = await client.Runs.GetRunAsync(thread.Id, run.Id);96}97while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);9899// Retrieve messages100await foreach (PersistentThreadMessage message in client.Messages.GetMessagesAsync(101 threadId: thread.Id,102 order: ListSortOrder.Ascending))103{104 Console.Write($"{message.Role}: ");105 foreach (MessageContent content in message.ContentItems)106 {107 if (content is MessageTextContent textContent)108 Console.WriteLine(textContent.Text);109 }110}111```112113### 4. Streaming Response114115```csharp116AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(117 thread.Id,118 agent.Id119);120121await foreach (StreamingUpdate update in stream)122{123 if (update.UpdateKind == StreamingUpdateReason.RunCreated)124 {125 Console.WriteLine("--- Run started! ---");126 }127 else if (update is MessageContentUpdate contentUpdate)128 {129 Console.Write(contentUpdate.Text);130 }131 else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)132 {133 Console.WriteLine("\n--- Run completed! ---");134 }135}136```137138### 5. Function Calling139140```csharp141// Define function tool142FunctionToolDefinition weatherTool = new(143 name: "getCurrentWeather",144 description: "Gets the current weather at a location.",145 parameters: BinaryData.FromObjectAsJson(new146 {147 Type = "object",148 Properties = new149 {150 Location = new { Type = "string", Description = "City and state, e.g. San Francisco, CA" },151 Unit = new { Type = "string", Enum = new[] { "c", "f" } }152 },153 Required = new[] { "location" }154 }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })155);156157// Create agent with function158PersistentAgent agent = await client.Administration.CreateAgentAsync(159 model: modelDeploymentName,160 name: "Weather Bot",161 instructions: "You are a weather bot.",162 tools: [weatherTool]163);164165// Handle function calls during polling166do167{168 await Task.Delay(500);169 run = await client.Runs.GetRunAsync(thread.Id, run.Id);170171 if (run.Status == RunStatus.RequiresAction172 && run.RequiredAction is SubmitToolOutputsAction submitAction)173 {174 List<ToolOutput> outputs = [];175 foreach (RequiredToolCall toolCall in submitAction.ToolCalls)176 {177 if (toolCall is RequiredFunctionToolCall funcCall)178 {179 // Execute function and get result180 string result = ExecuteFunction(funcCall.Name, funcCall.Arguments);181 outputs.Add(new ToolOutput(toolCall, result));182 }183 }184 run = await client.Runs.SubmitToolOutputsToRunAsync(run, outputs, toolApprovals: null);185 }186}187while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);188```189190### 6. File Search with Vector Store191192```csharp193// Upload file194PersistentAgentFileInfo file = await client.Files.UploadFileAsync(195 filePath: "document.txt",196 purpose: PersistentAgentFilePurpose.Agents197);198199// Create vector store200PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(201 fileIds: [file.Id],202 name: "my_vector_store"203);204205// Create file search resource206FileSearchToolResource fileSearchResource = new();207fileSearchResource.VectorStoreIds.Add(vectorStore.Id);208209// Create agent with file search210PersistentAgent agent = await client.Administration.CreateAgentAsync(211 model: modelDeploymentName,212 name: "Document Assistant",213 instructions: "You help users find information in documents.",214 tools: [new FileSearchToolDefinition()],215 toolResources: new ToolResources { FileSearch = fileSearchResource }216);217```218219### 7. Bing Grounding220221```csharp222var bingConnectionId = Environment.GetEnvironmentVariable("AZURE_BING_CONNECTION_ID");223224BingGroundingToolDefinition bingTool = new(225 new BingGroundingSearchToolParameters(226 [new BingGroundingSearchConfiguration(bingConnectionId)]227 )228);229230PersistentAgent agent = await client.Administration.CreateAgentAsync(231 model: modelDeploymentName,232 name: "Search Agent",233 instructions: "Use Bing to answer questions about current events.",234 tools: [bingTool]235);236```237238### 8. Azure AI Search239240```csharp241AzureAISearchToolResource searchResource = new(242 connectionId: searchConnectionId,243 indexName: "my_index",244 topK: 5,245 filter: "category eq 'documentation'",246 queryType: AzureAISearchQueryType.Simple247);248249PersistentAgent agent = await client.Administration.CreateAgentAsync(250 model: modelDeploymentName,251 name: "Search Agent",252 instructions: "Search the documentation index to answer questions.",253 tools: [new AzureAISearchToolDefinition()],254 toolResources: new ToolResources { AzureAISearch = searchResource }255);256```257258### 9. Cleanup259260```csharp261await client.Threads.DeleteThreadAsync(thread.Id);262await client.Administration.DeleteAgentAsync(agent.Id);263await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);264await client.Files.DeleteFileAsync(file.Id);265```266267## Available Tools268269| Tool | Class | Purpose |270|------|-------|---------|271| Code Interpreter | `CodeInterpreterToolDefinition` | Execute Python code, generate visualizations |272| File Search | `FileSearchToolDefinition` | Search uploaded files via vector stores |273| Function Calling | `FunctionToolDefinition` | Call custom functions |274| Bing Grounding | `BingGroundingToolDefinition` | Web search via Bing |275| Azure AI Search | `AzureAISearchToolDefinition` | Search Azure AI Search indexes |276| OpenAPI | `OpenApiToolDefinition` | Call external APIs via OpenAPI spec |277| Azure Functions | `AzureFunctionToolDefinition` | Invoke Azure Functions |278| MCP | `MCPToolDefinition` | Model Context Protocol tools |279| SharePoint | `SharepointToolDefinition` | Access SharePoint content |280| Microsoft Fabric | `MicrosoftFabricToolDefinition` | Access Fabric data |281282## Streaming Update Types283284| Update Type | Description |285|-------------|-------------|286| `StreamingUpdateReason.RunCreated` | Run started |287| `StreamingUpdateReason.RunInProgress` | Run processing |288| `StreamingUpdateReason.RunCompleted` | Run finished |289| `StreamingUpdateReason.RunFailed` | Run errored |290| `MessageContentUpdate` | Text content chunk |291| `RunStepUpdate` | Step status change |292293## Key Types Reference294295| Type | Purpose |296|------|---------|297| `PersistentAgentsClient` | Main entry point |298| `PersistentAgent` | Agent with model, instructions, tools |299| `PersistentAgentThread` | Conversation thread |300| `PersistentThreadMessage` | Message in thread |301| `ThreadRun` | Execution of agent against thread |302| `RunStatus` | Queued, InProgress, RequiresAction, Completed, Failed |303| `ToolResources` | Combined tool resources |304| `ToolOutput` | Function call response |305306## Best Practices3073081. **Always dispose clients** — Use `using` statements or explicit disposal3092. **Poll with appropriate delays** — 500ms recommended between status checks3103. **Clean up resources** — Delete threads and agents when done3114. **Handle all run statuses** — Check for `RequiresAction`, `Failed`, `Cancelled`3125. **Use streaming for real-time UX** — Better user experience than polling3136. **Store IDs not objects** — Reference agents/threads by ID3147. **Use async methods** — All operations should be async315316## Error Handling317318```csharp319using Azure;320321try322{323 var agent = await client.Administration.CreateAgentAsync(...);324}325catch (RequestFailedException ex) when (ex.Status == 404)326{327 Console.WriteLine("Resource not found");328}329catch (RequestFailedException ex)330{331 Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");332}333```334335## Related SDKs336337| SDK | Purpose | Install |338|-----|---------|---------|339| `Azure.AI.Agents.Persistent` | Low-level agents (this SDK) | `dotnet add package Azure.AI.Agents.Persistent` |340| `Azure.AI.Projects` | High-level project client | `dotnet add package Azure.AI.Projects` |341342## Reference Links343344| Resource | URL |345|----------|-----|346| NuGet Package | https://www.nuget.org/packages/Azure.AI.Agents.Persistent |347| API Reference | https://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent |348| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent |349| Samples | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples |350
Full transparency — inspect the skill content before installing.