-
-
Notifications
You must be signed in to change notification settings - Fork 272
event chunks created #1715
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
event chunks created #1715
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
570edb2
event chunks created
Dishant1804 eaa56a9
makefile changes
Dishant1804 229fd4a
checks and lint
Dishant1804 f67a88b
Merge branch 'main' into event_chunks
Rajgupta36 f529179
resuable code
Dishant1804 913e4b3
Merge branch 'main' into event_chunks
Dishant1804 45d8839
refactoring
Dishant1804 300cebd
Merge branch 'main' into event_chunks
arkid15r 4d2bd25
Update code
arkid15r c0247b1
Merge branch 'main' into pr/Dishant1804/1715
arkid15r 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| """AI utils.""" | ||
|
|
||
| import logging | ||
| import time | ||
| from datetime import UTC, datetime, timedelta | ||
|
|
||
| from apps.ai.common.constants import ( | ||
| DEFAULT_LAST_REQUEST_OFFSET_SECONDS, | ||
| MIN_REQUEST_INTERVAL_SECONDS, | ||
| ) | ||
| from apps.ai.models.chunk import Chunk | ||
|
|
||
| logger: logging.Logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def create_chunks_and_embeddings( | ||
| all_chunk_texts: list[str], | ||
| content_object, | ||
| openai_client, | ||
| ) -> list[Chunk]: | ||
| """Create chunks and embeddings from given texts using OpenAI embeddings. | ||
| Args: | ||
| all_chunk_texts (list[str]): List of text chunks to embed. | ||
| content_object: The object to associate the chunks with. | ||
| openai_client: Initialized OpenAI client instance. | ||
| Returns: | ||
| list[Chunk]: List of Chunk instances (not saved). | ||
| """ | ||
| try: | ||
| last_request_time = datetime.now(UTC) - timedelta( | ||
| seconds=DEFAULT_LAST_REQUEST_OFFSET_SECONDS | ||
| ) | ||
| time_since_last_request = datetime.now(UTC) - last_request_time | ||
|
|
||
| if time_since_last_request < timedelta(seconds=MIN_REQUEST_INTERVAL_SECONDS): | ||
| time.sleep(MIN_REQUEST_INTERVAL_SECONDS - time_since_last_request.total_seconds()) | ||
|
|
||
Dishant1804 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| response = openai_client.embeddings.create( | ||
| input=all_chunk_texts, | ||
| model="text-embedding-3-small", | ||
| ) | ||
|
|
||
| return [ | ||
| chunk | ||
| for text, embedding in zip( | ||
| all_chunk_texts, | ||
| [d.embedding for d in response.data], | ||
| strict=True, | ||
| ) | ||
| if ( | ||
| chunk := Chunk.update_data( | ||
| text=text, | ||
| content_object=content_object, | ||
| embedding=embedding, | ||
| save=False, | ||
| ) | ||
| ) | ||
| ] | ||
| except Exception: | ||
| logger.exception("OpenAI API error") | ||
| return [] | ||
Dishant1804 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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
133 changes: 133 additions & 0 deletions
133
backend/apps/ai/management/commands/ai_create_event_chunks.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,133 @@ | ||
| """A command to create chunks of OWASP event data for RAG.""" | ||
|
|
||
| import os | ||
|
|
||
| import openai | ||
| from django.core.management.base import BaseCommand | ||
|
|
||
| from apps.ai.common.constants import DELIMITER | ||
| from apps.ai.common.utils import create_chunks_and_embeddings | ||
| from apps.ai.models.chunk import Chunk | ||
| from apps.owasp.models.event import Event | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = "Create chunks for OWASP event data" | ||
|
|
||
| def add_arguments(self, parser): | ||
| parser.add_argument( | ||
| "--event", | ||
| type=str, | ||
| help="Process only the event with this key", | ||
| ) | ||
| parser.add_argument( | ||
| "--all", | ||
| action="store_true", | ||
| help="Process all the events", | ||
| ) | ||
| parser.add_argument( | ||
| "--batch-size", | ||
| type=int, | ||
| default=50, | ||
| help="Number of events to process in each batch", | ||
| ) | ||
|
|
||
| def handle(self, *args, **options): | ||
| if not (openai_api_key := os.getenv("DJANGO_OPEN_AI_SECRET_KEY")): | ||
| self.stdout.write( | ||
| self.style.ERROR("DJANGO_OPEN_AI_SECRET_KEY environment variable not set") | ||
| ) | ||
| return | ||
|
|
||
| self.openai_client = openai.OpenAI(api_key=openai_api_key) | ||
|
|
||
| if event := options["event"]: | ||
| queryset = Event.objects.filter(key=event) | ||
| elif options["all"]: | ||
| queryset = Event.objects.all() | ||
| else: | ||
| queryset = Event.upcoming_events() | ||
|
|
||
| if not (total_events := queryset.count()): | ||
| self.stdout.write("No events found to process") | ||
| return | ||
|
|
||
| self.stdout.write(f"Found {total_events} events to process") | ||
|
|
||
| batch_size = options["batch_size"] | ||
| for offset in range(0, total_events, batch_size): | ||
| batch_events = queryset[offset : offset + batch_size] | ||
Dishant1804 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| batch_chunks = [] | ||
| for event in batch_events: | ||
| batch_chunks.extend(self.handle_chunks(event)) | ||
|
|
||
| if batch_chunks: | ||
| Chunk.bulk_save(batch_chunks) | ||
| self.stdout.write(f"Saved {len(batch_chunks)} chunks") | ||
|
|
||
| self.stdout.write(f"Completed processing all {total_events} events") | ||
|
|
||
| def handle_chunks(self, event: Event) -> list[Chunk]: | ||
| """Create chunks from an event's data.""" | ||
| prose_content, metadata_content = self.extract_event_content(event) | ||
|
|
||
| all_chunk_texts = [] | ||
|
|
||
| if metadata_content.strip(): | ||
| all_chunk_texts.append(metadata_content) | ||
|
|
||
| if prose_content.strip(): | ||
| all_chunk_texts.extend(Chunk.split_text(prose_content)) | ||
|
|
||
| if not all_chunk_texts: | ||
| self.stdout.write(f"No content to chunk for event {event.key}") | ||
| return [] | ||
|
|
||
| return create_chunks_and_embeddings( | ||
| all_chunk_texts, | ||
| content_object=event, | ||
| openai_client=self.openai_client, | ||
| ) | ||
|
|
||
| def extract_event_content(self, event: Event) -> tuple[str, str]: | ||
| """Extract and separate prose content from metadata for an event. | ||
|
|
||
| Returns: | ||
| tuple[str, str]: (prose_content, metadata_content) | ||
|
|
||
| """ | ||
| prose_parts = [] | ||
| metadata_parts = [] | ||
|
|
||
| if event.description: | ||
| prose_parts.append(f"Description: {event.description}") | ||
|
|
||
| if event.summary: | ||
| prose_parts.append(f"Summary: {event.summary}") | ||
|
|
||
| if event.name: | ||
| metadata_parts.append(f"Event Name: {event.name}") | ||
|
|
||
| if event.category: | ||
| metadata_parts.append(f"Category: {event.get_category_display()}") | ||
|
|
||
| if event.start_date: | ||
| metadata_parts.append(f"Start Date: {event.start_date}") | ||
|
|
||
| if event.end_date: | ||
| metadata_parts.append(f"End Date: {event.end_date}") | ||
|
|
||
| if event.suggested_location: | ||
| metadata_parts.append(f"Location: {event.suggested_location}") | ||
|
|
||
| if event.latitude and event.longitude: | ||
| metadata_parts.append(f"Coordinates: {event.latitude}, {event.longitude}") | ||
|
|
||
| if event.url: | ||
| metadata_parts.append(f"Event URL: {event.url}") | ||
|
|
||
| return ( | ||
| DELIMITER.join(filter(None, prose_parts)), | ||
| DELIMITER.join(filter(None, metadata_parts)), | ||
| ) | ||
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.