From a150ec2936b9e730cc2a592e3f38873d738a4f0e Mon Sep 17 00:00:00 2001 From: Shun Miyazawa Date: Tue, 27 Aug 2024 16:08:45 +0000 Subject: [PATCH] Use OpenAI API --- .../src/server/routes/apiv3/openai/chat.ts | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/apps/app/src/server/routes/apiv3/openai/chat.ts b/apps/app/src/server/routes/apiv3/openai/chat.ts index 6798a8810eb..45cf5fa913c 100644 --- a/apps/app/src/server/routes/apiv3/openai/chat.ts +++ b/apps/app/src/server/routes/apiv3/openai/chat.ts @@ -1,21 +1,21 @@ import type { Request, RequestHandler } from 'express'; import type { ValidationChain } from 'express-validator'; +import { body } from 'express-validator'; import type Crowi from '~/server/crowi'; +import { openaiService } from '~/server/service/openai'; import loggerFactory from '~/utils/logger'; import { apiV3FormValidator } from '../../../middlewares/apiv3-form-validator'; import type { ApiV3Response } from '../interfaces/apiv3-response'; - const logger = loggerFactory('growi:routes:apiv3:openai:chat'); - -type ReqParams = { - // +type ReqBody = { + prompt: string, } -type Req = Request +type Req = Request type ChatHandlersFactory = (crowi: Crowi) => RequestHandler[]; @@ -23,15 +23,20 @@ export const chatHandlersFactory: ChatHandlersFactory = (crowi) => { const accessTokenParser = require('../../../middlewares/access-token-parser')(crowi); const loginRequiredStrictly = require('../../../middlewares/login-required')(crowi); - // define validators for req.body - const validator: ValidationChain[] = []; + const validator: ValidationChain[] = [ + body('prompt').isString().withMessage('prompt must be string'), + ]; return [ accessTokenParser, loginRequiredStrictly, validator, apiV3FormValidator, async(req: Req, res: ApiV3Response) => { - try { - return res.apiv3({}); + const chatCompletion = await openaiService.client.chat.completions.create({ + messages: [{ role: 'assistant', content: req.body.prompt }], + model: 'gpt-3.5-turbo-0125', + }); + + return res.apiv3({ assistantMessage: chatCompletion.choices[0].message.content }); } catch (err) { logger.error(err);