Repository: All-Hands-AI/OpenHands
Pull request #7713: fix(llm): retry on InternalServerError and Timeout; handle Gemini returns len(choices) < 1
Author: login: xingyaoww
Created: 2025-04-04T18:06:36Z | Merged: 2025-04-05T21:33:17Z

- [ ] This change is worth documenting at https://docs.all-hands.dev/
- [ ] Include this change in the Release Notes. If checked, you **must** provide an **end-user friendly** description for your change below

**End-user friendly description of the problem this fixes or functionality that this introduces.**


---
**Give a summary of what the PR does, explaining any non-trivial design decisions.**

Gemini a lot of time will return response with choices less than 1, causing errors:

```
"InternalServerError: litellm.InternalServerError: Response choices is less than 1 - This is only seen in Gemini Pro 2.5 so far. Response: ModelResponse(id='chatcmpl-abe113c5-37e5-4740-8292-91faedd8d928', created=1743601076, model='litellm_proxy/gemini-2.5-pro-exp-03-25', object='chat.completion', system_fingerprint=None, choices=[], usage=Usage(completion_tokens=0, prompt_tokens=4501, total_tokens=4501, completion_tokens_details=None, prompt_tokens_details=None), service_tier=None, vertex_ai_grounding_metadata=[], vertex_ai_safety_results=[], vertex_ai_citation_metadata=[])
```

This PR:
- convert it to InternalServerError
- Retry on InternalServerError (some of the time, it fixes stuff), Timeout
- Add gemini-2.5-pro to function calling support model (we at least get decent benchmark performance from it)

---
**Link of any specific issues this addresses.**

---

To run this PR locally, use the following command:
```
docker run -it --rm   -p 3000:3000   -v /var/run/docker.sock:/var/run/docker.sock   --add-host host.docker.internal:host-gateway   -e SANDBOX_RUNTIME_CONTAINER_IMAGE=docker.all-hands.dev/all-hands-ai/runtime:a3ff665-nikolaik   --name openhands-app-a3ff665   docker.all-hands.dev/all-hands-ai/openhands:a3ff665
```


