Skip to content

Commit

Permalink
Use OpenAI API
Browse files Browse the repository at this point in the history
  • Loading branch information
miya committed Aug 27, 2024
1 parent 1a79013 commit a150ec2
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions apps/app/src/server/routes/apiv3/openai/chat.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
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<ReqParams, ApiV3Response>
type Req = Request<undefined, ApiV3Response, ReqBody>

type ChatHandlersFactory = (crowi: Crowi) => RequestHandler[];

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);
Expand Down

0 comments on commit a150ec2

Please sign in to comment.