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 null in the task output schema embedded in the prompt (#6775)
monkscode5704ea08ebc4
diff --git a/lib/crewai/src/crewai/agent/utils.py b/lib/crewai/src/crewai/agent/utils.pyindex 20eb06b47..297322a0c 100644--- a/lib/crewai/src/crewai/agent/utils.py+++ b/lib/crewai/src/crewai/agent/utils.py@@ -74,13 +74,17 @@ def build_task_prompt_with_schema(task: Task, task_prompt: str) -> str:if (task.output_json or task.output_pydantic) and not task.response_model:if task.output_json:- schema_dict = generate_model_description(task.output_json)+ schema_dict = generate_model_description(+ task.output_json, strip_null_types=False+ )schema = json.dumps(schema_dict["json_schema"]["schema"], indent=2)task_prompt += "\n" + I18N_DEFAULT.slice("formatted_task_instructions").format(output_format=schema)elif task.output_pydantic:- schema_dict = generate_model_description(task.output_pydantic)+ schema_dict = generate_model_description(+ task.output_pydantic, strip_null_types=False+ )schema = json.dumps(schema_dict["json_schema"]["schema"], indent=2)task_prompt += "\n" + I18N_DEFAULT.slice("formatted_task_instructions"diff --git a/lib/crewai/tests/agents/test_agent_utils.py b/lib/crewai/tests/agents/test_agent_utils.pynew file mode 100644index 000000000..3d2a2152e--- /dev/null+++ b/lib/crewai/tests/agents/test_agent_utils.py@@ -0,0 +1,41 @@+"""Tests for crewai.agent.utils prompt-building helpers."""++from __future__ import annotations++import json++import pytest+from pydantic import BaseModel, Field++from crewai import Task+from crewai.agent.utils import build_task_prompt_with_schema+++class _Output(BaseModel):+ name: str+ note: str | None = Field(default=None)++[email protected]("output_attribute", ["output_pydantic", "output_json"])+def test_optional_fields_stay_nullable_in_the_prompt_schema(+ output_attribute: str,+) -> None:+ """An Optional field must still be expressible as null in the prompt schema.++ The provider-side response schema generated from the same model allows null,+ so stripping it here hands the model two contradictory contracts and leaves+ it no way to say "not applicable". Both output attributes embed a schema in+ the prompt, so both are pinned.+ """+ task = Task(description="d", expected_output="e", **{output_attribute: _Output})++ prompt = build_task_prompt_with_schema(task, "")++ start = prompt.index("{")+ end = prompt.rindex("}", start) + 1+ schema = json.loads(prompt[start:end])++ assert {entry["type"] for entry in schema["properties"]["note"]["anyOf"]} == {+ "string",+ "null",+ }