thread.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import type { IUserHasId } from '@growi/core/dist/interfaces';
  2. import { ErrorV3 } from '@growi/core/dist/models';
  3. import type { Request, RequestHandler } from 'express';
  4. import type { ValidationChain } from 'express-validator';
  5. import { body } from 'express-validator';
  6. import type Crowi from '~/server/crowi';
  7. import { accessTokenParser } from '~/server/middlewares/access-token-parser';
  8. import { apiV3FormValidator } from '~/server/middlewares/apiv3-form-validator';
  9. import type { ApiV3Response } from '~/server/routes/apiv3/interfaces/apiv3-response';
  10. import loggerFactory from '~/utils/logger';
  11. import { ThreadType } from '../../interfaces/thread-relation';
  12. import { getOpenaiService } from '../services/openai';
  13. import { certifyAiService } from './middlewares/certify-ai-service';
  14. const logger = loggerFactory('growi:routes:apiv3:openai:thread');
  15. type ReqBody = {
  16. type: ThreadType,
  17. aiAssistantId?: string,
  18. initialUserMessage?: string,
  19. }
  20. type CreateThreadReq = Request<undefined, ApiV3Response, ReqBody> & { user: IUserHasId };
  21. type CreateThreadFactory = (crowi: Crowi) => RequestHandler[];
  22. export const createThreadHandlersFactory: CreateThreadFactory = (crowi) => {
  23. const loginRequiredStrictly = require('~/server/middlewares/login-required')(crowi);
  24. const validator: ValidationChain[] = [
  25. body('type').isIn(Object.values(ThreadType)).withMessage('type must be one of "editor" or "knowledge"'),
  26. body('aiAssistantId').optional().isMongoId().withMessage('aiAssistantId must be string'),
  27. body('initialUserMessage').optional().isString().withMessage('initialUserMessage must be string'),
  28. ];
  29. return [
  30. accessTokenParser, loginRequiredStrictly, certifyAiService, validator, apiV3FormValidator,
  31. async(req: CreateThreadReq, res: ApiV3Response) => {
  32. const openaiService = getOpenaiService();
  33. if (openaiService == null) {
  34. return res.apiv3Err(new ErrorV3('GROWI AI is not enabled'), 501);
  35. }
  36. const { type, aiAssistantId, initialUserMessage } = req.body;
  37. // express-validator ensures aiAssistantId is a string
  38. try {
  39. const thread = await openaiService.createThread(req.user._id, type, aiAssistantId, initialUserMessage);
  40. return res.apiv3(thread);
  41. }
  42. catch (err) {
  43. logger.error(err);
  44. return res.apiv3Err(err);
  45. }
  46. },
  47. ];
  48. };