Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
feat(flow): accept crew-style LLM config in a conversational declaration (#7062)
João Moura6e714d6cad83
diff --git a/lib/crewai/src/crewai/experimental/conversational_mixin.py b/lib/crewai/src/crewai/experimental/conversational_mixin.pyindex aaef4146b..35422701c 100644--- a/lib/crewai/src/crewai/experimental/conversational_mixin.py+++ b/lib/crewai/src/crewai/experimental/conversational_mixin.py@@ -706,7 +706,7 @@ class _ConversationalMixin:outcome = self._collapse_to_outcome(feedback,("answer_from_history", "route_to_flow"),- config.answer_from_history_llm,+ self._coerce_llm(config.answer_from_history_llm),)return outcome == "answer_from_history"@@ -876,7 +876,11 @@ class _ConversationalMixin:feedback = f"{context_blob}\n\nLatest user message: {text}"else:feedback = text- return self._collapse_to_outcome(feedback, tuple(outcomes), llm)+ # ``_collapse_to_outcome`` takes only ``str | BaseLLM``, so a declared+ # config mapping has to be resolved before it gets there.+ return self._collapse_to_outcome(+ feedback, tuple(outcomes), self._coerce_llm(llm)+ )@propertydef _conversation_config(self) -> ConversationConfig | None:@@ -1424,14 +1428,33 @@ class _ConversationalMixin:@staticmethoddef _coerce_llm(llm: str | BaseLLM | Any) -> Any:- from crewai.llm import LLM+ """Resolve a declared or live LLM the way a crew agent's ``llm`` resolves.++ ``create_llm`` is the shared helper the crew/agent declaration layer+ uses, so a conversational block accepts the same shapes: a model-id+ string, a config mapping (``{model, max_tokens, ...}``), an+ ``LLMDefinition``, or a live ``LLM``/``BaseLLM`` passed straight+ through.+ """from crewai.llms.base_llm import BaseLLM as BaseLLMClass+ from crewai.project.crew_definition import LLMDefinition+ from crewai.utilities.llm_utils import create_llm- if isinstance(llm, str):- return LLM(model=llm)if isinstance(llm, BaseLLMClass) or callable(getattr(llm, "call", None)):return llm- raise ValueError(f"Invalid llm type: {type(llm)}. Expected str or BaseLLM.")+ if isinstance(llm, LLMDefinition):+ llm = llm.model_dump(exclude_none=True)+ if not isinstance(llm, (str, Mapping)):+ # ``create_llm`` would take an int or a list as a model name and+ # build an LLM that only fails later, at call time, with a+ # provider error. A declaration is hand-written, so a typo here+ # should say so now.+ raise ValueError(+ f"Invalid llm {llm!r}: expected a model-id string, a config "+ "mapping with a 'model' key, or an LLM instance."+ )++ return create_llm(dict(llm) if isinstance(llm, Mapping) else llm)@contextmanagerdef _conversation_streaming_enabled(self, llm: Any) -> Iterator[None]:diff --git a/lib/crewai/src/crewai/flow/conversational_definition.py b/lib/crewai/src/crewai/flow/conversational_definition.pyindex 5cd7dd13f..d1fde21cd 100644--- a/lib/crewai/src/crewai/flow/conversational_definition.py+++ b/lib/crewai/src/crewai/flow/conversational_definition.py@@ -17,7 +17,14 @@ class FlowConversationalRouterDefinition(BaseModel):prompt: str | None = Noneresponse_format: Any = None- llm: Any = None+ llm: Any = Field(+ default=None,+ description=(+ "Model used for the routing decision. Falls back to the "+ "conversational intent_llm, then llm. A model-id string, a config mapping such as {model, max_tokens}, an LLMDefinition, or a live LLM instance when built in Python."+ ),+ examples=["gpt-4o-mini", {"model": "openai/gpt-4o-mini", "max_tokens": 4096}],+ )routes: list[str] | None = Noneroute_descriptions: dict[str, str] | None = Nonedefault_intent: str | None = "converse"@@ -42,12 +49,33 @@ class FlowConversationalDefinition(BaseModel):examples=[True],)system_prompt: str | None = None- llm: Any = None+ llm: Any = Field(+ default=None,+ description=(+ "Model for the built-in converse handler, and the last router "+ "fallback: the router uses router.llm, then intent_llm, then this. "+ "A model-id string, a config mapping such as {model, max_tokens}, an LLMDefinition, or a live LLM instance when built in Python."+ ),+ examples=["gpt-4o-mini", {"model": "openai/gpt-4o-mini", "max_tokens": 4096}],+ )router: FlowConversationalRouterDefinition | None = Noneanswer_from_history_prompt: str | None = Nonedefault_intents: list[str] | None = None- intent_llm: Any = None- answer_from_history_llm: Any = None+ intent_llm: Any = Field(+ default=None,+ description=(+ "Model used to pre-classify default_intents. A model-id string, a config mapping such as {model, max_tokens}, an LLMDefinition, or a live LLM instance when built in Python."+ ),+ examples=["gpt-4o-mini"],+ )+ answer_from_history_llm: Any = Field(+ default=None,+ description=(+ "Setting this enables the optional answer_from_history route. "+ "A model-id string, a config mapping such as {model, max_tokens}, an LLMDefinition, or a live LLM instance when built in Python."+ ),+ examples=["gpt-4o-mini"],+ )visible_agent_outputs: list[str] | Literal["all"] | None = Nonedefer_trace_finalization: bool = Truebuiltin_routes: list[str] = Field(default_factory=lambda: ["converse", "end"])diff --git a/lib/crewai/tests/test_flow_conversation.py b/lib/crewai/tests/test_flow_conversation.pyindex 29fb57b72..87d0836ac 100644--- a/lib/crewai/tests/test_flow_conversation.py+++ b/lib/crewai/tests/test_flow_conversation.py@@ -2420,6 +2420,112 @@ class TestDeclarativeConversationalFlow:assert "cannot carry a model class" in caplog.text+class TestDeclaredConversationalLLM:+ """A conversational block accepts the shapes a crew agent's `llm` accepts."""++ @staticmethod+ def _resolved(llm: Any) -> Any:+ flow = Flow.from_declaration(+ contents=_conversational_declaration(conversational={"llm": llm})+ )+ return flow._coerce_llm(flow._conversation_config.llm)++ def test_model_id_string(self) -> None:+ assert self._resolved("gpt-4o-mini").model == "gpt-4o-mini"++ def test_config_mapping_carries_provider_settings(self) -> None:+ resolved = self._resolved({"model": "openai/gpt-4o-mini", "max_tokens": 512})++ assert resolved.model == "gpt-4o-mini"+ assert resolved.max_tokens == 512++ def test_config_mapping_passes_through_extra_settings(self) -> None:+ resolved = self._resolved({"model": "openai/gpt-4o-mini", "temperature": 0.2})++ assert resolved.temperature == 0.2++ def test_a_live_llm_object_is_passed_through_untouched(self) -> None:+ llm = _ScriptedLLM(["hi"])++ @ConversationConfig(llm=llm)+ class ClassChat(Flow[ConversationState]):+ pass++ assert ClassChat()._coerce_llm(llm) is llm++ def test_a_mapping_without_a_model_key_says_so(self) -> None:+ with pytest.raises(ValueError, match="must include 'model'"):+ self._resolved({"max_tokens": 512})++ def test_a_wrong_type_fails_now_not_at_call_time(self) -> None:+ """`create_llm` would take an int as a model name and fail later."""+ with pytest.raises(ValueError, match="expected a model-id string"):+ self._resolved(1234)++ def test_an_llm_definition_resolves_with_its_settings(self) -> None:+ from crewai.project.crew_definition import LLMDefinition++ flow = Flow.from_declaration(contents=_conversational_declaration())+ resolved = flow._coerce_llm(+ LLMDefinition(model="openai/gpt-4o-mini", max_tokens=256)+ )++ assert resolved.model == "gpt-4o-mini"+ assert resolved.max_tokens == 256++ def test_a_declared_mapping_reaches_create_llm_during_a_turn(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Swapping the config out before the turn would not prove the path."""+ declared = {"model": "openai/gpt-4o-mini", "max_tokens": 128}+ scripted = _ScriptedLLM(["Hello."])+ seen: list[Any] = []++ def fake_create_llm(value: Any) -> Any:+ seen.append(value)+ return scripted++ monkeypatch.setattr(+ "crewai.utilities.llm_utils.create_llm", fake_create_llm+ )+ flow = Flow.from_declaration(+ contents=_conversational_declaration(conversational={"llm": declared})+ )++ assert flow.handle_turn("hi") == "Hello."+ assert declared in seen++ def test_a_declared_intent_llm_mapping_is_resolved(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """`_collapse_to_outcome` takes only str | BaseLLM, so it must be coerced.++ Swapping the mapping for an LLM before the turn would skip the coercion+ entirely, so the mapping stays declared and ``create_llm`` is patched.+ """+ declared = {"model": "openai/gpt-4o-mini", "max_tokens": 64}+ intent_llm = _ScriptedLLM(['{"outcome": "order"}'])+ converse_llm = _ScriptedLLM(["ok"])+ seen: list[Any] = []++ def fake_create_llm(value: Any) -> Any:+ seen.append(value)+ return intent_llm if value == declared else converse_llm++ monkeypatch.setattr("crewai.utilities.llm_utils.create_llm", fake_create_llm)+ flow = Flow.from_declaration(+ contents=_conversational_declaration(+ conversational={"default_intents": ["order"], "intent_llm": declared}+ )+ )++ # Before coercion this raised "Invalid llm type: <class 'dict'>".+ flow.handle_turn("where is my order?")++ assert declared in seen+ assert [m.role for m in flow.state.messages][0] == "user"++class TestRoutingArtefactLabels:"""A route label echoed by a handler is a routing artefact, not a reply."""