-
Notifications
You must be signed in to change notification settings - Fork 971
.NET SDK #38
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
ckpearson
wants to merge
13
commits into
ag-ui-protocol:main
Choose a base branch
from
ckpearson:feature/28-dotnet-sdk
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.
+5,338
−0
Open
.NET SDK #38
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
a235e78
Core message and event types implemented, earliest work of the Abstra…
ckpearson 9d7e4fc
Significant tidy up, introduced new agent constructs and fleshed out …
ckpearson eedfbc3
fix: update user field names for clarity in output
ckpearson c4cde13
Further tweaks to support not tying system message overwriting solely…
ckpearson 0f9a779
Initial work on scaffolding docs for the .NET SDK
ckpearson 9be07d8
refactor: improve formatting and structure in EchoAgent and add MapAg…
ckpearson 034ca18
Further work on .NET SDK documentation:
ckpearson cce5336
fix: change default value of IncludeContextInSystemMessage to false
ckpearson d310e7b
Enhance .NET SDK Documentation
ckpearson c2002df
fix: add ConfigureAwait(false) to asynchronous calls that aren't the …
ckpearson 7f6e3ab
feat: add options for backend tool call emission and state function h…
ckpearson df3cf87
Add AGUIDotnet.Tests project and implement initial test cases
ckpearson bb5d85d
feat: implement TestStreamingChatClient for simulating streaming resp…
ckpearson 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
Further tweaks to support not tying system message overwriting solely…
… into the context inclusion mechanism.
- Loading branch information
commit c4cde133e81eb12c4cc1348ed41df0a919d60332
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Text.Json; | ||
| using System.Threading.Channels; | ||
| using AGUIDotnet.Events; | ||
| using AGUIDotnet.Types; | ||
| using Json.Patch; | ||
| using Microsoft.Extensions.AI; | ||
|
|
||
| namespace AGUIDotnet.Agent; | ||
|
|
||
| public record StatefulChatClientAgentOptions<TState> : ChatClientAgentOptions where TState : notnull | ||
| { | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Much like <see cref="ChatClientAgent"/> but tailored for scenarios where the agent and frontend collaborate on shared state. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// This agent is NOT guaranteed to be thread-safe, nor is it resilient to shared use across multiple threads / runs, a separate instance should be used for each invocation. | ||
| /// </remarks> | ||
| /// <typeparam name="TState"></typeparam> | ||
| public class StatefulChatClientAgent<TState> : ChatClientAgent where TState : notnull | ||
| { | ||
| private TState _currentState = default!; | ||
|
|
||
| public StatefulChatClientAgent(IChatClient chatClient, TState initialState, StatefulChatClientAgentOptions<TState> agentOptions) : base(chatClient, agentOptions) | ||
| { | ||
| if (agentOptions?.SystemMessage is null) | ||
| { | ||
| throw new ArgumentException("System message must be provided for a stateful agent.", nameof(agentOptions)); | ||
| } | ||
|
|
||
| _currentState = initialState; | ||
| } | ||
|
|
||
| private TState RetrieveState() | ||
| { | ||
| return _currentState; | ||
| } | ||
|
|
||
| private void UpdateState(TState newState) | ||
| { | ||
| _currentState = newState; | ||
| } | ||
|
|
||
| protected override async ValueTask<string> PrepareSystemMessage(RunAgentInput input, string systemMessage, ImmutableList<Context> context) | ||
| { | ||
| var coreMessage = await base.PrepareSystemMessage(input, systemMessage, context); | ||
|
|
||
| // Hijack the original system message to include some context to the LLM about the stateful nature of this agent. | ||
| // Nudging it to use the state collaboration tools available to it. | ||
| return $""" | ||
| <persona> | ||
| You are a stateful agent that wraps an existing agent, allowing it to collaborate with a human in the frontend on shared state to achieve a goal. | ||
| </persona> | ||
|
|
||
| <tools> | ||
| You may have a variety of tools available to you to help achieve your goal, and state collaboration is one of them. | ||
|
|
||
| You can retrieve the current shared state of the agent using the `retrieve_state` tool, and update the shared state using the `update_state` tool. | ||
| </tools> | ||
|
|
||
| <rules> | ||
| - Wherever necessary (e.g. it is aligned with your stated goal), you MUST make use of the state collaboration tools. | ||
| - Inspect the state of the agent to understand both the current state and the schema / purpose of the state in alignment with the agent's goal. | ||
| - Liberally use the `update_state` tool to update the shared state as you progress towards your goal. | ||
| - Avoid making assumptions about the state, always retrieve it first. | ||
| - Avoid making unnecessary updates to the state, e.g. if the user intent does not require it. | ||
| </rules> | ||
|
|
||
| <underlying_agent> | ||
| {coreMessage} | ||
| </underlying_agent> | ||
| """; | ||
| } | ||
|
|
||
| protected override async ValueTask<ImmutableList<AIFunction>> PrepareBackendTools(ImmutableList<AIFunction> backendTools, RunAgentInput input, ChannelWriter<BaseEvent> events, CancellationToken cancellationToken = default) | ||
| { | ||
| return [ | ||
| .. await base.PrepareBackendTools(backendTools, input, events, cancellationToken), | ||
| AIFunctionFactory.Create( | ||
| RetrieveState, | ||
| name: "retrieve_state", | ||
| description: "Retrieves the current shared state of the agent." | ||
| ), | ||
| AIFunctionFactory.Create( | ||
| async (TState newState) => { | ||
| var delta = _currentState.CreatePatch(newState, _jsonSerOpts); | ||
| if (delta.Operations.Count > 0) { | ||
| UpdateState(newState); | ||
| await events.WriteAsync(new StateDeltaEvent { | ||
| Delta = [.. delta.Operations.Cast<object>()], | ||
| Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), | ||
| }, cancellationToken); | ||
| } | ||
| }, | ||
| name: "update_state", | ||
| description: "Updates the current shared state of the agent." | ||
| ) | ||
| ]; | ||
| } | ||
|
|
||
| protected override async ValueTask OnRunStartedAsync(RunAgentInput input, ChannelWriter<BaseEvent> events, CancellationToken cancellationToken = default) | ||
| { | ||
| // Allow the base behaviour of emitting the RunStartedEvent | ||
| await base.OnRunStartedAsync(input, events, cancellationToken); | ||
|
|
||
| // Take the initial state from the input if possible | ||
| try | ||
| { | ||
| if (input.State.ValueKind == JsonValueKind.Object) | ||
| { | ||
| var state = input.State.Deserialize<TState>(_jsonSerOpts); | ||
| if (state is not null) | ||
| { | ||
| _currentState = state; | ||
| } | ||
| } | ||
| } | ||
| catch (JsonException) | ||
| { | ||
|
|
||
| } | ||
|
|
||
| await events.WriteAsync(new StateSnapshotEvent | ||
| { | ||
| Snapshot = _currentState, | ||
| Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), | ||
| }, cancellationToken); | ||
| } | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] The empty catch block may hide potential JSON deserialization issues; consider adding a comment or logging the exception to aid future troubleshooting.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is deliberate, for now it's just to avoid failure to extract the context causing an actual problem, it just swallows the exception, but we could perhaps surface it somehow so the consumer decides what behaviour to exhibit.