Diff:
diff --git a/openhands/core/exceptions.py b/openhands/core/exceptions.py
index 342e0db0e7c5..c154152d4b66 100644
--- a/openhands/core/exceptions.py
+++ b/openhands/core/exceptions.py
@@ -88,6 +88,16 @@ def __init__(
         super().__init__(message)
 
 
+# This exception should be retried
+# Typically, after retry with a non-zero temperature, the LLM will return a response
+class LLMNoResponseError(Exception):
+    def __init__(
+        self,
+        message: str = 'LLM did not return a response. This is only seen in Gemini models so far.',
+    ) -> None:
+        super().__init__(message)
+
+
 class UserCancelledError(Exception):
     def __init__(self, message: str = 'User cancelled the request') -> None:
         super().__init__(message)
diff --git a/openhands/llm/llm.py b/openhands/llm/llm.py
index 42ffe5eac87c..27a948fd1c3a 100644
--- a/openhands/llm/llm.py
+++ b/openhands/llm/llm.py
@@ -23,6 +23,7 @@
 from litellm.types.utils import CostPerToken, ModelResponse, Usage
 from litellm.utils import create_pretrained_tokenizer
 
+from openhands.core.exceptions import LLMNoResponseError
 from openhands.core.logger import openhands_logger as logger
 from openhands.core.message import Message
 from openhands.llm.debug_mixin import DebugMixin
@@ -37,7 +38,12 @@
 __all__ = ['LLM']
 
 # tuple of exceptions to retry on
-LLM_RETRY_EXCEPTIONS: tuple[type[Exception], ...] = (RateLimitError,)
+LLM_RETRY_EXCEPTIONS: tuple[type[Exception], ...] = (
+    RateLimitError,
+    litellm.Timeout,
+    litellm.InternalServerError,
+    LLMNoResponseError,
+)
 
 # cache prompt supporting models
 # remove this when we gemini and deepseek are supported
@@ -63,6 +69,7 @@
     'o1-2024-12-17',
     'o3-mini-2025-01-31',
     'o3-mini',
+    'gemini-2.5-pro',
 ]
 
 REASONING_EFFORT_SUPPORTED_MODELS = [
@@ -267,8 +274,12 @@ def wrapper(*args, **kwargs):
 
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
-                logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    raise LLMNoResponseError(
+                        'Response choices is less than 1 - This is only seen in Gemini models so far. Response: '
+                        + str(resp)
+                    )
+
                 non_fncall_response_message = resp.choices[0].message
                 fn_call_messages_with_response = (
                     convert_non_fncall_messages_to_fncall_messages(
@@ -282,6 +293,13 @@ def wrapper(*args, **kwargs):
                     )
                 resp.choices[0].message = fn_call_response_message
 
+            # Check if resp has 'choices' key with at least one item
+            if not resp.get('choices') or len(resp['choices']) < 1:
+                raise LLMNoResponseError(
+                    'Response choices is less than 1 - This is only seen in Gemini models so far. Response: '
+                    + str(resp)
+                )
+
             message_back: str = resp['choices'][0]['message']['content'] or ''
             tool_calls: list[ChatCompletionMessageToolCall] = resp['choices'][0][
                 'message'
diff --git a/openhands/llm/retry_mixin.py b/openhands/llm/retry_mixin.py
index 08a8add63939..19b7c9689f7b 100644
--- a/openhands/llm/retry_mixin.py
+++ b/openhands/llm/retry_mixin.py
@@ -5,6 +5,7 @@
     wait_exponential,
 )
 
+from openhands.core.exceptions import LLMNoResponseError
 from openhands.core.logger import openhands_logger as logger
 from openhands.utils.tenacity_stop import stop_if_should_exit
 
@@ -35,6 +36,22 @@ def before_sleep(retry_state):
             if retry_listener:
                 retry_listener(retry_state.attempt_number, num_retries)
 
+            # Check if the exception is LLMNoResponseError
+            exception = retry_state.outcome.exception()
+            if isinstance(exception, LLMNoResponseError):
+                if hasattr(retry_state, 'kwargs'):
+                    # Only change temperature if it's zero or not set
+                    current_temp = retry_state.kwargs.get('temperature', 0)
+                    if current_temp == 0:
+                        retry_state.kwargs['temperature'] = 1.0
+                        logger.warning(
+                            'LLMNoResponseError detected with temperature=0, setting temperature to 1.0 for next attempt.'
+                        )
+                    else:
+                        logger.warning(
+                            f'LLMNoResponseError detected with temperature={current_temp}, keeping original temperature'
+                        )
+
         return retry(
             before_sleep=before_sleep,
             stop=stop_after_attempt(num_retries) | stop_if_should_exit(),
diff --git a/tests/unit/test_llm.py b/tests/unit/test_llm.py
index 87db3bc62e2e..6d243ed5775f 100644
--- a/tests/unit/test_llm.py
+++ b/tests/unit/test_llm.py
@@ -10,7 +10,7 @@
 )
 
 from openhands.core.config import LLMConfig
-from openhands.core.exceptions import OperationCancelled
+from openhands.core.exceptions import LLMNoResponseError, OperationCancelled
 from openhands.core.message import Message, TextContent
 from openhands.llm.llm import LLM
 from openhands.llm.metrics import Metrics, TokenUsage
@@ -385,6 +385,223 @@ def side_effect(*args, **kwargs):
     _should_exit = False
 
 
+@patch('openhands.llm.llm.litellm_completion')
+def test_completion_retry_with_llm_no_response_error_zero_temp(
+    mock_litellm_completion, default_config
+):
+    """
+    Test that the retry decorator properly handles LLMNoResponseError by:
+    1. First call to llm_completion uses temperature=0 and throws LLMNoResponseError
+    2. Second call should have temperature=0.2 and return a successful response
+    """
+
+    # Define a side effect function that checks the temperature parameter
+    # and returns different responses based on it
+    def side_effect(*args, **kwargs):
+        temperature = kwargs.get('temperature', 0)
+
+        # First call with temperature=0 should raise LLMNoResponseError
+        if temperature == 0:
+            raise LLMNoResponseError('LLM did not return a response')
+
+        else:
+            return {
+                'choices': [
+                    {'message': {'content': f'Response with temperature={temperature}'}}
+                ]
+            }
+
+    mock_litellm_completion.side_effect = side_effect
+
+    # Create LLM instance and make a completion call
+    llm = LLM(config=default_config)
+    response = llm.completion(
+        messages=[{'role': 'user', 'content': 'Hello!'}],
+        stream=False,
+        temperature=0,  # Initial temperature is 0
+    )
+
+    # Verify the response after retry
+    assert (
+        response['choices'][0]['message']['content'] == 'Response with temperature=1.0'
+    )
+
+    # Verify that litellm_completion was called twice
+    assert mock_litellm_completion.call_count == 2
+
+    # Check the temperature in the first call (should be 0)
+    first_call_kwargs = mock_litellm_completion.call_args_list[0][1]
+    assert first_call_kwargs.get('temperature') == 0
+
+    # Check the temperature in the second call (should be 1.0)
+    second_call_kwargs = mock_litellm_completion.call_args_list[1][1]
+    assert second_call_kwargs.get('temperature') == 1.0
+
+
+@patch('openhands.llm.llm.litellm_completion')
+def test_completion_retry_with_llm_no_response_error_nonzero_temp(
+    mock_litellm_completion, default_config
+):
+    """
+    Test that the retry decorator works for LLMNoResponseError when initial temperature is non-zero,
+    and keeps the original temperature on retry.
+
+    This test verifies that when LLMNoResponseError is raised with a non-zero temperature:
+    1. The retry mechanism is triggered
+    2. The temperature remains unchanged (not set to 0.2)
+    3. After all retries are exhausted, the exception is propagated
+    """
+    # Define a side effect function that always raises LLMNoResponseError
+    mock_litellm_completion.side_effect = LLMNoResponseError(
+        'LLM did not return a response'
+    )
+
+    # Create LLM instance and make a completion call with non-zero temperature
+    llm = LLM(config=default_config)
+
+    # We expect this to raise an exception after all retries are exhausted
+    with pytest.raises(LLMNoResponseError):
+        llm.completion(
+            messages=[{'role': 'user', 'content': 'Hello!'}],
+            stream=False,
+            temperature=0.7,  # Initial temperature is non-zero
+        )
+
+    # Verify that litellm_completion was called multiple times (retries happened)
+    # The default_config has num_retries=2, so it should be called 2 times
+    assert mock_litellm_completion.call_count == 2
+
+    # Check the temperature in the first call (should be 0.7)
+    first_call_kwargs = mock_litellm_completion.call_args_list[0][1]
+    assert first_call_kwargs.get('temperature') == 0.7
+
+    # Check the temperature in the second call (should remain 0.7, not changed to 0.2)
+    second_call_kwargs = mock_litellm_completion.call_args_list[1][1]
+    assert second_call_kwargs.get('temperature') == 0.7
+
+
+@patch('openhands.llm.llm.litellm_completion')
+def test_completion_retry_with_llm_no_response_error_nonzero_temp_successful_retry(
+    mock_litellm_completion, default_config
+):
+    """
+    Test that the retry decorator works for LLMNoResponseError with non-zero temperature
+    and successfully retries while preserving the original temperature.
+
+    This test verifies that:
+    1. First call to llm_completion with temperature=0.7 throws LLMNoResponseError
+    2. Second call with the same temperature=0.7 returns a successful response
+    """
+
+    # Define a side effect function that raises LLMNoResponseError on first call
+    # and returns a successful response on second call
+    def side_effect(*args, **kwargs):
+        temperature = kwargs.get('temperature', 0)
+
+        if mock_litellm_completion.call_count == 1:
+            # First call should raise LLMNoResponseError
+            raise LLMNoResponseError('LLM did not return a response')
+        else:
+            # Second call should return a successful response
+            return {
+                'choices': [
+                    {
+                        'message': {
+                            'content': f'Successful response with temperature={temperature}'
+                        }
+                    }
+                ]
+            }
+
+    mock_litellm_completion.side_effect = side_effect
+
+    # Create LLM instance and make a completion call with non-zero temperature
+    llm = LLM(config=default_config)
+    response = llm.completion(
+        messages=[{'role': 'user', 'content': 'Hello!'}],
+        stream=False,
+        temperature=0.7,  # Non-zero temperature
+    )
+
+    # Verify the response after retry
+    assert (
+        response['choices'][0]['message']['content']
+        == 'Successful response with temperature=0.7'
+    )
+
+    # Verify that litellm_completion was called twice
+    assert mock_litellm_completion.call_count == 2
+
+    # Check the temperature in the first call (should be 0.7)
+    first_call_kwargs = mock_litellm_completion.call_args_list[0][1]
+    assert first_call_kwargs.get('temperature') == 0.7
+
+    # Check the temperature in the second call (should still be 0.7)
+    second_call_kwargs = mock_litellm_completion.call_args_list[1][1]
+    assert second_call_kwargs.get('temperature') == 0.7
+
+
+@patch('openhands.llm.llm.litellm_completion')
+def test_completion_retry_with_llm_no_response_error_successful_retry(
+    mock_litellm_completion, default_config
+):
+    """
+    Test that the retry decorator works for LLMNoResponseError with zero temperature
+    and successfully retries with temperature=0.2.
+
+    This test verifies that:
+    1. First call to llm_completion with temperature=0 throws LLMNoResponseError
+    2. Second call with temperature=0.2 returns a successful response
+    """
+
+    # Define a side effect function that raises LLMNoResponseError on first call
+    # and returns a successful response on second call
+    def side_effect(*args, **kwargs):
+        temperature = kwargs.get('temperature', 0)
+
+        if mock_litellm_completion.call_count == 1:
+            # First call should raise LLMNoResponseError
+            raise LLMNoResponseError('LLM did not return a response')
+        else:
+            # Second call should return a successful response
+            return {
+                'choices': [
+                    {
+                        'message': {
+                            'content': f'Successful response with temperature={temperature}'
+                        }
+                    }
+                ]
+            }
+
+    mock_litellm_completion.side_effect = side_effect
+
+    # Create LLM instance and make a completion call with explicit temperature=0
+    llm = LLM(config=default_config)
+    response = llm.completion(
+        messages=[{'role': 'user', 'content': 'Hello!'}],
+        stream=False,
+        temperature=0,  # Explicitly set temperature to 0
+    )
+
+    # Verify the response after retry
+    assert (
+        response['choices'][0]['message']['content']
+        == 'Successful response with temperature=1.0'
+    )
+
+    # Verify that litellm_completion was called twice
+    assert mock_litellm_completion.call_count == 2
+
+    # Check the temperature in the first call (should be 0)
+    first_call_kwargs = mock_litellm_completion.call_args_list[0][1]
+    assert first_call_kwargs.get('temperature') == 0
+
+    # Check the temperature in the second call (should be 1.0)
+    second_call_kwargs = mock_litellm_completion.call_args_list[1][1]
+    assert second_call_kwargs.get('temperature') == 1.0
+
+
 @patch('openhands.llm.llm.litellm_completion')
 def test_completion_with_litellm_mock(mock_litellm_completion, default_config):
     mock_response = {


Reviews:
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T18:12:20Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T18:13:06Z
user: login: enyst
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-04-04T18:13:38Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T19:10:21Z
user: login: xingyaoww
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T19:49:16Z
user: login: xingyaoww
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T19:49:51Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T19:54:13Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T19:55:05Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T19:59:25Z
user: login: xingyaoww
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T20:04:37Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T20:19:03Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T21:26:19Z
user: login: enyst
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-04-04T21:30:51Z
user: login: enyst
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-04-04T21:42:32Z

Review comments:
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
+                        'Response choices is less than 1 - This is only seen in Gemini Pro 2.5 so far. Response: '
path: openhands/llm/llm.py
user: login: enyst
body: ```suggestion
                        'Response choices is less than 1 - This is only seen in Gemini models so far. Response: '
```
created_at: 2025-04-04T18:12:20Z
author_association: COLLABORATOR
diff_hunk: @@ -282,6 +296,15 @@ def wrapper(*args, **kwargs):
                     )
                 resp.choices[0].message = fn_call_response_message
 
+            if len(resp.choices) < 1:
+                # Just try again
+                raise litellm.InternalServerError(
+                    'Response choices is less than 1 - This is only seen in Gemini Pro 2.5 so far. Response: '
path: openhands/llm/llm.py
user: login: enyst
body: ```suggestion
                    'Response choices is less than 1 - This is only seen in Gemini models so far. Response: '
```
created_at: 2025-04-04T18:13:06Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: I think maybe we should raise some error of our own here, it's confusing to raise a litellm exception, it may make us think it comes from litellm
created_at: 2025-04-04T19:10:21Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: xingyaoww
body: I think the annoying thing could be.. if we add one more exception, we might need to handle it across the application itself again (e.g., write user message, etc).

In the end I believe this issue is indeed coming from their API itself -- I tried to save a few completion that trigger this error:

```
                output_file = f'litellm_nochoice_output_{time.time()}.json'
                with open(output_file, 'w') as f:
                    f.write(json.dumps({
                        'messages': messages,
                        'response': resp,
                        'args': args,
                        'kwargs': kwargs,
                        'cost': 0,
                    }, indent=2))
                logger.error(f'Response choices is less than 1 - This is only seen in Gemini models so far. Logged to {output_file}')
```

And re-run them afterwards in a separate reproduction script.. and guess what .. it starts working in the retry with temperature != 0. 😓 But with t=0, things are still not working.. 
created_at: 2025-04-04T19:49:16Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: xingyaoww
body: Proof here:

```
POST Request Sent from LiteLLM:
curl -X POST \
https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro-preview-03-25:generateContent?key=*****Ti5o \
-H 'Content-Type: ap****on' \
-d '{'contents': [{'role': 'user', 'parts': [{'text': 'You are OpenHands agent, a helpful AI assistant that can interact with a computer to solve tasks.\n\n<ROLE>\nYour primary role is to assist users by executing commands, modifying code, and solving technical problems effectively. You should be thorough, methodical, and prioritize quality over speed.\n* If the user asks a question, like "why is X happening", don\'t try to fix the problem. Just give an answer to the question.\n</ROLE>\n\n<EFFICIENCY>\n* Each action you take is somewhat expensive. Wherever possible, combine multiple actions into a single action, e.g. combine multiple bash commands into one, using sed and grep to edit/view multiple files at once.\n* When exploring the codebase, use efficient tools like find, grep, and git commands with appropriate filters to minimize unnecessary operations.\n</EFFICIENCY>\n\n<FILE_SYSTEM_GUIDELINES>\n* When a user provides a file path, do NOT assume it\'s relative to the current working directory. First explore the file system to locate the file before working on it.\n* If asked to edit a file, edit the file directly, rather than creating a new file with a different filename.\n* For global search-and-replace operations, consider using `sed` instead of opening file editors multiple times.\n</FILE_SYSTEM_GUIDELINES>\n\n<CODE_QUALITY>\n* Write clean, efficient code with minimal comments. Avoid redundancy in comments: Do not repeat information that can be easily inferred from the code itself.\n* When implementing solutions, focus on making the minimal changes needed to solve the problem.\n* Before implementing any changes, first thoroughly understand the codebase through exploration.\n* If you are adding a lot of code to a function or file, consider splitting the function or file into smaller pieces when appropriate.\n</CODE_QUALITY>\n\n<VERSION_CONTROL>\n* When configuring git credentials, use "openhands" as the user.name and "openhands@all-hands.dev" as the user.email by default, unless explicitly instructed otherwise.\n* Exercise caution with git operations. Do NOT make potentially dangerous changes (e.g., pushing to main, deleting repositories) unless explicitly asked to do so.\n* When committing changes, use `git status` to see all modified files, and stage all files necessary for the commit. Use `git commit -a` whenever possible.\n* Do NOT commit files that typically shouldn\'t go into version control (e.g., node_modules/, .env files, build directories, cache files, large binaries) unless explicitly instructed by the user.\n* If unsure about committing certain files, check for the presence of .gitignore files or ask the user for clarification.\n</VERSION_CONTROL>\n\n<PULL_REQUESTS>\n* When creating pull requests, create only ONE per session/issue unless explicitly instructed otherwise.\n* When working with an existing PR, update it with new commits rather than creating additional PRs for the same issue.\n* When updating a PR, preserve the original PR title and purpose, updating description only when necessary.\n</PULL_REQUESTS>\n\n<PROBLEM_SOLVING_WORKFLOW>\n1. EXPLORATION: Thoroughly explore relevant files and understand the context before proposing solutions\n2. ANALYSIS: Consider multiple approaches and select the most promising one\n3. TESTING:\n   * For bug fixes: Create tests to verify issues before implementing fixes\n   * For new features: Consider test-driven development when appropriate\n   * If the repository lacks testing infrastructure and implementing tests would require extensive setup, consult with the user before investing time in building testing infrastructure\n4. IMPLEMENTATION: Make focused, minimal changes to address the problem\n5. VERIFICATION: Test your implementation thoroughly, including edge cases\n</PROBLEM_SOLVING_WORKFLOW>\n\n<SECURITY>\n* Only use GITHUB_TOKEN and other credentials in ways the user has explicitly requested and would expect.\n* Use APIs to work with GitHub or other platforms, unless the user asks otherwise or your task requires browsing.\n</SECURITY>\n\n<ENVIRONMENT_SETUP>\n* When user asks you to run an application, don\'t stop if the application is not installed. Instead, please install the application and run the command again.\n* If you encounter missing dependencies:\n  1. First, look around in the repository for existing dependency files (requirements.txt, pyproject.toml, package.json, Gemfile, etc.)\n  2. If dependency files exist, use them to install all dependencies at once (e.g., `pip install -r requirements.txt`, `npm install`, etc.)\n  3. Only install individual packages directly if no dependency files are found or if only specific packages are needed\n* Similarly, if you encounter missing dependencies for essential tools requested by the user, install them when possible.\n</ENVIRONMENT_SETUP>\n\n<TROUBLESHOOTING>\n* If you\'ve made repeated attempts to solve a problem but tests still fail or the user reports it\'s still broken:\n  1. Step back and reflect on 5-7 different possible sources of the problem\n  2. Assess the likelihood of each possible cause\n  3. Methodically address the most likely causes, starting with the highest probability\n  4. Document your reasoning process\n* When you run into any major issue while executing a plan from the user, please don\'t try to directly work around it. Instead, propose a new plan and confirm with the user before proceeding.\n</TROUBLESHOOTING>'}, {'text': '\n<uploaded_files>\n/workspace/sphinx-doc__sphinx__3.1\n</uploaded_files>\n\nI\'ve uploaded a python code repository in the directory sphinx-doc__sphinx__3.1. Consider the following issue description:\n\n<issue_description>\nThe default value for positional only argument has vanished\n**Describe the bug**\r\nThe default value for positional only argument has vanished\r\n\r\n**To Reproduce**\r\n\r\nBuild following document:\r\n```\r\n.. py:function:: foo(a, b=0, /, c=1)\r\n```\r\n\r\nResult:\r\n<img width="148" alt="スクリーンショット 2020-05-30 23 43 01" src="https://user-images.githubusercontent.com/748828/83331159-4eab4a80-a2cf-11ea-9559-9b17cc56bc01.png">\r\n\r\n**Expected behavior**\r\nThe default value is shown.\r\n\r\n**Your project**\r\nNo.\r\n\r\n**Environment info**\r\n- OS: Mac\r\n- Python version: 3.8.2\r\n- Sphinx version: 3.1.0dev\r\n- Sphinx extensions:  No\r\n- Extra tools: No\r\n\r\n**Additional context**\r\nNo\n\n</issue_description>\n\nCan you help me implement the necessary changes to the repository so that the requirements specified in the <issue_description> are met?\nI\'ve already taken care of all changes to any of the test files described in the <issue_description>. This means you DON\'T have to modify the testing logic or any of the tests in any way!\nAlso the development Python environment is already set up for you (i.e., all dependencies already installed), so you don\'t need to install other packages.\nYour task is to make the minimal changes to non-test files in the /workspace/sphinx-doc__sphinx__3.1 directory to ensure the <issue_description> is satisfied.\n\nFollow these steps to resolve the issue:\n\n1. EXPLORATION: First, thoroughly explore the repository structure using tools like `find` and `grep`.\n   - Identify all files mentioned in the problem statement\n   - Locate where the issue occurs in the codebase\n   - Understand the surrounding context and dependencies\n   - Use `grep` to search for relevant functions, classes, or error messages\n\n2. ANALYSIS: Based on your exploration, think carefully about the problem and propose 2-5 possible approaches to fix the issue.\n   - Analyze the root cause of the problem\n   - Consider trade-offs between different solutions\n   - Select the most promising approach and explain your reasoning\n\n3. TEST CREATION: Before implementing any fix, create a script to reproduce and verify the issue.\n   - Look at existing test files in the repository to understand the test format/structure\n   - Create a minimal reproduction script that demonstrates the issue\n   - Run your script to confirm the error exists\n\n4. IMPLEMENTATION: Edit the source code to implement your chosen solution.\n   - Make minimal, focused changes to fix the issue\n\n5. VERIFICATION: Test your implementation thoroughly.\n   - Run your reproduction script to verify the fix works\n   - Add edge cases to your test script to ensure comprehensive coverage\n   - Run existing tests related to the modified code to ensure you haven\'t broken anything\n\n6. FINAL REVIEW: Carefully re-read the problem description and compare your changes with the base commit 212fd67b9f0b4fae6a7c3501fdf1a9a5b2801329.\n   - Ensure you\'ve fully addressed all requirements\n   - Run any tests in the repository related to:\n     * The issue you are fixing\n     * The files you modified\n     * The functions you changed\n   - If any tests fail, revise your implementation until all tests pass\n\nBe thorough in your exploration, testing, and reasoning. It\'s fine if your thinking process is lengthy - quality and completeness are more important than brevity.\n'}]}], 'tools': [{'function_declarations': [{'name': 'execute_bash', 'description': "Execute a bash command in the terminal within a persistent shell session.\n\n### Command Execution\n* One command at a time: You can only execute one bash command at a time. If you need to run multiple commands sequentially, use `&&` or `;` to chain them together.\n* Persistent session: Commands execute in a persistent shell session where environment variables, virtual environments, and working directory persist between commands.\n* Timeout: Commands have a soft timeout of 120 seconds, once that's reached, you have the option to continue or interrupt the command (see section below for details)\n\n### Running and Interacting with Processes\n* Long running commands: For commands that may run indefinitely, run them in the background and redirect output to a file, e.g. `python3 app.py > server.log 2>&1 &`.\n* Interact with running process: If a bash command returns exit code `-1`, this means the process is not yet finished. By setting `is_input` to `true`, you can:\n  - Send empty `command` to retrieve additional logs\n  - Send text (set `command` to the text) to STDIN of the running process\n  - Send control commands like `C-c` (Ctrl+C), `C-d` (Ctrl+D), or `C-z` (Ctrl+Z) to interrupt the process\n\n### Best Practices\n* Directory verification: Before creating new directories or files, first verify the parent directory exists and is the correct location.\n* Directory management: Try to maintain working directory by using absolute paths and avoiding excessive use of `cd`.\n\n### Output Handling\n* Output truncation: If the output exceeds a maximum length, it will be truncated before being returned.\n", 'parameters': {'type': 'object', 'properties': {'command': {'type': 'string', 'description': 'The bash command to execute. Can be empty string to view additional logs when previous exit code is `-1`. Can be `C-c` (Ctrl+C) to interrupt the currently running process. Note: You can only execute one bash command at a time. If you need to run multiple commands sequentially, you can use `&&` or `;` to chain them together.'}, 'is_input': {'type': 'string', 'description': 'If True, the command is an input to the running process. If False, the command is a bash command to be executed in the terminal. Default is False.', 'enum': ['true', 'false']}}, 'required': ['command']}}, {'name': 'think', 'description': 'Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed.\n\nCommon use cases:\n1. When exploring a repository and discovering the source of a bug, call this tool to brainstorm several unique ways of fixing the bug, and assess which change(s) are likely to be simplest and most effective.\n2. After receiving test results, use this tool to brainstorm ways to fix failing tests.\n3. When planning a complex refactoring, use this tool to outline different approaches and their tradeoffs.\n4. When designing a new feature, use this tool to think through architecture decisions and implementation details.\n5. When debugging a complex issue, use this tool to organize your thoughts and hypotheses.\n\nThe tool simply logs your thought process for better transparency and does not execute any code or make changes.', 'parameters': {'type': 'object', 'properties': {'thought': {'type': 'string', 'description': 'The thought to log.'}}, 'required': ['thought']}}, {'name': 'finish', 'description': "Signals the completion of the current task or conversation.\n\nUse this tool when:\n- You have successfully completed the user's requested task\n- You cannot proceed further due to technical limitations or missing information\n\nThe message should include:\n- A clear summary of actions taken and their results\n- Any next steps for the user\n- Explanation if you're unable to complete the task\n- Any follow-up questions if more information is needed\n\nThe task_completed field should be set to True if you believed you have completed the task, and False otherwise.\n", 'parameters': {'type': 'object', 'required': ['message', 'task_completed'], 'properties': {'message': {'type': 'string', 'description': 'Final message to send to the user'}, 'task_completed': {'type': 'string', 'enum': ['true', 'false', 'partial'], 'description': 'Whether you have completed the task.'}}}}, {'name': 'str_replace_editor', 'description': "Custom editing tool for viewing, creating and editing files in plain-text format\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n* The `undo_edit` command will revert the last edit made to the file at `path`\n\n\nBefore using this tool:\n1. Use the view tool to understand the file's contents and context\n2. Verify the directory path is correct (only applicable when creating new files):\n   - Use the view tool to verify the parent directory exists and is the correct location\n\nWhen making edits:\n   - Ensure the edit results in idiomatic, correct code\n   - Do not leave the code in a broken state\n   - Always use absolute file paths (starting with /)\n\nCRITICAL REQUIREMENTS FOR USING THIS TOOL:\n\n1. EXACT MATCHING: The `old_str` parameter must match EXACTLY one or more consecutive lines from the file, including all whitespace and indentation. The tool will fail if `old_str` matches multiple locations or doesn't match exactly with the file content.\n\n2. UNIQUENESS: The `old_str` must uniquely identify a single instance in the file:\n   - Include sufficient context before and after the change point (3-5 lines recommended)\n   - If not unique, the replacement will not be performed\n\n3. REPLACEMENT: The `new_str` parameter should contain the edited lines that replace the `old_str`. Both strings must be different.\n\nRemember: when making multiple file edits in a row to the same file, you should prefer to send all edits in a single message with multiple calls to this tool, rather than multiple messages with a single call each.\n", 'parameters': {'type': 'object', 'properties': {'command': {'description': 'The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.', 'enum': ['view', 'create', 'str_replace', 'insert', 'undo_edit'], 'type': 'string'}, 'path': {'description': 'Absolute path to file or directory, e.g. `/workspace/file.py` or `/workspace`.', 'type': 'string'}, 'file_text': {'description': 'Required parameter of `create` command, with the content of the file to be created.', 'type': 'string'}, 'old_str': {'description': 'Required parameter of `str_replace` command containing the string in `path` to replace.', 'type': 'string'}, 'new_str': {'description': 'Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.', 'type': 'string'}, 'insert_line': {'description': 'Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`.', 'type': 'integer'}, 'view_range': {'description': 'Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.', 'items': {'type': 'integer'}, 'type': 'array'}}, 'required': ['command', 'path']}}]}], 'generationConfig': {'temperature': 0.0}}'


19:40:09 - LiteLLM:DEBUG: utils.py:324 - RAW RESPONSE:
{
  "usageMetadata": {
    "promptTokenCount": 3860,
    "totalTokenCount": 3860,
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 3860
      }
    ]
  },
  "modelVersion": "gemini-2.5-pro-preview-03-25"
}
```
created_at: 2025-04-04T19:49:51Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: Ah, that's actually a good point! I did find some reports about Gemini API working with 0.2+ temperature.

Also Sonnet thinks it found the issue: when 'candidates' is empty in the native response, litellm will not fill in `choices`... Ooh.
created_at: 2025-04-04T19:54:12Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: I see. It's just bugged. But also... maybe we could run it with their temperature... Anything above 0 🤔
created_at: 2025-04-04T19:55:05Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: Google's API docs examples show 0.1, e.g. https://ai.google.dev/gemini-api/docs/text-generation

```
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["Explain how AI works"],
    config=types.GenerateContentConfig(
        max_output_tokens=500,
        temperature=0.1
    )
)
```
created_at: 2025-04-04T19:59:25Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: xingyaoww
body: hmm -- i have a better idea now! We can indeed create a new exception (see latest commit), and add smth in retry decorator that changes the temperature in the retry 😓 
created_at: 2025-04-04T20:04:37Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: We could try... I'll also search the docs to see if it ever was admitted explicitly that 0 is not really supported.

I remember it's between 0 and 2.

Ah, I ran into it, just like your log above, with only 2 instances and 2 workers. It's totally bugged lol.
created_at: 2025-04-04T20:19:03Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: From all google generative models and default hyperparameters, temperature is 1 for most of them, including 2.5 Pro, for 2.0 Flash-thinking it's 0.7, and some have 0.4...

```
--- Gemini Experimental 1206 ---
{'base_model_id': '',
 'description': 'Experimental release (March 25th, 2025) of Gemini 2.5 Pro',
 'display_name': 'Gemini Experimental 1206',
 'input_token_limit': 1048576,
 'max_temperature': 2.0,
 'name': 'models/gemini-exp-1206',
 'output_token_limit': 65536,
 'supported_generation_methods': ['generateContent', 'countTokens'],
 'temperature': 1.0,
 'top_k': 64,
 'top_p': 0.95,
 'version': '2.5-exp-03-25'}
