-
Notifications
You must be signed in to change notification settings - Fork 2.3k
.NET: Add Foundry hosted session client samples #8227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Roger Barreto (rogerbarreto)
wants to merge
5
commits into
microsoft:main
Choose a base branch
from
rogerbarreto:hosted-foundry-session-sample
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e260200
.NET: Add Foundry hosted session client samples
rogerbarreto 4ca71f7
Merge remote-tracking branch 'origin/main' into hosted-foundry-sessio…
rogerbarreto 5ec8688
.NET: Handle closed input in hosted clients
rogerbarreto 98e7151
.NET: Clarify user isolation sample trust boundary
rogerbarreto 56fc228
.NET: Keep preview flag on direct Toolbox MCP calls
rogerbarreto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 2 additions & 0 deletions
2
.../04-hosting/FoundryHostedAgents/responses/Using-Samples/FoundryHostedSession/.env.example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| FOUNDRY_PROJECT_ENDPOINT=https://<account>.services.ai.azure.com/api/projects/<project> | ||
| AZURE_AI_AGENT_NAME=<deployed-hosted-agent-name> |
24 changes: 24 additions & 0 deletions
24
...ndryHostedAgents/responses/Using-Samples/FoundryHostedSession/FoundryHostedSession.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFrameworks>net10.0</TargetFrameworks> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled> | ||
| <RootNamespace>FoundryHostedSessionClient</RootNamespace> | ||
| <AssemblyName>foundry-hosted-session-client</AssemblyName> | ||
| <NoWarn>$(NoWarn);MEAI001;NU1605;OPENAI001</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Azure.AI.Projects" /> | ||
| <PackageReference Include="Azure.Identity" /> | ||
| <PackageReference Include="DotNetEnv" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\..\..\..\src\Microsoft.Agents.AI.Foundry\Microsoft.Agents.AI.Foundry.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
127 changes: 127 additions & 0 deletions
127
...es/04-hosting/FoundryHostedAgents/responses/Using-Samples/FoundryHostedSession/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| // Creates a Foundry hosted session explicitly, pins an Agent Framework session to it, | ||
| // reuses the hosted sandbox across turns, and deletes the hosted session on exit. | ||
|
|
||
| #pragma warning disable MEAI001 // Foundry hosted session helpers are experimental. | ||
|
|
||
| using Azure.AI.Projects; | ||
| using Azure.AI.Projects.Agents; | ||
| using Azure.Identity; | ||
| using DotNetEnv; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Agents.AI.Foundry; | ||
|
|
||
| Env.TraversePath().Load(); | ||
|
|
||
| Uri projectEndpoint = new(Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT") | ||
| ?? throw new InvalidOperationException("FOUNDRY_PROJECT_ENDPOINT is not set.")); | ||
| string agentName = Environment.GetEnvironmentVariable("AZURE_AI_AGENT_NAME") | ||
| ?? throw new InvalidOperationException("AZURE_AI_AGENT_NAME is not set."); | ||
| Uri agentEndpoint = new($"{projectEndpoint.ToString().TrimEnd('/')}/agents/{agentName}/endpoint/protocols/openai"); | ||
|
|
||
| var credential = new AzureCliCredential(); | ||
| var projectClient = new AIProjectClient(projectEndpoint, credential); | ||
| FoundryAgent agent = projectClient.AsAIAgent(agentEndpoint); | ||
| AgentAdministrationClient adminClient = projectClient.AgentAdministrationClient; | ||
|
|
||
| Console.WriteLine("Creating a Foundry hosted session..."); | ||
| ProjectsAgentRecord agentRecord = await adminClient.GetAgentAsync(agentName); | ||
| string agentVersion = agentRecord.GetLatestVersion().Version; | ||
| ProjectAgentSession hostedSession = await adminClient.CreateSessionAsync( | ||
| agentName, | ||
| new VersionRefIndicator(agentVersion)); | ||
| string hostedSessionId = hostedSession.AgentSessionId; | ||
|
|
||
| try | ||
| { | ||
| await WaitForSessionActiveAsync(adminClient, agentName, hostedSessionId); | ||
|
|
||
| ChatClientAgentSession session = await agent.CreateFoundryHostedAgentSessionAsync( | ||
| hostedSessionId: hostedSessionId); | ||
|
|
||
| Console.ForegroundColor = ConsoleColor.Cyan; | ||
| Console.WriteLine($""" | ||
| ============================================================ | ||
| Foundry Hosted Session Sample | ||
| Agent: {agentName} | ||
| Hosted session: {session.FoundryHostedAgentSessionId} | ||
|
|
||
| Every turn uses the same Foundry sandbox. Conversation history | ||
| remains a separate concern and is carried by this AgentSession. | ||
| Type a message or 'quit' to exit. | ||
| ============================================================ | ||
| """); | ||
| Console.ResetColor(); | ||
|
|
||
| while (true) | ||
| { | ||
| Console.ForegroundColor = ConsoleColor.Green; | ||
| Console.Write("You> "); | ||
| Console.ResetColor(); | ||
|
|
||
| string? input = Console.ReadLine(); | ||
| if (input is null) | ||
| { | ||
| break; | ||
| } | ||
|
|
||
| if (string.IsNullOrWhiteSpace(input)) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (input.Equals("quit", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| break; | ||
| } | ||
|
|
||
| Console.ForegroundColor = ConsoleColor.Yellow; | ||
| Console.Write("Agent> "); | ||
| Console.ResetColor(); | ||
|
|
||
| await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(input, session)) | ||
| { | ||
| Console.Write(update); | ||
| } | ||
|
|
||
| Console.WriteLine(); | ||
| Console.WriteLine(); | ||
| } | ||
| } | ||
| finally | ||
| { | ||
| Console.WriteLine($"Deleting hosted session {hostedSessionId}..."); | ||
| await adminClient.DeleteSessionAsync(agentName, hostedSessionId); | ||
| } | ||
|
|
||
| static async Task WaitForSessionActiveAsync( | ||
| AgentAdministrationClient adminClient, | ||
| string agentName, | ||
| string sessionId, | ||
| CancellationToken cancellationToken = default) | ||
| { | ||
| TimeSpan timeout = TimeSpan.FromMinutes(3); | ||
| DateTimeOffset deadline = DateTimeOffset.UtcNow + timeout; | ||
| ProjectAgentSession session = await adminClient.GetSessionAsync(agentName, sessionId, cancellationToken); | ||
|
|
||
| while (session.Status != AgentSessionStatus.Active) | ||
| { | ||
| if (session.Status == AgentSessionStatus.Failed | ||
| || session.Status == AgentSessionStatus.Deleted | ||
| || session.Status == AgentSessionStatus.Expired) | ||
| { | ||
| throw new InvalidOperationException( | ||
| $"Hosted session '{sessionId}' entered terminal status '{session.Status}'."); | ||
| } | ||
|
|
||
| if (DateTimeOffset.UtcNow >= deadline) | ||
| { | ||
| throw new TimeoutException( | ||
| $"Hosted session '{sessionId}' did not become active within {timeout.TotalSeconds:F0} seconds. Last status: {session.Status}."); | ||
| } | ||
|
|
||
| await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); | ||
| session = await adminClient.GetSessionAsync(agentName, sessionId, cancellationToken); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.