working chat interface with n8n

This commit is contained in:
Harivansh Rathi 2024-12-07 18:20:22 -05:00
parent 8cfff27165
commit bda69752c0
3 changed files with 160 additions and 37 deletions

View file

@ -13,6 +13,64 @@ const setInStorage = <T>(key: string, data: T[]) => {
localStorage.setItem(key, JSON.stringify(data));
};
// N8N webhook configuration
const N8N_WEBHOOK_URL = import.meta.env.VITE_N8N_WEBHOOK_URL;
// Define the expected response type from n8n RAG workflow
interface N8NResponse {
success: boolean;
response: {
content: string;
role: 'assistant';
metadata?: {
sources?: string[];
error?: string;
};
};
}
// Function to send message to n8n webhook and handle response
const sendToN8N = async (sessionId: string, message: string): Promise<N8NResponse> => {
try {
console.log('Sending message to n8n:', { sessionId, message });
const response = await fetch(N8N_WEBHOOK_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
sessionId,
action: 'sendMessage',
chatInput: message
})
});
console.log('Raw n8n response:', response);
if (!response.ok) {
throw new Error(`N8N webhook error: ${response.statusText}`);
}
const responseData = await response.json();
console.log('Parsed n8n response:', responseData);
return responseData;
} catch (error) {
console.error('Error sending message to n8n:', error);
return {
success: false,
response: {
content: 'Sorry, I encountered an error processing your request.',
role: 'assistant',
metadata: {
error: error instanceof Error ? error.message : 'Unknown error'
}
}
};
}
};
export const chatService = {
async createChatInstance(userId: string, title: string): Promise<ChatInstance | null> {
try {
@ -91,9 +149,10 @@ export const chatService = {
content: string,
role: 'user' | 'assistant',
metadata?: ChatMessage['metadata']
): Promise<ChatMessage | null> {
): Promise<ChatMessage[]> {
try {
const message: ChatMessage = {
// Create and save the user message
const userMessage: ChatMessage = {
id: generateId(),
chat_id: chatId,
content,
@ -102,10 +161,57 @@ export const chatService = {
metadata,
};
const messages = getFromStorage<ChatMessage>('chat_messages');
messages.push(message);
let messages = getFromStorage<ChatMessage>('chat_messages');
messages.push(userMessage);
setInStorage('chat_messages', messages);
// If it's a user message, send to n8n and create assistant message
if (role === 'user') {
try {
const n8nResponse = await sendToN8N(chatId, content);
console.log('Creating assistant message with n8n response:', n8nResponse);
if (n8nResponse.success && n8nResponse.response) {
// Create and save the assistant's response
const assistantMessage: ChatMessage = {
id: generateId(),
chat_id: chatId,
content: n8nResponse.response.content,
role: 'assistant',
created_at: new Date().toISOString(),
metadata: {
...n8nResponse.response.metadata,
make_response_id: userMessage.id // Link to the user's message
}
};
messages = getFromStorage<ChatMessage>('chat_messages');
messages.push(assistantMessage);
setInStorage('chat_messages', messages);
console.log('Assistant message saved:', assistantMessage);
} else {
throw new Error('Invalid response format from n8n');
}
} catch (n8nError) {
console.error('Failed to get response from n8n:', n8nError);
// Add an error message if n8n fails
const errorMessage: ChatMessage = {
id: generateId(),
chat_id: chatId,
content: 'Sorry, I encountered an error processing your request.',
role: 'assistant',
created_at: new Date().toISOString(),
metadata: {
error: 'Failed to process message',
make_response_id: userMessage.id
}
};
messages = getFromStorage<ChatMessage>('chat_messages');
messages.push(errorMessage);
setInStorage('chat_messages', messages);
}
}
// Update last_message_at in chat instance
const chats = getFromStorage<ChatInstance>('chat_instances');
const chatIndex = chats.findIndex(chat => chat.id === chatId);
@ -114,10 +220,14 @@ export const chatService = {
setInStorage('chat_instances', chats);
}
return message;
// Return all messages for this chat
const updatedMessages = messages.filter(msg => msg.chat_id === chatId)
.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
console.log('Returning updated messages:', updatedMessages);
return updatedMessages;
} catch (error) {
console.error('Error adding message:', error);
return null;
return [];
}
},