Skip to content

Commit 73ff8dd

Browse files
JoshuaDivineBlessingBlessing Jones, Joshua DivineCopilotthemaherkhalil
authored
fix: only send google_interactions_replay_available to Vertex engines (#497)
* fix: only send google_interactions_replay_available to Vertex engines The flag was added to the request for every model on the OpenAI and Anthropic compatible endpoints. Non-Vertex engines (e.g. GPT) forward it to the provider, which rejects it and returns a masked 500 (empty stream when stream=true). Set it and run the Google Interactions sidecar only for Vertex engines, and skip preserveInteractions when the flag is absent. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix: resolving issues with tests --------- Co-authored-by: Blessing Jones, Joshua Divine <jblessingjones+deloitte@deloitte.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Maher Khalil <themaherkhalil@gmail.com>
1 parent e0c28ff commit 73ff8dd

4 files changed

Lines changed: 245 additions & 103 deletions

File tree

‎src/prerna/semoss/web/services/local/AnthropicEndpoints.java‎

Lines changed: 47 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,13 @@
6464
import prerna.auth.User;
6565
import prerna.auth.utils.SecurityEngineUtils;
6666
import prerna.engine.api.IModelEngine;
67+
import prerna.engine.api.ModelTypeEnum;
6768
import prerna.engine.impl.model.AbstractModelEngine;
6869
import prerna.engine.impl.model.ModelPixelInvoker;
6970
import prerna.engine.impl.model.Room;
7071
import prerna.engine.impl.model.RoomUtils;
71-
import prerna.engine.impl.model.message.GoogleInteractionsState;
7272
import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils;
73+
import prerna.engine.impl.model.message.GoogleInteractionsState;
7374
import prerna.engine.impl.model.responses.AskModelEngineResponse;
7475
import prerna.engine.impl.model.usage.ModelUsageLimitException;
7576
import prerna.om.Insight;
@@ -288,9 +289,16 @@ public Response createMessage(@Context HttpServletRequest request, @Context Http
288289
// can re-attach them to replayed tool_use blocks. Empty map for non-Vertex
289290
// paths (no file written) - no-op then.
290291
Map<String, String> thoughtSigMap = ThoughtSignatureSidecar.load(room.getRoomFolderPath());
291-
boolean interactionReplay = engine.keepInputOutput() && engine.keepsConversationHistory()
292+
// Google Interactions replay is a Vertex-only feature. Only set the flag and
293+
// run the sidecar for Vertex engines; any other engine must not get the
294+
// parameter, or it leaks to that provider's API through the compatibility
295+
// endpoint and the request is rejected.
296+
boolean isVertex = engine.getModelType() == ModelTypeEnum.VERTEX;
297+
boolean interactionReplay = isVertex && engine.keepInputOutput() && engine.keepsConversationHistory()
292298
&& !"false".equalsIgnoreCase(String.valueOf(dataMap.get("use_history")));
293-
dataMap.put("google_interactions_replay_available", interactionReplay);
299+
if (isVertex) {
300+
dataMap.put("google_interactions_replay_available", interactionReplay);
301+
}
294302

295303
// HANDLE NON-STREAMING REQUESTS THROUGH THE LLM PIXEL
296304
if (!isStreamingRequest) {
@@ -472,15 +480,20 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
472480
Map<String, Object> streamData = (Map<String, Object>) streamObj.get("data");
473481
if (GoogleInteractionsState.KEY.equals(streamType)) {
474482
try {
475-
if (!Boolean.TRUE.equals(FINAL_DATAMAP.get("google_interactions_replay_available"))) {
476-
throw new IOException("Room retention settings prevent preserving replay");
483+
if (!Boolean.TRUE.equals(
484+
FINAL_DATAMAP.get("google_interactions_replay_available"))) {
485+
throw new IOException(
486+
"Room retention settings prevent preserving replay");
477487
}
478-
ThoughtSignatureSidecar.appendInteraction(FINAL_ROOM.getRoomFolderPath(),
479-
(List<Map<String, Object>>) FINAL_DATAMAP.get(AbstractModelEngine.FULL_PROMPT),
488+
ThoughtSignatureSidecar.appendInteraction(
489+
FINAL_ROOM.getRoomFolderPath(),
490+
(List<Map<String, Object>>) FINAL_DATAMAP
491+
.get(AbstractModelEngine.FULL_PROMPT),
480492
(Map<String, Object>) streamData.get("assistant"),
481493
streamData.get(GoogleInteractionsState.KEY));
482494
} catch (IOException | IllegalArgumentException e) {
483-
AnthropicMessagesHelper.writeErrorEvent("api_error", "Unable to preserve Google Interactions history", writer);
495+
AnthropicMessagesHelper.writeErrorEvent("api_error",
496+
"Unable to preserve Google Interactions history", writer);
484497
break STREAM_COMPLETE_LOOP;
485498
}
486499
continue;
@@ -512,7 +525,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
512525
// Thinking must lead the message at index 0. If a text or tool
513526
// block already opened we cannot insert it before them, so drop
514527
// the chunk rather than corrupt content-block ordering.
515-
if (thinkingChunk != null && !thinkingChunk.isEmpty() && !thinkingBlockClosed
528+
if (thinkingChunk != null && !thinkingChunk.isEmpty()
529+
&& !thinkingBlockClosed
516530
&& (thinkingBlockStarted || nextBlockIndex == 0)) {
517531
if (!thinkingBlockStarted) {
518532
AnthropicMessagesHelper.writeThinkingContentBlockStart(0, writer);
@@ -529,7 +543,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
529543
String finishReason = (String) streamData.get("finish_reason");
530544

531545
if (textBlockIndex != null) {
532-
AnthropicMessagesHelper.writeContentBlockStop(textBlockIndex, writer);
546+
AnthropicMessagesHelper.writeContentBlockStop(textBlockIndex,
547+
writer);
533548
textBlockIndex = null;
534549
}
535550
for (Integer blockIndex : toolBlockIndexes.values()) {
@@ -561,18 +576,21 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
561576
elapsed, asyncJobId);
562577
}
563578
textBlockIndex = nextBlockIndex++;
564-
AnthropicMessagesHelper.writeTextContentBlockStart(textBlockIndex, writer);
579+
AnthropicMessagesHelper
580+
.writeTextContentBlockStart(textBlockIndex, writer);
565581
textStreamed = true;
566582
}
567-
AnthropicMessagesHelper.writeTextDelta(textBlockIndex, newContent, writer);
583+
AnthropicMessagesHelper.writeTextDelta(textBlockIndex, newContent,
584+
writer);
568585
}
569586
}
570587
} else if ("tool".equalsIgnoreCase(streamType)) {
571588
if (streamData.containsKey("finish_reason")) {
572589
String finishReason = (String) streamData.get("finish_reason");
573590

574591
if (textBlockIndex != null) {
575-
AnthropicMessagesHelper.writeContentBlockStop(textBlockIndex, writer);
592+
AnthropicMessagesHelper.writeContentBlockStop(textBlockIndex,
593+
writer);
576594
textBlockIndex = null;
577595
}
578596
for (Integer blockIndex : toolBlockIndexes.values()) {
@@ -604,9 +622,10 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
604622
AnthropicMessagesHelper.writeMessageStop(writer);
605623
break STREAM_COMPLETE_LOOP;
606624
} else {
607-
Integer toolIndex = streamData.get("index") instanceof Number upstreamIndex
608-
? upstreamIndex.intValue()
609-
: 0;
625+
Integer toolIndex = streamData
626+
.get("index") instanceof Number upstreamIndex
627+
? upstreamIndex.intValue()
628+
: 0;
610629

611630
if (streamData.containsKey("id")) {
612631
pendingToolIds.put(toolIndex, (String) streamData.get("id"));
@@ -648,7 +667,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
648667
// clients key content by index, so the open text block is closed
649668
// and the tool takes the next free index
650669
if (textBlockIndex != null) {
651-
AnthropicMessagesHelper.writeContentBlockStop(textBlockIndex, writer);
670+
AnthropicMessagesHelper.writeContentBlockStop(textBlockIndex,
671+
writer);
652672
textBlockIndex = null;
653673
}
654674
int blockIndex = nextBlockIndex++;
@@ -661,14 +681,15 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
661681
AnthropicMessagesHelper.writeInputJsonDelta(blockIndex,
662682
accumulatedArgs.toString(), writer);
663683
}
664-
} else if (toolBlockIndexes.containsKey(toolIndex) && functionMap != null
684+
} else if (toolBlockIndexes.containsKey(toolIndex)
685+
&& functionMap != null
665686
&& functionMap.containsKey("arguments")) {
666687
Object argsObj = functionMap.get("arguments");
667688
String argsChunk = argsObj instanceof String ? (String) argsObj
668689
: GSON.toJson(argsObj);
669690
if (argsChunk != null && !argsChunk.isEmpty()) {
670-
AnthropicMessagesHelper.writeInputJsonDelta(toolBlockIndexes.get(toolIndex),
671-
argsChunk, writer);
691+
AnthropicMessagesHelper.writeInputJsonDelta(
692+
toolBlockIndexes.get(toolIndex), argsChunk, writer);
672693

673694
}
674695
}
@@ -750,9 +771,10 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
750771
}
751772

752773
int blockIndex = nextBlockIndex++;
753-
AnthropicMessagesHelper.writeToolUseContentBlockStart(blockIndex, toolId,
754-
toolName, writer);
755-
AnthropicMessagesHelper.writeInputJsonDelta(blockIndex, argsJson, writer);
774+
AnthropicMessagesHelper.writeToolUseContentBlockStart(blockIndex,
775+
toolId, toolName, writer);
776+
AnthropicMessagesHelper.writeInputJsonDelta(blockIndex, argsJson,
777+
writer);
756778
AnthropicMessagesHelper.writeContentBlockStop(blockIndex, writer);
757779

758780
Object sig = toolResp.get("thought_signature");
@@ -799,7 +821,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
799821

800822
String failure = ModelPixelExecutor.streamFailureMessage(jobStatus);
801823
if (failure != null) {
802-
classLogger.warn("Anthropic stream for engine '{}' job '{}' ended with job status {}",
824+
classLogger.warn(
825+
"Anthropic stream for engine '{}' job '{}' ended with job status {}",
803826
FINAL_ENGINE_ID, asyncJobId, jobStatus);
804827
AnthropicMessagesHelper.writeErrorEvent("api_error", failure, writer);
805828
break STREAM_COMPLETE_LOOP;

‎src/prerna/semoss/web/services/local/OpenAIEndpoints.java‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
import prerna.auth.User;
6969
import prerna.auth.utils.SecurityEngineUtils;
7070
import prerna.engine.api.IModelEngine;
71+
import prerna.engine.api.ModelTypeEnum;
7172
import prerna.engine.impl.model.AbstractModelEngine;
7273
import prerna.engine.impl.model.ModelPixelInvoker;
7374
import prerna.engine.impl.model.Room;
@@ -276,7 +277,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
276277
dataMap, SESSION_ID);
277278
new OpenAIChatCompletionsStream(engineId, messageId, creationTimestamp, jobId) {
278279
@Override
279-
protected boolean writeChunk(Map<String, Object> chunk, Writer sink) throws IOException {
280+
protected boolean writeChunk(Map<String, Object> chunk, Writer sink)
281+
throws IOException {
280282
return preserveInteractionsChunk(FINAL_ROOM, dataMap, chunk) ? false
281283
: super.writeChunk(chunk, sink);
282284
}
@@ -447,18 +449,25 @@ private static List<Map<String, Object>> restoreInteractions(IModelEngine engine
447449
message.remove(GoogleInteractionsState.KEY);
448450
messages.add(message);
449451
}
450-
boolean replay = engine.keepInputOutput() && engine.keepsConversationHistory()
452+
// Google Interactions replay is a Vertex-only feature. Only set the flag and
453+
// run the sidecar for Vertex engines; any other engine (OpenAI, Anthropic, ...)
454+
// must not get the parameter, or it leaks to that provider's API through the
455+
// OpenAI-compatibility endpoint and the request is rejected.
456+
boolean isVertex = engine.getModelType() == ModelTypeEnum.VERTEX;
457+
boolean replay = isVertex && engine.keepInputOutput() && engine.keepsConversationHistory()
451458
&& !"false".equalsIgnoreCase(String.valueOf(parameters.get("use_history")));
452-
parameters.put("google_interactions_replay_available", replay);
459+
if (isVertex) {
460+
parameters.put("google_interactions_replay_available", replay);
461+
}
453462
if (replay) {
454463
ThoughtSignatureSidecar.restoreInteractions(room.getRoomFolderPath(), messages);
455464
}
456465
return messages;
457466
}
458467

459468
@SuppressWarnings("unchecked")
460-
private static void preserveInteractions(Room room, Map<String, Object> parameters,
461-
AskModelEngineResponse response) throws IOException {
469+
private static void preserveInteractions(Room room, Map<String, Object> parameters, AskModelEngineResponse response)
470+
throws IOException {
462471
Object state = response.getMetadata() == null ? null : response.getMetadata().get(GoogleInteractionsState.KEY);
463472
if (state == null) {
464473
return;
@@ -469,8 +478,14 @@ private static void preserveInteractions(Room room, Map<String, Object> paramete
469478
}
470479

471480
@SuppressWarnings("unchecked")
472-
private static void preserveInteractions(Room room, Map<String, Object> parameters,
473-
Map<String, Object> assistant, Object state) throws IOException {
481+
private static void preserveInteractions(Room room, Map<String, Object> parameters, Map<String, Object> assistant,
482+
Object state) throws IOException {
483+
// Non-Vertex engines never carry this flag (restoreInteractions only sets it
484+
// for
485+
// Vertex), so there is nothing to preserve: skip cleanly rather than error.
486+
if (!parameters.containsKey("google_interactions_replay_available")) {
487+
return;
488+
}
474489
if (!Boolean.TRUE.equals(parameters.get("google_interactions_replay_available"))) {
475490
throw new IOException("Room retention settings prevent preserving Google Interactions history");
476491
}
@@ -530,7 +545,8 @@ public void write(OutputStream output) throws IOException, WebApplicationExcepti
530545
FINAL_DATA_MAP, FINAL_SESSION_ID);
531546
new OpenAIResponsesStream(FINAL_ENGINE_ID, responseId, creationTimestamp, jobId) {
532547
@Override
533-
protected boolean writeChunk(Map<String, Object> chunk, Writer sink) throws IOException {
548+
protected boolean writeChunk(Map<String, Object> chunk, Writer sink)
549+
throws IOException {
534550
return preserveInteractionsChunk(FINAL_ROOM, FINAL_DATA_MAP, chunk) ? false
535551
: super.writeChunk(chunk, sink);
536552
}

0 commit comments

Comments
 (0)