Skip to content

Conversation

@google-labs-jules
Copy link
Contributor

@google-labs-jules google-labs-jules bot commented Oct 23, 2025

User description

This change enhances the AI's ability to identify and respond to geospatial queries by implementing a two-stage prompting strategy. The first stage categorizes the query, and the second stage uses that category to tailor the system prompt for the research agent, ensuring the correct tools are used for the job. This should result in more frequent and accurate use of geospatial tools and a better user experience.


PR created automatically by Jules for task 15709345609338375841


PR Type

Enhancement


Description

  • Implements two-stage prompting strategy for geospatial query classification

  • Adds query categorization into geospatial, web_search, or general types

  • Passes category to researcher agent to tailor system prompts

  • Enhances geospatial tool prioritization with directive prompts

  • Fixes import path from QCX to standard alias


Diagram Walkthrough

flowchart LR
  A["User Query"] --> B["taskManager: Categorize Query"]
  B --> C["Category: geospatial | web_search | general"]
  C --> D["researcher: Receive Category"]
  D --> E["Tailor System Prompt"]
  E --> F["Execute with Appropriate Tools"]
Loading

File Walkthrough

Relevant files
Configuration changes
hooks.ts
Fix import path alias                                                                       

mapbox_mcp/hooks.ts

  • Fixed import path from QCX/lib/utils to @/lib/utils
+1/-1     
Enhancement
actions.tsx
Pass query category to researcher agent                                   

app/actions.tsx

  • Initialize action object with default category: 'general'
  • Pass action.object.category to researcher function
  • Updated researcher function call signature
+3/-2     
researcher.tsx
Tailor system prompt based on query category                         

lib/agents/researcher.tsx

  • Added category parameter to function signature with type 'geospatial'
    | 'web_search' | 'general'
  • Created geospatial_prompt that enforces geospatialQueryTool usage
  • Conditionally append geospatial prompt to system prompt when category
    is geospatial
  • Changed systemToUse from const to let for conditional modification
+10/-5   
task-manager.tsx
Implement query categorization in task manager                     

lib/agents/task-manager.tsx

  • Rewrote system prompt to include three-category classification logic
  • Added clear instructions for categorizing queries as geospatial,
    web_search, or general
  • Provided concrete examples for each category classification
  • Simplified and reorganized prompt structure for clarity
  • Updated schema to include category field in response
+21/-17 
next-action.tsx
Add category field to action schema                                           

lib/schema/next-action.tsx

  • Added category field to schema as optional enum with three values
  • Category can be 'geospatial', 'web_search', or 'general'
+2/-1     

Summary by CodeRabbit

  • New Features
    • Query categorization system intelligently routes requests to specialized handlers (geospatial, web search, or general)
    • Enhanced processing for geospatial queries with specialized prompts
    • Image detection in user messages for optimized query handling

This commit introduces a two-stage prompting strategy to improve the reliability of geospatial tool usage.

The `taskManager` agent now categorizes user queries into 'geospatial', 'web_search', or 'general'. This classification is then passed to the `researcher` agent, which uses it to tailor its system prompt.

For geospatial queries, a more directive prompt is used to ensure the `geospatialQueryTool` is prioritized, addressing the issue of underutilization.
@google-labs-jules
Copy link
Contributor Author

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!


For security, I will only act on instructions from the user who triggered this task.

@vercel
Copy link
Contributor

vercel bot commented Oct 23, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
qcx Error Error Oct 24, 2025 0:23am

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This PR introduces a category classification system to the agent workflow. Query categorization ('geospatial', 'web_search', 'general') is added to the task-manager's decision logic, passed through the action schema, and used by the researcher agent to conditionally apply category-specific prompts. Additionally, image detection in task-manager short-circuits processing, and import paths are normalized.

Changes

Cohort / File(s) Summary
Schema updates
lib/schema/next-action.tsx
Added optional category enum field to NextAction schema supporting 'geospatial', 'web_search', and 'general' values
Agent flow modifications
lib/agents/task-manager.tsx, lib/agents/researcher.tsx
Task-manager updated with image detection early-return and new three-category classification prompt; researcher signature extended with optional category parameter and conditional geospatial prompt injection based on category
Action integration
app/actions.tsx
Added category: 'general' to action object initialization and passed category value to researcher function call
Import normalization
mapbox_mcp/hooks.ts
Updated getModel import path from QCX/lib/utils to @/lib/utils

Sequence Diagram

