Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.
fix(agents): keep message roles when Agent.kickoff gets a conversation (#7065)
João Moura9652af6ae04b
diff --git a/docs/edge/en/concepts/agents.mdx b/docs/edge/en/concepts/agents.mdxindex bee0fdcd8..f35621f06 100644--- a/docs/edge/en/concepts/agents.mdx+++ b/docs/edge/en/concepts/agents.mdx@@ -623,6 +623,12 @@ messages = [result = researcher.kickoff(messages)```+The last `user` message is the request the agent answers. Every other message+keeps its role and its position around that request, so a conversation that+ends in assistant or tool messages still asks the user's question and still+delivers those trailing turns after it. With no `user` message at all, the last+message is treated as the request.+### Async SupportAn asynchronous version is available via `kickoff_async()` with the same parameters:diff --git a/docs/edge/ko/concepts/agents.mdx b/docs/edge/ko/concepts/agents.mdxindex b78fab109..67729bb1b 100644--- a/docs/edge/ko/concepts/agents.mdx+++ b/docs/edge/ko/concepts/agents.mdx@@ -630,6 +630,11 @@ messages = [result = researcher.kickoff(messages)```+마지막 `user` 메시지가 에이전트가 답변할 요청입니다. 나머지 메시지는 각자의 역할과+그 요청을 기준으로 한 위치를 그대로 유지하므로, assistant 또는 tool 메시지로 끝나는+대화도 사용자의 질문을 그대로 전달하며 뒤따르는 턴도 요청 뒤에 그대로 전달됩니다.+`user` 메시지가 전혀 없으면 마지막 메시지를 요청으로 처리합니다.+### 비동기 지원동일한 매개변수를 사용하는 비동기 버전은 `kickoff_async()`를 통해 사용할 수 있습니다:diff --git a/lib/crewai/src/crewai/agent/core.py b/lib/crewai/src/crewai/agent/core.pyindex 156e576c0..f387d88be 100644--- a/lib/crewai/src/crewai/agent/core.py+++ b/lib/crewai/src/crewai/agent/core.py@@ -176,6 +176,38 @@ def _serialize_executor_class(value: Any) -> str:return value.__name__ if isinstance(value, type) else str(value)+def _request_index(carried: list[LLMMessage]) -> int:+ """Index of the message that is this turn's request.++ The last ``user`` message, not simply the last one: a caller can hand over+ a conversation that ends in assistant or tool messages -- notably+ ``build_agent_context()``, which appends an agent's private thread after+ the current user turn -- and promoting that tail would make the agent's own+ scratch the task while demoting the real question to history. With no user+ message at all the last one stands in, which is what a single-message+ caller has always got.+ """+ for index in range(len(carried) - 1, -1, -1):+ if carried[index].get("role") == "user":+ return index+ return len(carried) - 1+++def _carries_payload(message: LLMMessage) -> bool:+ """Whether a message says anything the provider needs.++ Text is the usual case, but an assistant turn that only requests tool+ calls, the tool result that answers it, and a turn whose payload is an+ attachment all matter.+ """+ return bool(+ message.get("content")+ or message.get("tool_calls")+ or message.get("tool_call_id")+ or message.get("files")+ )++class Agent(BaseAgent):"""Represents an agent in a system.@@ -1524,15 +1556,38 @@ class Agent(BaseAgent):)all_files: dict[str, Any] = {}+ history: list[LLMMessage] = []+ trailing: list[LLMMessage] = []if isinstance(messages, str):formatted_messages = messages+ recall_text = messageselse:- formatted_messages = "\n".join(- str(msg.get("content", "")) for msg in messages if msg.get("content")+ # A message with no text still carries meaning when it holds tool+ # calls or is a tool result; dropping those leaves a `tool` message+ # with no preceding `assistant` tool_calls, which providers reject.+ carried = [msg for msg in messages if _carries_payload(msg)]+ # The executor's prompt needs one request string, so exactly one+ # message is promoted to it and the rest keep their roles as+ # history. Joining them all into one string told the model the+ # assistant's own replies were the user's.+ request_index = _request_index(carried)+ request = carried[request_index] if carried else None+ formatted_messages = str(request.get("content") or "") if request else ""+ # Split, rather than one history list: the promoted request keeps+ # its position in the conversation. Sending everything before it+ # would hoist a trailing tool pair above the question it answers,+ # which is the wrong chronology even where a provider tolerates it.+ if request is not None:+ history = carried[:request_index]+ trailing = carried[request_index + 1 :]+ recall_text = "\n".join(+ str(msg.get("content", "")) for msg in carried if msg.get("content"))- for msg in messages:- if msg.get("files"):- all_files.update(msg["files"])+ # Only the request's attachments go on the current turn; a history+ # message keeps its own, so unioning them all would send prior+ # attachments twice.+ if request is not None and request.get("files"):+ all_files.update(request["files"])if input_files:all_files.update(input_files)@@ -1548,7 +1603,7 @@ class Agent(BaseAgent):),)start_time = time.time()- matches = agent_memory.recall(formatted_messages, limit=20)+ matches = agent_memory.recall(recall_text, limit=20)memory_block = ""if matches:memory_block = "Relevant memories:\n" + "\n".join(@@ -1586,6 +1641,10 @@ class Agent(BaseAgent):}if all_files:inputs["files"] = all_files+ if history:+ inputs["history"] = history+ if trailing:+ inputs["trailing"] = trailingreturn executor, inputs, agent_info, parsed_tools@@ -1610,6 +1669,12 @@ class Agent(BaseAgent):If a string is provided, it will be converted to a user message.If a list is provided, each dict should have 'role' and 'content' keys.Messages can include a 'files' field with file inputs.+ The last ``user`` message is the request the agent answers;+ every other message keeps its role and its place around it,+ so a list that trails off in assistant or tool messages+ still asks the user's question and still delivers those+ turns after it. With no ``user`` message the last one is+ the request.response_format: Optional Pydantic model for structured output.input_files: Optional dict of named files to attach to the message.Files can be paths, bytes, or File objects from crewai_files.@@ -1984,6 +2049,12 @@ class Agent(BaseAgent):If a string is provided, it will be converted to a user message.If a list is provided, each dict should have 'role' and 'content' keys.Messages can include a 'files' field with file inputs.+ The last ``user`` message is the request the agent answers;+ every other message keeps its role and its place around it,+ so a list that trails off in assistant or tool messages+ still asks the user's question and still delivers those+ turns after it. With no ``user`` message the last one is+ the request.response_format: Optional Pydantic model for structured output.input_files: Optional dict of named files to attach to the message.Files can be paths, bytes, or File objects from crewai_files.diff --git a/lib/crewai/src/crewai/agents/crew_agent_executor.py b/lib/crewai/src/crewai/agents/crew_agent_executor.pyindex 040520e1f..17ad80a6a 100644--- a/lib/crewai/src/crewai/agents/crew_agent_executor.py+++ b/lib/crewai/src/crewai/agents/crew_agent_executor.py@@ -167,6 +167,21 @@ class CrewAgentExecutor(BaseAgentExecutor):self.llm.supports_stop_words() if isinstance(self.llm, BaseLLM) else False)+ def _append_history(self, inputs: dict[str, Any]) -> None:+ """Add prior turns, with their roles, before this turn's request."""+ for message in inputs.get("history", []):+ self.messages.append(dict(message))++ def _append_trailing(self, inputs: dict[str, Any]) -> None:+ """Add turns that followed the request, keeping them after it.++ A conversation can end past its last user message -- an assistant+ tool call and its result, or an agent's own scratch thread. Those+ belong after the question they answer, not hoisted above it.+ """+ for message in inputs.get("trailing", []):+ self.messages.append(dict(message))+def _setup_messages(self, inputs: dict[str, Any]) -> None:"""Set up messages for the agent execution.@@ -194,14 +209,21 @@ class CrewAgentExecutor(BaseAgentExecutor):format_message_for_llm(system_prompt, role="system")))+ self._append_history(inputs)self.messages.append(mark_cache_breakpoint(format_message_for_llm(user_prompt)))+ self._append_trailing(inputs)elif self.prompt is not None:user_prompt = self._format_prompt(self.prompt.get("prompt", ""), inputs)+ # Also here: with the system prompt disabled or a custom template+ # this is the only branch, and skipping history would drop every+ # turn but the last.+ self._append_history(inputs)self.messages.append(mark_cache_breakpoint(format_message_for_llm(user_prompt)))+ self._append_trailing(inputs)provider.post_setup_messages(cast(ExecutorContext, cast(object, self)))diff --git a/lib/crewai/src/crewai/events/types/agent_events.py b/lib/crewai/src/crewai/events/types/agent_events.pyindex 95b0520c9..689b3bdf7 100644--- a/lib/crewai/src/crewai/events/types/agent_events.py+++ b/lib/crewai/src/crewai/events/types/agent_events.py@@ -12,6 +12,7 @@ from crewai.agents.agent_builder.base_agent import BaseAgentfrom crewai.events.base_events import BaseEventfrom crewai.tools.base_tool import BaseToolfrom crewai.tools.structured_tool import CrewStructuredTool+from crewai.utilities.types import LLMMessageclass AgentExecutionStartedEvent(BaseEvent):@@ -71,7 +72,7 @@ class LiteAgentExecutionStartedEvent(BaseEvent):agent_info: dict[str, Any]tools: Sequence[BaseTool | CrewStructuredTool] | None- messages: str | list[dict[str, str]]+ messages: str | list[LLMMessage]type: Literal["lite_agent_execution_started"] = "lite_agent_execution_started"model_config = ConfigDict(arbitrary_types_allowed=True)diff --git a/lib/crewai/src/crewai/experimental/agent_executor.py b/lib/crewai/src/crewai/experimental/agent_executor.pyindex 88794c654..d2a0436fa 100644--- a/lib/crewai/src/crewai/experimental/agent_executor.py+++ b/lib/crewai/src/crewai/experimental/agent_executor.py@@ -307,6 +307,21 @@ class AgentExecutor(Flow[AgentExecutorState], BaseAgentExecutor):"""Set state messages."""self._state.messages = value+ def _append_history(self, inputs: dict[str, Any]) -> None:+ """Add prior turns, with their roles, before this turn's request."""+ for message in inputs.get("history", []):+ self.state.messages.append(dict(message))++ def _append_trailing(self, inputs: dict[str, Any]) -> None:+ """Add turns that followed the request, keeping them after it.++ A conversation can end past its last user message -- an assistant+ tool call and its result, or an agent's own scratch thread. Those+ belong after the question they answer, not hoisted above it.+ """+ for message in inputs.get("trailing", []):+ self.state.messages.append(dict(message))+def _setup_messages(self, inputs: dict[str, Any]) -> None:"""Set up messages for the agent execution."""provider = get_provider()@@ -323,14 +338,21 @@ class AgentExecutor(Flow[AgentExecutorState], BaseAgentExecutor):format_message_for_llm(system_prompt, role="system")))+ self._append_history(inputs)self.state.messages.append(mark_cache_breakpoint(format_message_for_llm(user_prompt)))+ self._append_trailing(inputs)elif isinstance(self.prompt, StandardPromptResult):user_prompt = self._format_prompt(self.prompt["prompt"], inputs)+ # Also here: with the system prompt disabled or a custom template+ # this is the only branch, and skipping history would drop every+ # turn but the last.+ self._append_history(inputs)self.state.messages.append(mark_cache_breakpoint(format_message_for_llm(user_prompt)))+ self._append_trailing(inputs)provider.post_setup_messages(cast("ExecutorContext", self))diff --git a/lib/crewai/src/crewai/flow/runtime/_actions.py b/lib/crewai/src/crewai/flow/runtime/_actions.pyindex 885a2f226..6b4aaa5a0 100644--- a/lib/crewai/src/crewai/flow/runtime/_actions.py+++ b/lib/crewai/src/crewai/flow/runtime/_actions.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport astimport asyncio-from collections.abc import Awaitable, Callable+from collections.abc import Awaitable, Callable, Mappingimport contextvarsimport inspectimport os@@ -29,6 +29,7 @@ from crewai.utilities.declarative_refs import (resolve_class_ref,resolve_ref,)+from crewai.utilities.types import LLMMessageif TYPE_CHECKING:@@ -184,8 +185,7 @@ class AgentAction:self.flow,local_context=local_context,).render_template()- if not isinstance(rendered_input, str):- raise ValueError("agent input must render to a string")+ agent_input = _normalize_agent_input(rendered_input)agent, response_format = await asyncio.to_thread(load_agent_from_definition,@@ -193,11 +193,46 @@ class AgentAction:source="agent action",)return await agent.kickoff_async(- rendered_input,+ agent_input,response_format=response_format,)+def _normalize_agent_input(rendered: Any) -> str | list[LLMMessage]:+ """Accept a prompt string or a rendered conversation.++ A whole-string ``${...}`` template keeps its evaluated type, so a CEL+ expression over ``state.messages`` renders a list. ``message_to_llm_dict``+ drops the metadata and ``None`` keys a serialized message carries, which+ the agent event schema rejects.+ """+ if isinstance(rendered, str):+ return rendered+ if isinstance(rendered, list) and all(+ isinstance(item, Mapping) for item in rendered+ ):+ from crewai.experimental.conversational import message_to_llm_dict++ # ``message_to_llm_dict`` only drops ``None`` keys for a model input;+ # a CEL render is plain dicts, so a serialized message keeps its+ # ``name: None`` -- which the agent event schema rejects.+ return [+ cast(+ LLMMessage,+ {+ key: value+ for key, value in message_to_llm_dict(item).items()+ if value is not None or key == "content"+ },+ )+ for item in rendered+ ]+ raise ValueError(+ "agent input must render to a string or a list of messages; "+ f"got {type(rendered).__name__}"+ )++class ExpressionAction:definition_type = FlowExpressionActionDefinitiondiff --git a/lib/crewai/src/crewai/project/crew_definition.py b/lib/crewai/src/crewai/project/crew_definition.pyindex 4afbace8b..49aa0411b 100644--- a/lib/crewai/src/crewai/project/crew_definition.py+++ b/lib/crewai/src/crewai/project/crew_definition.py@@ -2,6 +2,7 @@from __future__ import annotations+from collections.abc import Mappingfrom typing import Any, TypeAliasfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator@@ -222,9 +223,16 @@ class AgentDefinition(CrewAgentDefinition):description="Additional agent settings passed to the loader.",examples=[{"llm": "openai/gpt-4o-mini"}],)- input: str = Field(- description="Input passed to the individual agent kickoff outside of a crew.",- examples=["${state.ticket.body}"],+ input: str | list[dict[str, Any]] = Field(+ description=(+ "Input passed to the individual agent kickoff outside of a crew. "+ "A string, or a list of {role, content} messages to give the agent "+ "a conversation instead of a single prompt."+ ),+ examples=[+ "${state.ticket.body}",+ "${state.messages.map(m, {'role': m.role, 'content': m.content})}",+ ],)response_format: PythonReferenceDefinition | None = Field(default=None,@@ -235,9 +243,11 @@ class AgentDefinition(CrewAgentDefinition):@field_validator("input", mode="before")@classmethoddef _validate_input(cls, value: Any) -> Any:- if not isinstance(value, str):- raise ValueError("agent.input must be a string")- return value+ if isinstance(value, str):+ return value+ if isinstance(value, list) and all(isinstance(item, Mapping) for item in value):+ return value+ raise ValueError("agent.input must be a string or a list of messages")class CrewTaskDefinition(BaseModel):diff --git a/lib/crewai/tests/agents/test_agent_kickoff_message_history.py b/lib/crewai/tests/agents/test_agent_kickoff_message_history.pynew file mode 100644index 000000000..deb0b3c84--- /dev/null+++ b/lib/crewai/tests/agents/test_agent_kickoff_message_history.py@@ -0,0 +1,381 @@+"""`Agent.kickoff` keeps the roles of a multi-message conversation."""++from __future__ import annotations++from typing import Any++import pytest++from crewai import Agent+from crewai.agents.crew_agent_executor import CrewAgentExecutor+from crewai.lite_agent import LiteAgent+from crewai.llms.base_llm import BaseLLM+from crewai.utilities.prompts import StandardPromptResult, SystemPromptResult+++class _Recorder(BaseLLM):+ """Records the exact message list handed to the provider."""++ def __init__(self) -> None:+ super().__init__(model="recorder")+ object.__setattr__(self, "seen", [])++ def call(self, messages: Any, **kwargs: Any) -> str:+ self.seen.append(list(messages) if isinstance(messages, list) else messages)+ return "ok"++ async def acall(self, messages: Any, **kwargs: Any) -> str:+ return self.call(messages, **kwargs)++ def supports_function_calling(self) -> bool:+ return False++ def supports_stop_words(self) -> bool:+ return False++ def get_context_window_size(self) -> int:+ return 8192+++HISTORY = [+ {"role": "user", "content": "my order id is 42"},+ {"role": "assistant", "content": "thanks, checking"},+ {"role": "user", "content": "where is it?"},+]++# What `build_agent_context()` yields on a later turn: the conversation, then+# the agent's own private thread appended after the current user message.+TRAILING_THREAD = [+ {"role": "user", "content": "where is order 88213?"},+ {"role": "assistant", "content": "let me look that up"},+ {"role": "assistant", "content": "internal note: checked the warehouse"},+]+++TOOL_CONVERSATION = [+ {"role": "user", "content": "what is the weather in Lisbon?"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "get_weather"}}],+ },+ {"role": "tool", "tool_call_id": "c1", "content": "22C, clear"},+]++def _kickoff(payload: Any, agent_cls: type = Agent) -> list[dict[str, Any]]:+ llm = _Recorder()+ agent_cls(role="Support", goal="help", backstory="b", llm=llm).kickoff(payload)+ return llm.seen[0]+++def test_prior_turns_keep_their_roles() -> None:+ """Joining them into one string told the model the agent said the user's words."""+ seen = _kickoff(HISTORY)++ assert [message["role"] for message in seen] == [+ "system",+ "user",+ "assistant",+ "user",+ ]+ assert seen[1]["content"] == "my order id is 42"+ assert seen[2]["content"] == "thanks, checking"+ assert "where is it?" in str(seen[3]["content"])+++def test_history_sits_between_the_system_prompt_and_this_turn() -> None:+ seen = _kickoff(HISTORY)++ assert seen[0]["role"] == "system"+ assert "where is it?" in str(seen[-1]["content"])+ assert "my order id is 42" not in str(seen[-1]["content"])+++def test_agent_and_lite_agent_agree() -> None:+ assert [m["role"] for m in _kickoff(HISTORY)] == [+ m["role"] for m in _kickoff(HISTORY, LiteAgent)+ ]+++def test_neither_agent_drops_a_message_when_the_tail_is_not_a_user_turn() -> None:+ """The role-sequence check only agrees on a list ending in a user message.++ `Agent` has a task slot in its prompt and `LiteAgent` does not, so when the+ request is not the final message the two put it in different positions. What+ must still hold either way is that nothing is dropped and nothing is+ duplicated.+ """+ for agent_cls in (Agent, LiteAgent):+ seen = _kickoff(TRAILING_THREAD, agent_cls)+ body = [m for m in seen if m["role"] != "system"]++ assert len(body) == len(TRAILING_THREAD)+ assert sorted(m["role"] for m in body) == sorted(+ m["role"] for m in TRAILING_THREAD+ )+ for message in TRAILING_THREAD:+ assert any(message["content"] in str(m["content"]) for m in body)+++def test_the_request_is_the_last_user_message_not_the_last_message() -> None:+ """A trailing agent scratch must not become the task.++ `build_agent_context()` appends an agent's private thread after the current+ user turn, so promoting the tail made the agent's own note the request and+ demoted the real question to history.+ """+ seen = _kickoff(TRAILING_THREAD)+ request = seen[1]++ assert "where is order 88213?" in str(request["content"])+ assert "internal note" not in str(request["content"])+ # The scratch turns follow the question, keeping the conversation's order.+ assert [m["content"] for m in seen[2:]] == [+ "let me look that up",+ "internal note: checked the warehouse",+ ]+++def test_a_conversation_with_no_user_message_still_has_a_request() -> None:+ """Nothing to select, so the last message stands in as it always has."""+ seen = _kickoff(+ [+ {"role": "assistant", "content": "earlier note"},+ {"role": "assistant", "content": "summarize the above"},+ ]+ )++ assert "summarize the above" in str(seen[-1]["content"])+ assert [m["content"] for m in seen[1:-1]] == ["earlier note"]+++def test_a_conversation_ending_on_a_tool_result_keeps_its_order() -> None:+ """The tool pair answers the question, so it must not precede it.++ Splicing every non-request turn before the prompt hoisted a trailing+ tool call and its result above the user message they belong to.+ `LiteAgent` sends `user -> assistant -> tool`; so does this now.+ """+ seen = _kickoff(TOOL_CONVERSATION)++ assert [message["role"] for message in seen] == [+ "system",+ "user",+ "assistant",+ "tool",+ ]+ assert "what is the weather in Lisbon?" in str(seen[1]["content"])+ assert seen[2]["tool_calls"][0]["id"] == "c1"+ assert seen[3]["tool_call_id"] == "c1"++ lite = _kickoff(TOOL_CONVERSATION, LiteAgent)+ assert [m["role"] for m in lite[: len(seen)]] == [m["role"] for m in seen]+++def test_a_plain_string_is_unchanged() -> None:+ seen = _kickoff("just a string")++ assert [message["role"] for message in seen] == ["system", "user"]+ assert "just a string" in str(seen[-1]["content"])+++def test_a_single_message_matches_the_string_form() -> None:+ assert _kickoff("just a string") == _kickoff(+ [{"role": "user", "content": "just a string"}]+ )+++def test_empty_content_messages_are_skipped() -> None:+ seen = _kickoff(+ [+ {"role": "user", "content": ""},+ {"role": "user", "content": "the real question"},+ ]+ )++ assert [message["role"] for message in seen] == ["system", "user"]+ assert "the real question" in str(seen[-1]["content"])+++def test_an_empty_list_does_not_crash() -> None:+ seen = _kickoff([])++ assert [message["role"] for message in seen] == ["system", "user"]+++def test_a_tool_call_sequence_survives() -> None:+ """A `tool` message needs its preceding assistant `tool_calls` message.++ Filtering on truthy content dropped the assistant turn, leaving a sequence+ providers reject.+ """+ seen = _kickoff(+ [+ {"role": "user", "content": "what is the weather?"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "weather"}}],+ },+ {"role": "tool", "tool_call_id": "c1", "content": "sunny"},+ {"role": "user", "content": "and tomorrow?"},+ ]+ )++ assert [message["role"] for message in seen] == [+ "system",+ "user",+ "assistant",+ "tool",+ "user",+ ]+ assert seen[2]["tool_calls"][0]["id"] == "c1"+ assert seen[3]["tool_call_id"] == "c1"+++def test_history_survives_with_the_system_prompt_disabled() -> None:+ """That branch builds one combined prompt, so history had nowhere to go."""+ llm = _Recorder()+ Agent(+ role="Support",+ goal="help",+ backstory="b",+ llm=llm,+ use_system_prompt=False,+ ).kickoff(HISTORY)+ seen = llm.seen[0]++ assert [message["role"] for message in seen] == ["user", "assistant", "user"]+ assert seen[0]["content"] == "my order id is 42"+ assert "where is it?" in str(seen[-1]["content"])+++def test_trailing_turns_survive_with_the_system_prompt_disabled() -> None:+ """The combined-prompt branch needs the same after-request placement."""+ llm = _Recorder()+ Agent(+ role="Support",+ goal="help",+ backstory="b",+ llm=llm,+ use_system_prompt=False,+ ).kickoff(TRAILING_THREAD)+ seen = llm.seen[0]++ assert [message["role"] for message in seen] == [+ "user",+ "assistant",+ "assistant",+ ]+ assert "where is order 88213?" in str(seen[0]["content"])+ assert [m["content"] for m in seen[1:]] == [+ "let me look that up",+ "internal note: checked the warehouse",+ ]++[email protected]("use_system_prompt", [True, False])+def test_the_deprecated_executor_places_history_the_same_way(+ use_system_prompt: bool,+) -> None:+ """`CrewAgentExecutor` carries its own `_setup_messages` twin.++ `Agent.kickoff` builds an `AgentExecutor` unconditionally+ (`agent/core.py`), so the deprecated executor is not reachable through+ kickoff and is driven directly here. Both of its branches are covered:+ history must land after any system prompt and before this turn's request.+ """+ agent = Agent(role="Support", goal="help", backstory="b", llm=_Recorder())+ with pytest.warns(DeprecationWarning, match="CrewAgentExecutor is deprecated"):+ executor = CrewAgentExecutor(+ llm=agent.llm,+ agent=agent,+ prompt=SystemPromptResult(system="you are support", user="{input}")+ if use_system_prompt+ else StandardPromptResult(prompt="{input}"),+ max_iter=5,+ tools=[],+ tools_names="",+ stop_words=[],+ tools_description="",+ tools_handler=agent.tools_handler,+ original_tools=[],+ )++ executor._setup_messages(+ {+ "input": "where is it?",+ "tool_names": "",+ "tools": "",+ "history": HISTORY[:2],+ "trailing": [{"role": "assistant", "content": "checking now"}],+ }+ )++ roles = [message["role"] for message in executor.messages]+ assert roles == (["system"] if use_system_prompt else []) + [+ "user",+ "assistant",+ "user",+ "assistant",+ ]+ assert executor.messages[-4]["content"] == "my order id is 42"+ assert executor.messages[-3]["content"] == "thanks, checking"+ assert "where is it?" in str(executor.messages[-2]["content"])+ assert executor.messages[-1]["content"] == "checking now"+++def test_prior_turn_attachments_are_not_resent_on_this_turn() -> None:+ """History keeps its own files; unioning them all would send them twice."""+ llm = _Recorder()+ agent = Agent(role="S", goal="g", backstory="b", llm=llm)+ _executor, inputs, _info, _tools = agent._prepare_kickoff(+ [+ {"role": "user", "content": "here it is", "files": {"a": "old"}},+ {"role": "user", "content": "and now this", "files": {"b": "new"}},+ ]+ )++ assert inputs["files"] == {"b": "new"}+ assert inputs["history"][0]["files"] == {"a": "old"}+++def test_an_attachment_only_final_message_is_the_request() -> None:+ """Its files must reach `inputs["files"]`, not be filtered away."""+ llm = _Recorder()+ agent = Agent(role="S", goal="g", backstory="b", llm=llm)+ _executor, inputs, _info, _tools = agent._prepare_kickoff(+ [+ {"role": "user", "content": "here is the earlier note"},+ {"role": "user", "content": "", "files": {"scan": "bytes"}},+ ]+ )++ assert inputs["files"] == {"scan": "bytes"}+ assert [message["content"] for message in inputs["history"]] == [+ "here is the earlier note"+ ]+++async def test_kickoff_async_orders_the_conversation_the_same_way() -> None:+ """`kickoff_async` shares `_prepare_kickoff` and `_setup_messages`.++ Sharing is not the same as being covered: the async executor entry+ points reach `_setup_messages` separately, so the ordering is asserted+ through the async path too.+ """+ llm = _Recorder()+ await Agent(role="Support", goal="help", backstory="b", llm=llm).kickoff_async(+ TOOL_CONVERSATION+ )+ seen = llm.seen[0]++ assert [message["role"] for message in seen] == [+ "system",+ "user",+ "assistant",+ "tool",+ ]+ assert "what is the weather in Lisbon?" in str(seen[1]["content"])+ assert seen[3]["tool_call_id"] == "c1"diff --git a/lib/crewai/tests/test_flow_from_definition.py b/lib/crewai/tests/test_flow_from_definition.pyindex f5ac6ee15..14b85fedc 100644--- a/lib/crewai/tests/test_flow_from_definition.py+++ b/lib/crewai/tests/test_flow_from_definition.py@@ -1332,6 +1332,55 @@ methods:}+def test_agent_action_delivers_a_rendered_conversation_to_the_agent(+ monkeypatch: pytest.MonkeyPatch,+):+ """The whole path: `${state.messages}` -> normalization -> `kickoff_async`."""+ from crewai import Agent++ received: list[Any] = []++ async def fake_kickoff_async(self: Agent, messages: Any, **_kwargs: Any) -> str:+ received.append(messages)+ return "answered"++ monkeypatch.setattr(Agent, "kickoff_async", fake_kickoff_async)++ yaml_str = """+schema: crewai.flow/v1+name: HistoryAgentFlow+methods:+ answer:+ do:+ call: agent+ with:+ role: Analyst+ goal: Answer questions+ backstory: Knows things.+ input: "${state.messages}"+ start: true+"""++ flow = Flow.from_declaration(contents=yaml_str)+ result = flow.kickoff(+ inputs={+ "messages": [+ {"role": "user", "content": "my order id is 42", "name": None},+ {"role": "assistant", "content": "thanks, checking"},+ ]+ }+ )++ assert result == "answered"+ # A list, not a stringified blob, and the serialization noise is gone.+ assert received == [+ [+ {"role": "user", "content": "my order id is 42"},+ {"role": "assistant", "content": "thanks, checking"},+ ]+ ]++def test_agent_action_runs_inside_each(monkeypatch: pytest.MonkeyPatch):from crewai import Agent@@ -4039,6 +4088,95 @@ methods: {}FlowDefinition.from_declaration(contents=yaml_str)++def test_agent_action_accepts_a_rendered_message_list():+ """A chat handler can hand the agent the conversation, not just a string."""+ from crewai.flow.runtime._actions import _normalize_agent_input++ rendered = [+ {"role": "user", "content": "my order id is 42"},+ {"role": "assistant", "content": "thanks, checking"},+ ]++ assert _normalize_agent_input(rendered) == rendered+++def test_agent_action_strips_serialized_message_metadata():+ """A raw `${state.messages}` render carries None keys the event rejects."""+ from crewai.flow.runtime._actions import _normalize_agent_input++ normalized = _normalize_agent_input(+ [{"role": "user", "content": "hi", "name": None, "metadata": {}}]+ )++ assert normalized == [{"role": "user", "content": "hi"}]+++def test_agent_action_keeps_a_none_content_tool_call_message():+ """A tool-call turn has no content; dropping the key breaks the sequence."""+ from crewai.flow.runtime._actions import _normalize_agent_input++ normalized = _normalize_agent_input(+ [+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "lookup"}}],+ "name": None,+ }+ ]+ )++ assert normalized == [+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "lookup"}}],+ }+ ]+++def test_agent_action_still_accepts_a_string():+ from crewai.flow.runtime._actions import _normalize_agent_input++ assert _normalize_agent_input("just a prompt") == "just a prompt"+++def test_agent_action_rejects_a_shape_that_is_neither():+ from crewai.flow.runtime._actions import _normalize_agent_input++ with pytest.raises(+ ValueError, match="must render to a string or a list of messages"+ ):+ _normalize_agent_input(1234)+++def test_agent_definition_accepts_a_message_list_input():+ from crewai.project.crew_definition import AgentDefinition++ definition = AgentDefinition.model_validate(+ {+ "role": "R",+ "goal": "G",+ "backstory": "B",+ "input": [{"role": "user", "content": "hi"}],+ }+ )++ assert definition.input == [{"role": "user", "content": "hi"}]+++def test_agent_definition_rejects_a_non_message_input():+ from crewai.project.crew_definition import AgentDefinition++ with pytest.raises(+ ValidationError, match="must be a string or a list of messages"+ ):+ AgentDefinition.model_validate(+ {"role": "R", "goal": "G", "backstory": "B", "input": [1, 2]}+ )++def test_definition_method_missing_from_class_fails_loudly():class VanishingFlow(Flow):@start()