handleBotResponse()

in ChatbotUI/src/app/components/main/chat/chatbar/chatbar.component.ts [317:384]


  handleBotResponse(answer: string) {
    let events: string[] = answer.split("\n");

    // Filter out empty strings that might result from extra newlines.
    events = events.filter(event => event.trim() !== "");

    if (events.length === 0) {
        return; // Nothing to process
    }
    
    try {
        let parsedEvent = JSON.parse(events[0]);
        let answerId = parsedEvent.agent.messages[0].kwargs.id; // Access the "id" from the kwargs

        if (answerId === this.conversation[0].chat_id) {
            // Process the *last* event.  Use .at(-1) for clarity and safety.
            const lastEventString = events.at(-1);
            if (!lastEventString) {
                console.warn("No last event found after splitting.");
                return; // Or handle the error appropriately
            }

            const lastEventParsed = JSON.parse(lastEventString);
            const lastMessage = lastEventParsed.agent.messages.at(-1);

            if (lastMessage && lastMessage.kwargs.type === "ai") {
                this.conversation[0].botAnswer += this.removeUnpairedTripleBackticks(lastMessage.kwargs.content);
            }
            return;
        }

        let response: Chat = {
          id: answerId,
          question: this.chatQuery,
          answer: "",
          suggested_questions: []
        }
        
        let endTime = new Date().getTime();
        this.assignId(response?.id);
    
        let singleMesage: Message = {
          body: "",
          botAnswer: response.answer,
          type: 'bot',
          responseTime: ((endTime - this.botStartTime) / 1000).toString(),
          shareable: true,
          botStartTime: this.botStartTime.toString(),
          extras: {
            like: false,
            dislike: false,
            delete: false,
          },
          chat_id: response.id!
        };
    
        this.conversation.unshift(singleMesage);
        this.setSuggestedQuestionInChat(response, endTime);
        this.showLoader = false;
        this.clearTimeoutForLoaderText();
        this.isSuggestedQuestion = '';

    } catch (error) {
        console.error("Error parsing JSON:", error);
        console.error("Problematic event data:", answer); // Log the raw event data
        // Consider adding error handling here, such as retrying or logging.
    }
  }