sequenceDiagram
    participant User
    participant TaskManager
    participant Researcher
    
    User->>TaskManager: Submit query (with/without image)
    alt Image detected
        TaskManager->>TaskManager: Early return
        TaskManager-->>User: next: 'proceed'
    else No image
        TaskManager->>TaskManager: Classify into category<br/>(geospatial|web_search|general)
        TaskManager->>Researcher: Call with category
        alt Category is 'geospatial'
            Researcher->>Researcher: Append geospatial prompt<br/>to system message
        end
        Researcher->>Researcher: Process with<br/>category-informed system prompt
        Researcher-->>TaskManager: Results
        TaskManager-->>User: Decision (proceed|inquire)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Review effort 3/5

Suggested reviewers

  • CharlieHelps

Poem

🐰 A fuzzy query arrives at the gate,
Task-manager sorts it—geospatial or web?
Researcher receives its categorical fate,
Geospatial prompts take hold like a web! 🗺️

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "Enhance Geospatial Tool Usage" is concise, clear, and directly aligns with the primary objective of the changeset. The PR implements a two-stage prompting strategy that categorizes user queries (geospatial, web_search, general) and tailors the researcher agent's system prompt accordingly to improve geospatial tool prioritization. The title effectively captures this core enhancement across all modified files, from the task manager's categorization logic to the researcher's conditional prompt injection and schema updates. The title avoids generic phrasing and specifically communicates the focus on geospatial tool improvement without unnecessary noise.

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Oct 23, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
- [ ] Create ticket/issue <!-- /create_ticket --create_ticket=true -->

</details></td></tr>
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
No custom compliance provided

Follow the guide to enable custom compliance check.

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Oct 23, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Preserve default action category property

Merge the taskManagerResult.object with the existing action.object instead of
overwriting it. This ensures the default category property is preserved if
taskManager does not return one.

