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): fix text2sql #1230

Merged
merged 1 commit into from
Jan 25, 2025
Merged

Conversation

cyyeh
Copy link
Member

@cyyeh cyyeh commented Jan 25, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a data cleaning function to improve SQL generation result processing
    • Enhanced system prompts with clearer output format specifications for SQL queries
  • Improvements

    • Refined SQL correction and expansion processes
    • Implemented whitespace and formatting normalization for generation results
    • Improved consistency in SQL query generation and post-processing
  • Technical Updates

    • Updated generation pipeline to include more robust result handling
    • Standardized JSON output format for SQL-related operations

Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Walkthrough

This pull request introduces a new clean_generation_result function across multiple files in the Wren AI service, focusing on standardizing and cleaning SQL generation results. The changes primarily involve adding a utility function to normalize and clean generation outputs, particularly for SQL-related processes. The modifications enhance data handling by implementing a consistent cleaning mechanism for generation results, ensuring better formatting and removing unnecessary characters before further processing.

Changes

File Change Summary
wren-ai-service/src/core/engine.py Added clean_generation_result function to normalize and clean string results
wren-ai-service/src/pipelines/generation/sql_correction.py Updated system prompt to clarify semantics preservation and added JSON output format specification
wren-ai-service/src/pipelines/generation/sql_expansion.py Added JSON output format specification for SQL query results
wren-ai-service/src/pipelines/generation/utils/sql.py Integrated clean_generation_result into SQL processing classes, updated method signatures

Sequence Diagram

sequenceDiagram
    participant Generator
    participant CleaningFunction
    participant Processor
    
    Generator->>CleaningFunction: Generate raw result
    CleaningFunction-->>CleaningFunction: Normalize whitespace
    CleaningFunction-->>CleaningFunction: Remove special characters
    CleaningFunction->>Processor: Return cleaned result
    Processor->>Processor: Process cleaned result
Loading

Possibly related PRs

Suggested labels

module/ai-service, ci/ai-service

Suggested reviewers

  • paopa

Poem

🐰 A rabbit's tale of code so clean,
Whitespace trimmed, no mess to glean
SQL queries polished bright,
With characters stripped just right
Debugging made simple, oh so keen! 🧹✨

✨ 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.

@cyyeh cyyeh added module/ai-service ai-service related ci/ai-service ai-service related labels Jan 25, 2025
@cyyeh cyyeh changed the title chore(ai-service): fix text2sql chore(wren-ai-service): fix text2sql Jan 25, 2025
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: 0

🧹 Nitpick comments (2)
wren-ai-service/src/core/engine.py (1)

30-43: Add type hints and docstring for better maintainability.

The function would benefit from:

  1. Type hints for the helper function
  2. A docstring explaining the purpose and behavior
  3. Edge case handling for None/empty strings

Consider this implementation:

 def clean_generation_result(result: str) -> str:
+    """Clean and normalize SQL generation result.
+    
+    Args:
+        result: Raw generation result string
+    
+    Returns:
+        Cleaned and normalized string with consistent whitespace and removed markers
+    
+    Raises:
+        ValueError: If result is None or empty
+    """
+    if not result:
+        raise ValueError("Generation result cannot be None or empty")
+
-    def _normalize_whitespace(s: str) -> str:
+    def _normalize_whitespace(text: str) -> str:
         return re.sub(r"\s+", " ", s).strip()

     return (
         _normalize_whitespace(result)
         .replace("\\n", " ")
         .replace("```sql", "")
         .replace("```json", "")
         .replace('"""', "")
         .replace("'''", "")
         .replace("```", "")
         .replace(";", "")
     )
wren-ai-service/src/pipelines/generation/utils/sql.py (1)

33-33: LGTM! Consider improving error message specificity.

The integration of clean_generation_result is correct, but the error handling could be more specific.

Consider this improvement:

-        cleaned_generation_result = orjson.loads(clean_generation_result(replies[0]))
+        try:
+            cleaned_generation_result = orjson.loads(clean_generation_result(replies[0]))
+        except Exception as e:
+            logger.exception(f"Failed to parse generation result: {str(e)}")
+            return {
+                "results": {
+                    "description": "Failed to process generation result",
+                    "steps": [],
+                },
+            }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5b192dc and e09f526.

📒 Files selected for processing (4)
  • wren-ai-service/src/core/engine.py (1 hunks)
  • wren-ai-service/src/pipelines/generation/sql_correction.py (1 hunks)
  • wren-ai-service/src/pipelines/generation/sql_expansion.py (1 hunks)
  • wren-ai-service/src/pipelines/generation/utils/sql.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 (5)
wren-ai-service/src/core/engine.py (1)

42-42: Verify if semicolon removal is safe for all SQL dialects.

The function removes semicolons from SQL statements. While this might be acceptable for some SQL dialects, verify that this doesn't affect query execution across all supported databases.

✅ Verification successful

Semicolon removal is safe across all supported SQL dialects

The codebase only processes single SQL statements and all supported databases (BigQuery, DuckDB, Postgres) handle single statements without semicolons. Similar standardization is used consistently throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if semicolons are required in the supported SQL dialects
# Look for SQL execution patterns and dialect configurations

# Search for SQL execution patterns
echo "Searching for SQL execution patterns..."
rg -A 5 "execute_sql|run_sql|query" 

# Search for SQL dialect configurations
echo "Searching for SQL dialect configurations..."
rg -l "dialect|sql_flavor|database_type"

Length of output: 68108


Script:

#!/bin/bash
# Search for SQL execution implementation and dialect handling
echo "Searching for SQL execution implementation..."
rg -A 5 "execute_sql.*\{" 

echo "Searching for dialect-specific handling..."
rg -A 5 "dialect.*=|database_type.*=|sql_flavor.*="

echo "Searching for multi-statement query patterns..."
rg -A 3 "split.*sql|multiple.*queries|;.*;"

Length of output: 79453

wren-ai-service/src/pipelines/generation/sql_correction.py (1)

29-38: LGTM! Consider adding error handling for JSON parsing.

The prompt changes clearly specify the JSON format requirement. However, ensure that the post-processor can handle malformed JSON responses gracefully.

Let's verify the error handling in the post-processor:

wren-ai-service/src/pipelines/generation/sql_expansion.py (1)

30-36: LGTM! Consistent format specification across modules.

The changes maintain consistency with the SQL correction module by specifying the same JSON format requirement.

wren-ai-service/src/pipelines/generation/utils/sql.py (2)

123-125: LGTM! Consistent application of cleaning logic.

The cleaning function is correctly applied to both dictionary and string responses.

Also applies to: 130-132


344-350: LGTM! Format specification aligns with other modules.

The JSON format requirement in the system prompt maintains consistency across all SQL generation modules.

@cyyeh cyyeh merged commit 72fc05c into main Jan 25, 2025
13 of 14 checks passed
@cyyeh cyyeh deleted the chore/ai-service/fix-text2sql branch January 25, 2025 12:45
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