2024-07-10 16:44:39 +00:00
|
|
|
import type { Message } from 'ai';
|
|
|
|
import { useCallback, useState } from 'react';
|
2024-07-17 18:54:46 +00:00
|
|
|
import { createScopedLogger } from '../../utils/logger';
|
|
|
|
import { StreamingMessageParser } from '../runtime/message-parser';
|
|
|
|
import { workbenchStore } from '../stores/workbench';
|
2024-07-10 16:44:39 +00:00
|
|
|
|
|
|
|
const logger = createScopedLogger('useMessageParser');
|
|
|
|
|
|
|
|
const messageParser = new StreamingMessageParser({
|
|
|
|
callbacks: {
|
2024-07-17 18:54:46 +00:00
|
|
|
onArtifactOpen: (data) => {
|
|
|
|
logger.trace('onArtifactOpen', data);
|
|
|
|
|
|
|
|
workbenchStore.showWorkbench.set(true);
|
|
|
|
workbenchStore.addArtifact(data);
|
2024-07-10 16:44:39 +00:00
|
|
|
},
|
2024-07-17 18:54:46 +00:00
|
|
|
onArtifactClose: (data) => {
|
|
|
|
logger.trace('onArtifactClose');
|
|
|
|
|
|
|
|
workbenchStore.updateArtifact(data, { closed: true });
|
2024-07-10 16:44:39 +00:00
|
|
|
},
|
2024-07-17 18:54:46 +00:00
|
|
|
onAction: (data) => {
|
2024-07-17 19:31:47 +00:00
|
|
|
logger.debug('onAction', data);
|
2024-07-17 18:54:46 +00:00
|
|
|
|
|
|
|
workbenchStore.runAction(data);
|
2024-07-10 16:44:39 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
export function useMessageParser() {
|
|
|
|
const [parsedMessages, setParsedMessages] = useState<{ [key: number]: string }>({});
|
|
|
|
|
|
|
|
const parseMessages = useCallback((messages: Message[], isLoading: boolean) => {
|
|
|
|
let reset = false;
|
|
|
|
|
|
|
|
if (import.meta.env.DEV && !isLoading) {
|
|
|
|
reset = true;
|
|
|
|
messageParser.reset();
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const [index, message] of messages.entries()) {
|
|
|
|
if (message.role === 'assistant') {
|
|
|
|
/**
|
|
|
|
* In production, we only parse the last assistant message since previous messages can't change.
|
|
|
|
* During development they can change, e.g., if the parser gets modified.
|
|
|
|
*/
|
|
|
|
if (import.meta.env.PROD && index < messages.length - 1) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
const newParsedContent = messageParser.parse(message.id, message.content);
|
|
|
|
|
|
|
|
setParsedMessages((prevParsed) => ({
|
|
|
|
...prevParsed,
|
|
|
|
[index]: !reset ? (prevParsed[index] || '') + newParsedContent : newParsedContent,
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return { parsedMessages, parseMessages };
|
|
|
|
}
|