Skip to content

Commit

Permalink
Merge branch 'feature/f-33-chat-implementation' of https://github.com…
Browse files Browse the repository at this point in the history
…/jst-seminar-rostlab-tum/wfp-hunger-map into feature/f-33-chat-implementation
  • Loading branch information
Haidong Xu committed Nov 7, 2024
2 parents 1a0310e + 68d889b commit 8f5c664
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 90 deletions.
9 changes: 6 additions & 3 deletions src/components/Chatbot/Chatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';

import TypingText from '@/components/TypingText/TypingText';
import container from '@/container';
import {
CHAT_TITLE,
DATA_SOURCES,
Expand All @@ -21,15 +22,17 @@ import {
TYPING_PLACEHOLDER,
WELCOME_MESSAGE,
} from '@/domain/constant/chatbot/Chatbot';
import { APIError } from '@/domain/entities/chatbot/BackendCommunication';
import { IChat } from '@/domain/entities/chatbot/Chatbot';
import { SenderRole } from '@/domain/enums/SenderRole';
import { APIError, chatService, formatChatResponse } from '@/services/api/chatbot';
import ChatbotRepository from '@/domain/repositories/ChatbotRepository';
import { useMediaQuery } from '@/utils/resolution';

import TypingDots from '../TypingText/TypingDot';
import ChatbotSidebar from './ChatbotSidebar';

export default function HungerMapChatbot() {
const chatbot = container.resolve<ChatbotRepository>('ChatbotRepository');
const [isOpen, setIsOpen] = useState(false);
const [isFullScreen, setIsFullScreen] = useState(false);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
Expand Down Expand Up @@ -90,8 +93,8 @@ export default function HungerMapChatbot() {
const previousMessages = chats[currentChatIndex].messages;
let aiResponse = '';
try {
const response = await chatService.sendMessage(text, { previous_messages: previousMessages });
aiResponse = formatChatResponse(response).text;
const response = await chatbot.sendMessage(text, { previous_messages: previousMessages });
aiResponse = response.response;
} catch (err) {
if (err instanceof APIError) {
aiResponse = `Ups! Unfortunately, it seems like there was a problem connecting to the server...\n ${err.status}: ${err.message}`;
Expand Down
2 changes: 2 additions & 0 deletions src/container.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AlertRepositoryImpl } from './infrastructure/repositories/AlertRepositoryImpl';
import ChatbotRepositoryImpl from './infrastructure/repositories/ChatbotRepositoryImpl';
import CountryRepositoryImpl from './infrastructure/repositories/CountryRepositoryImpl';
import GlobalDataRepositoryImpl from './infrastructure/repositories/GlobalDataRepositoryImpl';

Expand All @@ -22,5 +23,6 @@ const container = new Container();
container.register('CountryRepository', new CountryRepositoryImpl());
container.register('AlertRepository', new AlertRepositoryImpl());
container.register('GlobalDataRepository', new GlobalDataRepositoryImpl());
container.register('ChatbotRepository', new ChatbotRepositoryImpl());

export default container;
26 changes: 26 additions & 0 deletions src/domain/entities/chatbot/BackendCommunication.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { IMessage } from './Chatbot';

export interface QueryRequest {
query: string;
version?: number;
chatbot_type?: string;
limit?: number;
previous_messages?: IMessage[];
}

export interface QueryResponse {
response: string;
prompt_tokens: number;
total_tokens: number;
}

// TO-DO: not sure if it belongs here. consider moving to another place
export class APIError extends Error {
constructor(
public status: number,
message: string
) {
super(message);
this.name = 'APIError';
}
}
17 changes: 17 additions & 0 deletions src/domain/repositories/ChatbotRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { QueryRequest, QueryResponse } from '@/domain/entities/chatbot/BackendCommunication.ts';

export default interface ChatbotRepository {
/**
* Tests the health of the chatbot service by sending a test message.
* @returns A promise that resolves to a boolean indicating the health status.
*/
testHealth(): Promise<boolean>;

/**
* Sends a message to the chatbot service with optional parameters.
* @param message The message to be sent to the chatbot.
* @param options Optional parameters for the message, excluding the query.
* @returns A promise that resolves to the response from the chatbot.
*/
sendMessage(message: string, options: Partial<Omit<QueryRequest, 'query'>>): Promise<QueryResponse>;
}
45 changes: 45 additions & 0 deletions src/infrastructure/repositories/ChatbotRepositoryImpl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { APIError, QueryRequest, QueryResponse } from '@/domain/entities/chatbot/BackendCommunication.ts';
import ChatbotRepository from '@/domain/repositories/ChatbotRepository';

export default class ChatbotRepositoryImpl implements ChatbotRepository {
async testHealth(): Promise<boolean> {
try {
const response = await fetch(`${process.env.BACKEND_CHATBOT_API_URL}/health`);
return response.ok;
} catch {
return false;
}
}

async sendMessage(message: string, options: Partial<Omit<QueryRequest, 'query'>>): Promise<QueryResponse> {
try {
const payload: QueryRequest = {
query: message,
version: options.version || 1,
chatbot_type: options.chatbot_type || 'gpt-4',
limit: options.limit || 5,
previous_messages: options.previous_messages || [],
};

const response = await fetch(`${process.env.BACKEND_CHATBOT_API_URL}/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});

if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new APIError(response.status, errorData.error || `Server responded with status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error instanceof APIError) {
throw error;
}
throw new APIError(500, 'Failed to connect to server');
}
}
}
87 changes: 0 additions & 87 deletions src/services/api/chatbot.ts

This file was deleted.

0 comments on commit 8f5c664

Please sign in to comment.