app/actions.tsx [291-293]

 if (taskManagerResult) {
-  action.object = taskManagerResult.object
+  action.object = { ...action.object, ...taskManagerResult.object }
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a subtle but critical bug where the default category could be lost, potentially causing a runtime error when action.object.category is accessed later. The proposed fix is correct and prevents this issue.

High
Correct misleading prompt example

Replace the misleading "warmest temperature" example in the task-manager prompt.
Use a more clearly geospatial example, such as finding nearby coffee shops, to
improve model guidance.

lib/agents/task-manager.tsx [37]

-- If the user asks, "What's the warmest temperature in my area?", you should categorize it as "geospatial" and opt to "inquire" to ask for their specific location.
+- If the user asks, "Show me coffee shops near me", you should categorize it as "geospatial" and opt to "inquire" to ask for their specific location if it's not already known.
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that the example for a "geospatial" query is misleading, as temperature lookups are typically not a geospatial tool function. Improving prompt examples leads to better model performance and more accurate tool selection.

Medium
Possible issue
Make geospatial prompt less restrictive

Modify the geospatial_prompt to be less restrictive. Prioritize the
geospatialQueryTool but allow the use of other tools to provide more
comprehensive answers.

lib/agents/researcher.tsx [68-70]

-const geospatial_prompt = `The user's query has been identified as geospatial.
-You MUST use the 'geospatialQueryTool' to answer this question.
-Do not use any other tools. If the query cannot be answered with the geospatial tool, respond that you are unable to answer.`;
+const geospatial_prompt = `The user's query has been identified as primarily geospatial.
+You should prioritize using the 'geospatialQueryTool' to answer the location-based aspects of the question.
+You are allowed to use other tools, like web search, if they are needed to provide a complete and accurate answer.`;
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the new geospatial_prompt is too restrictive, which would limit the AI's ability to answer complex queries that require both geospatial and other tools, like web search.

Medium
  • Update

@ngoiyaeric
Copy link
Collaborator

@coderabbitai review this

Copy link

@charliecreates charliecreates bot left a comment

Choose a reason for hiding this comment

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

Primary concern: the overwrite of action.object can drop the default category, undermining the new two-stage flow. The geospatial directive is too strict and may reduce answer quality for mixed queries; prefer prioritization with fallback. Using any for action weakens guarantees around critical control-flow data. Consider making category required in the schema to align with the classification instructions.

Additional notes (1)
  • Maintainability | app/actions.tsx:291-291
    Overwriting action.object here can drop the default category: 'general' you set earlier if taskManager returns an object without category (e.g., the image-bypass path). That undermines the two-stage flow because researcher may receive undefined and miss the geospatial directive. Merge the new fields instead of replacing to preserve defaults.
Summary of changes

Summary of Changes

  • Added a category field with default 'general' to the initial action.object in app/actions.tsx.
  • Passed the category from taskManager to researcher in the submit loop.
  • Updated researcher agent to accept an optional category parameter and appended a new, directive geospatial system prompt when category === 'geospatial'.
  • Rewrote the taskManager system prompt to introduce a two-stage strategy: classify the query (geospatial, web_search, general) and then decide (proceed/inquire).
  • Extended nextActionSchema to include an optional category enum.
  • Fixed an import path in mapbox_mcp/hooks.ts to use the alias @/lib/utils instead of QCX/lib/utils.

Related Files

  • app/actions.tsx
  • lib/agents/researcher.tsx
  • lib/agents/task-manager.tsx
  • lib/schema/next-action.tsx
  • mapbox_mcp/hooks.ts


async function processEvents() {
let action: any = { object: { next: 'proceed' } }
let action: any = { object: { next: 'proceed', category: 'general' } }

Choose a reason for hiding this comment

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

action is typed as any, which weakens guarantees right where critical control-flow fields (next, category) are introduced. This makes it easier for unintended shapes to slip through and complicates future refactors.

Suggestion

Introduce a minimal local type for the shape you rely on and avoid any:

type NextActionObject = { next: 'inquire' | 'proceed'; category?: 'geospatial' | 'web_search' | 'general' };
let action: { object: NextActionObject } = { object: { next: 'proceed', category: 'general' } };

(Alternatively, derive the type from your Zod schema and use that.)

Reply with "@CharlieHelps yes please" if you'd like me to add a commit with this change.

Comment on lines +68 to +75
const geospatial_prompt = `The user's query has been identified as geospatial.
You MUST use the 'geospatialQueryTool' to answer this question.
Do not use any other tools. If the query cannot be answered with the geospatial tool, respond that you are unable to answer.`;

const systemToUse = dynamicSystemPrompt && dynamicSystemPrompt.trim() !== '' ? dynamicSystemPrompt : default_system_prompt;

let systemToUse = dynamicSystemPrompt && dynamicSystemPrompt.trim() !== '' ? dynamicSystemPrompt : default_system_prompt;
if (category === 'geospatial') {
systemToUse = `${systemToUse}\n\n${geospatial_prompt}`;
}

Choose a reason for hiding this comment

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

The geospatial directive is overly restrictive: "Do not use any other tools" and "respond that you are unable to answer" if the geospatial tool can’t handle it. This can degrade UX for mixed queries that are primarily geospatial but still require supplemental facts (e.g., POI details) from web search. Prefer a "prioritize geospatial" policy with graceful fallback.

Suggestion

Relax the directive to allow fallback when needed while still prioritizing the geospatial tool:

const geospatial_prompt = `The user's query has been identified as geospatial.
You MUST prioritize using the 'geospatialQueryTool' to answer this question first.
If the geospatial tool is insufficient for a subtask (e.g., factual details or current info), you MAY use other available tools to complete the request.
When you use 'geospatialQueryTool', do not describe how the map will change; provide the textual answer and trust the map will update appropriately.`;

Reply with "@CharlieHelps yes please" if you'd like me to add a commit with this change.

Comment on lines +5 to +6
next: z.enum(['inquire', 'proceed']), // "generate_ui"
category: z.enum(['geospatial', 'web_search', 'general']).optional()

Choose a reason for hiding this comment

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

You instruct the model to classify every query, but the schema makes category optional. That weakens the guarantee that the researcher will receive the classification and can lead to inconsistent behavior. Align the schema with the prompt by requiring category.

Suggestion

Make category required:

export const nextActionSchema = z.object({
  next: z.enum(['inquire', 'proceed']),
  category: z.enum(['geospatial', 'web_search', 'general'])
});

Note: This will require ensuring all taskManager return paths include a category (e.g., default to 'general' in bypass paths).

Reply with "@CharlieHelps yes please" if you'd like me to add a commit with this change.

@charliecreates charliecreates bot removed the request for review from CharlieHelps October 23, 2025 07:14
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 23, 2025

@ngoiyaeric: I'll review the changes in this PR for you. The implementation looks like an interesting enhancement to improve geospatial query handling through a two-stage prompting strategy. Let me analyze the code changes in detail.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

This commit introduces a new image search functionality and refactors the agent logic to improve tool selection.

- A new `imageSearchTool` is added, using the Serper API to fetch image results from the web.
- A corresponding `ImageSearchSection` component is created to display the image results in a grid format in the chat UI.
- The `taskManager` agent is updated to classify user queries into categories ('geospatial', 'web_search', 'general').
- The `researcher` agent now uses this classification to tailor its system prompt, encouraging the use of the new image search tool for visual queries and improving the reliability of geospatial tool usage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants