Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"cross-env": "^7.0.3",
"crypto-js": "^4.1.1",
"form-data": "^4.0.0",
"groq-sdk": "^0.15.0",
"ioredis": "^5.3.2",
"joi": "^17.6.0",
"openai": "^4.80.0",
Expand Down
10 changes: 10 additions & 0 deletions src/ai/ai.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export interface AiService {
chat(chatRequest: {
messages: any[];
model: string;
temperature: number;
responseType: string;
}): Promise<string | null>;
}

export const AiService = Symbol('AiService');
37 changes: 37 additions & 0 deletions src/ai/groq/groq.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import Groq from 'groq-sdk';
import { AiService } from '../ai.service';

@Injectable()
export class GroqService implements AiService {
private readonly groq: Groq;

constructor(private readonly configService: ConfigService) {
this.groq = new Groq({
apiKey: this.configService.get('GROQ_API_KEY'),
});
}
async chat({
messages,
model,
temperature,
responseType,
}: {
messages: any[];
model: string;
temperature: number;
responseType: string;
}): Promise<string | null> {
const response = await this.groq.chat.completions.create({
messages,
model,
temperature,
response_format: {
type: responseType as 'text' | 'json_object' | undefined,
},
});

return response.choices[0].message.content;
}
}
9 changes: 9 additions & 0 deletions src/ai/openai.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { GroqService } from './groq/groq.service';
import { AiService } from './ai.service';

@Module({
providers: [{ provide: AiService, useClass: GroqService }],
exports: [{ provide: AiService, useClass: GroqService }],
})
export class AiModule {}
File renamed without changes.
37 changes: 23 additions & 14 deletions src/openai/openai.service.ts → src/ai/openai/openai.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

import { CreateCompletionBodyDto } from './dto/create-completion.dto';
import OpenAI from 'openai';
import { ChatCompletion } from 'openai/resources';
import {
ResponseFormatJSONObject,
ResponseFormatJSONSchema,
ResponseFormatText,
} from 'openai/resources';
import { AiService } from '../ai.service';

@Injectable()
export class OpenaiService {
export class OpenaiService implements AiService {
private readonly openAIApi: OpenAI;
constructor(private readonly configService: ConfigService) {
this.openAIApi = new OpenAI({
Expand All @@ -15,26 +19,31 @@ export class OpenaiService {
});
}

async createChatCompletion({
question,
async chat({
messages,
model,
temperature,
responseType,
}: CreateCompletionBodyDto): Promise<ChatCompletion> {
}: {
messages: any[];
model: string;
temperature: number;
responseType: string;
}): Promise<string | null> {
try {
const response = await this.openAIApi.chat.completions.create({
model: model || 'gpt-4o-mini',
messages: [
{
role: 'user',
content: question,
},
],
messages,
temperature: temperature || 0.1,
...(responseType && { response_format: responseType }),
...(responseType && {
response_format: responseType as unknown as
| ResponseFormatText
| ResponseFormatJSONObject
| ResponseFormatJSONSchema,
}),
});

return response;
return response.choices[0].message.content;
} catch (e) {
throw e;
}
Expand Down
3 changes: 1 addition & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { CollectionsModule } from './collections/collections.module';
import { BatchModule } from './batch/batch.module';
import { SummaryModule } from './summary/summary.module';
import { TypeOrmConfigService } from './database/typerom-config.service';
import { OpenaiModule } from './openai/openai.module';
import { AiModule } from './ai/openai.module';
import { AppController } from './app.controller';
import { AopModule } from './common/aop/aop.module';
import { InfraModule } from './infra/infra.module';
Expand Down Expand Up @@ -106,7 +106,6 @@ import { InfraModule } from './infra/infra.module';
? process.env.NAVER_CLOVA_SUMMARY_REQUEST_URL
: '',
}),
OpenaiModule,
AopModule,
InfraModule,
],
Expand Down
9 changes: 0 additions & 9 deletions src/auth/oauth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,4 @@ export class OAuthController {
async appleLogin(@Query('code') code: string): Promise<LoginOutput> {
return this.oauthService.appleLogin(code);
}

@ApiOperation({
summary: '카카오 로그인 요청',
description: 'accessToken을 받아 카카오 로그인을 요청합니다.',
})
@Post('kakao')
async createOneWithKakao(@Body() kakaoLoginRequest: KakaoLoginRequest) {
return this.oauthService.createOneWithKakao(kakaoLoginRequest);
}
}
63 changes: 23 additions & 40 deletions src/auth/oauth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ export class OAuthService {
) {}

// OAuth Login
async oauthLogin(email: string): Promise<LoginOutput> {
async oauthLogin(email: string, provider: PROVIDER): Promise<LoginOutput> {
try {
const user: User = await this.userRepository.findOneByOrFail({ email });
const user: User = await this.userRepository.findOneByOrFail({
email,
provider,
});
if (user) {
const payload: Payload = this.jwtService.createPayload(
user.email,
Expand Down Expand Up @@ -98,9 +101,12 @@ export class OAuthService {
throw new BadRequestException('Please Agree to share your email');
}

const user = await this.userRepository.findOneByEmail(email);
const user = await this.userRepository.findOneByEmailAndProvider(
email,
PROVIDER.KAKAO,
);
if (user) {
return this.oauthLogin(user.email);
return this.oauthLogin(user.email, PROVIDER.KAKAO);
}

// 회원가입인 경우 기본 카테고리 생성 작업 진행
Expand All @@ -115,51 +121,25 @@ export class OAuthService {
await this.userRepository.createOne(newUser);
await this.categoryRepository.createDefaultCategories(newUser);

return this.oauthLogin(newUser.email);
return this.oauthLogin(newUser.email, PROVIDER.KAKAO);
} catch (e) {
throw e;
}
}

async createOneWithKakao({ authorizationToken }: KakaoLoginDto) {
const { userInfo } =
await this.oauthUtil.getKakaoUserInfo(authorizationToken);

const email = userInfo.kakao_account.email;
if (!email) {
throw new BadRequestException('Please Agree to share your email');
}

const user = await this.userRepository.findOneByEmail(email);

if (user) {
return this.oauthLogin(user.email);
}

// 회원가입인 경우 기본 카테고리 생성 작업 진행
const newUser = User.of({
email,
name: userInfo.kakao_account.profile.nickname,
profileImage: userInfo.kakao_account.profile?.profile_image_url,
password: this.encodePasswordFromEmail(email, process.env.KAKAO_JS_KEY),
provider: PROVIDER.KAKAO,
});

await this.userRepository.createOne(newUser);
await this.categoryRepository.createDefaultCategories(newUser);
return this.oauthLogin(newUser.email);
}

// Login with Google account info
async googleOauth({
email,
name,
picture,
}: googleUserInfo): Promise<LoginOutput> {
const user = await this.userRepository.findOneByEmail(email);
const user = await this.userRepository.findOneByEmailAndProvider(
email,
PROVIDER.GOOGLE,
);

if (user) {
return this.oauthLogin(user.email);
return this.oauthLogin(user.email, PROVIDER.GOOGLE);
}

// 회원가입인 경우 기본 카테고리 생성 작업 진행
Expand All @@ -177,7 +157,7 @@ export class OAuthService {
await this.userRepository.createOne(newUser);
await this.categoryRepository.createDefaultCategories(newUser);

return this.oauthLogin(newUser.email);
return this.oauthLogin(newUser.email, PROVIDER.GOOGLE);
}

private encodePasswordFromEmail(email: string, key?: string): string {
Expand Down Expand Up @@ -225,10 +205,13 @@ export class OAuthService {

const { sub: id, email } = this.jwtService.decode(data.id_token);

const user = await this.userRepository.findOneByEmail(email);
const user = await this.userRepository.findOneByEmailAndProvider(
email,
PROVIDER.APPLE,
);

if (user) {
return this.oauthLogin(user.email);
return this.oauthLogin(user.email, PROVIDER.APPLE);
}

const newUser = User.of({
Expand All @@ -244,6 +227,6 @@ export class OAuthService {
await this.userRepository.createOne(newUser);
await this.categoryRepository.createDefaultCategories(newUser);

return this.oauthLogin(newUser.email);
return this.oauthLogin(newUser.email, PROVIDER.APPLE);
}
}
4 changes: 2 additions & 2 deletions src/categories/category.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Module } from '@nestjs/common';
import { ContentsModule } from '../contents/contents.module';
import { CategoryService } from './category.service';
import { OpenaiModule } from '../openai/openai.module';
import { AiModule } from '../ai/openai.module';
import { UsersModule } from '../users/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Category } from './category.entity';
Expand All @@ -14,7 +14,7 @@ import { CategoryV2Controller } from './v2/category.v2.controller';
imports: [
TypeOrmModule.forFeature([Category]),
ContentsModule,
OpenaiModule,
AiModule,
UsersModule,
],
controllers: [CategoryController, CategoryV2Controller],
Expand Down
Loading
Loading