Skip to content

feat: implement fallback LLMs for agent execution #3033

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/crewai/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ class Agent(BaseAgent):
function_calling_llm: Optional[Union[str, InstanceOf[BaseLLM], Any]] = Field(
description="Language model that will run the agent.", default=None
)
fallback_llms: Optional[List[Union[str, InstanceOf[BaseLLM], Any]]] = Field(
default=None, description="List of fallback language models to try if the primary LLM fails."
)
system_template: Optional[str] = Field(
default=None, description="System format for the agent."
)
Expand Down Expand Up @@ -174,6 +177,8 @@ def post_init_setup(self):
self.agent_ops_agent_name = self.role

self.llm = create_llm(self.llm)
if self.fallback_llms:
self.fallback_llms = [create_llm(fallback_llm) for fallback_llm in self.fallback_llms]
if self.function_calling_llm and not isinstance(
self.function_calling_llm, BaseLLM
):
Expand Down
1 change: 1 addition & 0 deletions src/crewai/agents/crew_agent_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ def _invoke_loop(self) -> AgentFinish:
messages=self.messages,
callbacks=self.callbacks,
printer=self._printer,
fallback_llms=getattr(self.agent, 'fallback_llms', None),
)
formatted_answer = process_llm_response(answer, self.use_stop_words)

Expand Down
1 change: 1 addition & 0 deletions src/crewai/lite_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,7 @@ def _invoke_loop(self) -> AgentFinish:
messages=self._messages,
callbacks=self._callbacks,
printer=self._printer,
fallback_llms=getattr(self, 'fallback_llms', None),
)

# Emit LLM call completed event
Expand Down
65 changes: 45 additions & 20 deletions src/crewai/utilities/agent_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,27 +145,52 @@ def get_llm_response(
messages: List[Dict[str, str]],
callbacks: List[Any],
printer: Printer,
fallback_llms: Optional[List[Union[LLM, BaseLLM]]] = None,
) -> str:
"""Call the LLM and return the response, handling any invalid responses."""
try:
answer = llm.call(
messages,
callbacks=callbacks,
)
except Exception as e:
printer.print(
content=f"Error during LLM call: {e}",
color="red",
)
raise e
if not answer:
printer.print(
content="Received None or empty response from LLM call.",
color="red",
)
raise ValueError("Invalid response from LLM call - None or empty.")

return answer
"""Call the LLM and return the response, handling any invalid responses and trying fallbacks if available."""
llms_to_try = [llm]
if fallback_llms:
llms_to_try.extend(fallback_llms)

last_exception = None

for i, current_llm in enumerate(llms_to_try):
try:
answer = current_llm.call(
messages,
callbacks=callbacks,
)
if not answer:
error_msg = "Received None or empty response from LLM call."
printer.print(content=error_msg, color="red")
if i < len(llms_to_try) - 1:
printer.print(content=f"Trying fallback LLM {i+1}...", color="yellow")
continue
else:
raise ValueError("Invalid response from LLM call - None or empty.")
return answer
except Exception as e:
last_exception = e
if i == 0:
printer.print(content=f"Primary LLM failed: {e}", color="red")
else:
printer.print(content=f"Fallback LLM {i} failed: {e}", color="red")

if e.__class__.__module__.startswith("litellm"):
error_str = str(e).lower()
if any(term in error_str for term in ["authentication", "api key", "unauthorized", "forbidden"]):
printer.print(content="Authentication error detected, skipping remaining fallbacks", color="red")
raise e

if i < len(llms_to_try) - 1:
printer.print(content=f"Trying fallback LLM {i+1}...", color="yellow")
continue

printer.print(content="All LLMs failed, raising last exception", color="red")
if last_exception is not None:
raise last_exception
else:
raise RuntimeError("All LLMs failed but no exception was captured")


def process_llm_response(
Expand Down
2 changes: 1 addition & 1 deletion tests/agent_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1984,7 +1984,7 @@ def test_crew_agent_executor_litellm_auth_error():
)

# Verify error handling messages
error_message = f"Error during LLM call: {str(mock_llm_call.side_effect)}"
error_message = f"Primary LLM failed: {str(mock_llm_call.side_effect)}"
mock_printer.assert_any_call(
content=error_message,
color="red",
Expand Down
Loading
Loading