New to Claude Skills? Learn how to install them →

sickn33 on GitHub

Azure AI Agents Persistent SDK

Free

Create and manage persistent AI agents in .NET.

Get this skill

Free · Opens the source repo

What Azure AI Agents Persistent SDK does

The Azure AI Agents Persistent SDK for .NET is a low-level software development kit designed for developers looking to create and manage AI agents with persistence capabilities. This SDK allows for the management of threads, messages, runs, and tools, making it a versatile choice for building intelligent systems that require stateful interactions. With its straightforward API, developers can easily set up agents that can handle complex tasks and maintain context over time.

Installation is simple, requiring just a few commands to add the necessary packages via the .NET CLI. Once installed, you can configure your environment with required variables such as the project endpoint and model deployment name. The SDK provides a structured client hierarchy that includes components for administration, thread management, message operations, run execution, file handling, and vector store management, allowing for comprehensive control over your AI agents.

The core workflow of the SDK is designed to facilitate the creation of agents, the management of threads and messages, and the execution of runs. Developers can create agents with specific instructions and tools, manage conversations through threads, and retrieve messages in a structured manner. The SDK also supports streaming responses, enabling real-time interaction with agents. Additionally, it includes functionality for handling function calls and integrating external resources, such as file uploads and vector stores, enhancing the capabilities of the agents you build.

This SDK is particularly suited for developers and designers who are building applications that require persistent AI interactions, such as chatbots, tutoring systems, or any application where stateful conversation is essential. Its low-level nature provides flexibility for custom implementations while maintaining the power of Azure's AI capabilities.

When to use it

Use this SDK when you need to build .NET applications that require persistent AI agents capable of handling stateful interactions and complex tasks.

When not to use it

This SDK may not be suitable for those looking for high-level abstractions or quick prototypes, as it requires a solid understanding of .NET and AI agent architecture.

What you can build with it

Building a Math Tutoring Agent

Create an agent that can assist users with math problems by processing requests and providing solutions.

Developing a Weather Bot

Implement a bot that retrieves and provides weather information based on user queries.

Creating a Document Assistant

Build an agent that helps users find information within uploaded documents using vector search.

How to install Azure AI Agents Persistent SDK

View source

1. Install with the skills CLI

npx skills add sickn33/agentic-awesome-skills/azure-ai-agents-persistent-dotnet --agent claude-code

2. Or install it manually

Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.

Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs

Inside SKILL.md

Written by sickn33

Azure.AI.Agents.Persistent (.NET)

Low-level SDK for creating and managing persistent AI agents with threads, messages, runs, and tools.

Installation

dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity

Current Versions: Stable v1.1.0, Preview v1.2.0-beta.8

Environment Variables

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>

Authentication

using Azure.AI.Agents.Persistent;
using Azure.Identity;

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

Client Hierarchy

PersistentAgentsClient
├── Administration  → Agent CRUD operations
├── Threads         → Thread management
├── Messages        → Message operations
├── Runs            → Run execution and streaming
├── Files           → File upload/download
└── VectorStores    → Vector store management

Core Workflow

1. Create Agent

var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Math Tutor",
    instructions: "You are a personal math tutor. Write and run code to answer math questions.",
    tools: [new CodeInterpreterToolDefinition()]
);

2. Create Thread and Message

// Create thread
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// Create message
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "I need to solve the equation `3x + 11 = 14`. Can you help me?"
);

3. Run Agent (Polling)

// Create run
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe."
);

// Poll for completion
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);

// Retrieve messages
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. Streaming Response

AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
    thread.Id, 
    agent.Id
);

await foreach (StreamingUpdate update in stream)
{
    if (update.UpdateKind == StreamingUpdateReason.RunCreated)
    {
        Console.WriteLine("--- Run started! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- Run completed! ---");
    }
}

5. Function Calling

// Define function tool
FunctionToolDefinition weatherTool = new(
    name: "getCurrentWeather",
    description: "Gets the current weather at a location.",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Location = new { Type = "string", Description = "City and state, e.g. San Francisco, CA" },
            Unit = new { Type = "string", Enum = new[] { "c", "f" } }
        },
        Required = new[] { "location" }
    }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);

// Create agent with function
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Weather Bot",
    instructions: "You are a weather bot.",
    tools: [weatherTool]
);

// Handle function calls during polling
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)
            {
                // Execute function and get result
                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. File Search with Vector Store

// Upload file
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
    filePath: "document.txt",
    purpose: PersistentAgentFilePurpose.Agents
);

// Create vector store
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "my_vector_store"
);

// Create file search resource
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// Create agent with file search
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Document Assistant",
    instructions: "You help users find information in documents.",
    tools: [new FileSearchToolDefinition()],
    toolResources: new ToolResources { FileSearch = fileSearchResource }
);

7. Bing Grounding

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: "Search Agent",
    instructions: "Use Bing to answer questions about current events.",
    tools: [bingTool]
);

8. Azure AI Search

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: "Search Agent",
    instructions: "Search the documentation index to answer questions.",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: new ToolResources { AzureAISearch = searchResource }
);

9. Cleanup

await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);

Available Tools

ToolClassPurpose
Code InterpreterCodeInterpreterToolDefinitionExecute Python code, generate visualizations
File SearchFileSearchToolDefinitionSearch uploaded files via vector stores
Function CallingFunctionToolDefinitionCall custom functions
Bing GroundingBingGroundingToolDefinitionWeb search via Bing
Azure AI SearchAzureAISearchToolDefinitionSearch Azure AI Search indexes
OpenAPIOpenApiToolDefinitionCall external APIs via OpenAPI spec
Azure FunctionsAzureFunctionToolDefinitionInvoke Azure Functions
MCPMCPToolDefinitionModel Context Protocol tools
SharePointSharepointToolDefinitionAccess SharePoint content
Microsoft FabricMicrosoftFabricToolDefinitionAccess Fabric data

Streaming Update Types

Update TypeDescription
StreamingUpdateReason.RunCreatedRun started
StreamingUpdateReason.RunInProgressRun processing
StreamingUpdateReason.RunCompletedRun finished
StreamingUpdateReason.RunFailedRun errored
MessageContentUpdateText content chunk
RunStepUpdateStep status change

Key Types Reference

TypePurpose
PersistentAgentsClientMain entry point
PersistentAgentAgent with model, instructions, tools
PersistentAgentThreadConversation thread
PersistentThreadMessageMessage in thread
ThreadRunExecution of agent against thread
RunStatusQueued, InProgress, RequiresAction, Completed, Failed
ToolResourcesCombined tool resources
ToolOutputFunction call response

Best Practices

  1. Always dispose clients — Use using statements or explicit disposal
  2. Poll with appropriate delays — 500ms recommended between status checks
  3. Clean up resources — Delete threads and agents when done
  4. Handle all run statuses — Check for RequiresAction, Failed, Cancelled
  5. Use streaming for real-time UX — Better user experience than polling
  6. Store IDs not objects — Reference agents/threads by ID
  7. Use async methods — All operations should be async

Error Handling

using Azure;

try
{
    var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Resource not found");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

Related SDKs

SDKPurposeInstall
Azure.AI.Agents.PersistentLow-level agents (this SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.ProjectsHigh-level project clientdotnet add package Azure.AI.Projects

Reference Links

ResourceURL
NuGet Packagehttps://www.nuget.org/packages/Azure.AI.Agents.Persistent
API Referencehttps://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
GitHub Sourcehttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
Sampleshttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples

When to Use

This skill is applicable to execute the workflow or actions described in the overview.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Frequently asked questions about Azure AI Agents Persistent SDK

Similar skills