-
Notifications
You must be signed in to change notification settings - Fork 414
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
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThe pull request introduces a chat history feature in the chat application. A new Changes
Poem
Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 historyThe unbounded array could consume excessive memory in long chat sessions.
Consider:
- Adding a maximum history size limit
- Implementing a cleanup mechanism
- 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 functionalityThe 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.`); }); }
data.forEach((message) => { | ||
const formattedMessage = `${"Agent"}: ${message.text}`; | ||
console.log(formattedMessage); | ||
chatHistory.push(formattedMessage); | ||
}); |
There was a problem hiding this comment.
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.
if (input.toLocaleLowerCase() === "history") { | ||
showChatHistory(); | ||
chat(); | ||
return; | ||
} | ||
|
||
chatHistory.push(`You: ${input}`); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Improve command handling robustness
The current implementation has reliability concerns.
Apply these improvements:
- Fix case sensitivity
- Add command prefix
- 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.
consider using a local file for this? and call it logs? |
@coderabbitai suggest changes for this
|
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:
🔗 Analysis chain🏁 Scripts executedThe following scripts were executed for the analysis: Script:
Length of output: 1783 |
Summary by CodeRabbit