步驟三:多回合對話

使用工作階段來維持交談內容,讓代理程式記得之前說過的話。

使用 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

請見 此 處的完整可執行範例應用。

完整範例會建立 Agent,並在多次呼叫之間重複使用同一個 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

完整範例可執行檔案請參閱 完整範例 。

下一步

深入探討: