cc-api / response_formatter.py
Severian's picture
Update response_formatter.py
a7a635b verified
raw
history blame
4.36 kB
export class LogicController {
constructor() {
this.storage = {
xmlBuffer: '',
isFirstMessage: true,
toolOutputs: new Map()
};
this.eventDispatcher = new EventTarget();
}
processStreamData(chunk) {
try {
const rawData = chunk.data || chunk;
console.log('Raw chunk received:', rawData);
if (typeof rawData === 'string' && rawData.includes('<agent_response>')) {
this.storage.xmlBuffer += rawData;
// Process complete messages
while (this.storage.xmlBuffer.includes('<agent_response>')) {
const startTag = '<agent_response>';
const endTag = '</agent_response>';
const startIndex = this.storage.xmlBuffer.indexOf(startTag);
const endIndex = this.storage.xmlBuffer.indexOf(endTag);
if (startIndex === -1 || endIndex === -1) break;
// Extract complete message
const completeMessage = this.storage.xmlBuffer.slice(
startIndex,
endIndex + endTag.length
);
// Process message content
this.processMessage(completeMessage);
// Remove processed message
this.storage.xmlBuffer = this.storage.xmlBuffer.slice(
endIndex + endTag.length
);
}
}
} catch (error) {
console.error('Error processing stream data:', error);
}
}
processMessage(xmlMessage) {
try {
// Parse message content
const messageMatch = xmlMessage.match(/<message>(.*?)<\/message>/s);
const thoughtMatch = xmlMessage.match(/<thought>(.*?)<\/thought>/s);
const toolOutputsMatch = xmlMessage.match(/<tool_outputs>(.*?)<\/tool_outputs>/s);
// Handle regular message
if (messageMatch?.[1]) {
this.dispatchUpdate('chatwindow', {
message: messageMatch[1].trim(),
replace: false,
format: true
});
}
// Handle thought content
if (thoughtMatch?.[1]) {
this.dispatchUpdate('chatwindow', {
message: thoughtMatch[1].trim(),
replace: false,
format: true,
isThought: true
});
}
// Handle tool outputs
if (toolOutputsMatch?.[1]) {
this.processToolOutputs(toolOutputsMatch[1]);
}
} catch (error) {
console.error('Error processing message:', error);
}
}
processToolOutputs(toolOutputsXml) {
try {
const parser = new DOMParser();
const doc = parser.parseFromString(toolOutputsXml, 'text/xml');
const outputs = doc.getElementsByTagName('tool_output');
Array.from(outputs).forEach(output => {
const type = output.getAttribute('type');
const content = output.textContent;
// Store tool output
const outputId = `${type}-${Date.now()}`;
this.storage.toolOutputs.set(outputId, {
type,
content,
timestamp: Date.now()
});
// Dispatch tool-specific update
this.dispatchUpdate('maincontent', {
observationWidget: {
id: outputId,
type,
tool: type,
observation: content
}
});
});
} catch (error) {
console.error('Error processing tool outputs:', error);
}
}
dispatchUpdate(component, data) {
console.log('Dispatching update:', component, data);
const event = new CustomEvent('componentUpdate', {
detail: { component, data }
});
this.eventDispatcher.dispatchEvent(event);
}
}