Skip to content

Conversation

@cyyeh
Copy link
Member

@cyyeh cyyeh commented Feb 13, 2025

  • demo ui: add retrieval tables and fix regenerating sql
  • allow streaming for sql generation reasoning

Summary by CodeRabbit

  • New Features

    • Enhanced the SQL query interface with additional table information and improved live streaming of results.
  • Bug Fixes

    • Strengthened feedback and error handling during SQL query regeneration.
    • Standardized query tracking to ensure consistent processing of user requests.

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

coderabbitai bot commented Feb 13, 2025

Walkthrough

The changes update session state handling, SQL generation reasoning, and asynchronous streaming in the application. A new session state variable (retrieved_tables) is introduced in the demo app. Function signatures in the utilities and SQL generation pipeline have been updated to include a query_id parameter, and new methods for streaming results have been added. In addition, the FastAPI ask endpoint now uses a static UUID instead of generating new ones, and related service methods have been modified accordingly, including updates to error handling and result processing.

Changes

File(s) Change Summary
wren-ai-service/demo/app.py Added a new session state variable retrieved_tables initialized to None.
wren-ai-service/demo/utils.py Updated on_click_regenerate_sql to accept a new parameter; modified show_asks_results to display retrieved tables; adjusted SQL generation reasoning handling and feedback status logic.
wren-ai-service/src/.../sql_generation_reasoning.py Updated method signatures to include query_id; added asyncio import; introduced _streaming_callback and get_streaming_results for managing streaming results; revised constant and post-process logic.
wren-ai-service/src/web/v1/routers/ask.py
wren-ai-service/src/web/v1/services/ask.py
Replaced dynamic UUID generation with a static UUID in the ask endpoint; updated AskService to pass query_id to the SQL generation reasoning pipeline and handle a new "planning" status.
wren-ai-service/src/web/v1/services/question_recommendation.py Simplified _validate_question by removing an intermediate await structure; enhanced error handling to specifically catch orjson.JSONDecodeError.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant AskService
    participant SQLGenerationReasoning

    Client->>Router: Send ask request
    Router->>AskService: Invoke ask(request, query_id)
    AskService->>SQLGenerationReasoning: Run query with query_id
    SQLGenerationReasoning-->>AskService: Process streaming callback (chunk)
    AskService->>SQLGenerationReasoning: Request streaming results (query_id)
    SQLGenerationReasoning-->>AskService: Return streaming results
    AskService-->>Router: Provide complete response
    Router-->>Client: Deliver response
Loading

Possibly related PRs

Suggested reviewers

  • paopa

Poem

I'm a rabbit with a code so bright,
Hopping through changes both day and night.
New states and streams make my circuits sing,
Query IDs static—a simple, friendly thing!
With each new line, carrots of logic take flight.

✨ 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 marked this pull request as ready for review February 13, 2025 08:13
@cyyeh cyyeh requested a review from paopa February 13, 2025 08:13
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: 3

🧹 Nitpick comments (4)
wren-ai-service/src/pipelines/generation/sql_generation_reasoning.py (3)

30-33: Potential confusion in the instructions.
Line 30 says not to include triple backticks, but line 33 directs returning plain Markdown. Consider clarifying that the output should be valid Markdown text without triple backtick delimitation, to avoid mixed signals.


81-83: Consider adding a docstring or type hint for clarity.
While this function signature is straightforward, adding a brief docstring and mentioning the expected shape of the returned dictionary can improve maintainability.


104-104: Ensure thread-safe handling of _user_queues.
A plain dictionary may risk key conflicts in concurrent usage. If concurrency is expected, consider using an asyncio-safe data structure, or ensure calls are properly synchronized.

wren-ai-service/src/web/v1/services/question_recommendation.py (1)

84-89: Consider passing query_id to the SQL Generation Reasoning pipeline.
Although this runs fine, passing query_id ensures better traceability, particularly if you intend to handle or stream partial reasoning results for each question in the future.

 await self._pipelines["sql_generation_reasoning"].run(
     query=candidate["question"],
     contexts=table_ddls,
     configuration=configuration,
+    query_id=request_id,
 ).get("post_process", {})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d89131a and 70ee22b.

📒 Files selected for processing (6)
  • wren-ai-service/demo/app.py (1 hunks)
  • wren-ai-service/demo/utils.py (6 hunks)
  • wren-ai-service/src/pipelines/generation/sql_generation_reasoning.py (6 hunks)
  • wren-ai-service/src/web/v1/routers/ask.py (1 hunks)
  • wren-ai-service/src/web/v1/services/ask.py (2 hunks)
  • wren-ai-service/src/web/v1/services/question_recommendation.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: pytest
  • GitHub Check: Analyze (go)
🔇 Additional comments (16)
wren-ai-service/demo/app.py (1)

43-44: LGTM!

The new session state variable retrieved_tables is properly initialized following the same pattern as other session state variables.

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

184-184: LGTM!

The function signature change improves the handling of SQL generation reasoning by making it explicit through the parameter.

Also applies to: 186-186


226-228: LGTM!

The new section properly displays retrieved tables from session state.


230-230: LGTM!

The SQL generation reasoning handling is properly updated to use the changed value from the text area.

Also applies to: 238-242


247-247: LGTM!

The label visibility is properly set for better UI experience.

Also applies to: 254-254


534-534: LGTM!

The session state is properly reset to maintain consistency.


587-589: LGTM!

The retrieved tables are properly joined with commas for better readability.


676-688: LGTM!

The new function properly handles streaming responses using Server-Sent Events (SSE) and follows the same pattern as display_sql_answer.

