Community라이팅 & 에디팅github.com

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. AI 에이전트와 스레드, 메시지, 실행, 도구를 생성 및 관리하기 위한 저수준 SDK입니다. 에이전트 CRUD, 대화 스레드, 스트리밍 응답, 함수 호출, 파일 검색, 코드 인터프리터에 사용됩니다.

azure-ai-agents-persistent-dotnet란 무엇인가요?

Azure.AI.Agents.Persistent(.NET)은 Azure AI 에이전트를 생성하고 관리하기 위한 저수준 SDK입니다. 이 스킬은 개발자가 에이전트의 CRUD 작업, 스레드 및 메시지 관리, 실행 및 스트리밍 응답, 함수 호출, 파일 검색, 코드 인터프리터, Bing 검색, Azure AI Search 통합 등을 프로그래밍 방식으로 처리할 수 있도록 지원합니다. 또한 다양한 도구(Code Interpreter, File Search, Function Calling, Bing Grounding, Azure AI Search, OpenAPI, Azure Functions, MCP, SharePoint, Microsoft Fabric)를 지원하며, 스트리밍 업데이트 유형을 제공하여 실시간 사용자 경험을 구현할 수 있습니다. 설치 및 환경 변수 설정이 간편하며, `PersistentAgentsClient`를 진입점으로 사용하여 에이전트와 상호 작용합니다. 이 스킬은 .NET 개발자를 대상으로 하며, Azure AI 프로젝트와 통합되어 지속적인 에이전트 기반 애플리케이션을 구축하는 데 유용합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-agents-persistent-dotnet

Installed? Explore more 라이팅 & 에디팅 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

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>  # 필수: Azure AI 프로젝트 엔드포인트
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # 필수: 모델 배포 이름
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # 필수: Bing 연결 리소스 ID
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # 필수: Azure AI Search 연결 리소스 ID
AZURE_TOKEN_CREDENTIALS=prod  # 프로덕션에서 DefaultAzureCredential을 사용하는 경우에만 필수

인증

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

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// 로컬 개발: DefaultAzureCredential. 프로덕션: AZURE_TOKEN_CREDENTIALS=prod 또는 AZURE_TOKEN_CREDENTIALS=<specific_credential> 설정
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 또는 프로덕션에서 특정 자격 증명을 직접 사용:
// https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes 참조
// var credential = new ManagedIdentityCredential();
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: "You are a personal math tutor. Write and run code to answer math questions.",
    tools: [new CodeInterpreterToolDefinition()]
);

2. 스레드 및 메시지 생성

// 스레드 생성
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

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

3. 에이전트 실행 (폴링)

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

// 완료될 때까지 폴링
할
{
    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("--- Run started! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- Run completed! ---");
    }
}

5. 함수 호출

// 함수 도구 정의
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 })
);

// 함수로 에이전트 생성
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Weather Bot",
    instructions: "You are a weather bot.",
    tools: [weatherTool]
);

// 폴링 중 함수 호출 처리
할
{
    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: "Document Assistant",
    instructions: "You help users find information in documents.",
    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: "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. 정리

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

사용 가능한 도구

도구클래스용도
코드 인터프리터CodeInterpreterToolDefinitionPython 코드 실행, 시각화 생성
파일 검색FileSearchToolDefinition벡터 저장소를 통해 업로드된 파일 검색
함수 호출FunctionToolDefinition사용자 정의 함수 호출
Bing 접지BingGroundingToolDefinitionBing을 통한 웹 검색
Azure AI SearchAzureAISearchToolDefinitionAzure AI Search 인덱스 검색
OpenAPIOpenApiToolDefinitionOpenAPI 사양을 통한 외부 API 호출
Azure FunctionsAzureFunctionToolDefinitionAzure Functions 호출
MCPMCPToolDefinition모델 컨텍스트 프로토콜 도구
SharePointSharepointToolDefinitionSharePoint 콘텐츠 액세스
Microsoft FabricMicrosoftFabricToolDefinitionFabric 데이터 액세스

스트리밍 업데이트 유형

업데이트 유형설명
StreamingUpdateReason.RunCreated실행 시작됨
StreamingUpdateReason.RunInProgress실행 처리 중
StreamingUpdateReason.RunCompleted실행 완료됨
StreamingUpdateReason.RunFailed실행 오류 발생
MessageContentUpdate텍스트 콘텐츠 청크
RunStepUpdate단계 상태 변경

주요 유형 참조

유형용도
PersistentAgentsClient주요 진입점
PersistentAgent모델, 지침, 도구가 있는 에이전트
PersistentAgentThread대화 스레드
PersistentThreadMessage스레드의 메시지
ThreadRun스레드에 대한 에이전트 실행
RunStatusQueued, InProgress, RequiresAction, Completed, Failed
ToolResources결합된 도구 리소스
ToolOutput함수 호출 응답

모범 사례

  1. 항상 클라이언트를 삭제 — using 문이나 명시적 삭제 사용
  2. 적절한 지연으로 폴링 — 상태 확인 간 500ms 권장
  3. 리소스 정리 — 작업 완료 후 스레드 및 에이전트 삭제
  4. 모든 실행 상태 처리 — RequiresAction, Failed, Cancelled 확인
  5. 실시간 UX에는 스트리밍 사용 — 폴링보다 사용자 경험 향상
  6. ID를 객체가 아닌 저장 — 에이전트/스레드를 ID로 참조
  7. 비동기 메서드 사용 — 모든 작업은 비동기여야 함

오류 처리

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

참조 링크

리소스URL
NuGet 패키지https://www.nuget.org/packages/Azure.AI.Agents.Persistent
API 참조https://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
GitHub 소스https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
샘플https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

관련 스킬