Files
heala-backend/src/modules/chatbot/providers/chatbot.service.ts
T

197 lines
5.1 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CHATBOT_SYSTEM_PROMPT } from '../constants';
import { User } from '@/modules/users/entities/user.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { ConversationService } from '@/modules/conversation/providers/conversation.service';
import { MessageRole } from '@/modules/conversation/enums/message-role.enum';
import { OpenRouterService } from '@/common/modules/open-router/providers/open-router.service';
import { SendChatCompletionRequestResponse } from '@openrouter/sdk/models/operations';
@Injectable()
export class ChatbotService {
constructor(
/**
* Inject Config Service
*/
private readonly configService: ConfigService,
/**
* Inject Conversation Service
*/
private readonly conversationService: ConversationService,
/**
* Inject OpenRouter Service
*/
private readonly openRouterService: OpenRouterService,
) {}
public async getConversations(user: User) {
const conversations =
await this.conversationService.findConversationsByUser(user);
return conversations.map((conversation) => ({
conversationId: conversation.id,
title: conversation.title,
updatedAt: conversation.updatedAt,
}));
}
public async getConversation(user: User, conversationId: number) {
const conversation = await this.conversationService.findConversationById(
conversationId,
user,
);
const messages = await this.conversationService.getMessages(conversation);
return {
conversationId: conversation.id,
title: conversation.title,
createdAt: conversation.createdAt,
updatedAt: conversation.updatedAt,
messages: messages.map((message) => ({
messageId: message.id,
role: message.role,
content: message.content,
createdAt: message.createdAt,
})),
};
}
private async getConversationMessages(
user: User,
message: string,
conversationId?: number,
) {
let conversation: Conversation;
if (conversationId) {
conversation = await this.conversationService.findConversationById(
conversationId,
user,
);
} else {
conversation = await this.conversationService.createConversation(user);
}
await this.conversationService.addMessage(
conversation,
MessageRole.USER,
message,
);
const messages = await this.conversationService.getMessages(conversation);
return {
conversation,
messages: [
{
role: 'system' as const,
content: CHATBOT_SYSTEM_PROMPT.trim(),
},
...messages.map((message) => ({
role:
message.role === MessageRole.USER
? ('user' as const)
: ('assistant' as const),
content: message.content,
})),
],
};
}
public async chat(user: User, message: string, conversationId?: number) {
const { conversation, messages } = await this.getConversationMessages(
user,
message,
conversationId,
);
const openRouter = await this.openRouterService.getOpenRouter();
let response: SendChatCompletionRequestResponse;
try {
response = await openRouter.chat.send({
chatRequest: {
model: this.configService.getOrThrow<string>('openRouter.model'),
messages,
},
});
} catch (err) {
console.error('[ChatbotService] OpenRouter request failed:', err);
throw err;
}
if (response instanceof ReadableStream) {
throw new Error('Expected non-streaming response');
}
const content = response.choices[0]?.message?.content;
if (typeof content !== 'string') {
throw new Error('OpenRouter returned an unexpected response');
}
await this.conversationService.addMessage(
conversation,
MessageRole.ASSISTANT,
content,
);
return {
conversationId: conversation.id,
message: content,
};
}
public async *streamChat(
user: User,
message: string,
conversationId?: number,
) {
const { conversation, messages } = await this.getConversationMessages(
user,
message,
conversationId,
);
const openRouter = await this.openRouterService.getOpenRouter();
const response = await openRouter.chat.send({
chatRequest: {
model: this.configService.getOrThrow<string>('openRouter.model'),
messages,
stream: true,
},
});
if ('choices' in response) {
throw new Error('Expected streaming response');
}
let assistantMessage = '';
for await (const chunk of response) {
const content = chunk.choices[0]?.delta?.content;
if (!content) {
continue;
}
assistantMessage += content;
yield { conversationId: conversation.id, content };
}
if (assistantMessage) {
await this.conversationService.addMessage(
conversation,
MessageRole.ASSISTANT,
assistantMessage,
);
}
}
}