Skip to content
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

chore(wren-ai-service): allow regenerate sql using retrieved tables #1324

Merged
merged 1 commit into from
Feb 24, 2025

Conversation

cyyeh
Copy link
Member

@cyyeh cyyeh commented Feb 22, 2025

POST /v1/ask-feedbacks: now users need to pass parameter tables (type: [string], which means table names) to regenerate sql.

Summary by CodeRabbit

  • New Features

    • Introduced a comma-separated text input for specifying table names, giving users direct control over SQL query regeneration.
    • Integrated database schema context into the SQL generation process for more accurate query outputs.
    • Enabled feedback requests to include specific table details for improved context.
  • Improvements

    • Updated the feedback status indicator to display “searching” for clearer progress communication.
    • Enhanced document retrieval with improved filtering, leading to a more reliable experience.

@cyyeh cyyeh added module/ai-service ai-service related ci/ai-service ai-service related labels Feb 22, 2025
Copy link
Contributor

coderabbitai bot commented Feb 22, 2025

Walkthrough

This set of changes updates several core modules by modifying function signatures to include lists of tables, integrating database schema documents into SQL generation prompts, and simplifying control flows by removing redundant user correction functions. The retrieval pipelines now handle empty queries better and support filtering, while the document store adds a new asynchronous query method. Additionally, status values in feedback responses have been updated to better reflect processing stages.

Changes

Files Change Summary
wren-ai-service/demo/utils.py Updated on_click_regenerate_sql and ask_feedback signatures to accept a tables list; replaced a session state display with a comma-separated text input; removed unused user correction functions.
wren-ai-service/src/pipelines/generation/sql_regeneration.py Modified prompt templates by adding a “DATABASE SCHEMA” section; updated function signatures to include new parameters (documents and contexts) for enhanced SQL regeneration.
wren-ai-service/src/pipelines/retrieval/retrieval.py Adjusted the logic to check for empty queries; updated signatures for table_retrieval and run to incorporate a new tables parameter; simplified dbschema_retrieval.
wren-ai-service/src/providers/document_store/qdrant.py Introduced a new async method _query_by_filters that constructs filters for paginated Qdrant queries; updated the run method to conditionally call query-by-embedding or query-by-filters.
wren-ai-service/src/web/v1/routers/ask.py,
wren-ai-service/src/web/v1/services/ask.py
Updated the feedback processing by adding a tables attribute to the request; changed the status value from "understanding" to "searching"; revised SQL generation context to use retrieved table DDLs.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant UI as UI (on_click_regenerate_sql)
  participant S as AskFeedback Service
  participant R as Retrieval Pipeline
  participant Q as Qdrant Document Store
  participant G as SQL Regeneration Pipeline

  U->>UI: Provide comma-separated table names & click regenerate
  UI->>S: Call ask_feedback(tables, sql_generation_reasoning, sql)
  S->>R: Invoke Retrieval with tables and SQL reasoning
  R->>Q: Query documents using embedding or filters
  Q-->>R: Return retrieved documents
  R->>G: Pass retrieved table DDLs as contexts
  G-->>R: Return regenerated SQL query
  R-->>S: Return feedback results
  S->>UI: Send AskFeedbackResultResponse ("searching")
Loading

Possibly related PRs

Suggested reviewers

  • paopa

Poem

I’m a sprightly rabbit in code’s wide field,
Hopping through functions with tables as yield.
With SQL flows refined and prompts shining bright,
Bugs scurry away in the calm of the night.
Celebrate these changes with a joyful byte!
🐇💻
Cheers to code that feels just right!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (2)
wren-ai-service/src/pipelines/retrieval/retrieval.py (1)

138-165: 🛠️ Refactor suggestion

Consider validating tables parameter.

The table_retrieval function should validate the tables parameter before using it in filters.

 async def table_retrieval(
     embedding: dict, id: str, tables: list[str], table_retriever: Any
 ) -> dict:
