|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +// Creates a Foundry hosted session explicitly, pins an Agent Framework session to it, |
| 4 | +// reuses the hosted sandbox across turns, and deletes the hosted session on exit. |
| 5 | + |
| 6 | +#pragma warning disable MEAI001 // Foundry hosted session helpers are experimental. |
| 7 | + |
| 8 | +using Azure.AI.Projects; |
| 9 | +using Azure.AI.Projects.Agents; |
| 10 | +using Azure.Identity; |
| 11 | +using DotNetEnv; |
| 12 | +using Microsoft.Agents.AI; |
| 13 | +using Microsoft.Agents.AI.Foundry; |
| 14 | + |
| 15 | +Env.TraversePath().Load(); |
| 16 | + |
| 17 | +Uri projectEndpoint = new(Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") |
| 18 | + ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.")); |
| 19 | +string agentName = Environment.GetEnvironmentVariable("AZURE_AI_AGENT_NAME") |
| 20 | + ?? throw new InvalidOperationException("AZURE_AI_AGENT_NAME is not set."); |
| 21 | +Uri agentEndpoint = new($"{projectEndpoint.ToString().TrimEnd('/')}/agents/{agentName}/endpoint/protocols/openai"); |
| 22 | + |
| 23 | +var credential = new AzureCliCredential(); |
| 24 | +var projectClient = new AIProjectClient(projectEndpoint, credential); |
| 25 | +FoundryAgent agent = projectClient.AsAIAgent(agentEndpoint); |
| 26 | +AgentAdministrationClient adminClient = projectClient.AgentAdministrationClient; |
| 27 | + |
| 28 | +Console.WriteLine("Creating a Foundry hosted session..."); |
| 29 | +ProjectsAgentRecord agentRecord = await adminClient.GetAgentAsync(agentName); |
| 30 | +string agentVersion = agentRecord.GetLatestVersion().Version; |
| 31 | +ProjectAgentSession hostedSession = await adminClient.CreateSessionAsync( |
| 32 | + agentName, |
| 33 | + new VersionRefIndicator(agentVersion)); |
| 34 | +string hostedSessionId = hostedSession.AgentSessionId; |
| 35 | + |
| 36 | +try |
| 37 | +{ |
| 38 | + await WaitForSessionActiveAsync(adminClient, agentName, hostedSessionId); |
| 39 | + |
| 40 | + ChatClientAgentSession session = await agent.CreateFoundryHostedAgentSessionAsync( |
| 41 | + hostedSessionId: hostedSessionId); |
| 42 | + |
| 43 | + Console.ForegroundColor = ConsoleColor.Cyan; |
| 44 | + Console.WriteLine($""" |
| 45 | + ============================================================ |
| 46 | + Foundry Hosted Session Sample |
| 47 | + Agent: {agentName} |
| 48 | + Hosted session: {session.FoundryHostedAgentSessionId} |
| 49 | +
|
| 50 | + Every turn uses the same Foundry sandbox. Conversation history |
| 51 | + remains a separate concern and is carried by this AgentSession. |
| 52 | + Type a message or 'quit' to exit. |
| 53 | + ============================================================ |
| 54 | + """); |
| 55 | + Console.ResetColor(); |
| 56 | + |
| 57 | + while (true) |
| 58 | + { |
| 59 | + Console.ForegroundColor = ConsoleColor.Green; |
| 60 | + Console.Write("You> "); |
| 61 | + Console.ResetColor(); |
| 62 | + |
| 63 | + string? input = Console.ReadLine(); |
| 64 | + if (input is null) |
| 65 | + { |
| 66 | + break; |
| 67 | + } |
| 68 | + |
| 69 | + if (string.IsNullOrWhiteSpace(input)) |
| 70 | + { |
| 71 | + continue; |
| 72 | + } |
| 73 | + |
| 74 | + if (input.Equals("quit", StringComparison.OrdinalIgnoreCase)) |
| 75 | + { |
| 76 | + break; |
| 77 | + } |
| 78 | + |
| 79 | + Console.ForegroundColor = ConsoleColor.Yellow; |
| 80 | + Console.Write("Agent> "); |
| 81 | + Console.ResetColor(); |
| 82 | + |
| 83 | + await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, session)) |
| 84 | + { |
| 85 | + Console.Write(update); |
| 86 | + } |
| 87 | + |
| 88 | + Console.WriteLine(); |
| 89 | + Console.WriteLine(); |
| 90 | + } |
| 91 | +} |
| 92 | +finally |
| 93 | +{ |
| 94 | + Console.WriteLine($"Deleting hosted session {hostedSessionId}..."); |
| 95 | + await adminClient.DeleteSessionAsync(agentName, hostedSessionId); |
| 96 | +} |
| 97 | + |
| 98 | +static async Task WaitForSessionActiveAsync( |
| 99 | + AgentAdministrationClient adminClient, |
| 100 | + string agentName, |
| 101 | + string sessionId, |
| 102 | + CancellationToken cancellationToken = default) |
| 103 | +{ |
| 104 | + TimeSpan timeout = TimeSpan.FromMinutes(3); |
| 105 | + DateTimeOffset deadline = DateTimeOffset.UtcNow + timeout; |
| 106 | + ProjectAgentSession session = await adminClient.GetSessionAsync(agentName, sessionId, cancellationToken); |
| 107 | + |
| 108 | + while (session.Status != AgentSessionStatus.Active) |
| 109 | + { |
| 110 | + if (session.Status == AgentSessionStatus.Failed |
| 111 | + || session.Status == AgentSessionStatus.Deleted |
| 112 | + || session.Status == AgentSessionStatus.Expired) |
| 113 | + { |
| 114 | + throw new InvalidOperationException( |
| 115 | + $"Hosted session '{sessionId}' entered terminal status '{session.Status}'."); |
| 116 | + } |
| 117 | + |
| 118 | + if (DateTimeOffset.UtcNow >= deadline) |
| 119 | + { |
| 120 | + throw new TimeoutException( |
| 121 | + $"Hosted session '{sessionId}' did not become active within {timeout.TotalSeconds:F0} seconds. Last status: {session.Status}."); |
| 122 | + } |
| 123 | + |
| 124 | + await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); |
| 125 | + session = await adminClient.GetSessionAsync(agentName, sessionId, cancellationToken); |
| 126 | + } |
| 127 | +} |
0 commit comments