api.controller.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import {
  2. Body,
  3. Controller,
  4. Get,
  5. HttpCode,
  6. HttpStatus,
  7. Post,
  8. Request,
  9. UseGuards,
  10. } from '@nestjs/common';
  11. import { ApiService } from './api.service';
  12. import { CombinedAuthGuard } from '../auth/combined-auth.guard';
  13. import { ModelConfigService } from '../model-config/model-config.service';
  14. import { I18nService } from '../i18n/i18n.service';
  15. class ChatDto {
  16. prompt: string;
  17. }
  18. @Controller()
  19. export class ApiController {
  20. constructor(
  21. private readonly apiService: ApiService,
  22. private readonly modelConfigService: ModelConfigService,
  23. private readonly i18nService: I18nService,
  24. ) { }
  25. @Get('health')
  26. healthCheck() {
  27. return this.apiService.healthCheck();
  28. }
  29. @Post('chat')
  30. @UseGuards(CombinedAuthGuard)
  31. @HttpCode(HttpStatus.OK)
  32. async chat(@Request() req, @Body() chatDto: ChatDto) {
  33. const { prompt } = chatDto;
  34. if (!prompt) {
  35. throw new Error(this.i18nService.getMessage('promptRequired'));
  36. }
  37. try {
  38. // ユーザーの LLM モデル設定を取得
  39. const models = await this.modelConfigService.findAll(req.user.id, req.user.tenantId);
  40. const llmModel = models.find((m) => m.type === 'llm');
  41. if (!llmModel) {
  42. throw new Error(this.i18nService.getMessage('addLLMConfig'));
  43. }
  44. // API key is optional - allows local models
  45. const modelConfigForService = {
  46. id: llmModel.id,
  47. name: llmModel.name,
  48. modelId: llmModel.modelId,
  49. baseUrl: llmModel.baseUrl,
  50. apiKey: llmModel.apiKey,
  51. type: llmModel.type as any,
  52. };
  53. const response = await this.apiService.getChatCompletion(
  54. prompt,
  55. modelConfigForService,
  56. );
  57. return { response };
  58. } catch (error) {
  59. throw new Error(error.message || this.i18nService.getMessage('internalServerError'));
  60. }
  61. }
  62. }