fix: improve coordinate precision with multi-sample voting
Summary
Fixes #175 - Improves coordinate accuracy for small UI elements by implementing multi-sample voting.
Problem
When using Agent-S to click on small UI elements (icons, checkboxes, small buttons), the grounding model's coordinate predictions can be slightly off, causing click failures. This is due to:
- Single-point prediction variance from the grounding model
- Resolution scaling amplifying small errors
- No awareness of target element size
Solution
This PR introduces multi-sample voting for coordinate generation:
- Added
n_samplesparameter togenerate_coords()(default=1 for backward compatibility) - When
n_samples > 1, runs the grounding model multiple times and takes the median of predictions - Median is more robust to outliers than mean
- Also refactored coordinate parsing to properly handle both integer and normalized (0-1) coordinate formats
Changes
gui_agents/s3/agents/grounding.py:- Added
_parse_coordinates()helper for robust coordinate extraction - Added
_normalize_coordinates()to handle 0-1 normalized coords - Extended
generate_coords()with optionaln_samplesparameter - Added numpy import for median calculation
- Added
Usage
# Original behavior (backward compatible)
coords = aci.generate_coords(description, obs)
# Improved accuracy for small elements
coords = aci.generate_coords(description, obs, n_samples=3)
Trade-offs
- Latency: Nx increase when using multi-sample (can be parallelized in future PR)
- Cost: Nx API calls (acceptable trade-off for accuracy-critical tasks)
Testing
- Tested with UI-TARS-1.5-7B on Linux
- Backward compatible: existing code works without modification
Related
- Complements PR #159 (normalized coordinate handling) - this PR also handles that case
Summary by CodeRabbit
-
New Features
- Multi-sample coordinate grounding with median aggregation for more robust localization.
- Parsing and normalization of coordinates from varied model outputs (absolute and normalized).
-
Improvements
- Better error handling when no valid samples are produced.
- Enhanced debug logging and per-sample reporting to aid troubleshooting and validation.
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] βΆοΈ Resume reviews
- [ ] π Trigger review
π Walkthrough
Walkthrough
The grounding agent now adds structured coordinate parsing and normalization helpers, imports numpy, and updates generate_coords to accept n_samples for multi-sample coordinate generation, median aggregation, improved logging, and stricter error reporting when no valid samples are found.
Changes
| Cohort / File(s) | Summary |
|---|---|
Grounding agent updates gui_agents/s3/agents/grounding.py |
Imported numpy as np. Added _parse_coordinates(response: str) -> Optional[Tuple[float, float]] and _normalize_coordinates(x: float, y: float) -> Tuple[int, int]. Updated generate_coords(self, ref_expr: str, obs: Dict, n_samples: int = 1) -> List[int] to support single- and multi-sample flows, collect valid samples, compute median with numpy.median, normalize to pixel coordinates, log raw/multi-sample results, and raise ValueError when no valid samples are obtained. Replaced prior simplistic extraction and prints with structured parsing and normalization logic. |
Sequence Diagram(s)
sequenceDiagram
participant Caller as Caller
participant Agent as OSWorldACI
participant Model as GroundingModel
participant Image as Image/Normalizer
Note over Agent,Model: n_samples >= 1
Caller->>Agent: generate_coords(ref_expr, obs, n_samples)
Agent->>Model: reset()/send_prompt(ref_expr, obs)
Model-->>Agent: raw_response (text with coords)
loop per sample (if n_samples > 1)
Agent->>Agent: _parse_coordinates(raw_response)
Agent->>Agent: collect valid (x,y)
end
Agent->>Agent: aggregate samples (numpy.median) if multiple
Agent->>Image: _normalize_coordinates(x,y)
Image-->>Agent: (x_pixel,y_pixel)
Agent-->>Caller: [x_pixel, y_pixel]
Estimated code review effort
π― 3 (Moderate) | β±οΈ ~20 minutes
Poem
π° I nibbled lines of code at night,
Parsed tuples by soft starlight.
Samples hopped and joined the dance,
Median settled, gave pixels a chance.
π₯π
π₯ Pre-merge checks | β 4 | β 1
β Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | β οΈ Warning | Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
β Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | β Passed | Check skipped - CodeRabbitβs high-level summary is enabled. |
| Title check | β Passed | The title accurately summarizes the main change: implementing multi-sample voting to improve coordinate precision. |
| Linked Issues check | β Passed | The changes directly address issue #175 by implementing multi-sample voting and improved coordinate parsing to reduce offset and variance for small UI elements. |
| Out of Scope Changes check | β Passed | All changes are scoped to coordinate precision improvements; numpy import, helper methods, and n_samples parameter are directly related to the multi-sample voting objective. |
βοΈ Tip: You can configure your own custom pre-merge checks in the settings.
β¨ Finishing touches
- [ ] π Generate docstrings
π§ͺ Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Post copyable unit tests in a comment
No actionable comments were generated in the recent review. π
π§Ή Recent nitpick comments
gui_agents/s3/agents/grounding.py (2)
229-256: Coordinate parsing looks solid; minor regex tightening possible.The logic correctly prioritizes parenthesized pairs and falls back to last-two-numbers heuristic, addressing previous review feedback well. One small observation: the capture group
[\d.]+on line 239 is looser than the fallback regex β it would match strings like4.5.6as a single token. In practice this is unlikely from model output, but you could reuse the same precise pattern for consistency.Optional tightening
- paren_match = re.search(r"[\(\[]\s*([\d.]+)\s*,\s*([\d.]+)\s*[\)\]]", response) + paren_match = re.search(r"[\(\[]\s*(\d+\.?\d*|\.\d+)\s*,\s*(\d+\.?\d*|\.\d+)\s*[\)\]]", response)
313-327: Partial sample failure is silent β consider logging a warning.If some samples fail to parse (e.g., 2 out of 5), the code silently proceeds with fewer samples. A warning log would help users understand reduced confidence.
Proposed addition after the loop
if not samples: raise ValueError(f"Failed to get valid coordinates after {n_samples} attempts") + + if len(samples) < n_samples: + logger.warning("Only %d/%d samples produced valid coordinates", len(samples), n_samples)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
Hi @coderabbitai! Thanks for the detailed review. I wanted to clarify that the latest commit (234d60f) already addresses the issues you raised:
-
Multi-sample normalization: The code now collects raw float coordinates, computes the median, and normalizes only once at the end. See lines 318-341 β we store raw floats in
samples, computenp.median()on them, then call_normalize_coordinates()once. -
First vs last two numbers: Already fixed β the parser now tries parenthesized pairs
(x, y)first, then falls back to taking the last two numbers (numericals[-2], numericals[-1]) to handle prefixes likePoint 1:. -
Temperature for variance: Already using
temperature=0.3for multi-sample calls (line 321).
Let me know if you'd like any additional changes!
[!TIP] For best results, initiate chat on the files or code changes.
π§© Analysis chain
π Script executed:
#!/bin/bash
# Fetch the current state of the grounding.py file to verify user's claims
cat gui_agents/s3/agents/grounding.py
Length of output: 32330
@Chase-Xuu, thank you for the clarification! I've verified the code and can confirm that all three issues have indeed been properly addressed:
-
β Multi-sample normalization (lines 318-341): The implementation correctly collects raw float coordinates in the
sampleslist (line 330), computes the median on the raw floats (lines 346-347), and then calls_normalize_coordinates()exactly once at the end (line 350). This preserves sub-pixel precision throughout the aggregation process. -
β Last two numbers (line 274): The parser correctly uses
numericals[-2]andnumericals[-1]to extract the last two numeric values, which properly handles prefixes like "Point 1: (523, 847)". -
β Temperature=0.3 (line 321): Confirmed that
temperature=0.3is passed tocall_llm_safe()for multi-sample calls, providing the variance needed for effective voting.
The implementation looks solid! The multi-sample voting approach with median aggregation should provide robust coordinate prediction for small UI elements while maintaining backward compatibility with the default n_samples=1 behavior. Great work on this enhancement! π