+    if tables is not None and not isinstance(tables, list):
+        raise ValueError("tables parameter must be a list of strings")
+    if tables is not None and not all(isinstance(t, str) for t in tables):
+        raise ValueError("all table names must be strings")
     filters = {
         "operator": "AND",
         "conditions": [
wren-ai-service/src/web/v1/services/ask.py (1)

642-642: ⚠️ Potential issue

Fix: SQL correction uses empty contexts.

The SQL correction pipeline is called with empty contexts (contexts=[]), which could lead to incorrect SQL corrections since the table DDLs are not passed through.

Apply this fix:

-                            contexts=[],
+                            contexts=table_ddls,
🧹 Nitpick comments (1)
wren-ai-service/demo/utils.py (1)

232-236: Consider making the table input handling more robust.

While the comma-separated input is user-friendly, the current splitting logic might be sensitive to extra spaces or different separators.

Consider this more robust implementation:

-            retrieved_tables.split(", "),
+            [table.strip() for table in retrieved_tables.split(",") if table.strip()],

Also applies to: 250-253

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bdaa1b1 and 46b0892.

📒 Files selected for processing (6)
  • wren-ai-service/demo/utils.py (5 hunks)
  • wren-ai-service/src/pipelines/generation/sql_regeneration.py (6 hunks)
  • wren-ai-service/src/pipelines/retrieval/retrieval.py (5 hunks)
  • wren-ai-service/src/providers/document_store/qdrant.py (3 hunks)
  • wren-ai-service/src/web/v1/routers/ask.py (1 hunks)
  • wren-ai-service/src/web/v1/services/ask.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pytest
  • GitHub Check: pytest
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (14)
wren-ai-service/src/pipelines/generation/sql_regeneration.py (4)

26-26: LGTM! Enhanced system prompt with database schema context.

The system prompt now correctly instructs the model to utilize the database schema when generating SQL queries.

Also applies to: 29-29


42-45: LGTM! Added database schema section to user prompt template.

The template now properly includes database schema information through document iteration.


63-63: LGTM! Updated prompt function signature with documents parameter.

The function signature and implementation correctly handle the new documents parameter for database schema context.

Also applies to: 72-74


140-142: Verify error handling for empty contexts list.

The run method now accepts contexts but should handle cases where the contexts list is empty.

# Add error handling for empty contexts
async def run(
    self,
    contexts: list[str],
    sql_generation_reasoning: str,
    sql: str,
    ...
):
    if not contexts:
        logger.warning("No database schema contexts provided for SQL regeneration")

Also applies to: 152-165

wren-ai-service/src/web/v1/routers/ask.py (1)

158-158: LGTM! Updated status to accurately reflect the operation state.

Changed status from "understanding" to "searching" to better represent the current operation phase.

wren-ai-service/src/providers/document_store/qdrant.py (1)

350-362: LGTM! Enhanced query logic with fallback to filters.

The run method now intelligently chooses between embedding-based and filter-based queries.

wren-ai-service/src/pipelines/retrieval/retrieval.py (3)

121-133: LGTM! Added proper handling for empty queries.

The function now correctly handles empty queries by returning an empty dictionary.


170-171: LGTM! Simplified dbschema_retrieval signature.

Removed unused embedding parameter and simplified the function signature.

Also applies to: 196-196


482-484: LGTM! Updated run method with optional parameters.

The run method now properly handles optional query and tables parameters.

Also applies to: 492-492

wren-ai-service/src/web/v1/services/ask.py (3)

105-105: LGTM! Well-structured addition of tables attribute.

The new tables attribute is properly typed and logically placed within the request model.


149-149: LGTM! Status update accurately reflects the operation.

The status change from "understanding" to "searching" better represents the actual operation being performed during feedback processing.


593-601: LGTM! Retrieval logic properly updated for table-specific search.

The retrieval pipeline is correctly modified to use the provided tables, and table DDLs are properly extracted from the results.

wren-ai-service/demo/utils.py (2)

186-188: LGTM! Function signature properly updated.

The addition of the retrieved_tables parameter is well-typed and correctly implements the new functionality.


533-533: LGTM! Function properly updated to handle table lists.

The ask_feedback function is correctly modified to accept and pass through the table list parameter.

Also applies to: 537-537

@cyyeh cyyeh requested a review from paopa February 24, 2025 01:22
Copy link
Member

@paopa paopa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overall lgtm. having comments for advice.

Comment on lines +220 to +230
while True:
points = await self.async_client.scroll(
collection_name=self.index,
offset=offset,
scroll_filter=qdrant_filters,
limit=top_k,
)
points_list.extend(points[0])
if points[1] is None:
break
offset = points[1]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I executed the code and found that None is present at index 1, allowing it to satisfy the condition and exit the while loop. However, I suggest we clarify this in the docstring for future reference.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additionally, the while loop w/ an always True condition poses a potential risk of an infinite loop. we are better to change the condition from my opinion.

@paopa paopa merged commit b941cf5 into main Feb 24, 2025
14 checks passed
@paopa paopa deleted the chore/ai-service/update-retrieved-tables branch February 24, 2025 09:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ci/ai-service ai-service related module/ai-service ai-service related
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants