-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #63 from BinaryStudioAcademy/task/OV-52-add-chat-h…
…istory-saving OV-52: add chat controller
- Loading branch information
Showing
41 changed files
with
459 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,176 @@ | ||
import { type FastifySessionObject } from '@fastify/session'; | ||
|
||
import { | ||
type ApiHandlerOptions, | ||
type ApiHandlerResponse, | ||
BaseController, | ||
} from '~/common/controller/controller.js'; | ||
import { ApiPath } from '~/common/enums/enums.js'; | ||
import { HttpCode, HTTPMethod } from '~/common/http/http.js'; | ||
import { type Logger } from '~/common/logger/logger.js'; | ||
import { MAX_TOKEN } from '~/common/services/open-ai/libs/constants/constants.js'; | ||
import { | ||
ChatPath, | ||
OpenAIRole, | ||
} from '~/common/services/open-ai/libs/enums/enums.js'; | ||
import { type OpenAIService } from '~/common/services/open-ai/open-ai.service.js'; | ||
|
||
import { type ChatService } from './chat.service.js'; | ||
import { type GenerateTextRequestDto } from './libs/types/types.js'; | ||
import { textGenerationValidationSchema } from './libs/validation-schemas/validation-schemas.js'; | ||
|
||
class ChatController extends BaseController { | ||
private openAIService: OpenAIService; | ||
private chatService: ChatService; | ||
|
||
public constructor( | ||
logger: Logger, | ||
openAIService: OpenAIService, | ||
chatService: ChatService, | ||
) { | ||
super(logger, ApiPath.CHAT); | ||
|
||
this.openAIService = openAIService; | ||
this.chatService = chatService; | ||
|
||
this.addRoute({ | ||
path: ChatPath.ROOT, | ||
method: HTTPMethod.POST, | ||
validation: { | ||
body: textGenerationValidationSchema, | ||
}, | ||
handler: (options) => | ||
this.generateChatAnswer( | ||
options as ApiHandlerOptions<{ | ||
body: GenerateTextRequestDto; | ||
session: FastifySessionObject; | ||
}>, | ||
), | ||
}); | ||
|
||
this.addRoute({ | ||
path: ChatPath.ROOT, | ||
method: HTTPMethod.DELETE, | ||
handler: (options) => | ||
this.deleteSession( | ||
options as ApiHandlerOptions<{ | ||
session: FastifySessionObject; | ||
}>, | ||
), | ||
}); | ||
} | ||
|
||
/** | ||
* @swagger | ||
* /chat/: | ||
* post: | ||
* description: Returns generated text by Open AI | ||
* requestBody: | ||
* description: User message | ||
* required: true | ||
* content: | ||
* application/json: | ||
* schema: | ||
* type: object | ||
* properties: | ||
* message: | ||
* type: string | ||
* responses: | ||
* 200: | ||
* description: Successful operation | ||
* content: | ||
* application/json: | ||
* schema: | ||
* type: object | ||
* properties: | ||
* generatedText: | ||
* type: string | ||
*/ | ||
|
||
private async generateChatAnswer( | ||
options: ApiHandlerOptions<{ | ||
body: GenerateTextRequestDto; | ||
session: FastifySessionObject; | ||
}>, | ||
): Promise<ApiHandlerResponse> { | ||
const { body, session } = options; | ||
|
||
session.chatHistory = this.chatService.addMessageToHistory( | ||
session.chatHistory, | ||
body.message, | ||
OpenAIRole.USER, | ||
); | ||
|
||
session.chatHistory = this.chatService.deleteOldMessages( | ||
session.chatHistory, | ||
MAX_TOKEN, | ||
); | ||
|
||
const generatedText = await this.openAIService.generateText( | ||
session.chatHistory, | ||
); | ||
|
||
session.chatHistory = this.chatService.addMessageToHistory( | ||
session.chatHistory, | ||
generatedText, | ||
OpenAIRole.ASSISTANT, | ||
); | ||
|
||
return { | ||
payload: { generatedText }, | ||
status: HttpCode.OK, | ||
}; | ||
} | ||
|
||
/** | ||
* @swagger | ||
* /chat/: | ||
* delete: | ||
* description: Clears chat history | ||
* requestBody: | ||
* description: User message | ||
* required: false | ||
* responses: | ||
* 200: | ||
* description: Successful operation | ||
* content: | ||
* application/json: | ||
* schema: | ||
* type: object | ||
* properties: | ||
* isDeleted: | ||
* type: boolean | ||
* 500: | ||
* description: Failed operation | ||
* content: | ||
* application/json: | ||
* schema: | ||
* type: object | ||
* properties: | ||
* isDeleted: | ||
* type: boolean | ||
*/ | ||
private deleteSession( | ||
options: ApiHandlerOptions<{ | ||
session: FastifySessionObject; | ||
}>, | ||
): ApiHandlerResponse { | ||
const { session } = options; | ||
|
||
session.destroy((error) => { | ||
if (error) { | ||
return { | ||
payload: { isDeleted: false }, | ||
status: HttpCode.INTERNAL_SERVER_ERROR, | ||
}; | ||
} | ||
}); | ||
|
||
return { | ||
payload: { isDeleted: true }, | ||
status: HttpCode.OK, | ||
}; | ||
} | ||
} | ||
|
||
export { ChatController }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { type ValueOf } from 'shared'; | ||
import { type Tiktoken, encoding_for_model } from 'tiktoken'; | ||
|
||
import { CHAT_MODEL } from '~/common/services/open-ai/libs/constants/constants.js'; | ||
import { type OpenAIRole } from '~/common/services/open-ai/libs/enums/enums.js'; | ||
|
||
import { | ||
type ChatService as ChatServiceT, | ||
type Message, | ||
} from './libs/types/types.js'; | ||
|
||
class ChatService implements ChatServiceT { | ||
private modelEncoding: Tiktoken; | ||
|
||
public constructor() { | ||
this.modelEncoding = encoding_for_model(CHAT_MODEL); | ||
} | ||
|
||
public addMessageToHistory( | ||
chatHistory: Message[], | ||
userMessage: string, | ||
role: ValueOf<typeof OpenAIRole>, | ||
): Message[] { | ||
const newUserMessage = { | ||
content: userMessage, | ||
role, | ||
}; | ||
|
||
return [...chatHistory, newUserMessage]; | ||
} | ||
|
||
private countTokens(messages: Message[]): number { | ||
return messages.reduce( | ||
(sum, message) => | ||
sum + this.modelEncoding.encode(message.content).length, | ||
0, | ||
); | ||
} | ||
|
||
public deleteOldMessages( | ||
messages: Message[], | ||
maxTokens: number, | ||
): Message[] { | ||
let totalTokens = this.countTokens(messages); | ||
let updatedMessages = [...messages]; | ||
|
||
while (totalTokens > maxTokens && updatedMessages.length > 0) { | ||
const [removedMessage, ...rest] = updatedMessages; | ||
updatedMessages = rest; | ||
|
||
if (!removedMessage) { | ||
break; | ||
} | ||
|
||
totalTokens -= this.modelEncoding.encode( | ||
removedMessage.content, | ||
).length; | ||
} | ||
|
||
return updatedMessages; | ||
} | ||
} | ||
|
||
export { ChatService }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { logger } from '~/common/logger/logger.js'; | ||
import { openAIService } from '~/common/services/services.js'; | ||
|
||
import { ChatController } from './chat.controller.js'; | ||
import { ChatService } from './chat.service.js'; | ||
|
||
const chatService = new ChatService(); | ||
const chatController = new ChatController(logger, openAIService, chatService); | ||
|
||
export { chatController }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { type ValueOf } from 'shared'; | ||
|
||
import { type OpenAIRole } from '~/common/services/open-ai/libs/enums/enums.js'; | ||
|
||
import { type Message } from './message.type.js'; | ||
|
||
type ChatService = { | ||
addMessageToHistory( | ||
chatHistory: Message[], | ||
userMessage: string, | ||
role: ValueOf<typeof OpenAIRole>, | ||
): Message[]; | ||
deleteOldMessages(messages: Message[], maxTokens: number): void; | ||
}; | ||
|
||
export { type ChatService }; |
2 changes: 1 addition & 1 deletion
2
...rvices/open-ai/libs/types/message.type.ts → ...c/bundles/chat/libs/types/message.type.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
export { type ChatService } from './chat-service.type.js'; | ||
export { type Message } from './message.type.js'; | ||
export { type GenerateTextRequestDto } from 'shared'; |
1 change: 1 addition & 0 deletions
1
backend/src/bundles/chat/libs/validation-schemas/validation-schemas.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { textGenerationValidationSchema } from 'shared'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
export { HttpCode } from 'shared'; | ||
export { HttpCode, HTTPMethod } from 'shared'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,3 @@ | ||
export { HttpCode } from './enums/enums.js'; | ||
export { HttpCode, HTTPMethod } from './enums/enums.js'; | ||
export { HttpError } from './exceptions/exceptions.js'; | ||
export { type HttpMethod } from './types/types.js'; |
5 changes: 5 additions & 0 deletions
5
backend/src/common/plugins/libs/enums/controller-hook.enum.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
const ControllerHook = { | ||
ON_REQUEST: 'onRequest', | ||
} as const; | ||
|
||
export { ControllerHook }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { ControllerHook } from './controller-hook.enum.js'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,2 @@ | ||
export { authenticateJWT } from './auth/auth-jwt.plugin.js'; | ||
export { session } from './session/session.plugin.js'; |
Oops, something went wrong.