|
1 | | -using System.Text.Json; |
| 1 | +using System.Runtime.CompilerServices; |
| 2 | +using System.Threading.Channels; |
2 | 3 | using Asp.Versioning; |
3 | | -using Microsoft.AspNetCore.Authorization; |
4 | 4 | using Microsoft.AspNetCore.Http; |
5 | 5 | using Microsoft.AspNetCore.Mvc; |
6 | 6 | using Microsoft.Extensions.AI; |
| 7 | +using Umbraco.Ai.Agui.Events; |
| 8 | +using Umbraco.Ai.Agui.Events.Lifecycle; |
| 9 | +using Umbraco.Ai.Agui.Events.Messages; |
| 10 | +using Umbraco.Ai.Agui.Models; |
| 11 | +using Umbraco.Ai.Agui.Streaming; |
7 | 12 | using Umbraco.Ai.Core.Chat; |
8 | 13 | using Umbraco.Ai.Core.Profiles; |
9 | 14 | using Umbraco.Ai.Extensions; |
10 | | -using Umbraco.Ai.Web.Api.Common.Configuration; |
| 15 | +using Umbraco.Ai.Web.Api.Common.Models; |
11 | 16 | using Umbraco.Ai.Web.Api.Management.Chat.Models; |
12 | 17 | using Umbraco.Ai.Web.Api.Management.Configuration; |
13 | | -using Umbraco.Cms.Core.Mapping; |
14 | | -using Umbraco.Cms.Web.Common.Authorization; |
15 | 18 |
|
16 | 19 | namespace Umbraco.Ai.Web.Api.Management.Chat.Controllers; |
17 | 20 |
|
18 | 21 | /// <summary> |
19 | | -/// Controller for streaming chat completion using Server-Sent Events (SSE). |
| 22 | +/// Controller for streaming chat completion using AG-UI protocol over Server-Sent Events (SSE). |
20 | 23 | /// </summary> |
21 | 24 | [ApiVersion("1.0")] |
22 | 25 | public class StreamChatController : ChatControllerBase |
23 | 26 | { |
24 | 27 | private readonly IAiChatService _chatService; |
25 | 28 | private readonly IAiProfileService _profileService; |
26 | | - private readonly IUmbracoMapper _umbracoMapper; |
27 | 29 |
|
28 | 30 | /// <summary> |
29 | 31 | /// Initializes a new instance of the <see cref="StreamChatController"/> class. |
30 | 32 | /// </summary> |
31 | 33 | public StreamChatController( |
32 | 34 | IAiChatService chatService, |
33 | | - IAiProfileService profileService, |
34 | | - IUmbracoMapper umbracoMapper) |
| 35 | + IAiProfileService profileService) |
35 | 36 | { |
36 | 37 | _chatService = chatService; |
37 | 38 | _profileService = profileService; |
38 | | - _umbracoMapper = umbracoMapper; |
39 | 39 | } |
40 | | - |
| 40 | + |
41 | 41 | /// <summary> |
42 | | - /// Complete a chat conversation with streaming response (SSE). |
| 42 | + /// Complete a chat conversation with AG-UI streaming response (SSE). |
43 | 43 | /// </summary> |
44 | | - /// <param name="requestModel">The chat request.</param> |
| 44 | + /// <param name="request">The AG-UI run request.</param> |
45 | 45 | /// <param name="cancellationToken">Cancellation token.</param> |
46 | | - /// <returns>A stream of chat completion chunks.</returns> |
| 46 | + /// <returns>A stream of AG-UI events.</returns> |
47 | 47 | [HttpPost("stream")] |
48 | 48 | [MapToApiVersion("1.0")] |
49 | 49 | [Produces("text/event-stream")] |
50 | 50 | [ProducesResponseType(StatusCodes.Status200OK)] |
51 | 51 | [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] |
52 | | - [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)] |
53 | | - public async Task StreamChat( |
54 | | - ChatRequestModel requestModel, |
| 52 | + public async Task<IResult> StreamChat( |
| 53 | + AguiRunRequest request, |
| 54 | + CancellationToken cancellationToken = default) |
| 55 | + { |
| 56 | + var events = StreamAguiEventsAsync(request, null, cancellationToken); |
| 57 | + |
| 58 | + return new AguiEventStreamResult(events); |
| 59 | + } |
| 60 | + |
| 61 | + /// <summary> |
| 62 | + /// Complete a chat conversation with AG-UI streaming response (SSE). |
| 63 | + /// </summary> |
| 64 | + /// <param name="profileIdOrAlias"></param> |
| 65 | + /// <param name="request">The AG-UI run request.</param> |
| 66 | + /// <param name="cancellationToken">Cancellation token.</param> |
| 67 | + /// <returns>A stream of AG-UI events.</returns> |
| 68 | + [HttpPost("{profileIdOrAlias}/stream")] |
| 69 | + [MapToApiVersion("1.0")] |
| 70 | + [Produces("text/event-stream")] |
| 71 | + [ProducesResponseType(StatusCodes.Status200OK)] |
| 72 | + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] |
| 73 | + public async Task<IResult> StreamChatWithProfile( |
| 74 | + IdOrAlias profileIdOrAlias, |
| 75 | + AguiRunRequest request, |
55 | 76 | CancellationToken cancellationToken = default) |
56 | 77 | { |
57 | | - Response.ContentType = "text/event-stream"; |
58 | | - Response.Headers.CacheControl = "no-cache"; |
59 | | - Response.Headers.Connection = "keep-alive"; |
| 78 | + var profileId = await _profileService.TryGetProfileIdAsync(profileIdOrAlias, cancellationToken); |
| 79 | + |
| 80 | + var events = StreamAguiEventsAsync(request, profileId, cancellationToken); |
| 81 | + |
| 82 | + return new AguiEventStreamResult(events); |
| 83 | + } |
| 84 | + |
| 85 | + private async IAsyncEnumerable<IAguiEvent> StreamAguiEventsAsync( |
| 86 | + AguiRunRequest request, |
| 87 | + Guid? profileId, |
| 88 | + [EnumeratorCancellation] CancellationToken cancellationToken) |
| 89 | + { |
| 90 | + var threadId = string.IsNullOrEmpty(request.ThreadId) ? Guid.NewGuid().ToString() : request.ThreadId; |
| 91 | + var runId = string.IsNullOrEmpty(request.RunId) ? Guid.NewGuid().ToString() : request.RunId; |
| 92 | + var messageId = Guid.NewGuid().ToString(); |
| 93 | + var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); |
| 94 | + |
| 95 | + // Emit RunStarted |
| 96 | + yield return new RunStartedEvent |
| 97 | + { |
| 98 | + ThreadId = threadId, |
| 99 | + RunId = runId, |
| 100 | + Timestamp = timestamp |
| 101 | + }; |
| 102 | + |
| 103 | + // Emit TextMessageStart for the assistant response |
| 104 | + yield return new TextMessageStartEvent |
| 105 | + { |
| 106 | + MessageId = messageId, |
| 107 | + Role = AguiMessageRole.Assistant, |
| 108 | + Timestamp = timestamp |
| 109 | + }; |
| 110 | + |
| 111 | + // Use Channel for streaming with proper error handling |
| 112 | + var channel = Channel.CreateUnbounded<IAguiEvent>(); |
| 113 | + var hasError = false; |
| 114 | + string? errorMessage = null; |
60 | 115 |
|
61 | | - try |
| 116 | + // Start background task to produce events |
| 117 | + _ = Task.Run(async () => |
62 | 118 | { |
63 | | - // Convert request messages to ChatMessage list |
64 | | - var messages = _umbracoMapper.MapEnumerable<ChatMessageModel, ChatMessage>(requestModel.Messages).ToList(); |
65 | | - |
66 | | - // Resolve profile ID from IdOrAlias |
67 | | - var profileId = requestModel.ProfileIdOrAlias != null |
68 | | - ? await _profileService.TryGetProfileIdAsync(requestModel.ProfileIdOrAlias, cancellationToken) |
69 | | - : null; |
70 | | - |
71 | | - // Get streaming chat response |
72 | | - var stream = profileId.HasValue |
73 | | - ? _chatService.GetStreamingResponseAsync( |
74 | | - profileId.Value, |
75 | | - messages, |
76 | | - cancellationToken: cancellationToken) |
77 | | - : _chatService.GetStreamingResponseAsync( |
78 | | - messages, |
79 | | - cancellationToken: cancellationToken); |
80 | | - |
81 | | - await foreach (var update in stream.WithCancellation(cancellationToken)) |
| 119 | + try |
82 | 120 | { |
83 | | - var chunk = _umbracoMapper.Map<ChatStreamChunkModel>(update); |
| 121 | + // Convert AG-UI messages to M.E.AI ChatMessages |
| 122 | + var chatMessages = ConvertToChatMessages(request.Messages); |
84 | 123 |
|
85 | | - var json = JsonSerializer.Serialize(chunk); |
86 | | - await Response.WriteAsync($"data: {json}\n\n", cancellationToken); |
87 | | - await Response.Body.FlushAsync(cancellationToken); |
| 124 | + // Get streaming response from chat service |
| 125 | + var stream = profileId.HasValue |
| 126 | + ? _chatService.GetStreamingResponseAsync(profileId.Value, chatMessages, cancellationToken: cancellationToken) |
| 127 | + : _chatService.GetStreamingResponseAsync(chatMessages, cancellationToken: cancellationToken); |
| 128 | + |
| 129 | + // Stream text content updates |
| 130 | + await foreach (var update in stream.WithCancellation(cancellationToken)) |
| 131 | + { |
| 132 | + var text = update.Text; |
| 133 | + if (!string.IsNullOrEmpty(text)) |
| 134 | + { |
| 135 | + await channel.Writer.WriteAsync(new TextMessageContentEvent |
| 136 | + { |
| 137 | + MessageId = messageId, |
| 138 | + Delta = text, |
| 139 | + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() |
| 140 | + }, cancellationToken); |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + catch (Exception ex) |
| 145 | + { |
| 146 | + hasError = true; |
| 147 | + errorMessage = ex.Message; |
| 148 | + } |
| 149 | + finally |
| 150 | + { |
| 151 | + channel.Writer.Complete(); |
88 | 152 | } |
| 153 | + }, cancellationToken); |
89 | 154 |
|
90 | | - // Send final event |
91 | | - await Response.WriteAsync("data: [DONE]\n\n", cancellationToken); |
92 | | - await Response.Body.FlushAsync(cancellationToken); |
| 155 | + // Read from channel and yield events |
| 156 | + await foreach (var evt in channel.Reader.ReadAllAsync(cancellationToken)) |
| 157 | + { |
| 158 | + yield return evt; |
93 | 159 | } |
94 | | - catch (InvalidOperationException ex) when (ex.Message.Contains("not found")) |
| 160 | + |
| 161 | + // Emit TextMessageEnd |
| 162 | + yield return new TextMessageEndEvent |
95 | 163 | { |
96 | | - Response.StatusCode = StatusCodes.Status404NotFound; |
97 | | - var error = JsonSerializer.Serialize(new { error = "Profile not found", detail = ex.Message }); |
98 | | - await Response.WriteAsync($"data: {error}\n\n", cancellationToken); |
| 164 | + MessageId = messageId, |
| 165 | + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() |
| 166 | + }; |
| 167 | + |
| 168 | + if (hasError) |
| 169 | + { |
| 170 | + // Emit error event |
| 171 | + yield return new RunErrorEvent |
| 172 | + { |
| 173 | + Message = errorMessage ?? "Unknown error occurred", |
| 174 | + Code = "CHAT_ERROR", |
| 175 | + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() |
| 176 | + }; |
99 | 177 | } |
100 | | - catch (Exception ex) |
| 178 | + |
| 179 | + // Emit RunFinished |
| 180 | + yield return new RunFinishedEvent |
101 | 181 | { |
102 | | - Response.StatusCode = StatusCodes.Status400BadRequest; |
103 | | - var error = JsonSerializer.Serialize(new { error = "Chat streaming failed", detail = ex.Message }); |
104 | | - await Response.WriteAsync($"data: {error}\n\n", cancellationToken); |
| 182 | + ThreadId = threadId, |
| 183 | + RunId = runId, |
| 184 | + Outcome = hasError ? AguiRunOutcome.Interrupt : AguiRunOutcome.Success, |
| 185 | + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() |
| 186 | + }; |
| 187 | + } |
| 188 | + |
| 189 | + private static List<ChatMessage> ConvertToChatMessages(IEnumerable<AguiMessage> messages) |
| 190 | + { |
| 191 | + var chatMessages = new List<ChatMessage>(); |
| 192 | + |
| 193 | + foreach (var msg in messages) |
| 194 | + { |
| 195 | + var role = msg.Role switch |
| 196 | + { |
| 197 | + AguiMessageRole.User => ChatRole.User, |
| 198 | + AguiMessageRole.Assistant => ChatRole.Assistant, |
| 199 | + AguiMessageRole.System => ChatRole.System, |
| 200 | + AguiMessageRole.Tool => ChatRole.Tool, |
| 201 | + AguiMessageRole.Developer => ChatRole.System, // Map developer to system |
| 202 | + _ => ChatRole.User |
| 203 | + }; |
| 204 | + |
| 205 | + chatMessages.Add(new ChatMessage(role, msg.Content ?? string.Empty)); |
105 | 206 | } |
| 207 | + |
| 208 | + return chatMessages; |
106 | 209 | } |
107 | 210 | } |
0 commit comments