mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
.NET: [BREAKING] Workflows API Review Naming Changes (Part 1?) (#4090)
* refactor: Normalize Run/RunStreaming with AIAgent * refactor: Clarify Session vs. Run -level concepts * Rename RunId to SessionId to better match Run/Session terminology in AIAgent * [BREAKING]: Will break existing checkpointed sessions in CosmosDb due to field rename * refactor: Rename and simplify interface around getting typed data out of ExternalRequest/Response * Also adds hints around using value types in PortableValue * refactor: Rename AddFanInEdge to AddFanInBarrierEdge This will prevent a breaking change later when we introduce a programmable FanIn edge, analogous to the FanOut edge's EdgeSelector. The goal, in the long run is to support a number of different FanIn scenarios, with naive FanIn (no barrier) by default, similar to FanOut. * refactor: AsAgent(this Workflow, ...) => AsAIAgent(...) * misc - part1: SwitchBuilder internal --------- Co-authored-by: Dmytro Struk <13853051+dmytrostruk@users.noreply.github.com>
This commit is contained in:
co-authored by
Dmytro Struk
parent
5fd260e11d
commit
0086d38f58
@@ -95,11 +95,11 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
public string ContainerId => this._container.Id;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask<CheckpointInfo> CreateCheckpointAsync(string runId, JsonElement value, CheckpointInfo? parent = null)
|
||||
public override async ValueTask<CheckpointInfo> CreateCheckpointAsync(string sessionId, JsonElement value, CheckpointInfo? parent = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(runId))
|
||||
if (string.IsNullOrWhiteSpace(sessionId))
|
||||
{
|
||||
throw new ArgumentException("Cannot be null or whitespace", nameof(runId));
|
||||
throw new ArgumentException("Cannot be null or whitespace", nameof(sessionId));
|
||||
}
|
||||
|
||||
#pragma warning disable CA1513 // Use ObjectDisposedException.ThrowIf - not available on all target frameworks
|
||||
@@ -110,28 +110,28 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
#pragma warning restore CA1513
|
||||
|
||||
var checkpointId = Guid.NewGuid().ToString("N");
|
||||
var checkpointInfo = new CheckpointInfo(runId, checkpointId);
|
||||
var checkpointInfo = new CheckpointInfo(sessionId, checkpointId);
|
||||
|
||||
var document = new CosmosCheckpointDocument
|
||||
{
|
||||
Id = $"{runId}_{checkpointId}",
|
||||
RunId = runId,
|
||||
Id = $"{sessionId}_{checkpointId}",
|
||||
SessionId = sessionId,
|
||||
CheckpointId = checkpointId,
|
||||
Value = JToken.Parse(value.GetRawText()),
|
||||
ParentCheckpointId = parent?.CheckpointId,
|
||||
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
|
||||
};
|
||||
|
||||
await this._container.CreateItemAsync(document, new PartitionKey(runId)).ConfigureAwait(false);
|
||||
await this._container.CreateItemAsync(document, new PartitionKey(sessionId)).ConfigureAwait(false);
|
||||
return checkpointInfo;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask<JsonElement> RetrieveCheckpointAsync(string runId, CheckpointInfo key)
|
||||
public override async ValueTask<JsonElement> RetrieveCheckpointAsync(string sessionId, CheckpointInfo key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(runId))
|
||||
if (string.IsNullOrWhiteSpace(sessionId))
|
||||
{
|
||||
throw new ArgumentException("Cannot be null or whitespace", nameof(runId));
|
||||
throw new ArgumentException("Cannot be null or whitespace", nameof(sessionId));
|
||||
}
|
||||
|
||||
if (key is null)
|
||||
@@ -146,26 +146,26 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
}
|
||||
#pragma warning restore CA1513
|
||||
|
||||
var id = $"{runId}_{key.CheckpointId}";
|
||||
var id = $"{sessionId}_{key.CheckpointId}";
|
||||
|
||||
try
|
||||
{
|
||||
var response = await this._container.ReadItemAsync<CosmosCheckpointDocument>(id, new PartitionKey(runId)).ConfigureAwait(false);
|
||||
var response = await this._container.ReadItemAsync<CosmosCheckpointDocument>(id, new PartitionKey(sessionId)).ConfigureAwait(false);
|
||||
using var document = JsonDocument.Parse(response.Resource.Value.ToString());
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
throw new InvalidOperationException($"Checkpoint with ID '{key.CheckpointId}' for run '{runId}' not found.");
|
||||
throw new InvalidOperationException($"Checkpoint with ID '{key.CheckpointId}' for session '{sessionId}' not found.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null)
|
||||
public override async ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(runId))
|
||||
if (string.IsNullOrWhiteSpace(sessionId))
|
||||
{
|
||||
throw new ArgumentException("Cannot be null or whitespace", nameof(runId));
|
||||
throw new ArgumentException("Cannot be null or whitespace", nameof(sessionId));
|
||||
}
|
||||
|
||||
#pragma warning disable CA1513 // Use ObjectDisposedException.ThrowIf - not available on all target frameworks
|
||||
@@ -176,10 +176,10 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
#pragma warning restore CA1513
|
||||
|
||||
QueryDefinition query = withParent == null
|
||||
? new QueryDefinition("SELECT c.runId, c.checkpointId FROM c WHERE c.runId = @runId ORDER BY c.timestamp ASC")
|
||||
.WithParameter("@runId", runId)
|
||||
: new QueryDefinition("SELECT c.runId, c.checkpointId FROM c WHERE c.runId = @runId AND c.parentCheckpointId = @parentCheckpointId ORDER BY c.timestamp ASC")
|
||||
.WithParameter("@runId", runId)
|
||||
? new QueryDefinition("SELECT c.sessionId, c.checkpointId FROM c WHERE c.sessionId = @sessionId ORDER BY c.timestamp ASC")
|
||||
.WithParameter("@sessionId", sessionId)
|
||||
: new QueryDefinition("SELECT c.sessionId, c.checkpointId FROM c WHERE c.sessionId = @sessionId AND c.parentCheckpointId = @parentCheckpointId ORDER BY c.timestamp ASC")
|
||||
.WithParameter("@sessionId", sessionId)
|
||||
.WithParameter("@parentCheckpointId", withParent.CheckpointId);
|
||||
|
||||
var iterator = this._container.GetItemQueryIterator<CheckpointQueryResult>(query);
|
||||
@@ -188,7 +188,7 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
while (iterator.HasMoreResults)
|
||||
{
|
||||
var response = await iterator.ReadNextAsync().ConfigureAwait(false);
|
||||
checkpoints.AddRange(response.Select(r => new CheckpointInfo(r.RunId, r.CheckpointId)));
|
||||
checkpoints.AddRange(response.Select(r => new CheckpointInfo(r.SessionId, r.CheckpointId)));
|
||||
}
|
||||
|
||||
return checkpoints;
|
||||
@@ -223,8 +223,8 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
[JsonProperty("id")]
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
[JsonProperty("runId")]
|
||||
public string RunId { get; set; } = string.Empty;
|
||||
[JsonProperty("sessionId")]
|
||||
public string SessionId { get; set; } = string.Empty;
|
||||
|
||||
[JsonProperty("checkpointId")]
|
||||
public string CheckpointId { get; set; } = string.Empty;
|
||||
@@ -245,7 +245,7 @@ public class CosmosCheckpointStore<T> : JsonCheckpointStore, IDisposable
|
||||
[SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Instantiated by Cosmos DB query deserialization")]
|
||||
private sealed class CheckpointQueryResult
|
||||
{
|
||||
public string RunId { get; set; } = string.Empty;
|
||||
public string SessionId { get; set; } = string.Empty;
|
||||
public string CheckpointId { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ public static class MicrosoftAgentAIDevUIServiceCollectionsExtensions
|
||||
var workflow = sp.GetKeyedService<Workflow>(keyAsStr);
|
||||
if (workflow is not null)
|
||||
{
|
||||
return workflow.AsAgent(name: workflow.Name);
|
||||
return workflow.AsAIAgent(name: workflow.Name);
|
||||
}
|
||||
|
||||
// another thing we can do is resolve a non-keyed workflow.
|
||||
@@ -41,7 +41,7 @@ public static class MicrosoftAgentAIDevUIServiceCollectionsExtensions
|
||||
workflow = sp.GetService<Workflow>();
|
||||
if (workflow is not null && workflow.Name?.Equals(keyAsStr, StringComparison.Ordinal) == true)
|
||||
{
|
||||
return workflow.AsAgent(name: workflow.Name);
|
||||
return workflow.AsAIAgent(name: workflow.Name);
|
||||
}
|
||||
|
||||
// and it's possible to lookup at the default-registered AIAgent
|
||||
|
||||
@@ -30,6 +30,6 @@ public static class HostedWorkflowBuilderExtensions
|
||||
var agentName = name ?? workflowName;
|
||||
|
||||
return builder.HostApplicationBuilder.AddAIAgent(agentName, (sp, key) =>
|
||||
sp.GetRequiredKeyedService<Workflow>(workflowName).AsAgent(name: key));
|
||||
sp.GetRequiredKeyedService<Workflow>(workflowName).AsAIAgent(name: key));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ public static partial class AgentWorkflowBuilder
|
||||
|
||||
ExecutorBinding end = endFactory.BindExecutor(ConcurrentEndExecutor.ExecutorId);
|
||||
|
||||
builder.AddFanInEdge(accumulators, end);
|
||||
builder.AddFanInBarrierEdge(accumulators, end);
|
||||
|
||||
builder = builder.WithOutputFrom(end);
|
||||
if (workflowName is not null)
|
||||
|
||||
@@ -7,14 +7,14 @@ using Microsoft.Shared.Diagnostics;
|
||||
namespace Microsoft.Agents.AI.Workflows;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a checkpoint with a unique identifier and a timestamp indicating when it was created.
|
||||
/// Represents a checkpoint with a unique identifier.
|
||||
/// </summary>
|
||||
public sealed class CheckpointInfo : IEquatable<CheckpointInfo>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the unique identifier for the current run.
|
||||
/// Gets the unique identifier for the current session.
|
||||
/// </summary>
|
||||
public string RunId { get; }
|
||||
public string SessionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The unique identifier for the checkpoint.
|
||||
@@ -22,37 +22,34 @@ public sealed class CheckpointInfo : IEquatable<CheckpointInfo>
|
||||
public string CheckpointId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CheckpointInfo"/> class with a unique identifier and the current
|
||||
/// UTC timestamp.
|
||||
/// Initializes a new instance of the <see cref="CheckpointInfo"/> class with a unique identifier.
|
||||
/// </summary>
|
||||
/// <remarks>This constructor generates a new unique identifier using a GUID in a 32-character, lowercase,
|
||||
/// hexadecimal format and sets the timestamp to the current UTC time.</remarks>
|
||||
internal CheckpointInfo(string runId) : this(runId, Guid.NewGuid().ToString("N")) { }
|
||||
internal CheckpointInfo(string sessionId) : this(sessionId, Guid.NewGuid().ToString("N")) { }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the CheckpointInfo class with the specified run and checkpoint identifiers.
|
||||
/// Initializes a new instance of the CheckpointInfo class with the specified session and checkpoint identifiers.
|
||||
/// </summary>
|
||||
/// <param name="runId">The unique identifier for the run. Cannot be null or empty.</param>
|
||||
/// <param name="sessionId">The unique identifier for the session. Cannot be null or empty.</param>
|
||||
/// <param name="checkpointId">The unique identifier for the checkpoint. Cannot be null or empty.</param>
|
||||
[JsonConstructor]
|
||||
public CheckpointInfo(string runId, string checkpointId)
|
||||
public CheckpointInfo(string sessionId, string checkpointId)
|
||||
{
|
||||
this.RunId = Throw.IfNullOrEmpty(runId);
|
||||
this.SessionId = Throw.IfNullOrEmpty(sessionId);
|
||||
this.CheckpointId = Throw.IfNullOrEmpty(checkpointId);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool Equals(CheckpointInfo? other) =>
|
||||
other is not null &&
|
||||
this.RunId == other.RunId &&
|
||||
this.SessionId == other.SessionId &&
|
||||
this.CheckpointId == other.CheckpointId;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override bool Equals(object? obj) => this.Equals(obj as CheckpointInfo);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override int GetHashCode() => HashCode.Combine(this.RunId, this.CheckpointId);
|
||||
public override int GetHashCode() => HashCode.Combine(this.SessionId, this.CheckpointId);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override string ToString() => $"CheckpointInfo(RunId: {this.RunId}, CheckpointId: {this.CheckpointId})";
|
||||
public override string ToString() => $"CheckpointInfo(SessionId: {this.SessionId}, CheckpointId: {this.CheckpointId})";
|
||||
}
|
||||
|
||||
@@ -50,12 +50,12 @@ public sealed class CheckpointManager : ICheckpointManager
|
||||
return new(CreateImpl(marshaller, store));
|
||||
}
|
||||
|
||||
ValueTask<CheckpointInfo> ICheckpointManager.CommitCheckpointAsync(string runId, Checkpoint checkpoint)
|
||||
=> this._impl.CommitCheckpointAsync(runId, checkpoint);
|
||||
ValueTask<CheckpointInfo> ICheckpointManager.CommitCheckpointAsync(string sessionId, Checkpoint checkpoint)
|
||||
=> this._impl.CommitCheckpointAsync(sessionId, checkpoint);
|
||||
|
||||
ValueTask<Checkpoint> ICheckpointManager.LookupCheckpointAsync(string runId, CheckpointInfo checkpointInfo)
|
||||
=> this._impl.LookupCheckpointAsync(runId, checkpointInfo);
|
||||
ValueTask<Checkpoint> ICheckpointManager.LookupCheckpointAsync(string sessionId, CheckpointInfo checkpointInfo)
|
||||
=> this._impl.LookupCheckpointAsync(sessionId, checkpointInfo);
|
||||
|
||||
ValueTask<IEnumerable<CheckpointInfo>> ICheckpointManager.RetrieveIndexAsync(string runId, CheckpointInfo? withParent)
|
||||
=> this._impl.RetrieveIndexAsync(runId, withParent);
|
||||
ValueTask<IEnumerable<CheckpointInfo>> ICheckpointManager.RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent)
|
||||
=> this._impl.RetrieveIndexAsync(sessionId, withParent);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ internal sealed partial class CheckpointInfoConverter() : JsonConverterDictionar
|
||||
protected override JsonTypeInfo<CheckpointInfo> TypeInfo
|
||||
=> WorkflowsJsonUtilities.JsonContext.Default.CheckpointInfo;
|
||||
|
||||
private const string CheckpointInfoPropertyNamePattern = @"^(?<runId>(((\|\|)|([^\|]))*))\|(?<checkpointId>(((\|\|)|([^\|]))*)?)$";
|
||||
private const string CheckpointInfoPropertyNamePattern = @"^(?<sessionId>(((\|\|)|([^\|]))*))\|(?<checkpointId>(((\|\|)|([^\|]))*)?)$";
|
||||
#if NET
|
||||
[GeneratedRegex(CheckpointInfoPropertyNamePattern, RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)]
|
||||
public static partial Regex CheckpointInfoPropertyNameRegex();
|
||||
@@ -33,17 +33,17 @@ internal sealed partial class CheckpointInfoConverter() : JsonConverterDictionar
|
||||
throw new JsonException($"Invalid CheckpointInfo property name format. Got '{propertyName}'.");
|
||||
}
|
||||
|
||||
string runId = scopeKeyPatternMatch.Groups["runId"].Value;
|
||||
string sessionId = scopeKeyPatternMatch.Groups["sessionId"].Value;
|
||||
string checkpointId = scopeKeyPatternMatch.Groups["checkpointId"].Value;
|
||||
|
||||
return new(Unescape(runId)!, Unescape(checkpointId)!);
|
||||
return new(Unescape(sessionId)!, Unescape(checkpointId)!);
|
||||
}
|
||||
|
||||
protected override string Stringify([DisallowNull] CheckpointInfo value)
|
||||
{
|
||||
string? runIdEscaped = Escape(value.RunId);
|
||||
string? sessionIdEscaped = Escape(value.SessionId);
|
||||
string? checkpointIdEscaped = Escape(value.CheckpointId);
|
||||
|
||||
return $"{runIdEscaped}|{checkpointIdEscaped}";
|
||||
return $"{sessionIdEscaped}|{checkpointIdEscaped}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,19 +16,19 @@ internal sealed class CheckpointManagerImpl<TStoreObject> : ICheckpointManager
|
||||
this._store = store;
|
||||
}
|
||||
|
||||
public ValueTask<CheckpointInfo> CommitCheckpointAsync(string runId, Checkpoint checkpoint)
|
||||
public ValueTask<CheckpointInfo> CommitCheckpointAsync(string sessionId, Checkpoint checkpoint)
|
||||
{
|
||||
TStoreObject storeObject = this._marshaller.Marshal(checkpoint);
|
||||
|
||||
return this._store.CreateCheckpointAsync(runId, storeObject, checkpoint.Parent);
|
||||
return this._store.CreateCheckpointAsync(sessionId, storeObject, checkpoint.Parent);
|
||||
}
|
||||
|
||||
public async ValueTask<Checkpoint> LookupCheckpointAsync(string runId, CheckpointInfo checkpointInfo)
|
||||
public async ValueTask<Checkpoint> LookupCheckpointAsync(string sessionId, CheckpointInfo checkpointInfo)
|
||||
{
|
||||
TStoreObject result = await this._store.RetrieveCheckpointAsync(runId, checkpointInfo).ConfigureAwait(false);
|
||||
TStoreObject result = await this._store.RetrieveCheckpointAsync(sessionId, checkpointInfo).ConfigureAwait(false);
|
||||
return this._marshaller.Marshal<Checkpoint>(result);
|
||||
}
|
||||
|
||||
public ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null)
|
||||
=> this._store.RetrieveIndexAsync(runId, withParent);
|
||||
public ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null)
|
||||
=> this._store.RetrieveIndexAsync(sessionId, withParent);
|
||||
}
|
||||
|
||||
+10
-10
@@ -93,15 +93,15 @@ public sealed class FileSystemJsonCheckpointStore : JsonCheckpointStore, IDispos
|
||||
}
|
||||
}
|
||||
|
||||
private string GetFileNameForCheckpoint(string runId, CheckpointInfo key)
|
||||
=> Path.Combine(this.Directory.FullName, $"{runId}_{key.CheckpointId}.json");
|
||||
private string GetFileNameForCheckpoint(string sessionId, CheckpointInfo key)
|
||||
=> Path.Combine(this.Directory.FullName, $"{sessionId}_{key.CheckpointId}.json");
|
||||
|
||||
private CheckpointInfo GetUnusedCheckpointInfo(string runId)
|
||||
private CheckpointInfo GetUnusedCheckpointInfo(string sessionId)
|
||||
{
|
||||
CheckpointInfo key;
|
||||
do
|
||||
{
|
||||
key = new(runId);
|
||||
key = new(sessionId);
|
||||
} while (!this.CheckpointIndex.Add(key));
|
||||
|
||||
return key;
|
||||
@@ -110,12 +110,12 @@ public sealed class FileSystemJsonCheckpointStore : JsonCheckpointStore, IDispos
|
||||
/// <inheritdoc/>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1835:Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync'",
|
||||
Justification = "Memory-based overload is missing for 4.7.2")]
|
||||
public override async ValueTask<CheckpointInfo> CreateCheckpointAsync(string runId, JsonElement value, CheckpointInfo? parent = null)
|
||||
public override async ValueTask<CheckpointInfo> CreateCheckpointAsync(string sessionId, JsonElement value, CheckpointInfo? parent = null)
|
||||
{
|
||||
this.CheckDisposed();
|
||||
|
||||
CheckpointInfo key = this.GetUnusedCheckpointInfo(runId);
|
||||
string fileName = this.GetFileNameForCheckpoint(runId, key);
|
||||
CheckpointInfo key = this.GetUnusedCheckpointInfo(sessionId);
|
||||
string fileName = this.GetFileNameForCheckpoint(sessionId, key);
|
||||
try
|
||||
{
|
||||
using Stream checkpointStream = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
@@ -145,10 +145,10 @@ public sealed class FileSystemJsonCheckpointStore : JsonCheckpointStore, IDispos
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async ValueTask<JsonElement> RetrieveCheckpointAsync(string runId, CheckpointInfo key)
|
||||
public override async ValueTask<JsonElement> RetrieveCheckpointAsync(string sessionId, CheckpointInfo key)
|
||||
{
|
||||
this.CheckDisposed();
|
||||
string fileName = this.GetFileNameForCheckpoint(runId, key);
|
||||
string fileName = this.GetFileNameForCheckpoint(sessionId, key);
|
||||
|
||||
if (!this.CheckpointIndex.Contains(key) ||
|
||||
!File.Exists(fileName))
|
||||
@@ -163,7 +163,7 @@ public sealed class FileSystemJsonCheckpointStore : JsonCheckpointStore, IDispos
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null)
|
||||
public override ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null)
|
||||
{
|
||||
this.CheckDisposed();
|
||||
|
||||
|
||||
@@ -13,30 +13,30 @@ internal interface ICheckpointManager
|
||||
/// <summary>
|
||||
/// Commits the specified checkpoint and returns information that can be used to retrieve it later.
|
||||
/// </summary>
|
||||
/// <param name="runId">The identifier for the current run or execution context.</param>
|
||||
/// <param name="sessionId">The identifier for the current session or execution context.</param>
|
||||
/// <param name="checkpoint">The checkpoint to commit.</param>
|
||||
/// <returns>A <see cref="CheckpointInfo"/> representing the incoming checkpoint.</returns>
|
||||
ValueTask<CheckpointInfo> CommitCheckpointAsync(string runId, Checkpoint checkpoint);
|
||||
ValueTask<CheckpointInfo> CommitCheckpointAsync(string sessionId, Checkpoint checkpoint);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the checkpoint associated with the specified checkpoint information.
|
||||
/// </summary>
|
||||
/// <param name="runId">The identifier for the current run of execution context.</param>
|
||||
/// <param name="sessionId">The identifier for the current session of execution context.</param>
|
||||
/// <param name="checkpointInfo">The information used to identify the checkpoint.</param>
|
||||
/// <returns>A <see cref="ValueTask{TResult}"/> representing the asynchronous operation. The result contains the <see
|
||||
/// cref="Checkpoint"/> associated with the specified <paramref name="checkpointInfo"/>.</returns>
|
||||
/// <exception cref="KeyNotFoundException">Thrown if the checkpoint is not found.</exception>
|
||||
ValueTask<Checkpoint> LookupCheckpointAsync(string runId, CheckpointInfo checkpointInfo);
|
||||
ValueTask<Checkpoint> LookupCheckpointAsync(string sessionId, CheckpointInfo checkpointInfo);
|
||||
|
||||
/// <summary>
|
||||
/// Asynchronously retrieves the collection of checkpoint information for the specified run identifier, optionally
|
||||
/// Asynchronously retrieves the collection of checkpoint information for the specified session identifier, optionally
|
||||
/// filtered by a parent checkpoint.
|
||||
/// </summary>
|
||||
/// <param name="runId">The unique identifier of the run for which to retrieve checkpoint information. Cannot be null or empty.</param>
|
||||
/// <param name="sessionId">The unique identifier of the session for which to retrieve checkpoint information. Cannot be null or empty.</param>
|
||||
/// <param name="withParent">An optional parent checkpoint to filter the results. If specified, only checkpoints with the given parent are
|
||||
/// returned; otherwise, all checkpoints for the run are included.</param>
|
||||
/// returned; otherwise, all checkpoints for the session are included.</param>
|
||||
/// <returns>A value task representing the asynchronous operation. The result contains a collection of <see
|
||||
/// cref="CheckpointInfo"/> objects associated with the specified run. The collection is empty if no checkpoints are
|
||||
/// cref="CheckpointInfo"/> objects associated with the specified session. The collection is empty if no checkpoints are
|
||||
/// found.</returns>
|
||||
ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null);
|
||||
ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null);
|
||||
}
|
||||
|
||||
@@ -6,44 +6,41 @@ using System.Threading.Tasks;
|
||||
namespace Microsoft.Agents.AI.Workflows.Checkpointing;
|
||||
|
||||
/// <summary>
|
||||
/// Defines a contract for storing and retrieving checkpoints associated with a specific run and key.
|
||||
/// Defines a contract for storing and retrieving checkpoints associated with a specific session and key.
|
||||
/// </summary>
|
||||
/// <remarks>Implementations of this interface enable durable or in-memory storage of checkpoints, which can be
|
||||
/// used to resume or audit long-running processes. The interface is generic to support different storage object types
|
||||
/// depending on the application's requirements.</remarks>
|
||||
/// <typeparam name="TStoreObject">The type of object to be stored as the value for each checkpoint.</typeparam>
|
||||
public interface ICheckpointStore<TStoreObject>
|
||||
{
|
||||
/// <summary>
|
||||
/// Asynchronously retrieves the collection of checkpoint information for the specified run identifier, optionally
|
||||
/// Asynchronously retrieves the collection of checkpoint information for the specified session identifier, optionally
|
||||
/// filtered by a parent checkpoint.
|
||||
/// </summary>
|
||||
/// <param name="runId">The unique identifier of the run for which to retrieve checkpoint information. Cannot be null or empty.</param>
|
||||
/// <param name="sessionId">The unique identifier of the session for which to retrieve checkpoint information. Cannot be null or empty.</param>
|
||||
/// <param name="withParent">An optional parent checkpoint to filter the results. If specified, only checkpoints with the given parent are
|
||||
/// returned; otherwise, all checkpoints for the run are included.</param>
|
||||
/// returned; otherwise, all checkpoints for the session are included.</param>
|
||||
/// <returns>A value task representing the asynchronous operation. The result contains a collection of <see
|
||||
/// cref="CheckpointInfo"/> objects associated with the specified run. The collection is empty if no checkpoints are
|
||||
/// cref="CheckpointInfo"/> objects associated with the specified session. The collection is empty if no checkpoints are
|
||||
/// found.</returns>
|
||||
ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null);
|
||||
ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null);
|
||||
|
||||
/// <summary>
|
||||
/// Asynchronously creates a checkpoint for the specified run and key, associating it with the provided value and
|
||||
/// Asynchronously creates a checkpoint for the specified session and key, associating it with the provided value and
|
||||
/// optional parent checkpoint.
|
||||
/// </summary>
|
||||
/// <param name="runId">The unique identifier of the run for which the checkpoint is being created. Cannot be null or empty.</param>
|
||||
/// <param name="sessionId">The unique identifier of the session for which the checkpoint is being created. Cannot be null or empty.</param>
|
||||
/// <param name="value">The value to associate with the checkpoint. Cannot be null.</param>
|
||||
/// <param name="parent">The optional parent checkpoint information. If specified, the new checkpoint will be linked as a child of this
|
||||
/// parent.</param>
|
||||
/// <returns>A ValueTask that represents the asynchronous operation. The result contains the <see cref="CheckpointInfo"/>
|
||||
/// object representing this stored checkpoint.</returns>
|
||||
ValueTask<CheckpointInfo> CreateCheckpointAsync(string runId, TStoreObject value, CheckpointInfo? parent = null);
|
||||
ValueTask<CheckpointInfo> CreateCheckpointAsync(string sessionId, TStoreObject value, CheckpointInfo? parent = null);
|
||||
|
||||
/// <summary>
|
||||
/// Asynchronously retrieves a checkpoint object associated with the specified run and checkpoint key.
|
||||
/// Asynchronously retrieves a checkpoint object associated with the specified session and checkpoint key.
|
||||
/// </summary>
|
||||
/// <param name="runId">The unique identifier of the run for which the checkpoint is to be retrieved. Cannot be null or empty.</param>
|
||||
/// <param name="sessionId">The unique identifier of the session for which the checkpoint is to be retrieved. Cannot be null or empty.</param>
|
||||
/// <param name="key">The key identifying the specific checkpoint to retrieve. Cannot be null.</param>
|
||||
/// <returns>A ValueTask that represents the asynchronous operation. The result contains the checkpoint object associated
|
||||
/// with the specified run and key.</returns>
|
||||
ValueTask<TStoreObject> RetrieveCheckpointAsync(string runId, CheckpointInfo key);
|
||||
/// with the specified session and key.</returns>
|
||||
ValueTask<TStoreObject> RetrieveCheckpointAsync(string sessionId, CheckpointInfo key);
|
||||
}
|
||||
|
||||
+18
-18
@@ -13,54 +13,54 @@ namespace Microsoft.Agents.AI.Workflows.Checkpointing;
|
||||
internal sealed class InMemoryCheckpointManager : ICheckpointManager
|
||||
{
|
||||
[JsonInclude]
|
||||
internal Dictionary<string, RunCheckpointCache<Checkpoint>> Store { get; } = [];
|
||||
internal Dictionary<string, SessionCheckpointCache<Checkpoint>> Store { get; } = [];
|
||||
|
||||
public InMemoryCheckpointManager() { }
|
||||
|
||||
[JsonConstructor]
|
||||
internal InMemoryCheckpointManager(Dictionary<string, RunCheckpointCache<Checkpoint>> store)
|
||||
internal InMemoryCheckpointManager(Dictionary<string, SessionCheckpointCache<Checkpoint>> store)
|
||||
{
|
||||
this.Store = store;
|
||||
}
|
||||
|
||||
private RunCheckpointCache<Checkpoint> GetRunStore(string runId)
|
||||
private SessionCheckpointCache<Checkpoint> GetSessionStore(string sessionId)
|
||||
{
|
||||
if (!this.Store.TryGetValue(runId, out RunCheckpointCache<Checkpoint>? runStore))
|
||||
if (!this.Store.TryGetValue(sessionId, out SessionCheckpointCache<Checkpoint>? sessionStore))
|
||||
{
|
||||
runStore = this.Store[runId] = new();
|
||||
sessionStore = this.Store[sessionId] = new();
|
||||
}
|
||||
|
||||
return runStore;
|
||||
return sessionStore;
|
||||
}
|
||||
|
||||
public ValueTask<CheckpointInfo> CommitCheckpointAsync(string runId, Checkpoint checkpoint)
|
||||
public ValueTask<CheckpointInfo> CommitCheckpointAsync(string sessionId, Checkpoint checkpoint)
|
||||
{
|
||||
RunCheckpointCache<Checkpoint> runStore = this.GetRunStore(runId);
|
||||
SessionCheckpointCache<Checkpoint> sessionStore = this.GetSessionStore(sessionId);
|
||||
|
||||
CheckpointInfo key;
|
||||
do
|
||||
{
|
||||
key = new(runId);
|
||||
} while (!runStore.Add(key, checkpoint));
|
||||
key = new(sessionId);
|
||||
} while (!sessionStore.Add(key, checkpoint));
|
||||
|
||||
return new(key);
|
||||
}
|
||||
|
||||
public ValueTask<Checkpoint> LookupCheckpointAsync(string runId, CheckpointInfo checkpointInfo)
|
||||
public ValueTask<Checkpoint> LookupCheckpointAsync(string sessionId, CheckpointInfo checkpointInfo)
|
||||
{
|
||||
if (!this.GetRunStore(runId).TryGet(checkpointInfo, out Checkpoint? value))
|
||||
if (!this.GetSessionStore(sessionId).TryGet(checkpointInfo, out Checkpoint? value))
|
||||
{
|
||||
throw new KeyNotFoundException($"Could not retrieve checkpoint with id {checkpointInfo.CheckpointId} for run {runId}");
|
||||
throw new KeyNotFoundException($"Could not retrieve checkpoint with id {checkpointInfo.CheckpointId} for session {sessionId}");
|
||||
}
|
||||
|
||||
return new(value);
|
||||
}
|
||||
|
||||
internal bool HasCheckpoints(string runId) => this.GetRunStore(runId).HasCheckpoints;
|
||||
internal bool HasCheckpoints(string sessionId) => this.GetSessionStore(sessionId).HasCheckpoints;
|
||||
|
||||
public bool TryGetLastCheckpoint(string runId, [NotNullWhen(true)] out CheckpointInfo? checkpoint)
|
||||
=> this.GetRunStore(runId).TryGetLastCheckpointInfo(out checkpoint);
|
||||
public bool TryGetLastCheckpoint(string sessionId, [NotNullWhen(true)] out CheckpointInfo? checkpoint)
|
||||
=> this.GetSessionStore(sessionId).TryGetLastCheckpointInfo(out checkpoint);
|
||||
|
||||
public ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null)
|
||||
=> new(this.GetRunStore(runId).CheckpointIndex.AsReadOnly());
|
||||
public ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null)
|
||||
=> new(this.GetSessionStore(sessionId).CheckpointIndex.AsReadOnly());
|
||||
}
|
||||
|
||||
@@ -18,11 +18,11 @@ public abstract class JsonCheckpointStore : ICheckpointStore<JsonElement>
|
||||
protected static JsonTypeInfo<CheckpointInfo> KeyTypeInfo => WorkflowsJsonUtilities.JsonContext.Default.CheckpointInfo;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public abstract ValueTask<CheckpointInfo> CreateCheckpointAsync(string runId, JsonElement value, CheckpointInfo? parent = null);
|
||||
public abstract ValueTask<CheckpointInfo> CreateCheckpointAsync(string sessionId, JsonElement value, CheckpointInfo? parent = null);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public abstract ValueTask<JsonElement> RetrieveCheckpointAsync(string runId, CheckpointInfo key);
|
||||
public abstract ValueTask<JsonElement> RetrieveCheckpointAsync(string sessionId, CheckpointInfo key);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public abstract ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string runId, CheckpointInfo? withParent = null);
|
||||
public abstract ValueTask<IEnumerable<CheckpointInfo>> RetrieveIndexAsync(string sessionId, CheckpointInfo? withParent = null);
|
||||
}
|
||||
|
||||
+5
-5
@@ -6,7 +6,7 @@ using System.Text.Json.Serialization;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Checkpointing;
|
||||
|
||||
internal sealed class RunCheckpointCache<TStoreObject>
|
||||
internal sealed class SessionCheckpointCache<TStoreObject>
|
||||
{
|
||||
[JsonInclude]
|
||||
internal List<CheckpointInfo> CheckpointIndex { get; } = [];
|
||||
@@ -14,10 +14,10 @@ internal sealed class RunCheckpointCache<TStoreObject>
|
||||
[JsonInclude]
|
||||
internal Dictionary<CheckpointInfo, TStoreObject> Cache { get; } = [];
|
||||
|
||||
public RunCheckpointCache() { }
|
||||
public SessionCheckpointCache() { }
|
||||
|
||||
[JsonConstructor]
|
||||
internal RunCheckpointCache(List<CheckpointInfo> checkpointIndex, Dictionary<CheckpointInfo, TStoreObject> cache)
|
||||
internal SessionCheckpointCache(List<CheckpointInfo> checkpointIndex, Dictionary<CheckpointInfo, TStoreObject> cache)
|
||||
{
|
||||
this.CheckpointIndex = checkpointIndex;
|
||||
this.Cache = cache;
|
||||
@@ -29,13 +29,13 @@ internal sealed class RunCheckpointCache<TStoreObject>
|
||||
public bool IsInIndex(CheckpointInfo key) => this.Cache.ContainsKey(key);
|
||||
public bool TryGet(CheckpointInfo key, [MaybeNullWhen(false)] out TStoreObject value) => this.Cache.TryGetValue(key, out value);
|
||||
|
||||
public CheckpointInfo Add(string runId, TStoreObject value)
|
||||
public CheckpointInfo Add(string sessionId, TStoreObject value)
|
||||
{
|
||||
CheckpointInfo key;
|
||||
|
||||
do
|
||||
{
|
||||
key = new(runId);
|
||||
key = new(sessionId);
|
||||
} while (!this.Add(key, value));
|
||||
|
||||
return key;
|
||||
@@ -16,7 +16,7 @@ public static class ConfigurationExtensions
|
||||
/// <param name="configured">The existing configuration for the subject type to be upcast to its parent type. Cannot be null.</param>
|
||||
/// <returns>A new <see cref="Configured{TParent}"/> instance that applies the original configuration logic to the parent type.</returns>
|
||||
public static Configured<TParent> Super<TSubject, TParent>(this Configured<TSubject> configured) where TSubject : TParent
|
||||
=> new(async (config, runId) => await configured.FactoryAsync(config, runId).ConfigureAwait(false), configured.Id, configured.Raw);
|
||||
=> new(async (config, sessionId) => await configured.FactoryAsync(config, sessionId).ConfigureAwait(false), configured.Id, configured.Raw);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new configuration that treats the subject as its base type, allowing configuration to be applied at
|
||||
|
||||
@@ -79,7 +79,7 @@ public class Configured<TSubject>(Func<Config, string, ValueTask<TSubject>> fact
|
||||
/// Gets a "partially" applied factory function that only requires no parameters to create an instance of
|
||||
/// <typeparamref name="TSubject"/> with the provided <see cref="Configuration"/> instance.
|
||||
/// </summary>
|
||||
internal Func<string, ValueTask<TSubject>> BoundFactoryAsync => (runId) => this.FactoryAsync(this.Configuration, runId);
|
||||
internal Func<string, ValueTask<TSubject>> BoundFactoryAsync => (sessionId) => this.FactoryAsync(this.Configuration, sessionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -122,20 +122,20 @@ public class Configured<TSubject, TOptions>(Func<Config<TOptions>, string, Value
|
||||
/// Gets a "partially" applied factory function that only requires no parameters to create an instance of
|
||||
/// <typeparamref name="TSubject"/> with the provided <see cref="Configuration"/> instance.
|
||||
/// </summary>
|
||||
internal Func<string, ValueTask<TSubject>> BoundFactoryAsync => (runId) => this.CreateValidatingMemoizedFactory()(this.Configuration, runId);
|
||||
internal Func<string, ValueTask<TSubject>> BoundFactoryAsync => (sessionId) => this.CreateValidatingMemoizedFactory()(this.Configuration, sessionId);
|
||||
|
||||
private Func<Config, string, ValueTask<TSubject>> CreateValidatingMemoizedFactory()
|
||||
{
|
||||
return FactoryAsync;
|
||||
|
||||
async ValueTask<TSubject> FactoryAsync(Config configuration, string runId)
|
||||
async ValueTask<TSubject> FactoryAsync(Config configuration, string sessionId)
|
||||
{
|
||||
if (this.Id != configuration.Id)
|
||||
{
|
||||
throw new InvalidOperationException($"Requested instance ID '{configuration.Id}' does not match configured ID '{this.Id}'.");
|
||||
}
|
||||
|
||||
TSubject subject = await this.FactoryAsync(this.Configuration, runId).ConfigureAwait(false);
|
||||
TSubject subject = await this.FactoryAsync(this.Configuration, sessionId).ConfigureAwait(false);
|
||||
|
||||
if (this.Id is not null && subject is IIdentified identified && identified.Id != this.Id)
|
||||
{
|
||||
|
||||
@@ -44,7 +44,7 @@ internal sealed class AsyncRunHandle : ICheckpointingHandle, IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
public string RunId => this._stepRunner.RunId;
|
||||
public string SessionId => this._stepRunner.SessionId;
|
||||
|
||||
public bool IsCheckpointingEnabled => this._checkpointingHandle.IsCheckpointingEnabled;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace Microsoft.Agents.AI.Workflows.Execution;
|
||||
|
||||
internal interface ISuperStepRunner
|
||||
{
|
||||
string RunId { get; }
|
||||
string SessionId { get; }
|
||||
|
||||
string StartExecutorId { get; }
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ internal sealed class LockstepRunEventStream : IRunEventStream
|
||||
this._stepRunner.OutgoingEvents.EventRaised += OnWorkflowEventAsync;
|
||||
|
||||
using Activity? activity = this._stepRunner.TelemetryContext.StartWorkflowRunActivity();
|
||||
activity?.SetTag(Tags.WorkflowId, this._stepRunner.StartExecutorId).SetTag(Tags.RunId, this._stepRunner.RunId);
|
||||
activity?.SetTag(Tags.WorkflowId, this._stepRunner.StartExecutorId).SetTag(Tags.SessionId, this._stepRunner.SessionId);
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@@ -61,7 +61,7 @@ internal sealed class StreamingRunEventStream : IRunEventStream
|
||||
this._stepRunner.OutgoingEvents.EventRaised += OnEventRaisedAsync;
|
||||
|
||||
using Activity? activity = this._stepRunner.TelemetryContext.StartWorkflowRunActivity();
|
||||
activity?.SetTag(Tags.WorkflowId, this._stepRunner.StartExecutorId).SetTag(Tags.RunId, this._stepRunner.RunId);
|
||||
activity?.SetTag(Tags.WorkflowId, this._stepRunner.StartExecutorId).SetTag(Tags.SessionId, this._stepRunner.SessionId);
|
||||
|
||||
try
|
||||
{
|
||||
|
||||
@@ -58,9 +58,9 @@ public abstract record class ExecutorBinding(string Id, Func<string, ValueTask<E
|
||||
return executor;
|
||||
}
|
||||
|
||||
internal async ValueTask<Executor> CreateInstanceAsync(string runId)
|
||||
internal async ValueTask<Executor> CreateInstanceAsync(string sessionId)
|
||||
=> !this.IsPlaceholder
|
||||
? this.CheckId(await this.FactoryAsync(runId).ConfigureAwait(false))
|
||||
? this.CheckId(await this.FactoryAsync(sessionId).ConfigureAwait(false))
|
||||
: throw new InvalidOperationException(
|
||||
$"Cannot create executor with ID '{this.Id}': Binding ({this.GetType().Name}) is a placeholder.");
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ public static class ExecutorBindingExtensions
|
||||
/// <returns>An <see cref="ExecutorBinding"/> instance that resolves to the result of the factory call when messages get sent to it.</returns>
|
||||
public static ExecutorBinding BindExecutor<TExecutor>(this Func<string, string, ValueTask<TExecutor>> factoryAsync)
|
||||
where TExecutor : Executor
|
||||
=> BindExecutor<TExecutor, ExecutorOptions>((config, runId) => factoryAsync(config.Id, runId), id: typeof(TExecutor).Name, options: null);
|
||||
=> BindExecutor<TExecutor, ExecutorOptions>((config, sessionId) => factoryAsync(config.Id, sessionId), id: typeof(TExecutor).Name, options: null);
|
||||
|
||||
/// <summary>
|
||||
/// Configures a factory method for creating an <see cref="Executor"/> of type <typeparamref name="TExecutor"/>, using the
|
||||
@@ -77,7 +77,7 @@ public static class ExecutorBindingExtensions
|
||||
/// <returns>An <see cref="ExecutorBinding"/> instance that resolves to the result of the factory call when messages get sent to it.</returns>
|
||||
public static ExecutorBinding BindExecutor<TExecutor>(this Func<string, string, ValueTask<TExecutor>> factoryAsync, string id)
|
||||
where TExecutor : Executor
|
||||
=> BindExecutor<TExecutor, ExecutorOptions>((_, runId) => factoryAsync(id, runId), id, options: null);
|
||||
=> BindExecutor<TExecutor, ExecutorOptions>((_, sessionId) => factoryAsync(id, sessionId), id, options: null);
|
||||
|
||||
/// <summary>
|
||||
/// Configures a factory method for creating an <see cref="Executor"/> of type <typeparamref name="TExecutor"/>, with
|
||||
|
||||
@@ -15,26 +15,28 @@ namespace Microsoft.Agents.AI.Workflows;
|
||||
/// <param name="Data">The data contained in the request.</param>
|
||||
public record ExternalRequest(RequestPortInfo PortInfo, string RequestId, PortableValue Data)
|
||||
{
|
||||
/// <summary>
|
||||
/// Attempts to retrieve the underlying data as the specified type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to which the data should be cast or converted.</typeparam>
|
||||
/// <returns>The data cast to the specified type, or null if the data cannot be cast to the specified type.</returns>
|
||||
public TValue? DataAs<TValue>() => this.Data.As<TValue>();
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the underlying data is of the specified type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to compare with the underlying data.</typeparam>
|
||||
/// <returns>true if the underlying data is of type TValue; otherwise, false.</returns>
|
||||
public bool DataIs<TValue>() => this.Data.Is<TValue>();
|
||||
public bool IsDataOfType<TValue>() => this.Data.Is<TValue>();
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the underlying data is of the specified type and outputs the value if it is.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to compare with the underlying data.</typeparam>
|
||||
/// <returns>true if the underlying data is of type TValue; otherwise, false.</returns>
|
||||
public bool DataIs<TValue>([NotNullWhen(true)] out TValue? value) => this.Data.Is(out value);
|
||||
public bool TryGetDataAs<TValue>([NotNullWhen(true)] out TValue? value) => this.Data.Is(out value);
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to retrieve the underlying data as the specified type.
|
||||
/// </summary>
|
||||
/// <param name="targetType">The type to which the data should be cast or converted.</param>
|
||||
/// <param name="value">When this method returns <see langword="true"/>, contains the value of type
|
||||
/// <paramref name="targetType"/> if the data is available and compatible.</param>
|
||||
/// <returns>true if the data is present and can be cast to <paramref name="targetType"/>; otherwise, false.</returns>
|
||||
public bool TryGetDataAs(Type targetType, [NotNullWhen(true)] out object? value) => this.Data.IsType(targetType, out value);
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ExternalRequest"/> for the specified input port and data payload.
|
||||
|
||||
@@ -14,19 +14,12 @@ namespace Microsoft.Agents.AI.Workflows;
|
||||
/// <param name="Data">The data contained in the response.</param>
|
||||
public record ExternalResponse(RequestPortInfo PortInfo, string RequestId, PortableValue Data)
|
||||
{
|
||||
/// <summary>
|
||||
/// Attempts to retrieve the underlying data as the specified type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to which the data should be cast or converted.</typeparam>
|
||||
/// <returns>The data cast to the specified type, or null if the data cannot be cast to the specified type.</returns>
|
||||
public TValue? DataAs<TValue>() => this.Data.As<TValue>();
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the underlying data is of the specified type.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to compare with the underlying data.</typeparam>
|
||||
/// <returns>true if the underlying data is of type TValue; otherwise, false.</returns>
|
||||
public bool DataIs<TValue>() => this.Data.Is<TValue>();
|
||||
public bool IsDataOfType<TValue>() => this.Data.Is<TValue>();
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the underlying data can be retrieved as the specified type.
|
||||
@@ -35,14 +28,7 @@ public record ExternalResponse(RequestPortInfo PortInfo, string RequestId, Porta
|
||||
/// <param name="value">When this method returns, contains the value of type <typeparamref name="TValue"/> if the data is
|
||||
/// available and compatible.</param>
|
||||
/// <returns>true if the data is present and can be cast to <typeparamref name="TValue"/>; otherwise, false.</returns>
|
||||
public bool DataIs<TValue>([NotNullWhen(true)] out TValue? value) => this.Data.Is(out value);
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to retrieve the underlying data as the specified type.
|
||||
/// </summary>
|
||||
/// <param name="targetType">The type to which the data should be cast or converted.</param>
|
||||
/// <returns>The data cast to the specified type, or null if the data cannot be cast to the specified type.</returns>
|
||||
public object? DataAs(Type targetType) => this.Data.AsType(targetType);
|
||||
public bool TryGetDataAs<TValue>([NotNullWhen(true)] out TValue? value) => this.Data.Is(out value);
|
||||
|
||||
/// <summary>
|
||||
/// Attempts to retrieve the underlying data as the specified type.
|
||||
@@ -51,5 +37,5 @@ public record ExternalResponse(RequestPortInfo PortInfo, string RequestId, Porta
|
||||
/// <param name="value">When this method returns <see langword="true"/>, contains the value of type
|
||||
/// <paramref name="targetType"/> if the data is available and compatible.</param>
|
||||
/// <returns>true if the data is present and can be cast to <paramref name="targetType"/>; otherwise, false.</returns>
|
||||
public bool DataIs(Type targetType, [NotNullWhen(true)] out object? value) => this.Data.IsType(targetType, out value);
|
||||
public bool TryGetDataAs(Type targetType, [NotNullWhen(true)] out object? value) => this.Data.IsType(targetType, out value);
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ public sealed class GroupChatWorkflowBuilder
|
||||
Dictionary<AIAgent, ExecutorBinding> agentMap = agents.ToDictionary(a => a, a => a.BindAsExecutor(options));
|
||||
|
||||
Func<string, string, ValueTask<Executor>> groupChatHostFactory =
|
||||
(id, runId) => new(new GroupChatHost(id, agents, agentMap, this._managerFactory));
|
||||
(id, sessionId) => new(new GroupChatHost(id, agents, agentMap, this._managerFactory));
|
||||
|
||||
ExecutorBinding host = groupChatHostFactory.BindExecutor(nameof(GroupChatHost));
|
||||
WorkflowBuilder builder = new(host);
|
||||
|
||||
@@ -21,11 +21,11 @@ public interface IWorkflowExecutionEnvironment
|
||||
/// <see cref="Executor"/> will not be invoked until an input message is received.
|
||||
/// </summary>
|
||||
/// <param name="workflow">The workflow to execute. Cannot be null.</param>
|
||||
/// <param name="runId">An optional identifier for the run. If null, a new run identifier will be generated.</param>
|
||||
/// <param name="sessionId">An optional identifier for the session. If null, a new identifier will be generated.</param>
|
||||
/// <param name="cancellationToken">A cancellation token that can be used to cancel the streaming operation.</param>
|
||||
/// <returns>A ValueTask that represents the asynchronous operation. The result contains a StreamingRun object for accessing
|
||||
/// the streamed workflow output.</returns>
|
||||
ValueTask<StreamingRun> OpenStreamAsync(Workflow workflow, string? runId = null, CancellationToken cancellationToken = default);
|
||||
ValueTask<StreamingRun> OpenStreamingAsync(Workflow workflow, string? sessionId = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Initiates an asynchronous streaming execution using the specified input.
|
||||
@@ -36,11 +36,11 @@ public interface IWorkflowExecutionEnvironment
|
||||
/// <typeparam name="TInput">A type of input accepted by the workflow. Must be non-nullable.</typeparam>
|
||||
/// <param name="workflow">The workflow to be executed. Must not be <c>null</c>.</param>
|
||||
/// <param name="input">The input message to be processed as part of the streaming run.</param>
|
||||
/// <param name="runId">An optional unique identifier for the run. If not provided, a new identifier will be generated.</param>
|
||||
/// <param name="sessionId">An optional unique identifier for the session. If not provided, a new identifier will be generated.</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
|
||||
/// <returns>A <see cref="ValueTask{StreamingRun}"/> that represents the asynchronous operation. The result contains a <see
|
||||
/// cref="StreamingRun"/> for managing and interacting with the streaming run.</returns>
|
||||
ValueTask<StreamingRun> StreamAsync<TInput>(Workflow workflow, TInput input, string? runId = null, CancellationToken cancellationToken = default) where TInput : notnull;
|
||||
ValueTask<StreamingRun> RunStreamingAsync<TInput>(Workflow workflow, TInput input, string? sessionId = null, CancellationToken cancellationToken = default) where TInput : notnull;
|
||||
|
||||
/// <summary>
|
||||
/// Resumes an asynchronous streaming execution for the specified input from a checkpoint.
|
||||
@@ -51,7 +51,7 @@ public interface IWorkflowExecutionEnvironment
|
||||
/// <param name="fromCheckpoint">The <see cref="CheckpointInfo"/> corresponding to the checkpoint from which to resume.</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
|
||||
/// <returns>A <see cref="StreamingRun"/> that provides access to the results of the streaming run.</returns>
|
||||
ValueTask<StreamingRun> ResumeStreamAsync(Workflow workflow, CheckpointInfo fromCheckpoint, CancellationToken cancellationToken = default);
|
||||
ValueTask<StreamingRun> ResumeStreamingAsync(Workflow workflow, CheckpointInfo fromCheckpoint, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Initiates a non-streaming execution of the workflow with the specified input.
|
||||
@@ -61,11 +61,11 @@ public interface IWorkflowExecutionEnvironment
|
||||
/// <typeparam name="TInput">The type of input accepted by the workflow. Must be non-nullable.</typeparam>
|
||||
/// <param name="workflow">The workflow to be executed. Must not be <c>null</c>.</param>
|
||||
/// <param name="input">The input message to be processed as part of the run.</param>
|
||||
/// <param name="runId">An optional unique identifier for the run. If not provided, a new identifier will be generated.</param>
|
||||
/// <param name="sessionId">An optional unique identifier for the session. If not provided, a new identifier will be generated.</param>
|
||||
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
|
||||
/// <returns>A <see cref="ValueTask{Run}"/> that represents the asynchronous operation. The result contains a <see
|
||||
/// cref="Run"/> for managing and interacting with the streaming run.</returns>
|
||||
ValueTask<Run> RunAsync<TInput>(Workflow workflow, TInput input, string? runId = null, CancellationToken cancellationToken = default) where TInput : notnull;
|
||||
ValueTask<Run> RunAsync<TInput>(Workflow workflow, TInput input, string? sessionId = null, CancellationToken cancellationToken = default) where TInput : notnull;
|
||||
|
||||
/// <summary>
|
||||
/// Resumes a non-streaming execution of the workflow from a checkpoint.
|
||||
|
||||
@@ -44,38 +44,38 @@ public sealed class InProcessExecutionEnvironment : IWorkflowExecutionEnvironmen
|
||||
/// <inheritdoc/>
|
||||
public bool IsCheckpointingEnabled => this.CheckpointManager != null;
|
||||
|
||||
internal ValueTask<AsyncRunHandle> BeginRunAsync(Workflow workflow, string? runId, IEnumerable<Type> knownValidInputTypes, CancellationToken cancellationToken)
|
||||
internal ValueTask<AsyncRunHandle> BeginRunAsync(Workflow workflow, string? sessionId, IEnumerable<Type> knownValidInputTypes, CancellationToken cancellationToken)
|
||||
{
|
||||
InProcessRunner runner = InProcessRunner.CreateTopLevelRunner(workflow, this.CheckpointManager, runId, this.EnableConcurrentRuns, knownValidInputTypes);
|
||||
InProcessRunner runner = InProcessRunner.CreateTopLevelRunner(workflow, this.CheckpointManager, sessionId, this.EnableConcurrentRuns, knownValidInputTypes);
|
||||
return runner.BeginStreamAsync(this.ExecutionMode, cancellationToken);
|
||||
}
|
||||
|
||||
internal ValueTask<AsyncRunHandle> ResumeRunAsync(Workflow workflow, CheckpointInfo fromCheckpoint, IEnumerable<Type> knownValidInputTypes, CancellationToken cancellationToken)
|
||||
{
|
||||
InProcessRunner runner = InProcessRunner.CreateTopLevelRunner(workflow, this.CheckpointManager, fromCheckpoint.RunId, this.EnableConcurrentRuns, knownValidInputTypes);
|
||||
InProcessRunner runner = InProcessRunner.CreateTopLevelRunner(workflow, this.CheckpointManager, fromCheckpoint.SessionId, this.EnableConcurrentRuns, knownValidInputTypes);
|
||||
return runner.ResumeStreamAsync(this.ExecutionMode, fromCheckpoint, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async ValueTask<StreamingRun> OpenStreamAsync(
|
||||
public async ValueTask<StreamingRun> OpenStreamingAsync(
|
||||
Workflow workflow,
|
||||
string? runId = null,
|
||||
string? sessionId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
AsyncRunHandle runHandle = await this.BeginRunAsync(workflow, runId, [], cancellationToken)
|
||||
AsyncRunHandle runHandle = await this.BeginRunAsync(workflow, sessionId, [], cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return new(runHandle);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async ValueTask<StreamingRun> StreamAsync<TInput>(
|
||||
public async ValueTask<StreamingRun> RunStreamingAsync<TInput>(
|
||||
Workflow workflow,
|
||||
TInput input,
|
||||
string? runId = null,
|
||||
string? sessionId = null,
|
||||
CancellationToken cancellationToken = default) where TInput : notnull
|
||||
{
|
||||
AsyncRunHandle runHandle = await this.BeginRunAsync(workflow, runId, [], cancellationToken)
|
||||
AsyncRunHandle runHandle = await this.BeginRunAsync(workflow, sessionId, [], cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return await runHandle.EnqueueAndStreamAsync(input, cancellationToken).ConfigureAwait(false);
|
||||
@@ -91,7 +91,7 @@ public sealed class InProcessExecutionEnvironment : IWorkflowExecutionEnvironmen
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async ValueTask<StreamingRun> ResumeStreamAsync(
|
||||
public async ValueTask<StreamingRun> ResumeStreamingAsync(
|
||||
Workflow workflow,
|
||||
CheckpointInfo fromCheckpoint,
|
||||
CancellationToken cancellationToken = default)
|
||||
@@ -106,11 +106,11 @@ public sealed class InProcessExecutionEnvironment : IWorkflowExecutionEnvironmen
|
||||
|
||||
private async ValueTask<AsyncRunHandle> BeginRunHandlingChatProtocolAsync<TInput>(Workflow workflow,
|
||||
TInput input,
|
||||
string? runId = null,
|
||||
string? sessionId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ProtocolDescriptor descriptor = await workflow.DescribeProtocolAsync(cancellationToken).ConfigureAwait(false);
|
||||
AsyncRunHandle runHandle = await this.BeginRunAsync(workflow, runId, descriptor.Accepts, cancellationToken)
|
||||
AsyncRunHandle runHandle = await this.BeginRunAsync(workflow, sessionId, descriptor.Accepts, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
await runHandle.EnqueueMessageAsync(input, cancellationToken).ConfigureAwait(false);
|
||||
@@ -127,13 +127,13 @@ public sealed class InProcessExecutionEnvironment : IWorkflowExecutionEnvironmen
|
||||
public async ValueTask<Run> RunAsync<TInput>(
|
||||
Workflow workflow,
|
||||
TInput input,
|
||||
string? runId = null,
|
||||
string? sessionId = null,
|
||||
CancellationToken cancellationToken = default) where TInput : notnull
|
||||
{
|
||||
AsyncRunHandle runHandle = await this.BeginRunHandlingChatProtocolAsync(
|
||||
workflow,
|
||||
input,
|
||||
runId,
|
||||
sessionId,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -22,27 +22,27 @@ namespace Microsoft.Agents.AI.Workflows.InProc;
|
||||
/// scenarios where workflow execution does not require executor distribution. </para></remarks>
|
||||
internal sealed class InProcessRunner : ISuperStepRunner, ICheckpointingHandle
|
||||
{
|
||||
public static InProcessRunner CreateTopLevelRunner(Workflow workflow, ICheckpointManager? checkpointManager, string? runId = null, bool enableConcurrentRuns = false, IEnumerable<Type>? knownValidInputTypes = null)
|
||||
public static InProcessRunner CreateTopLevelRunner(Workflow workflow, ICheckpointManager? checkpointManager, string? sessionId = null, bool enableConcurrentRuns = false, IEnumerable<Type>? knownValidInputTypes = null)
|
||||
{
|
||||
return new InProcessRunner(workflow,
|
||||
checkpointManager,
|
||||
runId,
|
||||
sessionId,
|
||||
enableConcurrentRuns: enableConcurrentRuns,
|
||||
knownValidInputTypes: knownValidInputTypes);
|
||||
}
|
||||
|
||||
public static InProcessRunner CreateSubworkflowRunner(Workflow workflow, ICheckpointManager? checkpointManager, string? runId = null, object? existingOwnerSignoff = null, bool enableConcurrentRuns = false, IEnumerable<Type>? knownValidInputTypes = null)
|
||||
public static InProcessRunner CreateSubworkflowRunner(Workflow workflow, ICheckpointManager? checkpointManager, string? sessionId = null, object? existingOwnerSignoff = null, bool enableConcurrentRuns = false, IEnumerable<Type>? knownValidInputTypes = null)
|
||||
{
|
||||
return new InProcessRunner(workflow,
|
||||
checkpointManager,
|
||||
runId,
|
||||
sessionId,
|
||||
existingOwnerSignoff: existingOwnerSignoff,
|
||||
enableConcurrentRuns: enableConcurrentRuns,
|
||||
knownValidInputTypes: knownValidInputTypes,
|
||||
subworkflow: true);
|
||||
}
|
||||
|
||||
private InProcessRunner(Workflow workflow, ICheckpointManager? checkpointManager, string? runId = null, object? existingOwnerSignoff = null, bool subworkflow = false, bool enableConcurrentRuns = false, IEnumerable<Type>? knownValidInputTypes = null)
|
||||
private InProcessRunner(Workflow workflow, ICheckpointManager? checkpointManager, string? sessionId = null, object? existingOwnerSignoff = null, bool subworkflow = false, bool enableConcurrentRuns = false, IEnumerable<Type>? knownValidInputTypes = null)
|
||||
{
|
||||
if (enableConcurrentRuns && !workflow.AllowConcurrent)
|
||||
{
|
||||
@@ -50,11 +50,11 @@ internal sealed class InProcessRunner : ISuperStepRunner, ICheckpointingHandle
|
||||
$"not supporting concurrent: {string.Join(", ", workflow.NonConcurrentExecutorIds)}");
|
||||
}
|
||||
|
||||
this.RunId = runId ?? Guid.NewGuid().ToString("N");
|
||||
this.SessionId = sessionId ?? Guid.NewGuid().ToString("N");
|
||||
this.StartExecutorId = workflow.StartExecutorId;
|
||||
|
||||
this.Workflow = Throw.IfNull(workflow);
|
||||
this.RunContext = new InProcessRunnerContext(workflow, this.RunId, checkpointingEnabled: checkpointManager != null, this.OutgoingEvents, this.StepTracer, existingOwnerSignoff, subworkflow, enableConcurrentRuns);
|
||||
this.RunContext = new InProcessRunnerContext(workflow, this.SessionId, checkpointingEnabled: checkpointManager != null, this.OutgoingEvents, this.StepTracer, existingOwnerSignoff, subworkflow, enableConcurrentRuns);
|
||||
this.CheckpointManager = checkpointManager;
|
||||
|
||||
this._knownValidInputTypes = knownValidInputTypes != null
|
||||
@@ -65,8 +65,8 @@ internal sealed class InProcessRunner : ISuperStepRunner, ICheckpointingHandle
|
||||
this.EdgeMap = new EdgeMap(this.RunContext, this.Workflow.Edges, this.Workflow.Ports.Values, this.Workflow.StartExecutorId, this.StepTracer);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ISuperStepRunner.RunId"/>
|
||||
public string RunId { get; }
|
||||
/// <inheritdoc cref="ISuperStepRunner.SessionId"/>
|
||||
public string SessionId { get; }
|
||||
|
||||
/// <inheritdoc cref="ISuperStepRunner.StartExecutorId"/>
|
||||
public string StartExecutorId { get; }
|
||||
@@ -303,7 +303,7 @@ internal sealed class InProcessRunner : ISuperStepRunner, ICheckpointingHandle
|
||||
Dictionary<ScopeKey, PortableValue> stateData = await this.RunContext.StateManager.ExportStateAsync().ConfigureAwait(false);
|
||||
|
||||
Checkpoint checkpoint = new(this.StepTracer.StepNumber, this._workflowInfoCache, runnerData, stateData, edgeData, this._lastCheckpointInfo);
|
||||
this._lastCheckpointInfo = await this.CheckpointManager.CommitCheckpointAsync(this.RunId, checkpoint).ConfigureAwait(false);
|
||||
this._lastCheckpointInfo = await this.CheckpointManager.CommitCheckpointAsync(this.SessionId, checkpoint).ConfigureAwait(false);
|
||||
this.StepTracer.TraceCheckpointCreated(this._lastCheckpointInfo);
|
||||
this._checkpoints.Add(this._lastCheckpointInfo);
|
||||
}
|
||||
@@ -317,7 +317,7 @@ internal sealed class InProcessRunner : ISuperStepRunner, ICheckpointingHandle
|
||||
throw new InvalidOperationException("This run was not configured with a CheckpointManager, so it cannot restore checkpoints.");
|
||||
}
|
||||
|
||||
Checkpoint checkpoint = await this.CheckpointManager.LookupCheckpointAsync(this.RunId, checkpointInfo)
|
||||
Checkpoint checkpoint = await this.CheckpointManager.LookupCheckpointAsync(this.SessionId, checkpointInfo)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
// Validate the checkpoint is compatible with this workflow
|
||||
@@ -346,7 +346,7 @@ internal sealed class InProcessRunner : ISuperStepRunner, ICheckpointingHandle
|
||||
async ValueTask UpdateCheckpointIndexAsync()
|
||||
{
|
||||
this._checkpoints.Clear();
|
||||
this._checkpoints.AddRange(await this.CheckpointManager!.RetrieveIndexAsync(this.RunId).ConfigureAwait(false));
|
||||
this._checkpoints.AddRange(await this.CheckpointManager!.RetrieveIndexAsync(this.SessionId).ConfigureAwait(false));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace Microsoft.Agents.AI.Workflows.InProc;
|
||||
internal sealed class InProcessRunnerContext : IRunnerContext
|
||||
{
|
||||
private int _runEnded;
|
||||
private readonly string _runId;
|
||||
private readonly string _sessionId;
|
||||
private readonly Workflow _workflow;
|
||||
private readonly object? _previousOwnership;
|
||||
private bool _ownsWorkflow;
|
||||
@@ -40,7 +40,7 @@ internal sealed class InProcessRunnerContext : IRunnerContext
|
||||
|
||||
public InProcessRunnerContext(
|
||||
Workflow workflow,
|
||||
string runId,
|
||||
string sessionId,
|
||||
bool checkpointingEnabled,
|
||||
IEventSink outgoingEvents,
|
||||
IStepTracer? stepTracer,
|
||||
@@ -61,7 +61,7 @@ internal sealed class InProcessRunnerContext : IRunnerContext
|
||||
}
|
||||
|
||||
this._workflow = workflow;
|
||||
this._runId = runId;
|
||||
this._sessionId = sessionId;
|
||||
|
||||
this._edgeMap = new(this, this._workflow, stepTracer);
|
||||
this._outputFilter = new(workflow);
|
||||
@@ -94,7 +94,7 @@ internal sealed class InProcessRunnerContext : IRunnerContext
|
||||
throw new InvalidOperationException($"Executor with ID '{executorId}' is not registered.");
|
||||
}
|
||||
|
||||
Executor executor = await registration.CreateInstanceAsync(this._runId).ConfigureAwait(false);
|
||||
Executor executor = await registration.CreateInstanceAsync(this._sessionId).ConfigureAwait(false);
|
||||
executor.AttachRequestContext(this.BindExternalRequestContext(executorId));
|
||||
|
||||
await executor.InitializeAsync(this.BindWorkflowContext(executorId), cancellationToken: cancellationToken)
|
||||
@@ -438,7 +438,7 @@ internal sealed class InProcessRunnerContext : IRunnerContext
|
||||
{
|
||||
if (Volatile.Read(ref this._runEnded) == 1)
|
||||
{
|
||||
throw new InvalidOperationException($"Workflow run '{this._runId}' has been ended. Please start a new Run or StreamingRun.");
|
||||
throw new InvalidOperationException($"Workflow run for session '{this._sessionId}' has been ended. Please start a new Run or StreamingRun.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,33 +41,33 @@ public static class InProcessExecution
|
||||
/// </summary>
|
||||
internal static InProcessExecutionEnvironment Subworkflow { get; } = new(ExecutionMode.Subworkflow);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.OpenStreamAsync(Workflow, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> OpenStreamAsync(Workflow workflow, string? runId = null, CancellationToken cancellationToken = default)
|
||||
=> Default.OpenStreamAsync(workflow, runId, cancellationToken);
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.OpenStreamingAsync(Workflow, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> OpenStreamingAsync(Workflow workflow, string? sessionId = null, CancellationToken cancellationToken = default)
|
||||
=> Default.OpenStreamingAsync(workflow, sessionId, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.StreamAsync{TInput}(Workflow, TInput, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> StreamAsync<TInput>(Workflow workflow, TInput input, string? runId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.StreamAsync(workflow, input, runId, cancellationToken);
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.RunStreamingAsync{TInput}(Workflow, TInput, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> RunStreamingAsync<TInput>(Workflow workflow, TInput input, string? sessionId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.RunStreamingAsync(workflow, input, sessionId, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.OpenStreamAsync(Workflow, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> OpenStreamAsync(Workflow workflow, CheckpointManager checkpointManager, string? runId = null, CancellationToken cancellationToken = default)
|
||||
=> Default.WithCheckpointing(checkpointManager).OpenStreamAsync(workflow, runId, cancellationToken);
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.OpenStreamingAsync(Workflow, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> OpenStreamingAsync(Workflow workflow, CheckpointManager checkpointManager, string? sessionId = null, CancellationToken cancellationToken = default)
|
||||
=> Default.WithCheckpointing(checkpointManager).OpenStreamingAsync(workflow, sessionId, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.StreamAsync{TInput}(Workflow, TInput, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> StreamAsync<TInput>(Workflow workflow, TInput input, CheckpointManager checkpointManager, string? runId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.WithCheckpointing(checkpointManager).StreamAsync(workflow, input, runId, cancellationToken);
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.RunStreamingAsync{TInput}(Workflow, TInput, string?, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> RunStreamingAsync<TInput>(Workflow workflow, TInput input, CheckpointManager checkpointManager, string? sessionId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.WithCheckpointing(checkpointManager).RunStreamingAsync(workflow, input, sessionId, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.ResumeStreamAsync(Workflow, CheckpointInfo, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> ResumeStreamAsync(Workflow workflow, CheckpointInfo fromCheckpoint, CheckpointManager checkpointManager, CancellationToken cancellationToken = default)
|
||||
=> Default.WithCheckpointing(checkpointManager).ResumeStreamAsync(workflow, fromCheckpoint, cancellationToken);
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.ResumeStreamingAsync(Workflow, CheckpointInfo, CancellationToken)"/>
|
||||
public static ValueTask<StreamingRun> ResumeStreamingAsync(Workflow workflow, CheckpointInfo fromCheckpoint, CheckpointManager checkpointManager, CancellationToken cancellationToken = default)
|
||||
=> Default.WithCheckpointing(checkpointManager).ResumeStreamingAsync(workflow, fromCheckpoint, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.RunAsync{TInput}(Workflow, TInput, string?, CancellationToken)"/>
|
||||
public static ValueTask<Run> RunAsync<TInput>(Workflow workflow, TInput input, string? runId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.RunAsync(workflow, input, runId, cancellationToken);
|
||||
public static ValueTask<Run> RunAsync<TInput>(Workflow workflow, TInput input, string? sessionId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.RunAsync(workflow, input, sessionId, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.RunAsync{TInput}(Workflow, TInput, string?, CancellationToken)"/>
|
||||
public static ValueTask<Run> RunAsync<TInput>(Workflow workflow, TInput input, CheckpointManager checkpointManager, string? runId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.WithCheckpointing(checkpointManager).RunAsync(workflow, input, runId, cancellationToken);
|
||||
public static ValueTask<Run> RunAsync<TInput>(Workflow workflow, TInput input, CheckpointManager checkpointManager, string? sessionId = null, CancellationToken cancellationToken = default) where TInput : notnull
|
||||
=> Default.WithCheckpointing(checkpointManager).RunAsync(workflow, input, sessionId, cancellationToken);
|
||||
|
||||
/// <inheritdoc cref="IWorkflowExecutionEnvironment.ResumeAsync(Workflow, CheckpointInfo, CancellationToken)"/>
|
||||
public static ValueTask<Run> ResumeAsync(Workflow workflow, CheckpointInfo fromCheckpoint, CheckpointManager checkpointManager, CancellationToken cancellationToken = default)
|
||||
|
||||
@@ -11,7 +11,7 @@ internal static class Tags
|
||||
public const string BuildErrorMessage = "build.error.message";
|
||||
public const string BuildErrorType = "build.error.type";
|
||||
public const string ErrorType = "error.type";
|
||||
public const string RunId = "run.id";
|
||||
public const string SessionId = "session.id";
|
||||
public const string ExecutorId = "executor.id";
|
||||
public const string ExecutorType = "executor.type";
|
||||
public const string ExecutorInput = "executor.input";
|
||||
|
||||
@@ -96,7 +96,8 @@ public sealed class PortableValue
|
||||
/// </summary>
|
||||
/// <remarks>If the underlying value implements delayed deserialization, this method will attempt to
|
||||
/// deserialize it to the specified type. If the value is already of the requested type, it is returned directly.
|
||||
/// Otherwise, the default value for TValue is returned.
|
||||
/// Otherwise, the default value for TValue is returned. For value types, the default is not <see langword="null"/>,
|
||||
/// UNLESS <typeparamref name="TValue"/> is nullable, e.g. <c>int?</c>.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TValue">The type to which the value should be cast or deserialized.</typeparam>
|
||||
/// <returns>The value cast or deserialized to type TValue if possible; otherwise, the default value for type TValue.</returns>
|
||||
|
||||
@@ -158,7 +158,7 @@ public class RouteBuilder
|
||||
|
||||
async ValueTask<ExternalResponse?> InvokeHandlerAsync(ExternalResponse response, IWorkflowContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!response.DataIs(out TResponse? typedResponse))
|
||||
if (!response.TryGetDataAs(out TResponse? typedResponse))
|
||||
{
|
||||
throw new InvalidOperationException($"Received response data is not of expected type {typeof(TResponse).FullName} for port {port.Id}.");
|
||||
}
|
||||
|
||||
@@ -36,9 +36,9 @@ public sealed class Run : CheckpointableRunBase, IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A unique identifier for the run. Can be provided at the start of the run, or auto-generated.
|
||||
/// A unique identifier for the session. Can be provided at the start of the session, or auto-generated.
|
||||
/// </summary>
|
||||
public string RunId => this._runHandle.RunId;
|
||||
public string SessionId => this._runHandle.SessionId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current execution status of the workflow run.
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace Microsoft.Agents.AI.Workflows.Specialized;
|
||||
|
||||
internal class WorkflowHostExecutor : Executor, IAsyncDisposable
|
||||
{
|
||||
private readonly string _runId;
|
||||
private readonly string _sessionId;
|
||||
private readonly Workflow _workflow;
|
||||
private readonly ProtocolDescriptor _workflowProtocol;
|
||||
private readonly object _ownershipToken;
|
||||
@@ -31,12 +31,11 @@ internal class WorkflowHostExecutor : Executor, IAsyncDisposable
|
||||
[MemberNotNullWhen(true, nameof(_checkpointManager))]
|
||||
private bool WithCheckpointing => this._checkpointManager != null;
|
||||
|
||||
public WorkflowHostExecutor(string id, Workflow workflow, ProtocolDescriptor workflowProtocol, string runId, object ownershipToken, ExecutorOptions? options = null) : base(id, options)
|
||||
public WorkflowHostExecutor(string id, Workflow workflow, ProtocolDescriptor workflowProtocol, string sessionId, object ownershipToken, ExecutorOptions? options = null) : base(id, options)
|
||||
{
|
||||
this._options = options ?? new();
|
||||
|
||||
//Throw.IfNull(workflow);
|
||||
this._runId = Throw.IfNull(runId);
|
||||
this._sessionId = Throw.IfNull(sessionId);
|
||||
this._ownershipToken = Throw.IfNull(ownershipToken);
|
||||
this._workflow = Throw.IfNull(workflow);
|
||||
this._workflowProtocol = Throw.IfNull(workflowProtocol);
|
||||
@@ -92,7 +91,7 @@ internal class WorkflowHostExecutor : Executor, IAsyncDisposable
|
||||
|
||||
this._activeRunner = InProcessRunner.CreateSubworkflowRunner(this._workflow,
|
||||
this._checkpointManager,
|
||||
this._runId,
|
||||
this._sessionId,
|
||||
this._ownershipToken,
|
||||
this.JoinContext.ConcurrentRunsEnabled);
|
||||
}
|
||||
@@ -122,7 +121,7 @@ internal class WorkflowHostExecutor : Executor, IAsyncDisposable
|
||||
if (resume)
|
||||
{
|
||||
// Attempting to resume from checkpoint
|
||||
if (!this._checkpointManager.TryGetLastCheckpoint(this._runId, out CheckpointInfo? lastCheckpoint))
|
||||
if (!this._checkpointManager.TryGetLastCheckpoint(this._sessionId, out CheckpointInfo? lastCheckpoint))
|
||||
{
|
||||
throw new InvalidOperationException("No checkpoints available to resume from.");
|
||||
}
|
||||
|
||||
@@ -24,9 +24,9 @@ public sealed class StreamingRun : CheckpointableRunBase, IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A unique identifier for the run. Can be provided at the start of the run, or auto-generated.
|
||||
/// A unique identifier for the session. Can be provided at the start of the session, or auto-generated.
|
||||
/// </summary>
|
||||
public string RunId => this._runHandle.RunId;
|
||||
public string SessionId => this._runHandle.SessionId;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current execution status of the workflow run.
|
||||
|
||||
@@ -27,11 +27,11 @@ public record SubworkflowBinding(Workflow WorkflowInstance, string Id, ExecutorO
|
||||
|
||||
return InitHostExecutorAsync;
|
||||
|
||||
async ValueTask<Executor> InitHostExecutorAsync(string runId)
|
||||
async ValueTask<Executor> InitHostExecutorAsync(string sessionId)
|
||||
{
|
||||
ProtocolDescriptor workflowProtocol = await workflow.DescribeProtocolAsync().ConfigureAwait(false);
|
||||
|
||||
return new WorkflowHostExecutor(id, workflow, workflowProtocol, runId, ownershipToken, options);
|
||||
return new WorkflowHostExecutor(id, workflow, workflowProtocol, sessionId, ownershipToken, options);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -84,9 +84,9 @@ public sealed class SwitchBuilder
|
||||
List<(Func<object?, bool> Predicate, HashSet<int> OutgoingIndicies)> caseMap = this._caseMap;
|
||||
HashSet<int> defaultIndicies = this._defaultIndicies;
|
||||
|
||||
return builder.AddFanOutEdge<object>(source, this._executors, CasePartitioner);
|
||||
return builder.AddFanOutEdge<object>(source, this._executors, EdgeSelector);
|
||||
|
||||
IEnumerable<int> CasePartitioner(object? input, int targetCount)
|
||||
IEnumerable<int> EdgeSelector(object? input, int targetCount)
|
||||
{
|
||||
Debug.Assert(targetCount == this._executors.Count);
|
||||
|
||||
|
||||
@@ -422,30 +422,26 @@ public class WorkflowBuilder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a fan-in edge to the workflow, connecting multiple source executors to a single target executor with an
|
||||
/// optional trigger condition.
|
||||
/// Adds a fan-in "barrier" edge to the workflow, connecting multiple source executors to a single target executor. Messages
|
||||
/// will be held until every source executor has generated at least one message, then they will be streamed to the target
|
||||
/// executor in the following step.
|
||||
/// </summary>
|
||||
/// <remarks>This method establishes a fan-in relationship, allowing the target executor to be activated
|
||||
/// based on the completion or state of multiple sources. The trigger parameter can be used to customize activation
|
||||
/// behavior.</remarks>
|
||||
/// <param name="sources">One or more source executors that provide input to the target. Cannot be null or empty.</param>
|
||||
/// <param name="target">The target executor that receives input from the specified source executors. Cannot be null.</param>
|
||||
/// <returns>The current instance of <see cref="WorkflowBuilder"/>.</returns>
|
||||
public WorkflowBuilder AddFanInEdge(IEnumerable<ExecutorBinding> sources, ExecutorBinding target)
|
||||
=> this.AddFanInEdge(sources, target, label: null);
|
||||
public WorkflowBuilder AddFanInBarrierEdge(IEnumerable<ExecutorBinding> sources, ExecutorBinding target)
|
||||
=> this.AddFanInBarrierEdge(sources, target, label: null);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a fan-in edge to the workflow, connecting multiple source executors to a single target executor with an
|
||||
/// optional trigger condition.
|
||||
/// Adds a fan-in "barrier" edge to the workflow, connecting multiple source executors to a single target executor. Messages
|
||||
/// will be held until every source executor has generated at least one message, then they will be streamed to the target
|
||||
/// executor in the following step.
|
||||
/// </summary>
|
||||
/// <remarks>This method establishes a fan-in relationship, allowing the target executor to be activated
|
||||
/// based on the completion or state of multiple sources. The trigger parameter can be used to customize activation
|
||||
/// behavior.</remarks>
|
||||
/// <param name="sources">One or more source executors that provide input to the target. Cannot be null or empty.</param>
|
||||
/// <param name="target">The target executor that receives input from the specified source executors. Cannot be null.</param>
|
||||
/// <param name="label">An optional label for the edge. Will be used in visualizations.</param>
|
||||
/// <returns>The current instance of <see cref="WorkflowBuilder"/>.</returns>
|
||||
public WorkflowBuilder AddFanInEdge(IEnumerable<ExecutorBinding> sources, ExecutorBinding target, string? label = null)
|
||||
public WorkflowBuilder AddFanInBarrierEdge(IEnumerable<ExecutorBinding> sources, ExecutorBinding target, string? label = null)
|
||||
{
|
||||
Throw.IfNull(target);
|
||||
Throw.IfNull(sources);
|
||||
@@ -472,10 +468,10 @@ public class WorkflowBuilder
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="AddFanInEdge(IEnumerable{ExecutorBinding}, ExecutorBinding)"/>
|
||||
[Obsolete("Use AddFanInEdge(IEnumerable<ExecutorBinding>, ExecutorBinding) instead.")]
|
||||
public WorkflowBuilder AddFanInEdge(ExecutorBinding target, params IEnumerable<ExecutorBinding> sources)
|
||||
=> this.AddFanInEdge(sources, target);
|
||||
/// <inheritdoc cref="AddFanInBarrierEdge(IEnumerable{ExecutorBinding}, ExecutorBinding)"/>
|
||||
[Obsolete("Use AddFanInBarrierEdge(IEnumerable<ExecutorBinding>, ExecutorBinding) instead.")]
|
||||
public WorkflowBuilder AddFanInBarrierEdge(ExecutorBinding target, params IEnumerable<ExecutorBinding> sources)
|
||||
=> this.AddFanInBarrierEdge(sources, target);
|
||||
|
||||
private void Validate(bool validateOrphans)
|
||||
{
|
||||
|
||||
@@ -22,7 +22,7 @@ internal sealed class WorkflowHostAgent : AIAgent
|
||||
private readonly bool _includeWorkflowOutputsInResponse;
|
||||
private readonly Task<ProtocolDescriptor> _describeTask;
|
||||
|
||||
private readonly ConcurrentDictionary<string, string> _assignedRunIds = [];
|
||||
private readonly ConcurrentDictionary<string, string> _assignedSessionIds = [];
|
||||
|
||||
public WorkflowHostAgent(Workflow workflow, string? id = null, string? name = null, string? description = null, IWorkflowExecutionEnvironment? executionEnvironment = null, bool includeExceptionDetails = false, bool includeWorkflowOutputsInResponse = false)
|
||||
{
|
||||
@@ -62,7 +62,7 @@ internal sealed class WorkflowHostAgent : AIAgent
|
||||
do
|
||||
{
|
||||
result = Guid.NewGuid().ToString("N");
|
||||
} while (!this._assignedRunIds.TryAdd(result, result));
|
||||
} while (!this._assignedSessionIds.TryAdd(result, result));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ public static class WorkflowHostingExtensions
|
||||
/// <param name="includeWorkflowOutputsInResponse">If <see langword="true"/>, will transform outgoing workflow outputs
|
||||
/// into into content in <see cref="AgentResponseUpdate"/>s or the <see cref="AgentResponse"/> as appropriate.</param>
|
||||
/// <returns></returns>
|
||||
public static AIAgent AsAgent(
|
||||
public static AIAgent AsAIAgent(
|
||||
this Workflow workflow,
|
||||
string? id = null,
|
||||
string? name = null,
|
||||
|
||||
@@ -41,7 +41,7 @@ internal sealed class WorkflowSession : AgentSession
|
||||
return true;
|
||||
}
|
||||
|
||||
public WorkflowSession(Workflow workflow, string runId, IWorkflowExecutionEnvironment executionEnvironment, bool includeExceptionDetails = false, bool includeWorkflowOutputsInResponse = false)
|
||||
public WorkflowSession(Workflow workflow, string sessionId, IWorkflowExecutionEnvironment executionEnvironment, bool includeExceptionDetails = false, bool includeWorkflowOutputsInResponse = false)
|
||||
{
|
||||
this._workflow = Throw.IfNull(workflow);
|
||||
this._executionEnvironment = Throw.IfNull(executionEnvironment);
|
||||
@@ -55,7 +55,7 @@ internal sealed class WorkflowSession : AgentSession
|
||||
this._executionEnvironment = inProcEnv.WithCheckpointing(this.EnsureExternalizedInMemoryCheckpointing());
|
||||
}
|
||||
|
||||
this.RunId = Throw.IfNullOrEmpty(runId);
|
||||
this.SessionId = Throw.IfNullOrEmpty(sessionId);
|
||||
this.ChatHistoryProvider = new WorkflowChatHistoryProvider();
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ internal sealed class WorkflowSession : AgentSession
|
||||
throw new ArgumentException("The session was saved with an externalized checkpoint manager, but the incoming execution environment does not support it.", nameof(executionEnvironment));
|
||||
}
|
||||
|
||||
this.RunId = sessionState.RunId;
|
||||
this.SessionId = sessionState.SessionId;
|
||||
this.ChatHistoryProvider = new WorkflowChatHistoryProvider();
|
||||
|
||||
this.LastCheckpoint = sessionState.LastCheckpoint;
|
||||
@@ -98,7 +98,7 @@ internal sealed class WorkflowSession : AgentSession
|
||||
{
|
||||
JsonMarshaller marshaller = new(jsonSerializerOptions);
|
||||
SessionState info = new(
|
||||
this.RunId,
|
||||
this.SessionId,
|
||||
this.LastCheckpoint,
|
||||
this._inMemoryCheckpointManager,
|
||||
this.StateBag);
|
||||
@@ -149,7 +149,7 @@ internal sealed class WorkflowSession : AgentSession
|
||||
{
|
||||
StreamingRun run =
|
||||
await this._executionEnvironment
|
||||
.ResumeStreamAsync(this._workflow,
|
||||
.ResumeStreamingAsync(this._workflow,
|
||||
this.LastCheckpoint,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
@@ -159,9 +159,9 @@ internal sealed class WorkflowSession : AgentSession
|
||||
}
|
||||
|
||||
return await this._executionEnvironment
|
||||
.StreamAsync(this._workflow,
|
||||
.RunStreamingAsync(this._workflow,
|
||||
messages,
|
||||
this.RunId,
|
||||
this.SessionId,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
@@ -262,18 +262,18 @@ internal sealed class WorkflowSession : AgentSession
|
||||
|
||||
public string? LastResponseId { get; set; }
|
||||
|
||||
public string RunId { get; }
|
||||
public string SessionId { get; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public WorkflowChatHistoryProvider ChatHistoryProvider { get; }
|
||||
|
||||
internal sealed class SessionState(
|
||||
string runId,
|
||||
string sessionId,
|
||||
CheckpointInfo? lastCheckpoint,
|
||||
InMemoryCheckpointManager? checkpointManager = null,
|
||||
AgentSessionStateBag? stateBag = null)
|
||||
{
|
||||
public string RunId { get; } = runId;
|
||||
public string SessionId { get; } = sessionId;
|
||||
public CheckpointInfo? LastCheckpoint { get; } = lastCheckpoint;
|
||||
public InMemoryCheckpointManager? CheckpointManager { get; } = checkpointManager;
|
||||
public AgentSessionStateBag StateBag { get; } = stateBag ?? new();
|
||||
|
||||
@@ -68,7 +68,7 @@ internal sealed class WorkflowRunner
|
||||
checkpointManager = CheckpointManager.CreateInMemory();
|
||||
}
|
||||
|
||||
StreamingRun run = await InProcessExecution.StreamAsync(workflow, input, checkpointManager).ConfigureAwait(false);
|
||||
StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, input, checkpointManager).ConfigureAwait(false);
|
||||
|
||||
bool isComplete = false;
|
||||
ExternalResponse? requestResponse = null;
|
||||
@@ -95,7 +95,7 @@ internal sealed class WorkflowRunner
|
||||
Debug.WriteLine($"RESTORE #{this.LastCheckpoint.CheckpointId}");
|
||||
Notify("WORKFLOW: Restore", ConsoleColor.DarkYellow);
|
||||
|
||||
run = await InProcessExecution.ResumeStreamAsync(workflow, this.LastCheckpoint, checkpointManager).ConfigureAwait(false);
|
||||
run = await InProcessExecution.ResumeStreamingAsync(workflow, this.LastCheckpoint, checkpointManager).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -272,9 +272,10 @@ internal sealed class WorkflowRunner
|
||||
/// </summary>
|
||||
private async ValueTask<ExternalInputResponse> HandleExternalRequestAsync(ExternalRequest request)
|
||||
{
|
||||
ExternalInputRequest inputRequest =
|
||||
request.DataAs<ExternalInputRequest>() ??
|
||||
throw new InvalidOperationException($"Expected external request type: {request.GetType().Name}.");
|
||||
if (!request.TryGetDataAs<ExternalInputRequest>(out var inputRequest))
|
||||
{
|
||||
throw new InvalidOperationException($"Expected external request type: {request.PortInfo.RequestType}.");
|
||||
}
|
||||
|
||||
List<ChatMessage> responseMessages = [];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user