-
Notifications
You must be signed in to change notification settings - Fork 50
Implement artifact streaming with append and sealing semantics #280
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
darrelmiller
wants to merge
5
commits into
main
Choose a base branch
from
enable-streaming-artifacts
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
d179289
feat: Implement artifact streaming with append and sealing semantics
darrelmiller edc2ea4
feat: Add StreamingArtifactAgent for streaming story generation and u…
darrelmiller 49ff840
feat: Refactor artifact update logic into ArtifactHelper and remove U…
darrelmiller cdef63d
feat: Add terminal state checks to TaskManager and corresponding unit…
darrelmiller 54cbebd
feat: Update CORS policy to allow specific local development origins
darrelmiller 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
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,109 @@ | ||
| using A2A; | ||
|
|
||
| namespace AgentServer; | ||
|
|
||
| /// <summary> | ||
| /// A sample agent that demonstrates streaming artifacts using TaskArtifactUpdateEvent. | ||
| /// It generates a story in chunks, streaming each paragraph as a separate artifact update. | ||
| /// </summary> | ||
| public class StreamingArtifactAgent | ||
| { | ||
| private ITaskManager? _taskManager; | ||
|
|
||
| public void Attach(ITaskManager taskManager) | ||
| { | ||
| _taskManager = taskManager; | ||
| taskManager.OnTaskCreated = ProcessMessageAsync; | ||
| taskManager.OnAgentCardQuery = GetAgentCardAsync; | ||
| } | ||
|
|
||
| private async Task ProcessMessageAsync(AgentTask task, CancellationToken cancellationToken) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| var lastMessage = task.History!.Last(); | ||
| var prompt = lastMessage.Parts.OfType<TextPart>().FirstOrDefault()?.Text ?? "a mysterious journey"; | ||
|
|
||
| await _taskManager!.UpdateStatusAsync( | ||
| task.Id, | ||
| status: TaskState.Working, | ||
| cancellationToken: cancellationToken); | ||
|
|
||
| // Stream a story as multiple artifact chunks | ||
| var artifactId = $"story-{Guid.NewGuid():N}"; | ||
| var paragraphs = GenerateStory(prompt); | ||
|
|
||
| for (int i = 0; i < paragraphs.Length; i++) | ||
| { | ||
| bool isFirst = i == 0; | ||
| bool isLast = i == paragraphs.Length - 1; | ||
|
|
||
| await _taskManager.ReturnArtifactStreamAsync(new TaskArtifactUpdateEvent | ||
| { | ||
| TaskId = task.Id, | ||
| Artifact = new Artifact | ||
| { | ||
| ArtifactId = artifactId, | ||
| Name = isFirst ? $"Story: {prompt}" : null, | ||
| Description = isFirst ? "A story generated in streaming chunks" : null, | ||
| Parts = [new TextPart { Text = paragraphs[i] }] | ||
| }, | ||
| Append = !isFirst, | ||
| LastChunk = isLast | ||
| }, cancellationToken: cancellationToken); | ||
|
|
||
| // Simulate generation delay | ||
| await Task.Delay(500, cancellationToken); | ||
| } | ||
|
|
||
| await _taskManager.UpdateStatusAsync( | ||
| task.Id, | ||
| status: TaskState.Completed, | ||
| final: true, | ||
| cancellationToken: cancellationToken); | ||
| } | ||
|
|
||
| private static string[] GenerateStory(string prompt) | ||
| { | ||
| return | ||
| [ | ||
| $"Once upon a time, in a land inspired by \"{prompt}\", there lived a curious adventurer.\n\n", | ||
| "The adventurer set out on a journey through enchanted forests and across vast mountains, seeking wisdom and wonder.\n\n", | ||
| "Along the way, they encountered a wise old owl who spoke of ancient secrets hidden beneath the stars.\n\n", | ||
| "With newfound knowledge, the adventurer returned home, forever changed by the journey.\n\nThe End." | ||
| ]; | ||
| } | ||
|
|
||
| private Task<AgentCard> GetAgentCardAsync(string agentUrl, CancellationToken cancellationToken) | ||
| { | ||
| if (cancellationToken.IsCancellationRequested) | ||
| { | ||
| return Task.FromCanceled<AgentCard>(cancellationToken); | ||
| } | ||
|
|
||
| return Task.FromResult(new AgentCard | ||
| { | ||
| Name = "Streaming Story Agent", | ||
| Description = "Agent that generates stories streamed as artifact chunks, demonstrating TaskArtifactUpdateEvent with append and lastChunk semantics.", | ||
| Url = agentUrl, | ||
| Version = "1.0.0", | ||
| DefaultInputModes = ["text"], | ||
| DefaultOutputModes = ["text"], | ||
| Capabilities = new AgentCapabilities | ||
| { | ||
| Streaming = true, | ||
| PushNotifications = false, | ||
| }, | ||
| Skills = | ||
| [ | ||
| new AgentSkill | ||
| { | ||
| Id = "story-writer", | ||
| Name = "Story Writer", | ||
| Description = "Generates a short story based on a prompt, streamed in paragraph chunks.", | ||
| Tags = ["creative-writing", "streaming"] | ||
| } | ||
| ], | ||
| }); | ||
| } | ||
| } | ||
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,128 @@ | ||
| using System.Text.Json; | ||
|
|
||
| namespace A2A; | ||
|
|
||
| /// <summary> | ||
| /// Provides helper methods for applying artifact updates to tasks. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Centralizes the merge logic for <see cref="TaskArtifactUpdateEvent"/> so that all | ||
| /// <see cref="ITaskStore"/> implementations produce consistent results. | ||
| /// </remarks> | ||
| public static class ArtifactHelper | ||
| { | ||
| /// <summary> | ||
| /// Applies an artifact update to a task's artifact list using delta semantics. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// When <paramref name="append"/> is true, the update is treated as a delta: | ||
| /// <list type="bullet"> | ||
| /// <item><description><b>Parts</b>: Appended to the existing parts list.</description></item> | ||
| /// <item><description><b>Metadata</b>: Upserted — new keys are added, existing keys are updated.</description></item> | ||
| /// <item><description><b>Extensions</b>: Appended — new values are added, duplicates are ignored.</description></item> | ||
| /// <item><description><b>Name/Description</b>: Updated if non-null/non-empty in the incoming artifact.</description></item> | ||
| /// </list> | ||
| /// If no existing artifact with the same <see cref="Artifact.ArtifactId"/> is found, a new artifact is created. | ||
| /// </para> | ||
| /// <para> | ||
| /// When <paramref name="append"/> is false, the incoming artifact replaces any existing artifact | ||
| /// with the same <see cref="Artifact.ArtifactId"/>, or is added if none exists. | ||
| /// </para> | ||
| /// </remarks> | ||
| /// <param name="task">The task to update. Its <see cref="AgentTask.Artifacts"/> list will be modified in place.</param> | ||
| /// <param name="artifact">The artifact or artifact chunk to apply.</param> | ||
| /// <param name="append">If true, apply delta semantics. If false, replace.</param> | ||
| public static void ApplyArtifactUpdate(AgentTask task, Artifact artifact, bool append) | ||
| { | ||
| task.Artifacts ??= []; | ||
|
|
||
| if (append) | ||
| { | ||
| var existingIndex = task.Artifacts.FindIndex(a => a.ArtifactId == artifact.ArtifactId); | ||
| if (existingIndex >= 0) | ||
| { | ||
| var existing = task.Artifacts[existingIndex]; | ||
|
|
||
| // Parts: append | ||
| var mergedParts = new List<Part>(existing.Parts); | ||
| mergedParts.AddRange(artifact.Parts); | ||
|
|
||
| // Metadata: upsert | ||
| Dictionary<string, JsonElement>? mergedMetadata = null; | ||
| if (existing.Metadata != null || artifact.Metadata != null) | ||
| { | ||
| mergedMetadata = existing.Metadata != null ? new(existing.Metadata) : []; | ||
| if (artifact.Metadata != null) | ||
| { | ||
| foreach (var kvp in artifact.Metadata) | ||
| { | ||
| mergedMetadata[kvp.Key] = kvp.Value; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Extensions: append (deduplicated) | ||
| List<string>? mergedExtensions = null; | ||
| if (existing.Extensions != null || artifact.Extensions != null) | ||
| { | ||
| mergedExtensions = existing.Extensions != null ? [.. existing.Extensions] : []; | ||
| if (artifact.Extensions != null) | ||
| { | ||
| foreach (var ext in artifact.Extensions) | ||
| { | ||
| if (!mergedExtensions.Contains(ext)) | ||
| { | ||
| mergedExtensions.Add(ext); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Build new artifact (immutable update) | ||
| task.Artifacts[existingIndex] = new Artifact | ||
| { | ||
| ArtifactId = artifact.ArtifactId, | ||
| Name = !string.IsNullOrEmpty(artifact.Name) ? artifact.Name : existing.Name, | ||
| Description = !string.IsNullOrEmpty(artifact.Description) ? artifact.Description : existing.Description, | ||
| Parts = mergedParts, | ||
| Metadata = mergedMetadata, | ||
| Extensions = mergedExtensions | ||
| }; | ||
| } | ||
| else | ||
| { | ||
| // No existing artifact — create new copy | ||
| task.Artifacts.Add(CopyArtifact(artifact)); | ||
| } | ||
| } | ||
| else | ||
| { | ||
| // Replace or add | ||
| var artifactCopy = CopyArtifact(artifact); | ||
| var existingIndex = task.Artifacts.FindIndex(a => a.ArtifactId == artifact.ArtifactId); | ||
| if (existingIndex >= 0) | ||
| { | ||
| task.Artifacts[existingIndex] = artifactCopy; | ||
| } | ||
| else | ||
| { | ||
| task.Artifacts.Add(artifactCopy); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates a defensive copy of an artifact to prevent external mutation of stored state. | ||
| /// </summary> | ||
| /// <param name="artifact">The artifact to copy.</param> | ||
| internal static Artifact CopyArtifact(Artifact artifact) => new() | ||
| { | ||
| ArtifactId = artifact.ArtifactId, | ||
| Name = artifact.Name, | ||
| Description = artifact.Description, | ||
| Parts = [.. artifact.Parts], | ||
| Metadata = artifact.Metadata != null ? new(artifact.Metadata) : null, | ||
| Extensions = artifact.Extensions != null ? [.. artifact.Extensions] : null | ||
| }; | ||
| } |
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
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.