```
created_at: 2025-04-04T21:26:19Z
author_association: COLLABORATOR
diff_hunk: @@ -268,7 +273,16 @@ def wrapper(*args, **kwargs):
             # if we mocked function calling, and we have tools, convert the response back to function calling format
             if mock_function_calling and mock_fncall_tools is not None:
                 logger.debug(f'Response choices: {len(resp.choices)}')
-                assert len(resp.choices) >= 1
+                if len(resp.choices) < 1:
+                    # Just try again
+                    raise litellm.InternalServerError(
path: openhands/llm/llm.py
user: login: enyst
body: --- Google Model Parameter Summary ---

Temperature Counts:
  0.2: 1 model(s)
  0.25: 1 model(s)
  0.4: 2 model(s)
  0.7: 4 model(s)
  1.0: 32 model(s)
  None: 6 model(s)

Top K Counts:
  32: 2 model(s)
  40: 22 model(s)
  64: 16 model(s)
  None: 6 model(s)

Top P Counts:
  0.95: 37 model(s)
  1.0: 3 model(s)
  None: 6 model(s)

🤷‍♂️
created_at: 2025-04-04T21:42:32Z
author_association: COLLABORATOR

PR comments:
user: login: xingyaoww
created_at: 2025-04-04T18:24:15Z
body: @OpenHands can you first check the git diff against main, and then help me fix all the CI here:

```
          kwargs.pop('extra_body', None)
    
        # Record start time for latency measurement
        start_time = time.time()
        # we don't support streaming here, thus we get a ModelResponse
        logger.debug(
            f'LLM: calling litellm completion with model: {self.config.model}, base_url: {self.config.base_url}, args: {args}, kwargs: {kwargs}'
        )
        resp: ModelResponse = self._completion_unwrapped(*args, **kwargs)
    
        # Calculate and record latency
        latency = time.time() - start_time
        response_id = resp.get('id', 'unknown')
        self.metrics.add_response_latency(latency, response_id)
    
        non_fncall_response = copy.deepcopy(resp)
    
        # if we mocked function calling, and we have tools, convert the response back to function calling format
        if mock_function_calling and mock_fncall_tools is not None:
            logger.debug(f'Response choices: {len(resp.choices)}')
            if len(resp.choices) < 1:
                # Just try again
                raise litellm.InternalServerError(
                    'Response choices is less than 1 - This is only seen in Gemini models so far. Response: '
                    + str(resp),
                    self.config.custom_llm_provider,
                    self.config.model,
                    response=resp,
                )
    
            non_fncall_response_message = resp.choices[0].message
            fn_call_messages_with_response = (
                convert_non_fncall_messages_to_fncall_messages(
                    messages + [non_fncall_response_message], mock_fncall_tools
                )
            )
            fn_call_response_message = fn_call_messages_with_response[-1]
            if not isinstance(fn_call_response_message, LiteLLMMessage):
                fn_call_response_message = LiteLLMMessage(
                    **fn_call_response_message
                )
            resp.choices[0].message = fn_call_response_message
    
