-
Notifications
You must be signed in to change notification settings - Fork 1
[Feat] RAG 파이프라인에 Reranker 로직 구현 #200
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ff484e1
[Feat] #199 Cohere 관련 환경변수 추가
jeong1112 284b23e
[Feat] #199 Cohere 호출용 요청, 응답 DTO 구현
jeong1112 23d110d
[Feat] #199 Cohere Rerank API 호출 로직 구현
jeong1112 4774af1
[Feat] #199 정책 문서 Retrieval 과정에서 Reranker 로직 추가
jeong1112 9098e47
[Refactor] #199 수정된 Member 정보에 맞게 Context 수정
jeong1112 ef3272b
[Chore] #199 로그 삭제
jeong1112 1d8087b
[Chore] #199 중복되는 컨텍스트 출력 제거
jeong1112 9c926fe
[Chore] #199 Cohere API Fallback 시 리스트 사이즈 조절
jeong1112 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
src/main/java/org/sopt/kareer/global/external/cohere/dto/request/CohereRerankRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package org.sopt.kareer.global.external.cohere.dto.request; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public record CohereRerankRequest( | ||
| String model, | ||
| String query, | ||
| List<String> documents, | ||
| @JsonProperty("top_n") | ||
| Integer topN | ||
| ) {} |
16 changes: 16 additions & 0 deletions
16
src/main/java/org/sopt/kareer/global/external/cohere/dto/response/CohereRerankResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package org.sopt.kareer.global.external.cohere.dto.response; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| public record CohereRerankResponse( | ||
| String id, | ||
| List<Result> results | ||
| ) { | ||
| public record Result( | ||
| Integer index, | ||
| @JsonProperty("relevance_score") | ||
| Double relevanceScore | ||
| ) {} | ||
| } |
15 changes: 15 additions & 0 deletions
15
src/main/java/org/sopt/kareer/global/external/cohere/properties/CohereProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| package org.sopt.kareer.global.external.cohere.properties; | ||
|
|
||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
|
||
| @ConfigurationProperties(prefix = "cohere") | ||
| public record CohereProperties( | ||
| String apiKey, | ||
| String baseUrl, | ||
| Rerank rerank | ||
| ) { | ||
| public record Rerank( | ||
| String model, | ||
| int topN | ||
| ) {} | ||
| } |
74 changes: 74 additions & 0 deletions
74
src/main/java/org/sopt/kareer/global/external/cohere/service/CohereRerankClient.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| package org.sopt.kareer.global.external.cohere.service; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.sopt.kareer.global.external.cohere.dto.request.CohereRerankRequest; | ||
| import org.sopt.kareer.global.external.cohere.dto.response.CohereRerankResponse; | ||
| import org.sopt.kareer.global.external.cohere.properties.CohereProperties; | ||
| import org.springframework.ai.document.Document; | ||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.MediaType; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.client.RestClient; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| @Slf4j | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class CohereRerankClient { | ||
|
|
||
| private final CohereProperties cohereProperties; | ||
|
|
||
| private RestClient restClient() { | ||
| return RestClient.builder() | ||
| .baseUrl(cohereProperties.baseUrl()) | ||
| .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + cohereProperties.apiKey()) | ||
| .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) | ||
| .build(); | ||
| } | ||
|
|
||
| public List<Document> rerank(String query, List<Document> documents, Integer topN) { | ||
| if (documents == null || documents.isEmpty()) { | ||
| return List.of(); | ||
| } | ||
|
|
||
| List<String> serializedDocs = documents.stream() | ||
| .map(Document::getText) | ||
| .toList(); | ||
|
|
||
| CohereRerankRequest request = new CohereRerankRequest( | ||
| cohereProperties.rerank().model(), | ||
| query, | ||
| serializedDocs, | ||
| topN != null | ||
| ? Math.min(topN, documents.size()) | ||
| : Math.min(cohereProperties.rerank().topN(), documents.size()) | ||
| ); | ||
|
|
||
| try { | ||
| CohereRerankResponse response = restClient() | ||
| .post() | ||
| .uri("/v2/rerank") | ||
| .body(request) | ||
| .retrieve() | ||
| .body(CohereRerankResponse.class); | ||
|
|
||
| if (response == null || response.results() == null || response.results().isEmpty()) { | ||
| log.warn("Cohere rerank response empty. query={}", query); | ||
| return documents; | ||
| } | ||
|
|
||
| List<Document> reranked = new ArrayList<>(); | ||
| for (CohereRerankResponse.Result result : response.results()) { | ||
| reranked.add(documents.get(result.index())); | ||
| } | ||
| return reranked; | ||
|
Comment on lines
+63
to
+67
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Cohere 응답의 index 값 유효성 검증 필요 Cohere API 응답의 🛡️ 인덱스 유효성 검증 추가 List<Document> reranked = new ArrayList<>();
for (CohereRerankResponse.Result result : response.results()) {
+ if (result.index() < 0 || result.index() >= documents.size()) {
+ log.warn("Cohere returned invalid index: {}. Skipping.", result.index());
+ continue;
+ }
reranked.add(documents.get(result.index()));
}
return reranked;🤖 Prompt for AI Agents |
||
|
|
||
| } catch (Exception e) { | ||
| log.error("Cohere rerank failed. fallback to original order. query={}", query, e); | ||
| return documents; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
응답이 비어있을 때의 fallback 동작 확인 필요
응답이 null이거나 비어있을 때 원본
documents(candidatePoolTopK 크기)를 그대로 반환합니다. 이 경우에도 호출부에서 기대하는topN크기와 불일치가 발생합니다.PolicyDocumentRetriever에서 언급한 것처럼 일관된 크기 처리가 필요합니다.🤖 Prompt for AI Agents