Compare commits

...

53 Commits

Author SHA1 Message Date
Vinicius Brasil
78fdf4cd85 Add script/code blocks to FlowDefinition
Let a Flow method run trusted inline Python with `call: script`. The code
is compiled once into a generated function and receives the runtime
values as arguments.

```yaml
methods:
  normalize:
    start: true
    do:
      call: script
      code: |
        import math
        state["rounded"] = math.ceil(state["raw_score"])
        return f"rounded:{state['rounded']}"
```

Even though this shares the same surface of tools (custom code), I
decided to make it opt-in for now, using
`CREWAI_ALLOW_FLOW_SCRIPT_EXECUTION=1`.
2026-06-17 10:17:40 -07:00
Greyson LaLonde
431100ddca fix(deps): widen litellm extra to >=1.84,<2
The litellm extra was capped at <1.85, which excludes future
patch lines and reintroduces resolution failures under uv/pip.
Widen to >=1.84.0,<2 so the extra resolves cleanly against
crewai's openai/python-dotenv pins.

Closes OSS-71
2026-06-17 10:07:19 -07:00
Lucas Gomide
a237ebabba feat: adopt directory-based docs versioning with Edge channel (#6202)
* feat: adopt directory-based docs versioning with Edge channel

Switch docs.crewai.com from navigation-only versioning (every version
selector entry rendered the same docs/<lang>/* source files) to
Mintlify's directory-based versioning so each version selector entry
renders its own snapshot. Add an "Edge" channel under docs/edge/<lang>/*
that always reflects main HEAD for unreleased work, eliminating
pre-release leakage onto frozen release labels. External links to
canonical /<lang>/* URLs are preserved via wildcard redirects that
always land on the current default version.

Layout:
- docs/edge/<lang>/*         rolling source (you edit here)
- docs/edge/enterprise-api.*.yaml
- docs/v<X.Y.Z>/<lang>/*     frozen, immutable snapshots
- docs/v<X.Y.Z>/enterprise-api.*.yaml
- docs/images/               shared, append-only
- docs/docs.json             nav + redirects

URLs follow the Mintlify-idiomatic shape: /edge/<lang>/<page> for
Edge, /v<X.Y.Z>/<lang>/<page> for every frozen snapshot. The wildcard
redirects /<lang>/:slug* -> /<default>/<lang>/:slug* keep stale links
working, and every freeze rewrites them (plus all per-section/per-page
redirects) so destinations always resolve to the current default
without depending on a second redirect hop.

Release flow integration (devtools release):
- New module crewai_devtools.docs_versioning.freeze() materialises
  docs/v<X.Y.Z>/ from docs/edge/, rewrites openapi: refs inside the
  snapshot, inserts the version into every language block in
  docs.json, and refreshes all redirect destinations.
- _update_docs_and_create_pr() in cli.py now calls that freeze during
  Phase 2 of devtools release. Edge changelogs are updated first (so
  the snapshot freeze picks them up), then the snapshot is staged
  alongside docs.json, branched as docs/freeze-v<X.Y.Z>, and the PR
  is titled [docs-freeze] docs: snapshot and changelog for v<X.Y.Z>
  — the title prefix the new CI guard reads.
- The PR still gates tag, GitHub release, PyPI publish, and the
  enterprise release as before; no new PRs are added.
- Pre-releases (1.X.YaN, 1.X.YbN, ...) skip the snapshot — they ride
  Edge — and the docs PR title omits the [docs-freeze] prefix.
- docs_check (AI-generated docs scaffolding) writes to
  docs/edge/<lang>/* so newly-generated unreleased docs land in Edge
  and never accidentally touch a frozen snapshot.

Migration scripts (one-shot):
- scripts/docs/freeze_historical_versions.py reconstructs all 16
  historical snapshots (v1.10.0 .. v1.14.7) from git tags via
  git archive | tar, rewriting openapi: MDX refs so each snapshot
  reads its own enterprise-api YAML rather than the live one.
- scripts/docs/prefix_version_paths.py one-shot-migrates docs.json:
  rewrites every page path in 16 versioned blocks to point under
  docs/v<X.Y.Z>/, inserts a new Edge entry per language, tags
  v1.14.7 as Latest (default), prunes pages whose target file
  doesn't exist in the snapshot (e.g. docs/ar/ didn't exist before
  v1.12.0), and writes the wildcard + per-section redirects.
- scripts/docs/freeze_current_edge.py is now a thin CLI wrapper
  around docs_versioning.freeze for manual one-off freezes (e.g.
  retroactively snapshotting a forgotten release).

CI guards (.github/workflows/docs-snapshots.yml):
- Frozen snapshots under docs/v[0-9]*/ are immutable; only PRs whose
  title contains [docs-freeze] (i.e. release-cut PRs generated by
  devtools release or the manual wrapper) may modify them.
- Images under docs/images/ are append-only since snapshots share a
  single image directory. Deleting or renaming an image breaks every
  historical snapshot that still references it.

Restored docs/images/crewai-otel-export.png from PR #3673; it was
deleted in PR #4908 but v1.10.0 / v1.10.1 snapshots still reference
it. Restoring instead of editing the snapshots preserves historical
rendering fidelity and validates the new append-only rule
retroactively.

Tests:
- lib/devtools/tests/test_docs_versioning.py covers the freeze: file
  copy, openapi rewrite, version insertion, default demotion, redirect
  upserts, per-section redirect rewriting, idempotency, and invalid
  inputs.

Verified locally with mintlify broken-links: 0 broken links across
the full site (Edge + 16 frozen versions, 4 locales).

AGENTS.md (repo root) is the contributor guide for the new model;
RELEASING.md is the release-cut runbook; README's Contribution
section links to both.

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

* style: resolve linter issues

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-17 11:56:59 -04:00
João Moura
d3c37c4a40 Enhance memory reset functionality and JSON crew handling (#6195)
* Enhance memory reset functionality and JSON crew handling

- Added `reset_all` method to the `Memory` class to reset the entire memory store, ignoring `root_scope`.
- Updated the `Crew` class to utilize `reset_all` when resetting memory.
- Enhanced the `_reset_flow_memory` function to check for `Memory` instances and call `reset_all` accordingly.
- Introduced helper functions to load JSON crew configurations and handle project declarations, improving the reset command's flexibility.
- Added tests to validate the new JSON crew memory reset behavior and ensure proper handling of declared flow projects.

* Fix memory reset review issues

* Bump litellm for security advisory
2026-06-17 12:14:50 -03:00
Vinicius Brasil
7bb9bc7e1a Discriminate FlowDefinition state types (#6196)
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 / pip-audit (push) Has been cancelled
Replace the single FlowStateDefinition model with a `type`-discriminated
union of FlowDictStateDefinition, FlowPydanticStateDefinition,
FlowJsonSchemaStateDefinition, and FlowUnknownStateDefinition.

Each branch only carries the fields it actually uses and forbids extras,
so an invalid combination like a `dict` state with a `ref` now fails
validation instead of being silently accepted. The runtime reads `ref`
and `json_schema` defensively since they no longer exist on every branch.

```yaml
state:
  type: json_schema
  json_schema:
    type: object
    properties:
      topic:
        type: string
```

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 21:31:07 -07:00
João Moura
ee4f853270 Update installation and quickstart documentation for JSON-first crew projects (#6181)
* Update installation and quickstart documentation for JSON-first crew projects

- Revised the installation guide to reflect the new JSON-first project structure, detailing the creation of `crew.jsonc` and `agents/*.jsonc` files.
- Updated the quickstart guide to demonstrate setting up agents and tasks using JSONC format, replacing previous YAML examples.
- Enhanced the agents and tasks documentation to clarify the transition from YAML to JSONC, including examples and explanations of the new structure.
- Added notes on the classic YAML structure for legacy projects and provided guidance on migrating to the new format.

* docs: clarify json crew quickstart guidance

* docs: address json docs review feedback
2026-06-16 19:55:23 -03:00
João Moura
ebbc0998ef Implement DMN mode support in crew creation and execution (#6194)
* Implement DMN mode support in crew creation and execution

- Added `is_dmn_mode_enabled` utility to check for enterprise non-interactive mode based on the `CREWAI_DMN` environment variable.
- Updated `create` function in `cli.py` to enforce required parameters when DMN mode is active, raising appropriate usage errors.
- Enhanced `create_crew` and `create_json_crew` functions to skip provider prompts and handle folder existence checks in DMN mode.
- Introduced non-interactive defaults for agent and task creation in DMN mode, ensuring seamless project setup without user input.
- Modified `run_crew` to bypass TUI and handle runtime inputs directly when in DMN mode, improving execution flow for JSON-defined crews.
- Added tests to validate DMN mode behavior, ensuring correct handling of required inputs and non-interactive defaults.

* Implement DMN mode support in crew creation and execution

- Introduced `is_dmn_mode_enabled()` utility to check for non-interactive mode based on the `CREWAI_DMN` environment variable.
- Updated `create` function to enforce required parameters when DMN mode is active, raising appropriate usage errors.
- Modified `create_crew` and `create_json_crew` functions to skip provider prompts and utilize non-interactive defaults in DMN mode.
- Enhanced `run_crew` to bypass TUI and handle runtime inputs directly in DMN mode, ensuring smooth execution without user interaction.
- Added tests to validate DMN mode behavior, including requirements for type and name, and ensuring proper handling of existing folders and missing inputs.
2026-06-16 19:48:31 -03:00
João Moura
06ada68083 Enhance crew loading and validation logic (#6182)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
* Enhance crew loading and validation logic

- Updated `crew_loader.py` to pass the project root when loading task and agent definitions, improving the handling of Python references.
- Refactored `json_loader.py` to include additional validation for Python references, ensuring they are resolved within the project root and enforcing depth limits.
- Added tests in `test_crew_loader.py` and `test_json_loader.py` to validate rejection of unsafe Python references and input files outside the project root.
- Improved error handling for JSON project validation, ensuring clearer feedback for invalid configurations.

* Refactor tests for hierarchical verbose manager agent

- Removed `@pytest.mark.vcr()` decorators from `test_hierarchical_verbose_manager_agent` and `test_hierarchical_verbose_false_manager_agent`.
- Introduced mocking for task outputs in both tests to simulate execution without relying on external dependencies.
- Ensured that the `crew.kickoff()` method is called within a context that patches the `Task.execute_sync` method, improving test isolation and reliability.

* Fix JSON loader PR review comments

* Fix JSON loader project root after rebase

* Handle UNC paths in JSON input files
2026-06-16 18:45:26 -03:00
Vinicius Brasil
4eb90ffbf3 Add crew actions to FlowDefinition (#6184) 2026-06-16 12:59:48 -07:00
Vinicius Brasil
a6cf52ec7e Add inline crew definition loading (#6183) 2026-06-16 11:51:22 -07:00
Vinicius Brasil
9d44d0a5e5 Serialize concrete Pydantic subclasses (#6187) 2026-06-16 11:00:07 -07:00
João Moura
e9d568dc69 Deep Crew / Agent / Task attributes support on json (#6172)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (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
Mark stale issues and pull requests / stale (push) Has been cancelled
* Enhance JSON crew project handling and validation

- Updated `create_json_crew.py` to specify input files with a brief path.
- Refactored `crew_loader.py` to improve agent and task loading logic, including the introduction of a `build_agent` function and better handling of task classes.
- Enhanced `json_loader.py` with additional validation for agent and task definitions, including support for Python references and conditional tasks.
- Added tests in `test_crew_loader.py` and `test_json_loader.py` to ensure proper loading of agents, tasks, and validation of project structures, including custom types and conditional tasks.
- Improved error handling and validation safety across the project loading process.

* Enhance JSON crew configuration options in create_json_crew.py

- Added optional fields for custom agent subclasses and advanced task options, including condition checks and output specifications.
- Improved documentation comments for better clarity on agent and task configurations.
- Updated JSON crew handling to support additional callbacks for pre- and post-execution processes.

* Enhance JSON crew template tests in test_create_crew.py

- Added assertions for new optional fields in crew and agent templates, including conditional tasks, custom converters, and input file specifications.
- Improved validation checks for manager agents and callback references to ensure proper configuration in JSON crew definitions.
- Expanded documentation references within the tests to provide clearer guidance on the expected structure and usage of crew templates.

* Fix JSON crew PR review issues
2026-06-16 02:00:19 -03:00
Vinicius Brasil
fe2c236601 Add each composite action to FlowDefinition (#6164)
Lets a definition loop over an array without writing Python. Each
iteration exposes `item` and prior steps `outputs`.

```yaml
do:
  call: each
  in: state.rows
  do:
    - normalize:
        call: tool
        ref: my_tools:NormalizeRowTool
        with: { row: "${ item }" }
    - lead_scoring:
        call: agent
        # ...
```
2026-06-15 21:44:33 -07:00
João Moura
53c2284484 Support ZIP deployment fallback and JSON crew project env runs (#6166)
* Update crewAI CLI with various enhancements and fixes

- Updated `create_json_crew.py` to require `crewai[tools]>=1.14.7`.
- Enhanced `git.py` with improved repository initialization, including automatic initial commit creation and exclusion patterns for initial commits.
- Modified `install_crew.py` to allow error handling during installation with an optional `raise_on_error` parameter.
- Expanded `plus_api.py` to include methods for creating and updating crews from ZIP files.
- Introduced a new `archive.py` for creating deployable ZIP archives of CrewAI projects, ensuring local artifacts are excluded.
- Updated `run_crew.py` to manage JSON crew dependencies and run crews in the project's environment.
- Enhanced deployment logic in `main.py` to handle ZIP uploads and improve user feedback during deployment processes.
- Added tests for new functionalities and ensured existing tests reflect recent changes in behavior and requirements.

* fix(cli): address deploy zip review feedback

* fix(cli): sync missing lockfile before deploy

* fix(cli): preserve remote deploy on git setup warnings

* test(cli): use single deploy main import style

* fix(cli): skip project install for json crew sync

* fix(cli): load json runner from source checkout

* fix(cli): skip json crew sync when locked

* fix(cli): address deploy zip review feedback

* fix(cli): pass env on zip redeploy

* fix(cli): harden json run and zip fallback

* fix(cli): validate before deploy lock install

* fix(cli): respect poetry lock for json runs

* fix(cli): align json zip wrapper detection

* fix(deps): bump starlette audit floor

* fix(cli): avoid auth retry for deploy exits

* fix(cli): update json zip script entrypoints
2026-06-15 18:46:54 -03:00
Lorenze Jay
a5cc6f6d0e Add crewai_version to flow execution telemetry (#6167)
Some checks failed
CodeQL Advanced / Analyze (python) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (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
2026-06-15 09:34:01 -07:00
João Moura
bb477f8a91 JSON first crews (#6131)
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 / 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
* feat(cli): introduce JSON crew project support and TUI enhancements

- Added support for creating and running JSON-defined crew projects, allowing users to scaffold projects with a new `create_json_crew.py` file.
- Implemented a full-screen Textual TUI for crew execution in `crew_run_tui.py`, enhancing user interaction with a two-column layout.
- Updated `run_crew.py` to prioritize JSON crew projects and added daemon mode for running without TUI.
- Introduced interactive pickers in `tui_picker.py` for improved CLI prompts.
- Enhanced validation for JSON crew files in `validate.py` to ensure proper structure and agent definitions.
- Updated `.gitignore` to exclude demo and crewai directories.

* feat: update LLM model references to gpt-5.4-mini

- Changed default LLM model from gpt-4o-mini to gpt-5.4-mini across various files, including CLI options, JSON crew configurations, and agent definitions.
- Enhanced benchmark and human feedback functionalities to utilize the new model.
- Improved user interface elements in the TUI for better interaction and feedback during execution.
- Added support for new skills directory in JSON crew project creation.

* feat(benchmark): add crew-level benchmarking functionality

- Introduced a new `benchmark` command in the CLI for crew-level benchmarking, allowing users to specify agents, models, and timeout settings.
- Implemented `CrewBenchmarkCase` to handle crew-level benchmark cases with inputs and criteria.
- Enhanced the benchmark runner to support progress tracking and detailed reporting of results for multiple models.
- Added tests for loading crew benchmark cases and validating their structure.
- Updated existing benchmark functions to accommodate the new crew-level execution model.

* feat(cli): enhance JSON crew project functionality and TUI improvements

- Added optional agent-level guardrails and advanced options in JSON crew configurations to improve output validation and flexibility.
- Updated the TUI to better handle plan step statuses, including visual indicators for task completion and failure.
- Introduced methods for parsing and managing step observation events, ensuring accurate updates to task statuses during execution.
- Enhanced validation for JSON crew projects, ensuring proper structure and error handling for agent and task definitions.
- Added comprehensive tests for new features and validation logic, ensuring robustness in JSON crew project handling.

* refactor(cli): streamline JSON crew project handling and improve validation

- Refactored JSON crew project loading and validation logic to enhance clarity and maintainability.
- Introduced utility functions for finding JSON crew files, improving code reuse across modules.
- Removed deprecated benchmark functionality and associated tests to simplify the codebase.
- Updated CLI commands to utilize the new JSON project structure, ensuring compatibility with recent changes.
- Enhanced test coverage for JSON crew project features, ensuring robust validation and error handling.

* feat(cli): enhance activity log navigation and focus management

- Added functionality to focus on the activity log when navigating through log entries.
- Implemented refresh logic for the log panel to ensure updates are displayed correctly during navigation.
- Improved keyboard navigation for log entries, allowing users to expand and scroll through logs seamlessly.
- Added tests to verify the correct behavior of log navigation and focus management in the TUI.

* feat(cli): enhance JSON crew project interaction and input handling

- Introduced a new function to enable prompt line editing for better user experience during input prompts.
- Updated the JSON crew project wizards to show interpolation hints for dynamic values, improving user guidance.
- Enhanced the handling of missing input placeholders by prompting users for required values during crew setup.
- Refactored the crew run logic to ensure proper loading and preparation of JSON-defined crews, including runtime input management.
- Added tests to verify the correct behavior of new input handling features and JSON crew project interactions.

* feat(cli): improve crew project input prompts and event handling

- Enhanced the `_prompt_text` function to allow for configurable spacing before prompts, improving user experience during input collection.
- Updated the wizards for agent and task creation to utilize the new prompt configuration, ensuring a more compact and streamlined interaction.
- Introduced new plan step lifecycle events (`PlanStepStartedEvent`, `PlanStepCompletedEvent`) to better track the execution status of plan steps.
- Refactored the step executor to emit these events during the execution of tasks, improving observability and debugging capabilities.
- Added tests to verify the correct behavior of new prompt handling and event emissions during crew project execution.

* fix: refine json-first crew interactions

* fix: prioritize common json crew tools

* fix: make json crew more tools expandable

* fix: show json crew tools by category

* feat(memory): update default embedder to OpenAI text-embedding-3-large and enhance memory compatibility

- Changed the default embedding model for Memory to OpenAI text-embedding-3-large, which uses 3072-dimensional vectors.
- Added warnings regarding compatibility issues with existing local memory stores created with 1536-dimensional embeddings.
- Updated documentation to reflect the new default embedder and its configuration options.
- Enhanced the CLI and codebase to support the new embedding model across various components, ensuring a seamless transition for users.

* fix: address PR review feedback for JSON-first crews

Review blockers:
- Forward trained_agents_file to JSON crews: crewai run -f now exports
  CREWAI_TRAINED_AGENTS_FILE for the in-process JSON crew path
- Wizard agent picker: Esc/cancel now reprompts instead of silently
  assigning the first agent
- JSON tool resolution hard-fails: unknown tool names, missing custom
  tool files, and invalid custom tool modules raise JSONProjectError
  with actionable messages instead of warn-and-continue
- Embedding dimension mismatch: LanceDB and Qdrant Edge storages raise
  EmbeddingDimensionMismatchError with reset/pin guidance instead of
  silently zero-filling vectors or returning empty search results
- Custom tool code execution documented in loader docstring and the
  scaffolded project README

CI fixes:
- ruff format across lib/
- All 133 PR-introduced mypy errors fixed (llm.py lazy-litellm and
  cli.py lazy command shims now use TYPE_CHECKING imports; textual
  is_mounted misuse fixed; pick_many overloads; misc annotations)

Bot review comments:
- Empty except blocks now have explanatory comments or debug logging
- Removed unused _C_BG/_C_PANEL/_C_BORDER globals and redundant
  import re; tests use a single import style for create_json_crew

Tests: trained-agents propagation, wizard cancel, tool resolution
failures, and dimension mismatch guidance.

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

* fix: address second round of PR review comments

Cursor Bugbot:
- Wizard agent slugs: strip to [a-z0-9_] and fall back to agent_<n> so
  symbol-only roles can't produce an empty agents/.jsonc filename
- Wizard task names: dedupe against prior task names and fall back to
  task_<n> for symbol-only descriptions

CodeRabbit:
- Agent.message(): import Task explicitly at runtime instead of relying
  on the namespace injection done by crewai/__init__
- Async executor: move the native-tools-unsupported fallback from
  _ainvoke_loop_react (self-recursion) to _ainvoke_loop_native_tools,
  mirroring the sync implementation
- StepExecutor downgrade: keep the in-step conversation and append the
  text-tooling instructions instead of rebuilding messages, so completed
  native tool calls are not re-executed
- crewai-files: extension-based MIME lookup now runs before byte
  sniffing so csv/xml types are not degraded to text/plain
- Memory storages: validate every record in a save() batch against a
  consistent embedding dimension (LanceDB previously checked only the
  first record); added mixed-batch tests
- _print_post_tui_summary now typed against CrewRunApp
- Docs: Azure OpenAI default embedder change called out in the memory
  migration warning and provider table

Code quality bots:
- Removed unused _C_YELLOW/_C_CYAN (crew_run_tui) and _GREEN (tui_picker)

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

* feat(cli): accordion tool picker in JSON crew wizard

The flat tool list had grown to ~90 rows. The picker now shows:
- Common tools always visible at the top
- Every other category as a single expandable row with tool and
  selection counts (e.g. "Search & Research  (27 tools, 2 selected)")
- Expanding a category collapses the previously expanded one
- Selections persist across expand/collapse via new preselected
  support in pick_many; cursor follows the toggled category row

tui_picker gains preselected + initial_cursor options on pick_many,
and Esc in multi-select now confirms the current selection instead of
discarding it (required so collapsing can't silently drop choices).

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

* refactor(cli): remove --daemon flag from crewai run

The flag only affected JSON crew projects — classic and flow projects
ignored it entirely, which made the behavior inconsistent. Removed the
option, the daemon code path (_run_json_crew_daemon), and its helper
(_load_json_crew_with_inputs).

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

* test: update run command tests after --daemon removal

lib/crewai/tests/cli/test_run_crew.py still asserted the old
run_crew(trained_agents_file=..., daemon=False) call signature.

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

* fix(cli): exit codes, mid-run quit, async statuses, hyphen placeholders

Addresses the latest Bugbot review round:

- Failed JSON crew runs now exit non-zero (SystemExit(1)) so scripts
  and CI don't treat failures as success, mirroring the classic path
- Quitting the TUI mid-run now ends the process (os._exit(130));
  kickoff runs in a thread worker that cannot be force-cancelled, so
  letting the CLI return would leave LLM/tool work burning tokens in
  the background
- Sidebar task statuses are now async-safe: completion/failure events
  resolve the task's own row via identity instead of assuming the most
  recently started task, and starting a task no longer blanket-marks
  earlier active rows as done
- The runtime-input prompt regex now accepts hyphenated placeholder
  names ({my-topic}), matching kickoff's interpolation pattern

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

* fix: validation safety, custom tool sandboxing, TUI log integrity, memory error surfacing

- Deploy validation no longer executes project code: validation mode
  checks tool declarations structurally (well-formed entries, custom
  tool file exists) without importing or instantiating anything.
  custom:<name> resolution only happens on the actual run path.
- custom:<name> is constrained to [A-Za-z_][A-Za-z0-9_]* and the
  resolved path must stay inside the project's tools/ directory, so
  custom:../foo or absolute-path names cannot execute code outside it.
  Tool paths resolve relative to the crew project root, not cwd.
- TUI task logs are built from per-task state captured at task start
  (idx, description, agent, start time); an out-of-order completion
  takes its output from the event and no longer steals or resets the
  current task's streamed steps/output.
- EmbeddingDimensionMismatchError now inherits ValueError instead of
  RuntimeError so background saves surface it through
  MemorySaveFailedEvent instead of silently dropping the save; the
  shutdown catch in _background_encode_batch is narrowed to the
  "cannot schedule new futures" case.

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

* fix(cli): declared project type wins over crew.json presence

A flow project that also contains a crew.json(c) file now runs and
validates as the flow it declares in pyproject.toml instead of being
hijacked by the JSON crew path. Both crewai run (_has_json_crew) and
deploy validation (_is_json_crew) check tool.crewai.type; a missing or
unreadable pyproject still means a bare JSON crew project.

Also documents why StepObservationFailedEvent intentionally marks the
plan step "done": the event signals an observer failure, not a step
failure, and the executor continues past it.

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

* fix(cli): type the declared_type locals so mypy stays clean

Comparing an Any-typed .get() chain returns Any, which tripped
no-any-return on the previous commit.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 04:19:48 -03:00
Vini Brasil
d80719df81 Add experimental crewai run --definition for flows (#6147)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (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
Let users run a Flow from a Flow Definition YAML file or inline string
without writing Python, passing kickoff inputs as `--inputs` JSON. The
flag is gated behind an experimental warning since the definition format
may still change.
2026-06-12 22:31:05 -07:00
Vini Brasil
6ad821b157 Add expressions to FlowDefinition actions (#6145)
* Add expressions to FlowDefinition actions

Let definitions compute values without Python. A new `call: expression`
action evaluates a Common Expression Language (CEL) expression, and tool
`with:` blocks now render `${...}` CEL templates.

Example 1:

```yaml
decide:
  do:
    call: expression
    expr: "state.score >= 80 ? 'qualified' : 'nurture'"
  router: true
  emit: [qualified, nurture]
```

Example 2:

```yaml
search:
  do:
    call: tool
    ref: my.pkg:SearchTool
    with:
      search_query: "${outputs.build_query.query + ' news'}"
      max_results: "${state.limit}"
```

* Address code review comments

* Address code review comments

* Fix linting offenses

* Address code review comments

* Fix scrapgraph issue
2026-06-12 21:56:02 -07:00
Vini Brasil
2444895ca4 Implement Flow definition run tools without Python code (#6144)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (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
A `do:` step can now say `call: tool` and name a CrewAI tool to run,
passing its inputs under `with:`. Before this, a definition could only
point at Python code to run.

```yaml
methods:
  search:
    start: true
    do:
      call: tool
      ref: crewai_tools:ExaSearchTool
      with:
        search_query: ai agents
```
2026-06-12 19:47:58 -07:00
Vini Brasil
bf291a7a55 Drive human feedback from the flow definition (#6133)
* Drive human feedback from the flow definition

@human_feedback previously wrapped methods with the full HITL runtime (feedback
request, outcome collapse, learn loop), so flows built from a YAML definition —
which carry no decorated callables — could not pause for or route on human
feedback.

# Conflicts:
#	lib/crewai/src/crewai/flow/persistence/decorators.py
#	lib/crewai/src/crewai/flow/runtime/__init__.py

* Address code review comments
2026-06-12 14:48:43 -07:00
Vini Brasil
64438cba37 Wire config and persistence from FlowDefinition into the runtime (#6132)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
* Wire config and persistence from FlowDefinition into the runtime

`from_definition` was silently dropping all config fields; it now passes
`config.model_dump()` so suppress_flow_events, max_method_calls, etc.
actually apply.

Persistence is now engine-driven: `_persist_method_completion` fires
after every method using the definition's persist metadata, so
`@persist` no longer needs to wrap methods — it just stamps them.

* Address code review comments
2026-06-12 11:51:44 -07:00
Lucas Gomide
887adafd2c fix: aggregate token usage across all LLM calls (#6122)
* feat: aggregate LLM token usage at the flow level

Introduces `flow.usage_metrics`, a snapshot of every LLMCallCompletedEvent
emitted under the flow's `current_flow_id` for the duration of one kickoff
(or resume) call. Aggregation happens on the singleton event bus so it
covers crews, direct `LLM.call`s, and nested listener calls — solving the
mismatch where the SDK reported only the last crew's usage while the
Enterprise UI showed the correct full total.

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

* refactor: centralize provider key normalization in UsageMetrics

Add UsageMetrics.from_provider_dict to normalize raw LLM usage dicts
across providers (LiteLLM, native Anthropic, native Gemini, OpenAI
nested cached). BaseLLM._track_token_usage_internal and the flow-level
aggregator now share this single source of truth, so `flow.usage_metrics`
agrees with per-LLM totals on every provider — including the native
Anthropic path that emits `input_tokens`/`output_tokens` instead of
`prompt_tokens`/`completion_tokens`.

* fix: flush event bus before reading aggregated usage_metrics

`crewai_event_bus.emit` dispatches LLMCallCompletedEvent handlers on a
ThreadPoolExecutor (fire-and-forget), so a flow whose last LLM call
completes right before kickoff_async/resume_async returns can detach
the usage listener while that handler is still queued, leaving its
tokens off `flow.usage_metrics`. Match `Crew.kickoff()` and call
`crewai_event_bus.flush()` in both finally blocks so every handler
drains before the listener is detached.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-12 12:55:22 -04:00
Rip&Tear
d3fc0d31f8 [codex] Redact file tool paths (#6134)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* Redact file tool paths

* Fix for pull request finding 'Empty except'

* Potential fix for pull request finding

---------
2026-06-12 15:50:40 +08:00
Vini Brasil
373dca3d04 Run flows from a definition without a Python subclass (#6104)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (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
* Read flow dispatch from FlowDefinition

Store the definition in a `_definition` PrivateAttr at post-init and
convert the dispatch helpers (`_start_method_names`, `_listener_methods`,
`_start_condition`, `_listen_condition`, `_is_router`) from classmethods
to instance methods that read it. Event names now fall back to
`self._definition.name` instead of `self.__class__.__name__`.

Behavior is identical for decorator subclasses, but the engine no longer
assumes the definition comes from the class. This is the seam for
`Flow.from_definition`, where an instance runs a definition that was
loaded rather than built from a Python subclass.

* Add Flow.from_definition to run flows without a subclass

A FlowDefinition (e.g. loaded from YAML) was only usable for dispatch on
decorator-authored subclasses. Now each method definition records an
importable `module:qualname` handler ref, and `Flow.from_definition`
resolves and binds those handlers to build a runnable flow directly.

* Build flow state from FlowDefinition

Definition-driven flows previously always started with a bare dict
state.

* Replace handler string with structured FlowActionDefinition

`handler: str | None` was optional and opaque — missing handlers only
surfaced at kickoff time. `do: FlowActionDefinition` is required, so
Pydantic rejects invalid definitions at parse time.

The `call: "code"` discriminator prepares the schema for future
non-Python action types (e.g. MCP tool, crew) without touching
`FlowMethodDefinition`. Resolution logic is extracted to
`runtime/_action_resolvers.py` to keep the dispatch point isolated.

* Fix conversational start router missing required do field

FlowMethodDefinition.do became required when the handler string was
replaced with FlowActionDefinition, but _conversation_start_router still
built its fragment without it, breaking crewai import entirely.

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

* Add event scoping to flow test

* Change lib/crewai/tests/test_flow_from_definition.py

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 14:18:49 -07:00
Greyson LaLonde
21fa8e32d9 docs: update changelog and version for v1.14.7
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
2026-06-11 10:13:40 -07:00
Greyson LaLonde
f18c03cd8f feat: bump versions to 1.14.7 2026-06-11 10:06:07 -07:00
Greyson LaLonde
50b9c02272 fix(checkpoint): rebuild custom BaseLLM as concrete LLM on restore
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 / pip-audit (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
A custom BaseLLM subclass serializes with the inherited llm_type "base",
which the registry maps to the abstract BaseLLM. Restore then crashed on
cls(**value). Rebuild a concrete LLM from the saved config when the
resolved class is abstract.
2026-06-10 22:21:35 -07:00
Greyson LaLonde
c55334be5f docs: update changelog and version for v1.14.7rc2 2026-06-10 20:52:56 -07:00
Greyson LaLonde
05a2ba9ca4 feat: bump versions to 1.14.7rc2 2026-06-10 20:45:29 -07:00
Greyson LaLonde
fbafe1f0d3 fix(flow): gate restore on a flag so live snapshots don't replay as resume
Checkpoint serialization stamps checkpoint_completed_methods onto every live
Flow in RuntimeState.root, including the agent executor reused across a crew's
tasks. kickoff_async read that stamp as a restore signal, so the second task
replayed the first task's completed methods and never reached a final answer.

Gate is_restoring on _restored_from_checkpoint, set only by
_restore_from_checkpoint, and consume it single-shot.
2026-06-10 20:40:08 -07:00
Greyson LaLonde
5267c059f5 test(flow): pass show=False in test_flow_plotting to not open a browser
flow.plot defaults to show=True, which calls webbrowser.open on every run.
The test only asserts FlowPlotEvent is emitted, so disable the browser open.
2026-06-10 20:36:14 -07:00
Greyson LaLonde
243c9edc1c docs: update changelog and version for v1.14.7rc1
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 / 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-06-10 18:56:52 -07:00
Greyson LaLonde
68910b70c0 feat: bump versions to 1.14.7rc1 2026-06-10 18:50:54 -07:00
Greyson LaLonde
299782765c ci: ignore GHSA-rrmf-rvhw-rf47 (torch alias of PYSEC-2025-194)
* ci: ignore GHSA-rrmf-rvhw-rf47 (torch alias of PYSEC-2025-194)

pip-audit reports CVE-2025-3000 under its GHSA id, which the existing
PYSEC-2025-194 ignore does not match. Same advisory: memory corruption
in torch.jit.script, CVSS 1.9, local-only, no fix for torch 2.11.0.

* ci: sync GHSA-rrmf-rvhw-rf47 ignore into pre-commit pip-audit
2026-06-10 18:45:42 -07:00
Greyson LaLonde
a1f44eb272 fix(events): scope runtime state per run to bound growth and isolate concurrent runs 2026-06-10 18:39:05 -07:00
Lorenze Jay
036b032ab6 handle supporting both custom prompts (#6108)
* handle supporting both custom prompts

* handle translations

* handle deprecation warnings better
2026-06-10 17:52:53 -07:00
Lorenze Jay
f88ae54f96 fix telemetry setup on crewai-login (#6106)
* fix telemetry setup on crewai-login

* type check fix
2026-06-10 17:03:25 -07:00
Lorenze Jay
b6e5d632c1 improve convo routing cycle with one less route (#6102)
* improve one less route

* flows in flows, new agent executor causing early trace batch finalization

* addressing comments

* addressing comments pt2

* lint and typecheck fix
2026-06-10 16:49:16 -07:00
Greyson LaLonde
0d971e5bc5 feat(events): add reset_runtime_state to release accumulated bus state 2026-06-10 16:12:28 -07:00
Lucas Gomide
b3f175b56f docs: update otel images (#6103)
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 / 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
2026-06-10 14:34:30 -04:00
Lucas Gomide
f523a7d029 docs: udpate docs to reflect new state of OpenTelemetry collector (#6100)
* docs: udpate docs to reflect new state of OpenTelemetry collector

* docs: add OTel collector and Datadog screenshots

These images are referenced by the capture_telemetry_logs guides but were
missing from the tree, which broke the link checker across all locales.

* docs: address PR review on OTel collector guide

- Clarify that OpenTelemetry Traces and Logs are separate integrations
  sharing the same fields (resolves Traces/Logs wording inconsistency)
- List regional Datadog OTLP hosts (US1/US3/US5/EU1/AP1) so users outside
  US5 can copy the right domain
2026-06-10 14:26:35 -04:00
Lorenze Jay
f214ff4b7b decouple convo logic from runtime and added a conversational_definition (#6091)
* decouple convo logic from runtime and added a conversational_definition

* type check fix

* always defer traces for convo and so fix tests to reflect that
2026-06-10 10:49:39 -07:00
Vini Brasil
a9e7c3a44f Simplify flow condition evaluation to be stateless per event (#6097)
Re-evaluate the whole `@listen`/`@router` condition tree against the set
of events seen so far, instead of tracking which AND sub-branches remain
pending.

Net effect:
* Fixes a regression where `or_()` short-circuited at the first
  satisfied branch, leaving a sibling `and_()` half-complete so a later
  trigger could spuriously re-fire the listener
* Removes the fragile per-branch pending state and `id()`-based keys
* Shrinks the evaluator to one readable predicate
2026-06-10 10:35:25 -07:00
Lucas Gomide
da8fe8c715 fix: respect suppress_flow_events for method-execution events (#6095)
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 / 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: respect suppress_flow_events for method-execution events

* test: align suppressed-flow test with new method-event behavior
2026-06-09 17:19:25 -04:00
Greyson LaLonde
ce42994ae3 docs: update changelog and version for v1.14.7a4 2026-06-09 12:58:38 -07:00
Greyson LaLonde
820c3905e3 feat: bump versions to 1.14.7a4 2026-06-09 12:51:55 -07:00
Vini Brasil
703ffe67ee Migrate @listen/@router runtime to read from FlowDefinition (#6084)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
* Migrate @listen/@router runtime to read from FlowDefinition

The runtime now resolves listener conditions, router status, and emit
values from `FlowMethodDefinition` instead of legacy method metadata and
the `_listeners`/`_routers`/`_router_emit` registries.

* Evaluate AND/OR listener conditions over the definition shape via
  `_evaluate_definition_condition`
* Drop the class registries and the `FlowMeta` extraction that built
  them; stop stamping `__trigger_methods__`, `__is_router__`,
  `__router_emit__`, and friends
* `@human_feedback` emit now lives only on its config

* Simplify conditionals DSL
2026-06-09 09:40:30 -07:00
Matt Aitchison
8919026326 feat(storage): pluggable default backends for memory, knowledge, rag, flow (#6079)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Vulnerability Scan / pip-audit (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Add opt-in extension seams so an application can route memory, knowledge,
RAG, and flow persistence through a custom backend without subclassing or
threading an explicit instance through every construction site -- mirroring
the existing crewai_core.lock_store.set_lock_backend seam.

- memory:    crewai.memory.storage.factory.set_memory_storage_factory
- knowledge: crewai.knowledge.storage.factory.set_knowledge_storage_factory
- rag:       crewai.rag.factory.register_rag_client_factory (provider registry)
- flow:      crewai.flow.persistence.factory.set_flow_persistence_factory

Each construction site consults the registered factory and falls back to the
built-in default when none is set; an explicit instance always wins. Widen
Knowledge.storage and the knowledge source base classes to BaseKnowledgeStorage
(consistent with BaseAgent.knowledge_storage) so any base-interface backend
plugs in. Runtime-free tests cover each seam.
2026-06-08 21:14:13 -05:00
Greyson LaLonde
988927006c docs: update changelog and version for v1.14.7a3
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (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
Build uv cache / build-cache (3.12) (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.13) (push) Has been cancelled
2026-06-08 18:56:39 -07:00
Greyson LaLonde
48c1987fcf feat: bump versions to 1.14.7a3 2026-06-08 18:43:15 -07:00
Greyson LaLonde
af62b7b583 fix: expose ask_for_human_input on experimental AgentExecutor
fixes #6065
2026-06-08 17:55:19 -07:00
Greyson LaLonde
1b14e162e9 fix: resolve pip-audit CVEs (aiohttp, docling, docling-core, pip)
* fix: resolve pip-audit CVEs for aiohttp, docling, docling-core, pip

- aiohttp 3.13.4 → 3.14.0: fixes GHSA-jg22-mg44-37j8, GHSA-hg6j-4rv6-33pg
- docling 2.84.0 → 2.97.0: fixes GHSA-cjqg-rq2h-2fvj, GHSA-pj2v-ggqh-cmq2,
  GHSA-r3xg-rg9j-67fv, GHSA-q29v-xc37-wh5m
- docling-core 2.74.0 → 2.79.0: fixes GHSA-j5xp-7m2f-49jv, GHSA-jmmv-h3mp-59v8
- pip 26.1.1 → 26.1.2: fixes PYSEC-2026-196

docling-core 2.74.1+ requires pydantic-settings>=2.14.0, so the crewai pin
is loosened from ~=2.10.1 to >=2.10.1,<3. pydantic-settings resolves to
2.14.1 in the lock.

* fix: correct aiohttp CVE floor to 3.14.0 (not 3.13.5)

* test: shim AsyncStreamReaderMixin for vcrpy under aiohttp 3.14.0

aiohttp 3.14.0 removed aiohttp.streams.AsyncStreamReaderMixin (folded into
StreamReader). vcrpy's aiohttp stub still subclasses it, so vcr's patch
machinery raised AttributeError at test collection. Restore an equivalent
mixin in conftest before vcr is imported.

* test: rebuild vcrpy MockClientResponse init for aiohttp 3.14.0

aiohttp 3.14.0 added a required stream_writer kwarg to ClientResponse.__init__
and reads stream_writer.output_size when writer is None. vcrpy's
MockClientResponse doesn't pass it, raising TypeError at cassette playback.
Rebuild the super().__init__ call from the live signature (defaulting required
keyword-only args to None, with a stream_writer stub exposing output_size) so
it survives future aiohttp signature additions too.

* test: avoid deprecated get_event_loop in vcrpy aiohttp shim

asyncio.get_event_loop() emits a DeprecationWarning (and can RuntimeError)
when no current loop is set on Python 3.12+. Prefer get_running_loop() (the
real cassette-playback path always has one) and fall back to a single cached
loop in sync contexts, since the mock only stores the loop and calls
get_debug().

* fix: pull docling-core[chunking] so HierarchicalChunker imports

docling 2.97 split into docling-slim, moving the chunker's code-chunking
deps (tree-sitter, semchunk, language grammars) behind docling-core's
[chunking] extra. crewai's knowledge source imports HierarchicalChunker,
whose package __init__ eagerly imports those submodules -> ModuleNotFoundError
('tree_sitter') without the extra. Request docling-core[chunking]; carry the
extra in override-dependencies too, since overrides replace the whole
requirement and would otherwise strip it.
2026-06-08 17:45:07 -07:00
Vini Brasil
e570534f15 Migrate @start to read from FlowDefinition (#6071)
* Remove `_start_methods` and `__is_start_method__` stamping
* Add helpers to read start info from the definition
* Scan `__dict__` instead of `dir()` to find flow methods
2026-06-08 15:03:50 -07:00
15965 changed files with 3263009 additions and 20879 deletions

View File

@@ -64,6 +64,7 @@ jobs:
--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 \
@@ -81,6 +82,7 @@ jobs:
# PYSEC-2025-183 - pyjwt 2.12.1: disputed weak-encryption claim; key length is application-chosen
# PYSEC-2025-189..197 - torch 2.11.0: memory-corruption/DoS in functions only reachable via untrusted models; no fix available
# PYSEC-2025-210, PYSEC-2026-139 - torch 2.11.0: profiler/deserialization issues; no fix available
# GHSA-rrmf-rvhw-rf47 - torch 2.11.0 (CVE-2025-3000, alias of PYSEC-2025-194): memory corruption in torch.jit.script, CVSS 1.9, local-only; affected <=2.12.0, no fix available. pip-audit reports it under the GHSA id so the PYSEC ignore above does not catch it.
# PYSEC-2025-211..218 - transformers 5.5.4: deserialization/code injection via malicious model checkpoints; no fix available
# GHSA-f4j7-r4q5-qw2c - chromadb 1.1.1 (CVE-2026-45829): pre-auth RCE via /api/v2/tenants/{tenant}/databases/{db}/collections when trust_remote_code=true.
# Advisory: vulnerable >=1.0.0,<=1.5.9, firstPatchedVersion=none. We only use chromadb.PersistentClient (lib/crewai/src/crewai/rag/chromadb/factory.py)

2
.gitignore vendored
View File

@@ -31,3 +31,5 @@ chromadb-*.lock
blogs/*
secrets/*
UNKNOWN.egg-info/
demos/*
.crewai/*

View File

@@ -47,6 +47,7 @@ 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

142
AGENTS.md Normal file
View File

@@ -0,0 +1,142 @@
# Docs contributor guide
The `docs/` directory is published at [docs.crewai.com](https://docs.crewai.com)
by [Mintlify](https://www.mintlify.com/). Mintlify watches `docs/docs.json`
and the MDX files referenced from it.
## TL;DR for editing docs
- Edit MDX under `docs/edge/<lang>/...` (e.g. `docs/edge/en/concepts/agents.mdx`).
- Your change ships under the **Edge** version selector the moment it merges
to `main`. Edge follows `main` and is the channel for unreleased work.
- On release cut, the current Edge state is frozen into `docs/v<X.Y.Z>/` and
that snapshot becomes the new default version in the selector (tag:
`Latest`). Canonical URLs (`/<lang>/...`) auto-redirect to the new default.
- Never modify files under `docs/v*/`. Those are frozen release snapshots
and the `docs-snapshots` CI guard rejects writes. The only exception is a
release-cut PR (auto-generated by `devtools release` or the manual
`scripts/docs/freeze_current_edge.py` wrapper), which uses a
`[docs-freeze]` title prefix to opt out.
- Never delete or rename files under `docs/images/`. Images are append-only.
See [Images](#images) below.
## The version model
The site has one rolling channel (Edge) plus one frozen snapshot per
release.
```
docs/
edge/ <-- Edge sources (you edit here)
en/...
pt-BR/ ko/ ar/
enterprise-api.*.yaml
v1.14.7/ <-- frozen snapshot of v1.14.7
en/...
pt-BR/ ko/ ar/
enterprise-api.*.yaml
v1.14.6/...
...
images/ <-- shared, append-only
docs.json <-- Mintlify config: navigation + redirects
```
`docs/docs.json` lists one navigation block per version per language. Edge
points at `docs/edge/<lang>/...`; every other version points at its own
`docs/v<X.Y.Z>/<lang>/...` subtree. Mintlify scopes both the sidebar and the
in-site search to whichever version the reader selects, so picking
`v1.10.0` genuinely shows the v1.10.0 docs (and only those).
### URLs and canonical redirects
Each Mintlify version corresponds to its own URL prefix:
- Edge: `/edge/<lang>/<page>` (e.g. `/edge/en/concepts/agents`)
- Frozen: `/v<X.Y.Z>/<lang>/<page>` (e.g. `/v1.14.7/en/concepts/agents`)
External links to the old, unversioned `/<lang>/<page>` URLs would 404 under
this layout. To keep them working, `docs.json` ships wildcard redirects:
```jsonc
{ "source": "/en/:slug*", "destination": "/v1.14.7/en/:slug*", "permanent": false }
```
The release-cut step rewrites the destination on every release so canonical
`/<lang>/...` URLs always resolve to the latest stable docs.
## Lifecycle
1. **During development.** You add or edit pages under
`docs/edge/<lang>/...` in normal PRs. They land in Edge as soon as the PR
merges. Both `/edge/<lang>/<page>` and the version selector's `Edge` entry
reflect the change immediately.
2. **Release cut.** The release engineer runs `devtools release X.Y.Z`. As
part of that flow the CLI opens a `[docs-freeze]` PR that copies Edge into
`docs/v<X.Y.Z>/`, rewrites internal OpenAPI references, updates
`docs/docs.json` to make `v<X.Y.Z>` the new default + `Latest`, and rewires
the canonical-URL redirects to the new default. The PR must merge before
the tag and PyPI publish run.
3. **After release.** Edge keeps rolling. Patch fixes to the just-released
docs go into Edge and ship with the next release. We do not back-edit
frozen snapshots.
See [`RELEASING.md`](RELEASING.md) for the full release runbook.
## Images
Snapshots share a single `docs/images/` directory. If an image is deleted
or renamed, every frozen snapshot that referenced it breaks. So the rule
is:
- Adding new images is always fine.
- Deleting or renaming an existing image fails CI unless the PR is a
`[docs-freeze]` release-cut PR.
- If an asset is wrong, add a new file with a new name and reference the
new name in the Edge MDX (`docs/edge/<lang>/...`). Leave the old file
alone.
## Local preview
Install the Mintlify CLI and run from `docs/`:
```bash
npm i -g mintlify
mintlify dev
```
Use the version selector at the top of the rendered page to switch between
Edge and frozen versions.
To check links across every version:
```bash
mintlify broken-links
```
CI runs the broken-links check on every PR that touches `docs/**` via
[`.github/workflows/docs-broken-links.yml`](.github/workflows/docs-broken-links.yml).
## Scripts
- `scripts/docs/freeze_historical_versions.py` — one-time migration that
reconstructed `docs/v1.10.0/` through `docs/v1.14.7/` from git tags. You
should not need to run this again.
- `scripts/docs/prefix_version_paths.py` — one-time migration that switched
`docs/docs.json` to directory-based versioning, inserted Edge, and added
the canonical-URL redirects. You should not need to run this again.
- `scripts/docs/freeze_current_edge.py` — thin CLI wrapper around
`crewai_devtools.docs_versioning.freeze`. `devtools release` calls the
same module during its docs PR step; this script is the manual escape
hatch (e.g. retroactively freezing a forgotten release).
## CI guards
- [`.github/workflows/docs-snapshots.yml`](.github/workflows/docs-snapshots.yml)
enforces the two rules above (frozen snapshots immutable, images
append-only). Both checks accept the `[docs-freeze]` PR-title escape
hatch.
- [`.github/workflows/docs-broken-links.yml`](.github/workflows/docs-broken-links.yml)
runs `mintlify broken-links` against the whole site, so adding a new
page or moving a snapshot file that breaks a link will fail CI.

View File

@@ -601,6 +601,19 @@ CrewAI is open-source and we welcome contributions. If you're looking to contrib
- Send a pull request.
- We appreciate your input!
### Contributing to the docs
The site at [docs.crewai.com](https://docs.crewai.com) is published from
`docs/` by [Mintlify](https://www.mintlify.com/). The docs use directory-based
versioning: edits to `docs/edge/<lang>/...` (e.g.
`docs/edge/en/concepts/agents.mdx`) land under the **Edge** version selector
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

View File

@@ -11,7 +11,99 @@ from typing import Any
from dotenv import load_dotenv
import pytest
from vcr.request import Request # type: ignore[import-untyped]
def _patch_vcrpy_aiohttp_compat() -> None:
"""Keep vcrpy's aiohttp stub working under aiohttp 3.14.0.
aiohttp 3.14.0 (pulled in to fix GHSA-jg22-mg44-37j8 and GHSA-hg6j-4rv6-33pg):
* removed ``aiohttp.streams.AsyncStreamReaderMixin`` (folded into ``StreamReader``),
which vcrpy's ``MockStream`` still subclasses -- vcr's patch machinery then raises
``AttributeError`` at collection time; and
* added a required ``stream_writer`` keyword-only arg to ``ClientResponse.__init__``,
which vcrpy's ``MockClientResponse`` does not pass -- raising ``TypeError`` at
cassette playback.
Restore the mixin, then rebuild ``MockClientResponse``'s ``super().__init__`` call from
the live ``ClientResponse`` signature (defaulting every required keyword-only arg to
``None``, mirroring vcrpy's original call) so it also survives future aiohttp additions.
"""
import asyncio
import inspect
from aiohttp import streams
from aiohttp.client_reqrep import ClientResponse
if not hasattr(streams, "AsyncStreamReaderMixin"):
class AsyncStreamReaderMixin:
__slots__ = ()
def __aiter__(self) -> streams.AsyncStreamIterator[bytes]:
return streams.AsyncStreamIterator(self.readline) # type: ignore[attr-defined]
def iter_chunked(self, n: int) -> streams.AsyncStreamIterator[bytes]:
return streams.AsyncStreamIterator(lambda: self.read(n)) # type: ignore[attr-defined]
def iter_any(self) -> streams.AsyncStreamIterator[bytes]:
return streams.AsyncStreamIterator(self.readany) # type: ignore[attr-defined]
def iter_chunks(self) -> streams.ChunkTupleAsyncStreamIterator:
return streams.ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-type]
streams.AsyncStreamReaderMixin = AsyncStreamReaderMixin # type: ignore[attr-defined]
# Importing the stub builds MockStream/MockClientResponse, so it must run after the
# mixin is restored above.
import vcr.stubs.aiohttp_stubs as aiohttp_stubs # type: ignore[import-untyped]
if getattr(aiohttp_stubs.MockClientResponse, "_crewai_aiohttp_patched", False):
return
keyword_only = [
name
for name, param in inspect.signature(ClientResponse.__init__).parameters.items()
if param.kind is inspect.Parameter.KEYWORD_ONLY
]
class _NullStreamWriter:
# aiohttp 3.14.0 reads stream_writer.output_size in the "request already
# sent" branch (writer is None), so None is not enough -- supply a stub.
output_size = 0
fallback_loop: list[asyncio.AbstractEventLoop] = []
def _resolve_loop() -> asyncio.AbstractEventLoop:
# MockClientResponse is normally built inside aiohttp's running loop, so
# prefer that. In a sync context there is no running loop; avoid
# asyncio.get_event_loop(), which on 3.12+ emits a DeprecationWarning
# (and can RuntimeError) when no current loop is set. Use one cached
# loop instead -- the mock only stores it and calls loop.get_debug().
try:
return asyncio.get_running_loop()
except RuntimeError:
if not fallback_loop:
fallback_loop.append(asyncio.new_event_loop())
return fallback_loop[0]
def _mock_client_response_init(
self: Any, method: str, url: Any, request_info: Any = None
) -> None:
kwargs: dict[str, Any] = dict.fromkeys(keyword_only)
kwargs["request_info"] = request_info
if "loop" in kwargs:
kwargs["loop"] = _resolve_loop()
if "stream_writer" in kwargs:
kwargs["stream_writer"] = _NullStreamWriter()
ClientResponse.__init__(self, method, url, **kwargs)
aiohttp_stubs.MockClientResponse.__init__ = _mock_client_response_init
aiohttp_stubs.MockClientResponse._crewai_aiohttp_patched = True
_patch_vcrpy_aiohttp_compat()
from vcr.request import Request # type: ignore[import-untyped] # noqa: E402
try:

File diff suppressed because it is too large Load Diff

1676
docs/edge/ar/changelog.mdx Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,383 @@
---
title: الوكلاء
description: دليل تفصيلي حول إنشاء وإدارة الوكلاء ضمن إطار عمل CrewAI.
icon: robot
mode: "wide"
---
## نظرة عامة على الوكيل
في إطار عمل CrewAI، الـ `Agent` هو وحدة مستقلة يمكنها:
- أداء مهام محددة
- اتخاذ قرارات بناءً على دوره وهدفه
- استخدام الأدوات لتحقيق الأهداف
- التواصل والتعاون مع وكلاء آخرين
- الاحتفاظ بذاكرة التفاعلات
- تفويض المهام عند السماح بذلك
<Tip>
فكّر في الوكيل كعضو فريق متخصص بمهارات وخبرات ومسؤوليات محددة.
على سبيل المثال، قد يتفوق وكيل `Researcher` في جمع وتحليل المعلومات،
بينما قد يكون وكيل `Writer` أفضل في إنشاء المحتوى.
</Tip>
<Note type="info" title="تحسين المؤسسات: منشئ الوكلاء المرئي">
يتضمن CrewAI AMP منشئ وكلاء مرئي يبسّط إنشاء وتهيئة الوكلاء بدون كتابة كود. صمم وكلاءك بصريًا واختبرهم في الوقت الفعلي.
![Visual Agent Builder Screenshot](/images/enterprise/crew-studio-interface.png)
يُمكّن منشئ الوكلاء المرئي من:
- تهيئة وكلاء بديهية بواجهات نماذج
- اختبار والتحقق في الوقت الفعلي
- مكتبة قوالب مع أنواع وكلاء مهيأة مسبقًا
- تخصيص سهل لخصائص وسلوكيات الوكيل
</Note>
## خصائص الوكيل
| الخاصية | المعامل | النوع | الوصف |
| :-------------------------------------- | :----------------------- | :------------------------------------ | :------------------------------------------------------------------------------------------------------- |
| **الدور** | `role` | `str` | يحدد وظيفة الوكيل وخبرته ضمن الطاقم. |
| **الهدف** | `goal` | `str` | الهدف الفردي الذي يوجه عملية اتخاذ القرار لدى الوكيل. |
| **الخلفية** | `backstory` | `str` | يوفر سياقًا وشخصية للوكيل، مما يثري التفاعلات. |
| **LLM** _(اختياري)_ | `llm` | `Union[str, LLM, Any]` | نموذج اللغة الذي يشغّل الوكيل. افتراضيًا النموذج المحدد في `OPENAI_MODEL_NAME` أو "gpt-4". |
| **الأدوات** _(اختياري)_ | `tools` | `List[BaseTool]` | القدرات أو الوظائف المتاحة للوكيل. افتراضيًا قائمة فارغة. |
| **LLM استدعاء الدوال** _(اختياري)_ | `function_calling_llm` | `Optional[Any]` | نموذج لغة لاستدعاء الأدوات، يتجاوز LLM الطاقم إذا حُدد. |
| **الحد الأقصى للتكرارات** _(اختياري)_ | `max_iter` | `int` | الحد الأقصى للتكرارات قبل أن يقدم الوكيل أفضل إجابته. الافتراضي 20. |
| **الحد الأقصى لـ RPM** _(اختياري)_ | `max_rpm` | `Optional[int]` | الحد الأقصى للطلبات في الدقيقة لتجنب حدود المعدل. |
| **الحد الأقصى لوقت التنفيذ** _(اختياري)_ | `max_execution_time` | `Optional[int]` | الحد الأقصى للوقت (بالثواني) لتنفيذ المهمة. |
| **الوضع المفصل** _(اختياري)_ | `verbose` | `bool` | تفعيل سجلات التنفيذ المفصلة للتصحيح. الافتراضي False. |
| **السماح بالتفويض** _(اختياري)_ | `allow_delegation` | `bool` | السماح للوكيل بتفويض المهام لوكلاء آخرين. الافتراضي False. |
| **دالة الخطوة** _(اختياري)_ | `step_callback` | `Optional[Any]` | دالة تُستدعى بعد كل خطوة للوكيل، تتجاوز دالة الطاقم. |
| **التخزين المؤقت** _(اختياري)_ | `cache` | `bool` | تفعيل التخزين المؤقت لاستخدام الأدوات. الافتراضي True. |
| **قالب النظام** _(اختياري)_ | `system_template` | `Optional[str]` | قالب أمر نظام مخصص للوكيل. |
| **قالب الأمر** _(اختياري)_ | `prompt_template` | `Optional[str]` | قالب أمر مخصص للوكيل. |
| **قالب الاستجابة** _(اختياري)_ | `response_template` | `Optional[str]` | قالب استجابة مخصص للوكيل. |
| **السماح بتنفيذ الكود** _(اختياري)_ | `allow_code_execution` | `Optional[bool]` | تفعيل تنفيذ الكود للوكيل. الافتراضي False. |
| **الحد الأقصى لإعادة المحاولة** _(اختياري)_ | `max_retry_limit` | `int` | الحد الأقصى لإعادات المحاولة عند حدوث خطأ. الافتراضي 2. |
| **احترام نافذة السياق** _(اختياري)_ | `respect_context_window` | `bool` | إبقاء الرسائل تحت حجم نافذة السياق عبر التلخيص. الافتراضي True. |
| **وضع تنفيذ الكود** _(اختياري)_ | `code_execution_mode` | `Literal["safe", "unsafe"]` | وضع تنفيذ الكود: 'safe' (باستخدام Docker) أو 'unsafe' (مباشر). الافتراضي 'safe'. |
| **متعدد الوسائط** _(اختياري)_ | `multimodal` | `bool` | ما إذا كان الوكيل يدعم القدرات متعددة الوسائط. الافتراضي False. |
| **حقن التاريخ** _(اختياري)_ | `inject_date` | `bool` | ما إذا كان يتم حقن التاريخ الحالي تلقائيًا في المهام. الافتراضي False. |
| **تنسيق التاريخ** _(اختياري)_ | `date_format` | `str` | سلسلة تنسيق التاريخ عند تفعيل inject_date. الافتراضي "%Y-%m-%d" (تنسيق ISO). |
| **الاستدلال** _(اختياري)_ | `reasoning` | `bool` | ما إذا كان يجب على الوكيل التأمل وإنشاء خطة قبل تنفيذ المهمة. الافتراضي False. |
| **الحد الأقصى لمحاولات الاستدلال** _(اختياري)_ | `max_reasoning_attempts` | `Optional[int]` | الحد الأقصى لمحاولات الاستدلال قبل تنفيذ المهمة. إذا None، سيحاول حتى الاستعداد. |
| **المُضمّن** _(اختياري)_ | `embedder` | `Optional[Dict[str, Any]]` | تهيئة المُضمّن المستخدم من قبل الوكيل. |
| **مصادر المعرفة** _(اختياري)_ | `knowledge_sources` | `Optional[List[BaseKnowledgeSource]]` | مصادر المعرفة المتاحة للوكيل. |
| **استخدام أمر النظام** _(اختياري)_ | `use_system_prompt` | `Optional[bool]` | ما إذا كان يُستخدم أمر النظام (لدعم نموذج o1). الافتراضي True. |
## إنشاء الوكلاء
هناك طريقتان شائعتان لإنشاء الوكلاء في CrewAI: باستخدام **تهيئة JSONC (الموصى بها للـ crews الجديدة)** أو تعريفهم **مباشرة في الكود**.
### تهيئة JSONC (موصى بها)
المشاريع الجديدة التي تُنشأ عبر `crewai create crew <name>` تستخدم تهيئة JSON-first. يُعرّف كل Agent في `agents/<agent_name>.jsonc`، ويحدد `crew.jsonc` أي Agents تدخل في الـ crew.
```jsonc agents/researcher.jsonc
{
"role": "{topic} Senior Data Researcher",
"goal": "Uncover cutting-edge developments in {topic}",
"backstory": "You find the most relevant information and present it clearly.",
"llm": "openai/gpt-4o",
"tools": ["SerperDevTool"],
"settings": {
"verbose": true,
"allow_delegation": false
}
}
```
استخدم `{placeholder}` داخل `role` أو `goal` أو `backstory`. ضع القيم الافتراضية في `inputs` داخل `crew.jsonc`؛ وسيطلب `crewai run` أي قيم ناقصة. يمكن وضع حقول السلوك مثل `verbose` و `allow_delegation` و `max_iter` و `memory` و `cache` و `planning_config` في المستوى الأعلى أو داخل `settings`.
<Note>
يدعم JSONC التعليقات والفواصل النهائية. إذا وُجد `agents/<name>.jsonc` و `agents/<name>.json` معًا، يستخدم CrewAI ملف JSONC.
</Note>
### تهيئة YAML الكلاسيكية
المشاريع الكلاسيكية التي تُنشأ عبر `crewai create crew <name> --classic` تستخدم `config/agents.yaml` وفئة `@CrewBase` في `crew.py`.
تظل تهيئة YAML مدعومة للمشاريع الحالية المبنية بـ Python/YAML وللفِرق التي تفضل تعريف الوكلاء من خلال فئة `@CrewBase`.
بعد إنشاء مشروع كلاسيكي، انتقل إلى ملف `src/<project_name>/config/agents.yaml` وعدّل القالب ليتوافق مع متطلباتك.
<Note>
ستُستبدل المتغيرات في ملفات YAML (مثل `{topic}`) بقيم من مدخلاتك عند تشغيل الطاقم:
```python Code
crew.kickoff(inputs={'topic': 'AI Agents'})
```
</Note>
إليك مثالًا على كيفية تهيئة الوكلاء باستخدام YAML:
```yaml agents.yaml
# src/<project_name>/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.
```
لاستخدام تهيئة YAML في الكود، أنشئ فئة طاقم ترث من `CrewBase`:
```python Code
# src/<project_name>/crew.py
from crewai import Agent, Crew, Process
from crewai.project import CrewBase, agent, crew
from crewai_tools import SerperDevTool
@CrewBase
class LatestAiDevelopmentCrew():
"""LatestAiDevelopment crew"""
agents_config = "config/agents.yaml"
@agent
def researcher(self) -> Agent:
return Agent(
config=self.agents_config['researcher'], # type: ignore[index]
verbose=True,
tools=[SerperDevTool()]
)
@agent
def reporting_analyst(self) -> Agent:
return Agent(
config=self.agents_config['reporting_analyst'], # type: ignore[index]
verbose=True
)
```
<Note>
يجب أن تتطابق الأسماء المستخدمة في ملفات YAML (`agents.yaml`) مع أسماء
الطرق في كود Python.
</Note>
### تعريف مباشر في الكود
يمكنك إنشاء الوكلاء مباشرة في الكود بإنشاء فئة `Agent`. إليك مثالًا شاملًا يوضح جميع المعاملات المتاحة:
```python Code
from crewai import Agent
from crewai_tools import SerperDevTool
# إنشاء وكيل بجميع المعاملات المتاحة
agent = Agent(
role="Senior Data Scientist",
goal="Analyze and interpret complex datasets to provide actionable insights",
backstory="With over 10 years of experience in data science and machine learning, "
"you excel at finding patterns in complex datasets.",
llm="gpt-4",
function_calling_llm=None,
verbose=False,
allow_delegation=False,
max_iter=20,
max_rpm=None,
max_execution_time=None,
max_retry_limit=2,
allow_code_execution=False,
code_execution_mode="safe",
respect_context_window=True,
use_system_prompt=True,
multimodal=False,
inject_date=False,
date_format="%Y-%m-%d",
reasoning=False,
max_reasoning_attempts=None,
tools=[SerperDevTool()],
knowledge_sources=None,
embedder=None,
system_template=None,
prompt_template=None,
response_template=None,
step_callback=None,
)
```
دعنا نستعرض بعض تركيبات المعاملات الرئيسية لحالات الاستخدام الشائعة:
#### وكيل بحث أساسي
```python Code
research_agent = Agent(
role="Research Analyst",
goal="Find and summarize information about specific topics",
backstory="You are an experienced researcher with attention to detail",
tools=[SerperDevTool()],
verbose=True
)
```
#### وكيل تطوير الكود
```python Code
dev_agent = Agent(
role="Senior Python Developer",
goal="Write and debug Python code",
backstory="Expert Python developer with 10 years of experience",
allow_code_execution=True,
code_execution_mode="safe",
max_execution_time=300,
max_retry_limit=3
)
```
#### وكيل تحليل طويل المدى
```python Code
analysis_agent = Agent(
role="Data Analyst",
goal="Perform deep analysis of large datasets",
backstory="Specialized in big data analysis and pattern recognition",
memory=True,
respect_context_window=True,
max_rpm=10,
function_calling_llm="gpt-4o-mini"
)
```
### تفاصيل المعاملات
#### المعاملات الحرجة
- `role` و `goal` و `backstory` مطلوبة وتشكّل سلوك الوكيل
- `llm` يحدد نموذج اللغة المستخدم (افتراضي: GPT-4 من OpenAI)
#### الذاكرة والسياق
- `memory`: تفعيل للحفاظ على سجل المحادثة
- `respect_context_window`: يمنع مشاكل حد الرموز
- `knowledge_sources`: إضافة قواعد معرفة خاصة بالمجال
#### التحكم في التنفيذ
- `max_iter`: الحد الأقصى للمحاولات قبل تقديم أفضل إجابة
- `max_execution_time`: المهلة بالثواني
- `max_rpm`: تحديد معدل استدعاءات API
- `max_retry_limit`: إعادات المحاولة عند الخطأ
#### تنفيذ الكود
<Warning>
`allow_code_execution` و`code_execution_mode` مهجوران. تمت إزالة `CodeInterpreterTool` من `crewai-tools`. استخدم خدمة بيئة معزولة مخصصة مثل [E2B](https://e2b.dev) أو [Modal](https://modal.com) لتنفيذ الكود بأمان.
</Warning>
- `allow_code_execution` _(مهجور)_: كان يُمكّن تنفيذ الكود المدمج عبر `CodeInterpreterTool`.
- `code_execution_mode` _(مهجور)_: كان يتحكم في وضع التنفيذ (`"safe"` لـ Docker، `"unsafe"` للتنفيذ المباشر).
#### الميزات المتقدمة
- `multimodal`: تفعيل القدرات متعددة الوسائط لمعالجة النص والمحتوى المرئي
- `reasoning`: تمكين الوكيل من التأمل وإنشاء خطط قبل تنفيذ المهام
- `inject_date`: حقن التاريخ الحالي تلقائيًا في أوصاف المهام
#### القوالب
- `system_template`: يحدد السلوك الأساسي للوكيل
- `prompt_template`: ينظم تنسيق الإدخال
- `response_template`: ينسّق استجابات الوكيل
<Note>
عند استخدام القوالب المخصصة، تأكد من تعريف كل من `system_template` و
`prompt_template`. `response_template` اختياري لكن يُوصى به
لتنسيق مخرجات متسق.
</Note>
## أدوات الوكيل
يمكن تجهيز الوكلاء بأدوات متنوعة لتعزيز قدراتهم. يدعم CrewAI أدوات من:
- [مجموعة أدوات CrewAI](https://github.com/joaomdmoura/crewai-tools)
- [أدوات LangChain](https://python.langchain.com/docs/integrations/tools)
إليك كيفية إضافة أدوات لوكيل:
```python Code
from crewai import Agent
from crewai_tools import SerperDevTool, WikipediaTools
# إنشاء الأدوات
search_tool = SerperDevTool()
wiki_tool = WikipediaTools()
# إضافة أدوات للوكيل
researcher = Agent(
role="AI Technology Researcher",
goal="Research the latest AI developments",
tools=[search_tool, wiki_tool],
verbose=True
)
```
## التفاعل المباشر مع الوكيل عبر `kickoff()`
يمكن استخدام الوكلاء مباشرة بدون المرور بمهمة أو سير عمل طاقم باستخدام طريقة `kickoff()`. يوفر هذا طريقة أبسط للتفاعل مع وكيل عندما لا تحتاج إلى إمكانيات تنسيق الطاقم الكاملة.
```python Code
from crewai import Agent
from crewai_tools import SerperDevTool
# إنشاء وكيل
researcher = Agent(
role="AI Technology Researcher",
goal="Research the latest AI developments",
tools=[SerperDevTool()],
verbose=True
)
# استخدام kickoff() للتفاعل مباشرة مع الوكيل
result = researcher.kickoff("What are the latest developments in language models?")
# الوصول إلى الاستجابة الخام
print(result.raw)
```
## اعتبارات مهمة وأفضل الممارسات
### الأمان وتنفيذ الكود
<Warning>
`allow_code_execution` و`code_execution_mode` مهجوران وتمت إزالة `CodeInterpreterTool`. استخدم خدمة بيئة معزولة مخصصة مثل [E2B](https://e2b.dev) أو [Modal](https://modal.com) لتنفيذ الكود بأمان.
</Warning>
### تحسين الأداء
- استخدم `respect_context_window: true` لمنع مشاكل حد الرموز
- عيّن `max_rpm` مناسبًا لتجنب تحديد المعدل
- فعّل `cache: true` لتحسين الأداء للمهام المتكررة
- اضبط `max_iter` و `max_retry_limit` بناءً على تعقيد المهمة
### إدارة الذاكرة والسياق
- استفد من `knowledge_sources` للمعلومات الخاصة بالمجال
- هيّئ `embedder` عند استخدام نماذج تضمين مخصصة
- استخدم القوالب المخصصة للتحكم الدقيق في سلوك الوكيل
### التعاون بين الوكلاء
- فعّل `allow_delegation: true` عندما يحتاج الوكلاء للعمل معًا
- استخدم `step_callback` لمراقبة وتسجيل تفاعلات الوكلاء
- فكّر في استخدام نماذج LLM مختلفة لأغراض مختلفة
### توافق النموذج
- عيّن `use_system_prompt: false` للنماذج القديمة التي لا تدعم رسائل النظام
- تأكد من أن `llm` المختار يدعم الميزات التي تحتاجها

View File

@@ -0,0 +1,302 @@
---
title: واجهة سطر الأوامر
description: تعرّف على كيفية استخدام واجهة سطر أوامر CrewAI للتفاعل مع CrewAI.
icon: terminal
mode: "wide"
---
<Warning>
منذ الإصدار 0.140.0، بدأ CrewAI AMP عملية نقل مزود تسجيل الدخول.
لذلك، تم تحديث تدفق المصادقة عبر CLI. المستخدمون الذين يسجلون الدخول
باستخدام Google، أو الذين أنشأوا حساباتهم بعد 3 يوليو 2025 لن يتمكنوا
من تسجيل الدخول مع الإصدارات القديمة من مكتبة `crewai`.
</Warning>
## نظرة عامة
توفر واجهة سطر أوامر CrewAI مجموعة من الأوامر للتفاعل مع CrewAI، مما يتيح لك إنشاء وتدريب وتشغيل وإدارة الأطقم والتدفقات.
## التثبيت
لاستخدام واجهة سطر أوامر CrewAI، تأكد من تثبيت CrewAI:
```shell Terminal
pip install crewai
```
## الاستخدام الأساسي
الهيكل الأساسي لأمر CrewAI CLI هو:
```shell Terminal
crewai [COMMAND] [OPTIONS] [ARGUMENTS]
```
## الأوامر المتاحة
### 1. إنشاء
إنشاء طاقم أو تدفق جديد.
```shell Terminal
crewai create [OPTIONS] TYPE NAME
```
- `TYPE`: اختر بين "crew" أو "flow"
- `NAME`: اسم الطاقم أو التدفق
مثال:
```shell Terminal
crewai create crew my_new_crew
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`.
### 2. الإصدار
عرض الإصدار المثبت من CrewAI.
```shell Terminal
crewai version [OPTIONS]
```
- `--tools`: (اختياري) عرض الإصدار المثبت من أدوات CrewAI
### 3. التدريب
تدريب الطاقم لعدد محدد من التكرارات.
```shell Terminal
crewai train [OPTIONS]
```
- `-n, --n_iterations INTEGER`: عدد تكرارات التدريب (افتراضي: 5)
- `-f, --filename TEXT`: مسار ملف مخصص للتدريب (افتراضي: "trained_agents_data.pkl")
### 4. الإعادة
إعادة تنفيذ الطاقم من مهمة محددة.
```shell Terminal
crewai replay [OPTIONS]
```
- `-t, --task_id TEXT`: إعادة تنفيذ الطاقم من معرّف المهمة هذا، بما في ذلك جميع المهام اللاحقة
### 5. سجل مخرجات المهام
استرجاع أحدث مخرجات مهام crew.kickoff().
```shell Terminal
crewai log-tasks-outputs
```
### 6. إعادة تعيين الذاكرة
إعادة تعيين ذاكرة الطاقم (طويلة، قصيرة، الكيانات، أحدث مخرجات التشغيل).
```shell Terminal
crewai reset-memories [OPTIONS]
```
- `-l, --long`: إعادة تعيين الذاكرة طويلة المدى
- `-s, --short`: إعادة تعيين الذاكرة قصيرة المدى
- `-e, --entities`: إعادة تعيين ذاكرة الكيانات
- `-k, --kickoff-outputs`: إعادة تعيين أحدث مخرجات التشغيل
- `-kn, --knowledge`: إعادة تعيين تخزين المعرفة
- `-akn, --agent-knowledge`: إعادة تعيين تخزين معرفة الوكيل
- `-a, --all`: إعادة تعيين جميع الذاكرات
### 7. الاختبار
اختبار الطاقم وتقييم النتائج.
```shell Terminal
crewai test [OPTIONS]
```
- `-n, --n_iterations INTEGER`: عدد تكرارات الاختبار (افتراضي: 3)
- `-m, --model TEXT`: نموذج LLM لتشغيل الاختبارات (افتراضي: "gpt-4o-mini")
### 8. التشغيل
تشغيل الطاقم أو التدفق.
```shell Terminal
crewai run
```
<Note>
بدءًا من الإصدار 0.103.0، يمكن استخدام أمر `crewai run` لتشغيل
كل من الأطقم القياسية والتدفقات. للتدفقات، يكتشف تلقائيًا النوع
من pyproject.toml ويشغّل الأمر المناسب. هذه هي الطريقة الموصى بها
لتشغيل كل من الأطقم والتدفقات.
</Note>
### 9. الدردشة
بدءًا من الإصدار `0.98.0`، عند تشغيل أمر `crewai chat`، تبدأ جلسة تفاعلية مع طاقمك. سيرشدك المساعد الذكي بطلب المدخلات اللازمة لتنفيذ الطاقم. بمجرد توفير جميع المدخلات، سينفذ الطاقم مهامه.
```shell Terminal
crewai chat
```
<Note>
مهم: عيّن خاصية `chat_llm` في تعريف الـ crew لتفعيل هذا الأمر.
للـ crews بنمط JSON-first، أضفها إلى `crew.jsonc`:
```jsonc
{
"name": "My Crew",
"agents": ["researcher"],
"tasks": [],
"chat_llm": "openai/gpt-4o"
}
```
للـ crews الكلاسيكية Python/YAML، عيّنها في `crew.py`:
```python
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
chat_llm="gpt-4o",
)
```
</Note>
### 10. النشر
نشر الطاقم أو التدفق إلى [CrewAI AMP](https://app.crewai.com).
- **المصادقة**: تحتاج لتكون مصادقًا للنشر إلى CrewAI AMP.
```shell Terminal
crewai login
```
- **إنشاء نشر**:
```shell Terminal
crewai deploy create
```
- **نشر الطاقم**:
```shell Terminal
crewai deploy push
```
- **حالة النشر**:
```shell Terminal
crewai deploy status
```
- **سجلات النشر**:
```shell Terminal
crewai deploy logs
```
- **عرض النشرات**:
```shell Terminal
crewai deploy list
```
- **حذف النشر**:
```shell Terminal
crewai deploy remove
```
### 11. إدارة المؤسسة
إدارة مؤسسات CrewAI AMP.
```shell Terminal
crewai org [COMMAND] [OPTIONS]
```
- `list`: عرض جميع المؤسسات
- `current`: عرض المؤسسة النشطة حاليًا
- `switch`: التبديل إلى مؤسسة محددة
### 12. تسجيل الدخول
المصادقة مع CrewAI AMP باستخدام تدفق رمز الجهاز الآمن.
```shell Terminal
crewai login
```
### 13. إدارة التهيئة
إدارة إعدادات تهيئة CLI لـ CrewAI.
```shell Terminal
crewai config [COMMAND] [OPTIONS]
```
- `list`: عرض جميع معاملات التهيئة
- `set`: تعيين معامل تهيئة
- `reset`: إعادة تعيين جميع المعاملات إلى القيم الافتراضية
### 14. إدارة التتبع
إدارة تفضيلات جمع التتبع لعمليات الطاقم والتدفق.
```shell Terminal
crewai traces [COMMAND]
```
- `enable`: تفعيل جمع التتبع
- `disable`: تعطيل جمع التتبع
- `status`: عرض حالة جمع التتبع الحالية
#### كيف يعمل التتبع
يتم التحكم في جمع التتبع بفحص ثلاثة إعدادات بترتيب الأولوية:
1. **علامة صريحة في الكود** (الأولوية الأعلى):
```python
crew = Crew(agents=[...], tasks=[...], tracing=True) # تفعيل دائمًا
crew = Crew(agents=[...], tasks=[...], tracing=False) # تعطيل دائمًا
crew = Crew(agents=[...], tasks=[...]) # فحص الأولويات الأدنى
```
2. **متغير البيئة** (الأولوية الثانية):
```env
CREWAI_TRACING_ENABLED=true
```
3. **تفضيل المستخدم** (الأولوية الأدنى):
```shell Terminal
crewai traces enable
```
<Note>
**لتفعيل التتبع**، استخدم أيًا من هذه الطرق:
- عيّن `tracing=True` في كود الطاقم/التدفق، أو
- أضف `CREWAI_TRACING_ENABLED=true` إلى ملف `.env`، أو
- شغّل `crewai traces enable`
**لتعطيل التتبع**، استخدم أيًا من هذه الطرق:
- عيّن `tracing=False` في كود الطاقم/التدفق، أو
- أزل أو عيّن `false` لمتغير `CREWAI_TRACING_ENABLED`، أو
- شغّل `crewai traces disable`
</Note>
<Tip>
يتعامل CrewAI CLI مع المصادقة لمستودع الأدوات تلقائيًا عند
إضافة حزم إلى مشروعك. فقط أضف `crewai` قبل أي أمر `uv`
لاستخدامه. مثلًا `crewai uv add requests`.
</Tip>
<Note>
تُخزن إعدادات التهيئة في `~/.config/crewai/settings.json`. بعض
الإعدادات مثل اسم المؤسسة ومعرّفها للقراءة فقط وتُدار من خلال
أوامر المصادقة والمؤسسة.
</Note>

View File

@@ -0,0 +1,245 @@
---
title: الأطقم
description: فهم واستخدام الأطقم في إطار عمل CrewAI مع خصائص ووظائف شاملة.
icon: people-group
mode: "wide"
---
## نظرة عامة
يمثل الطاقم في CrewAI مجموعة تعاونية من الوكلاء يعملون معًا لتحقيق مجموعة من المهام. يحدد كل طاقم استراتيجية تنفيذ المهام وتعاون الوكلاء وسير العمل العام.
## خصائص الطاقم
| الخاصية | المعامل | الوصف |
| :------------------------------------ | :--------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **المهام** | `tasks` | قائمة المهام المعيّنة للطاقم. |
| **الوكلاء** | `agents` | قائمة الوكلاء الذين يشكلون جزءًا من الطاقم. |
| **العملية** _(اختياري)_ | `process` | تدفق العملية (مثل تسلسلي، هرمي) الذي يتبعه الطاقم. الافتراضي `sequential`. |
| **الوضع المفصل** _(اختياري)_ | `verbose` | مستوى التفصيل في التسجيل أثناء التنفيذ. الافتراضي `False`. |
| **LLM المدير** _(اختياري)_ | `manager_llm` | نموذج اللغة المستخدم بواسطة وكيل المدير في العملية الهرمية. **مطلوب عند استخدام العملية الهرمية.** |
| **LLM استدعاء الدوال** _(اختياري)_ | `function_calling_llm` | إذا مُرر، سيستخدم الطاقم هذا LLM لاستدعاء دوال الأدوات لجميع الوكلاء. يمكن لكل وكيل أن يكون له LLM خاص يتجاوز LLM الطاقم. |
| **التهيئة** _(اختياري)_ | `config` | إعدادات تهيئة اختيارية للطاقم، بتنسيق `Json` أو `Dict[str, Any]`. |
| **الحد الأقصى لـ RPM** _(اختياري)_ | `max_rpm` | الحد الأقصى للطلبات في الدقيقة. الافتراضي `None`. |
| **الذاكرة** _(اختياري)_ | `memory` | تُستخدم لتخزين ذاكرات التنفيذ (قصيرة المدى، طويلة المدى، ذاكرة الكيانات). |
| **التخزين المؤقت** _(اختياري)_ | `cache` | يحدد ما إذا كان يُستخدم تخزين مؤقت لنتائج تنفيذ الأدوات. الافتراضي `True`. |
| **المُضمّن** _(اختياري)_ | `embedder` | تهيئة المُضمّن المستخدم من قبل الطاقم. الافتراضي `{"provider": "openai"}`. |
| **دالة الخطوة** _(اختياري)_ | `step_callback` | دالة تُستدعى بعد كل خطوة لكل وكيل. |
| **دالة المهمة** _(اختياري)_ | `task_callback` | دالة تُستدعى بعد اكتمال كل مهمة. |
| **مشاركة الطاقم** _(اختياري)_ | `share_crew` | ما إذا كنت تريد مشاركة معلومات الطاقم الكاملة وتنفيذه مع فريق CrewAI. |
| **ملف سجل المخرجات** _(اختياري)_ | `output_log_file` | عيّن True لحفظ السجلات كـ logs.txt أو وفّر مسار ملف. الافتراضي `None`. |
| **وكيل المدير** _(اختياري)_ | `manager_agent` | يعيّن وكيلًا مخصصًا سيُستخدم كمدير. |
| **التخطيط** *(اختياري)* | `planning` | يضيف قدرة التخطيط للطاقم. |
| **LLM التخطيط** *(اختياري)* | `planning_llm` | نموذج اللغة المستخدم بواسطة AgentPlanner في عملية التخطيط. |
| **مصادر المعرفة** _(اختياري)_ | `knowledge_sources` | مصادر المعرفة المتاحة على مستوى الطاقم، يمكن لجميع الوكلاء الوصول إليها. |
| **البث** _(اختياري)_ | `stream` | تفعيل مخرجات البث لتلقي تحديثات في الوقت الفعلي. الافتراضي `False`. |
<Tip>
**الحد الأقصى لـ RPM للطاقم**: تعيّن خاصية `max_rpm` الحد الأقصى للطلبات في الدقيقة التي يمكن للطاقم تنفيذها لتجنب حدود المعدل وستتجاوز إعدادات `max_rpm` الفردية للوكلاء إذا عيّنتها.
</Tip>
## إنشاء الأطقم
هناك طريقتان رئيسيتان لإنشاء الأطقم في CrewAI: باستخدام **تهيئة JSONC (الموصى بها للـ crews الجديدة)** أو تعريفها **مباشرة في الكود** للمشاريع الكلاسيكية والحالات المتقدمة.
### تهيئة JSONC (موصى بها)
المشاريع الجديدة التي تُنشأ عبر `crewai create crew <name>` تستخدم `crew.jsonc` لإعدادات الـ crew والمهام، وملفًا منفصلًا لكل Agent داخل `agents/`. يكتشف `crewai run` ملف `crew.jsonc` أو `crew.json`، ويحمّل الـ Agents المشار إليها، ويطلب قيم placeholders الناقصة، ثم يبدأ الـ crew.
```jsonc crew.jsonc
{
"name": "Market Research Crew",
"agents": ["researcher", "analyst"],
"tasks": [
{
"name": "research",
"description": "Research {topic} and collect the most relevant facts.",
"expected_output": "Structured research notes about {topic}.",
"agent": "researcher"
},
{
"name": "analysis",
"description": "Analyze the research and write a concise report.",
"expected_output": "A markdown report with findings and recommendations.",
"agent": "analyst",
"context": ["research"],
"output_file": "output/report.md"
}
],
"process": "sequential",
"verbose": true,
"memory": true,
"inputs": {
"topic": "AI Agents"
}
}
```
كل عنصر في `agents` يُحل أولًا إلى `agents/<name>.jsonc` ثم إلى `agents/<name>.json`. للـ crews الهرمية، استخدم `"process": "hierarchical"` مع `manager_llm` أو `manager_agent`.
<Warning>
شغّل مشاريع JSON crew من مصادر تثق بها فقط. أدوات `custom:<name>` ومراجع `{"python": "module.attribute"}` تنفذ كود Python محليًا عند تحميل الـ crew.
</Warning>
### تهيئة YAML الكلاسيكية
المشاريع الكلاسيكية التي تُنشأ عبر `crewai create crew <name> --classic` تستخدم `crew.py` و `config/agents.yaml` و `config/tasks.yaml` والمزيّنات `@CrewBase` و `@agent` و `@task` و `@crew`.
تظل هذه الطريقة مدعومة للمشاريع الحالية المبنية بـ Python/YAML وللفِرق التي تحتاج تحكمًا صريحًا عبر decorators.
```python code
from crewai import Agent, Crew, Task, Process
from crewai.project import CrewBase, agent, task, crew, before_kickoff, after_kickoff
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class YourCrewName:
"""Description of your crew"""
agents: List[BaseAgent]
tasks: List[Task]
agents_config = 'config/agents.yaml'
tasks_config = 'config/tasks.yaml'
@before_kickoff
def prepare_inputs(self, inputs):
inputs['additional_data'] = "Some extra information"
return inputs
@after_kickoff
def process_output(self, output):
output.raw += "\nProcessed after kickoff."
return output
@agent
def agent_one(self) -> Agent:
return Agent(
config=self.agents_config['agent_one'], # type: ignore[index]
verbose=True
)
@task
def task_one(self) -> Task:
return Task(
config=self.tasks_config['task_one'] # type: ignore[index]
)
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
```
<Note>
سيتم تنفيذ المهام بالترتيب الذي عُرّفت به.
</Note>
فئة `CrewBase`، مع هذه المزيّنات، تؤتمت جمع الوكلاء والمهام، مما يقلل الحاجة للإدارة اليدوية.
### تعريف مباشر في الكود (بديل)
بدلاً من ذلك، يمكنك تعريف الطاقم مباشرة في الكود بدون ملفات تهيئة YAML.
## مخرجات الطاقم
تُغلّف مخرجات الطاقم في فئة `CrewOutput`. توفر هذه الفئة طريقة منظمة للوصول إلى نتائج تنفيذ الطاقم، بما في ذلك تنسيقات متنوعة مثل السلاسل النصية الخام وJSON ونماذج Pydantic.
### خصائص مخرجات الطاقم
| الخاصية | المعامل | النوع | الوصف |
| :--------------- | :------------- | :------------------------- | :--------------------------------------------------------------------------------------------------- |
| **Raw** | `raw` | `str` | المخرجات الخام للطاقم. هذا هو التنسيق الافتراضي. |
| **Pydantic** | `pydantic` | `Optional[BaseModel]` | كائن نموذج Pydantic يمثل المخرجات المنظمة. |
| **JSON Dict** | `json_dict` | `Optional[Dict[str, Any]]` | قاموس يمثل مخرجات JSON. |
| **Tasks Output** | `tasks_output` | `List[TaskOutput]` | قائمة كائنات `TaskOutput`، كل منها يمثل مخرجات مهمة. |
| **Token Usage** | `token_usage` | `Dict[str, Any]` | ملخص استخدام الرموز. |
## استخدام الذاكرة
يمكن للأطقم استخدام الذاكرة (قصيرة المدى، طويلة المدى، وذاكرة الكيانات) لتحسين تنفيذها وتعلمها بمرور الوقت.
## استخدام التخزين المؤقت
يمكن استخدام التخزين المؤقت لتخزين نتائج تنفيذ الأدوات، مما يجعل العملية أكثر كفاءة.
## مقاييس استخدام الطاقم
بعد تنفيذ الطاقم، يمكنك الوصول إلى خاصية `usage_metrics` لعرض مقاييس استخدام نموذج اللغة (LLM) لجميع المهام المنفذة.
```python Code
crew = Crew(agents=[agent1, agent2], tasks=[task1, task2])
crew.kickoff()
print(crew.usage_metrics)
```
## عملية تنفيذ الطاقم
- **العملية التسلسلية**: تُنفذ المهام واحدة تلو الأخرى، مما يسمح بتدفق عمل خطي.
- **العملية الهرمية**: ينسق وكيل مدير الطاقم، ويفوّض المهام ويتحقق من النتائج.
### تشغيل الطاقم
بمجرد تجميع طاقمك، ابدأ سير العمل بطريقة `kickoff()`.
```python Code
result = my_crew.kickoff()
print(result)
```
### طرق مختلفة لتشغيل الطاقم
#### الطرق المتزامنة
- `kickoff()`: يبدأ عملية التنفيذ وفقًا لتدفق العملية المحدد.
- `kickoff_for_each()`: ينفذ المهام بالتتابع لكل مدخل.
#### الطرق غير المتزامنة
| الطريقة | النوع | الوصف |
|--------|------|-------------|
| `akickoff()` | غير متزامن أصلي | async/await أصلي عبر سلسلة التنفيذ بأكملها |
| `akickoff_for_each()` | غير متزامن أصلي | تنفيذ غير متزامن أصلي لكل مدخل في قائمة |
| `kickoff_async()` | مبني على الخيوط | يغلّف التنفيذ المتزامن في `asyncio.to_thread` |
| `kickoff_for_each_async()` | مبني على الخيوط | غير متزامن مبني على الخيوط لكل مدخل في قائمة |
<Note>
لأحمال العمل عالية التزامن، يُوصى بـ `akickoff()` و `akickoff_for_each()` لأنها تستخدم async أصلي.
</Note>
### بث تنفيذ الطاقم
للرؤية في الوقت الفعلي لتنفيذ الطاقم، يمكنك تفعيل البث:
```python Code
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True
)
streaming = crew.kickoff(inputs={"topic": "AI"})
for chunk in streaming:
print(chunk.content, end="", flush=True)
result = streaming.result
```
### الإعادة من مهمة محددة
يمكنك الآن الإعادة من مهمة محددة باستخدام أمر CLI `replay`.
```shell
crewai log-tasks-outputs
```
ثم للإعادة من مهمة محددة:
```shell
crewai replay -t <task_id>
```

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,261 @@
---
title: التحقق من التدوير
description: مثال طاقم مستقل يُثبت أن تدوير الأسرار ينتشر إلى عمليات النشر الجارية دون إعادة نشر.
sidebarTitle: التحقق من التدوير
icon: "arrows-rotate"
---
## نظرة عامة
يوضّح لك هذا الدليل كيفية التحقق من أن **السر المُدوَّر في مزود السحابة لديك يُلتقط في أول إطلاق أتمتة لاحق** — بدون إعادة نشر ولا إعادة تشغيل عامل. هذا ذو صلة فقط عندما تكون قد كوّنت بيانات اعتماد مدعومة بـ Workload Identity ([AWS](/ar/enterprise/features/secrets-manager/aws-workload-identity)، [GCP](/ar/enterprise/features/secrets-manager/gcp-workload-identity)، [Azure](/ar/enterprise/features/secrets-manager/azure-workload-identity)). تتطلب عمليات نشر بيانات الاعتماد الثابتة إعادة نشر بعد التدوير؛ ليس هناك ما يجب التحقق منه هنا.
تستخدم الوصفة أدناه طاقماً صغيراً مستقلاً بأداة واحدة ووكيل واحد ومهمة واحدة. لا يُشير موجه الطاقم أبداً إلى قيمة السر — بدلاً من ذلك، تقرأ أداة القيمة من `os.environ` وتُفيد ببصمة SHA-256 لما تراه. دوّر السر في مزود السحابة، أطلق مرة أخرى، وتتغير البصمة.
<Note>
لماذا بصمة وليس القيمة الخام؟ وضع الأسرار الخام في إخراج LLM وسجلات التتبع هو متجه تسرب. البصمة كافية لتأكيد "أن القيمة تغيّرت" دون كتابة القيمة الفعلية في أي مكان يمكن رصده.
</Note>
## المتطلبات المسبقة
قبل تشغيل هذا التحقق:
- بيانات اعتماد مزود أسرار مدعومة بـ WI مكوَّنة ([AWS](/ar/enterprise/features/secrets-manager/aws-workload-identity)، [GCP](/ar/enterprise/features/secrets-manager/gcp-workload-identity)، [Azure](/ar/enterprise/features/secrets-manager/azure-workload-identity)).
- متغير بيئة على عملية النشر بـ `Secret = true`، المفتاح `API_KEY` (أو أي اسم تفضّله — اضبط الأداة أدناه لتطابقه)، يُشير إلى سر في مزود السحابة.
- طريقة لتحديث قيمة السر في مزود السحابة (وصول CLI أو وحدة تحكم السحابة).
- طريقة لإطلاق عملية النشر عبر HTTP (curl أو Postman أو علامة التبويب **Run** في CrewAI Platform).
## الخطوة 1 — هيكلة طاقم التحقق
أنشئ مشروع crew كلاسيكيًا لأن هذا المثال يربط أداة Python عبر `crew.py`:
```bash
crewai create crew rotation_verifier --classic --skip_provider
cd rotation_verifier
```
## الخطوة 2 — إضافة أداة صدى بيانات الاعتماد
استبدل `src/rotation_verifier/tools/custom_tool.py` بأداة تقرأ متغير البيئة المدعوم بسر وتُعيد بصمة:
```python src/rotation_verifier/tools/credential_echo_tool.py
"""Tool that verifies a runtime-injected secret without leaking the value.
Reads the secret-backed env var (populated by the workload-identity
secrets manager at kickoff time) and returns a stable fingerprint. Never
echo raw credential values into LLM output or logs in production code —
the fingerprint alone is sufficient to confirm rotation worked.
"""
from __future__ import annotations
import hashlib
import os
from crewai.tools import BaseTool
# Match the deployment environment variable's `key` field.
ENV_VAR_NAME = "API_KEY"
class CredentialEchoTool(BaseTool):
name: str = "credential_echo"
description: str = (
"Read the API credential from the worker's environment and return a "
"fingerprint summary. Use this exactly once when asked to verify the "
"current credential. Takes no arguments."
)
def _run(self) -> str:
value = os.environ.get(ENV_VAR_NAME)
if not value:
return (
f"ERROR: {ENV_VAR_NAME} env var is not set. The workload-"
"identity secret fetch did not run, or the deployment is "
"missing the secret-backed env var."
)
fingerprint = hashlib.sha256(value.encode()).hexdigest()[:12]
return f"Authenticated. credential.fingerprint=sha256:{fingerprint}"
```
## الخطوة 3 — استبدال تكوينات الوكيل والمهمة الافتراضية
يضم الطاقم وكيلاً واحداً ومهمة واحدة — كلاهما بأوصاف **لا تذكر أبداً** قيمة السر، لذا تبقى مفاتيح المهام مستقرة عبر عمليات التدوير.
```yaml src/rotation_verifier/config/agents.yaml
credential_checker:
role: >
Credential Verifier
goal: >
Confirm that the workload-identity-backed secret reached this worker
process and report a fingerprint of the current value.
backstory: >
You are a no-nonsense reliability engineer responsible for verifying
that secrets fetched at runtime via workload identity are present
and fresh. You always use the credential_echo tool exactly once and
report the result verbatim — you never make up values.
```
```yaml src/rotation_verifier/config/tasks.yaml
verify_credential_task:
description: >
Use the credential_echo tool to read the runtime-injected credential
and produce a one-line confirmation. The current year is {current_year}
(use it only in the timestamp; do not transform the credential output).
expected_output: >
A single line in the form:
"[{current_year}] <credential_echo tool's exact output>"
agent: credential_checker
```
## الخطوة 4 — توصيل فئة الطاقم
```python src/rotation_verifier/crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from rotation_verifier.tools.credential_echo_tool import CredentialEchoTool
@CrewBase
class RotationVerifierCrew():
"""Single-task crew that verifies a workload-identity-backed secret
was successfully fetched at runtime.
Rotate the underlying secret in the cloud provider, kickoff again, and
the credential fingerprint in the agent's report changes — without any
re-deploy, worker restart, or input change. The crew prompt itself
never references the secret value.
"""
agents: list[BaseAgent]
tasks: list[Task]
@agent
def credential_checker(self) -> Agent:
return Agent(
config=self.agents_config["credential_checker"],
tools=[CredentialEchoTool()],
verbose=True,
)
@task
def verify_credential_task(self) -> Task:
return Task(config=self.tasks_config["verify_credential_task"])
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
```
## الخطوة 5 — نشر الطاقم وتكوين متغير بيئة السر
انشر هذا الطاقم على CrewAI Platform تماماً كما تنشر أي طاقم آخر. ثم على صفحة **Environment Variables** الخاصة بعملية النشر:
- **Key:** `API_KEY` (يجب أن يطابق `ENV_VAR_NAME` في الأداة)
- **Value Source:** بيانات الاعتماد المدعومة بـ WI التي أعدّتها في [AWS WI](/ar/enterprise/features/secrets-manager/aws-workload-identity) أو [GCP WI](/ar/enterprise/features/secrets-manager/gcp-workload-identity)
- **Secret Name:** اسم السر في Secret Manager الخاص بمزود السحابة لديك
{/* SCREENSHOT: Environment Variables form with key=API_KEY, secret-backed value source selected, secret name filled → /images/secrets-manager/verify-rotation/01-env-var-form.png */}
## الخطوة 6 — تشغيل الإطلاق الأول
استبدل `<DEPLOYMENT_AUTH_TOKEN>` و `<DEPLOYMENT_HOST>` بالقيم من علامة التبويب **Run** الخاصة بعملية النشر.
```bash
curl -m 60 \
-H "Authorization: Bearer <DEPLOYMENT_AUTH_TOKEN>" \
-H "Content-Type: application/json" \
-X POST https://<DEPLOYMENT_HOST>/kickoff \
-d '{"inputs":{"current_year":"2026"}}'
```
عندما يكتمل الإطلاق (بضع ثوان)، تحقق من إخراج الوكيل. سترى:
```
[2026] Authenticated. credential.fingerprint=sha256:004421b993c9
```
سجّل البصمة. هذا التجزئة مرتبط بشكل فريد بأي قيمة سر موجودة حالياً في مزود السحابة لديك.
## الخطوة 7 — تدوير السر في مزود السحابة
<Tabs>
<Tab title="AWS">
```bash
aws secretsmanager update-secret \
--region <REGION> \
--secret-id <SECRET_NAME> \
--secret-string "rotated value"
```
</Tab>
<Tab title="GCP">
أضف إصداراً جديداً (يقرأ Secret Manager دائماً `latest`):
```bash
echo -n "rotated value" | gcloud secrets versions add <SECRET_NAME> \
--data-file=- \
--project=<YOUR_PROJECT_ID>
```
</Tab>
<Tab title="Azure">
```bash
az keyvault secret set \
--vault-name <VAULT_NAME> \
--name <SECRET_NAME> \
--value "rotated value"
```
</Tab>
</Tabs>
## الخطوة 8 — تشغيل إطلاق ثانٍ والمقارنة
```bash
curl -m 60 \
-H "Authorization: Bearer <DEPLOYMENT_AUTH_TOKEN>" \
-H "Content-Type: application/json" \
-X POST https://<DEPLOYMENT_HOST>/kickoff \
-d '{"inputs":{"current_year":"2026"}}'
```
يُظهر إخراج الوكيل الآن **بصمة مختلفة**:
```
[2026] Authenticated. credential.fingerprint=sha256:e2fc89848f72
```
يُثبت هذا أن التدوير التُقط بواسطة عملية النشر الجارية دون إعادة نشر ولا إعادة تشغيل عامل ولا أي إجراء آخر من قِبل المشغّل.
## ما يتحقق منه هذا — وما لا يتحقق منه
**يتحقق من:**
- يعمل إصدار رمز OIDC الخاص بـ WI من CrewAI Platform.
- تقبل الثقة من جانب السحابة (مزود IAM OIDC لـ AWS، Workload Identity Pool لـ GCP، Federated Identity Credential لـ Azure) الرمز.
- تمتلك الهوية من جانب السحابة (IAM Role / حساب خدمة GCP / Entra App Registration) وصولاً لقراءة السر.
- تصل قيمة السر إلى `os.environ` لعملية العامل وقت الإطلاق.
- تنتشر عمليات التدوير اللاحقة إلى الإطلاق التالي.
**لا يتحقق من:**
- أن طواقم الإنتاج الفعلية لديك تتعامل مع التدوير بسلاسة — مثلاً، المهام طويلة الأمد التي تقرأ متغير البيئة مرة واحدة عند البدء ستستمر في استخدام القيمة القديمة حتى تنتهي المهمة. خطّط وفقاً لذلك: اقرأ الأسرار عند نقطة الاستخدام، وليس عند استيراد الوحدة.
## لماذا لا نُشير إلى السر مباشرةً في الموجه؟
سيضع عرض توضيحي يبدو أبسط قيمة السر مباشرةً في وصف مهمة (مثلاً، "البحث عن `{api_key}`") ويتفحص الموجه. **لا تفعل ذلك.** لسببين:
1. **يُسرّب السر إلى تتبعات استدعاء LLM والسجلات من جانب المزود.** يمكن لأي شخص لديه وصول للتتبعات قراءته.
2. **يُغيّر وصف المهمة في كل إطلاق.** تُحدّد CrewAI Platform المهام بتجزئة MD5 للوصف؛ القيمة المُدوَّرة تعني أن التجزئة تتغير لكل إطلاق، مما يكسر ربط المهمة من وقت النشر إلى وقت التشغيل. العَرَض: تُسجَّل سجلات المهام كـ `pending_run` إلى الأبد، أو تُسجَّل بعض مهام طاقم متعدد المهام فقط.
يتجاوز النمط القائم على الأداة في هذا الدليل كلتا المشكلتين: الموجه ثابت، تقرأ الأداة متغير البيئة وقت التشغيل، وتصل فقط بصمة القيمة إلى LLM.
## الخطوات التالية
- [العودة إلى نظرة عامة على مدير الأسرار](/ar/enterprise/features/secrets-manager/overview)
- بمجرد التحقق، أَسقط طاقم التحقق. يجب أن تتبع الطواقم الفعلية النمط نفسه: الوصول إلى الأسرار عبر `os.environ` داخل أداة، وعدم استبدالها أبداً في الموجهات.

View File

@@ -0,0 +1,63 @@
---
title: "تصدير OpenTelemetry"
description: "تصدير التتبعات والسجلات من عمليات نشر CrewAI AMP إلى مجمّع OpenTelemetry الخاص بك"
icon: "magnifying-glass-chart"
mode: "wide"
---
يمكن لـ CrewAI AMP تصدير **التتبعات** و**السجلات** من OpenTelemetry من عمليات النشر مباشرة إلى مجمّعك الخاص. يتيح لك ذلك مراقبة أداء الوكلاء وتتبع استدعاءات LLM وتصحيح الأخطاء باستخدام مجموعة المراقبة الحالية.
تتبع بيانات القياس [اتفاقيات OpenTelemetry GenAI الدلالية](https://opentelemetry.io/docs/specs/semconv/gen-ai/) بالإضافة إلى سمات خاصة بـ CrewAI.
## المتطلبات المسبقة
<CardGroup cols={2}>
<Card title="حساب CrewAI AMP" icon="users">
يجب أن يكون لدى مؤسستك حساب CrewAI AMP نشط.
</Card>
<Card title="مجمّع OpenTelemetry" icon="server">
تحتاج إلى نقطة نهاية مجمّع متوافقة مع OpenTelemetry (مثل OTel Collector الخاص بك أو Datadog أو Grafana أو أي واجهة خلفية متوافقة مع OTLP).
</Card>
</CardGroup>
## إعداد مجمّع
1. في CrewAI AMP، انتقل إلى **Settings** > **OpenTelemetry Collectors**.
2. انقر على **Add Collector**.
3. اختر تكاملاً:
- **OpenTelemetry Traces** و**OpenTelemetry Logs** — صدّر إلى أي مجمّع أو واجهة خلفية متوافقة مع OTLP.
- **Datadog** — أرسل التتبعات مباشرة إلى استقبال OTLP الخاص بـ Datadog، دون الحاجة إلى مجمّع منفصل أو Datadog Agent.
4. هيّئ الاتصال. تعتمد الحقول على التكامل الذي اخترته:
<Tabs>
<Tab title="OpenTelemetry Traces / Logs">
إن **OpenTelemetry Traces** و**OpenTelemetry Logs** تكاملان منفصلان يتشاركان نفس الحقول — اختر التكامل المطابق للإشارة التي تريد تصديرها.
- **Endpoint** — نقطة نهاية OTLP لمجمّعك (مثل `https://otel-collector.example.com:4317`).
- **Service Name** — اسم لتعريف هذه الخدمة في منصة المراقبة.
- **Custom Headers** *(اختياري)* — أضف رؤوس المصادقة أو التوجيه كأزواج مفتاح-قيمة.
- **Certificate** *(اختياري)* — قدم شهادة TLS إذا كان مجمّعك يتطلبها.
<Frame>![تهيئة مجمّع OpenTelemetry](/images/crewai-otel-collector-opentelemetry.png)</Frame>
</Tab>
<Tab title="Datadog">
- **Datadog Site Domain** — مضيف OTLP لموقع Datadog الخاص بك فقط، دون بروتوكول أو مسار. يقوم CrewAI ببناء نقطة نهاية HTTPS OTLP الكاملة نيابةً عنك. استخدم المضيف المطابق لـ [موقع Datadog](https://docs.datadoghq.com/getting_started/site/) الخاص بك:
- `otlp.datadoghq.com` (US1)
- `otlp.us3.datadoghq.com` (US3)
- `otlp.us5.datadoghq.com` (US5)
- `otlp.datadoghq.eu` (EU1)
- `otlp.ap1.datadoghq.com` (AP1)
- **API Key** — مفتاح واجهة برمجة تطبيقات Datadog الخاص بك. راجع [كيفية إنشاء واحد](https://docs.datadoghq.com/account_management/api-app-keys/#api-keys).
يصدّر تكامل Datadog **التتبعات**.
<Frame>![تهيئة مجمّع Datadog](/images/crewai-otel-collector-datadog.png)</Frame>
</Tab>
</Tabs>
5. *(اختياري)* انقر على **Test Connection** للتحقق من قدرة CrewAI على الوصول إلى نقطة النهاية باستخدام بيانات الاعتماد التي قدمتها.
6. انقر على **Save**.
<Tip>
يمكنك إضافة مجمّعات متعددة — على سبيل المثال، واحد للتتبعات وآخر للسجلات، أو الإرسال إلى واجهات خلفية مختلفة لأغراض مختلفة.
</Tip>

View File

@@ -0,0 +1,451 @@
---
title: "النشر على AMP"
description: "انشر طاقمك أو تدفقك على CrewAI AMP"
icon: "rocket"
mode: "wide"
---
<Note>
بعد إنشاء طاقم أو تدفق محلياً (أو عبر Crew Studio)، الخطوة التالية هي
نشره على منصة CrewAI AMP. يغطي هذا الدليل طرق نشر متعددة
لمساعدتك في اختيار النهج الأفضل لسير عملك.
</Note>
## المتطلبات المسبقة
<CardGroup cols={2}>
<Card title="مشروع جاهز للنشر" icon="check-circle">
يجب أن يكون لديك طاقم أو تدفق يعمل بنجاح محلياً.
اتبع [دليل التحضير](/ar/enterprise/guides/prepare-for-deployment) للتحقق من بنية مشروعك.
</Card>
<Card title="مستودع GitHub" icon="github">
يجب أن يكون الكود في مستودع GitHub (لطريقة تكامل
GitHub)
</Card>
</CardGroup>
<Info>
**الطواقم مقابل التدفقات**: يمكن نشر كلا نوعي المشاريع كـ "أتمتات" على CrewAI AMP.
عملية النشر هي نفسها، لكن لهما بنى مشاريع مختلفة.
راجع [التحضير للنشر](/ar/enterprise/guides/prepare-for-deployment) للتفاصيل.
</Info>
## الخيار 1: النشر باستخدام CrewAI CLI
يوفر CLI أسرع طريقة لنشر الطواقم أو التدفقات المطورة محلياً على منصة AMP.
يكتشف CLI تلقائياً نوع مشروعك من `pyproject.toml` ويبني وفقاً لذلك.
<Steps>
<Step title="تثبيت CrewAI CLI">
إذا لم تكن قد فعلت بالفعل، ثبّت CrewAI CLI:
```bash
pip install crewai[tools]
```
<Tip>
يأتي CLI مع حزمة CrewAI الرئيسية، لكن الإضافة `[tools]` تضمن حصولك على جميع اعتماديات النشر.
</Tip>
</Step>
<Step title="المصادقة مع منصة Enterprise">
أولاً، تحتاج لمصادقة CLI مع منصة CrewAI AMP:
```bash
# إذا كان لديك حساب CrewAI AMP بالفعل، أو تريد إنشاء واحد:
crewai login
```
عند تشغيل أي من الأمرين، سيقوم CLI بـ:
1. عرض رابط ورمز جهاز فريد
2. فتح متصفحك على صفحة المصادقة
3. طلب تأكيد الجهاز
4. إتمام عملية المصادقة
عند المصادقة الناجحة، سترى رسالة تأكيد في الطرفية!
</Step>
<Step title="إنشاء عملية نشر">
من مجلد مشروعك، شغّل:
```bash
crewai deploy create
```
سيقوم هذا الأمر بـ:
1. اكتشاف معلومات مستودع GitHub
2. تحديد متغيرات البيئة في ملف `.env` المحلي
3. نقل هذه المتغيرات بأمان إلى منصة Enterprise
4. إنشاء عملية نشر جديدة بمعرّف فريد
عند الإنشاء الناجح، سترى رسالة مثل:
```shell
Deployment created successfully!
Name: your_project_name
Deployment ID: 01234567-89ab-cdef-0123-456789abcdef
Current Status: Deploy Enqueued
```
</Step>
<Step title="مراقبة تقدم النشر">
تتبع حالة النشر بـ:
```bash
crewai deploy status
```
للسجلات المفصلة لعملية البناء:
```bash
crewai deploy logs
```
<Tip>
يستغرق النشر الأول عادة حوالي دقيقة واحدة.
</Tip>
</Step>
</Steps>
## أوامر CLI إضافية
يقدم CrewAI CLI عدة أوامر لإدارة عمليات النشر:
```bash
# عرض جميع عمليات النشر
crewai deploy list
# الحصول على حالة النشر
crewai deploy status
# عرض سجلات النشر
crewai deploy logs
# دفع التحديثات بعد تغييرات الكود
crewai deploy push
# إزالة عملية نشر
crewai deploy remove <deployment_id>
```
## الخيار 2: النشر مباشرة عبر واجهة الويب
يمكنك أيضاً نشر طواقمك أو تدفقاتك مباشرة عبر واجهة ويب CrewAI AMP بربط حساب GitHub. لا يتطلب هذا النهج استخدام CLI على جهازك المحلي. تكتشف المنصة تلقائياً نوع مشروعك وتتعامل مع البناء بشكل مناسب.
<Steps>
<Step title="الدفع إلى GitHub">
تحتاج لدفع طاقمك إلى مستودع GitHub. إذا لم تكن قد أنشأت طاقماً بعد، يمكنك [اتباع هذا الدليل](/ar/quickstart).
</Step>
<Step title="ربط GitHub بـ CrewAI AMP">
1. سجّل الدخول إلى [CrewAI AMP](https://app.crewai.com)
2. انقر على زر "Connect GitHub"
<Frame>
![زر ربط GitHub](/images/enterprise/connect-github.png)
</Frame>
</Step>
<Step title="اختيار المستودع">
بعد ربط حساب GitHub، ستتمكن من اختيار المستودع للنشر:
<Frame>
![اختيار المستودع](/images/enterprise/select-repo.png)
</Frame>
<Tip>
إذا كان Crew أو Flow داخل مجلد فرعي في monorepo، فوسّع **Advanced**
وعيّن دليل عمل قبل النشر. راجع
[النشر من Monorepo](/ar/enterprise/guides/monorepo-deployments).
</Tip>
</Step>
<Step title="تعيين متغيرات البيئة">
قبل النشر، ستحتاج لإعداد متغيرات البيئة للاتصال بمزود LLM أو خدمات أخرى:
1. يمكنك إضافة المتغيرات فردياً أو بشكل جماعي
2. أدخل متغيرات البيئة بتنسيق `KEY=VALUE` (واحد لكل سطر)
<Frame>
![تعيين متغيرات البيئة](/images/enterprise/set-env-variables.png)
</Frame>
<Info>
تستخدم حزم Python خاصة؟ ستحتاج لإضافة بيانات اعتماد السجل هنا أيضاً.
راجع [سجلات الحزم الخاصة](/ar/enterprise/guides/private-package-registry) للمتغيرات المطلوبة.
</Info>
</Step>
<Step title="نشر طاقمك">
1. انقر على زر "Deploy" لبدء عملية النشر
2. يمكنك مراقبة التقدم عبر شريط التقدم
3. يستغرق النشر الأول عادة حوالي دقيقة واحدة
<Frame>
![تقدم النشر](/images/enterprise/deploy-progress.png)
</Frame>
بمجرد اكتمال النشر، سترى:
- رابط طاقمك الفريد
- رمز Bearer لحماية API طاقمك
- زر "Delete" إذا كنت تحتاج لإزالة النشر
</Step>
</Steps>
## الخيار 3: إعادة النشر باستخدام API (تكامل CI/CD)
لعمليات النشر الآلية في خطوط أنابيب CI/CD، يمكنك استخدام CrewAI API لتشغيل إعادة نشر الطواقم الحالية. هذا مفيد بشكل خاص لـ GitHub Actions وJenkins أو سير عمل الأتمتة الأخرى.
<Steps>
<Step title="الحصول على رمز الوصول الشخصي">
انتقل إلى إعدادات حساب CrewAI AMP لإنشاء رمز API:
1. انتقل إلى [app.crewai.com](https://app.crewai.com)
2. انقر على **Settings** → **Account** → **Personal Access Token**
3. أنشئ رمزاً جديداً وانسخه بأمان
4. خزّن هذا الرمز كسر في نظام CI/CD
</Step>
<Step title="إيجاد UUID الأتمتة">
حدد موقع المعرّف الفريد لطاقمك المنشور:
1. انتقل إلى **Automations** في لوحة تحكم CrewAI AMP
2. اختر الأتمتة/الطاقم الحالي
3. انقر على **Additional Details**
4. انسخ **UUID** — يحدد هذا نشر طاقمك المحدد
</Step>
<Step title="تشغيل إعادة النشر عبر API">
استخدم نقطة نهاية Deploy API لتشغيل إعادة النشر:
```bash
curl -i -X POST \
-H "Authorization: Bearer YOUR_PERSONAL_ACCESS_TOKEN" \
https://app.crewai.com/crewai_plus/api/v1/crews/YOUR-AUTOMATION-UUID/deploy
# HTTP/2 200
# content-type: application/json
#
# {
# "uuid": "your-automation-uuid",
# "status": "Deploy Enqueued",
# "public_url": "https://your-crew-deployment.crewai.com",
# "token": "your-bearer-token"
# }
```
<Info>
إذا تم إنشاء أتمتتك متصلة بـ Git أولاً، سيسحب API تلقائياً أحدث التغييرات من مستودعك قبل إعادة النشر.
</Info>
</Step>
<Step title="مثال تكامل GitHub Actions">
إليك سير عمل GitHub Actions مع مشغلات نشر أكثر تعقيداً:
```yaml
name: Deploy CrewAI Automation
on:
push:
branches: [ main ]
pull_request:
types: [ labeled ]
release:
types: [ published ]
jobs:
deploy:
runs-on: ubuntu-latest
if: |
(github.event_name == 'push' && github.ref == 'refs/heads/main') ||
(github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'deploy')) ||
(github.event_name == 'release')
steps:
- name: Trigger CrewAI Redeployment
run: |
curl -X POST \
-H "Authorization: Bearer ${{ secrets.CREWAI_PAT }}" \
https://app.crewai.com/crewai_plus/api/v1/crews/${{ secrets.CREWAI_AUTOMATION_UUID }}/deploy
```
<Tip>
أضف `CREWAI_PAT` و`CREWAI_AUTOMATION_UUID` كأسرار مستودع. لعمليات نشر PR، أضف تسمية "deploy" لتشغيل سير العمل.
</Tip>
</Step>
</Steps>
## التفاعل مع أتمتتك المنشورة
بمجرد اكتمال النشر، يمكنك الوصول إلى طاقمك عبر:
1. **REST API**: تنشئ المنصة نقطة نهاية HTTPS فريدة بهذه المسارات الرئيسية:
- `/inputs`: يعرض معاملات الإدخال المطلوبة
- `/kickoff`: يبدأ التنفيذ بالمدخلات المقدمة
- `/status/{kickoff_id}`: يتحقق من حالة التنفيذ
2. **واجهة الويب**: زر [app.crewai.com](https://app.crewai.com) للوصول إلى:
- **علامة تبويب Status**: عرض معلومات النشر وتفاصيل نقطة نهاية API ورمز المصادقة
- **علامة تبويب Run**: تمثيل مرئي لبنية طاقمك
- **علامة تبويب Executions**: سجل جميع عمليات التنفيذ
- **علامة تبويب Metrics**: تحليلات الأداء
- **علامة تبويب Traces**: رؤى التنفيذ المفصلة
### تشغيل عملية تنفيذ
من لوحة تحكم Enterprise، يمكنك:
1. النقر على اسم طاقمك لفتح تفاصيله
2. اختيار "Trigger Crew" من واجهة الإدارة
3. إدخال المدخلات المطلوبة في النافذة المنبثقة
4. مراقبة التقدم أثناء مرور التنفيذ عبر خط الأنابيب
### المراقبة والتحليلات
توفر منصة Enterprise ميزات مراقبة شاملة:
- **إدارة التنفيذ**: تتبع عمليات التشغيل النشطة والمكتملة
- **التتبعات**: تحليلات مفصلة لكل عملية تنفيذ
- **المقاييس**: استخدام الرموز وأوقات التنفيذ والتكاليف
- **عرض الجدول الزمني**: تمثيل مرئي لتسلسل المهام
### ميزات متقدمة
تقدم منصة Enterprise أيضاً:
- **إدارة متغيرات البيئة**: تخزين وإدارة مفاتيح API بأمان
- **اتصالات LLM**: تهيئة التكاملات مع مزودي LLM المختلفين
- **مستودع الأدوات المخصصة**: إنشاء ومشاركة وتثبيت الأدوات
- **Crew Studio**: بناء الطواقم عبر واجهة محادثة دون كتابة كود
## استكشاف أخطاء النشر وإصلاحها
إذا فشل النشر، تحقق من هذه المشكلات الشائعة:
### فشل البناء
#### ملف uv.lock مفقود
**العرض**: فشل البناء مبكراً مع أخطاء حل الاعتماديات
**الحل**: أنشئ ملف القفل وارفعه:
```bash
uv lock
git add uv.lock
git commit -m "Add uv.lock for deployment"
git push
```
<Warning>
ملف `uv.lock` مطلوب لجميع عمليات النشر. بدونه، لا يمكن للمنصة
تثبيت اعتمادياتك بشكل موثوق.
</Warning>
#### بنية المشروع الخاطئة
**العرض**: أخطاء "Could not find entry point" أو "Module not found"
**الحل**: تحقق من أن مشروعك يتطابق مع البنية المتوقعة:
- **JSON-first Crews**: أبقِ `crew.jsonc` أو `crew.json` و `agents/` في جذر المشروع
- **Crews كلاسيكية**: استخدم `src/project_name/main.py` مع دالة دخول `run()`
- **Flows**: استخدم `src/project_name/main.py` مع دالة دخول `kickoff()`
راجع [التحضير للنشر](/ar/enterprise/guides/prepare-for-deployment) لمخططات البنية المفصلة.
#### مُزخرف CrewBase مفقود في crew كلاسيكية
**العرض**: أخطاء "Crew not found" أو "Config not found" أو أخطاء تهيئة الوكيل/المهمة
**الحل**: في crews الكلاسيكية Python/YAML، تأكد من أن جميع فئات الـ crew تستخدم مُزخرف `@CrewBase`. لا تحتاج crews بنمط JSON-first إلى هذا المزخرف.
```python
from crewai.project import CrewBase, agent, crew, task
@CrewBase # This decorator is REQUIRED
class YourCrew():
"""Your crew description"""
@agent
def my_agent(self) -> Agent:
return Agent(
config=self.agents_config['my_agent'], # type: ignore[index]
verbose=True
)
# ... rest of crew definition
```
<Info>
ينطبق هذا على فئات crew الكلاسيكية المكتوبة في Python، بما في ذلك crews الكلاسيكية المضمنة داخل مشاريع Flow.
يتم التحقق من crews بنمط JSON-first من `crew.jsonc` و `agents/` بدلاً من ذلك.
</Info>
#### نوع pyproject.toml غير صحيح
**العرض**: نجاح البناء لكن فشل وقت التشغيل، أو سلوك غير متوقع
**الحل**: تحقق من أن قسم `[tool.crewai]` يتطابق مع نوع مشروعك:
```toml
# For Crew projects:
[tool.crewai]
type = "crew"
# For Flow projects:
[tool.crewai]
type = "flow"
```
### فشل وقت التشغيل
#### فشل اتصال LLM
**العرض**: أخطاء مفتاح API، "model not found"، أو فشل المصادقة
**الحل**:
1. تحقق من صحة تعيين مفتاح API لمزود LLM في متغيرات البيئة
2. تأكد من تطابق أسماء متغيرات البيئة مع ما يتوقعه الكود
3. اختبر محلياً بنفس متغيرات البيئة بالضبط قبل النشر
#### أخطاء تنفيذ الطاقم
**العرض**: يبدأ الطاقم لكن يفشل أثناء التنفيذ
**الحل**:
1. تحقق من سجلات التنفيذ في لوحة تحكم AMP (علامة تبويب Traces)
2. تحقق من أن جميع الأدوات لديها مفاتيح API المطلوبة مُهيأة
3. في crews بنمط JSON-first، تحقق من `crew.jsonc` والملفات المشار إليها داخل `agents/`
4. في crews الكلاسيكية، تأكد من صحة `agents.yaml` و `tasks.yaml`
<Card title="تحتاج مساعدة؟" icon="headset" href="mailto:support@crewai.com">
تواصل مع فريق الدعم للمساعدة في مشاكل النشر أو أسئلة حول
منصة AMP.
</Card>

View File

@@ -0,0 +1,224 @@
---
title: "النشر من Monorepo"
description: "انشر Crew أو Flow من مجلد فرعي داخل مستودع أكبر"
icon: "folder-tree"
mode: "wide"
---
<Note>
استخدم دليل عمل عندما يكون Crew أو Flow داخل مستودع أكبر. يتحقق CrewAI AMP
من الأتمتة ويبنيها ويشغلها من ذلك المجلد الفرعي بدلاً من جذر المستودع.
</Note>
## متى تستخدم ذلك
يكون النشر من monorepo مفيداً عندما يحتوي مستودع واحد على عدة أتمتات أو حزم
مشتركة أو كود تطبيقات آخر:
```text
company-ai/
|-- uv.lock
|-- packages/
| `-- shared_tools/
`-- crews/
|-- support_agent/
| |-- pyproject.toml
| |-- crew.jsonc
| `-- agents/
| `-- support_agent.jsonc
`-- research_flow/
|-- pyproject.toml
`-- src/
`-- research_flow/
`-- main.py
```
لنشر `support_agent`، اضبط دليل العمل على:
```text
crews/support_agent
```
لا يزال AMP يجلب المستودع كاملاً أو يرفعه، لكنه يتعامل مع المجلد المحدد كجذر
مشروع الأتمتة.
## ما الذي يتحكم به دليل العمل
عند تعيين دليل عمل، يستخدم AMP ذلك المجلد من أجل:
- التحقق من المشروع، بما في ذلك `pyproject.toml` وملفات crew JSON وأي نقطة دخول كلاسيكية لـ Crew أو Flow
- تثبيت الاعتماديات باستخدام `uv`
- دليل العمل للعملية قيد التشغيل
- متغير البيئة `CREW_ROOT_DIR`
ترك الحقل فارغاً يحافظ على السلوك الحالي ويستخدم جذر المستودع.
## المصادر المدعومة
يمكنك تعيين دليل عمل عند إنشاء نشر من:
- مستودع GitHub متصل
- مستودع Git مكوّن في AMP
- رفع ملف ZIP
<Info>
اضبط أدلة العمل من واجهة AMP على الويب. لا يطلب تدفق CLI
`crewai deploy create` هذا الحقل.
</Info>
يمكنك أيضاً إضافة دليل العمل أو تغييره في نشر موجود من صفحة **Settings** الخاصة
بالنشر. يسري التغيير في النشر التالي.
<Warning>
لا يمكن استخدام أدلة العمل وauto-deploy معاً. إذا كان للنشر دليل عمل، يتم
تعطيل auto-deploy لذلك النشر. أوقف auto-deploy قبل تعيين دليل عمل.
</Warning>
## إعداد نشر جديد
<Steps>
<Step title="افتح Deploy from Code">
في CrewAI AMP، أنشئ نشراً جديداً واختر المصدر: GitHub أو Git Repository أو
رفع ZIP.
</Step>
<Step title="اختر المستودع أو الفرع أو ملف ZIP">
اختر المستودع والفرع اللذين يحتويان على monorepo، أو ارفع ملف ZIP يحتوي
جذره على محتويات monorepo.
</Step>
<Step title="افتح الإعدادات المتقدمة">
وسّع قسم **Advanced** في نموذج النشر.
</Step>
<Step title="أدخل دليل العمل">
أدخل المسار من جذر المستودع إلى مشروع Crew أو Flow:
```text
crews/support_agent
```
لا تضف شرطة مائلة في البداية.
</Step>
<Step title="انشر">
أضف أي متغيرات بيئة مطلوبة، ثم ابدأ النشر.
</Step>
</Steps>
## إعداد نشر موجود
<Steps>
<Step title="افتح إعدادات النشر">
انتقل إلى الأتمتة في AMP وافتح **Settings**.
</Step>
<Step title="أوقف auto-deploy إذا لزم الأمر">
إذا كان auto-deploy مفعلاً، أوقفه أولاً. لا يكون حقل دليل العمل متاحاً
أثناء تشغيل auto-deploy.
</Step>
<Step title="عيّن دليل العمل">
في **Basic settings**، أدخل مسار المجلد الفرعي، مثل:
```text
crews/support_agent
```
</Step>
<Step title="أعد النشر">
احفظ الإعداد وأعد نشر الأتمتة. سيتم استخدام دليل العمل الجديد في النشر
التالي.
</Step>
</Steps>
## قواعد المسار
يجب أن يكون دليل العمل مساراً نسبياً داخل جذر المستودع أو ZIP.
| القاعدة | المثال |
|---------|--------|
| استخدم مساراً نسبياً | `crews/support_agent` |
| لا تبدأ بـ `/` | `/crews/support_agent` غير صالح |
| لا تستخدم مقاطع المسار `.` أو `..` | `crews/../support_agent` غير صالح |
| استخدم الأحرف والأرقام والشرطات والشرطات السفلية والنقاط والشرطات المائلة فقط | `crews/support agent` غير صالح |
| اجعل المسار 255 حرفاً أو أقل | يتم رفض المسارات الأطول |
يزيل AMP المسافات البيضاء في البداية والنهاية، ويضغط الشرطات المائلة المتكررة،
ويزيل الشرطة المائلة النهائية. تستخدم القيمة الفارغة جذر المستودع.
## ملفات القفل وUV Workspaces
يجب أن يحتوي المجلد المحدد على `pyproject.toml` وملفات المشروع المناسبة لنوع
الأتمتة:
- crew بنمط JSON-first: ملف `crew.jsonc` أو `crew.json` مع مجلد `agents/`
- Crew كلاسيكي أو Flow: مجلد `src/` مع نقطة دخول Python المتوقعة
يمكن أن يوجد ملف `uv.lock` أو `poetry.lock` إما في المجلد المحدد أو في جذر
المستودع.
يدعم هذا تخطيطي ملفات القفل الشائعين:
<Tabs>
<Tab title="ملف قفل المشروع">
```text
company-ai/
`-- crews/
`-- support_agent/
|-- pyproject.toml
|-- uv.lock
|-- crew.jsonc
`-- agents/
`-- support_agent.jsonc
```
</Tab>
<Tab title="ملف قفل workspace">
```text
company-ai/
|-- uv.lock
|-- packages/
| `-- shared_tools/
`-- crews/
`-- support_agent/
|-- pyproject.toml
|-- crew.jsonc
`-- agents/
`-- support_agent.jsonc
```
</Tab>
</Tabs>
<Tip>
إذا كانت الأتمتة تستورد حزماً مشتركة من مكان آخر في monorepo، فصرّح بهذه
الحزم في `pyproject.toml` باستخدام إعدادات UV workspace أو path أو source.
يشغل AMP الأتمتة من المجلد المحدد، لذلك يجب تثبيت الكود المشترك كاعتمادية
بدلاً من الاعتماد على وجود جذر المستودع في Python path.
</Tip>
## استكشاف الأخطاء وإصلاحها
### لم يتم العثور على دليل العمل
تحقق من أن المسار نسبي إلى جذر المستودع أو ZIP. بالنسبة لرفع ZIP، يجب أن
تتضمن محتويات ZIP مسار دليل العمل تماماً كما أدخلته.
### pyproject.toml مفقود
يجب أن يشير دليل العمل إلى مجلد مشروع Crew أو Flow، وليس فقط إلى مجلد أب
يحتوي على عدة مشاريع.
### uv.lock أو poetry.lock مفقود
اعمل commit لملف قفل إما في مجلد المشروع المحدد أو في جذر المستودع. بالنسبة
إلى UV workspaces، يتم دعم إبقاء `uv.lock` في جذر workspace.
### Auto-Deploy غير متاح
يتم تعطيل auto-deploy أثناء تعيين دليل عمل. استخدم إعادة النشر اليدوية أو شغّل
إعادة النشر من CI/CD باستخدام AMP API.
<Card title="النشر على AMP" icon="rocket" href="/ar/enterprise/guides/deploy-to-amp">
تابع دليل النشر بعد اختيار دليل عمل monorepo.
</Card>

View File

@@ -0,0 +1,343 @@
---
title: "التحضير للنشر"
description: "تأكد من جاهزية طاقمك أو تدفقك للنشر على CrewAI AMP"
icon: "clipboard-check"
mode: "wide"
---
<Note>
قبل النشر على CrewAI AMP، من الضروري التحقق من صحة بنية مشروعك.
يمكن نشر كل من الطواقم والتدفقات كـ "أتمتات"، لكن لهما بنى مشاريع
ومتطلبات مختلفة يجب استيفاؤها لنجاح النشر.
</Note>
## فهم الأتمتات
في CrewAI AMP، **الأتمتات** هو المصطلح الشامل لمشاريع الذكاء الاصطناعي الوكيل القابلة للنشر. يمكن أن تكون الأتمتة إما:
- **طاقم**: فريق مستقل من وكلاء الذكاء الاصطناعي يعملون معاً على المهام
- **تدفق**: سير عمل مُنسّق يمكنه الجمع بين طواقم متعددة واستدعاءات LLM المباشرة والمنطق الإجرائي
فهم النوع الذي تنشره ضروري لأن لهما بنى مشاريع ونقاط دخول مختلفة.
## الطواقم مقابل التدفقات: الفروقات الرئيسية
<CardGroup cols={2}>
<Card title="مشاريع الطاقم" icon="users">
فرق وكلاء ذكاء اصطناعي مستقلة. الـ crews الجديدة تستخدم بنية JSON-first مع `crew.jsonc` و `agents/`؛ ويمكن للـ crews الكلاسيكية الاستمرار في استخدام `crew.py`.
</Card>
<Card title="مشاريع التدفق" icon="diagram-project">
سير عمل مُنسّق مع طواقم مضمنة في مجلد `crews/`. الأفضل للعمليات المعقدة متعددة المراحل.
</Card>
</CardGroup>
| الجانب | الطاقم | التدفق |
|--------|--------|--------|
| **بنية المشروع** | جذر المشروع مع `crew.jsonc` و `agents/` | `src/project_name/` مع مجلد `crews/` |
| **موقع المنطق الرئيسي** | `crew.jsonc` (كلاسيكي: `src/project_name/crew.py`) | `src/project_name/main.py` (فئة Flow) |
| **دالة نقطة الدخول** | تُحمّل من `crew.jsonc` (كلاسيكي: `run()` في `main.py`) | `kickoff()` في `main.py` |
| **نوع pyproject.toml** | `type = "crew"` | `type = "flow"` |
| **أمر CLI للإنشاء** | `crewai create crew name` | `crewai create flow name` |
| **موقع التهيئة** | `crew.jsonc` و `agents/` و `tools/` اختياريًا | `src/project_name/crews/crew_name/config/` أو مجلدات crew JSON مضمنة |
| **يمكن أن يحتوي طواقم أخرى** | لا | نعم (في مجلد `crews/`) |
## مرجع بنية المشروع
### بنية مشروع الطاقم
عند تشغيل `crewai create crew my_crew`، تحصل على بنية JSON-first:
```
my_crew/
├── .gitignore
├── pyproject.toml # Must have type = "crew"
├── README.md
├── .env
├── uv.lock # REQUIRED for deployment
├── crew.jsonc # إعدادات الـ crew والمهام والعملية والمدخلات
├── agents/
│ └── researcher.jsonc # تعريفات الـ Agents
├── tools/ # أدوات custom:<name> اختيارية
├── knowledge/
└── skills/
```
<Warning>
في crews بنمط JSON-first، أبقِ `crew.jsonc` و `agents/` و `tools/` و `knowledge/` و `skills/`
في جذر المشروع. وضعها داخل `src/` يمنع `crewai run` والتحقق قبل النشر من العثور على تعريف الـ crew.
</Warning>
<Info>
المشاريع الكلاسيكية التي تُنشأ عبر `crewai create crew my_crew --classic` تستخدم البنية القديمة
`src/project_name/crew.py` و `src/project_name/config/agents.yaml` و
`src/project_name/config/tasks.yaml`. تظل هذه البنية مدعومة للـ crews المكتوبة في Python مع decorators.
</Info>
### بنية مشروع التدفق
عند تشغيل `crewai create flow my_flow`، تحصل على هذه البنية:
```
my_flow/
├── .gitignore
├── pyproject.toml # Must have type = "flow"
├── README.md
├── .env
├── uv.lock # REQUIRED for deployment
└── src/
└── my_flow/
├── __init__.py
├── main.py # Entry point with kickoff() function + Flow class
├── crews/ # Embedded crews folder
│ └── poem_crew/
│ ├── __init__.py
│ ├── poem_crew.py # Crew with @CrewBase decorator
│ └── config/
│ ├── agents.yaml
│ └── tasks.yaml
└── tools/
├── __init__.py
└── custom_tool.py
```
<Info>
الـ crews المستقلة بنمط JSON-first تستخدم ملفات JSON في جذر المشروع. أما Flows فتظل تستخدم
`src/project_name/` ويمكن أن تحتوي crews مضمنة كلاسيكية أو مجلدات crew JSON يتم تحميلها عبر
`crewai.project.load_crew`.
</Info>
## قائمة فحص ما قبل النشر
استخدم هذه القائمة للتحقق من جاهزية مشروعك للنشر.
### 1. التحقق من تهيئة pyproject.toml
يجب أن يتضمن `pyproject.toml` قسم `[tool.crewai]` الصحيح:
<Tabs>
<Tab title="للطواقم">
```toml
[tool.crewai]
type = "crew"
```
</Tab>
<Tab title="للتدفقات">
```toml
[tool.crewai]
type = "flow"
```
</Tab>
</Tabs>
<Warning>
إذا لم يتطابق `type` مع بنية مشروعك، سيفشل البناء أو
لن تعمل الأتمتة بشكل صحيح.
</Warning>
### 2. التأكد من وجود ملف uv.lock
يستخدم CrewAI `uv` لإدارة الاعتماديات. يضمن ملف `uv.lock` بناءً قابلاً للتكرار وهو **مطلوب** للنشر.
```bash
# إنشاء أو تحديث ملف القفل
uv lock
# التحقق من وجوده
ls -la uv.lock
```
إذا لم يكن الملف موجوداً، شغّل `uv lock` وارفعه إلى مستودعك:
```bash
uv lock
git add uv.lock
git commit -m "Add uv.lock for deployment"
git push
```
### 3. التحقق من تعريف الـ Crew
<Tabs>
<Tab title="JSON-first Crews">
يجب أن تحتوي crews بنمط JSON-first على `crew.jsonc` أو `crew.json` في جذر المشروع.
يجب أن يشير مصفوفة `agents` إلى ملفات داخل `agents/`، ويجب أن تشير كل task إلى اسم Agent صحيح.
```jsonc crew.jsonc
{
"name": "Research Crew",
"agents": ["researcher"],
"tasks": [
{
"name": "research_task",
"description": "Research {topic}.",
"expected_output": "A concise report.",
"agent": "researcher"
}
],
"inputs": {
"topic": "AI Agents"
}
}
```
تُشار الأدوات المخصصة بصيغة `"custom:<name>"` ويجب تنفيذها في
`tools/<name>.py` كصنف يرث من `BaseTool`.
</Tab>
<Tab title="Crews كلاسيكية Python/YAML">
يجب أن تستخدم الـ crews الكلاسيكية وPython crews المضمنة داخل Flows مزخرف `@CrewBase`.
```python
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List
@CrewBase
class MyCrew():
"""My crew description"""
agents: List[BaseAgent]
tasks: List[Task]
@agent
def my_agent(self) -> Agent:
return Agent(
config=self.agents_config['my_agent'], # type: ignore[index]
verbose=True
)
@task
def my_task(self) -> Task:
return Task(
config=self.tasks_config['my_task'] # type: ignore[index]
)
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
```
</Tab>
</Tabs>
### 4. التحقق من نقاط دخول المشروع
لا تحتاج crews المستقلة بنمط JSON-first إلى ملف `src/project_name/main.py` مكتوب يدويًا؛
يقوم `crewai run` وتغليف النشر بتحميل `crew.jsonc` مباشرة. تستخدم crews الكلاسيكية وFlows نقاط دخول Python:
<Tabs>
<Tab title="JSON-first Crews">
شغّل محليًا من جذر المشروع:
```bash
crewai run
```
</Tab>
<Tab title="Crews كلاسيكية">
تستخدم نقطة الدخول دالة `run()`:
```python
# src/my_crew/main.py
from my_crew.crew import MyCrew
def run():
"""Run the crew."""
inputs = {'topic': 'AI in Healthcare'}
result = MyCrew().crew().kickoff(inputs=inputs)
return result
if __name__ == "__main__":
run()
```
</Tab>
<Tab title="للتدفقات">
تستخدم نقطة الدخول دالة `kickoff()` مع فئة Flow:
```python
# src/my_flow/main.py
from crewai.flow import Flow, listen, start
from my_flow.crews.poem_crew.poem_crew import PoemCrew
class MyFlow(Flow):
@start()
def begin(self):
# Flow logic here
result = PoemCrew().crew().kickoff(inputs={...})
return result
def kickoff():
"""Run the flow."""
MyFlow().kickoff()
if __name__ == "__main__":
kickoff()
```
</Tab>
</Tabs>
### 5. تحضير متغيرات البيئة
قبل النشر، تأكد من أن لديك:
1. **مفاتيح API لـ LLM** جاهزة (OpenAI، Anthropic، Google، إلخ.)
2. **مفاتيح API للأدوات** إذا كنت تستخدم أدوات خارجية (Serper، إلخ.)
<Info>
إذا كان مشروعك يعتمد على حزم من **سجل PyPI خاص**، ستحتاج أيضاً لتهيئة
بيانات اعتماد مصادقة السجل كمتغيرات بيئة. راجع
دليل [سجلات الحزم الخاصة](/ar/enterprise/guides/private-package-registry) للتفاصيل.
</Info>
<Tip>
اختبر مشروعك محلياً بنفس متغيرات البيئة قبل النشر
لاكتشاف مشاكل التهيئة مبكراً.
</Tip>
## أوامر التحقق السريع
شغّل هذه الأوامر من جذر مشروعك للتحقق السريع من إعدادك:
```bash
# 1. Check project type in pyproject.toml
grep -A2 "\[tool.crewai\]" pyproject.toml
# 2. Verify uv.lock exists
ls -la uv.lock || echo "ERROR: uv.lock missing! Run 'uv lock'"
# 3. For JSON-first crews, verify crew.jsonc and agents/
([ -f crew.jsonc ] || [ -f crew.json ]) || echo "No crew.jsonc or crew.json found"
test -d agents || echo "No agents/ directory found"
# 4. For classic Crews - verify crew.py exists
ls -la src/*/crew.py 2>/dev/null || echo "No crew.py (expected for Crews)"
# 5. For Flows - verify crews/ folder exists
ls -la src/*/crews/ 2>/dev/null || echo "No crews/ folder (expected for Flows)"
# 6. For classic Python crews - check for CrewBase usage
grep -r "@CrewBase" . --include="*.py"
```
## أخطاء الإعداد الشائعة
| الخطأ | العرض | الإصلاح |
|-------|-------|---------|
| `uv.lock` مفقود | فشل البناء أثناء حل الاعتماديات | شغّل `uv lock` وارفعه |
| `type` خاطئ في pyproject.toml | نجاح البناء لكن فشل وقت التشغيل | غيّر إلى النوع الصحيح |
| `crew.jsonc` أو `agents/` مفقود في crew بنمط JSON-first | لا يمكن العثور على تعريف الـ crew | أبقِ `crew.jsonc` و `agents/` في جذر المشروع |
| مُزخرف `@CrewBase` مفقود في crew كلاسيكية | أخطاء "Config not found" | أضف المُزخرف لجميع فئات الـ crew الكلاسيكية |
| ملفات كلاسيكية في الجذر بدل `src/` | نقطة الدخول غير موجودة | انقل ملفات Python الكلاسيكية إلى `src/project_name/` |
| `run()` أو `kickoff()` مفقودة | لا يمكن بدء الأتمتة | أضف دالة الدخول الصحيحة |
## الخطوات التالية
بمجرد اجتياز مشروعك لجميع عناصر القائمة، أنت جاهز للنشر:
<Card title="النشر على AMP" icon="rocket" href="/ar/enterprise/guides/deploy-to-amp">
اتبع دليل النشر لنشر طاقمك أو تدفقك على CrewAI AMP باستخدام
CLI أو واجهة الويب أو تكامل CI/CD.
</Card>

Some files were not shown because too many files have changed in this diff Show More