|
|
@@ -233,7 +233,29 @@ export class LlmResponseStreamProcessor {
|
|
|
}
|
|
|
|
|
|
// Final notification - extract all messages from complete JSON
|
|
|
- let finalMessage = '';
|
|
|
+ const finalMessage = this.extractFinalMessage(rawBuffer);
|
|
|
+ this.options?.dataFinalizedCallback?.(finalMessage, this.replacements);
|
|
|
+ }
|
|
|
+ catch (e) {
|
|
|
+ logger.debug('Failed to parse final JSON response:', e);
|
|
|
+
|
|
|
+ // Send final notification even on error
|
|
|
+ const finalMessage = this.extractFinalMessage(rawBuffer);
|
|
|
+ this.options?.dataFinalizedCallback?.(finalMessage, this.replacements);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Extract final message from JSON or fallback to processed messages
|
|
|
+ * @param rawBuffer The raw JSON buffer to extract from
|
|
|
+ * @returns The final message string
|
|
|
+ */
|
|
|
+ private extractFinalMessage(rawBuffer: string): string {
|
|
|
+ let finalMessage = '';
|
|
|
+
|
|
|
+ try {
|
|
|
+ const repairedJson = jsonrepair(rawBuffer);
|
|
|
+ const parsedJson = JSON.parse(repairedJson);
|
|
|
|
|
|
// Extract all messages from the final complete JSON
|
|
|
if (parsedJson?.contents && Array.isArray(parsedJson.contents)) {
|
|
|
@@ -244,44 +266,17 @@ export class LlmResponseStreamProcessor {
|
|
|
|
|
|
finalMessage = messageContents;
|
|
|
}
|
|
|
-
|
|
|
- // Fallback to processedMessages if final extraction fails
|
|
|
- if (!finalMessage) {
|
|
|
- finalMessage = Array.from(this.processedMessages.values()).join('');
|
|
|
- }
|
|
|
-
|
|
|
- this.options?.dataFinalizedCallback?.(finalMessage, this.replacements);
|
|
|
}
|
|
|
- catch (e) {
|
|
|
- logger.debug('Failed to parse final JSON response:', e);
|
|
|
-
|
|
|
- // Send final notification even on error - extract from complete JSON if possible
|
|
|
- let finalMessage = '';
|
|
|
-
|
|
|
- try {
|
|
|
- const repairedJson = jsonrepair(rawBuffer);
|
|
|
- const parsedJson = JSON.parse(repairedJson);
|
|
|
-
|
|
|
- if (parsedJson?.contents && Array.isArray(parsedJson.contents)) {
|
|
|
- const messageContents = parsedJson.contents
|
|
|
- .filter(item => isMessageItem(item))
|
|
|
- .map(item => item.message)
|
|
|
- .join('');
|
|
|
-
|
|
|
- finalMessage = messageContents;
|
|
|
- }
|
|
|
- }
|
|
|
- catch (parseError) {
|
|
|
- // Ignore parse errors in catch block
|
|
|
- }
|
|
|
-
|
|
|
- // Fallback to processedMessages
|
|
|
- if (!finalMessage) {
|
|
|
- finalMessage = Array.from(this.processedMessages.values()).join('');
|
|
|
- }
|
|
|
+ catch (parseError) {
|
|
|
+ // Ignore parse errors and fallback
|
|
|
+ }
|
|
|
|
|
|
- this.options?.dataFinalizedCallback?.(finalMessage, this.replacements);
|
|
|
+ // Fallback to processedMessages if final extraction fails
|
|
|
+ if (!finalMessage) {
|
|
|
+ finalMessage = Array.from(this.processedMessages.values()).join('');
|
|
|
}
|
|
|
+
|
|
|
+ return finalMessage;
|
|
|
}
|
|
|
|
|
|
/**
|