Passaggio 3: Conversazioni a più turni

Usare una sessione per mantenere il contesto della conversazione in modo che l'agente ricordi ciò che è stato detto in precedenza.

Usare AgentSession per mantenere il contesto tra più chiamate:

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));

Avvertimento

DefaultAzureCredential è utile per lo sviluppo, ma richiede un'attenta considerazione nell'ambiente di produzione. Nell'ambiente di produzione prendere in considerazione l'uso di credenziali specifiche ,ad esempio ManagedIdentityCredential, per evitare problemi di latenza, probe di credenziali indesiderate e potenziali rischi per la sicurezza dai meccanismi di fallback.

Tip

Vedere qui per un'applicazione di esempio eseguibile completa.

L'esempio completo crea un agente e ne riutilizza un AgentSession tra più chiamate:

# Copyright (c) Microsoft. All rights reserved.

import asyncio

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

"""
Multi-Turn Conversations — Use AgentSession to maintain context

This sample shows how to keep conversation history across multiple calls
by reusing the same session object.
"""


async def main() -> None:
    # <create_agent>
    client = FoundryChatClient(
        project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
        model="gpt-4o",
        credential=AzureCliCredential(),
    )

    agent = Agent(
        client=client,
        name="ConversationAgent",
        instructions="You are a friendly assistant. Keep your answers brief.",
    )
    # </create_agent>

    # <multi_turn>
    # Create a session to maintain conversation history
    session = agent.create_session()

    # First turn
    result = await agent.run("My name is Alice and I love hiking.", session=session)
    print(f"Agent: {result}\n")

    # Second turn — the agent should remember the user's name and hobby
    result = await agent.run("What do you remember about me?", session=session)
    print(f"Agent: {result}")
    # </multi_turn>


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

Tip

Vedere l'esempio completo per il file eseguibile completo.

Usare agent.Session per mantenere il contesto tra più chiamate:

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

Vedere l'esempio completo per il file eseguibile completo.

Passaggi successivi

Approfondimento: