Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

教育資料のフィードバックの機能の実装 #51

Merged
merged 28 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
153eab8
🗃️ fix: Remove feedback model from schema.prisma
Z00One Mar 10, 2024
0dc3c72
🚚 refactor: Rename decorator from ApiAuthMetadata to ApiDefaultMetadata
Z00One Mar 10, 2024
b78afbe
🐛 fix: Fix error handling in User decorator
Z00One Mar 10, 2024
3c1e5da
♻️ refactor: Refactor material controller
Z00One Mar 10, 2024
47ad44e
♻️ refactor: Change method's name from delete to remove
Z00One Mar 10, 2024
7c6d5ae
♻️ refactor: Changed the metadata decorator from ApiAuthMetadata to A…
Z00One Mar 10, 2024
d54aa72
♻️ refactor: Refactor langchain service in prompt
Z00One Mar 10, 2024
d547795
🐛 fix: Fix referCreate method call
Z00One Mar 10, 2024
42cc17a
🚚 refactor: Move to modules from modules/prompt
Z00One Mar 11, 2024
2dc19d0
🚚 refactor: Change the import path
Z00One Mar 11, 2024
954957f
🗃️ feat: Add created_at field to Refer model
Z00One Mar 19, 2024
9ab399a
➕ chore: add @langchain/anthropic
Z00One Mar 19, 2024
eb5524c
✨ feat: Implement MaterialFeedbackRepository
Z00One Mar 19, 2024
d3aa096
✨ feat: Implement Langchain service for feedback on documents
Z00One Mar 19, 2024
49455b2
✨ feat: Implement Langchain module
Z00One Mar 19, 2024
fadb989
✨ feat: Implement FileService for getting files from s3
Z00One Mar 19, 2024
b563b62
✨ feat: Implement FileModule
Z00One Mar 19, 2024
05d406a
✨ feat: Implement MaterialFeedbackService
Z00One Mar 19, 2024
46f69b9
✨ feat: Implement MaterialFeedbackController
Z00One Mar 19, 2024
cbab837
✅ feat: Add material controller test code
Z00One Mar 19, 2024
b2cd65e
✨ feat: Add CreateMaterialFeedbackDto
Z00One Mar 19, 2024
928055e
✨ feat: Add MaterialFeedBackEntity
Z00One Mar 19, 2024
171f778
✨ feat: Add KeywordEntity
Z00One Mar 19, 2024
bc0a061
✨ feat: Add pageFeedbackExamples for fewshotprompting in the process …
Z00One Mar 19, 2024
24abca2
✨ feat: Implement MaterialFeedbackModule
Z00One Mar 19, 2024
68e96fc
✨ feat: Add MaterialFeedbackModule
Z00One Mar 19, 2024
6d337d1
🔐 feat: Add anthropicApiKey to config
Z00One Mar 19, 2024
7b67bb9
✨ feat: Add getByMid method
Z00One Mar 19, 2024
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
91 changes: 91 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 @@ -21,6 +21,7 @@
},
"dependencies": {
"@aws-sdk/client-s3": "^3.515.0",
"@langchain/anthropic": "^0.1.7",
"@langchain/community": "0.0.32",
"@langchain/openai": "0.0.14",
"@nestjs/common": "^10.0.0",
Z00One marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
Warnings:

- You are about to drop the `Feedback` table. If the table is not empty, all the data it contains will be lost.

*/
-- DropForeignKey
ALTER TABLE "Feedback" DROP CONSTRAINT "Feedback_m_id_fkey";

-- DropTable
DROP TABLE "Feedback";
Z00One marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Refer" ADD COLUMN "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
Z00One marked this conversation as resolved.
Show resolved Hide resolved
11 changes: 1 addition & 10 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ model Material {
updated_at DateTime @updatedAt
quiz_deadline DateTime?

feedbacks Feedback[]
prompts Prompt[]
quizs Quiz[]

Expand All @@ -64,6 +63,7 @@ model Refer {
id BigInt @id @default(autoincrement())
page Int
content String
created_at DateTime @default(now())

f_id BigInt
file File @relation(fields: [f_id], references: [f_id], onDelete: Cascade)
Expand All @@ -81,15 +81,6 @@ model FileFeedback {
file File @relation(fields: [f_id], references: [f_id], onDelete: Cascade)
}

model Feedback {
id BigInt @id @default(autoincrement())
content String
created_at DateTime? @default(now())
m_id BigInt

material Material @relation(fields: [m_id], references: [id], onDelete: Cascade)
}

model Prompt {
id BigInt @id @default(autoincrement())
usage BigInt @default(0)
Z00One marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
1 change: 1 addition & 0 deletions src/common/configs/config.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ export interface S3Config {
export interface LangchainConfig {
openAIApiKey: string;
localStoragePath: string;
anthropicApiKey: string;
}
2 changes: 2 additions & 0 deletions src/common/configs/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ const config: Config = {
localStoragePath: process.env.LOCAL_STORAGE_PATH
? `${process.env.LOCAL_STORAGE_PATH}/vector-store`
: '/c/vector-store',
anthropicApiKey:
process.env.ANTHROPIC_API_KEY || 'anthropicApiKey',
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,21 @@ import { applyDecorators } from '@nestjs/common';
import {
ApiBearerAuth,
ApiExtraModels,
ApiInternalServerErrorResponse,
ApiTags,
ApiUnauthorizedResponse,
} from '@nestjs/swagger';

export const ApiAuthMetadata = (tag: string) => {
export const ApiDefaultMetadata = (tag: string) => {
return applyDecorators(
ApiTags(tag),
ApiBearerAuth('Authorization'),
ApiUnauthorizedResponse({
description: '認証が必要です。',
}),
ApiInternalServerErrorResponse({
description: 'サーバーエラー',
}),
ApiExtraModels(ResponseFormat),
);
};
4 changes: 1 addition & 3 deletions src/common/decorators/user.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ export const User = createParamDecorator(
try {
return BigInt(request.user);
} catch {
throw new InternalServerErrorException(
'User ID is not valid.',
);
throw new InternalServerErrorException();
}
},
);
2 changes: 2 additions & 0 deletions src/modules/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { APP_GUARD } from '@nestjs/core';
import { AuthGuard } from '@common/guards/auth.guard';
import { JwtModule } from '@nestjs/jwt';
import { SecurityConfig } from '@common/configs/config.interface';
import { MaterialFeedbackModule } from '@modules/material-feedback/material-feedback.module';

@Module({
imports: [
Expand All @@ -42,6 +43,7 @@ import { SecurityConfig } from '@common/configs/config.interface';
}),
MaterialModule,
PromptModule,
MaterialFeedbackModule,
],
controllers: [AppController],
providers: [
Expand Down
11 changes: 11 additions & 0 deletions src/modules/material-feedback/dto/create.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class CreateMaterialFeedbackDto {
@IsNotEmpty()
@IsString()
@ApiProperty({
description: 'フィードバックの内容',
})
content: string;
}
9 changes: 9 additions & 0 deletions src/modules/material-feedback/entity/feedback.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ApiProperty } from '@nestjs/swagger';

export class MaterialFeedBackEntity {
@ApiProperty()
id: bigint;

@ApiProperty()
content: string;
}
13 changes: 13 additions & 0 deletions src/modules/material-feedback/entity/keyword.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ApiProperty } from '@nestjs/swagger';

export class KeywordEntity {
@ApiProperty()
page: bigint;

@ApiProperty({
example: ['구글', '앤스로픽', 'AI'],
type: 'array',
isArray: true,
})
keywords: string[];
}
8 changes: 8 additions & 0 deletions src/modules/material-feedback/file/file.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { FileService } from './file.service';

@Module({
providers: [FileService],
exports: [FileService],
})
export class FileModule {}
63 changes: 63 additions & 0 deletions src/modules/material-feedback/file/file.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import {
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import {
S3Client,
GetObjectCommand,
} from '@aws-sdk/client-s3';
import { AwsConfig } from '@common/configs/config.interface';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class FileService {
private readonly s3Client: S3Client;
private readonly awsConfig: AwsConfig;

constructor(private configService: ConfigService) {
this.awsConfig =
this.configService.get<AwsConfig>('aws');

this.s3Client = new S3Client({
region: this.awsConfig.region,
credentials: {
accessKeyId: this.awsConfig.s3.accessKey,
secretAccessKey: this.awsConfig.s3.secretAccessKey,
},
});
}

/**
* S3からファイルを取得
* @param path - ファイルのパス
* @returns - 取得したファイルのBlob
*/
async getFileFromS3(path: string) {
const Key = path.replace(
`${this.awsConfig.cloudfront}`,
'',
);

const command = new GetObjectCommand({
Bucket: this.awsConfig.s3.bucket,
Key,
});
try {
const { Body } = await this.s3Client.send(command);

const bodyContents = await Body.transformToString(
'binary',
);
const bodyBuffer = Buffer.from(
bodyContents,
'binary',
);

return new Blob([bodyBuffer]);
} catch {
throw new InternalServerErrorException(
'Failed to load file from S3',
);
}
}
}
35 changes: 35 additions & 0 deletions src/modules/material-feedback/langchain/feedback.example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export const FeedbackExamples = {
MATERIAL: 'material',
PART_RELEVANT_TO_THE_QUESTIONS:
'Areas with many questions in the material',
};

export const pageFeedbackExamples = [
{
input: `${FeedbackExamples.MATERIAL}: "10 페이지의 내용 - 구글, 앤스로픽에 20억 달러 투자
n 구글이 앤스로픽에 최대 20억 달러 투자에 합의하고 5억 달러를 우선 투자
n 3대 클라우드 사업자인 구글, 마이크로소프트, 아마존은 앤스로픽 및 오픈AI와 협력 확대
KEY Contents
£ 구글, 앤스로픽에 최대 20억 달러 투자 합의 및 클라우드 서비스 제공
∙ 구글은 2023년 2월 앤스로픽에 이미 5억 5,000만 달러를 투자
∙ 앤스로픽은 구글의 클라우드 서비스 사용을 위해 4년간 30억 달러 규모의 계약 체결
∙ 앤스로픽은 챗GPT의 대항마 ‘클로드(Claude)’ LLM을 개발
∙ 구글은 차세대 AI 모델 ‘제미니(Gemini)’를 포함한 자체 AI 시스템 개발에 수십억 달러 투자
☞ 출처 : The Wall Street Journal, Google Commits $2 Billion in Funding to AI Startup Anthropic, 2023.10.27.
Bloomberg, AI Startup Anthropic to Use Google Chips in Expanded Partnership, 2023.11.09."

${FeedbackExamples.PART_RELEVANT_TO_THE_QUESTIONS}: "
∙ 구글은 챗GPT의 기반 기술과 직접 경쟁할 수 있는 차세대 LLM ‘제미니(Gemini)’를 포함한 자체 AI
∙ 구글은 2023년 2월 앤스로픽에 이미 5억 5,000만 달러를 투자 ∙
n구글이 앤스로픽에 최대 20억 달러 투자에 합의하고 5억 달러를 우선 투자 ∙
∙ 구글은 앤스로픽 외에도 AI 동영상 제작 도구를 개발하는 런웨이(Runway)와 오픈소스 소프트웨어 기업 허깅 페이스(Hugging Face)에도 투자"`,
output: `"자료의 10페이지의 내용에 대해서 개선사항이 있습니다. 구글의 차세대 LLM, 제미니(Gemini) 개발 관련 정보 보강
현재 제공된 정보는 구글이 챗GPT와 경쟁할 수 있는 차세대 LLM인 제미니(Gemini)를 개발 중이라는 사실만 언급하고 있습니다. 이 부분에 대해 추가적인 설명을 포함시켜 독자들이 제미니의 주요 특징, 예상되는 사용 사례, 개발 배경 및 목표 등을 이해할 수 있도록 하는 것이 좋습니다. 예를 들어, 제미니의 기술적 혁신, 차별화된 기능, 출시 일정 등에 대한 정보를 포함시킬 수 있습니다.",
"구글의 앤스로픽 및 다른 기업들에 대한 투자 정보 상세화
구글이 앤스로픽에 투자한 배경, 목적 및 구체적인 기대효과에 대해 자세히 설명하는 것이 도움이 될 것입니다. 또한, 아마존의 투자 계획과 비교하여 구글의 전략적 접근 방식이 어떻게 다른지 분석하는 내용을 추가하는 것도 유익할 것입니다.
런웨이(Runway)와 허깅 페이스(Hugging Face)에 대한 투자 역시 마찬가지로, 이들 기업이 개발하는 기술의 특징과 구글의 투자로 인해 기대되는 시너지 효과에 대해 상세하게 설명하는 것이 좋습니다.",
"정보 구조 및 표현의 명확성 강화
각 투자 사례별로 별도의 소제목을 사용하여 구분하고, 각 소제목 아래에서는 투자의 세부 사항, 목적, 기대 효과 등을 명확하고 간결하게 서술하는 것이 좋습니다. 이를 통해 독자가 각 투자 사례의 핵심 내용을 빠르게 파악할 수 있도록 합니다.
시각적 요소를 활용하는 것도 고려할 수 있습니다. 예를 들어, 투자 금액, 투자 대상 기업, 투자 목적 등을 요약한 표나 인포그래픽을 추가하여 정보의 이해와 가독성을 높일 수 있습니다."`,
},
];
8 changes: 8 additions & 0 deletions src/modules/material-feedback/langchain/langchain.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { LangchainService } from './langchain.service';

@Module({
providers: [LangchainService],
exports: [LangchainService],
})
export class LangchainModule {}
Loading
Loading