-
Notifications
You must be signed in to change notification settings - Fork 115
feat(RFC): implement candidate retrieval checkpoints D1 and D2 #944
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
Open
Abhijeet2409
wants to merge
4
commits into
OWASP:main
Choose a base branch
from
Abhijeet2409:feature/candidate-retrieval-d1-d2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
feefa3d
feat: add candidate retrieval checkpoints D1 & D2
Abhijeet2409 5d098e8
fix: address lint test issues
Abhijeet2409 9232bbb
Merge branch 'main' into feature/candidate-retrieval-d1-d2
Abhijeet2409 73cb49d
Merge branch 'main' into feature/candidate-retrieval-d1-d2
Abhijeet2409 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| import re | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class CandidateCRE: | ||
| """Represents a single CRE candidate match for a CheatsheetRecord.""" | ||
|
|
||
| cre_id: str | ||
| name: str | ||
| description: str | ||
| score: float | ||
|
|
||
| def __post_init__(self): | ||
| for field_name, value in [("cre_id", self.cre_id), ("name", self.name)]: | ||
| if not isinstance(value, str) or not value.strip(): | ||
| raise ValueError( | ||
| f"CandidateCRE: field '{field_name}' must be a non-empty string" | ||
| ) | ||
|
|
||
| # description is optional in CRE DB model, empty string allowed. | ||
| if not isinstance(self.description, str): | ||
| raise ValueError("CandidateCRE: field 'description' must be a string") | ||
|
|
||
| if not re.match(r"\d{3}-\d{3}", self.cre_id): | ||
| raise ValueError( | ||
| f"CandidateCRE: field 'cre_id' must match pattern 'NNN-NNN', got {self.cre_id!r}" | ||
| ) | ||
|
|
||
| if not isinstance(self.score, float): | ||
| raise ValueError("CandidateCRE: field 'score' must be a float") | ||
|
|
||
| if not (0.0 <= self.score <= 1.0): | ||
| raise ValueError( | ||
| f"CandidateCRE: field 'score' must be between 0.0 and 1.0, got {self.score}" | ||
| ) | ||
|
|
||
| self.cre_id = self.cre_id.strip() | ||
| self.name = self.name.strip() | ||
| self.description = self.description.strip() | ||
69 changes: 69 additions & 0 deletions
69
application/utils/external_project_parsers/parsers/cheatsheet_cre_retriever.py
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,69 @@ | ||
| import numpy as np | ||
|
|
||
| from scipy import sparse | ||
| from sklearn.metrics.pairwise import cosine_similarity | ||
| from typing import List | ||
|
|
||
| from application.database import db | ||
| from application.defs.candidate_cre_defs import CandidateCRE | ||
| from application.defs.cheatsheet_defs import CheatsheetRecord | ||
| from application.defs import cre_defs | ||
| from application.prompt_client import prompt_client | ||
|
|
||
|
|
||
| def retrieve_candidate_cres( | ||
| record: CheatsheetRecord, | ||
| cache: db.Node_collection, | ||
| ph: prompt_client.PromptHandler, | ||
| top_k: int = 20, | ||
| ) -> List[CandidateCRE]: | ||
| """Retrieve top-k CRE candidates for a CheatsheetRecord using embedding similarity. | ||
|
|
||
| Args: | ||
| record: the cheatsheet record to find CRE candidates for. | ||
| cache: database instance for retrieving CRE embeddings. | ||
| ph: PromptHandler instance for generating text embeddings. | ||
| top_k: number of top candidates to return, defaults to 20. | ||
|
|
||
| Returns: | ||
| List of CandidateCRE objects sorted descending by similarity score. | ||
| """ | ||
| # build query text from record summary and headings | ||
| query_text = record.summary + " " + " ".join(record.headings) | ||
|
|
||
| # embed query text via PromptHandler | ||
| query_vector = ph.get_text_embeddings(query_text) | ||
|
|
||
| # fetch all pre-stored CRE vectors from DB | ||
| db_cre_embeddings = cache.get_embeddings_by_doc_type(cre_defs.Credoctypes.CRE.value) | ||
|
|
||
| # build ordered lists of internal ids and their vectors | ||
| internal_ids = list(db_cre_embeddings.keys()) | ||
| cre_matrix = sparse.csr_matrix( | ||
| np.array(list(db_cre_embeddings.values())).astype(np.float64) | ||
| ) | ||
|
|
||
| # compute cosine similarity between query and all CRE vectors | ||
| query_array = sparse.csr_matrix( | ||
| np.array(query_vector).reshape(1, -1).astype(np.float64) | ||
| ) | ||
| similarities = cosine_similarity(query_array, cre_matrix)[0] | ||
|
|
||
| # get top-k indices sorted descending by score | ||
| top_k_indices = np.argsort(similarities)[::-1][:top_k] | ||
|
|
||
| # fetch full CRE objects and build CandidateCRE list | ||
| candidates = [] | ||
| for idx in top_k_indices: | ||
| internal_id = internal_ids[idx] | ||
| cre = cache.get_cre_by_db_id(internal_id) | ||
| candidates.append( | ||
| CandidateCRE( | ||
| cre_id=cre.id, | ||
| name=cre.name, | ||
| description=cre.description or "", | ||
|
Abhijeet2409 marked this conversation as resolved.
|
||
| score=float(similarities[idx]), | ||
| ) | ||
|
Abhijeet2409 marked this conversation as resolved.
|
||
| ) | ||
|
|
||
| return candidates | ||
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.
Uh oh!
There was an error while loading. Please reload this page.