Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added chat history #95

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

gusthawojunkes
Copy link

@gusthawojunkes gusthawojunkes commented Jan 18, 2025

Summary by CodeRabbit

  • New Features
    • Added chat history tracking functionality
    • Implemented ability to view chat history during conversation by typing "history" command

Copy link

coderabbitai bot commented Jan 18, 2025

Walkthrough

The pull request introduces a chat history feature in the chat application. A new chatHistory array is implemented to store and track messages during a conversation. Users can now retrieve their chat history by typing the "history" command, which triggers the showChatHistory function to display all previously exchanged messages with their corresponding indices.

Changes

File Change Summary
src/chat/index.ts - Added chatHistory array to store messages
- Implemented showChatHistory() function
- Modified handleUserInput to record messages

Poem

🤖 Memories of chats now preserved with care,
Lines of dialog floating in digital air,
A history command, a magical key,
Unlocking conversations, setting memories free!
Chat on, brave user, your words take flight! 📜✨

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/chat/index.ts (2)

14-14: Add memory management for chat history

The unbounded array could consume excessive memory in long chat sessions.

Consider:

  1. Adding a maximum history size limit
  2. Implementing a cleanup mechanism
  3. Using a circular buffer data structure
-const chatHistory: string[] = [];
+const MAX_HISTORY = 1000;
+const chatHistory: string[] = [];
+
+function addToChatHistory(message: string) {
+    if (chatHistory.length >= MAX_HISTORY) {
+        chatHistory.shift();
+    }
+    chatHistory.push(message);
+}

70-75: Enhance history display functionality

The current display lacks user-friendly features.

Add pagination and formatting:

 export function showChatHistory() {
+  const PAGE_SIZE = 10;
+  const pages = Math.ceil(chatHistory.length / PAGE_SIZE);
+  
   console.log('Chat History:');
-  chatHistory.forEach((message, index) => {
-    console.log(`${index + 1}: ${message}`);
+  for (let i = 0; i < PAGE_SIZE && i < chatHistory.length; i++) {
+    const msg = chatHistory[i];
+    console.log(`${i + 1}: [${new Date(msg.timestamp).toLocaleTimeString()}] ${msg.sender}: ${msg.text}`);
+  }
+  if (pages > 1) {
+    console.log(`\nShowing 1/${pages} pages. Use '/history <page>' to view more.`);
   });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdd0c18 and d69844c.

📒 Files selected for processing (1)
  • src/chat/index.ts (4 hunks)

Comment on lines +39 to +43
data.forEach((message) => {
const formattedMessage = `${"Agent"}: ${message.text}`;
console.log(formattedMessage);
chatHistory.push(formattedMessage);
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve message structure and consistency

Messages lack metadata and consistent formatting.

Implement a structured message format:

-      const formattedMessage = `${"Agent"}: ${message.text}`;
-      console.log(formattedMessage);
-      chatHistory.push(formattedMessage);
+      const historyEntry = {
+        timestamp: new Date().toISOString(),
+        sender: "Agent",
+        text: message.text
+      };
+      console.log(`${historyEntry.sender}: ${historyEntry.text}`);
+      chatHistory.push(historyEntry);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +53 to +59
if (input.toLocaleLowerCase() === "history") {
showChatHistory();
chat();
return;
}

chatHistory.push(`You: ${input}`);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve command handling robustness

The current implementation has reliability concerns.

Apply these improvements:

  1. Fix case sensitivity
  2. Add command prefix
  3. Handle async flow properly
-      if (input.toLocaleLowerCase() === "history") {
+      const normalizedInput = input.trim().toLowerCase();
+      if (normalizedInput === "/history") {
+        await showChatHistory();
         chat();
         return;
       }
       
-      chatHistory.push(`You: ${input}`);
+      addToChatHistory({
+        timestamp: new Date().toISOString(),
+        sender: "You",
+        text: input
+      });

Committable suggestion skipped: line range outside the PR's diff.

@wtfsayo
Copy link
Member

wtfsayo commented Jan 20, 2025

consider using a local file for this? and call it logs?

@wtfsayo
Copy link
Member

wtfsayo commented Jan 20, 2025

@coderabbitai suggest changes for this

consider using a local file for this? and call it logs?

Copy link

coderabbitai bot commented Jan 20, 2025

Tip

For best results, initiate chat on the files or code changes.

@wtfsayo Here's a suggested implementation that uses a local file for storing chat logs:

import { settings } from "@elizaos/core";
import readline from "readline";
import { promises as fs } from 'fs';
import path from 'path';

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("SIGINT", () => {
  rl.close();
  process.exit(0);
});

const LOGS_FILE = path.join(process.cwd(), 'chat-logs.txt');

// Initialize logs file if it doesn't exist
async function initLogs() {
  try {
    await fs.access(LOGS_FILE);
  } catch {
    await fs.writeFile(LOGS_FILE, '');
  }
}

async function appendToLogs(message: string) {
  await fs.appendFile(LOGS_FILE, message + '\n');
}

async function readLogs(): Promise<string[]> {
  try {
    const content = await fs.readFile(LOGS_FILE, 'utf-8');
    return content.split('\n').filter(line => line.trim());
  } catch {
    return [];
  }
}

async function handleUserInput(input: string, agentId: string) {
  if (input.toLowerCase() === "exit") {
    rl.close();
    process.exit(0);
  }

  try {
    const serverPort = parseInt(settings.SERVER_PORT || "3000");

    const response = await fetch(
      `http://localhost:${serverPort}/${agentId}/message`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          text: input,
          userId: "user",
          userName: "User",
        }),
      }
    );

    const data = await response.json();
    for (const message of data) {
      const formattedMessage = `Agent: ${message.text}`;
      console.log(formattedMessage);
      await appendToLogs(formattedMessage);
    }
  } catch (error) {
    console.error("Error fetching response:", error);
  }
}

export function startChat(characters) {
  async function chat() {
    await initLogs();
    const agentId = characters[0].name ?? "Agent";
    
    rl.question("You: ", async (input) => {
      if (input.toLocaleLowerCase() === "history") {
        await showChatHistory();
        chat();
        return;
      }
      
      await appendToLogs(`You: ${input}`);
      await handleUserInput(input, agentId);
      if (input.toLowerCase() !== "exit") {
        chat(); // Loop back to ask another question
      }
    });
  }

  return chat;
}

export async function showChatHistory() {
  console.log('Chat History:');
  const messages = await readLogs();
  messages.forEach((message, index) => {
    console.log(`${index + 1}: ${message}`);
  });
}

Key changes:

  1. Added file operations using fs/promises
  2. Created functions to manage logs: initLogs, appendToLogs, readLogs
  3. Messages are now stored in 'chat-logs.txt' in the current working directory
  4. Converted relevant functions to async to handle file operations
  5. Maintained the same message format and numbering in history
🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Get the content of the chat implementation file
cat src/chat/index.ts

Length of output: 1783

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants