Compare commits

..

167 Commits

Author SHA1 Message Date
João Moura
a660ca5a77 Merge branch 'main' into fix/scaffold-coding-agent-telemetry 2026-09-14 13:06:12 -03:00
theater
a225c1b373 fix(cli): don't crash the run TUI when streamed output contains a literal [...] (#7435)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
* fix(cli): reject non-serializable literal_eval results in TUI JSON formatting

_try_parse_structured() accepted any dict/list coming out of
ast.literal_eval(), including values json.dumps() cannot encode such as
[Ellipsis] from a literal [...]. _format_json_in_text() then raised
TypeError: Object of type ellipsis is not JSON serializable, which
propagated through _tick and cancelled the whole crew run.

Validate the parsed object with json.dumps() inside
_try_parse_structured() so only JSON-serializable dict/list values are
returned; anything else falls back to the original text. Fixes #7434.

* fix(cli): contain RecursionError in the TUI JSON formatting boundary

A streamed structure nested deeper than the JSON backend can walk could
raise RecursionError out of _try_parse_structured (from json.loads) or
out of the render-path dumps, escaping _tick and losing the TUI update.

Catch RecursionError when loading, and validate literal_eval results
with the exact kwargs the render path uses, so any structure the render
cannot encode is rejected at the boundary and the raw text renders
instead.

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-14 20:41:33 +05:30
Shivangi
a328710007 fix: reject replay when stored tasks differ (#7155)
* fix: reject replay when stored tasks differ

* fix: validate replay task descriptions

* fix: reject ambiguous replay task identities

* fix: persist stable replay task keys

* test: align legacy replay fixture

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-14 15:52:31 +05:30
Modusensus
7e80d94921 fix: use sys.platform guards so mypy passes on Windows (#7401)
mypy does not narrow on `platform.system()`, so Windows-based contributors
get 8 spurious attr-defined/unused-ignore errors from the termios and
resource imports. Switch to `sys.platform` comparisons, which mypy
understands natively, and drop the now-unneeded type-ignore comments.

Fixes #7400

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-14 14:38:50 +05:30
João Moura
440a8f79b9 Merge branch 'main' into fix/scaffold-coding-agent-telemetry 2026-09-14 04:21:17 -03:00
João Moura
9393a47f31 fix(agents): request the forced final answer as a user turn (#7450)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* fix(agents): request the forced final answer as a user turn

When an agent reaches max_iter, handle_max_iterations_exceeded appended
the "give your best final answer" instruction as an assistant message and
relied on assistant prefill to make the model continue it. Current Claude
models (Opus 5, Sonnet 5, Fable 5.x, the 4.6+ family) reject a request
that ends on an assistant turn with a 400, after the whole iteration
budget has already been spent.

The instruction is now appended as a user turn, which every provider
accepts. The handler's formatted_answer parameter is dropped: every
caller had already appended that text as the last assistant message, so
prefixing it again only duplicated history.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(agents): stop the lite agent loop after the forced final answer

LiteAgent._invoke_loop fell through after handle_max_iterations_exceeded
and issued a regular LLM call on the same history, discarding the forced
answer. Break out of the loop the way CrewAgentExecutor already does, and
assert a single LLM call in the test.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-14 11:52:08 +05:30
Melanie Hart Buehler
21678f8ac6 docs(rag): add xpu to embedding device options (#6808)
* docs(rag): add xpu to embedding device options

* address copilot review

* docs(rag): sync Korean and Portuguese RagTool pages

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-14 05:51:43 +00:00
Joao Moura
4c07273c6d fix(cli): scaffold assistant files for JSON crews and harden telemetry tests
- create_json_crew, the default `crewai create crew` path, now copies
  AGENTS.md, CLAUDE.md and GEMINI.md; AGENTS.md documents the JSON layout
- span helper no longer depends on OTEL_SDK_DISABLED being popped by an
  earlier test; thread-scope test stops its worker before leaving the mock
- single import style in the shutdown test

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 15:48:29 -07:00
Joao Moura
b8a1ca1a9d fix(cli): neutral observability guidance in scaffolded AGENTS.md
- State the observability rule as the user's decision, never a fix for
  console warnings, speed, or a "clean" configuration
- Rewrite the AMP section as built-in capabilities: no "free",
  "proactively", "sales pitch", or scripted pitches
- Turn the research mandate into a list of sources to consult when
  version details matter
- Retarget the scaffold tests to the new wording

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 15:28:20 -07:00
Joao Moura
6b75a8d270 feat: scaffold project with assistant instruction files
- Updated project creation to include `CLAUDE.md` and `GEMINI.md` that import `AGENTS.md`, ensuring consistent guidance across coding assistants.
- Implemented utility functions to copy assistant instruction files during project setup.
- Enhanced documentation in `AGENTS.md` to emphasize the importance of keeping telemetry enabled for optimal performance.
- Added tests to verify the correct scaffolding of assistant instruction files and their contents.
2026-09-13 13:17:39 -07:00
Vidit Ostwal
894898f84c ci: welcome first-time contributors after merge (#7397)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* ci: welcome first-time contributors after merge

* ci: welcome first-time contributors after merge

* ci: support fork contributor welcome comments

* ci: minimize contributor welcome permissions
2026-09-12 01:16:17 +05:30
Vidit Ostwal
93ad4d67c4 feat: validate platform integrations during crew setup (#7385)
* feat: validate platform integrations during crew setup

* fix: clarify platform integration validation

* refactor: split platform authentication workflow

* feat: list connected platform integrations
2026-09-11 12:20:33 -07:00
Vidit Ostwal
d20845f0a3 feat: add platform tools to JSON crew wizard (#7384)
* feat: support platform tools in JSON crews

* style: clarify platform integration labels

* fix: avoid repeating tool picker title

* fix(platform): surface JSON tool discovery errors
2026-09-11 12:13:55 -07:00
Vidit Ostwal
e1f3c4bdd4 feat: expose CrewAI Platform application catalog (#7383)
* feat: expose platform application catalog

* refactor: centralize platform application catalog

* fix: preserve platform application typing

* chore: remove unused platform app export
2026-09-11 21:02:00 +05:30
Vidit Ostwal
d5c7bac505 chore: update OpenRouter tool specifications (#7387) 2026-09-11 12:16:05 -03:00
Vidit Ostwal
004f7b58d5 test(bedrock): isolate session credential test (#7388) 2026-09-11 14:23:03 +00:00
Vidit Ostwal
c5759ce854 test(bedrock): verify environment credentials (#7375)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
* test(bedrock): verify environment credentials

* test(bedrock): isolate credential environment test
2026-09-10 23:07:50 -07:00
monkscode
5704ea08eb fix(agents): keep null in the task output schema embedded in the prompt (#6775)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* fix(agents): keep null in the task output schema embedded in the prompt

build_task_prompt_with_schema embeds the task output schema into the prompt
via generate_model_description, whose strip_null_types defaults to True.
Combined with ensure_all_properties_required, an Optional[str] = None field
reaches the model as a required, non-nullable string, contradicting the
provider-side response schema generated from the same model.

That sanitizer targets OpenAI strict function-calling schemas. This call site
produces prompt prose, where those constraints do not apply.

Pass strip_null_types=False, matching the existing call for tool schemas in
utilities/agent_utils.py.

Fixes #6774

* test(agents): cover the output_json branch of the prompt schema

build_task_prompt_with_schema embeds a schema on both the output_json and
the output_pydantic branch, and this PR changes both. The regression test
only built a Task with output_pydantic, so the output_json branch shipped
unpinned.

Parameterize over both output attributes. Checked on this branch with the
fix reverted: both cases fail on the missing anyOf, and both pass with it.

Also compare the anyOf members as a set, so member order is not part of the
test contract.

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-10 13:46:16 +05:30
8616dca5c0 docs: list all workspace packages (#6678)
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-10 12:51:37 +05:30
Gamal Osama
c860613c7a feat(embeddings): add openrouter as a supported embedding provider (#7127)
* feat(embeddings): add openrouter provider type definitions

* feat(embeddings): implement OpenRouterProvider

* feat(embeddings): export openrouter provider package symbols

* feat(embeddings): register openrouter in allowed embedding providers

* feat(embeddings): register openrouter provider and overloads in factory

* feat(tools): add openrouter embedding service support

* test(embeddings): add comprehensive openrouter provider and factory tests

* test(embeddings): add openrouter build test in embedding factory

* test(embeddings): add openrouter model key alias and env tests

* test(tools): add openrouter tests for embedding service

* docs: add openrouter embedder configuration example

* docs(ar): sync openrouter embedder translation

* docs(ko): sync openrouter embedder translation

* docs(pt-BR): sync openrouter embedder translation

* feat(embeddings): allow model alias and None fields in OpenRouterProviderConfig

* fix(tools): resolve EMBEDDINGS_OPENROUTER_API_KEY before OPENROUTER_API_KEY

* test(tools): add regression tests for openrouter env var precedence and fallback

* feat(embeddings): drop organization_id and resolve api_key via OPENROUTER_API_KEY only

* fix(tools): use OPENROUTER_API_KEY in embedding service and update tests

* docs: switch openrouter knowledge example to model_name and document OPENROUTER_API_KEY

* fix(tools): default openrouter model to namespaced openai/text-embedding-3-small

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-10 12:24:15 +05:30
Rohit Kanithi
4bfdb0df67 fix(tools): align DOCXSearchTool with standard RAG fixed schema pattern (#7356) (#7357)
Co-authored-by: Rohit Kanithi <rohitkanithi@users.noreply.github.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-10 11:16:08 +05:30
Lorenze Jay
a8d330de00 [docs-freeze] docs: snapshot and changelog for v1.15.21 (#7363) 2026-09-09 22:54:07 +00:00
Lorenze Jay
d469e9fb2b feat: bump versions to 1.15.21 (#7362) 2026-09-09 22:29:18 +00:00
João Moura
d729cade6b fix(openai): surface gateway errors reported inside an HTTP 200 (#7342)
* fix(openai): surface gateway errors reported inside an HTTP 200

OpenAI-compatible gateways commit `200 OK` as soon as the upstream provider
accepts a request, so a later provider failure arrives in the body as an
`error` object with no `choices`. That reached the SDK's parse helper and
surfaced as `TypeError: 'NoneType' object is not iterable`, naming neither the
provider, the status, nor the fact that a timeout happened.

The four non-streaming paths now inspect the raw body before parsing and raise
the exception the upstream code maps to, so a masked 504 is catchable exactly
like an honest one. Streaming already had this guard inside the SDK.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(openai): teach the tool-cache fake about with_raw_response

The provider now reads the raw body before parsing, so a client double that
only implements `create` no longer satisfies it. Same shape as the fixes to the
reasoning-effort retry and Snowflake doubles.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(tracing): reset the TraceCollectionListener singleton between tests

TraceCollectionListener caches a TraceBatchManager on the class and
`_initialized` short-circuits `__init__`, so batch state survives for the whole
xdist worker. `test_nested_agent_executor_flow_does_not_finalize_parent_batch`
left `trace_batch_id="debug-trace-batch"` behind, which moved every later trace
POST from /tracing/ephemeral/batches to /tracing/batches/<id>/events. The
recorded cassette then stopped matching, the agent retried, and the second call
found the cassette consumed -- surfacing as ConnectionError in an unrelated
test hundreds of tests later.

Reproduced deterministically by running the leaking test followed by
tests/tracing/test_trace_enable_disable.py::test_trace_calls_when_enabled_via_env;
fails on a68b5e903 too, so this predates the gateway fix it was blocking.

An autouse fixture now clears the cached instance after each test. Two canaries
pin the invariant and fail without the fixture.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(tracing): drop the unwritable _listeners_setup canary

Both review bots flagged that the canary read `_listeners_setup` off the class,
where it is always False, so it could never fail. Correct, and the suggested fix
does not work either: `BaseEventListener.__init__` calls `setup_listeners`
(base_event_listener.py:16), which sets the flag on the instance
(trace_listener.py:229), so reading it back through `TraceCollectionListener()`
is always True. Neither read observes a leak, so the canary is deleted rather
than replaced, with the reasoning recorded so it is not re-added.

The same finding showed the fixture was resetting two class attributes that are
never assigned at class level. Only dropping `_instance` is load-bearing, so the
fixture is now one line.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(tracing): correct why the _listeners_setup canary is unwritable

setup_listeners returns early when tracing is off and no override applies
(trace_listener.py:213-220), assigning the flag at :229 only when it actually
registers. Construction therefore does not always set it, as the previous note
claimed: with tracing disabled the flag never even reaches the instance dict.

The instance read reports ambient tracing state rather than isolation, which is
a better reason not to assert on it than the one recorded before.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): clear trace batch state in place instead of dropping the singleton

Dropping `TraceCollectionListener._instance` made the next construction re-run
`setup_listeners`, re-registering its handlers on the event bus. That broke
tests/telemetry/test_task_failure_instrumentation.py, which requires exactly one
handler per event: the re-registered `on_task_failed` made two. Verified against
a53ecc17f, where the same sequence passes -- the regression was mine.

The leak that needed fixing was batch state, not registration, so the fixture
now clears the manager's batch fields in place. Handler cleanup already belongs
to `cleanup_event_handlers`, and `first_time_handler` keeps its reference to the
same manager object.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tests): clear tracing context vars so the listener can re-register

Bugbot flagged that keeping the singleton leaves `_listeners_setup` set, so after
`cleanup_event_handlers` wipes the bus `setup_listeners` returns early
(trace_listener.py:208) and tracing silently registers nothing for the rest of
the worker. Confirmed: after a tracing-enabled run, re-running setup restores 0
of 119 handler entries.

Dropping the singleton fixes that but previously broke
test_task_failure_instrumentation. The real cause was a third leak: the
`_tracing_enabled` context var stayed set, so the replacement listener still
believed tracing was on and re-registered `on_task_failed` next to telemetry's.
Clearing the context vars is what makes replacing the listener safe, so the
fixture now does both, and a canary pins it (fails with `assert True is False`
without the drop).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 15:12:57 -07:00
Vidit Ostwal
4ed4aba6cd fix(cli): keep deploy push on the AMP create source (#7345)
Push was choosing ZIP vs git from a local origin remote, so adding origin later rebuilt the last ZIP with no files. Prefer AMP zip_deployment from status, and fall back to the old origin heuristic when that field is missing.
2026-09-10 00:23:40 +05:30
Vidit Ostwal
57df7f5202 test(bedrock): restore provider module after import test (#7355)
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2026-09-09 23:46:37 +05:30
Daniel Barreto
b92e80be53 chore(tools): make the vision_tool more dynamic (#7350)
* chore(tools): make the vision_tool more dynamic

* tackle review comments

* chore: update tool specifications

* refactor(tools): simplify vision tool model selection

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: ViditOstwal <viditostwal@gmail.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-09 22:18:53 +05:30
Lorenze Jay
b0fd0a9fa3 feat(telemetry): track checkpoint runtime and CLI usage (#7348)
* feat(cli): track checkpoint command and TUI usage

* feat(telemetry): track runtime checkpoint operations

* fix(telemetry): count prune usage after argument validation

* style(cli): format checkpoint prune command

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-09 22:13:11 +05:30
Devulapalli Naga Sri Vaishnavi
a53ecc17f1 fix: make pre-commit hooks portable on Windows (#6881)
* fix: make pre-commit hooks portable on Windows

* test: validate each pre-commit hook command

* test: restore Bedrock module state after import check

* test: keep provider module references in sync

* fix: select virtualenv activation path by platform

* chore(ci): ignore unpatched accelerate advisory

* chore: keep Windows hook fix focused

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-09 08:50:41 +00:00
Liangshanbobo
929a173575 test(agents): cover native result as answer (#7334) (#7336)
* test(agents): cover native result as answer (#7334)

* test(agents): document result as answer coverage

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-09 13:32:27 +05:30
George Pickett
9feaf5ecab docs(tools): fix parallel search reference link (#7344)
Co-authored-by: George Pickett <297992784+georgeatparallel@users.noreply.github.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-09 13:21:59 +05:30
Vidit Ostwal
5c47c4a559 ci: ignore unpatched accelerate GHSA-4j2p-28q2-5m79 (#7347)
pip-audit fails on accelerate 1.13.0; no PyPI release past 1.14.0 ships the path-traversal fix yet.
2026-09-09 12:50:55 +05:30
Vidit Ostwal
a68b5e903c chore(ci): label FTC-closed PRs as needs-issue (#7249) 2026-09-09 00:32:53 +05:30
Vidit Ostwal
79befd0ce5 docs: clarify that tracing is managed separately from telemetry (#7311)
Users who disable telemetry still need the tracing docs to understand first-run trace viewing and how the two settings relate.
2026-09-08 23:08:10 +05:30
YOON KIWOONG
5d9b77ba10 GitContribute issue #7287 (#7288)
Signed-off-by: kiwoong <rldnddbs@naver.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-08 22:22:03 +05:30
oxy-giedrius
34199c21b7 chore(oxylabs): allow the 3.x oxylabs SDK (#7331)
`oxylabs` was pinned to exactly 2.0.0, so consumers could not take 3.0.0, out
since March. 3.x keeps the `RealtimeClient` surface these tools use, and all
four tools plus their failure paths were verified against the live API on both
2.0.0 and 3.0.0.

The lockfile keeps oxylabs at 2.0.0, so this permits the upgrade rather than
forcing it.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 07:22:23 +00:00
oxy-giedrius
fe62d04cdb fix(oxylabs): report scrape failures instead of raising IndexError (#7044)
* fix(oxylabs): report scrape failures instead of raising IndexError

The oxylabs SDK logs HTTP errors and returns an empty response rather than
raising, so the unchecked `response.results[0]` in every Oxylabs tool turned a
rejected request into `IndexError: list index out of range`. Invalid credentials
-- the most likely first-run mistake -- gave no indication of the cause. A
result carrying a non-2xx `status_code` had the same problem one level down: the
job ran, the page did not come back, and the tool returned its empty content as
though the scrape had succeeded, handing the agent "[]".

Both are now reported as a `ToolFailure` naming what went wrong, so the agent
gets something it can act on and the framework records the call as failed:

    401 Unauthorized
    400 Bad Request - Parameter `parsing_instructions` can be used just with
    `parse` parameter set to `true`.

Because the SDK keeps the cause only in its own log, the failing call is run
with a handler attached to the `oxylabs` logger and the status, the API's
explanation and timeouts are read back off it. `code` and `retryable` are set
from the status, so 429 and 5xx are marked worth retrying. Nothing about the
caller's logging configuration is changed; an application that has silenced the
SDK still gets the generic failure.

Content that is neither a string nor a dict is also serialized properly:
`parsing_instructions` commonly yields a list, and the previous `str()`
fallback produced a Python repr with single quotes instead of JSON.

The client construction and response handling these four tools duplicated
verbatim now live in a shared `OxylabsBaseTool`, following the existing
`SerpApiBaseTool` pattern, so the handling above exists in one place. The
generated tool specs change only by the new `locale` field, confirming the
tools' public surface is otherwise untouched.

Also add the `locale` option to the Google Search config, which the docs
already documented but the config model silently dropped, and correct two
copy-paste errors in the docs across all four locales.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(oxylabs): keep concurrent scrape diagnoses apart

The error capture attached a fresh handler to the shared `oxylabs` logger for
each scrape, so two scrapes in flight at once each saw both errors. `_diagnose`
reads the first HTTP status it finds, so a timeout could be reported as the
other request's 400 -- `retryable=False` on a failure that was worth retrying.

One handler now serves every scrape and routes each record to the capture of
the call that caused it via a `ContextVar`, which isolates threads and asyncio
tasks alike. Serializing the captures would have fixed the cross-talk too, but
at the cost of running every scrape one at a time. The handler stays attached
once installed: it is inert outside a capture, and detaching it would race with
concurrent scrapes.

The regression test forces the interleaving -- one capture is held open while
the other call logs -- and fails against the previous implementation.

Also drive `config` through the public constructor in the tests instead of
assigning `__dict__["config"]`, so they would catch `__init__` dropping a
supplied config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 12:42:48 +05:30
αI
7e18abd108 fix(llm): route all DashScope models through native provider (#7234)
DashScope's OpenAI-compatible endpoint serves DeepSeek/Kimi/GLM/etc.,
not only Qwen. Stop restricting the native match to the qwen* prefix so
DASHSCOPE_BASE_URL applies consistently. Fixes #7233.

Co-authored-by: Alphaxiaoteng <230277249+Alphaxiaoteng@users.noreply.github.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-08 06:08:40 +00:00
Rolly Calma
09997bfd6f fix(state): persist json checkpoints as utf-8 (#7257)
* fix(state): persist json checkpoints as utf-8

* test: import pathlib Path in checkpoint tests

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-08 06:02:41 +00:00
陈志谦
98c067c22a fix(brightdata): drop stray $ in f-string search URLs (#7326)
get_search_url interpolated ${query} inside an f-string, producing
URLs like https://www.bing.com/search?q=$test. The URL is passed
straight to the SERP request, so every search carried the malformed
query string.

Fixes #7325
2026-09-08 04:55:52 +00:00
Bright Oparaji
1b855b4ff9 docs(events): remove stale params from handle_llm_stream_chunk docstring (#7313)
The Args block for ConsoleFormatter.handle_llm_stream_chunk listed
'chunk' and 'crew_tree' parameters that no longer exist on the method.
The signature was refactored to (accumulated_text, call_type) but the
docstring was not updated. Callers in event_listener.py pass only the
two real params.

Refs #7312.
2026-09-07 19:10:44 +05:30
Bright Oparaji
1f3e6113d7 docs(streaming): fix streaming output docstring examples (#7286)
* docs(streaming): fix streaming output docstring examples

CrewStreamingOutput's example called crew.kickoff() without setting
stream=True on the Crew, so the snippet returned a CrewOutput and did
not stream anything.

FlowStreamingOutput's example called flow.kickoff_streaming() and
flow.kickoff_streaming_async(); neither method exists. Flow-level
streaming is exposed through Flow.kickoff with stream=True and
returns a StreamSession, not a FlowStreamingOutput.

Refs #7285

* docs(streaming): clarify Flow.kickoff does not take stream param

Flow.kickoff() has no stream parameter; the runtime returns a
StreamSession when self.stream is True. Reword the FlowStreamingOutput
note so callers know to configure the Flow with stream=True before
calling kickoff().

Addresses CodeRabbit review on #7286.

* docs(streaming): restore FlowStreamingOutput example

Add back an Example block showing valid usage of FlowStreamingOutput.
The class is only ever constructed directly with a chunk-producing
iterator (see lib/crewai/tests/test_streaming.py), so the example
mirrors that pattern instead of the original snippet that referenced
non-existent Flow.kickoff_streaming methods.

Addresses review feedback on #7286.

* docs(streaming): swap FlowStreamingOutput example for public Flow streaming path

Replace the test-only FlowStreamingOutput(sync_iterator=...) example
with the actual public flow-streaming path: Flow.stream=True followed
by kickoff() / kickoff_async(), which return StreamSession /
AsyncStreamSession. The example is labeled explicitly to make clear
that Flow.kickoff() does not return a FlowStreamingOutput, and points
readers at the streaming-flow-execution guide.

Addresses review feedback on #7286.

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-07 16:27:15 +05:30
DrewWhittleNZ
193a166e61 fix(schema): support list-form type arrays in JSON schema conversion (#7281)
* fix(schema): support list-form "type" arrays in JSON schema conversion

_json_schema_to_pydantic_type already handles anyOf/oneOf for nullable
unions -- the form Pydantic's own schema generation produces for
Optional[T] fields -- but had no handling for the other, equally valid
JSON Schema way of expressing the same thing: a list-form type array,
e.g. {"type": ["string", "null"]}. This is what .NET/System.Text.Json
-based schema generators produce instead, so any MCP tool schema from
a non-Python server using this form crashed create_model_from_schema
outright with "Unsupported JSON schema type: ['string', 'null']" --
taking down the entire MCPServerAdapter connection, not just the one
affected tool.

Confirmed against a real self-hosted MCP server (Equibles,
github.com/daniel3303/Equibles): several of its tools (e.g.
ListCompanyDocuments's startDate/endDate filters) use exactly this
pattern, and MCPServerAdapter couldn't connect to it at all as a
result -- reproduced identically on both Windows and macOS.

Fix mirrors the existing anyOf/oneOf handling: treat each entry in a
list-form type the same way an anyOf member is handled, building a
Union of the corresponding Python types. A single-element list
collapses to that one type via typing.Union's own behavior, and
"null" entries resolve to None (matching how the type == "null"
branch already behaves), producing the same Optional[T] shape as the
anyOf case would.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(schema): preserve union members when applying FORMAT_TYPE_MAP

CodeRabbit flagged this reviewing #7058: the format override in
_json_schema_to_pydantic_field replaced the whole resolved type with
FORMAT_TYPE_MAP[format_], even when that type was a Union built from a
list-form `type` (or anyOf/oneOf) rather than a plain `str`. For a
schema like {"type": ["string", "null"], "format": "date-time"}, this
collapsed Union[str, None] down to plain datetime, silently dropping
the null option -- masked for non-required fields by the
Optional-rewrap at the end of the same function, but not for a
required-but-nullable field (a valid, if unusual, JSON Schema shape).
The same override also drops any non-string members of a multi-type
array (e.g. ["string", "integer", "null"]) regardless of required
status, since nothing rewraps those.

Narrow the override to the `str` member specifically: replace `type_`
outright when it's already plain `str`, or substitute only the `str`
element inside a Union via get_origin/get_args, leaving null and
other type-array members untouched.

Added two tests covering the previously-broken cases: a required
nullable formatted field, and a multi-type array (string/integer/null)
with a format.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-07 12:36:02 +05:30
Shxiao
7fe8317fc4 fix(llm): correct gpt-4o-mini context window 200000 -> 128000 (#7294)
gpt-4o-mini's official context window is 128,000 tokens (OpenAI
announcement and API docs; litellm's model database agrees), but the
shared LLM_CONTEXT_WINDOW_SIZES table and the OpenAI/Azure provider-local
tables listed 200000 - apparently copied from the neighboring o3-mini /
o4-mini entries. With CONTEXT_WINDOW_USAGE_RATIO = 0.85, crews resolved
the usable window to 170000 instead of 108800, letting history grow past
the model's real 128k limit and failing with API 400s on long runs.

Fixes #7293
2026-09-07 11:11:57 +05:30
Jesse Miller
143e902178 docs: use organization UUIDs in the skill install reference (#7273)
Organization names are not unique, so the documented `@org/name` form can
resolve to the wrong organization and fail to find the skill. Document the
`@org-uuid/name` form instead, and add a note pointing at `crewai org list`
for the UUID.

Applies to the agent-side registry refs too: they resolve through the same
`/skills/:org/:name` endpoint and the same `~/.crewai/skills/{org}/{name}/`
cache path, so leaving them as `@acme` would contradict the install command.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-04 13:26:07 -07:00
Lucas Kim
c00e3228fc fix(bedrock): preserve streaming tool call arguments at contentBlockStop (#6150)
* fix(bedrock): preserve streaming tool call arguments at contentBlockStop

Streaming Converse handlers accumulate tool input as JSON string deltas in
accumulated_tool_input but never fold it back into current_tool_use["input"],
so function_args reads an empty {} at contentBlockStop. Parse the accumulated
input into the tool-use block (with a {} fallback) in both the sync and async
streaming handlers. This is the streaming counterpart of the non-streaming fix
in #5415 (issue #4972).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(bedrock): coerce non-dict streaming tool input to empty dict

json.loads on the accumulated tool input can return a valid-but-non-object
JSON value (e.g. a string or list), which would fail at fn(**function_args)
with a TypeError. Enforce a dict shape before use in both the sync and async
streaming handlers, and add a regression test for the non-dict case.

Addresses CodeRabbit review feedback on #6150.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-04 20:19:47 +05:30
João Moura
a024115e4e [docs-freeze] docs: snapshot and changelog for v1.15.20 (#7271) 2026-09-04 09:42:07 -03:00
João Moura
1457740528 feat: bump versions to 1.15.20 (#7270) 2026-09-04 09:40:31 -03:00
Vinicius Brasil
a5f26f3598 Fix legacy platform tool alias discovery (#7269)
LegacyClient filtered the server response with exact app and action
names. The platform returns canonical app names and provider action
names, so valid aliases produced no tools.
2026-09-04 09:39:25 -03:00
João Moura
04e2efbdab [docs-freeze] docs: snapshot and changelog for v1.15.19 (#7266) 2026-09-04 08:28:16 -03:00
João Moura
227844ef86 feat: bump versions to 1.15.19 (#7265) 2026-09-04 08:26:06 -03:00
João Moura
1e8cbef1b8 fix(tools): read octet-stream and xlsx urls in urlreadtool (#7261)
* fix(tools): read octet-stream URLs by sniffing the body

URLReadTool resolved content type from the Content-Type header and then
the URL path extension. Presigned object-store links carry neither: they
pin every object to application/octet-stream and use a content hash for a
path, so a SharePoint download landing in R2 was refused outright.

Sniff the already-fetched body as a third source, consulted only after the
header and both URL extensions come back with nothing. The sniff can turn
a refusal into a read but never a read into a different read, so no URL
that works today changes behavior.

Fails closed: a zip is DOCX only when word/document.xml is in its central
directory, so an .xlsx keeps its honest refusal instead of surfacing a
misleading "failed to read DOCX"; text requires a strict, whole-body UTF-8
decode with no NUL byte; an empty body identifies nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(tools): extract text from XLSX URLs

The reported presigned SharePoint link is a spreadsheet, so sniffing the
body identified it as OOXML but still had nowhere to send it: URLReadTool
had no XLSX extractor, and the file would have been refused even with a
correct spreadsheetml Content-Type.

Read workbooks with openpyxl, already a core crewai dependency, so this
adds no new one. Sheets are emitted as CSV under a "Sheet <name>:" heading,
mirroring the PDF extractor's per-page shape. read_only streams the sheets
instead of building the whole object graph and data_only takes cached
values, both of which matter for a workbook arriving from an untrusted URL.

Cells are written through csv rather than joined, so a comma, quote or
newline inside a cell cannot corrupt the grid, and trailing phantom rows
are trimmed because Excel reports sheet dimensions generously.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tools): bound xlsx expansion and refuse ambiguous ooxml packages

Bot review found two real defects in the XLSX extractor, both reproduced.

openpyxl pads every row up to a sheet's declared dimension, so a single
stray cell far down the sheet turned a 4.8 KB upload into 100,000 rows and
200,000 cells. Trimming only trailing blanks did not help, because the
stray cell sits at the end and keeps the last row non-empty. Blank rows are
now skipped as they stream, and a cell budget caps what any one workbook
can hand an agent -- announced in the output rather than silently applied.

A zip carrying both word/document.xml and xl/workbook.xml was classified as
DOCX. Two identities is not a positive identification, so it is refused.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tools): keep whitespace-only xlsx cell values

Bot review, verified: openpyxl's row padding arrives as None, so testing
cells for exactly-empty drops it just as well as .strip() did while leaving
a row whose cells the author really did fill with spaces. And rstrip() on
the rendered grid removed a trailing space from the final cell along with
the line terminator; only the terminator should go.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tools): bound xlsx scan work, not just emitted cells

The cell budget only counted cells that reached the output, and blank rows
skip before that point. A sheet can declare Excel's maximum dimension while
holding two real cells; openpyxl then pads every row out to 16,384 columns
and yields one row per gap. Measured: a 4,848-byte workbook drove 1.64
billion cell normalizations in 15.2 seconds with the budget never touched.

Charge a separate scan budget per row, before the row is normalized and
before the blank check, so the work a hostile sheet can demand is bounded
whether or not any of it is emitted. The regression test asserts the read
completes in under 5 seconds and is mutation-verified: dropping the per-row
charge takes it back to 26 seconds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(deps): clear the six pip-audit advisories

gitpython 3.1.58 has PYSEC-2026-3785 through -3788, fixed in 3.1.59; the
lock now takes 3.1.61. Its exclude-newer-package cutoff is dropped rather
than bumped -- the global 3-day cutoff has long since passed 2026-08-05, so
that per-package pin was only holding the fix back.

snowflake-sqlalchemy 1.10.0 has GHSA-8g6f-qw9x-4q6q (SQL injection and
local file disclosure), fixed in 1.11.0.

unstructured 0.18.32 has GHSA-4mvj-m6j5-pmf7, a full-read SSRF via the url=
argument of partition(). The patched 0.24.0 requires Python >=3.11 while
crewai-tools supports 3.10, so the floor carries a marker and 3.10 stays on
the old line. 0.24+ also requires beautifulsoup4>=4.14.3, so the bs4 pin
widens from ~=4.13.4 to >=4.13.4,<5 -- a widening, so no existing install
breaks. uv resolves bs4 4.13.5 on 3.10 and 4.15.0 on 3.11+.

pip-audit locally: "No known vulnerabilities found, 5 ignored", with no new
--ignore-vuln entries. Only crewai-tools[xml] grows, gaining spacy and
openai-whisper transitively through unstructured's extras.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tools): narrow bs4 find_all results without a cast

Widening the beautifulsoup4 pin let uv resolve 4.15.0 on Python 3.11+ while
3.10 stays on 4.13.5, because the old unstructured line holds it back there.
4.15 types find_all precisely, so cast(Tag, link) became redundant and mypy
failed the 3.11-3.13 type-checker jobs while 3.10 passed.

isinstance narrowing is correct under both versions and is what AGENTS.md
asks for anyway. Verified by running mypy against 4.15.0 and again against
4.13.5: browser_toolkit is clean under both, leaving only the pre-existing
errors in crewai/rag/embeddings/providers/ibm.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(deps): declare security floors in crewai-tools, not only as overrides

Bot review caught a regression I introduced. override-dependencies replace
the whole requirement including its marker, so gating the unstructured
override on python_version >= '3.11' dropped the dependency outright on
3.10: the lock held only 0.24.1, never the 0.18 line the comment claimed.
crewai-tools[xml] would have installed no unstructured at all there.

Move the floors into lib/crewai-tools/pyproject.toml, where a marker split
means what it says -- >=0.24.0 on 3.11+, >=0.17.2 below -- and drop the
root override for unstructured entirely. The lock now carries both 0.18.32
and 0.24.1 under complementary markers.

Same reasoning applies to the other two, per the nltk precedent already in
that file: a uv override only shapes this workspace's lock, so consumers
installing crewai-tools[snowflake] or [github] were still getting the
vulnerable floors. Declared there now as well.

Also documents the tool as a fit for presigned and share links from S3, R2,
Google Drive, OneDrive and SharePoint -- the case this PR fixes -- while
saying plainly that it reads a URL and does not authenticate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore: update tool specifications

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-09-04 16:51:47 +05:30
Havel Cyrus
92eb5f9183 fix: append trailing user turn in native Gemini provider (#6973)
* fix: append trailing user turn in native Gemini provider

GeminiCompletion._format_messages_for_gemini maps assistant messages
to Gemini's 'model' role but never guards against the resulting
contents list ending on a model turn. CrewAI's own agent loop (max
iterations, guardrail retries) can produce exactly that history, and
Gemini's generateContent API rejects it with 400 'Requests ending
with a model turn are not supported'.

Mirrors the existing Mistral/Ollama guard in
LLM._format_messages_for_provider, which never applies to Gemini
since gemini/google model strings resolve to this native provider
instead of the LiteLLM fallback path.

Fixes #6972

* fix: append trailing user turn for Gemini on the LiteLLM fallback path

LLM._format_messages_for_provider already guards Mistral/Ollama
against a trailing assistant turn, but Gemini models routed through
the LiteLLM fallback (no google-genai installed, or a model name not
recognized as native) had no equivalent guard. litellm's own
Vertex/Gemini transformation doesn't handle this either, so the
request reaches Gemini's generateContent API unguarded and 400s.

Complements the native-provider fix in GeminiCompletion, covering
both dispatch paths.

* fix: don't append text turn after unresolved Gemini function call

Address CodeRabbit review on #6973: appending a plain 'Please
continue.' user turn after a trailing model turn that contains an
unresolved function_call violates Gemini's function-calling protocol
-- it requires a matching functionResponse, not free text. Raise a
targeted error instead so the caller notices rather than silently
sending a malformed follow-up.

Also strengthens the native-provider formatting tests to assert exact
role sequence and text content (not just the last role), per review,
and adds a regression test for the unresolved-function-call case.

* fix: guard None parts when checking Gemini history for unresolved function call

contents[-1].parts is typed list[Part] | None; iterating it directly
failed mypy (union-attr) on 3.10-3.13. Narrow to [] before the any()
check and document the ValueError in the docstring.

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-03 16:26:44 +05:30
Parthiban Sivakumar
c90337ba5a fix(llms): normalize scheme and port in Ollama base URL (#7206)
* fix(llms): normalize scheme and port in Ollama base URL

OLLAMA_HOST follows Ollama's own convention and may be a bare host
("0.0.0.0") or a host:port pair ("127.0.0.1:11434") rather than a full
URL. _normalize_ollama_base_url only appended "/v1", so those values
produced invalid base URLs such as "0.0.0.0/v1", and every request
failed with the misleading error "Failed to connect to OpenAI API:
Connection error." - confusing, since no OpenAI model was requested.

Fill in the missing parts the way Ollama's own client does: prepend
http:// when no scheme is present, append the default port 11434 when
none is present and the scheme is http (https implies 443), then append
the /v1 suffix the OpenAI-compatible endpoint requires.

Six of nine realistic OLLAMA_HOST forms were affected, including
127.0.0.1:11434, which is Ollama's documented default.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(llms): strip only the parsed path when normalizing Ollama base URL

Stripping trailing slashes from the whole URL before parsing corrupted
inputs that carry a query or fragment. "http://ollama/?tenant=acme" kept
a "/" path and produced a doubled "//v1", and a query or fragment ending
in "/" silently lost that character.

Parse first, then rstrip only parts.path. Adds regression tests for a
root path alongside a query and for a query value ending in "/".

Reported by CodeRabbit on #7206.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-03 16:05:56 +05:30
Vidit Ostwal
3d72c707d5 chore(ci): ignore unpatched nltk GHSA-8mgp-746c-j5xp (#7215)
* chore(ci): ignore unpatched nltk GHSA-8mgp-746c-j5xp

No patched PyPI release exists beyond 3.10.3. nltk is transitive via
crewai-tools[xml] -> unstructured; CrewAI does not call the vulnerable
model-artifact APIs.

Co-authored-by: Vidit Ostwal <Vidit-Ostwal@users.noreply.github.com>

* chore(ci): note dropping nltk GHSA ignore on the next bump

Leave an explicit TODO beside the ignore so GHSA-8mgp-746c-j5xp is
removed when nltk moves past the unpatched 3.10.3 floor.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Vidit Ostwal <Vidit-Ostwal@users.noreply.github.com>
2026-09-02 10:04:20 -07:00
Zhewen Tan
98799a3b09 fix(memory): preserve reusable scope configs (#7068)
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-02 19:35:30 +05:30
Vidit Ostwal
1cef70de52 fix: bump pypdf to 6.16.2 for GHSA-jp53-mhqp-8xcg (#7200)
* fix: bump pypdf to 6.16.2 for GHSA-jp53-mhqp-8xcg

pypdf 6.15.0 fails pip-audit on three moderate DoS advisories; 6.16.1+ patches them.

* chore: keep existing uv.lock environment markers

A full uv lock refresh rewrote unrelated dependency markers; restore them so the pypdf bump stays isolated.

* chore: drop unused pypdf exclude-newer-package in crewai-files

~=6.16.1 plus the global 3-day cutoff already admits 6.16.2.

* chore: drop pypdf from exclude-newer-package

6.16.2 is already older than the global 3-day cutoff; the version floor is enough.
2026-09-02 10:38:33 -03:00
Fang Kaiqi
b608a3595c docs: remove CodeInterpreterTool from AI/ML overview examples (#7100)
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-02 10:31:18 +05:30
Fang Kaiqi
f5db5a1788 docs: point prompt-template link at its current path (#7101)
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-02 10:21:40 +05:30
Vinicius Brasil
968c3065d3 Add Clipper integrations client (#7196)
* Add Clipper integrations client

Implement the internal Clipper discovery and execution contract with
deployment authentication and normalized results. Keep
CrewAIPlatformTools on LegacyClient until the new path is ready for
selection.

* Allow Clipper requests without deployment instances

Local and self-hosted CrewAI executions can have a valid integration
token without a deployment instance UUID. Send the deployment header
when it is available and allow Clipper to attribute other executions to
the organization.

* fixup! Allow Clipper requests without deployment instances

* fixup! Add Clipper integrations client
2026-09-01 14:11:43 -07:00
Vidit Ostwal
818f2624e8 [OSS-149] Accept 1/yes/on on telemetry disable flags (#7185)
* fix(telemetry): accept 1/yes/on on disable flags

CREWAI_DISABLE_TELEMETRY=1 was ignored because the gate only matched true, so telemetry stayed on with no warning.

* fix(telemetry): warn once on unrecognized disable values

Stop repeating the same invalid-flag warning on every telemetry check, and drop the undocumented CREWAI_DISABLE_TRACKING alias from docs.

---------

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2026-09-01 11:41:20 -07:00
Vidit Ostwal
8e46205619 [OSS-151] Fail closed when human-feedback emit cannot classify (#7188)
* fix(flow): resolve @human_feedback emit LLM from the project model

Omitting llm= no longer hardcodes OpenAI. Collapse and learn resolve through create_llm so MODEL / MODEL_NAME / OPENAI_MODEL_NAME win, then DEFAULT_LLM_MODEL.

* fix(flow): fail closed when human-feedback collapse cannot classify

Stop routing to emit[0] when the collapse LLM cannot be called or its response does not match an outcome. Empty skip still uses default_outcome.

* refactor(flow): extract human-feedback collapse matching helpers

Move match/require outcome helpers out of _collapse_to_outcome so the classify path stays flat.

* refactor(flow): catch only LLM call failures in collapse

Keep HumanFeedbackCollapseError from matching outside the call try so it is raised once and does not trigger a second prompt.

* fix(flow): treat non-object JSON as raw collapse text

Avoid AttributeError when the collapse LLM returns JSON that is not an object.
2026-09-01 17:25:07 +00:00
Thiago Moretto
1bc2e0722d feat(flows): add now() to the CEL expression environment (#7194)
* feat(flows): add now() to the CEL expression environment

CEL expressions in flow definitions had no way to produce the current
date: the environment was built bare, so date-dependent flows failed at
runtime. Register a now() function that returns the current UTC time as
a CEL timestamp. The value is frozen once per kickoff so every
expression in a run sees the same instant, even across midnight.

Standard CEL covers formatting from there: string(now()),
now().getFullYear(), now() - duration('24h').

* chore(flows): drop redundant comment on _cel_now

* refactor(flows): derive CEL env and functions from one registry

A function now lives in one _CelFunctionSpec entry: its annotation for
compile and its implementation factory for evaluate, so the two cannot
drift. Run-scoped values move into _CelRunContext; adding one is a
field, not a new parameter through every helper signature.

* chore(flows): drop _CelRunContext docstring

* fix(flows): freeze a fresh cel now() on human-feedback resume

resume_async never passes through kickoff_async, so a flow restored
with from_pending() had no frozen instant and now() fell back to live
wall-clock per expression. Freeze a fresh instant at resume instead of
persisting the kickoff one: a flow can pause on feedback for days, and
expressions after resume must see today.
2026-09-01 17:05:47 +00:00
Vinicius Brasil
48cc5d4e5e Decouple platform tools from the integrations API (#7180)
* Decouple platform tools from the integrations API

Define normalized selector and tool data so platform tool creation does
not depend on the legacy API response shape. This contract makes the
legacy client easier to replace later.

- Move action discovery and response normalization into LegacyClient.
- Pass ToolInfo from discovery through tool creation and execution.
- Replace the builder flow with direct factory orchestration.
- Preserve app, action, and connection data in immutable models.
- Build sanitized tool names from the full tool identity.
- Preserve legacy request, SSL, and failure behavior with contract tests.

* fixup! Decouple platform tools from the integrations API

* fixup! Decouple platform tools from the integrations API

* fixup! Decouple platform tools from the integrations API

* fixup! Decouple platform tools from the integrations API
2026-09-01 16:07:08 +00:00
Lorenze Jay
917b9df6d7 Validate JSON crews in project environments (#7171)
* Validate JSON crews in project environments

* fix(cli): address standalone deploy review feedback

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-09-01 16:00:59 +00:00
João Moura
ec53d6f534 fix(llms): native structured outputs for current claude models, and snowflake CVE floor (#7182)
* fix(llms): let current claude models use native structured outputs

NATIVE_STRUCTURED_OUTPUT_MODELS only listed 4.5-era prefixes, so Opus 5,
Sonnet 5, Fable 5 and Opus 4.8 fell through to the forced-tool-call
fallback. That path also overwrites params["tools"], so a call combining
tools with a response_model silently lost the caller's tools.

_infer_provider_from_model documented a pattern-matching fallback it never
performed, so a Claude release newer than the constants list resolved to
"openai". Bedrock ('.' in model) and Azure (every OpenAI prefix) are left
out of that fallback because they would capture gpt-* models.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(llms): route bedrock-namespaced anthropic ids to bedrock

"anthropic.claude-*" is Bedrock's namespace, not the Anthropic API, and it
satisfies the anthropic prefix pattern. Settle it before the pattern loop so
an unlisted Bedrock id picks BedrockCompletion. The region-prefixed form
("us.anthropic.claude-*") was resolving to openai, so this repairs that too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(deps): raise snowflake-connector-python floor for CVE-2026-15925

GHSA-5cc2-282f-jjq2 (CRITICAL): the connector does not verify TLS hostnames,
so a network attacker can impersonate the Snowflake endpoint. Fixed in 4.7.1.

crewai-tools[snowflake] declares "snowflake-connector-python>=3.12.4", which
the lock had resolved to 4.6.0. Following the existing convention, the security
floor goes in [tool.uv] override-dependencies rather than the source
declaration, matching how cryptography is handled.

Relocking also refreshes numpy/humanfriendly/nvidia environment markers, which
re-resolution under the relative exclude-newer window produces regardless of
this change.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 12:01:22 +05:30
Vinicius Brasil
381fef73be Add injectable client for CrewAI platform tools (#7177)
* Add injectable client for CrewAI platform tools

Define an integrations client contract for action discovery and
execution. Keep the existing platform API as the default client to
preserve current behavior.

Allow callers to provide a custom client through CrewaiPlatformTools.

* Fix platform action tool failure tests

* Remove redundant protocol placeholders
2026-08-31 16:01:54 -07:00
Vidit Ostwal
bf56bb13bd ci: require an open issue for first-time contributor PRs (#7169)
* ci: require an open issue for first-time contributor PRs

Gate anyone who is not a returning contributor, and allow the PR only when a closing keyword points at an open issue in this repo.

* ci: accept any open issue mention for first-timer PRs

Drop the closing-keyword regex so #123, owner/repo#N, or an issue URL is enough when that issue is open.

* ci: ignore foreign owner/repo#N in first-timer issue gate

Bare #123 no longer matches the suffix of other/repo#123, so an open local issue cannot keep that PR open.
2026-08-31 22:48:14 +05:30
Vidit Ostwal
614efcdd30 ci: close first-time contributor PRs that lack a linked issue (#7164)
* ci: close first-time contributor PRs that lack a linked issue

* ci: indent FTC close comment so the workflow YAML parses
2026-08-31 21:29:59 +05:30
Vidit Ostwal
0e7625813b fix: bump nltk to 3.10.3 for PYSEC-2026-3726 (#7162)
Force the xml extra and workspace override onto the patched release so pip-audit stops failing on the 3.10.0 symlink file-read advisory.
2026-08-31 21:26:41 +05:30
Ran Shemtov
a35fbc864d docs: update channels guide to current copilotkit channels api (#7016)
* docs: update channels guide to current copilotkit channels api

* docs: translate channels and frontend overview guides to ar, ko, pt-BR

---------

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2026-08-31 15:47:58 +00:00
chenshiyang
265697b6f8 docs: refresh retired Gemini model ids (#7003)
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-31 10:43:31 -03:00
Vinicius Brasil
da4daadba0 Parse platform application selectors (#7148)
Stores application, action, and connection values in an internal
selector. Validates the selector with clearer error messages. Keeps
existing application syntax and legacy API requests unchanged.
2026-08-28 15:36:29 -07:00
Lucas Gomide
e9d4c57b2a fix: run model call hooks on every path and propagate a deny (#7111)
* fix: let a hook deny reach the caller as a deny

A hook that raised `HookAborted` on `pre_model_call` never reached the code
making the call: the LLM layer caught it and returned `False`, which providers
translated into `ValueError("LLM call blocked by before_llm_call hook")`,
dropping the reason and the source and making a policy decision
indistinguishable from a provider outage. Every internal model call then
absorbed that error through the `except Exception` that keeps a provider hiccup
from failing a run, so memory analysis fell back to defaults and the converter
and reasoning handler retried the call that was just denied. The abort now
propagates out of the LLM layer while the boolean convention keeps its
documented `ValueError` via `LegacyHookBlocked`, and the fail-open handlers
around internal model calls re-raise it instead of degrading.

* fix: dispatch model call hooks on the paths that skipped them

A model call was only checked when the executor loop drove it: the
`from_agent is not None` short-circuit in `base_llm` silenced the hooks
for agent planning and step observation, no provider `acall` dispatched
them at all, and `InternalInstructor` bypassed `llm.call` entirely. This
replaces that short-circuit with an explicit
`model_call_hooks_already_dispatched` window so the enclosing caller
claims the dispatch, adds the pre-call dispatch to every provider's
`acall`, and runs the hooks around the Instructor client call. A denial
now emits a denied event instead of being logged and reported as a
provider failure.

* fix: report a boolean-convention deny as a deny, not an outage

A `before_llm_call` hook that blocks by returning `False` reached the five
native providers as a plain `ValueError`, which fell through to their generic
`except Exception` and was logged and emitted as `OpenAI API call failed: ...`
— the same deny raised as `HookAborted` was already labelled correctly, so the
two dialects disagreed on whether a policy decision was a provider outage. The
LLM layer now converts it into `LLMCallBlockedError`, still a `ValueError` so
the fail-open handlers around internal model calls keep absorbing it, but its
own type so a provider can report the decision it is. Since a block is raised
rather than returned, the thirteen callers that turned the return flag into a
raise by hand drop that line, and `_prepare_llm_call` raises the same type.

* fix: keep a denied plan from letting the agent run unplanned

`AgentExecutor.generate_plan` wraps `handle_agent_reasoning()` in a bare
`except Exception`, so guarding the reasoning handler alone still left the
deny absorbed one frame up: the executor logged "Error during planning" and
the agent proceeded with no plan. It now re-raises `HookAborted` like the
other planning boundaries, and the accompanying test also covers the
boolean convention still degrading at a fail-open site.

* fix: stop a denied knowledge query from running the task without knowledge

`handle_knowledge_retrieval` and its async twin wrap the query rewrite in
their own `except Exception`, so guarding `_get_knowledge_search_query`
alone still let `execute_task` continue on the unaugmented prompt after a
deny. Both now emit the terminal `KnowledgeSearchQueryFailedEvent` and
re-raise `HookAborted`, matching the second-frame guard already added to
`AgentExecutor.generate_plan`. Also documents the abort contract on
`PlannerObserver.observe`.

* fix: stop nine callers from re-swallowing a model call deny

CodeRabbit caught the replan path re-swallowing a deny, so an AST sweep of
every caller of a guarded function found the same defeat in nine places:
classic and replan planning, memory recall and memory save on both `Agent`
and `LiteAgent`, the base executor's save, and `LLMGuardrail.__call__`,
which turned a refused call into validation feedback. Each now re-raises
`HookAborted` after emitting whatever terminal event it owes, while every
other failure keeps degrading as before — the knowledge guards move to that
same idiom instead of duplicating their emit.

* fix: pair a denied guardrail with the event it started

Re-raising from `LLMGuardrail` left `process_guardrail` between its started
and completed events, so a denied validation read as one still in flight
rather than a policy decision. It now emits `LLMGuardrailCompletedEvent`
with the deny reason before the abort leaves, matching what every other
guarded site in this change already does.

* fix: stop retrying a task after a hook denied its model call

`Agent.execute_task` funnels every exception into `_handle_execution_error`,
which re-runs the whole task up to `max_retry_limit` times, so a policy deny
read as a transient blip: a crew whose first model call was denied retried and
returned a normal answer. `HookAborted` now joins `_passthrough_exceptions`,
the tuple already reserved for deliberate stops. The new boundary tests drive
the public entry points instead of the frame that makes the call, and count
model calls so a deny that gets retried fails the assertion — ten of the twelve
fail against `main`.

* fix: stop a denied plan step from being reported as a failed step

Making model call hooks reachable on agent-bearing calls put a deny inside
`StepExecutor.execute`, whose broad `except Exception` turned it into
`StepResult(success=False)` and let the plan carry on; `HookAborted` now
joins `ToolExecutionFailedError` in the passthrough handlers there, and
`execute_todos_parallel` re-raises a deny that `return_exceptions=True`
would otherwise record as one failed todo. `_emit_call_denied_event` also
renders the source through the now-public `source_name`, so a hook that
names itself with a callable reads as its name instead of a repr.

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-28 12:32:09 -04:00
João Moura
cba6c03646 feat(events): record how a crew run ended, for every user (#7118)
* feat(events): record how a crew run ended, for every user

Crew was the one level with no ungated terminal record. `Crew Execution` and
`end_crew` are both behind `share_crew`, which defaults False, so for
essentially every run there is no end-of-crew span at all - not one with fields
missing. Task outcomes ship ungated, flow outcomes ship ungated; crew being the
exception looks like an accident of history rather than a decision.

Adds `Crew Completed` carrying `outcome` and an explicit `duration_ms`, keyed by
crew_key/crew_id so it joins the existing ungated `Crew Created`. Modelled
directly on `flow_completed_span`, including its reasoning: a separate span
rather than holding `Crew Execution` open, because that span is emitted and
closed at start, so holding it would drop every run that is killed or crashes.

`on_crew_failed` called no telemetry at all before this, so a failed crew
produced nothing. It deliberately does not call `end_crew`, which writes onto
the gated execution span a failed run may never have opened.

Deliberately NOT included, each for a reason:

- Tokens. `crew.token_usage` sums per-agent LLM counters, and two agents sharing
  one LLM object share one counter, so the total double-counts today. Putting it
  on a span would propagate a known-wrong number into a metric. The dedup keys on
  `id(llm._token_usage)`, not `id(llm)` - `Agent.copy()` shallow-copies the LLM -
  and it changes the value of public `Crew.calculate_usage_metrics`, so it earns
  its own change.
- Models. Already on the ungated `Crew Created` span at 99.86% coverage; this
  joins to them by crew_id rather than duplicating.
- Tool counts. The ungated `Tool Usage` span covers only the ReAct path, the
  plan/step path double-emits, and nested crews share one RuntimeState - the
  count needs a design decision on cache hits before it is worth emitting.
- error_type. Needs 4.1's exception-class field factored out of task_events so
  both events share it, rather than duplicated hours after that merged.

Tests use the exporter pattern this suite already uses rather than mocking
`EventListener._telemetry`: EventListener is a singleton, so swapping that leaks
a MagicMock into every later test. The listener tests assert on the stamp
lifecycle instead. Verified order-independent over five randomized runs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(telemetry): docstring the crew-completed helpers

Eight of the thirteen functions in this file carried a docstring and five
did not, which is an inconsistency inside the file this PR adds rather
than anything inherited. Documents the two fixtures, the span lookup, the
event-bus runner and the two test methods that were missing one.

No behaviour change: 9 passed, and re-run under random ordering on two
seeds to confirm order-independence.

Deliberately not addressed: the reviewer's 52.17% docstring-coverage
figure is dominated by event_listener.py, where 84 functions - nearly
every pre-existing on_* handler - carry no docstring. That is the file's
convention, and documenting them here would be an unrelated refactor.
The public API this PR adds, Telemetry.crew_completed_span, is documented.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 13:06:51 -03:00
João Moura
1f6e327b3c feat(events): report machine size as a coarse band, not a core count (#7117)
* feat(events): report machine size as a coarse band, not a core count

`runtime_context` says where a process runs but carries no capacity axis, and
its largest bucket is a catch-all: a gunicorn worker on a VM and
`python main.py > out.log` on a MacBook both report `non_interactive`. Docker
Desktop on a laptop reports `container` via /.dockerenv, and a Remote-SSH shell
on a server reports `vscode_terminal`. So "server or laptop" is not answerable
from it today.

Adds `cpu_band` to the common span attributes, so it rides every span the way
`runtime_context` does rather than sitting on `Crew Created` alone - which would
answer nothing for Flow-only, CLI-only or standalone-agent runs.

Six bands, powers of two, top one open-ended: 1-2, 3-4, 5-8, 9-16, 17-32, 33+.
Open-ended because the exact count is the fingerprint - the observed fleet
maximum is 512, and a span reporting 512 identifies one machine. The vocabulary
is closed and asserted, like KNOWN_CODING_AGENTS and KNOWN_RUNTIME_CONTEXTS.

The share_crew-gated exact `cpus` attribute and the four platform* attributes
are untouched. That gating was a deliberate 2024 classification of machine
fingerprint as shareable content (44e38b1d5), and this does not reverse it: a
band is a range, the gated attribute remains the precise value.

Documents a trap in the docstring rather than leaving it to be rediscovered:
os.cpu_count() reports HOST cores, not the cgroup quota, so a 1-vCPU pod on a
96-core node lands in 33+. Right for "what kind of machine", wrong for "what did
this run get" - os.process_cpu_count() gives the latter but needs 3.13, above
this package's floor.

Docs updated in en/ar/ko/pt-BR, in the default-on Execution Environment row,
stating explicitly that the band is a range and the exact count stays opt-in.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(telemetry): say where the cpu band comes from

The Execution Environment row ended "Detection reads only whether known
environment variables are set, never their values". True for the assistant
and runtime-context fields, and wrong for the band this PR adds:
detect_cpu_band() reads os.cpu_count() (runtime_env.py:306) and touches no
environment variable. In a privacy disclosure table that is the kind of
inaccuracy worth a line.

Names the source explicitly and scopes the env-var sentence to the two
fields it actually describes. All four locales at parity.

pt-BR also takes the reviewer's wording fix: "um de uma lista fixa" ->
"um valor de uma lista fixa", and the missing comma before o `project_id`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 08:50:10 -07:00
Lorenze Jay
4bc5d29242 [docs-freeze] docs: snapshot and changelog for v1.15.18 (#7138) 2026-08-27 18:07:05 +00:00
Lorenze Jay
5fd7c47669 feat: bump versions to 1.15.18 (#7136) 2026-08-27 18:00:28 +00:00
Lorenze Jay
f90d37b4ac feat(flow): promote conversational flows to stable (#7107)
Move the canonical API into crewai.flow while preserving experimental imports and declarative references through compatibility aliases.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 23:06:57 +05:30
Lorenze Jay
5139078c6a fix(agents): preserve tool results when final answer is empty (#7133)
* fix(agents): preserve tool results when final answer is empty

Updated the StepExecutor to ensure that if the final answer from a tool call is empty, the last valid tool result is returned instead. This change enhances the reliability of the output in scenarios where the final answer may not provide useful information. Added tests to verify that both text and native steps correctly preserve tool results under these conditions.

* raise on empty string path
2026-08-27 22:10:11 +05:30
João Moura
fcdeb3d98d feat(events): record a created deployment with the uuid it was given (#7115)
`Create Crew Deployment` fires before the API call that creates the
deployment, so it counts creation ATTEMPTS and cannot carry the uuid - the
call that creates the deployment is the call that returns it. Live effect:
`create_deployment` reads 76,015 events with 0 carrying a uuid (0.000%), so
deployments cannot be joined to anything.

Moving the existing span after the response would fix the uuid and silently
redefine the metric, turning attempts into successes; the deployment churn
figures are built on attempts. So this adds a second span rather than moving
the first.

`Crew Deployment Created` fires after `_validate_response`, which raises
SystemExit on failure - a failed create therefore still counts as an attempt
and reports no creation. Both creation paths, git remote and zip upload,
converge on that line and both return the uuid.

Emits no `deploy:created` feature count: the attempt span already does, and a
second emit would double the deployment count that origin-independent
aggregation depends on.

Tests cover the emitter (uuid carried, distinct span name, no second feature
count, absent-vs-empty uuid) and the call site across both creation paths plus
the failure path.

The warehouse consumer must be widened BEFORE this merges or it delivers
nothing: `mv_span_fanout_forward` filters on a hard-coded 13-name allowlist,
and `mv_fanout_deployment_spans`'s `multiIf` ends in a catch-all `remove_crew`
arm that would mislabel the new span. Runbook prepared separately.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 17:13:17 -07:00
Vidit Ostwal
704db1d66f fix(llms): map default Claude Sonnet 4.6 to its 1M context window (#7125)
* fix(llms): map default Claude Sonnet 4.6 to its 1M context window

Native AnthropicCompletion fell back to 200k for claude-sonnet-4-6, so the default instance understated the documented limit.

* fix(llms): align Anthropic context windows with active Claude models

Retired Claude 3/2/Instant IDs no longer have dedicated entries; the map now covers the current Claude API lineup and their documented 1M vs 200k windows.

* fix(llms): map Claude Mythos 5 to its documented 1M context window

Native AnthropicCompletion fell back to 200k for claude-mythos-5 even though Anthropic lists a 1M-token window.
2026-08-26 14:09:35 -07:00
Vidit Ostwal
039f6ff5f6 fix(llms): raise Anthropic default max_tokens so large tool calls survive (#7077)
* fix(llms): raise Anthropic default max_tokens so large tool calls survive

* fix(llms): default Anthropic to sonnet-4-6 and drop retired models

---------

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2026-08-26 19:01:31 +00:00
Vidit Ostwal
56e0e85a81 [OSS-115] Persist custom conversational replies after fallback append (#7026)
* fix(flows): persist custom conversational replies after fallback append

Custom @listen routes that only return a public string were appended after kickoff, so @persist snapshots missed the assistant turn. Snapshot again from the same persist path once the fallback writes state.messages.

* test(flows): cover @persist restore of custom conversational replies

Add regression coverage for custom @listen returns across fresh Flow instances, no double-append on built-in converse, and a single user/assistant message-added event.

* docs: note that public listen returns persist as assistant replies
2026-08-26 09:41:28 -07:00
Vidit Ostwal
871c9c5131 chore(telemetry): remove unused _safe_telemetry_operation from crewai_core (#6977) 2026-08-25 20:29:02 +00:00
João Moura
6ad3bf9390 fix(agents): render message content parts as text, not a python repr (#7109)
* fix(agents): render message content parts as text, not a Python repr

A message whose `content` is a multimodal parts list collapsed to
`str(content)` wherever a message had to become a string, so the model
saw `[{'type': 'text', 'text': 'hello'}]` in Current Task, and memory
stored and searched that same repr.

Four sites flattened it that way: the turn promoted into the executor
prompt, the memory recall query, what `_save_kickoff_to_memory` writes,
and `_message_content_text` (token estimation and oversized-message
splitting).

The extraction already existed, inline in `_format_messages_for_summary`
-- text blocks joined, or `[multimodal content]` when a list carries
none. This lifts it to `_content_parts_text` and routes all five callers
through it, so summary, prompt, memory and token counting agree.

`_message_content_text` becomes `message_content_text`: it now has a
caller outside its module, and `agent/core.py` imports only public names
from `agent_utils`. It is not re-exported from any `__init__`, so no
public import path changes.

`test_list_content_uses_str` pinned the repr, so it is intentionally
rewritten to pin the text. Every other existing caller is unchanged:
30 failures on main, 30 on this branch, identical names.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwxiogL9mQg9q8cx4qLfYJ

* fix(agents): skip a content part whose text is not a string

`_content_parts_text` joined `block["text"]` straight into a string, and
content blocks are `dict[str, Any]` arriving from a model, so a `text`
key holding an int, dict or None raised `TypeError`. That was contained
to summarization before; routing the prompt, memory and token-estimation
paths through the same helper widened it to `Agent.kickoff`, where the
old `str()` had merely produced an ugly string.

Such a block carries no usable text, so it is skipped. A list left with
nothing usable still falls back to `[multimodal content]`.

Writes the convention down in AGENTS.md rather than leaving it in a
review thread: never `str()` a message's content, use
`message_content_text`. Four sites had independently reached for
`str()`, which is what this whole change is undoing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwxiogL9mQg9q8cx4qLfYJ

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 19:34:05 +00:00
Vidit Ostwal
7c23857aed [OSS-137] Report MCP HTTP auth failures instead of cancelled connections (#7067)
* feat(mcp): add shared error classifier for HTTP auth failures

When an MCP server refuses a streamable-HTTP connection, the HTTP status is
observed by the client but often buried inside anyio teardown. Add typed
connection exceptions and helpers to recover the status from exception groups,
CancelledError context chains, and httpx errors so later call sites can report
authentication failures instead of guessing.

Groundwork only; no call sites wired yet.

* feat(mcp): raise typed errors from HTTPTransport.connect on HTTP status

When streamable-HTTP connect fails with an httpx HTTPStatusError, classify
the status via the shared MCP exception helpers and raise MCPAuthenticationError
for 401/403 or MCPHTTPError for other refused statuses instead of a generic
ConnectionError that hides the credential problem.

* refactor(mcp): centralize raise_connection_failure and simplify connect

Move connection failure classification into exceptions.py so transports and
clients share one helper. Flatten HTTPTransport.connect to a single except
path that cleans up once and raises, avoiding the outer handler re-classifying
errors the inner handler already typed.

* fix(mcp): classify auth failures in MCPClient.connect before reporting cancelled

When a streamable-HTTP server refuses the connection, the awaiting coroutine
often sees only CancelledError while the HTTP status surfaces during transport
unwind. Inspect cleanup for the status before emitting error_type=cancelled,
and fix HTTPTransport.disconnect so it raises typed errors instead of
suppressing exception groups that carry the refusal.

* fix(mcp): replace speculative tool resolver errors with classifier

Use raise_connection_failure for native MCP discovery instead of hedged
cancel-scope wording, preserve typed MCPConnectionError from setup, and
detect event-loop presence explicitly so ConnectionError is not mistaken
for a missing running loop. Update HTTPS discovery to classify HTTP status
codes via find_http_status.

* refactor(mcp): collapse native tool resolver failure handlers

CancelledError is not an Exception subclass, so handle it alongside
Exception in one except clause and delegate to a shared helper.

* refactor(mcp): call raise_connection_failure directly in tool resolver

* fix(mcp): classify tool execution auth failures in events

Add tool_execution_error_type so call_tool_result emits authentication
instead of server_error for MCPAuthenticationError and HTTP 401/403.
Preserve typed MCPConnectionError in _retry_operation instead of flattening
them into a generic ConnectionError first.

* feat(mcp): add status_code to MCPConnectionFailedEvent

Surface the HTTP status observed during connection failures on the event
payload and in verbose console output, so executions and checkpoints record
401/403 alongside error_type=authentication instead of only the message text.

* fix(mcp): handle cancellation and exception groups in auth paths

Ensure discovery cleanup runs on CancelledError, classify mixed
BaseExceptionGroups during HTTP connect, and fix ExceptionGroup imports
on Python 3.10 with regression tests.

* fix(mcp): preserve auth errors from discovery disconnect cleanup

Re-raise MCPConnectionError from disconnect during cancellation cleanup
instead of logging and swallowing it, with a regression test.

* fix(mcp): unwind transport context to recover auth on cancel

Always exit pending streamable-HTTP contexts before classifying failures,
handle CancelledError during client cleanup, propagate typed HTTPS discovery
errors, and add regression tests for the teardown recovery path.

* fix(mcp): classify auth from groups and timeout teardown

Handle BaseExceptionGroup in HTTPS discovery and recover HTTP 401 from
streamable-HTTP context exit after connect timeouts, with regression tests.

* refactor(mcp): consolidate client connection failure reporting

Extract _report_connection_failure and delegate _http_failure and
_connection_failure to it without changing connect error behavior.

* refactor(mcp): drop redundant client failure helper wrappers

Call _report_connection_failure directly from connect() instead of
_http_failure and _connection_failure delegators.

* fix(mcp): propagate CancelledError after HTTP transport teardown

Re-raise cancellation from disconnect when no HTTP auth status is
recovered during context unwind, with a regression test.

* fix(mcp): preserve typed errors from MCPClient.disconnect

Re-raise MCPConnectionError and CancelledError from exit-stack teardown
instead of wrapping auth failures in RuntimeError, with a regression test.
2026-08-25 16:47:31 +00:00
Lucas Gomide
3df34d9169 fix: skip interception hooks on crewai-internal flows (#7079)
* fix: skip interception hooks on crewai-internal flows

The `AgentExecutor` and the memory encoding/recall flows are `Flow`
subclasses CrewAI runs for its own bookkeeping, and they were dispatching
interception points as if their methods were the caller's steps — a hook
saw machinery no user wrote, and a policy could deny a run over it.
`Flow._skip_interception` now suppresses every point on a flow marked
`is_crewai_internal`, except the execution boundary on machinery that is
itself the run the caller asked for. A standalone `Agent.kickoff()` keeps
its boundary and stays blockable, while the same executor bound to a crew
or nested in a caller's flow stays silent, so boundaries only ever fire
at the root.

* docs: note that the resume match id feeds the boundary check

`from_pending` seeds `_flow_match_id` from `instance.flow_id` for the usage
listener's filter, and `resume_async` forces `current_flow_id` to it for the
duration of the resume. `AgentExecutor._owns_execution_boundary` compares the
two, so seeding the original persisted id instead would make a resumed
standalone agent disown a boundary its kickoff already opened.
2026-08-25 09:54:17 -04:00
João Moura
4e0b2e2b15 fix(events): record task failures as failures, not as successes (#7073)
* fix(telemetry): record task failures as failures, not as successes

close_span() sets StatusCode.OK unconditionally, and TaskFailedEvent was routed
to Telemetry.task_ended, which calls it. Every failed task was therefore
exported as OK, which is why error_count downstream is not merely low but
exactly zero: 240.0M task executions across 13 months in
crew_task_executions_daily_target, error_count = 0 in every one of them.

The same line had a second defect. The span was only ended when
source.agent.crew was present, so a task failing without one was popped from the
span map and then never closed - never ended, never exported, invisible rather
than mislabelled. task_failed takes no crew (it reads nothing off one), so that
condition disappears rather than being widened.

Only the exception class name is recorded, never the message, which routinely
contains prompts, model output, file paths and credentials.
close_span_with_error drops any value failing str.isidentifier(), so a message
cannot be recorded even if one is passed by mistake.

This is the task half of closed PR #6781, re-cut onto main as that PR asked for.
The crew half is deliberately left out: crew_execution_span() returns None unless
share_crew=True, so crew._execution_span is None for nearly every user and a
crew-failure handler would exit immediately for the default population.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* fix(telemetry): take the exception class for error_type, not a free-form string

cursor and CodeRabbit both flagged the sanitization, and they were right: the
package already had a stronger convention and this change had not used it.
Telemetry._safe_error_type takes the exception *class*, and its docstring says
why in as many words - "a single-word message such as 'secret_token' is itself a
valid identifier", so filtering a string with isidentifier() is not enough. The
ported code predates that helper and reinvented the weaker check.

TaskFailedEvent.error_type is now type[BaseException] | None, so pydantic itself
rejects a message before any of our code runs, and task_failed routes it through
_safe_error_type. The identifier check in close_span_with_error stays as the
second gate on the derived name, which is the role _safe_error_type's docstring
already describes.

Also adds producer-level tests, which CodeRabbit correctly identified as missing:
every earlier test constructed TaskFailedEvent directly, so a regression in the
two emit sites this change touches in task.py would have passed the whole suite.
The sync and async producers are driven through Task._execute_core and
Task._aexecute_core with a distinctive exception class, and each patches a
different agent method (execute_task vs aexecute_task), which is why they can
regress independently. Verified by dropping error_type from both producers: all
three new tests fail, and pass again when restored.

Removes an unused `import os` left behind when the fixture was rewritten.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(telemetry): capture producer failures at the emit boundary, not via the bus

The producer tests subscribed a handler to crewai_event_bus and asserted on what
it received. That passed this file in isolation and every randomized local run,
then failed in CI inside a 621-test shard with zero events captured:

  FAILED tests/telemetry/test_task_failure_instrumentation.py::
    test_sync_producer_puts_the_exception_class_on_the_event
  assert 0 == 1  +  where 0 = len([])

task_failed is an "ending" event, and with an empty scope stack - there is no
real kickoff in these tests - dispatch is conditional on event-context state that
other tests in the same worker process can leave behind. Subscribing made the
assertion depend on the bus choosing to dispatch, which is not what these tests
are about: they are about what the producer in task.py constructs.

Patching crewai_event_bus.emit records the event unconditionally at the point the
producer hands it over, with no dispatch involved. Both producers ignore emit's
return value, so returning None is faithful.

Containment re-verified after the change: dropping error_type from both producers
fails exactly these three tests and nothing else.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* fix(events): keep TaskFailedEvent JSON-serializable with a class-valued error_type

error_type holds an exception class, which is not a JSON type, so
model_dump(mode="json") raised PydanticSerializationError for the whole event -
not just that field. Two real consumers depend on it: the checkpoint listener
dumps every event through EventRecord, and the tracing listener JSON-POSTs events
to AMP. A single task failure therefore took out checkpointing.

field_serializer with when_used="json" returns the class name. The "json" scope is
load-bearing: event_listener hands the live class to Telemetry.task_failed, which
needs it for _safe_error_type, so python-mode dumps must keep the class.

The annotation is a module-level _ExceptionClass alias rather than an inline
type[BaseException], because TaskFailedEvent declares a field named `type` which
shadows the builtin for the rest of the class body - inline, it raises TypeError
at import ("task_failed"[BaseException]) and mypy rejects it as "Variable ... is
not valid as a type". Quoting satisfies neither tool: ruff flags UP037 and mypy
still resolves it in the class scope.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* fix(events): let a dumped error_type restore, instead of degrading the event

The serializer added in the previous commit stopped model_dump(mode="json") from
raising, but nothing accepted the class-name string back. _resolve_event
(state/event_record.py:32-35) wraps cls.model_validate in a bare except and falls
back to BaseEvent, so restoring a checkpoint after a task failure silently
dropped the whole event -- including `error`, a plain string that would otherwise
have survived. Traded a loud failure for a quiet one.

Measured before: dumped error_type='ValueError' and error='boom', restored as
BaseEvent with neither attribute. After: restores as TaskFailedEvent with
error='boom' and error_type is ValueError.

A BeforeValidator resolves a name against real exception classes only -- builtins
first, then a walk of BaseException.__subclasses__(). So this does not reopen the
hole the class-typed field closes: "secret_token" resolves to nothing, is returned
unchanged, and is rejected by the field's own type. Asserted for secret_token,
sk_live_1234, dict and os.

A name whose class is not imported in this process still degrades, which is
deliberate: synthesising a class from an arbitrary string is the injection risk
this field exists to avoid.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-25 14:30:46 +05:30
Lorenze Jay
a9cb0bdf02 Lorenze/deprecate/answer from history (#7105)
* feat(flows): enhance conversational flow documentation and APIs

- Updated the description to clarify the use of `handle_turn` and structured streaming in multi-turn chat applications.
- Added a warning about the experimental nature of the conversational features.
- Improved the overview section to include structured streaming and refined the explanation of session handling.
- Enhanced the API documentation for `handle_turn`, `stream_turn`, and `chat` methods, emphasizing their roles in conversational flows.
- Clarified the turn lifecycle and the handling of user messages within the flow.
- Updated examples to reflect changes in message handling and session tracing.
- Ensured consistency across language versions in the documentation.

* feat(flow): deprecate answer_from_history route

Guide conversational flows toward the existing converse route while preserving compatibility warnings and schema metadata.

Co-authored-by: Cursor <cursoragent@cursor.com>

* stacklevel=3 raising it higher

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 11:01:22 +05:30
Vidit Ostwal
390ee770cb chore(ci): ignore unpatched chromadb HTTP-server GHSAs (#7108)
No patched PyPI release exists, and CrewAI only uses the embedded
PersistentClient, not the vulnerable HTTP server.
2026-08-25 13:21:10 +08:00
João Moura
9652af6ae0 fix(agents): keep message roles when Agent.kickoff gets a conversation (#7065)
* fix(agents): keep message roles when Agent.kickoff gets a conversation

`Agent.kickoff` accepts `str | list[LLMMessage]`, but `_prepare_kickoff` joined
every message's content into one string. Measured with a recording LLM, a
three-turn conversation reached the provider as two messages:

    system | You are Support...
    user   | Current Task: my order id is 42\nthanks, checking\nwhere is it?

So the agent's own previous reply was presented as something the user said, and
the model could not tell who said what. `LiteAgent.kickoff` already did this
correctly, which is why the same list gave four messages with roles intact
there.

The last message is now this turn's request and the ones before it travel as
`inputs["history"]` -- the way `inputs["files"]` already does -- which both
executors splice in after the system prompt and before the user prompt. Memory
recall still runs over the whole conversation text, not just the last turn.

A plain string and a single-message list are byte-identical to before, which is
what every existing caller passes.

Also widens `LiteAgentExecutionStartedEvent.messages` from `list[dict[str, str]]`
to `list[LLMMessage]`: it raised a ValidationError for a message whose content
was `None` or a content-part list, both of which are valid `LLMMessage` shapes
that `Agent.kickoff` already accepts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(agents): carry history without a system prompt, tool calls, or dup files

Three review findings on the message-role work, all real.

History was spliced only in the branch that builds a system prompt. With
`use_system_prompt=False` or a custom template there is one combined prompt, so
history went nowhere and only the last turn reached the model -- worse than the
flattening this PR replaced, which at least included the text. Both executors
now splice in either branch, via one `_append_history` helper each.

Filtering on truthy content dropped an assistant turn that only requests tool
calls, leaving a `tool` message with no preceding `tool_calls` message -- a
sequence providers reject. A message now counts when it has content, tool
calls, or a tool_call_id.

And `files` were unioned from every message onto the current request while
history messages kept their own, so prior attachments were sent twice. Only the
current request's attachments travel in `inputs["files"]` now.

Found by Cursor and CodeRabbit on #7065.

* fix(agents): treat an attachment as message payload

_carries_payload counted text, tool calls and tool results, but not files.
A final message whose only payload was an attachment was filtered out, so the
previous message became this turn request and the attachment never reached
inputs["files"].

Found independently by Cursor and CodeRabbit on #7065.

* fix(agents): promote the last user message, not the last message

build_agent_context() appends an agent private thread after the current user
turn, so on a later turn the trailing message is an assistant scratch. That
scratch became Current Task while the real question was demoted to history --
reproduced: the request came back as "internal note: checked warehouse".

The request is now the last user message, with everything else kept as history
in order; with no user message the last one stands in, which is what a
single-message caller has always got. Documented on kickoff and kickoff_async.

The old cross-check against LiteAgent only compared roles on a fixture already
ending in a user message, so it could not catch this. It now asserts what holds
for both -- nothing dropped, nothing duplicated -- since Agent has a task slot
in its prompt and LiteAgent does not.

Reported by Vidit-Ostwal on #7065.

* test(agents): cover history placement on the deprecated executor too

`CrewAgentExecutor` carries its own `_setup_messages`, and `Agent.kickoff`
builds an `AgentExecutor` unconditionally, so nothing reached the twin's
two `_append_history` sites. This drives that executor directly with the
real `SystemPromptResult` / `StandardPromptResult` shapes, so both its
branches are pinned.

Verified by mutation: removing either `_append_history` call in either
executor now fails the matching test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwxiogL9mQg9q8cx4qLfYJ

* fix(agents): keep turns that follow the request after it

`_prepare_kickoff` packed every non-request message into one `history`
list, and both executors spliced that list before the current user
prompt. A conversation ending on a tool result therefore reached the
provider as `assistant tool_calls -> tool -> user`, hoisting the tool
pair above the question it answers. `LiteAgent` sends the same list as
`user -> assistant -> tool`.

Splits the carried messages at the request instead: what came before
stays `history`, what came after travels as `trailing` and is appended
after the user prompt. Promoting the last user message to `{input}` is
unchanged.

`test_a_tool_call_sequence_survives` missed this because it ends on a
follow-up user line, so the tool pair was already before the request.

Reported by lorenzejay, who also confirmed gpt-4o-mini and gpt-5.6-sol
accept the reordered payload -- an order bug, not a provider 400.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwxiogL9mQg9q8cx4qLfYJ

* test(agents): assert the ordering through kickoff_async too

`kickoff_async` shares `_prepare_kickoff`, and the async executor entry
points reach the same `_setup_messages`, but sharing a code path is not
the same as covering it. Pins the tool-result ordering through the async
path, and lifts the tool conversation to a module-level fixture so the
sync and async assertions cannot drift.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwxiogL9mQg9q8cx4qLfYJ

* docs(agents): state where a kickoff conversation's turns land

`concepts/agents.mdx` documents the multi-message form but not which
message becomes the request or what happens to the turns around it --
the contract this branch changed. Corrects the `kickoff` /
`kickoff_async` docstrings to match.

en and ko only: the ar and pt-BR pages do not carry the "Multiple
Messages" section at all, which is a pre-existing translation gap rather
than one this change introduces.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VwxiogL9mQg9q8cx4qLfYJ

* feat(flow): let a declarative agent action receive the conversation (#7066)

* feat(flow): let a declarative agent action receive the conversation

A chat handler could only hand its agent a single string, so a declarative
conversational flow's `agent` action never saw prior turns. Both ends blocked
it: `AgentDefinition.input` was `str` with a validator rejecting anything else,
and `AgentAction.run` raised "agent input must render to a string" once a CEL
template rendered to a list.

`input` now takes a string or a list of messages, and the action normalizes
rather than rejecting. A whole-string `${...}` template keeps its evaluated
type, so `state.messages.map(m, {'role': m.role, 'content': m.content})`
renders the exact shape the agent wants -- no new CEL function needed.

Serialized messages carry `name: None` and `metadata` that the agent event
schema rejects, and `message_to_llm_dict` only drops `None` for a model input,
not the plain dicts a CEL render produces. The normalizer drops them, keeping
`content: None` since that is a valid message shape.

Declarative crews are unaffected: they use `CrewAgentDefinition`, which has no
`input` field at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(flows): pin content=None survival through agent input normalization

A filter-all-None change would silently drop the assistant turn that only
requests tool calls, and no test covered that key.

Found by CodeRabbit on #7066.

* test(flows): cover the agent action through kickoff, not the helper

The existing tests called _normalize_agent_input directly, so nothing pinned
that Expression.render_template -> normalization -> Agent.kickoff_async keeps a
message list intact. Removing the normalization call now fails this test.

Found by CodeRabbit on #7066.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2026-08-24 21:09:36 +00:00
João Moura
500ebc7a68 feat(flow): let a declaration name the router's response format (#7063)
* feat(flow): let a declaration name the router's response format

`conversational.router.response_format` was typed `Any` and dropped with a
warning, because `_router_response_format` hands its value straight to
`llm.call(response_format=...)`, which needs a real class. So the router always
used its synthesized fallback: `intent: str` with the route labels only in a
field description.

The field now takes the same `{"python": "module.path.Class"}` shape a crew
agent's `response_format` uses, resolved through the same
`_resolve_model_class`. That brings the project-root containment with it -- a
declaration cannot reach outside the project to import code -- and gives the
router a `Literal[...]` of the real route labels instead of a bare string.

The DSL projection now emits that shape too, so a live class on a Python flow
round-trips as `{"python": ...}` rather than an opaque `{"ref": ...}` that
nothing could reload.

A bare `module:qualname` ref is now a load-time validation error instead of
being silently discarded; the test that pinned the old drop-with-warning
behavior is updated to assert that.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): do not project a response format that cannot be reloaded

`_python_reference` emitted a dotted path for any class, including two that
cannot be imported back: a non-Pydantic class, and one defined inside a
function, whose `__qualname__` carries `<locals>`. The definition then held a
ref that only failed when something tried to resolve it.

Both are dropped at projection time with a warning naming why, so a reload
falls back to the synthesized response format. The live class still drives the
running flow; only the projection omits it.

Found by CodeRabbit on #7063.

* test(flows): assert the response_format omission warnings

The projection tests only checked for None, so removing the warning that tells
an author their response_format was dropped would still pass.

Found by CodeRabbit on #7063.

* fix(flows): only project a response_format ref that imports back

The check rejected <locals> classes but still emitted a path for a nested one.
The loader splits a ref on its last dot, so module.Outer.Route resolves
module.Outer as a module that does not exist - proven: reload raised
JSONProjectError. A create_model() class held only in a local is unreachable
the same way.

Projection now confirms module.qualname resolves back to the class, against the
already-imported module so it never triggers an import.

Found by CodeRabbit on #7063.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 13:53:15 -07:00
Vidit Ostwal
d0e9208627 [OSS-129] Map GPT-5.6 family to the official 1.05M context window (#7012)
* fix(core): map GPT-5.6 to the official 1.05M context window

LiteLLM fallback treated Sol, Terra, Luna, and the gpt-5.6 alias as unknown and used the 8k default.

* fix(openai): give GPT-5.6 its own 1.05M window

Native lookup matched gpt-5 first, so Sol, Terra, and Luna inherited 1,047,576. Longest-prefix matching keeps gpt-5 and gpt-5.4-mini on their own sizes.

* fix(azure): map GPT-5.6 deployments to the official 1.05M window

Azure had no gpt-5 / gpt-5.6 entry, so Sol, Terra, and Luna fell back to 8k.

* feat(cli): list GPT-5.6 Sol, Terra, and Luna in curated catalogs

The family is generally available; keep gpt-5.5 as the offline default.

* refactor: keep context-window tables in longest-prefix order

Drop the runtime sort and document that new keys must be inserted longest-first so startswith matching stays correct.

* fix(core): resolve prefixed LiteLLM models to the GPT-5.6 window

openai/gpt-5.6-luna kept its provider prefix on self.model, so startswith matching missed the 1.05M mapping. Strip recognized prefixes for lookup and leave unknown ones intact.
2026-08-24 19:03:48 +00:00
Vidit Ostwal
2746bb88b7 [OSS-130] Align README setup with current docs (#7036)
Update GitHub and PyPI READMEs to the JSON-first CLI path so setup matches docs.crewai.com.

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2026-08-24 11:49:19 -07:00
Lorenze Jay
090633737c feat(flows): enhance conversational flow documentation and APIs (#7104)
- Updated the description to clarify the use of `handle_turn` and structured streaming in multi-turn chat applications.
- Added a warning about the experimental nature of the conversational features.
- Improved the overview section to include structured streaming and refined the explanation of session handling.
- Enhanced the API documentation for `handle_turn`, `stream_turn`, and `chat` methods, emphasizing their roles in conversational flows.
- Clarified the turn lifecycle and the handling of user messages within the flow.
- Updated examples to reflect changes in message handling and session tracing.
- Ensured consistency across language versions in the documentation.
2026-08-24 11:26:31 -07:00
João Moura
f68fd9e850 feat(flow): let a chat flow declare its own state shape (#7061)
* feat(flow): let a chat flow declare its own state shape

A conversational declaration could only use `state: {type: pydantic, ref: ...}`
pointing at a `ConversationState` subclass. Every other shape loaded clean and
then died on the first turn -- inline `json_schema` and a non-subclass ref with
`AttributeError: 'StateWithId' object has no attribute 'messages'`, and
`type: dict` with `AttributeError: 'dict' object has no attribute 'id'`.

`Flow._compose_extension_state_model` is a new runtime extension seam -- the
seventh alongside the existing six -- applied to the model built from `state:`
before the engine wraps it for `id`. The conversational mixin uses it to add
the chat fields to whatever the declaration asked for, so declared fields and
defaults survive; a model that already extends `ConversationState` is returned
untouched, so today's supported shape is a no-op.

`dict` and `unknown` state cannot carry those fields at all, so the default
extension state supplies the real shape (seeded from the declared defaults
where they fit) rather than forbidding it. Raising instead would break
construction, and `Flow[dict]` with `conversational = True` constructs today --
`crewai flow plot` and definition-only consumers would stop working.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): keep declared defaults and cover an unbuildable state model

Two review follow-ups on the declared-state work.

A `dict` state's defaults are arbitrary keys, and the fallback kept only the
ones matching `ConversationState`, so `{"type": "dict", "default": {"topic":
"ai"}}` lost `topic` before the first turn and an action reading `state.topic`
would fail. They are carried as extras now.

And a declared `pydantic`/`json_schema` state whose model cannot be built --
a bad ref, an invalid schema -- fell through to a plain dict with none of the
chat fields, so the turn died on `state.id` instead. The engine now re-asks the
extension in that case, as if nothing had been declared.

Found by Cursor and CodeRabbit on #7061.

* refactor(flows): drop the unreachable extension-state fallback

The _initial_state_t branch sat after an unconditional return. The
state_definition is None case and _conversation_state_with_defaults now cover
every path that used to reach it.

Found by Cursor on #7061.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 22:09:46 +05:30
João Moura
9e9a8577be feat(events): report project creation with the id minted for it (#7074)
* feat(telemetry): report project creation with the id minted for it

Acquisition was only observable from a project's first run. That misses every
project created and never run, and dates the rest to the wrong day.

All three scaffolding paths already mint a project_id into the new
pyproject.toml. None of them reported it, and two of them - create_crew and
create_json_crew, which is the default `crewai create crew` path - emitted no
telemetry at all.

`Project Created` carries the kind (crew, json_crew, flow) and the id that was
just minted, and is emitted after the mint so it can carry it.

The attribute is `created_project_id`, not `project_id`, because those are two
different things. CommonAttributesSpanProcessor stamps `project_id` on every
span from get_project_id(), which reads the current working directory and is
cached for the life of the process - during `crewai create` that describes the
directory the command was run from, not the project being created. Reusing the
name would have given one column two meanings depending on span type.

Nothing is emitted for `create_crew(parent_folder=...)`: that adds a crew to a
project which already exists, mints no id, and is not an acquisition.

The existing `Flow Creation` span is left exactly as it is. Note for whoever
reads it: it is emitted from two places with two different meanings - CLI
scaffolding (create_flow.py) and runtime flow construction (event_listener.py on
FlowCreatedEvent) - so it cannot separate acquisition from usage. Not changed
here because it is a live series and renaming it would break continuity.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(telemetry): stop the creation-span tests exporting to the real collector

The recorded_spans fixture has to enable telemetry for its assertions to mean
anything - a disabled Telemetry never builds self.provider, so every assertion
would pass vacuously against a non-recording span. But enabling it is exactly
what makes __init__ wire a BatchSpanProcessor around the real
SafeOTLPSpanExporter, pointed at the production collector.

Measured, with a spy on both SafeOTLPSpanExporter classes reporting at
interpreter exit: before this change the file made 3 real export calls, handed 3
synthetic Project Created spans with invented created_project_id values to the
production exporter, and completed 3 connects to the collector. After: 0, 0, 0.

Sampling at pytest_sessionfinish reports 0 either way and is how this was missed
- BatchSpanProcessor flushes on a background timer, and with no
provider.shutdown() the flush lands in the atexit handler, which runs after
sessionfinish.

--block-network does not prevent it: it is function-scoped and only swaps
socket.connect, which a background batch thread outlives.

Follows telemetry_with_exporter in tests/telemetry/test_tracer_isolation.py:
_NullExporter swapped in before construction, _register_shutdown_handlers
suppressed so no atexit hook is left behind, and provider.shutdown() in finally.
Patch target is crewai_core because that is where this Telemetry comes from.

Also disambiguates the docs rows: the minted ID belongs to the new project, not
to the directory the command ran in, and the two can differ. Reworded in all four
languages rather than renaming the token to created_project_id - this table
documents data, never span-attribute keys (kind and crewai_version on the same
row are unnamed), and `project_id` is already the page's name for the
pyproject.toml key.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* docs(ar): use tanwin fath on the letter, not on the alif

مشروعًا / جديدًا rather than مشروعاً / جديداً, in the row added by this PR.

Both forms appear in docs/edge/ar (3 each), so this is not a house convention
being broken either way; the corrected form is the more standard one and the text
is mine.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* docs: stop the creation row implying the span's project_id holds the minted value

CodeRabbit re-raised this as Major after I rejected the first version, and it was
right to. My rejection argued the page never names wire keys, so introducing
created_project_id would be its only one. That part still holds -- grep finds no
attribute key anywhere in the four files. But it was the wrong conclusion: the row
still used the token `project_id` for a value the span does NOT carry under that
key, while the same span's real project_id holds the cwd-derived value. The row
also already exposes literal wire values (`crew`, `json_crew`, `flow` are the
actual kind values), so "this page has no wire detail" was overstated.

Dropping the token resolves the ambiguity without adding the page's only key
name: the row now says "the project ID minted for that new project", and names
`project_id` only to say the minted value is recorded separately from it.

All four languages. No docs/v*/ touched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* docs: use an em dash in the creation row, matching the rest of the page

The two ASCII `--` occurrences in these files were both mine, introduced by this
PR: the page otherwise uses em dashes throughout (en 4, ar 4, ko 2, pt-BR 4).

CodeRabbit flagged pt-BR; the same slip was in en, so both are fixed. Now zero
ASCII `--` across all four language files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-23 15:59:56 -03:00
João Moura
f4731f5025 feat(events): record whether a run had inputs, without recording the inputs (#7072)
* feat(telemetry): record whether a run had inputs, without recording the inputs

The `crew_inputs` payload is gated behind `share_crew` and stays that way, so the
only way to tell a parameterised run from an unparameterised one was to read a
gated key: it is present on roughly 0.02% of spans, all of them opt-in sharers.
That is a measurement of people who opted into sharing, not of users.

`crew_inputs_present` carries just the answer -- "true"/"false" -- on the
already-ungated `Crew Created` span. The payload stays inside the `share_crew`
branch, so nothing new about the contents of anyone's inputs is collected.

A string, for the reason `crew_memory` is a string, and the encoding matters
more here because the majority case is the empty one. Measured over a single day
(312,424,709 spans): `vInt64='0'` occurs 0 times and `vBool='false'` occurs 0
times, while `vStr='0'` does occur. proto3 omits the zero value for ints as well
as bools, so an integer key count would have silently dropped every
unparameterised run -- and among sharers, 54.46% of runs pass `{}`.

`{}` and `None` are both "false": an empty dict parameterises nothing, so
truthiness is the question being asked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(telemetry): assert input keys are absent too, not only input values

The gating test checked only the input value. A regression that emitted the input
keys - json.dumps(sorted(inputs)) or similar - would have passed it, and key
names are user data as much as values are.

Verified by injecting exactly that regression: the new assertion fails on it and
passes once reverted.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 16:10:02 +05:30
João Moura
113e572e05 fix(deps): raise the pip floor to 26.2 for PYSEC-2026-3721 (#7076)
pip-audit started failing on every open PR. The advisory is against pip itself:
PYSEC-2026-3721 / CVE-2026-13346, which OSV records as affecting pip up to but
not including 26.2. The floor was already pinned at >=26.1.2, so the previously
patched version became the vulnerable one.

Not caused by any open PR. Reproduced on tag 1.15.17 itself (`b3ab193c3`), which
resolves pip 26.1.2: `uv run pip-audit` with CI's exact arguments reports
"Found 1 known vulnerability" there with no branch changes at all. That is why
this is its own PR rather than a fix inside whichever PR happened to run first.

Raising the floor rather than adding --ignore-vuln, since a patched release
exists: 26.2 fixes it and 26.2.1 is current. The trailing comment follows the
convention already used for setuptools>=83.0.0.

The uv.lock change is deliberately hand-scoped to pip's four lines. Running
`uv lock` -- with either uv 0.11.12 or 0.11.15 -- also re-expands environment
markers for numpy, humanfriendly, grpcio, mcp and a dozen nvidia-* packages,
because the committed lock was produced by a uv that simplifies markers
differently from any version available here. Those rewrites change CUDA and
platform resolution and have no business riding along in a security fix. The
four lines applied here are exactly the ones uv itself produced for pip.

Verified: `uv lock --check` passes, so the lock is consistent with pyproject and
needs no regeneration; pip resolves to 26.2.1; `uv run pip-audit` with CI's
arguments reports "No known vulnerabilities found, 1 ignored"; crewai and
crewai_core still import.


Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-21 16:02:32 +05:30
João Moura
8e6c23430f fix(flow): emit the flow lifecycle on a suppressed resume (#7071)
* fix(flow): a resumed flow must emit flow_started, not only flow_finished

_resume_async_body gated FlowStartedEvent behind suppress_flow_events while the
matching FlowFinishedEvent a few hundred lines below stayed ungated. A suppressed
resume therefore emitted an unpaired finish: a flow that reported finishing
without ever having started. That is worse than a missing row - it breaks every
started/finished pairing and any duration or funnel built on it, and it removed
the resumed leg from telemetry entirely.

suppress_flow_events is also the wrong gate for emission. It asks for console
quiet: _flow_origin in events/event_listener.py says so explicitly and notes it
"can legitimately be set on a caller's own flow", and the listener already
honours it at each point where it prints. So a user who set it on their own flow
for quiet output silently lost their resumed runs from telemetry.

The emit is now unconditional, matching both the kickoff path - which never gated
it - and the FlowFinishedEvent it pairs with. The method-execution gates in this
function are left alone: _execute_method gates the same events on the same flag,
so those are symmetric and intended.

Internal flows that set this flag (agent_executor, the memory recall/encoding
flows) will now emit a started event when resumed. That is the point, and the
is_crewai_internal marker already keeps them out of user-facing flow metrics -
a distinction _flow_origin draws precisely because this flag cannot carry it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* fix(flow): emit the whole lifecycle on a suppressed resume, not just the start

The first commit on this branch ungated FlowStartedEvent on the resume path
while FlowFinishedEvent stayed gated, which left a suppressed resume emitting a
start with no terminal event. CodeRabbit and cursor both caught it.

The premise that commit was written against was wrong: origin/main gated the
started event and the finished event, so it emitted neither and was symmetric.
It was the detection that was broken, not the code -- a fixed-line lookback for
the enclosing condition missed the multi-line `if (not self.suppress_flow_events
and not self._should_defer_trace_finalization()):` guarding the finish.

The defect is therefore not an unpaired event on main but a silent one: a
resumed run with suppress_flow_events set emits no lifecycle events at all, so
it never reaches a listener or the trace exporter and the run is invisible
downstream. kickoff_async emits them either way and lets listeners filter, and
suppress_flow_events asks for console quiet rather than for telemetry to be
dropped, so resume now matches kickoff.

_should_defer_trace_finalization() still withholds the finish, which is a real
reason: finalize_session_traces() emits it later instead.

respect_suppression is deleted rather than left defaulting to False -- the
resume call site was its only caller, so nothing passes True any more.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 15:51:20 +05:30
João Moura
6e714d6cad feat(flow): accept crew-style LLM config in a conversational declaration (#7062)
* feat(flow): accept crew-style LLM config in a conversational declaration

`conversational.llm` / `intent_llm` / `answer_from_history_llm` and
`router.llm` only accepted a model-id string, so a declaration could not set
`max_tokens`, `temperature` or anything else a declarative crew's agent can.

`_coerce_llm` now delegates to `crewai.utilities.llm_utils.create_llm` -- the
same helper the crew/agent declaration layer resolves through -- so the shapes
match: a model-id string, a config mapping, an `LLMDefinition`, or a live
`LLM`/`BaseLLM` passed straight through.

It keeps one thing `create_llm` does not: `create_llm(1234)` takes the int as a
model name and returns an LLM that only fails later with a provider error. A
declaration is hand-written, so a non-string, non-mapping value raises now
instead. A mapping missing `model` keeps `create_llm`'s own message.

The contract fields stay permissively typed and gain descriptions naming the
accepted shapes. Tightening them to `str | LLMDefinition` would break the DSL
projection: a live custom `BaseLLM` whose config dump lacks a `model` key
degrades to a `{"ref": ...}` mapping, which such a type would reject -- turning
`flow_definition()` on an existing Python flow into a validation error.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): resolve declared LLM mappings for intent classification

`intent_llm` and `answer_from_history_llm` were documented as taking the same
shapes as `llm`, but both route through `_collapse_to_outcome`, whose own
coercion accepts only `str | BaseLLM`. A declared config mapping reached it
unchanged and raised "Invalid llm type: <class 'dict'>" mid-turn -- so the
documentation promised something that failed.

Also fixes the field descriptions. The previous commit's `llm` description
landed on `FlowConversationalRouterDefinition.llm` rather than
`FlowConversationalDefinition.llm`, because both fields are literally
`llm: Any = None` and the first match won. All four now describe their own
field and name every accepted shape, including `LLMDefinition` and a live
instance.

Test changes: adds an `LLMDefinition` resolution case, and the declared-mapping
turn test now patches `create_llm` to prove the mapping reaches it instead of
swapping the config out beforehand, which proved nothing.

Found by Cursor and CodeRabbit on #7062.

* docs(flows): name the full router LLM precedence; pin the coercion path

The conversational llm description skipped intent_llm in the router fallback
order (router.llm, then intent_llm, then llm), and the intent_llm test replaced
the declared mapping with a scripted LLM before the turn, so it never exercised
the coercion. Patch create_llm instead: removing the coercion now fails the
test with "Invalid llm type: <class 'dict'>".

Found by CodeRabbit on #7062.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 14:47:37 +05:30
João Moura
4718b190d1 fix(cli): open the conversational TUI for a declarative chat flow (#7060)
* fix(cli): open the conversational TUI for a declarative chat flow

`crewai run` refused a declarative conversational flow and told the user to
drive it from Python. That was wrong: the conversational TUI already exists and
already does this job. `CrewRunApp(conversational=True)` renders a chat pane and
drives `handle_turn` per message (crew_run_tui.py:833-935), and
`kickoff_flow._run_conversational_flow_tui` launches it for a Python
conversational Flow.

A declaration-built flow satisfies everything that TUI needs -- `handle_turn`,
a settable `defer_trace_finalization`, and `finalize_session_traces()` -- so it
now routes there instead of exiting.

A chat loop still needs a terminal. A headless run (`is_interactive()` false,
which folds in CREWAI_DMN) says what it would have needed rather than kicking
off a single turn and presenting that as the whole conversation.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cli): do not send a human-feedback chat flow to the Textual TUI

A declaration can carry both a `conversational:` block and a method with
`human_feedback:` -- verified, both predicates return True on the same flow.
Routing it to the chat TUI hangs: the runtime collects feedback with a blocking
`input()` (flow/runtime/__init__.py:3719) that Textual cannot service, so the
prompt is never shown. The STEPS TUI already declines these for exactly this
reason. Such a flow now falls back to the terminal REPL, which can prompt.

Also updates the guide in en/ar/ko/pt-BR: it still said `crewai run` has no
chat loop and exits, which is now the opposite of what the CLI does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(cli): reject --inputs on a conversational flow instead of dropping it

The conversational branch returns before `_resolve_flow_inputs`, and the TUI
calls `handle_turn(message)` -- which owns the kickoff inputs, passing
`{"id": session_id}` itself. So any `--inputs` value was silently discarded and
the conversation ran as if it had been applied. It now errors, and says that
resuming a session by id is not wired up yet rather than implying it worked.

Also corrects the Arabic guide: `مُوجّه محجوز` reads as "reserved router", not
the blocking prompt it describes.

Both found by CodeRabbit on #7060.

* fix(cli): document the conversational routing exceptions

Three review follow-ups:

- The Arabic guide read خدمته (masculine) against the feminine
  مُطالبة introduced by the last fix.
- Both docstrings described a routing path that now has exceptions: a
  conversational declaration rejects --inputs and skips state-schema
  resolution, and a human-feedback one uses the terminal REPL.
- The --inputs rejection test accepted SystemExit(0); it now pins code 1.

Found by CodeRabbit on #7060.

* fix(cli): reject --inputs on a chat flow even when it parses empty

parse_inputs_json returns {} both when the option is absent and when the user
passes --inputs "{}", so the falsy check started the TUI for the second case
while the docs said it was unsupported. The conversational path now takes
whether the option was supplied, not what it parsed to.

Documents the restriction in en, ar, ko and pt-BR.

Found by CodeRabbit on #7060.

* test(cli): pin the headless conversational exit status

pytest.raises(SystemExit) also accepts SystemExit(0), so the error path could
regress to a successful exit unnoticed.

Found by CodeRabbit on #7060.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 14:36:40 +05:30
João Moura
456c67d7c2 fix(telemetry): record crew_memory as a string, not a bool (#7064)
This pipeline cannot carry a false boolean. Measured across 218,400,577 spans,
not one carries vBool=false - proto3 omits the bool zero value, so false is
never serialized and arrives as the key simply being absent. "Memory disabled"
was therefore structurally unrepresentable, and presence had to stand in for the
value, which is why crew_memory read 1 for 99.8% of crews against a field that
defaults to False.

The fix is the convention this file already documents and applies to `resumed`
and `conversational`; crew_memory is the attribute those comments name as the
outstanding case. It was the only remaining CrewAI-emitted boolean attribute -
checked empirically: every other attribute appearing in vBool comes from
third-party instrumentation.

Truthiness rather than `is True`, per the decision that memory counts as enabled
when set by any means: a Memory, MemoryScope or MemorySlice instance is enabled
just as much as `memory=True`. None of those classes defines __bool__ or __len__,
so an instance is always truthy.

Tests cover all four inputs - True, False, None and an instance - and reuse the
existing guard that no attribute is ever passed as a bare boolean. Verified they
fail against the unpatched emitter.


Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 21:59:35 +00:00
Dat Daryl Ngo
89c04a0a08 Clarify Arize Phoenix observability docs (#7069)
Co-authored-by: Dat Ngo <datngo@Mac.digi.box>
2026-08-20 16:08:46 +00:00
João Moura
0c2bcb510c feat(cli): backfill project_id from every user-invoked project command (#7057)
* feat(cli): backfill project_id from every user-invoked project command

`crewai run` has always backfilled: a project declaring [tool.crewai] without a
project_id gets one minted the first time it runs. No other command did, so a
project driven entirely through `crewai test`, `crewai deploy` or
`crewai traces enable` never acquired an id and every one of its runs stayed
unattributable - which is the denominator problem, not a cosmetic gap.

Adds the same call to train, replay, test, login, deploy create, deploy push,
flow add-crew, enterprise configure and traces enable. Every one is an action the
user explicitly invoked, which is the condition run_crew already relies on, so this
is the existing principle applied evenly rather than a new policy. It is still never
called from the SDK during kickoff, and get_or_create_project_id still refuses to
create the [tool.crewai] table, so an unrelated directory is never rewritten.

`crewai flow kickoff` is deliberately untouched: it delegates to run_crew and
already inherits the backfill. A test pins that so the delegation is not
accidentally duplicated. There is no `crewai evaluate` command - `crewai test` is
that path.

The call is the first statement in each command so a command that later fails still
leaves the project with an id. The tests patch the backfill to raise, which proves
the call happened and guarantees nothing after it runs, so no test touches user
settings, spawns a subprocess or reaches the network. Verified they fail against the
unpatched module: 9 command tests fail, the 2 guard tests still pass.

Tests live under lib/crewai/tests/cli/ because that is the path the required CI job
runs; nothing runs lib/cli/tests/.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(cli): assert the backfill at runtime instead of reading source text

Addresses CodeRabbit and github-code-quality on #7057. The two guard tests
grepped module source for a call string, which asserts on formatting rather than
behavior: a reformat would break them and a real regression could slip past.

They now invoke the commands in an isolated project and assert on observed calls.
The flow-kickoff test patches the two distinct import sites separately and asserts
run_crew's is called exactly once while cli's is not called at all, which is what
makes 'delegates' and 'duplicates' distinguishable at runtime rather than by
reading the file.

Verified both catch what they claim: injecting a duplicate call into flow_run
fails the delegation test, and removing run_crew's own call fails the run test.

This also drops the module-level 'import crewai_cli.cli as cli_module' that mixed
import styles with the existing 'from crewai_cli.cli import crewai', which is the
code-quality finding - the rewrite removes the need for it entirely.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(cli): make the exact-once assertion observable

Addresses CodeRabbit on #7057, and the finding was correct: with
side_effect=_BackfillReached the mock raised on first use, so call_count == 1 was
guaranteed by the mock rather than by the code. A second backfill call inside the
same run_crew execution could never have been observed.

Both backfill mocks now return normally and execution is stopped at the first call
AFTER the backfill (configured_project_json_crew), so the recorded count is real.

Verified the difference this makes: injecting a duplicate get_or_create_project_id()
INSIDE run_crew now fails both tests, which the previous version could not detect at
all. The flow_run duplicate case is still caught.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(cli): assert flow kickoff reaches the post-backfill boundary

Addresses CodeRabbit on #7057, and the finding was right: the flow-kickoff test
discarded the runner.invoke() result, so if the path returned or raised after one
backfill call but before configured_project_json_crew, both call-count assertions
would still have passed - for the wrong reason.

test_run_still_backfills already asserted the boundary; this makes the pair
consistent.

Verified it earns its place: injecting an early return after the backfill and
before the boundary now fails both tests, and previously would have failed
neither.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* test(cli): pin that the backfill precedes command-specific work

Addresses CodeRabbit on #7057. The finding is valid: the parametrized test proves
the backfill is reached, not that nothing ran before it, so its assertion message
claimed more than the test established.

Fixed in two parts rather than as proposed. The message now states what the test
actually proves, and a new test pins the ordering on login: , whose first action
goes through a module-level name that can be patched without reaching into the
command.

Deliberately not parameterized across all nine commands, which is what the finding
suggested: that would mean naming each command's current first action, and those
change as commands evolve, so the suite would end up tracking their internals
rather than this ordering property. One representative command establishes it, and
placement is visible in the diff for the rest.

Verified it catches the regression: swapping login's first two statements so its
own work runs before the backfill fails the new test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 23:14:09 -07:00
João Moura
7c72d57b73 fix(events): always emit project_id so absent and empty stay distinct (#7056)
* fix(telemetry): always emit project_id so absent and empty stay distinct

common_span_attributes() stamped project_id onto every span only when the project
declared one, and omitted the key otherwise. That makes two different situations
indistinguishable downstream: a client too old to report a project id at all, and
a current client whose project simply declares none.

The consequence is not cosmetic. The share of clients that COULD have reported an
id is the denominator of every attribution rate, and with both cases collapsed into
"key absent" that denominator cannot be computed at all - it can only be inferred
from a version floor, which is fragile and silently wrong for any client that
backports or pins.

The key is now always present and is the empty string when the project declares
none. It still never invents an identity: get_project_id() remains read-only and
minting stays with the CLI commands a user explicitly invoked.

Two existing tests asserted the old contract and are updated rather than deleted,
one of them renamed because its name described the behaviour that changed. A third
test is added pinning the distinction itself. The test asserting that a foreign
application's spans are never annotated is unaffected and still passes: this
changes what our processor stamps, not where it is attached.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

* docs(telemetry): note that a failed project_id lookup also yields empty

Addresses CodeRabbit on #7056. The docstring and inline comment described the
empty string only as an undeclared project, but the except branch sets
project_id to None and so lands on the same empty value. Both are deliberately
indistinguishable - neither yields an id - and saying so matters to anyone
debugging an empty value, since an unreadable pyproject.toml looks identical to
a project that simply declares nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 01:10:23 -03:00
João Moura
b3ab193c31 [docs-freeze] docs: snapshot and changelog for v1.15.17 (#7055) 2026-08-20 00:27:10 +00:00
João Moura
5ddf62ae7b feat: bump versions to 1.15.17 (#7054) 2026-08-20 00:16:11 +00:00
João Moura
4dfd074fae docs(flow): document declarative conversational flows (#7035)
* test(flow): unskip the conversational end-to-end suite

The `conversational_graph_broken` marker parked 21 end-to-end conversational
tests with the reason "the definition-first start migration intentionally
stopped scanning inherited methods, so that graph no longer registers".

That is no longer true: `_iter_flow_methods` walks the MRO for
`__conversational_only__` methods (dsl/_utils.py:406-420), so a
`conversational = True` subclass does register `route_conversation`,
`converse_turn`, `end_conversation` and `answer_from_history_turn` — which
`test_flow_definition.py:391-407` already asserts.

Removing the marker takes the file from 47 passed / 21 skipped to 68 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): make conversational opt-in unmistakable

Opting a Flow into chat took two statements, and forgetting one failed
silently. With `@ConversationConfig(...)` but no `conversational = True`:
`FlowDefinition.conversational` came back `None`, the built-in graph never
registered, and `handle_turn()` returned `None` without appending a message
or raising — while `chat()` reported "only available on conversational flows"
on a class that was literally decorated with a conversational config.

Three changes:

- `ConversationConfig.__call__` now also sets `conversational = True`. Every
  field on the config is consumed only by the conversational graph, so a
  decorated non-conversational Flow could only ever discard it.
- `FlowConversationalDefinition.enabled` defaults to True. The block is absent
  on non-conversational flows, so declaring it is the opt-in; `enabled: false`
  remains an explicit opt-out.
- `handle_turn()` raises like `chat()` and `stream_turn()` already do instead
  of silently returning `None`.

Setting `conversational = True` by hand still works and is still the way to
opt in without a config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): let a declaration drive conversational mode

`FlowDefinition.conversational` was written by the DSL projection and read by
nothing: every conversational gate resolved through `type(self).flow_definition()`
— the class projection — instead of `self._definition`, the declaration a flow
was actually built from. So `Flow.from_declaration()` on a definition with a
conversational block produced a flow that reported itself non-conversational,
dropped the user message, and never registered its declared routes.

Resolution rules, applied consistently:

- Structure (enabled, methods, route labels, builtin/internal routes) comes
  from `self._definition`, which is the loaded declaration for a declarative
  flow and the class projection otherwise. Both paths now agree.
- Behavior (`conversational_config`) still prefers the class attribute, which
  can hold live objects — a configured LLM, a custom BaseLLM, a response_format
  model class — that the serializable definition degrades to a config dict or a
  `module:qualname` ref. Reading the definition first would silently downgrade
  every decorated Python flow. A declaration-built flow has no class config, so
  `_config_from_definition` supplies one, cached for stable identity.
- A declared `state:` block is never replaced. `_create_default_extension_state`
  is consulted before `_create_definition_state`, so returning `ConversationState`
  there discarded every field the declaration asked for. It now yields to a
  declared state and only supplies the default when nothing else does.

The class-scoped `_is_conversational` / `_conversational_definition`
classmethods are gone; the existing instance-scoped `_is_conversational_enabled`
is the single gate.

A router `response_format` that survived serialization as a ref or schema dict
is dropped with a warning rather than handed to `llm.call()`, which needs a
real class.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): synthesize the built-in conversational methods for declarations

A declaration carrying `conversational: {}` loaded clean and then ran zero
methods and returned `None`, because the four built-in graph handlers are
inherited from `_ConversationalMixin` and a declaration has nothing to inherit
from. Authors had to name `crewai.experimental.conversational_mixin:_Conversational
Mixin.route_conversation` and three siblings by hand.

`Flow._extend_definition` is a new runtime extension hook, called once
`_definition` is resolved and before methods are bound. The conversational
mixin overrides it to fill in `route_conversation`, `converse_turn`,
`end_conversation` and `answer_from_history_turn` when they are missing, using
the same code refs the DSL projection already emits so a declaration and a
class projection of the same flow produce identical method definitions.

Synthesis is deliberately a runtime concern, not a contract one:
`FlowDefinition` stays independent of the authoring layer and of the engine,
as `test_flow_definition_contract_is_dsl_agnostic` requires, and a loaded
declaration still serializes back to exactly what its author wrote.

Route descriptions are now carried by the contract. The DSL projects a handler
docstring's first line into `FlowMethodDefinition.description`, and the router
catalog reads that before falling back to the live docstring. This also fixes
a real defect: for a declarative flow `getattr(type(self), handler_name, None)`
is `None`, and the old code read `None.__doc__` — so the router LLM was told a
route's description was "The type of the None singleton."

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): let an agent or crew handler reply in a conversation (#7034)

`handle_turn` promotes a handler's return value to the assistant message when
the handler did not append one itself, but the check required `isinstance(result,
str)`. Declarative `agent` and `crew` actions return `LiteAgentOutput` and
`CrewOutput`, whose text lives on `.raw` — so the most natural declarative
handler was exactly the one whose reply never reached the transcript.

`_is_public_turn_result` now unwraps `.raw` before deciding, matching
`_stringify_result`, which already did. The routing-artefact guards are applied
to the unwrapped text, so an output echoing a route label or this turn's intent
is still not promoted.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): keep privately recorded agent results out of the transcript

Unwrapping `.raw` in `_is_public_turn_result` made the end-of-turn fallback
promote `LiteAgentOutput` / `CrewOutput` objects that the handler had already
recorded via `append_agent_result` with the default private visibility. That
call does not set `_assistant_reply_appended`, so the fallback republished the
very object the handler asked to keep private — defeating
`visible_agent_outputs`.

Reproduced against `main` for contrast: no leak before the unwrap, leak after.

`append_agent_result` now remembers the object it recorded for the duration of
the turn, and the fallback skips anything already routed that way. The check is
identity-based on purpose: a handler that records scratch work privately and
then returns a user-facing summary still gets that summary promoted, which a
simple "handler already handled it" flag would have broken.

Found by Cursor Bugbot on #7033.

* feat(flow): mark a declarative chat flow conversational on the instance

A declaration enables chat through `conversational.enabled`, without the
`conversational = True` class attribute. Callers outside this package
capability-check that attribute -- the AG-UI serving guide states it as a
requirement -- so it disagreed with `_is_conversational_enabled()` and a
declarative conversational flow looked non-conversational from outside.

`_extend_definition` now sets it on the instance when the definition enables
chat. Instance-only on purpose: the DSL projection reads the attribute off the
*class* to decide whether to emit a conversational block, so setting it there
would make every later subclass look conversational.

Verified on a real declarative flow: `conversational` and `stream_turn` both
now satisfy the documented capability check, while `Flow.conversational` and
any later subclass stay False.

* refactor(flow): derive routing-artefact labels from the effective routes

`_is_public_turn_result` matched a literal set of route labels, duplicating
knowledge that `_effective_builtin_routes()` already owns. A declaration that
adds a builtin route was not covered, so a handler echoing that label could be
promoted into the transcript -- the same class of divergence already fixed for
`route_turn`.

Verified the derived set is byte-identical to the old literal one for a
class-based flow, so this is a pure generalization: `conversation` and
`route_to_flow` stay explicit because neither is a route.

Also replaces a tuple-index lambda in the chat REPL test with a named
`input_fn`; it relied on tuple evaluation order and on the list being mutated
before its length was read.

Both found by CodeRabbit on #7033.

* docs(flow): document declarative conversational flows

The authoring skill told LLM authors "use top-level `conversational` only when
the user asks for a chat flow" while documenting none of its 19 fields — there
was no ModelSpec for either conversational model, so the API reference appendix
skipped them entirely.

- Adds both conversational models to the skill reference, with field
  descriptions, and registers them under the existing `conversational` skip so
  `skills(skips=["conversational"])` still suppresses the whole block.
- Adds authoring rules: do not declare the built-in graph, do not name a
  handler after the route it listens to, do not declare state unless it needs
  extra fields, and give every route handler a description.
- Documents the declarative form in the conversational-flows guide across en,
  ar, ko and pt-BR, including what is supplied automatically, how to run it,
  and what a declaration cannot express (live LLM objects, a response_format
  class, route_turn overrides).
- `crewai run` on a conversational declaration now says it has no chat loop and
  points at handle_turn/chat, instead of quietly running a single turn and
  exiting. It fails closed: a flow that cannot be inspected runs normally.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): render the conversational router section in the skill

Both conversational models shared one `Conversational` section, and the
template renders only the first model of a non-union section. The router's
fields were therefore dropped from the API reference and the generated link to
them pointed at a heading that did not exist.

Also softens the built-in-handler rule: `_extend_definition` keeps an
author-supplied entry and the guide documents that override, so the skill
should say to omit those handlers by default rather than never declare them.

Adds regression tests for both sections rendering, for every field of both
models appearing, and for `skips=["conversational"]` suppressing both.

Both found by CodeRabbit on #7035.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(flow): correct the route-description rule in the authoring skill

The rule said every route handler must define `description`, but
`conversational.router.route_descriptions` is the higher-precedence source --
`_build_route_catalog` checks the overrides before falling back to the method
description. Either one describes a route; the rule now says so, and says what
happens when a route has neither.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: ViditOstwal <viditostwal@gmail.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-19 20:18:18 +05:30
João Moura
01a156d738 feat(flow): synthesize the built-in conversational methods for declarations (#7033)
* test(flow): unskip the conversational end-to-end suite

The `conversational_graph_broken` marker parked 21 end-to-end conversational
tests with the reason "the definition-first start migration intentionally
stopped scanning inherited methods, so that graph no longer registers".

That is no longer true: `_iter_flow_methods` walks the MRO for
`__conversational_only__` methods (dsl/_utils.py:406-420), so a
`conversational = True` subclass does register `route_conversation`,
`converse_turn`, `end_conversation` and `answer_from_history_turn` — which
`test_flow_definition.py:391-407` already asserts.

Removing the marker takes the file from 47 passed / 21 skipped to 68 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): make conversational opt-in unmistakable

Opting a Flow into chat took two statements, and forgetting one failed
silently. With `@ConversationConfig(...)` but no `conversational = True`:
`FlowDefinition.conversational` came back `None`, the built-in graph never
registered, and `handle_turn()` returned `None` without appending a message
or raising — while `chat()` reported "only available on conversational flows"
on a class that was literally decorated with a conversational config.

Three changes:

- `ConversationConfig.__call__` now also sets `conversational = True`. Every
  field on the config is consumed only by the conversational graph, so a
  decorated non-conversational Flow could only ever discard it.
- `FlowConversationalDefinition.enabled` defaults to True. The block is absent
  on non-conversational flows, so declaring it is the opt-in; `enabled: false`
  remains an explicit opt-out.
- `handle_turn()` raises like `chat()` and `stream_turn()` already do instead
  of silently returning `None`.

Setting `conversational = True` by hand still works and is still the way to
opt in without a config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): let a declaration drive conversational mode

`FlowDefinition.conversational` was written by the DSL projection and read by
nothing: every conversational gate resolved through `type(self).flow_definition()`
— the class projection — instead of `self._definition`, the declaration a flow
was actually built from. So `Flow.from_declaration()` on a definition with a
conversational block produced a flow that reported itself non-conversational,
dropped the user message, and never registered its declared routes.

Resolution rules, applied consistently:

- Structure (enabled, methods, route labels, builtin/internal routes) comes
  from `self._definition`, which is the loaded declaration for a declarative
  flow and the class projection otherwise. Both paths now agree.
- Behavior (`conversational_config`) still prefers the class attribute, which
  can hold live objects — a configured LLM, a custom BaseLLM, a response_format
  model class — that the serializable definition degrades to a config dict or a
  `module:qualname` ref. Reading the definition first would silently downgrade
  every decorated Python flow. A declaration-built flow has no class config, so
  `_config_from_definition` supplies one, cached for stable identity.
- A declared `state:` block is never replaced. `_create_default_extension_state`
  is consulted before `_create_definition_state`, so returning `ConversationState`
  there discarded every field the declaration asked for. It now yields to a
  declared state and only supplies the default when nothing else does.

The class-scoped `_is_conversational` / `_conversational_definition`
classmethods are gone; the existing instance-scoped `_is_conversational_enabled`
is the single gate.

A router `response_format` that survived serialization as a ref or schema dict
is dropped with a warning rather than handed to `llm.call()`, which needs a
real class.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): synthesize the built-in conversational methods for declarations

A declaration carrying `conversational: {}` loaded clean and then ran zero
methods and returned `None`, because the four built-in graph handlers are
inherited from `_ConversationalMixin` and a declaration has nothing to inherit
from. Authors had to name `crewai.experimental.conversational_mixin:_Conversational
Mixin.route_conversation` and three siblings by hand.

`Flow._extend_definition` is a new runtime extension hook, called once
`_definition` is resolved and before methods are bound. The conversational
mixin overrides it to fill in `route_conversation`, `converse_turn`,
`end_conversation` and `answer_from_history_turn` when they are missing, using
the same code refs the DSL projection already emits so a declaration and a
class projection of the same flow produce identical method definitions.

Synthesis is deliberately a runtime concern, not a contract one:
`FlowDefinition` stays independent of the authoring layer and of the engine,
as `test_flow_definition_contract_is_dsl_agnostic` requires, and a loaded
declaration still serializes back to exactly what its author wrote.

Route descriptions are now carried by the contract. The DSL projects a handler
docstring's first line into `FlowMethodDefinition.description`, and the router
catalog reads that before falling back to the live docstring. This also fixes
a real defect: for a declarative flow `getattr(type(self), handler_name, None)`
is `None`, and the old code read `None.__doc__` — so the router LLM was told a
route's description was "The type of the None singleton."

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): let an agent or crew handler reply in a conversation (#7034)

`handle_turn` promotes a handler's return value to the assistant message when
the handler did not append one itself, but the check required `isinstance(result,
str)`. Declarative `agent` and `crew` actions return `LiteAgentOutput` and
`CrewOutput`, whose text lives on `.raw` — so the most natural declarative
handler was exactly the one whose reply never reached the transcript.

`_is_public_turn_result` now unwraps `.raw` before deciding, matching
`_stringify_result`, which already did. The routing-artefact guards are applied
to the unwrapped text, so an output echoing a route label or this turn's intent
is still not promoted.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(flow): keep privately recorded agent results out of the transcript

Unwrapping `.raw` in `_is_public_turn_result` made the end-of-turn fallback
promote `LiteAgentOutput` / `CrewOutput` objects that the handler had already
recorded via `append_agent_result` with the default private visibility. That
call does not set `_assistant_reply_appended`, so the fallback republished the
very object the handler asked to keep private — defeating
`visible_agent_outputs`.

Reproduced against `main` for contrast: no leak before the unwrap, leak after.

`append_agent_result` now remembers the object it recorded for the duration of
the turn, and the fallback skips anything already routed that way. The check is
identity-based on purpose: a handler that records scratch work privately and
then returns a user-facing summary still gets that summary promoted, which a
simple "handler already handled it" flag would have broken.

Found by Cursor Bugbot on #7033.

* feat(flow): mark a declarative chat flow conversational on the instance

A declaration enables chat through `conversational.enabled`, without the
`conversational = True` class attribute. Callers outside this package
capability-check that attribute -- the AG-UI serving guide states it as a
requirement -- so it disagreed with `_is_conversational_enabled()` and a
declarative conversational flow looked non-conversational from outside.

`_extend_definition` now sets it on the instance when the definition enables
chat. Instance-only on purpose: the DSL projection reads the attribute off the
*class* to decide whether to emit a conversational block, so setting it there
would make every later subclass look conversational.

Verified on a real declarative flow: `conversational` and `stream_turn` both
now satisfy the documented capability check, while `Flow.conversational` and
any later subclass stay False.

* refactor(flow): derive routing-artefact labels from the effective routes

`_is_public_turn_result` matched a literal set of route labels, duplicating
knowledge that `_effective_builtin_routes()` already owns. A declaration that
adds a builtin route was not covered, so a handler echoing that label could be
promoted into the transcript -- the same class of divergence already fixed for
`route_turn`.

Verified the derived set is byte-identical to the old literal one for a
class-based flow, so this is a pure generalization: `conversation` and
`route_to_flow` stay explicit because neither is a route.

Also replaces a tuple-index lambda in the chat REPL test with a named
`input_fn`; it relied on tuple evaluation order and on the list being mutated
before its length was read.

Both found by CodeRabbit on #7033.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: ViditOstwal <viditostwal@gmail.com>
2026-08-19 20:03:11 +05:30
João Moura
6f16e741aa feat(flow): let a declaration drive conversational mode (#7032)
* test(flow): unskip the conversational end-to-end suite

The `conversational_graph_broken` marker parked 21 end-to-end conversational
tests with the reason "the definition-first start migration intentionally
stopped scanning inherited methods, so that graph no longer registers".

That is no longer true: `_iter_flow_methods` walks the MRO for
`__conversational_only__` methods (dsl/_utils.py:406-420), so a
`conversational = True` subclass does register `route_conversation`,
`converse_turn`, `end_conversation` and `answer_from_history_turn` — which
`test_flow_definition.py:391-407` already asserts.

Removing the marker takes the file from 47 passed / 21 skipped to 68 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): make conversational opt-in unmistakable

Opting a Flow into chat took two statements, and forgetting one failed
silently. With `@ConversationConfig(...)` but no `conversational = True`:
`FlowDefinition.conversational` came back `None`, the built-in graph never
registered, and `handle_turn()` returned `None` without appending a message
or raising — while `chat()` reported "only available on conversational flows"
on a class that was literally decorated with a conversational config.

Three changes:

- `ConversationConfig.__call__` now also sets `conversational = True`. Every
  field on the config is consumed only by the conversational graph, so a
  decorated non-conversational Flow could only ever discard it.
- `FlowConversationalDefinition.enabled` defaults to True. The block is absent
  on non-conversational flows, so declaring it is the opt-in; `enabled: false`
  remains an explicit opt-out.
- `handle_turn()` raises like `chat()` and `stream_turn()` already do instead
  of silently returning `None`.

Setting `conversational = True` by hand still works and is still the way to
opt in without a config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): let a declaration drive conversational mode

`FlowDefinition.conversational` was written by the DSL projection and read by
nothing: every conversational gate resolved through `type(self).flow_definition()`
— the class projection — instead of `self._definition`, the declaration a flow
was actually built from. So `Flow.from_declaration()` on a definition with a
conversational block produced a flow that reported itself non-conversational,
dropped the user message, and never registered its declared routes.

Resolution rules, applied consistently:

- Structure (enabled, methods, route labels, builtin/internal routes) comes
  from `self._definition`, which is the loaded declaration for a declarative
  flow and the class projection otherwise. Both paths now agree.
- Behavior (`conversational_config`) still prefers the class attribute, which
  can hold live objects — a configured LLM, a custom BaseLLM, a response_format
  model class — that the serializable definition degrades to a config dict or a
  `module:qualname` ref. Reading the definition first would silently downgrade
  every decorated Python flow. A declaration-built flow has no class config, so
  `_config_from_definition` supplies one, cached for stable identity.
- A declared `state:` block is never replaced. `_create_default_extension_state`
  is consulted before `_create_definition_state`, so returning `ConversationState`
  there discarded every field the declaration asked for. It now yields to a
  declared state and only supplies the default when nothing else does.

The class-scoped `_is_conversational` / `_conversational_definition`
classmethods are gone; the existing instance-scoped `_is_conversational_enabled`
is the single gate.

A router `response_format` that survived serialization as a ref or schema dict
is dropped with a warning rather than handed to `llm.call()`, which needs a
real class.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: ViditOstwal <viditostwal@gmail.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-19 19:03:11 +05:30
Lucas Gomide
dabd123528 fix: use the URL hostname as MCP HTTP and SSE server_name (#7048)
Connection events used the raw endpoint as `server_name`, so traces
titled the row with the full Bright Data URL including query params.
HTTP and SSE `_get_server_info` now emit the hostname and keep the
full URL on `server_url`.
2026-08-19 18:52:25 +05:30
João Moura
f0e00df036 feat(flow): make conversational opt-in unmistakable (#7031)
* test(flow): unskip the conversational end-to-end suite

The `conversational_graph_broken` marker parked 21 end-to-end conversational
tests with the reason "the definition-first start migration intentionally
stopped scanning inherited methods, so that graph no longer registers".

That is no longer true: `_iter_flow_methods` walks the MRO for
`__conversational_only__` methods (dsl/_utils.py:406-420), so a
`conversational = True` subclass does register `route_conversation`,
`converse_turn`, `end_conversation` and `answer_from_history_turn` — which
`test_flow_definition.py:391-407` already asserts.

Removing the marker takes the file from 47 passed / 21 skipped to 68 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(flow): make conversational opt-in unmistakable

Opting a Flow into chat took two statements, and forgetting one failed
silently. With `@ConversationConfig(...)` but no `conversational = True`:
`FlowDefinition.conversational` came back `None`, the built-in graph never
registered, and `handle_turn()` returned `None` without appending a message
or raising — while `chat()` reported "only available on conversational flows"
on a class that was literally decorated with a conversational config.

Three changes:

- `ConversationConfig.__call__` now also sets `conversational = True`. Every
  field on the config is consumed only by the conversational graph, so a
  decorated non-conversational Flow could only ever discard it.
- `FlowConversationalDefinition.enabled` defaults to True. The block is absent
  on non-conversational flows, so declaring it is the opt-in; `enabled: false`
  remains an explicit opt-out.
- `handle_turn()` raises like `chat()` and `stream_turn()` already do instead
  of silently returning `None`.

Setting `conversational = True` by hand still works and is still the way to
opt in without a config.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 12:39:27 +05:30
Lucas Gomide
47fa48d787 fix: close the agent scope on every failed attempt (#6997)
* fix: close the agent scope on every failed attempt

`_check_execution_error` only emitted `AgentExecutionErrorEvent` once the
retries were exhausted, but each retry re-enters `execute_task` and opens a
new `agent_execution_started` scope. The scopes left open were then popped
by the next ending event, so `task_failed` closed an agent scope instead of
`task_started` and the task never got its own terminal pairing. Passthrough
exceptions keep bubbling untouched, since a HITL pause must leave its scope
open for the resume.

* fix: return the retried result instead of finalizing it twice

A retry reenters `execute_task`, whose own `_finalize_task_execution`
already emitted `AgentExecutionCompletedEvent`, and the outer frame then
finalized the same result again. The duplicate used to be absorbed by the
`agent_execution_started` scope that a failed attempt left open, so
closing every attempt exposed it: the extra completed event popped
`task_started`, and the task and crew ends paired with the wrong scopes.

---------

Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-19 11:37:33 +05:30
João Moura
b1c9c89ad0 fix(telemetry): attribute tool errors to the tool that failed (#7043)
`Telemetry.tool_usage_error` has always accepted `tool_name` and writes the
attribute when it is truthy, but no caller passed it, so every `Tool Usage Error`
span landed with an empty name. Per-tool error rates were therefore not
computable at all: named tools read zero errors while the unnamed bucket held
all of them.

Passes the tool name at the four sites where the tool is known. They are the same
two failures in both execution modes - usage-limit and execution-error, each once
in the sync `_use` and once in the async `_ause` - so the fix is symmetric across
the sync/async matrix rather than four unrelated edits.

Leaves the fifth site in `_tool_calling` unattributed on purpose, with a comment
saying why: that path is a tool-call PARSING failure, so the tool the model wanted
was never identified. The only string available is the raw, unparsed model output,
and putting that into a metrics dimension would give it unbounded cardinality. An
empty name is the honest representation there.

Adds tests over the full matrix, including the parsing case pinning the opposite
expectation. Verified they fail against the unpatched module: the four attribution
tests fail and the parsing test still passes, which is the intended split.


Claude-Session: https://claude.ai/code/session_01RfV2uMqWRcdfufMvtdCVoN

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-18 23:29:19 -03:00
João Moura
7942ce0c76 test(flow): unskip the conversational graph end-to-end suite (#7030)
The `conversational_graph_broken` marker parked 21 end-to-end conversational
tests with the reason "the definition-first start migration intentionally
stopped scanning inherited methods, so that graph no longer registers".

That is no longer true: `_iter_flow_methods` walks the MRO for
`__conversational_only__` methods (dsl/_utils.py:406-420), so a
`conversational = True` subclass does register `route_conversation`,
`converse_turn`, `end_conversation` and `answer_from_history_turn` — which
`test_flow_definition.py:391-407` already asserts.

Removing the marker takes the file from 47 passed / 21 skipped to 68 passed.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 01:00:05 +00:00
Lucas Gomide
2ebb9390fe feat(mcp): carry the AMP slug on tools resolved from a slug reference (#7029)
An MCP tool's name is derived from the server URL, so nothing on the
resolved tool records which reference it was requested by. `MCPNativeTool`
now keeps that reference as `server_reference` when `_resolve_amp` built
it, leaving servers requested by URL untouched. Hooks can then attribute a
tool call to the server the user actually selected.
2026-08-18 15:15:27 -04:00
Vidit Ostwal
6388421510 [OSS-128] Handle oversized single messages during chunking (#7014)
* fix(OSS-128): split oversized messages before context chunking

Normalize single messages that exceed the token budget before boundary
chunking so summarization LLM calls do not replay the same context error.
Reserve summarization prompt overhead from the chunk budget for large
context windows.

* refactor(OSS-128): inline message content text extraction as lambda

* refactor(OSS-128): restore _message_content_text as a function

Revert the lambda assignment to satisfy ruff E731 and keep the helper
readable alongside the LLMMessage content shape.

* refactor(OSS-128): drop summarization prompt overhead from chunk budget

Use the full context window size for message chunking instead of
subtracting a fixed prompt overhead.

* fix(OSS-128): preserve LLMMessage fields when splitting oversized content

Copy the original message attributes into each sub-message and only
replace content when expanding oversized entries for chunking.

* test(OSS-128): assert rendered summarization requests fit raw context

Verify each chunked summarization payload, including system and
instruction overhead, stays within the model limit implied by the
85% context window usage ratio.
2026-08-17 09:41:54 -07:00
Rip&Tear
9b1f4938f0 fix(tools): pin SSRF checks to each redirect hop and peer IP (#6981)
* fix(tools): pin SSRF checks to each redirect hop and peer IP

validate_url only inspected the original URL string, so scraping fetches
could follow a 302 to an internal address or rebind DNS between check and
connect. Route safe_get through an HTTPAdapter that re-validates every hop
and connects to the authorised sockaddr, and let FORCE_SAFE_PATHS ignore a
tenant-supplied escape hatch on managed workers.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

* Potential fix for pull request finding 'Except block handles 'BaseException''

Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>

* test(azure): use a plain stand-in for Responses API delegate mocks

MagicMock instances are not reliably stored on Pydantic PrivateAttr via
BaseLLM.__setattr__, which left _responses_delegate as None and failed
last_response_id / reset_chain assertions on CI.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
2026-08-17 13:08:03 +05:30
Rip&Tear
754d7323be fix: native tool calls broken over OpenAI Responses API (#6515)
* fix(agent): recognize OpenAI Responses API tool-call shape in native tool loop

is_tool_call_list() and extract_tool_call_info() only recognized
Chat-Completions-style ({"function": {...}}), Anthropic-style
({"name", "input"}), and Gemini-style tool-call shapes. The Responses
API's function_call output items are flat dicts shaped
{"id", "name", "arguments"} with no nested "function" key and no
"input" key, so they matched none of the checks.

This caused is_tool_call_list() to misclassify a genuine tool call as
a plain text answer, so the native tool loop returned the raw
tool-call list as the agent's final output instead of executing the
tool. Even after recognizing the shape, extract_tool_call_info() would
have passed an empty arguments dict, since it only read "input" for
the dict fallback.

Verified against LLM(api="responses") with tools attached: the agent
now correctly executes the tool with the parsed arguments instead of
returning the unexecuted tool-call JSON as its answer.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(agent_utils): cover OpenAI Responses API tool-call shape

Regression tests for is_tool_call_list() and extract_tool_call_info()
against the Responses API's flat {"id", "name", "arguments"} dict
shape, alongside existing Chat-Completions and Bedrock/Anthropic
shapes to confirm no regression there.

Confirmed these tests fail against the pre-fix version of
agent_utils.py (3 failures matching exactly the Responses API cases)
and pass against the fix in 37087b7e1.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(llms/openai): convert Chat-Completions tool messages to Responses API input items

_prepare_responses_params() passed non-system messages straight through
as the Responses API "input" array without converting them. That's
fine for plain user/assistant text (matches the API's lenient "easy
input message" shape), but Chat-Completions-style assistant messages
carrying "tool_calls" and "tool"-role messages have no equivalent
shape in the Responses API - it expects standalone "function_call" and
"function_call_output" input items instead. Sending the raw
Chat-Completions shapes gets rejected with a 400 (union-type
validation failure against every Responses API input item variant).

This broke every multi-turn tool-calling conversation over
api="responses" that doesn't rely on auto_chain/previous_response_id
(i.e. the common case: resending full history each turn instead of
referencing server-side state).

Added _convert_message_to_responses_input_items() to translate:
  - assistant + tool_calls -> one function_call item per call
  - tool role               -> function_call_output item
  - everything else         -> passed through unchanged

Verified against a real multi-turn tool-calling run: the agent now
completes the full conversation and returns the actual extracted
answer instead of erroring on the second turn.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(llms/openai): fix mypy list-item type error in message conversion

_convert_message_to_responses_input_items() was annotated to return
list[dict[str, Any]], but the passthrough branch returns the LLMMessage
argument unchanged. Lists are invariant in mypy, so a bare LLMMessage
(TypedDict) isn't assignable into a list[dict[str, Any]] return - this
was flagged by CI's type-checker job across all Python versions.

Widened the return type (and the local list built in the tool_calls
branch) to list[dict[str, Any] | LLMMessage], matching what the
function actually returns.

Confirmed with a local mypy run and the full openai/agent_utils test
suites (176 passed).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix: harden Responses API tool call conversion

* style: format Responses API conversion

* fix: upgrade nltk to 3.10.0 to resolve path traversal vulnerabilities

Upgrades nltk from 3.9.4 to 3.10.0 which fixes three path traversal
vulnerabilities (GHSA-qvv7-cg9c-w4x3, GHSA-fg7f-2386-8897,
GHSA-xh95-f55m-82fw) that were causing the pip-audit CI job to fail.

Also removes the now-obsolete PYSEC-2026-597 ignore entry from the
vulnerability-scan workflow since the vulnerability is fixed in 3.10.0.

* fix: bump aiohttp to >=3.14.2 and cryptography to >=50.0.0 to fix pip-audit vulns

Co-authored-by: theCyberTech <84775494+theCyberTech@users.noreply.github.com>

* fix: default empty Responses tool-call arguments to {}

Missing or empty Chat Completions tool-call arguments were forwarded
as an empty string, which is invalid JSON for Responses API
function_call items and breaks parse_tool_call_args. Normalize to
"{}" and cover the case in regression tests. Also assert a supplied
tool-call id is preserved as call_id.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

* Removing fallback from call_id

* Removing fallback from call_id

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: João Moura <joaomdmoura@gmail.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
Co-authored-by: ViditOstwal <viditostwal@gmail.com>
2026-08-13 21:27:35 -04:00
Lorenze Jay
808ecc95f5 [docs-freeze] docs: snapshot and changelog for v1.15.16 (#6991) 2026-08-13 21:07:53 -03:00
Lorenze Jay
852916c8bf feat: bump versions to 1.15.16 (#6990) 2026-08-14 00:06:10 +00:00
João Moura
d74e647502 fix(core): record the running release on every emitted span (#6989)
* fix(core): record the running release on every emitted span

Nine of twenty-four span kinds never recorded crewai_version, including the
two highest-volume ones - Task Created and Task Execution - plus Human
Feedback, Flow Plotting, and the whole deployment family. add_crew_attributes
writes crew_key, crew_id and crew_fingerprint but never the release, so any
question filtered by version silently returned nothing for those spans and
per-release comparison was blind to them.

Add it at the fourteen sites that were missing it across both emitters,
matching each module's existing convention: version("crewai") in crewai,
get_crewai_version() with the file's local-import pattern in crewai_core.

Guarded by a test that parses both modules and fails when any method creates
a span without recording the release, so a span added later cannot
reintroduce the gap. Verified non-vacuous: removing the attribute from one
span makes it fail and names that method.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* test(core): count spans against release attributes, and cover both emitters

Two review findings, both real.

The guard only asked whether a method mentioned crewai_version anywhere, so a
method opening two spans while recording the release on one of them passed.
task_started is exactly that shape. It now counts start_span calls against
_add_attribute(..., "crewai_version", ...) calls and fails when the second is
smaller, naming the method and both counts. Verified non-vacuous: removing the
attribute from Task Execution alone - which the previous version accepted -
now fails with "task_started (2 span(s), 1 version attribute(s))".

The behavioural cases only ever ran against crewai's emitter, because _emit
builds that singleton, so the five changed crewai_core methods had no
behavioural coverage at all. Added a parametrized case over all eight spans
crewai_core emits, using the fixture already in that file - covering the three
that already recorded the release as well, so a regression there is caught too.

Also removed the function-local `import crewai`: the paths now come from
inspect.getfile() on the two classes, which is both consistent with the file's
existing import style and more direct than guessing the module layout.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 23:57:37 +00:00
Lorenze Jay
1818792fb1 feat(execution): introduce execution context management with UUID sup… (#6988)
* feat(execution): introduce execution context management with UUID support

- Added `execution.py` to manage execution UUIDs for tracking nested execution contexts.
- Implemented `begin_execution` and `end_execution` functions to handle the lifecycle of execution contexts.
- Updated `Crew` and `Flow` classes to utilize the new execution context management, ensuring proper tracking during execution.
- Added tests for execution UUID creation, inheritance, and lifecycle management to ensure functionality and correctness.

* feat(execution): enhance execution context management in Crew class

- Introduced `begin_execution` and `end_execution` calls in the `Crew` class to manage execution tokens effectively.
- Updated the `akickoff` method to ensure proper lifecycle handling of execution contexts.
- Added tests to verify the creation and clearing of execution UUIDs during the `akickoff` process, ensuring correct behavior in various scenarios.

* feat(execution): add execution_uuid to PendingFeedbackContext for flow resumption

- Introduced `execution_uuid` to the `PendingFeedbackContext` class to maintain the UUID across flow pauses and resumes, ensuring traceability of execution contexts.
- Updated the `Flow` class to utilize the new `execution_uuid` during execution management, enhancing the handling of paused flows.
- Added tests to verify that the execution UUID is correctly persisted and restored during flow operations, ensuring consistent behavior across sessions.

* refactor(execution): streamline execution UUID management and update tests

- Removed the `ensure_execution_uuid` function to simplify UUID handling, consolidating logic into `begin_execution` and `end_execution`.
- Updated the `clear_execution_uuid` function to ensure it correctly restores previous UUIDs using context tokens.
- Modified tests to reflect changes in execution UUID management, ensuring proper creation, inheritance, and clearing of UUIDs during execution contexts.
- Enhanced the `PendingFeedbackContext` documentation to clarify the handling of `execution_uuid` for pending rows.
2026-08-13 16:29:46 -07:00
João Moura
4b9b8bcbb9 feat(events): record what kind of exception ended a flow (#6982)
* feat(telemetry): record what kind of exception ended a flow

Flow failures are visible but undiagnosable. Live data shows roughly 17% of
flows ending in outcome=failed, and 72% of AgentExecutor failures completing
in under 200ms - far too fast to be an LLM call - but nothing records what
the failure actually is, so there is no way to tell a real defect from a
user pressing Ctrl-C.

Record the exception's class name as error_type on Flow Completed and Flow
Method Failed. The class name only: str(error) is never read, because it
routinely carries prompts, model output, file paths and credentials. The
isidentifier() check is the allowlist that enforces it - any message text
reaching that argument carries a space or punctuation and is dropped - and
it lives inside Telemetry rather than at the call site so a future caller
cannot bypass it. Method names and flow state remain unrecorded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* docs(frontend): point the frontend guides at their edge paths

The frontend guides added in #6686 exist only under edge - they are not in
any frozen version snapshot - but their 80 internal links use the bare
/en/guides/frontend/... form, which resolves against the released versions
where those pages do not exist. mint broken-links fails on every one of
them, which blocks every open PR, not only the one that added them.

Use the /edge/en/... form the repo already uses for other edge-only pages
(concepts/streaming, learn/execution-boundary-hooks). Anchors are preserved.
No page content changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 16:12:19 +00:00
Rip&Tear
5d7ae87177 fix mysql search table name validation (#6341)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
2026-08-13 14:10:01 +08:00
Ran Shemtov
27083f4131 docs: add Frontend guides (CopilotKit + AG-UI) (#6686)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
* docs: add Frontend guides section (CopilotKit + AG-UI)

Add a Frontend sub-group under Guides documenting how to build user
interfaces for CrewAI Crews and Flows with CopilotKit over the AG-UI
protocol. Pages: overview, generative UI, tool-based generative UI,
agentic generative UI, human-in-the-loop, shared state, frontend
actions, predictive state updates, and channels.

* docs: mirror Frontend guides into v1.15.5 (Latest)

Also register the Frontend sub-group and pages under the default
v1.15.5 version so the section is visible without switching to Edge.

* docs(frontend): address audit — correct APIs and claims

- Use useRenderTool for display-only tool rendering (was useFrontendTool)
- Correct state 'auto-streams' claims: snapshot at step boundaries,
  document copilotkit_emit_state for mid-step progress
- Fix setState usage to spread full state (replace, not merge)
- Add tool description to the frontend-action example
- Rewrite Channels with the real @copilotkit/channels createBot API
  (Slack + Discord adapters); drop unsupported platform claims
- Note self-hosted vs managed CopilotKit paths and pin package versions

* docs(frontend): remove versions callout from overview

* docs(frontend): drop package-generation framing from emit_state note

* docs(frontend): add generative UI spectrum (A2UI, reasoning) + Conversational Flows

Rewrite generative-ui as the controlled/declarative/open-ended spectrum;
add A2UI (declarative), Reasoning (controlled), and a Conversational Flows
page; add a backend-tools section to tool-based; note the three execution
shapes in the overview.

* docs(frontend): address review — edge-only, attribute access, safe defaults

Remove the docs/v1.15.5 mirror (versioned snapshots are cut from edge by
the release tooling; the docs-snapshots CI guard rejects manual docs/v*
writes). Use attribute access on the LiteLLM message in shared-state,
guard setState against undefined agent/recipe, and use
Field(default_factory=list) for the agent-state list.
2026-08-12 10:01:16 -07:00
João Moura
77a929ecf5 feat(tracing): record when a trace batch is shared with amp (#6966)
* feat(tracing): record when a trace batch is shared with amp

A trace batch is sent to AMP on every traced run, but nothing on the OSS
side recorded that it happened, so a project's first touch with AMP was
invisible in telemetry. Emit a Feature Usage span on successful
finalization: tracing:ephemeral_sent before the user has an account,
tracing:authenticated_sent after.

Emitted on finalize rather than init because a batch that initializes and
then fails to send never lands in AMP. Reading is_ephemeral from batch
state at finalize also means a run that starts authenticated and falls
back to ephemeral on a 401 reports ephemeral, which is what happened.

Rides the existing Feature Usage span, so no new pipeline is needed to
read it, and it carries project_id and coding_agent for free through the
common attributes processor. Records only that a batch arrived - never
trace contents, crew or flow names, inputs, or outputs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* docs(telemetry): disclose the attributes the trace signal carries

The new row said only that a batch arrived was recorded, which reads as
excluding the common attributes every span carries. project_id and the
coding assistant are disclosed in the Execution Environment row, but
"only" actively contradicted that. Name them here too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 09:46:11 -07:00
João Moura
93d7a07422 feat(telemetry): count deployments from any origin and record where they started (#6974)
Deployments were only countable through two span types that no aggregation
reads, and cli_usage:deploy counted the TUI button rather than deployments.
Emit deploy:created and deploy:pushed alongside the existing spans so a
deployment is countable from the feature-usage aggregation no matter how it
was started, and tag Create Crew Deployment / Start Deployment with
source=cli|tui so the two origins stay distinguishable.

Separately, the TUI's `t` and `d` key bindings dispatch straight to
action_view_traces / action_deploy_crew, which never recorded anything -
only on_button_pressed did. Every keyboard-driven trace view and deploy was
therefore invisible. Move the recording into the actions, which both input
paths funnel through, and past the completed guard so a mid-run keypress
that does nothing is not counted as usage.


Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 15:41:59 +00:00
João Moura
8b646620be fix(events): stop a failed turn from marking the next one failed (#6965)
* fix(telemetry): stop a failed turn from marking the next one failed

A conversational session that opts out of deferred finalization ends each
turn with its own FlowFailedEvent, emitted inside kickoff() before
handle_turn() emits ConversationTurnFailedEvent. The flag was therefore set
after the run that owned it had already cleared it, survived on the
instance, and reported the next healthy turn as failed.

Gate the flag on the run still having its start stamp: a deferring session
keeps it (no per-turn terminal event), so it still reports a failed turn at
session end.

Also aligns the Flow Lifecycle Signals privacy row with the rest of the
telemetry table, which qualifies every user-authored field it records with
"should not include personal info", and fixes a telemetry test that built
InputResponse with an unsupported `value` keyword - ask() swallowed the
TypeError, so the test asserted the signals while exercising the
provider-error path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(telemetry): cover the streamed turn emitter of the failure flag

stream_turn() is the second emitter of ConversationTurnFailedEvent and
leaks the same flag as handle_turn(). Both regression tests fail on
77c68bd with ['failed', 'failed'].

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 20:59:19 +05:30
João Moura
28d868c4f4 [docs-freeze] docs: snapshot and changelog for v1.15.15 (#6964)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2026-08-11 18:27:18 -07:00
João Moura
7d2437cf85 feat: bump versions to 1.15.15 (#6962)
* feat(flow): report flow outcome and human-in-the-loop signals

A flow reported only that it started. FlowFinishedEvent, FlowFailedEvent,
MethodExecutionFailedEvent, MethodExecutionPausedEvent and FlowPausedEvent all
reached the console formatter and stopped there, and FlowInputRequestedEvent,
FlowInputReceivedEvent and ConversationTurnFailedEvent had no listener at all -
so success rate, failure rate and every HITL pause were unmeasurable.

Adds flow:completed, flow:failed, flow:method_failed, flow:paused,
flow:hitl_paused, flow:input_requested, flow:input_received and
flow:conversation_turn_failed as feature-usage spans, which the existing
feature-usage aggregation already reads.

Deliberately does not hold the Flow Execution span open to measure duration:
flow_executions_daily_target counts those spans at start, so a run that never
finishes would disappear from the count entirely. Duration needs its own span.

Counts only - flow names, method names, error text and flow state are never
recorded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* feat(flow): record how long a flow ran

Adds a Flow Completed span carrying flow_name, duration_ms and outcome,
emitted when a flow finishes or fails. Elapsed time comes from a monotonic
stamp taken at flow start and cleared on use.

Kept separate from the Flow Execution span rather than holding that one open:
it is emitted and closed at start and the daily aggregate counts it, so
holding it would drop every run that is killed or crashes from the execution
count. A killed run now simply has no Flow Completed row, and the count is
unaffected.

Elapsed time is an explicit duration_ms attribute rather than the span's own
duration, which the ingestion pipeline stores as a suffixed string
("0.0000184s") that downstream aggregation parses to zero.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* feat(flow): tag flow origin and report resumed runs

Two gaps found while testing the pause/resume path end to end.

Resumed runs were invisible. There is no resume event: a restored run re-enters
through kickoff(), so it looked identical to a fresh start. flow:resumed is
derived from _is_execution_resuming at flow start, which makes
flow:paused - flow:resumed the abandonment rate.

Flow counts are dominated by CrewAI's own AgentExecutor, which is itself a Flow
and runs once per agent execution - it is the top flow in the warehouse by a
wide margin. Nothing distinguished it from a user's flows except guessing at the
name. Both Flow Execution and Flow Completed now carry origin: "internal" when
the flow class is defined under crewai.*, "user" otherwise. Tagging only the new
span would have left the existing daily count unsplittable.

Both span methods take origin with a default, so their signatures stay
backward compatible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(flow): scope outcome and resume signals to user flows

Two findings from review, both confirmed against the code.

Outcome features counted CrewAI's own flows. The agent executor, memory
encoding and memory recall are all Flows and all set suppress_flow_events;
they run far more often than anything a user wrote, so flow:completed,
flow:failed and flow:method_failed were mostly bookkeeping. Those three are now
emitted only for flows the caller wrote. Internal outcomes are still recorded
on the Flow Completed span, which carries origin.

flow:resumed counted checkpoint restores. _is_execution_resuming is set both by
from_pending (a human pause) and by a checkpoint restore that never paused for
anyone, so resumes could exceed pauses and the abandonment rate was unusable.
Keyed off _pending_feedback_context instead, which only from_pending sets.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(flow): declare internal flows instead of inferring them

Three findings from review, all confirmed against the code.

Gating on suppress_flow_events was wrong. That flag asks for console quiet and
is a public field, so a caller who set it on their own flow silently lost
flow:completed, flow:failed and flow:method_failed.

Deciding origin from the defining module was also wrong. Flow.from_declaration()
returns a Flow typed in crewai.flow.flow, so a caller's declarative flow was
reported as one of CrewAI's own - the inversion this split exists to prevent.

Both had the same root cause: the discriminator was inferred. Flow now declares
is_crewai_internal, set on the agent executor and the memory encoding/recall
flows, and one helper serves both origin and the outcome gate.

A failed conversational session was reported as completed. Its session closes
with FlowFinishedEvent whatever happened, so a failed turn produced
flow:conversation_turn_failed and flow:completed together. The turn failure is
now recorded on the flow and read back when the session finishes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* refactor(flow): report flow lifecycle as spans, not feature usage

Flow start, completion, pause and method failure are lifecycle facts, and the
lifecycle is reported as spans everywhere else. Reporting them through
feature usage put them in a table that aggregates on the feature string alone -
it cannot carry origin, duration or outcome, so those signals could never be
split between a user's flows and the ones CrewAI runs for itself.

Adds Flow Paused and Flow Method Failed spans, and a resumed marker on Flow
Execution so a run restored from a pause is not counted as a second fresh
start. Removes the duplicate feature rows for completed, failed, method_failed,
paused and resumed - every one of those facts is now on a span, with more
attached to it than the feature row ever carried.

Feature usage keeps only genuine adoption signals: flow:hitl_paused,
flow:input_requested, flow:input_received and flow:conversation_turn_failed.

Also clears the conversational turn-failure flag on every terminal path. A turn
that failed without deferred finalization ends via FlowFailedEvent, and the flag
left set there marked the next run on that instance as failed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* test(flow): update the flow_execution_span caller for the resumed argument

Adding the resumed marker changed a signature that tests/utilities/test_events.py
asserts on exactly, and that assertion was not re-run before pushing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* test(flow): make the checkpoint-restore guard actually guard

The test asserted that flow:resumed was absent from feature usage, but that
signal moved onto the Flow Execution span. The assertion could no longer fail,
so a regression that mis-tagged checkpoint restores as resumes would have gone
unnoticed.

Now asserts the resumed attribute, and waits for the handlers: the manual emit
dispatches asynchronously, so the previous shape also read its result before the
listener had run.

Confirmed it discriminates - keying resumed off _is_execution_resuming again
fails it with [('RestoredFlow', True)] == [('RestoredFlow', False)].

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(telemetry): record the resumed marker as a string

Verified end to end against the live collector and ClickHouse: the pipeline
encodes a boolean attribute as the presence of a vBool key, so false arrives as
the key simply being absent. That is invisible in the schema and easy to read
wrongly - crew_memory is extracted as "the attribute exists" and consequently
reports 1 for 99.8% of crews against a field that defaults to False.

A string leaves nothing to infer. Confirmed in the warehouse: the emitted span
reads resumed = "false".

Adds direct coverage for the attributes each flow span records, including both
resumed values, and resets the Telemetry singleton in the helper so more than
one span method can be exercised per session.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* feat: bump versions to 1.15.15

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 22:13:41 -03:00
João Moura
7642e615a3 feat(flow): report flow outcome, duration and human-in-the-loop signals (#6961)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
* feat(flow): report flow outcome and human-in-the-loop signals

A flow reported only that it started. FlowFinishedEvent, FlowFailedEvent,
MethodExecutionFailedEvent, MethodExecutionPausedEvent and FlowPausedEvent all
reached the console formatter and stopped there, and FlowInputRequestedEvent,
FlowInputReceivedEvent and ConversationTurnFailedEvent had no listener at all -
so success rate, failure rate and every HITL pause were unmeasurable.

Adds flow:completed, flow:failed, flow:method_failed, flow:paused,
flow:hitl_paused, flow:input_requested, flow:input_received and
flow:conversation_turn_failed as feature-usage spans, which the existing
feature-usage aggregation already reads.

Deliberately does not hold the Flow Execution span open to measure duration:
flow_executions_daily_target counts those spans at start, so a run that never
finishes would disappear from the count entirely. Duration needs its own span.

Counts only - flow names, method names, error text and flow state are never
recorded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* feat(flow): record how long a flow ran

Adds a Flow Completed span carrying flow_name, duration_ms and outcome,
emitted when a flow finishes or fails. Elapsed time comes from a monotonic
stamp taken at flow start and cleared on use.

Kept separate from the Flow Execution span rather than holding that one open:
it is emitted and closed at start and the daily aggregate counts it, so
holding it would drop every run that is killed or crashes from the execution
count. A killed run now simply has no Flow Completed row, and the count is
unaffected.

Elapsed time is an explicit duration_ms attribute rather than the span's own
duration, which the ingestion pipeline stores as a suffixed string
("0.0000184s") that downstream aggregation parses to zero.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* feat(flow): tag flow origin and report resumed runs

Two gaps found while testing the pause/resume path end to end.

Resumed runs were invisible. There is no resume event: a restored run re-enters
through kickoff(), so it looked identical to a fresh start. flow:resumed is
derived from _is_execution_resuming at flow start, which makes
flow:paused - flow:resumed the abandonment rate.

Flow counts are dominated by CrewAI's own AgentExecutor, which is itself a Flow
and runs once per agent execution - it is the top flow in the warehouse by a
wide margin. Nothing distinguished it from a user's flows except guessing at the
name. Both Flow Execution and Flow Completed now carry origin: "internal" when
the flow class is defined under crewai.*, "user" otherwise. Tagging only the new
span would have left the existing daily count unsplittable.

Both span methods take origin with a default, so their signatures stay
backward compatible.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(flow): scope outcome and resume signals to user flows

Two findings from review, both confirmed against the code.

Outcome features counted CrewAI's own flows. The agent executor, memory
encoding and memory recall are all Flows and all set suppress_flow_events;
they run far more often than anything a user wrote, so flow:completed,
flow:failed and flow:method_failed were mostly bookkeeping. Those three are now
emitted only for flows the caller wrote. Internal outcomes are still recorded
on the Flow Completed span, which carries origin.

flow:resumed counted checkpoint restores. _is_execution_resuming is set both by
from_pending (a human pause) and by a checkpoint restore that never paused for
anyone, so resumes could exceed pauses and the abandonment rate was unusable.
Keyed off _pending_feedback_context instead, which only from_pending sets.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(flow): declare internal flows instead of inferring them

Three findings from review, all confirmed against the code.

Gating on suppress_flow_events was wrong. That flag asks for console quiet and
is a public field, so a caller who set it on their own flow silently lost
flow:completed, flow:failed and flow:method_failed.

Deciding origin from the defining module was also wrong. Flow.from_declaration()
returns a Flow typed in crewai.flow.flow, so a caller's declarative flow was
reported as one of CrewAI's own - the inversion this split exists to prevent.

Both had the same root cause: the discriminator was inferred. Flow now declares
is_crewai_internal, set on the agent executor and the memory encoding/recall
flows, and one helper serves both origin and the outcome gate.

A failed conversational session was reported as completed. Its session closes
with FlowFinishedEvent whatever happened, so a failed turn produced
flow:conversation_turn_failed and flow:completed together. The turn failure is
now recorded on the flow and read back when the session finishes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* refactor(flow): report flow lifecycle as spans, not feature usage

Flow start, completion, pause and method failure are lifecycle facts, and the
lifecycle is reported as spans everywhere else. Reporting them through
feature usage put them in a table that aggregates on the feature string alone -
it cannot carry origin, duration or outcome, so those signals could never be
split between a user's flows and the ones CrewAI runs for itself.

Adds Flow Paused and Flow Method Failed spans, and a resumed marker on Flow
Execution so a run restored from a pause is not counted as a second fresh
start. Removes the duplicate feature rows for completed, failed, method_failed,
paused and resumed - every one of those facts is now on a span, with more
attached to it than the feature row ever carried.

Feature usage keeps only genuine adoption signals: flow:hitl_paused,
flow:input_requested, flow:input_received and flow:conversation_turn_failed.

Also clears the conversational turn-failure flag on every terminal path. A turn
that failed without deferred finalization ends via FlowFailedEvent, and the flag
left set there marked the next run on that instance as failed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* test(flow): update the flow_execution_span caller for the resumed argument

Adding the resumed marker changed a signature that tests/utilities/test_events.py
asserts on exactly, and that assertion was not re-run before pushing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* test(flow): make the checkpoint-restore guard actually guard

The test asserted that flow:resumed was absent from feature usage, but that
signal moved onto the Flow Execution span. The assertion could no longer fail,
so a regression that mis-tagged checkpoint restores as resumes would have gone
unnoticed.

Now asserts the resumed attribute, and waits for the handlers: the manual emit
dispatches asynchronously, so the previous shape also read its result before the
listener had run.

Confirmed it discriminates - keying resumed off _is_execution_resuming again
fails it with [('RestoredFlow', True)] == [('RestoredFlow', False)].

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(telemetry): record the resumed marker as a string

Verified end to end against the live collector and ClickHouse: the pipeline
encodes a boolean attribute as the presence of a vBool key, so false arrives as
the key simply being absent. That is invisible in the schema and easy to read
wrongly - crew_memory is extracted as "the attribute exists" and consequently
reports 1 for 99.8% of crews against a field that defaults to False.

A string leaves nothing to infer. Confirmed in the warehouse: the emitted span
reads resumed = "false".

Adds direct coverage for the attributes each flow span records, including both
resumed values, and resets the Telemetry singleton in the helper so more than
one span method can be exercised per session.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 00:42:09 +00:00
Lucas Gomide
65a4b7cede fix: emit FlowStartedEvent when a boundary hook aborts the flow (#6953)
* fix: emit FlowStartedEvent when a boundary hook aborts the flow

A HookAborted at EXECUTION_START or INPUT propagated before
`FlowStartedEvent` was emitted, so a policy deny left logs but no
record of the execution. On abort, stamp the state id and open the
flow scope before re-raising: the deny surfaces as a started -> failed
execution while normal runs keep the existing ordering — the started
event carries hook-resolved inputs and `id` rewrites keep redirecting
persistence restoration.

* docs: translate execution-boundary-hooks page to ar, ko, and pt-BR

The English page updated on this branch had never been localized.
Translate it into the three supported locales following
`DOCS_TRANSLATIONS.md` and register the page in each locale's
navigation in `docs/docs.json`. Untranslated link targets (the
step-hooks page and the aborting-an-operation anchor) are omitted
rather than pointed at English, matching the locale navigation
convention.
2026-08-11 11:54:27 -07:00
Lorenze Jay
6c19669d63 refactor: update date injection functionality in agents (#6850)
* refactor: update date injection functionality in agents

- Changed the description of the  parameter to clarify that it injects the current date into the agent's prompt instead of tasks.
- Removed the  method as it was no longer needed.
- Implemented a new  method in the  class to handle date injection directly into the prompt.
- Updated tests to ensure the date is correctly injected into the system prompt and user messages based on the  flag.

* translations

* nit
2026-08-11 14:36:47 -03:00
Vidit Ostwal
11890e6701 Standardize CLI flags to kebab-case (#6880)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
* Standardize CLI flags to kebab-case with deprecated snake_case aliases.

Unify active long-option naming across create, train, test, and replay while keeping hidden backward-compatible aliases and documenting the migration in edge docs and AGENTS.md.

* Emit deprecation warnings when snake_case CLI flag aliases are used.

Route hidden legacy flags through separate internal params so warnings fire only when the alias is supplied, and extend CLI tests for create, replay, and --help coverage.

* Merge CLI deprecation warn helpers into warn_deprecated(kind=...).

Replace warn_deprecated_command and warn_deprecated_flag with one helper that accepts kind="command" or kind="flag".
2026-08-11 22:17:24 +05:30
Rip&Tear
505d52323f fix(deps): bump torch to 2.13.0 for GHSA-rrmf-rvhw-rf47 (#6957)
Force torch>=2.13.0 via override-dependencies so the transitive
docling/unstructured stack picks up the CVE-2025-3000 fix, and drop the
now-unnecessary pip-audit ignore. chromadb's CVE-2026-45829 remains
ignored: the upstream fix is merged but not released on PyPI.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
2026-08-11 21:16:39 +05:30
João Moura
094b94e8d0 fix(core): scope span export to our own tracer provider (#6954)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* fix(telemetry): stop exporting third-party spans to the collector

set_tracer() installed CrewAI's TracerProvider as the global one, so every
OTel-instrumented library in the host process - HTTP servers, Redis clients,
ORMs - resolved trace.get_tracer() to our provider and exported to CrewAI's
endpoint. A 20M-row sample of the telemetry table found 18,866 distinct
operation names under our serviceName; CrewAI emits 21.

The same wiring lost data in the other direction: when an application had
already installed its own provider, our spans were created by theirs and went
to their collector, so CrewAI received nothing from instrumented processes.

Spans are now created from the private provider in both packages. Deletes
_attach_common_attributes and its WeakSet/lock, whose multi-provider dedupe
guarded a state that can no longer occur.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(telemetry): keep process context on crewai-core spans

Isolating each package to its own TracerProvider removed an accident the CLI
spans depended on: crewai_core.telemetry had no CommonAttributesSpanProcessor,
so its spans only ever carried coding_agent/runtime_context/project_id by
riding the global provider that crewai installed at import.

A differential capture of every span reaching the exporter showed 8 of 54 spans
losing those attributes - Feature Usage (cli_usage:*), Start Deployment,
Template Installed, Create Crew Deployment, Get Crew Logs, Remove Crew,
Deploy Signup Error and Flow Creation.

Moves the marker tables and the detect_* helpers to crewai_core.runtime_env and
the processor plus common_span_attributes() to crewai_core.telemetry, so both
implementations share one source of truth. crewai.telemetry.utils and
crewai.utilities.constants re-export the moved names, so their import paths are
unchanged.

Also fixes a gap that predates the isolation change: a CLI-only process never
imports crewai, so it never reported either attribute. It does now.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* fix(core): type test helpers and stop tests reaching the collector

mypy runs over lib/crewai-core/tests (the one test tree not excluded), so the
new test file needed full annotations and a narrowed span.attributes.

Also patches SafeOTLPSpanExporter before Telemetry is constructed and shuts the
provider down afterwards: __init__ wires a BatchSpanProcessor around the real
OTLP exporter, so each test was attempting a live export and leaving its batch
worker thread running.

Corrects the marker-precedence docstring, which named Cursor third when the
table checks it last so that assistants running inside its terminal are not
masked.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* style(core): use one import form per module in telemetry tests

Both test modules imported their telemetry module twice - once aliased for the
monkeypatch target and once via from-import for the names. Dropping the alias
in favour of monkeypatch's dotted-string target leaves a single import form and
removes the need to qualify every reference.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

* docs(core): drop comments that restate the code

The TRACER_NAME constants were annotated with what their name and
set_tracer()'s docstring already say, and the test fixtures narrated
provider.shutdown() and the exporter patch at more length than either needed.

Keeps the ones carrying something the code cannot: the resource-attribute
ingestion quirk, why the marker tables moved packages, and the two ordering
traps the fixtures exist to avoid.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ASfWmW3RGy4qAQm6s8U9jH

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 00:16:27 +00:00
Rip&Tear
17f107c197 fix(deps): bump gitpython to 3.1.58 in crewai-tools[github] (#6885)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
gitpython 3.1.57 has GHSA-9rj7-rf2p-w77r, GHSA-4gmw-gg2m-w46p,
GHSA-hh9p-6wh2-4mfc, GHSA-wvpp-8hx9-p66j and GHSA-jm78-9fvv-mhgr
(further unguarded git option forwarding / arbitrary file read via
--pathspec-from-file). All are fixed in 3.1.58, which the root
override-dependencies already require; align the crewai-tools github
extra with it and regenerate the lockfile.
2026-08-09 13:25:26 -07:00
João Moura
f7ba8e3521 [docs-freeze] docs: snapshot and changelog for v1.15.14 (#6877)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2026-08-08 15:57:27 -07:00
João Moura
752a2a9c0a feat: bump versions to 1.15.14 (#6876) 2026-08-08 19:55:33 -03:00
João Moura
92012aec55 feat: split runtime context from coding agent, add project id (#6867)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* feat(telemetry): split runtime context from coding agent, add project id

The coding-agent field answered two questions at once. A run with no TTY
reported "non_interactive" and an editor's integrated terminal reported
"vscode_terminal", both in the same field as the assistant name, so a run
that never had an assistant to detect was indistinguishable from one
whose assistant we failed to recognize. Together those two values were
the majority of what the field reported.

detect_coding_agent now answers only which assistant, returning "unknown"
when no marker matches. detect_runtime_context answers where the process
runs: ci, serverless, hosted_ide, notebook, container, the editor
terminals, and the interactive/non_interactive fallback. Both ride on
every span, so an assistant running inside CI reports both rather than
one masking the other.

The runtime markers are published platform contracts - CI providers,
container and serverless runtimes, hosted IDEs - so unlike the assistant
table they need no per-tool verification step. Presence is checked; no
value is read. The assistant table is unchanged: its entries still
require a confirmed, session-scoped variable, and the existing guard test
still enforces that.

Spans also carry project_id when the project declares one. It is read
through the read-only accessor, since minting an id belongs to the CLI
commands a user invoked rather than to a library call during execution,
and it is omitted entirely for projects without one. The attributes are
computed once per process and memoized, so the project file is not
re-read for each provider.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs: document execution environment telemetry attributes

Adds the execution-environment row to the data table in en, ar, ko and
pt-BR. Covers the assistant and runtime fields this branch splits apart
and the project id, and states that detection reads only whether known
environment variables are set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(telemetry): detect runtime markers by presence, split paas from serverless

Three findings from the CodeRabbit, code-quality and Cursor reviews.

The runtime loop tested truthiness while constants.py documented presence,
so a platform exporting a bare CI= fell through to the TTY fallback and
was mislabelled as an ordinary local run. Presence is now what it says.
The assistant markers keep truthiness deliberately: there an empty value
means the tool set a placeholder rather than claiming the session.

DYNO and WEBSITE_INSTANCE_ID marked Heroku dynos and Azure App Service
instances as serverless, and since serverless is checked first they could
never reach the container label. They move to a paas context, which is
what they are: long-lived containers rather than per-invocation
functions. AWS_EXECUTION_ENV is dropped entirely - it is set on ECS and
EC2 as well as Lambda, and AWS_LAMBDA_FUNCTION_NAME already covers Lambda
without the collision.

The container probe no longer wraps os.path.exists in a try/except.
os.path.exists handles OSError internally and returns False, so the
handler guarded a condition that cannot occur and only hid the intent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(telemetry): widen assistant detection from published marker sets

The table previously covered three assistants because the rest were
unverified. They are documented after all: vercel/detect-agent publishes
a machine-readable detection matrix (agents.json), corroborated by the
proposal in agentsmd/agents.md#136 and by microsoft/vscode#311734.

Adds cline, gemini_cli, augment, opencode, antigravity and junie, plus
CLAUDE_CODE alongside CLAUDECODE. Gemini's marker is confirmed by its own
docs, which state that run_shell_command sets GEMINI_CLI=1 in the
subprocess environment.

Rule 2 excluded several entries those sources list. Goose's
GOOSE_PROVIDER and Copilot's COPILOT_MODEL and COPILOT_GITHUB_TOKEN are
user configuration, and a committed .env carrying one would relabel every
ordinary run - the AIDER_MODEL trap the guard test already pins, now
parametrized over all four. Replit's REPL_ID names a hosted environment
rather than an assistant, so it stays a runtime context. Copilot sets no
session marker at all today; that is an open request upstream.

The new assistants are ordered ahead of Cursor, since CURSOR_* is set for
every integrated terminal and would otherwise mask anything spawned
inside it - the same ordering Codex already needed.

Also adds the proposed cross-vendor AI_AGENT marker as a last resort,
reported as "other". It establishes that an assistant is present without
naming one, and its value is an arbitrary vendor string, so the value is
never read.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(deps): raise gitpython and pypdf floors for new advisories

gitpython 3.1.57 carries GHSA-9rj7-rf2p-w77r, GHSA-4gmw-gg2m-w46p,
GHSA-hh9p-6wh2-4mfc, GHSA-wvpp-8hx9-p66j and GHSA-jm78-9fvv-mhgr: further
unguarded git option forwarding in Repo.init, read-tree and git-config,
plus arbitrary file read via --pathspec-from-file. Fixed in 3.1.58.

pypdf 6.14.2 carries GHSA-fwg2-594c-jp42 and GHSA-fp3f-mc75-235c,
unbounded runtime and memory on large content and /ToUnicode streams.
Fixed in 6.15.0.

Both floors were already pinned, so only the versions move. Their
exclude-newer-package cutoffs had to move with them - 3.1.58 landed
2026-08-04 and 6.15.0 on 2026-08-06, both past the existing dates, so the
resolver could not have seen either release.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(telemetry): share assistant precedence with the env-context path

Four findings from the Cursor and CodeRabbit reviews, three of them the
same root cause.

get_env_context restated the precedence the shared table already defines,
so every marker added for telemetry was invisible to it: a session
exposing only CLAUDE_CODE reported claude_code on spans while emitting
DefaultEnvEvent, and an assistant running inside a Cursor terminal
reported that assistant on spans while emitting CursorEnvEvent. It now
walks CODING_AGENT_ENV_MARKERS and maps the three assistants that have an
event class of their own, defaulting the rest to DefaultEnvEvent. A test
now asserts the two paths agree for every marker in the table, so they
cannot drift again.

The generic AI_AGENT marker was documented as presence-only but ran
through the truthiness loop with everything else, so an empty value fell
through to unknown. It moves out of the table and is checked by presence
after it, which also keeps the named markers' truthiness intact.

Azure Functions run on the App Service host and inherit
WEBSITE_INSTANCE_ID, so moving that marker to paas would have relabelled
them. The FUNCTIONS_* markers are checked first to keep them serverless.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(telemetry): stop export assertions depending on test order

test_all_common_attributes_land_on_exported_spans failed in CI with an
IndexError on an empty span list, and only in one shard: the suite runs
with OTEL_SDK_DISABLED set, so TracerProvider hands out no-op tracers and
an export-based assertion sees zero spans rather than a wrong attribute.
It passed only when it happened to run after a test whose fixture flips
the variable, which random ordering decides.

Adds an otel_enabled fixture that sets the variable for the four tests
asserting on exported spans. Three of them predate this branch and had
the same latent dependency - they are fixed here because the new test
made the ordering hit reachable, and leaving them would keep the required
check red.

Verified by running every test in the file individually, all of which
previously exposed the dependency, and the telemetry suite three times
under random ordering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-07 17:28:52 -07:00
João Moura
5fa010450b [docs-freeze] docs: snapshot and changelog for v1.15.13 (#6866)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
2026-08-07 14:13:07 -07:00
João Moura
42e041146e feat: bump versions to 1.15.13 (#6865) 2026-08-07 21:10:19 +00:00
Lucas Gomide
e264e058a7 fix: preserve provider on LiteLLM-routed models (#6849)
* fix: preserve provider on LiteLLM-routed models

LiteLLM construction computed the real provider in `__new__` but never
passed it into init, so `BaseLLM` silently defaulted every shared-path
model to `openai`. Infer the provider from a `provider/model` prefix
when none is supplied so groq, cohere, mistral, and the rest report
themselves correctly to callers like the policy engine.

* fix: avoid double-prefixing instructor model strings

With LiteLLM models now carrying a real `provider` while `model` keeps
its `provider/name` form, `InternalInstructor` was building
`groq/groq/...` for `instructor.from_provider`. Skip the prefix when
the model string is already qualified.

* fix: format LiteLLM multimodal content as OpenAI-shaped blocks

Preserving the real provider on the LiteLLM path made
`format_multimodal_content` emit Anthropic-native blocks for
`anthropic/...` models, which LiteLLM rejects. Keep `provider` as the
model identity for policies, but format multimodal blocks with the
OpenAI chat schema when `is_litellm` is set. Expose the formatter helper
on `BaseLLM` so native OpenAI/Azure completions share the same API.
2026-08-07 11:20:28 -04:00
Lucas Gomide
34230a0182 fix: harden brittle LLM event-bus mocks (#6861)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
* fix: patch the event-bus singleton in usage event tests

`TestEmitCallCompletedEventPassesUsage` mocked `CrewAIEventsBus.emit`
on the class, but `_emit_call_completed_event` calls the
`crewai_event_bus` singleton. Under CI that left the real bus emitting
and the mock never seeing a call. Patch the singleton where
`base_llm` imports it instead.

* fix: harden llm call-failed event test against VCR fallback

`test_llm_emits_call_failed_event` marked VCR while mocking
`_handle_completion`, and its cassette recorded a successful reply.
When the class-level patch missed under xdist, VCR replayed success
and the expected exception never fired. Patch the instance method and
drop the cassette so the failure path cannot silently succeed.

* fix: patch the event-bus singleton instance in emit mocks

`patch.object(CrewAIEventsBus, "emit")` misses callers when an
instance-level `emit` shadows the class method — common under xdist
after other suites touch the singleton. Patch `crewai_event_bus.emit`
on the shared instance instead across the LLM event mock fixtures.
2026-08-07 19:23:32 +05:30
Vidit Ostwal
988f060c93 Fix Anthropic cache token usage underreporting (#6844)
* Fix Anthropic native provider to include cache tokens in input totals.

Anthropic reports cache read and cache creation separately from input_tokens; fold them into input_tokens and total_tokens so billed usage is not underreported on cached workloads.

* Reconcile unreconciled Anthropic cache tokens in UsageMetrics.

LiteLLM and flow event paths can pass raw Anthropic usage where input_tokens excludes cache counters; fold them into prompt and total tokens without double-counting native provider payloads.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Document UsageMetrics token field semantics for flows and crews.

Clarify that total_tokens is prompt plus completion, breakdown fields are not additive, and Anthropic cache counters are folded into prompt_tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Document Anthropic cache token accounting in LLM provider docs.

Explain how split Anthropic input counters map to UsageMetrics and link to the flows field semantics section.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Restore cache_creation_tokens breakdown in UsageMetrics normalization.

Keep cache writes as a separate breakdown field while they remain folded into prompt_tokens for billed totals.

* Replace cross-page doc links with plain-text section references.

Avoid internal hyperlinks between concept pages for SEO; point readers to section names in prose instead.

* Apply ruff formatting to usage metrics helpers.

* Sync ar, ko, and pt-BR docs for Anthropic usage metrics updates.

Translate UsageMetrics semantics and Anthropic cache token accounting changes in crews, flows, and llms concept pages.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:07:02 +05:30
Vidit Ostwal
150dd1cadd fix: bump h2 to 4.4.1 for GHSA-6hr6-w5qg-qmwg (#6860)
Override the transitive h2 pin so pip-audit no longer fails on CVE-2026-71554 (duplicate Host header request smuggling).
2026-08-07 16:50:56 +05:30
Vidit Ostwal
03e3724bff docs: add DOCS_TRANSLATIONS workflow for locale sync (#6846)
* docs: add DOCS_TRANSLATIONS workflow for locale sync

Document how to git-detect English MDX changes and sync ar, ko, and pt-BR
translations, and reference it from AGENTS.md.

* docs: add fence language tags in DOCS_TRANSLATIONS.md

Mark the checklist and example output blocks with markdown and text
identifiers for correct rendering.
2026-08-07 15:25:35 +05:30
Rip&Tear
0a8f6c920f docs: fix broken README links, TOC, and contribution guidance (#6854)
* docs: fix broken README links, TOC, and contribution guidance

Update stale docs/AMP URLs, repair the Learning Resources heading and TOC
nesting, align contribution commands with the monorepo CONTRIBUTING guide,
and clean up small copy issues in examples and FAQ.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

* docs: restore tiktoken troubleshooting wording in README

Keep the more explicit install guidance per review feedback.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
2026-08-07 15:15:07 +05:30
João Moura
18c52c4e1d [docs-freeze] docs: snapshot and changelog for v1.15.12 (#6836)
Some checks failed
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
2026-08-05 22:56:24 +00:00
João Moura
10583d6ee3 feat: bump versions to 1.15.12 (#6835) 2026-08-05 19:49:52 -03:00
Lorenze Jay
b1b6f6f539 feat(devtools): bump Flow canary on release (#6830) 2026-08-05 15:46:51 -07:00
João Moura
0c74f23596 feat(tools): add URLReadTool for reading arbitrary URLs (#6834)
* feat(tools): add URLReadTool for reading arbitrary URLs

FileReadTool is confined to the local filesystem, so there was no way for
an agent to read a document that lives behind an http(s) URL. Rather than
adding a flag to FileReadTool, this adds a separate tool: granting it
grants network egress to addresses an LLM picks at runtime, and that
should be a deliberate choice rather than a toggle on a filesystem tool.

URLReadTool fetches a URL and returns its content as text. PDF and DOCX
bodies have their text extracted, HTML is stripped to visible text, and
text-shaped types (plain text, Markdown, JSON, XML, YAML, CSV) are
decoded using the charset the server declares. Any other content type is
refused rather than returned as base64, keeping the output text-only.

Requests reuse the existing SSRF protections in security/safe_requests:
validate_url resolves every hostname and rejects private, loopback,
link-local and reserved addresses (covering cloud metadata endpoints),
and safe_get never auto-follows redirects, revalidating each hop and
dropping credentials on cross-origin ones. Resolving before validating
also normalizes encoded forms, so http://2130706433/ is rejected as
127.0.0.1 without needing a string blocklist.

Adds safe_get_bounded on top of that, which streams the body and
abandons it once it crosses max_bytes. The cap counts decoded bytes,
which is what a compressed response expands into -- Content-Length
describes the wire size and cannot bound that. It also closes the
redirect hops, which stream=True would otherwise leave holding their
connections.

Two risks are documented rather than closed. Validation resolves the
hostname and requests resolves it again to connect, so DNS rebinding
remains possible; closing it needs the connection pinned to the
validated address, which would change behavior for all existing
safe_get callers. And the returned text is untrusted remote content
entering an agent's context, which input validation cannot address.

Also fixes a temp file leak in PDFLoader, which reached the same
pymupdf-from-URL path. It wrote downloads to NamedTemporaryFile with
delete=False and never unlinked them, so every PDF ingested from a URL
left a file behind. It now opens from memory, the way URLReadTool does,
which removes the leak by construction instead of relying on cleanup on
each error path; its doc.close() also moves into a finally so a failure
mid-extraction still releases the handle. PDFLoader had no test file, so
this adds one covering both paths plus a regression test asserting no
temp file is created.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tools): address review feedback on URLReadTool

Bound start_line and line_count with ge=1 in the args schema. Both were
unbounded, and _window computes stop as start + line_count, so a negative
line_count reached islice, which rejects a negative stop. The windowing
runs outside the tool's error handling, so that escaped _run as a raw
ValueError instead of an error string. BaseTool.run validates kwargs
against args_schema, so the constraint refuses the value before any
request is made. _window also clamps its own bounds now, so it cannot
raise if called directly.

Bound the PDFLoader download with safe_get_bounded. The body is held in
memory for the whole extraction, so it needed a ceiling; it defaults to
50 MiB and takes a max_bytes kwarg to load() for callers ingesting
larger documents.

Patch the loader's own seam in its tests rather than requests.get. Both
safe_get and safe_get_bounded resolve the hostname before requesting, so
the previous mocks made the tests depend on DNS for example.com and fail
in a network-isolated runner for reasons unrelated to the loader.

Exercise the content-type fallback through run() rather than asserting on
_resolve_kind, so the tests survive a refactor of the classification
internals, and cover the octet-stream PDF, missing-type, query-string and
unknown-extension cases as observable behavior.

Add docstrings to the new tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(tools): close streamed redirect hops and widen type fallback

Four findings from the Copilot and Cursor reviews.

safe_get leaked its accumulated hops on every failure path. It closed the
response it was about to abandon but not the ones already in history, and
a caller handed an exception has no handle on them -- under stream=True
each holds its connection until its body is read or closed. The loop now
closes history before re-raising. Hops are still the caller's on success,
where they arrive via response.history.

safe_get_bounded rejected a non-positive max_bytes only after issuing the
request, and then reported it as an oversized body. It now fails before
the request. Its oversized-body error also named the requested URL rather
than the one that served the body, which differ after a redirect.

The content-type fallback consulted only the final URL for an extension,
so a .pdf link redirecting to an extensionless CDN or presigned path was
refused even though the requested URL identified the type. It now checks
the final URL first, then the requested one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 19:38:36 -03:00
Lucas Gomide
53def96b53 feat: add app metadata to platform action tools (#6832)
* feat: add app metadata to platform action tools

Platform policy matching needs an explicit integration slug on every
`CrewAIPlatformActionTool` at runtime. The builder now propagates each API
app key and tests cover the resulting tool metadata.

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: remove redundant platform tool app assignment

`CrewAIPlatformActionTool` already receives `app` through Pydantic during base initialization. Remove the duplicate assignment to retain one owner for field state.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 18:13:01 -04:00
Vidit Ostwal
319a20c028 docs: update scaffold AGENTS.md for unified create CLI (#6829)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Document crewai create tool/skill/template, lifecycle commands, and
deprecated-but-supported scaffolding aliases in the project template
AGENTS.md. Remove the no-op --skip_provider flag from the flow example.
2026-08-06 01:10:19 +05:30
Vidit Ostwal
8320178697 fix(flow): clarify conversational route/handler name collision errors (#6825)
* fix(flow): clarify route/handler name collision validation errors

When @listen(...) includes the handler's own name, FlowDefinition validation
fails. This change improves the error text and how it surfaces for Python
Flow classes.

What changed
- _self_listen_error in flow_definition.py: two message variants (conversational
  vs default), both include the listen condition
- build_flow_definition in dsl/_utils.py: wraps FlowDefinition ValidationError
  with the Python Flow class name
- Tests for declarative and DSL-built flows; docs follow in a separate commit

When each error surfaces

1. Conversational message — FlowDefinition validation when
   conversational.enabled is true and listen references the handler name.
   Example: @listen("create_video") on def create_video in a conversational flow.
   Surfaces via:
   - FlowDefinition.from_declaration(dict/yaml) → pydantic ValidationError for
     FlowDefinition (Value error, methods.create_video.listen listen condition...)
   - MyFlow.flow_definition() / MyFlow() → ValueError Invalid flow definition
     for MyFlow: ... (wrapped by pydantic as ValidationError for MyFlow on
     instantiation)

2. Default (non-conversational) message — same trigger check when the flow is
   not conversational. Example: @listen("publish") on def publish.
   Surfaces via the same paths as (1).

3. Class-name wrapper — only on the Python DSL path when build_flow_definition
   catches FlowDefinition ValidationError. Prepends Invalid flow definition for
   {ClassName}: to the underlying message from (1) or (2). Does not apply to
   from_declaration without a Flow class.

* docs(flow): explain conversational handler naming vs route labels

Document why @listen route labels must differ from handler method names and
recommend the handle_* naming pattern.

* docs(cli): warn against matching @listen labels to handler names

Add AGENTS.md guidance for crew and flow scaffolding so coding assistants
do not name handlers the same as their @listen route or event labels.

* docs(cli): clarify @listen self-reference fails at validation

Document that matching @listen labels to handler names raises a validation
error at flow instantiation, and that the runtime loop only occurs if
validation is bypassed.
2026-08-06 00:14:55 +05:30
Vidit Ostwal
fef32f43a0 feat(cli): unify scaffolding under crewai create <resource> (#6821)
* feat(cli): add canonical `crewai create tool` command

Unify tool scaffolding under the create verb and deprecate
`crewai tool create` with a yellow warning while keeping backward
compatibility.

* feat(cli): add canonical `crewai create skill` command

Unify skill scaffolding under the create verb and deprecate
`crewai skill create` with a yellow warning while keeping backward
compatibility.

* feat(cli): add canonical `crewai create template` command

Unify template scaffolding under the create verb and deprecate
`crewai template add` with a yellow warning while keeping backward
compatibility.

* docs: document unified `crewai create` scaffolding commands

Document canonical create forms for tool, skill, and template projects,
note deprecated aliases, and update skills and agents-md guides.

* feat(cli): extend create picker and DMN guidance for all types

Show tool, skill, and template in the interactive create picker and
list every supported type in the CREWAI_DMN usage error.

* fix(cli): allow create tool/skill/template in CREWAI_DMN mode

Only set skip_provider in DMN mode for crew creation, since tool,
skill, and template paths reject that flag as a crew-only option.

* test(cli): patch TemplateCommand at cli lookup site in DMN test

create() resolves TemplateCommand from crewai_cli.cli, not from
remote_template.main directly.
2026-08-05 16:41:27 +00:00
Rip&Tear
a3351d153d ci: report required test check names on non-code PRs (#6822)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Skipped matrix jobs never post status for branch-protection names like
tests (3.10). Add lightweight skip jobs with the same names so Actions-only
and docs-only PRs can merge without waiting forever.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
2026-08-05 19:46:19 +08:00
Rip&Tear
cfb1ed2226 Include all lib packages in CodeQL analysis paths (#6815)
lib/cli and lib/crewai-core were missing from the CodeQL config paths.
Also update the templates ignore path to the relocated CLI package.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-05 17:08:23 +08:00
Rip&Tear
fae634070b ci: skip python heavy CI on Actions-only PRs (#6818)
Exclude .github/** from the code path filter used by tests, lint,
type-checker, and vulnerability-scan so workflow-only changes (including
CodeQL) do not run the Python matrix. CodeQL itself is unchanged and still
analyzes Actions YAML on those PRs.

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
Co-authored-by: Vidit Ostwal <110953813+Vidit-Ostwal@users.noreply.github.com>
2026-08-05 16:38:45 +08:00
João Moura
b5bf858b5c [docs-freeze] docs: snapshot and changelog for v1.15.11 (#6817) 2026-08-05 03:29:51 -03:00
João Moura
a60d36a8df feat: bump versions to 1.15.11 (#6816) 2026-08-04 22:52:54 -07:00
Rip&Tear
323334dac6 fix: clear CodeQL incomplete URL substring sanitization alerts (#6804)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Nightly Canary Release / Check for new commits (push) Has been cancelled
Nightly Canary Release / Build nightly packages (push) Has been cancelled
Nightly Canary Release / Publish nightly to PyPI (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* fix: clear CodeQL incomplete URL substring sanitization alerts

Replace hostname substring checks with urlparse hostname matching in
RAG DataType classification, and assert the full mocked Stagehand
navigate result instead of searching for a URL substring.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

* test: call DataTypes.from_content in GitHub hostname tests

from_content lives on DataTypes, not the DataType enum.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

* test: harden tool-call streaming emit mock against instance shadowing

CI failed when class-level CrewAIEventsBus.emit patches were shadowed by
the singleton instance. Patch both the class and crewai_event_bus.emit,
and read events from kwargs/args explicitly.

Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rip&Tear <theCyberTech@users.noreply.github.com>
2026-08-05 13:28:47 +08:00
Vidit Ostwal
7accafbaf4 chore(ci): group uv patch/minor Dependabot updates (#6807)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / Detect changes (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Add a patch-minor-updates group for routine version bumps while keeping
the existing security-updates grouping. Ignore semver-major updates so
breaking upgrades stay manual.
2026-08-04 23:04:20 +05:30
Lucas Gomide
9d659a644b feat: track interception-hook dispatches in telemetry (#6805)
`HookDispatchedEvent` was already emitted from the dispatcher but never
landed in Feature Usage. Wire it through `hook_dispatched_span` so hook
adoption and abort outcomes (e.g. policy checks) show up in the same
ClickHouse aggregation as other features.
2026-08-04 13:13:24 -04:00
8798 changed files with 1919562 additions and 6217 deletions

View File

@@ -29,7 +29,7 @@ uv run pre-commit install
## Repository Structure
This is a uv workspace with four packages under `lib/`:
This is a uv workspace with six packages under `lib/`:
| Package | Path | Description |
|---------|------|-------------|
@@ -37,6 +37,8 @@ This is a uv workspace with four packages under `lib/`:
| `crewai-tools` | `lib/crewai-tools/` | Tool integrations |
| `crewai-files` | `lib/crewai-files/` | File handling |
| `devtools` | `lib/devtools/` | Internal release tooling |
| `crewai-cli` | `lib/cli/` | Command-line interface |
| `crewai-core` | `lib/crewai-core/` | Shared core utilities |
Documentation lives in `docs/` with translations under `docs/{en,ar,ko,pt-BR}/`.
@@ -103,7 +105,8 @@ chore(deps): bump pydantic to 2.11
- Keep PRs focused — avoid bundling unrelated changes
- PRs over 500 lines are labeled `size/XL` automatically
- Title must follow the same conventional commit format
- Link related issues where applicable
- Link related issues where applicable (`#123`, `Fixes #123`, or the issue URL)
- First-time contributors must open or pick an existing **open** issue first, then mention it in the PR title or body (for example `#123`). PRs without a linked open issue are closed automatically and labeled `needs-issue`.
## Testing

View File

@@ -2,7 +2,7 @@ name: "CodeQL Config"
paths-ignore:
# Ignore template files - these are boilerplate code that shouldn't be analyzed
- "lib/crewai/src/crewai/cli/templates/**"
- "lib/cli/src/crewai_cli/templates/**"
# Ignore test cassettes - these are test fixtures/recordings
- "lib/crewai/tests/cassettes/**"
- "lib/crewai-tools/tests/cassettes/**"
@@ -18,12 +18,16 @@ paths:
- ".github/workflows/**"
- ".github/actions/**"
# Include all Python source code from workspace packages
- "lib/cli/src/**"
- "lib/crewai/src/**"
- "lib/crewai-core/src/**"
- "lib/crewai-tools/src/**"
- "lib/crewai-files/src/**"
- "lib/devtools/src/**"
# Include tests (but exclude cassettes via paths-ignore)
- "lib/cli/tests/**"
- "lib/crewai/tests/**"
- "lib/crewai-core/tests/**"
- "lib/crewai-tools/tests/**"
- "lib/crewai-files/tests/**"
- "lib/devtools/tests/**"

View File

@@ -1,6 +1,3 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
@@ -8,9 +5,22 @@ updates:
- package-ecosystem: uv
directory: "/"
schedule:
interval: "weekly"
interval: weekly
day: monday
open-pull-requests-limit: 10
groups:
security-updates:
applies-to: security-updates
patterns:
- "*"
patch-minor-updates:
applies-to: version-updates
patterns:
- "*"
update-types:
- patch
- minor
ignore:
- dependency-name: "*"
update-types:
- version-update:semver-major

24
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,24 @@
## Related issue
Fixes #
<!--
First-time contributors must mention an existing open issue in this repo
(for example #123). PRs without a linked open issue are closed automatically
and labeled needs-issue.
-->
## Summary
<!-- Explain the solution and why. -->
## Verification
<!-- List the automated and manual checks used to verify the change. -->
- [ ] Tests added or updated for the changed behavior
- [ ] Relevant tests and quality checks pass locally
## Additional context
<!-- Include screenshots, compatibility notes, follow-up work, or "None". -->

View File

@@ -15,11 +15,11 @@ on:
push:
branches: [ "main" ]
paths-ignore:
- "lib/crewai/src/crewai/cli/templates/**"
- "lib/cli/src/crewai_cli/templates/**"
pull_request:
branches: [ "main" ]
paths-ignore:
- "lib/crewai/src/crewai/cli/templates/**"
- "lib/cli/src/crewai_cli/templates/**"
jobs:
analyze:

View File

@@ -0,0 +1,88 @@
name: Welcome First-Time Contributors
on:
pull_request_target:
types: [closed]
permissions:
contents: read
issues: write
jobs:
welcome:
# Match the first-time contributor definition used by ftc-require-issue.
if: >
github.event.pull_request.merged == true &&
github.event.pull_request.user.type != 'Bot' &&
!contains(fromJSON('["MEMBER","OWNER","COLLABORATOR","CONTRIBUTOR"]'),
github.event.pull_request.author_association)
runs-on: ubuntu-latest
steps:
- name: Thank first-time contributors
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
script: |
const pullRequest = context.payload.pull_request;
const owner = context.repo.owner;
const repo = context.repo.repo;
const marker = "<!-- crewai-first-merged-pr-welcome -->";
const existingComments = await github.paginate(
github.rest.issues.listComments,
{
owner,
repo,
issue_number: pullRequest.number,
per_page: 100,
},
);
if (existingComments.some((comment) => comment.body?.includes(marker))) {
core.info("Welcome comment already exists; skipping duplicate.");
return;
}
const prUrl = pullRequest.html_url;
const shareText = [
"I just made my first contribution to @crewAIInc!",
"",
"Excited to help build the future of AI agents with CrewAI.",
"",
prUrl,
"",
"#OpenSource #AI #CrewAI",
].join("\n");
const xShareUrl = `https://x.com/intent/post?text=${encodeURIComponent(shareText)}`;
const linkedInShareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(prUrl)}`;
const body = [
marker,
"",
`## Thanks for your first contribution to CrewAI, @${pullRequest.user.login}!`,
"",
"We really appreciate the time and care you put into this PR. Your work is now part of CrewAI — welcome to the contributor community.",
"",
"Want to share your contribution? Totally optional:",
"",
`[Share on X](${xShareUrl}) · [Share the PR on LinkedIn](${linkedInShareUrl})`,
"",
"If the links don't work, feel free to copy and personalize this:",
"",
"```text",
"I just made my first contribution to @crewAIInc!",
"",
"Excited to help build the future of AI agents with CrewAI.",
"",
prUrl,
"",
"#OpenSource #AI #CrewAI",
"```",
"",
"If you share, we'd love to see it — tag **@crewAIInc** on X and **CrewAI** on LinkedIn.",
].join("\n");
await github.rest.issues.createComment({
owner,
repo,
issue_number: pullRequest.number,
body,
});

134
.github/workflows/ftc-require-issue.yml vendored Normal file
View File

@@ -0,0 +1,134 @@
name: First-time contributor issue required
on:
pull_request_target:
types: [opened, edited, reopened]
permissions:
pull-requests: write
issues: write
concurrency:
group: ftc-require-issue-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
require-issue:
# Allow-list returning contributors. FIRST_TIMER / FIRST_TIME_CONTRIBUTOR
# are often NONE on pull_request_target at opened time, which skipped the
# previous deny-list and left first-timer PRs open.
if: >
github.event.pull_request.user.type != 'Bot' &&
!contains(fromJSON('["MEMBER","OWNER","COLLABORATOR","CONTRIBUTOR"]'),
github.event.pull_request.author_association)
runs-on: ubuntu-latest
steps:
- name: Require an open issue
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}
AUTHOR_ASSOCIATION: ${{ github.event.pull_request.author_association }}
run: |
python3 << 'PY'
import json
import os
import re
import subprocess
import sys
repo = os.environ["REPO"]
pr_number = os.environ["PR_NUMBER"]
owner, name = repo.split("/", 1)
print(
"author_association=",
os.environ.get("AUTHOR_ASSOCIATION", ""),
sep="",
)
patterns = (
re.compile(r"(?<![\w./-])#(\d+)\b"),
re.compile(rf"{re.escape(owner)}/{re.escape(name)}#(\d+)\b"),
re.compile(
rf"https://github\.com/{re.escape(owner)}/{re.escape(name)}/issues/(\d+)\b"
),
)
def gh_json(*args: str) -> dict:
return json.loads(
subprocess.check_output(["gh", *args], text=True)
)
def is_open_repo_issue(number: int) -> bool:
result = subprocess.run(
["gh", "api", f"repos/{repo}/issues/{number}"],
capture_output=True,
text=True,
)
if result.returncode != 0:
stderr = result.stderr or ""
if "404" in stderr or "Not Found" in stderr:
return False
raise RuntimeError(
f"GitHub API error looking up #{number}: {stderr}"
)
payload = json.loads(result.stdout)
if "pull_request" in payload:
return False
return (payload.get("state") or "").lower() == "open"
pr = gh_json(
"pr", "view", pr_number, "--repo", repo, "--json", "title,body,state"
)
text = f"{pr.get('title') or ''}\n{pr.get('body') or ''}"
candidates = {
int(match)
for pattern in patterns
for match in pattern.findall(text)
}
if any(is_open_repo_issue(number) for number in sorted(candidates)):
sys.exit(0)
if (pr.get("state") or "").upper() == "CLOSED":
sys.exit(0)
comment = f"""Thanks for the pull request.
First-time contributors need an associated open issue before we can review a PR.
1. Open an issue with a [template](https://github.com/{repo}/issues/new/choose), or pick an existing open one.
2. Open a new PR (or reopen this one) whose title or body mentions that issue, for example `#123`.
See the [contributing guide](https://github.com/{repo}/blob/main/.github/CONTRIBUTING.md).
"""
subprocess.run(
[
"gh",
"pr",
"comment",
pr_number,
"--repo",
repo,
"--body",
comment,
],
check=True,
)
subprocess.run(
[
"gh",
"pr",
"edit",
pr_number,
"--repo",
repo,
"--add-label",
"needs-issue",
],
check=True,
)
subprocess.run(
["gh", "pr", "close", pr_number, "--repo", repo],
check=True,
)
PY

View File

@@ -18,13 +18,14 @@ jobs:
with:
# Exclusion-only patterns match every non-excluded file under the
# default "some" quantifier. Require all patterns (including "**")
# so docs-only / markdown-only PRs correctly set code=false.
# so docs/markdown/Actions-only PRs correctly set code=false.
predicate-quantifier: every
filters: |
code:
- '**'
- '!docs/**'
- '!**/*.md'
- '!.github/**'
lint-run:
needs: changes
@@ -81,7 +82,7 @@ jobs:
- name: Check results
run: |
if [ "${{ needs.changes.outputs.code }}" != "true" ]; then
echo "Docs-only change, skipping lint"
echo "Non-code change, skipping lint"
exit 0
fi
if [ "${{ needs.lint-run.result }}" == "success" ]; then

View File

@@ -18,13 +18,14 @@ jobs:
with:
# Exclusion-only patterns match every non-excluded file under the
# default "some" quantifier. Require all patterns (including "**")
# so docs-only / markdown-only PRs correctly set code=false.
# so docs/markdown/Actions-only PRs correctly set code=false.
predicate-quantifier: every
filters: |
code:
- '**'
- '!docs/**'
- '!**/*.md'
- '!.github/**'
tests-matrix:
name: tests (${{ matrix.python-version }})
@@ -121,17 +122,31 @@ jobs:
.venv
key: uv-main-py${{ matrix.python-version }}-${{ hashFiles('uv.lock') }}
# Report the required check names (tests 3.103.13) when the matrix is skipped.
# Branch protection expects these names; a skipped matrix never reports them.
tests-skip:
name: tests (${{ matrix.python-version }})
needs: changes
if: needs.changes.outputs.code != 'true'
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.10', '3.11', '3.12', '3.13']
steps:
- name: Skip non-code change
run: echo "Non-code change, skipping tests"
# Summary job to provide single status for branch protection
tests:
name: tests
runs-on: ubuntu-latest
needs: [changes, tests-matrix]
needs: [changes, tests-matrix, tests-skip]
if: always()
steps:
- name: Check results
run: |
if [ "${{ needs.changes.outputs.code }}" != "true" ]; then
echo "Docs-only change, skipping tests"
echo "Non-code change, skipping tests"
exit 0
fi
if [ "${{ needs.tests-matrix.result }}" == "success" ]; then

View File

@@ -18,13 +18,14 @@ jobs:
with:
# Exclusion-only patterns match every non-excluded file under the
# default "some" quantifier. Require all patterns (including "**")
# so docs-only / markdown-only PRs correctly set code=false.
# so docs/markdown/Actions-only PRs correctly set code=false.
predicate-quantifier: every
filters: |
code:
- '**'
- '!docs/**'
- '!**/*.md'
- '!.github/**'
type-checker-matrix:
name: type-checker (${{ matrix.python-version }})
@@ -75,17 +76,31 @@ jobs:
.venv
key: uv-main-py${{ matrix.python-version }}-${{ hashFiles('uv.lock') }}
# Report the required check names when the matrix is skipped.
# Branch protection expects these names; a skipped matrix never reports them.
type-checker-skip:
name: type-checker (${{ matrix.python-version }})
needs: changes
if: needs.changes.outputs.code != 'true'
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
steps:
- name: Skip non-code change
run: echo "Non-code change, skipping type checks"
# Summary job to provide single status for branch protection
type-checker:
name: type-checker
runs-on: ubuntu-latest
needs: [changes, type-checker-matrix]
needs: [changes, type-checker-matrix, type-checker-skip]
if: always()
steps:
- name: Check results
run: |
if [ "${{ needs.changes.outputs.code }}" != "true" ]; then
echo "Docs-only change, skipping type checks"
echo "Non-code change, skipping type checks"
exit 0
fi
if [ "${{ needs.type-checker-matrix.result }}" == "success" ]; then

View File

@@ -26,13 +26,14 @@ jobs:
with:
# Exclusion-only patterns match every non-excluded file under the
# default "some" quantifier. Require all patterns (including "**")
# so docs-only / markdown-only PRs correctly set code=false.
# so docs/markdown/Actions-only PRs correctly set code=false.
predicate-quantifier: every
filters: |
code:
- '**'
- '!docs/**'
- '!**/*.md'
- '!.github/**'
- name: Set code output
id: set
run: |
@@ -85,8 +86,37 @@ jobs:
--skip-editable
--format json
--output pip-audit-report.json
--ignore-vuln GHSA-rrmf-rvhw-rf47 # torch 2.12.0 (CVE-2025-3000): local-only memory corruption in torch.jit.script; no fix available.
--ignore-vuln GHSA-f4j7-r4q5-qw2c # chromadb 1.1.1 (CVE-2026-45829): pre-auth RCE in the HTTP server; no fix available.
# chromadb <=1.5.9: Python HTTP server issues. No PyPI release beyond
# 1.5.9 yet. CrewAI only uses PersistentClient (embedded), not the
# HTTP server.
# GHSA-f4j7-r4q5-qw2c (CVE-2026-45829): pre-auth RCE. Fix merged in
# chroma-core/chroma#7237.
--ignore-vuln GHSA-f4j7-r4q5-qw2c
# GHSA-2wm9-hf6c-p5cr (CVE-2026-45830): authenticated cross-tenant IDOR.
--ignore-vuln GHSA-2wm9-hf6c-p5cr
# GHSA-36p7-vc44-83pf (CVE-2026-45833): authenticated trust_remote_code
# injection on the collection-update endpoint.
--ignore-vuln GHSA-36p7-vc44-83pf
# GHSA-xph7-9rjv-w5fr (CVE-2026-45831): SimpleRBACAuthorizationProvider
# ignores tenant/database/collection scope.
--ignore-vuln GHSA-xph7-9rjv-w5fr
# nltk <=3.10.3: GHSA-8mgp-746c-j5xp (CVE-2026-81726): model-artifact
# APIs bypass pathsec and read/write outside allowed roots. No patched
# PyPI release yet (fixes are on nltk develop only). Transitive via
# crewai-tools[xml] -> unstructured; CrewAI does not call those APIs.
# TODO: drop this ignore when bumping nltk past 3.10.3 to a patched
# release; keep the ignore list in sync with .pre-commit-config.yaml.
--ignore-vuln GHSA-8mgp-746c-j5xp
# accelerate <=1.14.0: GHSA-4j2p-28q2-5m79 (CVE-2026-69112): path
# traversal / FIFO DoS via unsanitized sharded-checkpoint weight_map
# entries. No patched PyPI release yet (fix is huggingface/accelerate
# #4138, not shipped). Transitive via docling extras
# (docling-ibm-models / docling-slim[standard]); CrewAI does not load
# untrusted checkpoints through those APIs.
# TODO: drop this ignore when bumping accelerate past 1.14.0 to a
# patched release; keep the ignore list in sync with
# .pre-commit-config.yaml.
--ignore-vuln GHSA-4j2p-28q2-5m79
)
uv run pip-audit "${pip_audit_args[@]}"
continue-on-error: true

View File

@@ -3,19 +3,19 @@ repos:
hooks:
- id: ruff
name: ruff
entry: bash -c 'source .venv/bin/activate && uv run ruff check --config pyproject.toml "$@"' --
entry: bash -c 'case "$OSTYPE" in msys*|cygwin*|win32*) source .venv/Scripts/activate ;; *) source .venv/bin/activate ;; esac && uv run ruff check --config pyproject.toml "$@"' --
language: system
pass_filenames: true
types: [python]
- id: ruff-format
name: ruff-format
entry: bash -c 'source .venv/bin/activate && uv run ruff format --config pyproject.toml "$@"' --
entry: bash -c 'case "$OSTYPE" in msys*|cygwin*|win32*) source .venv/Scripts/activate ;; *) source .venv/bin/activate ;; esac && uv run ruff format --config pyproject.toml "$@"' --
language: system
pass_filenames: true
types: [python]
- id: mypy
name: mypy
entry: bash -c 'source .venv/bin/activate && uv run mypy --config-file pyproject.toml "$@"' --
entry: bash -c 'case "$OSTYPE" in msys*|cygwin*|win32*) source .venv/Scripts/activate ;; *) source .venv/bin/activate ;; esac && uv run mypy --config-file pyproject.toml "$@"' --
language: system
pass_filenames: true
types: [python]
@@ -29,8 +29,10 @@ repos:
- id: pip-audit
name: pip-audit
# Keep this ignore list in sync with .github/workflows/vulnerability-scan.yml.
# TODO: drop --ignore-vuln GHSA-8mgp-746c-j5xp when bumping nltk past 3.10.3.
# TODO: drop --ignore-vuln GHSA-4j2p-28q2-5m79 when bumping accelerate past 1.14.0.
entry: >-
bash -c 'source .venv/bin/activate && uv run pip-audit --skip-editable
bash -c 'case "$OSTYPE" in msys*|cygwin*|win32*) source .venv/Scripts/activate ;; *) source .venv/bin/activate ;; esac && uv run pip-audit --skip-editable
--ignore-vuln PYSEC-2024-277
--ignore-vuln PYSEC-2026-89
--ignore-vuln PYSEC-2026-97
@@ -48,7 +50,6 @@ repos:
--ignore-vuln PYSEC-2025-197
--ignore-vuln PYSEC-2025-210
--ignore-vuln PYSEC-2026-139
--ignore-vuln GHSA-rrmf-rvhw-rf47
--ignore-vuln PYSEC-2025-211
--ignore-vuln PYSEC-2025-212
--ignore-vuln PYSEC-2025-213
@@ -57,7 +58,12 @@ repos:
--ignore-vuln PYSEC-2025-216
--ignore-vuln PYSEC-2025-217
--ignore-vuln PYSEC-2025-218
--ignore-vuln GHSA-f4j7-r4q5-qw2c' --
--ignore-vuln GHSA-f4j7-r4q5-qw2c
--ignore-vuln GHSA-2wm9-hf6c-p5cr
--ignore-vuln GHSA-36p7-vc44-83pf
--ignore-vuln GHSA-xph7-9rjv-w5fr
--ignore-vuln GHSA-8mgp-746c-j5xp
--ignore-vuln GHSA-4j2p-28q2-5m79' --
language: system
pass_filenames: false
stages: [pre-push, manual]

View File

@@ -14,6 +14,23 @@ Follow these guidelines when contributing:
6. Follow software principles such as DRY and YAGNI.
7. Keep diffs as minimal as possible.
## Message Content
`LLMMessage.content` is `str | list[dict[str, Any]] | None`; the list form is
multimodal content parts. Never `str()` it — that puts a Python repr
(`[{'type': 'text', 'text': 'hi'}]`) in front of the model and into memory.
Collapse a message to text with the helper instead:
```python
from crewai.utilities.agent_utils import message_content_text
text = message_content_text(msg) # "" for None; joined text for a parts list
```
Parts arrive from a model and are typed `dict[str, Any]`, so a `text` key that
is not a string is possible. `_content_parts_text` skips those blocks rather
than raising, and names a list with no usable text `[multimodal content]`.
## Changing Docs
1. Edit MDX under `docs/edge/en/*` and reference it from `docs/docs.json` if
@@ -24,3 +41,5 @@ Follow these guidelines when contributing:
may reference them.
4. If you want to preview your changes locally, use `cd docs && mintlify dev`.
To check for broken links, run `cd docs && mintlify broken-links`.
5. After editing English docs, sync translations to `ar`, `ko`, and `pt-BR`
before finishing the task. Follow [DOCS_TRANSLATIONS.md](DOCS_TRANSLATIONS.md).

81
DOCS_TRANSLATIONS.md Normal file
View File

@@ -0,0 +1,81 @@
# Sync Docs Translations
After English documentation changes, sync the same updates to Arabic (`ar`),
Korean (`ko`), and Brazilian Portuguese (`pt-BR`).
Supported locales: `ar`, `ko`, `pt-BR`.
## Step 1 — Find changed English files with git
From the repo root:
```bash
# Uncommitted changes (staged or unstaged)
git diff --name-only HEAD -- docs/edge/en/
# All changes on this branch vs main
git diff --name-only main...HEAD -- docs/edge/en/
# Newly added files
git status --porcelain docs/edge/en/
```
Only process `*.mdx` under `docs/edge/en/`. Do not edit `docs/v*/` snapshots.
## Step 2 — Map each file to locale targets
For `docs/edge/en/<path>.mdx`, update or create:
- `docs/edge/ar/<path>.mdx`
- `docs/edge/ko/<path>.mdx`
- `docs/edge/pt-BR/<path>.mdx`
If English is a **new page**, also add matching entries in `docs/docs.json`
navigation for each locale.
## Step 3 — Translate
Use the updated English file as source of truth. When locale files already
exist, apply the same semantic change — do not rewrite unrelated sections.
Rules:
- Translate prose and frontmatter values (`title`, `description`, `sidebarTitle`)
- Keep MDX/JSX tags, code blocks, URLs, and identifiers unchanged
- Keep terms like Agent, Crew, Task, Flow, LLM, API, CLI, MCP in English where
appropriate
- Rewrite internal links: `/en/``/{lang}/` (`/ar/`, `/ko/`, `/pt-BR/`)
- Do not add translator notes
## Step 4 — Verify (optional)
```bash
cd docs && mintlify broken-links
```
Commit English and locale files together.
## Checklist
```markdown
- [ ] Git: listed changed docs/edge/en/*.mdx files
- [ ] ar: updated/created matching files
- [ ] ko: updated/created matching files
- [ ] pt-BR: updated/created matching files
- [ ] Links use /{lang}/ prefix; code blocks unchanged
- [ ] docs/docs.json updated if new English page added
```
## Example
`git diff --name-only HEAD -- docs/edge/en/` returns:
```text
docs/edge/en/concepts/llms.mdx
```
Update:
- `docs/edge/ar/concepts/llms.mdx`
- `docs/edge/ko/concepts/llms.mdx`
- `docs/edge/pt-BR/concepts/llms.mdx`

415
README.md
View File

@@ -66,7 +66,7 @@ standard for production-ready agentic automation.
# CrewAI AMP Suite
For organizations that need a commercial control plane around CrewAI, [CrewAI AMP Suite](https://www.crewai.com/enterprise) adds managed deployment, observability, governance, security, and enterprise support.
For organizations that need a commercial control plane around CrewAI, [CrewAI AMP Suite](https://crewai.com/amp) adds managed deployment, observability, governance, security, and enterprise support.
You can try one part of the suite, the [Crew Control Plane, for free](https://app.crewai.com).
@@ -88,8 +88,12 @@ intelligent automations.
- [Build with AI](#build-with-ai)
- [Why CrewAI?](#why-crewai)
- [Getting Started](#getting-started)
- [Learning Resources](#learning-resources)
- [Understanding Flows and Crews](#understanding-flows-and-crews)
- [Installation](#1-installation)
- [Setting Up Your Crew](#2-setting-up-your-crew)
- [Running Your Crew](#3-running-your-crew)
- [Key Features](#key-features)
- [Understanding Flows and Crews](#understanding-flows-and-crews)
- [Examples](#examples)
- [Quick Tutorial](#quick-tutorial)
- [Write Job Descriptions](#write-job-descriptions)
@@ -117,7 +121,7 @@ Four skills that activate automatically when you ask relevant CrewAI questions:
| Skill | When it runs |
|-------|--------------|
| `getting-started` | Scaffolding new projects, choosing between `LLM.call()` / `Agent` / `Crew` / `Flow`, wiring `crew.py` / `main.py` |
| `getting-started` | Scaffolding new projects, choosing between `LLM.call()` / `Agent` / `Crew` / `Flow`, wiring `crew.jsonc` / `main.py` |
| `design-agent` | Configuring agents — role, goal, backstory, tools, LLMs, memory, guardrails |
| `design-task` | Writing task descriptions, dependencies, structured output (`output_pydantic`, `output_json`), human review |
| `ask-docs` | Querying the live [CrewAI docs MCP server](https://docs.crewai.com/mcp) for up-to-date API details |
@@ -151,9 +155,7 @@ Setup and run your first CrewAI agents by following this tutorial.
[![CrewAI Getting Started Tutorial](https://img.youtube.com/vi/-kSOTtYzgEw/hqdefault.jpg)](https://www.youtube.com/watch?v=-kSOTtYzgEw "CrewAI Getting Started Tutorial")
###
Learning Resources
### Learning Resources
Learn CrewAI through our comprehensive courses:
@@ -187,47 +189,76 @@ The true power of CrewAI emerges when combining Crews and Flows. This synergy al
### Getting Started with Installation
To get started with CrewAI, follow these simple steps:
To get started with CrewAI, follow these simple steps. The full walkthrough lives in the [installation guide](https://docs.crewai.com/en/installation).
### 1. Installation
Ensure you have Python >=3.10 <3.14 installed on your system. CrewAI uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling, offering a seamless setup and execution experience.
CrewAI requires `Python >=3.10 and <3.14`. Check your version with:
First, install CrewAI:
```shell
uv pip install crewai
```bash
python3 --version
```
If you want to install the 'crewai' package along with its optional features that include additional tools for agents, you can do so by using the following command:
CrewAI uses [UV](https://docs.astral.sh/uv/) for dependency management and package handling. If you haven't installed `uv` yet, install it first.
**macOS/Linux:**
```shell
uv pip install 'crewai[tools]'
curl -LsSf https://astral.sh/uv/install.sh | sh
```
The command above installs the basic package and also adds extra components which require more dependencies to function.
If your system doesn't have `curl`, you can use `wget`:
### Troubleshooting Dependencies
```shell
wget -qO- https://astral.sh/uv/install.sh | sh
```
If you encounter issues during installation or usage, here are some common solutions:
**Windows:**
#### Common Issues
```shell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```
1. **ModuleNotFoundError: No module named 'tiktoken'**
If you run into any issues, refer to [UV's installation guide](https://docs.astral.sh/uv/getting-started/installation/).
- Install tiktoken explicitly: `uv pip install 'crewai[embeddings]'`
- If using embedchain or other tools: `uv pip install 'crewai[tools]'`
Then install the CrewAI CLI:
2. **Failed building wheel for tiktoken**
```shell
uv tool install crewai
```
- Ensure Rust compiler is installed (see installation steps above)
- For Windows: Verify Visual C++ Build Tools are installed
- Try upgrading pip: `uv pip install --upgrade pip`
- If issues persist, use a pre-built wheel: `uv pip install tiktoken --prefer-binary`
If you encounter a `PATH` warning, run:
### 2. Setting Up Your Crew with the YAML Configuration
```shell
uv tool update-shell
```
To create a new CrewAI project, run the following CLI (Command Line Interface) command:
If you encounter the `chroma-hnswlib==0.7.6` build error (`fatal error C1083: Cannot open include file: 'float.h'`) on Windows, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/downloads/) with *Desktop development with C++*.
Verify the install:
```shell
uv tool list
```
You should see something like:
```shell
crewai v0.102.0
- crewai
```
To upgrade the global CLI later:
```shell
uv tool install crewai --upgrade
```
This upgrades the **global `crewai` CLI tool** only. To upgrade the `crewai` version inside a project's virtual environment, see [Upgrading CrewAI in a project](https://docs.crewai.com/en/guides/migration/upgrading-crewai).
### 2. Setting Up Your Crew
`crewai create crew` creates a JSON-first crew project. Agents live in `agents/*.jsonc`, tasks and crew-level settings live in `crew.jsonc`, and `crewai run` loads that JSON definition directly.
```shell
crewai create crew <project_name>
@@ -238,199 +269,125 @@ This command creates a new project folder with the following structure:
```
my_project/
├── .gitignore
├── .env
├── agents/
│ └── researcher.jsonc
├── crew.jsonc
├── knowledge/
├── pyproject.toml
├── README.md
├── .env
└── src/
└── my_project/
├── __init__.py
├── main.py
├── crew.py
├── tools/
│ ├── custom_tool.py
│ └── __init__.py
└── config/
├── agents.yaml
└── tasks.yaml
├── skills/
└── tools/
```
You can now start developing your crew by editing the files in the `src/my_project` folder. The `main.py` file is the entry point of the project, the `crew.py` file is where you define your crew, the `agents.yaml` file is where you define your agents, and the `tasks.yaml` file is where you define your tasks.
If you need the older Python/YAML scaffold with `crew.py`, `config/agents.yaml`, and `config/tasks.yaml`, run:
```shell
crewai create crew <project_name> --classic
```
See [Using Annotations](https://docs.crewai.com/en/learn/using-annotations) for the classic pattern.
#### To customize your project, you can:
- Modify `src/my_project/config/agents.yaml` to define your agents.
- Modify `src/my_project/config/tasks.yaml` to define your tasks.
- Modify `src/my_project/crew.py` to add your own logic, tools, and specific arguments.
- Modify `src/my_project/main.py` to add custom inputs for your agents and tasks.
- Modify `agents/*.jsonc` to define each agent's role, goal, backstory, LLM, tools, and behavior.
- Modify `crew.jsonc` to define tasks, process, and input defaults.
- Add custom tools in `tools/` and reference them as `"custom:<name>"`.
- Add optional knowledge files in `knowledge/` and skill files in `skills/`.
- Add your environment variables into the `.env` file.
Use `{placeholder}` values in agent and task text, then set defaults in `crew.jsonc` under `inputs`. When you run `crewai run`, the CLI prompts for any missing values.
#### Example of a simple crew with a sequential process:
Instantiate your crew:
```shell
crewai create crew latest-ai-development
cd latest_ai_development
```
Modify the files as needed to fit your use case:
Then edit the generated files:
**agents.yaml**
**agents/researcher.jsonc**
```yaml
# src/my_project/config/agents.yaml
researcher:
role: >
{topic} Senior Data Researcher
goal: >
Uncover cutting-edge developments in {topic}
backstory: >
You're a seasoned researcher with a knack for uncovering the latest
developments in {topic}. Known for your ability to find the most relevant
information and present it in a clear and concise manner.
reporting_analyst:
role: >
{topic} Reporting Analyst
goal: >
Create detailed reports based on {topic} data analysis and research findings
backstory: >
You're a meticulous analyst with a keen eye for detail. You're known for
your ability to turn complex data into clear and concise reports, making
it easy for others to understand and act on the information you provide.
```jsonc
{
"role": "{topic} Senior Data Researcher",
"goal": "Uncover cutting-edge developments in {topic}",
"backstory": "You're a seasoned researcher who finds relevant information and presents it clearly.",
"llm": "openai/gpt-4o",
"tools": ["SerperDevTool"],
"settings": {
"verbose": true
}
}
```
**tasks.yaml**
**agents/reporting_analyst.jsonc**
````yaml
# src/my_project/config/tasks.yaml
research_task:
description: >
Conduct a thorough research about {topic}
Make sure you find any interesting and relevant information given
the current year is 2025.
expected_output: >
A list with 10 bullet points of the most relevant information about {topic}
agent: researcher
reporting_task:
description: >
Review the context you got and expand each topic into a full section for a report.
Make sure the report is detailed and contains any and all relevant information.
expected_output: >
A fully fledge reports with the mains topics, each with a full section of information.
Formatted as markdown without '```'
agent: reporting_analyst
output_file: report.md
````
**crew.py**
```python
# src/my_project/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
agents: List[BaseAgent]
tasks: List[Task]
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'],
verbose=True,
tools=[SerperDevTool()]
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'],
verbose=True
)
@task
def research_task(self) -> Task:
return Task(
config=self.tasks_config['research_task'],
)
@task
def reporting_task(self) -> Task:
return Task(
config=self.tasks_config['reporting_task'],
output_file='report.md'
)
@crew
def crew(self) -> Crew:
"""Creates the LatestAiDevelopment crew"""
return Crew(
agents=self.agents, # Automatically created by the @agent decorator
tasks=self.tasks, # Automatically created by the @task decorator
process=Process.sequential,
verbose=True,
)
```jsonc
{
"role": "{topic} Reporting Analyst",
"goal": "Create detailed reports based on {topic} data analysis and research findings",
"backstory": "You're a meticulous analyst who turns complex data into clear, concise reports.",
"llm": "openai/gpt-4o",
"settings": {
"verbose": true
}
}
```
**main.py**
**crew.jsonc**
```python
#!/usr/bin/env python
# src/my_project/main.py
import sys
from latest_ai_development.crew import LatestAiDevelopmentCrew
def run():
"""
Run the crew.
"""
inputs = {
'topic': 'AI Agents'
```jsonc
{
"name": "Latest AI Development",
"agents": ["researcher", "reporting_analyst"],
"tasks": [
{
"name": "research_task",
"description": "Conduct thorough research about {topic}. Find recent, relevant information.",
"expected_output": "A list with 10 bullet points of the most relevant information about {topic}.",
"agent": "researcher"
},
{
"name": "reporting_task",
"description": "Review the research and expand each topic into a full section for a report.",
"expected_output": "A markdown report with the main topics, each with a full section of information. No fenced code blocks around the whole document.",
"agent": "reporting_analyst",
"context": ["research_task"],
"output_file": "output/report.md",
"markdown": true
}
LatestAiDevelopmentCrew().crew().kickoff(inputs=inputs)
],
"process": "sequential",
"verbose": true,
"inputs": {
"topic": "AI Agents"
}
}
```
### 3. Running Your Crew
Before running your crew, make sure you have the following keys set as environment variables in your `.env` file:
Before running your crew, set the required keys in your `.env` file:
- An [OpenAI API key](https://platform.openai.com/account/api-keys) (or other LLM API key): `OPENAI_API_KEY=sk-...`
- A [Serper.dev](https://serper.dev/) API key: `SERPER_API_KEY=YOUR_KEY_HERE`
- Your model provider API key — see [LLM setup](https://docs.crewai.com/en/concepts/llms#setting-up-your-llm)
- A [Serper.dev](https://serper.dev/) API key if you use web search: `SERPER_API_KEY=YOUR_KEY_HERE`
Lock the dependencies and install them by using the CLI command but first, navigate to your project directory:
Then install dependencies and run from the project directory:
```shell
cd my_project
crewai install (Optional)
```
To run your crew, execute the following command in the root of your project:
```bash
crewai install
crewai run
```
or
If you need additional packages, use `uv add <package-name>`.
```bash
python src/my_project/main.py
```
You should see the output in the console, and `output/report.md` should be created in the project root.
If an error happens due to the usage of poetry, please run the following command to update your crewai package:
In addition to the sequential process, you can use the hierarchical process, which automatically assigns a manager to the defined crew to properly coordinate the planning and execution of tasks through delegation and validation of results. [See more about the processes here](https://docs.crewai.com/en/concepts/processes).
```bash
crewai update
```
You should see the output in the console and the `report.md` file should be created in the root of your project with the full final report.
In addition to the sequential process, you can use the hierarchical process, which automatically assigns a manager to the defined crew to properly coordinate the planning and execution of tasks through delegation and validation of results. [See more about the processes here](https://docs.crewai.com/core-concepts/Processes/).
For a Flow-first walkthrough, see the [Quickstart](https://docs.crewai.com/en/quickstart).
## Key Features
@@ -451,7 +408,7 @@ Choose CrewAI to build powerful, adaptable, and production-ready AI automations.
You can test different real life examples of AI crews in the [CrewAI-examples repo](https://github.com/crewAIInc/crewAI-examples?tab=readme-ov-file):
- [Landing Page Generator](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/landing_page_generator)
- [Having Human input on the execution](https://docs.crewai.com/how-to/Human-Input-on-Execution)
- [Having Human input on the execution](https://docs.crewai.com/en/learn/human-input-on-execution)
- [Trip Planner](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/trip_planner)
- [Stock Analysis](https://github.com/crewAIInc/crewAI-examples/tree/main/crews/stock_analysis)
@@ -483,7 +440,7 @@ CrewAI's power truly shines when combining Crews with Flows to create sophistica
CrewAI flows support logical operators like `or_` and `and_` to combine multiple conditions. This can be used with `@start`, `@listen`, or `@router` decorators to create complex triggering conditions.
- `or_`: Triggers when any of the specified conditions are met.
- `and_`Triggers when all of the specified conditions are met.
- `and_`: Triggers when all of the specified conditions are met.
Here's how you can orchestrate multiple Crews within a Flow:
@@ -580,7 +537,7 @@ This example demonstrates how to:
CrewAI supports using various LLMs through a variety of connection options. By default your agents will use the OpenAI API when querying the model. However, there are several other ways to allow your agents to connect to models. For example, you can configure your agents to use a local model via the Ollama tool.
Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/how-to/LLM-Connections/) page for details on configuring your agents' connections to models.
Please refer to the [Connect CrewAI to LLMs](https://docs.crewai.com/en/learn/llm-connections) page for details on configuring your agents' connections to models.
## When to Use CrewAI
@@ -596,13 +553,26 @@ CrewAI is especially useful when you want to:
## Contribution
CrewAI is open-source and we welcome contributions. If you're looking to contribute, please:
CrewAI is open-source and we welcome contributions. See
[`.github/CONTRIBUTING.md`](.github/CONTRIBUTING.md) for the full setup guide,
branching conventions, and PR checklist.
- Fork the repository.
- Create a new branch for your feature.
- Add your feature or improvement.
- Send a pull request.
- We appreciate your input!
Quick start:
```bash
git clone https://github.com/crewAIInc/crewAI.git
cd crewAI
uv sync --all-groups --all-extras
uv run pre-commit install
```
```bash
# Tests
uv run pytest lib/crewai/tests/ -x -q
# Type checks
uv run mypy lib/
```
### Contributing to the docs
@@ -614,51 +584,8 @@ immediately and are frozen into a new versioned snapshot under
`docs/v<X.Y.Z>/` at the next release cut. Frozen snapshots are immutable — CI
rejects PRs that modify them without a `[docs-freeze]` title prefix. The
release CLI (`devtools release`) handles the freeze automatically; see
[`AGENTS.md`](AGENTS.md) for the full contributor guide and
[`RELEASING.md`](RELEASING.md) for the release-cut runbook.
### Installing Dependencies
```bash
uv lock
uv sync
```
### Virtual Env
```bash
uv venv
```
### Pre-commit hooks
```bash
pre-commit install
```
### Running Tests
```bash
uv run pytest .
```
### Running static type checks
```bash
uvx mypy src
```
### Packaging
```bash
uv build
```
### Installing Locally
```bash
uv pip install dist/*.tar.gz
```
[`.github/CONTRIBUTING.md`](.github/CONTRIBUTING.md) for contributor guidance and
[`lib/devtools/README.md`](lib/devtools/README.md) for release tooling.
## Telemetry
@@ -729,17 +656,13 @@ A: CrewAI is a lean, fast Python framework built specifically for orchestrating
### Q: How do I install CrewAI?
A: Install CrewAI using pip:
A: Install the CrewAI CLI with [UV](https://docs.astral.sh/uv/):
```shell
uv pip install crewai
uv tool install crewai
```
For additional tools, use:
```shell
uv pip install 'crewai[tools]'
```
Then create a project with `crewai create crew <project_name>`, run `crewai install`, and start it with `crewai run`. See the [installation guide](https://docs.crewai.com/en/installation) for details.
### Q: Is CrewAI a standalone framework?
@@ -751,7 +674,7 @@ A: Yes. CrewAI excels at both simple and highly complex real-world scenarios, of
### Q: Can I use CrewAI with local AI models?
A: Absolutely! CrewAI supports various language models, including local ones. Tools like Ollama and LM Studio allow seamless integration. Check the [LLM Connections documentation](https://docs.crewai.com/how-to/LLM-Connections/) for more details.
A: Absolutely! CrewAI supports various language models, including local ones. Tools like Ollama and LM Studio allow seamless integration. Check the [LLM Connections documentation](https://docs.crewai.com/en/learn/llm-connections) for more details.
### Q: What makes Crews different from Flows?
@@ -771,7 +694,7 @@ A: Check out practical examples in the [CrewAI-examples repository](https://gith
### Q: How can I contribute to CrewAI?
A: Contributions are warmly welcomed! Fork the repository, create your branch, implement your changes, and submit a pull request. See the Contribution section of the README for detailed guidelines.
A: Contributions are warmly welcomed! Fork the repository, create your branch, implement your changes, and submit a pull request. See [`.github/CONTRIBUTING.md`](.github/CONTRIBUTING.md) for detailed guidelines.
### Q: What additional features does CrewAI AMP offer?

View File

@@ -202,6 +202,38 @@ def cleanup_event_handlers() -> Generator[None, Any, None]:
pass
@pytest.fixture(autouse=True, scope="function")
def reset_tracing_state() -> Generator[None, Any, None]:
"""Drop the tracing singleton and its context after each test.
`TraceCollectionListener` is a singleton, so without this three things leak
for the rest of the xdist worker:
- `TraceBatchManager.trace_batch_id`, which moves later trace POSTs from
`/tracing/ephemeral/batches` to `/tracing/batches/<id>/events` until some
unrelated cassette stops matching, naming neither the leak nor its source.
- `_listeners_setup`, which makes `setup_listeners` return early
(`trace_listener.py:208`) after `cleanup_event_handlers` has wiped the bus,
so tracing silently registers nothing and collects no events.
- the `_tracing_enabled` context var, which leaves tracing on for later tests
and re-registers `on_task_failed` alongside telemetry's — breaking
`test_task_failure_instrumentation`, which requires one handler per event.
All three go together: clearing the context vars is what makes dropping the
singleton safe, because the replacement listener then sees tracing disabled
and registers nothing. Dropping the singleton alone re-registers handlers and
breaks the telemetry test.
"""
yield
from crewai.events.listeners.tracing import utils as tracing_utils
from crewai.events.listeners.tracing.trace_listener import TraceCollectionListener
tracing_utils._tracing_enabled.set(None)
tracing_utils._tui_mode.set(False)
TraceCollectionListener._instance = None
@pytest.fixture(autouse=True, scope="function")
def reset_event_state() -> None:
"""Reset event system state before each test for isolation."""

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,322 @@ description: "تحديثات المنتج والتحسينات وإصلاحات
icon: "clock"
mode: "wide"
---
<Update label="9 سبتمبر 2026">
## v1.15.21
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.21)
## ما الذي تغير
### الميزات
- إضافة بيانات تتبع لتتبع وقت تشغيل نقاط التحقق واستخدام واجهة سطر الأوامر.
### إصلاحات الأخطاء
- إصلاح أخطاء البوابة المبلغ عنها داخل استجابة HTTP 200.
- الحفاظ على دفع النشر عند إنشاء مصدر AMP.
- الإبلاغ عن فشل السحب بدلاً من رفع IndexError في تكامل Oxylabs.
- توجيه جميع نماذج DashScope عبر المزود الأصلي.
- الاحتفاظ بنقاط تحقق JSON كـ UTF-8.
- إزالة $ الزائدة في عناوين URL الخاصة بالبحث في f-string لـ BrightData.
- دعم مصفوفات نوع القائمة في تحويل مخطط JSON.
- تصحيح نافذة السياق لـ gpt-4o-mini من 200000 إلى 128000.
- الحفاظ على وسائط استدعاء أداة البث عند contentBlockStop.
- جعل خطافات ما قبل الالتزام قابلة للنقل على Windows.
### الوثائق
- توضيح أن تتبع البيانات يتم إدارته بشكل منفصل عن بيانات التتبع.
- إصلاح رابط مرجع البحث المتوازي.
- إزالة المعلمات القديمة من سلسلة توثيق handle_llm_stream_chunk.
- إصلاح أمثلة سلسلة توثيق مخرجات البث.
- استخدام UUIDs الخاصة بالمنظمة في مرجع تثبيت المهارة.
## المساهمون
@Alphaxiaoteng, @DrewWhittleNZ, @Ghraven, @Shxiao101, @Vaishnavi220506, @Vidit-Ostwal, @danielfsbarreto, @georgeatparallel, @github-actions[bot], @jessemiller, @joaomdmoura, @kimnamu, @kiwoongyoon, @liang0417, @lorenzejay, @oxy-giedrius, @simpleqt, @uoparaji
</Update>
<Update label="4 سبتمبر 2026">
## v1.15.20
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.20)
## ما الذي تغير
### إصلاحات الأخطاء
- إصلاح اكتشاف اسم مستعار لأداة المنصة القديمة
### الوثائق
- تحديث اللقطة وسجل التغييرات للإصدار v1.15.19
## المساهمون
@joaomdmoura, @vinibrsl
</Update>
<Update label="4 سبتمبر 2026">
## v1.15.19
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.19)
## ما الذي تغير
### الميزات
- إضافة عميل تكامل Clipper
- إضافة `now()` إلى بيئة تعبير CEL
- تسجيل كيفية انتهاء تشغيل الطاقم لكل مستخدم
- الإبلاغ عن حجم الآلة كحزام خشن، وليس عدد النوى
- إضافة عميل قابل للحقن لأدوات منصة CrewAI
### إصلاحات الأخطاء
- إصلاح قراءة عناوين octet-stream و xlsx في `urlreadtool`
- إصلاح إضافة دوران المستخدم المتأخر في موفر Gemini الأصلي
- تطبيع المخطط والمنفذ في عنوان URL الأساسي لـ Ollama
- الحفاظ على تكوينات النطاق القابلة لإعادة الاستخدام في الذاكرة
- تحديث `pypdf` إلى 6.16.2 لمعالجة ثغرة أمنية
- تحديث `nltk` إلى 3.10.3 لمعالجة ثغرة أمنية
- إصلاح المخرجات الهيكلية الأصلية لنماذج Claude الحالية وسقف CVE لـ Snowflake
- تشغيل روابط استدعاء النموذج على كل مسار ونشر رفض
### الوثائق
- إزالة `CodeInterpreterTool` من أمثلة نظرة عامة على الذكاء الاصطناعي/التعلم الآلي
- توجيه رابط `prompt-template` إلى مساره الحالي
- تحديث دليل القنوات إلى واجهة برمجة التطبيقات الحالية لقنوات CopilotKit
- تحديث معرفات نماذج Gemini المتقاعدة
## المساهمون
@Vidit-Ostwal, @a-yeyang, @github-actions[bot], @hvlcrs, @joaomdmoura, @kikifrost, @lorenzejay, @lucasgomide, @parthiban-sivakumar, @ranst91, @tandede, @thiagomoretto, @vinibrsl
</Update>
<Update label="27 أغسطس 2026">
## v1.15.18
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.18)
## ما الذي تغير
### الميزات
- ترقية تدفقات المحادثة إلى حالة مستقرة
- تسجيل نشر تم إنشاؤه مع UUID المعطى
- تحسين وثائق تدفقات المحادثة وواجهات برمجة التطبيقات
- السماح لإعلان بتسمية تنسيق استجابة الموجه
- السماح لتدفق الدردشة بإعلان شكل حالته الخاصة
- قبول إعدادات LLM على نمط الطاقم في إعلان المحادثة
- الإبلاغ عن إنشاء المشروع مع المعرف المُصنّع
- تسجيل ما إذا كانت العملية تحتوي على مدخلات، دون تسجيل المدخلات
- ملء معرف المشروع من كل أمر مشروع يتم استدعاؤه بواسطة المستخدم
### إصلاحات الأخطاء
- الحفاظ على نتائج الأداة عندما تكون الإجابة النهائية فارغة
- ربط Claude Sonnet 4.6 الافتراضي بنافذة السياق 1M الخاصة به
- رفع الحد الأقصى الافتراضي لـ max_tokens من Anthropic لاستدعاءات الأدوات الكبيرة
- عرض أجزاء محتوى الرسالة كنص، وليس كتمثيل بايثون
- الاحتفاظ بأدوار الرسائل عندما يحصل Agent.kickoff على محادثة
- تخطي روابط الاعتراض على تدفقات crewai-internal
- تسجيل فشل المهام كفشلات، وليس نجاحات
- إصدار دورة حياة التدفق عند استئناف مكتوم
- فتح واجهة المستخدم النصية للمحادثة لتدفق دردشة إعلاني
- تسجيل crew_memory كسلسلة نصية، وليس كقيمة منطقية
- إصدار project_id دائمًا حتى تظل القيم الغائبة والفارغة متميزة
### الوثائق
- توضيح وثائق المراقبة لـ Arize Phoenix
## المساهمون
@Vidit-Ostwal, @arizedatngo, @joaomdmoura, @lorenzejay, @lucasgomide
</Update>
<Update label="19 أغسطس 2026">
## v1.15.17
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.17)
## ما الذي تغيّر
### الميزات
- إضافة وثائق تدفقات المحادثة التصريحية
- توليف طرق المحادثة المدمجة للتصريحات
- تمكين التصريحات من قيادة وضع المحادثة
- جعل خيار الانضمام إلى المحادثة لا لبس فيه
- حمل شريحة AMP على الأدوات المستخرجة من مرجع الشريحة
- التعامل مع الرسائل الفردية الكبيرة أثناء تقسيمها
### إصلاحات الأخطاء
- إصلاح استخدام اسم المضيف URL كاسم خادم MCP HTTP و SSE
- إغلاق نطاق الوكيل في كل محاولة فاشلة
- نسب أخطاء الأدوات إلى الأداة التي فشلت
- تثبيت فحوصات SSRF على كل خطوة إعادة توجيه وعنوان IP النظير
- حل المشكلات المتعلقة بالاستدعاءات الأصلية للأدوات المعطلة عبر واجهة برمجة تطبيقات استجابات OpenAI
### الوثائق
- تحديث الوثائق مع لقطة وتغيير السجل للإصدار v1.15.16
## المساهمون
@Copilot, @Vidit-Ostwal, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="13 أغسطس 2026">
## v1.15.16
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.16)
## ما الذي تغير
### الميزات
- تقديم إدارة سياق التنفيذ مع دعم UUID
- تسجيل نوع الاستثناء الذي أنهى تدفق العمل
- تسجيل متى تم مشاركة دفعة تتبع مع AMP
- عد عمليات النشر من أي مصدر وتسجيل مكان بدايتها
### إصلاحات الأخطاء
- تسجيل الإصدار الجاري على كل نطاق تم إصداره
- إصلاح التحقق من صحة اسم جدول البحث في MySQL
- منع فشل دورة من تحديد الدورة التالية على أنها فاشلة
### الوثائق
- إضافة أدلة الواجهة الأمامية لـ CopilotKit و AG-UI
## المساهمون
@joaomdmoura, @lorenzejay, @ranst91, @theCyberTech
</Update>
<Update label="11 أغسطس 2026">
## v1.15.15
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.15)
## ما الذي تغيّر
### الميزات
- الإبلاغ عن نتيجة التدفق، والمدة، وإشارات الإنسان في الحلقة.
### إصلاحات الأخطاء
- إصدار FlowStartedEvent عندما يقوم خطاف الحدود بإلغاء التدفق.
- تحديد نطاق تصدير النطاق لمزود المتعقب الخاص بنا.
- ترقية torch إلى الإصدار 2.13.0 لمعالجة ثغرة أمنية.
- ترقية gitpython إلى الإصدار 3.1.58 في crewai-tools[github].
### إعادة الهيكلة
- تحديث وظيفة حقن التاريخ في الوكلاء.
- توحيد علامات CLI إلى صيغة kebab-case.
### الوثائق
- لقطة وتغيير السجل للإصدار v1.15.14.
## المساهمون
@Vidit-Ostwal, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="8 أغسطس 2026">
## v1.15.14
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.14)
## ما الذي تغير
### الميزات
- فصل سياق وقت التشغيل عن وكيل الترميز وإضافة معرف المشروع
### الوثائق
- تحديث اللقطة وسجل التغييرات للإصدار v1.15.13
## المساهمون
@joaomdmoura
</Update>
<Update label="7 أغسطس 2026">
## v1.15.13
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.13)
## ما الذي تغير
### إصلاحات الأخطاء
- إصلاح الحفاظ على مزود النماذج الموجهة بواسطة LiteLLM.
- تعزيز نماذج حدث LLM الهشة.
- إصلاح التقارير الناقصة لاستخدام رموز التخزين المؤقت من Anthropic.
- ترقية h2 إلى الإصدار 4.4.1 لمعالجة ثغرة الأمان GHSA-6hr6-w5qg-qmwg.
### الوثائق
- إضافة سير العمل DOCS_TRANSLATIONS لمزامنة المواقع.
- إصلاح الروابط المعطلة في README، وفهرس المحتويات، وإرشادات المساهمة.
- لقطة وتغيير سجل الإصدار 1.15.12.
## المساهمون
@Vidit-Ostwal, @joaomdmoura, @lucasgomide, @theCyberTech
</Update>
<Update label="5 أغسطس 2026">
## v1.15.12
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.12)
## ما الذي تغير
### الميزات
- زيادة إصدار Flow canary عند الإصدار
- إضافة URLReadTool لقراءة عناوين URL العشوائية
- إضافة بيانات التعريف الخاصة بالتطبيق إلى أدوات إجراءات المنصة
- توحيد الهيكل تحت `crewai create <resource>`
### إصلاحات الأخطاء
- توضيح أخطاء تصادم أسماء المسارات/المعالجين في المحادثات
### الوثائق
- تحديث ملف AGENTS.md للهيكل الموحد لأداة سطر الأوامر لإنشاء
### تغييرات كبيرة
- لا شيء
## المساهمون
@Vidit-Ostwal, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="4 أغسطس 2026">
## v1.15.11
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.11)
## ما الذي تغير
### الميزات
- تتبع عمليات إرسال خطاف الاعتراض في التلميتري
- إضافة project_id لربط استخدام OSS بحساب المؤسسة
- عرض AMP في AGENTS.md واكتشاف وكلاء الترميز في التلميتري
- إضافة أداة بحث IBM Db2
### إصلاحات الأخطاء
- مسح تنبيهات تطهير جزء URL غير المكتمل في CodeQL
- تحديث aiohttp وcryptography لمسح ستة تحذيرات GHSA
- الإبلاغ عن خطأ CEL الحقيقي للفشل داخل الأدبيات الخرائطية
- تخطي CI الكود بشكل صحيح لطلبات السحب الخاصة بالوثائق فقط
### الوثائق
- لقطة وتغيير السجل للإصدار v1.15.10
## المساهمون
@PawanThakurIBM, @Vidit-Ostwal, @gabemilani, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="31 يوليو 2026">
## v1.15.10

View File

@@ -60,7 +60,7 @@ mode: "wide"
| **احترام نافذة السياق** _(اختياري)_ | `respect_context_window` | `bool` | إبقاء الرسائل تحت حجم نافذة السياق عبر التلخيص. الافتراضي True. |
| **وضع تنفيذ الكود** _(اختياري)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | وضع تنفيذ الكود: 'safe' (باستخدام Docker) أو 'unsafe' (مباشر). الافتراضي 'safe'. |
| **متعدد الوسائط** _(اختياري)_ | `multimodal` | `bool` | ما إذا كان الوكيل يدعم القدرات متعددة الوسائط. الافتراضي False. |
| **حقن التاريخ** _(اختياري)_ | `inject_date` | `bool` | ما إذا كان يتم حقن التاريخ الحالي تلقائيًا في المهام. الافتراضي False. |
| **حقن التاريخ** _(اختياري)_ | `inject_date` | `bool` | ما إذا كان يتم حقن التاريخ الحالي تلقائيًا في أمر الوكيل. الافتراضي False. |
| **تنسيق التاريخ** _(اختياري)_ | `date_format` | `str` | سلسلة تنسيق التاريخ عند تفعيل inject_date. الافتراضي "%Y-%m-%d" (تنسيق ISO). |
| **الاستدلال** _(اختياري)_ | `reasoning` | `bool` | ما إذا كان يجب على الوكيل التأمل وإنشاء خطة قبل تنفيذ المهمة. الافتراضي False. |
| **الحد الأقصى لمحاولات الاستدلال** _(اختياري)_ | `max_reasoning_attempts` | `Optional[int]` | الحد الأقصى لمحاولات الاستدلال قبل تنفيذ المهمة. إذا None، سيحاول حتى الاستعداد. |
@@ -287,7 +287,7 @@ analysis_agent = Agent(
- `multimodal`: تفعيل القدرات متعددة الوسائط لمعالجة النص والمحتوى المرئي
- `reasoning`: تمكين الوكيل من التأمل وإنشاء خطط قبل تنفيذ المهام
- `inject_date`: حقن التاريخ الحالي تلقائيًا في أوصاف المهام
- `inject_date`: حقن التاريخ الحالي تلقائيًا في أمر الوكيل
#### القوالب

View File

@@ -54,6 +54,16 @@ crewai create flow my_new_flow
افتراضيًا، ينشئ `crewai create crew` مشروعًا JSON-first يحتوي على `crew.jsonc` و `agents/*.jsonc`. استخدم `crewai create crew my_new_crew --classic` فقط إذا أردت البنية القديمة Python/YAML مع `crew.py` و `config/agents.yaml` و `config/tasks.yaml`.
#### أسماء مستعار قديمة للأعلام (مهملة)
لا تزال أعلام snake_case القديمة تعمل، لكنها مخفية من `--help`. يُفضّل استخدام صيغ kebab-case الموثّقة في أقسام الأوامر أدناه.
| مهمل | استخدم بدلاً منه |
| :--- | :--- |
| `--skip_provider` (في `crewai create crew`) | `--skip-provider` |
| `--n_iterations` (في `crewai train`، `crewai test`) | `--n-iterations` |
| `--task_id` (في `crewai replay`) | `--task-id` |
### 2. الإصدار
عرض الإصدار المثبت من CrewAI.
@@ -72,7 +82,7 @@ crewai version [OPTIONS]
crewai train [OPTIONS]
```
- `-n, --n_iterations INTEGER`: عدد تكرارات التدريب (افتراضي: 5)
- `-n, --n-iterations INTEGER`: عدد تكرارات التدريب (افتراضي: 5)
- `-f, --filename TEXT`: مسار ملف مخصص للتدريب (افتراضي: "trained_agents_data.pkl")
### 4. الإعادة
@@ -83,7 +93,7 @@ crewai train [OPTIONS]
crewai replay [OPTIONS]
```
- `-t, --task_id TEXT`: إعادة تنفيذ الطاقم من معرّف المهمة هذا، بما في ذلك جميع المهام اللاحقة
- `-t, --task-id TEXT`: إعادة تنفيذ الطاقم من معرّف المهمة هذا، بما في ذلك جميع المهام اللاحقة
### 5. سجل مخرجات المهام
@@ -117,7 +127,7 @@ crewai reset-memories [OPTIONS]
crewai test [OPTIONS]
```
- `-n, --n_iterations INTEGER`: عدد تكرارات الاختبار (افتراضي: 3)
- `-n, --n-iterations INTEGER`: عدد تكرارات الاختبار (افتراضي: 3)
- `-m, --model TEXT`: نموذج LLM لتشغيل الاختبارات (افتراضي: "gpt-4o-mini")
### 8. التشغيل
@@ -191,6 +201,7 @@ def crew(self) -> Crew:
```shell Terminal
crewai deploy push
```
يحافظ الدفع على المصدر المستخدم عند الإنشاء. إضافة `origin` لاحقًا لا تحوّل نشر ZIP إلى git.
- **حالة النشر**:
```shell Terminal
@@ -276,6 +287,7 @@ crewai traces [COMMAND]
```shell Terminal
crewai traces enable
```
- يحدّث موجه التشغيل الأول (`Would you like to view your execution traces?`) هذا التفضيل أيضاً
<Note>
**لتفعيل التتبع**، استخدم أيًا من هذه الطرق:

View File

@@ -172,6 +172,8 @@ class YourCrewName:
بعد تنفيذ الطاقم، يمكنك الوصول إلى خاصية `usage_metrics` لعرض مقاييس استخدام نموذج اللغة (LLM) لجميع المهام المنفذة.
`total_tokens` هو الإجمالي المفوتر (`prompt_tokens + completion_tokens`). حقول التفصيل مثل `cached_prompt_tokens` و`cache_creation_tokens` تصف أجزاءً مُدرجة بالفعل ضمن تلك الإجماليات ولا تُضاف مرة أخرى إلى `total_tokens`. راجع قسم **UsageMetrics field semantics** في توثيق مفهوم Flows للحصول على العقد الكامل.
```python Code
crew = Crew(agents=[agent1, agent2], tasks=[task1, task2])
crew.kickoff()

View File

@@ -266,6 +266,24 @@ print(flow.usage_metrics)
كلما احتجت إلى الإجمالي **الكامل** للتوكنات لتنفيذ التدفق.
</Note>
### دلالات حقول UsageMetrics
يستخدم كائن [`UsageMetrics`](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/types/usage_metrics.py) المُعاد عقدًا محايدًا للمزود:
| الحقل | المعنى |
| --- | --- |
| `total_tokens` | الإجمالي المفوتر: `prompt_tokens + completion_tokens` |
| `prompt_tokens` | إجمالي رموز الإدخال/المطالبة المفوترة للطلب |
| `completion_tokens` | رموز الإخراج/الإكمال المفوترة للطلب |
| `cached_prompt_tokens` | جزء قراءة الذاكرة المؤقتة من رموز المطالبة (تفصيل فقط) |
| `cache_creation_tokens` | جزء كتابة الذاكرة المؤقتة من رموز المطالبة (تفصيل فقط، Anthropic) |
| `reasoning_tokens` | جزء التفكير/الاستدلال حيث يبلّغ المزود عنه بشكل منفصل (تفصيل فقط) |
| `successful_requests` | عدد استدعاءات LLM المُجمّعة |
حقول التفصيل مثل `cached_prompt_tokens` و`cache_creation_tokens` و`reasoning_tokens` **لا تُضاف** فوق `total_tokens` — بل تصف أجزاءً مُدرجة بالفعل ضمن `prompt_tokens` أو `completion_tokens`.
بالنسبة إلى Anthropic، تُدمج عدادات قراءة وكتابة الذاكرة المؤقتة ضمن `prompt_tokens`، لذا تنعكس أعباء العمل المخزنة مؤقتًا بالكامل في `total_tokens`. يُدرج مزودو OpenAI الرموز المخزنة مؤقتًا بالفعل داخل `prompt_tokens`؛ يعرض CrewAI الجزء المخزن مؤقتًا بشكل منفصل للوضوح.
كل حقل في [`UsageMetrics`](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/types/usage_metrics.py) المُعاد هو مجموع جميع استدعاءات نموذج اللغة التي حدثت خلال استدعاء واحد لـ `flow.kickoff()`. تتم إعادة تعيين العدادات عند الاستدعاء التالي لـ `kickoff()` (وفي كل تكرار من `kickoff_for_each`)، لذلك لن تتكرر العدّات عبر التشغيلات المتتالية. يمكن قراءة هذه الخاصية بأمان في أي وقت بعد اكتمال `kickoff()`؛ قراءتها أثناء التنفيذ تُرجع المجموع الجزئي المتراكم حتى تلك اللحظة.
## إدارة حالة التدفق

View File

@@ -636,6 +636,21 @@ agent = Agent(
}
}
)
# Option 4: Use OpenRouter embeddings (supports models across providers)
# Set OPENROUTER_API_KEY environment variable if api_key is omitted in config
crew = Crew(
agents=[agent],
tasks=[...],
knowledge_sources=[knowledge_source],
embedder={
"provider": "openrouter",
"config": {
"model_name": "openai/text-embedding-3-small",
"api_key": "your-openrouter-api-key" # Optional if OPENROUTER_API_KEY is set
}
}
)
```
#### إعداد تضمينات Azure OpenAI

View File

@@ -392,6 +392,22 @@ mode: "wide"
- تتبع استخدام الرموز
- محادثات استخدام أدوات متعددة الأدوار
**استخدام الرموز والتخزين المؤقت للمطالبة:**
يُبلّغ Anthropic عن الإدخال المفوتر في عدادات منفصلة — `input_tokens` (غير المخزن مؤقتًا)، و`cache_read_input_tokens`، و`cache_creation_input_tokens`. يدمج CrewAI الثلاثة ضمن `prompt_tokens` (و`input_tokens` الأصلي في استجابات المزود) بحيث يعكس `total_tokens` الاستخدام المفوتر الكامل على أعباء العمل المخزنة مؤقتًا.
يسجّل `cached_prompt_tokens` جزء قراءة الذاكرة المؤقتة كتفصيل فقط؛ وهو مُدرج بالفعل ضمن `prompt_tokens` ولا يجب إضافته مرة أخرى إلى `total_tokens`. يسجّل `cache_creation_tokens` عمليات الكتابة في الذاكرة المؤقتة بنفس الطريقة.
```python Code
usage = llm.get_token_usage_summary()
# total_tokens == prompt_tokens + completion_tokens
# prompt_tokens includes cache read + cache write for Anthropic
```
راجع قسم **UsageMetrics field semantics** في توثيق مفهوم Flows
للحصول على العقد المحايد للمزود المستخدم في `crew.usage_metrics`
و`flow.usage_metrics`.
**ملاحظات مهمة:**
- `max_tokens` معامل **مطلوب** لجميع نماذج Anthropic
- يستخدم Claude `stop_sequences` بدلاً من `stop`
@@ -1323,6 +1339,38 @@ llm = LLM(
llm = LLM(model="gpt-4")
```
</Tab>
<Tab title="أخطاء البوابة">
<Tip>
تُعيد البوابات مثل OpenRouter الرمز `200 OK` بمجرد قبول المزود الأساسي للطلب، لذلك يصل انتهاء مهلة المزود داخل جسم الاستجابة بدلًا من رمز الحالة.
</Tip>
تُطلق CrewAI الاستثناء نفسه الذي كان رمز الحالة الأصلي سيُنتجه، ومن ثم يلتقط منطق إعادة المحاولة الموجود لديك هذا الفشل المُقنَّع:
```python
import openai
from pydantic import BaseModel
from crewai import LLM
class Report(BaseModel):
summary: str
llm = LLM(model="openrouter/z-ai/glm-5.3", response_format=Report)
try:
result = llm.call("Summarize the incident", response_model=Report)
except openai.InternalServerError as e:
# "z-ai/glm-5.3 via openrouter.ai returned HTTP 200 with an upstream error
# and no choices: The operation was aborted (upstream code 504)"
print(f"Upstream provider failed, safe to retry: {e}")
```
<Warning>
إن استخدام `response_model` كبير أو متداخل بعمق يزيد احتمال انتهاء مهلة المزود. تعامل مع هذه الحالات كأعطال مؤقتة في المزود، وليس كإنتاج النموذج مخرجات منظمة تالفة.
</Warning>
</Tab>
<Tab title="طول السياق">
<Tip>
استخدم نماذج سياق أكبر للمهام الواسعة

View File

@@ -736,7 +736,7 @@ memory = Memory(llm="anthropic/claude-3-haiku-20240307")
memory = Memory(llm="ollama/llama3.2")
# Use Google Gemini
memory = Memory(llm="gemini/gemini-2.0-flash")
memory = Memory(llm="gemini/gemini-3.7-flash")
# Pass a pre-configured LLM instance with custom settings
llm = LLM(model="gpt-4o", temperature=0)

View File

@@ -202,13 +202,17 @@ crewai skill publish
### التثبيت
ثبّت مهارة منشورة عبر مرجعها `@org/name`:
ثبّت مهارة منشورة عبر مرجعها `@org-uuid/name`:
```shell Terminal
crewai skill install @acme/code-review
crewai skill install @your-org-uuid/code-review
```
داخل مشروع الطاقم تُثبَّت المهارة في `./skills/{name}/`؛ وخارج المشروع تذهب إلى ذاكرة التخزين المؤقتة المشتركة في `~/.crewai/skills/{org}/{name}/`.
<Note>
استخدم **UUID** الخاص بمؤسستك وليس اسمها — فأسماء المؤسسات ليست فريدة، وقد يشير الاسم إلى مؤسسة خاطئة فيفشل التثبيت برسالة "غير موجود". شغّل `crewai org list` لعرض الـ UUID (عمود `ID`) لكل مؤسسة تنتمي إليها.
</Note>
داخل مشروع الطاقم تُثبَّت المهارة في `./skills/{name}/`؛ وخارج المشروع تذهب إلى ذاكرة التخزين المؤقتة المشتركة في `~/.crewai/skills/{org-uuid}/{name}/`.
يمكن للوكلاء أيضًا الإشارة إلى مهارات السجل مباشرة — يتم حلّها من ذاكرة التخزين المؤقتة المحلية (أو من مجلد `skills/` في المشروع) وقت التشغيل:
@@ -217,7 +221,7 @@ agent = Agent(
role="Senior Code Reviewer",
goal="Review pull requests for quality and security issues",
backstory="Staff engineer with expertise in secure coding practices.",
skills=["@acme/code-review"], # registry ref, resolved locally
skills=["@your-org-uuid/code-review"], # registry ref, resolved locally
)
```

View File

@@ -20,7 +20,7 @@ crewai test
إذا أردت تشغيل المزيد من التكرارات أو استخدام نموذج مختلف، يمكنك تحديد المعاملات هكذا:
```bash
crewai test --n_iterations 5 --model gpt-4o
crewai test --n-iterations 5 --model gpt-4o
```
أو باستخدام الصيغة المختصرة:
@@ -29,6 +29,11 @@ crewai test --n_iterations 5 --model gpt-4o
crewai test -n 5 -m gpt-4o
```
<Note>
العلم القديم `--n_iterations` لا يزال يعمل، لكنه مهمل ومخفي من `--help`.
استخدم `--n-iterations` (أو `-n`) بدلاً من ذلك.
</Note>
عند تشغيل أمر `crewai test`، سيتم تنفيذ الطاقم للعدد المحدد من التكرارات، وستُعرض مقاييس الأداء في نهاية التشغيل.
سيظهر جدول الدرجات في النهاية لعرض أداء الطاقم من حيث المقاييس التالية:

View File

@@ -26,7 +26,7 @@ mode: "wide"
- **معالجة الأخطاء** توجيه كيفية استجابة الـ Agents للإخفاقات والاستثناءات وحالات انتهاء المهلة.
- **مطالبات خاصة بالأدوات** تعريف تعليمات مفصلة لكيفية استدعاء الأدوات أو استخدامها.
اطلع على [قوالب المطالبات الأصلية في مستودع CrewAI](https://github.com/crewAIInc/crewAI/blob/main/src/crewai/translations/en.json) لمعرفة كيفية تنظيم هذه العناصر. من هناك، يمكنك تجاوزها أو تكييفها حسب الحاجة لفتح سلوكيات متقدمة.
اطلع على [قوالب المطالبات الأصلية في مستودع CrewAI](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/translations/en.json) لمعرفة كيفية تنظيم هذه العناصر. من هناك، يمكنك تجاوزها أو تكييفها حسب الحاجة لفتح سلوكيات متقدمة.
## فهم تعليمات النظام الافتراضية

View File

@@ -11,7 +11,7 @@ mode: "wide"
## إنشاء مشروع باستخدام CLI
استخدم CLI الخاص بـ CrewAI لإنشاء هيكل مشروع، وسيُضاف `AGENTS.md` تلقائيًا في الجذر.
استخدم CLI الخاص بـ CrewAI لإنشاء هيكل مشروع. يُضاف `AGENTS.md` في الجذر، ومعه ملفا `CLAUDE.md` و`GEMINI.md` اللذان يستوردانه، بحيث يقرأ Claude Code وGemini CLI نفس التوجيهات التي يقرأها كل مساعد آخر.
```bash
# Crew
@@ -32,24 +32,28 @@ crewai tool create my_tool
### Claude Code
يخزّن Claude Code ذاكرة المشروع في `CLAUDE.md`. يمكنك تهيئته بـ `/init` وتحريره باستخدام `/memory`. يدعم Claude Code أيضًا الاستيرادات داخل `CLAUDE.md`، فيمكنك إضافة سطر واحد مثل `@AGENTS.md` لسحب التعليمات المشتركة دون تكرارها.
يقرأ Claude Code ملف `CLAUDE.md` ويتجاهل `AGENTS.md`. تأتي المشاريع المُنشأة بملف `CLAUDE.md` تعليمته الوحيدة هي سطر الاستيراد `@AGENTS.md`، بحيث تُحمَّل التوجيهات المشتركة دون تكرارها. أضف الملاحظات الخاصة بـ Claude تحت هذا السطر واحتفظ بالاصطلاحات المشتركة في `AGENTS.md`.
يمكنك ببساطة استخدام:
لمشروع أُنشئ قبل أن يُضاف `CLAUDE.md` إلى الهيكل، أضف الاستيراد بنفسك:
```bash
mv AGENTS.md CLAUDE.md
printf '@AGENTS.md\n' > CLAUDE.md
```
لا تُعِد تسمية `AGENTS.md` إلى `CLAUDE.md`: يقرأ Codex وCursor ملف `AGENTS.md`، وإعادة التسمية تخفيه عنهما.
### Gemini CLI وGoogle Antigravity
يقوم Gemini CLI وAntigravity بتحميل ملف سياق المشروع (الافتراضي: `GEMINI.md`) من جذر المستودع والمجلدات الأصلية. يمكنك تهيئته لقراءة `AGENTS.md` بدلاً من ذلك (أو بالإضافة إليه) بتعيين `context.fileName` في إعدادات Gemini CLI. على سبيل المثال، عيّنه إلى `AGENTS.md` فقط، أو أدرج كلاً من `AGENTS.md` و`GEMINI.md` إذا أردت الاحتفاظ بتنسيق كل أداة.
يقوم Gemini CLI وAntigravity بتحميل ملف سياق المشروع (الافتراضي: `GEMINI.md`) من جذر المستودع والمجلدات الأصلية. تأتي المشاريع المُنشأة بملف `GEMINI.md` تعليمته الوحيدة هي سطر الاستيراد `@./AGENTS.md`، بحيث تُحمَّل التوجيهات المشتركة دون تكرارها. أضف الملاحظات الخاصة بـ Gemini تحت هذا السطر واحتفظ بالاصطلاحات المشتركة في `AGENTS.md`.
يمكنك ببساطة استخدام:
لمشروع أُنشئ قبل أن يُضاف `GEMINI.md` إلى الهيكل، أضف الاستيراد بنفسك:
```bash
mv AGENTS.md GEMINI.md
printf '@./AGENTS.md\n' > GEMINI.md
```
بدلاً من ذلك، عيّن `context.fileName` في إعدادات Gemini CLI ليشمل `AGENTS.md` فيقرأه Gemini مباشرة. لا تُعِد تسمية `AGENTS.md` إلى `GEMINI.md`: يقرأ Codex وCursor ملف `AGENTS.md`، وإعادة التسمية تخفيه عنهما.
### Cursor
يدعم Cursor ملف `AGENTS.md` كملف تعليمات مشروع. ضعه في جذر المشروع لتوفير توجيهات لمساعد البرمجة في Cursor.

View File

@@ -75,7 +75,7 @@ research_crew/
}
```
استبدل `provider/model-id` بالنموذج الذي تستخدمه، مثل `openai/gpt-4o` أو `anthropic/claude-sonnet-4-6` أو `gemini/gemini-2.0-flash-001`.
استبدل `provider/model-id` بالنموذج الذي تستخدمه، مثل `openai/gpt-4o` أو `anthropic/claude-sonnet-4-6` أو `gemini/gemini-3.7-flash`.
## الخطوة 3: تعريف المهام وإعدادات الـ Crew

View File

@@ -1,35 +1,37 @@
---
title: تدفقات المحادثة
description: أنشئ تطبيقات دردشة متعددة الجولات مع kickoff لكل جولة وسجل الرسائل وتوجيه النية والتتبع وجسور WebSocket.
description: أنشئ تطبيقات دردشة متعددة الجولات باستخدام handle_turn لكل جولة، وسجل الرسائل، وتوجيه النية، والتتبع، والبث المنظّم.
icon: comments
mode: "wide"
---
## نظرة عامة
تعامل التطبيقات المحادثية مع كل سطر من المستخدم كـ **تشغيل flow جديد** بنفس **معرّف الجلسة**. توفر CrewAI مساعدات لسجل الرسائل وتصنيف النية الاختياري وتأجيل التتبع وجسور الواجهة، إضافة إلى REPL محلي `flow.chat()` للتدفقات المحادثية.
تعامل التطبيقات المحادثية مع كل سطر من المستخدم كـ **تشغيل flow جديد** بنفس **معرّف الجلسة**. توفر CrewAI مساعدات لسجل الرسائل، وتوجيه النية الاختياري، وتأجيل التتبع، والبث المنظّم للجولات، إضافة إلى REPL محلي عبر `flow.chat()`.
| المفهوم | التنفيذ |
|---------|---------|
| معرّف الجلسة | `handle_turn(..., session_id=...)` → `kickoff(inputs={"id": ...})` → `state.id` |
| سطر المستخدم | `handle_turn(message)` يضيف الرسالة إلى `state.messages` قبل تشغيل الرسم |
| اكتمال الجولة | `FlowFinished` لهذا **التشغيل** فقط؛ تستمر المحادثة في `handle_turn` التالي |
| تتبع الجلسة | `ConversationConfig(defer_trace_finalization=True)` + `finalize_session_traces()` |
| اكتمال الجولة | `conversation_turn_completed`؛ ومع تأجيل التتبع الافتراضي ينتظر `FlowFinished` استدعاء `finalize_session_traces()` |
| تتبع الجلسة الكامل | `ConversationConfig(defer_trace_finalization=True)` + `finalize_session_traces()` |
## واجهات الجولات
استخدم **`flow.handle_turn(message, session_id=...)`** لكل رسالة مستخدم من REST أو WebSocket أو الاختبارات أو الواجهات المخصصة. استخدم **`flow.chat()`** عندما تريد حلقة دردشة محلية في الطرفية لـ `Flow` محادثي.
لا يقبل `Flow.kickoff()` الوسيطين `user_message=` أو `session_id=`. في التدفقات المحادثية، يخزن `handle_turn()` الرسالة المعلقة ويستدعي داخلياً `kickoff(inputs={"id": session_id})`.
لا يقبل `Flow.kickoff()` الوسيطين `user_message=` أو `session_id=`. في التدفقات المحادثية، يخزن `handle_turn()` الرسالة المعلقة ويستدعي داخلياً `kickoff(inputs={"id": session_id})` بعد إعادة ضبط حالة التنفيذ الخاصة بالجولة.
| API | الاستخدام |
|-----|-----------|
| `handle_turn(message, session_id=...)` | غلاف مريح لجولة واحدة في `Flow` محادثي |
| `stream_turn(message, session_id=...)` | بث جولة محادثية واحدة كإطارات runtime مرتبة |
| `chat()` | REPL محلي في الطرفية لـ `Flow` محادثي |
| `kickoff(inputs={...})` | تشغيل متقدم للـ flow بدون معالجة جولة محادثية |
| `ask()` | مطالبة حاجزة **داخل** خطوة واحدة |
| `ask()` | مطالبة حاجزة **داخل** خطوة واحدة (معالج إرشادي أو طلب توضيح) |
| `@human_feedback` | الموافقة/الرفض على **مخرجات خطوة** — وليس السطر التالي |
| `ChatSession.handle_turn(...)` | طبقة نقل فوق `handle_turn` |
ترفع `handle_turn()` و`stream_turn()` و`chat()` الخطأ `ValueError` ما لم يكن الوضع المحادثاتي مفعّلاً. يؤدي تطبيق `@ConversationConfig(...)` إلى تفعيله تلقائياً؛ وإلا فعيّن `conversational = True`.
## بداية سريعة
@@ -38,7 +40,7 @@ from uuid import uuid4
from crewai import Flow
from crewai.flow import listen
from crewai.experimental.conversational import (
from crewai.flow import (
ConversationConfig,
ConversationState,
)
@@ -46,31 +48,29 @@ from crewai.experimental.conversational import (
@ConversationConfig(defer_trace_finalization=True)
class SupportFlow(Flow[ConversationState]):
conversational = True
def route_turn(self, context):
message = (self.state.current_user_message or "").lower()
if "طلب" in message or "order" in message:
if "order" in message:
return "order"
if "وداع" in message or "goodbye" in message:
if "bye" in message or "goodbye" in message:
return "goodbye"
return "help"
@listen("order")
def handle_order(self):
reply = "طلبك في الطريق."
reply = "Your order is on the way."
self.append_assistant_message(reply)
return reply
@listen("help")
def handle_help(self):
reply = "كيف يمكنني المساعدة؟"
reply = "How can I help?"
self.append_assistant_message(reply)
return reply
@listen("goodbye")
def handle_goodbye(self):
reply = "وداعاً!"
reply = "Goodbye!"
self.append_assistant_message(reply)
return reply
@@ -79,130 +79,141 @@ session_id = str(uuid4())
flow = SupportFlow()
try:
flow.handle_turn("أين طلبي؟", session_id=session_id)
flow.handle_turn("وماذا عن الإرجاع؟", session_id=session_id)
flow.handle_turn("Where is my order?", session_id=session_id)
flow.handle_turn("What about returns?", session_id=session_id)
finally:
flow.finalize_session_traces()
flow.finalize_session_traces() # one trace link for the whole chat
```
## بث جولة
استخدم `stream_turn()` عندما تحتاج واجهة مستخدم أو بيئة تشغيل إلى أحداث منظّمة لجولة دردشة واحدة. يعيد جلسة بث تحتوي على إطارات مرتبة لتوجيه Flow، وأجزاء LLM، ونشاط الأدوات، ورسائل المحادثة.
```python
stream = flow.stream_turn("Where is my order?", session_id=session_id)
with stream:
for frame in stream.events:
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
print(frame.content, end="", flush=True)
result = stream.result
```
راجع [عقد بيئة البث](/edge/ar/learn/streaming-runtime-contract) للاطلاع على عقد الإطارات الكامل وقائمة القنوات.
## دورة حياة الجولة
كل `handle_turn` يشغّل:
يشغّل كل `handle_turn` المسار التالي:
1. **`_configure_conversational_kickoff`** — دمج `session_id` / `user_message` في `inputs` وتطبيق `ConversationalConfig`.
2. **استعادة الحالة** — عند وجود `inputs["id"]` و`@persist`.
1. **إعداد الجولة** — يخزن رسالة المستخدم المعلقة، ويحل معرّف الجلسة، ويعيد ضبط تعقّب التنفيذ الخاص بالجولة، ثم يستدعي `kickoff(inputs={"id": session_id})`.
2. **استعادة الحالة** — إذا وُجد `inputs["id"]` وكان `@persist` مهيّأً، تُحمّل أحدث لقطة.
3. **`FlowStarted`** — في أول جولة للجلسة المؤجلة فقط.
4. **`prepare_conversational_turn`** — إضافة رسالة المستخدم و`last_user_message` وتصنيف اختياري.
5. **تنفيذ الرسم** — `@start` → `@router` → معالجات `@listen`.
6. **نهاية التشغيل** — يُتخطى `flow_finished` والتتبع لكل جولة عند التأجيل؛ `Agent.kickoff()` / crews لا تغلق دفعة الأب.
4. **ترطيب الجولة المعلقة** — تُضاف رسالة المستخدم إلى `state.messages`، وتُضبط `current_user_message` / `last_user_message`، ويُجرى التصنيف اختيارياً عند ضبط `intents` / `default_intents` مع `intent_llm`.
5. **تنفيذ الرسم** — طرق `@start` التي يعرّفها المستخدم (إن وجدت) → `route_conversation` (نقطة البدء/الموجّه المدمجة) → معالج `@listen` المختار. تستدعي `route_conversation` أيضاً المساعد القابل للتجاوز `conversation_start()`.
6. **نهاية التشغيل** — يُتخطى `flow_finished` لكل جولة وإنهاء التتبع عند تفعيل التأجيل؛ كما لا تغلق استدعاءات `Agent.kickoff()` المتداخلة أو crews دفعة الأب.
استدعِ **`append_assistant_message(reply)`** في المعالجات. سطر المستخدم محفوظ عبر `handle_turn` — لا تُضفه مرة أخرى.
استدعِ **`append_assistant_message(reply)`** عندما لا تطابق الرد الظاهر قيمة الإرجاع، أو عند قصّ التاريخ. تُسجَّل أيضاً سلسلة الإرجاع العامة كمساعد وتُضمَّن في لقطة `@persist`، فتستعيدها نسخة Flow جديدة. سطر المستخدم محفوظ عبر `handle_turn` — لا تُضفه مرة أخرى.
## `ConversationalConfig` (افتراضيات على مستوى الصنف)
## نظرة عامة على الإعداد
عيّن على صنف `Flow` كـ `conversational_config: ClassVar[ConversationalConfig | None]`.
يؤدي تزيين صنف فرعي من `Flow` بـ `ConversationConfig` إلى إرفاق افتراضيات الدردشة وتفعيل الوضع المحادثاتي معاً. راجع [مرجع الحقول الكامل](#conversationconfig) أدناه. ويمكنك تجاوز التصنيف المسبق لكل جولة عبر `handle_turn(..., intents=..., intent_llm=...)`.
| الحقل | الافتراضي | الغرض |
|-------|-----------|--------|
| `default_intents` | `None` | تسميات outcome للتصنيف التلقائي قبل kickoff |
| `intent_llm` | `None` | نموذج التصنيف (مطلوب عند وجود intents) |
| `interactive_prompt` | `"You: "` | مطالبة `kickoff(interactive=True)` |
| `interactive_timeout` | `None` | مهلة لكل سطر في الوضع التفاعلي |
| `exit_commands` | `exit`, `quit` | كلمات إنهاء الوضع التفاعلي |
| `defer_trace_finalization` | `True` | إبقاء دفعة trace واحدة مفتوحة بين الجولات |
## مساعدات `ChatState` منخفضة المستوى
يمكن التجاوز لكل kickoff عبر `intents=` و`intent_llm=`.
## `ChatState` (شكل الحالة الموصى به للحفظ)
تظل `ChatState` و`ConversationalConfig` القديمة ومساعدات `crewai.flow.conversation` قابلة للاستيراد للتنسيق المتقدم أو الاختبارات أو الأغلفة المخصصة. وهي منفصلة عن واجهتي `ConversationState` / `ConversationConfig`، ولا تضيف وسيطي `user_message=` أو `session_id=` إلى `Flow.kickoff()`.
```python
from crewai.flow import ChatState
class MyChatState(ChatState):
# موروث: id, messages, last_user_message, last_intent, session_ready
# Inherited: id, messages, last_user_message, last_intent, session_ready
research_turn_count: int = 0
custom_flag: bool = False
```
| الحقل | الدور |
|-------|------|
| `id` | UUID الجلسة (مثل `session_id` / `inputs["id"]`) |
| `messages` | قائمة `{role, content}` لسجل LLM |
| `id` | UUID الجلسة (نفس `inputs["id"]`) |
| `messages` | `list` من `{role, content}` لسجل LLM |
| `last_user_message` | آخر سطر مستخدم في هذه الجولة |
| `last_intent` | تسمية المسار بعد التصنيف (إن وُجد) |
| `session_ready` | علم bootstrap لمرة واحدة |
| `session_ready` | علم bootstrap لمرة واحدة (الصلاحيات، وذاكرات التخزين المؤقت، وغيرها) |
`ConversationalInputs` هو `TypedDict` لـ `kickoff(inputs={...})`: `id`, `user_message`, `last_intent`.
`ConversationalInputs` هو `TypedDict` لمفاتيح `kickoff(inputs={...})` الاصطلاحية: `id` و`user_message` و`last_intent`.
تخزن `ConversationState` رسائل `messages` ككائنات `ConversationMessage`، وتوفر أيضاً `current_user_message` و`ended` و`events` و`agent_threads`. استخدم `conversation_messages` عند تمرير سجلها القانوني إلى LLM.
## API المحادثة على `Flow`
### معاملات `kickoff` / `kickoff_async`
### معاملات `handle_turn`
| المعامل | الغرض |
|---------|--------|
| `user_message` | نص هذه الجولة (أو `{"role": "user", "content": "..."}`) |
| `message` | نص هذه الجولة |
| `session_id` | UUID المحادثة → `inputs["id"]` / `state.id` |
| `intents` | تسميات outcome لـ `classify_intent` قبل kickoff |
| `intents` | تسميات النتائج لـ `classify_intent` قبل kickoff |
| `intent_llm` | LLM للتصنيف (مطلوب مع `intents`) |
| `interactive` | حلقة CLI عبر `ask()` (للعروض المحلية فقط) |
| `interactive_prompt` | مطالبة الوضع التفاعلي |
| `interactive_timeout` | مهلة `ask()` لكل سطر |
| `exit_commands` | كلمات إنهاء الوضع التفاعلي |
| `inputs` | حقول حالة إضافية |
| `restore_from_state_id` | استنساخ من flow محفوظ آخر |
| `**kickoff_kwargs` | تُمرر إلى `kickoff()` لخيارات مثل `input_files` و`from_checkpoint` و`restore_from_state_id` |
### معاملات `kickoff`
يقبل `Flow.kickoff()` كلاً من `inputs` و`input_files` و`from_checkpoint` و`restore_from_state_id`. مرر `inputs={"id": session_id}` عندما تحتاج إلى تنفيذ flow خام، لكن استخدم `handle_turn()` عندما يمثل الاستدعاء رسالة دردشة.
### سمات المثيل
| السمة | الغرض |
|-------|--------|
| `conversational_config` | افتراضيات `ConversationalConfig` على مستوى الصنف |
| `defer_trace_finalization` | علم المثيل؛ يُضبط تلقائياً من config عند kickoff |
| `suppress_flow_events` | يخفي لوحات console؛ **التتبع يُسجّل** |
| `stream` | بث؛ مع `ChatSession.handle_turn(..., stream=True)` |
| `conversational` | عيّنه على `True` لتفعيل الرسم المحادثاتي و`handle_turn()` |
| `defer_trace_finalization` | تجاوز اختياري على مستوى المثيل. وإلا تقرأ `_should_defer_trace_finalization()` القيمة `ConversationConfig.defer_trace_finalization`. |
| `suppress_flow_events` | يخفي لوحات flow في الطرفية ويمنع أحداث تنفيذ الطرق؛ وتظل أحداث بدء/انتهاء flow تصدر |
| `stream` | علم البث العام لـ Flow. استخدم `stream_turn()` للجولات المحادثية بدلاً من جمع هذا العلم مع `handle_turn()`. |
### طرق وخصائص
| الاسم | الوصف |
|------|--------|
| `append_assistant_message(content)` | إضافة رد مساعد مرئي للمستخدم إلى `state.messages` |
| `append_message(role, content, **extra)` | إضافة إلى `state.messages` |
| `conversation_messages` | سجل للقراءة فقط لاستدعاءات LLM |
| `classify_intent(text, outcomes, *, llm, context=None)` | تعيين outcome |
| `receive_user_message(text, *, outcomes=None, llm=None)` | إضافة رسالة مستخدم؛ `last_intent` اختياري |
| `classify_intent(text, outcomes, *, llm, context=None)` | تعيين النص إلى نتيجة واحدة (بنفس منطق الاختزال المستخدم في `@human_feedback`) |
| `receive_user_message(text, *, outcomes=None, llm=None)` | إضافة رسالة مستخدم، وضبط `last_intent` اختيارياً |
| `finalize_session_traces()` | إصدار `flow_finished` المؤجل وإنهاء دفعة trace |
| `_should_defer_trace_finalization()` | هل يُؤجل إنهاء trace لكل جولة |
| `_should_defer_trace_finalization()` | hook متقدم/داخلي يحسم ما إذا كان إنهاء trace لكل جولة مؤجلاً |
| `input_history` | سجل تدقيق مطالبات وردود `ask()` |
### مساعدات الوحدة (`crewai.flow.conversation`)
يمكن استيرادها من `crewai.flow.conversation` للاختبارات أو التنسيق المخصص. تستخدم هذه المساعدات بنية `ConversationalConfig` القديمة؛ كما تمسح `prepare_conversational_turn()` قيمة `last_intent`، بخلاف `handle_turn()` التي تحتفظ بها كسياق للموجّه.
| الدالة | الوصف |
|--------|--------|
| `normalize_kickoff_inputs(...)` | دمج kwargs المحادثة في `inputs` |
| `normalize_kickoff_inputs(inputs, user_message=..., session_id=...)` | دمج وسائط المحادثة في `inputs` |
| `get_conversation_messages(flow)` | قراءة الرسائل من الحالة أو المخزن |
| `append_message(flow, ...)` | مثل طريقة المثيل |
| `prepare_conversational_turn(flow, ...)` | تهيئة الجولة (عادةً kickoff يستدعيها) |
| `receive_user_message(flow, ...)` | مثل طريقة المثيل |
| `append_message(flow, role, content, **extra)` | مثل طريقة المثيل |
| `prepare_conversational_turn(flow, user_message=..., intents=..., intent_llm=..., config=...)` | ترطيب الجولة منخفض المستوى للأغلفة المخصصة |
| `receive_user_message(flow, text, ...)` | مثل طريقة المثيل |
| `set_state_field(flow, name, value)` | تعيين حقل dict أو Pydantic |
| `get_conversational_config(flow)` | قراءة `conversational_config` |
| `input_history_to_messages(entries)` | تحويل `input_history` لصيغة رسائل LLM |
## أنماط توجيه النية
### أ. تصنيف مسبق عبر `ConversationalConfig` (الأبسط)
### أ. تصنيف مسبق عبر `ConversationConfig` (الأبسط)
عيّن `default_intents` و`intent_llm`. كل kickoff يصنّف قبل `@router`؛ اقرأ `self.state.last_intent` في `route()`.
عيّن `default_intents` و`intent_llm`. يصنّف كل `handle_turn()` الرسالة الحالية مسبقاً. تكون الأولوية لنتيجة غير فارغة يعيدها `route_turn()` مخصص؛ وإلا تستخدم `route_conversation` النية المصنّفة للجولة الحالية.
### ب. تصنيف داخل `@router` (مطالبات أغنى)
### ب. تصنيف داخل `route_turn` (مطالبات أغنى)
عيّن `default_intents=None` ليضيف kickoff الرسالة فقط. في `route()` استدعِ `classify_intent`:
عيّن `default_intents=None` كي يضيف `handle_turn()` رسالة المستخدم فقط. داخل `route_turn()`، استدعِ `classify_intent` بمطالبة أو أوصاف مخصصة:
```python
@router(bootstrap)
def route(self):
def route_turn(self, context):
intent = self.classify_intent(
self._routing_prompt(self.state.last_user_message),
self._routing_prompt(self.state.current_user_message),
("GREETING", "ORDER", "RESEARCH", "GOODBYE"),
llm=self.conversational_config.intent_llm or "gpt-4o-mini",
llm="gpt-4o-mini",
)
self.state.last_intent = intent
return intent
@@ -212,70 +223,59 @@ def route(self):
## عندما ينتهي الـ flow ويستمر المستخدم
`FlowFinished` يعني أن **تنفيذ الرسم هذا** اكتمل. تستمر المحادثة بـ `kickoff` آخر ونفس `session_id`. `@persist` يستعيد `messages` والأعلام والسياق.
يُكمل كل `handle_turn()` تشغيل رسم واحد، وتستمر المحادثة عبر `handle_turn()` آخر يستخدم `session_id` نفسه. مع دورة حياة التتبع المؤجلة افتراضياً، يصدر ذلك التشغيل `conversation_turn_completed`، بينما يصدر `FlowFinished` مرة واحدة عندما تغلق `finalize_session_traces()` الجلسة. ويستعيد `@persist` الرسائل والأعلام والسياق.
**نمط الحفظ:** يُفضّل `@persist` على **خطوة نهائية واحدة** (مثل `finalize`) وليس على صنف `Flow` بالكامل. الحفظ على مستوى الصنف بعد كل method قد يفقد تحديثات المعالجات في نفس الجولة.
**نمط الحفظ:** يُفضّل `@persist` على **خطوة نهائية واحدة** (مثل `finalize`) وليس على صنف `Flow` بالكامل. يحفظ الاستمرار على مستوى الصنف بعد كل طريقة؛ وتستخدم `load_state` أحدث صف، وقد يكون لقطة في منتصف التشغيل (مثلاً بعد `bootstrap` مباشرة) لا تتضمن تحديثات المعالج من الجولة نفسها.
لا تستخدم `@human_feedback` لأسطر المتابعة في الدردشة إلا عند الحاجة لموافقة بشرية على مخرجات خطوة محددة.
## `Flow` المحادثاتي (تجريبي)
## `Flow` المحادثاتي
<Warning>
**ميزة تجريبية.** سطح `Flow` المحادثاتي (`conversational = True`،
`handle_turn`، `ConversationConfig`، `RouterConfig`،
`ConversationState`، الرسم البياني المدمج والمساعدات) يقع تحت
`crewai.experimental` وقد يتغير شكله قبل التخرج. ثبّت إصدار CrewAI إذا
كنت تعتمد على سلوك محدد، وراقب changelog للتحديثات الكاسرة. الملاحظات
والمشاكل مرحب بها.
</Warning>
فعّل الرسم المحادثاتي بتعيين `conversational = True` على صنف فرعي من `Flow`. عندئذٍ يُظهر `Flow` الأساسي رسم `@start` / `@router` / `converse_turn` / `end_conversation` مدمجاً، ويدير `state.messages`، ويُشغّل LLM التوجيه، ويبقي دفعة trace مفتوحة عبر الجولات. أنت تكتب **المسارات المخصصة** فقط؛ والإطار يتولى الباقي.
اشترك في رسم الدردشة المحادثاتي بتعيين `conversational = True` على صنف فرعي من `Flow` أو بتطبيق `@ConversationConfig(...)`. يوفر `Flow` الأساسي عندئذٍ `route_conversation` كنقطة البدء/الموجّه المدمجة، إضافة إلى مستمعي `converse_turn` و`end_conversation`. يظل المستمع المهمل `answer_from_history_turn` متاحاً للتوافق. يدير الإطار `state.messages`، ويمكنه تشغيل LLM للموجّه، ويبقي دفعة trace مفتوحة عبر الجولات. أنت تكتب **المسارات المخصصة**؛ والإطار يتولى الباقي.
استخدمه عندما تريد دردشة متعددة الجولات مع موجّه قائم على LLM ومعالجات لكل مسار دون توصيل دورة الحياة يدوياً. استخدم `Flow[ChatState]` (النمط الأدنى مستوى في الأعلى) عندما تحتاج تحكماً كاملاً.
### مثال سريع
```python
from crewai import LLM, Flow
from crewai import Flow
from crewai.flow import listen
from crewai.experimental.conversational import (
from crewai.flow import (
ConversationConfig,
ConversationState,
RouterConfig,
)
ROUTER_LLM = LLM(model="gpt-4o-mini")
@ConversationConfig(
system_prompt="A multi-agent assistant for ordinary chat and tool-backed tasks.",
llm=ROUTER_LLM,
router=RouterConfig(), # المسارات + الأوصاف تُكتشف تلقائياً من معالجات @listen
)
@ConversationConfig(defer_trace_finalization=True)
class SupportFlow(Flow[ConversationState]):
conversational = True
def route_turn(self, context: dict) -> str | None:
message = (self.state.current_user_message or "").lower()
if "search" in message or "news" in message:
return "INTERNET_SEARCH"
if "docs" in message or "crewai" in message:
return "CREWAI_DOCS"
return "converse"
@listen("INTERNET_SEARCH")
def handle_internet_search(self) -> str:
"""Fresh web research, current news, real-time lookups."""
...
reply = "I would run the web research route here."
self.append_assistant_message(reply)
return reply
@listen("CREWAI_DOCS")
def handle_crewai_docs(self) -> str:
"""Look up the CrewAI documentation for framework/API questions."""
...
reply = "I would look up the CrewAI docs here."
self.append_assistant_message(reply)
return reply
flow = SupportFlow()
try:
flow.handle_turn("ماذا يمكنك أن تفعل؟") # يوجَّه إلى converse (مدمج)
flow.handle_turn("ابحث في الويب عن أخبار الذكاء الاصطناعي.") # يوجَّه إلى INTERNET_SEARCH
flow.handle_turn("لخص النتيجة الأولى.") # يعود إلى converse
flow.handle_turn("What can you do?") # routes to converse
flow.handle_turn("Search the web for AI news.") # routes to INTERNET_SEARCH
flow.handle_turn("Check the CrewAI docs.") # routes to CREWAI_DOCS
finally:
flow.finalize_session_traces()
```
@@ -297,27 +297,54 @@ def kickoff() -> None:
|-------|-----------|-------|
| `system_prompt` | `slices.conversational_system_prompt` من i18n | رسالة system يستخدمها `converse_turn` المدمج. مرر `""` للتعطيل التام. |
| `llm` | `None` | LLM المحادثة (يستخدمه `converse_turn` وكاحتياطي للموجّه). |
| `router` | `None` | `RouterConfig` للتوجيه عبر LLM. بدونه، يسقط الـ flow دائماً إلى `converse`. |
| `answer_from_history_prompt` | افتراضي الإطار | رسالة system للمسار الاختياري `answer_from_history`. |
| `answer_from_history_llm` | `None` | يُفعّل الاختصار `answer_from_history` عند تعيينه. |
| `router` | `None` | تجاوزات `RouterConfig` اختيارية. مع وجود مستمعين مخصصين وLLM قابل للحل، يُفعّل التوجيه تلقائياً حتى عند إغفال هذا الحقل. |
| `answer_from_history_prompt` | افتراضي الإطار | **مهمل.** استخدم system prompt الخاص بـ `converse` أو تجاوز `converse_turn()`. |
| `answer_from_history_llm` | `None` | **مهمل.** استخدم `llm`؛ إذ يتلقى `converse` السجل القانوني بالفعل. |
| `intent_llm` | `None` | LLM لمسار التصنيف المسبق القديم `intents=`/`default_intents`. |
| `default_intents` | `None` | تسميات النتائج للتصنيف المسبق القديم. |
| `visible_agent_outputs` | `None` | `"all"` أو قائمة بأسماء الـ agents الذين تُرفع مخرجاتهم من `append_agent_result()` إلى رسائل عامة. |
| `defer_trace_finalization` | `True` | يبقي دفعة trace واحدة مفتوحة عبر استدعاءات `handle_turn()`. |
<Warning>
تم إهمال `answer_from_history_prompt` و`answer_from_history_llm` ومسار
`answer_from_history`، وستُزال في إصدار مستقبلي. فهي تكرر `converse`، الذي
يتولى بالفعل السجل القانوني، وتضيف استدعاء LLM للتحقق من أهلية الإجابة،
ويجري تجاوزها عندما يعيد الموجّه التلقائي المعتاد مساراً. تظل الإعدادات
الحالية تعمل وتُصدر `DeprecationWarning`.
</Warning>
عند عدم وجود مسارات مخصصة، تسقط الجولات إلى `converse`. ومع وجود مسارات مخصصة وLLM للمحادثة/الموجّه، ينشئ الإطار `RouterConfig` افتراضية؛ لا توفر واحدة صراحةً إلا لتخصيص المطالبة أو قائمة المسارات أو الأوصاف أو سلوك fallback. أما ضبط `default_intents` فيستخدم مسار التصنيف المسبق القديم.
إذا لم يُهيأ LLM للمحادثة، يعيد `converse_turn` المدمج عنصراً نائباً للإعداد بدلاً من توليد إجابة.
### `RouterConfig` وفهرس المسارات المُولَّد تلقائياً
```python
RouterConfig(
prompt="تأطير اختياري للنطاق (سياسة، صوت، شخصية).",
response_format=MyRoute, # اختياري؛ يُولَّد تلقائياً عند الإغفال
llm=ROUTER_LLM, # يسقط إلى ConversationConfig.llm
routes=["INTERNET_SEARCH", "CREWAI_DOCS"], # اختياري؛ يُستنتج من المستمعين
from typing import Literal
from pydantic import BaseModel
from crewai import LLM
from crewai.flow import RouterConfig
class MyRoute(BaseModel):
intent: Literal["INTERNET_SEARCH", "CREWAI_DOCS", "converse"]
ROUTER_LLM = LLM(model="gpt-4o-mini")
router_config = RouterConfig(
prompt="Optional domain framing (policy, voice, persona).",
response_format=MyRoute, # optional; auto-generated otherwise
llm=ROUTER_LLM, # falls back to ConversationConfig.llm
routes=["INTERNET_SEARCH", "CREWAI_DOCS"], # optional; inferred from listeners
route_descriptions={
"INTERNET_SEARCH": "تجاوز الـ docstring لهذا المسار فقط.",
"INTERNET_SEARCH": "Override the docstring for this one route.",
},
default_intent="converse", # يُستخدم عند فشل LLM أو غيابه
fallback_intent="converse", # يُستخدم عندما يعيد LLM مساراً غير صالح
default_intent="converse", # used when LLM call fails or no LLM available
fallback_intent="converse", # used when LLM returns an invalid route
intent_field="intent",
)
```
@@ -325,13 +352,17 @@ RouterConfig(
تُبنى رسالة الموجّه إلى LLM تلقائياً. لكل مسار يختار الإطار وصفاً بهذا الترتيب من الأولوية:
1. `RouterConfig.route_descriptions[label]` — تجاوز صريح.
2. `Flow.builtin_route_descriptions[label]` — نص جاهز من الإطار لـ `converse` و`end` و`answer_from_history` (مصاغ لـ LLM التوجيه).
3. أول سطر غير فارغ من docstring معالج `@listen(label)`.
4. فارغ (المسار يظهر في الفهرس بلا وصف).
2. `Flow.builtin_route_descriptions[label]` — نص جاهز من الإطار لـ `converse` و`end` ولمسار التوافق المهمل `answer_from_history` (مصاغ لـ LLM التوجيه).
3. قيمة `description` المعلنة للطريقة (تستخدمها التدفقات التعريفية وإسقاطات DSL).
4. أول سطر غير فارغ من docstring معالج `@listen(label)`.
5. فارغ (المسار يظهر في الفهرس بلا وصف).
عملياً، **إضافة مسار جديد = `@listen("X")` + docstring من سطر واحد**:
```python
from crewai.flow import listen
@listen("INTERNET_SEARCH")
def handle_internet_search(self) -> str:
"""Fresh web research, current news, real-time lookups."""
@@ -350,13 +381,34 @@ Routes:
`RouterConfig.prompt` مخصص لـ **تأطير النطاق** (شخصية المساعد، قواعد العمل، النبرة). فهرس المسارات يُبنى تلقائياً — لا تُدرج المسارات في `prompt`؛ سيختل التزامن لحظة إضافة معالج جديد.
### تسمية المعالجات
السلسلة النصية في `@listen("…")` هي **تسمية مسار للموجّه** (اسم حدث)، وليست اسم طريقة Python. تتشارك تسميات المسارات وأحداث اكتمال الطرق مساحة مشغلات واحدة، ولذلك تؤدي تسمية المعالج باسم مساره نفسه إلى إعادة تشغيل المعالج في حلقة.
استخدم اسماً مختلفاً للطريقة — تستخدم أمثلة التوثيق بادئة `handle_*`:
```python
@listen("create_video")
def handle_create_video(self) -> str:
"""User wants a new video."""
...
```
لا تكرر تسمية المسار في اسم الطريقة:
```python
@listen("create_video")
def create_video(self) -> str: # rejected at flow instantiation
...
```
### المسارات المدمجة
| المسار | المعالج | الغرض |
|--------|---------|-------|
| `converse` | `converse_turn` | معالج الدردشة الافتراضي. يستدعي `ConversationConfig.llm` بـ system prompt + التاريخ القانوني للرسائل. |
| `end` | `end_conversation` | يضبط `state.ended = True` ويُصدر رد إنهاء. |
| `answer_from_history` | `answer_from_history_turn` | اختياري. يُوجَّه إليه عندما يكون `ConversationConfig.answer_from_history_llm` مُعيَّناً ويمكن الإجابة على الرسالة من التاريخ فقط. |
| `answer_from_history` | `answer_from_history_turn` | **مسار توافق مهمل.** استخدم `converse`، الذي يتلقى السجل القانوني بالفعل. |
يمكنك تجاوز أي من هذه بتعريف معالج بنفس الاسم في الصنف الفرعي.
@@ -366,9 +418,9 @@ Routes:
1. يعيد ضبط تعقّب التنفيذ لكل جولة (`_completed_methods`, `_method_outputs`) ليُعاد تشغيل الرسم — بدون ذلك، استدعاءات `kickoff` المتكررة على نفس النسخة ستُحدث دائرة قصر من الجولة الثانية لأن `Flow.kickoff_async` يعتبر `inputs={"id": ...}` استعادة من نقطة تفتيش.
2. يُلحق رسالة المستخدم بـ `state.messages` ويضبط `current_user_message` / `last_user_message`. يُحافَظ على `last_intent` **من الجولة السابقة** كي يستخدمها LLM التوجيه كإشارة.
3. يُشغّل `conversation_start` → `route_conversation` → معالج `@listen` المختار.
3. يُشغّل طرق `@start` التي يعرّفها المستخدم (إن وجدت)، ثم `route_conversation` كنقطة البدء/الموجّه المدمجة، ثم معالج `@listen` المختار. وتستدعي `route_conversation` المساعد القابل للتجاوز `conversation_start()`.
4. يخزّن الموجّه قراره في `state.last_intent` (يكون مرئياً لسياق التوجيه في الجولة التالية).
5. إذا أعاد معالجك سلسلة نصية ولم يستدعِ `append_assistant_message`، فإن `handle_turn` يُلحقها نيابةً عنك.
5. إذا أعاد معالجك سلسلة نصية ولم يستدعِ `append_assistant_message`، فإن `handle_turn` يُلحقها نيابةً عنك ويحفظ `state.messages` المحدَّث حتى تشمل استعادة `@persist` جولة المساعد.
استدعِ `handle_turn()` لرسائل الدردشة. استدعاء `kickoff(inputs={"id": ...})` مباشرةً يشغل الرسم بدون غلاف الجولة المحادثية.
@@ -389,6 +441,8 @@ flow.chat()
4. يطبع نتيجة المساعد.
5. ينهي traces الجلسة المؤجلة داخل كتلة `finally`.
يُفعّل `chat(defer_trace_finalization=True)` مؤقتاً علم التأجيل على مستوى المثيل للـ REPL، ثم يعيد قيمته السابقة عند الخروج.
خصص سلوك الطرفية عبر I/O قابل للحقن:
```python
@@ -407,6 +461,12 @@ flow.chat(
لتشغيل آثار جانبية (إعداد ناقل أحداث، قياس عن بُعد) في كل قرار توجيه، تجاوز `route_turn`:
```python
from typing import Any
from crewai import Flow
from crewai.flow import ConversationState
class SupportFlow(Flow[ConversationState]):
conversational = True
@@ -415,7 +475,7 @@ class SupportFlow(Flow[ConversationState]):
return super().route_turn(context)
```
لتجاوز موجّه LLM واختيار مسار برمجياً، أعد سلسلة نصية من `route_turn`؛ إعادة `None` تسقط إلى `_route_with_config(...)`.
لتجاوز موجّه LLM بالكامل واختيار مسار برمجياً، أعد سلسلة نصية غير فارغة من `route_turn`. لا يؤدي إرجاع قيمة falsy من التجاوز إلى استدعاء `_route_with_config()`؛ بل يسقط التوجيه إلى النية المصنّفة مسبقاً لهذه الجولة، ثم إلى مسار التوافق المهمل `answer_from_history` عند إعداده، وأخيراً إلى `converse`. تكون `last_intent` من الجولة السابقة متاحة في سياق الموجّه، لكنها لا تُعاد أبداً كـ fallback.
### `append_assistant_message` و`append_agent_result`
@@ -426,9 +486,76 @@ class SupportFlow(Flow[ConversationState]):
يمكن لـ `ConversationConfig.visible_agent_outputs` رفع النتائج الخاصة لـ agents محددين إلى عامة عالمياً (`"all"` أو قائمة بالأسماء).
## تعريف تدفق محادثاتي بصيغة JSON/YAML
يمكن لـ [التدفق التعريفي](/edge/ar/concepts/cli) أن يكون محادثاتيًا أيضًا. أضف كتلة `conversational` في المستوى الأعلى وعرّف مساراتك الخاصة كطرق تستمع (`listen`) إلى تسمية مسار:
```yaml
schema: crewai.flow/v1
name: SupportFlow
conversational:
system_prompt: You are a terse support assistant.
llm: gpt-4o-mini
router:
llm: gpt-4o-mini
methods:
handle_order:
description: Order status, shipping and delivery questions.
listen: order
do:
call: agent
with:
role: Support specialist
goal: Answer order questions accurately
backstory: Knows the fulfilment pipeline.
input: "${state.current_user_message}"
```
تعريف الكتلة هو الاشتراك نفسه — القيمة الافتراضية لـ `enabled` هي `true`. اضبطها على `enabled: false` للاحتفاظ بالإعدادات مع إيقاف المحادثة. يؤدي ذلك أيضاً إلى تعطيل إنشاء الطرق المدمجة، ولذلك يجب أن توفر التعريفة رسماً عادياً غير محادثاتي.
تُوفَّر لك ثلاثة أشياء:
| المُوفَّر | التفاصيل |
|----------|--------|
| الرسم البياني المدمج | تُضاف `route_conversation` و`converse_turn` و`end_conversation` تلقائيًا. يُحتفظ بـ `answer_from_history_turn` المهملة للتوافق. عرّف طريقة بأحد هذه الأسماء لتجاوزها. |
| حالة المحادثة | تُستخدم `ConversationState` عند عدم وجود كتلة `state`. وتُركّب حالة Pydantic ذات `ref` أو `json_schema` تلقائياً مع الحقول المحادثية؛ ولا يلزم أن ترث من `ConversationState`. |
| كتالوج المسارات | يُستنتج من الطرق غير الموجّهة التي تحمل تسميات `listen`، مع استبعاد المسارات الداخلية. تتبع الأوصاف ترتيب الأولوية أعلاه، ويمكن لـ `router.routes` الصريحة تقييد الخيارات. |
تقبل حقول `llm` و`router.llm` و`intent_llm` التعريفية إما معرّف نموذج أو خريطة إعدادات مثل `{model: openai/gpt-4o-mini, max_tokens: 512}`. وتدعم كتلة `conversational` أيضاً `default_intents` و`visible_agent_outputs` و`defer_trace_finalization` وحقول `RouterConfig` الموضحة أعلاه. تظل تعريفات `answer_from_history_prompt` / `answer_from_history_llm` المهملة مقبولة للتوافق.
شغّله من Python بنفس واجهات الجولة المستخدمة مع تدفق محادثاتي معرّف بصنف:
```python
from crewai.flow import Flow
flow = Flow.from_declaration(path="flow.yaml")
try:
flow.handle_turn("Where is my order?", session_id="session-1")
finally:
flow.finalize_session_traces()
```
### تسمية المسارات
تتشارك تسميات المسارات وأسماء الطرق مساحة اسم واحدة للمشغّلات، لذا يجب ألا يحمل المعالج اسم المسار الذي يستمع إليه — يُرفض `create_video` الذي يستمع إلى `create_video` عند بناء التدفق. استخدم بادئة `handle_*`.
### ما لا يمكن للتعريفة التعبير عنه
| غير قابل للتعبير | استخدم بدلًا منه |
|-----------------|-------------|
| مثيل `LLM` حي أو `BaseLLM` مخصص | سلسلة معرّف نموذج أو خريطة إعدادات ثابتة |
| `router.response_format` كصنف نموذج حيّ | سمِّ الصنف بمرجع python: `response_format: {python: my_project.schemas.ConversationRoute}`. احذفه ويولّد الإطار واحدًا |
| تجاوز `route_turn()` | اكتب Flow بلغة Python، أو استبدل طريقة `route_conversation` التعريفية بإجراء `call: code` / expression |
| تجاوز `can_answer_from_history()` | مهمل. استخدم `converse` أو تجاوز `converse_turn()` في Python. |
يفتح `crewai run` واجهة المحادثة النصية للتدفق المحادثاتي التعريفي — نفس الواجهة التي يحصل عليها Flow محادثاتي مكتوب بلغة Python. تحتاج حلقة المحادثة إلى طرفية، ولذلك يخرج التشغيل بدون طرفية برمز غير صفري مع إرشادات بدلاً من تنفيذ جولة واحدة؛ شغّله من Python هناك عبر `handle_turn()` أو `stream_turn()`. وتعمل الطريقة التعريفية ذات كتلة `human_feedback:` (وفي Python: `@human_feedback`) على REPL طرفي، لأن runtime يجمع الملاحظات بمطالبة حاجزة لا تستطيع TUI خدمتها. لا يُقبل `--inputs` مع Flow محادثاتي — فمدخل كل جولة هو الرسالة التي تكتبها — واستئناف جلسة حسب المعرّف غير موصول بواجهة CLI بعد؛ استخدم `flow.handle_turn(message, session_id=...)` من Python لذلك.
## التتبع عبر الجولات
مع `defer_trace_finalization=True` (افتراضي في `ConversationalConfig`):
مع `defer_trace_finalization=True` (افتراضي في `ConversationConfig`):
- **دفعة trace واحدة** لجلسة الدردشة.
- **`flow_started`** في الجولة الأولى فقط؛ **`flow_finished`** مرة في `finalize_session_traces()`.
@@ -439,17 +566,30 @@ class SupportFlow(Flow[ConversationState]):
flow.chat(session_id=session_id)
```
`flow.chat()` يستدعي `finalize_session_traces()` نيابةً عنك. عندما تملك الحلقة عبر `handle_turn()` أو `kickoff(...)`، استدعِ `finalize_session_traces()` عند انتهاء الجلسة.
`flow.chat()` يستدعي `finalize_session_traces()` نيابةً عنك. عندما تملك الحلقة عبر `handle_turn()`، استدعِ `finalize_session_traces()` عند انتهاء الجلسة.
`suppress_flow_events=True` يخفي لوحات Rich فقط؛ أحداث trace والـ methods تُصدر.
يخفي `suppress_flow_events=True` لوحات Rich ويمنع أحداث تنفيذ الطرق. وتظل أحداث بدء/انتهاء Flow تصدر، فيبقى بالإمكان تتبع دورة حياة Flow الخارجية، بينما تُحذف spans الطرق الفردية.
### دورة حياة trace لـ `Flow` المحادثاتي
يستخدم [`Flow` المحادثاتي](#flow-المحادثاتي-تجريبي) التجريبي نفس دورة حياة tracing: `defer_trace_finalization` افتراضياً `True`، فيبقي كل `handle_turn()` أثر الجلسة مفتوحاً. أنهِ دوماً عند نهاية الجلسة — لُف حلقتك بـ `try/finally` واستدعِ `flow.finalize_session_traces()` عند الخروج. بدون ذلك، تبقى الدفعة مفتوحة وقد لا تُصدَّر آخر محادثة أبداً.
يستخدم [`Flow` المحادثاتي](#flow-المحادثاتي) دورة حياة التتبع نفسها: القيمة الافتراضية لـ `defer_trace_finalization` هي `True`، ولذلك يبقي كل `handle_turn()` trace الجلسة مفتوحاً. تمنع الجولات المؤجلة أيضاً إصدار `flow_failed` لكل جولة؛ وعند حدوث خطأ في جولة أو إلغاء الجلسة، أنهِ الجلسة صراحةً. يغلق ذلك الدفعة بحدث `FlowFinished` على مستوى الجلسة بدلاً من حدث `FlowFailed` لكل جولة. لُف REPL/الحلقة دائماً بـ `try/finally` واستدعِ `flow.finalize_session_traces()` عند الخروج. بدون ذلك، تبقى دفعة trace مفتوحة وقد لا تُصدَّر المحادثة النهائية أبداً.
## البث
اضبط `stream = True` على صنف `Flow`. عندئذٍ يُصدر `kickoff(...)` أحداث `assistant_delta` (وما يرتبط بها) عبر ناقل الأحداث القياسي.
استخدم `stream_turn()` للواجهات المحادثية، وكرّر عبر كائنات `StreamFrame` المرتبة التي يعيدها:
```python
stream = flow.stream_turn("Where is my order?", session_id=session_id)
with stream:
for frame in stream.events:
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
print(frame.content, end="", flush=True)
reply = stream.result
```
بالنسبة إلى Flow غير محادثاتي، يؤدي ضبط `stream = True` إلى جعل `kickoff()` يعيد `StreamSession`. لا تضبط `flow.stream = True` عند استخدام `handle_turn()`؛ إذ تملك `stream_turn()` دورة حياة البث المحادثاتي.
## الاستيراد
@@ -464,10 +604,15 @@ from crewai.flow import (
router,
start,
)
from crewai.flow.conversation import prepare_conversational_turn
from crewai.flow import (
ConversationConfig,
ConversationState,
RouterConfig,
)
```
## مراجع
- [إتقان إدارة حالة Flow](/ar/guides/flows/mastering-flow-state)
- [أنشئ أول Flow](/ar/guides/flows/first-flow)
- Demo: `lib/crewai/runner_conversational_flow_simple.py` — REPL بسيط مع `RESEARCH` ووكيل Exa

View File

@@ -104,7 +104,7 @@ crewai flow add-crew content-crew
}
```
استبدل `provider/model-id` بالنموذج الذي تستخدمه، مثل `openai/gpt-4o` أو `gemini/gemini-2.0-flash-001` أو `anthropic/claude-sonnet-4-6`.
استبدل `provider/model-id` بالنموذج الذي تستخدمه، مثل `openai/gpt-4o` أو `gemini/gemini-3.7-flash` أو `anthropic/claude-sonnet-4-6`.
3. أنشئ `src/guide_creator_flow/crews/content_crew/crew.jsonc`:

View File

@@ -0,0 +1,156 @@
---
title: القنوات
description: شغّل نفس وكيل CrewAI كروبوت على Slack أو Teams باستخدام CopilotKit Channels SDK ومنصة Intelligence المُدارة.
icon: messages
mode: "wide"
---
## قابل مستخدميك حيث هم بالفعل
وكيل CrewAI الذي بنيته في [النظرة العامة](/edge/ar/guides/frontend/overview) لا يجب أن يعيش خلف تطبيق ويب فقط. يمكن لنفس الـ Crew أو الـ Flow أن يعمل كروبوت داخل منصة مراسلة. لا حاجة لإعادة البناء ولا لنسخة ثانية من منطق وكيلك: يبقى الوكيل مكشوفًا عبر [بروتوكول AG-UI](https://docs.ag-ui.com)، وتقوم **قناة** بتشغيله من Slack أو Microsoft Teams.
يوفّر [Channels SDK](https://docs.copilotkit.ai/slack) من CopilotKit تلك القناة. تُعرّف `createChannel` في وقت تشغيل صغير، وتوجّهه إلى وكيل CrewAI الخاص بك، وتتولى منصة **Intelligence** المُدارة من CopilotKit التوسّط في الاتصال مع مزوّد المراسلة.
<Note>
على خلاف بقية هذا القسم، فإن Channels **ليست ذاتية الاستضافة**. تعمل من خلال **CopilotKit Intelligence** — وهي سطح مطلوب لـ Channels، بحكم التصميم (تتوفر طبقة مجانية). تحتفظ Intelligence باتصال المنصة وبيانات الاعتماد، وتستقبل كل حدث من المنصة، وتسلّم الدور إلى عملية قناتك؛ تشغّل عمليتك الوكيل وتبثّ الرد مرة أخرى. تقوم بإعداد Slack مرة واحدة في لوحة تحكم Intelligence، ولا تدخل بيانات اعتماد المنصة عمليتك أبدًا. يبقى وكيلك وأدواتك وحالتك ملكًا لك.
</Note>
## كيف تتكامل الأجزاء معًا
لا يتغير أي شيء بخصوص خادم وكيل CrewAI الخاص بك. يستمر في تقديم الـ Crew أو الـ Flow عبر AG-UI تمامًا كما في النظرة العامة. ما تضيفه هو عملية Node منفصلة طويلة الأمد مبنية باستخدام `@copilotkit/channels`: تسجّل قناة على `CopilotRuntime`، وتتصل بـ Intelligence، وتشغّل وكيلك كلما وصلت رسالة.
```
Slack / Teams ──► CopilotKit Intelligence ──► channel process (Node) ──► CrewAI server (AG-UI) ──► Crew / Flow
```
تحتفظ عملية القناة باتصال دائم مع بوابة Intelligence، لذا فهي تحتاج إلى مضيف طويل الأمد — لا يمكن لمعالج طلبات بلا خادم (serverless) أن يملك ذلك الاتصال. يمكن لخادم CrewAI الخاص بك أن يستمر في تقديم واجهة الويب الأمامية من النظرة العامة في الوقت نفسه: تطبيق الويب والقناة ما هما إلا عميلان لنقطة نهاية AG-UI واحدة.
## دليل التكامل
<Steps>
<Step title="ثبّت حزم Channels">
يأتي Channels SDK مكتمل العناصر — كل منصة تُشحن في الحزمة الواحدة، بلا محوّل خاص بكل منصة لتثبيته. أضفه إلى جانب وقت التشغيل الذي يستضيف القناة وعميل CrewAI AG-UI:
```bash
npm install @copilotkit/channels @copilotkit/runtime @ag-ui/crewai
```
</Step>
<Step title="أنشئ قناة في Intelligence">
في [لوحة تحكم CopilotKit](https://docs.copilotkit.ai/slack)، أنشئ قناة واربط Slack — ترشدك Intelligence خلال إنشاء تطبيق Slack وتحتفظ ببيانات اعتماده. يترك ذلك متغيّري بيئة لعمليتك، كلاهما من لوحة التحكم:
```bash
export INTELLIGENCE_API_KEY=... # authenticates the runtime with Intelligence (free tier available)
export INTELLIGENCE_CHANNEL_ID=... # the Channel ID, matched by createChannel({ name })
```
</Step>
<Step title="عرّف القناة">
تُعرّف `createChannel` القناة وتربط وكيلك بها. ابنِ الوكيل كمصنع لكل خيط (thread) بحيث تحصل كل محادثة على جلستها الخاصة، مستخدمًا نفس `CrewAIAgent` الذي تستخدمه النظرة العامة في وقت تشغيل الويب، موجّهًا إلى نقطة نهاية AG-UI الخاصة بك. تتيح `identifyUser: "platform"` لـ Intelligence ربط كل مستخدم من المنصة بهوية ثابتة.
```ts
// channel.ts
import { createChannel } from "@copilotkit/channels";
import { CrewAIAgent } from "@ag-ui/crewai";
const channel = createChannel({
name: process.env.INTELLIGENCE_CHANNEL_ID!, // must match the Channel ID in Intelligence
identifyUser: "platform",
// A fresh agent per conversation, pointed at your CrewAI AG-UI endpoint.
agent: (threadId) => {
const agent = new CrewAIAgent({ url: "http://localhost:8000/recipe" });
agent.threadId = threadId;
return agent;
},
});
// A mention subscribes the thread and runs the agent; afterwards every message
// in a subscribed thread runs it without needing another mention.
channel.onMention(async ({ thread }) => {
await thread.subscribe();
await thread.runAgent();
});
channel.onMessage(async ({ thread }) => {
if (await thread.isSubscribed()) await thread.runAgent();
});
export { channel };
```
</Step>
<Step title="سجّل القناة على وقت التشغيل">
أنشئ `CopilotRuntime` مع بوابة Intelligence وقناتك، ثم قدّمه باستخدام `createCopilotNodeListener`. تبقى خريطة `agents` فارغة — القناة توفّر وكيلها الخاص. انتظر حتى تكون القناة جاهزة كي يفشل بدء التشغيل بصوت عالٍ عند وجود إعداد معطوب.
```ts
// server.ts
import { createServer } from "node:http";
import { CopilotRuntime, CopilotKitIntelligence } from "@copilotkit/runtime/v2";
import { createCopilotNodeListener } from "@copilotkit/runtime/v2/node";
import { channel } from "./channel";
const runtime = new CopilotRuntime({
agents: {}, // the channel supplies its own agent; no web-facing agents needed
intelligence: new CopilotKitIntelligence({
apiKey: process.env.INTELLIGENCE_API_KEY!, // free tier available
}),
channels: [channel],
});
const listener = createCopilotNodeListener({ runtime });
await listener.channels?.ready({ timeoutMs: 15_000 });
createServer(listener).listen(3123, () => {
console.log("Channels runtime listening on port 3123");
});
```
</Step>
<Step title="شغّل وقت تشغيل القناة">
ابدأه إلى جانب خادم وكيل CrewAI الخاص بك:
```bash
uvicorn server:app --port 8000 # terminal 1 — CrewAI agent server
npx tsx server.ts # terminal 2 — Channels runtime
```
اذكر الروبوت في Slack أو Teams فيشغّل الـ Crew أو الـ Flow الخاص بك، ويبثّ الرد مرة أخرى داخل الخيط. يبقى الخيط مشتركًا، لذا تعمل رسائل المتابعة دون الحاجة إلى ذكر آخر.
</Step>
</Steps>
## نموذج الأحداث
تتفاعل القناة مع أحداث المنصة عبر معالِجات، ويستقبل كل معالِج خيطًا (`thread`) تديره بعدد قليل من الدوال:
- **`channel.onMention`** يُطلَق عندما يذكر مستخدم الروبوت بـ @. استدعِ `thread.subscribe()` للانضمام إلى الخيط، ثم `thread.runAgent()` لتشغيل وكيل CrewAI الخاص بك عند الذكر.
- **`channel.onMessage`** يُطلَق عند كل رسالة في خيط يمكن للروبوت رؤيته. قيّده بـ `thread.isSubscribed()` كي لا يستجيب الوكيل إلا حيث انضمّ، ثم `thread.runAgent()`.
- **`thread.runAgent()`** يشغّل وكيل CrewAI المرفق للدور الحالي ويبثّ مخرجاته مرة أخرى داخل القناة. مرّر `{ prompt }` لتجاوز النص الذي يعمل عليه الوكيل.
يستقبل وكيلك `RunAgentInput` عاديًا من AG-UI ويصدر أحداث AG-UI عادية؛ تبقى آليات المنصة خلف القناة، لذا يعمل نفس الـ Crew أو الـ Flow دون تغيير عبر كل منصة. تكشف القناة أيضًا معالِجات للترحيبات والمقاطعات والأوامر والتفاعلات والنوافذ (modals) — راجع [مرجع `Channel`](https://docs.copilotkit.ai/reference/channels/classes/Channel) للاطلاع على السطح الكامل.
## دعم المنصات
يغطي مسار Intelligence المُدار **Slack** و**Microsoft Teams** اليوم — يعمل نفس كود القناة على أيٍّ منهما، وتفيد `message.platform` / `thread.platform` بالأصل الأصلي. تُبلَغ المنصات الأخرى (Discord وTelegram وWhatsApp) عبر **محوّلات مباشرة** يشغّلها المطوّر بدلًا من المسار المُدار — تملك عمليتك الخاصة بيانات اعتماد المنصة والنقل. راجع [توثيق CopilotKit Channels](https://docs.copilotkit.ai/slack) للاطلاع على قائمة المنصات الحالية والإعداد الخاص بكل منصة.
## ذات صلة
<CardGroup cols={2}>
<Card title="النظرة العامة على الواجهة الأمامية" icon="browser" href="/edge/ar/guides/frontend/overview">
قدّم الـ Crew أو الـ Flow الخاص بك عبر AG-UI — الأساس الذي تُبنى عليه كل قناة.
</Card>
<Card title="التدخل البشري (Human-in-the-Loop)" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
أوقف الوكيل مؤقتًا لجمع موافقة المستخدم أو مدخلاته في منتصف التشغيل.
</Card>
</CardGroup>

View File

@@ -0,0 +1,238 @@
---
title: النظرة العامة على الواجهة الأمامية
description: ابنِ واجهات مستخدم تفاعلية لوكلاء CrewAI الخاصين بك باستخدام CopilotKit وبروتوكول AG-UI.
icon: browser
mode: "wide"
---
## امنح وكلاءك واجهة مستخدم
يشغّل CrewAI وكلاءك. ويمنحهم [CopilotKit](https://copilotkit.ai) واجهة أمامية. معًا يتيحان لك بناء تطبيقات يحادث فيها المستخدمون Crew أو Flow، ويشاهدونه يعمل في الوقت الفعلي، ويوافقون على قراراته، ويرون مخرجاته معروضة كواجهة حيّة بدلًا من جدران من النص.
يتصل الاثنان عبر [بروتوكول AG-UI](https://docs.ag-ui.com). تكشف حزمة `ag-ui-crewai` أي Crew أو Flow كنقطة نهاية AG-UI. وتستهلك خطافات (hooks) ومكوّنات React من CopilotKit تلك النقطة. يفتح ذلك تجارب تتجاوز بكثير صندوق المحادثة:
<CardGroup cols={2}>
<Card title="واجهة المستخدم التوليدية (Generative UI)" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
اعرض استدعاءات أدوات الوكيل وحالته كمكوّنات React خاصة بك.
</Card>
<Card title="التدخل البشري (Human-in-the-Loop)" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
أوقف الوكيل مؤقتًا لجمع موافقة المستخدم أو مدخلاته في منتصف التشغيل.
</Card>
<Card title="الحالة المشتركة (Shared State)" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
أبقِ حالة الوكيل وواجهة تطبيقك متزامنتين في الاتجاهين.
</Card>
<Card title="القنوات (Channels)" icon="messages" href="/edge/ar/guides/frontend/channels">
شغّل نفس الوكيل كروبوت على Slack أو Discord أو Teams.
</Card>
</CardGroup>
يجعل هذا الدليل Crew أو Flow يتحدث مع واجهة أمامية بـ Next.js من البداية إلى النهاية. تبني بقية القسم على التطبيق الذي تعدّه هنا.
## البنية
هناك ثلاثة أجزاء:
1. **خادم وكيل CrewAI** — عملية Python تقدّم الـ Crew أو الـ Flow الخاص بك عبر AG-UI (FastAPI + `ag-ui-crewai`).
2. **وقت تشغيل CopilotKit** — مسار Next.js يسجّل وكيلك ويوكّل الطلبات إليه.
3. **الواجهة الأمامية بـ React** — مزوّد `<CopilotKit>` إلى جانب مكوّنات المحادثة والواجهة التوليدية.
```
React app ──► CopilotKit runtime (/api/copilotkit) ──► CrewAI server (AG-UI) ──► Crew / Flow
```
<Note>
يغطي هذا الدليل المسار **الذاتي الاستضافة**: تشغّل خادم وكيل CrewAI بنفسك باستخدام `ag-ui-crewai`، ويعمل محليًا دون أي خدمة مُدارة. يقدّم CopilotKit أيضًا مسارًا **مُدارًا** (CopilotKit Cloud / Enterprise Intelligence) بخيوط مستضافة وأداة فحص — راجع [دليل البدء السريع لـ CopilotKit مع CrewAI](https://docs.copilotkit.ai/crewai-crews/quickstart) إن أردت ذلك بدلًا منه. كود الواجهة الأمامية في هذا القسم هو نفسه في الحالتين؛ الاختلاف فقط في كيفية استضافة الوكيل وتسجيله.
</Note>
<Note>
يعمل CrewAI خلف AG-UI بثلاثة أشكال: الـ **Flows** العادية (المستخدمة في هذه الأدلة)، و**[الـ Flows المحادثية (Conversational Flows)](/edge/en/guides/frontend/conversational-flows)** (أصلية، مدركة للجلسة، قائمة على الأدوار، بتكافؤ كامل في الميزات)، والـ **Crews** (محادثة أساسية). الواجهة الأمامية في هذا القسم متطابقة عبرها جميعًا — الاختلاف فقط في تأليف الخلفية وتسجيلها.
</Note>
## دليل التكامل
<Steps>
<Step title="قدّم وكيلك عبر AG-UI">
ثبّت حزمة التكامل في مشروع CrewAI الخاص بك:
```bash
pip install ag-ui-crewai
```
اكشف وكيلك من تطبيق FastAPI. تستخدم الـ Flows دالة `add_crewai_flow_fastapi_endpoint`؛ وتستخدم الـ Crews دالة `add_crewai_crew_fastapi_endpoint`. يمكنك تسجيل ما تشاء منها، كلٌّ على مساره الخاص.
<CodeGroup>
```python Flow
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
from my_agents.recipe_flow import RecipeFlow
app = FastAPI(title="CrewAI Agent Server")
add_crewai_flow_fastapi_endpoint(
app=app,
flow=RecipeFlow(),
path="/recipe",
)
```
```python Crew
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_crew_fastapi_endpoint
from my_agents.research_crew import ResearchCrew
app = FastAPI(title="CrewAI Agent Server")
add_crewai_crew_fastapi_endpoint(
app=app,
crew=ResearchCrew().crew(),
path="/research",
)
```
</CodeGroup>
شغّله:
```bash
uvicorn server:app --port 8000
```
<Note>
اضبط متغيّرات البيئة الخاصة بمزوّد الـ LLM الخاص بك (على سبيل المثال `OPENAI_API_KEY`) قبل بدء الخادم.
</Note>
</Step>
<Step title="أنشئ تطبيق Next.js">
إن لم تكن لديك واجهة أمامية بعد، أنشئ هيكلًا:
```bash
npx create-next-app@latest my-app
cd my-app
```
ثبّت CopilotKit وعميل CrewAI AG-UI:
```bash
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime @ag-ui/crewai
```
</Step>
<Step title="أضف وقت تشغيل CopilotKit">
أنشئ مسارًا يسجّل وكيل (أو وكلاء) CrewAI مع وقت تشغيل CopilotKit. يشير كل وكيل إلى مسار على خادم Python الخاص بك عبر `CrewAIAgent`.
```ts
// app/api/copilotkit/route.ts
import {
CopilotRuntime,
InMemoryAgentRunner,
createCopilotEndpoint,
} from "@copilotkit/runtime/v2";
import { CrewAIAgent } from "@ag-ui/crewai";
import { handle } from "hono/vercel";
const runtime = new CopilotRuntime({
agents: {
recipe: new CrewAIAgent({ url: "http://localhost:8000/recipe" }),
},
runner: new InMemoryAgentRunner(),
});
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
});
const handler = handle(app);
export const GET = handler;
export const POST = handler;
```
</Step>
<Step title="غلّف تطبيقك بالمزوّد">
وجّه `<CopilotKit>` إلى مسار وقت التشغيل واذكر اسم الوكيل الذي سجّلته.
```tsx
// app/page.tsx
"use client";
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotSidebar } from "@copilotkit/react-core/v2";
import "@copilotkit/react-core/v2/styles.css";
export default function Page() {
return (
<CopilotKit runtimeUrl="/api/copilotkit" agent="recipe">
<YourApp />
<CopilotSidebar agentId="recipe" labels={{ modalHeaderTitle: "Assistant" }} />
</CopilotKit>
);
}
```
</Step>
<Step title="شغّله">
ابدأ العمليتين وافتح التطبيق. تشغّل المحادثة في الشريط الجانبي الآن الـ Crew أو الـ Flow الخاص بك.
```bash
uvicorn server:app --port 8000 # terminal 1
npm run dev # terminal 2
```
</Step>
</Steps>
## خيارات واجهة المحادثة
يشحن CopilotKit ثلاثة أسطح محادثة قابلة للتبديل. بدّل المكوّن؛ يبقى التوصيل متطابقًا.
<CodeGroup>
```tsx Sidebar
import { CopilotSidebar } from "@copilotkit/react-core/v2";
<CopilotSidebar agentId="recipe" />
```
```tsx Popup
import { CopilotPopup } from "@copilotkit/react-core/v2";
<CopilotPopup agentId="recipe" />
```
```tsx Inline
import { CopilotChat } from "@copilotkit/react-core/v2";
<CopilotChat agentId="recipe" />
```
</CodeGroup>
## إلى أين تذهب بعد ذلك
<CardGroup cols={2}>
<Card title="واجهة المستخدم التوليدية (Generative UI)" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
اعرض استدعاءات الأدوات وحالة الوكيل كمكوّنات مخصّصة.
</Card>
<Card title="إجراءات الواجهة الأمامية (Frontend Actions)" icon="bolt" href="/edge/en/guides/frontend/frontend-actions">
دع الوكيل يستدعي دوالًا تعمل في المتصفح.
</Card>
<Card title="التدخل البشري (Human-in-the-Loop)" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
قيّد إجراءات الوكيل خلف موافقة المستخدم.
</Card>
<Card title="الحالة التنبؤية (Predictive State)" icon="gauge-high" href="/edge/en/guides/frontend/predictive-state-updates">
ابثّ الحالة قيد التنفيذ إلى الواجهة أثناء عمل الوكيل.
</Card>
</CardGroup>

View File

@@ -0,0 +1,200 @@
---
title: خطافات حدود التنفيذ
description: اعتراض بداية تنفيذ الـ Crew والـ Flow ومدخلاته ومخرجاته ونهايته باستخدام المزخرف @on
mode: "wide"
---
تعترض خطافات حدود التنفيذ الأطراف الخارجية للتشغيل — قبل بدء أي عمل، وعند
حسم المدخلات، وعند جاهزية النتيجة النهائية، وعند انتهاء التنفيذ. وهي تعمل مع
الـ Crew والـ Flow على حد سواء، وتُعد المكان المناسب لفحوصات السياسة على
مستوى التشغيل وإعادة كتابة المدخلات وتنقية المخرجات.
## نظرة عامة
أربع نقاط اعتراض تغطي الحدود:
| النقطة | التوقيت | `ctx.payload` |
|--------|---------|---------------|
| `EXECUTION_START` | Crew أو Flow على وشك البدء | `dict` المدخلات |
| `INPUT` | المدخلات المحسومة للتنفيذ | `dict` المدخلات |
| `OUTPUT` | النتيجة النهائية جاهزة | كائن المخرجات |
| `EXECUTION_END` | انتهى التنفيذ (نجاحًا أو فشلًا) | كائن المخرجات، أو `None` عند الفشل |
بالنسبة إلى الـ Crew، يكون payload المخرجات `CrewOutput`. أما في الـ Flow فهو
النتيجة النهائية لدالة الـ Flow.
## توقيع الخطاف
```python
from crewai.hooks import on, HookAborted, InterceptionPoint
@on(InterceptionPoint.EXECUTION_START)
def boundary_hook(ctx) -> Any | None:
# Mutate ctx.payload in place, or
# return a non-None value to replace it, or
# raise HookAborted(reason, source) to stop the run
return None
```
تتبع خطافات الحدود العقد القياسي: المتابعة (`return None`)، أو التعديل في
المكان، أو الاستبدال بإرجاع قيمة، أو الإجهاض برفع `HookAborted`. أي إجهاض
عند أي حد ينتشر خارج `kickoff()` مع سببه.
## مخطط السياق
تتلقى كل نقطة سياقًا منمّطًا. تشترك جميع السياقات في الحقول الأساسية:
```python
class InterceptionContext:
payload: Any # The interceptable value (see table above)
agent: Any = None # Not populated at execution boundaries
agent_role: str | None # Not populated at execution boundaries
task: Any = None # Not populated at execution boundaries
crew: Any = None # The Crew instance (crew runs only)
flow: Any = None # The Flow instance (flow runs only)
```
تضيف سياقات كل نقطة اسمًا بديلًا للـ payload:
```python
class ExecutionStartContext(InterceptionContext):
inputs: dict # Same dict as payload
class InputContext(InterceptionContext):
inputs: dict # Same dict as payload
class OutputContext(InterceptionContext):
output: Any # The output object
class ExecutionEndContext(InterceptionContext):
output: Any # The output object (None when status == "failed")
status: str # "completed" or "failed"
error: BaseException | None # The exception when status == "failed"
```
<Note>
`ctx.inputs` هو اسم بديل لقاموس المدخلات **الأصلي**، لذا فإن التعديلات في
المكان عبر أي من الاسمين متكافئة. إذا *استبدل* خطاف سابق الـ payload بإرجاع
dict جديد، فإن `ctx.payload` وحده يُعاد ربطه — اقرأ واكتب دائمًا عبر
`ctx.payload` عندما يمكن أن تتسلسل الخطافات.
</Note>
## تشغيلات الـ Crew مقابل تشغيلات الـ Flow
تعمل خطافات الحدود على كلا وقتي التشغيل، وتنفيذ الـ Crew يجري داخليًا فوق وقت
تشغيل Flow. لذلك أثناء `crew.kickoff()` يُطلق الخطاف الحدودي العام لحدّ الـ
Crew (`ctx.crew` مضبوط و`ctx.flow` يساوي `None`) **و** للـ Flow الداخلي
(`ctx.flow` مضبوط و`ctx.crew` يساوي `None`). ميّز حسب وقت التشغيل:
```python
@on(InterceptionPoint.OUTPUT)
def crew_output_only(ctx):
if ctx.crew is None:
return None # Skip the internal flow (or a bare flow)
ctx.payload.raw = ctx.payload.raw.strip()
```
## حالات استخدام شائعة
### فحص السياسة عند البدء
```python
@on(InterceptionPoint.EXECUTION_START)
def enforce_policy(ctx):
if ctx.crew is not None and not ctx.payload.get("authorized"):
raise HookAborted(reason="unauthorized execution", source="access-control")
```
### إعادة كتابة المدخلات
```python
@on(InterceptionPoint.INPUT)
def add_defaults(ctx):
if ctx.crew is None:
return None
ctx.payload.setdefault("locale", "en-US")
ctx.payload["topic"] = ctx.payload["topic"].strip().lower()
```
تتدفق المدخلات المعاد كتابتها إلى استيفاء الـ Task، فيتصرف التشغيل كما لو
بدأ بالقاموس المعدل.
فضّل `INPUT` لإعادة الكتابة وعامل `EXECUTION_START` كبوابة سماح/منع. إعادة
الكتابة عند `EXECUTION_START` تظل مُحترمة — في الـ Crew تغذي أيضًا استدعاءات
`before_kickoff`؛ وفي الـ Flow تُطبق تمامًا كإعادة كتابة `INPUT`.
### تنقية المخرجات
```python
import re
@on(InterceptionPoint.OUTPUT)
def redact_emails(ctx):
if ctx.crew is None:
return None
ctx.payload.raw = re.sub(
r"\b[\w.+-]+@[\w-]+\.[\w.]+\b", "[EMAIL-REDACTED]", ctx.payload.raw
)
```
يعمل `OUTPUT` قبل `EXECUTION_END`، وكلاهما يرى الـ payload (الذي ربما
استُبدل) من الخطافات السابقة؛ والقيمة النهائية المعاد كتابتها هي ما يعيده
`kickoff()`.
### مراقبة الإخفاقات
يُطلق `EXECUTION_END` مرة واحدة بالضبط لكل تنفيذ، عند النجاح والفشل على حد
سواء. عندما يرفع التشغيل استثناءً — خطأ في Task، أو استثناء في دالة Flow، أو
`HookAborted` من نقطة سابقة — يتلقى الخطاف `status="failed"` مع الاستثناء في
`ctx.error`، ويظل الاستثناء الأصلي ينتشر خارج `kickoff()` دون تغيير:
```python
@on(InterceptionPoint.EXECUTION_END)
def report_outcome(ctx):
if ctx.status == "failed":
notify_policy_engine(status="failed", error=repr(ctx.error))
else:
notify_policy_engine(status="completed")
```
تنبيهان: لا يُطلق `EXECUTION_END` عندما لا يكون `EXECUTION_START` قد أُرسل
أصلًا (الإجهاض عند البدء يعني أن الحد لم يُفتح قط، فلا توجد نهاية تقابله)،
ورفع `HookAborted` من إرسال `EXECUTION_END` في مسار الفشل يُتجاهل — لم يعد
هناك ما يُجهض، والخطأ الأصلي هو الغالب.
## الترتيب
لتشغيل Crew يكون ترتيب الحدود:
```
EXECUTION_START → before_kickoff callbacks → INPUT → tasks execute → OUTPUT → EXECUTION_END
```
لتشغيل Flow، تحسم خطافات الحدود المدخلات قبل أن تبدأ أحداث دورة الحياة:
```
EXECUTION_START → INPUT → FlowStartedEvent → flow methods execute → OUTPUT → EXECUTION_END → FlowFinishedEvent
```
يحمل `FlowStartedEvent` المدخلات كما حسمتها الخطافات، وإعادة كتابة
`inputs["id"]` داخل خطاف حدودي تعيد توجيه استعادة الحالة. يظهر الإجهاض عند
`EXECUTION_START` مع ذلك كحدث `FlowStartedEvent` يتبعه `FlowFailedEvent`،
ويُبثان عند الإجهاض مع الحمولة كما حسمتها الخطافات التي عملت قبله.
تعمل الخطافات في النقطة نفسها حسب ترتيب التسجيل، الخطافات العامة أولًا ثم
الخطافات المحدودة بالـ Crew. تُبث القياسات (`HookDispatchedEvent`) مع كل
إرسال.
## إدارة الخطافات في الاختبارات
```python
from crewai.hooks import clear_all_hooks
clear_all_hooks() # Clears every point, including boundaries
```
## وثائق ذات صلة
- [نظرة عامة على خطافات التنفيذ →](/edge/ar/learn/execution-hooks)
- [خطافات استدعاء LLM →](/edge/ar/learn/llm-hooks)
- [خطافات استدعاء الأدوات →](/edge/ar/learn/tool-hooks)

View File

@@ -176,7 +176,7 @@ grep -r "llm:" --include="*.yaml" .
# llm = LLM(model="mistral/mistral-large-latest")
# After (Native):
llm = LLM(model="gemini/gemini-2.0-flash")
llm = LLM(model="gemini/gemini-3.7-flash")
```
```bash
@@ -312,7 +312,7 @@ llm = LLM(model="anthropic/claude-haiku-3-5") # Fast & affordable
# Together AI → OpenAI or Gemini
# llm = LLM(model="together_ai/meta-llama/Meta-Llama-3.1-70B")
llm = LLM(model="openai/gpt-4o") # High quality
llm = LLM(model="gemini/gemini-2.0-flash") # Fast & capable
llm = LLM(model="gemini/gemini-3.7-flash") # Fast & capable
# Mistral → Anthropic or OpenAI
# llm = LLM(model="mistral/mistral-large-latest")

View File

@@ -141,7 +141,7 @@ mode: "wide"
# Example using Gemini's OpenAI-compatible API.
os.environ["OPENAI_API_KEY"] = "your-gemini-key" # Should start with AIza...
os.environ["OPENAI_API_BASE"] = "https://generativelanguage.googleapis.com/v1beta/openai/"
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-2.0-flash" # Add your Gemini model here, under openai/
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-3.7-flash" # Add your Gemini model here, under openai/
```
</CodeGroup>
</Tab>
@@ -159,7 +159,7 @@ mode: "wide"
```python Google
# Example using Gemini's OpenAI-compatible API
llm = LLM(
model="openai/gemini-2.0-flash",
model="openai/gemini-3.7-flash",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key="your-gemini-key", # Should start with AIza...
)

View File

@@ -144,7 +144,7 @@ Planning agents benefit from reasoning models that can handle complex strategic
from crewai import Agent, Task, Crew, LLM
# High-capability reasoning model for strategic planning
manager_llm = LLM(model="gemini-2.5-flash-preview-05-20", temperature=0.1)
manager_llm = LLM(model="gemini/gemini-3.7-flash", temperature=0.1)
# Creative model for content generation
content_llm = LLM(model="claude-3-5-sonnet-20241022", temperature=0.7)
@@ -409,7 +409,7 @@ Rather than repeating the strategic framework, here's a tactical checklist for i
# Manager or coordination agents
manager_agent = Agent(
role="Project Manager",
llm=LLM(model="gemini-2.5-flash-preview-05-20"), # Premium for coordination
llm=LLM(model="gemini/gemini-3.7-flash"), # Premium for coordination
# ... rest of config
)

View File

@@ -151,7 +151,7 @@ result = stream.result
```python
from crewai import Flow
from crewai.experimental.conversational import ConversationConfig, ConversationState
from crewai.flow import ConversationConfig, ConversationState
@ConversationConfig(llm="gpt-4o-mini", defer_trace_finalization=True)

View File

@@ -7,9 +7,9 @@ mode: "wide"
# تكامل Arize Phoenix
يوضح هذا الدليل كيفية دمج **Arize Phoenix** مع **CrewAI** باستخدام OpenTelemetry عبر حزمة [OpenInference](https://github.com/openinference/openinference) SDK. بنهاية هذا الدليل، ستتمكن من تتبع وكلاء CrewAI وتصحيح أخطاء وكلائك بسهولة.
يوضح هذا الدليل كيفية دمج **Arize Phoenix** مع **CrewAI** باستخدام OpenTelemetry عبر حزمة [OpenInference](https://github.com/openinference/openinference) SDK. بنهاية هذا الدليل، ستتمكن من تتبع وكلاء CrewAI وتصحيح سلوك الوكلاء.
> **ما هو Arize Phoenix؟** [Arize Phoenix](https://phoenix.arize.com) هو منصة مراقبة LLM توفر التتبع والتقييم لتطبيقات الذكاء الاصطناعي.
> **ما هو Arize Phoenix؟** [Arize Phoenix](https://arize.com/phoenix/) هو خيار المراقبة والتقييم مفتوح المصدر من [Arize AI](https://arize.com/?utm_source=crewai-docs&utm_medium=partner&utm_campaign=partner-docs&utm_content=observability-arize-phoenix). استخدم Phoenix عندما تريد التشغيل محلياً أو الاستضافة الذاتية. استخدم [Arize AX](https://arize.com/products/ax/) لمنصة سحابية مُدارة أو ذاتية الاستضافة للمؤسسات لأنظمة الذكاء الاصطناعي في الإنتاج.
[![شاهد عرض فيديو لتكاملنا مع Phoenix](https://storage.googleapis.com/arize-assets/fixtures/setup_crewai.png)](https://www.youtube.com/watch?v=Yc5q3l6F7Ww)
@@ -27,7 +27,7 @@ pip install openinference-instrumentation-crewai crewai crewai-tools arize-phoen
### الخطوة 2: إعداد متغيرات البيئة
قم بإعداد مفاتيح API لـ Phoenix Cloud وإعداد OpenTelemetry لإرسال التتبعات إلى Phoenix. Phoenix Cloud هو إصدار مستضاف من Arize Phoenix، لكنه ليس مطلوباً لاستخدام هذا التكامل.
قم بإعداد مفتاح API الخاص بـ Phoenix ونقطة نهاية OpenTelemetry لإرسال التتبعات إلى Phoenix. يعمل الإعداد نفسه مع نقطة نهاية Phoenix محلية أو ذاتية الاستضافة عن طريق تغيير عنوان المجمع.
يمكنك الحصول على مفتاح Serper API المجاني [هنا](https://serper.dev/).
@@ -35,8 +35,8 @@ pip install openinference-instrumentation-crewai crewai crewai-tools arize-phoen
import os
from getpass import getpass
# Get your Phoenix Cloud credentials
PHOENIX_API_KEY = getpass("🔑 Enter your Phoenix Cloud API Key: ")
# Get your Phoenix API key
PHOENIX_API_KEY = getpass("🔑 Enter your Phoenix API key: ")
# Get API keys for services
OPENAI_API_KEY = getpass("🔑 Enter your OpenAI API key: ")
@@ -44,7 +44,7 @@ SERPER_API_KEY = getpass("🔑 Enter your Serper API key: ")
# Set environment variables
os.environ["PHOENIX_CLIENT_HEADERS"] = f"api_key={PHOENIX_API_KEY}"
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "https://app.phoenix.arize.com" # Phoenix Cloud, change this to your own endpoint if you are using a self-hosted instance
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "https://app.phoenix.arize.com" # Change this to your own endpoint if you are using a self-hosted instance
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
os.environ["SERPER_API_KEY"] = SERPER_API_KEY
```
@@ -131,7 +131,7 @@ print(result)
بعد تشغيل الوكيل، يمكنك عرض التتبعات المولدة من تطبيق CrewAI في Phoenix. سترى خطوات مفصلة لتفاعلات الوكلاء واستدعاءات LLM، مما يساعدك في التصحيح والتحسين.
سجل الدخول إلى حساب Phoenix Cloud الخاص بك وانتقل إلى المشروع الذي حددته في معامل `project_name`. سترى عرض زمني للتتبع مع جميع تفاعلات الوكلاء واستخدامات الأدوات واستدعاءات LLM.
افتح مشروع Phoenix وانتقل إلى المشروع الذي حددته في معامل `project_name`. سترى عرض زمني للتتبع مع جميع تفاعلات الوكلاء واستخدامات الأدوات واستدعاءات LLM.
![مثال تتبع في Phoenix يوضح تفاعلات الوكلاء](https://storage.googleapis.com/arize-assets/fixtures/crewai_traces.png)
@@ -145,6 +145,9 @@ print(result)
### المراجع
- [وثائق Phoenix](https://docs.arize.com/phoenix/) - نظرة عامة على منصة Phoenix.
- [Arize AX](https://arize.com/products/ax/) - مراقبة وتقييم مُداران سحابياً أو ذاتيا الاستضافة للمؤسسات.
- [دليل Arize لتقييم الوكلاء](https://arize.com/guides/ai-agent-handbook/agent-evaluation/) - سير عمل إنتاجي لتقييم سلوك الوكلاء من التتبعات.
- [دليل Arize لتقييم LLM](https://arize.com/resources/llm-evaluation/) - طرق ومقاييس لتقييم تطبيقات LLM.
- [وثائق CrewAI](https://docs.crewai.com/) - نظرة عامة على إطار عمل CrewAI.
- [وثائق OpenTelemetry](https://opentelemetry.io/docs/) - دليل OpenTelemetry
- [OpenInference GitHub](https://github.com/openinference/openinference) - الكود المصدري لـ OpenInference SDK.

View File

@@ -9,7 +9,7 @@ mode: "wide"
يوفر CrewAI إمكانيات تتبع مدمجة تتيح لك مراقبة وتصحيح أخطاء الطواقم والتدفقات في الوقت الفعلي. يوضح هذا الدليل كيفية تفعيل التتبع لكل من **الطواقم** و**التدفقات** باستخدام منصة المراقبة المتكاملة في CrewAI.
> **ما هو تتبع CrewAI؟** يوفر التتبع المدمج في CrewAI مراقبة شاملة لوكلاء الذكاء الاصطناعي، بما في ذلك قرارات الوكلاء وجداول تنفيذ المهام واستخدام الأدوات واستدعاءات LLM - كل ذلك متاح عبر [منصة CrewAI AMP](https://app.crewai.com).
> **ما هو تتبع CrewAI؟** يوفر التتبع المدمج في CrewAI مراقبة شاملة لوكلاء الذكاء الاصطناعي، بما في ذلك قرارات الوكلاء وجداول تنفيذ المهام واستخدام الأدوات واستدعاءات LLM - كل ذلك متاح عبر [منصة CrewAI AMP](https://app.crewai.com). يتم إدارة التتبع بشكل مستقل عن [القياس عن بُعد](/ar/telemetry).
![واجهة تتبع CrewAI](/images/crewai-tracing.png)
@@ -170,6 +170,18 @@ CREWAI_TRACING_ENABLED=true
عند تعيين متغير البيئة هذا، ستُفعّل جميع الطواقم والتدفقات التتبع تلقائياً، حتى بدون تعيين `tracing=True` صراحةً.
## عرض التتبعات بعد أول تشغيل
في المرة الأولى التي تشغّل فيها طاقماً أو تدفقاً، قد يسألك طرف تفاعلي:
```text
Would you like to view your execution traces? [y/N]
```
اختر **yes** لفتح رابط العرض. يمكنك تغيير ذلك لاحقاً باستخدام
`crewai traces enable` أو `crewai traces disable`، أو بتعيين `tracing`
على الطاقم أو التدفق.
## عرض التتبعات
### الوصول إلى لوحة تحكم CrewAI AMP

View File

@@ -23,7 +23,8 @@ mode: "wide"
عند تفعيل ميزة `share_crew`، يتم جمع بيانات تفصيلية تشمل أوصاف المهام وخلفيات وأهداف الوكلاء وسمات محددة أخرى
لتوفير رؤى أعمق. قد يتضمن جمع البيانات الموسع هذا معلومات شخصية إذا دمجها المستخدمون في طواقمهم أو مهامهم.
يجب على المستخدمين النظر بعناية في محتوى طواقمهم ومهامهم قبل تفعيل `share_crew`.
يمكن للمستخدمين تعطيل القياس عن بُعد عبر تعيين متغير البيئة `CREWAI_DISABLE_TELEMETRY` إلى `true` أو تعيين `OTEL_SDK_DISABLED` إلى `true` (لاحظ أن الأخير يعطل جميع أدوات OpenTelemetry عالمياً).
يمكن للمستخدمين تعطيل القياس عن بُعد في CrewAI عبر تعيين `CREWAI_DISABLE_TELEMETRY` إلى `true` أو `1` أو `yes` أو `on` (بغض النظر عن حالة الأحرف). `OTEL_SDK_DISABLED` بنفس القيم يعطّل أيضاً مُصدِّر CrewAI. مجموعة أدوات OpenTelemetry نفسها ما تزال تقبل `true` فقط لتعطيل بقية أدوات القياس في العملية.
تتبع AMP مشمول بشكل منفصل في [التتبع](/ar/observability/tracing).
### أمثلة:
```python
@@ -34,18 +35,38 @@ os.environ['CREWAI_DISABLE_TELEMETRY'] = 'true'
os.environ['OTEL_SDK_DISABLED'] = 'true'
```
`CREWAI_DISABLE_TELEMETRY=1` (أو `yes` / `on`) يعمل بنفس طريقة `true`. تُتجاهل القيم غير المعروفة ويبقى القياس عن بُعد مفعّلاً.
### العزل عن إعداد OpenTelemetry الخاص بك
يعمل القياس عن بُعد الخاص بـ CrewAI على `TracerProvider` خاص به ولا يسجل نفسه
أبدًا كمزوّد عام. هذا يفصل الاتجاهين:
- لا تُرسَل أبدًا إلى CrewAI الامتدادات (spans) الصادرة عن المكتبات الأخرى
المزوّدة بأدوات القياس في عمليتك — أطر الويب، وعملاء قواعد البيانات،
وعملاء HTTP.
- لا تُرسَل امتدادات القياس عن بُعد الخاصة بـ CrewAI إلى نظام المراقبة لديك، لذا
لن تظهر في Langfuse أو Braintrust أو Phoenix أو أي مُجمِّع آخر تقوم بإعداده.
لا تتأثر تكاملات المراقبة: فهي تقيس CrewAI عبر مزوّد التتبع الخاص بها، وهو
مستقل عن المزوّد الموصوف هنا.
### شرح البيانات:
| افتراضي | البيانات | السبب والتفاصيل |
|:----------|:------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------|
| نعم | إصدار CrewAI وPython | تتبع إصدارات البرمجيات. مثال: CrewAI v1.2.3، Python 3.8.10. لا بيانات شخصية. |
| نعم | بيانات وصفية للطاقم | تشمل: مفتاح ومعرّف مُولّد عشوائياً، نوع العملية (مثل 'sequential'، 'parallel')، علم منطقي لاستخدام الذاكرة (true/false)، عدد المهام، عدد الوكلاء. كلها غير شخصية. |
| نعم | بيانات وصفية للطاقم | تشمل: مفتاح ومعرّف مُولّد عشوائياً، نوع العملية (مثل 'sequential'، 'parallel')، علم منطقي لاستخدام الذاكرة (true/false)، علم منطقي يوضح ما إذا تم تمرير أي مدخلات للتشغيل (true/false — وليس مفاتيح المدخلات أو قيمها، والتي لا تُجمع إلا عند تمكين `share_crew`)، عدد المهام، عدد الوكلاء. كلها غير شخصية. |
| نعم | بيانات الوكيل | تشمل: مفتاح ومعرّف مُولّد عشوائياً، اسم الدور (يجب ألا يتضمن معلومات شخصية)، إعدادات منطقية (verbose، التفويض مُفعّل، تنفيذ الكود مسموح)، أقصى عدد تكرارات، أقصى RPM، أقصى حد لإعادة المحاولة، معلومات LLM (انظر سمات LLM)، قائمة أسماء الأدوات (يجب ألا تتضمن معلومات شخصية). لا بيانات شخصية. |
| نعم | بيانات وصفية للمهمة | تشمل: مفتاح ومعرّف مُولّد عشوائياً، إعدادات تنفيذ منطقية (async_execution، human_input)، دور ومفتاح الوكيل المرتبط، قائمة أسماء الأدوات. كلها غير شخصية. |
| نعم | إحصائيات استخدام الأدوات | تشمل: اسم الأداة (يجب ألا يتضمن معلومات شخصية)، عدد محاولات الاستخدام (عدد صحيح)، سمات LLM المستخدمة. لا بيانات شخصية. |
| نعم | بيانات تنفيذ الاختبار | تشمل: مفتاح ومعرّف الطاقم المُولّد عشوائياً، عدد التكرارات، اسم النموذج المستخدم، درجة الجودة (عدد عشري)، وقت التنفيذ (بالثواني). كلها غير شخصية. |
| نعم | بيانات دورة حياة المهمة | تشمل: أوقات الإنشاء وبدء/انتهاء التنفيذ، معرّفات الطاقم والمهمة. مخزنة كنطاقات مع طوابع زمنية. لا بيانات شخصية. |
| نعم | بيانات دورة حياة المهمة | تشمل: أوقات الإنشاء وبدء/انتهاء التنفيذ، معرّفات الطاقم والمهمة، وما إذا نجحت المهمة أو فشلت. وعند فشل المهمة، يُسجَّل **اسم صنف** الاستثناء (مثل `TimeoutError`) بحيث يمكن عدّ حالات الفشل وتشخيصها — وليس رسالة الخطأ أبدًا، فهي قد تحتوي على مطالبات أو مخرجات نموذج أو مسارات ملفات أو بيانات اعتماد. مخزنة كنطاقات مع طوابع زمنية. لا بيانات شخصية. |
| نعم | سمات LLM | تشمل: الاسم، model_name، model، top_k، temperature، واسم فئة LLM. كلها بيانات تقنية غير شخصية. |
| نعم | محاولة نشر الطاقم باستخدام CLI الخاص بـ CrewAI | تشمل: حقيقة إجراء النشر ومعرّف الطاقم، وما إذا كان يحاول سحب السجلات، لا بيانات أخرى. |
| نعم | إنشاء مشروع باستخدام CLI الخاص بـ CrewAI | تشمل: أن مشروعًا جديدًا أُنشئ عبر `crewai create`، ونوعه (`crew` أو `json_crew` أو `flow`)، ومعرّف المشروع الذي تم توليده لهذا المشروع الجديد وكُتب في ملف `pyproject.toml` الخاص به. وهو معرّف المشروع الجديد نفسه، ويُسجَّل بشكل منفصل عن `project_id` الخاص بالمجلد الذي شُغّل منه الأمر — وقد يختلفان. لا اسم مشروع، ولا محتويات ملفات، ولا شيفرة. لا بيانات شخصية. |
| نعم | محاولة نشر الطاقم باستخدام CLI الخاص بـ CrewAI | تشمل: حقيقة إجراء النشر ومعرّف الطاقم، وما إذا كان يحاول سحب السجلات، وما إذا بدأ النشر من أمر CLI أو من واجهة التشغيل TUI. لا تُسجَّل محتويات المشروع أو الطاقم. لا توجد بيانات شخصية. |
| نعم | بيئة التنفيذ | تشمل: مساعد البرمجة بالذكاء الاصطناعي الذي يشغّل العملية إن وُجد (واحد من قائمة ثابتة مثل `claude_code` أو `codex` أو `cursor` أو `unknown`)، ومكان تشغيل العملية (واحد من قائمة ثابتة مثل `ci` أو `container` أو `serverless` أو `interactive`)، و`project_id` من ملف `pyproject.toml` عند ضبطه، ونطاقًا تقريبيًا لحجم الجهاز (واحد من `1-2` أو `3-4` أو `5-8` أو `9-16` أو `17-32` أو `33+` أو `unknown`). النطاق مجال وليس العدد الدقيق للأنوية أبدًا — العدد الدقيق اختياري فقط، ضمن «معلومات البيئة» أدناه. تأتي فئة الحجم من عدد أنوية المضيف؛ ويتحقق اكتشاف المساعد وموقع التشغيل فقط مما إذا كانت متغيرات البيئة المعروفة مضبوطة، ولا يقرأ قيمها أبدًا. لا بيانات شخصية. |
| نعم | إشارات دورة حياة التدفق | تشمل: بدء التدفق، وما إذا اكتمل أو فشل، وما إذا فشلت إحدى طرقه، وما إذا توقف مؤقتًا لانتظار إدخال أو ملاحظات بشرية، وما إذا كان البدء تشغيلًا مستأنفًا، وما إذا فشل دور محادثة، ومدة تشغيل التدفق، وما إذا كان التدفق مما تشغّله CrewAI داخليًا أو مما كتبته أنت. ويُسجَّل اسم التدفق، كما هو الحال بالفعل لإنشاء التدفق وتنفيذه. وعند فشل تدفق أو إحدى طرقه، يُسجَّل **اسم فئة** الاستثناء (مثل `TimeoutError`) لتشخيص الأعطال — ولا تُسجَّل أبدًا رسالة الخطأ، التي قد تحتوي على مطالبات أو مخرجات النموذج أو مسارات ملفات أو بيانات اعتماد. ولا تُسجَّل أبدًا أسماء الطرق أو حالة التدفق. لا توجد بيانات شخصية. |
| نعم | إشارة مشاركة التتبع | تشمل: نجاح مشاركة دفعة من عمليات التتبع مع CrewAI AMP، وما إذا تمت المشاركة بشكل مجهول (قبل إنشاء حساب) أو مرتبطة بحسابك. ومثل كل span، تحمل أيضًا سمات بيئة التنفيذ الموضحة أعلاه (`project_id` عند تكوينه، ومساعد البرمجة، وبيئة التشغيل). يصف هذا الصف بيانات القياس عن بُعد الخاصة بالمشاركة فقط — وليس محتويات التتبع أو الوصول الذي تمنحه روابط التتبع المشتركة. لا تُسجَّل محتويات التتبع أو المدخلات أو المخرجات في هذه الإشارة. قبل مشاركة التتبعات، راجع الأسرار والبيانات الشخصية وإعدادات التنقيح والاحتفاظ في AMP. |
| لا | بيانات الوكيل الموسّعة | تشمل: وصف الهدف، نص الخلفية، معرّف ملف موجهات i18n. يجب على المستخدمين التأكد من عدم تضمين معلومات شخصية في حقول النص. |
| لا | معلومات المهمة التفصيلية | تشمل: وصف المهمة، وصف المخرجات المتوقعة، مراجع السياق. يجب على المستخدمين التأكد من عدم تضمين معلومات شخصية في هذه الحقول. |
| لا | معلومات البيئة | تشمل: المنصة، الإصدار، النظام، الإصدار، وعدد وحدات المعالجة المركزية. مثال: 'Windows 10'، 'x86_64'. لا بيانات شخصية. |

View File

@@ -50,16 +50,15 @@ mode: "wide"
- **سلامة الذكاء الاصطناعي**: تنفيذ فحوصات الإشراف على المحتوى والسلامة
```python
from crewai_tools import DallETool, VisionTool, CodeInterpreterTool
from crewai_tools import DallETool, VisionTool
# Create AI tools
image_generator = DallETool()
vision_processor = VisionTool()
code_executor = CodeInterpreterTool()
# Add to your agent
agent = Agent(
role="AI Specialist",
tools=[image_generator, vision_processor, code_executor],
tools=[image_generator, vision_processor],
goal="Create and analyze content using AI capabilities"
)

View File

@@ -460,7 +460,7 @@ rag_tool = RagTool(config=config, summarize=True)
**خيارات الإعداد:**
- `model_name` (str): معرّف نموذج HuggingFace. القيمة الافتراضية: `hkunlp/instructor-base`. الخيارات: `hkunlp/instructor-xl`، `hkunlp/instructor-large`، `hkunlp/instructor-base`
- `device` (str): الجهاز للتشغيل. القيمة الافتراضية: `cpu`. الخيارات: `cpu`، `cuda`، `mps`
- `device` (str): الجهاز للتشغيل. القيمة الافتراضية: `cpu`. الخيارات: `cpu`، `cuda`، `mps`، `xpu`
- `instruction` (str): بادئة التعليمات للتضمينات
**متغيرات البيئة:**
@@ -485,7 +485,7 @@ rag_tool = RagTool(config=config, summarize=True)
**خيارات الإعداد:**
- `model_name` (str): اسم نموذج Sentence Transformers. القيمة الافتراضية: `all-MiniLM-L6-v2`. الخيارات: `all-mpnet-base-v2`، `all-MiniLM-L6-v2`، `paraphrase-multilingual-MiniLM-L12-v2`
- `device` (str): الجهاز للتشغيل. القيمة الافتراضية: `cpu`. الخيارات: `cpu`، `cuda`، `mps`
- `device` (str): الجهاز للتشغيل. القيمة الافتراضية: `cpu`. الخيارات: `cpu`، `cuda`، `mps`، `xpu`
- `normalize_embeddings` (bool): ما إذا كان يتم تطبيع التضمينات. القيمة الافتراضية: `False`
**متغيرات البيئة:**

View File

@@ -12,6 +12,16 @@ mode: "wide"
تُستخدم هذه الأداة لاستخراج النص من الصور. عند تمريرها إلى الوكيل، ستستخرج النص من الصورة ثم تستخدمه لتوليد استجابة أو تقرير أو أي مخرج آخر.
يجب تمرير عنوان URL أو مسار الصورة إلى الوكيل.
يمكنك أيضًا طرح استعلام `query` مخصص حول الصورة واختيار مستوى تعقيد `complexity_level` يقوم تلقائيًا باختيار النموذج الأنسب للطلب:
| مستوى التعقيد | النموذج |
| :--------------- | :------------ |
| `easy` | `gpt-5.6-luna` |
| `medium` (افتراضي) | `gpt-5.6-terra` |
| `hard` | `gpt-5.6-sol` |
عند تمرير `llm` أو `model` بشكل صريح إلى الأداة، فإنه يأخذ الأولوية على اختيار النموذج المستند إلى مستوى التعقيد.
## التثبيت
ثبّت حزمة crewai_tools
@@ -43,8 +53,10 @@ def researcher(self) -> Agent:
## المعاملات
تتطلب VisionTool المعاملات التالية:
تقبل VisionTool المعاملات التالية:
| المعامل | النوع | الوصف |
| :----------------- | :------- | :------------------------------------------------------------------------------- |
| **image_path_url** | `string` | **إلزامي**. مسار ملف الصورة المراد استخراج النص منها. |
| **image_path_url** | `string` | **إلزامي**. مسار ملف الصورة (أو عنوان URL) المراد استخراج النص منها. |
| **query** | `string` | **اختياري**. السؤال أو التعليمات المراد طرحها على النموذج حول الصورة. القيمة الافتراضية هي `"What's in this image?"`. |
| **complexity_level** | `string` | **اختياري**. مستوى تعقيد الطلب، والذي يحدد النموذج: `easy` أو `medium` أو `hard`. القيمة الافتراضية هي `medium`. |

View File

@@ -4,7 +4,7 @@ description: >
تتيح أدوات استخراج Oxylabs الوصول بسهولة إلى المعلومات من المصادر المعنية. يرجى الاطلاع على قائمة المصادر المتاحة أدناه:
- `Amazon Product`
- `Amazon Search`
- `Google Seach`
- `Google Search`
- `Universal`
icon: globe
mode: "wide"
@@ -87,7 +87,7 @@ print(result)
### المعاملات
- `query` - مصطلح بحث Amazon.
- `domain` - توطين النطاق لـ Bestbuy.
- `domain` - توطين النطاق لـ Amazon.
- `start_page` - رقم صفحة البداية.
- `pages` - عدد الصفحات المراد استرجاعها.
- `geo_location` - موقع _التوصيل إلى_.

View File

@@ -9,7 +9,7 @@ mode: "wide"
## الوصف
أداة `ScrapeElementFromWebsiteTool` مصممة لاستخراج عناصر محددة من المواقع باستخدام محددات CSS. تسمح هذه الأداة لوكلاء CrewAI باستخراج محتوى مستهدف من صفحات الويب، مما يجعلها مفيدة لمهام استخراج البيانات حيث تكون أجزاء محددة فقط من صفحة الويب مطلوبة.
أداة `ScrapeElementFromWebsiteTool` مصممة لاستخراج عناصر محددة من المواقع باستخدام محددات CSS. تسمح هذه الأداة لوكلاء CrewAI باستخراج محتوى مستهدف من صفحات الويب، مما يجعلها مفيدة لمهام استخراج البيانات حيث تكون أجزاء محددة فقط من صفحة الويب مطلوبة. تمر الطلبات عبر مساعد HTTP الآمن ضد SSRF في CrewAI: يتم فحص عنوان URL المطلوب وكل قفزة إعادة توجيه مقابل النطاقات الخاصة والمحجوزة (بما في ذلك بيانات تعريف السحابة)، ويُثبَّت اتصال TCP على عنوان IP الذي اجتاز هذا الفحص.
## التثبيت

View File

@@ -16,6 +16,8 @@ mode: "wide"
أداة مصممة لاستخراج وقراءة محتوى موقع محدد. قادرة على التعامل مع أنواع مختلفة من صفحات الويب عن طريق إجراء طلبات HTTP وتحليل محتوى HTML المستلم.
يمكن أن تكون هذه الأداة مفيدة بشكل خاص لمهام استخراج البيانات من الويب وجمع البيانات أو استخراج معلومات محددة من المواقع.
تمر الطلبات عبر مساعد HTTP الآمن ضد SSRF في CrewAI: يتم فحص عنوان URL المطلوب وكل قفزة إعادة توجيه مقابل النطاقات الخاصة والمحجوزة (بما في ذلك بيانات تعريف السحابة)، ويُثبَّت اتصال TCP على عنوان IP الذي اجتاز هذا الفحص.
## التثبيت
ثبّت حزمة crewai_tools

View File

@@ -4,6 +4,322 @@ description: "Product updates, improvements, and bug fixes for CrewAI"
icon: "clock"
mode: "wide"
---
<Update label="Sep 09, 2026">
## v1.15.21
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.21)
## What's Changed
### Features
- Add telemetry to track checkpoint runtime and CLI usage.
### Bug Fixes
- Fix gateway errors reported inside an HTTP 200 response.
- Keep deploy push on the AMP create source.
- Report scrape failures instead of raising IndexError in the Oxylabs integration.
- Route all DashScope models through the native provider.
- Persist JSON checkpoints as UTF-8.
- Drop stray $ in f-string search URLs for BrightData.
- Support list-form type arrays in JSON schema conversion.
- Correct gpt-4o-mini context window from 200000 to 128000.
- Preserve streaming tool call arguments at contentBlockStop.
- Make pre-commit hooks portable on Windows.
### Documentation
- Clarify that tracing is managed separately from telemetry.
- Fix parallel search reference link.
- Remove stale parameters from handle_llm_stream_chunk docstring.
- Fix streaming output docstring examples.
- Use organization UUIDs in the skill install reference.
## Contributors
@Alphaxiaoteng, @DrewWhittleNZ, @Ghraven, @Shxiao101, @Vaishnavi220506, @Vidit-Ostwal, @danielfsbarreto, @georgeatparallel, @github-actions[bot], @jessemiller, @joaomdmoura, @kimnamu, @kiwoongyoon, @liang0417, @lorenzejay, @oxy-giedrius, @simpleqt, @uoparaji
</Update>
<Update label="Sep 04, 2026">
## v1.15.20
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.20)
## What's Changed
### Bug Fixes
- Fix legacy platform tool alias discovery
### Documentation
- Update snapshot and changelog for v1.15.19
## Contributors
@joaomdmoura, @vinibrsl
</Update>
<Update label="Sep 04, 2026">
## v1.15.19
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.19)
## What's Changed
### Features
- Add Clipper integrations client
- Add `now()` to the CEL expression environment
- Record how a crew run ended for every user
- Report machine size as a coarse band, not a core count
- Add injectable client for CrewAI platform tools
### Bug Fixes
- Fix reading of octet-stream and xlsx URLs in `urlreadtool`
- Fix appending trailing user turn in native Gemini provider
- Normalize scheme and port in Ollama base URL
- Preserve reusable scope configs in memory
- Bump `pypdf` to 6.16.2 for security vulnerability
- Bump `nltk` to 3.10.3 for security vulnerability
- Fix native structured outputs for current Claude models and Snowflake CVE floor
- Run model call hooks on every path and propagate a deny
### Documentation
- Remove `CodeInterpreterTool` from AI/ML overview examples
- Point `prompt-template` link at its current path
- Update channels guide to current CopilotKit channels API
- Refresh retired Gemini model IDs
## Contributors
@Vidit-Ostwal, @a-yeyang, @github-actions[bot], @hvlcrs, @joaomdmoura, @kikifrost, @lorenzejay, @lucasgomide, @parthiban-sivakumar, @ranst91, @tandede, @thiagomoretto, @vinibrsl
</Update>
<Update label="Aug 27, 2026">
## v1.15.18
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.18)
## What's Changed
### Features
- Promote conversational flows to stable
- Record a created deployment with the given UUID
- Enhance conversational flow documentation and APIs
- Let a declaration name the router's response format
- Let a chat flow declare its own state shape
- Accept crew-style LLM config in a conversational declaration
- Report project creation with the minted ID
- Record whether a run had inputs, without recording the inputs
- Backfill project ID from every user-invoked project command
### Bug Fixes
- Preserve tool results when the final answer is empty
- Map default Claude Sonnet 4.6 to its 1M context window
- Raise Anthropic default max_tokens for large tool calls
- Render message content parts as text, not as a Python repr
- Keep message roles when Agent.kickoff gets a conversation
- Skip interception hooks on crewai-internal flows
- Record task failures as failures, not successes
- Emit the flow lifecycle on a suppressed resume
- Open the conversational TUI for a declarative chat flow
- Record crew_memory as a string, not a bool
- Always emit project_id so absent and empty stay distinct
### Documentation
- Clarify Arize Phoenix observability docs
## Contributors
@Vidit-Ostwal, @arizedatngo, @joaomdmoura, @lorenzejay, @lucasgomide
</Update>
<Update label="Aug 19, 2026">
## v1.15.17
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.17)
## What's Changed
### Features
- Add declarative conversational flows documentation
- Synthesize built-in conversational methods for declarations
- Enable declarations to drive conversational mode
- Make conversational opt-in unmistakable
- Carry the AMP slug on tools resolved from a slug reference
- Handle oversized single messages during chunking
### Bug Fixes
- Fix usage of the URL hostname as MCP HTTP and SSE server_name
- Close the agent scope on every failed attempt
- Attribute tool errors to the tool that failed
- Pin SSRF checks to each redirect hop and peer IP
- Resolve issues with native tool calls broken over OpenAI Responses API
### Documentation
- Update documentation with a snapshot and changelog for v1.15.16
## Contributors
@Copilot, @Vidit-Ostwal, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="Aug 13, 2026">
## v1.15.16
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.16)
## What's Changed
### Features
- Introduce execution context management with UUID support
- Record what kind of exception ended a flow
- Record when a trace batch is shared with AMP
- Count deployments from any origin and record where they started
### Bug Fixes
- Record the running release on every emitted span
- Fix MySQL search table name validation
- Stop a failed turn from marking the next one as failed
### Documentation
- Add Frontend guides for CopilotKit and AG-UI
## Contributors
@joaomdmoura, @lorenzejay, @ranst91, @theCyberTech
</Update>
<Update label="Aug 11, 2026">
## v1.15.15
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.15)
## What's Changed
### Features
- Report flow outcome, duration, and human-in-the-loop signals.
### Bug Fixes
- Emit FlowStartedEvent when a boundary hook aborts the flow.
- Scope span export to our own tracer provider.
- Bump torch to version 2.13.0 to address security vulnerability.
- Bump gitpython to version 3.1.58 in crewai-tools[github].
### Refactoring
- Update date injection functionality in agents.
- Standardize CLI flags to kebab-case.
### Documentation
- Snapshot and changelog for v1.15.14.
## Contributors
@Vidit-Ostwal, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="Aug 08, 2026">
## v1.15.14
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.14)
## What's Changed
### Features
- Split runtime context from coding agent and add project ID
### Documentation
- Update snapshot and changelog for v1.15.13
## Contributors
@joaomdmoura
</Update>
<Update label="Aug 07, 2026">
## v1.15.13
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.13)
## What's Changed
### Bug Fixes
- Fix preservation of provider on LiteLLM-routed models.
- Harden brittle LLM event-bus mocks.
- Fix underreporting of Anthropic cache token usage.
- Bump h2 to version 4.4.1 to address security vulnerability GHSA-6hr6-w5qg-qmwg.
### Documentation
- Add DOCS_TRANSLATIONS workflow for locale synchronization.
- Fix broken README links, table of contents, and contribution guidance.
- Snapshot and changelog for version 1.15.12.
## Contributors
@Vidit-Ostwal, @joaomdmoura, @lucasgomide, @theCyberTech
</Update>
<Update label="Aug 05, 2026">
## v1.15.12
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.12)
## What's Changed
### Features
- Bump Flow canary on release
- Add URLReadTool for reading arbitrary URLs
- Add app metadata to platform action tools
- Unify scaffolding under `crewai create <resource>`
### Bug Fixes
- Clarify conversational route/handler name collision errors
### Documentation
- Update scaffold AGENTS.md for unified create CLI
### Breaking Changes
- None
## Contributors
@Vidit-Ostwal, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="Aug 04, 2026">
## v1.15.11
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.11)
## What's Changed
### Features
- Track interception-hook dispatches in telemetry
- Add project_id to link OSS usage to an enterprise account
- Surface AMP in AGENTS.md and detect coding agents in telemetry
- Add IBM Db2 search tool
### Bug Fixes
- Clear CodeQL incomplete URL substring sanitization alerts
- Bump aiohttp and cryptography to clear six GHSA advisories
- Report the real CEL error for failures inside map literals
- Correctly skip code CI for docs-only PRs
### Documentation
- Snapshot and changelog for v1.15.10
## Contributors
@PawanThakurIBM, @Vidit-Ostwal, @gabemilani, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="Jul 31, 2026">
## v1.15.10

View File

@@ -61,7 +61,7 @@ The Visual Agent Builder enables:
| **Respect Context Window** _(optional)_ | `respect_context_window` | `bool` | Keep messages under context window size by summarizing. Default is True. |
| **Code Execution Mode** _(optional)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | Mode for code execution: 'safe' (using Docker) or 'unsafe' (direct). Default is 'safe'. |
| **Multimodal** _(optional)_ | `multimodal` | `bool` | Whether the agent supports multimodal capabilities. Default is False. |
| **Inject Date** _(optional)_ | `inject_date` | `bool` | Whether to automatically inject the current date into tasks. Default is False. |
| **Inject Date** _(optional)_ | `inject_date` | `bool` | Whether to automatically inject the current date into the agent's prompt. Default is False. |
| **Date Format** _(optional)_ | `date_format` | `str` | Format string for date when inject_date is enabled. Default is "%Y-%m-%d" (ISO format). |
| **Reasoning** _(optional)_ | `reasoning` | `bool` | Whether the agent should reflect and create a plan before executing a task. Default is False. |
| **Max Reasoning Attempts** _(optional)_ | `max_reasoning_attempts` | `Optional[int]` | Maximum number of reasoning attempts before executing the task. If None, will try until ready. |
@@ -236,7 +236,7 @@ strategic_agent = Agent(
role="Market Analyst",
goal="Track market movements with precise date references and strategic planning",
backstory="Expert in time-sensitive financial analysis and strategic reporting",
inject_date=True, # Automatically inject current date into tasks
inject_date=True, # Automatically inject current date into the prompt
date_format="%B %d, %Y", # Format as "May 21, 2025"
reasoning=True, # Enable strategic planning
max_reasoning_attempts=2, # Limit planning iterations
@@ -303,7 +303,7 @@ multimodal_agent = Agent(
- `multimodal`: Enable multimodal capabilities for processing text and visual content
- `reasoning`: Enable agent to reflect and create plans before executing tasks
- `inject_date`: Automatically inject current date into task descriptions
- `inject_date`: Automatically inject current date into the agents prompt
#### Templates
@@ -623,6 +623,12 @@ messages = [
result = researcher.kickoff(messages)
```
The last `user` message is the request the agent answers. Every other message
keeps its role and its position around that request, so a conversation that
ends in assistant or tool messages still asks the user's question and still
delivers those trailing turns after it. With no `user` message at all, the last
message is treated as the request.
### Async Support
An asynchronous version is available via `kickoff_async()` with the same parameters:

View File

@@ -36,24 +36,83 @@ crewai [COMMAND] [OPTIONS] [ARGUMENTS]
### 1. Create
Create a new crew or flow.
Create a new crew, flow, tool, skill, or template project.
```shell Terminal
crewai create [OPTIONS] TYPE NAME
```
- `TYPE`: Choose between "crew" or "flow"
- `NAME`: Name of the crew or flow
- `TYPE`: `crew`, `flow`, `tool`, `skill`, or `template`
- `NAME`: Name of the project, tool handle, skill, or template
Example:
#### Crew
```shell Terminal
crewai create crew my_new_crew
crewai create flow my_new_flow
crewai create crew my_new_crew --classic
```
By default, `crewai create crew` creates a JSON-first crew project with `crew.jsonc` and `agents/*.jsonc`. Use `crewai create crew my_new_crew --classic` only when you want the older Python/YAML scaffold with `crew.py`, `config/agents.yaml`, and `config/tasks.yaml`.
#### Flow
```shell Terminal
crewai create flow my_new_flow
crewai create flow my_new_flow --declarative
```
#### Tool
Scaffold a custom tool repository:
```shell Terminal
crewai create tool my_tool
```
#### Skill
Scaffold an agent skill. Inside a crew project (where `pyproject.toml` exists), the skill is created under `./skills/`:
```shell Terminal
crewai create skill my-skill
crewai create skill my-skill --no-project
```
Use `--no-project` to create the skill in the current directory instead of `./skills/`.
#### Template
Add a remote project template to the current directory:
```shell Terminal
crewai create template my-template
crewai create template my-template --output-dir custom_dir
```
Use `--output-dir` to override the output folder name (defaults to the template name).
#### Deprecated create aliases
These older commands still work but print a yellow deprecation warning. Prefer the `crewai create <type>` forms above.
| Deprecated | Use instead |
| :--- | :--- |
| `crewai tool create <handle>` | `crewai create tool <handle>` |
| `crewai skill create <name>` | `crewai create skill <name>` |
| `crewai template add <name>` | `crewai create template <name>` |
Lifecycle commands are unchanged — for example `crewai tool install`, `crewai skill publish`, and `crewai template list` stay under their resource groups.
#### Deprecated flag aliases
These older snake_case flags still work but are hidden from `--help`. Prefer the kebab-case forms documented in each command section below.
| Deprecated | Use instead |
| :--- | :--- |
| `--skip_provider` (on `crewai create crew`) | `--skip-provider` |
| `--n_iterations` (on `crewai train`, `crewai test`) | `--n-iterations` |
| `--task_id` (on `crewai replay`) | `--task-id` |
### 2. Version
Show the installed version of CrewAI.
@@ -79,7 +138,7 @@ Train the crew for a specified number of iterations.
crewai train [OPTIONS]
```
- `-n, --n_iterations INTEGER`: Number of iterations to train the crew (default: 5)
- `-n, --n-iterations INTEGER`: Number of iterations to train the crew (default: 5)
- `-f, --filename TEXT`: Path to a custom file for training (default: "trained_agents_data.pkl")
Example:
@@ -96,7 +155,7 @@ Replay the crew execution from a specific task.
crewai replay [OPTIONS]
```
- `-t, --task_id TEXT`: Replay the crew from this task ID, including all subsequent tasks
- `-t, --task-id TEXT`: Replay the crew from this task ID, including all subsequent tasks
Example:
@@ -143,7 +202,7 @@ Test the crew and evaluate the results.
crewai test [OPTIONS]
```
- `-n, --n_iterations INTEGER`: Number of iterations to test the crew (default: 3)
- `-n, --n-iterations INTEGER`: Number of iterations to test the crew (default: 3)
- `-m, --model TEXT`: LLM Model to run the tests on the Crew (default: "gpt-4o-mini")
Example:
@@ -279,6 +338,7 @@ crewai org switch <organization_id>
- Initiates the deployment process on the CrewAI AMP platform.
- Upon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID).
- Push keeps the source used at create. Adding a git `origin` later does not switch a ZIP deployment to git.
- **Deployment Status**: You can check the status of your deployment with:
@@ -519,6 +579,7 @@ Trace collection is controlled by checking three settings in priority order:
```
- Checked only if `tracing` is not set in code and `CREWAI_TRACING_ENABLED` is not set to `true`
- Running `crewai traces enable` is sufficient to enable tracing by itself
- The first-run prompt (`Would you like to view your execution traces?`) also updates this preference
<Note>
**To enable tracing**, use any one of these methods:

View File

@@ -37,7 +37,7 @@ A crew in crewAI represents a collaborative group of agents working together to
| **Chat LLM** _(optional)_ | `chat_llm` | The language model used to orchestrate `crewai chat` CLI interactions with the crew. Accepts a model name string or `LLM` instance. Defaults to `None`. |
| **Before Kickoff Callbacks** _(optional)_ | `before_kickoff_callbacks` | A list of callable functions executed **before** the crew starts. Each callback receives and can modify the inputs dict. Distinct from the `@before_kickoff` decorator. Defaults to `[]`. |
| **After Kickoff Callbacks** _(optional)_ | `after_kickoff_callbacks` | A list of callable functions executed **after** the crew finishes. Each callback receives and can modify the `CrewOutput`. Distinct from the `@after_kickoff` decorator. Defaults to `[]`. |
| **Tracing** _(optional)_ | `tracing` | Controls OpenTelemetry tracing for the crew. `True` = always enable, `False` = always disable, `None` = inherit from environment / user settings. Defaults to `None`. |
| **Tracing** _(optional)_ | `tracing` | Controls tracing for the crew. `True` = always enable, `False` = always disable, `None` = inherit from environment / user settings. Defaults to `None`. |
| **Skills** _(optional)_ | `skills` | A list of `Path` objects (skill search directories) or pre-loaded `Skill` objects applied to all agents in the crew. Defaults to `None`. |
| **Security Config** _(optional)_ | `security_config` | A `SecurityConfig` instance managing crew fingerprinting and identity. Defaults to `SecurityConfig()`. |
| **Checkpoint** _(optional)_ | `checkpoint` | Enables automatic checkpointing. Pass `True` for sensible defaults, a `CheckpointConfig` for full control, `False` to opt out, or `None` to inherit. See the [Checkpointing](#checkpointing) section below. Defaults to `None`. |
@@ -322,6 +322,8 @@ Caches can be employed to store the results of tools' execution, making the proc
After the crew execution, you can access the `usage_metrics` attribute to view the language model (LLM) usage metrics for all tasks executed by the crew. This provides insights into operational efficiency and areas for improvement.
`total_tokens` is the billed total (`prompt_tokens + completion_tokens`). Breakdown fields such as `cached_prompt_tokens` and `cache_creation_tokens` describe subsets already included in those totals and are not added on top of `total_tokens`. See the **UsageMetrics field semantics** section in the Flows concept documentation for the full contract.
```python Code
# Access the crew's usage metrics
crew = Crew(agents=[agent1, agent2], tasks=[task1, task2])

View File

@@ -267,7 +267,27 @@ print(flow.usage_metrics)
execution.
</Note>
Each entry in the returned [`UsageMetrics`](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/types/usage_metrics.py) is the sum across all LLM calls made within a single `flow.kickoff()` invocation. Counters reset on the next `kickoff()` call (or on each iteration of `kickoff_for_each`), so successive runs don't double-count. The property is safe to read at any point after `kickoff()` completes; reading it during execution returns the partial total accumulated so far.
### UsageMetrics field semantics
The returned [`UsageMetrics`](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/types/usage_metrics.py) object uses a provider-neutral contract:
| Field | Meaning |
| --- | --- |
| `total_tokens` | Billed total: `prompt_tokens + completion_tokens` |
| `prompt_tokens` | Full input/prompt tokens billed for the request |
| `completion_tokens` | Output/completion tokens billed for the request |
| `cached_prompt_tokens` | Cache-read subset of prompt tokens (breakdown only) |
| `cache_creation_tokens` | Cache-write subset of prompt tokens (breakdown only, Anthropic) |
| `reasoning_tokens` | Reasoning/thinking subset where the provider reports it separately (breakdown only) |
| `successful_requests` | Number of LLM calls aggregated |
Breakdown fields such as `cached_prompt_tokens`, `cache_creation_tokens`, and
`reasoning_tokens` are **not** added on top of `total_tokens` — they describe
portions already included in `prompt_tokens` or `completion_tokens`.
For Anthropic, cache read and cache write counters are folded into `prompt_tokens`, so cached workloads are fully reflected in `total_tokens`. OpenAI-style providers already include cached input inside `prompt_tokens`; CrewAI surfaces the cached portion separately for visibility.
Each entry in the returned `UsageMetrics` is the sum across all LLM calls made within a single `flow.kickoff()` invocation. Counters reset on the next `kickoff()` call (or on each iteration of `kickoff_for_each`), so successive runs don't double-count. The property is safe to read at any point after `kickoff()` completes; reading it during execution returns the partial total accumulated so far.
## Flow State Management

View File

@@ -636,6 +636,21 @@ agent = Agent(
}
}
)
# Option 4: Use OpenRouter embeddings (supports models across providers)
# Set OPENROUTER_API_KEY environment variable if api_key is omitted in config
crew = Crew(
agents=[agent],
tasks=[...],
knowledge_sources=[knowledge_source],
embedder={
"provider": "openrouter",
"config": {
"model_name": "openai/text-embedding-3-small",
"api_key": "your-openrouter-api-key" # Optional if OPENROUTER_API_KEY is set
}
}
)
```
#### Configuring Azure OpenAI Embeddings

View File

@@ -418,6 +418,27 @@ In this section, you'll find detailed examples that help you select, configure,
- Token usage tracking
- Multi-turn tool use conversations
**Token usage and prompt caching:**
Anthropic reports billed input in separate counters — `input_tokens` (uncached),
`cache_read_input_tokens`, and `cache_creation_input_tokens`. CrewAI folds all
three into `prompt_tokens` (and native `input_tokens` in provider responses) so
`total_tokens` reflects full billed usage on cached workloads.
`cached_prompt_tokens` records the cache-read portion as a breakdown only; it is
already included in `prompt_tokens` and must not be added again to
`total_tokens`. `cache_creation_tokens` records cache writes the same way.
```python Code
usage = llm.get_token_usage_summary()
# total_tokens == prompt_tokens + completion_tokens
# prompt_tokens includes cache read + cache write for Anthropic
```
See the **UsageMetrics field semantics** section in the Flows concept
documentation for the provider-neutral contract used by `crew.usage_metrics`
and `flow.usage_metrics`.
**Important Notes:**
- `max_tokens` is a **required** parameter for all Anthropic models
- Claude uses `stop_sequences` instead of `stop`
@@ -1466,6 +1487,38 @@ llm = LLM(
llm = LLM(model="gpt-4")
```
</Tab>
<Tab title="Gateway Errors">
<Tip>
Gateways such as OpenRouter return `200 OK` as soon as the upstream provider accepts the request, so a provider timeout arrives in the response body instead of the status code.
</Tip>
CrewAI raises the same exception the upstream code would have produced as a real HTTP status, so a masked failure is caught by the retry handling you already have:
```python
import openai
from pydantic import BaseModel
from crewai import LLM
class Report(BaseModel):
summary: str
llm = LLM(model="openrouter/z-ai/glm-5.3", response_format=Report)
try:
result = llm.call("Summarize the incident", response_model=Report)
except openai.InternalServerError as e:
# "z-ai/glm-5.3 via openrouter.ai returned HTTP 200 with an upstream error
# and no choices: The operation was aborted (upstream code 504)"
print(f"Upstream provider failed, safe to retry: {e}")
```
<Warning>
A large or deeply nested `response_model` makes upstream timeouts more likely. Treat these as transient provider failures, not as the model producing malformed structured output.
</Warning>
</Tab>
<Tab title="Context Length">
<Tip>
Use larger context models for extensive tasks

View File

@@ -740,7 +740,7 @@ memory = Memory(llm="anthropic/claude-3-haiku-20240307")
memory = Memory(llm="ollama/llama3.2")
# Use Google Gemini
memory = Memory(llm="gemini/gemini-2.0-flash")
memory = Memory(llm="gemini/gemini-3.7-flash")
# Pass a pre-configured LLM instance with custom settings
llm = LLM(model="gpt-4o", temperature=0)

View File

@@ -32,10 +32,10 @@ You often need **both**: skills for expertise, tools for action. They are config
The CLI is the supported way to create a skill — it scaffolds the directory layout and a valid `SKILL.md` for you:
```shell Terminal
crewai skill create code-review
crewai create skill code-review
```
Inside a crew project (where `pyproject.toml` lives) this creates `./skills/code-review/`; outside a project it creates `./code-review/` in the current directory (you can force that behavior with `--no-project`):
Inside a crew project (where `pyproject.toml` lives) this creates `./skills/code-review/`; outside a project it creates `./code-review/` in the current directory (you can force that behavior with `--no-project` on `crewai create skill`):
```
skills/
@@ -178,12 +178,16 @@ agent = Agent(
## Creating, Publishing, and Installing Skills
Skills have a full lifecycle managed by the CLI: **create them with `crewai skill create`, publish them with `crewai skill publish`** — hand-rolling directories works for local experiments, but the CLI is the intended workflow and keeps your skill layout and frontmatter valid.
Skills have a full lifecycle managed by the CLI: **create them with `crewai create skill`, publish them with `crewai skill publish`** — hand-rolling directories works for local experiments, but the CLI is the intended workflow and keeps your skill layout and frontmatter valid.
<Note>
`crewai skill create` is deprecated and still works with a warning. Use `crewai create skill` instead.
</Note>
### Create
```shell Terminal
crewai skill create my-skill
crewai create skill my-skill
```
Scaffolds the directory (into `./skills/` inside a crew project) with a template `SKILL.md`, plus empty `scripts/`, `references/`, and `assets/` directories. Edit `SKILL.md` to define the instructions.
@@ -206,13 +210,17 @@ Publishing reads `name`, `description`, and `metadata.version` from the `SKILL.m
### Install
Install a published skill by its `@org/name` reference:
Install a published skill by its `@org-uuid/name` reference:
```shell Terminal
crewai skill install @acme/code-review
crewai skill install @your-org-uuid/code-review
```
Inside a crew project the skill lands in `./skills/{name}/`; outside a project it goes to the shared cache at `~/.crewai/skills/{org}/{name}/`.
<Note>
Use your organization's **UUID**, not its name — organization names are not unique, so a name can resolve to the wrong organization and the install fails with a "not found" error. Run `crewai org list` to see the UUID (the `ID` column) of every organization you belong to.
</Note>
Inside a crew project the skill lands in `./skills/{name}/`; outside a project it goes to the shared cache at `~/.crewai/skills/{org-uuid}/{name}/`.
Agents can also reference registry skills directly — they resolve from the local cache (or project `skills/` directory) at runtime:
@@ -221,7 +229,7 @@ agent = Agent(
role="Senior Code Reviewer",
goal="Review pull requests for quality and security issues",
backstory="Staff engineer with expertise in secure coding practices.",
skills=["@acme/code-review"], # registry ref, resolved locally
skills=["@your-org-uuid/code-review"], # registry ref, resolved locally
)
```
@@ -236,7 +244,7 @@ agent = Agent(
role="Senior Code Reviewer",
goal="Review pull requests for quality and security issues",
backstory="Staff engineer with expertise in secure coding practices.",
skills=["@acme/code-review@1.2.0"], # pinned; a leading "v" also works
skills=["@your-org-uuid/code-review@1.2.0"], # pinned; a leading "v" also works
)
```

View File

@@ -20,7 +20,7 @@ crewai test
If you want to run more iterations or use a different model, you can specify the parameters like this:
```bash
crewai test --n_iterations 5 --model gpt-4o
crewai test --n-iterations 5 --model gpt-4o
```
or using the short forms:
@@ -29,6 +29,11 @@ or using the short forms:
crewai test -n 5 -m gpt-4o
```
<Note>
The older `--n_iterations` flag still works but is deprecated and hidden from
`--help`. Use `--n-iterations` (or `-n`) instead.
</Note>
When you run the `crewai test` command, the crew will be executed for the specified number of iterations, and the performance metrics will be displayed at the end of the run.
A table of scores at the end will show the performance of the crew in terms of the following metrics:

View File

@@ -26,7 +26,7 @@ Under the hood, CrewAI employs a modular prompt system that you can customize ex
- **Error handling** Direct how agents respond to failures, exceptions, or timeouts.
- **Tool-specific prompts** Define detailed instructions for how tools are invoked or utilized.
Check out the [original prompt templates in CrewAI's repository](https://github.com/crewAIInc/crewAI/blob/main/src/crewai/translations/en.json) to see how these elements are organized. From there, you can override or adapt them as needed to unlock advanced behaviors.
Check out the [original prompt templates in CrewAI's repository](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/translations/en.json) to see how these elements are organized. From there, you can override or adapt them as needed to unlock advanced behaviors.
## Understanding Default System Instructions

View File

@@ -11,7 +11,7 @@ mode: "wide"
## Create a Project with the CLI
Use the CrewAI CLI to scaffold a project, then `AGENTS.md` will be automatically added at the root.
Use the CrewAI CLI to scaffold a project. `AGENTS.md` is added at the root, together with a `CLAUDE.md` and a `GEMINI.md` that import it, so Claude Code and Gemini CLI read the same guidance as every other assistant.
```bash
# Crew
@@ -21,9 +21,13 @@ crewai create crew my_crew
crewai create flow my_flow
# Tool repository
crewai tool create my_tool
crewai create tool my_tool
```
<Note>
`crewai tool create` is deprecated and still works with a warning. Use `crewai create tool` instead.
</Note>
## Tool Setup: Point Assistants to AGENTS.md
### Codex
@@ -32,24 +36,28 @@ Codex can be guided by `AGENTS.md` files placed in your repository. Use them to
### Claude Code
Claude Code stores project memory in `CLAUDE.md`. You can bootstrap it with `/init` and edit it using `/memory`. Claude Code also supports imports inside `CLAUDE.md`, so you can add a single line like `@AGENTS.md` to pull in the shared instructions without duplicating them.
Claude Code reads `CLAUDE.md` and ignores `AGENTS.md`. Scaffolded projects ship a `CLAUDE.md` whose only instruction is the import line `@AGENTS.md`, so the shared guidance is loaded without duplicating it. Add Claude-specific notes under that line and keep shared conventions in `AGENTS.md`.
You can simply use:
For a project created before `CLAUDE.md` was scaffolded, add the import yourself:
```bash
mv AGENTS.md CLAUDE.md
printf '@AGENTS.md\n' > CLAUDE.md
```
Do not rename `AGENTS.md` to `CLAUDE.md`: Codex and Cursor read `AGENTS.md`, and the rename hides it from them.
### Gemini CLI and Google Antigravity
Gemini CLI and Antigravity load a project context file (default: `GEMINI.md`) from the repo root and parent directories. You can configure it to read `AGENTS.md` instead (or in addition) by setting `context.fileName` in your Gemini CLI settings. For example, set it to `AGENTS.md` only, or include both `AGENTS.md` and `GEMINI.md` if you want to keep each tools format.
Gemini CLI and Antigravity load a project context file (default: `GEMINI.md`) from the repo root and parent directories. Scaffolded projects ship a `GEMINI.md` whose only instruction is the import line `@./AGENTS.md`, so the shared guidance is loaded without duplicating it. Add Gemini-specific notes under that line and keep shared conventions in `AGENTS.md`.
You can simply use:
For a project created before `GEMINI.md` was scaffolded, add the import yourself:
```bash
mv AGENTS.md GEMINI.md
printf '@./AGENTS.md\n' > GEMINI.md
```
Alternatively, set `context.fileName` in your Gemini CLI settings to include `AGENTS.md` and Gemini reads it directly. Do not rename `AGENTS.md` to `GEMINI.md`: Codex and Cursor read `AGENTS.md`, and the rename hides it from them.
### Cursor
Cursor supports `AGENTS.md` as a project instruction file. Place it at the project root to provide guidance for Cursors coding assistant.

View File

@@ -77,7 +77,7 @@ Replace the generated `agents/researcher.jsonc` file and add `agents/analyst.jso
}
```
Replace `provider/model-id` with the model you use, for example `openai/gpt-4o`, `anthropic/claude-sonnet-4-6`, or `gemini/gemini-2.0-flash-001`.
Replace `provider/model-id` with the model you use, for example `openai/gpt-4o`, `anthropic/claude-sonnet-4-6`, or `gemini/gemini-3.7-flash`.
## Step 3: Define Tasks and Crew Settings

View File

@@ -1,19 +1,19 @@
---
title: Conversational Flows
description: Build multi-turn chat apps with handle_turn per turn, message history, intent routing, tracing, and WebSocket bridges.
description: Build multi-turn chat apps with handle_turn per turn, message history, intent routing, tracing, and structured streaming.
icon: comments
mode: "wide"
---
## Overview
Conversational apps treat each user line as a **new flow run** with the **same session id**. CrewAI adds helpers for message history, optional intent routing, deferred tracing, UI bridges, and a local `flow.chat()` REPL for conversational flows.
Conversational apps treat each user line as a **new flow run** with the **same session id**. CrewAI adds helpers for message history, optional intent routing, deferred tracing, structured turn streaming, and a local `flow.chat()` REPL.
| Concept | Implementation |
|---------|----------------|
| Session id | `handle_turn(..., session_id=...)` → `kickoff(inputs={"id": ...})` → `state.id` |
| User line | `handle_turn(message)` appends to `state.messages` before the graph runs |
| Turn complete | `FlowFinished` for **this run** only; chat continues on the next `handle_turn` |
| Turn complete | `conversation_turn_completed`; with default trace deferral, `FlowFinished` waits for `finalize_session_traces()` |
| Full-session trace | `ConversationConfig(defer_trace_finalization=True)` + `finalize_session_traces()` |
## Turn APIs
@@ -30,7 +30,8 @@ Use **`flow.handle_turn(message, session_id=...)`** for every user message from
| `kickoff(inputs={...})` | Advanced flow execution without conversational turn handling |
| `ask()` | Blocking prompt **inside** one step (wizard, clarification) |
| `@human_feedback` | Approve/reject **a step output** — not the next chat line |
| `ChatSession.handle_turn(...)` | Transport layer over `handle_turn` (SSE / WebSocket) |
`handle_turn()`, `stream_turn()`, and `chat()` raise `ValueError` unless conversational mode is enabled. Applying `@ConversationConfig(...)` enables it automatically; otherwise set `conversational = True`.
## Quick start
@@ -39,7 +40,7 @@ from uuid import uuid4
from crewai import Flow
from crewai.flow import listen
from crewai.experimental.conversational import (
from crewai.flow import (
ConversationConfig,
ConversationState,
)
@@ -47,8 +48,6 @@ from crewai.experimental.conversational import (
@ConversationConfig(defer_trace_finalization=True)
class SupportFlow(Flow[ConversationState]):
conversational = True
def route_turn(self, context):
message = (self.state.current_user_message or "").lower()
if "order" in message:
@@ -96,12 +95,12 @@ stream = flow.stream_turn("Where is my order?", session_id=session_id)
with stream:
for frame in stream.events:
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
print(frame.data.get("chunk", ""), end="", flush=True)
print(frame.content, end="", flush=True)
result = stream.result
```
For the full frame contract, channel list, and async API, see [Streaming Runtime Contract](/edge/en/learn/streaming-runtime-contract).
For the full frame contract and channel list, see [Streaming Runtime Contract](/edge/en/learn/streaming-runtime-contract).
## Turn lifecycle
@@ -111,29 +110,18 @@ Each `handle_turn` runs this pipeline:
2. **State restore** — if `inputs["id"]` exists and `@persist` is configured, loads the latest snapshot.
3. **`FlowStarted`** — emitted on the first deferred session turn only.
4. **Pending turn hydration** — appends the user message to `state.messages`, sets `current_user_message` / `last_user_message`, and optionally classifies when `intents` / `default_intents` + `intent_llm` are set.
5. **Graph execution** — `conversation_start` → `route_conversation` → the selected `@listen` handler.
5. **Graph execution** — user-defined `@start` methods (if any) → `route_conversation` (the built-in start/router) → the selected `@listen` handler. `route_conversation` also calls the overridable `conversation_start()` helper.
6. **End of run** — per-turn `flow_finished` and trace finalization are **skipped** when deferral is enabled; nested `Agent.kickoff()` / crews do not close the parent batch either.
Handlers should call **`append_assistant_message(reply)`** so the next turns `conversation_messages` includes assistant text. The user line is already stored by `handle_turn` — do not append it again in handlers.
Handlers should call **`append_assistant_message(reply)`** when the visible reply is not the return value, or when you trim history. A public string return is also recorded as assistant and included in the `@persist` snapshot, so a fresh Flow instance restores it. The user line is already stored by `handle_turn` — do not append it again in handlers.
## `ConversationConfig` (class-level defaults)
## Configuration overview
Decorate your conversational `Flow` subclass with `ConversationConfig`.
| Field | Default | Purpose |
|-------|---------|---------|
| `system_prompt` | Framework default | System message used by the built-in `converse_turn`. |
| `llm` | `None` | Conversation LLM used by `converse_turn` and as router fallback. |
| `router` | `None` | `RouterConfig` for LLM-driven routing. |
| `intent_llm` | `None` | LLM for `intents=` / `default_intents` pre-classification. |
| `default_intents` | `None` | Outcome labels for pre-classification. |
| `defer_trace_finalization` | `True` | Keep one trace batch open across `handle_turn()` calls. |
Override pre-classification per turn with `handle_turn(..., intents=..., intent_llm=...)`.
Decorating a `Flow` subclass with `ConversationConfig` both attaches the chat defaults and enables conversational mode. See the [full field reference](#conversationconfig) below. Override pre-classification per turn with `handle_turn(..., intents=..., intent_llm=...)`.
## Lower-level `ChatState` helpers
`ChatState`, `ConversationalConfig`, and `crewai.flow.conversation` helpers are still importable for advanced orchestration, tests, or custom wrappers. They do not add `user_message=` or `session_id=` keyword arguments to `Flow.kickoff()`.
`ChatState`, the legacy `ConversationalConfig`, and `crewai.flow.conversation` helpers are still importable for advanced orchestration, tests, or custom wrappers. They are separate from the `ConversationState` / `ConversationConfig` API and do not add `user_message=` or `session_id=` keyword arguments to `Flow.kickoff()`.
```python
from crewai.flow import ChatState
@@ -155,6 +143,8 @@ class MyChatState(ChatState):
`ConversationalInputs` is a `TypedDict` for conventional `kickoff(inputs={...})` keys: `id`, `user_message`, `last_intent`.
`ConversationState` stores `messages` as `ConversationMessage` objects and additionally provides `current_user_message`, `ended`, `events`, and `agent_threads`. Use `conversation_messages` when passing its canonical history to an LLM.
## `Flow` conversational API
### `handle_turn` parameters
@@ -176,9 +166,9 @@ class MyChatState(ChatState):
| Attribute | Purpose |
|-----------|---------|
| `conversational` | Set to `True` to enable the conversational graph and `handle_turn()` |
| `defer_trace_finalization` | Instance flag; set automatically from config on `handle_turn()` |
| `suppress_flow_events` | Hides console flow panels; **tracing still records** method/flow events |
| `stream` | Enable streaming; use with `ChatSession.handle_turn(..., stream=True)` |
| `defer_trace_finalization` | Optional instance override. Otherwise `_should_defer_trace_finalization()` reads `ConversationConfig.defer_trace_finalization`. |
| `suppress_flow_events` | Hides console flow panels and suppresses method execution events; flow start/finish events still emit |
| `stream` | Generic Flow streaming flag. For conversational turns, use `stream_turn()` instead of combining this flag with `handle_turn()`. |
### Methods and properties
@@ -190,12 +180,12 @@ class MyChatState(ChatState):
| `classify_intent(text, outcomes, *, llm, context=None)` | Map text to one outcome (same collapse logic as `@human_feedback`) |
| `receive_user_message(text, *, outcomes=None, llm=None)` | Append user message; optionally set `last_intent` |
| `finalize_session_traces()` | Emit deferred `flow_finished` and finalize the session trace batch |
| `_should_defer_trace_finalization()` | Whether this flow defers per-turn trace finalization |
| `_should_defer_trace_finalization()` | Advanced/internal hook that resolves whether per-turn trace finalization is deferred |
| `input_history` | Audit trail of `ask()` prompts and responses |
### Module helpers (`crewai.flow.conversation`)
Importable for tests or custom orchestration:
Importable from `crewai.flow.conversation` for tests or custom orchestration. These helpers use the legacy `ConversationalConfig` shape; `prepare_conversational_turn()` also clears `last_intent`, unlike `handle_turn()`, which preserves it as router context.
| Function | Description |
|----------|-------------|
@@ -212,7 +202,7 @@ Importable for tests or custom orchestration:
### A. Pre-classify via `ConversationConfig` (simplest)
Set `default_intents` and `intent_llm`. Each `handle_turn()` runs classification before routing; read `self.state.last_intent` in `route_turn()`.
Set `default_intents` and `intent_llm`. Each `handle_turn()` pre-classifies the current message. A non-empty result returned by a custom `route_turn()` takes precedence; otherwise `route_conversation` uses the current turn's classified intent.
### B. Classify inside `route_turn` (richer prompts)
@@ -233,24 +223,15 @@ Use **`@listen("RESEARCH")`** (or similar) for steps that run `Agent.kickoff()`
## When the flow finishes but the user keeps chatting
`FlowFinished` means **this graph run** completed. The conversation continues with another `handle_turn()` and the same `session_id`. `@persist` restores `messages`, flags, and context.
Each `handle_turn()` completes one graph run, and the conversation continues with another `handle_turn()` using the same `session_id`. With the default deferred trace lifecycle, that run emits `conversation_turn_completed`, while `FlowFinished` is emitted once when `finalize_session_traces()` closes the session. `@persist` restores `messages`, flags, and context.
**Persist pattern:** prefer `@persist` on a **single terminal step** (for example `finalize`) rather than on the whole `Flow` class. Class-level persist saves after every method; `load_state` uses the latest row, which may be a mid-run snapshot (for example right after `bootstrap`) and miss handler updates from the same turn.
Do **not** use `@human_feedback` for follow-up chat lines unless a human must approve a specific step output before it is shown.
## Conversational `Flow` (experimental)
## Conversational `Flow`
<Warning>
**This is an experimental feature.** The conversational `Flow` surface
(`conversational = True`, `handle_turn`, `ConversationConfig`,
`RouterConfig`, `ConversationState`, the built-in graph + helpers) lives
under `crewai.experimental` and may change shape before it graduates.
Pin your CrewAI version if you depend on specific behavior, and watch the
changelog for breaking updates. Open issues / feedback welcome.
</Warning>
Opt into the conversational chat graph by setting `conversational = True` on a `Flow` subclass. The base `Flow` then ships a built-in `@start` / `@router` / `converse_turn` / `end_conversation` graph, manages `state.messages`, can drive a router LLM, and keeps the trace batch open across turns. You write the **custom routes**; the framework owns the rest.
Opt into the conversational chat graph by setting `conversational = True` on a `Flow` subclass or applying `@ConversationConfig(...)`. The base `Flow` then supplies `route_conversation` as the built-in start/router plus the `converse_turn` and `end_conversation` listeners. The deprecated `answer_from_history_turn` listener remains available for compatibility. The framework manages `state.messages`, can drive a router LLM, and keeps the trace batch open across turns. You write the **custom routes**; the framework owns the rest.
Use this when you want a multi-turn chat with a router and per-route handlers without wiring the lifecycle yourself. Use `Flow[ChatState]` (the lower-level pattern above) when you need full control.
@@ -259,7 +240,7 @@ Use this when you want a multi-turn chat with a router and per-route handlers wi
```python
from crewai import Flow
from crewai.flow import listen
from crewai.experimental.conversational import (
from crewai.flow import (
ConversationConfig,
ConversationState,
)
@@ -267,8 +248,6 @@ from crewai.experimental.conversational import (
@ConversationConfig(defer_trace_finalization=True)
class SupportFlow(Flow[ConversationState]):
conversational = True
def route_turn(self, context: dict) -> str | None:
message = (self.state.current_user_message or "").lower()
if "search" in message or "news" in message:
@@ -318,14 +297,26 @@ Class decorator that attaches per-class chat defaults.
|-------|---------|---------|
| `system_prompt` | `slices.conversational_system_prompt` from i18n | System message used by the built-in `converse_turn`. Pass `""` to opt out entirely. |
| `llm` | `None` | Conversation LLM (used by `converse_turn` and as router fallback). |
| `router` | `None` | `RouterConfig` for LLM-driven routing. Without it, the flow always falls through to `converse`. |
| `answer_from_history_prompt` | Framework default | System message for the optional `answer_from_history` route. |
| `answer_from_history_llm` | `None` | Enables the `answer_from_history` short-circuit when set. |
| `router` | `None` | Optional `RouterConfig` overrides. With custom listeners and a resolvable LLM, routing auto-enables even when this is omitted. |
| `answer_from_history_prompt` | Framework default | **Deprecated.** Use the `converse` system prompt or override `converse_turn()`. |
| `answer_from_history_llm` | `None` | **Deprecated.** Use `llm`; `converse` already receives canonical history. |
| `intent_llm` | `None` | LLM for legacy `intents=`/`default_intents` pre-classification. |
| `default_intents` | `None` | Outcome labels for legacy pre-classification. |
| `visible_agent_outputs` | `None` | `"all"`, or a list of agent names whose `append_agent_result()` calls should be promoted to public assistant messages. |
| `defer_trace_finalization` | `True` | Keep one trace batch open across `handle_turn()` calls. |
<Warning>
`answer_from_history_prompt`, `answer_from_history_llm`, and the
`answer_from_history` route are deprecated and will be removed in a future
release. They duplicate `converse`, add an eligibility LLM call, and are
bypassed when the normal auto-router returns a route. Existing configurations
continue to work and emit `DeprecationWarning`.
</Warning>
With no custom routes, turns fall through to `converse`. With custom routes and a conversation/router LLM, the framework synthesizes a default `RouterConfig`; provide one explicitly only to customize its prompt, route list, descriptions, or fallback behavior. Setting `default_intents` uses the legacy pre-classification path instead.
If no conversation LLM is configured, the built-in `converse_turn` returns a configuration placeholder rather than generating an answer.
### `RouterConfig` and the auto-built route catalog
```python
@@ -334,7 +325,7 @@ from typing import Literal
from pydantic import BaseModel
from crewai import LLM
from crewai.experimental.conversational import RouterConfig
from crewai.flow import RouterConfig
class MyRoute(BaseModel):
@@ -360,9 +351,10 @@ router_config = RouterConfig(
The router prompt that gets sent to the LLM is built automatically. For each route the framework picks a description with this precedence:
1. `RouterConfig.route_descriptions[label]` — explicit override.
2. `Flow.builtin_route_descriptions[label]` — framework-canned text for `converse`, `end`, `answer_from_history` (phrased for the router LLM).
3. First non-empty line of the `@listen(label)` handler's docstring.
4. Empty (the route is listed without a description).
2. `Flow.builtin_route_descriptions[label]` — framework-canned text for `converse`, `end`, and the deprecated `answer_from_history` compatibility route (phrased for the router LLM).
3. The method's declared `description` (used by declarative flows and DSL projections).
4. First non-empty line of the `@listen(label)` handler's docstring.
5. Empty (the route is listed without a description).
So in practice, **adding a new route is `@listen("X")` + a one-line docstring**:
@@ -376,6 +368,27 @@ def handle_internet_search(self) -> str:
...
```
### Naming handlers
The string in `@listen("…")` is a **router route label** (an event name), not the Python method name. Route labels and method completion events share one trigger namespace, so naming a handler the same as its route causes the handler to re-trigger itself in a loop.
Use a different method name — the docs examples use a `handle_*` prefix:
```python
@listen("create_video")
def handle_create_video(self) -> str:
"""User wants a new video."""
...
```
Do **not** mirror the route label on the method:
```python
@listen("create_video")
def create_video(self) -> str: # rejected at flow instantiation
...
```
…and the router LLM sees:
```
@@ -394,7 +407,7 @@ Routes:
|-------|---------|---------|
| `converse` | `converse_turn` | Default chat handler. Calls `ConversationConfig.llm` with the system prompt + canonical message history. |
| `end` | `end_conversation` | Sets `state.ended = True` and emits a terminator reply. |
| `answer_from_history` | `answer_from_history_turn` | Optional. Routes here when `ConversationConfig.answer_from_history_llm` is set and the message can be answered from existing history. |
| `answer_from_history` | `answer_from_history_turn` | **Deprecated compatibility route.** Use `converse`, which already receives canonical history. |
You can override any of these by defining a same-named handler in your subclass.
@@ -404,9 +417,9 @@ You can override any of these by defining a same-named handler in your subclass.
1. Resets per-execution tracking (`_completed_methods`, `_method_outputs`) so the graph re-runs — without this, repeated `kickoff` calls on the same flow instance would short-circuit on turn 2+ because `Flow.kickoff_async` treats `inputs={"id": ...}` as a checkpoint restore.
2. Appends the user message to `state.messages`, sets `current_user_message` / `last_user_message`. `last_intent` is **preserved from the prior turn** so the router LLM can use it as a signal.
3. Runs `conversation_start` → `route_conversation` → the chosen `@listen` handler.
3. Runs user-defined `@start` methods (if any), then `route_conversation` as the built-in start/router, then the chosen `@listen` handler. `route_conversation` invokes the overridable `conversation_start()` helper.
4. The router stores its decision in `state.last_intent` (visible to the next turn's router context).
5. If your handler returned a string and didn't already call `append_assistant_message`, `handle_turn` appends it for you.
5. If your handler returned a string and didn't already call `append_assistant_message`, `handle_turn` appends it for you and persists the updated `state.messages` so `@persist` restore includes the assistant turn.
Call `handle_turn()` for chat messages. Calling `kickoff(inputs={"id": ...})` directly runs the flow graph without applying the conversational turn wrapper.
@@ -427,6 +440,8 @@ It handles the common local loop:
4. Prints the assistant result.
5. Finalizes deferred session traces in a `finally` block.
`chat(defer_trace_finalization=True)` temporarily enables the instance deferral flag for the REPL and restores its prior value on exit.
Customize the terminal behavior with injectable I/O:
```python
@@ -448,7 +463,7 @@ To run side effects (event bus setup, telemetry) on every routing decision, over
from typing import Any
from crewai import Flow
from crewai.experimental.conversational import ConversationState
from crewai.flow import ConversationState
class SupportFlow(Flow[ConversationState]):
@@ -459,7 +474,7 @@ class SupportFlow(Flow[ConversationState]):
return super().route_turn(context)
```
To bypass the LLM router entirely and pick a route programmatically, return a string from `route_turn`; returning `None` falls back to `_route_with_config(...)`.
To bypass the LLM router entirely and pick a route programmatically, return a non-empty string from `route_turn`. A falsy return does **not** invoke `_route_with_config()` from your override; routing falls through to this turn's pre-classified intent, then the deprecated `answer_from_history` compatibility path when configured, and finally `converse`. A previous turn's `last_intent` is available in router context but is never replayed as a fallback.
### `append_assistant_message` and `append_agent_result`
@@ -470,6 +485,73 @@ Inside a `@listen(label)` handler, choose:
`ConversationConfig.visible_agent_outputs` can promote specific agents' private results to public globally (`"all"`, or a list of agent names).
## Declaring a conversational flow in JSON/YAML
A [declarative Flow](/edge/en/concepts/cli) can be conversational too. Add a top-level `conversational` block and declare your own routes as methods that `listen` to a route label:
```yaml
schema: crewai.flow/v1
name: SupportFlow
conversational:
system_prompt: You are a terse support assistant.
llm: gpt-4o-mini
router:
llm: gpt-4o-mini
methods:
handle_order:
description: Order status, shipping and delivery questions.
listen: order
do:
call: agent
with:
role: Support specialist
goal: Answer order questions accurately
backstory: Knows the fulfilment pipeline.
input: "${state.current_user_message}"
```
Declaring the block is the opt-in — `enabled` defaults to `true`. Set `enabled: false` to keep the configuration while turning chat off. This also disables built-in method synthesis, so the declaration must provide a normal non-conversational graph.
Three things are supplied for you:
| Supplied | Detail |
|----------|--------|
| The built-in graph | `route_conversation`, `converse_turn`, and `end_conversation` are added automatically. Deprecated `answer_from_history_turn` is retained for compatibility. Declare a method under one of those names to override it. |
| Conversation state | `ConversationState` is used when there is no `state` block. A Pydantic `ref` or `json_schema` state is automatically composed with the conversational fields; it does not need to extend `ConversationState`. |
| The route catalog | Inferred from non-router methods with `listen` labels, excluding internal routes. Descriptions follow the precedence above, and explicit `router.routes` can limit the choices. |
Declarative `llm`, `router.llm`, and `intent_llm` fields accept either a model id or a configuration mapping such as `{model: openai/gpt-4o-mini, max_tokens: 512}`. The `conversational` block also supports `default_intents`, `visible_agent_outputs`, `defer_trace_finalization`, and the `RouterConfig` fields shown above. Deprecated `answer_from_history_prompt` / `answer_from_history_llm` declarations remain accepted for compatibility.
Run it from Python with the same turn APIs as a class-based conversational Flow:
```python
from crewai.flow import Flow
flow = Flow.from_declaration(path="flow.yaml")
try:
flow.handle_turn("Where is my order?", session_id="session-1")
finally:
flow.finalize_session_traces()
```
### Naming routes
Route labels and method names share one trigger namespace, so a handler must not be named after the route it listens to — `create_video` listening to `create_video` is rejected when the flow is built. Use a `handle_*` prefix.
### What a declaration cannot express
| Not expressible | Use instead |
|-----------------|-------------|
| A live `LLM` instance or a custom `BaseLLM` | A model id string or static configuration mapping |
| `router.response_format` as a live model class | Name the class with a python ref: `response_format: {python: my_project.schemas.ConversationRoute}`. Omit it and the framework synthesizes one |
| A `route_turn()` override | Author the Flow in Python, or replace the declarative `route_conversation` method with a `call: code` / expression action |
| A `can_answer_from_history()` override | Deprecated. Use `converse` or override `converse_turn()` in Python. |
`crewai run` opens the chat TUI for a declarative conversational flow — the same one a Python conversational Flow gets. A chat loop needs a terminal, so a headless run exits non-zero with guidance instead of running a single turn; drive it from Python there with `handle_turn()` or `stream_turn()`. A declarative method with a `human_feedback:` block (Python: `@human_feedback`) runs on a terminal REPL, because the runtime collects feedback with a blocking prompt the TUI cannot service. `--inputs` is not accepted for a conversational flow — each turn's input is the message you type — and resuming a session by id is not wired into the CLI yet; use `flow.handle_turn(message, session_id=...)` from Python for that.
## Tracing across turns
With `defer_trace_finalization=True` (default in `ConversationConfig`):
@@ -487,15 +569,28 @@ flow.chat(session_id=session_id)
with `handle_turn()`, call `finalize_session_traces()` when
the session ends.
`suppress_flow_events=True` only hides Rich console panels; trace and method events still emit for observability.
`suppress_flow_events=True` hides Rich console panels and suppresses method execution events. Flow start/finish events still emit, so the outer Flow lifecycle remains traceable, but individual method spans are omitted.
### Conversational `Flow` trace lifecycle
The experimental [conversational `Flow`](#conversational-flow-experimental) uses the same tracing lifecycle: `defer_trace_finalization` defaults to `True`, so each `handle_turn()` keeps the session trace open. Always finalize at the end of the session — wrap your REPL/loop in `try/finally` and call `flow.finalize_session_traces()` on exit. Without it, the trace batch stays open and the final conversation may never export.
The [conversational `Flow`](#conversational-flow) uses the same tracing lifecycle: `defer_trace_finalization` defaults to `True`, so each `handle_turn()` keeps the session trace open. Deferred turns also suppress per-turn `flow_failed`; on a turn error or session abort, finalize the session explicitly. This closes the batch with the session-level `FlowFinished` event rather than a per-turn `FlowFailed` event. Always wrap your REPL/loop in `try/finally` and call `flow.finalize_session_traces()` on exit. Without it, the trace batch stays open and the final conversation may never export.
## Streaming
Set `stream = True` on the `Flow` class. `kickoff(...)` will then emit `assistant_delta` (and related) events through the standard event bus.
For conversational UIs, use `stream_turn()` and iterate its ordered `StreamFrame` objects:
```python
stream = flow.stream_turn("Where is my order?", session_id=session_id)
with stream:
for frame in stream.events:
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
print(frame.content, end="", flush=True)
reply = stream.result
```
For a non-conversational Flow, setting `stream = True` makes `kickoff()` return a `StreamSession`. Do not set `flow.stream = True` when using `handle_turn()`; `stream_turn()` owns the conversational streaming lifecycle.
## Imports
@@ -510,10 +605,15 @@ from crewai.flow import (
router,
start,
)
from crewai.flow.conversation import prepare_conversational_turn
from crewai.flow import (
ConversationConfig,
ConversationState,
RouterConfig,
)
```
## See also
- [Mastering Flow State Management](/en/guides/flows/mastering-flow-state) — persistence, Pydantic state, `@persist`
- [Build Your First Flow](/en/guides/flows/first-flow) — flow basics
- Demo: `lib/crewai/runner_conversational_flow_simple.py` — minimal REPL with `RESEARCH` + Exa agent

View File

@@ -136,7 +136,7 @@ Now, let's configure the content writer crew with JSONC. We'll set up two specia
}
```
Replace `provider/model-id` with the model you use, for example `openai/gpt-4o`, `gemini/gemini-2.0-flash-001`, or `anthropic/claude-sonnet-4-6`.
Replace `provider/model-id` with the model you use, for example `openai/gpt-4o`, `gemini/gemini-3.7-flash`, or `anthropic/claude-sonnet-4-6`.
3. Create `src/guide_creator_flow/crews/content_crew/crew.jsonc`:
@@ -483,7 +483,7 @@ Flows allow you to make direct calls to language models when you need simple, st
```python
llm = LLM(
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
model="model-id-here", # gpt-4o, gemini/gemini-3.7-flash, anthropic/claude...
response_format=GuideOutline
)
response = llm.call(messages=messages)

View File

@@ -0,0 +1,127 @@
---
title: A2UI
description: The declarative tier of generative UI — the agent assembles a surface from a catalog of components you own.
icon: table-cells
mode: "wide"
---
## The agent assembles the UI
[Tool-based rendering](/edge/en/guides/frontend/tool-based-generative-ui) maps one tool to one component: the agent picks a component, you draw it. A2UI is the **declarative** tier of the [generative-UI spectrum](/edge/en/guides/frontend/generative-ui#declarative) — instead of picking a single component, the agent **assembles a surface** by combining building blocks from a catalog you define.
You still own the components. The agent can only use what is in your catalog, so it can never render something you did not ship. What the agent decides is the **layout and the data** — how those building blocks come together into a panel, and what goes in them.
<Note>
A2UI works with [Flows](/en/concepts/flows). Both modes below — dynamic and fixed-schema — run as Flows served over AG-UI, exactly like the rest of this section.
</Note>
## The catalog (same for every mode)
The frontend wiring is identical no matter which backend mode you use: you register a **catalog** on the `<CopilotKit>` provider with the `a2ui` prop.
```tsx
import { CopilotKit } from "@copilotkit/react-core";
import { catalog } from "@/a2ui-catalog";
<CopilotKit runtimeUrl="/api/copilotkit" agent="assistant" a2ui={{ catalog }}>
{/* ... */}
</CopilotKit>
```
The catalog is your set of React components keyed by a catalog id — a `FlightCard`, a `HotelCard`, a `Chart`, whatever your app needs. The agent references catalog ids; CopilotKit paints your components with the data the agent supplies.
<Note>
Authoring the catalog itself — the id schema, prop mapping, and composition rules — is deeper than this page covers. See the [CopilotKit A2UI docs](https://docs.copilotkit.ai) for the full authoring reference. Here we focus on the two backend modes and when to reach for each.
</Note>
## Two backend modes
A2UI backends come in two shapes. In **dynamic** mode the agent designs the surface; in **fixed-schema** mode you pre-author the layout and the agent only fills in data.
| Mode | Who designs the layout | Backend | Predictability |
| --- | --- | --- | --- |
| **[Dynamic](#dynamic)** | The agent, from the conversation | No A2UI tool — auto-injected | Novel layouts, LLM layout step |
| **[Fixed-schema](#fixed-schema)** | You, up front | Backend tools return an envelope | Deterministic, no layout step |
### Dynamic
The Flow wires **no** A2UI tool. Enable A2UI on the runtime for this agent and it gains a `generate_a2ui` tool automatically. A sub-agent designs a surface from the conversation against your catalog, streams it to the frontend progressively, and self-heals invalid output through a validate-then-retry recovery pass. You write a normal agentic-chat Flow; the tool is injected for you.
<Steps>
<Step title="Register the catalog on the provider">
Same as above — pass your catalog through the `a2ui` prop:
```tsx
<CopilotKit runtimeUrl="/api/copilotkit" agent="assistant" a2ui={{ catalog }}>
{/* ... */}
</CopilotKit>
```
</Step>
<Step title="Serve a normal Flow">
Your backend is a plain agentic-chat Flow. You do not define an A2UI tool — the runtime injects `generate_a2ui` when A2UI is enabled for the agent, and the sub-agent invents the layout from the conversation.
</Step>
<Step title="Let the agent compose">
When a turn calls for UI, the agent assembles a surface from your catalog, streams the components in as it designs them, and repairs any invalid output before it reaches the screen. Your registered components render in the layout the agent chose.
</Step>
</Steps>
### Fixed-schema
When you already know the layout and only the data changes per call, pre-author the surface and let the agent fill it. The Flow wires backend tools (for example `search_flights`, `search_hotels`). Each tool returns an **A2UI operations envelope** as its result — `createSurface` -> `updateComponents` -> `updateDataModel` — which the frontend paints. There is no sub-agent, no generation, and no recovery pass: the layout JSON is authored by you, and only the data varies.
Install the toolkit that provides the envelope helpers:
```bash
pip install ag-ui-a2ui-toolkit
```
Build the envelope with the toolkit helpers and emit it as the tool result:
```python
from ag_ui_a2ui_toolkit import (
A2UI_OPERATIONS_KEY,
create_surface,
update_components,
update_data_model,
)
from ag_ui_crewai.sdk import copilotkit_emit_tool_result, copilotkit_stream
```
The tool assembles the `createSurface` -> `updateComponents` -> `updateDataModel` operations into an envelope keyed by `A2UI_OPERATIONS_KEY`, then hands it back with `copilotkit_emit_tool_result(...)`. Because the layout is fixed, the same tool always produces the same shape — only the values differ from call to call.
## When to use which
<CardGroup cols={2}>
<Card title="Dynamic" icon="wand-magic-sparkles">
The layout is not known ahead of time and you want the agent to compose novel surfaces from your primitives. You gain flexibility and pay for an LLM layout step.
</Card>
<Card title="Fixed-schema" icon="table-cells">
The layout is known and only the data varies. More predictable and deterministic — no generation, no recovery, no LLM in the layout path.
</Card>
</CardGroup>
Both modes share the same frontend: one catalog, registered once on the provider. Start with fixed-schema when your surfaces are stable, and reach for dynamic when you want the agent to design layouts you did not anticipate.
## Related
<CardGroup cols={3}>
<Card title="Generative UI" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
The full spectrum — A2UI is its declarative tier.
</Card>
<Card title="Tool-Based Generative UI" icon="puzzle-piece" href="/edge/en/guides/frontend/tool-based-generative-ui">
Map one tool to one component (controlled).
</Card>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state (controlled).
</Card>
</CardGroup>

View File

@@ -0,0 +1,208 @@
---
title: Agentic Generative UI
description: Render your CrewAI Flow's live state as UI that updates as the agent works through multi-step tasks.
icon: list-check
mode: "wide"
---
## Render the agent's live state
Some work does not fit into a single tool call. A research task, a multi-step plan, a long-running job: the interesting thing to show the user is not one result, but *progress*. Agentic generative UI renders the agent's **state** and re-renders it every time that state changes.
The pattern has two halves:
1. Your Flow writes progress into its own state as it works.
2. Your frontend reads that state with `useAgent` and paints it, re-rendering as the state streams in.
The Flow's state reaches the frontend over AG-UI without you wiring up any transport. A state snapshot is emitted automatically at each step (method) boundary of the Flow, and you can push intermediate updates during a long-running step by calling `copilotkit_emit_state` explicitly. You subclass the state to add your own fields, update them in the Flow, and read them in React.
<Note>
State-driven rendering requires a **Flow** with custom state (`Flow[AgentState]`). Crews are chat-oriented and do not expose custom state this way, so with a Crew use [tool rendering](/edge/en/guides/frontend/tool-based-generative-ui) instead.
</Note>
## Build a live task planner
This example builds a planner that breaks a request into about ten steps and streams them to the UI as a checklist. It assumes you already have a CrewAI server and a CopilotKit frontend wired up. If you do not, start with the [Frontend Overview](/edge/en/guides/frontend/overview).
<Steps>
<Step title="Add your own fields to the agent state">
Subclass `CopilotKitState` to declare the state your UI needs. `CopilotKitState` already carries the conversation (`messages`); you add whatever else you want to render, here a list of task steps.
```python
from typing import List, Literal
from pydantic import BaseModel, Field
from ag_ui_crewai.sdk import CopilotKitState
class TaskStep(BaseModel):
description: str
status: Literal["enabled", "disabled"]
class AgentState(CopilotKitState):
steps: List[TaskStep] = Field(default_factory=list)
```
Everything on `AgentState` is included in the state snapshot the frontend receives. A snapshot is emitted automatically at each step boundary, so writing to `self.state` is enough for the UI to pick it up between steps. To update the UI *during* a long step, emit explicitly (shown below).
</Step>
<Step title="Write progress into state from the Flow">
Type your Flow with the custom state (`Flow[AgentState]`) and let the model fill it in. Here the LLM calls a `generate_task_steps` tool; the streamed tool call lands in the conversation and the steps become visible in state.
```python
from crewai.flow.flow import Flow, start
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream
GENERATE_TASK_STEPS_TOOL = {
"type": "function",
"function": {
"name": "generate_task_steps",
"description": "Break a task into about 10 short imperative steps.",
"parameters": {
"type": "object",
"properties": {
"steps": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": {"type": "string"},
"status": {"type": "string", "enum": ["enabled"]},
},
"required": ["description", "status"],
},
},
},
"required": ["steps"],
},
},
}
class TaskPlannerFlow(Flow[AgentState]):
@start()
async def chat(self):
response = await copilotkit_stream(
await acompletion(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "Plan the task the user asks for."},
*self.state.messages,
],
tools=[GENERATE_TASK_STEPS_TOOL],
parallel_tool_calls=False,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
```
Wrapping the LLM call in `copilotkit_stream` streams the assistant's tokens and tool call to the frontend as they are produced. The `steps` you write to `self.state` are sent in the state snapshot emitted at the end of this step.
</Step>
<Step title="Stream progress during a long step (optional)">
The automatic snapshot fires at step boundaries. If a single step does substantial work and you want the checklist to fill in *as it happens*, emit intermediate state yourself with `copilotkit_emit_state`. Each call pushes the current state to the frontend immediately.
```python
from ag_ui_crewai.sdk import copilotkit_emit_state
class TaskPlannerFlow(Flow[AgentState]):
@start()
async def execute(self):
for step in self.state.steps:
step.status = "disabled" # mark done as you go
await copilotkit_emit_state(self.state) # push update now
await do_work(step)
```
Import `copilotkit_emit_state` from `ag_ui_crewai.sdk`. It requires the CopilotKit SDK (`pip install "copilotkit[crewai]"`). Reach for it only when a step is long enough that waiting for its boundary snapshot would feel unresponsive.
</Step>
<Step title="Serve the Flow over AG-UI">
Register the Flow exactly as any other, on its own path:
```python
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
from my_agents.task_planner import TaskPlannerFlow
app = FastAPI(title="CrewAI Agent Server")
add_crewai_flow_fastapi_endpoint(
app=app,
flow=TaskPlannerFlow(),
path="/task_planner",
)
```
See the [Frontend Overview](/edge/en/guides/frontend/overview) for the full server, runtime, and provider setup, and remember to register the agent (here `task_planner`) in your CopilotKit runtime route.
</Step>
<Step title="Read the live state in React">
On the frontend, `useAgent` gives you the agent's live state. Subscribe to state changes so your component re-renders every time the Flow writes an update.
```tsx
"use client";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";
function TaskPlan() {
const { agent } = useAgent({
agentId: "task_planner",
updates: [UseAgentUpdate.OnStateChanged],
});
const steps = agent?.state?.steps ?? [];
return (
<ul>
{steps.map((s, i) => (
<li key={i}>{s.description}</li>
))}
</ul>
);
}
```
`useAgent` returns `{ agent }`. A few things to know:
- `agent.state` is the live Flow state. Its shape matches the fields you added to `AgentState`, so `agent.state.steps` is your list of task steps.
- `agent.isRunning` tells you when the agent is actively working, useful for showing a spinner or disabling input.
- `updates: [UseAgentUpdate.OnStateChanged]` re-renders the component whenever state changes, so the checklist fills in as the Flow streams its steps.
</Step>
</Steps>
## Where this goes next
Reading state is the foundation. Two guides build directly on it:
- [Shared State](/edge/en/guides/frontend/shared-state) adds the other direction: editing the agent's state from the UI and having the Flow pick up the change.
- [Predictive State](/edge/en/guides/frontend/predictive-state-updates) streams a tool's in-progress arguments into state so the UI reflects work before it is committed.
## Related
<CardGroup cols={2}>
<Card title="Shared State" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
Sync agent state and app UI in both directions.
</Card>
<Card title="Predictive State" icon="gauge-high" href="/edge/en/guides/frontend/predictive-state-updates">
Stream in-progress tool arguments into state.
</Card>
<Card title="Tool-Based Generative UI" icon="puzzle-piece" href="/edge/en/guides/frontend/tool-based-generative-ui">
Map agent tool calls to components.
</Card>
</CardGroup>

View File

@@ -0,0 +1,156 @@
---
title: Channels
description: Run the same CrewAI agent as a Slack or Teams bot with the CopilotKit Channels SDK and managed Intelligence platform.
icon: messages
mode: "wide"
---
## Meet your users where they already are
The CrewAI agent you built in the [Overview](/edge/en/guides/frontend/overview) does not have to live behind a web app. The same Crew or Flow can run as a bot inside a messaging platform. No rebuild, no second copy of your agent logic: the agent stays exposed over the [AG-UI protocol](https://docs.ag-ui.com), and a **channel** drives it from Slack or Microsoft Teams.
CopilotKit's [Channels SDK](https://docs.copilotkit.ai/slack) provides that channel. You declare a `createChannel` in a small runtime, point it at your CrewAI agent, and CopilotKit's managed **Intelligence** platform brokers the connection to the messaging provider.
<Note>
Unlike the rest of this section, Channels is **not self-hosted**. It runs through **CopilotKit Intelligence** — a required surface for Channels, by design (a free tier is available). Intelligence holds the platform connection and credentials, receives each platform event, and delivers the turn to your channel process; your process runs the agent and streams the reply back. You configure Slack once in the Intelligence dashboard, and platform credentials never enter your process. Your agent, tools, and state stay yours.
</Note>
## How it fits together
Nothing about your CrewAI agent server changes. It keeps serving your Crew or Flow over AG-UI exactly as in the Overview. What you add is a separate long-running Node process built with `@copilotkit/channels`: it registers a channel on the `CopilotRuntime`, connects to Intelligence, and runs your agent whenever a message arrives.
```
Slack / Teams ──► CopilotKit Intelligence ──► channel process (Node) ──► CrewAI server (AG-UI) ──► Crew / Flow
```
The channel process holds a persistent connection to the Intelligence gateway, so it needs a long-running host — a serverless request handler cannot own that connection. Your CrewAI server can keep serving the web frontend from the Overview at the same time: the web app and the channel are just two clients of one AG-UI endpoint.
## Integration guide
<Steps>
<Step title="Install the Channels packages">
The Channels SDK is batteries-included — every platform ships in the one package, with no per-platform adapter to install. Add it alongside the runtime that hosts the channel and the CrewAI AG-UI client:
```bash
npm install @copilotkit/channels @copilotkit/runtime @ag-ui/crewai
```
</Step>
<Step title="Create a Channel in Intelligence">
In the [CopilotKit dashboard](https://docs.copilotkit.ai/slack), create a Channel and connect Slack — Intelligence walks you through creating the Slack app and holds its credentials. That leaves two environment variables for your process, both from the dashboard:
```bash
export INTELLIGENCE_API_KEY=... # authenticates the runtime with Intelligence (free tier available)
export INTELLIGENCE_CHANNEL_ID=... # the Channel ID, matched by createChannel({ name })
```
</Step>
<Step title="Define the channel">
`createChannel` declares the channel and attaches your agent. Build the agent as a per-thread factory so each conversation gets its own session, using the same `CrewAIAgent` the Overview uses in the web runtime, pointed at your AG-UI endpoint. `identifyUser: "platform"` lets Intelligence map each platform user to a stable identity.
```ts
// channel.ts
import { createChannel } from "@copilotkit/channels";
import { CrewAIAgent } from "@ag-ui/crewai";
const channel = createChannel({
name: process.env.INTELLIGENCE_CHANNEL_ID!, // must match the Channel ID in Intelligence
identifyUser: "platform",
// A fresh agent per conversation, pointed at your CrewAI AG-UI endpoint.
agent: (threadId) => {
const agent = new CrewAIAgent({ url: "http://localhost:8000/recipe" });
agent.threadId = threadId;
return agent;
},
});
// A mention subscribes the thread and runs the agent; afterwards every message
// in a subscribed thread runs it without needing another mention.
channel.onMention(async ({ thread }) => {
await thread.subscribe();
await thread.runAgent();
});
channel.onMessage(async ({ thread }) => {
if (await thread.isSubscribed()) await thread.runAgent();
});
export { channel };
```
</Step>
<Step title="Register the channel on the runtime">
Create a `CopilotRuntime` with the Intelligence gateway and your channel, then serve it with `createCopilotNodeListener`. The `agents` map stays empty — the channel supplies its own agent. Wait for the channel to be ready so a broken config fails startup loudly.
```ts
// server.ts
import { createServer } from "node:http";
import { CopilotRuntime, CopilotKitIntelligence } from "@copilotkit/runtime/v2";
import { createCopilotNodeListener } from "@copilotkit/runtime/v2/node";
import { channel } from "./channel";
const runtime = new CopilotRuntime({
agents: {}, // the channel supplies its own agent; no web-facing agents needed
intelligence: new CopilotKitIntelligence({
apiKey: process.env.INTELLIGENCE_API_KEY!, // free tier available
}),
channels: [channel],
});
const listener = createCopilotNodeListener({ runtime });
await listener.channels?.ready({ timeoutMs: 15_000 });
createServer(listener).listen(3123, () => {
console.log("Channels runtime listening on port 3123");
});
```
</Step>
<Step title="Run the channel runtime">
Start it alongside your CrewAI agent server:
```bash
uvicorn server:app --port 8000 # terminal 1 — CrewAI agent server
npx tsx server.ts # terminal 2 — Channels runtime
```
Mention the bot in Slack or Teams and it runs your Crew or Flow, streaming the reply back into the thread. The thread stays subscribed, so follow-up messages run without another mention.
</Step>
</Steps>
## The event model
A channel reacts to platform events with handlers, and each handler receives a `thread` you drive with a few methods:
- **`channel.onMention`** fires when a user @-mentions the bot. Call `thread.subscribe()` to join the thread, then `thread.runAgent()` to run your CrewAI agent on the mention.
- **`channel.onMessage`** fires on every message in a thread the bot can see. Gate it with `thread.isSubscribed()` so the agent only responds where it has joined, then `thread.runAgent()`.
- **`thread.runAgent()`** runs the attached CrewAI agent for the current turn and streams its output back into the channel. Pass `{ prompt }` to override the text the agent runs on.
Your agent receives an ordinary AG-UI `RunAgentInput` and emits ordinary AG-UI events; the platform mechanics stay behind the channel, so the same Crew or Flow runs unchanged across every platform. The channel also exposes handlers for welcomes, interrupts, commands, reactions, and modals — see the [`Channel` reference](https://docs.copilotkit.ai/reference/channels/classes/Channel) for the full surface.
## Platform support
The managed Intelligence path covers **Slack** and **Microsoft Teams** today — the same channel code runs on either, and `message.platform` / `thread.platform` report the native origin. Other platforms (Discord, Telegram, WhatsApp) are reached through developer-operated **direct adapters** rather than the managed path — your own process holds the platform credentials and transport. Check the [CopilotKit Channels documentation](https://docs.copilotkit.ai/slack) for the current platform list and per-platform setup.
## Related
<CardGroup cols={2}>
<Card title="Frontend Overview" icon="browser" href="/edge/en/guides/frontend/overview">
Serve your Crew or Flow over AG-UI — the foundation every channel builds on.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Pause the agent to collect user approval or input mid-run.
</Card>
</CardGroup>

View File

@@ -0,0 +1,106 @@
---
title: Conversational Flows
description: Serve native, session-aware CrewAI Flows over AG-UI with managed conversation state and full frontend parity.
icon: comments
mode: "wide"
---
## Three execution shapes, one bridge
Behind the AG-UI bridge, a CrewAI backend can take one of three shapes. Knowing which one you are serving decides how you author the backend, not how you build the frontend.
| Shape | What it is | How it is entered |
| --- | --- | --- |
| **Regular Flows** | Author-controlled `@start`/`@listen`/`@router` graphs. The default used throughout these guides. | `kickoff` / `astream` |
| **Conversational Flows** | Native, session-aware, turn-based Flows with managed conversation state. | `stream_turn(message, session_id=...)` |
| **Crews** | Closed autonomous task/agent loops. Basic chat only, a separate compatibility path. | Not the focus here. |
Conversational Flows are a newer CrewAI capability, and an important thing to be clear about up front: **they are Flows, not Crews.** They now run at full regular-Flow feature parity. This page introduces them and shows how they fit the rest of the frontend guides.
<Note>
Reach for a Conversational Flow when you want native multi-turn conversation with CrewAI managing session state and history for you, rather than wiring turn and state handling into a regular Flow yourself. If you are new here, start with the [Frontend Overview](/edge/en/guides/frontend/overview) for the base server, runtime, and provider setup.
</Note>
## Register a Conversational Flow
You register a Conversational Flow through the same endpoint helper as any other Flow, with one extra argument: `conversational=True`.
```python
# server.py
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
add_crewai_flow_fastapi_endpoint(
app,
flow,
"/conversation",
conversational=True,
)
```
Two requirements must hold for this to work:
- The Flow instance declares `conversational = True`.
- The Flow exposes CrewAI's public, callable `stream_turn(message, session_id=...)`.
Detection is capability-based, not version-gated: the bridge checks that the Flow actually offers turn-based conversation, rather than keying off a version number.
<Warning>
If those requirements are not met, the request fails loudly with a `RUN_ERROR` (code `AGUI_CREWAI_CONVERSATIONAL_FLOW_UNSUPPORTED`). It never silently falls back to regular kickoff semantics, so you always know exactly which path you are on.
</Warning>
Authoring the Flow itself, including how you implement `stream_turn`, belongs to CrewAI's Conversational Flows documentation. This page stays at the registration and integration boundary.
## Session and state
Conversational Flows manage session state and history for you across turns. You do not re-thread history manually.
- The AG-UI `threadId` **is** the CrewAI conversation `session_id`. The same thread is the same conversation.
- Before each turn the bridge hydrates the Flow's state and conversation history, then calls `stream_turn`. CrewAI restores the stored session state, and a per-request overlay reapplies the incoming AG-UI state and history so the browser's latest edits win over stale storage.
The result: from the backend author's side, each turn arrives already carrying the conversation's state, and CrewAI persists what you write for the next turn.
## Frontend parity
This is the point to hold onto: **Conversational Flows run through the same event pipeline as regular Flows, so the frontend code is identical.**
There is no Conversational-Flow-specific frontend API. Every feature in these guides works exactly the same way with a Conversational Flow as it does with a regular Flow, using the same hooks and components:
<CardGroup cols={2}>
<Card title="Tool-Based Generative UI" icon="puzzle-piece" href="/edge/en/guides/frontend/tool-based-generative-ui">
Map agent tool calls to your React components.
</Card>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render the Flow's live state as it works.
</Card>
<Card title="Shared State" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
Keep agent state and app UI in two-way sync.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Pause the agent for user approval or input mid-turn.
</Card>
<Card title="Predictive State" icon="gauge-high" href="/edge/en/guides/frontend/predictive-state-updates">
Stream in-progress tool arguments into state.
</Card>
<Card title="Reasoning" icon="brain" href="/edge/en/guides/frontend/reasoning">
Show the model's thinking in the chat.
</Card>
<Card title="A2UI" icon="table-cells" href="/edge/en/guides/frontend/a2ui">
Render agent-authored UI from a component catalog.
</Card>
</CardGroup>
The only difference is on the backend: how you author the Flow (turn-based `stream_turn` with managed session state) and the `conversational=True` registration. Once the endpoint is up, everything you already know about building the frontend applies unchanged.
## Related
<CardGroup cols={2}>
<Card title="Frontend Overview" icon="browser" href="/edge/en/guides/frontend/overview">
Wire a Crew or Flow to a Next.js frontend end to end.
</Card>
<Card title="Generative UI" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
Render tool calls and agent state as custom components.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Gate agent actions behind user approval.
</Card>
</CardGroup>

View File

@@ -0,0 +1,121 @@
---
title: Frontend Actions
description: Let your CrewAI agent call functions that run in the user's browser, from switching themes to navigating your app.
icon: bolt
mode: "wide"
---
## Let the agent act on the app
A frontend action is a tool the agent calls that runs code in the browser instead of on the server. The model decides to invoke it; your handler switches the theme, navigates, highlights an element, or updates your app data; and the result flows back to the agent.
It uses the same hook as tool-based generative UI, `useFrontendTool`. The difference is what you give it: a `handler` that runs code, instead of (or alongside) a `render` that draws UI.
<Note>
Frontend actions work with both Crews and Flows. Any agent that binds `copilotkit.actions` into its LLM call can invoke them.
</Note>
## Build a frontend action
The example below lets the agent switch the app into dark mode on request.
<Steps>
<Step title="Register the action on the frontend">
Call `useFrontendTool` with a `handler`. The handler runs in the browser when the agent invokes the tool, and the string it returns is fed back to the agent.
```tsx
"use client";
import { useFrontendTool } from "@copilotkit/react-core/v2";
import { z } from "zod";
useFrontendTool({
agentId: "assistant",
name: "set_theme",
description: "Switch the app between light and dark mode.",
parameters: z.object({
theme: z.enum(["light", "dark"]),
}),
followUp: false,
handler: async ({ theme }) => {
document.documentElement.dataset.theme = theme; // runs in the browser
return `Theme set to ${theme}.`;
},
});
```
The arguments:
- **`name`** — the tool name the model calls (`set_theme`).
- **`description`** — a short explanation of what the tool does. The model reads it to decide *when* to call the tool, so make it specific. Omitting it leaves the model guessing from the name alone.
- **`parameters`** — a [zod](https://zod.dev) schema describing the arguments the model must supply. CopilotKit turns this into the tool's JSON schema and validates the incoming call.
- **`handler(args)`** — runs in the browser with the parsed arguments. Do your side effect here (set the theme, navigate, update state). The string you return is handed back to the agent as the tool result.
- **`followUp: false`** — stops the agent from taking another turn after the action runs. Leave it out (or set `true`) when you want the agent to respond after acting.
</Step>
<Step title="Bind the frontend tools on the backend">
The agent can only call a tool it has been given. In your Flow, pass the frontend-registered tools into the LLM `tools` list with `*self.state.copilotkit.actions`.
```python
from crewai.flow.flow import Flow, start
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream, CopilotKitState
class AssistantFlow(Flow[CopilotKitState]):
@start()
async def chat(self):
response = await copilotkit_stream(
await acompletion(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "Help the user. Use the tools available to control the app."},
*self.state.messages,
],
tools=[*self.state.copilotkit.actions], # tools the frontend registered
parallel_tool_calls=False,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
```
`self.state.copilotkit.actions` holds the tool definitions for every frontend action registered with `useFrontendTool`. Spreading them into the LLM `tools` list is what makes the agent able to invoke browser-side actions. `copilotkit_stream` streams the response, including the tool call, back to the frontend, where CopilotKit runs the matching handler.
</Step>
<Step title="Serve the Flow">
Expose the Flow over AG-UI with `add_crewai_flow_fastapi_endpoint(...)` and register it in the CopilotKit runtime, exactly as in the [Frontend Overview](/edge/en/guides/frontend/overview). Once both are running, asking the assistant to "switch to dark mode" triggers `set_theme`, and the page flips.
</Step>
</Steps>
## Actions vs. generative UI
`useFrontendTool` covers both ends of a spectrum, and you pick per tool:
| You provide | What it does |
| --- | --- |
| **`handler`** | Runs code in the browser (a frontend action) |
| **`render`** | Draws UI for the tool call (generative UI) |
You can supply either one, or both. A `handler` with a `render` alongside it performs the action and draws UI while it runs. For render-only tools that just display the result of an agent action, see [Tool-Based Generative UI](/edge/en/guides/frontend/tool-based-generative-ui).
## Related
<CardGroup cols={2}>
<Card title="Tool-Based Generative UI" icon="puzzle-piece" href="/edge/en/guides/frontend/tool-based-generative-ui">
Map agent tool calls to React components.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Gate agent actions behind user approval.
</Card>
<Card title="Shared State" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
Keep agent state and your app UI in two-way sync.
</Card>
</CardGroup>

View File

@@ -0,0 +1,107 @@
---
title: Generative UI
description: Render your CrewAI agent's work as live React components, across the full spectrum from author-controlled to agent-invented UI.
icon: wand-magic-sparkles
mode: "wide"
---
## Beyond the chat bubble
Generative UI means the agent's work shows up as real interface, not just text. When your Crew or Flow calls a tool, updates its state, or reasons about a problem, you decide what the user sees: a progress checklist, a recipe card, a chart, a whole assembled panel.
CopilotKit renders generative UI along a **spectrum**, from fully author-controlled (you decide every pixel) to agent-invented (the agent assembles the surface):
| Tier | Who decides the UI | CrewAI mechanism |
| --- | --- | --- |
| **[Controlled](#controlled)** | You — a fixed set of components the agent picks from | `useRenderTool`, `useAgent`, reasoning |
| **[Declarative](#declarative)** | The agent — assembles a surface from *your* component catalog | [A2UI](/edge/en/guides/frontend/a2ui) |
| **[Open-ended](#open-ended)** | An external tool/server invents the surface | MCP tools |
The tiers compose freely; a single app usually mixes them.
## Controlled
You own the components. The agent chooses which to show and with what data. This is the most predictable tier and where most apps start.
### Tool rendering
The agent calls a tool on the backend. You register a matching component on the frontend with `useRenderTool`, and CopilotKit renders it, streaming the arguments in as they arrive.
```tsx
"use client";
import { useRenderTool } from "@copilotkit/react-core/v2";
import { z } from "zod";
useRenderTool({
name: "generate_recipe",
parameters: z.object({
title: z.string(),
ingredients: z.array(z.string()),
}),
render: ({ args }) => <RecipeCard title={args.title} ingredients={args.ingredients} />,
});
```
<Note>
`useRenderTool` renders a tool call. When a tool also needs to *run* code in the browser, use [`useFrontendTool`](/edge/en/guides/frontend/frontend-actions) (a `handler`, with optional `render`).
</Note>
See [Tool-Based Generative UI](/edge/en/guides/frontend/tool-based-generative-ui) for the full walkthrough, including progressive rendering as arguments stream, and [Backend Tool Rendering](/edge/en/guides/frontend/tool-based-generative-ui#backend-tools) for tools your Crew or Flow executes server-side.
### State rendering
Instead of reacting to a single tool call, render the agent's **state** as it changes. This is the right pattern for multi-step work: read the agent's working state with `useAgent` and paint it however you like.
```tsx
"use client";
import { useAgent } from "@copilotkit/react-core/v2";
function TaskProgress() {
const { agent } = useAgent({ agentId: "task_runner" });
const steps = agent?.state?.steps ?? [];
return <StepList steps={steps} />;
}
```
See [Agentic Generative UI](/edge/en/guides/frontend/agentic-generative-ui) for streaming state from a Flow, and [Shared State](/edge/en/guides/frontend/shared-state) for editing that state from the UI.
### Reasoning
When the model reasons before answering, that thinking renders in the chat automatically. No component to write. See [Reasoning](/edge/en/guides/frontend/reasoning).
## Declarative
The agent goes beyond picking a component: it **assembles a surface** by combining building blocks from a catalog *you* define. You still own the components (the agent can only use what is in your catalog), but the layout is the agent's.
This is [A2UI](/edge/en/guides/frontend/a2ui). You register a catalog on the provider:
```tsx
<CopilotKit runtimeUrl="/api/copilotkit" agent="assistant" a2ui={{ catalog }}>
{/* ... */}
</CopilotKit>
```
The agent then builds surfaces from that catalog — either dynamically (it designs the layout from the conversation) or from a fixed schema your backend fills with data. See [A2UI](/edge/en/guides/frontend/a2ui) for both modes and error recovery.
## Open-ended
At the far end, the surface is invented outside your app entirely. For CrewAI this comes through **MCP**: tools served by an MCP server the agent connects to render as tool calls in the chat, the same way backend tools do. This is the least constrained and the least predictable tier.
MCP tool calls surface as standard tool-call UI — render them with `useRenderTool` like any other tool. Full agent-invented "MCP App" surfaces are an emerging capability; see the [CopilotKit docs](https://docs.copilotkit.ai) for the current state.
## Related
<CardGroup cols={2}>
<Card title="Tool-Based Generative UI" icon="puzzle-piece" href="/edge/en/guides/frontend/tool-based-generative-ui">
Map agent tool calls to components (controlled).
</Card>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state (controlled).
</Card>
<Card title="A2UI" icon="table-cells" href="/edge/en/guides/frontend/a2ui">
Let the agent assemble surfaces from your catalog (declarative).
</Card>
<Card title="Reasoning" icon="brain" href="/edge/en/guides/frontend/reasoning">
Render the agent's thinking.
</Card>
</CardGroup>

View File

@@ -0,0 +1,191 @@
---
title: Human-in-the-Loop
description: Pause your CrewAI agent mid-run to collect a user decision, then resume the agent with their answer.
icon: user-check
mode: "wide"
---
## Put the user in the loop
Some steps should not happen without a human saying yes. Human-in-the-loop pauses the agent mid-run, renders an interactive component in the frontend, and waits. The user makes a choice; the agent resumes with that choice and continues.
The mechanism is a tool the frontend registers. When the model calls it, the run halts at that tool call until the user responds. Nothing happens automatically: the agent stays parked until `respond()` hands control back.
In the example below, the agent proposes a list of task steps. The user enables or disables each step and confirms. The agent then continues, respecting exactly what the user approved.
<Note>
This pattern works with Flows. It relies on the Flow's chat loop re-entering after `respond()`: the returned value comes back as a tool result, and the agent's next turn acts on it.
</Note>
## Build it
<Steps>
<Step title="Bind the frontend actions into the model's tools">
In your Flow, add the frontend-registered actions to the model's tool list with `*self.state.copilotkit.actions`. Those actions are the tools your frontend registered (via `useHumanInTheLoop`). Binding them lets the model call them; the run pauses at that tool call until the user responds.
```python
# human_in_the_loop_flow.py
from crewai.flow.flow import Flow, start, router, listen
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream, CopilotKitState
class HumanInTheLoopFlow(Flow[CopilotKitState]):
@start()
@listen("route_follow_up")
async def start_flow(self):
pass
@router(start_flow)
async def chat(self):
system_prompt = (
"You perform tasks for the user. When asked to do a task, call the "
"tool the frontend provides so the user can approve or adjust the steps "
"before you continue."
)
response = await copilotkit_stream(
await acompletion(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
*self.state.messages,
],
tools=[*self.state.copilotkit.actions], # tools registered by the frontend
parallel_tool_calls=False,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
return "route_end"
@listen("route_end")
async def end(self):
pass
```
`CopilotKitState` carries the frontend-registered actions on `self.state.copilotkit.actions`. When the model calls one, the run pauses there. After the user responds, the returned value lands in `self.state.messages` as the tool result, and the Flow loops back through `chat` so the model can act on the decision.
</Step>
<Step title="Serve the Flow over AG-UI">
Expose the Flow from your FastAPI server with `add_crewai_flow_fastapi_endpoint`, the same way as every other agent. See [Frontend Overview](/edge/en/guides/frontend/overview) for the full server, runtime, and provider setup.
```python
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
from my_agents.human_in_the_loop_flow import HumanInTheLoopFlow
app = FastAPI(title="CrewAI Agent Server")
add_crewai_flow_fastapi_endpoint(
app=app,
flow=HumanInTheLoopFlow(),
path="/human_in_the_loop",
)
```
</Step>
<Step title="Register the interactive tool on the frontend">
`useHumanInTheLoop` registers the tool the agent pauses on and gives you a `render` function to draw the interactive UI. When the agent calls the tool, your component appears; when the user acts, you call `respond()` to resume the agent.
```tsx
"use client";
import { useHumanInTheLoop } from "@copilotkit/react-core/v2";
import { z } from "zod";
useHumanInTheLoop({
agentId: "human_in_the_loop",
name: "generate_task_steps",
parameters: z.object({
steps: z.array(
z.object({
description: z.string(),
status: z.enum(["enabled", "disabled", "executing"]),
})
),
}),
render: ({ args, respond, status }) => (
<StepReview
steps={args.steps ?? []}
// `status === "executing"` means the agent is waiting for the user
waiting={status === "executing"}
onConfirm={(chosen) => respond?.(chosen)}
/>
),
});
```
The `render` function receives:
- **`args`** — the tool arguments the model produced (here, the proposed `steps`). These stream in as the model generates them.
- **`status`** — the tool call's lifecycle. While it is `"executing"`, the agent is paused and waiting on the human.
- **`respond(value)`** — resumes the agent with the user's decision. The agent's next turn sees the returned value and acts on it.
</Step>
<Step title="Let the user decide, then respond">
Your component reads `args.steps`, lets the user toggle each one, and calls `respond()` with the final selection. That value is what the agent continues with.
```tsx
function StepReview({ steps, waiting, onConfirm }) {
const [choices, setChoices] = useState(steps);
const toggle = (i) =>
setChoices((prev) =>
prev.map((s, idx) =>
idx === i
? { ...s, status: s.status === "enabled" ? "disabled" : "enabled" }
: s
)
);
return (
<div>
{choices.map((step, i) => (
<label key={i}>
<input
type="checkbox"
checked={step.status === "enabled"}
disabled={!waiting}
onChange={() => toggle(i)}
/>
{step.description}
</label>
))}
<button disabled={!waiting} onClick={() => onConfirm(choices)}>
Confirm
</button>
</div>
);
}
```
Once the user clicks Confirm, `respond()` fires, the run resumes, and the Flow's `chat` step runs again with the user's choices in the message history.
</Step>
</Steps>
## Related
<CardGroup cols={2}>
<Card title="Frontend Actions" icon="bolt" href="/edge/en/guides/frontend/frontend-actions">
Let the agent call functions that run in the browser.
</Card>
<Card title="Shared State" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
Keep agent state and your app UI in two-way sync.
</Card>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state as custom components.
</Card>
</CardGroup>

View File

@@ -0,0 +1,238 @@
---
title: Frontend Overview
description: Build interactive user interfaces for your CrewAI agents with CopilotKit and the AG-UI protocol.
icon: browser
mode: "wide"
---
## Give your agents a user interface
CrewAI runs your agents. [CopilotKit](https://copilotkit.ai) gives them a frontend. Together they let you build applications where users chat with a Crew or Flow, watch it work in real time, approve its decisions, and see its output rendered as live UI instead of walls of text.
The two connect through the [AG-UI protocol](https://docs.ag-ui.com). The `ag-ui-crewai` package exposes any Crew or Flow as an AG-UI endpoint. CopilotKit's React hooks and components consume that endpoint. This unlocks experiences that go well beyond a chat box:
<CardGroup cols={2}>
<Card title="Generative UI" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
Render agent tool calls and state as your own React components.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Pause the agent to collect user approval or input mid-run.
</Card>
<Card title="Shared State" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
Keep agent state and your app UI in two-way sync.
</Card>
<Card title="Channels" icon="messages" href="/edge/en/guides/frontend/channels">
Run the same agent as a Slack, Discord, or Teams bot.
</Card>
</CardGroup>
This guide gets a Crew or Flow talking to a Next.js frontend end to end. The rest of the section builds on the app you set up here.
## Architecture
There are three pieces:
1. **CrewAI agent server** — a Python process that serves your Crew or Flow over AG-UI (FastAPI + `ag-ui-crewai`).
2. **CopilotKit runtime** — a Next.js route that registers your agent and proxies requests to it.
3. **React frontend** — the `<CopilotKit>` provider plus chat and generative-UI components.
```
React app ──► CopilotKit runtime (/api/copilotkit) ──► CrewAI server (AG-UI) ──► Crew / Flow
```
<Note>
This guide covers the **self-hosted** path: you run the CrewAI agent server yourself with `ag-ui-crewai`, and it works locally with no managed service. CopilotKit also offers a **managed** path (CopilotKit Cloud / Enterprise Intelligence) with hosted threads and an inspector — see the [CopilotKit CrewAI quickstart](https://docs.copilotkit.ai/crewai-crews/quickstart) if you want that instead. The frontend code in this section is the same either way; only how the agent is hosted and registered differs.
</Note>
<Note>
CrewAI runs behind AG-UI in three shapes: regular **Flows** (used throughout these guides), **[Conversational Flows](/edge/en/guides/frontend/conversational-flows)** (native, session-aware, turn-based, at full feature parity), and **Crews** (basic chat). The frontend in this section is identical across them — only the backend authoring and registration differ.
</Note>
## Integration guide
<Steps>
<Step title="Serve your agent over AG-UI">
Install the integration package into your CrewAI project:
```bash
pip install ag-ui-crewai
```
Expose your agent from a FastAPI app. Flows use `add_crewai_flow_fastapi_endpoint`; Crews use `add_crewai_crew_fastapi_endpoint`. You can register as many as you want, each on its own path.
<CodeGroup>
```python Flow
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
from my_agents.recipe_flow import RecipeFlow
app = FastAPI(title="CrewAI Agent Server")
add_crewai_flow_fastapi_endpoint(
app=app,
flow=RecipeFlow(),
path="/recipe",
)
```
```python Crew
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_crew_fastapi_endpoint
from my_agents.research_crew import ResearchCrew
app = FastAPI(title="CrewAI Agent Server")
add_crewai_crew_fastapi_endpoint(
app=app,
crew=ResearchCrew().crew(),
path="/research",
)
```
</CodeGroup>
Run it:
```bash
uvicorn server:app --port 8000
```
<Note>
Set the environment variables for your LLM provider (for example `OPENAI_API_KEY`) before starting the server.
</Note>
</Step>
<Step title="Create a Next.js app">
If you do not have a frontend yet, scaffold one:
```bash
npx create-next-app@latest my-app
cd my-app
```
Install CopilotKit and the CrewAI AG-UI client:
```bash
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime @ag-ui/crewai
```
</Step>
<Step title="Add the CopilotKit runtime">
Create a route that registers your CrewAI agent(s) with the CopilotKit runtime. Each agent points at a path on your Python server via `CrewAIAgent`.
```ts
// app/api/copilotkit/route.ts
import {
CopilotRuntime,
InMemoryAgentRunner,
createCopilotEndpoint,
} from "@copilotkit/runtime/v2";
import { CrewAIAgent } from "@ag-ui/crewai";
import { handle } from "hono/vercel";
const runtime = new CopilotRuntime({
agents: {
recipe: new CrewAIAgent({ url: "http://localhost:8000/recipe" }),
},
runner: new InMemoryAgentRunner(),
});
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
});
const handler = handle(app);
export const GET = handler;
export const POST = handler;
```
</Step>
<Step title="Wrap your app with the provider">
Point `<CopilotKit>` at the runtime route and name the agent you registered.
```tsx
// app/page.tsx
"use client";
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotSidebar } from "@copilotkit/react-core/v2";
import "@copilotkit/react-core/v2/styles.css";
export default function Page() {
return (
<CopilotKit runtimeUrl="/api/copilotkit" agent="recipe">
<YourApp />
<CopilotSidebar agentId="recipe" labels={{ modalHeaderTitle: "Assistant" }} />
</CopilotKit>
);
}
```
</Step>
<Step title="Run it">
Start both processes and open the app. Chatting in the sidebar now runs your Crew or Flow.
```bash
uvicorn server:app --port 8000 # terminal 1
npm run dev # terminal 2
```
</Step>
</Steps>
## Chat UI options
CopilotKit ships three interchangeable chat surfaces. Swap the component; the wiring is identical.
<CodeGroup>
```tsx Sidebar
import { CopilotSidebar } from "@copilotkit/react-core/v2";
<CopilotSidebar agentId="recipe" />
```
```tsx Popup
import { CopilotPopup } from "@copilotkit/react-core/v2";
<CopilotPopup agentId="recipe" />
```
```tsx Inline
import { CopilotChat } from "@copilotkit/react-core/v2";
<CopilotChat agentId="recipe" />
```
</CodeGroup>
## Where to go next
<CardGroup cols={2}>
<Card title="Generative UI" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
Render tool calls and agent state as custom components.
</Card>
<Card title="Frontend Actions" icon="bolt" href="/edge/en/guides/frontend/frontend-actions">
Let the agent call functions that run in the browser.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Gate agent actions behind user approval.
</Card>
<Card title="Predictive State" icon="gauge-high" href="/edge/en/guides/frontend/predictive-state-updates">
Stream in-progress state to the UI as the agent works.
</Card>
</CardGroup>

View File

@@ -0,0 +1,142 @@
---
title: Predictive State Updates
description: Stream an in-progress tool call's arguments into agent state so the UI updates optimistically while the agent is still generating.
icon: gauge-high
mode: "wide"
---
## Show the work as it happens
Normally a tool call is atomic from the UI's point of view: the agent decides what to write, and your interface only sees the result once the call finishes. For a tool that produces a large document that means a long pause followed by everything snapping into place at once.
Predictive state updates remove the wait. You project a streaming tool argument onto a field of the agent's state, so as the model generates the argument token by token, that state field fills in live. A document the agent is writing appears in the editor as it is typed, not after.
<Note>
Predictive state relies on a Flow with custom state (`Flow[AgentState]`). It projects a streaming tool argument onto a state field, so there is no equivalent for a bare Crew.
</Note>
## How it compares to Shared State
Both patterns read the agent's state from the frontend, but they solve different problems:
| Pattern | What it does |
| --- | --- |
| **Predictive state** | One-way. Streams an in-progress tool argument into a state field so the UI updates *during* generation, before the call completes. |
| **[Shared State](/edge/en/guides/frontend/shared-state)** | Two-way. The UI reads *and writes* the agent's committed state, keeping app and agent in sync across turns. |
Reach for predictive state when you want an optimistic, in-flight preview of what the agent is producing. Reach for [Shared State](/edge/en/guides/frontend/shared-state) when the user needs to edit that state back.
## Walkthrough
This assumes you already have a Crew or Flow served over AG-UI and a CopilotKit frontend wired up. If not, start with the [Frontend Overview](/edge/en/guides/frontend/overview).
<Steps>
<Step title="Define a Flow with custom state">
Predictive state projects a tool argument onto a state field, so your Flow needs a typed state field to receive it. Add the field you want to stream into to your `CopilotKitState` subclass.
```python
from typing import Optional
from crewai.flow.flow import Flow, start, router, listen
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream, copilotkit_predict_state, CopilotKitState
WRITE_DOCUMENT_TOOL = {
"type": "function",
"function": {
"name": "write_document",
"description": "Write the full document in markdown.",
"parameters": {
"type": "object",
"properties": {
"document": {"type": "string", "description": "The document to write"},
},
},
},
}
class AgentState(CopilotKitState):
document: Optional[str] = None
class DocumentFlow(Flow[AgentState]):
@start()
@listen("route_follow_up")
async def start_flow(self):
pass
```
</Step>
<Step title="Map a state field to a tool argument">
Call `copilotkit_predict_state` **before** you start streaming the completion. It tells the runtime to project the named tool argument onto the named state field: as the `write_document` call streams its `document` argument, the `document` state field updates live.
```python
@router(start_flow)
async def chat(self):
# Map the `document` state field to the `document` argument of write_document.
# As the tool call streams, the state field updates live.
await copilotkit_predict_state({
"document": {"tool_name": "write_document", "tool_argument": "document"},
})
response = await copilotkit_stream(
await acompletion(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": "Write and edit the document with write_document."},
*self.state.messages,
],
tools=[*self.state.copilotkit.actions, WRITE_DOCUMENT_TOOL],
parallel_tool_calls=False,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
```
The key is `copilotkit_predict_state({ "<state_field>": {"tool_name": ..., "tool_argument": ...} })`. Without it, the frontend would only see `document` once the tool call completed. With it, the partial argument streams onto the field while the agent is still generating.
Serve the Flow with `add_crewai_flow_fastapi_endpoint(...)` as shown in the [Frontend Overview](/edge/en/guides/frontend/overview).
</Step>
<Step title="Read the predicted state on the frontend">
On the frontend, read the field with `useAgent` and subscribe to state changes. Because the backend is projecting the streaming argument onto `document`, this component re-renders as the agent types.
```tsx
"use client";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";
function DocumentView() {
const { agent } = useAgent({
agentId: "document",
updates: [UseAgentUpdate.OnStateChanged],
});
const document = (agent?.state as { document?: string })?.document ?? "";
return <article>{document}</article>; // updates as the agent types
}
```
The `document` field fills in progressively as the agent generates the `write_document` call, so the editor updates in real time rather than snapping in at the end.
</Step>
</Steps>
## Related
<CardGroup cols={2}>
<Card title="Shared State" icon="arrows-rotate" href="/edge/en/guides/frontend/shared-state">
Read and write the agent's state two-way.
</Card>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state as it changes.
</Card>
<Card title="Tool-Based Generative UI" icon="puzzle-piece" href="/edge/en/guides/frontend/tool-based-generative-ui">
Map agent tool calls to components.
</Card>
</CardGroup>

View File

@@ -0,0 +1,68 @@
---
title: Reasoning
description: Show the model's thinking in the chat automatically, with no component to build.
icon: brain
mode: "wide"
---
## Thinking, rendered for free
When a reasoning-capable model thinks before it answers, CopilotKit renders that thinking right in the chat. This is the simplest generative-UI pattern in the whole section: there is nothing to build. No hook, no component, no props. Use a reasoning-capable model, keep the streaming wrapper your Flows already have, and the chat surface from the [Overview](/edge/en/guides/frontend/overview) does the rest.
## Use a reasoning-capable model
Reasoning is surfaced automatically by `copilotkit_stream`, which every Flow example already wraps the model call in. The bridge reads the model's reasoning deltas and emits them to the frontend. It is provider-agnostic and works over both of CrewAI's streaming transports, so the only thing you change is the model.
```python
# recipe_flow.py
from crewai.flow.flow import Flow, start
from ag_ui_crewai.sdk import copilotkit_stream, CopilotKitState
from litellm import acompletion
class RecipeFlow(Flow[CopilotKitState]):
@start()
async def chat(self):
response = await copilotkit_stream(
acompletion(
# any reasoning-capable model, e.g. deepseek-reasoner
model="deepseek/deepseek-reasoner",
messages=self.state.messages,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
```
Models that emit reasoning over the standard channel include DeepSeek `deepseek-reasoner`, Anthropic extended thinking (Claude), and Gemini thinking, among others. Swap the `model` for one of these and its thinking starts streaming through.
This works the same for both Crews and Flows, since both run their model calls through `copilotkit_stream`.
## Render it
There is no frontend step. The `CopilotChat`, `CopilotSidebar`, or `CopilotPopup` surface you already mounted shows the reasoning as it streams, above the answer it produced.
```tsx
import { CopilotChat } from "@copilotkit/react-core/v2";
<CopilotChat agentId="recipe" />
```
<Note>
There is no `useReasoning` hook and no reasoning component to write. Reasoning is not something you wire up on the frontend; it renders automatically as long as the model emits it.
</Note>
## Related
<CardGroup cols={2}>
<Card title="Generative UI" icon="wand-magic-sparkles" href="/edge/en/guides/frontend/generative-ui">
The full spectrum, from author-controlled to agent-invented UI.
</Card>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state as the Flow works.
</Card>
<Card title="Frontend Overview" icon="browser" href="/edge/en/guides/frontend/overview">
Set up the chat surface and runtime.
</Card>
</CardGroup>

View File

@@ -0,0 +1,210 @@
---
title: Shared State
description: Keep your CrewAI agent's state and your app's UI in two-way sync, so edits on either side flow to the other.
icon: arrows-rotate
mode: "wide"
---
## One state, both directions
Shared state is a single state object that the agent and the UI both read and write. The agent updates it as it works and your React components render it live. When the user edits that same state in the UI, the change flows back so the agent sees it on its next turn.
The classic example is a recipe: the agent drafts it, the user tweaks an ingredient or an instruction, and the agent picks up from the edited version. Neither side owns the state; they share it.
<Note>
Shared state relies on a Flow with custom state. Define an `AgentState` that subclasses `CopilotKitState` and type your Flow as `Flow[AgentState]`. Crews do not carry custom state, so this pattern is Flow-only.
</Note>
## How it works
<Steps>
<Step title="Define the shared state on your Flow">
Subclass `CopilotKitState` so the agent keeps CopilotKit's message plumbing, then add your own fields. Here the shared field is `recipe`.
```python
# recipe_flow.py
import json
from typing import List, Optional
from pydantic import BaseModel, Field
from crewai.flow.flow import Flow, start, router, listen
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream, CopilotKitState
class Ingredient(BaseModel):
name: str
amount: str
class Recipe(BaseModel):
title: str
ingredients: List[Ingredient] = Field(default_factory=list)
instructions: List[str] = Field(default_factory=list)
class AgentState(CopilotKitState):
recipe: Optional[Recipe] = None
```
</Step>
<Step title="Read and write the state from the agent">
The agent reads the current state by dumping it into the system prompt, and writes it back by assigning to `self.state.recipe`. A `generate_recipe` tool lets the model return the updated recipe as structured arguments.
```python
GENERATE_RECIPE_TOOL = {
"type": "function",
"function": {
"name": "generate_recipe",
"description": "Generate or modify the recipe.",
"parameters": {
"type": "object",
"properties": {"recipe": {"type": "object"}},
"required": ["recipe"],
},
},
}
class SharedStateFlow(Flow[AgentState]):
@start()
@listen("route_follow_up")
async def start_flow(self):
pass
@router(start_flow)
async def chat(self):
# The current shared state is visible to the model.
system_prompt = f"""You help the user build a recipe.
Current recipe: {self.state.model_dump_json(indent=2)}
Modify it by calling generate_recipe."""
response = await copilotkit_stream(
await acompletion(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
*self.state.messages,
],
tools=[*self.state.copilotkit.actions, GENERATE_RECIPE_TOOL],
parallel_tool_calls=False,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
if message.tool_calls:
call = message.tool_calls[0]
if call.function.name == "generate_recipe":
args = json.loads(call.function.arguments)
self.state.recipe = Recipe(**args["recipe"]) # write to shared state
self.state.messages.append({
"role": "tool",
"content": "Recipe updated.",
"tool_call_id": call.id,
})
return "route_follow_up"
return "route_end"
@listen("route_end")
async def end(self):
pass
```
Two things make this shared rather than one-way: dumping `self.state` into the prompt means the agent always works from the latest recipe (including edits the user made in the UI), and assigning `self.state.recipe` puts the new value into the state snapshot sent to connected clients at the end of the step. For updates during a long step, emit explicitly with `copilotkit_emit_state` (see [Agentic Generative UI](/edge/en/guides/frontend/agentic-generative-ui)).
</Step>
<Step title="Serve the Flow over AG-UI">
Expose the Flow from your FastAPI app with `add_crewai_flow_fastapi_endpoint`, then register it in the CopilotKit runtime. See the [Frontend Overview](/edge/en/guides/frontend/overview) for the full server and runtime setup.
```python
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
from recipe_flow import SharedStateFlow
app = FastAPI(title="CrewAI Agent Server")
add_crewai_flow_fastapi_endpoint(
app=app,
flow=SharedStateFlow(),
path="/shared_state",
)
```
</Step>
<Step title="Read and write the state from the UI">
`useAgent` gives you both directions in one hook. Read the shared state off `agent.state`, and write it back with `agent.setState(...)`. Subscribe to `OnStateChanged` so your component re-renders whenever the agent updates the state.
```tsx
"use client";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";
function RecipeEditor() {
const { agent } = useAgent({
agentId: "shared_state",
updates: [UseAgentUpdate.OnStateChanged],
});
const state = agent?.state as { recipe?: Recipe } | undefined;
const isLoading = agent?.isRunning;
const recipe = state?.recipe;
// setState replaces the whole state object, so spread the current
// state and override only the field you changed. Passing just
// `{ recipe }` would drop messages and other runtime fields.
const updateRecipe = (patch: Partial<Recipe>) =>
agent?.setState({ ...(agent.state ?? {}), recipe: { ...(recipe ?? {}), ...patch } });
return (
<div>
<input
value={recipe?.title ?? ""}
disabled={isLoading}
onChange={(e) => updateRecipe({ title: e.target.value })}
/>
{/* render inputs for ingredients and instructions the same way */}
</div>
);
}
```
`agent.state` reads the shared state, `agent.setState(...)` writes it back so the agent sees the change on its next turn, and `agent.isRunning` reflects whether the agent is currently working.
<Note>
`setState` **replaces** the entire state object rather than merging. Always spread the current state (`{ ...agent.state, ... }`) and override only the fields you are changing, or you will drop the conversation and other runtime fields the agent depends on.
</Note>
</Step>
</Steps>
## The two-way loop
Putting the pieces together, a single recipe object is kept in sync in both directions:
- **Agent edits, UI updates.** The Flow assigns `self.state.recipe`, the new value ships in the step's state snapshot, and `OnStateChanged` re-renders your inputs.
- **User edits, agent sees it.** A change in the UI calls `agent.setState(...)`, and because the Flow dumps `self.state` into its prompt, the agent works from the edited recipe on its next turn.
## Related
<CardGroup cols={2}>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state as it changes.
</Card>
<Card title="Predictive State" icon="gauge-high" href="/edge/en/guides/frontend/predictive-state-updates">
Stream in-progress state to the UI as the agent works.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Pause the agent to collect user approval or input mid-run.
</Card>
</CardGroup>

View File

@@ -0,0 +1,235 @@
---
title: Tool-Based Generative UI
description: Map a CrewAI agent's tool calls to React components and stream the arguments in as they arrive.
icon: puzzle-piece
mode: "wide"
---
## Render tool calls as components
When your Crew or Flow calls a tool, you rarely want the raw arguments dumped into the chat. Tool-based generative UI maps each tool the agent calls to a React component you own. The agent decides *when* to call the tool; you decide what the user sees.
Because CopilotKit streams the tool call to the frontend as the model generates it, the arguments fill in progressively. Your component can paint the moment the first field arrives and update as the rest stream in.
This guide builds a haiku generator: the agent calls a `generate_haiku` tool, and the frontend renders each haiku as a card. It assumes you already have a Crew or Flow talking to a Next.js app. If not, start with the [Frontend Overview](/edge/en/guides/frontend/overview) for the full server, runtime, and provider setup.
<Note>
Tool rendering works with both Crews and Flows. The example below uses a Flow, but the frontend wiring is identical either way.
</Note>
## Walkthrough
<Steps>
<Step title="Define the tool on the backend">
Declare the tool with a JSON schema and pass it to the model. The `copilotkit_stream` wrapper together with `stream=True` is what streams the tool call to the frontend as it is generated, one argument chunk at a time.
```python
# haiku_flow.py
from crewai.flow.flow import Flow, start
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream, CopilotKitState
GENERATE_HAIKU_TOOL = {
"type": "function",
"function": {
"name": "generate_haiku",
"description": "Generate a haiku in Japanese and its English translation",
"parameters": {
"type": "object",
"properties": {
"japanese": {
"type": "array",
"items": {"type": "string"},
"description": "Three lines in Japanese",
},
"english": {
"type": "array",
"items": {"type": "string"},
"description": "Three lines in English",
},
},
"required": ["japanese", "english"],
},
},
}
class HaikuFlow(Flow[CopilotKitState]):
@start()
async def chat(self):
system_prompt = "You help the user write haikus. Use the generate_haiku tool."
response = await copilotkit_stream(
await acompletion(
model="openai/gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
*self.state.messages,
],
tools=[GENERATE_HAIKU_TOOL],
parallel_tool_calls=False,
stream=True,
)
)
message = response.choices[0].message
self.state.messages.append(message)
if message.tool_calls:
self.state.messages.append({
"tool_call_id": message.tool_calls[0].id,
"role": "tool",
"content": "Haiku generated.",
})
```
The tool has no Python implementation. It exists only so the model emits a structured call the frontend can render. After the call, append a short tool result so the conversation stays well-formed for the next turn.
</Step>
<Step title="Serve the Flow over AG-UI">
Expose the Flow from your FastAPI app on its own path:
```python
# server.py
from fastapi import FastAPI
from ag_ui_crewai.endpoint import add_crewai_flow_fastapi_endpoint
from haiku_flow import HaikuFlow
app = FastAPI(title="CrewAI Agent Server")
add_crewai_flow_fastapi_endpoint(
app=app,
flow=HaikuFlow(),
path="/haiku",
)
```
Register the agent with the CopilotKit runtime and point `<CopilotKit>` at it exactly as shown in the [Frontend Overview](/edge/en/guides/frontend/overview). The rest of this guide assumes the agent is registered under the id `haiku`.
</Step>
<Step title="Register the rendering component">
On the frontend, call `useRenderTool` with the same `name` the backend declared. `useRenderTool` is the hook for *rendering* a tool call: it takes a `render` function and nothing to execute, because this tool is pure display.
<Note>
Use `useRenderTool` when the tool only draws UI. If the tool also needs to *run* something in the browser, use [`useFrontendTool`](/edge/en/guides/frontend/frontend-actions) instead, which pairs a `handler` with an optional `render`.
</Note>
```tsx
"use client";
import { useRenderTool } from "@copilotkit/react-core/v2";
import { z } from "zod";
useRenderTool({
name: "generate_haiku",
parameters: z.object({
japanese: z.array(z.string()),
english: z.array(z.string()),
}),
render: ({ args, status }) => {
if (!args.japanese) return <></>; // still streaming
return <HaikuCard japanese={args.japanese} english={args.english} />;
},
});
```
The tool is scoped to the active agent by the `<CopilotKit agent="haiku">` provider, so no `agentId` is needed here. A few things to note:
- **`name` must match the backend tool name** exactly (`generate_haiku`). That match is how CopilotKit routes the call to this component.
- **`render` receives `{ args, status }`.** `args` fills in progressively as the model streams the call; early on it may be empty or partial. `status` moves through `"inProgress"` / `"executing"` to `"complete"` if you want to show a loading state while arguments stream.
- **Guard against partial args.** Return an empty fragment until the fields you need exist. Here we wait for `args.japanese` before rendering the card.
</Step>
<Step title="Render the haiku">
The `render` function delegates to an ordinary React component. Nothing about it is CopilotKit-specific: it takes props and returns markup.
```tsx
function HaikuCard({
japanese,
english,
}: {
japanese: string[];
english: string[];
}) {
return (
<div className="haiku-card">
{japanese.map((line, i) => (
<div key={i} className="haiku-line">
<span className="jp">{line}</span>
<span className="en">{english?.[i]}</span>
</div>
))}
</div>
);
}
```
Because `english` streams in alongside `japanese`, use optional access (`english?.[i]`) so the card renders cleanly while the translation is still arriving.
</Step>
<Step title="Run it">
Start both processes and ask the assistant for a haiku. The card renders as the arguments stream in, filling out line by line.
```bash
uvicorn server:app --port 8000 # terminal 1
npm run dev # terminal 2
```
</Step>
</Steps>
## How progressive rendering works
The model does not emit the tool call all at once. It streams tokens, and CopilotKit re-invokes your `render` function every time a new chunk of arguments arrives:
1. The call begins. `args` is empty, so your guard returns an empty fragment.
2. `args.japanese` fills in line by line. The card appears and grows.
3. `args.english` fills in. Translations slot into place.
4. The call completes. `args` holds the final, fully-validated object.
This is why the partial-args guard matters: `render` runs against incomplete data by design. Read only the fields you have, and let the rest paint as they arrive.
## Backend tools
The `generate_haiku` tool above has no Python implementation — it exists only so the model emits a structured call the frontend renders. But a **real tool your Crew or Flow runs server-side** renders the same way.
When an Agent or Crew executes a tool during its run, the bridge surfaces that tool call along with its **result**. Register a `useRenderTool` for the tool's name and read `result` in the render:
```tsx
useRenderTool({
name: "get_weather",
parameters: z.object({ location: z.string() }),
render: ({ args, result, status }) => {
if (status !== "complete") return <WeatherSkeleton location={args.location} />;
return <WeatherCard data={JSON.parse(result)} />;
},
});
```
<Note>
A backend tool must return a **JSON string**, not a Python dict. The bridge stringifies tool output, so a raw dict arrives as a Python repr the browser cannot `JSON.parse`. Return `json.dumps(...)` from the tool.
</Note>
## Related
<CardGroup cols={2}>
<Card title="Agentic Generative UI" icon="list-check" href="/edge/en/guides/frontend/agentic-generative-ui">
Render live agent state as it changes across a multi-step run.
</Card>
<Card title="Human-in-the-Loop" icon="user-check" href="/edge/en/guides/frontend/human-in-the-loop">
Pause the agent to collect user approval or input mid-run.
</Card>
<Card title="Frontend Actions" icon="bolt" href="/edge/en/guides/frontend/frontend-actions">
Let the agent call functions that run in the browser.
</Card>
</CardGroup>

View File

@@ -120,6 +120,11 @@ def add_defaults(ctx):
Rewritten inputs flow into task interpolation, so the run behaves as if it was
kicked off with the modified dict.
Prefer `INPUT` for rewriting and treat `EXECUTION_START` as the allow/deny
gate. Rewrites at `EXECUTION_START` are still honored — on crews they also
feed the `before_kickoff` callbacks; on flows they land exactly like an
`INPUT` rewrite.
### Output Sanitization
```python
@@ -156,9 +161,10 @@ def report_outcome(ctx):
```
Two caveats: `EXECUTION_END` does not fire when `EXECUTION_START` never
dispatched (an abort at start counts as the execution never beginning), and
raising `HookAborted` from a failure-path `EXECUTION_END` dispatch is ignored —
there is nothing left to abort, and the original error wins.
dispatched (an abort at start means the boundary never opened, so there is no
end to pair), and raising `HookAborted` from a failure-path `EXECUTION_END`
dispatch is ignored — there is nothing left to abort, and the original error
wins.
## Ordering
@@ -168,6 +174,19 @@ For a crew run the boundary order is:
EXECUTION_START → before_kickoff callbacks → INPUT → tasks execute → OUTPUT → EXECUTION_END
```
For a flow run, the boundary hooks resolve the inputs before the lifecycle
events begin:
```
EXECUTION_START → INPUT → FlowStartedEvent → flow methods execute → OUTPUT → EXECUTION_END → FlowFinishedEvent
```
`FlowStartedEvent` carries the hook-resolved inputs, and rewriting
`inputs["id"]` in a boundary hook redirects state restoration. An abort at
`EXECUTION_START` still surfaces as `FlowStartedEvent` followed by
`FlowFailedEvent`, emitted at the abort with the payload as resolved by the
hooks that ran before it.
Hooks at the same point run in registration order, global hooks first, then
crew-scoped hooks. Telemetry (`HookDispatchedEvent`) is emitted per dispatch.

View File

@@ -176,7 +176,7 @@ grep -r "llm:" --include="*.yaml" .
# llm = LLM(model="mistral/mistral-large-latest")
# After (Native):
llm = LLM(model="gemini/gemini-2.0-flash")
llm = LLM(model="gemini/gemini-3.7-flash")
```
```bash
@@ -399,7 +399,7 @@ llm = LLM(model="anthropic/claude-haiku-3-5") # Fast & affordable
# Together AI → OpenAI or Gemini
# llm = LLM(model="together_ai/meta-llama/Meta-Llama-3.1-70B")
llm = LLM(model="openai/gpt-4o") # High quality
llm = LLM(model="gemini/gemini-2.0-flash") # Fast & capable
llm = LLM(model="gemini/gemini-3.7-flash") # Fast & capable
# Mistral → Anthropic or OpenAI
# llm = LLM(model="mistral/mistral-large-latest")

View File

@@ -141,7 +141,7 @@ You can connect to OpenAI-compatible LLMs using either environment variables or
# Example using Gemini's OpenAI-compatible API.
os.environ["OPENAI_API_KEY"] = "your-gemini-key" # Should start with AIza...
os.environ["OPENAI_API_BASE"] = "https://generativelanguage.googleapis.com/v1beta/openai/"
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-2.0-flash" # Add your Gemini model here, under openai/
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-3.7-flash" # Add your Gemini model here, under openai/
```
</CodeGroup>
</Tab>
@@ -159,7 +159,7 @@ You can connect to OpenAI-compatible LLMs using either environment variables or
```python Google
# Example using Gemini's OpenAI-compatible API
llm = LLM(
model="openai/gemini-2.0-flash",
model="openai/gemini-3.7-flash",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key="your-gemini-key", # Should start with AIza...
)

View File

@@ -147,7 +147,7 @@ Planning agents benefit from reasoning models that can handle complex strategic
from crewai import Agent, Task, Crew, LLM
# High-capability reasoning model for strategic planning
manager_llm = LLM(model="gemini-2.5-flash-preview-05-20", temperature=0.1)
manager_llm = LLM(model="gemini/gemini-3.7-flash", temperature=0.1)
# Creative model for content generation
content_llm = LLM(model="claude-3-5-sonnet-20241022", temperature=0.7)
@@ -412,7 +412,7 @@ Rather than repeating the strategic framework, here's a tactical checklist for i
# Manager or coordination agents
manager_agent = Agent(
role="Project Manager",
llm=LLM(model="gemini-2.5-flash-preview-05-20"), # Premium for coordination
llm=LLM(model="gemini/gemini-3.7-flash"), # Premium for coordination
# ... rest of config
)

View File

@@ -151,7 +151,7 @@ Conversational Flows can stream one user turn with `stream_turn()`:
```python
from crewai import Flow
from crewai.experimental.conversational import ConversationConfig, ConversationState
from crewai.flow import ConversationConfig, ConversationState
@ConversationConfig(llm="gpt-4o-mini", defer_trace_finalization=True)

View File

@@ -7,9 +7,9 @@ mode: "wide"
# Arize Phoenix Integration
This guide demonstrates how to integrate **Arize Phoenix** with **CrewAI** using OpenTelemetry via the [OpenInference](https://github.com/openinference/openinference) SDK. By the end of this guide, you will be able to trace your CrewAI agents and easily debug your agents.
This guide demonstrates how to integrate **Arize Phoenix** with **CrewAI** using OpenTelemetry via the [OpenInference](https://github.com/openinference/openinference) SDK. By the end of this guide, you will be able to trace your CrewAI agents and debug agent behavior.
> **What is Arize Phoenix?** [Arize Phoenix](https://phoenix.arize.com) is an LLM observability platform that provides tracing and evaluation for AI applications.
> **What is Arize Phoenix?** [Arize Phoenix](https://arize.com/phoenix/) is the open-source observability and evaluation option from [Arize AI](https://arize.com/?utm_source=crewai-docs&utm_medium=partner&utm_campaign=partner-docs&utm_content=observability-arize-phoenix). Use Phoenix when you want to run locally or self-host. Use [Arize AX](https://arize.com/products/ax/) for a managed cloud or enterprise self-hosted platform for production AI systems.
[![Watch a Video Demo of Our Integration with Phoenix](https://storage.googleapis.com/arize-assets/fixtures/setup_crewai.png)](https://www.youtube.com/watch?v=Yc5q3l6F7Ww)
@@ -27,7 +27,7 @@ pip install openinference-instrumentation-crewai crewai crewai-tools arize-phoen
### Step 2: Set Up Environment Variables
Setup Phoenix Cloud API keys and configure OpenTelemetry to send traces to Phoenix. Phoenix Cloud is a hosted version of Arize Phoenix, but it is not required to use this integration.
Configure your Phoenix API key and OpenTelemetry endpoint to send traces to Phoenix. The same setup works with a local or self-hosted Phoenix endpoint by changing the collector URL.
You can get your free Serper API key [here](https://serper.dev/).
@@ -35,8 +35,8 @@ You can get your free Serper API key [here](https://serper.dev/).
import os
from getpass import getpass
# Get your Phoenix Cloud credentials
PHOENIX_API_KEY = getpass("🔑 Enter your Phoenix Cloud API Key: ")
# Get your Phoenix API key
PHOENIX_API_KEY = getpass("🔑 Enter your Phoenix API key: ")
# Get API keys for services
OPENAI_API_KEY = getpass("🔑 Enter your OpenAI API key: ")
@@ -44,7 +44,7 @@ SERPER_API_KEY = getpass("🔑 Enter your Serper API key: ")
# Set environment variables
os.environ["PHOENIX_CLIENT_HEADERS"] = f"api_key={PHOENIX_API_KEY}"
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "https://app.phoenix.arize.com" # Phoenix Cloud, change this to your own endpoint if you are using a self-hosted instance
os.environ["PHOENIX_COLLECTOR_ENDPOINT"] = "https://app.phoenix.arize.com" # Change this to your own endpoint if you are using a self-hosted instance
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
os.environ["SERPER_API_KEY"] = SERPER_API_KEY
```
@@ -133,7 +133,7 @@ print(result)
After running the agent, you can view the traces generated by your CrewAI application in Phoenix. You should see detailed steps of the agent interactions and LLM calls, which can help you debug and optimize your AI agents.
Log into your Phoenix Cloud account and navigate to the project you specified in the `project_name` parameter. You'll see a timeline view of your trace with all the agent interactions, tool usages, and LLM calls.
Open your Phoenix project and navigate to the project you specified in the `project_name` parameter. You'll see a timeline view of your trace with all the agent interactions, tool usages, and LLM calls.
![Example trace in Phoenix showing agent interactions](https://storage.googleapis.com/arize-assets/fixtures/crewai_traces.png)
@@ -147,6 +147,9 @@ Log into your Phoenix Cloud account and navigate to the project you specified in
### References
- [Phoenix Documentation](https://docs.arize.com/phoenix/) - Overview of the Phoenix platform.
- [Arize AX](https://arize.com/products/ax/) - Managed cloud and enterprise self-hosted observability and evaluation.
- [Arize agent evaluation guide](https://arize.com/guides/ai-agent-handbook/agent-evaluation/) - Production workflow for evaluating agent behavior from traces.
- [Arize LLM evaluation guide](https://arize.com/resources/llm-evaluation/) - Methods and metrics for evaluating LLM applications.
- [CrewAI Documentation](https://docs.crewai.com/) - Overview of the CrewAI framework.
- [OpenTelemetry Docs](https://opentelemetry.io/docs/) - OpenTelemetry guide
- [OpenInference GitHub](https://github.com/openinference/openinference) - Source code for OpenInference SDK.

View File

@@ -9,7 +9,7 @@ mode: "wide"
CrewAI provides built-in tracing capabilities that allow you to monitor and debug your Crews and Flows in real-time. This guide demonstrates how to enable tracing for both **Crews** and **Flows** using CrewAI's integrated observability platform.
> **What is CrewAI Tracing?** CrewAI's built-in tracing provides comprehensive observability for your AI agents, including agent decisions, task execution timelines, tool usage, and LLM calls - all accessible through the [CrewAI AMP platform](https://app.crewai.com).
> **What is CrewAI Tracing?** CrewAI's built-in tracing provides comprehensive observability for your AI agents, including agent decisions, task execution timelines, tool usage, and LLM calls - all accessible through the [CrewAI AMP platform](https://app.crewai.com). Tracing is managed independently from [telemetry](/en/telemetry).
![CrewAI Tracing Interface](/images/crewai-tracing.png)
@@ -170,6 +170,18 @@ CREWAI_TRACING_ENABLED=true
When this environment variable is set, all Crews and Flows will automatically have tracing enabled, even without explicitly setting `tracing=True`.
## Viewing traces after your first run
The first time you run a Crew or Flow, an interactive terminal may ask:
```text
Would you like to view your execution traces? [y/N]
```
Choose **yes** to open a view link. You can change this later with
`crewai traces enable` or `crewai traces disable`, or by setting `tracing`
on the Crew or Flow.
## Viewing Your Traces
### Access the CrewAI AMP Dashboard

View File

@@ -23,7 +23,8 @@ usage of tools, API calls, responses, any data processed by the agents, or secre
When the `share_crew` feature is enabled, detailed data including task descriptions, agents' backstories or goals, and other specific attributes are collected
to provide deeper insights. This expanded data collection may include personal information if users have incorporated it into their crews or tasks.
Users should carefully consider the content of their crews and tasks before enabling `share_crew`.
Users can disable telemetry by setting the environment variable `CREWAI_DISABLE_TELEMETRY` to `true` or by setting `OTEL_SDK_DISABLED` to `true` (note that the latter disables all OpenTelemetry instrumentation globally).
Users can disable CrewAI telemetry by setting `CREWAI_DISABLE_TELEMETRY` to `true`, `1`, `yes`, or `on` (any case). `OTEL_SDK_DISABLED` with the same values also disables CrewAI's exporter. The OpenTelemetry SDK itself still only honors `true` for disabling other instrumentation in the process.
AMP tracing is covered separately in [Tracing](/en/observability/tracing).
### Examples:
```python
@@ -34,18 +35,38 @@ os.environ['CREWAI_DISABLE_TELEMETRY'] = 'true'
os.environ['OTEL_SDK_DISABLED'] = 'true'
```
`CREWAI_DISABLE_TELEMETRY=1` (or `yes` / `on`) works the same as `true`. Unrecognized values are ignored and leave telemetry on.
### Isolation from your own OpenTelemetry setup
CrewAI's telemetry runs on its own private `TracerProvider` and never registers
itself as the global one. This keeps the two directions separate:
- Spans from other instrumented libraries in your process — web frameworks,
database clients, HTTP clients — are never sent to CrewAI.
- CrewAI's telemetry spans are never sent to your observability backend, so they
will not appear in Langfuse, Braintrust, Phoenix, or any other collector you
configure.
Observability integrations are unaffected: they instrument CrewAI through their
own tracer provider, which is independent of the one described here.
### Data Explanation:
| Defaulted | Data | Reason and Specifics |
|:----------|:------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------|
| Yes | CrewAI and Python Version | Tracks software versions. Example: CrewAI v1.2.3, Python 3.8.10. No personal data. |
| Yes | Crew Metadata | Includes: randomly generated key and ID, process type (e.g., 'sequential', 'parallel'), boolean flag for memory usage (true/false), count of tasks, count of agents. All non-personal. |
| Yes | Crew Metadata | Includes: randomly generated key and ID, process type (e.g., 'sequential', 'parallel'), boolean flag for memory usage (true/false), a boolean flag for whether any inputs were passed to the run (true/false — never the input keys or values, which are only collected when `share_crew` is enabled), count of tasks, count of agents. All non-personal. |
| Yes | Agent Data | Includes: randomly generated key and ID, role name (should not include personal info), boolean settings (verbose, delegation enabled, code execution allowed), max iterations, max RPM, max retry limit, LLM info (see LLM Attributes), list of tool names (should not include personal info). No personal data. |
| Yes | Task Metadata | Includes: randomly generated key and ID, boolean execution settings (async_execution, human_input), associated agent's role and key, list of tool names. All non-personal. |
| Yes | Tool Usage Statistics | Includes: tool name (should not include personal info), number of usage attempts (integer), LLM attributes used. No personal data. |
| Yes | Test Execution Data | Includes: crew's randomly generated key and ID, number of iterations, model name used, quality score (float), execution time (in seconds). All non-personal. |
| Yes | Task Lifecycle Data | Includes: creation and execution start/end times, crew and task identifiers. Stored as spans with timestamps. No personal data. |
| Yes | Task Lifecycle Data | Includes: creation and execution start/end times, crew and task identifiers, and whether the task succeeded or failed. When a task fails, the **class name** of the exception is recorded (for example `TimeoutError`) so failures can be counted and diagnosed — never the error message, which can contain prompts, model output, file paths or credentials. Stored as spans with timestamps. No personal data. |
| Yes | LLM Attributes | Includes: name, model_name, model, top_k, temperature, and class name of the LLM. All technical, non-personal data. |
| Yes | Crew Deployment attempt using crewAI CLI | Includes: The fact a deploy is being made and crew id, and if it's trying to pull logs, no other data. |
| Yes | Project Creation using crewAI CLI | Includes: that a new project was scaffolded by `crewai create`, which kind it was (`crew`, `json_crew` or `flow`), and the project ID minted for that new project and written into its own `pyproject.toml`. That is the new project's own ID, recorded separately from the `project_id` of the directory the command was run from — the two can differ. No project name, no file contents, no code. No personal data. |
| Yes | Crew Deployment attempt using crewAI CLI | Includes: The fact a deploy is being made and crew id, whether it's trying to pull logs, and whether the deploy was started from a CLI command or from the run TUI. No project or crew contents. No personal data. |
| Yes | Execution Environment | Includes: which AI coding assistant is running the process, if any (one of a fixed list such as `claude_code`, `codex`, `cursor`, or `unknown`), where the process runs (one of a fixed list such as `ci`, `container`, `serverless`, `interactive`), the `project_id` from your `pyproject.toml` when one is configured, and a coarse size band for the machine (one of `1-2`, `3-4`, `5-8`, `9-16`, `17-32`, `33+`, or `unknown`). The band is a range, never the exact core count — the exact count is opt-in only, under Environment Information below. The size band comes from the host CPU count; assistant and location detection reads only whether known environment variables are set, never their values. No personal data. |
| Yes | Flow Lifecycle Signals | Includes: that a flow started, whether it completed or failed, whether one of its methods failed, whether it paused for human input or feedback, whether the start was a resumed run, whether a conversation turn failed, how long the flow ran, and whether the flow is one CrewAI runs internally or one you wrote. The flow name is recorded, as it already is for flow creation and execution. When a flow or one of its methods fails, the **class name** of the exception is recorded (for example `TimeoutError`) so that failures can be diagnosed — never the error message, which can contain prompts, model output, file paths or credentials. Method names and flow state are never recorded. No personal data. |
| Yes | Trace Sharing Signal | Includes: that a batch of traces was successfully shared with CrewAI AMP, and whether it was shared anonymously (before you have an account) or linked to your account. Like every span, it also carries the Execution Environment attributes described above (`project_id` when configured, the coding assistant, and the runtime). This row describes sharing telemetry only — not the trace contents or access granted by shared trace links. Trace contents, inputs, and outputs are never recorded on this signal. Before sharing traces, review secrets, personal data, and AMP redaction and retention settings. |
| No | Agent's Expanded Data | Includes: goal description, backstory text, i18n prompt file identifier. Users should ensure no personal info is included in text fields. |
| No | Detailed Task Information | Includes: task description, expected output description, context references. Users should ensure no personal info is included in these fields. |
| No | Environment Information | Includes: platform, release, system, version, and CPU count. Example: 'Windows 10', 'x86_64'. No personal data. |

View File

@@ -50,16 +50,15 @@ These tools integrate with AI and machine learning services to enhance your agen
- **AI Safety**: Implement content moderation and safety checks
```python
from crewai_tools import DallETool, VisionTool, CodeInterpreterTool
from crewai_tools import DallETool, VisionTool
# Create AI tools
image_generator = DallETool()
vision_processor = VisionTool()
code_executor = CodeInterpreterTool()
# Add to your agent
agent = Agent(
role="AI Specialist",
tools=[image_generator, vision_processor, code_executor],
tools=[image_generator, vision_processor],
goal="Create and analyze content using AI capabilities"
)

View File

@@ -460,7 +460,7 @@ The `embedding_model` parameter accepts a `crewai.rag.embeddings.types.ProviderS
**Config Options:**
- `model_name` (str): HuggingFace model ID. Default: `hkunlp/instructor-base`. Options: `hkunlp/instructor-xl`, `hkunlp/instructor-large`, `hkunlp/instructor-base`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`, `mps`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`, `mps`, `xpu`
- `instruction` (str): Instruction prefix for embeddings
**Environment Variables:**
@@ -485,7 +485,7 @@ The `embedding_model` parameter accepts a `crewai.rag.embeddings.types.ProviderS
**Config Options:**
- `model_name` (str): Sentence Transformers model name. Default: `all-MiniLM-L6-v2`. Options: `all-mpnet-base-v2`, `all-MiniLM-L6-v2`, `paraphrase-multilingual-MiniLM-L12-v2`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`, `mps`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`, `mps`, `xpu`
- `normalize_embeddings` (bool): Whether to normalize embeddings. Default: `False`
**Environment Variables:**

View File

@@ -12,6 +12,16 @@ mode: "wide"
This tool is used to extract text from images. When passed to the agent it will extract the text from the image and then use it to generate a response, report or any other output.
The URL or the PATH of the image should be passed to the Agent.
You can also ask a custom `query` about the image and pick a `complexity_level` that automatically selects the model best suited for the request:
| Complexity level | Model |
| :--------------- | :------------ |
| `easy` | `gpt-5.6-luna` |
| `medium` (default) | `gpt-5.6-terra` |
| `hard` | `gpt-5.6-sol` |
When an explicit `llm` or `model` is provided to the tool, it takes precedence over the complexity-based model selection.
## Installation
Install the crewai_tools package
@@ -43,8 +53,10 @@ def researcher(self) -> Agent:
## Arguments
The VisionTool requires the following arguments:
The VisionTool accepts the following arguments:
| Argument | Type | Description |
| :----------------- | :------- | :------------------------------------------------------------------------------- |
| **image_path_url** | `string` | **Mandatory**. The path to the image file from which text needs to be extracted. |
| Argument | Type | Description |
| :------------------- | :------- | :----------------------------------------------------------------------------------------------------------- |
| **image_path_url** | `string` | **Mandatory**. The path to the image file (or URL) from which text needs to be extracted. |
| **query** | `string` | **Optional**. The question or instruction to ask the model about the image. Defaults to `"What's in this image?"`. |
| **complexity_level** | `string` | **Optional**. The complexity of the request, which selects the model: `easy`, `medium`, or `hard`. Defaults to `medium`. |

View File

@@ -77,4 +77,4 @@ To let an agent read a directory tree outside the working directory, point `base
file_read_tool = FileReadTool(base_dir='/data')
```
As a last resort, setting `CREWAI_TOOLS_ALLOW_UNSAFE_PATHS=true` disables path validation. This applies process-wide to every crewai-tools tool, including the SSRF protections on URL-fetching tools, so prefer `base_dir`.
As a last resort, setting `CREWAI_TOOLS_ALLOW_UNSAFE_PATHS=true` disables path validation. This applies process-wide to every crewai-tools tool, including the SSRF protections on URL-fetching tools, so prefer `base_dir`. Managed workers should set `CREWAI_TOOLS_FORCE_SAFE_PATHS=true` so a tenant cannot disable those checks by exporting the escape hatch.

View File

@@ -4,7 +4,7 @@ description: >
Oxylabs Scrapers allow to easily access the information from the respective sources. Please see the list of available sources below:
- `Amazon Product`
- `Amazon Search`
- `Google Seach`
- `Google Search`
- `Universal`
icon: globe
mode: "wide"
@@ -87,7 +87,7 @@ print(result)
### Parameters
- `query` - Amazon search term.
- `domain` - Domain localization for Bestbuy.
- `domain` - domain localization for Amazon.
- `start_page` - starting page number.
- `pages` - number of pages to retrieve.
- `geo_location` - the _Deliver to_ location.

View File

@@ -9,7 +9,7 @@ mode: "wide"
## Description
The `ScrapeElementFromWebsiteTool` is designed to extract specific elements from websites using CSS selectors. This tool allows CrewAI agents to scrape targeted content from web pages, making it useful for data extraction tasks where only specific parts of a webpage are needed.
The `ScrapeElementFromWebsiteTool` is designed to extract specific elements from websites using CSS selectors. This tool allows CrewAI agents to scrape targeted content from web pages, making it useful for data extraction tasks where only specific parts of a webpage are needed. Fetches go through CrewAI's SSRF-safe HTTP helper: the requested URL and every redirect hop are checked against private and reserved ranges (including cloud metadata), and the TCP connection is pinned to an IP that passed that check.
## Installation

View File

@@ -16,6 +16,8 @@ mode: "wide"
A tool designed to extract and read the content of a specified website. It is capable of handling various types of web pages by making HTTP requests and parsing the received HTML content.
This tool can be particularly useful for web scraping tasks, data collection, or extracting specific information from websites.
Fetches go through CrewAI's SSRF-safe HTTP helper: the requested URL and every redirect hop are checked against private and reserved ranges (including cloud metadata), and the TCP connection is pinned to an IP that passed that check.
## Installation
Install the crewai_tools package

View File

@@ -4,6 +4,322 @@ description: "CrewAI의 제품 업데이트, 개선 사항 및 버그 수정"
icon: "clock"
mode: "wide"
---
<Update label="2026년 9월 9일">
## v1.15.21
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.21)
## 변경 사항
### 기능
- 체크포인트 실행 시간 및 CLI 사용을 추적하기 위한 텔레메트리 추가.
### 버그 수정
- HTTP 200 응답 내에서 보고된 게이트웨이 오류 수정.
- AMP 소스 생성 시 배포 푸시 유지.
- Oxylabs 통합에서 IndexError를 발생시키는 대신 스크랩 실패 보고.
- 모든 DashScope 모델을 네이티브 제공자를 통해 라우팅.
- JSON 체크포인트를 UTF-8로 유지.
- BrightData의 f-string 검색 URL에서 이탈한 $ 제거.
- JSON 스키마 변환에서 리스트 형태의 배열 지원.
- gpt-4o-mini 컨텍스트 창 크기를 200000에서 128000으로 수정.
- contentBlockStop에서 스트리밍 도구 호출 인수 유지.
- Windows에서 pre-commit 훅을 휴대 가능하게 만듦.
### 문서
- 추적이 텔레메트리와 별도로 관리됨을 명확히 함.
- 병렬 검색 참조 링크 수정.
- handle_llm_stream_chunk 문서 문자열에서 오래된 매개변수 제거.
- 스트리밍 출력 문서 문자열 예제 수정.
- 기술 설치 참조에서 조직 UUID 사용.
## 기여자
@Alphaxiaoteng, @DrewWhittleNZ, @Ghraven, @Shxiao101, @Vaishnavi220506, @Vidit-Ostwal, @danielfsbarreto, @georgeatparallel, @github-actions[bot], @jessemiller, @joaomdmoura, @kimnamu, @kiwoongyoon, @liang0417, @lorenzejay, @oxy-giedrius, @simpleqt, @uoparaji
</Update>
<Update label="2026년 9월 4일">
## v1.15.20
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.20)
## 변경 사항
### 버그 수정
- 레거시 플랫폼 도구 별칭 검색 수정
### 문서
- v1.15.19에 대한 스냅샷 및 변경 로그 업데이트
## 기여자
@joaomdmoura, @vinibrsl
</Update>
<Update label="2026년 9월 4일">
## v1.15.19
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.19)
## 변경 사항
### 기능
- Clipper 통합 클라이언트 추가
- CEL 표현식 환경에 `now()` 추가
- 모든 사용자에 대해 크루 실행이 어떻게 종료되었는지 기록
- 기계 크기를 코어 수가 아닌 대략적인 범위로 보고
- CrewAI 플랫폼 도구를 위한 주입 가능한 클라이언트 추가
### 버그 수정
- `urlreadtool`에서 octet-stream 및 xlsx URL 읽기 수정
- 네이티브 Gemini 제공자에서 후행 사용자 전환 추가 수정
- Ollama 기본 URL에서 스킴 및 포트 정규화
- 메모리에서 재사용 가능한 범위 구성 유지
- 보안 취약성을 위해 `pypdf`를 6.16.2로 업데이트
- 보안 취약성을 위해 `nltk`를 3.10.3으로 업데이트
- 현재 Claude 모델 및 Snowflake CVE 바닥을 위한 네이티브 구조화된 출력 수정
- 모든 경로에서 모델 호출 후크 실행 및 거부 전파
### 문서
- AI/ML 개요 예제에서 `CodeInterpreterTool` 제거
- `prompt-template` 링크를 현재 경로로 지정
- 현재 CopilotKit 채널 API에 맞게 채널 가이드 업데이트
- 퇴역한 Gemini 모델 ID 새로 고침
## 기여자
@Vidit-Ostwal, @a-yeyang, @github-actions[bot], @hvlcrs, @joaomdmoura, @kikifrost, @lorenzejay, @lucasgomide, @parthiban-sivakumar, @ranst91, @tandede, @thiagomoretto, @vinibrsl
</Update>
<Update label="2026년 8월 27일">
## v1.15.18
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.18)
## 변경 사항
### 기능
- 대화 흐름을 안정 상태로 승격
- 주어진 UUID로 생성된 배포를 기록
- 대화 흐름 문서 및 API 개선
- 선언이 라우터의 응답 형식을 지정하도록 허용
- 채팅 흐름이 자체 상태 형태를 선언하도록 허용
- 대화 선언에서 크루 스타일 LLM 구성 수용
- 발급된 ID로 프로젝트 생성 보고
- 실행에 입력이 있었는지 여부를 기록하되 입력은 기록하지 않음
- 모든 사용자 호출 프로젝트 명령에서 프로젝트 ID를 백필
### 버그 수정
- 최종 답변이 비어 있을 때 도구 결과 보존
- 기본 Claude Sonnet 4.6을 1M 컨텍스트 윈도우에 매핑
- 대형 도구 호출을 위한 Anthropic 기본 max_tokens 증가
- 메시지 내용 부분을 텍스트로 렌더링, Python repr로 렌더링하지 않음
- Agent.kickoff가 대화를 받을 때 메시지 역할 유지
- crewai 내부 흐름에서 가로채기 후크 건너뛰기
- 작업 실패를 실패로 기록하고 성공으로 기록하지 않음
- 억제된 재개에서 흐름 생명 주기 방출
- 선언적 채팅 흐름을 위한 대화형 TUI 열기
- crew_memory를 문자열로 기록하고 불리언으로 기록하지 않음
- 항상 project_id를 방출하여 부재 및 비어 있는 상태를 구분
### 문서
- Arize Phoenix 가시성 문서 명확화
## 기여자
@Vidit-Ostwal, @arizedatngo, @joaomdmoura, @lorenzejay, @lucasgomide
</Update>
<Update label="2026년 8월 19일">
## v1.15.17
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.17)
## 변경 사항
### 기능
- 선언적 대화 흐름 문서 추가
- 선언을 위한 내장 대화 방법 합성
- 선언이 대화 모드를 주도할 수 있도록 활성화
- 대화 선택 참여를 명확하게 표시
- 슬러그 참조에서 해결된 도구에 AMP 슬러그 전달
- 청크 처리 중 과도한 단일 메시지 처리
### 버그 수정
- MCP HTTP 및 SSE server_name으로 URL 호스트 이름 사용 수정
- 모든 실패한 시도에서 에이전트 범위 닫기
- 도구 오류를 실패한 도구에 귀속
- 각 리디렉션 홉 및 피어 IP에 SSRF 검사 고정
- OpenAI Responses API를 통해 깨진 네이티브 도구 호출 문제 해결
### 문서
- v1.15.16에 대한 스냅샷 및 변경 로그로 문서 업데이트
## 기여자
@Copilot, @Vidit-Ostwal, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="2026년 8월 13일">
## v1.15.16
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.16)
## 변경 사항
### 기능
- UUID 지원을 통한 실행 컨텍스트 관리 도입
- 흐름을 종료한 예외의 종류 기록
- 트레이스 배치가 AMP와 공유된 시점 기록
- 모든 출처에서 배포를 카운트하고 시작 위치 기록
### 버그 수정
- 모든 생성된 스팬에서 실행 중인 릴리스를 기록
- MySQL 검색 테이블 이름 유효성 검사 수정
- 실패한 턴이 다음 턴을 실패로 표시하지 않도록 중지
### 문서
- CopilotKit 및 AG-UI에 대한 프론트엔드 가이드 추가
## 기여자
@joaomdmoura, @lorenzejay, @ranst91, @theCyberTech
</Update>
<Update label="2026년 8월 11일">
## v1.15.15
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.15)
## 변경 사항
### 기능
- 보고서 흐름 결과, 지속 시간 및 인간 개입 신호를 보고합니다.
### 버그 수정
- 경계 후크가 흐름을 중단할 때 FlowStartedEvent를 발생시킵니다.
- 범위 스팬 내보내기를 우리 고유의 트레이서 제공자로 제한합니다.
- 보안 취약점을 해결하기 위해 torch를 2.13.0 버전으로 업데이트합니다.
- crewai-tools[github]에서 gitpython을 3.1.58 버전으로 업데이트합니다.
### 리팩토링
- 에이전트의 날짜 주입 기능을 업데이트합니다.
- CLI 플래그를 케밥 케이스로 표준화합니다.
### 문서
- v1.15.14에 대한 스냅샷 및 변경 로그.
## 기여자
@Vidit-Ostwal, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="2026년 8월 8일">
## v1.15.14
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.14)
## 변경 사항
### 기능
- 코딩 에이전트와 런타임 컨텍스트 분리 및 프로젝트 ID 추가
### 문서
- v1.15.13에 대한 스냅샷 및 변경 로그 업데이트
## 기여자
@joaomdmoura
</Update>
<Update label="2026년 8월 7일">
## v1.15.13
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.13)
## 변경 사항
### 버그 수정
- LiteLLM 라우팅 모델에서 제공자의 보존 문제 수정.
- 취약한 LLM 이벤트 버스 모의 객체 강화.
- Anthropic 캐시 토큰 사용량의 과소 보고 문제 수정.
- 보안 취약점 GHSA-6hr6-w5qg-qmwg를 해결하기 위해 h2를 버전 4.4.1로 업데이트.
### 문서
- 로케일 동기화를 위한 DOCS_TRANSLATIONS 워크플로 추가.
- 깨진 README 링크, 목차 및 기여 가이드 수정.
- 버전 1.15.12에 대한 스냅샷 및 변경 로그.
## 기여자
@Vidit-Ostwal, @joaomdmoura, @lucasgomide, @theCyberTech
</Update>
<Update label="2026년 8월 5일">
## v1.15.12
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.12)
## 변경 사항
### 기능
- 릴리스 시 Flow 카나리 버전 증가
- 임의의 URL을 읽기 위한 URLReadTool 추가
- 플랫폼 액션 도구에 앱 메타데이터 추가
- `crewai create <resource>` 아래에서 스캐폴딩 통합
### 버그 수정
- 대화형 경로/핸들러 이름 충돌 오류 명확화
### 문서
- 통합된 생성 CLI를 위한 AGENTS.md 스캐폴드 업데이트
### 주요 변경 사항
- 없음
## 기여자
@Vidit-Ostwal, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="2026년 8월 4일">
## v1.15.11
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.11)
## 변경 사항
### 기능
- 텔레메트리에서 인터셉션 훅 디스패치를 추적합니다.
- OSS 사용을 기업 계정에 연결하기 위해 project_id를 추가합니다.
- AGENTS.md에서 AMP를 표시하고 텔레메트리에서 코딩 에이전트를 감지합니다.
- IBM Db2 검색 도구를 추가합니다.
### 버그 수정
- CodeQL의 불완전한 URL 하위 문자열 정화 경고를 지웁니다.
- 여섯 개의 GHSA 권고 사항을 해결하기 위해 aiohttp와 cryptography를 업데이트합니다.
- 맵 리터럴 내 실패에 대한 실제 CEL 오류를 보고합니다.
- 문서 전용 PR에 대해 코드 CI를 올바르게 건너뜁니다.
### 문서
- v1.15.10에 대한 스냅샷 및 변경 로그
## 기여자
@PawanThakurIBM, @Vidit-Ostwal, @gabemilani, @joaomdmoura, @lorenzejay, @lucasgomide, @theCyberTech
</Update>
<Update label="2026년 7월 31일">
## v1.15.10

View File

@@ -56,7 +56,7 @@ CrewAI AOP에는 코드를 작성하지 않고도 에이전트 생성 및 구성
| **컨텍스트 윈도우 준수** _(옵션)_ | `respect_context_window` | `bool` | 메시지를 컨텍스트 윈도우 크기 내로 유지하기 위하여 요약 기능을 사용합니다. 기본값은 True입니다. |
| **코드 실행 모드** _(옵션)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | 코드 실행 모드: 'safe'(Docker 사용) 또는 'unsafe'(직접 실행). 기본값은 'safe'입니다. |
| **멀티모달** _(옵션)_ | `multimodal` | `bool` | 에이전트가 멀티모달 기능을 지원하는지 여부입니다. 기본값은 False입니다. |
| **날짜 자동 삽입** _(옵션)_ | `inject_date` | `bool` | 작업에 현재 날짜를 자동으로 삽입할지 여부입니다. 기본값은 False입니다. |
| **날짜 자동 삽입** _(옵션)_ | `inject_date` | `bool` | 에이전트 프롬프트에 현재 날짜를 자동으로 삽입할지 여부입니다. 기본값은 False입니다. |
| **날짜 형식** _(옵션)_ | `date_format` | `str` | inject_date 활성화 시 날짜 표시 형식 문자열입니다. 기본값은 "%Y-%m-%d"(ISO 포맷)입니다. |
| **추론** _(옵션)_ | `reasoning` | `bool` | 에이전트가 작업을 실행하기 전에 반영 및 플랜을 생성할지 여부입니다. 기본값은 False입니다. |
| **최대 추론 시도 수** _(옵션)_ | `max_reasoning_attempts` | `Optional[int]` | 작업 실행 전 최대 추론 시도 횟수입니다. 설정하지 않으면 준비될 때까지 시도합니다. |
@@ -267,7 +267,7 @@ strategic_agent = Agent(
role="Market Analyst",
goal="Track market movements with precise date references and strategic planning",
backstory="Expert in time-sensitive financial analysis and strategic reporting",
inject_date=True, # Automatically inject current date into tasks
inject_date=True, # Automatically inject current date into the prompt
date_format="%B %d, %Y", # Format as "May 21, 2025"
reasoning=True, # Enable strategic planning
max_reasoning_attempts=2, # Limit planning iterations
@@ -328,7 +328,7 @@ multimodal_agent = Agent(
#### 고급 기능
- `multimodal`: 텍스트와 시각적 콘텐츠 처리를 위한 멀티모달 기능 활성화
- `reasoning`: 에이전트가 작업을 수행하기 전에 반영하고 계획을 작성할 수 있도록 활성화
- `inject_date`: 현재 날짜를 작업 설명에 자동으로 삽입
- `inject_date`: 현재 날짜를 에이전트 프롬프트에 자동으로 삽입
#### 템플릿
- `system_template`: 에이전트의 핵심 동작을 정의합니다
@@ -630,6 +630,11 @@ messages = [
result = researcher.kickoff(messages)
```
마지막 `user` 메시지가 에이전트가 답변할 요청입니다. 나머지 메시지는 각자의 역할과
그 요청을 기준으로 한 위치를 그대로 유지하므로, assistant 또는 tool 메시지로 끝나는
대화도 사용자의 질문을 그대로 전달하며 뒤따르는 턴도 요청 뒤에 그대로 전달됩니다.
`user` 메시지가 전혀 없으면 마지막 메시지를 요청으로 처리합니다.
### 비동기 지원
동일한 매개변수를 사용하는 비동기 버전은 `kickoff_async()`를 통해 사용할 수 있습니다:

View File

@@ -54,6 +54,16 @@ crewai create flow my_new_flow
기본적으로 `crewai create crew`는 `crew.jsonc`와 `agents/*.jsonc`가 있는 JSON-first 프로젝트를 만듭니다. `crew.py`, `config/agents.yaml`, `config/tasks.yaml`을 사용하는 기존 Python/YAML 스캐폴드가 필요할 때만 `crewai create crew my_new_crew --classic`을 사용하세요.
#### 사용 중단된 플래그 별칭
이전 snake_case 플래그는 여전히 동작하지만 `--help`에는 표시되지 않습니다. 아래 각 명령 섹션에 문서화된 kebab-case 형식을 사용하세요.
| 사용 중단 | 대신 사용 |
| :--- | :--- |
| `--skip_provider` (`crewai create crew`) | `--skip-provider` |
| `--n_iterations` (`crewai train`, `crewai test`) | `--n-iterations` |
| `--task_id` (`crewai replay`) | `--task-id` |
### 2. 버전
설치된 CrewAI의 버전을 표시합니다.
@@ -79,7 +89,7 @@ crewai version --tools
crewai train [OPTIONS]
```
- `-n, --n_iterations INTEGER`: crew를 훈련할 반복 횟수 (기본값: 5)
- `-n, --n-iterations INTEGER`: crew를 훈련할 반복 횟수 (기본값: 5)
- `-f, --filename TEXT`: 훈련에 사용할 커스텀 파일의 경로 (기본값: "trained_agents_data.pkl")
예시:
@@ -96,7 +106,7 @@ crewai train -n 10 -f my_training_data.pkl
crewai replay [OPTIONS]
```
- `-t, --task_id TEXT`: 이 task ID에서부터 crew를 다시 재생하며, 이후의 모든 task를 포함합니다.
- `-t, --task-id TEXT`: 이 task ID에서부터 crew를 다시 재생하며, 이후의 모든 task를 포함합니다.
예시:
@@ -143,7 +153,7 @@ crew를 테스트하고 결과를 평가합니다.
crewai test [OPTIONS]
```
- `-n, --n_iterations INTEGER`: crew를 테스트할 반복 횟수 (기본값: 3)
- `-n, --n-iterations INTEGER`: crew를 테스트할 반복 횟수 (기본값: 3)
- `-m, --model TEXT`: Crew에서 테스트를 실행할 LLM 모델 (기본값: "gpt-4o-mini")
예시:
@@ -276,6 +286,7 @@ crewai org switch <organization_id>
- CrewAI AMP 플랫폼에서 배포 프로세스를 시작합니다.
- 성공적으로 시작되면, Deployment created successfully! 메시지와 함께 Deployment Name 및 고유한 Deployment ID(UUID)가 출력됩니다.
- Push는 생성 시 사용한 소스를 유지합니다. 나중에 git `origin`을 추가해도 ZIP 배포가 git으로 바뀌지 않습니다.
- **배포 상태**: 배포 상태를 확인하려면 다음을 사용합니다:

View File

@@ -324,6 +324,8 @@ crew는 메모리(단기, 장기 및 엔티티 메모리)를 활용하여 시간
crew 실행 후, `usage_metrics` 속성에 접근하여 crew가 실행한 모든 작업에 대한 언어 모델(LLM) 사용 메트릭을 확인할 수 있습니다. 이를 통해 운영 효율성과 개선이 필요한 영역에 대한 인사이트를 얻을 수 있습니다.
`total_tokens`는 청구된 총합(`prompt_tokens + completion_tokens`)입니다. `cached_prompt_tokens` 및 `cache_creation_tokens`와 같은 breakdown 필드는 이미 해당 총합에 포함된 부분 집합을 설명하며 `total_tokens` 위에 다시 더하지 않습니다. 전체 계약은 Flows 개념 문서의 **UsageMetrics field semantics** 섹션을 참조하세요.
```python Code
# Access the crew's usage metrics
crew = Crew(agents=[agent1, agent2], tasks=[task1, task2])

View File

@@ -261,6 +261,24 @@ print(flow.usage_metrics)
**전체** 토큰 집계가 필요할 때는 항상 `flow.usage_metrics`를 사용하십시오.
</Note>
### UsageMetrics 필드 의미
반환되는 [`UsageMetrics`](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/types/usage_metrics.py) 객체는 제공자 중립 계약을 사용합니다:
| 필드 | 의미 |
| --- | --- |
| `total_tokens` | 청구된 총합: `prompt_tokens + completion_tokens` |
| `prompt_tokens` | 요청에 대해 청구된 전체 입력/프롬프트 토큰 |
| `completion_tokens` | 요청에 대해 청구된 출력/완료 토큰 |
| `cached_prompt_tokens` | 프롬프트 토큰 중 캐시 읽기 부분 집합 (breakdown 전용) |
| `cache_creation_tokens` | 프롬프트 토큰 중 캐시 쓰기 부분 집합 (breakdown 전용, Anthropic) |
| `reasoning_tokens` | 제공자가 별도로 보고하는 추론/사고 부분 집합 (breakdown 전용) |
| `successful_requests` | 집계된 LLM 호출 수 |
`cached_prompt_tokens`, `cache_creation_tokens`, `reasoning_tokens`와 같은 breakdown 필드는 `total_tokens` **위에 추가되지 않습니다** — 이미 `prompt_tokens` 또는 `completion_tokens`에 포함된 부분을 설명합니다.
Anthropic의 경우 캐시 읽기 및 쓰기 카운터가 `prompt_tokens`에 포함되므로, 캐시된 워크로드가 `total_tokens`에 완전히 반영됩니다. OpenAI 스타일 제공자는 캐시된 입력을 이미 `prompt_tokens`에 포함합니다. CrewAI는 가시성을 위해 캐시된 부분을 별도로 표시합니다.
반환되는 [`UsageMetrics`](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/types/usage_metrics.py)의 각 항목은 단일 `flow.kickoff()` 실행 동안 발생한 모든 LLM 호출의 합계입니다. 다음 `kickoff()` 호출(및 `kickoff_for_each`의 각 반복)에서 카운터가 초기화되므로 연속 실행이 이중으로 집계되지 않습니다. 이 속성은 `kickoff()` 완료 후 언제든지 안전하게 읽을 수 있으며, 실행 중에 읽으면 그 시점까지 누적된 부분 합계를 반환합니다.
## 플로우 상태 관리

View File

@@ -603,6 +603,21 @@ agent = Agent(
}
}
)
# Option 4: Use OpenRouter embeddings (supports models across providers)
# Set OPENROUTER_API_KEY environment variable if api_key is omitted in config
crew = Crew(
agents=[agent],
tasks=[...],
knowledge_sources=[knowledge_source],
embedder={
"provider": "openrouter",
"config": {
"model_name": "openai/text-embedding-3-small",
"api_key": "your-openrouter-api-key" # Optional if OPENROUTER_API_KEY is set
}
}
)
```
#### Azure OpenAI 임베딩 구성

View File

@@ -270,6 +270,21 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
)
```
**토큰 사용량 및 프롬프트 캐싱:**
Anthropic은 청구된 입력을 별도 카운터로 보고합니다 — `input_tokens`(캐시되지 않은 입력), `cache_read_input_tokens`, `cache_creation_input_tokens`. CrewAI는 세 값을 모두 `prompt_tokens`(및 제공자 응답의 네이티브 `input_tokens`)에 포함시켜 캐시된 워크로드에서 `total_tokens`가 전체 청구 사용량을 반영하도록 합니다.
`cached_prompt_tokens`는 캐시 읽기 부분을 breakdown으로만 기록합니다. 이미 `prompt_tokens`에 포함되어 있으므로 `total_tokens`에 다시 더하면 안 됩니다. `cache_creation_tokens`도 캐시 쓰기를 같은 방식으로 기록합니다.
```python Code
usage = llm.get_token_usage_summary()
# total_tokens == prompt_tokens + completion_tokens
# prompt_tokens includes cache read + cache write for Anthropic
```
`crew.usage_metrics` 및 `flow.usage_metrics`에 사용되는 제공자 중립 계약은
Flows 개념 문서의 **UsageMetrics field semantics** 섹션을 참조하세요.
현재 모델 ID와 기능은 Anthropic의 [모델 개요](https://platform.claude.com/docs/en/about-claude/models/overview)를 확인하고, 프로덕션에서 모델을 고정하기 전에 [모델 지원 중단 표](https://platform.claude.com/docs/en/about-claude/model-deprecations)를 검토하세요.
</Accordion>
@@ -980,6 +995,38 @@ LLM 설정을 최대한 활용하는 방법을 알아보세요:
llm = LLM(model="gpt-4")
```
</Tab>
<Tab title="게이트웨이 오류">
<Tip>
OpenRouter와 같은 게이트웨이는 업스트림 공급자가 요청을 수락하는 즉시 `200 OK`를 반환하므로, 공급자 타임아웃은 상태 코드가 아니라 응답 본문에 담겨 도착합니다.
</Tip>
CrewAI는 해당 업스트림 코드가 실제 HTTP 상태로 왔을 때 발생시킬 예외와 동일한 예외를 발생시키므로, 이미 구성해 둔 재시도 처리로 가려진 실패를 잡을 수 있습니다:
```python
import openai
from pydantic import BaseModel
from crewai import LLM
class Report(BaseModel):
summary: str
llm = LLM(model="openrouter/z-ai/glm-5.3", response_format=Report)
try:
result = llm.call("Summarize the incident", response_model=Report)
except openai.InternalServerError as e:
# "z-ai/glm-5.3 via openrouter.ai returned HTTP 200 with an upstream error
# and no choices: The operation was aborted (upstream code 504)"
print(f"Upstream provider failed, safe to retry: {e}")
```
<Warning>
크거나 깊게 중첩된 `response_model`은 업스트림 타임아웃 가능성을 높입니다. 이를 모델이 잘못된 구조화 출력을 생성한 것으로 보지 말고, 일시적인 공급자 장애로 처리하세요.
</Warning>
</Tab>
<Tab title="컨텍스트 길이">
<Tip>
대규모 작업에는 더 큰 컨텍스트 모델을 사용하세요.

View File

@@ -736,7 +736,7 @@ memory = Memory(llm="anthropic/claude-3-haiku-20240307")
memory = Memory(llm="ollama/llama3.2")
# Google Gemini 사용
memory = Memory(llm="gemini/gemini-2.0-flash")
memory = Memory(llm="gemini/gemini-3.7-flash")
# 사용자 정의 설정이 있는 사전 구성된 LLM 인스턴스 전달
llm = LLM(model="gpt-4o", temperature=0)

View File

@@ -202,13 +202,17 @@ crewai skill publish
### 설치
게시된 스킬을 `@org/name` 참조로 설치합니다:
게시된 스킬을 `@org-uuid/name` 참조로 설치합니다:
```shell Terminal
crewai skill install @acme/code-review
crewai skill install @your-org-uuid/code-review
```
크루 프로젝트 내부에서는 스킬이 `./skills/{name}/`에 설치되고, 프로젝트 외부에서는 공유 캐시인 `~/.crewai/skills/{org}/{name}/`에 저장됩니다.
<Note>
조직 이름이 아니라 조직 **UUID**를 사용하세요 — 조직 이름은 고유하지 않아서 잘못된 조직으로 해석될 수 있고, 그러면 설치가 "찾을 수 없음" 오류로 실패합니다. `crewai org list`를 실행하면 소속된 각 조직의 UUID(`ID` 열)를 확인할 수 있습니다.
</Note>
크루 프로젝트 내부에서는 스킬이 `./skills/{name}/`에 설치되고, 프로젝트 외부에서는 공유 캐시인 `~/.crewai/skills/{org-uuid}/{name}/`에 저장됩니다.
에이전트는 레지스트리 스킬을 직접 참조할 수도 있습니다 — 런타임에 로컬 캐시(또는 프로젝트 `skills/` 디렉터리)에서 해석됩니다:
@@ -217,7 +221,7 @@ agent = Agent(
role="Senior Code Reviewer",
goal="Review pull requests for quality and security issues",
backstory="Staff engineer with expertise in secure coding practices.",
skills=["@acme/code-review"], # registry ref, resolved locally
skills=["@your-org-uuid/code-review"], # registry ref, resolved locally
)
```

View File

@@ -20,7 +20,7 @@ crewai test
더 많은 반복 횟수로 실행하거나 다른 모델을 사용하려면 다음과 같이 매개변수를 지정할 수 있습니다:
```bash
crewai test --n_iterations 5 --model gpt-4o
crewai test --n-iterations 5 --model gpt-4o
```
또는 축약형을 사용할 수 있습니다:
@@ -29,6 +29,11 @@ crewai test --n_iterations 5 --model gpt-4o
crewai test -n 5 -m gpt-4o
```
<Note>
이전 `--n_iterations` 플래그는 여전히 동작하지만 사용 중단되었으며 `--help`에는
표시되지 않습니다. 대신 `--n-iterations`(또는 `-n`)를 사용하세요.
</Note>
`crewai test` 명령어를 실행하면 crew가 지정한 횟수만큼 실행되고, 수행이 끝나면 성능 지표가 표시됩니다.
실행 마지막에 표시되는 점수 표는 다음과 같은 지표로 crew의 성능을 보여줍니다:

Some files were not shown because too many files have changed in this diff Show More