Skip to content
TheChatArchiveThe Chat Archive
gpt-4-turbo-2024-04-09· OpenAIAi2 WildChat-4.8M (AI2)

User Create a JavaScript function for parsing last message from "assistant" in example…

  1. User

    User Create a JavaScript function for parsing last message from "assistant" in example JSON data: { generated_text: '<|system|>\n' + 'You are a friendly assistant named Tom!\n' + '<|assistant|>\n' + 'Hi, my name is Tom how may I help you!\n' + '<|user|>\n' + 'Hey! Can you introduce yourself to my friend .\n' + '<|assistant|>\n' + 'Sure, my name is Fred. How have you been?' } ]

  2. Assistant

    To create a JavaScript function that parses the last message from the "assistant" in the provided JSON data, you can follow these steps using regular expressions and string manipulation. Here's a simple function that will accomplish this task:

    function parseLastAssistantMessage(data) {
        // Extract the 'generated_text' property
        const text = data.generated_text;
    
        // Split the text based on the `<|assistant|>` and `<|user|>` tags
        const entries = text.split(/<\|user\|>|<\|assistant\|>/);
    
        // Iterate through the entries backwards and find the last message from the assistant
        for (let i = entries.length - 1; i >= 0; i--) {
            const entry = entries[i].trim(); // Trim to remove any surrounding whitespace
            if (entry && i % 2 === 1) { // Check if the entry is assistant's (odd index after split)
                return entry;
            }
        }
        
        // Return null if no message from the assistant is found
        return null;
    }
    
    // Example JSON data
    const jsonData = {
        generated_text: '<|system|>\n' +
          'You are a friendly assistant named Tom!\n' +
          '<|assistant|>\n' +
          'Hi, my name is Tom how may I help you!\n' +
          '<|user|>\n' +
          'Hey! Can you introduce yourself to my friend .\n' +
          '<|assistant|>\n' +
          'Sure, my name is Fred. How have you been?'
    };
    
    // Example usage
    console.log(parseLastAssistantMessage(jsonData));
    

    This code snippet defines a parseLastAssistantMessage function that when provided with specific JSON data:

    1. Extracts the generated_text string.
    2. Splits the string into chunks based on where <|assistant|> or <|user|> tags appear.
    3. Iterates backward through these chunks to find the last chunk of text that was proclaimed by the assistant.
    4. Treats chunks with even indices (starting from 0) as from system/assistant settings or user, and odd indices as from the assistant.
    5. Removes any whitespace surrounding the message using trim() and returns the most recent assistant message, or null if no assistant message is found.

    An example JSON data structure is given and the function is tested with a console.log() statement to display the last message from the assistant.