Repository navigation
Expand file tree
/
Copy pathOllamaEndpoints.java
More file actions
858 lines (776 loc) · 34.5 KB
/
Copy pathOllamaEndpoints.java
File metadata and controls
858 lines (776 loc) · 34.5 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
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.semoss.web.services.local;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.github.f4b6a3.uuid.alt.GUID;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.ToNumberPolicy;
import com.google.gson.reflect.TypeToken;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.StreamingOutput;
import prerna.auth.User;
import prerna.auth.utils.SecurityEngineUtils;
import prerna.engine.api.IModelEngine;
import prerna.engine.impl.model.AbstractModelEngine;
import prerna.engine.impl.model.ModelPixelInvoker;
import prerna.engine.impl.model.Room;
import prerna.engine.impl.model.RoomUtils;
import prerna.engine.impl.model.responses.AskModelEngineResponse;
import prerna.engine.impl.model.responses.EmbeddingsModelEngineResponse;
import prerna.engine.impl.model.usage.ModelUsageLimitException;
import prerna.om.Insight;
import prerna.om.InsightStore;
import prerna.sablecc2.PixelRunner;
import prerna.sablecc2.comm.PixelJobManager;
import prerna.sablecc2.comm.PixelJobRunner;
import prerna.sablecc2.comm.PixelJobStatus;
import prerna.sablecc2.om.nounmeta.NounMetadata;
import prerna.util.Constants;
import prerna.util.Utility;
import prerna.web.services.util.ModelPixelExecutor;
import prerna.web.services.util.WebUtility;
@Path("/model/ollama")
@PermitAll
public class OllamaEndpoints {
private static final Logger classLogger = LogManager.getLogger(OllamaEndpoints.class);
private static final String ERROR_TYPE = "errorType";
private static final String INSIGHT_NOT_FOUND = "INSIGHT_NOT_FOUND";
private static final Gson GSON = new GsonBuilder().setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.disableHtmlEscaping().create();
// Ollama sampling options SEMOSS models take under the same name
private static final Set<String> SAMPLING_OPTIONS = Set.of("temperature", "top_p", "stop", "seed",
"frequency_penalty", "presence_penalty");
@POST
@Path("/api/chat")
@Consumes({ "application/json" })
@Produces({ "application/json;charset=utf-8", "application/x-ndjson" })
public Response apiChat(@Context HttpServletRequest request) {
return chat(request);
}
@POST
@Path("/chat")
@Consumes({ "application/json" })
@Produces({ "application/json;charset=utf-8", "application/x-ndjson" })
public Response chat(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
User user = ModelPixelExecutor.getSessionUser(session);
if (user == null) {
return ModelPixelExecutor.invalidSessionResponse(request, session);
}
// set the user timezone
ModelPixelExecutor.applyUserTimezone(user, request);
Map<String, Object> dataMap;
try {
dataMap = readRequestData(request);
} catch (JsonSyntaxException e) {
classLogger.error("Failed to parse JSON payload for Ollama /chat request: {}", e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, "Error processing JSON data: " + e.getMessage());
} catch (IOException e) {
classLogger.error("Failed to read request body for Ollama /chat endpoint: {}", e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, "Bad Request: Could not read request body.");
}
String engineId = sanitize(dataMap.remove("model"));
if (engineId == null || engineId.isEmpty()) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: Missing required field 'model'.");
}
if (!SecurityEngineUtils.userCanViewEngine(user, engineId)) {
return ModelPixelExecutor.errorResponse(403,
"Model " + engineId + " does not exist or user does not have access to this model");
}
IModelEngine engine = Utility.getModel(engineId);
if (engine == null) {
return ModelPixelExecutor.errorResponse(404, "Model not found: " + engineId);
}
translateOllamaParams(dataMap);
final String SESSION_ID = session.getId();
final String JOB_ID = GUID.v7().toUUID().toString();
Insight insight = resolveInsight(SESSION_ID, sanitize(dataMap.remove("insight_id")));
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not resolve insight context");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
return WebUtility.getResponse(errorMap, 400);
}
insight.setUser(user);
String roomId = sanitize(dataMap.remove("room_id"));
Room room = RoomUtils.createRoomIfNotExists(roomId, insight, engine, null);
ModelPixelInvoker.initializeThreadStore(insight, SESSION_ID, JOB_ID);
Object messagesInput = dataMap.remove("messages");
if (messagesInput == null) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: Missing required field 'messages'.");
}
List<Map<String, Object>> normalizedMessages = OllamaResponsesHelper.normalizeChatMessages(messagesInput);
if (normalizedMessages.isEmpty()) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: 'messages' must contain at least one item.");
}
boolean stream = Boolean.parseBoolean(String.valueOf(dataMap.getOrDefault("stream", true)));
dataMap.remove("stream");
boolean appendFullPrompt = Boolean
.parseBoolean(String.valueOf(dataMap.getOrDefault("append_full_prompt", false)));
dataMap.remove("append_full_prompt");
dataMap.put(AbstractModelEngine.FULL_PROMPT, normalizedMessages);
dataMap.put(AbstractModelEngine.APPEND_FULL_PROMPT, appendFullPrompt);
if (!stream) {
try {
AskModelEngineResponse llmResponse = ModelPixelExecutor.askModelSync(engine, insight, room, dataMap);
Map<String, Object> payload = OllamaResponsesHelper.processFullChatResponse(engineId, llmResponse);
return WebUtility.getResponse(payload, 200);
} catch (Exception e) {
ModelUsageLimitException refusal = ModelPixelExecutor.findUsageLimitRefusal(e);
if (refusal != null) {
return usageLimitResponse(refusal);
}
classLogger.error("Synchronous Ollama /chat call failed for engine '{}': {}", engineId, e.getMessage(),
e);
return ModelPixelExecutor.errorResponse(400, e.getMessage());
}
}
ModelUsageLimitException refusal = ModelPixelExecutor.checkUsageLimitsBeforeStream(user, engine);
if (refusal != null) {
return usageLimitResponse(refusal);
}
StreamingOutput output = new StreamingOutput() {
@Override
@SuppressWarnings("unchecked")
public void write(OutputStream rawOutput) throws IOException, WebApplicationException {
// ollama does not actually stream tool deltas
// need to aggregate the entire tool
// and then send
Map<String, Object> currentToolMap = new HashMap<>();
String jobId = null;
try (Writer writer = new BufferedWriter(new OutputStreamWriter(rawOutput, StandardCharsets.UTF_8))) {
jobId = ModelPixelInvoker.startAsyncModelRequest(engine, insight, room, dataMap, SESSION_ID);
boolean started = false;
Integer capturedPromptTokens = null;
Integer capturedCompletionTokens = null;
Integer capturedCachedTokens = null;
Integer capturedReasoningTokens = null;
// polling streaming endpoint until response complete
STREAM_COMPLETE_LOOP: while (true) {
PixelJobRunner jt = PixelJobManager.getManager().getJob(jobId);
// read before the chunks, so a job that has stopped has sent every chunk
// this read returns
PixelJobStatus jobStatus = jt == null ? PixelJobStatus.UNKNOWN_JOB : jt.getPixelJobStatus();
List<Map<String, Object>> partialResponseContent = PixelJobManager.getManager()
.getStreamOut(jobId);
/**
* The partialResponseContent Map<String,Object> values comes from the python
* code
*
* smss_stream_func defined in gaas_tcp_server_handler.py determines the payload
* {"stream_type": stream_type, "data": data}
*
* The data portion of this payload matches the Dictionary definitions in
* semoss_streaming_util.py StreamUtil class
*
*/
if (partialResponseContent != null && partialResponseContent.size() > 0) {
for (Map<String, Object> streamObj : partialResponseContent) {
String streamType = (String) streamObj.get("stream_type");
Map<String, Object> dataMap = (Map<String, Object>) streamObj.get("data");
if ("usage".equalsIgnoreCase(streamType)) {
Object inT = dataMap.get("input_tokens");
if (inT instanceof Number) {
capturedPromptTokens = ((Number) inT).intValue();
}
Object outT = dataMap.get("output_tokens");
if (outT instanceof Number) {
capturedCompletionTokens = ((Number) outT).intValue();
}
Object crT = dataMap.get("cache_read_input_tokens");
if (crT instanceof Number) {
capturedCachedTokens = ((Number) crT).intValue();
}
Object rT = dataMap.get("reasoning_tokens");
if (rT instanceof Number) {
capturedReasoningTokens = ((Number) rT).intValue();
}
continue;
}
if ("content".equalsIgnoreCase(streamType)) {
if (dataMap.containsKey("finish_reason")) {
String finishReason = (String) dataMap.get("finish_reason");
// this is a map only on finish reason
OllamaResponsesHelper.writeFinishReason(finishReason, capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens,
writer);
break STREAM_COMPLETE_LOOP;
} else {
String newContent = (String) dataMap.get("content");
if (newContent != null && !newContent.isEmpty()) {
OllamaResponsesHelper.writeChatContentChunk(engineId, newContent, writer);
started = true;
}
}
} else if ("thinking".equalsIgnoreCase(streamType)) {
// thinking is not the answer, so a result that was not streamed is
// still sent when the job completes
Object thinking = dataMap.get("thinking");
if (thinking != null && !thinking.toString().isEmpty()) {
OllamaResponsesHelper.writeChatThinkingChunk(engineId, thinking.toString(),
writer);
}
} else if ("tool".equalsIgnoreCase(streamType)) {
if (dataMap.containsKey("finish_reason")) {
// we need to send the aggregated tool chunk
if (!currentToolMap.isEmpty()) {
OllamaResponsesHelper.writeChatTool(engineId, currentToolMap, writer);
currentToolMap = new HashMap<>();
}
// send the finish chunk
String finishReason = (String) dataMap.get("finish_reason");
OllamaResponsesHelper.writeFinishReason(finishReason, capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens,
writer);
break STREAM_COMPLETE_LOOP;
} else {
// we are entering a new tool
if (!currentToolMap.isEmpty() && dataMap.containsKey("id")) {
OllamaResponsesHelper.writeChatTool(engineId, currentToolMap, writer);
currentToolMap = new HashMap<>();
}
OllamaResponsesHelper.aggregateToolChunks(currentToolMap, dataMap);
started = true;
}
}
}
}
// if job is complete, we should never hit this if
// a completion should have been sent
if (jobStatus == PixelJobStatus.PROGRESS_COMPLETE && started) {
// send final chunk with empty delta && finish_reason="stop"
OllamaResponsesHelper.writeFinishReason("stop", capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens, writer);
break STREAM_COMPLETE_LOOP;
} else if (jobStatus == PixelJobStatus.PROGRESS_COMPLETE && !started) {
// we didn't start
// and there is no output
// lets check the result
// ... most likely this is a tool output
PixelRunner finalOutput = PixelJobManager.getManager().getOutput(jobId);
NounMetadata finalNoun = finalOutput.getResults().get(0);
Object finalObject = finalNoun.getValue();
String messageType = null;
Map<String, Object> resultOutput = null;
if (finalObject instanceof Map) {
resultOutput = (Map<String, Object>) finalObject;
messageType = (String) resultOutput.get("messageType");
}
if ("TOOL".equals(messageType)) {
// this is a function call request that was not streamed
// maybe the model doesn't support streaming of tools
List<Map<String, Object>> response = (List<Map<String, Object>>) resultOutput
.get("response");
if (response != null && !response.isEmpty()) {
OllamaResponsesHelper.writeFullChatToolResponseAsChunk(engineId, response, writer);
}
// done reason is still stop
// unlike open_ai which is tool_calls
OllamaResponsesHelper.writeFinishReason("stop", capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens,
writer);
} else {
// Handle regular text response
String content = null;
if (resultOutput != null) {
content = (String) resultOutput.get("response");
if (content != null && !content.isEmpty()) {
OllamaResponsesHelper.writeChatContentChunk(engineId, content, writer);
}
}
// send final chunk with empty delta && finish_reason="stop"
OllamaResponsesHelper.writeFinishReason("stop", capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens,
writer);
}
// job is marked complete, always break
break STREAM_COMPLETE_LOOP;
}
String failure = ModelPixelExecutor.streamFailureMessage(jobStatus);
if (failure != null) {
classLogger.warn("Ollama stream for engine '{}' ended with job status {}", engineId,
jobStatus);
OllamaResponsesHelper.writeStreamError(failure, writer);
break STREAM_COMPLETE_LOOP;
}
// small delay
try {
Thread.sleep(ModelPixelInvoker.STREAM_POLL_INTERVAL_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
} catch (IOException ioe) {
if (!WebUtility.handleStreamingException(ioe, classLogger, engineId, null, null)) {
classLogger.error("Streaming Ollama /chat call failed for engine '{}': {}", engineId,
ioe.getMessage(), ioe);
throw new WebApplicationException(ioe, 500);
}
} catch (Exception e) {
classLogger.error("Streaming Ollama /chat call failed for engine '{}': {}", engineId,
e.getMessage(), e);
throw new WebApplicationException(e, 500);
} finally {
if (jobId != null) {
PixelJobManager.getManager().clearJob(jobId);
PixelJobManager.getManager().removeJob(jobId);
}
}
}
};
return Response.ok().header("Content-Type", "application/x-ndjson").header("Cache-Control", "no-cache")
.header("Connection", "keep-alive").entity(output).build();
}
@POST
@Path("/api/generate")
@Consumes({ "application/json" })
@Produces({ "application/json;charset=utf-8", "application/x-ndjson" })
public Response apigenerate(@Context HttpServletRequest request) {
return generate(request);
}
@POST
@Path("/generate")
@Consumes({ "application/json" })
@Produces({ "application/json;charset=utf-8", "application/x-ndjson" })
public Response generate(@Context HttpServletRequest request) {
// this is equivalent of legacy OpenAI Text completion
HttpSession session = request.getSession(false);
User user = ModelPixelExecutor.getSessionUser(session);
if (user == null) {
return ModelPixelExecutor.invalidSessionResponse(request, session);
}
// set the user timezone
ModelPixelExecutor.applyUserTimezone(user, request);
Map<String, Object> dataMap;
try {
dataMap = readRequestData(request);
} catch (JsonSyntaxException e) {
classLogger.error("Failed to parse JSON payload for Ollama /generate request: {}", e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, "Error processing JSON data: " + e.getMessage());
} catch (IOException e) {
classLogger.error("Failed to read request body for Ollama /generate endpoint: {}", e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, "Bad Request: Could not read request body.");
}
String engineId = sanitize(dataMap.remove("model"));
if (engineId == null || engineId.isEmpty()) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: Missing required field 'model'.");
}
if (!SecurityEngineUtils.userCanViewEngine(user, engineId)) {
return ModelPixelExecutor.errorResponse(403,
"Model " + engineId + " does not exist or user does not have access to this model");
}
IModelEngine engine = Utility.getModel(engineId);
if (engine == null) {
return ModelPixelExecutor.errorResponse(404, "Model not found: " + engineId);
}
translateOllamaParams(dataMap);
final String SESSION_ID = session.getId();
final String JOB_ID = GUID.v7().toUUID().toString();
Insight insight = resolveInsight(SESSION_ID, sanitize(dataMap.remove("insight_id")));
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not resolve insight context");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
return WebUtility.getResponse(errorMap, 400);
}
insight.setUser(user);
String roomId = sanitize(dataMap.remove("room_id"));
Room room = RoomUtils.createRoomIfNotExists(roomId, insight, engine, null);
ModelPixelInvoker.initializeThreadStore(insight, SESSION_ID, JOB_ID);
Object promptInput = dataMap.remove("prompt");
Object inputFallback = dataMap.remove("input");
String prompt = OllamaResponsesHelper.extractPrompt(promptInput, inputFallback);
if (prompt == null || prompt.isEmpty()) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: Missing required field 'prompt'.");
}
boolean stream = Boolean.parseBoolean(String.valueOf(dataMap.getOrDefault("stream", true)));
dataMap.remove("stream");
// route through the LLM pixel by carrying the prompt as a full_prompt message
List<Map<String, Object>> generateMessages = new ArrayList<>();
Map<String, Object> generateUserMessage = new HashMap<>();
generateUserMessage.put("role", "user");
generateUserMessage.put("content", prompt);
generateMessages.add(generateUserMessage);
dataMap.put(AbstractModelEngine.FULL_PROMPT, generateMessages);
if (!stream) {
try {
AskModelEngineResponse llmResponse = ModelPixelExecutor.askModelSync(engine, insight, room, dataMap);
Map<String, Object> payload = OllamaResponsesHelper.processFullGenerateResponse(engineId, llmResponse);
return WebUtility.getResponse(payload, 200);
} catch (Exception e) {
ModelUsageLimitException refusal = ModelPixelExecutor.findUsageLimitRefusal(e);
if (refusal != null) {
return usageLimitResponse(refusal);
}
classLogger.error("Synchronous Ollama /generate call failed for engine '{}': {}", engineId,
e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, e.getMessage());
}
}
ModelUsageLimitException refusal = ModelPixelExecutor.checkUsageLimitsBeforeStream(user, engine);
if (refusal != null) {
return usageLimitResponse(refusal);
}
StreamingOutput output = new StreamingOutput() {
@Override
@SuppressWarnings("unchecked")
public void write(OutputStream rawOutput) throws IOException, WebApplicationException {
String jobId = null;
try (Writer writer = new BufferedWriter(new OutputStreamWriter(rawOutput, StandardCharsets.UTF_8))) {
jobId = ModelPixelInvoker.startAsyncModelRequest(engine, insight, room, dataMap, SESSION_ID);
boolean started = false;
Integer capturedPromptTokens = null;
Integer capturedCompletionTokens = null;
Integer capturedCachedTokens = null;
Integer capturedReasoningTokens = null;
// polling streaming endpoint until response complete
STREAM_COMPLETE_LOOP: while (true) {
PixelJobRunner jt = PixelJobManager.getManager().getJob(jobId);
// read before the chunks, so a job that has stopped has sent every chunk
// this read returns
PixelJobStatus jobStatus = jt == null ? PixelJobStatus.UNKNOWN_JOB : jt.getPixelJobStatus();
List<Map<String, Object>> partialResponseContent = PixelJobManager.getManager()
.getStreamOut(jobId);
/**
* The partialResponseContent Map<String,Object> values comes from the python
* code
*
* smss_stream_func defined in gaas_tcp_server_handler.py determines the payload
* {"stream_type": stream_type, "data": data}
*
* The data portion of this payload matches the Dictionary definitions in
* semoss_streaming_util.py StreamUtil class
*
*/
if (partialResponseContent != null && partialResponseContent.size() > 0) {
for (Map<String, Object> streamObj : partialResponseContent) {
String streamType = (String) streamObj.get("stream_type");
Map<String, Object> dataMap = (Map<String, Object>) streamObj.get("data");
if ("usage".equalsIgnoreCase(streamType)) {
Object inT = dataMap.get("input_tokens");
if (inT instanceof Number) {
capturedPromptTokens = ((Number) inT).intValue();
}
Object outT = dataMap.get("output_tokens");
if (outT instanceof Number) {
capturedCompletionTokens = ((Number) outT).intValue();
}
Object crT = dataMap.get("cache_read_input_tokens");
if (crT instanceof Number) {
capturedCachedTokens = ((Number) crT).intValue();
}
Object rT = dataMap.get("reasoning_tokens");
if (rT instanceof Number) {
capturedReasoningTokens = ((Number) rT).intValue();
}
continue;
}
if ("content".equalsIgnoreCase(streamType)) {
if (dataMap.containsKey("finish_reason")) {
String finishReason = (String) dataMap.get("finish_reason");
// this is a map only on finish reason
OllamaResponsesHelper.writeFinishReason(finishReason, capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens,
writer);
break STREAM_COMPLETE_LOOP;
} else {
String newContent = (String) dataMap.get("content");
if (newContent != null && !newContent.isEmpty()) {
OllamaResponsesHelper.writeGenerateContentChunk(engineId, newContent,
writer);
started = true;
}
}
} else {
// for future stream types
}
}
}
// if job is complete, we should never hit this if
// a completion should have been sent
if (jobStatus == PixelJobStatus.PROGRESS_COMPLETE && started) {
// send final chunk with empty delta && finish_reason="stop"
OllamaResponsesHelper.writeFinishReason("stop", capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens, writer);
break STREAM_COMPLETE_LOOP;
} else if (jobStatus == PixelJobStatus.PROGRESS_COMPLETE && !started) {
// we didn't start
// and there is no output
// lets check the result
// ... most likely this is a tool output
PixelRunner finalOutput = PixelJobManager.getManager().getOutput(jobId);
NounMetadata finalNoun = finalOutput.getResults().get(0);
Object finalObject = finalNoun.getValue();
// this is not used, but for future in terms of thinking vs regular content
String messageType = null;
Map<String, Object> resultOutput = null;
if (finalObject instanceof Map) {
resultOutput = (Map<String, Object>) finalObject;
messageType = (String) resultOutput.get("messageType");
}
// Handle regular text response
String content = null;
if (resultOutput != null) {
content = (String) resultOutput.get("response");
if (content != null && !content.isEmpty()) {
OllamaResponsesHelper.writeGenerateContentChunk(engineId, content, writer);
}
}
// send final chunk with empty delta && finish_reason="stop"
OllamaResponsesHelper.writeFinishReason("stop", capturedPromptTokens,
capturedCompletionTokens, capturedCachedTokens, capturedReasoningTokens, writer);
// job is marked complete, always break
break STREAM_COMPLETE_LOOP;
}
String failure = ModelPixelExecutor.streamFailureMessage(jobStatus);
if (failure != null) {
classLogger.warn("Ollama stream for engine '{}' ended with job status {}", engineId,
jobStatus);
OllamaResponsesHelper.writeStreamError(failure, writer);
break STREAM_COMPLETE_LOOP;
}
// small delay
try {
Thread.sleep(ModelPixelInvoker.STREAM_POLL_INTERVAL_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
} catch (IOException ioe) {
if (!WebUtility.handleStreamingException(ioe, classLogger, engineId, null, null)) {
classLogger.error("Streaming Ollama /generate call failed for engine '{}': {}", engineId,
ioe.getMessage(), ioe);
throw new WebApplicationException(ioe, 500);
}
} catch (Exception e) {
classLogger.error("Streaming Ollama /generate call failed for engine '{}': {}", engineId,
e.getMessage(), e);
throw new WebApplicationException(e, 500);
} finally {
if (jobId != null) {
PixelJobManager.getManager().clearJob(jobId);
PixelJobManager.getManager().removeJob(jobId);
}
}
}
};
return Response.ok().header("Content-Type", "application/x-ndjson").header("Cache-Control", "no-cache")
.header("Connection", "keep-alive").entity(output).build();
}
@POST
@Path("/embeddings")
@Consumes({ "application/json" })
@Produces("application/json;charset=utf-8")
public Response embeddings(@Context HttpServletRequest request) {
HttpSession session = request.getSession(false);
User user = ModelPixelExecutor.getSessionUser(session);
if (user == null) {
return ModelPixelExecutor.invalidSessionResponse(request, session);
}
// set the user timezone
ModelPixelExecutor.applyUserTimezone(user, request);
Map<String, Object> dataMap;
try {
dataMap = readRequestData(request);
} catch (JsonSyntaxException e) {
classLogger.error("Failed to parse JSON payload for Ollama /embeddings request: {}", e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, "Error processing JSON data: " + e.getMessage());
} catch (IOException e) {
classLogger.error("Failed to read request body for Ollama /embeddings endpoint: {}", e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, "Bad Request: Could not read request body.");
}
String engineId = sanitize(dataMap.remove("model"));
if (engineId == null || engineId.isEmpty()) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: Missing required field 'model'.");
}
if (!SecurityEngineUtils.userCanViewEngine(user, engineId)) {
return ModelPixelExecutor.errorResponse(403,
"Model " + engineId + " does not exist or user does not have access to this model");
}
IModelEngine engine = Utility.getModel(engineId);
if (engine == null) {
return ModelPixelExecutor.errorResponse(404, "Model not found: " + engineId);
}
removeOllamaParams(dataMap);
final String SESSION_ID = session.getId();
final String JOB_ID = GUID.v7().toUUID().toString();
Insight insight = resolveInsight(SESSION_ID, sanitize(dataMap.remove("insight_id")));
if (insight == null) {
Map<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Could not resolve insight context");
errorMap.put(ERROR_TYPE, INSIGHT_NOT_FOUND);
return WebUtility.getResponse(errorMap, 400);
}
insight.setUser(user);
ModelPixelInvoker.initializeThreadStore(insight, SESSION_ID, JOB_ID);
Object promptInput = dataMap.remove("prompt");
Object inputInput = dataMap.remove("input");
List<String> stringsToEncode = OllamaResponsesHelper.extractEmbeddingInputs(promptInput, inputInput);
if (stringsToEncode == null || stringsToEncode.isEmpty()) {
return ModelPixelExecutor.errorResponse(400, "Bad Request: Missing required field 'prompt' or 'input'.");
}
try {
EmbeddingsModelEngineResponse embeddingsResponse = engine.embeddings(stringsToEncode, insight, dataMap);
Map<String, Object> payload = OllamaResponsesHelper.processEmbeddingsResponse(engineId, embeddingsResponse,
stringsToEncode.size() == 1);
return WebUtility.getResponse(payload, 200);
} catch (Exception e) {
ModelUsageLimitException refusal = ModelPixelExecutor.findUsageLimitRefusal(e);
if (refusal != null) {
return usageLimitResponse(refusal);
}
classLogger.error("Ollama /embeddings call failed for engine '{}': {}", engineId, e.getMessage(), e);
return ModelPixelExecutor.errorResponse(400, e.getMessage());
}
}
/**
* The response for a call a usage limit refused, with an Ollama error body and
* the code from {@link ModelPixelExecutor#usageLimitCode}.
*
* @param refusal the refusal
* @return the response
*/
private static Response usageLimitResponse(ModelUsageLimitException refusal) {
Map<String, Object> body = new HashMap<>();
body.put("error", refusal.getMessage());
body.put("code", ModelPixelExecutor.usageLimitCode(refusal));
body.put(Constants.ERROR_MESSAGE, refusal.getMessage());
return ModelPixelExecutor.usageLimitResponse(refusal, body);
}
private Map<String, Object> readRequestData(HttpServletRequest request) throws IOException {
StringBuilder requestData = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
requestData.append(line);
}
}
return GSON.fromJson(WebUtility.jsonSanitizer(requestData.toString()), new TypeToken<Map<String, Object>>() {
}.getType());
}
private Insight resolveInsight(String sessionId, String insightId) {
Insight insight;
if (insightId == null || insightId.isEmpty()) {
Set<String> sessionInsights = InsightStore.getInstance().getInsightIDsForSession(sessionId);
if (sessionInsights == null || sessionInsights.isEmpty()) {
insight = new Insight();
InsightStore.getInstance().put(insight);
InsightStore.getInstance().addToSessionHash(sessionId, insight.getInsightId());
} else {
String existingId = sessionInsights.iterator().next();
insight = InsightStore.getInstance().get(existingId);
}
} else {
insight = InsightStore.getInstance().get(insightId);
InsightStore.getInstance().addToSessionHash(sessionId, insightId);
}
return insight;
}
private String sanitize(Object input) {
if (input == null) {
return null;
}
return WebUtility.inputSanitizer(input.toString());
}
/**
* Moves an Ollama request's settings into the SEMOSS model parameters: the
* sampling options SEMOSS models take, {@code num_predict} as
* {@code max_tokens}, and {@code think} as SEMOSS thinking and effort. A
* parameter the request also sets at the top level keeps that value. Options
* with no SEMOSS counterpart, and {@code keep_alive}, which only applies to an
* Ollama server, are dropped.
*
* @param dataMap the request body, changed in place
*/
static void translateOllamaParams(Map<String, Object> dataMap) {
Object options = dataMap.get("options");
Object think = dataMap.get("think");
removeOllamaParams(dataMap);
if (options instanceof Map<?, ?> optionMap) {
for (String option : SAMPLING_OPTIONS) {
Object value = optionMap.get(option);
if (value != null) {
dataMap.putIfAbsent(option, value);
}
}
// a negative num_predict means no limit, which is the SEMOSS default
if (optionMap.get("num_predict") instanceof Number numPredict && numPredict.longValue() > 0) {
dataMap.putIfAbsent("max_tokens", numPredict.longValue());
}
}
if (think instanceof Boolean enabled) {
dataMap.putIfAbsent("thinking", enabled);
} else if (think instanceof String level && !level.isBlank()) {
String value = level.trim().toLowerCase();
if ("true".equals(value) || "false".equals(value)) {
dataMap.putIfAbsent("thinking", Boolean.parseBoolean(value));
} else {
// Ollama names a thinking level in place of true
dataMap.putIfAbsent("thinking", true);
dataMap.putIfAbsent("effort", value);
}
}
}
/**
* Removes the Ollama-only request settings, which SEMOSS models do not take.
*
* @param dataMap the request body, changed in place
*/
private static void removeOllamaParams(Map<String, Object> dataMap) {
dataMap.remove("options");
dataMap.remove("think");
dataMap.remove("keep_alive");
}
}