mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-07-28 10:09:21 +00:00
feat(tools): add WaitTool for pausing on long-running jobs (#6690)
Some checks failed
Some checks failed
* feat(tools): add WaitTool for pausing on long-running jobs Agents that kick off out-of-band work (a sandbox build, a deployment, an async API job) have no way to let clock time pass: they either poll in a tight loop or give up before the work finishes. WaitTool pauses for a given number of seconds, with an optional reason echoed back for traces. A single call waits at most max_seconds (default 300, configurable). Longer requests are clamped to the cap and the result says so, so the model calls again rather than failing. Sync and async execution are both implemented; stdlib only, no new dependencies. The tool description spells out when to reach for it (builds, deploys, batch jobs, async polling, backoff) and when not to, so models pick it up for the right reason. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(tools): enforce non-negative wait on positional calls, fix doc snippets BaseTool.run() skips args_schema validation when called with positional arguments, so tool.run(-5) reached time.sleep(-5) and failed with an unrelated error. _resolve_duration now enforces the seconds >= 0 contract itself, covered for both run() and arun(). Docs and README examples are now self-contained: check_build_status_tool is defined with the @tool decorator instead of referenced out of nowhere, and the async example awaits inside asyncio.run() rather than at top level. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs: point the wait tool card at the edge path Unprefixed links resolve against the default docs version (v1.15.7), where the wait tool page does not exist, so the card 404'd in the broken link check. Prefixing with /edge matches how other edge pages link. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(tools): never cache waits and keep the advertised cap accurate Two issues from review, both confirmed against the code. Waits inherited the default cache_function, which always allows caching. With crew cache enabled, a repeat call with the same arguments returned "Waited N seconds." straight from the cache without sleeping, turning a poll-wait-check loop into a busy loop. WaitTool now declares a cache_function that always refuses. The description advertising the cap was only rebuilt when max_seconds reached __init__ without an explicit description. Passing both (as a platform building from tool.specs.json init params would), calling model_validate, or assigning max_seconds left the text claiming 300 seconds while clamping to something else. A model_validator now derives the description from max_seconds on construction, validation, and assignment, and leaves a caller-supplied description untouched. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(tools): reject NaN waits and pluralize single-second results _resolve_duration now rejects NaN with its own message instead of letting time.sleep raise "Invalid value NaN (not a number)" from a positional call. Infinity keeps clamping to the cap like any other oversized wait. Result and description text no longer says "1 seconds". Tests use the public WaitTool().description as the baseline rather than reaching for module-private helpers. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -318,6 +318,7 @@
|
||||
"edge/en/tools/automation/apifyactorstool",
|
||||
"edge/en/tools/automation/composiotool",
|
||||
"edge/en/tools/automation/multiontool",
|
||||
"edge/en/tools/automation/waittool",
|
||||
"edge/en/tools/automation/zapieractionstool"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ These tools enable your agents to automate workflows, integrate with external pl
|
||||
Automate browser interactions and web-based workflows.
|
||||
</Card>
|
||||
|
||||
<Card title="Wait Tool" icon="hourglass-half" href="/edge/en/tools/automation/waittool">
|
||||
Pause before re-checking a long-running job such as a build or deployment.
|
||||
</Card>
|
||||
|
||||
<Card title="Zapier Actions Adapter" icon="bolt" href="/en/tools/automation/zapieractionstool">
|
||||
Expose Zapier Actions as CrewAI tools for automation across thousands of apps.
|
||||
</Card>
|
||||
|
||||
124
docs/edge/en/tools/automation/waittool.mdx
Normal file
124
docs/edge/en/tools/automation/waittool.mdx
Normal file
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: Wait Tool
|
||||
description: The `WaitTool` lets an agent pause before checking a long-running job again.
|
||||
icon: hourglass-half
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The `WaitTool` pauses execution for a given number of seconds. It exists because agents that
|
||||
kick off long-running work — a sandbox build, a deployment, a batch import, an async API job —
|
||||
otherwise have no way to let time pass. Without it, an agent either polls in a tight loop or
|
||||
gives up before the work finishes.
|
||||
|
||||
The tool takes no API key and has no dependencies beyond the standard library.
|
||||
|
||||
## When to Use It
|
||||
|
||||
The tool's description tells the model to reach for it when out-of-band work needs real time
|
||||
to progress:
|
||||
|
||||
- A sandbox build, test run, or script that is still executing
|
||||
- A deployment or provisioning step that is still rolling out
|
||||
- A batch import, export, or training job
|
||||
- An async API that returned a job id to poll later
|
||||
- A rate limit or backoff that has to cool down before retrying
|
||||
|
||||
The pattern the model is steered toward is: start the job, wait, check status, wait again if it
|
||||
is still running. The description also tells it *not* to wait to pace a conversation or when the
|
||||
information it needs is already available — waiting only lets clock time pass, it does not
|
||||
advance or check the job.
|
||||
|
||||
## Installation
|
||||
|
||||
The tool ships with `crewai-tools`:
|
||||
|
||||
```shell
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.tools import tool
|
||||
from crewai_tools import WaitTool
|
||||
|
||||
wait_tool = WaitTool()
|
||||
|
||||
|
||||
@tool("Check build status")
|
||||
def check_build_status_tool(build_id: str) -> str:
|
||||
"""Return the current status of a build: queued, running, passed, or failed."""
|
||||
# Replace this with a call to your own build system.
|
||||
return my_ci_client.get_build(build_id).status
|
||||
|
||||
|
||||
build_agent = Agent(
|
||||
role="Build Monitor",
|
||||
goal="Start the build and report its final status",
|
||||
backstory="An engineer who knows that builds take time.",
|
||||
tools=[wait_tool, check_build_status_tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
monitor_task = Task(
|
||||
description=(
|
||||
"Start the build, then wait and re-check its status until it finishes."
|
||||
),
|
||||
expected_output="The final build status.",
|
||||
agent=build_agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[build_agent], tasks=[monitor_task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
| Argument | Type | Required | Description |
|
||||
| :-------- | :------ | :------- | :----------------------------------------------------------------------------- |
|
||||
| `seconds` | `float` | ✅ | How many seconds to wait. Must be zero or greater. |
|
||||
| `reason` | `str` | ❌ | Optional note on what is being waited for. Echoed back in the tool's result. |
|
||||
|
||||
## Initialization Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| :------------ | :------ | :------ | :----------------------------------------------------------------------------------- |
|
||||
| `max_seconds` | `float` | `300` | Upper bound for a single wait. Longer requests are capped to this value, not rejected. |
|
||||
|
||||
## Capping Long Waits
|
||||
|
||||
A single call waits at most `max_seconds`. If an agent asks for more, the tool waits the
|
||||
maximum and says so in its result, so the agent can call it again rather than fail:
|
||||
|
||||
```python Code
|
||||
wait_tool = WaitTool()
|
||||
wait_tool.run(seconds=3600)
|
||||
# 'Waited 300 seconds. Requested 3600 seconds, capped at 300 seconds per call -
|
||||
# call this tool again if more waiting is needed.'
|
||||
```
|
||||
|
||||
Raise the cap when a workflow genuinely needs longer single pauses:
|
||||
|
||||
```python Code
|
||||
wait_tool = WaitTool(max_seconds=1800)
|
||||
```
|
||||
|
||||
## Async Support
|
||||
|
||||
The tool implements both sync and async execution, so it does not block the event loop when
|
||||
awaited:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
|
||||
async def main():
|
||||
result = await wait_tool.arun(seconds=30, reason="waiting for the sandbox build")
|
||||
print(result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
@@ -206,6 +206,7 @@ from crewai_tools.tools.tavily_research_tool.tavily_research_tool import (
|
||||
from crewai_tools.tools.tavily_search_tool.tavily_search_tool import TavilySearchTool
|
||||
from crewai_tools.tools.txt_search_tool.txt_search_tool import TXTSearchTool
|
||||
from crewai_tools.tools.vision_tool.vision_tool import VisionTool
|
||||
from crewai_tools.tools.wait_tool.wait_tool import WaitTool
|
||||
from crewai_tools.tools.weaviate_tool.vector_search import WeaviateVectorSearchTool
|
||||
from crewai_tools.tools.website_search.website_search_tool import WebsiteSearchTool
|
||||
from crewai_tools.tools.xml_search_tool.xml_search_tool import XMLSearchTool
|
||||
@@ -321,6 +322,7 @@ __all__ = [
|
||||
"TavilyResearchTool",
|
||||
"TavilySearchTool",
|
||||
"VisionTool",
|
||||
"WaitTool",
|
||||
"WeaviateVectorSearchTool",
|
||||
"WebsiteSearchTool",
|
||||
"XMLSearchTool",
|
||||
|
||||
@@ -193,6 +193,7 @@ from crewai_tools.tools.tavily_research_tool.tavily_research_tool import (
|
||||
from crewai_tools.tools.tavily_search_tool.tavily_search_tool import TavilySearchTool
|
||||
from crewai_tools.tools.txt_search_tool.txt_search_tool import TXTSearchTool
|
||||
from crewai_tools.tools.vision_tool.vision_tool import VisionTool
|
||||
from crewai_tools.tools.wait_tool.wait_tool import WaitTool
|
||||
from crewai_tools.tools.weaviate_tool.vector_search import WeaviateVectorSearchTool
|
||||
from crewai_tools.tools.website_search.website_search_tool import WebsiteSearchTool
|
||||
from crewai_tools.tools.xml_search_tool.xml_search_tool import XMLSearchTool
|
||||
@@ -304,6 +305,7 @@ __all__ = [
|
||||
"TavilyResearchTool",
|
||||
"TavilySearchTool",
|
||||
"VisionTool",
|
||||
"WaitTool",
|
||||
"WeaviateVectorSearchTool",
|
||||
"WebsiteSearchTool",
|
||||
"XMLSearchTool",
|
||||
|
||||
70
lib/crewai-tools/src/crewai_tools/tools/wait_tool/README.md
Normal file
70
lib/crewai-tools/src/crewai_tools/tools/wait_tool/README.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# WaitTool
|
||||
|
||||
The **WaitTool** pauses execution for a given number of seconds. Use it when an agent needs to
|
||||
let time pass before re-checking a long-running job — a sandbox build, a deployment, a batch
|
||||
import, an async API call.
|
||||
|
||||
No API key, no dependencies beyond the standard library.
|
||||
|
||||
## Arguments
|
||||
|
||||
| Argument | Type | Required | Description |
|
||||
| --------- | ------- | -------- | ---------------------------------------------------------------------------- |
|
||||
| `seconds` | `float` | ✅ | How many seconds to wait. Must be zero or greater. |
|
||||
| `reason` | `str` | ❌ | Optional note on what is being waited for. Echoed back in the tool's result. |
|
||||
|
||||
## Initialization Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| ------------- | ------- | ------- | -------------------------------------------------------------------------------------- |
|
||||
| `max_seconds` | `float` | `300` | Upper bound for a single wait. Longer requests are capped to this value, not rejected. |
|
||||
|
||||
## Usage Example
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai.tools import tool
|
||||
from crewai_tools import WaitTool
|
||||
|
||||
wait_tool = WaitTool()
|
||||
|
||||
|
||||
@tool("Check build status")
|
||||
def check_build_status_tool(build_id: str) -> str:
|
||||
"""Return the current status of a build: queued, running, passed, or failed."""
|
||||
# Replace this with a call to your own build system.
|
||||
return my_ci_client.get_build(build_id).status
|
||||
|
||||
|
||||
agent = Agent(
|
||||
role="Build Monitor",
|
||||
goal="Start the build and report its final status",
|
||||
backstory="An engineer who knows that builds take time.",
|
||||
tools=[wait_tool, check_build_status_tool],
|
||||
)
|
||||
```
|
||||
|
||||
A single call waits at most `max_seconds`. Longer requests are capped and the result says so,
|
||||
so the agent can simply call the tool again:
|
||||
|
||||
```python
|
||||
wait_tool.run(seconds=3600)
|
||||
# 'Waited 300 seconds. Requested 3600 seconds, capped at 300 seconds per call -
|
||||
# call this tool again if more waiting is needed.'
|
||||
|
||||
WaitTool(max_seconds=1800).run(seconds=900)
|
||||
# 'Waited 900 seconds.'
|
||||
```
|
||||
|
||||
Async execution is supported and does not block the event loop:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
|
||||
async def main():
|
||||
print(await wait_tool.arun(seconds=30, reason="waiting for the sandbox build"))
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
@@ -0,0 +1,4 @@
|
||||
from crewai_tools.tools.wait_tool.wait_tool import WaitTool, WaitToolSchema
|
||||
|
||||
|
||||
__all__ = ["WaitTool", "WaitToolSchema"]
|
||||
232
lib/crewai-tools/src/crewai_tools/tools/wait_tool/wait_tool.py
Normal file
232
lib/crewai-tools/src/crewai_tools/tools/wait_tool/wait_tool.py
Normal file
@@ -0,0 +1,232 @@
|
||||
"""Tool that pauses execution for a given amount of time."""
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from crewai.tools import BaseTool
|
||||
from crewai.types.callback import SerializableCallable
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
|
||||
DEFAULT_MAX_SECONDS: float = 300.0
|
||||
|
||||
_DESCRIPTION_TEMPLATE = (
|
||||
"Pause and do nothing for a set number of seconds before continuing.\n"
|
||||
"Use this when work that was already started somewhere else needs real time to "
|
||||
"finish before its status or result can be checked again, for example: a sandbox "
|
||||
"build, test run, or script that is still executing; a deployment or provisioning "
|
||||
"step that is still rolling out; a batch import, export, or training job; an async "
|
||||
"API that returned a job id to poll later; or a rate limit or backoff that has to "
|
||||
"cool down before retrying.\n"
|
||||
"The usual pattern is: start the job, wait, check its status, and wait again if it "
|
||||
"is still running.\n"
|
||||
"Do not use this to pace a conversation, to pretend to work, or when the "
|
||||
"information needed is already available. Waiting only lets clock time pass, it "
|
||||
"does not advance or check the job.\n"
|
||||
"A single call waits at most {cap}. If more time is needed, "
|
||||
"call this tool again."
|
||||
)
|
||||
|
||||
# Everything before the cap figure; used to tell a generated description from one
|
||||
# the caller wrote, so only generated text is kept in sync with ``max_seconds``.
|
||||
_GENERATED_DESCRIPTION_PREFIX = _DESCRIPTION_TEMPLATE.split("{cap}")[0]
|
||||
|
||||
|
||||
def _format_seconds(value: float) -> str:
|
||||
"""Render a duration with a correctly pluralized unit.
|
||||
|
||||
Args:
|
||||
value: The duration in seconds.
|
||||
|
||||
Returns:
|
||||
The duration and its unit, e.g. ``"1 second"`` or ``"300 seconds"``.
|
||||
"""
|
||||
return f"{value:g} second" if value == 1 else f"{value:g} seconds"
|
||||
|
||||
|
||||
def _build_description(max_seconds: float) -> str:
|
||||
"""Build the LLM-facing description, including the current per-call cap.
|
||||
|
||||
Args:
|
||||
max_seconds: The per-call cap advertised to the model.
|
||||
|
||||
Returns:
|
||||
The tool description shown to the model.
|
||||
"""
|
||||
return _DESCRIPTION_TEMPLATE.format(cap=_format_seconds(max_seconds))
|
||||
|
||||
|
||||
def _is_generated_description(description: str) -> bool:
|
||||
"""Report whether a description came from :func:`_build_description`.
|
||||
|
||||
Args:
|
||||
description: The description to inspect.
|
||||
|
||||
Returns:
|
||||
True if the text was generated rather than authored by the caller.
|
||||
"""
|
||||
return description.startswith(_GENERATED_DESCRIPTION_PREFIX)
|
||||
|
||||
|
||||
def _never_cache(_args: Any = None, _result: Any = None) -> bool:
|
||||
"""Refuse caching of wait results.
|
||||
|
||||
The value of a wait is the time that passed, not the message returned. A
|
||||
cached hit would hand back "Waited 300 seconds." without waiting, silently
|
||||
turning a poll-wait-check loop into a busy loop.
|
||||
|
||||
Args:
|
||||
_args: Unused, part of the ``cache_function`` signature.
|
||||
_result: Unused, part of the ``cache_function`` signature.
|
||||
|
||||
Returns:
|
||||
Always False.
|
||||
"""
|
||||
return False
|
||||
|
||||
|
||||
class WaitToolSchema(BaseModel):
|
||||
"""Input for WaitTool."""
|
||||
|
||||
seconds: float = Field(
|
||||
...,
|
||||
ge=0,
|
||||
description="How many seconds to wait before continuing.",
|
||||
)
|
||||
reason: str | None = Field(
|
||||
default=None,
|
||||
description="Optional short note on what is being waited for, echoed back in the result.",
|
||||
)
|
||||
|
||||
|
||||
class WaitTool(BaseTool):
|
||||
"""Pause execution so a long-running job elsewhere has time to progress.
|
||||
|
||||
Agents that kick off out-of-band work (a sandbox build, a deployment, an async
|
||||
API job) have no other way to let clock time pass: without this tool they either
|
||||
poll in a tight loop or give up before the work finishes.
|
||||
|
||||
A single call waits at most ``max_seconds``. Longer requests are clamped to that
|
||||
cap and the result says so, so the model can call again instead of failing.
|
||||
|
||||
The generated description advertises the cap to the model, and is kept in sync
|
||||
with ``max_seconds``. A description supplied by the caller is left alone.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
name: str = "Wait"
|
||||
description: str = _build_description(DEFAULT_MAX_SECONDS)
|
||||
args_schema: type[BaseModel] = WaitToolSchema
|
||||
max_seconds: float = Field(
|
||||
default=DEFAULT_MAX_SECONDS,
|
||||
gt=0,
|
||||
description="Upper bound, in seconds, for a single wait. Longer requests are capped to this value.",
|
||||
)
|
||||
cache_function: SerializableCallable = Field(
|
||||
default=_never_cache,
|
||||
description="Waits are never cached: a cache hit would return the message without any time passing.",
|
||||
)
|
||||
|
||||
def __init__(self, max_seconds: float | None = None, **kwargs: Any) -> None:
|
||||
if max_seconds is not None:
|
||||
kwargs["max_seconds"] = max_seconds
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _sync_description_with_cap(self) -> Self:
|
||||
"""Keep a generated description's advertised cap equal to ``max_seconds``.
|
||||
|
||||
Runs on construction, ``model_validate``, and assignment, so the cap the
|
||||
model is told about cannot drift from the one enforced. ``model_copy``
|
||||
skips validation, as it does for any pydantic model, so prefer
|
||||
construction or assignment when changing the cap.
|
||||
|
||||
Returns:
|
||||
The validated tool.
|
||||
"""
|
||||
expected = _build_description(self.max_seconds)
|
||||
if self.description != expected and _is_generated_description(self.description):
|
||||
# Bypass the field setter: assigning here would re-enter validation.
|
||||
self.__dict__["description"] = expected
|
||||
return self
|
||||
|
||||
def _resolve_duration(self, seconds: float) -> tuple[float, bool]:
|
||||
"""Validate and clamp the requested duration to ``max_seconds``.
|
||||
|
||||
``BaseTool.run`` skips ``args_schema`` validation when called with
|
||||
positional arguments, so the bounds are enforced here too rather than
|
||||
left to ``time.sleep`` to reject. Infinity is a valid request: it clamps
|
||||
to the cap like any other oversized wait.
|
||||
|
||||
Args:
|
||||
seconds: The requested wait duration.
|
||||
|
||||
Returns:
|
||||
A tuple of the duration to actually wait and whether it was capped.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``seconds`` is negative or not a number.
|
||||
"""
|
||||
if math.isnan(seconds):
|
||||
raise ValueError("seconds must be a number, got NaN.")
|
||||
if seconds < 0:
|
||||
raise ValueError(f"seconds must be zero or greater, got {seconds:g}.")
|
||||
if seconds > self.max_seconds:
|
||||
return self.max_seconds, True
|
||||
return seconds, False
|
||||
|
||||
def _format_result(
|
||||
self, waited: float, requested: float, reason: str | None
|
||||
) -> str:
|
||||
"""Describe the completed wait back to the model.
|
||||
|
||||
Args:
|
||||
waited: The duration actually waited.
|
||||
requested: The duration the model asked for.
|
||||
reason: Optional note on what is being waited for.
|
||||
|
||||
Returns:
|
||||
A summary of how long was waited and whether the request was capped.
|
||||
"""
|
||||
parts = [f"Waited {_format_seconds(waited)}."]
|
||||
if waited < requested:
|
||||
parts.append(
|
||||
f"Requested {_format_seconds(requested)}, capped at "
|
||||
f"{_format_seconds(self.max_seconds)} per call - "
|
||||
"call this tool again if more waiting is needed."
|
||||
)
|
||||
if reason:
|
||||
parts.append(f"Reason: {reason}")
|
||||
return " ".join(parts)
|
||||
|
||||
def _run(self, seconds: float, reason: str | None = None) -> str:
|
||||
"""Block for ``seconds``, capped at ``max_seconds``.
|
||||
|
||||
Args:
|
||||
seconds: How many seconds to wait.
|
||||
reason: Optional note on what is being waited for.
|
||||
|
||||
Returns:
|
||||
A summary of how long was waited and whether the request was capped.
|
||||
"""
|
||||
waited, _ = self._resolve_duration(seconds)
|
||||
time.sleep(waited)
|
||||
return self._format_result(waited, seconds, reason)
|
||||
|
||||
async def _arun(self, seconds: float, reason: str | None = None) -> str:
|
||||
"""Await for ``seconds``, capped at ``max_seconds``, without blocking the loop.
|
||||
|
||||
Args:
|
||||
seconds: How many seconds to wait.
|
||||
reason: Optional note on what is being waited for.
|
||||
|
||||
Returns:
|
||||
A summary of how long was waited and whether the request was capped.
|
||||
"""
|
||||
waited, _ = self._resolve_duration(seconds)
|
||||
await asyncio.sleep(waited)
|
||||
return self._format_result(waited, seconds, reason)
|
||||
181
lib/crewai-tools/tests/tools/wait_tool_test.py
Normal file
181
lib/crewai-tools/tests/tools/wait_tool_test.py
Normal file
@@ -0,0 +1,181 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from crewai_tools.tools.wait_tool import WaitTool
|
||||
from pydantic import ValidationError
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tool():
|
||||
return WaitTool()
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_waits_requested_duration(mock_sleep, tool):
|
||||
result = tool.run(seconds=2)
|
||||
|
||||
mock_sleep.assert_called_once_with(2)
|
||||
assert "Waited 2 seconds." in result
|
||||
assert "capped" not in result
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_caps_long_waits(mock_sleep, tool):
|
||||
result = tool.run(seconds=3600)
|
||||
|
||||
mock_sleep.assert_called_once_with(300)
|
||||
assert "Waited 300 seconds." in result
|
||||
assert "Requested 3600 seconds, capped at 300 seconds per call" in result
|
||||
assert "call this tool again" in result
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_custom_max_seconds(mock_sleep):
|
||||
tool = WaitTool(max_seconds=10)
|
||||
|
||||
result = tool.run(seconds=45)
|
||||
|
||||
mock_sleep.assert_called_once_with(10)
|
||||
assert "Waited 10 seconds." in result
|
||||
assert "10 seconds" in tool.description
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_reason_is_echoed_back(mock_sleep, tool):
|
||||
result = tool.run(seconds=1, reason="sandbox build running")
|
||||
|
||||
assert "Reason: sandbox build running" in result
|
||||
|
||||
|
||||
def test_zero_seconds_is_allowed(tool):
|
||||
assert "Waited 0 seconds." in tool.run(seconds=0)
|
||||
|
||||
|
||||
def test_negative_seconds_is_rejected(tool):
|
||||
with pytest.raises(ValueError, match="greater than or equal to 0"):
|
||||
tool.run(seconds=-5)
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_negative_seconds_is_rejected_when_passed_positionally(mock_sleep, tool):
|
||||
# BaseTool.run() skips args_schema validation for positional arguments.
|
||||
with pytest.raises(ValueError, match="seconds must be zero or greater"):
|
||||
tool.run(-5)
|
||||
|
||||
mock_sleep.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_negative_seconds_is_rejected_when_passed_positionally(tool):
|
||||
with patch(
|
||||
"crewai_tools.tools.wait_tool.wait_tool.asyncio.sleep", new_callable=AsyncMock
|
||||
) as mock_sleep:
|
||||
with pytest.raises(ValueError, match="seconds must be zero or greater"):
|
||||
await tool.arun(-5)
|
||||
|
||||
mock_sleep.assert_not_awaited()
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_nan_seconds_is_rejected_when_passed_positionally(mock_sleep, tool):
|
||||
with pytest.raises(ValueError, match="seconds must be a number"):
|
||||
tool.run(float("nan"))
|
||||
|
||||
mock_sleep.assert_not_called()
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_infinite_seconds_is_capped_like_any_other_long_wait(mock_sleep, tool):
|
||||
result = tool.run(float("inf"))
|
||||
|
||||
mock_sleep.assert_called_once_with(300)
|
||||
assert "Waited 300 seconds." in result
|
||||
|
||||
|
||||
@patch("crewai_tools.tools.wait_tool.wait_tool.time.sleep")
|
||||
def test_singular_second_is_not_pluralized(mock_sleep):
|
||||
tool = WaitTool(max_seconds=1)
|
||||
|
||||
assert "Waited 1 second." in tool.run(seconds=1)
|
||||
assert "capped at 1 second per call" in tool.run(seconds=5)
|
||||
assert "at most 1 second." in tool.description
|
||||
|
||||
|
||||
def test_invalid_max_seconds_is_rejected():
|
||||
with pytest.raises(ValidationError):
|
||||
WaitTool(max_seconds=0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_wait_caps_long_waits(tool):
|
||||
with patch(
|
||||
"crewai_tools.tools.wait_tool.wait_tool.asyncio.sleep", new_callable=AsyncMock
|
||||
) as mock_sleep:
|
||||
result = await tool.arun(seconds=3600, reason="deployment")
|
||||
|
||||
mock_sleep.assert_awaited_once_with(300)
|
||||
assert "Waited 300 seconds." in result
|
||||
assert "Reason: deployment" in result
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"build",
|
||||
[
|
||||
pytest.param(lambda d: WaitTool(max_seconds=10), id="init"),
|
||||
pytest.param(lambda d: WaitTool(10), id="init_positional"),
|
||||
pytest.param(lambda d: WaitTool(max_seconds=10, description=d), id="init_desc"),
|
||||
pytest.param(
|
||||
lambda d: WaitTool.model_validate({"max_seconds": 10, "description": d}),
|
||||
id="model_validate",
|
||||
),
|
||||
pytest.param(
|
||||
lambda d: WaitTool.model_validate(WaitTool(max_seconds=10).model_dump()),
|
||||
id="round_trip",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_advertised_cap_matches_enforced_cap(build):
|
||||
tool = build(WaitTool().description)
|
||||
|
||||
assert tool.max_seconds == 10
|
||||
assert "at most 10 seconds" in tool.description
|
||||
assert "300 seconds" not in tool.description
|
||||
|
||||
|
||||
def test_advertised_cap_follows_assignment():
|
||||
tool = WaitTool()
|
||||
tool.max_seconds = 10
|
||||
|
||||
assert "at most 10 seconds" in tool.description
|
||||
|
||||
|
||||
def test_caller_supplied_description_is_left_alone():
|
||||
tool = WaitTool(max_seconds=10, description="Hold on for a bit.")
|
||||
|
||||
assert tool.description == "Hold on for a bit."
|
||||
|
||||
|
||||
def test_waits_are_never_cached():
|
||||
# A cache hit would hand back "Waited N seconds." without any time passing,
|
||||
# turning a poll-wait-check loop into a busy loop.
|
||||
tool = WaitTool()
|
||||
|
||||
assert tool.cache_function("{}", "Waited 1 second.") is False
|
||||
assert WaitTool.model_validate(tool.model_dump()).cache_function() is False
|
||||
|
||||
|
||||
def test_description_explains_when_to_use_it(tool):
|
||||
description = tool.description.lower()
|
||||
|
||||
assert "sandbox" in description
|
||||
assert "deployment" in description
|
||||
assert "300 seconds" in description
|
||||
assert "call this tool again" in description
|
||||
|
||||
|
||||
def test_exported_from_package():
|
||||
from crewai_tools import WaitTool as ExportedWaitTool
|
||||
from crewai_tools.tools import WaitTool as ToolsExportedWaitTool
|
||||
|
||||
assert ExportedWaitTool is WaitTool
|
||||
assert ToolsExportedWaitTool is WaitTool
|
||||
@@ -25793,6 +25793,94 @@
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "Pause and do nothing for a set number of seconds before continuing.\nUse this when work that was already started somewhere else needs real time to finish before its status or result can be checked again, for example: a sandbox build, test run, or script that is still executing; a deployment or provisioning step that is still rolling out; a batch import, export, or training job; an async API that returned a job id to poll later; or a rate limit or backoff that has to cool down before retrying.\nThe usual pattern is: start the job, wait, check its status, and wait again if it is still running.\nDo not use this to pace a conversation, to pretend to work, or when the information needed is already available. Waiting only lets clock time pass, it does not advance or check the job.\nA single call waits at most 300 seconds. If more time is needed, call this tool again.",
|
||||
"env_vars": [],
|
||||
"humanized_name": "Wait",
|
||||
"init_params_schema": {
|
||||
"$defs": {
|
||||
"EnvVar": {
|
||||
"properties": {
|
||||
"default": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"default": null,
|
||||
"title": "Default"
|
||||
},
|
||||
"description": {
|
||||
"title": "Description",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
},
|
||||
"required": {
|
||||
"default": true,
|
||||
"title": "Required",
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"description"
|
||||
],
|
||||
"title": "EnvVar",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"description": "Pause execution so a long-running job elsewhere has time to progress.\n\nAgents that kick off out-of-band work (a sandbox build, a deployment, an async\nAPI job) have no other way to let clock time pass: without this tool they either\npoll in a tight loop or give up before the work finishes.\n\nA single call waits at most ``max_seconds``. Longer requests are clamped to that\ncap and the result says so, so the model can call again instead of failing.\n\nThe generated description advertises the cap to the model, and is kept in sync\nwith ``max_seconds``. A description supplied by the caller is left alone.",
|
||||
"properties": {
|
||||
"max_seconds": {
|
||||
"default": 300.0,
|
||||
"description": "Upper bound, in seconds, for a single wait. Longer requests are capped to this value.",
|
||||
"exclusiveMinimum": 0,
|
||||
"title": "Max Seconds",
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [],
|
||||
"title": "WaitTool",
|
||||
"type": "object"
|
||||
},
|
||||
"name": "WaitTool",
|
||||
"package_dependencies": [],
|
||||
"run_params_schema": {
|
||||
"description": "Input for WaitTool.",
|
||||
"properties": {
|
||||
"reason": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"default": null,
|
||||
"description": "Optional short note on what is being waited for, echoed back in the result.",
|
||||
"title": "Reason"
|
||||
},
|
||||
"seconds": {
|
||||
"description": "How many seconds to wait before continuing.",
|
||||
"minimum": 0,
|
||||
"title": "Seconds",
|
||||
"type": "number"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"seconds"
|
||||
],
|
||||
"title": "WaitToolSchema",
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"description": "A tool to search the Weaviate database for relevant information on internal documents.",
|
||||
"env_vars": [
|
||||
|
||||
Reference in New Issue
Block a user