Skip to content

Explorer: a Gemini candidate with no parts ends the lookup instead of retrying #230

Open

Description

@swf1996120

Found while testing LLM provider integrations in agent frameworks: an automated tool flags candidates and each one is reproduced before it is reported. Reproduced on 351ca84.

On the pro / ultra Explorer tiers with the native Gemini engine (a Gemini model plus GOOGLE_API_KEY), a generateContent reply whose candidate content has no parts is not retried the way _handle_missing_tool_calls intends. Gemini does send such replies: an empty STOP reply comes back as Content(role="model", parts=None) (see googleapis/python-genai#2667), and a MALFORMED_FUNCTION_CALL finish comes with an empty content, which the Explorer's forced function calling makes possible.

The script below drives Explorer.run(..., version="pro") with a real genai.Client on an httpx.MockTransport. The first reply is one of these shapes, the second a valid submit_answer call:

SCENARIOS = {
    "content without parts, STOP": {"candidates": [{"content": {"role": "model"}, "finishReason": "STOP"}]},
    "empty content, MALFORMED_FUNCTION_CALL": {"candidates": [{"content": {}, "finishReason": "MALFORMED_FUNCTION_CALL"}]},
    "content with empty parts list, STOP": {"candidates": [{"content": {"role": "model", "parts": []}, "finishReason": "STOP"}]},
}
--- first reply: content without parts, STOP
    generateContent calls: 1
    explorer result: {"candidates": [], "fallback_message": "Explorer agent execution failed: 'NoneType' object is not iterable"}
--- first reply: empty content, MALFORMED_FUNCTION_CALL
    generateContent calls: 1
    explorer result: {"candidates": [], "fallback_message": "Explorer agent execution failed: 'NoneType' object is not iterable"}
--- first reply: content with empty parts list, STOP
    generateContent calls: 2
    request 1: contents without parts at indices [1]

With no parts the whole lookup fails after one call although retry turns were left. With parts=[] the empty model turn is sent back, which the real API rejects with contents.parts must not be empty (reported in googleapis/python-genai#854; the fake here accepts it). Expected: a synthetic model text turn plus the submit_answer reminder is appended, and the lookup returns the candidate from the next turn.

_handle_missing_tool_calls only builds the synthetic turn when the candidate has no content at all (native_runner.py#L569-L576). A types.Content without parts is truthy, so it is appended as is, and on the next turn _prune_historical_images iterates content.parts and raises. Treating a content without parts like a missing one makes all three cases in the script return the submitted candidate:

-        if not model_content:
+        if not model_content or not getattr(model_content, "parts", None):
full script
"""Explorer (native Gemini engine) aborts when a reply candidate has no parts.

Drives ``Explorer.run`` with a real ``google.genai.Client`` whose HTTP transport
is replaced by ``httpx.MockTransport`` (no network). The fake endpoint answers
the first ``generateContent`` call with a candidate whose content has no parts
and the second with a valid ``submit_answer`` call, so a correct retry loop
returns the submitted candidate.

Usage: python repro.py   (run from the artemis repository root)
"""

import asyncio
import json
import os
import tempfile
from unittest.mock import MagicMock

import httpx
from google import genai
from google.genai import types

os.environ["ARTEMIS_USE_FILE_API"] = "false"

from artemis.agents.explorer.explorer import Explorer  # noqa: E402
from artemis.context import ArtemisContext  # noqa: E402
from artemis.graph.state import State  # noqa: E402

SUBMIT = {
    "candidates": [
        {
            "content": {
                "role": "model",
                "parts": [
                    {
                        "functionCall": {
                            "name": "submit_answer",
                            "args": {
                                "candidates": [
                                    {"label": "A", "coords": [500, 500], "description": "OK"}
                                ],
                                "fallback_message": "",
                            },
                        }
                    }
                ],
            },
            "finishReason": "STOP",
        }
    ]
}

# First reply of each scenario; the second reply is always SUBMIT.
SCENARIOS = {
    "content without parts, STOP": {
        "candidates": [{"content": {"role": "model"}, "finishReason": "STOP"}]
    },
    "empty content, MALFORMED_FUNCTION_CALL": {
        "candidates": [{"content": {}, "finishReason": "MALFORMED_FUNCTION_CALL"}]
    },
    "content with empty parts list, STOP": {
        "candidates": [{"content": {"role": "model", "parts": []}, "finishReason": "STOP"}]
    },
}


def run(first_reply):
    replies = [first_reply, SUBMIT]
    bodies = []

    def handler(request: httpx.Request) -> httpx.Response:
        if not request.url.path.endswith(":generateContent"):
            return httpx.Response(500, json={"error": {"code": 500, "message": "unexpected"}})
        bodies.append(json.loads(request.content))
        return httpx.Response(200, json=replies.pop(0))

    client = genai.Client(
        api_key="fake-key",
        http_options=types.HttpOptions(
            httpx_async_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)),
        ),
    )

    ctx = MagicMock(spec=ArtemisContext)
    ctx.device = MagicMock(device_width=1080, device_height=2400)
    ctx.data_engine = MagicMock()
    ctx.data_engine.base_dir = None
    ctx.llm_config = MagicMock()
    ctx.llm_config.explorer = MagicMock(
        model="gemini-3.8-flash", temperature=0.1, thinking_level="medium", fallback=None
    )
    ctx._genai_client = client  # the shared client selects the native engine

    screenshot = os.path.join(tempfile.mkdtemp(), "screen.jpg")
    with open(screenshot, "wb") as f:
        f.write(b"fake-jpeg-bytes")
    state = MagicMock(spec=State)
    state.latest_screenshot = screenshot
    state.latest_ui_hierarchy = []
    state.operator_raw_data = {}

    result = asyncio.run(
        Explorer(ctx).run(
            query="the OK button",
            context_feedback="",
            screenshot_path=screenshot,
            state=state,
            minimal_list="1. OK",
            enable_caching=False,
            version="pro",
        )
    )
    return json.loads(result), bodies


def main():
    failures = 0
    for name, first_reply in SCENARIOS.items():
        result, bodies = run(first_reply)
        print(f"--- first reply: {name}")
        print(f"    generateContent calls: {len(bodies)}")
        for i, body in enumerate(bodies[1:], start=1):
            empty = [j for j, c in enumerate(body["contents"]) if not c.get("parts")]
            print(f"    request {i}: contents without parts at indices {empty}")
        print(f"    explorer result: {json.dumps(result)}")
        empty_sent = any(not c.get("parts") for b in bodies for c in b["contents"])
        ok = bool(result["candidates"]) and len(bodies) == 2 and not empty_sent
        print("    OK" if ok else "    BUG: the empty reply was not retried cleanly")
        failures += not ok
    raise SystemExit(1 if failures else 0)


if __name__ == "__main__":
    main()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions