-
Notifications
You must be signed in to change notification settings - Fork 2
Update knowledge.py #15
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
U2SG
wants to merge
2
commits into
dev/main
Choose a base branch
from
U2SG-patch-1
base: dev/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
2 commits
Select commit
Hold shift + click to select a range
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 |
|---|---|---|
|
|
@@ -2,6 +2,8 @@ | |
| import logging | ||
| from typing import TYPE_CHECKING, List, Optional, Dict, Any | ||
|
|
||
| import httpx | ||
|
|
||
| if TYPE_CHECKING: | ||
| from config.application.knowledge_config import KnowledgeConfig | ||
|
|
||
|
|
@@ -24,8 +26,19 @@ def __init__(self, config: 'KnowledgeConfig'): | |
| # Semaphore to control concurrent indexing operations | ||
| max_concurrent_indexing = config.max_concurrent_indexing | ||
| self.indexing_semaphore = asyncio.Semaphore(max_concurrent_indexing) | ||
|
|
||
| # Semaphore to control concurrent indexing operations | ||
| max_concurrent_indexing = config.max_concurrent_indexing | ||
| self.indexing_semaphore = asyncio.Semaphore(max_concurrent_indexing) | ||
|
|
||
| def upload_file(self, file: UploadFile, user_id: uuid.UUID) -> str: | ||
| def upload_file( | ||
| self, | ||
| file: UploadFile, | ||
| user_id: uuid.UUID, | ||
| callback_url: str | None = None, | ||
| job_id: str | None = None, | ||
| callback_secret: str | None = None, | ||
| ) -> Dict[str, Any]: | ||
| try: | ||
| doc_id = self.file_storage.upload_file( | ||
| filename=file.filename, | ||
|
|
@@ -34,43 +47,151 @@ def upload_file(self, file: UploadFile, user_id: uuid.UUID) -> str: | |
| content_type=file.content_type | ||
| ) | ||
| # Start indexing in background (fire-and-forget) | ||
| self._start_background_indexing(doc_id) | ||
| job_identifier = job_id or str(uuid.uuid4()) | ||
| logger.info( | ||
| "Upload accepted for file_id=%s (job_id=%s, callback_url=%s)", | ||
| doc_id, | ||
| job_identifier, | ||
| callback_url, | ||
| ) | ||
| self._start_background_indexing( | ||
| doc_id, | ||
| callback_url, | ||
| job_identifier, | ||
| callback_secret, | ||
| ) | ||
| logger.info(f"File {file.filename} uploaded with ID {doc_id}, indexing started in background") | ||
| return doc_id | ||
| return { | ||
| "file_id": doc_id, | ||
| "job_id": job_identifier, | ||
| } | ||
|
|
||
| except Exception as e: | ||
| logger.error(e) | ||
| raise | ||
|
|
||
| def _start_background_indexing(self, doc_id: str): | ||
| def _start_background_indexing( | ||
| self, | ||
| doc_id: str, | ||
| callback_url: str | None = None, | ||
| job_id: str | None = None, | ||
| callback_secret: str | None = None, | ||
| ): | ||
| """Start background indexing task safely""" | ||
| try: | ||
| # Try to get the current event loop | ||
| loop = asyncio.get_running_loop() | ||
| # If we're in an async context, create the task | ||
| loop.create_task(self._index_file_background(doc_id)) | ||
| loop.create_task( | ||
| self._index_file_background( | ||
| doc_id, | ||
| callback_url, | ||
| job_id, | ||
| callback_secret, | ||
| ) | ||
| ) | ||
| except RuntimeError: | ||
| # No event loop running, start a new one in a thread | ||
| import threading | ||
| def run_async(): | ||
| asyncio.run(self._index_file_background(doc_id)) | ||
| asyncio.run( | ||
| self._index_file_background( | ||
| doc_id, | ||
| callback_url, | ||
| job_id, | ||
| callback_secret, | ||
| ) | ||
| ) | ||
| thread = threading.Thread(target=run_async, daemon=True) | ||
| thread.start() | ||
|
|
||
| async def _index_file_background(self, doc_id: str): | ||
| async def _index_file_background( | ||
| self, | ||
| doc_id: str, | ||
| callback_url: str | None = None, | ||
| job_id: str | None = None, | ||
| callback_secret: str | None = None, | ||
| ): | ||
| """Background task for indexing files with semaphore control""" | ||
| callback_payload: Dict[str, Any] | None = None | ||
| status: str = "processing" | ||
| async with self.indexing_semaphore: | ||
| try: | ||
| logger.info(f"Starting background indexing for file_id: {doc_id} (semaphore acquired)") | ||
| result = await self.file_index.index_file(doc_id) | ||
| if result.get("success"): | ||
| success = bool(result.get("success")) | ||
| error_message = result.get("error_message") | ||
| status = "succeeded" if success else "failed" | ||
| metadata = { | ||
| key: value | ||
| for key, value in (result or {}).items() | ||
| if key not in {"success", "error_message"} | ||
| } if isinstance(result, dict) else {} | ||
| if success: | ||
| logger.info(f"Background indexing completed successfully for file_id: {doc_id}") | ||
| else: | ||
| logger.error(f"Background indexing failed for file_id: {doc_id}, error: {result.get('error_message')}") | ||
| logger.error(f"Background indexing failed for file_id: {doc_id}, error: {error_message}") | ||
| callback_payload = { | ||
| "file_id": doc_id, | ||
| "rag_file_id": doc_id, | ||
| "success": success, | ||
| "status": status, | ||
| "error": None if success else error_message, | ||
| "metadata": metadata or None, | ||
| } | ||
| except Exception as e: | ||
| logger.error(f"Background indexing failed for file_id: {doc_id}, exception: {str(e)}") | ||
| status = "failed" | ||
| callback_payload = { | ||
| "file_id": doc_id, | ||
| "rag_file_id": doc_id, | ||
| "success": False, | ||
| "status": status, | ||
| "error": str(e), | ||
| "metadata": None, | ||
| } | ||
| finally: | ||
| logger.debug(f"Background indexing semaphore released for file_id: {doc_id}") | ||
| if callback_url and callback_payload is not None: | ||
| payload_with_job = dict(callback_payload) | ||
|
Collaborator
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. What's the purpose of this line? To create a hard copy? if so why not directly use copy() |
||
| payload_with_job["job_id"] = job_id or str(uuid.uuid4()) | ||
| await self._send_callback( | ||
| callback_url, | ||
| payload_with_job, | ||
| callback_secret=callback_secret, | ||
| ) | ||
|
|
||
| async def _send_callback( | ||
|
Collaborator
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.
|
||
| self, | ||
| callback_url: str, | ||
| payload: Dict[str, Any], | ||
| callback_secret: str | None = None, | ||
| ): | ||
| """Send callback notification with indexing results.""" | ||
| try: | ||
| headers = {} | ||
| if callback_secret: | ||
| headers["X-Callback-Secret"] = callback_secret | ||
| async with httpx.AsyncClient(timeout=10.0) as client: | ||
| response = await client.post(callback_url, json=payload, headers=headers) | ||
| response.raise_for_status() | ||
| logger.info( | ||
| "Sent callback for job_id=%s file_id=%s to %s (status=%s)", | ||
| payload.get("job_id"), | ||
| payload.get("file_id"), | ||
| callback_url, | ||
| response.status_code, | ||
| ) | ||
| except httpx.HTTPStatusError as e: | ||
| logger.error( | ||
| "Callback endpoint returned error for job_id=%s file_id=%s (status=%s, body=%s)", | ||
| payload.get("job_id"), | ||
| payload.get("file_id"), | ||
| e.response.status_code if e.response else "unknown", | ||
| e.response.text if e.response else "no-body", | ||
| ) | ||
| except Exception as e: | ||
| logger.error(f"Failed to send callback to {callback_url}: {e}") | ||
|
|
||
| def get_file(self, doc_id: str, user_id: uuid.UUID) -> Response: | ||
| metadata = self.file_storage.get_file_metadata(doc_id) | ||
|
|
||
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.
what's the difference b/t file_id and rag_file_id?