3단계: 다중 회차 대화

에이전트가 이전에 말한 내용을 기억하도록 세션을 사용하여 대화 컨텍스트를 유지합니다.

여러 호출에서 컨텍스트를 유지하는 데 사용합니다 AgentSession .

using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a friendly assistant. Keep your answers brief.",
        name: "ConversationAgent");

// Create a session to maintain conversation history
AgentSession session = await agent.CreateSessionAsync();

// First turn
Console.WriteLine(await agent.RunAsync("My name is Alice and I love hiking.", session));

// Second turn — the agent remembers the user's name and hobby
Console.WriteLine(await agent.RunAsync("What do you remember about me?", session));

Warning

DefaultAzureCredential 은 개발에 편리하지만 프로덕션 환경에서 신중하게 고려해야 합니다. 프로덕션 환경에서는 특정 자격 증명(예: ManagedIdentityCredential)을 사용하여 대기 시간 문제, 의도하지 않은 자격 증명 검색 및 대체 메커니즘의 잠재적인 보안 위험을 방지하는 것이 좋습니다.

Tip

전체 실행 가능한 샘플 애플리케이션은 여기 를 참조하세요.

전체 샘플은 에이전트를 만들고 여러 호출에서 하나의 AgentSession를 다시 사용합니다.

import asyncio

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential


async def main() -> None:
    agent = Agent(
        client=FoundryChatClient(
            project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
            model="gpt-6-luna",
            credential=AzureCliCredential(),
        ),
        instructions="You are a friendly assistant. Keep your answers brief.",
    )
    session = agent.create_session()

    print(await agent.run("My name is Alice and I love hiking.", session=session))
    print(await agent.run("What do you remember about me?", session=session))


if __name__ == "__main__":
    asyncio.run(main())

Tip

전체 실행 가능한 파일에 대한 전체 샘플을 참조하세요.

여러 호출에서 컨텍스트를 유지하는 데 사용합니다 agent.Session .

a := foundryprovider.NewAgent(
    endpoint,
    token,
    foundryprovider.ModelDeployment(model),
    foundryprovider.AgentConfig{
        Instructions: "You are a friendly assistant. Keep your answers brief.",
        Config: agent.Config{
            Name: "ConversationAgent",
        },
    },
)

ctx := context.Background()

// Create a session to maintain conversation history.
session, err := a.CreateSession(ctx)
if err != nil {
    panic(err)
}

// First turn.
resp, err := a.RunText(ctx, "My name is Alice and I love hiking.", agent.WithSession(session)).Collect()
fmt.Println(resp, err)

// Second turn — the agent remembers the user's name and hobby.
resp, err = a.RunText(ctx, "What do you remember about me?", agent.WithSession(session)).Collect()
fmt.Println(resp, err)

Tip

전체 실행 가능한 파일에 대한 전체 샘플을 참조하세요.

다음 단계

더 자세히 살펴보기: