AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix: add empty choices guard in extract_openai_tool_calls() (#12540)
goingforstudying-ctrlc410be890e33
diff --git a/autogpt_platform/backend/backend/blocks/llm.py b/autogpt_platform/backend/backend/blocks/llm.pyindex f31ccc6f05..c686031f4e 100644--- a/autogpt_platform/backend/backend/blocks/llm.py+++ b/autogpt_platform/backend/backend/blocks/llm.py@@ -724,6 +724,9 @@ def convert_openai_tool_fmt_to_anthropic(def extract_openai_reasoning(response) -> str | None:"""Extract reasoning from OpenAI-compatible response if available.""""""Note: This will likely not working since the reasoning is not present in another Response API"""+ if not response.choices:+ logger.warning("LLM response has empty choices in extract_openai_reasoning")+ return Nonereasoning = Nonechoice = response.choices[0]if hasattr(choice, "reasoning") and getattr(choice, "reasoning", None):@@ -739,6 +742,9 @@ def extract_openai_reasoning(response) -> str | None:def extract_openai_tool_calls(response) -> list[ToolContentBlock] | None:"""Extract tool calls from OpenAI-compatible response."""+ if not response.choices:+ logger.warning("LLM response has empty choices in extract_openai_tool_calls")+ return Noneif response.choices[0].message.tool_calls:return [ToolContentBlock(@@ -972,6 +978,8 @@ async def llm_call(response_format=response_format, # type: ignoremax_tokens=max_tokens,)+ if not response.choices:+ raise ValueError("Groq returned empty choices in response")return LLMResponse(raw_response=response.choices[0].message,prompt=prompt,@@ -1031,12 +1039,8 @@ async def llm_call(parallel_tool_calls=parallel_tool_calls_param,)- # If there's no response, raise an errorif not response.choices:- if response:- raise ValueError(f"OpenRouter error: {response}")- else:- raise ValueError("No response from OpenRouter.")+ raise ValueError(f"OpenRouter returned empty choices: {response}")tool_calls = extract_openai_tool_calls(response)reasoning = extract_openai_reasoning(response)@@ -1073,12 +1077,8 @@ async def llm_call(parallel_tool_calls=parallel_tool_calls_param,)- # If there's no response, raise an errorif not response.choices:- if response:- raise ValueError(f"Llama API error: {response}")- else:- raise ValueError("No response from Llama API.")+ raise ValueError(f"Llama API returned empty choices: {response}")tool_calls = extract_openai_tool_calls(response)reasoning = extract_openai_reasoning(response)@@ -1108,6 +1108,8 @@ async def llm_call(messages=prompt, # type: ignoremax_tokens=max_tokens,)+ if not completion.choices:+ raise ValueError("AI/ML API returned empty choices in response")return LLMResponse(raw_response=completion.choices[0].message,@@ -1144,6 +1146,9 @@ async def llm_call(parallel_tool_calls=parallel_tool_calls_param,)+ if not response.choices:+ raise ValueError(f"v0 API returned empty choices: {response}")+tool_calls = extract_openai_tool_calls(response)reasoning = extract_openai_reasoning(response)diff --git a/autogpt_platform/backend/backend/blocks/test/test_llm_empty_choices.py b/autogpt_platform/backend/backend/blocks/test/test_llm_empty_choices.pynew file mode 100644index 0000000000..b695e0e917--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/test/test_llm_empty_choices.py@@ -0,0 +1,87 @@+"""Tests for empty-choices guard in extract_openai_tool_calls() and extract_openai_reasoning()."""++from unittest.mock import MagicMock++from backend.blocks.llm import extract_openai_reasoning, extract_openai_tool_calls+++class TestExtractOpenaiToolCallsEmptyChoices:+ """extract_openai_tool_calls() must return None when choices is empty."""++ def test_returns_none_for_empty_choices(self):+ response = MagicMock()+ response.choices = []+ assert extract_openai_tool_calls(response) is None++ def test_returns_none_for_none_choices(self):+ response = MagicMock()+ response.choices = None+ assert extract_openai_tool_calls(response) is None++ def test_returns_tool_calls_when_choices_present(self):+ tool = MagicMock()+ tool.id = "call_1"+ tool.type = "function"+ tool.function.name = "my_func"+ tool.function.arguments = '{"a": 1}'++ message = MagicMock()+ message.tool_calls = [tool]++ choice = MagicMock()+ choice.message = message++ response = MagicMock()+ response.choices = [choice]++ result = extract_openai_tool_calls(response)+ assert result is not None+ assert len(result) == 1+ assert result[0].function.name == "my_func"++ def test_returns_none_when_no_tool_calls(self):+ message = MagicMock()+ message.tool_calls = None++ choice = MagicMock()+ choice.message = message++ response = MagicMock()+ response.choices = [choice]++ assert extract_openai_tool_calls(response) is None+++class TestExtractOpenaiReasoningEmptyChoices:+ """extract_openai_reasoning() must return None when choices is empty."""++ def test_returns_none_for_empty_choices(self):+ response = MagicMock()+ response.choices = []+ assert extract_openai_reasoning(response) is None++ def test_returns_none_for_none_choices(self):+ response = MagicMock()+ response.choices = None+ assert extract_openai_reasoning(response) is None++ def test_returns_reasoning_from_choice(self):+ choice = MagicMock()+ choice.reasoning = "Step-by-step reasoning"+ choice.message = MagicMock(spec=[]) # no 'reasoning' attr on message++ response = MagicMock(spec=[]) # no 'reasoning' attr on response+ response.choices = [choice]++ result = extract_openai_reasoning(response)+ assert result == "Step-by-step reasoning"++ def test_returns_none_when_no_reasoning(self):+ choice = MagicMock(spec=[]) # no 'reasoning' attr+ choice.message = MagicMock(spec=[]) # no 'reasoning' attr++ response = MagicMock(spec=[]) # no 'reasoning' attr+ response.choices = [choice]++ result = extract_openai_reasoning(response)+ assert result is Nonediff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.tomlindex 47a071dc6f..c9bf080529 100644--- a/autogpt_platform/backend/pyproject.toml+++ b/autogpt_platform/backend/pyproject.toml@@ -155,6 +155,7 @@ asyncio_default_fixture_loop_scope = "session"addopts = "-p no:syrupy"markers = ["supplementary: tests kept for coverage but superseded by integration tests",+ "integration: end-to-end tests that require a live database (skipped in CI)",]filterwarnings = ["ignore:'audioop' is deprecated:DeprecationWarning:discord.player",diff --git a/autogpt_platform/backend/test/test_data_creator.py b/autogpt_platform/backend/test/test_data_creator.pyindex 75ffb63154..15f6eec8fc 100644--- a/autogpt_platform/backend/test/test_data_creator.py+++ b/autogpt_platform/backend/test/test_data_creator.py@@ -17,6 +17,7 @@ images: {"""import asyncio+import osimport randomfrom datetime import datetime@@ -569,6 +570,10 @@ async def main():@pytest.mark.asyncio@pytest.mark.integration+ os.getenv("CI") == "true",+ reason="Data seeding test requires a dedicated database; not for CI",+)async def test_main_function_runs_without_errors():await main()