-
Notifications
You must be signed in to change notification settings - Fork 0
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
OV-52: add chat controller #63
Merged
Merged
Changes from 50 commits
Commits
Show all changes
55 commits
Select commit
Hold shift + click to select a range
d377c33
OV-52: - generatedText type
sergiy4 c369e99
OV-52: + enums
sergiy4 0a9de7a
OV-52: + HTTPMethod enum
sergiy4 23bbba9
OV-52: * ApiPath enum
sergiy4 60bb05c
OV-52: + HTTPMethod enum
sergiy4 16b9285
OV-52: + GenerateTextRequestDto type
sergiy4 fd75b00
OV-52: + validation schema
sergiy4 a9b7198
OV-52: * rename file
sergiy4 9dc16e6
OV-52: * rename endpoint
sergiy4 23fd9b3
OV-52: + shared exports
sergiy4 2cdc718
OV-52: + session key
sergiy4 da455ab
OV-52: + fastify session library
sergiy4 0dcbe1c
OV-52: + types
sergiy4 31e7bdc
OV-52: + libs
sergiy4 fbd2dff
OV-52: + libs
sergiy4 dbe2dfb
OV-52: + plugin
sergiy4 e69ce2a
OV-52: + open ai service
sergiy4 61e42d4
OV-52: + chat controller
sergiy4 f4a1e58
OV-52: + fastify module
sergiy4 0314364
Merge branch 'next' into task/OV-52-add-chat-history-saving
sergiy4 7b3c962
OV-52: * HttpMethod type
sergiy4 3a1ebc3
OV-52: * OpenAISerrvice type
sergiy4 4e95492
OV-52: + clear chat logic
sergiy4 6d3f7e0
OV-52: - sessionChatHistory type
sergiy4 331a987
OV-52: + tiktoken package
sergiy4 d5438bf
OV-52: * HttpMethod type
sergiy4 37c3dd9
OV-52: - sessionChatHistory type
sergiy4 d76157a
OV-52: * MAX_TOKEN
sergiy4 33b4c70
OV-52: + delete old messages logic
sergiy4 6b646bb
OV-52: + delete session handler
sergiy4 1c3f5ef
OV-52: * openAi service
sergiy4 ff6f18c
OV-52: * openAi service
sergiy4 d400b39
OV-52: + chat service
sergiy4 3ef2954
OV-52: * openAI service
sergiy4 e0f6a47
OV-52: * chat controller
sergiy4 1029592
OV-52: * chat service
sergiy4 dec2880
OV-52: * chat controller
sergiy4 053a0dd
OV-52: * move OpenAi service
sergiy4 6f50b86
OV-52: * chat controller
sergiy4 1dbd383
OV-52: * rename
sergiy4 222d36e
OV-52: + swagger docs
sergiy4 14cb9f3
OV-52: * .env.example
sergiy4 bd51240
OV-52: + merge
sergiy4 623fee7
OV-52: - as const
sergiy4 567bd8b
OV-52: * chat enum
sergiy4 37664fb
OV-52: * chat service
sergiy4 08d1e70
OV-52: * chat controller
sergiy4 0f66887
OV-52: * openai service
sergiy4 a1eeb57
OV-52: * .env.example
sergiy4 a31d874
OV-52: + merge
sergiy4 ded87cc
OV-52: * exports
sergiy4 70f9652
Merge branch 'next' into task/OV-52-add-chat-history-saving
sergiy4 9c5488e
OV-52: + merge
sergiy4 1c21628
OV-52: + merge
sergiy4 dcb791f
Merge branch 'next' into task/OV-52-add-chat-history-saving
sergiy4 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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( | ||
sergiy4 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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( | ||
sergiy4 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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 |
---|---|---|
@@ -0,0 +1 @@ | ||
export { session } from './session/session.plugin.js'; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Use relative imports