Use parseMessage to convert a raw string from an LLM into an array of structured MessagePart objects. This function identifies three types of content based on specific XML-like tags:
- Text: Standard conversational text.
- Thought: Content wrapped in
<thinking> and </thinking> tags. - Artifact: Content wrapped in
<artifact> and </artifact> tags. The <artifact> tag can include attributes like identifier, type, title, and language.
When an <artifact> tag is encountered, the parser initializes generating: true. Once the closing </artifact> tag is found, generating is set to false.
import { parseMessage } from './lib/utils';
const rawMessage = `
Here is your code:
<artifact identifier="code-1" type="code" title="Example" language="typescript">
console.log("hello");
</artifact>
`;
const parts = parseMessage(rawMessage);
// parts will contain:
// [
// { type: 'text', data: 'Here is your code:' },
// { type: 'artifact', data: { id: 'code-1', type: 'code', title: 'Example', language: 'typescript', content: 'console.log("hello");', generating: false } }
// ]