108 lines
2.6 KiB
TypeScript
108 lines
2.6 KiB
TypeScript
import {
|
|
Body,
|
|
Controller,
|
|
Get,
|
|
HttpCode,
|
|
HttpStatus,
|
|
Param,
|
|
ParseIntPipe,
|
|
Post,
|
|
Res,
|
|
} from '@nestjs/common';
|
|
import { ChatbotService } from './providers/chatbot.service';
|
|
import type { Response } from 'express';
|
|
import { ChatDTO } from './dtos/chat.dto';
|
|
import { ChatResponseDto } from './dtos/chat-response.dto';
|
|
import { ActiveUser } from '@/common/decorators/active-user.decorator';
|
|
import { User } from '../users/entities/user.entity';
|
|
import { ApiAppResponse } from '@/common/decorators/api-app-response.decorator';
|
|
import { Throttle } from '@nestjs/throttler';
|
|
import { GetConversationDTO } from './dtos/get-conversation.dto';
|
|
import { GetConversationDetailsDTO } from './dtos/get-conversation-details.dto';
|
|
|
|
@Controller('chatbot')
|
|
@Throttle({ default: { limit: 30, ttl: 60_000 } })
|
|
export class ChatbotController {
|
|
constructor(
|
|
/**
|
|
* Inject Chatbot Service
|
|
*/
|
|
private readonly chatbotService: ChatbotService,
|
|
) {}
|
|
|
|
@Get('conversations')
|
|
@ApiAppResponse([
|
|
{
|
|
status: HttpStatus.OK,
|
|
variants: [{ model: GetConversationDTO, isArray: true }],
|
|
},
|
|
])
|
|
public async getConversations(@ActiveUser() user: User) {
|
|
return this.chatbotService.getConversations(user);
|
|
}
|
|
|
|
@Get('conversations/:conversationId')
|
|
@ApiAppResponse([
|
|
{
|
|
status: HttpStatus.OK,
|
|
variants: [{ model: GetConversationDetailsDTO }],
|
|
},
|
|
])
|
|
public async getConversation(
|
|
@Param('conversationId', ParseIntPipe) conversationId: number,
|
|
@ActiveUser() user: User,
|
|
) {
|
|
return this.chatbotService.getConversation(user, conversationId);
|
|
}
|
|
|
|
@Post('chat')
|
|
@HttpCode(HttpStatus.OK)
|
|
@ApiAppResponse([
|
|
{
|
|
status: HttpStatus.OK,
|
|
variants: [
|
|
{
|
|
model: ChatResponseDto,
|
|
},
|
|
],
|
|
},
|
|
])
|
|
public async chat(@Body() chatDto: ChatDTO, @ActiveUser() user: User) {
|
|
return this.chatbotService.chat(
|
|
user,
|
|
chatDto.message,
|
|
chatDto.conversationId,
|
|
);
|
|
}
|
|
|
|
@Post('stream')
|
|
@HttpCode(HttpStatus.OK)
|
|
public async streamChat(
|
|
@Body() chatDto: ChatDTO,
|
|
@ActiveUser() user: User,
|
|
@Res() res: Response,
|
|
) {
|
|
const headers = {
|
|
'Content-Type': 'text/event-stream',
|
|
'Cache-Control': 'no-cache',
|
|
Connection: 'keep-alive',
|
|
};
|
|
|
|
for await (const content of this.chatbotService.streamChat(
|
|
user,
|
|
chatDto.message,
|
|
chatDto.conversationId,
|
|
)) {
|
|
if (!res.headersSent) res.set(headers);
|
|
res.write(
|
|
`data: ${JSON.stringify({
|
|
message: content,
|
|
})}\n\n`,
|
|
);
|
|
}
|
|
|
|
if (!res.headersSent) res.set(headers);
|
|
res.end();
|
|
}
|
|
}
|