// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Agents.AI.Workflows.Execution;
using Microsoft.Shared.Diagnostics;
namespace Microsoft.Agents.AI.Workflows;
///
/// A run instance supporting a streaming form of receiving workflow events, and providing
/// a mechanism to send responses back to the workflow.
///
public sealed class StreamingRun : CheckpointableRunBase, IAsyncDisposable
{
private readonly AsyncRunHandle _runHandle;
internal StreamingRun(AsyncRunHandle runHandle) : base(runHandle)
{
this._runHandle = Throw.IfNull(runHandle);
}
///
/// A unique identifier for the session. Can be provided at the start of the session, or auto-generated.
///
public string SessionId => this._runHandle.SessionId;
///
/// Gets the current execution status of the workflow run.
///
public ValueTask GetStatusAsync(CancellationToken cancellationToken = default)
=> this._runHandle.GetStatusAsync(cancellationToken);
///
/// Asynchronously sends the specified response to the external system and signals completion of the current
/// response wait operation.
///
/// The response will be queued for processing for the next superstep.
/// The to send. Must not be null.
/// A that represents the asynchronous send operation.
public ValueTask SendResponseAsync(ExternalResponse response)
=> this._runHandle.EnqueueResponseAsync(response);
///
/// Attempts to send the specified message asynchronously and returns a value indicating whether the operation was
/// successful.
///
/// The type of the message to send. Must be compatible with the expected message types for
/// the starting executor, or receiving port.
/// The message instance to send. Cannot be null.
/// A that represents the asynchronous send operation. It's
/// is if the message was sent
/// successfully; otherwise, .
public ValueTask TrySendMessageAsync(TMessage message)
=> this._runHandle.EnqueueMessageAsync(message);
internal ValueTask TrySendMessageUntypedAsync(object message, Type? declaredType = null)
=> this._runHandle.EnqueueMessageUntypedAsync(message, declaredType);
internal bool TryGetResponsePortExecutorId(string portId, out string? executorId)
=> this._runHandle.TryGetResponsePortExecutorId(portId, out executorId);
///
/// Asynchronously streams workflow events as they occur during workflow execution.
///
/// This method yields instances in real time as the workflow
/// progresses. The stream completes when a is encountered. Events are
/// delivered in the order they are raised.
/// A that can be used to cancel the streaming operation. If cancellation is
/// requested, the stream will end and no further events will be yielded, but this will not cancel the workflow execution.
/// An asynchronous stream of objects representing significant workflow state changes.
/// The stream ends when the workflow completes or when cancellation is requested.
public IAsyncEnumerable WatchStreamAsync(
CancellationToken cancellationToken = default)
=> this.WatchStreamAsync(blockOnPendingRequest: true, cancellationToken);
internal IAsyncEnumerable WatchStreamAsync(
bool blockOnPendingRequest,
CancellationToken cancellationToken = default)
=> this._runHandle.TakeEventStreamAsync(blockOnPendingRequest, cancellationToken);
///
/// Attempt to cancel the streaming run.
///
/// A that represents the asynchronous send operation.
public ValueTask CancelRunAsync() => this._runHandle.CancelRunAsync();
///
public ValueTask DisposeAsync() => this._runHandle.DisposeAsync();
}
///
/// Provides extension methods for processing and executing workflows using streaming runs.
///
public static class StreamingRunExtensions
{
///
/// Processes all events from the workflow execution stream until completion.
///
/// This method continuously monitors the workflow execution stream provided by and invokes the for each event. If the callback returns a
/// non- response, the response is sent back to the workflow using the handle.
/// The representing the workflow execution stream to monitor.
/// An optional callback function invoked for each received from the stream.
/// The callback can return a response object to be sent back to the workflow, or if no response
/// is required.
/// The to monitor for cancellation requests. The default is .
/// A that represents the asynchronous operation. The task completes when the workflow
/// execution stream is fully processed.
public static async ValueTask RunToCompletionAsync(this StreamingRun handle, Func? eventCallback = null, CancellationToken cancellationToken = default)
{
Throw.IfNull(handle);
await foreach (WorkflowEvent @event in handle.WatchStreamAsync(cancellationToken).ConfigureAwait(false))
{
ExternalResponse? maybeResponse = eventCallback?.Invoke(@event);
if (maybeResponse is not null)
{
await handle.SendResponseAsync(maybeResponse).ConfigureAwait(false);
}
}
}
}