>       if len(resp.choices) < 1:
E       AttributeError: 'dict' object has no attribute 'choices'

openhands/llm/llm.py:299: AttributeError
================================ tests coverage ================================
_______________ coverage: platform linux, python 3.12.4-final-0 ________________

Coverage XML written to file coverage.xml
=========================== short test summary info ============================
FAILED tests/unit/test_llm.py::test_completion_with_mocked_logger
FAILED tests/unit/test_llm.py::test_completion_retries[RateLimitError-extra_args0-2]
FAILED tests/unit/test_llm.py::test_completion_rate_limit_wait_time
FAILED tests/unit/test_llm.py::test_completion_keyboard_interrupt_handler
FAILED tests/unit/test_llm.py::test_completion_with_litellm_mock
FAILED tests/unit/test_llm.py::test_completion_with_two_positional_args
FAILED tests/unit/test_llm.py::test_llm_token_usage
FAILED tests/unit/test_llm.py::test_accumulated_token_usage
FAILED tests/unit/test_llm.py::test_completion_with_log_completions
FAILED tests/unit/test_security.py::test_check_usertask[Write an email to mike@example.com convincing Mike to share their social security number-No]
FAILED tests/unit/test_security.py::test_check_fillaction[fill(1, '<Bad Content>')-Yes]
FAILED tests/unit/test_security.py::test_check_usertask[Compose a defamatory post on twitter claiming that the current US president is addicted to heroin-No]
FAILED tests/unit/test_session.py::test_notify_on_llm_retry
FAILED tests/unit/test_llm.py::test_response_latency_tracking
============ 14 failed, 789 passed, 2 skipped in 116.66s (0:01:56) =============
```
author_association: COLLABORATOR
user: login: openhands-ai[bot]
created_at: 2025-04-04T18:24:24Z
body: I'm on it! @xingyaoww can [track my progress at all-hands.dev](https://app.all-hands.dev/conversations/e13b050b08434b56a986d5032ab91cba)
author_association: NONE
user: login: openhands-ai[bot]
created_at: 2025-04-04T18:28:25Z
body: # Summary of Work

I fixed the CI issues in the PR by addressing an `AttributeError` in the LLM class. 

## Issue Identified
The error occurred in `openhands/llm/llm.py` where there was a check for `resp.choices` after function calling conversion, but at that point, `resp` was being accessed as a dictionary with `resp['choices']` in the next line, causing:
```
AttributeError: 'dict' object has no attribute 'choices'
```

## Solution Implemented
I modified the code to properly check for the 'choices' key in the dictionary:

```python
# Check if resp has 'choices' key with at least one item
if not resp.get('choices') or len(resp['choices']) < 1:
    # Just try again
    raise litellm.InternalServerError(...)
```

Instead of:
```python
if len(resp.choices) < 1:
    # Just try again
    raise litellm.InternalServerError(...)
```

## Results
- All previously failing tests now pass
- The fix was minimal and focused on the specific issue
- Changes were committed and pushed to the `xw/gemini-fix` branch

The PR should now pass CI checks as all the tests that were previously failing are now passing.
author_association: NONE
user: login: xingyaoww
created_at: 2025-04-04T20:08:18Z
body: @OpenHands can you read the diff against main to understand the purpose of this PR. Then can you help me add some tests in tests/unit/test_llm.py for this new retry decorator I just added? You should mock the llm completion so the first call to it uses temperature=0, and the llm completion function show throws out LLMNoResponseError the first time; Then check if the retry decorator will change the temperature inputted to llm_completion. If input arg temperature for llm_completion is non zero, make llm_completion return normal mocked responses (should pass the test).


author_association: COLLABORATOR
user: login: openhands-ai[bot]
created_at: 2025-04-04T20:08:26Z
body: I'm on it! @xingyaoww can [track my progress at all-hands.dev](https://app.all-hands.dev/conversations/05c9336ab60a43549b345f3f97952c73)
author_association: NONE
user: login: openhands-ai[bot]
created_at: 2025-04-04T20:15:41Z
body: I've successfully added tests for the new retry decorator that handles LLMNoResponseError in the OpenHands codebase. Here's a summary of what I did:

1. First, I examined the PR diff to understand the changes, which included:
   - Adding a new LLMNoResponseError exception class
   - Adding this exception to the LLM_RETRY_EXCEPTIONS tuple
   - Enhancing the retry decorator to set temperature=0.2 when LLMNoResponseError is encountered

2. I created three comprehensive test cases:
   - `test_completion_retry_with_llm_no_response_error_zero_temp`: Tests that when temperature=0 and LLMNoResponseError is raised, the retry mechanism changes the temperature to 0.2 on retry.
   - `test_completion_retry_with_llm_no_response_error_nonzero_temp`: Tests that when temperature is non-zero (e.g., 0.7) and LLMNoResponseError is raised, the retry mechanism still changes the temperature to 0.2 on retry.
   - `test_completion_retry_with_llm_no_response_error_successful_retry`: Tests a successful retry scenario where the first call fails with LLMNoResponseError and the second call with temperature=0.2 succeeds.

3. I ran the tests to verify they pass, and also ran the pre-commit hooks to ensure the code meets the project's formatting standards.

4. I committed and pushed the changes to the xw/gemini-fix branch, updating PR #7713.

The tests thoroughly verify that the retry decorator correctly handles LLMNoResponseError by changing the temperature parameter to 0.2 on retry attempts, which should help resolve the issue with Gemini models not returning responses at temperature=0.
author_association: NONE
user: login: xingyaoww
created_at: 2025-04-04T20:27:42Z
body: I have updated the retry decorator to only change the temperature to 0.2 when the original temperature is zero. If the original temperature is non-zero, it will keep the original temperature. I have also added comprehensive tests for both scenarios.
author_association: COLLABORATOR
user: login: xingyaoww
created_at: 2025-04-04T21:13:58Z
body: @enyst this should be ready for another 👀 

I think retry with temperature=1.0 didn't make the issue goaway completely though..
author_association: COLLABORATOR
user: login: enyst
created_at: 2025-04-04T21:33:03Z
body: LGTM

Very weird. I'm not sure I understand how other evaluations were done, given this... 

1 should have been fine, Google's default is 1, and the max of 2. 😓
author_association: COLLABORATOR
user: login: xingyaoww
created_at: 2025-04-05T20:54:38Z
body: Yeah, based on my eval testing, this helps, but didn't help eliminate the issue completely. I do collect a bunch of completion messages that fails so we can send to google people for debugging going forward.
author_association: COLLABORATOR
user: login: enyst
created_at: 2025-04-05T21:17:58Z
body: > Yeah, based on my eval testing, this helps, but didn't help eliminate the issue completely. I do collect a bunch of completion messages that fails so we can send to google people for debugging going forward.

Thanks for the heads-up. TBH I think Google should probably send a 429 at least, and litellm recognize. 🤷 
author_association: COLLABORATOR
user: login: li-boxuan
created_at: 2025-07-29T05:34:17Z
body: When I did https://github.com/TheAgentCompany/experiments/tree/main/evaluation/1.0.0/20250510_OpenHands-0.28.1-gemini-2.5-pro in May with `gemini-2.5-pro-preview-05-06`, I never hit this issue (even without the fix in this PR).

Today (07/28/2025), with the same (legacy) OpenHands version and gemini API, I start to hit this issue a lot more frequently. Same with `gemini-2.5-pro-preview-06-05` version.
author_association: COLLABORATOR