{"record":{"id":"50989fd79bfd7835","repo":"mlflow/mlflow","slug":"max-iterations-reached","errorCode":null,"errorMessage":"Max iterations reached","messagePattern":"Max iterations reached","errorType":"http","errorClass":"AIGatewayException","httpStatus":500,"severity":"error","filePath":"mlflow/gateway/providers/openai.py","lineNumber":464,"sourceCode":"                            \"function\": {\n                                \"name\": func[\"name\"],\n                                \"arguments\": func[\"arguments\"],\n                            },\n                        })\n\n                if message_content := assistant_msg.pop(\"content\", None):\n                    messages.append({\"role\": \"assistant\", \"content\": message_content})\n                messages += [assistant_msg, *tool_messages]\n\n                if user_tool_calls:\n                    # We can't go on without a response from the user, so we break here\n                    if uc_func_calls:\n                        resp[\"choices\"][0][\"message\"][\"content\"] = join_uc_functions(uc_func_calls)\n\n                    resp[\"choices\"][0][\"message\"][\"tool_calls\"] = user_tool_calls\n                    break\n            else:\n                raise AIGatewayException(\n                    status_code=500,\n                    detail=\"Max iterations reached\",\n                )\n        else:\n            # No UC functions to execute\n            resp = await send_request(\n                headers=self.headers,\n                base_url=self.base_url,\n                path=\"chat/completions\",\n                payload=self.adapter_class.chat_to_model(payload, self.config),\n            )\n            token_usage_accumulator.update(resp.get(\"usage\", {}))\n\n        # Update the token usage\n        resp[\"usage\"].update(token_usage_accumulator.dict())\n\n        return resp\n","sourceCodeStart":446,"sourceCodeEnd":482,"githubUrl":"https://github.com/mlflow/mlflow/blob/6a27f2decc0b76eb1b54af31849784addb357dbc/mlflow/gateway/providers/openai.py#L446-L482","documentation":"During UC function calling, _chat_uc_function loops executing tool calls until the model stops requesting tools. A for/else guard raises AIGatewayException (status 500, 'Max iterations reached') when the iteration limit is exhausted while the model still demands tool calls, preventing an infinite loop.","triggerScenarios":"A chat request with UC functions where the model keeps emitting tool_calls for the maximum number of loop iterations without producing a final answer — often due to malformed tool results, functions that error repeatedly, or a model stuck in a tool-calling cycle.","commonSituations":"UC functions that return errors the model retries endlessly, very large/ambiguous prompts causing repeated tool invocations, or missing/invalid tool results fed back in subsequent messages.","solutions":["Inspect the conversation payload and executed UC function results to find why the model keeps calling tools; fix the function or its inputs.","Reduce or clarify the tools exposed (remove irrelevant UC functions from the endpoint's UC function list).","Retry the request; transient model behavior can cause the loop to not converge.","Check that tool result messages returned in follow-up requests are correctly formatted (role 'tool' with proper tool_call_id).","Upgrade MLflow if the loop limit seems too low for your multi-tool workflow."],"exampleFix":null,"handlingStrategy":"retry","validationCode":"# Trim tool definitions and verify tool result messages are well-formed before sending:\nassert all(m.get(\"role\") != \"tool\" or m.get(\"tool_call_id\") for m in messages)","typeGuard":null,"tryCatchPattern":"try:\n    resp = client.chat.completions.create(...)\nexcept Exception as e:\n    if \"Max iterations reached\" in str(e):\n        logging.warning(\"UC tool loop did not converge; retrying with fewer tools\")\n        resp = client.chat.completions.create(..., tools=tools[:1])\n    else:\n        raise","preventionTips":["Only expose the UC functions the task actually needs","Ensure UC functions return success payloads, not repeated errors","Feed tool results back with correct role 'tool' and tool_call_id","Monitor for repeated tool_call patterns in traces"],"tags":["gateway","databricks","tool-calling","openai","timeout"],"backgroundTag":"tool-call-loop-limit-exceeded","analyzedSha":"6a27f2decc0b76eb1b54af31849784addb357dbc","analyzedAt":"2026-08-29T20:54:51.419Z","schemaVersion":2},"datasetVersion":"2026-08-29T22:17:34.462Z"}