Repository navigation
Expand file tree
/
Copy pathChatService.java
More file actions
1228 lines (1137 loc) · 49.1 KB
/
Copy pathChatService.java
File metadata and controls
1228 lines (1137 loc) · 49.1 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cc.projectargus.workbench.chat;
import cc.projectargus.workbench.config.ArgusVisionProperties;
import cc.projectargus.workbench.config.ArgusWorkbenchProperties;
import cc.projectargus.workbench.runtime.CancellationToken;
import cc.projectargus.workbench.runtime.InferenceConcurrencyGate;
import cc.projectargus.workbench.runtime.InferenceConcurrencyGate.PermitLease;
import cc.projectargus.workbench.runtime.InferenceGateway;
import cc.projectargus.workbench.runtime.ModelNotReadyException;
import cc.projectargus.workbench.web.dto.ApiErrorDto;
import cc.projectargus.workbench.web.dto.ChatImageAttachmentDto;
import cc.projectargus.workbench.web.dto.ChatMessageDto;
import cc.projectargus.workbench.web.dto.ChatRequestDto;
import cc.projectargus.workbench.web.dto.ChatResponseDto;
import cc.projectargus.workbench.web.dto.StopResponseDto;
import cc.projectargus.workbench.web.dto.StreamCompleteEventDto;
import cc.projectargus.workbench.web.dto.StreamStartEventDto;
import cc.projectargus.workbench.web.dto.StreamThinkingEventDto;
import cc.projectargus.workbench.web.dto.StreamTokenEventDto;
import cc.projectargus.workbench.web.dto.TokenUsageDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.Content;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.PartialResponse;
import dev.langchain4j.model.chat.response.PartialResponseContext;
import dev.langchain4j.model.chat.response.PartialThinking;
import dev.langchain4j.model.chat.response.PartialThinkingContext;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.chat.response.StreamingHandle;
import dev.langchain4j.model.output.FinishReason;
import dev.langchain4j.model.output.TokenUsage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/**
* Orchestrates request validation, server-owned {@link SystemMessage} injection, BPE token budgeting
* with sliding turn eviction, bounded concurrency leasing, synchronous chat, and SSE streaming chat
* with {@code <think>} reasoning separation and {@link StreamingHandle} cooperative cancellation.
*/
@Service
public class ChatService implements DisposableBean {
private static final Logger log = LoggerFactory.getLogger(ChatService.class);
private final InferenceGateway inferenceGateway;
private final InferenceConcurrencyGate concurrencyGate;
private final ArgusWorkbenchProperties properties;
private final ArgusVisionProperties visionProperties;
private final ObjectMapper objectMapper;
private final ExecutorService streamingExecutor;
private final ScheduledExecutorService timeoutScheduler;
public ChatService(
InferenceGateway inferenceGateway,
InferenceConcurrencyGate concurrencyGate,
ArgusWorkbenchProperties properties,
ObjectMapper objectMapper
) {
this(inferenceGateway, concurrencyGate, properties, new ArgusVisionProperties(), objectMapper);
}
@Autowired
public ChatService(
InferenceGateway inferenceGateway,
InferenceConcurrencyGate concurrencyGate,
ArgusWorkbenchProperties properties,
ArgusVisionProperties visionProperties,
ObjectMapper objectMapper
) {
this.inferenceGateway = Objects.requireNonNull(inferenceGateway, "inferenceGateway");
this.concurrencyGate = Objects.requireNonNull(concurrencyGate, "concurrencyGate");
this.properties = Objects.requireNonNull(properties, "properties");
this.visionProperties = Objects.requireNonNull(visionProperties, "visionProperties");
this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper");
int poolSize = Math.max(1, properties.getMaxConcurrentInference());
AtomicInteger workerIndex = new AtomicInteger(1);
ThreadFactory workerFactory = runnable -> {
Thread t = new Thread(runnable, "argus-inference-worker-" + workerIndex.getAndIncrement());
t.setDaemon(true);
return t;
};
this.streamingExecutor = Executors.newFixedThreadPool(poolSize, workerFactory);
this.timeoutScheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread t = new Thread(runnable, "argus-inference-watchdog");
t.setDaemon(true);
return t;
});
}
/**
* Executes a synchronous multi-turn chat generation.
*/
public ChatResponseDto chat(ChatRequestDto requestDto) {
ensureChatModeAllowsSync();
NormalizedRequest normalized = validateAndNormalizeRequest(requestDto);
ensureVisionReadyIfNeeded(normalized);
CancellationToken cancellationToken = inferenceGateway.createCancellationToken();
try (PermitLease lease = concurrencyGate.acquireOrReject(normalized.requestId(), cancellationToken)) {
BudgetedConversation budgeted = buildBudgetedConversation(normalized);
ChatRequest chatRequest = buildLangChainRequest(budgeted.messages(), normalized);
long startNanos = System.nanoTime();
ScheduledFuture<?> timeoutHandle = scheduleTimeoutWatchdog(lease.cancellationToken());
try {
ChatResponse response;
try {
response = inferenceGateway.chat(chatRequest, lease.cancellationToken());
} catch (RuntimeException mediaOrInferenceEx) {
if (normalized.hasImages() && isMediaValidationFailure(mediaOrInferenceEx)) {
throw new InvalidChatRequestException(
"invalid_image_payload",
"Invalid or unsupported image attachment payload."
);
}
throw mediaOrInferenceEx;
}
long durationMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
String replyText = response != null && response.aiMessage() != null && response.aiMessage().text() != null
? response.aiMessage().text()
: "";
String thinkingText = response != null && response.aiMessage() != null
? emptyToNull(response.aiMessage().thinking())
: null;
TokenUsageDto usageDto = toTokenUsageDto(response != null ? response.tokenUsage() : null, budgeted.promptTokens());
String finishReason = resolveFinishReason(
response != null ? response.finishReason() : null,
lease.cancellationToken().isAborted()
);
log.info(
"Completed sync chat requestId={} promptTokens={} outputTokens={} evicted={} hasThinking={} finishReason={} durationMs={}",
normalized.requestId(),
usageDto.inputTokens(),
usageDto.outputTokens(),
budgeted.evictedMessages(),
thinkingText != null,
finishReason,
durationMs
);
return new ChatResponseDto(
normalized.requestId(),
replyText,
thinkingText,
null,
finishReason,
usageDto,
budgeted.evictedMessages(),
durationMs
);
} finally {
timeoutHandle.cancel(false);
}
}
}
/**
* Initiates a Server-Sent Events (SSE) streaming chat generation.
*
* <p>Validation, readiness checks, permit acquisition, and token budgeting execute synchronously
* before the {@link SseEmitter} is returned so HTTP 400/429/503 errors are reported cleanly.
*/
public SseEmitter streamChat(ChatRequestDto requestDto) {
ensureChatModeAllowsStream();
NormalizedRequest normalized = validateAndNormalizeRequest(requestDto);
ensureVisionReadyIfNeeded(normalized);
CancellationToken cancellationToken = inferenceGateway.createCancellationToken();
PermitLease lease = concurrencyGate.acquireOrReject(normalized.requestId(), cancellationToken);
final BudgetedConversation budgeted;
final ChatRequest chatRequest;
try {
budgeted = buildBudgetedConversation(normalized);
chatRequest = buildLangChainRequest(budgeted.messages(), normalized);
} catch (Throwable t) {
lease.close();
throw t;
}
long timeoutMs = TimeUnit.SECONDS.toMillis(properties.getInferenceTimeoutSeconds());
SseEmitter emitter = new SseEmitter(timeoutMs);
AtomicBoolean clientDisconnected = new AtomicBoolean(false);
emitter.onTimeout(() -> {
clientDisconnected.set(true);
lease.cancellationToken().abort();
emitter.complete();
});
emitter.onCompletion(() -> {
lease.cancellationToken().abort();
});
emitter.onError(err -> {
clientDisconnected.set(true);
lease.cancellationToken().abort();
});
try {
streamingExecutor.execute(() -> runStreamingJob(
emitter,
lease,
normalized,
budgeted,
chatRequest,
clientDisconnected
));
} catch (RejectedExecutionException rejected) {
lease.close();
throw new IllegalStateException("Streaming executor rejected inference task", rejected);
}
return emitter;
}
/**
* Signals cooperative cancellation to an active request (or all active requests if {@code requestId} is blank).
*/
public StopResponseDto stopGeneration(String requestId) {
if (requestId != null && !requestId.isBlank()) {
String trimmed = requestId.trim();
boolean stopped = concurrencyGate.cancelRequest(trimmed);
return new StopResponseDto(stopped, trimmed);
}
int count = concurrencyGate.cancelAllActive();
return new StopResponseDto(count > 0, null);
}
private void ensureChatModeAllowsSync() {
String mode = properties.getChatMode() == null
? "both"
: properties.getChatMode().trim().toLowerCase(Locale.ROOT);
if (!"both".equals(mode) && !"sync".equals(mode)) {
throw new InvalidChatRequestException(
"sync_chat_disabled",
"Synchronous chat is disabled when ARGUS_CHAT_MODE="
+ mode
+ ". Use POST /api/chat/stream or set ARGUS_CHAT_MODE=both."
);
}
}
private void ensureChatModeAllowsStream() {
String mode = properties.getChatMode() == null
? "both"
: properties.getChatMode().trim().toLowerCase(Locale.ROOT);
if (!"both".equals(mode) && !"stream".equals(mode)) {
throw new InvalidChatRequestException(
"stream_chat_disabled",
"Streaming chat is disabled when ARGUS_CHAT_MODE="
+ mode
+ ". Use POST /api/chat or set ARGUS_CHAT_MODE=both."
);
}
}
private void runStreamingJob(
SseEmitter emitter,
PermitLease lease,
NormalizedRequest normalized,
BudgetedConversation budgeted,
ChatRequest chatRequest,
AtomicBoolean clientDisconnected
) {
long startNanos = System.nanoTime();
ScheduledFuture<?> timeoutHandle = scheduleTimeoutWatchdog(lease.cancellationToken());
StringBuilder accumulatedText = new StringBuilder();
StringBuilder accumulatedThinking = new StringBuilder();
AtomicLong thinkingStartNanos = new AtomicLong(0L);
AtomicLong thinkingEndNanos = new AtomicLong(0L);
AtomicBoolean terminalEventSent = new AtomicBoolean(false);
try {
try (PermitLease ignored = lease) {
try {
if (!sendSseEvent(
emitter,
"start",
new StreamStartEventDto(
normalized.requestId(),
budgeted.promptTokens(),
budgeted.evictedMessages()
),
clientDisconnected,
lease.cancellationToken()
)) {
return;
}
inferenceGateway.streamChat(
chatRequest,
new StreamingChatResponseHandler() {
@Override
public void onPartialThinking(PartialThinking partialThinking) {
if (partialThinking != null) {
handleThinkingChunk(partialThinking.text(), null);
}
}
@Override
public void onPartialThinking(
PartialThinking partialThinking,
PartialThinkingContext context
) {
if (partialThinking != null) {
handleThinkingChunk(
partialThinking.text(),
context != null ? context.streamingHandle() : null
);
}
}
@Override
public void onPartialResponse(String partialResponse) {
handleResponseChunk(partialResponse, null);
}
@Override
public void onPartialResponse(
PartialResponse partialResponse,
PartialResponseContext context
) {
if (partialResponse != null) {
handleResponseChunk(
partialResponse.text(),
context != null ? context.streamingHandle() : null
);
}
}
private void handleThinkingChunk(String chunk, StreamingHandle handle) {
if (chunk == null || chunk.isEmpty()) {
return;
}
if (clientDisconnected.get()) {
cancelStream(handle, lease.cancellationToken());
return;
}
thinkingStartNanos.compareAndSet(0L, System.nanoTime());
accumulatedThinking.append(chunk);
if (!sendSseEvent(
emitter,
"thinking",
new StreamThinkingEventDto(chunk),
clientDisconnected,
lease.cancellationToken()
)) {
cancelStream(handle, lease.cancellationToken());
}
}
private void handleResponseChunk(String chunk, StreamingHandle handle) {
if (chunk == null || chunk.isEmpty()) {
return;
}
if (clientDisconnected.get()) {
cancelStream(handle, lease.cancellationToken());
return;
}
if (thinkingStartNanos.get() != 0L) {
thinkingEndNanos.compareAndSet(0L, System.nanoTime());
}
accumulatedText.append(chunk);
if (!sendSseEvent(
emitter,
"token",
new StreamTokenEventDto(chunk),
clientDisconnected,
lease.cancellationToken()
)) {
cancelStream(handle, lease.cancellationToken());
}
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
if (!terminalEventSent.compareAndSet(false, true)) {
return;
}
long completedNanos = System.nanoTime();
long durationMs = TimeUnit.NANOSECONDS.toMillis(completedNanos - startNanos);
boolean cancelled = lease.cancellationToken().isAborted();
String finalText = completeResponse != null
&& completeResponse.aiMessage() != null
&& completeResponse.aiMessage().text() != null
&& !completeResponse.aiMessage().text().isEmpty()
? completeResponse.aiMessage().text()
: accumulatedText.toString();
String completeThinking = completeResponse != null
&& completeResponse.aiMessage() != null
? emptyToNull(completeResponse.aiMessage().thinking())
: null;
String finalThinking = completeThinking != null
? completeThinking
: emptyToNull(accumulatedThinking.toString());
Long thinkingDurationMs = computeThinkingDurationMs(
finalThinking,
thinkingStartNanos.get(),
thinkingEndNanos.get(),
completedNanos
);
TokenUsageDto usageDto = toTokenUsageDto(
completeResponse != null ? completeResponse.tokenUsage() : null,
budgeted.promptTokens()
);
String finishReason = resolveFinishReason(
completeResponse != null ? completeResponse.finishReason() : null,
cancelled
);
log.info(
"Completed stream chat requestId={} promptTokens={} outputTokens={} evicted={} hasThinking={} finishReason={} cancelled={} durationMs={}",
normalized.requestId(),
usageDto.inputTokens(),
usageDto.outputTokens(),
budgeted.evictedMessages(),
finalThinking != null,
finishReason,
cancelled,
durationMs
);
sendSseEvent(
emitter,
"complete",
new StreamCompleteEventDto(
normalized.requestId(),
finalText,
finalThinking,
thinkingDurationMs,
finishReason,
cancelled,
usageDto,
budgeted.evictedMessages(),
durationMs
),
clientDisconnected,
lease.cancellationToken()
);
}
@Override
public void onError(Throwable error) {
handleStreamFailure(
emitter,
lease.cancellationToken(),
normalized,
budgeted,
accumulatedText,
accumulatedThinking,
thinkingStartNanos.get(),
thinkingEndNanos.get(),
startNanos,
terminalEventSent,
clientDisconnected,
error
);
}
},
lease.cancellationToken()
);
} catch (Throwable t) {
handleStreamFailure(
emitter,
lease.cancellationToken(),
normalized,
budgeted,
accumulatedText,
accumulatedThinking,
thinkingStartNanos.get(),
thinkingEndNanos.get(),
startNanos,
terminalEventSent,
clientDisconnected,
t
);
}
}
} finally {
timeoutHandle.cancel(false);
completeEmitterQuietly(emitter);
}
}
private void handleStreamFailure(
SseEmitter emitter,
CancellationToken cancellationToken,
NormalizedRequest normalized,
BudgetedConversation budgeted,
StringBuilder accumulatedText,
StringBuilder accumulatedThinking,
long thinkingStartNanos,
long thinkingEndNanos,
long startNanos,
AtomicBoolean terminalEventSent,
AtomicBoolean clientDisconnected,
Throwable error
) {
if (!terminalEventSent.compareAndSet(false, true)) {
return;
}
long completedNanos = System.nanoTime();
long durationMs = TimeUnit.NANOSECONDS.toMillis(completedNanos - startNanos);
if (cancellationToken.isAborted()) {
log.info(
"Stream chat cancelled requestId={} durationMs={}",
normalized.requestId(),
durationMs
);
String finalThinking = emptyToNull(accumulatedThinking.toString());
Long thinkingDurationMs = computeThinkingDurationMs(
finalThinking,
thinkingStartNanos,
thinkingEndNanos,
completedNanos
);
TokenUsageDto usage = new TokenUsageDto(budgeted.promptTokens(), 0, budgeted.promptTokens());
sendSseEvent(
emitter,
"complete",
new StreamCompleteEventDto(
normalized.requestId(),
accumulatedText.toString(),
finalThinking,
thinkingDurationMs,
"CANCELLED",
true,
usage,
budgeted.evictedMessages(),
durationMs
),
clientDisconnected,
cancellationToken
);
return;
}
if (normalized.hasImages() && isMediaValidationFailure(error)) {
log.warn("Streaming multimodal validation error for requestId={}", normalized.requestId(), error);
sendSseEvent(
emitter,
"error",
new ApiErrorDto(
"invalid_image_payload",
"Invalid or unsupported image attachment payload."
),
clientDisconnected,
cancellationToken
);
return;
}
log.error("Streaming inference error for requestId={}", normalized.requestId(), error);
sendSseEvent(
emitter,
"error",
new ApiErrorDto(
"inference_failed",
"Local inference encountered an internal runtime error during generation."
),
clientDisconnected,
cancellationToken
);
}
private static void cancelStream(StreamingHandle handle, CancellationToken token) {
if (handle != null) {
try {
handle.cancel();
} catch (Throwable ignored) {
}
}
token.abort();
}
private static Long computeThinkingDurationMs(
String finalThinking,
long startNanos,
long endNanos,
long completedNanos
) {
if (finalThinking == null || startNanos <= 0L) {
return null;
}
long resolvedEnd = endNanos > 0L ? endNanos : completedNanos;
return Math.max(1L, TimeUnit.NANOSECONDS.toMillis(Math.max(0L, resolvedEnd - startNanos)));
}
private static String emptyToNull(String value) {
return (value == null || value.isEmpty()) ? null : value;
}
private boolean sendSseEvent(
SseEmitter emitter,
String eventName,
Object payload,
AtomicBoolean clientDisconnected,
CancellationToken cancellationToken
) {
if (clientDisconnected.get()) {
cancellationToken.abort();
return false;
}
try {
String json = objectMapper.writeValueAsString(payload);
emitter.send(
SseEmitter.event()
.name(eventName)
.data(json, MediaType.APPLICATION_JSON)
);
return true;
} catch (IOException | IllegalStateException sendErr) {
clientDisconnected.set(true);
cancellationToken.abort();
return false;
}
}
private static void completeEmitterQuietly(SseEmitter emitter) {
try {
emitter.complete();
} catch (Throwable ignored) {
}
}
private ScheduledFuture<?> scheduleTimeoutWatchdog(CancellationToken token) {
return timeoutScheduler.schedule(
token::abort,
properties.getInferenceTimeoutSeconds(),
TimeUnit.SECONDS
);
}
private void ensureVisionReadyIfNeeded(NormalizedRequest normalized) {
if (normalized.hasImages() && inferenceGateway.isReady() && !inferenceGateway.isVisionReady()) {
throw new ModelNotReadyException(
"vision_not_enabled",
"Multimodal vision is not enabled. Set ARGUS_VISION_MMPROJ_PATH to a compatible .mmproj GGUF projector file."
);
}
}
private static boolean isMediaValidationFailure(Throwable error) {
Throwable current = error;
for (int depth = 0; current != null && depth < 6; depth++) {
if (current instanceof IllegalArgumentException || current instanceof SecurityException) {
return true;
}
current = current.getCause();
}
return false;
}
NormalizedRequest validateAndNormalizeRequest(ChatRequestDto dto) {
if (dto == null) {
throw new InvalidChatRequestException(
"invalid_request",
"Request body must be a non-empty JSON object."
);
}
boolean hasMessages = dto.messages() != null && !dto.messages().isEmpty();
boolean hasPrompt = dto.prompt() != null && !dto.prompt().isBlank();
boolean hasTopLevelImages = dto.images() != null && !dto.images().isEmpty();
if (hasMessages && (hasPrompt || hasTopLevelImages)) {
throw new InvalidChatRequestException(
"ambiguous_request",
"Provide either 'messages' or 'prompt'/'images', not both."
);
}
if (!hasMessages && !hasPrompt && !hasTopLevelImages) {
throw new InvalidChatRequestException(
"empty_messages",
"Request must include a non-empty 'messages' array, a non-blank 'prompt' string, or 'images'."
);
}
List<ChatMessageDto> rawTurns = hasMessages
? dto.messages()
: List.of(new ChatMessageDto("user", dto.prompt(), dto.images()));
if (rawTurns.size() > properties.getMaxHistoryMessages()) {
throw new InvalidChatRequestException(
"too_many_messages",
"Conversation contains "
+ rawTurns.size()
+ " messages, exceeding the configured limit of "
+ properties.getMaxHistoryMessages()
+ "."
);
}
List<ChatMessage> validatedHistory = new ArrayList<>(rawTurns.size());
int totalChars = 0;
int attachedImageCount = 0;
for (int i = 0; i < rawTurns.size(); i++) {
ChatMessageDto turn = rawTurns.get(i);
if (turn == null) {
throw new InvalidChatRequestException(
"invalid_message",
"Message at index " + i + " must not be null."
);
}
if (turn.role() == null || turn.role().isBlank()) {
throw new InvalidChatRequestException(
"invalid_message_role",
"Message at index " + i + " is missing a role."
);
}
String normalizedRole = turn.role().trim().toLowerCase(Locale.ROOT);
if ("system".equals(normalizedRole) || "tool".equals(normalizedRole)) {
throw new InvalidChatRequestException(
"forbidden_message_role",
"Client messages may only use 'user' or 'assistant' roles; system instructions are owned by the server."
);
}
if (!"user".equals(normalizedRole) && !"assistant".equals(normalizedRole)) {
throw new InvalidChatRequestException(
"invalid_message_role",
"Unsupported message role '" + turn.role() + "'. Allowed roles: 'user', 'assistant'."
);
}
boolean hasImages = turn.images() != null && !turn.images().isEmpty();
if (hasImages && !"user".equals(normalizedRole)) {
throw new InvalidChatRequestException(
"images_only_allowed_on_user_messages",
"Image attachments are only allowed on 'user' messages."
);
}
boolean hasText = turn.content() != null && !turn.content().isBlank();
if (!hasText && !hasImages) {
throw new InvalidChatRequestException(
"empty_message_content",
"Message at index " + i + " must contain non-blank text or image attachments."
);
}
String content = hasText ? turn.content() : "";
if (hasText) {
if (content.length() > properties.getMaxPromptChars()) {
throw new InvalidChatRequestException(
"prompt_too_long",
"Message at index "
+ i
+ " ("
+ content.length()
+ " chars) exceeds the maximum allowed size of "
+ properties.getMaxPromptChars()
+ " characters."
);
}
totalChars += content.length();
if (totalChars > properties.getMaxPromptChars()) {
throw new InvalidChatRequestException(
"prompt_too_long",
"Total conversation character length ("
+ totalChars
+ " chars) exceeds the maximum allowed size of "
+ properties.getMaxPromptChars()
+ " characters."
);
}
}
if ("assistant".equals(normalizedRole)) {
validatedHistory.add(AiMessage.from(content));
} else if (!hasImages) {
validatedHistory.add(UserMessage.from(content));
} else {
List<ChatImageAttachmentDto> images = turn.images();
if (images.size() > visionProperties.getMaxImagesPerMessage()) {
throw new InvalidChatRequestException(
"too_many_images",
"Message at index "
+ i
+ " contains "
+ images.size()
+ " image(s), exceeding the configured limit of "
+ visionProperties.getMaxImagesPerMessage()
+ "."
);
}
List<Content> contents = new ArrayList<>(images.size() + (hasText ? 1 : 0));
if (hasText) {
contents.add(TextContent.from(content));
}
for (ChatImageAttachmentDto attachment : images) {
contents.add(validateAndDecodeImage(attachment, i));
attachedImageCount++;
}
validatedHistory.add(UserMessage.from(contents));
}
}
ChatMessage lastMessage = validatedHistory.get(validatedHistory.size() - 1);
if (!(lastMessage instanceof UserMessage)) {
throw new InvalidChatRequestException(
"last_message_must_be_user",
"The final message in the conversation must have role 'user'."
);
}
float effectiveTemperature = properties.getTemperature();
if (dto.temperature() != null) {
float candidateTemp = dto.temperature();
if (Float.isNaN(candidateTemp) || Float.isInfinite(candidateTemp) || candidateTemp < 0.0f || candidateTemp > 2.0f) {
throw new InvalidChatRequestException(
"invalid_temperature",
"temperature must be between 0.0 and 2.0."
);
}
effectiveTemperature = candidateTemp;
}
int effectiveMaxTokens = properties.getMaxOutputTokens();
if (dto.maxOutputTokens() != null) {
int candidateMax = dto.maxOutputTokens();
if (candidateMax < 1 || candidateMax > properties.getMaxOutputTokens()) {
throw new InvalidChatRequestException(
"invalid_max_output_tokens",
"maxOutputTokens must be between 1 and " + properties.getMaxOutputTokens() + "."
);
}
effectiveMaxTokens = candidateMax;
}
String resolvedRequestId = InferenceConcurrencyGate.normalizeOrGenerateRequestId(dto.requestId());
return new NormalizedRequest(
resolvedRequestId,
List.copyOf(validatedHistory),
effectiveTemperature,
effectiveMaxTokens,
attachedImageCount > 0
);
}
private ImageContent validateAndDecodeImage(ChatImageAttachmentDto attachment, int turnIndex) {
if (attachment == null || attachment.data() == null || attachment.data().isBlank()) {
throw new InvalidChatRequestException(
"invalid_image_base64",
"Image attachment at message index " + turnIndex + " is missing Base64 data."
);
}
String declaredMime = normalizeMimeType(attachment.mimeType());
if (declaredMime != null && !declaredMime.startsWith("image/")) {
throw new InvalidChatRequestException(
"unsupported_image_format",
"Unsupported image MIME type '" + attachment.mimeType() + "'."
);
}
String rawPayload = attachment.data().trim();
String dataUriMime = null;
if (rawPayload.length() >= 5 && rawPayload.regionMatches(true, 0, "data:", 0, 5)) {
int commaIdx = rawPayload.indexOf(',');
if (commaIdx < 0) {
throw new InvalidChatRequestException(
"invalid_image_base64",
"Image data URI at message index " + turnIndex + " is malformed."
);
}
String metadata = rawPayload.substring(5, commaIdx).trim().toLowerCase(Locale.ROOT);
if (!metadata.endsWith(";base64")) {
throw new InvalidChatRequestException(
"invalid_image_base64",
"Image data URI at message index " + turnIndex + " must be Base64 encoded."
);
}
String uriMime = normalizeMimeType(metadata.substring(0, metadata.length() - ";base64".length()));
if (uriMime == null || !uriMime.startsWith("image/")) {
throw new InvalidChatRequestException(
"unsupported_image_format",
"Only image/* data URIs are supported."
);
}
dataUriMime = uriMime;
rawPayload = rawPayload.substring(commaIdx + 1).trim();
}
long maxImageBytes = visionProperties.getMaxImageBytes();
long maxRawChars = ((maxImageBytes + 2L) / 3L) * 4L + (maxImageBytes / 16L) + 256L;
if (rawPayload.length() > maxRawChars) {
throw new InvalidChatRequestException(
"image_too_large",
"Encoded image payload exceeds maximum decoded limit of " + maxImageBytes + " bytes."
);
}
String cleanBase64 = stripAsciiWhitespace(rawPayload);
if (cleanBase64.isEmpty()) {
throw new InvalidChatRequestException(
"invalid_image_base64",
"Image attachment at message index " + turnIndex + " is empty."
);
}
int cleanLen = cleanBase64.length();
int padding = 0;
if (cleanBase64.charAt(cleanLen - 1) == '=') {
padding++;
}
if (cleanLen >= 2 && cleanBase64.charAt(cleanLen - 2) == '=') {
padding++;
}
long estimatedBytes = ((long) cleanLen * 3L) / 4L - padding;
if (estimatedBytes > maxImageBytes) {
throw new InvalidChatRequestException(
"image_too_large",
"Image attachment exceeds the configured limit of " + maxImageBytes + " bytes."
);
}
final byte[] decoded;
try {
decoded = Base64.getDecoder().decode(cleanBase64);
} catch (IllegalArgumentException badBase64) {
throw new InvalidChatRequestException(
"invalid_image_base64",
"Image attachment at message index " + turnIndex + " contains invalid Base64 characters."
);
}
if (decoded.length == 0) {
throw new InvalidChatRequestException(
"invalid_image_base64",
"Image attachment at message index " + turnIndex + " decoded to empty bytes."
);
}
if (decoded.length > maxImageBytes) {
throw new InvalidChatRequestException(
"image_too_large",
"Decoded image size (" + decoded.length + " bytes) exceeds the configured limit of " + maxImageBytes + " bytes."
);
}
String canonicalMime = detectImageMimeType(decoded);
if (canonicalMime == null) {
throw new InvalidChatRequestException(
"unsupported_image_format",
"Image attachment at message index " + turnIndex + " does not match PNG, JPEG, WEBP, GIF, or BMP binary magic bytes."
);
}
if ((dataUriMime != null && !dataUriMime.equals(canonicalMime))
|| (declaredMime != null && !declaredMime.equals(canonicalMime))) {
throw new InvalidChatRequestException(
"unsupported_image_format",
"Declared image MIME type does not match binary signature (" + canonicalMime + ")."
);
}
return ImageContent.from(cleanBase64, canonicalMime);
}
private static String normalizeMimeType(String rawMime) {
if (rawMime == null) {
return null;
}
String trimmed = rawMime.trim().toLowerCase(Locale.ROOT);
if (trimmed.isEmpty()) {
return null;