I want to add an AI renaming feature to my AI assistant… · The Chat Archive
Explore o1-mini-2024-09-12 · OpenAI WildChat-4.8M (AI2)I want to add an AI renaming feature to my AI assistant interface website. When… Save Share Download ▾ ReportUser: I want to add an AI renaming feature to my AI assistant interface website. When the user clicks on the existing rename button, instead of being prompted to enter a name, a request will be sent to the existing AI model to summarise the chat in 5 words. Then, this will become the new name of the chat, all in the background. It should use the predefined model in the backend, and not any user models, to make sure it doesn't cost money for the user.// src/components/ChatInterface.js
import React, { useState, useContext, useRef, useEffect, useCallback } from "react";
import { ChatContext } from "../context/ChatContext";
import Message from "./Message";
import CodeModal from "./CodeModal";
import InlineCodeEditor from "./InlineCodeEditor";
import { escapeHtml } from "../utils/escapeHtml";
function ChatInterface() {
const {
chats,
currentChatId,
addMessage,
updateChat,
selectedModelId,
models,
} = useContext(ChatContext);
const currentChat = chats.find((chat) => chat.id === currentChatId);
const [message, setMessage] = useState("");
const [isTyping, setIsTyping] = useState(false);
const messagesEndRef = useRef(null);
const [isCodeModalOpen, setIsCodeModalOpen] = useState(false);
const [currentEditingCode, setCurrentEditingCode] = useState(null);
const [isSystemPromptOpen, setIsSystemPromptOpen] = useState(false);
const addCodeAttachment = ({ codeContent, fileName, notes }) => {
const escapedCode = escapeHtml(codeContent);
const escapedFileName = escapeHtml(fileName || "untitled");
const escapedNotes = escapeHtml(notes || "");
const codeTag = <code fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCode}</code>;
setMessage((prev) => prev + codeTag);
};
const handleAttachCode = useCallback((codeSegment = null) => {
setCurrentEditingCode(codeSegment);
setIsCodeModalOpen(true);
}, []);
const handleCodeSave = (updatedCode) => {
if (currentEditingCode) {
// Update existing code
const escapedCode = escapeHtml(updatedCode.codeContent);
const escapedFileName = escapeHtml(updatedCode.fileName || "untitled");
const escapedNotes = escapeHtml(updatedCode.notes || "");
// Improved regex to handle multi-line and special characters
const regex = new RegExp(
`<code\\s+fileName="${currentEditingCode.fileName}"\\s+notes="${currentEditingCode.notes}">([\\s\\S]*?)<\\/code>`
);
const updatedMessage = message.replace(
regex,
`<code fileName="${escapedFileName}" notes="${escapedNotes}">${escapedCode}</code>`
);
setMessage(updatedMessage);
} else {
// Add new code
addCodeAttachment(updatedCode);
}
setIsCodeModalOpen(false);
setCurrentEditingCode(null);
};
const handleSend = useCallback(async () => {
if (!message.trim() || !currentChatId || !selectedModelId) return;
// Retrieve the system prompt from the current chat
const systemPrompt = currentChat.systemPrompt || "";
// Combine the system prompt with the user message
// Ensure there's a separator (like a newline) for clarity
const fullMessage = systemPrompt ? `${systemPrompt}\n${message}` : message;
const userMessage = { sender: "user", text: message };
addMessage(currentChatId, userMessage);
setMessage("");
scrollToBottom();
// Set typing indicator
setIsTyping(true);
try {
const response = await fetch("http://localhost:8000/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
session_id: currentChatId,
text: fullMessage,
model_id: selectedModelId, // Ensure this is correctly set
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(
errorData.detail || "Failed to get response from the server."
);
}
const data = await response.json();
const responseText = data.response;
const responseModelId = data.model_id; // Extract model_id from response
const botMessage = {
sender: "bot",
text: responseText,
model_id: responseModelId, // Include model_id
};
addMessage(currentChatId, botMessage);
scrollToBottom();
} catch (error) {
console.error("Error:", error);
const errorMessage = {
sender: "bot",
text: "Sorry, something went wrong. Please try again.",
};
addMessage(currentChatId, errorMessage);
scrollToBottom();
} finally {
// Remove typing indicator
setIsTyping(false);
}
Assistant2024-09-25 10:27 UTC Copy response
Copy first prompt
Details
Model o1-mini-2024-09-12
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Sep 25, 2024
Added to archive Nov 16, 2026
ID 01m7h41vyd919gnd4e0360dsqpSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 953e84f174b8aa206a53b774018b5e4b
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
const handleKeyDown = useCallback(
(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
},
[handleSend]
);
const handleEditorKeyDown = useCallback((e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}, [handleSend]);
const scrollToBottom = useCallback(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, []);
if (!currentChat) {
return (
<div className="flex-1 p-4">No active chat. Please start a new chat.</div>
);
}
const handleSystemPromptChange = (e) => {
const newPrompt = e.target.value;
updateChat(currentChatId, { systemPrompt: newPrompt });
};
const toggleSystemPrompt = () => {
setIsSystemPromptOpen(!isSystemPromptOpen);
};
return (
<div className="flex flex-col h-screen">
<div className="flex-1 p-32 pt-8 pb-8 overflow-y-auto bg-[#eeeeee] dark:bg-[#161618]">
{/* Removed Model Selector Dropdown */}
{/* Chat Messages */}
{currentChat.messages.map((msg, index) => (
<Message
key={index}
chatId={currentChatId}
messageIndex={index}
sender={msg.sender}
text={msg.text}
model_id={msg.model_id} // Pass model_id
/>
))}
{isTyping && (
<div className="mb-4 flex justify-start">
<div className="max-w-xs md:max-w-md lg:max-w-lg p-3 rounded-lg bg-gray-200 dark:bg-gray-800 text-gray-800 dark:text-gray-200 flex items-center">
<div className="flex space-x-1 mr-2">
<div className="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-0"></div>
<div className="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-200"></div>
<div className="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-400"></div>
</div>
<span className="text-sm">Echo is typing...</span>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
<div
id="message_area"
className="p-4 border-t dark:border-gray-700 bg-white dark:bg-[#161618]"
>
<button
onClick={toggleSystemPrompt}
className="mb-2 text-sm text-blue-500 hover:underline focus:outline-none"
>
{isSystemPromptOpen ? "Hide System Prompt" : "Show System Prompt"}
</button>
{isSystemPromptOpen && (
<textarea
className="w-full p-2 border rounded-lg resize-none dark:bg-gray-800 dark:text-gray-200 mb-2"
rows="3"
placeholder="Enter system prompt..."
value={currentChat.systemPrompt}
onChange={handleSystemPromptChange}
/>
)}
<div className="flex flex-row">
<div className="flex-grow">
<InlineCodeEditor
value={message}
onChange={setMessage}
onAttachCode={handleAttachCode}
onKeyDown={handleEditorKeyDown}
/>
</div>
<div className="flex flex-col flex-shrink-0 items-start pl-4 space-y-2">
<button
onClick={() => setIsCodeModalOpen(true)}
className="bg-blue-500 text-white px-3 py-2 rounded-lg hover:bg-blue-600 flex-grow w-full"
>
Attach Code
</button>
<button
className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 flex-grow mt-2 w-full"
onClick={handleSend}
>
Send
</button>
</div>
</div>
</div>
{isCodeModalOpen && (
<CodeModal
onClose={() => {
setIsCodeModalOpen(false);
setCurrentEditingCode(null);
}}
onSave={handleCodeSave}
initialData={currentEditingCode}
/>
)}
</div>
export default ChatInterface;
// src/components/ChatItem.js
import React, { useContext, useState } from 'react';
import { TrashIcon, PencilIcon, CheckIcon, XIcon } from '@heroicons/react/solid';
import { ChatContext } from '../context/ChatContext';
function ChatItem({ chat }) {
const { currentChatId, setCurrentChatId, deleteChat, updateChat } = useContext(ChatContext);
const [isEditing, setIsEditing] = useState(false);
const [newName, setNewName] = useState(chat.name);
const [renameError, setRenameError] = useState(null);
const handleSelectChat = () => {
setCurrentChatId(chat.id);
setIsEditing(false); // Exit edit mode if selecting the chat
};
const handleDeleteChat = (e) => {
e.stopPropagation(); // Prevent triggering the chat selection
deleteChat(chat.id);
};
const handleEditClick = (e) => {
e.stopPropagation(); // Prevent triggering the chat selection
setIsEditing(true);
};
const handleRename = (e) => {
e.preventDefault();
if (newName.trim() === '') {
setRenameError('Chat name cannot be empty.');
return;
}
console.log(Renaming chat ID: ${chat.id} to "${newName.trim()}"); // Debug log
updateChat(chat.id, { name: newName.trim() });
setIsEditing(false);
setRenameError(null);
};
const handleCancelRename = () => {
setNewName(chat.name);
setIsEditing(false);
setRenameError(null);
};
return (
<div
className={mb-2 cursor-pointer p-2 rounded ${ chat.id === currentChatId ? 'bg-blue-100 dark:bg-blue-900' : 'hover:bg-gray-100 dark:hover:bg-gray-700' }}
onClick={!isEditing ? handleSelectChat : undefined} // Conditional onClick
>
{isEditing ? (
<form onSubmit={handleRename} className="flex items-center space-x-2">
<input
type="text"
value={newName}
onChange={(e) => setNewName(e.target.value)}
className="flex-1 min-w-0 px-2 py-1 rounded border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring focus:border-blue-300 dark:bg-zinc-800 dark:text-white"
autoFocus
/>
<button type="submit" className="text-green-500 hover:text-green-700" title="Save">
<CheckIcon className="h-5 w-5" />
</button>
<button
type="button"
onClick={handleCancelRename}
className="text-gray-500 hover:text-gray-700"
title="Cancel"
>
<XIcon className="h-5 w-5" />
</button>
</form>
) : (
<div className="flex justify-between items-center">
<span className="text-black dark:text-white">{chat.name}</span>
<div className="flex items-center space-x-2">
<button
onClick={handleEditClick}
className="text-gray-500 hover:text-gray-700 dark:text-gray-200 dark:hover:text-gray-400"
title="Rename Chat"
aria-label="Rename Chat"
>
<PencilIcon className="h-5 w-5" />
</button>
<button
onClick={handleDeleteChat}
className="text-red-500 hover:text-red-700"
title="Delete Chat"
aria-label="Delete Chat"
>
<TrashIcon className="h-5 w-5" />
</button>
</div>
</div>
)}
{renameError && (
<div className="text-red-500 text-sm mt-1">
{renameError}
</div>
)}
</div>
);
}
export default ChatItem;
import React, { useContext } from 'react';
import { ChatContext } from '../context/ChatContext';
function Home() {
const { addChat } = useContext(ChatContext);
const getGreeting = () => {
const hour = new Date().getHours();
if (hour < 12) return 'Good Morning, Ziggy';
if (hour < 18) return 'Good Afternoon, Ziggy';
return 'Good Evening, Ziggy';
};
const handleStart = () => {
addChat('New Chat');
};
return (
<div className="flex flex-col items-center justify-center flex-1 p-4">
<h1 className="text-4xl font-bold mb-8 text-gray-800 dark:text-gray-200">{getGreeting()}</h1>
<button
className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600"
onClick={handleStart}
>
Start a New Chat
</button>
</div>
);
}
export default Home;// src/components/Message.js
import React, { useState, useContext } from 'react';
import MarkdownRenderer from './MarkdownRenderer';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { ClipboardCopyIcon } from '@heroicons/react/solid';
import { CodeContext } from '../context/CodeContext';
import CodeAttachmentBubble from './CodeAttachmentBubble';
import CodeModal from './CodeModal';
import { ChatContext } from '../context/ChatContext';
function Message({ chatId, messageIndex, sender, text, model_id }) {
const [copied, setCopied] = useState(false);
const { showCode } = useContext(CodeContext);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [currentAttachment, setCurrentAttachment] = useState(null);
const { updateMessage } = useContext(ChatContext); // Ensure ChatContext is imported
const { models } = useContext(ChatContext); // Access models from context
const modelName = model_id
? models.find((model) => model.id === model_id)?.name || "Unknown Model"
: null;
const handleCopy = () => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const safeText = String(text);
// Function to extract code attachments
const extractCodeAttachments = (text) => {
const codeRegex = /<code(?:\s+fileName="([^"])")?(?:\s+notes="([^"] )")?>([\s\S]*?)</code>/g;
let match;
const attachments = [];
while ((match = codeRegex.exec(text)) !== null) {
attachments.push({
fileName: match[1] || 'Untitled',
notes: match[2] || '',
codeContent: match[3],
});
}
return attachments;
};
const codeAttachments = extractCodeAttachments(safeText);
const cleanedText = safeText.replace(/<code(?:\s+fileName="[^"]")?(?:\s+notes="[^"] ")?>[\s\S]*?</code>/g, '');
// Handlers for editing and deleting attachments
const handleEdit = (attachment) => {
setCurrentAttachment(attachment);
setIsEditModalOpen(true);
};
const handleDelete = (attachment) => {
// Implement deletion logic
// For example, remove the attachment's <code> block from the message text
const updatedText = text.replace(
<code fileName="${attachment.fileName}" notes="${attachment.notes}">${attachment.codeContent}</code>,
''
);
updateMessage(chatId, messageIndex, { text: updatedText });
};
const handleUpdateAttachment = (updatedAttachment) => {
// Replace the old <code> block with the updated one
const oldCodeBlockRegex = new RegExp(
<code(?:\\s+fileName="${updatedAttachment.fileName || 'Untitled'}")?(?:\\s+notes="${updatedAttachment.notes || ''}")?>[\\s\\S]*?<\\/code>,
'g'
);
const newCodeBlock = <code fileName="${updatedAttachment.fileName}" notes="${updatedAttachment.notes}">${updatedAttachment.codeContent}</code>;
const updatedText = text.replace(oldCodeBlockRegex, newCodeBlock);
updateMessage(chatId, messageIndex, { text: updatedText });
};
return (
<>
<div className={mb-4 flex ${sender === 'user' ? 'justify-end' : 'justify-start'}}>
<div
className={max-w-xs md:max-w-md lg:max-w-5xl p-5 rounded-xl ${ sender === 'user' ? 'bg-zinc-950 text-white' : 'bg-gray-200 dark:bg-[#282828] text-gray-800 dark:text-gray-200' }}
>
{sender === 'bot' && modelName && (
<div className="mb-2 text-sm text-gray-500 dark:text-gray-400">
<strong>Model:</strong> {modelName}
</div>
)}
<MarkdownRenderer text={cleanedText} />
<div className="mt-2 flex flex-wrap">
{codeAttachments.map((attachment, index) => (
<CodeAttachmentBubble
key={index}
attachment={attachment}
onEdit={() => handleEdit(attachment)}
onDelete={() => handleDelete(attachment)}
/>
))}
</div>
<CopyToClipboard text={text} onCopy={handleCopy}>
<button className="mt-2 text-sm text-gray-500 hover:text-gray-700 flex items-center">
<ClipboardCopyIcon className="h-5 w-5 mr-1" /> {copied ? 'Copied!' : 'Copy'}
</button>
</CopyToClipboard>
</div>
</div>
{isEditModalOpen && currentAttachment && (
<CodeModal
onClose={() => setIsEditModalOpen(false)}
onSave={handleUpdateAttachment}
initialData={currentAttachment}
/>
)}
</>
export default React.memo(Message);// src/components/Sidebar.js
import React, { useContext, useState } from "react";
import { ChatContext } from "../context/ChatContext";
import { PlusIcon, TrashIcon } from "@heroicons/react/solid";
import { ThemeContext } from "../context/ThemeContext";
import ChatItem from "./ChatItem";
import DarkModeToggle from "./DarkModeToggle";
import ConfirmModal from "./ConfirmModal";
import ModelList from "./ModelList"; // Import the ModelList component
import Favicon from "../assets/favicon.png"
function Sidebar() {
const {
chats,
currentChatId,
setCurrentChatId,
addChat,
deleteChat,
updateChat,
clearChats,
models,
} = useContext(ChatContext);
const { theme, toggleTheme } = useContext(ThemeContext);
const [isResetting, setIsResetting] = useState(false);
const [error, setError] = useState(null);
const [isModalOpen, setIsModalOpen] = useState(false); // For deleting all chats
const handleNewChat = async () => {
setIsResetting(true);
setError(null);
try {
const response = await fetch("http://localhost:8000/api/reset", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Failed to reset chat.");
}
const data = await response.json();
console.log(data.status);
addChat("New Chat");
//setCurrentChatId(null);
} catch (err) {
console.error("Error resetting chat:", err);
setError("Unable to reset the chat. Please try again.");
} finally {
setIsResetting(false);
}
const handleGoHome = () => {
setCurrentChatId(null);
};
const handleDeleteAllChats = () => {
setIsModalOpen(true);
};
const confirmDeleteAllChats = () => {
clearChats();
setIsModalOpen(false);
};
const cancelDeleteAllChats = () => {
setIsModalOpen(false);
};
return (
<div className="w-72 bg-gray-100 dark:bg-zinc-900 border-r dark:border-gray-700 p-4 flex flex-col">
{/* Chatbot Name "Echo" at the top */}
<div
className="mb-6 text-2xl font-bold text-gray-800 dark:text-gray-200 cursor-pointer flex flex-row align-middle"
onClick={handleGoHome}
>
<img src={Favicon} alt="Logo of Echo" width={"32"} className="mr-2 mt-[2px]" />
Echo
</div>
<div className="flex justify-between items-center mb-4">
<h2 className="text-xl font-bold text-gray-800 dark:text-gray-200">
Past Chats
</h2>
<button
onClick={handleNewChat}
className={`p-2 bg-blue-500 text-white rounded hover:bg-blue-600 flex items-center justify-center ${
isResetting ? "opacity-50 cursor-not-allowed" : ""
}`}
title="Start New Chat"
disabled={isResetting}
>
{isResetting ? "Resetting..." : <PlusIcon className="h-5 w-5" />}
</button>
</div>
{error && <div className="mb-4 text-red-500 text-sm">{error}</div>}
<ul className="flex-1 overflow-y-auto space-y-2">
{chats.length === 0 && (
<li className="text-gray-500 dark:text-gray-400">No past chats.</li>
)}
{chats.map((chat) => (
<ChatItem key={chat.id} chat={chat} />
))}
</ul>
{/* Delete All Chats Button */}
{chats.length > 0 && (
<button
onClick={handleDeleteAllChats}
className="mt-4 p-2 bg-red-500 text-white rounded hover:bg-red-600 flex items-center justify-center"
title="Delete All Chats"
>
<TrashIcon className="h-5 w-5" />
<span className="ml-2">Delete All</span>
</button>
)}
{/* Confirm Modal */}
{isModalOpen && (
<ConfirmModal
title="Delete All Chats"
message="Are you sure you want to delete all chats? This action cannot be undone."
onConfirm={confirmDeleteAllChats}
onCancel={cancelDeleteAllChats}
/>
)}
{/* Model List */}
<ModelList />
{/* Dark Mode Toggle at the bottom */}
<div className="mt-4">
<DarkModeToggle theme={theme} toggleTheme={toggleTheme} />
</div>
</div>
export default Sidebar;// src/context/ChatContext.js
import React, { createContext, useState, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
export const ChatContext = createContext();
export const ChatProvider = ({ children }) => {
const [chats, setChats] = useState(() => {
const saved = localStorage.getItem('chats');
return saved ? JSON.parse(saved) : [];
});
useEffect(() => {
const saved = localStorage.getItem('chats');
if (saved) {
const parsedChats = JSON.parse(saved).map(chat => ({
...chat,
messages: chat.messages.map(msg => ({
...msg,
text: String(msg.text) // Ensure text is string
}))
}));
setChats(parsedChats);
} else {
setChats([]);
}
}, []);
const [currentChatId, setCurrentChatId] = useState(() => {
const saved = localStorage.getItem('currentChatId');
return saved ? JSON.parse(saved) : null;
});
const [models, setModels] = useState([]); // List of available models
const [selectedModelId, setSelectedModelId] = useState(() => {
const saved = localStorage.getItem('selectedModelId');
return saved ? JSON.parse(saved) : null;
});
// Fetch models from the backend on component mount
useEffect(() => {
fetch('http://localhost:8000/api/models' ;)
.then((res) => {
if (!res.ok) {
throw new Error(HTTP error! Status: ${res.status});
}
return res.json();
})
.then((data) => {
console.log('Fetched models:', data); // Debugging line
if (Array.isArray(data) && data.length > 0 && !selectedModelId) {
setSelectedModelId(data[0].id); // Select the first model by default
}
setModels(data);
})
.catch((error) => {
console.error('Error fetching models:', error);
setModels([]); // Prevent .map errors
});
}, []);
// Persist chats to localStorage
useEffect(() => {
localStorage.setItem('chats', JSON.stringify(chats));
}, [chats]);
// Persist currentChatId to localStorage
useEffect(() => {
localStorage.setItem('currentChatId', JSON.stringify(currentChatId));
}, [currentChatId]);
// Persist selectedModelId to localStorage
useEffect(() => {
if (selectedModelId) {
localStorage.setItem('selectedModelId', JSON.stringify(selectedModelId));
}
}, [selectedModelId]);
const addChat = (name = Chat ${chats.length + 1}) => {
const newChat = {
id: uuidv4(),
name: name,
messages: [],
systemPrompt: '',
model_id: selectedModelId, // Associate with selected model
};
setChats((prev) => [newChat, ...prev]);
setCurrentChatId(newChat.id);
};
const updateChat = (id, updatedChat) => {
console.log(Updating chat with ID: ${id}, updatedChat); // Add this line
setChats((prevChats) =>
prevChats.map((chat) => (chat.id === id ? { ...chat, ...updatedChat } : chat))
);
};
const addMessage = (id, message) => {
setChats((prevChats) =>
prevChats.map((chat) =>
chat.id === id
? { ...chat, messages: [...chat.messages, { ...message, text: String(message.text) }] }
: chat
)
);
};
const deleteChat = (id) => {
setChats((prevChats) => prevChats.filter((chat) => chat.id !== id));
// If the deleted chat was the current one, reset currentChatId
if (id === currentChatId) {
setCurrentChatId(null);
}
};
const clearChats = () => {
setChats([]);
setCurrentChatId(null);
};
const updateMessage = (chatId, messageIndex, updatedMessage) => {
setChats((prevChats) =>
prevChats.map((chat) =>
chat.id === chatId
? {
...chat,
messages: chat.messages.map((msg, idx) =>
idx === messageIndex
? { ...msg, text: String(updatedMessage.text) }
: msg
),
}
: chat
)
);
};
const addModel = (model) => {
setModels((prev) => [...prev, model]);
};
const removeModel = (modelId) => {
setModels((prev) => prev.filter((model) => model.id !== modelId));
// Optionally, handle chat associations if the removed model was in use
if (selectedModelId === modelId) {
setSelectedModelId(models.length > 0 ? models[0].id : null);
}
};
return (
<ChatContext.Provider
value={{
chats,
currentChatId,
setCurrentChatId,
addChat,
updateChat,
addMessage,
updateMessage,
deleteChat,
clearChats,
models,
addModel,
removeModel,
selectedModelId,
setSelectedModelId,
}}
>
{children}
</ChatContext.Provider>
);
};
To implement the AI-driven renaming feature for your chat application, you'll need to modify the ChatItem.js component. Instead of allowing users to manually enter a new name, the application will automatically generate a 5-word summary of the chat using a predefined AI model on the backend.
Here's a step-by-step guide to achieve this:
Modify the Rename Button Handler
Replace the existing rename functionality with a function that sends the current chat's messages to the backend for summarization. Once the summary is received, update the chat name accordingly.
Update ChatItem.js
Below is the updated ChatItem.js with the necessary changes:
// src/components/ChatItem.js
import React, { useContext, useState } from 'react';
import { TrashIcon, PencilIcon, CheckIcon, XIcon } from '@heroicons/react/solid';
import { ChatContext } from '../context/ChatContext';
function ChatItem({ chat }) {
const { currentChatId, setCurrentChatId, deleteChat, updateChat, models } = useContext(ChatContext);
const [isRenaming, setIsRenaming] = useState(false);
const [error, setError] = useState(null);
const handleSelectChat = () => {
setCurrentChatId(chat.id);
setIsRenaming(false); // Exit rename mode if selecting the chat
};
const handleDeleteChat = (e) => {
e.stopPropagation(); // Prevent triggering the chat selection
deleteChat(chat.id);
};
const handleRenameClick = async (e) => {
e.stopPropagation(); // Prevent triggering the chat selection
setIsRenaming(true);
setError(null);
try {
// Gather all messages from the chat
const messages = chat.messages.map(msg => msg.text).join('\n');
// Send the messages to the backend for summarization
const response = await fetch('http://localhost:8000/api/summarize', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
session_id: chat.id,
messages: messages,
summary_length: 5, // Specify the number of words
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || 'Failed to summarize the chat.');
}
const data = await response.json();
const summary = data.summary; // Assuming the backend returns { summary: '...' }
if (summary && summary.split(' ').length <= 5) {
updateChat(chat.id, { name: summary });
} else {
throw new Error('Received an invalid summary from the AI model.');
}
} catch (err) {
console.error('Rename Error:', err);
setError('Failed to rename the chat. Please try again.');
} finally {
setIsRenaming(false);
}
};
return (
<div
className={`mb-2 cursor-pointer p-2 rounded ${
chat.id === currentChatId
? 'bg-blue-100 dark:bg-blue-900'
: 'hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
onClick={!isRenaming ? handleSelectChat : undefined} // Conditional onClick
>
{isRenaming ? (
<div className="flex items-center space-x-2">
<span className="text-gray-500 dark:text-gray-400">Renaming...</span>
</div>
) : (
<div className="flex justify-between items-center">
<span className="text-black dark:text-white">{chat.name}</span>
<div className="flex items-center space-x-2">
<button
onClick={handleRenameClick}
className="text-gray-500 hover:text-gray-700 dark:text-gray-200 dark:hover:text-gray-400"
title="Rename Chat"
aria-label="Rename Chat"
disabled={isRenaming}
>
<PencilIcon className="h-5 w-5" />
</button>
<button
onClick={handleDeleteChat}
className="text-red-500 hover:text-red-700"
title="Delete Chat"
aria-label="Delete Chat"
>
<TrashIcon className="h-5 w-5" />
</button>
</div>
</div>
)}
{error && (
<div className="text-red-500 text-sm mt-1">
{error}
</div>
)}
</div>
);
}
export default ChatItem;
Explanation of Changes:
Backend Endpoint for Summarization
Ensure that your backend has an endpoint (/api/summarize) that accepts the chat messages and returns a 5-word summary. Here's an example of how you might implement this in a Python-based backend using FastAPI:
# backend/main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import openai # Assuming you're using OpenAI's API
app = FastAPI()
class SummarizeRequest(BaseModel):
session_id: str
messages: str
summary_length: int = 5
class SummarizeResponse(BaseModel):
summary: str
@app.post("/api/summarize", response_model=SummarizeResponse)
async def summarize_chat(request: SummarizeRequest):
try:
# Use the predefined model; ensure you have set it up in your environment
response = openai.ChatCompletion.create(
model="your-predefined-model-id",
messages=[
{"role": "system", "content": "Summarize the following chat in exactly 5 words."},
{"role": "user", "content": request.messages},
],
max_tokens=10, # Adjust tokens to fit 5 words
)
summary = response.choices[0].message['content'].strip()
# Optionally, enforce the summary to be exactly 5 words
summary_words = summary.split()
if len(summary_words) != request.summary_length:
raise ValueError("Summary does not meet the required word count.")
summary = ' '.join(summary_words[:request.summary_length])
return SummarizeResponse(summary=summary)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Notes:
Replace "your-predefined-model-id" with the actual model ID you intend to use.
Ensure that the backend API has appropriate error handling and security measures in place.
Adjust max_tokens as needed to generate a concise 5-word summary.
Update ChatContext.js (Optional)
If you prefer to handle the summarization logic within the context, you can add a method in ChatContext.js to perform the summarization. However, handling it directly in ChatItem.js as illustrated above keeps the component self-contained and minimizes changes to the context.
Error Handling and User Feedback
The updated ChatItem.js provides feedback to users during the renaming process and handles errors gracefully by displaying relevant messages. You can further enhance this by adding toast notifications or other UI elements as per your application's design.
Testing the Feature
After implementing the changes, thoroughly test the feature:
Successful Rename:
Click the rename button and ensure the chat name updates to a 5-word summary.
Error Scenarios:
Simulate backend failures or invalid responses to check if error messages are displayed correctly.
Edge Cases:
Ensure that chats with very few messages are handled appropriately.
Verify that the summary is indeed 5 words long.
Optimizations and Enhancements
Security Considerations
Input Sanitization:
Ensure that the messages sent to the backend are sanitized to prevent any injection attacks.
Authentication:
If your application requires user authentication, make sure the summarization endpoint enforces proper access controls.
Final Thoughts
Integrating AI-driven features can significantly enhance user experience by automating mundane tasks. By following the steps above, you can seamlessly add an automated chat renaming feature to your application, leveraging the power of AI while ensuring cost-effectiveness by using predefined models on the backend.
If you encounter any issues or need further customization, feel free to ask!
Copy first response