-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathChatController.cs
More file actions
245 lines (221 loc) · 11.2 KB
/
ChatController.cs
File metadata and controls
245 lines (221 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
using System.IO;
using System.Security.Claims;
using System.Text.Json;
using EssentialCSharp.Chat.Common.Services;
using EssentialCSharp.Web.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
namespace EssentialCSharp.Web.Controllers;
[ApiController]
[Route("api/[controller]")]
[Authorize]
[EnableRateLimiting("ChatEndpoint")]
[IgnoreAntiforgeryToken]
public partial class ChatController : ControllerBase
{
private readonly AIChatService _AIChatService;
private readonly ResponseIdValidationService _ResponseIdValidationService;
private readonly ILogger<ChatController> _Logger;
public ChatController(ILogger<ChatController> logger, AIChatService aiChatService, ResponseIdValidationService responseIdValidationService)
{
_AIChatService = aiChatService;
_ResponseIdValidationService = responseIdValidationService;
_Logger = logger;
}
[HttpPost("message")]
public async Task<IActionResult> SendMessage([FromBody] ChatMessageRequest request, CancellationToken cancellationToken = default)
{
request.Message = request.Message.Trim();
if (string.IsNullOrEmpty(request.Message))
return BadRequest(new { error = "Message cannot be empty." });
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userId))
return Unauthorized();
var previousResponseId = string.IsNullOrWhiteSpace(request.PreviousResponseId)
? null
: request.PreviousResponseId.Trim();
if (!_ResponseIdValidationService.ValidateResponseId(userId, previousResponseId))
return BadRequest(new { error = "Invalid conversation context." });
try
{
var (response, responseId) = await _AIChatService.GetChatCompletion(
prompt: request.Message,
previousResponseId: previousResponseId,
enableContextualSearch: request.EnableContextualSearch,
endUserId: userId,
cancellationToken: cancellationToken);
_ResponseIdValidationService.RecordResponseId(userId, responseId);
return Ok(new ChatMessageResponse
{
Response = response,
ResponseId = responseId,
Timestamp = DateTime.UtcNow
});
}
catch (ConversationContextLimitExceededException)
{
return BadRequest(new { error = "This conversation has grown too long. Please start a new one.", errorCode = "context_limit_exceeded" });
}
}
[HttpPost("stream")]
public async Task StreamMessage([FromBody] ChatMessageRequest request, CancellationToken cancellationToken = default)
{
request.Message = request.Message.Trim();
if (string.IsNullOrEmpty(request.Message))
{
Response.StatusCode = 400;
await Response.WriteAsJsonAsync(new { error = "Message cannot be empty." }, cancellationToken);
return;
}
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = 401;
await Response.WriteAsJsonAsync(new { error = "Unauthorized." }, cancellationToken);
return;
}
var previousResponseId = string.IsNullOrWhiteSpace(request.PreviousResponseId)
? null
: request.PreviousResponseId.Trim();
if (!_ResponseIdValidationService.ValidateResponseId(userId, previousResponseId))
{
Response.StatusCode = 400;
await Response.WriteAsJsonAsync(new { error = "Invalid conversation context." }, cancellationToken);
return;
}
Response.ContentType = "text/event-stream";
Response.Headers.CacheControl = "no-cache";
Response.Headers.Connection = "keep-alive";
try
{
await foreach (var (text, responseId) in _AIChatService.GetChatCompletionStream(
prompt: request.Message,
previousResponseId: previousResponseId,
enableContextualSearch: request.EnableContextualSearch,
endUserId: userId,
cancellationToken: cancellationToken))
{
if (!string.IsNullOrEmpty(text))
{
var eventData = JsonSerializer.Serialize(new { type = "text", data = text });
await Response.WriteAsync($"data: {eventData}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
if (!string.IsNullOrEmpty(responseId))
{
// Record ownership for every responseId emitted — one per API call leg
// (initial request + each tool-call continuation). This ensures all leg IDs
// are bound to the authenticated user before being forwarded to the client.
_ResponseIdValidationService.RecordResponseId(userId, responseId);
var eventData = JsonSerializer.Serialize(new { type = "responseId", data = responseId });
await Response.WriteAsync($"data: {eventData}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
}
await Response.WriteAsync("data: [DONE]\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
catch (OperationCanceledException)
{
if (cancellationToken.IsCancellationRequested || HttpContext.RequestAborted.IsCancellationRequested)
{
LogChatStreamCancelled(_Logger, User.Identity?.Name);
return;
}
throw;
}
catch (ConversationContextLimitExceededException ex)
{
if (!Response.HasStarted)
{
if (cancellationToken.IsCancellationRequested || HttpContext.RequestAborted.IsCancellationRequested)
return;
Response.StatusCode = 400;
Response.ContentType = "application/json";
try
{
var writeCancellationToken =
cancellationToken.IsCancellationRequested || HttpContext.RequestAborted.IsCancellationRequested
? CancellationToken.None
: cancellationToken;
await Response.WriteAsJsonAsync(new { error = "This conversation has grown too long. Please start a new one.", errorCode = "context_limit_exceeded" }, writeCancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || HttpContext.RequestAborted.IsCancellationRequested)
{
// Best-effort write during an aborted request — no response body can be delivered.
}
catch (IOException) when (HttpContext.RequestAborted.IsCancellationRequested)
{
// Expected client disconnect while attempting a best-effort error response write.
}
catch (ObjectDisposedException) when (HttpContext.RequestAborted.IsCancellationRequested)
{
// Response stream can already be disposed after an abrupt client disconnect.
}
}
else
{
LogChatStreamErrorMidStream(_Logger, ex, User.Identity?.Name);
try
{
await Response.WriteAsync("data: {\"type\":\"error\",\"message\":\"This conversation has grown too long. Please start a new one.\",\"errorCode\":\"context_limit_exceeded\"}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
catch (Exception writeException) when (writeException is IOException or OperationCanceledException or ObjectDisposedException)
{
// Best-effort write to an already-streaming response. Kestrel can throw
// IOException (connection reset), OperationCanceledException, or
// ObjectDisposedException on abrupt client disconnect — swallow expected
// transport/disconnect exceptions to avoid masking the original exception.
}
}
}
catch (Exception ex) when (!Response.HasStarted)
{
LogChatStreamErrorBeforeResponseStarted(_Logger, ex, User.Identity?.Name);
if (cancellationToken.IsCancellationRequested || HttpContext.RequestAborted.IsCancellationRequested)
return;
Response.StatusCode = 500;
Response.ContentType = "application/json";
try
{
await Response.WriteAsJsonAsync(new { error = "Chat service unavailable" }, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || HttpContext.RequestAborted.IsCancellationRequested)
{
// Best-effort write during an aborted request — no response body can be delivered.
}
catch (IOException) when (HttpContext.RequestAborted.IsCancellationRequested)
{
// Expected client disconnect while attempting a best-effort error response write.
}
catch (ObjectDisposedException) when (HttpContext.RequestAborted.IsCancellationRequested)
{
// Response stream can already be disposed after an abrupt client disconnect.
}
}
catch (Exception ex)
{
LogChatStreamErrorMidStream(_Logger, ex, User.Identity?.Name);
try
{
await Response.WriteAsync("data: {\"type\":\"error\",\"message\":\"Stream interrupted\"}\n\n", cancellationToken);
await Response.Body.FlushAsync(cancellationToken);
}
catch (Exception writeException) when (writeException is IOException or OperationCanceledException or ObjectDisposedException)
{
// Best-effort write to an already-streaming response. Kestrel can throw
// IOException (connection reset), OperationCanceledException, or
// ObjectDisposedException on abrupt client disconnect — swallow expected
// transport/disconnect exceptions to avoid masking the original exception.
}
}
}
[LoggerMessage(Level = LogLevel.Debug, Message = "Chat stream cancelled for user {User}")]
private static partial void LogChatStreamCancelled(ILogger<ChatController> logger, string? user);
[LoggerMessage(Level = LogLevel.Error, Message = "Chat streaming error before response started for user {User}")]
private static partial void LogChatStreamErrorBeforeResponseStarted(ILogger<ChatController> logger, Exception exception, string? user);
[LoggerMessage(Level = LogLevel.Error, Message = "Chat streaming error mid-stream for user {User}")]
private static partial void LogChatStreamErrorMidStream(ILogger<ChatController> logger, Exception exception, string? user);
}