mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-07-14 11:25:09 +00:00
Compare commits
11 Commits
docs/deplo
...
luzk/fix-p
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
782b623a4d | ||
|
|
9d72e269e4 | ||
|
|
fb8e93be25 | ||
|
|
4fdb7f2bfb | ||
|
|
bfa652a7be | ||
|
|
b65c8487d2 | ||
|
|
a8b3ecb723 | ||
|
|
7967b19057 | ||
|
|
85c467dfe2 | ||
|
|
7baf8f9ba1 | ||
|
|
860817cbcd |
6
.github/workflows/vulnerability-scan.yml
vendored
6
.github/workflows/vulnerability-scan.yml
vendored
@@ -74,7 +74,8 @@ jobs:
|
||||
--ignore-vuln PYSEC-2025-217 \
|
||||
--ignore-vuln PYSEC-2025-218 \
|
||||
--ignore-vuln PYSEC-2026-597 \
|
||||
--ignore-vuln GHSA-f4j7-r4q5-qw2c
|
||||
--ignore-vuln GHSA-f4j7-r4q5-qw2c \
|
||||
--ignore-vuln GHSA-xf7x-x43h-rpqh
|
||||
# Ignored CVEs:
|
||||
# PYSEC-2024-277 - joblib 1.5.3: disputed; NumpyArrayWrapper only used with trusted caches
|
||||
# PYSEC-2026-89 - markdown 3.10.2: DoS via malformed HTML; fix 3.8.1 — already past, advisory range is stale
|
||||
@@ -89,6 +90,9 @@ jobs:
|
||||
# GHSA-f4j7-r4q5-qw2c - chromadb 1.1.1 (CVE-2026-45829): pre-auth RCE via /api/v2/tenants/{tenant}/databases/{db}/collections when trust_remote_code=true.
|
||||
# Advisory: vulnerable >=1.0.0,<=1.5.9, firstPatchedVersion=none. We only use chromadb.PersistentClient (lib/crewai/src/crewai/rag/chromadb/factory.py)
|
||||
# and chromadb.utils.embedding_functions; the chromadb HTTP server is never started, so the vulnerable route is not exposed.
|
||||
# GHSA-xf7x-x43h-rpqh - json-repair 0.25.3 (published 2026-07-13): CPU DoS via circular $ref in SchemaRepairer.resolve_schema().
|
||||
# The vulnerable schema_repair module does not exist in 0.25.x (added in later releases), and CrewAI only calls
|
||||
# repair_json() without schemas. The fixed release 0.60.1 is outside the json-repair~=0.25.2 pin.
|
||||
continue-on-error: true
|
||||
|
||||
- name: Display results
|
||||
|
||||
@@ -144,6 +144,18 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
)
|
||||
```
|
||||
|
||||
**Custom OpenAI-Compatible Endpoint:**
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
base_url="https://your-gateway.example.com/v1",
|
||||
api_key="your-gateway-api-key",
|
||||
)
|
||||
```
|
||||
|
||||
**Advanced Configuration:**
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
@@ -240,14 +240,15 @@ from crewai import LLM
|
||||
|
||||
# After (OpenAI-compatible mode, no LiteLLM needed):
|
||||
llm = LLM(
|
||||
model="openai/llama3",
|
||||
model="llama3",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama" # Ollama doesn't require a real API key
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Many local inference servers (Ollama, vLLM, LM Studio, llama.cpp) expose an OpenAI-compatible API. You can use the `openai/` prefix with a custom `base_url` to connect to any of them natively.
|
||||
Many local inference servers (Ollama, vLLM, LM Studio, llama.cpp) expose an OpenAI-compatible API. You can use `custom_openai=True` with a custom `base_url` to connect to any of them natively while keeping the model ID your gateway expects.
|
||||
</Tip>
|
||||
|
||||
### Step 4: Update your YAML configs
|
||||
@@ -295,6 +296,92 @@ crewai run
|
||||
uv run pytest
|
||||
```
|
||||
|
||||
## Custom OpenAI-Compatible Endpoints
|
||||
|
||||
Many providers and local servers (Ollama, vLLM, LM Studio, llama.cpp, LiteLLM proxies, and hosted gateways) expose an **OpenAI-compatible** API. Instead of routing these through LiteLLM, you can talk to them directly with CrewAI's native OpenAI integration by setting `custom_openai=True`.
|
||||
|
||||
This is the recommended replacement for any LiteLLM provider that offers an OpenAI-compatible endpoint.
|
||||
|
||||
### How it works
|
||||
|
||||
- `custom_openai=True` forces CrewAI to use the native OpenAI SDK, regardless of the model name.
|
||||
- The model ID is passed to the endpoint without validation against OpenAI's known-model list. This lets you use arbitrary model IDs your gateway expects (for example, `anthropic/claude-sonnet-4-6` served behind an OpenAI-compatible proxy). An optional leading `openai/` routing prefix is stripped.
|
||||
- A base URL is **required**. CrewAI resolves it, in order, from:
|
||||
1. `base_url=...`
|
||||
2. `api_base=...`
|
||||
3. `OPENAI_BASE_URL` environment variable
|
||||
4. `OPENAI_API_BASE` environment variable (legacy)
|
||||
|
||||
If none are set, CrewAI raises a `ValueError` so misconfiguration fails fast instead of silently hitting `api.openai.com`.
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4-6", # passed through as-is
|
||||
custom_openai=True,
|
||||
base_url="https://your-gateway.example/v1",
|
||||
api_key="your-key",
|
||||
)
|
||||
```
|
||||
|
||||
### Connect to common servers
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Ollama">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="llama3.2:latest",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama", # Ollama ignores it, but the client requires a value
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="vLLM">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:8000/v1",
|
||||
api_key="not-needed",
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="LM Studio">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="your-loaded-model",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:1234/v1",
|
||||
api_key="lm-studio",
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Env vars">
|
||||
```bash
|
||||
export OPENAI_BASE_URL="https://your-gateway.example/v1"
|
||||
export OPENAI_API_KEY="your-key"
|
||||
```
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# base_url is picked up from OPENAI_BASE_URL / OPENAI_API_BASE
|
||||
llm = LLM(model="anthropic/claude-sonnet-4-6", custom_openai=True)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Tip>
|
||||
If you use the `openai/` prefix with a model that isn't a known OpenAI model and pass `base_url` or `api_base` directly, CrewAI automatically treats it as a custom OpenAI-compatible endpoint. Environment variables alone do not enable automatic routing for unknown models; set `custom_openai=True` when configuring the endpoint through `OPENAI_BASE_URL` or `OPENAI_API_BASE`.
|
||||
</Tip>
|
||||
|
||||
## Quick Reference: Model String Mapping
|
||||
|
||||
Here are common migration paths from LiteLLM-dependent providers to native ones:
|
||||
@@ -321,7 +408,8 @@ llm = LLM(model="anthropic/claude-sonnet-4-20250514") # High quality
|
||||
# Ollama → OpenAI-compatible (keep using local models)
|
||||
# llm = LLM(model="ollama/llama3")
|
||||
llm = LLM(
|
||||
model="openai/llama3",
|
||||
model="llama3",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama"
|
||||
)
|
||||
@@ -349,6 +437,9 @@ llm = LLM(
|
||||
<Accordion title="What about environment variables like OPENAI_API_KEY?">
|
||||
Native providers use the same environment variables you're already familiar with. No changes needed for `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, etc.
|
||||
</Accordion>
|
||||
<Accordion title="How do I connect to Groq, Together AI, or other OpenAI-compatible providers without LiteLLM?">
|
||||
Most of these providers expose an OpenAI-compatible API. Use `custom_openai=True` with their base URL and API key — see [Custom OpenAI-Compatible Endpoints](#custom-openai-compatible-endpoints). For example, Groq: `LLM(model="llama-3.1-70b-versatile", custom_openai=True, base_url="https://api.groq.com/openai/v1", api_key="...")`. The model ID is passed through untouched, so use whatever ID the provider expects.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Related Resources
|
||||
|
||||
@@ -568,12 +568,32 @@ FooterKey .footer-key--key {
|
||||
self._default_inputs: dict[str, Any] | None = None
|
||||
self._crew_result: Any = None
|
||||
self._crew_json_path: Any = None
|
||||
# Declarative-flow execution state. A flow renders per-method "STEPS"
|
||||
# (built from flow method events) instead of the crew task list.
|
||||
self._flow_inputs: dict[str, Any] | None = None
|
||||
self._flow_method_types: dict[str, str] = {}
|
||||
self._flow_steps: list[dict[str, Any]] = []
|
||||
self._current_method: str | None = None
|
||||
self._elapsed_frozen: float | None = None
|
||||
self._want_deploy: bool = False
|
||||
self._trace_url: str | None = None
|
||||
self._consent_screen: TraceConsentScreen | None = None
|
||||
self._telemetry: Telemetry | None = None
|
||||
|
||||
@property
|
||||
def _is_flow_run(self) -> bool:
|
||||
"""True for a non-conversational declarative flow (the STEPS view).
|
||||
|
||||
Gates every flow-specific rendering branch so crew and conversational
|
||||
paths stay byte-identical.
|
||||
"""
|
||||
return self._flow is not None and not self._is_conversational
|
||||
|
||||
@property
|
||||
def _run_noun(self) -> str:
|
||||
"""User-facing noun for the run — 'flow' for a declarative flow, else 'crew'."""
|
||||
return "flow" if self._is_flow_run else "crew"
|
||||
|
||||
# ── Layout ──────────────────────────────────────────────
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
@@ -602,6 +622,8 @@ FooterKey .footer-key--key {
|
||||
self._tick_timer = self.set_interval(1 / 8, self._tick)
|
||||
if self._is_conversational and self._flow:
|
||||
self._start_conversational_session()
|
||||
elif self._flow:
|
||||
self._run_flow_worker()
|
||||
elif self._crew:
|
||||
self._run_crew_worker()
|
||||
elif self._crew_json_path:
|
||||
@@ -681,6 +703,49 @@ FooterKey .footer-key--key {
|
||||
except Exception as e:
|
||||
self.call_from_thread(self._on_crew_failed, str(e))
|
||||
|
||||
@work(thread=True, exclusive=True, group="flow")
|
||||
def _run_flow_worker(self) -> None:
|
||||
from crewai.events.listeners.tracing.utils import (
|
||||
set_suppress_tracing_messages,
|
||||
set_tui_mode,
|
||||
)
|
||||
|
||||
set_tui_mode(True)
|
||||
set_suppress_tracing_messages(True)
|
||||
try:
|
||||
# A declarative flow returns either a CrewOutput (has ``.raw``) or a
|
||||
# bare value (str/dict/pydantic); _stringify_output handles both.
|
||||
result = self._flow.kickoff(inputs=self._flow_inputs)
|
||||
output = self._stringify_output(result)
|
||||
with self._lock:
|
||||
self._crew_result = result
|
||||
self.call_from_thread(self._on_crew_done, output)
|
||||
except Exception as e:
|
||||
self.call_from_thread(self._on_crew_failed, str(e))
|
||||
|
||||
def _set_flow_step_status(self, name: str, status: str) -> None:
|
||||
"""Update a flow method step's status. Caller must hold ``self._lock``."""
|
||||
for step in self._flow_steps:
|
||||
if step["name"] == name:
|
||||
step["status"] = status
|
||||
return
|
||||
|
||||
def _clear_current_method(self, finished_name: str) -> None:
|
||||
"""Drop the header's active method once it ends. Caller holds the lock.
|
||||
|
||||
Falls back to another still-active step (methods can overlap) so the
|
||||
header never keeps spinning a method the STEPS list already shows as
|
||||
done or failed.
|
||||
"""
|
||||
if self._current_method != finished_name:
|
||||
return
|
||||
self._current_method = next(
|
||||
(s["name"] for s in self._flow_steps if s["status"] == "active"), None
|
||||
)
|
||||
# The active method changed; drop its agent so the header doesn't show a
|
||||
# stale agent until the next method's agent event arrives.
|
||||
self._current_agent = ""
|
||||
|
||||
def _on_crew_done(self, output: str | None) -> None:
|
||||
with self._lock:
|
||||
self._status = "completed"
|
||||
@@ -694,13 +759,18 @@ FooterKey .footer-key--key {
|
||||
for k in self._task_statuses:
|
||||
if self._task_statuses[k] == "active":
|
||||
self._task_statuses[k] = "done"
|
||||
for step in self._flow_steps:
|
||||
if step["status"] == "active":
|
||||
step["status"] = "done"
|
||||
now = time.time()
|
||||
for entry in self._log_entries:
|
||||
if entry["status"] == "running":
|
||||
if entry["tool_name"] == "memory_save":
|
||||
continue
|
||||
entry["status"] = "timeout"
|
||||
entry["error"] = "No result received before crew completed"
|
||||
entry["error"] = (
|
||||
f"No result received before {self._run_noun} completed"
|
||||
)
|
||||
entry["duration"] = now - entry["start_time"]
|
||||
try:
|
||||
from crewai.events.listeners.tracing.trace_listener import (
|
||||
@@ -739,13 +809,18 @@ FooterKey .footer-key--key {
|
||||
self._is_streaming = False
|
||||
self._current_step = None
|
||||
self._elapsed_frozen = time.time() - self._start_time
|
||||
for step in self._flow_steps:
|
||||
if step["status"] == "active":
|
||||
step["status"] = "failed"
|
||||
now = time.time()
|
||||
for entry in self._log_entries:
|
||||
if entry["status"] == "running":
|
||||
if entry["tool_name"] == "memory_save":
|
||||
continue
|
||||
entry["status"] = "error"
|
||||
entry["error"] = "No result received before crew failed"
|
||||
entry["error"] = (
|
||||
f"No result received before {self._run_noun} failed"
|
||||
)
|
||||
entry["duration"] = now - entry["start_time"]
|
||||
self._tick()
|
||||
self.call_later(self._focus_activity_log)
|
||||
@@ -1156,6 +1231,45 @@ FooterKey .footer-key--key {
|
||||
widget.update(t)
|
||||
return
|
||||
|
||||
if self._is_flow_run:
|
||||
t.append(" STEPS\n", style=f"bold {_C_PRIMARY}")
|
||||
t.append("\n")
|
||||
if not self._flow_steps:
|
||||
t.append(" ○ waiting…\n", style=_C_DIM)
|
||||
for step in self._flow_steps:
|
||||
name = step["name"]
|
||||
max_name = sidebar_width - 6
|
||||
if len(name) > max_name:
|
||||
name = name[: max_name - 1] + "…"
|
||||
status = step.get("status", "pending")
|
||||
if status == "done":
|
||||
t.append(" ✔ ", style=_C_GREEN)
|
||||
t.append(name, style=_C_DIM)
|
||||
elif status == "active":
|
||||
t.append(f" {self._spinner()} ", style=_C_PRIMARY)
|
||||
t.append(name, style=f"bold {_C_TEXT}")
|
||||
elif status == "failed":
|
||||
t.append(" ✘ ", style=_C_RED)
|
||||
t.append(name, style=_C_RED)
|
||||
elif status == "paused":
|
||||
t.append(" ⏸ ", style=_C_TEAL)
|
||||
t.append(name, style=_C_TEAL)
|
||||
else:
|
||||
t.append(" ○ ", style=_C_DIM)
|
||||
t.append(name, style=_C_DIM)
|
||||
if step.get("call_type"):
|
||||
t.append(f" ({step['call_type']})", style=_C_DIM)
|
||||
t.append("\n")
|
||||
|
||||
t.append("\n")
|
||||
t.append(" TOKENS\n", style=f"bold {_C_PRIMARY}")
|
||||
t.append("\n")
|
||||
out = self._output_tokens + self._live_out_tokens
|
||||
t.append(f" ↑ {self._input_tokens:,}\n", style=_C_DIM)
|
||||
t.append(f" ↓ {out:,}\n", style=_C_DIM)
|
||||
widget.update(t)
|
||||
return
|
||||
|
||||
t.append(" TASKS\n", style=f"bold {_C_PRIMARY}")
|
||||
t.append("\n")
|
||||
|
||||
@@ -1225,6 +1339,55 @@ FooterKey .footer-key--key {
|
||||
widget.update(t)
|
||||
return
|
||||
|
||||
if self._is_flow_run:
|
||||
if self._status == "completed":
|
||||
elapsed = self._elapsed_frozen or (time.time() - self._start_time)
|
||||
t.append("✔ ", style=f"bold {_C_GREEN}")
|
||||
t.append("Flow complete", style=f"bold {_C_GREEN}")
|
||||
t.append(f" {elapsed:.1f}s", style=_C_DIM)
|
||||
out = self._output_tokens + self._live_out_tokens
|
||||
parts = []
|
||||
if self._input_tokens:
|
||||
parts.append(f"↑{self._input_tokens:,}")
|
||||
if out:
|
||||
parts.append(f"↓{out:,}")
|
||||
if parts:
|
||||
t.append(f" {' '.join(parts)} tokens", style=_C_DIM)
|
||||
elif self._status == "failed":
|
||||
t.append("✘ ", style=f"bold {_C_RED}")
|
||||
t.append("Failed", style=f"bold {_C_RED}")
|
||||
if self._error:
|
||||
t.append(f"\n{self._error[:120]}", style=_C_RED)
|
||||
elif self._current_method:
|
||||
paused = any(
|
||||
s["name"] == self._current_method and s["status"] == "paused"
|
||||
for s in self._flow_steps
|
||||
)
|
||||
if paused:
|
||||
t.append("⏸ ", style=_C_TEAL)
|
||||
t.append(self._current_method, style=f"bold {_C_TEAL}")
|
||||
else:
|
||||
t.append(f"{self._spinner()} ", style=_C_PRIMARY)
|
||||
t.append(self._current_method, style=f"bold {_C_PRIMARY}")
|
||||
call_type = self._flow_method_types.get(self._current_method)
|
||||
if call_type:
|
||||
t.append(f" ({call_type})", style=_C_DIM)
|
||||
if paused:
|
||||
t.append(" waiting for feedback", style=_C_DIM)
|
||||
elif self._current_agent:
|
||||
t.append("\nAgent: ", style=_C_DIM)
|
||||
t.append(self._current_agent, style=f"bold {_C_TEXT}")
|
||||
else:
|
||||
t.append(f"{self._spinner()} ", style=_C_PRIMARY)
|
||||
# "Working…" once a step has run (between/after methods);
|
||||
# "Starting flow…" only before the first method.
|
||||
t.append(
|
||||
"Working…" if self._flow_steps else "Starting flow…",
|
||||
style=_C_DIM,
|
||||
)
|
||||
widget.update(t)
|
||||
return
|
||||
|
||||
if self._status == "completed":
|
||||
elapsed = self._elapsed_frozen or (time.time() - self._start_time)
|
||||
t.append("✔ ", style=f"bold {_C_GREEN}")
|
||||
@@ -1839,6 +2002,13 @@ FooterKey .footer-key--key {
|
||||
def _subscribe(self) -> None:
|
||||
from crewai.events.event_bus import crewai_event_bus
|
||||
from crewai.events.types.crew_events import CrewKickoffStartedEvent
|
||||
from crewai.events.types.flow_events import (
|
||||
FlowStartedEvent,
|
||||
MethodExecutionFailedEvent,
|
||||
MethodExecutionFinishedEvent,
|
||||
MethodExecutionPausedEvent,
|
||||
MethodExecutionStartedEvent,
|
||||
)
|
||||
from crewai.events.types.llm_events import (
|
||||
LLMCallCompletedEvent,
|
||||
LLMCallStartedEvent,
|
||||
@@ -1872,13 +2042,74 @@ FooterKey .footer-key--key {
|
||||
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
||||
def on_crew_started(source: Any, event: CrewKickoffStartedEvent) -> None:
|
||||
with self._lock:
|
||||
if event.crew_name:
|
||||
# In flow mode the app is named for the flow; a nested crew's
|
||||
# kickoff (a `call: crew` step) must not rename it.
|
||||
if event.crew_name and not self._is_flow_run:
|
||||
self._crew_name = event.crew_name
|
||||
self.title = f"CrewAI — {event.crew_name}"
|
||||
self._status = "working"
|
||||
|
||||
self._register_handler(CrewKickoffStartedEvent, on_crew_started)
|
||||
|
||||
# ── Declarative-flow method events → STEPS panel ────────
|
||||
@crewai_event_bus.on(FlowStartedEvent)
|
||||
def on_flow_started(source: Any, event: FlowStartedEvent) -> None:
|
||||
with self._lock:
|
||||
self._status = "working"
|
||||
|
||||
self._register_handler(FlowStartedEvent, on_flow_started)
|
||||
|
||||
@crewai_event_bus.on(MethodExecutionStartedEvent)
|
||||
def on_method_started(source: Any, event: MethodExecutionStartedEvent) -> None:
|
||||
with self._lock:
|
||||
name = event.method_name
|
||||
self._current_method = name
|
||||
# Agent is per-method; clear it so the header doesn't show the
|
||||
# previous method's agent until a new agent event arrives.
|
||||
self._current_agent = ""
|
||||
for step in self._flow_steps:
|
||||
if step["name"] == name:
|
||||
step["status"] = "active"
|
||||
break
|
||||
else:
|
||||
self._flow_steps.append(
|
||||
{
|
||||
"name": name,
|
||||
"call_type": self._flow_method_types.get(name),
|
||||
"status": "active",
|
||||
}
|
||||
)
|
||||
|
||||
self._register_handler(MethodExecutionStartedEvent, on_method_started)
|
||||
|
||||
@crewai_event_bus.on(MethodExecutionFinishedEvent)
|
||||
def on_method_finished(
|
||||
source: Any, event: MethodExecutionFinishedEvent
|
||||
) -> None:
|
||||
with self._lock:
|
||||
self._set_flow_step_status(event.method_name, "done")
|
||||
self._clear_current_method(event.method_name)
|
||||
|
||||
self._register_handler(MethodExecutionFinishedEvent, on_method_finished)
|
||||
|
||||
@crewai_event_bus.on(MethodExecutionFailedEvent)
|
||||
def on_method_failed(source: Any, event: MethodExecutionFailedEvent) -> None:
|
||||
with self._lock:
|
||||
self._set_flow_step_status(event.method_name, "failed")
|
||||
self._clear_current_method(event.method_name)
|
||||
|
||||
self._register_handler(MethodExecutionFailedEvent, on_method_failed)
|
||||
|
||||
@crewai_event_bus.on(MethodExecutionPausedEvent)
|
||||
def on_method_paused(source: Any, event: MethodExecutionPausedEvent) -> None:
|
||||
# A @human_feedback method paused; flow status panels are suppressed
|
||||
# in TUI mode, so surface the wait in STEPS/header instead of leaving
|
||||
# a spinner. _current_method stays pointed at it.
|
||||
with self._lock:
|
||||
self._set_flow_step_status(event.method_name, "paused")
|
||||
|
||||
self._register_handler(MethodExecutionPausedEvent, on_method_paused)
|
||||
|
||||
@crewai_event_bus.on(TaskStartedEvent)
|
||||
def on_task_started(source: Any, event: TaskStartedEvent) -> None:
|
||||
with self._lock:
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import click
|
||||
from crewai_core.project import ProjectDefinitionError, configured_project_definition
|
||||
@@ -18,6 +19,13 @@ from crewai_cli.input_prompt import (
|
||||
from crewai_cli.utils import build_env_with_all_tool_credentials
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crewai.flow.flow import Flow
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def run_declarative_flow_in_project_env(
|
||||
definition: str | Path, inputs: str | None = None
|
||||
) -> None:
|
||||
@@ -66,17 +74,182 @@ def run_declarative_flow(definition: str | Path, inputs: str | None = None) -> N
|
||||
flow = load_declarative_flow(definition)
|
||||
resolved_inputs = _resolve_flow_inputs(flow, provided)
|
||||
|
||||
# The TUI is the interactive default. Headless contexts run directly on the
|
||||
# terminal: deploy/CREWAI_DMN, piped output, CI — anything without an
|
||||
# interactive TTY. is_interactive() already folds in the CREWAI_DMN check.
|
||||
# Human-feedback flows also run on the terminal: their methods collect input
|
||||
# via the flow runtime's blocking input()/Rich prompts (and async feedback
|
||||
# returns a pending marker rather than completing), neither of which the
|
||||
# Textual TUI can handle correctly.
|
||||
if is_interactive() and not _flow_uses_human_feedback(flow):
|
||||
_run_declarative_flow_tui(flow, resolved_inputs or None)
|
||||
return
|
||||
|
||||
try:
|
||||
result = flow.kickoff(inputs=resolved_inputs or None)
|
||||
except Exception as exc:
|
||||
click.echo(
|
||||
f"An error occurred while running the declarative flow: {exc}", err=True
|
||||
f"An error occurred while running the declarative flow: {exc}",
|
||||
err=True,
|
||||
)
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
click.echo(_format_result(result))
|
||||
|
||||
|
||||
def _run_declarative_flow_tui(
|
||||
flow: Flow[Any], resolved_inputs: dict[str, Any] | None
|
||||
) -> Any:
|
||||
"""Run a declarative flow on the CrewAI TUI (the interactive default).
|
||||
|
||||
Mirrors the declarative-crew TUI contract (``run_crew._run_json_crew``):
|
||||
a failed flow exits non-zero, a user quit ends the process so in-flight LLM
|
||||
work stops, and choosing Deploy chains into the deploy command.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
from crewai.events.event_listener import EventListener
|
||||
|
||||
from crewai_cli.crew_run_tui import CrewRunApp
|
||||
|
||||
# The flow runtime (unlike a Crew constructor) doesn't create the event
|
||||
# listener, and the TUI's trace/telemetry features depend on it.
|
||||
EventListener()
|
||||
|
||||
# The STEPS panel and header are driven by flow method events. A flow may
|
||||
# declare ``config.suppress_flow_events`` (a headless/production
|
||||
# optimization) which would leave STEPS stuck on "waiting…" here — so force
|
||||
# emission on for the interactive TUI run. The headless path never reaches
|
||||
# this and keeps the flow's declared setting.
|
||||
try:
|
||||
flow.suppress_flow_events = False
|
||||
except Exception:
|
||||
logger.debug(
|
||||
"Could not disable suppress_flow_events for the flow TUI", exc_info=True
|
||||
)
|
||||
|
||||
app = CrewRunApp(crew_name=flow.name or type(flow).__name__)
|
||||
app._flow = flow
|
||||
app._flow_inputs = resolved_inputs
|
||||
app._flow_method_types = _flow_method_types(flow)
|
||||
|
||||
app.run()
|
||||
|
||||
_print_flow_post_tui_summary(app)
|
||||
|
||||
if app._status == "failed":
|
||||
raise SystemExit(1)
|
||||
|
||||
if app._status not in ("completed", "failed"):
|
||||
# User quit mid-run. kickoff runs in a thread worker that cannot be
|
||||
# force-cancelled, so end the process to stop in-flight LLM and tool
|
||||
# work instead of letting it burn tokens in the background.
|
||||
click.secho("\n Run cancelled.", fg="yellow")
|
||||
sys.stdout.flush()
|
||||
os._exit(130)
|
||||
|
||||
if getattr(app, "_want_deploy", False):
|
||||
from crewai_cli.run_crew import _chain_deploy
|
||||
|
||||
_chain_deploy()
|
||||
|
||||
return app._crew_result
|
||||
|
||||
|
||||
def _flow_uses_human_feedback(flow: Flow[Any]) -> bool:
|
||||
"""True if any declarative method declares ``@human_feedback``.
|
||||
|
||||
Such flows need the flow runtime's interactive stdin / Rich prompts, which
|
||||
don't compose with Textual — so they run on the terminal, not the TUI.
|
||||
"""
|
||||
try:
|
||||
return any(
|
||||
method.human_feedback is not None
|
||||
for method in flow._definition.methods.values()
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Could not inspect flow for human feedback", exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def _flow_method_types(flow: Flow[Any]) -> dict[str, str]:
|
||||
"""Map each declarative method name to its ``call`` type (crew/agent/…).
|
||||
|
||||
Best-effort: the STEPS panel shows this as a dim label. Method events don't
|
||||
carry the call type, so it's read from the flow definition up front.
|
||||
"""
|
||||
method_types: dict[str, str] = {}
|
||||
try:
|
||||
for name, method_definition in flow._definition.methods.items():
|
||||
method_types[name] = method_definition.do.call
|
||||
except Exception:
|
||||
logger.debug("Could not derive flow method types", exc_info=True)
|
||||
return method_types
|
||||
|
||||
|
||||
def _print_flow_post_tui_summary(app: Any) -> None:
|
||||
"""Print a compact result panel after the flow TUI exits."""
|
||||
import time
|
||||
|
||||
from rich.console import Console
|
||||
from rich.markdown import Markdown
|
||||
from rich.padding import Padding
|
||||
from rich.panel import Panel
|
||||
from rich.text import Text
|
||||
|
||||
console = Console()
|
||||
elapsed = (app._elapsed_frozen or (time.time() - app._start_time)) or 0.0
|
||||
|
||||
out_tokens = app._output_tokens + app._live_out_tokens
|
||||
token_parts = []
|
||||
if app._input_tokens:
|
||||
token_parts.append(f"↑{app._input_tokens:,}")
|
||||
if out_tokens:
|
||||
token_parts.append(f"↓{out_tokens:,}")
|
||||
token_str = " ".join(token_parts)
|
||||
if token_str:
|
||||
token_str += " tokens"
|
||||
|
||||
crewai_red = "#FF5A50"
|
||||
crewai_teal = "#1F7982"
|
||||
|
||||
if app._status == "completed":
|
||||
summary = Text()
|
||||
summary.append(" ✔ Flow complete", style=f"bold {crewai_teal}")
|
||||
summary.append(f" in {elapsed:.1f}s", style="dim")
|
||||
if token_str:
|
||||
summary.append(f" {token_str}", style="dim")
|
||||
console.print(
|
||||
Panel(
|
||||
summary,
|
||||
title=f" {app._crew_name} ",
|
||||
title_align="left",
|
||||
border_style=crewai_teal,
|
||||
padding=(0, 1),
|
||||
)
|
||||
)
|
||||
if app._final_output:
|
||||
console.print()
|
||||
console.print(Text(" Final Result", style=f"bold {crewai_teal}"))
|
||||
console.print()
|
||||
console.print(Padding(Markdown(app._final_output), (0, 2)))
|
||||
elif app._status == "failed":
|
||||
content = Text()
|
||||
content.append(" ✘ Failed", style=f"bold {crewai_red}")
|
||||
content.append(f" after {elapsed:.1f}s\n", style="dim")
|
||||
if app._error:
|
||||
content.append(f"\n {app._error}\n", style=crewai_red)
|
||||
console.print(
|
||||
Panel(
|
||||
content,
|
||||
title=f" {app._crew_name} ",
|
||||
title_align="left",
|
||||
border_style=crewai_red,
|
||||
padding=(0, 1),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _resolve_flow_inputs(flow: Any, provided: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Resolve kickoff inputs from the flow's state schema.
|
||||
|
||||
|
||||
@@ -59,9 +59,9 @@ Use these expression forms correctly:
|
||||
- Raw CEL: use in `expr`. Do not wrap raw CEL in `${...}`.
|
||||
- Use `${...}` inside action mapping strings to read Flow data with CEL. Example value: `Ticket: ${state.ticket_id}`.
|
||||
- Use `state` for input data. Use `outputs.step_name` for a completed method result.
|
||||
- In action mapping strings, keep literal text outside `${...}` and interpolate each Flow value directly. Write `Ticket: ${state.ticket_id}`; do not assemble the string with CEL `+`.
|
||||
- If a value is only one `${...}` expression, the result keeps its type. Use this for numbers, booleans, objects, and lists.
|
||||
- If the string has other text, the final value is text. Non-text values become JSON. `null` becomes empty text.
|
||||
- Use `text(root, "path", "default")` for values that may be missing or null. The default is optional and is `""`.
|
||||
|
||||
Expression examples:
|
||||
|
||||
@@ -78,12 +78,6 @@ domains: "${state.domains}"
|
||||
limit: "${state.limit}"
|
||||
```
|
||||
|
||||
Use a default for missing text:
|
||||
|
||||
```yaml
|
||||
input: "Ticket ${text(state, \"ticket.id\", \"unknown\")}"
|
||||
```
|
||||
|
||||
- Crew text: use `{name}` placeholders from crew inputs. Example: `Research {topic}`.
|
||||
- Crew inputs become prompt text only when agent or task text references matching `{name}` placeholders.
|
||||
- Passing an input that is not referenced by any `{name}` placeholder does not ground the crew. If the crew needs a field, put that placeholder in an agent `goal`, task `description`, or task `expected_output`.
|
||||
@@ -111,6 +105,7 @@ Dynamic value rules:
|
||||
- Do not use fields outside the declaration schema.
|
||||
- Do not put more than one action under a method's `do`.
|
||||
- Do not make `do` a list.
|
||||
- Do not use CEL `+` to build text in action mappings. Keep the text literal and insert each dynamic value with `${...}`.
|
||||
- Do not reference `outputs.some_method` before `some_method` can run.
|
||||
- Do not set a method's `listen` to its own method name.
|
||||
- Do not use the same string for an emitted event and a method name unless the user asks for it.
|
||||
@@ -246,7 +241,7 @@ Shape:
|
||||
Fields:
|
||||
- `call` (required): must be `crew`. Action discriminator. Use crew to run an inline Crew definition. Example: `crew`
|
||||
- `with` (required): inline crew definition. Inline Crew definition to load and execute for this action. Example: `{"agents": {"researcher": {"backstory": "Knows the domain.", "goal": "Research {topic}", "role": "Researcher"}}, "name": "inline_research", "tasks": [{"agent": "researcher", "description": "Research {topic}", "expected_output": "Findings about {topic}", "name": "research_task"}]}`
|
||||
- `inputs` (optional): map of string to expression data | null; default `null`. Actual kickoff inputs passed to the Crew. Use `${...}` inside action mapping strings to read Flow data with CEL. Example value: `Ticket: ${state.ticket_id}`. Use `state` for input data. Use `outputs.step_name` for a completed method result. If a value is only one `${...}` expression, the result keeps its type. Use this for numbers, booleans, objects, and lists. If the string has other text, the final value is text. Non-text values become JSON. `null` becomes empty text. Use `text(root, "path", "default")` for values that may be missing or null. The default is optional and is `""`. The evaluated values are available to crew agent and task interpolation as `{name}` placeholders; reference each input the crew needs in agent or task text. Example: `{"topic": "${state.topic}"}`
|
||||
- `inputs` (optional): map of string to expression data | null; default `null`. Runtime inputs passed to the Crew. Insert Flow values with `${...}` and reference each input as `{name}` in agent or task text. Example: `{"topic": "${state.topic}"}`
|
||||
|
||||
#### Crew Definition (`methods.<name>.do[call=crew].with`)
|
||||
|
||||
@@ -311,7 +306,7 @@ Fields:
|
||||
- `tools` (optional): list[string | map of string to any] | null; default `null`. Tool refs or serialized tool definitions available to this agent. String refs can use CrewAI tool names, `custom:<name>`, or fully qualified `module:Class` references. Example: `["crewai_tools:SerperDevTool", "custom:file_read"]`
|
||||
- `apps` (optional): list[string] | null; default `null`. Platform apps available to this agent. Can contain app names such as `gmail` or app/action refs such as `gmail/send_email`. Example: `["gmail", "slack/send_message"]`
|
||||
- `mcps` (optional): list[string | map of string to any] | null; default `null`. MCP server refs or serialized MCP server configs available to this agent. String refs can use HTTPS URLs, connected MCP integration slugs, or refs with a `#tool_name` suffix for specific tools. Example: `["https://api.weather.com/mcp#get_current_weather", "snowflake", "stripe#list_invoices", {"cache_tools_list": true, "headers": {"Authorization": "Bearer your_token"}, "streamable": true, "url": "https://api.example.com/mcp"}]`
|
||||
- `input` (required): string. Input passed to the individual agent kickoff outside of a crew. Use one string. Use `${...}` inside action mapping strings to read Flow data with CEL. Example value: `Ticket: ${state.ticket_id}`. Use `state` for input data. Use `outputs.step_name` for a completed method result. If a value is only one `${...}` expression, the result keeps its type. Use this for numbers, booleans, objects, and lists. If the string has other text, the final value is text. Non-text values become JSON. `null` becomes empty text. Use `text(root, "path", "default")` for values that may be missing or null. The default is optional and is `""`. When an agent needs multiple fields, write one string with labels and separators, for example `Ticket ID: ${state.ticket_id}; Message: ${state.message}`. Example: `${state.ticket.body}`
|
||||
- `input` (required): string. Agent prompt template. Insert Flow values with `${...}`, for example `Ticket: ${state.ticket_id}`. Example: `${state.ticket.body}`
|
||||
|
||||
#### LLM Definition
|
||||
|
||||
@@ -349,4 +344,3 @@ Fields:
|
||||
- Crew action-level `inputs` are the Crew kickoff inputs; use CEL-wrapped strings there for runtime values.
|
||||
- Crew agent/task interpolation uses `{name}` placeholders from evaluated crew inputs.
|
||||
- Agent `with.input` must be text. Use `${outputs.method_name.raw}` or a text field like `${outputs.method_name.json_dict.summary}`.
|
||||
|
||||
|
||||
@@ -29,7 +29,9 @@ def test_create_flow_declarative_project_can_run(
|
||||
agents_md = (project_root / "AGENTS.md").read_text(encoding="utf-8")
|
||||
assert "CrewAI Flow declaration" in agents_md
|
||||
assert "schema: crewai.flow/v1" in agents_md
|
||||
assert 'text(root, "path", "default")' in agents_md
|
||||
assert "do not assemble the string with CEL `+`" in agents_md
|
||||
assert "Agent prompt template. Insert Flow values with `${...}`" in agents_md
|
||||
assert "Runtime inputs passed to the Crew" in agents_md
|
||||
assert "call: expression" in agents_md
|
||||
assert "call: tool" not in agents_md
|
||||
assert "call: script" not in agents_md
|
||||
|
||||
@@ -6,6 +6,14 @@ from unittest.mock import Mock
|
||||
import pytest
|
||||
|
||||
from crewai.events.event_bus import crewai_event_bus
|
||||
from crewai.events.types.crew_events import CrewKickoffStartedEvent
|
||||
from crewai.events.types.flow_events import (
|
||||
FlowStartedEvent,
|
||||
MethodExecutionFailedEvent,
|
||||
MethodExecutionFinishedEvent,
|
||||
MethodExecutionPausedEvent,
|
||||
MethodExecutionStartedEvent,
|
||||
)
|
||||
from crewai.events.types.memory_events import (
|
||||
MemorySaveCompletedEvent,
|
||||
MemorySaveFailedEvent,
|
||||
@@ -959,6 +967,31 @@ async def test_crew_done_does_not_mark_unfinished_tool_successful() -> None:
|
||||
assert app._plan_step_status == {1: "failed", 2: "done", 3: "done"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_flow_done_uses_flow_wording_for_unfinished_tool() -> None:
|
||||
# The shared completion handler reports "flow" (not "crew") in flow mode.
|
||||
app = CrewRunApp(crew_name="Demo Flow")
|
||||
app._flow = SimpleNamespace()
|
||||
|
||||
async with app.run_test(size=(100, 40)) as pilot:
|
||||
app._log_entries = [
|
||||
{
|
||||
"tool_name": "search",
|
||||
"status": "running",
|
||||
"args": None,
|
||||
"result": None,
|
||||
"error": None,
|
||||
"start_time": time.time() - 2,
|
||||
"duration": None,
|
||||
"task_idx": 1,
|
||||
}
|
||||
]
|
||||
app._on_crew_done("final output")
|
||||
await pilot.pause()
|
||||
|
||||
assert app._log_entries[0]["error"] == "No result received before flow completed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_crew_done_does_not_timeout_memory_save() -> None:
|
||||
app = _app_with_plan()
|
||||
@@ -1481,3 +1514,210 @@ def test_overlapping_task_logs_keep_their_own_state() -> None:
|
||||
assert any(step.get("summary") == "thinking" for step in entry2["steps"])
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
|
||||
# ── Declarative-flow (non-conversational) TUI support ───────
|
||||
|
||||
|
||||
def test_is_flow_run_gating() -> None:
|
||||
"""The flow-render gate must be true only for a non-conversational flow."""
|
||||
crew_app = CrewRunApp(total_tasks=1)
|
||||
crew_app._crew = SimpleNamespace()
|
||||
assert crew_app._is_flow_run is False
|
||||
|
||||
conv_app = CrewRunApp(conversational=True)
|
||||
conv_app._flow = SimpleNamespace()
|
||||
assert conv_app._is_flow_run is False
|
||||
|
||||
flow_app = CrewRunApp()
|
||||
flow_app._flow = SimpleNamespace()
|
||||
assert flow_app._is_flow_run is True
|
||||
|
||||
|
||||
def test_flow_method_events_build_steps() -> None:
|
||||
app = CrewRunApp(crew_name="Demo")
|
||||
app._flow = SimpleNamespace()
|
||||
app._flow_method_types = {"research": "crew", "summarize": "agent"}
|
||||
app._subscribe()
|
||||
try:
|
||||
_emit_event(FlowStartedEvent(flow_name="Demo"))
|
||||
assert app._status == "working"
|
||||
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(
|
||||
flow_name="Demo", method_name="research", state={}
|
||||
)
|
||||
)
|
||||
assert app._flow_steps == [
|
||||
{"name": "research", "call_type": "crew", "status": "active"}
|
||||
]
|
||||
assert app._current_method == "research"
|
||||
|
||||
_emit_event(
|
||||
MethodExecutionFinishedEvent(
|
||||
flow_name="Demo", method_name="research", result="ok", state={}
|
||||
)
|
||||
)
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(
|
||||
flow_name="Demo", method_name="summarize", state={}
|
||||
)
|
||||
)
|
||||
_emit_event(
|
||||
MethodExecutionFailedEvent(
|
||||
flow_name="Demo",
|
||||
method_name="summarize",
|
||||
error=RuntimeError("boom"),
|
||||
)
|
||||
)
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
assert app._flow_steps == [
|
||||
{"name": "research", "call_type": "crew", "status": "done"},
|
||||
{"name": "summarize", "call_type": "agent", "status": "failed"},
|
||||
]
|
||||
# The header must not keep spinning a method that already ended.
|
||||
assert app._current_method is None
|
||||
|
||||
|
||||
def test_current_method_clears_and_falls_back_across_overlap() -> None:
|
||||
app = CrewRunApp(crew_name="Demo")
|
||||
app._flow = SimpleNamespace()
|
||||
app._subscribe()
|
||||
try:
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(flow_name="Demo", method_name="a", state={})
|
||||
)
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(flow_name="Demo", method_name="b", state={})
|
||||
)
|
||||
assert app._current_method == "b"
|
||||
|
||||
# 'a' finishes while 'b' is still active → header stays on 'b'.
|
||||
_emit_event(
|
||||
MethodExecutionFinishedEvent(
|
||||
flow_name="Demo", method_name="a", result=None, state={}
|
||||
)
|
||||
)
|
||||
assert app._current_method == "b"
|
||||
|
||||
# 'b' finishes → nothing active left → header clears.
|
||||
_emit_event(
|
||||
MethodExecutionFinishedEvent(
|
||||
flow_name="Demo", method_name="b", result=None, state={}
|
||||
)
|
||||
)
|
||||
assert app._current_method is None
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
|
||||
def test_flow_method_transitions_clear_current_agent() -> None:
|
||||
app = CrewRunApp(crew_name="Demo")
|
||||
app._flow = SimpleNamespace()
|
||||
app._subscribe()
|
||||
try:
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(flow_name="Demo", method_name="a", state={})
|
||||
)
|
||||
app._current_agent = "Researcher" # an agent ran during method 'a'
|
||||
|
||||
# Starting a new method clears the previous method's agent.
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(flow_name="Demo", method_name="b", state={})
|
||||
)
|
||||
assert app._current_agent == ""
|
||||
|
||||
app._current_agent = "Writer"
|
||||
# 'b' ending switches the active method ('a' still active) → agent clears.
|
||||
_emit_event(
|
||||
MethodExecutionFinishedEvent(
|
||||
flow_name="Demo", method_name="b", result=None, state={}
|
||||
)
|
||||
)
|
||||
assert app._current_agent == ""
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
|
||||
def test_crew_kickoff_does_not_rename_flow_run() -> None:
|
||||
# A `call: crew` step must not relabel the flow with the nested crew's name.
|
||||
app = CrewRunApp(crew_name="My Flow")
|
||||
app._flow = SimpleNamespace()
|
||||
app._subscribe()
|
||||
try:
|
||||
_emit_event(CrewKickoffStartedEvent(crew_name="Nested Crew", inputs=None))
|
||||
assert app._crew_name == "My Flow"
|
||||
assert app._status == "working"
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
|
||||
def test_crew_kickoff_renames_in_crew_mode() -> None:
|
||||
# Regression: crew runs still adopt the crew name from the event.
|
||||
app = CrewRunApp(crew_name="Crew")
|
||||
app._crew = SimpleNamespace()
|
||||
app._subscribe()
|
||||
try:
|
||||
_emit_event(CrewKickoffStartedEvent(crew_name="Real Crew", inputs=None))
|
||||
assert app._crew_name == "Real Crew"
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
|
||||
def test_method_paused_marks_step_paused() -> None:
|
||||
app = CrewRunApp(crew_name="Demo")
|
||||
app._flow = SimpleNamespace()
|
||||
app._subscribe()
|
||||
try:
|
||||
_emit_event(
|
||||
MethodExecutionStartedEvent(flow_name="Demo", method_name="ask", state={})
|
||||
)
|
||||
_emit_event(
|
||||
MethodExecutionPausedEvent(
|
||||
flow_name="Demo",
|
||||
method_name="ask",
|
||||
state={},
|
||||
flow_id="flow-1",
|
||||
message="Need your input",
|
||||
)
|
||||
)
|
||||
assert app._flow_steps == [
|
||||
{"name": "ask", "call_type": None, "status": "paused"}
|
||||
]
|
||||
assert app._current_method == "ask"
|
||||
finally:
|
||||
app._unsubscribe()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_declarative_flow_runs_on_tui() -> None:
|
||||
"""End-to-end: on_mount dispatches _run_flow_worker → flow.kickoff →
|
||||
_on_crew_done, and any still-active step is swept to done on completion."""
|
||||
kicked: dict[str, object] = {}
|
||||
|
||||
class FakeFlow:
|
||||
name = "Demo Flow"
|
||||
|
||||
def kickoff(self, inputs=None):
|
||||
kicked["inputs"] = inputs
|
||||
return "flow result"
|
||||
|
||||
app = CrewRunApp(crew_name="Demo Flow")
|
||||
app._flow = FakeFlow()
|
||||
app._flow_inputs = {"topic": "AI"}
|
||||
# A step left active (no Finished event) must be swept to done by _on_crew_done.
|
||||
app._flow_steps = [{"name": "compute", "call_type": "expression", "status": "active"}]
|
||||
|
||||
async with app.run_test() as pilot:
|
||||
for _ in range(100):
|
||||
await pilot.pause(0.05)
|
||||
if app._status == "completed":
|
||||
break
|
||||
|
||||
assert kicked["inputs"] == {"topic": "AI"}
|
||||
assert app._status == "completed"
|
||||
assert app._final_output == "flow result"
|
||||
assert app._crew_result == "flow result"
|
||||
assert app._flow_steps[0]["status"] == "done"
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -9,6 +10,17 @@ import crewai_cli.input_prompt as input_prompt_module
|
||||
import crewai_cli.run_declarative_flow as run_declarative_flow_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _headless_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Default these tests to the headless/terminal path.
|
||||
|
||||
``run_declarative_flow`` now launches the TUI when interactive, which can't
|
||||
run under pytest; tests here assert the terminal/headless contract. Tests
|
||||
that exercise TUI routing override ``is_dmn_mode_enabled`` explicitly.
|
||||
"""
|
||||
monkeypatch.setenv("CREWAI_DMN", "true")
|
||||
|
||||
|
||||
FLOW_YAML = """\
|
||||
schema: crewai.flow/v1
|
||||
name: TestFlow
|
||||
@@ -400,3 +412,202 @@ def test_id_restore_still_drops_unknown_keys(
|
||||
assert resolved == {"id": "run-123"} # id kept, typo dropped
|
||||
assert "Ignoring unknown input 'prospect_emai'" in captured.err
|
||||
assert "Ignoring unknown input 'id'" not in captured.err
|
||||
|
||||
|
||||
# ── TUI vs terminal (headless/deploy) routing ──────────────────────
|
||||
|
||||
|
||||
def _install_fake_flow_app(monkeypatch, *, status, want_deploy=False):
|
||||
"""Replace CrewRunApp/EventListener/summary so _run_declarative_flow_tui is
|
||||
driven by a controllable fake app."""
|
||||
|
||||
class FakeEventListener:
|
||||
pass
|
||||
|
||||
class FakeApp:
|
||||
def __init__(self, crew_name=""):
|
||||
self._crew_name = crew_name
|
||||
self._status = status
|
||||
self._want_deploy = want_deploy
|
||||
self._crew_result = "result"
|
||||
|
||||
def run(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(
|
||||
"crewai.events.event_listener.EventListener", FakeEventListener
|
||||
)
|
||||
monkeypatch.setattr("crewai_cli.crew_run_tui.CrewRunApp", FakeApp)
|
||||
monkeypatch.setattr(
|
||||
run_declarative_flow_module, "_print_flow_post_tui_summary", lambda app: None
|
||||
)
|
||||
|
||||
|
||||
def test_run_declarative_flow_dmn_uses_terminal(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("CREWAI_DMN", "true")
|
||||
monkeypatch.setattr(
|
||||
run_declarative_flow_module,
|
||||
"_run_declarative_flow_tui",
|
||||
lambda *a, **k: pytest.fail("DMN/headless mode must not launch the TUI"),
|
||||
)
|
||||
path = _write(tmp_path, REQUIRED_FLOW_YAML)
|
||||
|
||||
run_declarative_flow_module.run_declarative_flow(
|
||||
str(path), '{"prospect_email":"a@b.com"}'
|
||||
)
|
||||
|
||||
assert capsys.readouterr().out == "a@b.com\n"
|
||||
|
||||
|
||||
def test_run_declarative_flow_interactive_uses_tui(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(run_declarative_flow_module, "is_interactive", lambda: True)
|
||||
captured: dict[str, object] = {}
|
||||
monkeypatch.setattr(
|
||||
run_declarative_flow_module,
|
||||
"_run_declarative_flow_tui",
|
||||
lambda flow, resolved: captured.update(flow=flow, inputs=resolved),
|
||||
)
|
||||
path = _write(tmp_path, REQUIRED_FLOW_YAML)
|
||||
|
||||
run_declarative_flow_module.run_declarative_flow(
|
||||
str(path), '{"prospect_email":"a@b.com"}'
|
||||
)
|
||||
|
||||
assert captured["inputs"] == {"prospect_email": "a@b.com"}
|
||||
assert captured["flow"] is not None
|
||||
|
||||
|
||||
def test_run_declarative_flow_tui_failed_exits_nonzero(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_install_fake_flow_app(monkeypatch, status="failed")
|
||||
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
run_declarative_flow_module._run_declarative_flow_tui(
|
||||
SimpleNamespace(name="Flow"), None
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 1
|
||||
|
||||
|
||||
def test_run_declarative_flow_tui_user_quit_exits_130(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_install_fake_flow_app(monkeypatch, status="chatting")
|
||||
exit_calls: list[int] = []
|
||||
monkeypatch.setattr(os, "_exit", lambda code: exit_calls.append(code))
|
||||
|
||||
run_declarative_flow_module._run_declarative_flow_tui(
|
||||
SimpleNamespace(name="Flow"), None
|
||||
)
|
||||
|
||||
assert exit_calls == [130]
|
||||
|
||||
|
||||
def test_run_declarative_flow_tui_chains_deploy(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_install_fake_flow_app(monkeypatch, status="completed", want_deploy=True)
|
||||
deploy_calls: list[bool] = []
|
||||
monkeypatch.setattr(
|
||||
"crewai_cli.run_crew._chain_deploy", lambda: deploy_calls.append(True)
|
||||
)
|
||||
|
||||
run_declarative_flow_module._run_declarative_flow_tui(
|
||||
SimpleNamespace(name="Flow"), None
|
||||
)
|
||||
|
||||
assert deploy_calls == [True]
|
||||
|
||||
|
||||
def test_run_declarative_flow_tui_no_deploy_when_not_requested(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
_install_fake_flow_app(monkeypatch, status="completed", want_deploy=False)
|
||||
deploy_calls: list[bool] = []
|
||||
monkeypatch.setattr(
|
||||
"crewai_cli.run_crew._chain_deploy", lambda: deploy_calls.append(True)
|
||||
)
|
||||
|
||||
run_declarative_flow_module._run_declarative_flow_tui(
|
||||
SimpleNamespace(name="Flow"), None
|
||||
)
|
||||
|
||||
assert deploy_calls == []
|
||||
|
||||
|
||||
def test_run_declarative_flow_tui_enables_flow_events(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# The STEPS panel depends on flow method events; a flow that declared
|
||||
# suppress_flow_events must have it forced off for the interactive TUI run.
|
||||
_install_fake_flow_app(monkeypatch, status="completed")
|
||||
flow = SimpleNamespace(name="Flow", suppress_flow_events=True)
|
||||
|
||||
run_declarative_flow_module._run_declarative_flow_tui(flow, None)
|
||||
|
||||
assert flow.suppress_flow_events is False
|
||||
|
||||
|
||||
def test_flow_uses_human_feedback_detection() -> None:
|
||||
hf_flow = SimpleNamespace(
|
||||
_definition=SimpleNamespace(
|
||||
methods={
|
||||
"ask": SimpleNamespace(human_feedback=SimpleNamespace(emit=None)),
|
||||
"plain": SimpleNamespace(human_feedback=None),
|
||||
}
|
||||
)
|
||||
)
|
||||
assert run_declarative_flow_module._flow_uses_human_feedback(hf_flow) is True
|
||||
|
||||
no_hf = SimpleNamespace(
|
||||
_definition=SimpleNamespace(
|
||||
methods={"a": SimpleNamespace(human_feedback=None)}
|
||||
)
|
||||
)
|
||||
assert run_declarative_flow_module._flow_uses_human_feedback(no_hf) is False
|
||||
# No definition → False, no error.
|
||||
assert run_declarative_flow_module._flow_uses_human_feedback(SimpleNamespace()) is False
|
||||
|
||||
|
||||
def test_human_feedback_flow_uses_terminal_even_when_interactive(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# A human-feedback flow must run on the terminal (blocking input / Rich
|
||||
# prompts) even in an interactive session, never on the TUI.
|
||||
monkeypatch.setattr(run_declarative_flow_module, "is_interactive", lambda: True)
|
||||
monkeypatch.setattr(
|
||||
run_declarative_flow_module, "_flow_uses_human_feedback", lambda flow: True
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
run_declarative_flow_module,
|
||||
"_run_declarative_flow_tui",
|
||||
lambda *a, **k: pytest.fail("human-feedback flow must run on the terminal"),
|
||||
)
|
||||
path = _write(tmp_path, FLOW_YAML)
|
||||
|
||||
run_declarative_flow_module.run_declarative_flow(str(path), '{"topic":"AI"}')
|
||||
|
||||
assert capsys.readouterr().out == "AI\n"
|
||||
|
||||
|
||||
def test_flow_method_types_from_definition() -> None:
|
||||
flow = SimpleNamespace(
|
||||
_definition=SimpleNamespace(
|
||||
methods={
|
||||
"fetch": SimpleNamespace(do=SimpleNamespace(call="expression")),
|
||||
"research": SimpleNamespace(do=SimpleNamespace(call="crew")),
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
assert run_declarative_flow_module._flow_method_types(flow) == {
|
||||
"fetch": "expression",
|
||||
"research": "crew",
|
||||
}
|
||||
# No definition → empty map, no error.
|
||||
assert run_declarative_flow_module._flow_method_types(SimpleNamespace()) == {}
|
||||
|
||||
@@ -86,6 +86,7 @@ from crewai.skills.models import Skill as SkillModel
|
||||
from crewai.state.checkpoint_config import CheckpointConfig, apply_checkpoint
|
||||
from crewai.tools.agent_tools.agent_tools import AgentTools
|
||||
from crewai.types.callback import SerializableCallable
|
||||
from crewai.types.usage_metrics import UsageMetrics
|
||||
from crewai.utilities.agent_utils import (
|
||||
get_tool_names,
|
||||
is_inside_event_loop,
|
||||
@@ -400,10 +401,29 @@ class Agent(BaseAgent):
|
||||
return self.planning_config is not None or self.planning
|
||||
|
||||
def _setup_agent_executor(self) -> None:
|
||||
"""Initialize the agent executor with a default cache handler."""
|
||||
if not self.cache_handler:
|
||||
self.cache_handler = CacheHandler()
|
||||
self.set_cache_handler(self.cache_handler)
|
||||
"""Initialize the agent's tools handler and optional tool cache.
|
||||
|
||||
Tool-result caching is opt-in: a standalone agent gets a cache only
|
||||
when it was constructed with an explicit ``cache=True`` or a
|
||||
``cache_handler``. Agents inside a crew additionally receive the
|
||||
crew's shared handler when ``Crew(cache=True)``. Without an opt-in,
|
||||
repeated tool calls with identical arguments always re-execute the
|
||||
tool — the safe default for live-data and state-mutating tools.
|
||||
"""
|
||||
# Recorded before any crew can offer its shared handler at kickoff,
|
||||
# so copy() can distinguish a construction-time opt-in from runtime
|
||||
# crew wiring (which must not turn copies into cachers).
|
||||
self._constructor_cache_opt_in = bool(
|
||||
self.cache
|
||||
and (self.cache_handler is not None or "cache" in self.model_fields_set)
|
||||
)
|
||||
opted_in = self.cache_handler is not None or (
|
||||
"cache" in self.model_fields_set and self.cache
|
||||
)
|
||||
if opted_in:
|
||||
if not self.cache_handler:
|
||||
self.cache_handler = CacheHandler()
|
||||
self.set_cache_handler(self.cache_handler)
|
||||
|
||||
def set_knowledge(self, crew_embedder: EmbedderConfig | None = None) -> None:
|
||||
"""Initialize knowledge sources with the agent or crew embedder config."""
|
||||
@@ -1582,9 +1602,18 @@ class Agent(BaseAgent):
|
||||
crewai_event_bus.emit(self, event=started_event)
|
||||
self._kickoff_event_id = started_event.event_id
|
||||
|
||||
output = self._execute_and_build_output(executor, inputs, response_format)
|
||||
usage_baseline = self._current_usage_summary()
|
||||
output = self._execute_and_build_output(
|
||||
executor, inputs, response_format, usage_baseline
|
||||
)
|
||||
return self._finalize_kickoff(
|
||||
output, executor, inputs, response_format, messages, agent_info
|
||||
output,
|
||||
executor,
|
||||
inputs,
|
||||
response_format,
|
||||
messages,
|
||||
agent_info,
|
||||
usage_baseline,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -1598,6 +1627,7 @@ class Agent(BaseAgent):
|
||||
response_format: type[Any] | None,
|
||||
messages: str | list[LLMMessage],
|
||||
agent_info: dict[str, Any],
|
||||
usage_baseline: UsageMetrics | None = None,
|
||||
) -> LiteAgentOutput:
|
||||
"""Apply guardrails, save to memory, and emit completion event.
|
||||
|
||||
@@ -1608,6 +1638,8 @@ class Agent(BaseAgent):
|
||||
response_format: Optional response format.
|
||||
messages: The original messages.
|
||||
agent_info: Agent metadata for events.
|
||||
usage_baseline: Usage snapshot taken at kickoff start, so retries
|
||||
report per-call usage relative to it.
|
||||
|
||||
Returns:
|
||||
The finalized output.
|
||||
@@ -1618,6 +1650,7 @@ class Agent(BaseAgent):
|
||||
executor=executor,
|
||||
inputs=inputs,
|
||||
response_format=response_format,
|
||||
usage_baseline=usage_baseline,
|
||||
)
|
||||
|
||||
self._save_kickoff_to_memory(messages, output.raw)
|
||||
@@ -1669,11 +1702,24 @@ class Agent(BaseAgent):
|
||||
except Exception as e:
|
||||
self._logger.log("error", f"Failed to save kickoff result to memory: {e}")
|
||||
|
||||
def _current_usage_summary(self) -> UsageMetrics:
|
||||
"""Snapshot the cumulative usage counters backing this agent's LLM.
|
||||
|
||||
The counters live on the LLM instance (or the agent's token process
|
||||
for non-BaseLLM models) and grow for the object's lifetime — across
|
||||
calls and across agents sharing the instance. Per-call usage is the
|
||||
delta between two snapshots.
|
||||
"""
|
||||
if isinstance(self.llm, BaseLLM):
|
||||
return self.llm.get_token_usage_summary()
|
||||
return self._token_process.get_summary()
|
||||
|
||||
def _build_output_from_result(
|
||||
self,
|
||||
result: dict[str, Any],
|
||||
executor: AgentExecutor,
|
||||
response_format: type[Any] | None = None,
|
||||
usage_baseline: UsageMetrics | None = None,
|
||||
) -> LiteAgentOutput:
|
||||
"""Build a LiteAgentOutput from an executor result dict.
|
||||
|
||||
@@ -1683,6 +1729,9 @@ class Agent(BaseAgent):
|
||||
result: The result dictionary from executor.invoke / invoke_async.
|
||||
executor: The executor instance.
|
||||
response_format: Optional response format.
|
||||
usage_baseline: Usage snapshot taken at kickoff start. When given,
|
||||
the output carries only this call's usage (the delta) instead
|
||||
of the LLM instance's cumulative lifetime counters.
|
||||
|
||||
Returns:
|
||||
LiteAgentOutput with raw output, formatted result, and metrics.
|
||||
@@ -1727,10 +1776,9 @@ class Agent(BaseAgent):
|
||||
else:
|
||||
raw_output = str(output) if not isinstance(output, str) else output
|
||||
|
||||
if isinstance(self.llm, BaseLLM):
|
||||
usage_metrics = self.llm.get_token_usage_summary()
|
||||
else:
|
||||
usage_metrics = self._token_process.get_summary()
|
||||
usage_metrics = self._current_usage_summary()
|
||||
if usage_baseline is not None:
|
||||
usage_metrics = usage_metrics.delta_since(usage_baseline)
|
||||
|
||||
raw_str = (
|
||||
raw_output
|
||||
@@ -1759,20 +1807,26 @@ class Agent(BaseAgent):
|
||||
executor: AgentExecutor,
|
||||
inputs: dict[str, str],
|
||||
response_format: type[Any] | None = None,
|
||||
usage_baseline: UsageMetrics | None = None,
|
||||
) -> LiteAgentOutput:
|
||||
"""Execute the agent synchronously and build the output object."""
|
||||
result = cast(dict[str, Any], executor.invoke(inputs))
|
||||
return self._build_output_from_result(result, executor, response_format)
|
||||
return self._build_output_from_result(
|
||||
result, executor, response_format, usage_baseline
|
||||
)
|
||||
|
||||
async def _execute_and_build_output_async(
|
||||
self,
|
||||
executor: AgentExecutor,
|
||||
inputs: dict[str, str],
|
||||
response_format: type[Any] | None = None,
|
||||
usage_baseline: UsageMetrics | None = None,
|
||||
) -> LiteAgentOutput:
|
||||
"""Execute the agent asynchronously and build the output object."""
|
||||
result = await executor.invoke_async(inputs)
|
||||
return self._build_output_from_result(result, executor, response_format)
|
||||
return self._build_output_from_result(
|
||||
result, executor, response_format, usage_baseline
|
||||
)
|
||||
|
||||
def _process_kickoff_guardrail(
|
||||
self,
|
||||
@@ -1781,6 +1835,7 @@ class Agent(BaseAgent):
|
||||
inputs: dict[str, str],
|
||||
response_format: type[Any] | None = None,
|
||||
retry_count: int = 0,
|
||||
usage_baseline: UsageMetrics | None = None,
|
||||
) -> LiteAgentOutput:
|
||||
"""Process guardrail for kickoff execution with retry logic.
|
||||
|
||||
@@ -1790,6 +1845,9 @@ class Agent(BaseAgent):
|
||||
inputs: Input dictionary for re-execution.
|
||||
response_format: Optional response format.
|
||||
retry_count: Current retry count.
|
||||
usage_baseline: Usage snapshot taken at kickoff start, so a
|
||||
retried output reports the whole call's usage, not just the
|
||||
last attempt's.
|
||||
|
||||
Returns:
|
||||
Validated/updated output.
|
||||
@@ -1827,7 +1885,9 @@ class Agent(BaseAgent):
|
||||
role="user",
|
||||
)
|
||||
|
||||
output = self._execute_and_build_output(executor, inputs, response_format)
|
||||
output = self._execute_and_build_output(
|
||||
executor, inputs, response_format, usage_baseline
|
||||
)
|
||||
|
||||
return self._process_kickoff_guardrail(
|
||||
output=output,
|
||||
@@ -1835,6 +1895,7 @@ class Agent(BaseAgent):
|
||||
inputs=inputs,
|
||||
response_format=response_format,
|
||||
retry_count=retry_count + 1,
|
||||
usage_baseline=usage_baseline,
|
||||
)
|
||||
|
||||
if guardrail_result.result is not None:
|
||||
@@ -1897,11 +1958,18 @@ class Agent(BaseAgent):
|
||||
crewai_event_bus.emit(self, event=started_event)
|
||||
self._kickoff_event_id = started_event.event_id
|
||||
|
||||
usage_baseline = self._current_usage_summary()
|
||||
output = await self._execute_and_build_output_async(
|
||||
executor, inputs, response_format
|
||||
executor, inputs, response_format, usage_baseline
|
||||
)
|
||||
return self._finalize_kickoff(
|
||||
output, executor, inputs, response_format, messages, agent_info
|
||||
output,
|
||||
executor,
|
||||
inputs,
|
||||
response_format,
|
||||
messages,
|
||||
agent_info,
|
||||
usage_baseline,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -205,7 +205,11 @@ class BaseAgent(BaseModel, ABC, metaclass=AgentMeta):
|
||||
role (str): Role of the agent.
|
||||
goal (str): Objective of the agent.
|
||||
backstory (str): Backstory of the agent.
|
||||
cache (bool): Whether the agent should use a cache for tool usage.
|
||||
cache (bool): Whether the agent participates in tool-result caching
|
||||
when a cache is enabled. The default (True) only permits
|
||||
participation — caching activates when the crew sets cache=True
|
||||
or the agent explicitly opts in with cache=True or a
|
||||
cache_handler; cache=False excludes the agent entirely.
|
||||
config (dict[str, Any] | None): Configuration for the agent.
|
||||
verbose (bool): Verbose mode for the Agent Execution.
|
||||
max_rpm (int | None): Maximum number of requests per minute for the agent execution.
|
||||
@@ -254,6 +258,7 @@ class BaseAgent(BaseModel, ABC, metaclass=AgentMeta):
|
||||
_logger: Logger = PrivateAttr(default_factory=lambda: Logger(verbose=False))
|
||||
_rpm_controller: RPMController | None = PrivateAttr(default=None)
|
||||
_request_within_rpm_limit: SerializableCallable | None = PrivateAttr(default=None)
|
||||
_constructor_cache_opt_in: bool = PrivateAttr(default=False)
|
||||
_original_role: str | None = PrivateAttr(default=None)
|
||||
_original_goal: str | None = PrivateAttr(default=None)
|
||||
_original_backstory: str | None = PrivateAttr(default=None)
|
||||
@@ -267,7 +272,14 @@ class BaseAgent(BaseModel, ABC, metaclass=AgentMeta):
|
||||
description="Configuration for the agent", default=None, exclude=True
|
||||
)
|
||||
cache: bool = Field(
|
||||
default=True, description="Whether the agent should use a cache for tool usage."
|
||||
default=True,
|
||||
description=(
|
||||
"Whether the agent participates in tool-result caching when a "
|
||||
"cache is enabled. Caching itself is opt-in: it activates only "
|
||||
"when the crew sets cache=True or the agent explicitly opts in "
|
||||
"(cache=True or a cache_handler at construction). Set False to "
|
||||
"exclude this agent even when the crew enables caching."
|
||||
),
|
||||
)
|
||||
verbose: bool = Field(
|
||||
default=False, description="Verbose mode for the Agent Execution"
|
||||
@@ -716,6 +728,19 @@ class BaseAgent(BaseModel, ABC, metaclass=AgentMeta):
|
||||
|
||||
copied_data = self.model_dump(exclude=exclude)
|
||||
copied_data = {k: v for k, v in copied_data.items() if v is not None}
|
||||
# Tool-result caching distinguishes "explicitly enabled" from the
|
||||
# field default via model_fields_set; don't let the dump turn the
|
||||
# default into an explicit opt-in on the copy. An agent that opted
|
||||
# in at construction via an explicit cache_handler (excluded from
|
||||
# the dump) must stay opted in — carry the consent as cache=True so
|
||||
# the copy wires its own fresh handler. A handler merely offered by
|
||||
# a crew at kickoff is runtime wiring, not consent, and must not
|
||||
# opt the copy in; _constructor_cache_opt_in is recorded before any
|
||||
# crew wiring can happen.
|
||||
if "cache" not in self.model_fields_set:
|
||||
copied_data.pop("cache", None)
|
||||
if self._constructor_cache_opt_in:
|
||||
copied_data["cache"] = True
|
||||
return type(self)(
|
||||
**copied_data,
|
||||
llm=existing_llm,
|
||||
|
||||
@@ -168,8 +168,11 @@ class Crew(FlowTrackable, BaseModel):
|
||||
manager_agent: Custom agent that will be used as manager.
|
||||
memory: Whether the crew should use memory to store memories of it's
|
||||
execution.
|
||||
cache: Whether the crew should use a cache to store the results of the
|
||||
tools execution.
|
||||
cache: Whether to cache tool results for the crew's agents. Off by
|
||||
default; when enabled, repeated calls to the same tool with
|
||||
identical arguments reuse the first result without re-executing —
|
||||
avoid enabling for live-data or state-mutating tools unless they
|
||||
gate writes with a cache_function.
|
||||
function_calling_llm: The language model that will run the tool calling
|
||||
for all the agents.
|
||||
process: The process flow that the crew will follow (e.g., sequential,
|
||||
@@ -216,7 +219,16 @@ class Crew(FlowTrackable, BaseModel):
|
||||
_kickoff_event_id: str | None = PrivateAttr(default=None)
|
||||
|
||||
name: str | None = Field(default="crew")
|
||||
cache: bool = Field(default=True)
|
||||
cache: bool = Field(
|
||||
default=False,
|
||||
description=(
|
||||
"Whether to cache tool results for the crew's agents. Opt-in: "
|
||||
"when enabled, repeated calls to the same tool with identical "
|
||||
"arguments return the first result without re-executing the "
|
||||
"tool — do not enable for live-data or state-mutating tools "
|
||||
"unless they set a cache_function that prevents caching."
|
||||
),
|
||||
)
|
||||
tasks: list[Task] = Field(default_factory=list)
|
||||
agents: Annotated[
|
||||
list[BaseAgent],
|
||||
@@ -1048,8 +1060,9 @@ class Crew(FlowTrackable, BaseModel):
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if self._memory is not None and hasattr(self._memory, "drain_writes"):
|
||||
self._memory.drain_writes()
|
||||
# Safety net for the exception path; the success path already
|
||||
# drained in _create_crew_output before emitting completion.
|
||||
self._drain_memory_writes()
|
||||
clear_files(self.id)
|
||||
detach(token)
|
||||
crewai_event_bus._exit_runtime_scope(runtime_scope)
|
||||
@@ -1260,6 +1273,9 @@ class Crew(FlowTrackable, BaseModel):
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
# Safety net for the exception path; the success path already
|
||||
# drained in _create_crew_output before emitting completion.
|
||||
self._drain_memory_writes()
|
||||
clear_files(self.id)
|
||||
detach(token)
|
||||
crewai_event_bus._exit_runtime_scope(runtime_scope)
|
||||
@@ -1503,6 +1519,11 @@ class Crew(FlowTrackable, BaseModel):
|
||||
)
|
||||
self.manager_agent = manager
|
||||
manager.crew = self
|
||||
# The manager is created outside the agents loop that offers the
|
||||
# crew's cache handler at validation time; offer it here so an
|
||||
# opted-in crew (cache=True) also dedupes the manager's tool calls.
|
||||
if self.cache:
|
||||
manager.set_cache_handler(self._cache_handler)
|
||||
|
||||
def _get_execution_start_index(self, tasks: list[Task]) -> int | None:
|
||||
if self.checkpoint_kickoff_event_id is None:
|
||||
@@ -1841,6 +1862,38 @@ class Crew(FlowTrackable, BaseModel):
|
||||
output=output.raw,
|
||||
)
|
||||
|
||||
def _drain_memory_writes(self) -> None:
|
||||
"""Block until all pending background memory saves have completed.
|
||||
|
||||
Covers the crew memory, per-agent memories, and the manager agent's
|
||||
memory — agents save through ``agent.memory`` when set (see
|
||||
``BaseAgentExecutor._save_to_memory``), so draining only
|
||||
``self._memory`` can miss in-flight saves. Scope/slice views are
|
||||
unwrapped to their backing ``Memory`` so each pool is drained once.
|
||||
|
||||
Must run before ``CrewKickoffCompletedEvent`` is emitted: listeners
|
||||
(e.g. telemetry sessions) tear down on that event, and any
|
||||
``MemorySaveCompletedEvent``/``MemorySaveFailedEvent`` emitted after
|
||||
teardown is lost, leaving the save span orphaned.
|
||||
"""
|
||||
seen: set[int] = set()
|
||||
candidates = [
|
||||
self._memory,
|
||||
self.memory,
|
||||
getattr(self.manager_agent, "memory", None),
|
||||
*(getattr(agent, "memory", None) for agent in self.agents),
|
||||
]
|
||||
for mem in candidates:
|
||||
if mem is None or isinstance(mem, bool):
|
||||
continue
|
||||
backing = getattr(mem, "_memory", None) or mem
|
||||
if id(backing) in seen:
|
||||
continue
|
||||
seen.add(id(backing))
|
||||
drain = getattr(backing, "drain_writes", None)
|
||||
if callable(drain):
|
||||
drain()
|
||||
|
||||
def _create_crew_output(self, task_outputs: list[TaskOutput]) -> CrewOutput:
|
||||
if not task_outputs:
|
||||
raise ValueError("No task outputs available to create crew output.")
|
||||
@@ -1853,6 +1906,10 @@ class Crew(FlowTrackable, BaseModel):
|
||||
final_string_output = final_task_output.raw
|
||||
self._finish_execution(final_string_output)
|
||||
self.token_usage = self.calculate_usage_metrics()
|
||||
# Ensure background memory saves finish (and emit their
|
||||
# completed/failed events) before the kickoff-completed event below
|
||||
# triggers listener teardown/finalization.
|
||||
self._drain_memory_writes()
|
||||
crewai_event_bus.flush()
|
||||
crewai_event_bus.emit(
|
||||
self,
|
||||
|
||||
@@ -24,9 +24,23 @@ class CrewOutput(BaseModel):
|
||||
description="Output of each task", default_factory=list
|
||||
)
|
||||
token_usage: UsageMetrics = Field(
|
||||
description="Processed token summary", default_factory=UsageMetrics
|
||||
description=(
|
||||
"Processed token summary; ``usage_metrics`` exposes the same "
|
||||
"data as a plain dict"
|
||||
),
|
||||
default_factory=UsageMetrics,
|
||||
)
|
||||
|
||||
@property
|
||||
def usage_metrics(self) -> dict[str, Any]:
|
||||
"""Token usage as a plain dict.
|
||||
|
||||
Same attribute name and shape as ``LiteAgentOutput.usage_metrics``
|
||||
(the ``Agent.kickoff()`` result), so a usage accessor written for one
|
||||
result type works on both.
|
||||
"""
|
||||
return self.token_usage.model_dump()
|
||||
|
||||
@property
|
||||
def json(self) -> str | None: # type: ignore[override]
|
||||
if self.tasks_output[-1].output_format != OutputFormat.JSON:
|
||||
|
||||
@@ -211,6 +211,13 @@ To enable tracing, do any one of these:
|
||||
"""Print a panel with consistent formatting if verbose is enabled."""
|
||||
panel = self.create_panel(content, title, style)
|
||||
if is_flow:
|
||||
# A TUI (e.g. the CLI's CrewRunApp) owns the screen and renders flow
|
||||
# progress in its own STEPS panel; emitting Rich panels here would
|
||||
# interleave with and corrupt the TUI, so suppress them in TUI mode.
|
||||
from crewai.events.listeners.tracing.utils import is_tui_mode
|
||||
|
||||
if is_tui_mode():
|
||||
return
|
||||
self.print(panel)
|
||||
self.print()
|
||||
else:
|
||||
|
||||
@@ -133,6 +133,8 @@ class _ConversationalMixin:
|
||||
_pending_user_message: str | dict[str, Any] | None
|
||||
_pending_intents: Sequence[str] | None
|
||||
_pending_intent_llm: str | BaseLLM | None
|
||||
_turn_classified_intent: str | None
|
||||
_assistant_reply_appended: bool
|
||||
|
||||
def _clear_or_listeners(self) -> None:
|
||||
pass
|
||||
@@ -185,12 +187,22 @@ class _ConversationalMixin:
|
||||
)
|
||||
return configured_route
|
||||
|
||||
if state.last_intent:
|
||||
turn_intent = self._turn_classified_intent
|
||||
if turn_intent:
|
||||
state.last_intent = turn_intent
|
||||
self._emit_conversation_route_selected(
|
||||
state.last_intent,
|
||||
turn_intent,
|
||||
previous_intent=previous_intent,
|
||||
)
|
||||
return state.last_intent
|
||||
return turn_intent
|
||||
|
||||
if previous_intent:
|
||||
logger.debug(
|
||||
"route_turn() returned no route and no intent was classified "
|
||||
"this turn; ignoring stale last_intent=%r from a previous turn "
|
||||
"and falling back to built-in routing",
|
||||
previous_intent,
|
||||
)
|
||||
|
||||
if self.can_answer_from_history(context):
|
||||
state.last_intent = "answer_from_history"
|
||||
@@ -310,11 +322,11 @@ class _ConversationalMixin:
|
||||
if "from_checkpoint" not in kickoff_kwargs:
|
||||
self._reset_turn_execution_state()
|
||||
|
||||
assistant_count = self._assistant_message_count()
|
||||
object.__setattr__(self, "_assistant_reply_appended", False)
|
||||
result = self.kickoff(inputs={"id": sid}, **kickoff_kwargs)
|
||||
if (
|
||||
result is not None
|
||||
and self._assistant_message_count() == assistant_count
|
||||
and not self._assistant_reply_appended
|
||||
and self._is_public_turn_result(result)
|
||||
):
|
||||
self.append_assistant_message(self._stringify_result(result))
|
||||
@@ -387,7 +399,7 @@ class _ConversationalMixin:
|
||||
if "from_checkpoint" not in kickoff_kwargs:
|
||||
self._reset_turn_execution_state()
|
||||
|
||||
assistant_count = self._assistant_message_count()
|
||||
object.__setattr__(self, "_assistant_reply_appended", False)
|
||||
original_stream = bool(getattr(self, "stream", False))
|
||||
original_streaming_turn = getattr(
|
||||
self, "_streaming_conversation_turn", False
|
||||
@@ -403,7 +415,7 @@ class _ConversationalMixin:
|
||||
)
|
||||
if (
|
||||
result is not None
|
||||
and self._assistant_message_count() == assistant_count
|
||||
and not self._assistant_reply_appended
|
||||
and self._is_public_turn_result(result)
|
||||
):
|
||||
self.append_assistant_message(self._stringify_result(result))
|
||||
@@ -550,6 +562,11 @@ class _ConversationalMixin:
|
||||
supply per-route descriptions, or change the default/fallback intent.
|
||||
Override this method to bypass the LLM router entirely (e.g.,
|
||||
permission gates before the LLM decision).
|
||||
|
||||
Returning a falsy value means "no routing decision": the turn falls
|
||||
through to the built-in defaults (``answer_from_history`` when
|
||||
configured, else ``converse``). It never replays a previous turn's
|
||||
intent.
|
||||
"""
|
||||
config = self._conversation_config
|
||||
if config is None:
|
||||
@@ -618,6 +635,9 @@ class _ConversationalMixin:
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Append a final user-visible assistant message."""
|
||||
# Explicit signal for handle_turn's "did the handler reply?" check.
|
||||
# A count heuristic breaks when handlers trim history mid-turn.
|
||||
object.__setattr__(self, "_assistant_reply_appended", True)
|
||||
state = cast(ConversationState, self.state)
|
||||
state.messages.append(
|
||||
ConversationMessage(
|
||||
@@ -722,6 +742,7 @@ class _ConversationalMixin:
|
||||
context=self.conversation_messages,
|
||||
)
|
||||
state.last_intent = intent
|
||||
object.__setattr__(self, "_turn_classified_intent", intent)
|
||||
return intent
|
||||
return text
|
||||
|
||||
@@ -788,6 +809,10 @@ class _ConversationalMixin:
|
||||
object.__setattr__(self, "_pending_intent_llm", None)
|
||||
if not hasattr(self, "_streaming_conversation_turn"):
|
||||
object.__setattr__(self, "_streaming_conversation_turn", False)
|
||||
if not hasattr(self, "_turn_classified_intent"):
|
||||
object.__setattr__(self, "_turn_classified_intent", None)
|
||||
if not hasattr(self, "_assistant_reply_appended"):
|
||||
object.__setattr__(self, "_assistant_reply_appended", False)
|
||||
|
||||
def _create_default_extension_state(self) -> ConversationState | None:
|
||||
initial_state_t = getattr(self, "_initial_state_t", None)
|
||||
@@ -852,6 +877,7 @@ class _ConversationalMixin:
|
||||
self._method_call_counts.clear()
|
||||
self._clear_or_listeners()
|
||||
self._is_execution_resuming = False
|
||||
object.__setattr__(self, "_turn_classified_intent", None)
|
||||
|
||||
def _apply_pending_conversational_turn(self) -> None:
|
||||
"""Drain the stashed user message + classify if intents configured.
|
||||
@@ -859,6 +885,7 @@ class _ConversationalMixin:
|
||||
Called from ``Flow.kickoff_async`` AFTER persist state restore so
|
||||
the appended message survives ``self.persistence.load_state(...)``.
|
||||
"""
|
||||
object.__setattr__(self, "_turn_classified_intent", None)
|
||||
if self._pending_user_message is None:
|
||||
return
|
||||
|
||||
@@ -1107,10 +1134,6 @@ class _ConversationalMixin:
|
||||
return "public"
|
||||
return "private"
|
||||
|
||||
def _assistant_message_count(self) -> int:
|
||||
state = cast(ConversationState, self.state)
|
||||
return sum(1 for message in state.messages if message.role == "assistant")
|
||||
|
||||
def _is_public_turn_result(self, result: Any) -> bool:
|
||||
if not isinstance(result, str):
|
||||
return False
|
||||
@@ -1190,6 +1213,15 @@ class _ConversationalMixin:
|
||||
)
|
||||
from crewai.events.types.flow_events import FlowFinishedEvent
|
||||
|
||||
# Background memory saves must finish (and emit their completed/failed
|
||||
# events) before the session-end flow_finished / batch finalization
|
||||
# below tears down listeners, mirroring the non-deferred kickoff path.
|
||||
# The flush then waits for those events' async bus handlers.
|
||||
drain_memory_writes = getattr(self, "_drain_memory_writes", None)
|
||||
if callable(drain_memory_writes):
|
||||
drain_memory_writes()
|
||||
crewai_event_bus.flush()
|
||||
|
||||
# Only emit the session-end event when a deferred flow_started is
|
||||
# actually pending. ``_deferred_flow_started_event_id`` is set only by
|
||||
# deferred kickoffs; when finalization was not deferred, each per-turn
|
||||
|
||||
@@ -11,9 +11,6 @@ from crewai.utilities.serialization import to_serializable
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from celpy.celtypes import StringType
|
||||
from celpy.evaluation import CELFunction
|
||||
|
||||
from crewai.flow.runtime import Flow
|
||||
else:
|
||||
from typing_extensions import TypeAliasType
|
||||
@@ -24,29 +21,6 @@ _CEL_MACROS_WITH_LOCAL_BINDINGS = frozenset(
|
||||
)
|
||||
|
||||
|
||||
def _handle_text_custom_expression(
|
||||
root: Any, path: Any, default: Any = ""
|
||||
) -> StringType:
|
||||
from celpy.celtypes import StringType
|
||||
|
||||
fallback = StringType("" if default is None else str(default))
|
||||
current = root
|
||||
for part in str(path).split("."):
|
||||
if current is None:
|
||||
return fallback
|
||||
try:
|
||||
if isinstance(current, list):
|
||||
current = current[int(part)]
|
||||
else:
|
||||
current = current[StringType(part)]
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
if current is None:
|
||||
return fallback
|
||||
return StringType(_stringify_cel_value(current))
|
||||
|
||||
|
||||
def _stringify_cel_value(value: Any) -> str:
|
||||
from celpy.adapter import CELJSONEncoder
|
||||
|
||||
@@ -98,21 +72,18 @@ def _parse_template_segments(value: str) -> tuple[str | _ExpressionSegment, ...]
|
||||
return tuple(segments)
|
||||
|
||||
|
||||
_EXPRESSION_FUNCTIONS: dict[str, CELFunction] = {
|
||||
"text": _handle_text_custom_expression,
|
||||
}
|
||||
|
||||
FLOW_TEMPLATE_EXPRESSION_RULES: tuple[str, ...] = (
|
||||
"Use `${...}` inside action mapping strings to read Flow data with CEL. "
|
||||
"Example value: `Ticket: ${state.ticket_id}`.",
|
||||
"Use `state` for input data. Use `outputs.step_name` for a completed "
|
||||
"method result.",
|
||||
"In action mapping strings, keep literal text outside `${...}` and "
|
||||
"interpolate each Flow value directly. Write `Ticket: ${state.ticket_id}`; "
|
||||
"do not assemble the string with CEL `+`.",
|
||||
"If a value is only one `${...}` expression, the result keeps its type. "
|
||||
"Use this for numbers, booleans, objects, and lists.",
|
||||
"If the string has other text, the final value is text. Non-text values "
|
||||
"become JSON. `null` becomes empty text.",
|
||||
'Use `text(root, "path", "default")` for values that may be missing '
|
||||
'or null. The default is optional and is `""`.',
|
||||
)
|
||||
FLOW_TEMPLATE_EXPRESSION_CONTRACT = " ".join(FLOW_TEMPLATE_EXPRESSION_RULES)
|
||||
FLOW_TEMPLATE_EXPRESSION_EXAMPLES: dict[str, tuple[dict[str, str], ...]] = {
|
||||
@@ -125,10 +96,6 @@ FLOW_TEMPLATE_EXPRESSION_EXAMPLES: dict[str, tuple[dict[str, str], ...]] = {
|
||||
"title": "Keep a list or number type",
|
||||
"code": 'domains: "${state.domains}"\nlimit: "${state.limit}"',
|
||||
},
|
||||
{
|
||||
"title": "Use a default for missing text",
|
||||
"code": 'input: "Ticket ${text(state, \\"ticket.id\\", \\"unknown\\")}"',
|
||||
},
|
||||
),
|
||||
"json": (
|
||||
{
|
||||
@@ -141,14 +108,6 @@ FLOW_TEMPLATE_EXPRESSION_EXAMPLES: dict[str, tuple[dict[str, str], ...]] = {
|
||||
'{\n "domains": "${state.domains}",\n "limit": "${state.limit}"\n}'
|
||||
),
|
||||
},
|
||||
{
|
||||
"title": "Use a default for missing text",
|
||||
"code": (
|
||||
"{\n"
|
||||
' "input": "Ticket ${text(state, \\"ticket.id\\", \\"unknown\\")}"\n'
|
||||
"}"
|
||||
),
|
||||
},
|
||||
),
|
||||
}
|
||||
|
||||
@@ -374,8 +333,7 @@ class Expression:
|
||||
|
||||
environment = Environment()
|
||||
program = environment.program(
|
||||
Expression._compile_cel(expression, environment=environment),
|
||||
functions=_EXPRESSION_FUNCTIONS,
|
||||
Expression._compile_cel(expression, environment=environment)
|
||||
)
|
||||
result = program.evaluate(cast(Context, json_to_cel(context)))
|
||||
return json.loads(json.dumps(result, cls=CELJSONEncoder))
|
||||
|
||||
@@ -956,6 +956,22 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
|
||||
return self.memory.remember_many(content, **kwargs)
|
||||
return self.memory.remember(content, **kwargs)
|
||||
|
||||
def _drain_memory_writes(self) -> None:
|
||||
"""Block until pending background memory saves for this flow finish.
|
||||
|
||||
Must run before ``FlowFinishedEvent`` is emitted: listeners (e.g.
|
||||
telemetry sessions) tear down on that event, and any
|
||||
``MemorySaveCompletedEvent``/``MemorySaveFailedEvent`` emitted after
|
||||
teardown is lost, leaving the save span orphaned.
|
||||
"""
|
||||
mem = self.memory
|
||||
if mem is None:
|
||||
return
|
||||
backing = getattr(mem, "_memory", None) or mem
|
||||
drain = getattr(backing, "drain_writes", None)
|
||||
if callable(drain):
|
||||
drain()
|
||||
|
||||
def extract_memories(self, content: str) -> list[str]:
|
||||
"""Extract discrete memories from content. Delegates to this flow's memory.
|
||||
|
||||
@@ -1474,6 +1490,14 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
|
||||
not self.suppress_flow_events
|
||||
and not self._should_defer_trace_finalization()
|
||||
):
|
||||
# Background memory saves must finish (and emit their
|
||||
# completed/failed events) before flow-finished triggers
|
||||
# listener teardown/finalization; the flush then waits for those
|
||||
# events' async handlers, mirroring Crew._create_crew_output.
|
||||
# Offloaded to a thread so the blocking waits don't stall other
|
||||
# coroutines on the loop.
|
||||
await asyncio.to_thread(self._drain_memory_writes)
|
||||
await asyncio.to_thread(crewai_event_bus.flush)
|
||||
future = crewai_event_bus.emit(
|
||||
self,
|
||||
FlowFinishedEvent(
|
||||
@@ -2285,6 +2309,14 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
|
||||
# flag is read from either the instance attribute or an extension
|
||||
# definition.
|
||||
if not self._should_defer_trace_finalization():
|
||||
# Background memory saves must finish (and emit their
|
||||
# completed/failed events) before flow-finished triggers
|
||||
# listener teardown/finalization; the flush then waits for
|
||||
# those events' async handlers, mirroring
|
||||
# Crew._create_crew_output. Offloaded to a thread so the
|
||||
# blocking waits don't stall other coroutines on the loop.
|
||||
await asyncio.to_thread(self._drain_memory_writes)
|
||||
await asyncio.to_thread(crewai_event_bus.flush)
|
||||
future = crewai_event_bus.emit(
|
||||
self,
|
||||
FlowFinishedEvent(
|
||||
@@ -2317,9 +2349,9 @@ class Flow(BaseModel, Generic[T], metaclass=FlowMeta):
|
||||
|
||||
return final_output
|
||||
finally:
|
||||
# Ensure all background memory saves complete before returning
|
||||
if self.memory is not None and hasattr(self.memory, "drain_writes"):
|
||||
self.memory.drain_writes()
|
||||
# Safety net for the exception path; the success path already
|
||||
# drained before emitting FlowFinishedEvent.
|
||||
self._drain_memory_writes()
|
||||
# Drain pending LLMCallCompletedEvent handlers before
|
||||
# detaching so `flow.usage_metrics` reflects every call
|
||||
# emitted during this kickoff — mirrors `Crew.kickoff()`,
|
||||
|
||||
@@ -11,7 +11,6 @@ from jinja2 import Environment, FileSystemLoader
|
||||
import yaml
|
||||
|
||||
from crewai.flow.expressions import (
|
||||
FLOW_TEMPLATE_EXPRESSION_CONTRACT,
|
||||
FLOW_TEMPLATE_EXPRESSION_EXAMPLES,
|
||||
FLOW_TEMPLATE_EXPRESSION_RULES,
|
||||
)
|
||||
@@ -186,7 +185,14 @@ MODEL_SPECS: tuple[ModelSpec, ...] = (
|
||||
hidden=True,
|
||||
),
|
||||
ModelSpec("FlowScriptActionDefinition", "Action", "methods.<name>.do[call=script]"),
|
||||
ModelSpec("FlowToolActionDefinition", "Action", "methods.<name>.do[call=tool]"),
|
||||
ModelSpec(
|
||||
"FlowToolActionDefinition",
|
||||
"Action",
|
||||
"methods.<name>.do[call=tool]",
|
||||
descriptions={
|
||||
"with": "Tool input arguments. Insert Flow values with `${...}`.",
|
||||
},
|
||||
),
|
||||
ModelSpec(
|
||||
"FlowCrewActionDefinition",
|
||||
"Action",
|
||||
@@ -194,7 +200,7 @@ MODEL_SPECS: tuple[ModelSpec, ...] = (
|
||||
examples=True,
|
||||
descriptions={
|
||||
"call": "Action discriminator. Use crew to run an inline Crew definition.",
|
||||
"inputs": f"Actual kickoff inputs passed to the Crew. {FLOW_TEMPLATE_EXPRESSION_CONTRACT} The evaluated values are available to crew agent and task interpolation as `{{name}}` placeholders; reference each input the crew needs in agent or task text.",
|
||||
"inputs": "Runtime inputs passed to the Crew. Insert Flow values with `${...}` and reference each input as `{name}` in agent or task text.",
|
||||
},
|
||||
),
|
||||
ModelSpec(
|
||||
@@ -262,7 +268,7 @@ MODEL_SPECS: tuple[ModelSpec, ...] = (
|
||||
hidden=True,
|
||||
examples=True,
|
||||
descriptions={
|
||||
"input": f"Input passed to the individual agent kickoff outside of a crew. Use one string. {FLOW_TEMPLATE_EXPRESSION_CONTRACT} When an agent needs multiple fields, write one string with labels and separators, for example `Ticket ID: ${{state.ticket_id}}; Message: ${{state.message}}`.",
|
||||
"input": "Agent prompt template. Insert Flow values with `${...}`, for example `Ticket: ${state.ticket_id}`.",
|
||||
"llm": "Language model that runs this agent. Use an object when setting LLM options such as `max_tokens`.",
|
||||
"planning_config": "Agent planning configuration. Set `max_attempts` to limit planning refinement attempts before task execution.",
|
||||
},
|
||||
|
||||
@@ -46,6 +46,7 @@ Pick the simplest action that does the job.
|
||||
- Use `call: tool` for packaged deterministic work: API calls, searches, lookups, scoring, file work, or custom CrewAI tools.
|
||||
{% endif %}
|
||||
- Use `call: agent` for one AI worker that classifies, decides, summarizes, writes, or drafts. Put `role`, `goal`, `backstory`, and `input` under `with`. Do not add an action-level `inputs` map to an agent.
|
||||
- Repository-backed agents may set `from_repository` and omit inline `role`, `goal`, and `backstory`. Explicitly provided fields override repository values.
|
||||
- Use `call: crew` for coordinated AI work with multiple agents or tasks. Define the crew under `with`. Pass runtime values with the action-level `inputs` map.
|
||||
{% if include_each_action %}
|
||||
- Use `call: each` when the same ordered mini-pipeline must run once per item. Give every step a `name`.
|
||||
@@ -137,6 +138,7 @@ Dynamic value rules:
|
||||
- Do not use fields outside the declaration schema{% if include_tool_action %} or tool refs shown here{% endif %}.
|
||||
- Do not put more than one action under a method's `do`.
|
||||
- Do not make `do` a list.
|
||||
- Do not use CEL `+` to build text in action mappings. Keep the text literal and insert each dynamic value with `${...}`.
|
||||
- Do not reference `outputs.some_method` before `some_method` can run.
|
||||
- Do not set a method's `listen` to its own method name.
|
||||
- Do not use the same string for an emitted event and a method name unless the user asks for it.
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from crewai.types.usage_metrics import UsageMetrics
|
||||
from crewai.utilities.planning_types import TodoItem
|
||||
from crewai.utilities.types import LLMMessage
|
||||
|
||||
@@ -38,7 +39,13 @@ class LiteAgentOutput(BaseModel):
|
||||
)
|
||||
agent_role: str = Field(description="Role of the agent that produced this output")
|
||||
usage_metrics: dict[str, Any] | None = Field(
|
||||
description="Token usage metrics for this execution", default=None
|
||||
description=(
|
||||
"Token usage for this kickoff call only (guardrail retries "
|
||||
"included), not the LLM instance's cumulative totals, as a "
|
||||
"plain dict; ``token_usage`` exposes the same data as a "
|
||||
"UsageMetrics object"
|
||||
),
|
||||
default=None,
|
||||
)
|
||||
messages: list[LLMMessage] = Field(
|
||||
description="Messages of the agent", default_factory=list
|
||||
@@ -86,6 +93,19 @@ class LiteAgentOutput(BaseModel):
|
||||
return self.pydantic.model_dump()
|
||||
return {}
|
||||
|
||||
@property
|
||||
def token_usage(self) -> UsageMetrics:
|
||||
"""Token usage as a ``UsageMetrics`` object.
|
||||
|
||||
Same attribute name and type as ``CrewOutput.token_usage``, so a
|
||||
usage accessor written for one result type works on both. Returns
|
||||
zeroed metrics when no usage was captured (``usage_metrics`` is
|
||||
``None``).
|
||||
"""
|
||||
if not self.usage_metrics:
|
||||
return UsageMetrics()
|
||||
return UsageMetrics.model_validate(self.usage_metrics)
|
||||
|
||||
@property
|
||||
def completed_todos(self) -> list[TodoExecutionResult]:
|
||||
"""Get only the completed todos."""
|
||||
|
||||
@@ -394,19 +394,35 @@ class LLM(BaseLLM):
|
||||
"""Factory method that routes to native SDK or falls back to LiteLLM.
|
||||
|
||||
Routing priority:
|
||||
1. If 'provider' kwarg is present, use that provider with constants
|
||||
2. If only 'model' kwarg, use constants to infer provider
|
||||
3. If "/" in model name:
|
||||
1. If ``custom_openai=True``, force the native OpenAI provider,
|
||||
overriding any explicit provider. A custom endpoint is required.
|
||||
2. If ``provider`` is present, use that provider.
|
||||
3. If "/" is in the model name:
|
||||
- Check if prefix is a native provider (openai/anthropic/azure/bedrock/gemini)
|
||||
- If yes, validate model against constants
|
||||
- If valid, route to native SDK; otherwise route to LiteLLM
|
||||
4. Otherwise, infer the provider from the model name.
|
||||
"""
|
||||
if not model or not isinstance(model, str):
|
||||
raise ValueError("Model must be a non-empty string")
|
||||
|
||||
custom_openai = bool(kwargs.pop("custom_openai", False))
|
||||
custom_openai_route = custom_openai
|
||||
explicit_provider = kwargs.get("provider")
|
||||
|
||||
if explicit_provider:
|
||||
if custom_openai:
|
||||
if not cls._has_custom_openai_endpoint(kwargs):
|
||||
raise ValueError(
|
||||
"custom_openai=True requires base_url, api_base, "
|
||||
"OPENAI_BASE_URL, or OPENAI_API_BASE"
|
||||
)
|
||||
provider = "openai"
|
||||
use_native = True
|
||||
prefix, separator, model_part = model.partition("/")
|
||||
model_string = (
|
||||
model_part if separator and prefix.lower() == "openai" else model
|
||||
)
|
||||
elif explicit_provider:
|
||||
provider = explicit_provider
|
||||
use_native = True
|
||||
model_string = model
|
||||
@@ -435,9 +451,17 @@ class LLM(BaseLLM):
|
||||
|
||||
canonical_provider = provider_mapping.get(prefix.lower())
|
||||
|
||||
if canonical_provider and cls._validate_model_in_constants(
|
||||
model_part, canonical_provider
|
||||
):
|
||||
valid_native_model = bool(
|
||||
canonical_provider
|
||||
and cls._validate_model_in_constants(model_part, canonical_provider)
|
||||
)
|
||||
custom_openai_route = bool(
|
||||
canonical_provider == "openai"
|
||||
and not valid_native_model
|
||||
and cls._has_custom_openai_base_url(kwargs)
|
||||
)
|
||||
|
||||
if canonical_provider and (valid_native_model or custom_openai_route):
|
||||
provider = canonical_provider
|
||||
use_native = True
|
||||
model_string = model_part
|
||||
@@ -455,6 +479,8 @@ class LLM(BaseLLM):
|
||||
try:
|
||||
# Remove 'provider' from kwargs if it exists to avoid duplicate keyword argument
|
||||
kwargs_copy = {k: v for k, v in kwargs.items() if k != "provider"}
|
||||
if custom_openai_route:
|
||||
kwargs_copy["custom_openai"] = True
|
||||
return cast(
|
||||
Self,
|
||||
native_class(model=model_string, provider=provider, **kwargs_copy),
|
||||
@@ -590,6 +616,20 @@ class LLM(BaseLLM):
|
||||
|
||||
return cls._matches_provider_pattern(model, provider)
|
||||
|
||||
@staticmethod
|
||||
def _has_custom_openai_base_url(kwargs: dict[str, Any]) -> bool:
|
||||
"""Return whether this call explicitly configures a custom endpoint."""
|
||||
return bool(kwargs.get("base_url") or kwargs.get("api_base"))
|
||||
|
||||
@classmethod
|
||||
def _has_custom_openai_endpoint(cls, kwargs: dict[str, Any]) -> bool:
|
||||
"""Return whether a custom endpoint is configured explicitly or by env."""
|
||||
return bool(
|
||||
cls._has_custom_openai_base_url(kwargs)
|
||||
or os.getenv("OPENAI_BASE_URL")
|
||||
or os.getenv("OPENAI_API_BASE")
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _infer_provider_from_model(cls, model: str) -> str:
|
||||
"""Infer the provider from the model name.
|
||||
|
||||
@@ -966,8 +966,15 @@ class BaseLLM(BaseModel, ABC):
|
||||
def get_token_usage_summary(self) -> UsageMetrics:
|
||||
"""Get summary of token usage for this LLM instance.
|
||||
|
||||
The counters are cumulative for the lifetime of this instance: they
|
||||
grow across every call made through it, including calls issued by
|
||||
different agents sharing the instance. For usage scoped to a single
|
||||
call, snapshot before and after and use
|
||||
``UsageMetrics.delta_since`` (agent kickoff results already report
|
||||
per-call usage this way).
|
||||
|
||||
Returns:
|
||||
Dictionary with token usage totals
|
||||
UsageMetrics with this instance's lifetime token usage totals.
|
||||
"""
|
||||
return UsageMetrics(**self._token_usage)
|
||||
|
||||
|
||||
@@ -232,6 +232,7 @@ class OpenAICompletion(BaseLLM):
|
||||
auto_chain: bool = False
|
||||
auto_chain_reasoning: bool = False
|
||||
api_base: str | None = None
|
||||
custom_openai: bool = False
|
||||
is_o1_model: bool = False
|
||||
is_gpt4_model: bool = False
|
||||
|
||||
@@ -245,6 +246,20 @@ class OpenAICompletion(BaseLLM):
|
||||
def _normalize_openai_fields(cls, data: Any) -> Any:
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
if data.get("custom_openai"):
|
||||
custom_base_url = (
|
||||
data.get("base_url")
|
||||
or data.get("api_base")
|
||||
or os.getenv("OPENAI_BASE_URL")
|
||||
or os.getenv("OPENAI_API_BASE")
|
||||
)
|
||||
if not custom_base_url:
|
||||
raise ValueError(
|
||||
"custom_openai=True requires base_url, api_base, "
|
||||
"OPENAI_BASE_URL, or OPENAI_API_BASE"
|
||||
)
|
||||
if not data.get("base_url") and not data.get("api_base"):
|
||||
data["base_url"] = custom_base_url
|
||||
if not data.get("provider"):
|
||||
data["provider"] = "openai"
|
||||
data["api_key"] = data.get("api_key") or os.getenv("OPENAI_API_KEY")
|
||||
@@ -355,6 +370,15 @@ class OpenAICompletion(BaseLLM):
|
||||
config["seed"] = self.seed
|
||||
if self.reasoning_effort is not None:
|
||||
config["reasoning_effort"] = self.reasoning_effort
|
||||
if self.custom_openai:
|
||||
config["model"] = self.model
|
||||
config["custom_openai"] = True
|
||||
config["base_url"] = (
|
||||
self.base_url
|
||||
or self.api_base
|
||||
or os.getenv("OPENAI_BASE_URL")
|
||||
or os.getenv("OPENAI_API_BASE")
|
||||
)
|
||||
return config
|
||||
|
||||
def _get_client_params(self) -> dict[str, Any]:
|
||||
@@ -372,6 +396,7 @@ class OpenAICompletion(BaseLLM):
|
||||
"base_url": self.base_url
|
||||
or self.api_base
|
||||
or os.getenv("OPENAI_BASE_URL")
|
||||
or os.getenv("OPENAI_API_BASE")
|
||||
or None,
|
||||
"timeout": self.timeout,
|
||||
"max_retries": self.max_retries,
|
||||
|
||||
@@ -5,7 +5,6 @@ import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
import importlib
|
||||
from inspect import Parameter, signature
|
||||
import json
|
||||
import threading
|
||||
from typing import (
|
||||
Any,
|
||||
@@ -37,9 +36,9 @@ from crewai.tools.structured_tool import (
|
||||
_infer_result_schema_from_callable,
|
||||
_serialize_schema,
|
||||
build_schema_hint,
|
||||
format_description_for_llm,
|
||||
)
|
||||
from crewai.types.callback import SerializableCallable, _resolve_dotted_path
|
||||
from crewai.utilities.pydantic_schema_utils import generate_model_description
|
||||
from crewai.utilities.string_utils import sanitize_tool_name
|
||||
|
||||
|
||||
@@ -479,15 +478,27 @@ class BaseTool(BaseModel, ABC):
|
||||
f"{self.__class__.__name__}Schema", **fields
|
||||
)
|
||||
|
||||
@property
|
||||
def formatted_description(self) -> str:
|
||||
"""LLM-facing composite of name, argument schema, and description.
|
||||
|
||||
Use this when rendering the tool into a prompt; ``description``
|
||||
holds only the authored text.
|
||||
"""
|
||||
return format_description_for_llm(self.name, self.args_schema, self.description)
|
||||
|
||||
def _generate_description(self) -> None:
|
||||
"""Generate the tool description with a JSON schema for arguments."""
|
||||
schema = generate_model_description(self.args_schema)
|
||||
args_json = json.dumps(schema["json_schema"]["schema"], indent=2)
|
||||
self.description = (
|
||||
f"Tool Name: {sanitize_tool_name(self.name)}\n"
|
||||
f"Tool Arguments: {args_json}\n"
|
||||
f"Tool Description: {self.description}"
|
||||
)
|
||||
"""Deprecated hook kept for backward compatibility; does nothing.
|
||||
|
||||
Historically this rewrote the public ``description`` field at
|
||||
construction time into the LLM-facing composite (``Tool Name: …\\n
|
||||
Tool Arguments: …\\nTool Description: <authored>``). The authored
|
||||
``description`` is now preserved as written and the composite is
|
||||
exposed separately via :attr:`formatted_description`.
|
||||
|
||||
``model_post_init`` still calls this so subclasses that override it
|
||||
(e.g. adapters that customize the composite) keep working.
|
||||
"""
|
||||
|
||||
|
||||
_BASE_TOOL_CLS = BaseTool
|
||||
|
||||
@@ -4,6 +4,7 @@ import asyncio
|
||||
from collections.abc import Callable
|
||||
import inspect
|
||||
import json
|
||||
import re
|
||||
import textwrap
|
||||
from typing import TYPE_CHECKING, Annotated, Any, cast, get_type_hints
|
||||
import warnings
|
||||
@@ -21,7 +22,10 @@ from pydantic import (
|
||||
from typing_extensions import Self
|
||||
|
||||
from crewai.utilities.logger import Logger
|
||||
from crewai.utilities.pydantic_schema_utils import create_model_from_schema
|
||||
from crewai.utilities.pydantic_schema_utils import (
|
||||
create_model_from_schema,
|
||||
generate_model_description,
|
||||
)
|
||||
from crewai.utilities.string_utils import sanitize_tool_name
|
||||
|
||||
|
||||
@@ -108,6 +112,70 @@ def build_schema_hint(args_schema: type[BaseModel]) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
# Matches a description that IS a pre-composed LLM block (as written by
|
||||
# older versions into the field, and by adapters that still bake it in).
|
||||
# Anchored to the full three-line shape so authored prose that merely
|
||||
# mentions "Tool Description:" is never mistaken for a composite. Greedy
|
||||
# ``.*`` keeps only the text after the LAST marker, matching the historical
|
||||
# split behavior for nested pre-baked blocks.
|
||||
_COMPOSITE_DESCRIPTION_RE = re.compile(
|
||||
r"^Tool Name:.*\nTool Arguments:.*\nTool Description:\s*",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def strip_composite_description_prefix(description: str) -> str:
|
||||
"""Return the authored text from a pre-composed LLM description block.
|
||||
|
||||
Descriptions that don't start with the composite shape are returned
|
||||
unchanged.
|
||||
"""
|
||||
match = _COMPOSITE_DESCRIPTION_RE.match(description)
|
||||
if match:
|
||||
return description[match.end() :]
|
||||
return description
|
||||
|
||||
|
||||
def format_description_for_llm(
|
||||
name: str,
|
||||
args_schema: type[BaseModel] | None,
|
||||
description: str,
|
||||
) -> str:
|
||||
"""Compose the LLM-facing tool description.
|
||||
|
||||
Combines the tool name, its argument JSON schema, and the authored
|
||||
description into the prompt block agents see. The authored
|
||||
``description`` field itself is never mutated — prompt rendering calls
|
||||
this on demand.
|
||||
|
||||
Idempotent: if ``description`` already *is* a composed block (e.g. a
|
||||
tool deserialized from a checkpoint written by an older version, or an
|
||||
adapter that bakes the composite into the field), only the authored
|
||||
text after the marker is used. The check is anchored to the composite
|
||||
shape, so authored prose that merely mentions ``"Tool Description:"``
|
||||
passes through untouched.
|
||||
|
||||
Args:
|
||||
name: The tool name (sanitized for the prompt).
|
||||
args_schema: The tool's argument schema, if any.
|
||||
description: The authored tool description.
|
||||
|
||||
Returns:
|
||||
The composed, LLM-facing description block.
|
||||
"""
|
||||
description = strip_composite_description_prefix(description)
|
||||
if args_schema is not None:
|
||||
schema = generate_model_description(args_schema)
|
||||
args_json = json.dumps(schema["json_schema"]["schema"], indent=2)
|
||||
else:
|
||||
args_json = "{}"
|
||||
return (
|
||||
f"Tool Name: {sanitize_tool_name(name)}\n"
|
||||
f"Tool Arguments: {args_json}\n"
|
||||
f"Tool Description: {description}"
|
||||
)
|
||||
|
||||
|
||||
class ToolUsageLimitExceededError(Exception):
|
||||
"""Exception raised when a tool has reached its maximum usage limit."""
|
||||
|
||||
@@ -141,6 +209,15 @@ class CrewStructuredTool(BaseModel):
|
||||
_logger: Logger = PrivateAttr(default_factory=Logger)
|
||||
_original_tool: Any = PrivateAttr(default=None)
|
||||
|
||||
@property
|
||||
def formatted_description(self) -> str:
|
||||
"""LLM-facing composite of name, argument schema, and description.
|
||||
|
||||
Use this when rendering the tool into a prompt; ``description``
|
||||
holds only the authored text.
|
||||
"""
|
||||
return format_description_for_llm(self.name, self.args_schema, self.description)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_func(self) -> Self:
|
||||
if self.func is not None:
|
||||
|
||||
@@ -430,7 +430,7 @@ class ToolUsage:
|
||||
).format(
|
||||
error=e,
|
||||
tool=sanitize_tool_name(tool.name),
|
||||
tool_inputs=tool.description,
|
||||
tool_inputs=tool.formatted_description,
|
||||
)
|
||||
result = ToolUsageError(
|
||||
f"\n{error_message}.\nMoving on then. {I18N_DEFAULT.slice('format').format(tool_names=self.tools_names)}"
|
||||
@@ -670,7 +670,7 @@ class ToolUsage:
|
||||
).format(
|
||||
error=e,
|
||||
tool=sanitize_tool_name(tool.name),
|
||||
tool_inputs=tool.description,
|
||||
tool_inputs=tool.formatted_description,
|
||||
)
|
||||
result = ToolUsageError(
|
||||
f"\n{error_message}.\nMoving on then. {I18N_DEFAULT.slice('format').format(tool_names=self.tools_names)}"
|
||||
@@ -803,7 +803,7 @@ class ToolUsage:
|
||||
|
||||
def _render(self) -> str:
|
||||
"""Render the tool name and description in plain text."""
|
||||
descriptions = [tool.description for tool in self.tools]
|
||||
descriptions = [tool.formatted_description for tool in self.tools]
|
||||
return "\n--\n".join(descriptions)
|
||||
|
||||
def _function_calling(
|
||||
|
||||
@@ -76,6 +76,38 @@ class UsageMetrics(BaseModel):
|
||||
self.cache_creation_tokens += usage_metrics.cache_creation_tokens
|
||||
self.successful_requests += usage_metrics.successful_requests
|
||||
|
||||
def delta_since(self, baseline: Self) -> Self:
|
||||
"""Return the per-call usage accrued since ``baseline`` was captured.
|
||||
|
||||
Both objects must come from the same monotonically increasing
|
||||
accumulator (e.g. an LLM instance's lifetime counters). Differences
|
||||
are clamped at zero so a reset accumulator can't produce negative
|
||||
usage.
|
||||
|
||||
Args:
|
||||
baseline: A snapshot of the same accumulator taken earlier.
|
||||
|
||||
Returns:
|
||||
A new UsageMetrics with the field-wise difference.
|
||||
"""
|
||||
return type(self)(
|
||||
total_tokens=max(0, self.total_tokens - baseline.total_tokens),
|
||||
prompt_tokens=max(0, self.prompt_tokens - baseline.prompt_tokens),
|
||||
cached_prompt_tokens=max(
|
||||
0, self.cached_prompt_tokens - baseline.cached_prompt_tokens
|
||||
),
|
||||
completion_tokens=max(
|
||||
0, self.completion_tokens - baseline.completion_tokens
|
||||
),
|
||||
reasoning_tokens=max(0, self.reasoning_tokens - baseline.reasoning_tokens),
|
||||
cache_creation_tokens=max(
|
||||
0, self.cache_creation_tokens - baseline.cache_creation_tokens
|
||||
),
|
||||
successful_requests=max(
|
||||
0, self.successful_requests - baseline.successful_requests
|
||||
),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_provider_dict(cls, usage_data: dict[str, Any] | None) -> Self | None:
|
||||
"""Normalize a provider's raw usage dict into a ``UsageMetrics``.
|
||||
|
||||
@@ -27,7 +27,10 @@ from crewai.agents.parser import (
|
||||
from crewai.llms.base_llm import BaseLLM, call_stop_override
|
||||
from crewai.tools import BaseTool as CrewAITool
|
||||
from crewai.tools.base_tool import BaseTool
|
||||
from crewai.tools.structured_tool import CrewStructuredTool
|
||||
from crewai.tools.structured_tool import (
|
||||
CrewStructuredTool,
|
||||
strip_composite_description_prefix,
|
||||
)
|
||||
from crewai.tools.tool_types import ToolResult
|
||||
from crewai.utilities.errors import AgentRepositoryError
|
||||
from crewai.utilities.exceptions.context_window_exceeding_exception import (
|
||||
@@ -147,7 +150,14 @@ def render_text_description_and_args(
|
||||
Returns:
|
||||
Plain text description of tools.
|
||||
"""
|
||||
tool_strings = [tool.description for tool in tools]
|
||||
# Fall back to the raw description for duck-typed tools (including test
|
||||
# mocks) that don't provide a real formatted_description string.
|
||||
tool_strings = [
|
||||
formatted
|
||||
if isinstance((formatted := getattr(tool, "formatted_description", None)), str)
|
||||
else tool.description
|
||||
for tool in tools
|
||||
]
|
||||
return "\n".join(tool_strings)
|
||||
|
||||
|
||||
@@ -190,10 +200,10 @@ def convert_tools_to_openai_schema(
|
||||
except Exception:
|
||||
parameters = {}
|
||||
|
||||
# BaseTool formats description as "Tool Name: ...\nTool Arguments: ...\nTool Description: {original}"
|
||||
description = tool.description
|
||||
if "Tool Description:" in description:
|
||||
description = description.split("Tool Description:")[-1].strip()
|
||||
# Old checkpoints and some adapters bake the composed LLM block
|
||||
# ("Tool Name: ...\nTool Arguments: ...\nTool Description: {authored}")
|
||||
# into the description field; keep only the authored text here.
|
||||
description = strip_composite_description_prefix(tool.description)
|
||||
|
||||
sanitized_name = sanitize_tool_name(tool.name)
|
||||
|
||||
|
||||
@@ -1138,3 +1138,160 @@ def test_lite_agent_memory_instance_recall_and_save_called():
|
||||
mock_memory.remember_many.assert_called_once_with(
|
||||
["Fact one.", "Fact two."], agent_role="Test"
|
||||
)
|
||||
|
||||
|
||||
class _FixedUsageLLM(BaseLLM):
|
||||
"""Offline BaseLLM that records fixed usage (100/10 tokens) per call."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(model="fixed-usage-model")
|
||||
|
||||
def call(
|
||||
self,
|
||||
messages,
|
||||
tools=None,
|
||||
callbacks=None,
|
||||
available_functions=None,
|
||||
from_task=None,
|
||||
from_agent=None,
|
||||
response_model=None,
|
||||
) -> str:
|
||||
self._track_token_usage_internal(
|
||||
{"prompt_tokens": 100, "completion_tokens": 10, "total_tokens": 110}
|
||||
)
|
||||
return "Thought: I know the answer.\nFinal Answer: fake answer"
|
||||
|
||||
def supports_function_calling(self) -> bool:
|
||||
return False
|
||||
|
||||
def supports_stop_words(self) -> bool:
|
||||
return False
|
||||
|
||||
def get_context_window_size(self) -> int:
|
||||
return 4096
|
||||
|
||||
|
||||
class TestKickoffUsageMetricsArePerCall:
|
||||
"""Regression tests for EPD-177: kickoff results used to expose the LLM
|
||||
instance's cumulative lifetime counters, so counts accumulated across
|
||||
calls and pooled across agents sharing one LLM object.
|
||||
"""
|
||||
|
||||
def _make_agent(self, role: str, llm: BaseLLM) -> Agent:
|
||||
return Agent(
|
||||
role=role,
|
||||
goal="Answer questions.",
|
||||
backstory="Test agent.",
|
||||
llm=llm,
|
||||
verbose=False,
|
||||
)
|
||||
|
||||
def test_agents_sharing_one_llm_report_per_call_usage(self):
|
||||
shared = _FixedUsageLLM()
|
||||
r1 = self._make_agent("agent one", shared).kickoff("question one")
|
||||
r2 = self._make_agent("agent two", shared).kickoff("question two")
|
||||
|
||||
assert r1.usage_metrics is not None
|
||||
assert r1.usage_metrics["prompt_tokens"] > 0
|
||||
# The second agent's call must not include the first agent's tokens.
|
||||
assert r2.usage_metrics == r1.usage_metrics
|
||||
|
||||
# The shared LLM instance still exposes cumulative lifetime totals.
|
||||
lifetime = shared.get_token_usage_summary()
|
||||
assert lifetime.prompt_tokens == (
|
||||
r1.usage_metrics["prompt_tokens"] + r2.usage_metrics["prompt_tokens"]
|
||||
)
|
||||
assert lifetime.successful_requests == (
|
||||
r1.usage_metrics["successful_requests"]
|
||||
+ r2.usage_metrics["successful_requests"]
|
||||
)
|
||||
|
||||
def test_repeated_kickoffs_on_same_agent_report_per_call_usage(self):
|
||||
agent = self._make_agent("agent", _FixedUsageLLM())
|
||||
r1 = agent.kickoff("question one")
|
||||
r2 = agent.kickoff("question two")
|
||||
|
||||
assert r1.usage_metrics is not None
|
||||
assert r1.usage_metrics["prompt_tokens"] > 0
|
||||
assert r2.usage_metrics == r1.usage_metrics
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_kickoff_reports_per_call_usage(self):
|
||||
shared = _FixedUsageLLM()
|
||||
r1 = await self._make_agent("agent one", shared).kickoff_async("question one")
|
||||
r2 = await self._make_agent("agent two", shared).kickoff_async("question two")
|
||||
|
||||
assert r1.usage_metrics is not None
|
||||
assert r1.usage_metrics["prompt_tokens"] > 0
|
||||
assert r2.usage_metrics == r1.usage_metrics
|
||||
|
||||
def test_guardrail_retry_usage_includes_all_attempts(self):
|
||||
"""A guardrail retry re-invokes the LLM within the same kickoff, so
|
||||
the result must report the whole call's usage — every attempt — not
|
||||
just the last one."""
|
||||
baseline = (
|
||||
self._make_agent("baseline", _FixedUsageLLM())
|
||||
.kickoff("question one")
|
||||
.usage_metrics
|
||||
)
|
||||
|
||||
attempts: list[str] = []
|
||||
|
||||
def flaky_guardrail(output):
|
||||
attempts.append(output.raw)
|
||||
if len(attempts) == 1:
|
||||
return (False, "Please try again.")
|
||||
return (True, output.raw)
|
||||
|
||||
agent = Agent(
|
||||
role="agent",
|
||||
goal="Answer questions.",
|
||||
backstory="Test agent.",
|
||||
llm=_FixedUsageLLM(),
|
||||
guardrail=flaky_guardrail,
|
||||
verbose=False,
|
||||
)
|
||||
result = agent.kickoff("question one")
|
||||
|
||||
assert len(attempts) == 2
|
||||
assert result.usage_metrics["successful_requests"] == (
|
||||
2 * baseline["successful_requests"]
|
||||
)
|
||||
assert result.usage_metrics["prompt_tokens"] == 2 * baseline["prompt_tokens"]
|
||||
assert result.usage_metrics["total_tokens"] == 2 * baseline["total_tokens"]
|
||||
|
||||
|
||||
class TestUsageMetricsDeltaSince:
|
||||
def test_field_wise_difference(self):
|
||||
baseline = UsageMetrics(
|
||||
total_tokens=110,
|
||||
prompt_tokens=100,
|
||||
completion_tokens=10,
|
||||
successful_requests=1,
|
||||
)
|
||||
current = UsageMetrics(
|
||||
total_tokens=330,
|
||||
prompt_tokens=300,
|
||||
completion_tokens=30,
|
||||
cached_prompt_tokens=5,
|
||||
reasoning_tokens=7,
|
||||
cache_creation_tokens=3,
|
||||
successful_requests=3,
|
||||
)
|
||||
|
||||
delta = current.delta_since(baseline)
|
||||
|
||||
assert delta == UsageMetrics(
|
||||
total_tokens=220,
|
||||
prompt_tokens=200,
|
||||
completion_tokens=20,
|
||||
cached_prompt_tokens=5,
|
||||
reasoning_tokens=7,
|
||||
cache_creation_tokens=3,
|
||||
successful_requests=2,
|
||||
)
|
||||
|
||||
def test_clamps_negative_differences_to_zero(self):
|
||||
baseline = UsageMetrics(total_tokens=100, prompt_tokens=90, successful_requests=2)
|
||||
delta = UsageMetrics().delta_since(baseline)
|
||||
assert delta == UsageMetrics()
|
||||
|
||||
@@ -30,10 +30,156 @@ def test_openai_completion_is_used_when_no_provider_prefix():
|
||||
llm = LLM(model="gpt-4o")
|
||||
|
||||
from crewai.llms.providers.openai.completion import OpenAICompletion
|
||||
assert isinstance(llm, OpenAICompletion)
|
||||
assert llm.__class__.__name__ == "OpenAICompletion"
|
||||
assert llm.provider == "openai"
|
||||
assert llm.model == "gpt-4o"
|
||||
|
||||
|
||||
def test_custom_openai_flag_uses_native_openai_without_provider_prefix():
|
||||
"""Custom OpenAI-compatible endpoints can serve arbitrary model ids."""
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}, clear=False):
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
base_url="https://gateway.example/v1",
|
||||
is_litellm=False,
|
||||
)
|
||||
|
||||
assert llm.__class__.__name__ == "OpenAICompletion"
|
||||
assert llm.is_litellm is False
|
||||
assert llm.provider == "openai"
|
||||
assert llm.model == "anthropic/claude-sonnet-4-6"
|
||||
assert llm.base_url == "https://gateway.example/v1"
|
||||
assert llm.custom_openai is True
|
||||
assert "custom_openai" not in llm.additional_params
|
||||
|
||||
config = llm.to_config_dict()
|
||||
assert config["model"] == "anthropic/claude-sonnet-4-6"
|
||||
assert config["custom_openai"] is True
|
||||
assert config["base_url"] == "https://gateway.example/v1"
|
||||
|
||||
rebuilt = LLM(**config)
|
||||
assert isinstance(rebuilt, OpenAICompletion)
|
||||
assert rebuilt.model == "anthropic/claude-sonnet-4-6"
|
||||
assert rebuilt.base_url == "https://gateway.example/v1"
|
||||
|
||||
|
||||
def test_custom_openai_flag_requires_custom_base_url():
|
||||
"""Avoid routing arbitrary custom model ids to api.openai.com by mistake."""
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}, clear=True):
|
||||
with pytest.raises(ValueError, match="custom_openai=True requires"):
|
||||
LLM(
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
is_litellm=False,
|
||||
)
|
||||
|
||||
|
||||
def test_direct_custom_openai_completion_requires_custom_base_url():
|
||||
"""Direct construction must not silently fall back to api.openai.com."""
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}, clear=True):
|
||||
with pytest.raises(ValueError, match="custom_openai=True requires"):
|
||||
OpenAICompletion(
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
)
|
||||
|
||||
|
||||
def test_custom_openai_flag_strips_openai_routing_prefix():
|
||||
"""The openai/ routing prefix is not part of the gateway's model id."""
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}, clear=False):
|
||||
llm = LLM(
|
||||
model="openai/anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
base_url="https://gateway.example/v1",
|
||||
is_litellm=False,
|
||||
)
|
||||
|
||||
assert isinstance(llm, OpenAICompletion)
|
||||
assert llm.model == "anthropic/claude-sonnet-4-6"
|
||||
|
||||
|
||||
def test_openai_prefixed_custom_endpoint_uses_native_sdk_for_nested_model_id():
|
||||
"""Custom OpenAI-compatible endpoints may serve non-OpenAI model ids."""
|
||||
with patch.dict(os.environ, {"OPENAI_API_KEY": "test-key"}, clear=False):
|
||||
llm = LLM(
|
||||
model="openai/anthropic/claude-sonnet-4-6",
|
||||
base_url="https://gateway.example/v1",
|
||||
is_litellm=False,
|
||||
)
|
||||
|
||||
assert llm.__class__.__name__ == "OpenAICompletion"
|
||||
assert llm.is_litellm is False
|
||||
assert llm.provider == "openai"
|
||||
assert llm.model == "anthropic/claude-sonnet-4-6"
|
||||
assert llm.custom_openai is True
|
||||
assert llm.base_url == "https://gateway.example/v1"
|
||||
|
||||
def test_explicit_custom_openai_uses_legacy_api_base_env_var():
|
||||
"""Explicit custom routing supports the legacy endpoint environment variable."""
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OPENAI_API_KEY": "test-key",
|
||||
"OPENAI_API_BASE": "https://gateway.example/v1",
|
||||
},
|
||||
clear=False,
|
||||
):
|
||||
os.environ.pop("OPENAI_BASE_URL", None)
|
||||
llm = LLM(
|
||||
model="openai/anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
is_litellm=False,
|
||||
)
|
||||
|
||||
assert isinstance(llm, OpenAICompletion)
|
||||
assert llm.is_litellm is False
|
||||
assert llm.provider == "openai"
|
||||
assert llm.model == "anthropic/claude-sonnet-4-6"
|
||||
assert llm.custom_openai is True
|
||||
|
||||
|
||||
def test_openai_prefixed_unknown_model_ignores_ambient_base_url_for_routing():
|
||||
"""Ambient OpenAI configuration must not opt unknown models into native routing."""
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
"OPENAI_API_KEY": "test-key",
|
||||
"OPENAI_BASE_URL": "https://gateway.example/v1",
|
||||
},
|
||||
clear=True,
|
||||
):
|
||||
with (
|
||||
patch("crewai.llm._ensure_litellm", return_value=False),
|
||||
pytest.raises(ImportError, match="LiteLLM fallback package"),
|
||||
):
|
||||
LLM(model="openai/not-a-real-openai-model")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("endpoint_field", ["api_base", "env"])
|
||||
def test_custom_openai_config_preserves_resolved_endpoint(endpoint_field):
|
||||
"""Serialized custom OpenAI configs can reconstruct the same endpoint."""
|
||||
kwargs = {}
|
||||
env = {"OPENAI_API_KEY": "test-key"}
|
||||
if endpoint_field == "api_base":
|
||||
kwargs["api_base"] = "https://gateway.example/v1"
|
||||
else:
|
||||
env["OPENAI_API_BASE"] = "https://gateway.example/v1"
|
||||
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
config = llm.to_config_dict()
|
||||
assert config["base_url"] == "https://gateway.example/v1"
|
||||
rebuilt = LLM(**config)
|
||||
assert isinstance(rebuilt, OpenAICompletion)
|
||||
assert rebuilt.base_url == "https://gateway.example/v1"
|
||||
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_openai_is_default_provider_without_explicit_llm_set_on_agent():
|
||||
"""
|
||||
@@ -60,14 +206,13 @@ def test_openai_is_default_provider_without_explicit_llm_set_on_agent():
|
||||
|
||||
|
||||
|
||||
def test_openai_completion_module_is_imported():
|
||||
def test_openai_completion_module_is_imported(monkeypatch):
|
||||
"""
|
||||
Test that the completion module is properly imported when using OpenAI provider
|
||||
"""
|
||||
module_name = "crewai.llms.providers.openai.completion"
|
||||
|
||||
if module_name in sys.modules:
|
||||
del sys.modules[module_name]
|
||||
monkeypatch.delitem(sys.modules, module_name, raising=False)
|
||||
|
||||
LLM(model="gpt-4o")
|
||||
|
||||
@@ -421,12 +566,25 @@ def test_openai_get_client_params_with_env_var():
|
||||
client_params = llm._get_client_params()
|
||||
assert client_params["base_url"] == "https://env.openai.com/v1"
|
||||
|
||||
def test_openai_get_client_params_with_legacy_api_base_env_var():
|
||||
"""
|
||||
Test that _get_client_params uses OPENAI_API_BASE when OPENAI_BASE_URL is absent.
|
||||
"""
|
||||
with patch.dict(os.environ, {
|
||||
"OPENAI_API_BASE": "https://legacy-env.openai.com/v1",
|
||||
}, clear=False):
|
||||
os.environ.pop("OPENAI_BASE_URL", None)
|
||||
llm = OpenAICompletion(model="gpt-4o")
|
||||
client_params = llm._get_client_params()
|
||||
assert client_params["base_url"] == "https://legacy-env.openai.com/v1"
|
||||
|
||||
def test_openai_get_client_params_priority_order():
|
||||
"""
|
||||
Test the priority order: base_url > api_base > OPENAI_BASE_URL env var
|
||||
Test the priority order: base_url > api_base > OPENAI_BASE_URL > OPENAI_API_BASE
|
||||
"""
|
||||
with patch.dict(os.environ, {
|
||||
"OPENAI_BASE_URL": "https://env.openai.com/v1",
|
||||
"OPENAI_API_BASE": "https://legacy-env.openai.com/v1",
|
||||
}):
|
||||
llm1 = OpenAICompletion(
|
||||
model="gpt-4o",
|
||||
|
||||
@@ -859,6 +859,7 @@ def test_cache_hitting_between_agents(researcher, writer, ceo):
|
||||
crew = Crew(
|
||||
agents=[ceo, researcher],
|
||||
tasks=tasks,
|
||||
cache=True,
|
||||
)
|
||||
|
||||
with patch.object(CacheHandler, "read") as read:
|
||||
@@ -2246,7 +2247,9 @@ def test_tools_with_custom_caching():
|
||||
agent=writer2,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[writer1, writer2], tasks=[task1, task2, task3, task4])
|
||||
crew = Crew(
|
||||
agents=[writer1, writer2], tasks=[task1, task2, task3, task4], cache=True
|
||||
)
|
||||
|
||||
with patch.object(
|
||||
CacheHandler, "add", wraps=crew._cache_handler.add
|
||||
@@ -4598,6 +4601,98 @@ def test_reset_memory_uses_full_unified_memory_reset(researcher):
|
||||
reset.assert_not_called()
|
||||
|
||||
|
||||
def test_kickoff_drains_pending_memory_saves_before_completion_event(researcher):
|
||||
"""Background memory saves must finish (and emit their completion events)
|
||||
before CrewKickoffCompletedEvent, otherwise listeners that tear down on
|
||||
kickoff-completed (e.g. telemetry sessions) see the save span as orphaned."""
|
||||
import time
|
||||
|
||||
from crewai.events.types.crew_events import CrewKickoffCompletedEvent
|
||||
|
||||
order: list[str] = []
|
||||
|
||||
def slow_save():
|
||||
time.sleep(0.3)
|
||||
order.append("save-done")
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
process=Process.sequential,
|
||||
tasks=[
|
||||
Task(description="Task 1", expected_output="output", agent=researcher),
|
||||
],
|
||||
memory=True,
|
||||
task_callback=lambda _output: crew._memory._submit_save(slow_save),
|
||||
)
|
||||
|
||||
completed = threading.Event()
|
||||
|
||||
with crewai_event_bus.scoped_handlers():
|
||||
|
||||
@crewai_event_bus.on(CrewKickoffCompletedEvent)
|
||||
def on_completed(_source, _event):
|
||||
order.append("kickoff-completed")
|
||||
completed.set()
|
||||
|
||||
with patch.object(Agent, "execute_task", return_value="ok"):
|
||||
crew.kickoff()
|
||||
|
||||
assert completed.wait(timeout=5)
|
||||
|
||||
assert order.index("save-done") < order.index("kickoff-completed")
|
||||
|
||||
|
||||
def test_kickoff_drains_agent_memory_saves_before_completion_event(tmp_path):
|
||||
"""Agents save through their own ``agent.memory`` when set; those pools
|
||||
must also be drained before CrewKickoffCompletedEvent."""
|
||||
import time
|
||||
|
||||
from crewai.events.types.crew_events import CrewKickoffCompletedEvent
|
||||
|
||||
agent_memory = Memory(storage=str(tmp_path / "agent-mem"))
|
||||
agent_with_memory = Agent(
|
||||
role="Researcher",
|
||||
goal="Research things",
|
||||
backstory="Experienced researcher",
|
||||
memory=agent_memory,
|
||||
)
|
||||
|
||||
order: list[str] = []
|
||||
|
||||
def slow_save():
|
||||
time.sleep(0.3)
|
||||
order.append("save-done")
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent_with_memory],
|
||||
process=Process.sequential,
|
||||
tasks=[
|
||||
Task(
|
||||
description="Task 1",
|
||||
expected_output="output",
|
||||
agent=agent_with_memory,
|
||||
),
|
||||
],
|
||||
task_callback=lambda _output: agent_memory._submit_save(slow_save),
|
||||
)
|
||||
|
||||
completed = threading.Event()
|
||||
|
||||
with crewai_event_bus.scoped_handlers():
|
||||
|
||||
@crewai_event_bus.on(CrewKickoffCompletedEvent)
|
||||
def on_completed(_source, _event):
|
||||
order.append("kickoff-completed")
|
||||
completed.set()
|
||||
|
||||
with patch.object(Agent, "execute_task", return_value="ok"):
|
||||
crew.kickoff()
|
||||
|
||||
assert completed.wait(timeout=5)
|
||||
|
||||
assert order.index("save-done") < order.index("kickoff-completed")
|
||||
|
||||
|
||||
def test_reset_knowledge_with_only_crew_knowledge(researcher, writer):
|
||||
mock_ks = MagicMock(spec=Knowledge)
|
||||
|
||||
|
||||
@@ -2353,3 +2353,41 @@ def test_locked_dict_proxy_ior():
|
||||
def test_locked_dict_proxy_reversed():
|
||||
flow = _make_dict_flow()
|
||||
assert list(reversed(flow.state.data)) == ["c", "b", "a"]
|
||||
|
||||
|
||||
def test_flow_drains_pending_memory_saves_before_finished_event(tmp_path):
|
||||
"""Background memory saves must finish (and emit their completion events)
|
||||
before FlowFinishedEvent, otherwise listeners that tear down on
|
||||
flow-finished (e.g. telemetry sessions) see the save span as orphaned."""
|
||||
import time
|
||||
|
||||
from crewai.memory.unified_memory import Memory
|
||||
|
||||
order: list[str] = []
|
||||
|
||||
def slow_save():
|
||||
time.sleep(0.3)
|
||||
order.append("save-done")
|
||||
|
||||
class MemoryFlow(Flow):
|
||||
@start()
|
||||
def step_1(self):
|
||||
self.memory._submit_save(slow_save)
|
||||
return "done"
|
||||
|
||||
flow = MemoryFlow(memory=Memory(storage=str(tmp_path / "flow-mem")))
|
||||
|
||||
finished = threading.Event()
|
||||
|
||||
with crewai_event_bus.scoped_handlers():
|
||||
|
||||
@crewai_event_bus.on(FlowFinishedEvent)
|
||||
def on_finished(_source, _event):
|
||||
order.append("flow-finished")
|
||||
finished.set()
|
||||
|
||||
flow.kickoff()
|
||||
|
||||
assert finished.wait(timeout=5)
|
||||
|
||||
assert order.index("save-done") < order.index("flow-finished")
|
||||
|
||||
@@ -1555,6 +1555,180 @@ class TestConversationalFlow:
|
||||
)
|
||||
|
||||
|
||||
class TestHandleTurnReplyFallback:
|
||||
"""Regression tests for EPD-181: ``handle_turn()`` decided "did the
|
||||
handler append its reply?" by comparing assistant-message counts. A
|
||||
handler that appends its reply AND trims history to a cap left the count
|
||||
unchanged, so the fallback appended the reply a second time — every turn,
|
||||
once trimming engaged. The check now uses an explicit appended-this-turn
|
||||
flag.
|
||||
"""
|
||||
|
||||
MAX_MESSAGES = 4
|
||||
|
||||
def _make_bot(self) -> ConversationalFlow:
|
||||
max_messages = self.MAX_MESSAGES
|
||||
|
||||
class EchoBot(ConversationalFlow):
|
||||
def route_turn(self, context: dict[str, Any]) -> str | None:
|
||||
return "ECHO"
|
||||
|
||||
@listen("ECHO")
|
||||
def echo(self) -> str:
|
||||
reply = f"echo: {self.state.current_user_message or ''}"
|
||||
self.append_assistant_message(reply) # handler DOES append
|
||||
if len(self.state.messages) > max_messages: # ...and trims
|
||||
self.state.messages = self.state.messages[-max_messages:]
|
||||
return reply
|
||||
|
||||
return EchoBot()
|
||||
|
||||
def test_no_duplicate_reply_when_handler_trims_history(self) -> None:
|
||||
bot = self._make_bot()
|
||||
for i in range(1, 5):
|
||||
bot.handle_turn(f"message {i}")
|
||||
contents = [message.content for message in bot.state.messages]
|
||||
assert len(contents) == len(set(contents)), (
|
||||
f"duplicate reply on turn {i}: {contents}"
|
||||
)
|
||||
|
||||
# The capped window holds the last two full turns, in order.
|
||||
assert [message.content for message in bot.state.messages] == [
|
||||
"message 3",
|
||||
"echo: message 3",
|
||||
"message 4",
|
||||
"echo: message 4",
|
||||
]
|
||||
|
||||
def test_fallback_still_appends_when_handler_does_not_reply(self) -> None:
|
||||
class SilentBot(ConversationalFlow):
|
||||
def route_turn(self, context: dict[str, Any]) -> str | None:
|
||||
return "WORK"
|
||||
|
||||
@listen("WORK")
|
||||
def work(self) -> str:
|
||||
return "computed reply" # returns without appending
|
||||
|
||||
bot = SilentBot()
|
||||
bot.handle_turn("hello")
|
||||
|
||||
assistant_messages = [
|
||||
message.content
|
||||
for message in bot.state.messages
|
||||
if message.role == "assistant"
|
||||
]
|
||||
assert assistant_messages == ["computed reply"]
|
||||
|
||||
|
||||
class TestFalsyRouteTurnFallback:
|
||||
"""A falsy ``route_turn()`` must never replay a previous turn's intent.
|
||||
|
||||
Regression tests for EPD-176: an overridden ``route_turn()`` returning
|
||||
``None`` on an unhandled input used to silently reuse the sticky
|
||||
``state.last_intent`` from the *previous* turn, running the wrong handler
|
||||
with no error or warning.
|
||||
"""
|
||||
|
||||
def test_falsy_route_turn_does_not_replay_previous_turns_intent(self) -> None:
|
||||
ran: list[str] = []
|
||||
|
||||
class Bot(ConversationalFlow):
|
||||
def route_turn(self, context: dict[str, Any]) -> str | None:
|
||||
message = context.get("current_user_message") or ""
|
||||
if "hello" in message.lower():
|
||||
return "GREETING"
|
||||
return None # unhandled input -> falsy return
|
||||
|
||||
@listen("GREETING")
|
||||
def greeting(self) -> str:
|
||||
ran.append("GREETING")
|
||||
reply = "Hi! I only do greetings."
|
||||
self.append_assistant_message(reply)
|
||||
return reply
|
||||
|
||||
@listen("WEATHER")
|
||||
def weather(self) -> str:
|
||||
ran.append("WEATHER")
|
||||
reply = "It is sunny."
|
||||
self.append_assistant_message(reply)
|
||||
return reply
|
||||
|
||||
flow = Bot()
|
||||
flow.handle_turn("hello there")
|
||||
assert ran == ["GREETING"]
|
||||
assert flow.state.last_intent == "GREETING"
|
||||
|
||||
flow.handle_turn("what is the meaning of life?")
|
||||
assert ran == ["GREETING"], (
|
||||
"an unhandled turn must not re-run the previous turn's handler"
|
||||
)
|
||||
# With no routing decision the turn falls through to the built-in
|
||||
# 'converse' default instead of replaying the stale intent.
|
||||
assert flow.state.last_intent == "converse"
|
||||
assert flow.state.messages[-1].content != "Hi! I only do greetings."
|
||||
|
||||
def test_stale_intent_ignored_but_route_selected_event_still_emitted(
|
||||
self,
|
||||
) -> None:
|
||||
class Bot(ConversationalFlow):
|
||||
def route_turn(self, context: dict[str, Any]) -> str | None:
|
||||
message = context.get("current_user_message") or ""
|
||||
return "work" if "work" in message else None
|
||||
|
||||
@listen("work")
|
||||
def do_work(self) -> str:
|
||||
self.append_assistant_message("worked")
|
||||
return "worked"
|
||||
|
||||
flow = Bot()
|
||||
routes: list[ConversationRouteSelectedEvent] = []
|
||||
with crewai_event_bus.scoped_handlers():
|
||||
|
||||
@crewai_event_bus.on(ConversationRouteSelectedEvent)
|
||||
def capture(_: Any, event: ConversationRouteSelectedEvent) -> None:
|
||||
routes.append(event)
|
||||
|
||||
flow.handle_turn("work please")
|
||||
flow.handle_turn("something unrelated")
|
||||
crewai_event_bus.flush()
|
||||
|
||||
assert [event.route for event in routes] == ["work", "converse"]
|
||||
# The fallback decision still reports the prior intent for visibility.
|
||||
assert routes[1].previous_intent == "work"
|
||||
|
||||
def test_fresh_intent_classified_this_turn_still_routes(self) -> None:
|
||||
"""The legacy ``default_intents`` path classifies per turn and must
|
||||
keep routing on the freshly classified intent — including when the
|
||||
intent changes between turns."""
|
||||
ran: list[str] = []
|
||||
|
||||
@ConversationConfig(
|
||||
default_intents=["search", "weather"], intent_llm="gpt-4o-mini"
|
||||
)
|
||||
class LegacyFlow(ConversationalFlow):
|
||||
@listen("search")
|
||||
def handle_search(self) -> str:
|
||||
ran.append("search")
|
||||
self.append_assistant_message("searched")
|
||||
return "searched"
|
||||
|
||||
@listen("weather")
|
||||
def handle_weather(self) -> str:
|
||||
ran.append("weather")
|
||||
self.append_assistant_message("sunny")
|
||||
return "sunny"
|
||||
|
||||
flow = LegacyFlow()
|
||||
with patch.object(
|
||||
flow, "_collapse_to_outcome", side_effect=["search", "weather"]
|
||||
):
|
||||
flow.handle_turn("look up crewai")
|
||||
flow.handle_turn("how is the weather?")
|
||||
|
||||
assert ran == ["search", "weather"]
|
||||
assert flow.state.last_intent == "weather"
|
||||
|
||||
|
||||
class TestFlowTracingWhenSuppressed:
|
||||
def test_flow_started_emitted_when_panel_events_suppressed(self) -> None:
|
||||
class QuietFlow(Flow[ChatState]):
|
||||
|
||||
@@ -1348,7 +1348,15 @@ def test_skill_documents_flow_wiring():
|
||||
assert "```yaml" in skill
|
||||
assert "[Method](#method-methods)" in skill
|
||||
assert 'input: "Reviewed research: ${outputs.research_brief.raw}"' in skill
|
||||
assert 'text(root, "path", "default")' in skill
|
||||
assert "do not assemble the string with CEL `+`" in skill
|
||||
assert "Do not use CEL `+` to build text in action mappings" in skill
|
||||
assert "Agent prompt template. Insert Flow values with `${...}`" in skill
|
||||
assert (
|
||||
"Repository-backed agents may set `from_repository` and omit inline "
|
||||
"`role`, `goal`, and `backstory`" in skill
|
||||
)
|
||||
assert "Runtime inputs passed to the Crew" in skill
|
||||
assert "Tool input arguments. Insert Flow values with `${...}`" in skill
|
||||
assert "trust CrewAI defaults and omit them" in skill
|
||||
assert "#### LLM Definition" in skill
|
||||
assert "`max_tokens` (optional): integer | null; default `null`" in skill
|
||||
|
||||
@@ -1102,7 +1102,7 @@ methods:
|
||||
)
|
||||
|
||||
|
||||
def test_tool_action_renders_text_custom_expression_inputs():
|
||||
def test_tool_action_renders_interpolated_inputs():
|
||||
yaml_str = f"""
|
||||
schema: crewai.flow/v1
|
||||
name: ToolFlow
|
||||
@@ -1112,8 +1112,8 @@ methods:
|
||||
call: tool
|
||||
ref: {__name__}:StaticSearchTool
|
||||
with:
|
||||
search_query: "${{'Ticket ID: ' + text(state, 'ticket.id') + '; Subject: ' + text(state, 'ticket.subject') + '; Priority: ' + text(state, 'priority', 'unknown') + '; Message: ' + text(state, 'messages.0.body')}}"
|
||||
prefix: "${{text(state, 'ticket')}}"
|
||||
search_query: "Ticket ID: ${{state.ticket.id}}; Subject: ${{state.ticket.subject}}; Message: ${{state.messages[0].body}}"
|
||||
prefix: "${{state.prefix}}"
|
||||
start: true
|
||||
"""
|
||||
|
||||
@@ -1124,9 +1124,10 @@ methods:
|
||||
inputs={
|
||||
"ticket": {"id": 123, "subject": None},
|
||||
"messages": [{"body": "Initial report"}],
|
||||
"prefix": "ticket",
|
||||
}
|
||||
)
|
||||
== '{"id": 123, "subject": null}:Ticket ID: 123; Subject: ; Priority: unknown; Message: Initial report'
|
||||
== "ticket:Ticket ID: 123; Subject: ; Message: Initial report"
|
||||
)
|
||||
|
||||
|
||||
@@ -1319,7 +1320,7 @@ methods:
|
||||
role: Analyst
|
||||
goal: Answer questions
|
||||
backstory: Knows things.
|
||||
input: "Ticket ID: ${text(state, 'ticket.id')}; Subject: ${text(state, 'ticket.subject')}"
|
||||
input: "Ticket ID: ${state.ticket.id}; Subject: ${state.ticket.subject}"
|
||||
start: true
|
||||
"""
|
||||
|
||||
@@ -2909,37 +2910,6 @@ def test_explicit_cel_fields_accept_expression_markers():
|
||||
assert Flow.from_declaration(contents=definition).kickoff(inputs={"score": 90}) == "qualified"
|
||||
|
||||
|
||||
def test_expression_action_runs_text_custom_expression():
|
||||
definition = FlowDefinition.from_declaration(contents=
|
||||
{
|
||||
"schema": "crewai.flow/v1",
|
||||
"name": "ExpressionFlow",
|
||||
"methods": {
|
||||
"summarize": {
|
||||
"start": True,
|
||||
"do": {
|
||||
"call": "expression",
|
||||
"expr": (
|
||||
"'Ticket ID: ' + text(state, 'ticket.id') + "
|
||||
"'; Tags: ' + text(state, 'tags')"
|
||||
),
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
assert (
|
||||
Flow.from_declaration(contents=definition).kickoff(
|
||||
inputs={
|
||||
"ticket": {"id": 123},
|
||||
"tags": ["urgent", "billing"],
|
||||
}
|
||||
)
|
||||
== 'Ticket ID: 123; Tags: ["urgent", "billing"]'
|
||||
)
|
||||
|
||||
|
||||
def test_expression_local_context_recurses_into_dataclass_values():
|
||||
from crewai.flow.expressions import Expression
|
||||
|
||||
|
||||
263
lib/crewai/tests/test_tool_cache_default.py
Normal file
263
lib/crewai/tests/test_tool_cache_default.py
Normal file
@@ -0,0 +1,263 @@
|
||||
# mypy: ignore-errors
|
||||
"""Regression tests for EPD-180: tool-result caching used to be ON by default,
|
||||
so an LLM calling the same tool with identical arguments twice in one run got
|
||||
the first (possibly stale) result back without the tool executing — silently
|
||||
wrong for live-data tools, and silently dropped actions for stateful tools.
|
||||
|
||||
Caching is now opt-in: ``Crew(cache=True)`` for crews, ``Agent(cache=True)``
|
||||
(or an explicit ``cache_handler``) for standalone agents. The machinery —
|
||||
including per-tool ``cache_function`` write gating — is unchanged once opted
|
||||
in.
|
||||
|
||||
The end-to-end tests run fully offline: a fake OpenAI client scripts two
|
||||
identical tool calls followed by a final answer, mirroring the EPD-180
|
||||
clean-room repro.
|
||||
"""
|
||||
|
||||
from openai.types.chat import ChatCompletion
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from crewai import LLM, Agent, Crew, Task
|
||||
from crewai.agents.cache.cache_handler import CacheHandler
|
||||
from crewai.tools import BaseTool
|
||||
|
||||
|
||||
class LookupArgs(BaseModel):
|
||||
city: str = Field(description="City to look up.")
|
||||
|
||||
|
||||
def make_live_tool():
|
||||
"""A tool returning a different value on every real execution."""
|
||||
executions = []
|
||||
|
||||
class LiveLookupTool(BaseTool):
|
||||
name: str = "live_lookup"
|
||||
description: str = "Returns a live (time-varying) reading for a city."
|
||||
args_schema: type[BaseModel] = LookupArgs
|
||||
# cache_function deliberately NOT set — exercising the default.
|
||||
|
||||
def _run(self, city: str) -> str:
|
||||
executions.append(city)
|
||||
return f"reading #{len(executions)} for {city}"
|
||||
|
||||
return LiveLookupTool(), executions
|
||||
|
||||
|
||||
def make_scripted_llm():
|
||||
"""An offline LLM whose client scripts two identical tool calls."""
|
||||
|
||||
def tool_call_response(call_id: str):
|
||||
return {
|
||||
"index": 0,
|
||||
"finish_reason": "tool_calls",
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "live_lookup",
|
||||
"arguments": '{"city": "paris"}',
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
scripted = [
|
||||
tool_call_response("call_1"),
|
||||
tool_call_response("call_2"), # identical name+args, new id
|
||||
{
|
||||
"index": 0,
|
||||
"finish_reason": "stop",
|
||||
"message": {"role": "assistant", "content": "Final answer: done."},
|
||||
},
|
||||
]
|
||||
|
||||
class FakeCompletions:
|
||||
def __init__(self):
|
||||
self.n = 0
|
||||
|
||||
def create(self, **params):
|
||||
choice = scripted[min(self.n, len(scripted) - 1)]
|
||||
self.n += 1
|
||||
return ChatCompletion.model_validate(
|
||||
{
|
||||
"id": f"chatcmpl-fake-{self.n}",
|
||||
"object": "chat.completion",
|
||||
"created": 1,
|
||||
"model": params.get("model", "gpt-4o"),
|
||||
"choices": [choice],
|
||||
"usage": {
|
||||
"prompt_tokens": 10,
|
||||
"completion_tokens": 5,
|
||||
"total_tokens": 15,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self):
|
||||
self.chat = type("Chat", (), {"completions": FakeCompletions()})()
|
||||
|
||||
llm = LLM(model="openai/gpt-4o")
|
||||
llm._client = FakeClient()
|
||||
return llm
|
||||
|
||||
|
||||
def run_crew(**crew_kwargs):
|
||||
tool, executions = make_live_tool()
|
||||
agent = Agent(
|
||||
role="reader",
|
||||
goal="Look things up.",
|
||||
backstory="Test agent.",
|
||||
llm=make_scripted_llm(),
|
||||
tools=[tool],
|
||||
verbose=False,
|
||||
)
|
||||
task = Task(
|
||||
description="Look up paris twice and report.",
|
||||
expected_output="A report.",
|
||||
agent=agent,
|
||||
)
|
||||
crew = Crew(agents=[agent], tasks=[task], verbose=False, **crew_kwargs)
|
||||
crew.kickoff()
|
||||
return executions
|
||||
|
||||
|
||||
class TestToolCachingIsOptIn:
|
||||
def test_default_reexecutes_identical_tool_calls(self):
|
||||
"""EPD-180: with no opt-in, both identical calls must really execute."""
|
||||
executions = run_crew()
|
||||
assert len(executions) == 2
|
||||
|
||||
def test_crew_cache_true_dedupes_identical_tool_calls(self):
|
||||
"""Opting in via Crew(cache=True) restores the dedup behavior."""
|
||||
executions = run_crew(cache=True)
|
||||
assert len(executions) == 1
|
||||
|
||||
|
||||
class TestAgentCacheWiring:
|
||||
def _agent(self, **kwargs) -> Agent:
|
||||
return Agent(
|
||||
role="reader",
|
||||
goal="Look things up.",
|
||||
backstory="Test agent.",
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def test_standalone_agent_has_no_cache_by_default(self):
|
||||
agent = self._agent()
|
||||
assert agent.tools_handler.cache is None
|
||||
assert agent.cache_handler is None
|
||||
|
||||
def test_standalone_agent_explicit_cache_true_opts_in(self):
|
||||
agent = self._agent(cache=True)
|
||||
assert agent.tools_handler.cache is not None
|
||||
assert agent.cache_handler is not None
|
||||
|
||||
def test_standalone_agent_explicit_cache_handler_opts_in(self):
|
||||
handler = CacheHandler()
|
||||
agent = self._agent(cache_handler=handler)
|
||||
assert agent.tools_handler.cache is handler
|
||||
|
||||
def test_explicit_cache_false_stays_off_even_with_handler(self):
|
||||
agent = self._agent(cache=False, cache_handler=CacheHandler())
|
||||
assert agent.tools_handler.cache is None
|
||||
|
||||
def test_agents_accept_a_crew_offered_handler_by_default(self):
|
||||
"""``Crew(cache=True)`` offers its handler via set_cache_handler at
|
||||
kickoff; agents that didn't explicitly opt out must accept it."""
|
||||
agent = self._agent()
|
||||
assert agent.tools_handler.cache is None
|
||||
|
||||
handler = CacheHandler()
|
||||
agent.set_cache_handler(handler)
|
||||
assert agent.tools_handler.cache is handler
|
||||
|
||||
def test_agents_that_opted_out_refuse_a_crew_offered_handler(self):
|
||||
agent = self._agent(cache=False)
|
||||
agent.set_cache_handler(CacheHandler())
|
||||
assert agent.tools_handler.cache is None
|
||||
|
||||
def test_copy_of_default_agent_does_not_opt_in(self):
|
||||
"""copy() rebuilds from model_dump(), which includes the field
|
||||
default cache=True — that must not read as an explicit opt-in on
|
||||
the copy (Bugbot review finding on the original PR)."""
|
||||
copied = self._agent().copy()
|
||||
assert copied.tools_handler.cache is None
|
||||
assert copied.cache_handler is None
|
||||
|
||||
def test_copy_of_opted_in_agent_stays_opted_in(self):
|
||||
copied = self._agent(cache=True).copy()
|
||||
assert copied.tools_handler.cache is not None
|
||||
|
||||
def test_copy_of_handler_opted_in_agent_stays_opted_in(self):
|
||||
"""An explicit cache_handler is an opt-in too; copy() excludes the
|
||||
handler itself, but the consent must survive — the copy wires its
|
||||
own fresh handler (Bugbot review finding on the original PR)."""
|
||||
source = self._agent(cache_handler=CacheHandler())
|
||||
copied = source.copy()
|
||||
assert copied.tools_handler.cache is not None
|
||||
assert copied.tools_handler.cache is not source.tools_handler.cache
|
||||
|
||||
def test_copy_of_explicit_cache_false_with_handler_stays_off(self):
|
||||
copied = self._agent(cache=False, cache_handler=CacheHandler()).copy()
|
||||
assert copied.tools_handler.cache is None
|
||||
|
||||
def test_copy_of_crew_wired_agent_does_not_opt_in(self):
|
||||
"""A handler offered by a crew at kickoff (set_cache_handler) is
|
||||
runtime wiring, not construction-time consent — copies of such
|
||||
agents must not become standalone cachers (Bugbot review finding
|
||||
on the original PR)."""
|
||||
agent = self._agent()
|
||||
agent.set_cache_handler(CacheHandler()) # what Crew(cache=True) does
|
||||
assert agent.tools_handler.cache is not None
|
||||
|
||||
copied = agent.copy()
|
||||
assert copied.tools_handler.cache is None
|
||||
assert copied.cache_handler is None
|
||||
|
||||
|
||||
class TestHierarchicalManagerCacheWiring:
|
||||
"""The auto-created hierarchical manager is built outside the agents
|
||||
loop that offers the crew's cache handler; an opted-in crew must wire
|
||||
the manager too (Bugbot review finding on the original PR)."""
|
||||
|
||||
def _crew(self, **crew_kwargs) -> Crew:
|
||||
from crewai.process import Process
|
||||
|
||||
agent = Agent(role="worker", goal="Do work.", backstory="Test agent.")
|
||||
task = Task(description="Do the work.", expected_output="Done.")
|
||||
return Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process=Process.hierarchical,
|
||||
manager_llm="gpt-4o",
|
||||
**crew_kwargs,
|
||||
)
|
||||
|
||||
def test_manager_gets_crew_handler_when_cache_enabled(self):
|
||||
crew = self._crew(cache=True)
|
||||
crew._create_manager_agent()
|
||||
assert crew.manager_agent.tools_handler.cache is crew._cache_handler
|
||||
|
||||
def test_manager_has_no_cache_when_crew_did_not_opt_in(self):
|
||||
crew = self._crew()
|
||||
crew._create_manager_agent()
|
||||
assert crew.manager_agent.tools_handler.cache is None
|
||||
|
||||
def test_user_provided_manager_with_cache_false_stays_excluded(self):
|
||||
manager = Agent(
|
||||
role="manager",
|
||||
goal="Manage.",
|
||||
backstory="Test manager.",
|
||||
cache=False,
|
||||
allow_delegation=True,
|
||||
)
|
||||
crew = self._crew(cache=True)
|
||||
crew.manager_agent = manager
|
||||
crew._create_manager_agent()
|
||||
assert manager.tools_handler.cache is None
|
||||
143
lib/crewai/tests/test_usage_shape_parity.py
Normal file
143
lib/crewai/tests/test_usage_shape_parity.py
Normal file
@@ -0,0 +1,143 @@
|
||||
# mypy: ignore-errors
|
||||
"""Regression tests for EPD-178: token usage was exposed in different shapes
|
||||
and attribute names per code path — ``Agent.kickoff()`` results carried a
|
||||
plain dict at ``.usage_metrics`` (no ``token_usage`` attribute at all), while
|
||||
``Crew.kickoff()`` results carried a ``UsageMetrics`` object at
|
||||
``.token_usage`` (no ``usage_metrics`` attribute), so any single accessor
|
||||
written for one path raised ``AttributeError`` on the other.
|
||||
|
||||
Both result types now expose both surfaces: ``.token_usage`` as a
|
||||
``UsageMetrics`` object and ``.usage_metrics`` as a plain dict.
|
||||
"""
|
||||
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.crews.crew_output import CrewOutput
|
||||
from crewai.lite_agent_output import LiteAgentOutput
|
||||
from crewai.llms.base_llm import BaseLLM
|
||||
from crewai.types.usage_metrics import UsageMetrics
|
||||
|
||||
|
||||
class _FixedUsageLLM(BaseLLM):
|
||||
"""Offline BaseLLM that records fixed usage (100/10 tokens) per call."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(model="fixed-usage-model")
|
||||
|
||||
def call(
|
||||
self,
|
||||
messages,
|
||||
tools=None,
|
||||
callbacks=None,
|
||||
available_functions=None,
|
||||
from_task=None,
|
||||
from_agent=None,
|
||||
response_model=None,
|
||||
) -> str:
|
||||
self._track_token_usage_internal(
|
||||
{"prompt_tokens": 100, "completion_tokens": 10, "total_tokens": 110}
|
||||
)
|
||||
return "Thought: I know the answer.\nFinal Answer: fake answer"
|
||||
|
||||
def supports_function_calling(self) -> bool:
|
||||
return False
|
||||
|
||||
def supports_stop_words(self) -> bool:
|
||||
return False
|
||||
|
||||
def get_context_window_size(self) -> int:
|
||||
return 4096
|
||||
|
||||
|
||||
class TestUsageShapeUnitParity:
|
||||
def test_lite_agent_output_exposes_token_usage_object(self):
|
||||
metrics = UsageMetrics(
|
||||
total_tokens=110,
|
||||
prompt_tokens=100,
|
||||
completion_tokens=10,
|
||||
successful_requests=1,
|
||||
)
|
||||
output = LiteAgentOutput(
|
||||
agent_role="analyst", usage_metrics=metrics.model_dump()
|
||||
)
|
||||
|
||||
assert output.token_usage == metrics
|
||||
assert isinstance(output.token_usage, UsageMetrics)
|
||||
|
||||
def test_lite_agent_output_token_usage_zeroed_when_absent(self):
|
||||
output = LiteAgentOutput(agent_role="analyst")
|
||||
|
||||
assert output.usage_metrics is None
|
||||
assert output.token_usage == UsageMetrics()
|
||||
|
||||
def test_crew_output_exposes_usage_metrics_dict(self):
|
||||
metrics = UsageMetrics(
|
||||
total_tokens=110,
|
||||
prompt_tokens=100,
|
||||
completion_tokens=10,
|
||||
successful_requests=1,
|
||||
)
|
||||
output = CrewOutput(token_usage=metrics)
|
||||
|
||||
assert output.usage_metrics == metrics.model_dump()
|
||||
assert isinstance(output.usage_metrics, dict)
|
||||
|
||||
def test_both_shapes_carry_identical_keys(self):
|
||||
"""The dict shape has exactly the UsageMetrics fields on both types."""
|
||||
crew_dict = CrewOutput(token_usage=UsageMetrics()).usage_metrics
|
||||
lite = LiteAgentOutput(
|
||||
agent_role="analyst", usage_metrics=UsageMetrics().model_dump()
|
||||
)
|
||||
|
||||
assert set(crew_dict) == set(UsageMetrics.model_fields)
|
||||
assert set(lite.usage_metrics) == set(UsageMetrics.model_fields)
|
||||
|
||||
|
||||
class TestUsageShapeEndToEnd:
|
||||
"""Mirror of the EPD-178 clean-room repro, offline via a fake BaseLLM."""
|
||||
|
||||
@staticmethod
|
||||
def _read_via_object(result) -> int:
|
||||
"""Single accessor written against the CrewOutput shape."""
|
||||
return result.token_usage.prompt_tokens
|
||||
|
||||
@staticmethod
|
||||
def _read_via_dict(result) -> int:
|
||||
"""Single accessor written against the LiteAgentOutput shape."""
|
||||
return result.usage_metrics["prompt_tokens"]
|
||||
|
||||
def test_single_accessor_works_on_both_kickoff_paths(self):
|
||||
agent_a = Agent(
|
||||
role="analyst",
|
||||
goal="Answer questions.",
|
||||
backstory="Test agent.",
|
||||
llm=_FixedUsageLLM(),
|
||||
verbose=False,
|
||||
)
|
||||
result_agent = agent_a.kickoff("a question")
|
||||
|
||||
agent_b = Agent(
|
||||
role="analyst",
|
||||
goal="Answer questions.",
|
||||
backstory="Test agent.",
|
||||
llm=_FixedUsageLLM(),
|
||||
verbose=False,
|
||||
)
|
||||
task = Task(
|
||||
description="Answer: a question",
|
||||
expected_output="A short answer.",
|
||||
agent=agent_b,
|
||||
)
|
||||
crew = Crew(agents=[agent_b], tasks=[task], verbose=False)
|
||||
result_crew = crew.kickoff()
|
||||
|
||||
assert isinstance(result_agent, LiteAgentOutput)
|
||||
assert isinstance(result_crew, CrewOutput)
|
||||
|
||||
# Both accessors work on both result types and agree with each other.
|
||||
for result in (result_agent, result_crew):
|
||||
object_read = self._read_via_object(result)
|
||||
dict_read = self._read_via_dict(result)
|
||||
assert object_read == dict_read
|
||||
assert object_read > 0
|
||||
assert isinstance(result.token_usage, UsageMetrics)
|
||||
assert isinstance(result.usage_metrics, dict)
|
||||
@@ -18,11 +18,16 @@ def test_creating_a_tool_using_annotation():
|
||||
return question
|
||||
|
||||
assert my_tool.name == "Name of my tool"
|
||||
assert "Tool Name: name_of_my_tool" in my_tool.description
|
||||
assert "Tool Arguments:" in my_tool.description
|
||||
assert '"question"' in my_tool.description
|
||||
assert '"type": "string"' in my_tool.description
|
||||
assert "Tool Description: Clear description for what this tool is useful for" in my_tool.description
|
||||
# The authored description is preserved as written; the LLM-facing
|
||||
# composite lives at formatted_description.
|
||||
assert my_tool.description == (
|
||||
"Clear description for what this tool is useful for, your agent will need this information to use it."
|
||||
)
|
||||
assert "Tool Name: name_of_my_tool" in my_tool.formatted_description
|
||||
assert "Tool Arguments:" in my_tool.formatted_description
|
||||
assert '"question"' in my_tool.formatted_description
|
||||
assert '"type": "string"' in my_tool.formatted_description
|
||||
assert "Tool Description: Clear description for what this tool is useful for" in my_tool.formatted_description
|
||||
assert my_tool.args_schema.model_json_schema()["properties"] == {
|
||||
"question": {"title": "Question", "type": "string"}
|
||||
}
|
||||
@@ -33,9 +38,10 @@ def test_creating_a_tool_using_annotation():
|
||||
converted_tool = my_tool.to_structured_tool()
|
||||
assert converted_tool.name == "Name of my tool"
|
||||
|
||||
assert "Tool Name: name_of_my_tool" in converted_tool.description
|
||||
assert "Tool Arguments:" in converted_tool.description
|
||||
assert '"question"' in converted_tool.description
|
||||
assert converted_tool.description == my_tool.description
|
||||
assert "Tool Name: name_of_my_tool" in converted_tool.formatted_description
|
||||
assert "Tool Arguments:" in converted_tool.formatted_description
|
||||
assert '"question"' in converted_tool.formatted_description
|
||||
assert converted_tool.args_schema.model_json_schema()["properties"] == {
|
||||
"question": {"title": "Question", "type": "string"}
|
||||
}
|
||||
@@ -56,11 +62,16 @@ def test_creating_a_tool_using_baseclass():
|
||||
my_tool = MyCustomTool()
|
||||
assert my_tool.name == "Name of my tool"
|
||||
|
||||
assert "Tool Name: name_of_my_tool" in my_tool.description
|
||||
assert "Tool Arguments:" in my_tool.description
|
||||
assert '"question"' in my_tool.description
|
||||
assert '"type": "string"' in my_tool.description
|
||||
assert "Tool Description: Clear description for what this tool is useful for" in my_tool.description
|
||||
# The authored description is preserved as written; the LLM-facing
|
||||
# composite lives at formatted_description.
|
||||
assert my_tool.description == (
|
||||
"Clear description for what this tool is useful for, your agent will need this information to use it."
|
||||
)
|
||||
assert "Tool Name: name_of_my_tool" in my_tool.formatted_description
|
||||
assert "Tool Arguments:" in my_tool.formatted_description
|
||||
assert '"question"' in my_tool.formatted_description
|
||||
assert '"type": "string"' in my_tool.formatted_description
|
||||
assert "Tool Description: Clear description for what this tool is useful for" in my_tool.formatted_description
|
||||
assert my_tool.args_schema.model_json_schema()["properties"] == {
|
||||
"question": {"title": "Question", "type": "string"}
|
||||
}
|
||||
@@ -69,9 +80,10 @@ def test_creating_a_tool_using_baseclass():
|
||||
converted_tool = my_tool.to_structured_tool()
|
||||
assert converted_tool.name == "Name of my tool"
|
||||
|
||||
assert "Tool Name: name_of_my_tool" in converted_tool.description
|
||||
assert "Tool Arguments:" in converted_tool.description
|
||||
assert '"question"' in converted_tool.description
|
||||
assert converted_tool.description == my_tool.description
|
||||
assert "Tool Name: name_of_my_tool" in converted_tool.formatted_description
|
||||
assert "Tool Arguments:" in converted_tool.formatted_description
|
||||
assert '"question"' in converted_tool.formatted_description
|
||||
assert converted_tool.args_schema.model_json_schema()["properties"] == {
|
||||
"question": {"title": "Question", "type": "string"}
|
||||
}
|
||||
@@ -695,3 +707,88 @@ class TestToolDecoratorArunValidation:
|
||||
|
||||
with pytest.raises(ValueError, match="validation failed"):
|
||||
await async_execute.arun(wrong_arg="value")
|
||||
|
||||
|
||||
class TestAuthoredDescriptionPreserved:
|
||||
"""Regression tests for EPD-179: BaseTool.model_post_init silently
|
||||
rewrote the authored ``description`` into the LLM-facing composite
|
||||
(``Tool Name: …\\nTool Arguments: …\\nTool Description: <authored>``).
|
||||
The authored field must survive construction as written, with the
|
||||
composite exposed separately at ``formatted_description``.
|
||||
"""
|
||||
|
||||
AUTHORED = "Returns the current temperature for a city."
|
||||
|
||||
def _make_tool(self) -> BaseTool:
|
||||
class TempArgs(BaseModel):
|
||||
city: str = Field(description="City name to look up.")
|
||||
|
||||
class TempTool(BaseTool):
|
||||
name: str = "get_temperature"
|
||||
description: str = TestAuthoredDescriptionPreserved.AUTHORED
|
||||
args_schema: type[BaseModel] = TempArgs
|
||||
|
||||
def _run(self, city: str) -> str:
|
||||
return f"22C in {city}"
|
||||
|
||||
return TempTool()
|
||||
|
||||
def test_description_equals_authored_text(self):
|
||||
tool_instance = self._make_tool()
|
||||
assert tool_instance.description == self.AUTHORED
|
||||
|
||||
def test_formatted_description_contains_composite(self):
|
||||
tool_instance = self._make_tool()
|
||||
formatted = tool_instance.formatted_description
|
||||
assert "Tool Name: get_temperature" in formatted
|
||||
assert "Tool Arguments:" in formatted
|
||||
assert '"city"' in formatted
|
||||
assert formatted.endswith(f"Tool Description: {self.AUTHORED}")
|
||||
|
||||
def test_formatted_description_tracks_later_description_edits(self):
|
||||
tool_instance = self._make_tool()
|
||||
tool_instance.description = "Edited description."
|
||||
assert tool_instance.formatted_description.endswith(
|
||||
"Tool Description: Edited description."
|
||||
)
|
||||
|
||||
def test_prose_mentioning_the_marker_is_not_truncated(self):
|
||||
"""Authored text that merely mentions "Tool Description:" must reach
|
||||
the LLM untouched — only descriptions that ARE a pre-composed block
|
||||
(anchored three-line shape) get stripped."""
|
||||
tool_instance = self._make_tool()
|
||||
prose = (
|
||||
"Formats prompts. The output includes a line reading "
|
||||
"'Tool Description:' followed by the tool's summary."
|
||||
)
|
||||
tool_instance.description = prose
|
||||
assert tool_instance.formatted_description.endswith(
|
||||
f"Tool Description: {prose}"
|
||||
)
|
||||
|
||||
def test_composite_is_not_reapplied_to_prebaked_descriptions(self):
|
||||
"""A description that already contains a composed block (old
|
||||
checkpoints, adapters that bake the composite into the field) must
|
||||
not be double-wrapped."""
|
||||
tool_instance = self._make_tool()
|
||||
tool_instance.description = (
|
||||
"Tool Name: get_temperature\n"
|
||||
'Tool Arguments: {"city": "str"}\n'
|
||||
f"Tool Description: {self.AUTHORED}"
|
||||
)
|
||||
formatted = tool_instance.formatted_description
|
||||
assert formatted.count("Tool Description:") == 1
|
||||
assert formatted.endswith(f"Tool Description: {self.AUTHORED}")
|
||||
|
||||
def test_prompt_rendering_still_uses_composite(self):
|
||||
from crewai.utilities.agent_utils import render_text_description_and_args
|
||||
|
||||
tool_instance = self._make_tool()
|
||||
structured = tool_instance.to_structured_tool()
|
||||
assert structured.description == self.AUTHORED
|
||||
|
||||
for candidate in (tool_instance, structured):
|
||||
rendered = render_text_description_and_args([candidate])
|
||||
assert "Tool Name: get_temperature" in rendered
|
||||
assert "Tool Arguments:" in rendered
|
||||
assert f"Tool Description: {self.AUTHORED}" in rendered
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Flow panels must be suppressed while a TUI owns the screen."""
|
||||
|
||||
from rich.text import Text
|
||||
|
||||
from crewai.events.listeners.tracing.utils import set_tui_mode
|
||||
from crewai.events.utils.console_formatter import ConsoleFormatter
|
||||
|
||||
|
||||
def _make_formatter(monkeypatch):
|
||||
fmt = ConsoleFormatter(verbose=True)
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(fmt, "print", lambda *a, **k: calls.append(a))
|
||||
return fmt, calls
|
||||
|
||||
|
||||
def test_flow_panel_suppressed_in_tui_mode(monkeypatch):
|
||||
fmt, calls = _make_formatter(monkeypatch)
|
||||
set_tui_mode(True)
|
||||
try:
|
||||
fmt.print_panel(Text("x"), "🌊 Flow Started", "blue", is_flow=True)
|
||||
finally:
|
||||
set_tui_mode(False)
|
||||
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_flow_panel_prints_when_not_tui_mode(monkeypatch):
|
||||
fmt, calls = _make_formatter(monkeypatch)
|
||||
set_tui_mode(False)
|
||||
|
||||
fmt.print_panel(Text("x"), "🌊 Flow Started", "blue", is_flow=True)
|
||||
|
||||
# Panel + trailing blank line.
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
def test_non_flow_panel_unaffected_by_tui_mode(monkeypatch):
|
||||
# tui_mode only gates flow panels; regular panels still follow verbose.
|
||||
fmt, calls = _make_formatter(monkeypatch)
|
||||
set_tui_mode(True)
|
||||
try:
|
||||
fmt.print_panel(Text("x"), "Task", "blue", is_flow=False)
|
||||
finally:
|
||||
set_tui_mode(False)
|
||||
|
||||
assert len(calls) == 2
|
||||
121
uv.lock
generated
121
uv.lock
generated
@@ -13,7 +13,7 @@ resolution-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-07-04T15:35:51.457693Z"
|
||||
exclude-newer = "2026-07-11T05:37:26.328112Z"
|
||||
exclude-newer-span = "P3D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
@@ -1028,14 +1028,14 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "click"
|
||||
version = "8.1.8"
|
||||
version = "8.4.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b9/2e/0090cbf739cee7d23781ad4b89a9894a41538e4fcf4c31dcdd705b78eb8b/click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a", size = 226593, upload-time = "2024-12-21T18:38:44.339Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/76/d4/81420972a676e8ffea40450d8c8c92943e7218a78fe9b64359836cc9876b/click-8.4.2.tar.gz", hash = "sha256:9a6cea6e60b17ebe0a44c5cc636d94f09bd66142c1cd7d8b4cd731c4917a15f6", size = 338000, upload-time = "2026-06-24T17:45:15.148Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7e/d4/7ebdbd03970677812aac39c869717059dbb71a4cfc033ca6e5221787892c/click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2", size = 98188, upload-time = "2024-12-21T18:38:41.666Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/e2/79c688af8b210d232694e31e59da9f6ec747bae31c3f5946e4e9b98860d5/click-8.4.2-py3-none-any.whl", hash = "sha256:e6f9f66136c816745b9d65817da91d61d957fb16e02e4dcd0552553c5a197b76", size = 119243, upload-time = "2026-06-24T17:45:13.73Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6126,75 +6126,54 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "pillow"
|
||||
version = "12.2.0"
|
||||
version = "12.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8c/21/c2bcdd5906101a30244eaffc1b6e6ce71a31bd0742a01eb89e660ebfac2d/pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5", size = 46987819, upload-time = "2026-04-01T14:46:17.687Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/1c/3d/bb7fca845737cf9d7dbde16ed1843984665ff2e0a518f5db43e77ec540b9/pillow-12.3.0.tar.gz", hash = "sha256:3b8182a766685eaa002637e28b4ec8d6b18819a0c71f579bf0dbaa5830297cce", size = 47025035, upload-time = "2026-07-01T11:56:38.965Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/aa/d0b28e1c811cd4d5f5c2bfe2e022292bd255ae5744a3b9ac7d6c8f72dd75/pillow-12.2.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:a4e8f36e677d3336f35089648c8955c51c6d386a13cf6ee9c189c5f5bd713a9f", size = 5354355, upload-time = "2026-04-01T14:42:15.402Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/27/8e/1d5b39b8ae2bd7650d0c7b6abb9602d16043ead9ebbfef4bc4047454da2a/pillow-12.2.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2e589959f10d9824d39b350472b92f0ce3b443c0a3442ebf41c40cb8361c5b97", size = 4695871, upload-time = "2026-04-01T14:42:18.234Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/c5/dcb7a6ca6b7d3be41a76958e90018d56c8462166b3ef223150360850c8da/pillow-12.2.0-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a52edc8bfff4429aaabdf4d9ee0daadbbf8562364f940937b941f87a4290f5ff", size = 6269734, upload-time = "2026-04-01T14:42:20.608Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ea/f1/aa1bb13b2f4eba914e9637893c73f2af8e48d7d4023b9d3750d4c5eb2d0c/pillow-12.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:975385f4776fafde056abb318f612ef6285b10a1f12b8570f3647ad0d74b48ec", size = 8076080, upload-time = "2026-04-01T14:42:23.095Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a1/2a/8c79d6a53169937784604a8ae8d77e45888c41537f7f6f65ed1f407fe66d/pillow-12.2.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bd9c0c7a0c681a347b3194c500cb1e6ca9cab053ea4d82a5cf45b6b754560136", size = 6382236, upload-time = "2026-04-01T14:42:25.82Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b5/42/bbcb6051030e1e421d103ce7a8ecadf837aa2f39b8f82ef1a8d37c3d4ebc/pillow-12.2.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:88d387ff40b3ff7c274947ed3125dedf5262ec6919d83946753b5f3d7c67ea4c", size = 7070220, upload-time = "2026-04-01T14:42:28.68Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3f/e1/c2a7d6dd8cfa6b231227da096fd2d58754bab3603b9d73bf609d3c18b64f/pillow-12.2.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:51c4167c34b0d8ba05b547a3bb23578d0ba17b80a5593f93bd8ecb123dd336a3", size = 6493124, upload-time = "2026-04-01T14:42:31.579Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/41/7c8617da5d32e1d2f026e509484fdb6f3ad7efaef1749a0c1928adbb099e/pillow-12.2.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:34c0d99ecccea270c04882cb3b86e7b57296079c9a4aff88cb3b33563d95afaa", size = 7194324, upload-time = "2026-04-01T14:42:34.615Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2d/de/a777627e19fd6d62f84070ee1521adde5eeda4855b5cf60fe0b149118bca/pillow-12.2.0-cp310-cp310-win32.whl", hash = "sha256:b85f66ae9eb53e860a873b858b789217ba505e5e405a24b85c0464822fe88032", size = 6376363, upload-time = "2026-04-01T14:42:37.19Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e7/34/fc4cb5204896465842767b96d250c08410f01f2f28afc43b257de842eed5/pillow-12.2.0-cp310-cp310-win_amd64.whl", hash = "sha256:673aa32138f3e7531ccdbca7b3901dba9b70940a19ccecc6a37c77d5fdeb05b5", size = 7083523, upload-time = "2026-04-01T14:42:39.62Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2d/a0/32852d36bc7709f14dc3f64f929a275e958ad8c19a6deba9610d458e28b3/pillow-12.2.0-cp310-cp310-win_arm64.whl", hash = "sha256:3e080565d8d7c671db5802eedfb438e5565ffa40115216eabb8cd52d0ecce024", size = 2463318, upload-time = "2026-04-01T14:42:42.063Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/68/e1/748f5663efe6edcfc4e74b2b93edfb9b8b99b67f21a854c3ae416500a2d9/pillow-12.2.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:8be29e59487a79f173507c30ddf57e733a357f67881430449bb32614075a40ab", size = 5354347, upload-time = "2026-04-01T14:42:44.255Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/47/a1/d5ff69e747374c33a3b53b9f98cca7889fce1fd03d79cdc4e1bccc6c5a87/pillow-12.2.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:71cde9a1e1551df7d34a25462fc60325e8a11a82cc2e2f54578e5e9a1e153d65", size = 4695873, upload-time = "2026-04-01T14:42:46.452Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/21/e3fbdf54408a973c7f7f89a23b2cb97a7ef30c61ab4142af31eee6aebc88/pillow-12.2.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f490f9368b6fc026f021db16d7ec2fbf7d89e2edb42e8ec09d2c60505f5729c7", size = 6280168, upload-time = "2026-04-01T14:42:49.228Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d3/f1/00b7278c7dd52b17ad4329153748f87b6756ec195ff786c2bdf12518337d/pillow-12.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8bd7903a5f2a4545f6fd5935c90058b89d30045568985a71c79f5fd6edf9b91e", size = 8088188, upload-time = "2026-04-01T14:42:51.735Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/cf/220a5994ef1b10e70e85748b75649d77d506499352be135a4989c957b701/pillow-12.2.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3997232e10d2920a68d25191392e3a4487d8183039e1c74c2297f00ed1c50705", size = 6394401, upload-time = "2026-04-01T14:42:54.343Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/bd/e51a61b1054f09437acfbc2ff9106c30d1eb76bc1453d428399946781253/pillow-12.2.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e74473c875d78b8e9d5da2a70f7099549f9eb37ded4e2f6a463e60125bccd176", size = 7079655, upload-time = "2026-04-01T14:42:56.954Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/3d/45132c57d5fb4b5744567c3817026480ac7fc3ce5d4c47902bc0e7f6f853/pillow-12.2.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:56a3f9c60a13133a98ecff6197af34d7824de9b7b38c3654861a725c970c197b", size = 6503105, upload-time = "2026-04-01T14:42:59.847Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7d/2e/9df2fc1e82097b1df3dce58dc43286aa01068e918c07574711fcc53e6fb4/pillow-12.2.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:90e6f81de50ad6b534cab6e5aef77ff6e37722b2f5d908686f4a5c9eba17a909", size = 7203402, upload-time = "2026-04-01T14:43:02.664Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bd/2e/2941e42858ebb67e50ae741473de81c2984e6eff7b397017623c676e2e8d/pillow-12.2.0-cp311-cp311-win32.whl", hash = "sha256:8c984051042858021a54926eb597d6ee3012393ce9c181814115df4c60b9a808", size = 6378149, upload-time = "2026-04-01T14:43:05.274Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/69/42/836b6f3cd7f3e5fa10a1f1a5420447c17966044c8fbf589cc0452d5502db/pillow-12.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:6e6b2a0c538fc200b38ff9eb6628228b77908c319a005815f2dde585a0664b60", size = 7082626, upload-time = "2026-04-01T14:43:08.557Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c2/88/549194b5d6f1f494b485e493edc6693c0a16f4ada488e5bd974ed1f42fad/pillow-12.2.0-cp311-cp311-win_arm64.whl", hash = "sha256:9a8a34cc89c67a65ea7437ce257cea81a9dad65b29805f3ecee8c8fe8ff25ffe", size = 2463531, upload-time = "2026-04-01T14:43:10.743Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/58/be/7482c8a5ebebbc6470b3eb791812fff7d5e0216c2be3827b30b8bb6603ed/pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5", size = 5308279, upload-time = "2026-04-01T14:43:13.246Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d8/95/0a351b9289c2b5cbde0bacd4a83ebc44023e835490a727b2a3bd60ddc0f4/pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421", size = 4695490, upload-time = "2026-04-01T14:43:15.584Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/de/af/4e8e6869cbed569d43c416fad3dc4ecb944cb5d9492defaed89ddd6fe871/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987", size = 6284462, upload-time = "2026-04-01T14:43:18.268Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e9/9e/c05e19657fd57841e476be1ab46c4d501bffbadbafdc31a6d665f8b737b6/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76", size = 8094744, upload-time = "2026-04-01T14:43:20.716Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2b/54/1789c455ed10176066b6e7e6da1b01e50e36f94ba584dc68d9eebfe9156d/pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005", size = 6398371, upload-time = "2026-04-01T14:43:23.443Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/e3/fdc657359e919462369869f1c9f0e973f353f9a9ee295a39b1fea8ee1a77/pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780", size = 7087215, upload-time = "2026-04-01T14:43:26.758Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8b/f8/2f6825e441d5b1959d2ca5adec984210f1ec086435b0ed5f52c19b3b8a6e/pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5", size = 6509783, upload-time = "2026-04-01T14:43:29.56Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/f9/029a27095ad20f854f9dba026b3ea6428548316e057e6fc3545409e86651/pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5", size = 7212112, upload-time = "2026-04-01T14:43:32.091Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/be/42/025cfe05d1be22dbfdb4f264fe9de1ccda83f66e4fc3aac94748e784af04/pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940", size = 6378489, upload-time = "2026-04-01T14:43:34.601Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5d/7b/25a221d2c761c6a8ae21bfa3874988ff2583e19cf8a27bf2fee358df7942/pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5", size = 7084129, upload-time = "2026-04-01T14:43:37.213Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/e1/542a474affab20fd4a0f1836cb234e8493519da6b76899e30bcc5d990b8b/pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414", size = 2463612, upload-time = "2026-04-01T14:43:39.421Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4a/01/53d10cf0dbad820a8db274d259a37ba50b88b24768ddccec07355382d5ad/pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:8297651f5b5679c19968abefd6bb84d95fe30ef712eb1b2d9b2d31ca61267f4c", size = 4100837, upload-time = "2026-04-01T14:43:41.506Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0f/98/f3a6657ecb698c937f6c76ee564882945f29b79bad496abcba0e84659ec5/pillow-12.2.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:50d8520da2a6ce0af445fa6d648c4273c3eeefbc32d7ce049f22e8b5c3daecc2", size = 4176528, upload-time = "2026-04-01T14:43:43.773Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/69/bc/8986948f05e3ea490b8442ea1c1d4d990b24a7e43d8a51b2c7d8b1dced36/pillow-12.2.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:766cef22385fa1091258ad7e6216792b156dc16d8d3fa607e7545b2b72061f1c", size = 3640401, upload-time = "2026-04-01T14:43:45.87Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/34/46/6c717baadcd62bc8ed51d238d521ab651eaa74838291bda1f86fe1f864c9/pillow-12.2.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5d2fd0fa6b5d9d1de415060363433f28da8b1526c1c129020435e186794b3795", size = 5308094, upload-time = "2026-04-01T14:43:48.438Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/71/43/905a14a8b17fdb1ccb58d282454490662d2cb89a6bfec26af6d3520da5ec/pillow-12.2.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:56b25336f502b6ed02e889f4ece894a72612fe885889a6e8c4c80239ff6e5f5f", size = 4695402, upload-time = "2026-04-01T14:43:51.292Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/73/dd/42107efcb777b16fa0393317eac58f5b5cf30e8392e266e76e51cff28c3d/pillow-12.2.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f1c943e96e85df3d3478f7b691f229887e143f81fedab9b20205349ab04d73ed", size = 6280005, upload-time = "2026-04-01T14:43:54.242Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/68/b93e09e5e8549019e61acf49f65b1a8530765a7f812c77a7461bca7e4494/pillow-12.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:03f6fab9219220f041c74aeaa2939ff0062bd5c364ba9ce037197f4c6d498cd9", size = 8090669, upload-time = "2026-04-01T14:43:57.335Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4b/6e/3ccb54ce8ec4ddd1accd2d89004308b7b0b21c4ac3d20fa70af4760a4330/pillow-12.2.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5cdfebd752ec52bf5bb4e35d9c64b40826bc5b40a13df7c3cda20a2c03a0f5ed", size = 6395194, upload-time = "2026-04-01T14:43:59.864Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/ee/21d4e8536afd1a328f01b359b4d3997b291ffd35a237c877b331c1c3b71c/pillow-12.2.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eedf4b74eda2b5a4b2b2fb4c006d6295df3bf29e459e198c90ea48e130dc75c3", size = 7082423, upload-time = "2026-04-01T14:44:02.74Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/5f/e9f86ab0146464e8c133fe85df987ed9e77e08b29d8d35f9f9f4d6f917ba/pillow-12.2.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:00a2865911330191c0b818c59103b58a5e697cae67042366970a6b6f1b20b7f9", size = 6505667, upload-time = "2026-04-01T14:44:05.381Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ed/1e/409007f56a2fdce61584fd3acbc2bbc259857d555196cedcadc68c015c82/pillow-12.2.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1e1757442ed87f4912397c6d35a0db6a7b52592156014706f17658ff58bbf795", size = 7208580, upload-time = "2026-04-01T14:44:08.39Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/23/c4/7349421080b12fb35414607b8871e9534546c128a11965fd4a7002ccfbee/pillow-12.2.0-cp313-cp313-win32.whl", hash = "sha256:144748b3af2d1b358d41286056d0003f47cb339b8c43a9ea42f5fea4d8c66b6e", size = 6375896, upload-time = "2026-04-01T14:44:11.197Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3f/82/8a3739a5e470b3c6cbb1d21d315800d8e16bff503d1f16b03a4ec3212786/pillow-12.2.0-cp313-cp313-win_amd64.whl", hash = "sha256:390ede346628ccc626e5730107cde16c42d3836b89662a115a921f28440e6a3b", size = 7081266, upload-time = "2026-04-01T14:44:13.947Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c3/25/f968f618a062574294592f668218f8af564830ccebdd1fa6200f598e65c5/pillow-12.2.0-cp313-cp313-win_arm64.whl", hash = "sha256:8023abc91fba39036dbce14a7d6535632f99c0b857807cbbbf21ecc9f4717f06", size = 2463508, upload-time = "2026-04-01T14:44:16.312Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/a4/b342930964e3cb4dce5038ae34b0eab4653334995336cd486c5a8c25a00c/pillow-12.2.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:042db20a421b9bafecc4b84a8b6e444686bd9d836c7fd24542db3e7df7baad9b", size = 5309927, upload-time = "2026-04-01T14:44:18.89Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9f/de/23198e0a65a9cf06123f5435a5d95cea62a635697f8f03d134d3f3a96151/pillow-12.2.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:dd025009355c926a84a612fecf58bb315a3f6814b17ead51a8e48d3823d9087f", size = 4698624, upload-time = "2026-04-01T14:44:21.115Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/01/a6/1265e977f17d93ea37aa28aa81bad4fa597933879fac2520d24e021c8da3/pillow-12.2.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88ddbc66737e277852913bd1e07c150cc7bb124539f94c4e2df5344494e0a612", size = 6321252, upload-time = "2026-04-01T14:44:23.663Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3c/83/5982eb4a285967baa70340320be9f88e57665a387e3a53a7f0db8231a0cd/pillow-12.2.0-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d362d1878f00c142b7e1a16e6e5e780f02be8195123f164edf7eddd911eefe7c", size = 8126550, upload-time = "2026-04-01T14:44:26.772Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/48/6ffc514adce69f6050d0753b1a18fd920fce8cac87620d5a31231b04bfc5/pillow-12.2.0-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2c727a6d53cb0018aadd8018c2b938376af27914a68a492f59dfcaca650d5eea", size = 6433114, upload-time = "2026-04-01T14:44:29.615Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/a3/f9a77144231fb8d40ee27107b4463e205fa4677e2ca2548e14da5cf18dce/pillow-12.2.0-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:efd8c21c98c5cc60653bcb311bef2ce0401642b7ce9d09e03a7da87c878289d4", size = 7115667, upload-time = "2026-04-01T14:44:32.773Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/fc/ac4ee3041e7d5a565e1c4fd72a113f03b6394cc72ab7089d27608f8aaccb/pillow-12.2.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9f08483a632889536b8139663db60f6724bfcb443c96f1b18855860d7d5c0fd4", size = 6538966, upload-time = "2026-04-01T14:44:35.252Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c0/a8/27fb307055087f3668f6d0a8ccb636e7431d56ed0750e07a60547b1e083e/pillow-12.2.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:dac8d77255a37e81a2efcbd1fc05f1c15ee82200e6c240d7e127e25e365c39ea", size = 7238241, upload-time = "2026-04-01T14:44:37.875Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/4b/926ab182c07fccae9fcb120043464e1ff1564775ec8864f21a0ebce6ac25/pillow-12.2.0-cp313-cp313t-win32.whl", hash = "sha256:ee3120ae9dff32f121610bb08e4313be87e03efeadfc6c0d18f89127e24d0c24", size = 6379592, upload-time = "2026-04-01T14:44:40.336Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c2/c4/f9e476451a098181b30050cc4c9a3556b64c02cf6497ea421ac047e89e4b/pillow-12.2.0-cp313-cp313t-win_amd64.whl", hash = "sha256:325ca0528c6788d2a6c3d40e3568639398137346c3d6e66bb61db96b96511c98", size = 7085542, upload-time = "2026-04-01T14:44:43.251Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/00/a4/285f12aeacbe2d6dc36c407dfbbe9e96d4a80b0fb710a337f6d2ad978c75/pillow-12.2.0-cp313-cp313t-win_arm64.whl", hash = "sha256:2e5a76d03a6c6dcef67edabda7a52494afa4035021a79c8558e14af25313d453", size = 2465765, upload-time = "2026-04-01T14:44:45.996Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/b7/2437044fb910f499610356d1352e3423753c98e34f915252aafecc64889f/pillow-12.2.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0538bd5e05efec03ae613fd89c4ce0368ecd2ba239cc25b9f9be7ed426b0af1f", size = 5273969, upload-time = "2026-04-01T14:45:55.538Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f6/f4/8316e31de11b780f4ac08ef3654a75555e624a98db1056ecb2122d008d5a/pillow-12.2.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:394167b21da716608eac917c60aa9b969421b5dcbbe02ae7f013e7b85811c69d", size = 4659674, upload-time = "2026-04-01T14:45:58.093Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/37/664fca7201f8bb2aa1d20e2c3d5564a62e6ae5111741966c8319ca802361/pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5d04bfa02cc2d23b497d1e90a0f927070043f6cbf303e738300532379a4b4e0f", size = 5288479, upload-time = "2026-04-01T14:46:01.141Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/49/62/5b0ed78fce87346be7a5cfcfaaad91f6a1f98c26f86bdbafa2066c647ef6/pillow-12.2.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0c838a5125cee37e68edec915651521191cef1e6aa336b855f495766e77a366e", size = 7032230, upload-time = "2026-04-01T14:46:03.874Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c3/28/ec0fc38107fc32536908034e990c47914c57cd7c5a3ece4d8d8f7ffd7e27/pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a6c9fa44005fa37a91ebfc95d081e8079757d2e904b27103f4f5fa6f0bf78c0", size = 5355404, upload-time = "2026-04-01T14:46:06.33Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5e/8b/51b0eddcfa2180d60e41f06bd6d0a62202b20b59c68f5a132e615b75aecf/pillow-12.2.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:25373b66e0dd5905ed63fa3cae13c82fbddf3079f2c8bf15c6fb6a35586324c1", size = 6002215, upload-time = "2026-04-01T14:46:08.83Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bc/60/5382c03e1970de634027cee8e1b7d39776b778b81812aaf45b694dfe9e28/pillow-12.2.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:bfa9c230d2fe991bed5318a5f119bd6780cda2915cca595393649fc118ab895e", size = 7080946, upload-time = "2026-04-01T14:46:11.734Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/c2/669d88644cddb1485bd9534e63e8cf476c8e51cb3c3a1297677023505c0e/pillow-12.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:6c0016e7b354317c4e9e525b937ac8596c38d2d232b419529b9cd7a1cd46e39a", size = 5392418, upload-time = "2026-07-01T11:53:27.808Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/ba/3762f376a2948e3036488d773a146e0ae6ecc2ca03ac20e2615bd0b2ba02/pillow-12.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:bcc33feacfaefce60c12fd500a277533bdc02b10a19f7f6d348763d8140bbba7", size = 4785287, upload-time = "2026-07-01T11:53:29.761Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/07/50/b5d688cc9c52d4482f3d5bcab6ce20bc2a74a85d2343841c907444a3be2c/pillow-12.3.0-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5594fc43d548a7ed94949d139aa1341b270f1863f11cfd37f5a6c8b778a6b67f", size = 6253754, upload-time = "2026-07-01T11:53:32.298Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/89/36f4cd76cf4baf05c50ababb976249153f18c959171c7f6ba09a6f217260/pillow-12.3.0-cp310-cp310-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ec", size = 6925605, upload-time = "2026-07-01T11:53:34.487Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/c0/4de58cf6633b9e3a6061ef4be6fb91fc3c90b812ece886f531e3c523d777/pillow-12.3.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:85f998ea1848bc6757289e739cfbdda3a04adfd58b02fc018ce54d754a5ce468", size = 6327788, upload-time = "2026-07-01T11:53:36.433Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/3c/14d53682a19550dbbaf3b598f807d5457646c510805a44c7d7891cd1cd1a/pillow-12.3.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:25b9b82bb22e6e2b3cd07b39c68b7b862001226cb3dff7130d1cb914121b39ed", size = 7036288, upload-time = "2026-07-01T11:53:38.712Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/38/1d/36279e3c77efe034e4cc2b0393ee74ffdb5a62391dacbf9b916154f5f0b8/pillow-12.3.0-cp310-cp310-win32.whl", hash = "sha256:37dc8f7bbb66efe481bb60defacef820c950c24713fb44962ed6aa2a50966de1", size = 6472396, upload-time = "2026-07-01T11:53:40.781Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/48/7c/8fa0039574c476d7c6fa57dd7c32a130436877c6ec1e5ce1cc8ec44878c1/pillow-12.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:300557495eb45ebb8aec96c2da9c4be642fbf7cd937278b4013ba894ea8eb0eb", size = 7226887, upload-time = "2026-07-01T11:53:42.764Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/17/e324be141d173c1c919428066c3259f21c1b8982e564e01a4a81e96dbdcf/pillow-12.3.0-cp310-cp310-win_arm64.whl", hash = "sha256:514435a37670e3e5e08f3945b68718b6ed329bb84367777e16f9f4dfe1e61a0f", size = 2568039, upload-time = "2026-07-01T11:53:45.372Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fb/c8/0a78b0e02d7ac54bc03e5321c9220da52f0c2ea83b21f7c40e7f3169c502/pillow-12.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:00808c5e14ef63ac5161091d242999076604ff74b883423a11e5d7bbb38bf756", size = 5392415, upload-time = "2026-07-01T11:53:47.162Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b2/5b/a02d30018abd97ced9f5a6c63d28597694a00d066516b9c1c6de45859fc9/pillow-12.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37d6d0a00072fd2948eb22bce7e1475f34569d90c87c59f7a2ec59541b77f7a6", size = 4785266, upload-time = "2026-07-01T11:53:49.079Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c8/98/766667a4be768150a202836acd9fad19c06824ca86c4286d3cf6b274964e/pillow-12.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bcb46e2f9feff8d06323983bd83ed00c201fdcab3d74973e7072a889b3979fcd", size = 6263814, upload-time = "2026-07-01T11:53:51.32Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/2d/ede717bc1144f63886c21fd349bb95860b0d1a21149ff16f2bb362b612b6/pillow-12.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:23d27a3e0307ec2244cc51e7287b919aa68d097504ebe19df4e76a98a3eea5bd", size = 6934408, upload-time = "2026-07-01T11:53:53.487Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a3/48/9c58b685e69d49c31af6c8eb9012055fab7e665785165c84796e2c73ce72/pillow-12.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4f883547d4b7f0495ebe7056b0cc2aea76094e7a4abc8e933540f3271df27d9c", size = 6337160, upload-time = "2026-07-01T11:53:55.457Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ff/fa/dc2a5c0ba6df93f67c31d34b808b7ce440b40cdbf96f0b81cde1d1e6fa93/pillow-12.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:236ff70b9312fb68943c703aa842ca6a758abfa45ac187a5e7c1452e96ef72b5", size = 7045172, upload-time = "2026-07-01T11:53:57.736Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/86/a5/444817a4d4c4c2417df00513086ca196f388d8f9ef40c2e4ccd1ad1af54b/pillow-12.3.0-cp311-cp311-win32.whl", hash = "sha256:10e41f0fbf1eec8cfd234b8fe17a4caac7c9d0db4c204d3c173a8f9f6ef3232b", size = 6472232, upload-time = "2026-07-01T11:53:59.767Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/63/c6/4bad1b18d132a50b27e1365e1ab163616f7a5bb56d330f66f9d1d9d4f9d4/pillow-12.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:8e95e1385e4998ae9694eeaa4730ba5457ff61185b3a55e2e7bea0880aef452a", size = 7233653, upload-time = "2026-07-01T11:54:02.066Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fd/16/00f91ab7760dc842f5aad55217e80fc4a7067a0604535249bc8a2d6d9870/pillow-12.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:ebaea975e03d3141d9d3a507df75c9b3ec90fa9d2ffd07567b3a978d9d790b26", size = 2568195, upload-time = "2026-07-01T11:54:04.622Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/37/bf/fb3ebff8ddcb76aac5a01389251bbbb9519922a9b520d8247c1ca864a25d/pillow-12.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ba09209fbe443b4acccebe845d8a138b89a8f4fbaeedd44953490b5315d5e965", size = 5345969, upload-time = "2026-07-01T11:54:06.397Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d8/66/9a386a92561f402389a4fc70c18838bf6d35eb5eb5c6850b4b2dc64f5048/pillow-12.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ffd0c5368496f41b0944be820fcb7a838aa6e623d250b01acf2643939c3f99d7", size = 4780323, upload-time = "2026-07-01T11:54:09.351Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/25/27/ac8f99618ffd3dde21db0f4d4b1d2ab00c0880595bfd17df103f7f39fd0c/pillow-12.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d9c7f76c0673154f044e9d78c8655fb4213f6ca31a836df48b40fe5d187717b9", size = 6266838, upload-time = "2026-07-01T11:54:11.71Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/84/21/a35af28dcc61f37ed850a2d64c65c701321dfbf25085e469d5559360cbbf/pillow-12.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78cb2c6865a35ab8ff8b75fd122f6033b92a62c82801110e48ddd6c936a45d91", size = 6940830, upload-time = "2026-07-01T11:54:13.732Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/eb/51/8b08617af3ad95e33ce6d7dd2c99ed6c8298f7fb131636303956be022e25/pillow-12.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:e491916b378fba47242221bb9ead245211b70d504f495d105d17b14a24b4907c", size = 6344383, upload-time = "2026-07-01T11:54:15.756Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/72/cf78ac9780bb93c28328f408973845a309d4d145041665f734572ced1b52/pillow-12.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0dd2064cbc55aaec028ef5fbb60fa47bb6c3e7918e07ff17935284b227a9d2df", size = 7052934, upload-time = "2026-07-01T11:54:17.721Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/20/20/25e0f4dc178a6bc0696793720055519a0de89e7661dae886992decbd2f81/pillow-12.3.0-cp312-cp312-win32.whl", hash = "sha256:dbce0b29841537a2fa4a214c2bbf14de3587c9680caa9b4e217568472490b28f", size = 6472684, upload-time = "2026-07-01T11:54:19.839Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/45/89/da2f7971a317f83d807fdd4065c0af40208e59e692cc43d315a71a0e96d1/pillow-12.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a2b55dd6b2a4c4b7d87ffa56bdb33fdc5fdb9a462173861a7bc097f17d91cb09", size = 7227137, upload-time = "2026-07-01T11:54:22.025Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/de/47/4845a0a6c0dbf1db8456bd9fc791f13c5ced7ced20606d08a0aacfd25b49/pillow-12.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:331b624368d4f1d069149002f25f44bc61c8919ce8ddb3c45bdad8f6e2d89510", size = 2568267, upload-time = "2026-07-01T11:54:24.051Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/ac/31fb64e1e7efb5a4b50cd3d92049ba89ac6e4d8d3bb6a74e15048ca3353e/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:21900ce7ba264168cd50defae43cd75d25c833ad4ad6e73ffc5596d12e25ac89", size = 4161684, upload-time = "2026-07-01T11:54:25.934Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/87/b4/9805e23d2b4d77842b468513841fda254ee42f0289d25088340e4ff46e2d/pillow-12.3.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:4e8c2a84d977f50b9daed6eeaf3baef67d00d5d74d932288f02cb94518ee3ace", size = 4255487, upload-time = "2026-07-01T11:54:27.935Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/df/39/ecf519435a200c693fe053a6ee4d835b41cf963a4dfc2551c4e637cb2a71/pillow-12.3.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ae26d61dfa7a47befdc7572b521024e8745f3d809bd95ca9505a7bba9ef849ec", size = 3696433, upload-time = "2026-07-01T11:54:29.813Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/92/2fc3ffad878ae8dd5469ec1bc8eb83b71f48e13efdf68f02709003982a32/pillow-12.3.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66", size = 5345889, upload-time = "2026-07-01T11:54:31.97Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/10/76/8803c13605b763d33d156c4678fc77f8443389c0c51c8aef707bb02015f4/pillow-12.3.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35", size = 4780109, upload-time = "2026-07-01T11:54:34.026Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1f/01/e18aff37cb0b4aac47ac90f016d347a49aca667ef97f190b06ac2aabc928/pillow-12.3.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f7401aebd7f581d7f83a439d87d474999317ee099218e5ad25d125290990ba65", size = 6263736, upload-time = "2026-07-01T11:54:36.131Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f7/62/de5bdd77d935331f4f802edc11e4d82950f642caad6cb2f949837b8560e2/pillow-12.3.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0847a763afefb695bc912d7c131e7e0632d4edc1d8698f58ddabec8e46b8b6d3", size = 6937129, upload-time = "2026-07-01T11:54:38.216Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/70/4d/105627a13300c5e0df1d174230b32fd1273062c96f7745fd552b945d1e1d/pillow-12.3.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:571b9fcb07b97ef3a492028fb3d2dc0993ca23a06138b0315286566d29ef718a", size = 6339562, upload-time = "2026-07-01T11:54:40.354Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6b/1d/f13de01a553988ab895ba1c722e06cf3144d4f57656fd5b81b6d881f1179/pillow-12.3.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:756c768d0c9c2955feb7a56c37ea24aea2e369f8d36a88da270b6a9f19e62b5e", size = 7049439, upload-time = "2026-07-01T11:54:42.489Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/f9/066794cca041b969964f779ee5fa66a9498bbf34248ac39c5d7954e4198f/pillow-12.3.0-cp313-cp313-win32.whl", hash = "sha256:a876864214e136f0eb367788dbd7df045f4806801518e2cfe9e13229cfe06d8f", size = 6473287, upload-time = "2026-07-01T11:54:44.9Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a6/9b/7a58e61d62be561da3a356fe2384d4059a6345fc130e23ef1c36a5b81d24/pillow-12.3.0-cp313-cp313-win_amd64.whl", hash = "sha256:1cca606cd25738df4ed873d5ad46bbdb3d83b5cbca291f6b4ff13a4df6b0bbe8", size = 7239691, upload-time = "2026-07-01T11:54:47.141Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/aa/b0/c4ed4f0ef8f8fa5ee8351537db6650bb8189f7e118842978dd6589065692/pillow-12.3.0-cp313-cp313-win_arm64.whl", hash = "sha256:b629de27fda84b42cde7edef0d85f13b958b47f6e9bbcbba9b673c562a89bd8b", size = 2568185, upload-time = "2026-07-01T11:54:49.137Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/75/18/2e8b40223153ccbc60df07f9e8928dc0c76202aa4e55ae9f53962b6510d6/pillow-12.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:b3c777e849237620b022f7f297dd67705f9f5cf1685f09f02e46f93e92725468", size = 5302510, upload-time = "2026-07-01T11:56:25.736Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/46/3e/51fabf59d5ab801ceab709453d3ab6b180083496579549de4c45ced6528a/pillow-12.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:b343699e8308bdc51978310e1c959c584e7869cc8c40780058c87da7781a1e94", size = 4736058, upload-time = "2026-07-01T11:56:28.041Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/bf/20/22fe9384b7949e25fb1293bcfc84fb82590ff4ea6b37c95b24d26d793d86/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fbd139c8447d25dd750ab79ee274cc5e1fe80fc56340ab10b18a195e1b6eca3e", size = 5237776, upload-time = "2026-07-01T11:56:30.263Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/08/14/f6ba68107680ffa74b39985f3f30884e41318fbc4250caa423c79b4788bb/pillow-12.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e7e480451b9fa137494bccd3a7d69adbe8ac65a87d97be61e11f1b1050a5bac3", size = 5860358, upload-time = "2026-07-01T11:56:32.68Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/54/0169bc772ec491108b62f644f8ecf1fe5d8ae5ebafde2ee2142210166903/pillow-12.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:04f01d28a6aaff387bf842a13be313df23ba0597a44f1a976c9feb3c6ff4711a", size = 7231786, upload-time = "2026-07-01T11:56:35.046Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user