wren-ai-service/src/pipelines/generation/sql_generation_reasoning.py (6)

1-1: Import looks good.
Using asyncio will enable the asynchronous callbacks and streaming operations. No issues found here.


95-95: Simplified model kwargs.
Declaring a clear text response_format is coherent with the rest of the pipeline usage. Good addition.


109-109: Callback assignment looks consistent.
No concerns—tying _streaming_callback into the generator maintains a straightforward streaming mechanism.


120-129: Check concurrency in _streaming_callback.
Multiple coroutines may try to create or put items in the queue concurrently. Ensure that the dictionary manipulations and queue operations do not cause race conditions. Consider applying locks or verifying single-threaded usage under event loops.


162-163: Optional query_id parameter is well introduced.
This addition nicely aligns with the streaming callback logic. No issues found.


172-172: Wiring query_id into inputs.
Good job consistently populating the pipeline with query_id. No issues found.

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

355-362: LGTM! Clean integration of query_id parameter.

The addition of the query_id parameter to the SQL generation reasoning pipeline call maintains consistency with other pipeline calls and improves request tracking.


548-564: LGTM! Well-structured streaming enhancement.

The streaming enhancement for the "planning" status follows the established pattern, includes proper null checks, and cleanly integrates with the existing SSE event system.

generate_sql_reasoning: dict,
) -> dict:
return orjson.loads(generate_sql_reasoning.get("replies")[0])
return generate_sql_reasoning.get("replies")[0]
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard against empty or missing replies.
Accessing generate_sql_reasoning.get("replies")[0] can raise an IndexError if replies is empty. Add a safety check to avoid runtime failures.

-return generate_sql_reasoning.get("replies")[0]
+replies = generate_sql_reasoning.get("replies")
+if not replies:
+    return {}
+return replies[0]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return generate_sql_reasoning.get("replies")[0]
replies = generate_sql_reasoning.get("replies")
if not replies:
return {}
return replies[0]

Comment on lines +130 to +154
async def get_streaming_results(self, query_id):
async def _get_streaming_results(query_id):
return await self._user_queues[query_id].get()

if query_id not in self._user_queues:
self._user_queues[
query_id
] = asyncio.Queue() # Ensure the user's queue exists
while True:
try:
# Wait for an item from the user's queue
self._streaming_results = await asyncio.wait_for(
_get_streaming_results(query_id), timeout=120
)
if (
self._streaming_results == "<DONE>"
): # Check for end-of-stream signal
del self._user_queues[query_id]
break
if self._streaming_results: # Check if there are results to yield
yield self._streaming_results
self._streaming_results = "" # Clear after yielding
except TimeoutError:
break

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid storing streaming data in a shared instance property.
Using self._streaming_results can cause concurrency issues if multiple queries are handled simultaneously, as they would overwrite each other's result state. Use a local variable or wrap the logic in a dedicated queue read instead.

-            self._streaming_results = await asyncio.wait_for(
-                _get_streaming_results(query_id), timeout=120
-            )
-            if self._streaming_results == "<DONE>":
+            next_chunk = await asyncio.wait_for(
+                _get_streaming_results(query_id), timeout=120
+            )
+            if next_chunk == "<DONE>":
                 ...
-            if self._streaming_results:
-                yield self._streaming_results
-                self._streaming_results = ""
+            if next_chunk:
+                yield next_chunk
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async def get_streaming_results(self, query_id):
async def _get_streaming_results(query_id):
return await self._user_queues[query_id].get()
if query_id not in self._user_queues:
self._user_queues[
query_id
] = asyncio.Queue() # Ensure the user's queue exists
while True:
try:
# Wait for an item from the user's queue
self._streaming_results = await asyncio.wait_for(
_get_streaming_results(query_id), timeout=120
)
if (
self._streaming_results == "<DONE>"
): # Check for end-of-stream signal
del self._user_queues[query_id]
break
if self._streaming_results: # Check if there are results to yield
yield self._streaming_results
self._streaming_results = "" # Clear after yielding
except TimeoutError:
break
async def get_streaming_results(self, query_id):
async def _get_streaming_results(query_id):
return await self._user_queues[query_id].get()
if query_id not in self._user_queues:
self._user_queues[
query_id
] = asyncio.Queue() # Ensure the user's queue exists
while True:
try:
# Wait for an item from the user's queue
next_chunk = await asyncio.wait_for(
_get_streaming_results(query_id), timeout=120
)
if next_chunk == "<DONE>": # Check for end-of-stream signal
del self._user_queues[query_id]
break
if next_chunk: # Check if there are results to yield
yield next_chunk
except TimeoutError:
break

service_metadata: ServiceMetadata = Depends(get_service_metadata),
) -> AskResponse:
query_id = str(uuid.uuid4())
query_id = "c1b011f4-1360-43e0-9c20-22c0c6025206" # str(uuid.uuid4())
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Using a static UUID can cause collisions.
By hardcoding query_id, all new queries share the same ID, which breaks traceability and concurrency. Return to a dynamic UUID or otherwise ensure uniqueness if you need per-request separation.

-    query_id = "c1b011f4-1360-43e0-9c20-22c0c6025206"  # str(uuid.uuid4())
+    query_id = str(uuid.uuid4())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
query_id = "c1b011f4-1360-43e0-9c20-22c0c6025206" # str(uuid.uuid4())
query_id = str(uuid.uuid4())

Copy link
Contributor

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

lgtm, wait for ci done.

@cyyeh cyyeh merged commit 9f65525 into main Feb 13, 2025
9 checks passed
@cyyeh cyyeh deleted the chore/ai-service/minor-updates branch February 13, 2025 08:24
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.

3 participants