Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

feat(cli): crewai deploy push --force, and why AMP held a push back (#8150)

João Moura8dcb00584f5f
diff --git a/lib/cli/src/crewai_cli/cli.py b/lib/cli/src/crewai_cli/cli.py
index c2a6c2789..f0765e4dc 100644
--- a/lib/cli/src/crewai_cli/cli.py
+++ b/lib/cli/src/crewai_cli/cli.py
@@ -833,7 +833,16 @@ def deploy_list() -> None:
is_flag=True,
help="Skip the pre-deploy validation checks.",
)
-def deploy_push(uuid: str | None, skip_validate: bool) -> None:
+ "--force",
+ is_flag=True,
+ help=(
+ "Redeploy even while a models comparison is running on the deployment. "
+ "It stops the comparison and its runs under way are lost; without it, "
+ "AMP holds the push back."
+ ),
+)
+def deploy_push(uuid: str | None, skip_validate: bool, force: bool) -> None:
"""Deploy the Crew."""
# Backfills a project_id for projects that have [tool.crewai] but no id yet.
# Safe in every command the user explicitly invoked: get_or_create_project_id
@@ -841,7 +850,7 @@ def deploy_push(uuid: str | None, skip_validate: bool) -> None:
# never rewrites an unrelated directory. Never called from the SDK during kickoff.
get_or_create_project_id()
deploy_cmd = DeployCommand()
- deploy_cmd.deploy(uuid=uuid, skip_validate=skip_validate)
+ deploy_cmd.deploy(uuid=uuid, skip_validate=skip_validate, force=force)
@deploy.command(name="validate")
diff --git a/lib/cli/src/crewai_cli/deploy/main.py b/lib/cli/src/crewai_cli/deploy/main.py
index 5dfa66529..96d0912a1 100644
--- a/lib/cli/src/crewai_cli/deploy/main.py
+++ b/lib/cli/src/crewai_cli/deploy/main.py
@@ -190,6 +190,31 @@ def _response_failure_reason(response: httpx.Response) -> DeployFailureReason |
return None
+def _refuse_on_running_comparison(response: httpx.Response) -> None:
+ """AMP held the push back because a models comparison is running on the
+ deployment (a redeploy would stop it and lose its runs): say so in AMP's
+ own sentence, which names `--force`, and exit 1 — nothing was deployed."""
+ if response.status_code != 409:
+ return
+ try:
+ body = response.json()
+ except ValueError:
+ return
+ if not isinstance(body, dict) or body.get("error") != "comparison_running":
+ return
+ # AMP's words, printed as they are: Rich markup in them (a bracketed
+ # word, a stray closing tag) must neither vanish nor raise.
+ console.print(
+ str(
+ body.get("message") or "A models comparison is running on this deployment."
+ ),
+ style="bold yellow",
+ markup=False,
+ )
+ console.print("Nothing was deployed.")
+ raise SystemExit(1)
+
+
def _needs_lockfile_for_deploy(project_root: Path | None = None) -> bool:
"""Return True when deploy should create the project's first lockfile."""
root = project_root or Path.cwd()
@@ -256,11 +281,19 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
# deployment runs — `crewai eval --models` finds the deployment by it.
# Read, never minted: a deploy does not rewrite pyproject.toml.
self.project_id = get_project_id()
+ # `crewai deploy push --force`: go ahead even while a models
+ # comparison runs on the deployment (`deploy` sets it per push).
+ self._force = False
def _project(self) -> dict[str, str]:
"""`project_id=` for a create or push request, when the project has one."""
return {"project_id": self.project_id} if self.project_id else {}
+ def _push(self) -> dict[str, Any]:
+ """A push request's options: `project_id=` as `_project`, and
+ `force=True` when the push was asked to go ahead whatever runs."""
+ return {**self._project(), **({"force": True} if self._force else {})}
+
def _standard_no_param_error_message(self) -> None:
"""
Display a standard error message when no UUID or project name is available.
@@ -371,6 +404,7 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
uuid: str | None = None,
skip_validate: bool = False,
source: DeploySource = "cli",
+ force: bool = False,
) -> None:
"""
Deploy a crew using either UUID or project name.
@@ -379,7 +413,10 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
uuid (Optional[str]): The UUID of the crew to deploy.
skip_validate (bool): Skip pre-deploy validation checks.
source (DeploySource): Where the deployment was initiated from.
+ force (bool): Redeploy even while a models comparison runs on the
+ deployment, which stops it (AMP refuses otherwise).
"""
+ self._force = force
if not _prepare_project_for_deploy(skip_validate):
return
self._telemetry.start_deployment_span(uuid, source=source)
@@ -402,6 +439,7 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
self._standard_no_param_error_message()
return
+ _refuse_on_running_comparison(response)
self._validate_response(response)
self._display_deployment_info(response.json())
@@ -452,10 +490,10 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
env_vars = fetch_and_json_env_file()
return self._update_crew_from_zip(deployment_uuid, repository, env_vars)
if uuid:
- return self.plus_api_client.deploy_by_uuid(uuid, **self._project())
+ return self.plus_api_client.deploy_by_uuid(uuid, **self._push())
if not project_name:
raise ValueError("project_name is required to deploy by name")
- return self.plus_api_client.deploy_by_name(project_name, **self._project())
+ return self.plus_api_client.deploy_by_name(project_name, **self._push())
def _deploy_from_local_source(
self,
@@ -466,9 +504,9 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
) -> Any | None:
"""Deploy using local origin, as before AMP zip_deployment existed."""
if remote_repo_url and uuid:
- return self.plus_api_client.deploy_by_uuid(uuid, **self._project())
+ return self.plus_api_client.deploy_by_uuid(uuid, **self._push())
if remote_repo_url and project_name:
- return self.plus_api_client.deploy_by_name(project_name, **self._project())
+ return self.plus_api_client.deploy_by_name(project_name, **self._push())
if uuid:
_display_git_remote_help()
env_vars = fetch_and_json_env_file()
@@ -678,7 +716,7 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
uuid,
zip_file_path,
env=env_vars,
- **self._project(),
+ **self._push(),
)
finally:
zip_file_path.unlink(missing_ok=True)
diff --git a/lib/cli/src/crewai_cli/plus_api.py b/lib/cli/src/crewai_cli/plus_api.py
index b9b2f1d28..9632e8a8f 100644
--- a/lib/cli/src/crewai_cli/plus_api.py
+++ b/lib/cli/src/crewai_cli/plus_api.py
@@ -158,14 +158,19 @@ class PlusAPI(_CorePlusAPI):
*,
env: dict[str, str] | None = None,
project_id: str | None = None,
+ force: bool = False,
) -> httpx.Response:
"""Update an existing crew deployment from a local project ZIP archive.
- PROJECT_ID as for `create_crew_from_zip`.
+ PROJECT_ID as for `create_crew_from_zip`; FORCE redeploys even while a
+ models comparison runs on the deployment (AMP answers 409
+ ``comparison_running`` otherwise; an older AMP ignores it).
"""
data: dict[str, str] = {}
if project_id:
data["project_id"] = project_id
+ if force:
+ data["force"] = "true"
if env:
data.update({f"env[{key}]": value for key, value in env.items()})
return self._make_multipart_request(
diff --git a/lib/cli/tests/deploy/test_deploy_main.py b/lib/cli/tests/deploy/test_deploy_main.py
index c049f358c..0bb846409 100644
--- a/lib/cli/tests/deploy/test_deploy_main.py
+++ b/lib/cli/tests/deploy/test_deploy_main.py
@@ -447,6 +447,67 @@ class TestDeployCommand(unittest.TestCase):
self.mock_client.deploy_by_uuid.assert_called_once_with("test-uuid")
mock_display.assert_called_once_with({"uuid": "test-uuid"})
+ @patch("crewai_cli.deploy.main.git.Repository")
+ @patch("crewai_cli.deploy.main.DeployCommand._display_deployment_info")
+ def test_a_push_amp_holds_back_for_a_running_comparison_says_why_and_force_goes_ahead(
+ self, mock_display, mock_repository
+ ):
+ mock_repository.return_value.origin_url.return_value = "https://github.com/test/repo.git"
+ mock_repository.return_value.create_initial_commit_if_needed.return_value = False
+ self.mock_client.crew_status_by_uuid.return_value = self._status_response(zip_deployment=False)
+ held = MagicMock()
+ held.status_code = 409
+ held.json.return_value = {
+ "error": "comparison_running",
+ "message": "A models comparison is running on this deployment (started 05:03 UTC): redeploying now "
+ "stops it, and the runs under way are lost. Wait for it to finish, or redeploy anyway with "
+ "`crewai deploy push --force`.",
+ }
+ self.mock_client.deploy_by_uuid.return_value = held
+
+ with patch("sys.stdout", new=StringIO()) as out, self.assertRaises(SystemExit) as stopped:
+ self.deploy_command.deploy(uuid="test-uuid", skip_validate=True)
+
+ self.assertEqual(stopped.exception.code, 1)
+ printed = " ".join(out.getvalue().split())
+ self.assertIn("A models comparison is running on this deployment (started 05:03 UTC)", printed)
+ self.assertIn("`crewai deploy push --force`", printed)
+ self.assertIn("Nothing was deployed.", printed)
+ self.assertNotIn("comparison_running", printed)
+ mock_display.assert_not_called()
+
+ ok = MagicMock()
+ ok.status_code = 200
+ ok.json.return_value = {"uuid": "test-uuid"}
+ self.mock_client.deploy_by_uuid.reset_mock()
+ self.mock_client.deploy_by_uuid.return_value = ok
+ self.deploy_command.deploy(uuid="test-uuid", skip_validate=True, force=True)
+ self.mock_client.deploy_by_uuid.assert_called_once_with("test-uuid", force=True)
+ mock_display.assert_called_once_with({"uuid": "test-uuid"})
+
+ @patch("crewai_cli.deploy.main.git.Repository")
+ @patch("crewai_cli.deploy.main.DeployCommand._display_deployment_info")
+ def test_amps_hold_back_sentence_is_printed_literally_whatever_brackets_it_has(
+ self, mock_display, mock_repository
+ ):
+ mock_repository.return_value.origin_url.return_value = "https://github.com/test/repo.git"
+ mock_repository.return_value.create_initial_commit_if_needed.return_value = False
+ self.mock_client.crew_status_by_uuid.return_value = self._status_response(zip_deployment=False)
+ held = MagicMock()
+ held.status_code = 409
+ held.json.return_value = {
+ "error": "comparison_running",
+ "message": "A comparison [bold]running[/] on [crew] [/unmatched] — redeploy with --force.",
+ }
+ self.mock_client.deploy_by_uuid.return_value = held
+
+ with patch("sys.stdout", new=StringIO()) as out, self.assertRaises(SystemExit):
+ self.deploy_command.deploy(uuid="test-uuid", skip_validate=True)
+
+ printed = " ".join(out.getvalue().split())
+ self.assertIn("A comparison [bold]running[/] on [crew] [/unmatched] — redeploy with --force.", printed)
+ self.assertIn("Nothing was deployed.", printed)
+
@patch("crewai_cli.deploy.main.git.Repository")
@patch("crewai_cli.deploy.main.DeployCommand._display_deployment_info")
def test_deploy_with_project_name(self, mock_display, mock_repository):
diff --git a/lib/cli/tests/test_cli.py b/lib/cli/tests/test_cli.py
index 4a5738370..a4a7ee738 100644
--- a/lib/cli/tests/test_cli.py
+++ b/lib/cli/tests/test_cli.py
@@ -384,7 +384,16 @@ def test_deploy_push(command, runner):
result = runner.invoke(deploy_push, ["-u", uuid])
assert result.exit_code == 0
- mock_deploy.deploy.assert_called_once_with(uuid=uuid, skip_validate=False)
+ mock_deploy.deploy.assert_called_once_with(uuid=uuid, skip_validate=False, force=False)
+
+
[email protected]("crewai_cli.cli.DeployCommand")
+def test_deploy_push_force_goes_ahead_whatever_runs(command, runner):
+ mock_deploy = command.return_value
+ result = runner.invoke(deploy_push, ["-u", "test-uuid", "--force"])
+
+ assert result.exit_code == 0
+ mock_deploy.deploy.assert_called_once_with(uuid="test-uuid", skip_validate=False, force=True)
@mock.patch("crewai_cli.cli.DeployCommand")
@@ -393,7 +402,7 @@ def test_deploy_push_no_uuid(command, runner):
result = runner.invoke(deploy_push)
assert result.exit_code == 0
- mock_deploy.deploy.assert_called_once_with(uuid=None, skip_validate=False)
+ mock_deploy.deploy.assert_called_once_with(uuid=None, skip_validate=False, force=False)
@mock.patch("crewai_cli.cli.DeployCommand")
diff --git a/lib/cli/tests/test_plus_api.py b/lib/cli/tests/test_plus_api.py
index eb5269152..15abb8ba2 100644
--- a/lib/cli/tests/test_plus_api.py
+++ b/lib/cli/tests/test_plus_api.py
@@ -312,6 +312,23 @@ class TestPlusAPI(unittest.TestCase):
"POST", "/crewai_plus/api/v1/crews/test_uuid/deploy"
)
+ @patch("crewai_core.plus_api.PlusAPI._make_request")
+ def test_a_forced_push_says_so_and_an_unforced_one_sends_what_it_always_did(self, mock_make_request):
+ self.api.deploy_by_uuid("test_uuid", force=True)
+ mock_make_request.assert_called_with(
+ "POST", "/crewai_plus/api/v1/crews/test_uuid/deploy", json={"force": True}
+ )
+ self.api.deploy_by_name("test_project", project_id="proj-1", force=True)
+ mock_make_request.assert_called_with(
+ "POST",
+ "/crewai_plus/api/v1/crews/by-name/test_project/deploy",
+ json={"project_id": "proj-1", "force": True},
+ )
+ self.api.deploy_by_uuid("test_uuid", force=False)
+ mock_make_request.assert_called_with(
+ "POST", "/crewai_plus/api/v1/crews/test_uuid/deploy"
+ )
+
@patch("crewai_core.plus_api.PlusAPI._make_request")
def test_deploy_sends_the_project_id_when_there_is_one(self, mock_make_request):
self.api.deploy_by_name("test_project", project_id="proj-1")
@@ -442,6 +459,8 @@ class TestPlusAPI(unittest.TestCase):
data={"env[ENV_VAR]": "value"},
timeout=300,
)
+ self.api.update_crew_from_zip("test_uuid", "/tmp/test.zip", force=True)
+ assert mock_make_multipart_request.call_args.kwargs["data"] == {"force": "true"}
@patch("crewai_core.plus_api.Settings")
@patch.dict(os.environ, {"CREWAI_PLUS_URL": ""})
diff --git a/lib/crewai-core/src/crewai_core/plus_api.py b/lib/crewai-core/src/crewai_core/plus_api.py
index 97af76042..a8ce4dbc0 100644
--- a/lib/crewai-core/src/crewai_core/plus_api.py
+++ b/lib/crewai-core/src/crewai_core/plus_api.py
@@ -329,27 +329,37 @@ class PlusAPI:
)
def deploy_by_name(
- self, project_name: str, *, project_id: str | None = None
+ self, project_name: str, *, project_id: str | None = None, force: bool = False
) -> httpx.Response:
"""Redeploy by name, with PROJECT_ID (`[tool.crewai].project_id`) when set.
- The body is sent only when there is a project id. An AMP that predates
- project ids ignores it: this route has read its body through Rails'
- ``params.permit`` since the v1 API (2024-08), which drops a key it does
- not name, and AMP never made unpermitted keys an error.
+ The body is sent only when there is something in it. An AMP that
+ predates project ids ignores it: this route has read its body through
+ Rails' ``params.permit`` since the v1 API (2024-08), which drops a key
+ it does not name, and AMP never made unpermitted keys an error. FORCE
+ redeploys even while a models comparison runs on the deployment (AMP
+ answers 409 ``comparison_running`` otherwise; an older AMP ignores it).
"""
endpoint = f"{self.CREWS_RESOURCE}/by-name/{project_name}/deploy"
- if project_id:
- return self._make_request("POST", endpoint, json={"project_id": project_id})
- return self._make_request("POST", endpoint)
+ return self._redeploy(endpoint, project_id=project_id, force=force)
def deploy_by_uuid(
- self, uuid: str, *, project_id: str | None = None
+ self, uuid: str, *, project_id: str | None = None, force: bool = False
) -> httpx.Response:
- """Redeploy by uuid, with PROJECT_ID as for `deploy_by_name`."""
+ """Redeploy by uuid, with PROJECT_ID and FORCE as for `deploy_by_name`."""
endpoint = f"{self.CREWS_RESOURCE}/{uuid}/deploy"
+ return self._redeploy(endpoint, project_id=project_id, force=force)
+
+ def _redeploy(
+ self, endpoint: str, *, project_id: str | None, force: bool
+ ) -> httpx.Response:
+ body: dict[str, Any] = {}
if project_id:
- return self._make_request("POST", endpoint, json={"project_id": project_id})
+ body["project_id"] = project_id
+ if force:
+ body["force"] = True
+ if body:
+ return self._make_request("POST", endpoint, json=body)
return self._make_request("POST", endpoint)
def crew_status_by_name(self, project_name: str) -> httpx.Response:
@@ -421,14 +431,17 @@ class PlusAPI:
*,
env: dict[str, str] | None = None,
project_id: str | None = None,
+ force: bool = False,
) -> httpx.Response:
"""Update an existing crew deployment from a local project ZIP archive.
- PROJECT_ID as for `create_crew_from_zip`.
+ PROJECT_ID as for `create_crew_from_zip`, FORCE as for `deploy_by_name`.
"""
data: dict[str, str] = {}
if project_id:
data["project_id"] = project_id
+ if force:
+ data["force"] = "true"
if env:
data.update({f"env[{key}]": value for key, value in env.items()})
return self._make_multipart_request(