-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(wren-ai-service): Add SQL Correction Service and API Endpoints #1420
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
9 commits
Select commit
Hold shift + click to select a range
ea1503f
feat: impl svc for sql correction
paopa c3f7b15
feat: add service into global container
paopa 46482d5
feat: impl sql correction router
paopa 24e8961
chore: modify the endpoint spec
paopa 665be7d
chore: refactor the code for service
paopa 79a8078
fix: invoking the error type
paopa ea2f419
feat: remove document class to avoid PydanticSchemaGenerationError
paopa 54ef445
feat: modify the interface spec for sql correction router and svc
paopa caa3f87
feat: simplify the output spec
paopa 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
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,113 @@ | ||
| import uuid | ||
| from dataclasses import asdict | ||
| from typing import Literal, Optional | ||
|
|
||
| from fastapi import APIRouter, BackgroundTasks, Depends | ||
| from pydantic import BaseModel | ||
|
|
||
| from src.globals import ( | ||
| ServiceContainer, | ||
| ServiceMetadata, | ||
| get_service_container, | ||
| get_service_metadata, | ||
| ) | ||
| from src.web.v1.services import SqlCorrectionService | ||
|
|
||
| router = APIRouter() | ||
|
|
||
|
|
||
| """ | ||
| SQL Correction Router | ||
|
|
||
| This router handles endpoints related to correcting invalid SQL queries. | ||
|
|
||
| Endpoints: | ||
| 1. POST /sql-corrections | ||
| - Initiates SQL correction process for invalid SQL queries | ||
| - Request body: PostRequest | ||
| { | ||
| "sql": "SELECT * FROM table", # Invalid SQL statement | ||
| "error": "Error message" # Error message | ||
| "project_id": "project-id" # Optional project ID | ||
| } | ||
| - Response: PostResponse | ||
| { | ||
| "event_id": "unique-uuid" # Unique identifier for tracking correction | ||
| } | ||
|
|
||
| 2. GET /sql-corrections/{event_id} | ||
| - Retrieves status and results of SQL correction process | ||
| - Path parameter: event_id (str) | ||
| - Response: GetResponse | ||
| { | ||
| "event_id": "unique-uuid", # Unique identifier | ||
| "status": "correcting" | "finished" | "failed", | ||
| "response": "corrected-sql", # Correction results (when status is "finished") | ||
| "error": { # Present only if status is "failed" | ||
| "code": "OTHERS", | ||
| "message": "Error description" | ||
| }, | ||
| "trace_id": "trace-id" # Optional trace ID for debugging | ||
| } | ||
|
|
||
| The SQL correction is an asynchronous process. The POST endpoint initiates the operation | ||
| and returns immediately with an event_id. The GET endpoint can then be used to check the | ||
| status and retrieve the results. | ||
|
|
||
| Usage: | ||
| 1. Send a POST request to start the correction process | ||
| 2. Use the returned event_id to poll the GET endpoint until status is "finished" or "failed" | ||
|
|
||
| Note: The actual processing is performed in the background using FastAPI's BackgroundTasks. | ||
| Results are cached with a TTL defined in the service configuration. | ||
| """ | ||
|
|
||
|
|
||
| class PostRequest(BaseModel): | ||
| sql: str | ||
| error: str | ||
| project_id: Optional[str] = None | ||
|
|
||
|
|
||
| class PostResponse(BaseModel): | ||
| event_id: str | ||
|
|
||
|
|
||
| @router.post("/sql-corrections") | ||
| async def correct( | ||
| request: PostRequest, | ||
| background_tasks: BackgroundTasks, | ||
| service_container: ServiceContainer = Depends(get_service_container), | ||
| service_metadata: ServiceMetadata = Depends(get_service_metadata), | ||
| ) -> PostResponse: | ||
| event_id = str(uuid.uuid4()) | ||
| service = service_container.sql_correction_service | ||
| service[event_id] = SqlCorrectionService.Event(event_id=event_id) | ||
|
|
||
| _request = SqlCorrectionService.CorrectionRequest( | ||
| event_id=event_id, **request.model_dump() | ||
| ) | ||
|
|
||
| background_tasks.add_task( | ||
| service.correct, | ||
| _request, | ||
| service_metadata=asdict(service_metadata), | ||
| ) | ||
| return PostResponse(event_id=event_id) | ||
|
|
||
|
|
||
| class GetResponse(BaseModel): | ||
| event_id: str | ||
| status: Literal["correcting", "finished", "failed"] | ||
| response: Optional[str] = None | ||
| error: Optional[dict] = None | ||
| trace_id: Optional[str] = None | ||
|
|
||
|
|
||
| @router.get("/sql-corrections/{event_id}") | ||
| async def get( | ||
| event_id: str, | ||
| container: ServiceContainer = Depends(get_service_container), | ||
| ) -> GetResponse: | ||
| event: SqlCorrectionService.Event = container.sql_correction_service[event_id] | ||
| return GetResponse(**event.model_dump()) |
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
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,122 @@ | ||
| import logging | ||
| from typing import Literal, Optional | ||
|
|
||
| from cachetools import TTLCache | ||
| from langfuse.decorators import observe | ||
| from pydantic import BaseModel | ||
|
|
||
| from src.core.pipeline import BasicPipeline | ||
| from src.utils import trace_metadata | ||
| from src.web.v1.services import MetadataTraceable | ||
|
|
||
| logger = logging.getLogger("wren-ai-service") | ||
|
|
||
|
|
||
| class SqlCorrectionService: | ||
| class Error(BaseModel): | ||
| code: Literal["OTHERS"] | ||
| message: str | ||
|
|
||
| class Event(BaseModel, MetadataTraceable): | ||
| event_id: str | ||
| status: Literal["correcting", "finished", "failed"] = "correcting" | ||
| response: Optional[str] = None | ||
| error: Optional["SqlCorrectionService.Error"] = None | ||
| trace_id: Optional[str] = None | ||
|
|
||
| def __init__( | ||
| self, | ||
| pipelines: dict[str, BasicPipeline], | ||
| maxsize: int = 1_000_000, | ||
| ttl: int = 120, | ||
| ): | ||
| self._pipelines = pipelines | ||
| self._cache: dict[str, self.Event] = TTLCache(maxsize=maxsize, ttl=ttl) | ||
|
|
||
| def _handle_exception( | ||
| self, | ||
| event_id: str, | ||
| error_message: str, | ||
| code: str = "OTHERS", | ||
| trace_id: Optional[str] = None, | ||
| ): | ||
| self._cache[event_id] = self.Event( | ||
| event_id=event_id, | ||
| status="failed", | ||
| error=self.Error(code=code, message=error_message), | ||
| trace_id=trace_id, | ||
| ) | ||
| logger.error(error_message) | ||
|
|
||
| class CorrectionRequest(BaseModel): | ||
| event_id: str | ||
| sql: str | ||
| error: str | ||
| project_id: Optional[str] = None | ||
|
|
||
| @observe(name="SQL Correction") | ||
| @trace_metadata | ||
| async def correct( | ||
| self, | ||
| request: CorrectionRequest, | ||
| **kwargs, | ||
| ): | ||
| logger.info(f"Request {request.event_id}: SQL Correction process is running...") | ||
| trace_id = kwargs.get("trace_id") | ||
|
|
||
| try: | ||
| _invalid = { | ||
| "sql": request.sql, | ||
| "error": request.error, | ||
| } | ||
|
|
||
| res = await self._pipelines["sql_correction"].run( | ||
| contexts=[], | ||
| invalid_generation_results=[_invalid], | ||
| project_id=request.project_id, | ||
| ) | ||
|
|
||
| post_process = res["post_process"] | ||
| valid = post_process["valid_generation_results"] | ||
| invalid = post_process["invalid_generation_results"] | ||
|
|
||
| if not valid: | ||
| error = invalid[0]["error"] | ||
| raise Exception( | ||
| f"Unable to correct the SQL query. Error: {error}. Please try with a different SQL query or simplify your request." | ||
| ) | ||
|
|
||
| corrected = valid[0]["sql"] | ||
|
|
||
| self._cache[request.event_id] = self.Event( | ||
| event_id=request.event_id, | ||
| status="finished", | ||
| trace_id=trace_id, | ||
| response=corrected, | ||
| ) | ||
|
|
||
| except Exception as e: | ||
| self._handle_exception( | ||
| request.event_id, | ||
| f"An error occurred during SQL correction: {str(e)}", | ||
| trace_id=trace_id, | ||
| ) | ||
|
|
||
| return self._cache[request.event_id].with_metadata() | ||
|
|
||
| def __getitem__(self, event_id: str) -> Event: | ||
| response = self._cache.get(event_id) | ||
|
|
||
| if response is None: | ||
| message = f"SQL Correction Event with ID '{event_id}' not found." | ||
| logger.exception(message) | ||
| return self.Event( | ||
| event_id=event_id, | ||
| status="failed", | ||
| error=self.Error(code="OTHERS", message=message), | ||
| ) | ||
|
|
||
| return response | ||
|
|
||
| def __setitem__(self, event_id: str, value: Event): | ||
| self._cache[event_id] = value | ||
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.