Compare commits
87 Commits
fix/codeql
...
1.15.8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e9caf1e1b8 | ||
|
|
133baf39b8 | ||
|
|
2e95bfb4e8 | ||
|
|
97981ed31b | ||
|
|
e2c8d7ca88 | ||
|
|
ca5ef810be | ||
|
|
daa7019898 | ||
|
|
1870b444e7 | ||
|
|
38ca5edce2 | ||
|
|
213d9485fe | ||
|
|
c459d01c35 | ||
|
|
cc0759854d | ||
|
|
bd2cb0f23e | ||
|
|
c52d0d9530 | ||
|
|
b64c92c87b | ||
|
|
80fa0295c4 | ||
|
|
728183e420 | ||
|
|
b3aaaab023 | ||
|
|
a4cbeacca5 | ||
|
|
c528e8bdee | ||
|
|
c06043f7e8 | ||
|
|
b14d36bfe4 | ||
|
|
3bb87532da | ||
|
|
6d496f799b | ||
|
|
40279e3152 | ||
|
|
ce739e28c7 | ||
|
|
4c7e483936 | ||
|
|
fa255387a3 | ||
|
|
69c0308f2c | ||
|
|
e0bd967484 | ||
|
|
f0704ebb22 | ||
|
|
4e23bf6d45 | ||
|
|
df2e68fe0a | ||
|
|
475ce6cb6a | ||
|
|
cbb8c982f8 | ||
|
|
a2b0af6bc8 | ||
|
|
a1021de7f3 | ||
|
|
9a49af098b | ||
|
|
5dba2ef623 | ||
|
|
c5ac2d93b4 | ||
|
|
79da292d79 | ||
|
|
999bee8344 | ||
|
|
985cf52028 | ||
|
|
da9902da4f | ||
|
|
0e5d0ecfb9 | ||
|
|
a194f3867a | ||
|
|
7d21283630 | ||
|
|
6452608724 | ||
|
|
5f4ac9f407 | ||
|
|
9d72e269e4 | ||
|
|
fb8e93be25 | ||
|
|
4fdb7f2bfb | ||
|
|
bfa652a7be | ||
|
|
b65c8487d2 | ||
|
|
a8b3ecb723 | ||
|
|
7967b19057 | ||
|
|
85c467dfe2 | ||
|
|
7baf8f9ba1 | ||
|
|
860817cbcd | ||
|
|
289686ab49 | ||
|
|
589baa3e7f | ||
|
|
835b93d8c8 | ||
|
|
3246cb30f5 | ||
|
|
fc41c42773 | ||
|
|
792b58f46b | ||
|
|
799ab0f548 | ||
|
|
2b56dab813 | ||
|
|
e55e710df0 | ||
|
|
56edf1f95f | ||
|
|
2b90117e88 | ||
|
|
24901cd4f6 | ||
|
|
559a9c65c4 | ||
|
|
6244738d2a | ||
|
|
8b197a7ca8 | ||
|
|
f630c471cf | ||
|
|
31a4a4e162 | ||
|
|
1452ee2021 | ||
|
|
629f5d537b | ||
|
|
ba2dafdeda | ||
|
|
b37505bcf9 | ||
|
|
694881c7bf | ||
|
|
958d8270db | ||
|
|
ba855bae2b | ||
|
|
c157199065 | ||
|
|
8eed457e70 | ||
|
|
04fec31f1e | ||
|
|
1556dbea3e |
41
.github/workflows/docs-broken-links.yml
vendored
@@ -4,13 +4,11 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "docs/**"
|
||||
- "docs.json"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "docs/**"
|
||||
- "docs.json"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -28,11 +26,40 @@ jobs:
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Install Mintlify CLI
|
||||
run: npm i -g mintlify
|
||||
- name: Install Mint CLI
|
||||
run: npm i -g mint@4.2.741
|
||||
|
||||
# Pruning immutable snapshots keeps the check fast (--files still parses every
|
||||
# page); the default version must stay because unprefixed links resolve to it.
|
||||
- name: Prune frozen doc versions (keep edge and latest)
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
run: |
|
||||
python3 - <<'EOF'
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
docs = Path("docs")
|
||||
spec_path = docs / "docs.json"
|
||||
spec = json.loads(spec_path.read_text())
|
||||
|
||||
keep_dirs = {"edge"}
|
||||
for lang in spec["navigation"]["languages"]:
|
||||
kept = [v for v in lang["versions"] if v["version"] == "Edge" or v.get("default")]
|
||||
lang["versions"] = kept
|
||||
keep_dirs.update(v["version"] for v in kept if v["version"] != "Edge")
|
||||
|
||||
missing = [d for d in keep_dirs if not (docs / d).is_dir()]
|
||||
if missing:
|
||||
raise SystemExit(f"docs.json version labels do not match directories: {missing}")
|
||||
|
||||
spec_path.write_text(json.dumps(spec, indent=2))
|
||||
|
||||
for path in docs.glob("v*"):
|
||||
if path.is_dir() and path.name not in keep_dirs:
|
||||
shutil.rmtree(path)
|
||||
EOF
|
||||
|
||||
- name: Run broken link checker
|
||||
run: |
|
||||
# Auto-answer the prompt with yes command
|
||||
yes "" | mintlify broken-links || test $? -eq 141
|
||||
run: mint broken-links
|
||||
working-directory: ./docs
|
||||
|
||||
52
.github/workflows/vulnerability-scan.yml
vendored
@@ -47,46 +47,17 @@ jobs:
|
||||
|
||||
- name: Run pip-audit
|
||||
run: |
|
||||
uv run pip-audit --desc --aliases --skip-editable --format json --output pip-audit-report.json \
|
||||
--ignore-vuln PYSEC-2024-277 \
|
||||
--ignore-vuln PYSEC-2026-89 \
|
||||
--ignore-vuln PYSEC-2026-97 \
|
||||
--ignore-vuln PYSEC-2025-148 \
|
||||
--ignore-vuln PYSEC-2025-183 \
|
||||
--ignore-vuln PYSEC-2025-189 \
|
||||
--ignore-vuln PYSEC-2025-190 \
|
||||
--ignore-vuln PYSEC-2025-191 \
|
||||
--ignore-vuln PYSEC-2025-192 \
|
||||
--ignore-vuln PYSEC-2025-193 \
|
||||
--ignore-vuln PYSEC-2025-194 \
|
||||
--ignore-vuln PYSEC-2025-195 \
|
||||
--ignore-vuln PYSEC-2025-196 \
|
||||
--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 \
|
||||
--ignore-vuln PYSEC-2025-214 \
|
||||
--ignore-vuln PYSEC-2025-215 \
|
||||
--ignore-vuln PYSEC-2025-216 \
|
||||
--ignore-vuln PYSEC-2025-217 \
|
||||
--ignore-vuln PYSEC-2025-218 \
|
||||
--ignore-vuln GHSA-f4j7-r4q5-qw2c
|
||||
# Ignored CVEs:
|
||||
# PYSEC-2024-277 - joblib 1.5.3: disputed; NumpyArrayWrapper only used with trusted caches
|
||||
# PYSEC-2026-89 - markdown 3.10.2: DoS via malformed HTML; fix 3.8.1 — already past, advisory range is stale
|
||||
# PYSEC-2026-97 - nltk 3.9.4: arbitrary file read in filestring(); no fix available
|
||||
# PYSEC-2025-148 - onnx 1.21.0: path traversal in save_external_data; no fix available
|
||||
# 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)
|
||||
# and chromadb.utils.embedding_functions; the chromadb HTTP server is never started, so the vulnerable route is not exposed.
|
||||
pip_audit_args=(
|
||||
--desc
|
||||
--aliases
|
||||
--skip-editable
|
||||
--format json
|
||||
--output pip-audit-report.json
|
||||
--ignore-vuln PYSEC-2026-597 # nltk 3.9.4 (CVE-2026-12243): no fix available, transitive through crewai-tools[xml] -> unstructured.
|
||||
--ignore-vuln GHSA-rrmf-rvhw-rf47 # torch 2.12.0 (CVE-2025-3000): local-only memory corruption in torch.jit.script; no fix available.
|
||||
--ignore-vuln GHSA-f4j7-r4q5-qw2c # chromadb 1.1.1 (CVE-2026-45829): pre-auth RCE in the HTTP server; no fix available.
|
||||
)
|
||||
uv run pip-audit "${pip_audit_args[@]}"
|
||||
continue-on-error: true
|
||||
|
||||
- name: Display results
|
||||
@@ -132,4 +103,3 @@ jobs:
|
||||
~/.local/share/uv
|
||||
.venv
|
||||
key: uv-main-py3.11-${{ hashFiles('uv.lock') }}
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ repos:
|
||||
--ignore-vuln PYSEC-2024-277
|
||||
--ignore-vuln PYSEC-2026-89
|
||||
--ignore-vuln PYSEC-2026-97
|
||||
--ignore-vuln PYSEC-2026-597
|
||||
--ignore-vuln PYSEC-2025-148
|
||||
--ignore-vuln PYSEC-2025-183
|
||||
--ignore-vuln PYSEC-2025-189
|
||||
|
||||
158
AGENTS.md
@@ -1,142 +1,26 @@
|
||||
# Docs contributor guide
|
||||
# Agent Instructions for CrewAI OSS
|
||||
|
||||
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.
|
||||
CrewAI is a Python based framework for building AI agents and agentic systems.
|
||||
Follow these guidelines when contributing:
|
||||
|
||||
## TL;DR for editing docs
|
||||
## Key Guidelines
|
||||
|
||||
- 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.
|
||||
1. Follow Python best practices and idiomatic patterns.
|
||||
2. Maintain existing code structure and organization.
|
||||
3. Write unit tests for new functionality focusing on behaivor and not
|
||||
implementation.
|
||||
4. Document public APIs and complex logic.
|
||||
5. Suggest changes to the `docs/` folder when appropriate
|
||||
6. Follow software principles such as DRY and YAGNI.
|
||||
7. Keep diffs as minimal as possible.
|
||||
|
||||
## The version model
|
||||
## Changing Docs
|
||||
|
||||
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.
|
||||
1. Edit MDX under `docs/edge/en/*` and reference it from `docs/docs.json` if
|
||||
needed.
|
||||
2. Do not modify files under `docs/v*/`. Those are frozen release snapshots
|
||||
managed by devtools.
|
||||
3. Do not delete or rename files under `docs/images/` as frozen snapshots
|
||||
may reference them.
|
||||
4. If you want to preview your changes locally, use `cd docs && mintlify dev`.
|
||||
To check for broken links, run `cd docs && mintlify broken-links`.
|
||||
|
||||
14753
docs/docs.json
@@ -4,6 +4,330 @@ description: "تحديثات المنتج والتحسينات وإصلاحات
|
||||
icon: "clock"
|
||||
mode: "wide"
|
||||
---
|
||||
<Update label="28 يوليو 2026">
|
||||
## v1.15.8
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.8)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- إضافة WaitTool لإيقاف التنفيذ في المهام الطويلة.
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- إصلاح كتابات FileWriterTool ومعالجة الحواف الخشنة في أداة الملف.
|
||||
- وضع E2B_API_KEY كمتغير بيئي مطلوب لأدوات E2B.
|
||||
|
||||
### الوثائق
|
||||
- تحديث إرشادات توفر النموذج.
|
||||
|
||||
## المساهمون
|
||||
|
||||
@github-actions[bot], @joaomdmoura, @lucasgomide, @oalami, @thiagomoretto
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="26 يوليو 2026">
|
||||
## v1.15.7
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- حل مهارات السجل من خلال عميل CrewAI+ الخاص بالوقت الفعلي
|
||||
- استعادة من أدوات GPT-5.6 + reasoning_effort 400
|
||||
- جعل استدعاء الأدوات يعمل على مسار واجهة برمجة التطبيقات Responses
|
||||
- توجيه النماذج التي تعيد الاستجابات فقط بدلاً من الفشل مع 404
|
||||
- رفع bedrock-agentcore لتصحيح CVE-2026-16796
|
||||
|
||||
### الرصد
|
||||
- إصدار أحداث استخدام المهارات في الوقت الفعلي للرصد
|
||||
|
||||
### الوثائق
|
||||
- إضافة لقطة وتغيير السجل للإصدار v1.15.7a1
|
||||
|
||||
## المساهمون
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="26 يوليو 2026">
|
||||
## v1.15.7a1
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7a1)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- إصلاح حل مهارات السجل من خلال عميل CrewAI+ الخاص بالوقت الفعلي.
|
||||
- استعادة الأداء من أخطاء أدوات GPT-5.6 وجهد الاستدلال 400.
|
||||
- جعل استدعاء الأدوات يعمل على مسار واجهة برمجة التطبيقات للاستجابات.
|
||||
- توجيه نماذج الاستجابات فقط لمنع أخطاء 404.
|
||||
- رفع اعتماد bedrock-agentcore لإصلاح CVE-2026-16796.
|
||||
|
||||
### الرصد
|
||||
- إصدار أحداث استخدام المهارات في الوقت الفعلي لتحسين الرصد.
|
||||
|
||||
### الوثائق
|
||||
- تحديثات لقطة وتغيير للإصدار 1.15.6.
|
||||
|
||||
## المساهمون
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="24 يوليو 2026">
|
||||
## v1.15.6
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.6)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- إصلاح الكشف عن أدوات معاينة Anthropic.
|
||||
- الحفاظ على أسماء خصائص مخطط الأدوات الصارمة.
|
||||
- تنفيذ حدث execution_end عند فشل تنفيذ الطاقم والتدفق.
|
||||
- التعامل مع get_agent غير المتزامن في load_agent_from_repository.
|
||||
- إصلاح مشكلات حل الاعتماد.
|
||||
|
||||
### الوثائق
|
||||
- لقطة وتاريخ التغييرات للإصدار v1.15.5.
|
||||
|
||||
## المساهمون
|
||||
|
||||
@alex-clawd, @iris-clawd, @lorenzejay, @lucasgomide, @theCyberTech, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="20 يوليو 2026">
|
||||
## v1.15.5
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.5)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- مصادقة تنزيلات سجل المهارات
|
||||
|
||||
### الوثائق
|
||||
- تحديث اللقطة وسجل التغييرات للإصدار v1.15.4
|
||||
|
||||
## المساهمون
|
||||
|
||||
@vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="17 يوليو 2026">
|
||||
## v1.15.4
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.4)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- ترقية مستودع المهارات من حالة تجريبية
|
||||
|
||||
### الوثائق
|
||||
- إضافة تدفقات في وثائق الاستوديو
|
||||
|
||||
## المساهمون
|
||||
|
||||
@jessemiller, @joaomdmoura, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="16 يوليو 2026">
|
||||
## v1.15.3
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- إضافة معلمة معرف المنظمة إلى عميل PlusAPI
|
||||
- إضافة نقاط اعتراض الخطوات وإعادة صياغة توثيق نقاط تنفيذ @on
|
||||
- توصيل نقاط اعتراض حدود التنفيذ
|
||||
- إضافة موزع اعتراض عام
|
||||
- تشغيل التدفقات التصريحية على واجهة المستخدم النصية (خيار الطرية بدون واجهة)
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- مزامنة حدث بدء التنفيذ المكتمل مع نتيجة خطاف OUTPUT
|
||||
- إصلاح سمات وكيل المستودع الفارغة
|
||||
- التأكد من أن خطافات after_llm_call لا تكسر تنفيذ الأدوات الأصلية
|
||||
- تجنب الإضافة المزدوجة لرد الدور عندما يقوم المعالج بقص التاريخ
|
||||
- جعل تخزين نتائج الأدوات اختيارياً بدلاً من أن يكون مفعلًا بشكل افتراضي
|
||||
- التوقف عن إعادة كتابة وصف الأداة المؤلف عند الإنشاء
|
||||
- كشف استخدام الرموز تحت كلا الاسمين في نتائج الوكيل والطاقم
|
||||
- الإبلاغ عن مقاييس الاستخدام لكل استدعاء في نتائج بدء التنفيذ
|
||||
- التوقف عن إعادة تشغيل نية الدور السابق عندما تعيد route_turn() قيمة غير صحيحة
|
||||
|
||||
### الوثائق
|
||||
- تحديث تجميع خطافات التنفيذ وتوثيق جميع سياقات الخطاف
|
||||
|
||||
## المساهمون
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="16 يوليو 2026">
|
||||
## v1.15.3a2
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a2)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- إصلاح تزامن حدث انتهاء الانطلاق مع نتيجة خطاف OUTPUT
|
||||
|
||||
### الوثائق
|
||||
- تحديث لقطة الشاشة وسجل التغييرات للإصدار v1.15.3a1
|
||||
|
||||
### تحديثات التبعية
|
||||
- رفع setuptools إلى 0.83.0 لمعالجة PYSEC-2026-3447
|
||||
|
||||
## المساهمون
|
||||
|
||||
@lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="16 يوليو 2026">
|
||||
## v1.15.3a1
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a1)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- إضافة معلمة معرف المنظمة إلى عميل PlusAPI.
|
||||
- إضافة نقاط اعتراض الخطوات وإعادة صياغة وثائق نقاط تنفيذ `@on`.
|
||||
- توصيل نقاط اعتراض حدود التنفيذ.
|
||||
- إضافة موصل عام للاعتراضات.
|
||||
- تشغيل التدفقات التصريحية على واجهة المستخدم النصية (نسخة احتياطية من الطرفية بدون واجهة).
|
||||
- تحسين عناوين URL المخصصة لـ OpenAI.
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- إصلاح سمات وكيل المستودع الفارغة.
|
||||
- إصلاح نقاط `after_llm_call` لمنع كسر تنفيذ الأدوات الأصلية.
|
||||
- إيقاف الإضافة المزدوجة لرد الدور عندما يقوم المعالج بقص التاريخ.
|
||||
- جعل تخزين نتائج الأدوات اختيارياً بدلاً من أن يكون مفعلًا بشكل افتراضي.
|
||||
- إيقاف إعادة كتابة وصف الأداة المؤلف عند الإنشاء.
|
||||
- كشف استخدام الرموز تحت كلا الاسمين في نتائج الوكيل والطاقم.
|
||||
- الإبلاغ عن مقاييس الاستخدام لكل استدعاء في نتائج البداية.
|
||||
- إيقاف إعادة تشغيل نية الدور السابق عندما تعيد `route_turn()` قيمة غير صحيحة.
|
||||
- تصريف الكتابات في الذاكرة قبل أحداث البداية وإكمال التدفق.
|
||||
|
||||
### الوثائق
|
||||
- تجميع نقاط تنفيذ الوثائق وتوثيق جميع سياقات الاعتراض.
|
||||
- تحديث الوثائق لنقاط تنفيذ الاعتراض.
|
||||
|
||||
## المساهمون
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="7 يوليو 2026">
|
||||
## v1.15.2
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- سحب أحدث نماذج LLM ديناميكيًا في معالج الطاقم.
|
||||
- دعم تعريفات المهارات المضمنة.
|
||||
- إضافة مهارة تأليف تعريف التدفق المُولد.
|
||||
- دعم مدخلات إجراءات التدفق المهيكلة.
|
||||
- إضافة مساعد نصي لمطالبات CEL للتدفق.
|
||||
- إضافة مساعد نصي لمثال مهارة التدفق.
|
||||
- تنفيذ إعداد الرسائل ومعالجة التعليقات في AgentExecutor.
|
||||
- إضافة وكلاء المستودع إلى تعريفات التدفق.
|
||||
- تعريف بروتوكول إطار البث للتدفقات.
|
||||
- نوع الأداة والتطبيق في CrewDefinition.
|
||||
- إعادة توجيه أوامر القالب إلى crewAIInc-fde org.
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- تخزين نموذج كتالوج المفتاح بواسطة مفتاح API الدقيق، تقصير TTL، وتخطي Ollama.
|
||||
- توحيد دقة مدخلات التدفق لـ `crewai run` والمطالبة من مخطط الحالة.
|
||||
- حل مشكلات pip-audit لـ onnx 1.22.0 و nltk PYSEC-2026-597.
|
||||
- التأكد من أننا نكتب الإصدار للتدفقات.
|
||||
- تضمين aiobotocore في الإضافات الأساسية.
|
||||
- رفض طرق التدفق ذات الاستماع الذاتي.
|
||||
- قطع تنقل إصدار الوثائق من Edge حتى لا يتم إسقاط الصفحات الجديدة.
|
||||
|
||||
### الوثائق
|
||||
- تحديث اللغة من القواعد إلى السياسات لتتناسب مع تغييرات لوحة المعلومات الجديدة.
|
||||
- توثيق خيارات وكيل التدفق.
|
||||
- إضافة وثائق البث إلى التنقل.
|
||||
- توثيق نوع قاعدة حد التكلفة في وحدة التحكم الخاصة بالوكيل.
|
||||
- حذف مراجع CREWAI_LOG_FORMAT من دليل Datadog.
|
||||
|
||||
## المساهمون
|
||||
|
||||
@akaKuruma, @danielfsbarreto, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @manisrinivasan2k1, @renatonitta, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="1 يوليو 2026">
|
||||
## v1.15.2a2
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a2)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- إضافة aiobotocore إلى الإضافات الأساسية
|
||||
- توثيق خيارات وكيل التدفق
|
||||
- إضافة مساعد نصي إلى مثال مهارة التدفق
|
||||
- إضافة مساعد نصي لمطالب CEL الخاصة بالتدفق
|
||||
- إضافة وثائق البث إلى التنقل
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- رفض طرق التدفق ذات الاستماع الذاتي
|
||||
|
||||
### الوثائق
|
||||
- تحديث اللقطة وسجل التغييرات للإصدار v1.15.2a1
|
||||
- ضغط ملف AGENTS.md
|
||||
|
||||
## المساهمون
|
||||
|
||||
@akaKuruma, @github-code-quality[bot], @lorenzejay, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="30 يونيو 2026">
|
||||
## v1.15.2a1
|
||||
|
||||
[عرض الإصدار على GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a1)
|
||||
|
||||
## ما الذي تغير
|
||||
|
||||
### الميزات
|
||||
- إعادة توجيه أوامر القالب إلى منظمة crewAIInc-fde
|
||||
- دعم تعريفات المهارات المضمنة
|
||||
- تعريف بروتوكول إطار التدفق للتدفقات
|
||||
- إضافة أداة النوع والتطبيق في CrewDefinition
|
||||
- إضافة مهارة تأليف تعريف التدفق المُنشأ
|
||||
|
||||
### إصلاحات الأخطاء
|
||||
- قطع تنقل إصدار الوثائق من Edge لمنع فقدان الصفحات الجديدة
|
||||
|
||||
### الوثائق
|
||||
- توثيق نوع قاعدة حد التكلفة في وحدة التحكم الخاصة بالوكيل
|
||||
- إزالة مراجع CREWAI_LOG_FORMAT من دليل Datadog
|
||||
|
||||
## المساهمون
|
||||
|
||||
@danielfsbarreto, @joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="26 يونيو 2026">
|
||||
## v1.15.1
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ mode: "wide"
|
||||
تحدد نافذة السياق مقدار النص الذي يمكن لـ LLM معالجته في وقت واحد. النوافذ الأكبر (مثل 128K رمز) تتيح سياقًا أكثر لكنها قد تكون أكثر تكلفة وأبطأ.
|
||||
</Card>
|
||||
<Card title="درجة الحرارة" icon="temperature-three-quarters">
|
||||
تتحكم درجة الحرارة (0.0 إلى 1.0) في عشوائية الاستجابة. القيم المنخفضة (مثل 0.2) تنتج مخرجات أكثر تركيزًا وحتمية، بينما القيم الأعلى (مثل 0.8) تزيد الإبداع والتنوع.
|
||||
درجة الحرارة هي أداة للتحكم في أخذ العينات تدعمها بعض النماذج. تجعل القيم المنخفضة أخذ العينات أكثر تركيزًا عمومًا، بينما تزيد القيم الأعلى التباين. تتجاهل بعض نماذج الاستدلال الأحدث هذا المعامل أو توقف دعمه أو ترفضه، لذا راجع وثائق النموذج المحدد قبل ضبطه.
|
||||
</Card>
|
||||
<Card title="اختيار المزود" icon="server">
|
||||
يقدم كل مزود LLM (مثل OpenAI و Anthropic و Google) نماذج مختلفة بقدرات وأسعار وميزات متفاوتة. اختر بناءً على احتياجاتك من الدقة والسرعة والتكلفة.
|
||||
@@ -38,7 +38,7 @@ mode: "wide"
|
||||
أبسط طريقة للبدء. عيّن النموذج في بيئتك مباشرة، من خلال ملف `.env` أو في كود تطبيقك. إذا استخدمت `crewai create` لبدء مشروعك، سيكون مُعيّنًا بالفعل.
|
||||
|
||||
```bash .env
|
||||
MODEL=model-id # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...
|
||||
MODEL=provider/model-id # e.g. openai/gpt-5.6-terra
|
||||
|
||||
# Be sure to set your API keys here too. See the Provider
|
||||
# section below.
|
||||
@@ -57,7 +57,7 @@ mode: "wide"
|
||||
goal: Conduct comprehensive research and analysis
|
||||
backstory: A dedicated research professional with years of experience
|
||||
verbose: true
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
llm: provider/model-id # e.g. anthropic/claude-sonnet-4-6
|
||||
# (see provider configuration examples below for more)
|
||||
```
|
||||
|
||||
@@ -76,32 +76,24 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
# Basic configuration
|
||||
llm = LLM(model="model-id-here") # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
llm = LLM(model="provider/model-id") # e.g. gemini/gemini-3.6-flash
|
||||
|
||||
# Advanced configuration with detailed parameters
|
||||
llm = LLM(
|
||||
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
temperature=0.7, # Higher for more creative outputs
|
||||
timeout=120, # Seconds to wait for response
|
||||
max_tokens=4000, # Maximum length of response
|
||||
top_p=0.9, # Nucleus sampling parameter
|
||||
frequency_penalty=0.1 , # Reduce repetition
|
||||
presence_penalty=0.1, # Encourage topic diversity
|
||||
model="provider/model-id",
|
||||
timeout=120,
|
||||
max_tokens=4000,
|
||||
response_format={"type": "json"}, # For structured outputs
|
||||
seed=42 # For reproducible results
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
شرح المعاملات:
|
||||
- `temperature`: تتحكم في العشوائية (0.0-1.0)
|
||||
- `timeout`: أقصى وقت انتظار للاستجابة
|
||||
- `max_tokens`: تحدد طول الاستجابة
|
||||
- `top_p`: بديل لدرجة الحرارة للعينات
|
||||
- `frequency_penalty`: تقلل تكرار الكلمات
|
||||
- `presence_penalty`: تشجع موضوعات جديدة
|
||||
- `response_format`: تحدد هيكل المخرجات
|
||||
- `seed`: تضمن مخرجات متسقة
|
||||
|
||||
عناصر التحكم في أخذ العينات مثل `temperature` و`top_p`، ومعاملات العقوبة، وأسماء حدود الرموز، وعناصر التحكم في الاستدلال خاصة بكل نموذج. أضفها فقط عندما يدعمها المزود والنموذج المحددان. راجع أمثلة المزودين أدناه ووثائق النموذج لدى المزود.
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -120,6 +112,10 @@ mode: "wide"
|
||||
يدعم CrewAI العديد من مزودي LLM، كل منهم يقدم ميزات فريدة وطرق مصادقة وقدرات نماذج.
|
||||
في هذا القسم، ستجد أمثلة مفصلة تساعدك في اختيار وإعداد وتحسين LLM الأنسب لاحتياجات مشروعك.
|
||||
|
||||
<Warning>
|
||||
يتغير توفر النماذج باستمرار وقد يختلف حسب الحساب والمنطقة والمنصة السحابية. تستخدم الأمثلة أدناه نماذج متاحة وقت كتابة هذا الدليل، لكنها ليست قوائم دعم شاملة. قبل النشر، تحقق من معرّف النموذج وحالة دورة حياته في كتالوج المزود المرتبط.
|
||||
</Warning>
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI">
|
||||
يوفر CrewAI تكاملًا أصليًا مع OpenAI من خلال OpenAI Python SDK.
|
||||
@@ -137,10 +133,10 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
api_key="your-api-key", # Or set OPENAI_API_KEY
|
||||
temperature=0.7,
|
||||
max_tokens=4000
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4000
|
||||
)
|
||||
```
|
||||
|
||||
@@ -149,25 +145,16 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
api_key="your-api-key",
|
||||
base_url="https://api.openai.com/v1", # Optional custom endpoint
|
||||
organization="org-...", # Optional organization ID
|
||||
project="proj_...", # Optional project ID
|
||||
temperature=0.7,
|
||||
max_tokens=4000,
|
||||
max_completion_tokens=4000, # For newer models
|
||||
top_p=0.9,
|
||||
frequency_penalty=0.1,
|
||||
presence_penalty=0.1,
|
||||
stop=["END"],
|
||||
seed=42, # For reproducible outputs
|
||||
max_completion_tokens=4000,
|
||||
reasoning_effort="medium",
|
||||
stream=True, # Enable streaming
|
||||
timeout=60.0, # Request timeout in seconds
|
||||
max_retries=3, # Maximum retry attempts
|
||||
logprobs=True, # Return log probabilities
|
||||
top_logprobs=5, # Number of most likely tokens
|
||||
reasoning_effort="medium" # For o1 models: low, medium, high
|
||||
max_retries=3 # Maximum retry attempts
|
||||
)
|
||||
```
|
||||
|
||||
@@ -182,7 +169,7 @@ mode: "wide"
|
||||
summary: str
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
)
|
||||
```
|
||||
|
||||
@@ -191,30 +178,15 @@ mode: "wide"
|
||||
- `OPENAI_BASE_URL`: عنوان URL مخصص لـ OpenAI API (اختياري)
|
||||
|
||||
**الميزات:**
|
||||
- دعم استدعاء الدوال الأصلي (باستثناء نماذج o1)
|
||||
- دعم أصلي لاستدعاء الدوال
|
||||
- مخرجات منظمة مع JSON schema
|
||||
- دعم البث للاستجابات في الوقت الفعلي
|
||||
- تتبع استخدام الرموز
|
||||
- دعم تسلسلات التوقف (باستثناء نماذج o1)
|
||||
- عناصر تحكم في التوليد خاصة بالمزود
|
||||
- احتمالات السجل لرؤى على مستوى الرموز
|
||||
- التحكم في جهد الاستدلال لنماذج o1
|
||||
- التحكم في جهد الاستدلال للنماذج المتوافقة
|
||||
|
||||
**النماذج المدعومة:**
|
||||
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|---------------------|------------------|-----------------------------------------------|
|
||||
| gpt-4.1 | 1M tokens | أحدث نموذج بقدرات محسّنة |
|
||||
| gpt-4.1-mini | 1M tokens | إصدار فعال بسياق كبير |
|
||||
| gpt-4.1-nano | 1M tokens | متغير فائق الكفاءة |
|
||||
| gpt-4o | 128,000 tokens | محسّن للسرعة والذكاء |
|
||||
| gpt-4o-mini | 200,000 tokens | فعال من حيث التكلفة بسياق كبير |
|
||||
| gpt-4-turbo | 128,000 tokens | المحتوى الطويل، تحليل المستندات |
|
||||
| gpt-4 | 8,192 tokens | مهام الدقة العالية، الاستدلال المعقد |
|
||||
| o1 | 200,000 tokens | الاستدلال المتقدم، حل المشكلات المعقدة |
|
||||
| o1-preview | 128,000 tokens | معاينة قدرات الاستدلال |
|
||||
| o1-mini | 128,000 tokens | نموذج استدلال فعال |
|
||||
| o3-mini | 200,000 tokens | نموذج استدلال خفيف |
|
||||
| o4-mini | 200,000 tokens | استدلال فعال من الجيل التالي |
|
||||
تضيف OpenAI نماذج جديدة وتسحب snapshots قديمة بانتظام. راجع [كتالوج نماذج OpenAI](https://developers.openai.com/api/docs/models) للحصول على معرّفات النماذج الحالية ونوافذ السياق وتوافق endpoints ومعلومات دورة الحياة.
|
||||
|
||||
**Responses API:**
|
||||
|
||||
@@ -276,14 +248,7 @@ mode: "wide"
|
||||
)
|
||||
```
|
||||
|
||||
جميع النماذج المدرجة هنا https://llama.developer.meta.com/docs/models/ مدعومة.
|
||||
|
||||
| معرّف النموذج | طول سياق الإدخال | طول سياق المخرجات | وسائط الإدخال | وسائط المخرجات |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8` | 128k | 4028 | نص، صورة | نص |
|
||||
| `meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 128k | 4028 | نص، صورة | نص |
|
||||
| `meta_llama/Llama-3.3-70B-Instruct` | 128k | 4028 | نص | نص |
|
||||
| `meta_llama/Llama-3.3-8B-Instruct` | 128k | 4028 | نص | نص |
|
||||
راجع [نظرة عامة على نماذج Meta Llama](https://ai.meta.com/llama/get-started/) للتعرّف على عائلات النماذج والوسائط وإرشادات حدود السياق الحالية.
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
@@ -353,7 +318,7 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-5-sonnet-20241022",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
api_key="your-api-key", # Or set ANTHROPIC_API_KEY
|
||||
max_tokens=4096 # Required for Anthropic
|
||||
)
|
||||
@@ -364,12 +329,10 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-5-sonnet-20241022",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
api_key="your-api-key",
|
||||
base_url="https://api.anthropic.com", # Optional custom endpoint
|
||||
temperature=0.7,
|
||||
max_tokens=4096, # Required parameter
|
||||
top_p=0.9,
|
||||
stop_sequences=["END", "STOP"], # Anthropic uses stop_sequences
|
||||
stream=True, # Enable streaming
|
||||
timeout=60.0, # Request timeout in seconds
|
||||
@@ -377,7 +340,7 @@ mode: "wide"
|
||||
)
|
||||
```
|
||||
|
||||
**التفكير الموسّع (Claude Sonnet 4 وما بعده):**
|
||||
**التفكير الموسّع:**
|
||||
|
||||
يدعم CrewAI ميزة التفكير الموسّع من Anthropic، التي تتيح لـ Claude التفكير في المشكلات بطريقة أكثر شبهًا بالبشر قبل الاستجابة. مفيد بشكل خاص لمهام الاستدلال والتحليل وحل المشكلات المعقدة.
|
||||
|
||||
@@ -386,14 +349,14 @@ mode: "wide"
|
||||
|
||||
# Enable extended thinking with default settings
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
thinking={"type": "enabled"},
|
||||
max_tokens=10000
|
||||
)
|
||||
|
||||
# Configure thinking with budget control
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
thinking={
|
||||
"type": "enabled",
|
||||
"budget_tokens": 5000 # Limit thinking tokens
|
||||
@@ -406,9 +369,7 @@ mode: "wide"
|
||||
- `type`: عيّن إلى `"enabled"` لتفعيل وضع التفكير الموسّع
|
||||
- `budget_tokens` (اختياري): أقصى رموز للتفكير (يساعد في التحكم بالتكاليف)
|
||||
|
||||
**النماذج التي تدعم التفكير الموسّع:**
|
||||
- `claude-sonnet-4` والنماذج الأحدث
|
||||
- `claude-3-7-sonnet` (مع قدرات التفكير الموسّع)
|
||||
تختلف أوضاع التفكير والمعاملات المقبولة بين أجيال Claude. تحقق من قدرات النموذج المحدد قبل تفعيل `thinking`.
|
||||
|
||||
**متى تستخدم التفكير الموسّع:**
|
||||
- الاستدلال المعقد وحل المشكلات متعددة الخطوات
|
||||
@@ -424,7 +385,7 @@ mode: "wide"
|
||||
|
||||
**الميزات:**
|
||||
- دعم استخدام الأدوات الأصلي لنماذج Claude 3+
|
||||
- دعم التفكير الموسّع لـ Claude Sonnet 4+
|
||||
- دعم التفكير الموسّع لنماذج Claude المتوافقة
|
||||
- دعم البث للاستجابات في الوقت الفعلي
|
||||
- معالجة تلقائية لرسائل النظام
|
||||
- تسلسلات التوقف للتحكم في المخرجات
|
||||
@@ -438,20 +399,7 @@ mode: "wide"
|
||||
- يجب أن تكون الرسالة الأولى من المستخدم (يتم التعامل معها تلقائيًا)
|
||||
- يجب أن تتناوب الرسائل بين المستخدم والمساعد
|
||||
|
||||
**النماذج المدعومة:**
|
||||
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|------------------------------|------------------|-----------------------------------------------|
|
||||
| claude-sonnet-4 | 200,000 tokens | الأحدث مع قدرات التفكير الموسّع |
|
||||
| claude-3-7-sonnet | 200,000 tokens | الاستدلال المتقدم والمهام الوكيلية |
|
||||
| claude-3-5-sonnet-20241022 | 200,000 tokens | أحدث Sonnet بأفضل أداء |
|
||||
| claude-3-5-haiku | 200,000 tokens | نموذج سريع وصغير للاستجابات السريعة |
|
||||
| claude-3-opus | 200,000 tokens | الأكثر قدرة للمهام المعقدة |
|
||||
| claude-3-sonnet | 200,000 tokens | توازن بين الذكاء والسرعة |
|
||||
| claude-3-haiku | 200,000 tokens | الأسرع للمهام البسيطة |
|
||||
| claude-2.1 | 200,000 tokens | سياق موسّع، هلوسات أقل |
|
||||
| claude-2 | 100,000 tokens | نموذج متعدد الاستخدامات |
|
||||
| claude-instant | 100,000 tokens | سريع وفعال من حيث التكلفة للمهام اليومية |
|
||||
راجع [نظرة عامة على نماذج Anthropic](https://platform.claude.com/docs/en/about-claude/models/overview) للحصول على معرّفات النماذج وقدراتها الحالية، وراجع [جدول إيقاف النماذج](https://platform.claude.com/docs/en/about-claude/model-deprecations) قبل تثبيت نموذج في الإنتاج.
|
||||
|
||||
**ملاحظة:** لاستخدام Anthropic، ثبّت التبعيات المطلوبة:
|
||||
```bash
|
||||
@@ -483,9 +431,8 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
model="gemini/gemini-3.6-flash",
|
||||
api_key="your-api-key", # Or set GOOGLE_API_KEY/GEMINI_API_KEY
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
@@ -494,11 +441,8 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.5-flash",
|
||||
model="gemini/gemini-3.6-flash",
|
||||
api_key="your-api-key",
|
||||
temperature=0.7,
|
||||
top_p=0.9,
|
||||
top_k=40, # Top-k sampling parameter
|
||||
max_output_tokens=8192,
|
||||
stop_sequences=["END", "STOP"],
|
||||
stream=True, # Enable streaming
|
||||
@@ -524,8 +468,7 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -542,7 +485,7 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-1.5-pro",
|
||||
model="gemini/gemini-3.6-flash",
|
||||
project="your-gcp-project-id",
|
||||
location="us-central1" # GCP region
|
||||
)
|
||||
@@ -555,7 +498,7 @@ mode: "wide"
|
||||
- `GOOGLE_CLOUD_LOCATION`: موقع GCP (الافتراضي `us-central1`)
|
||||
|
||||
**الميزات:**
|
||||
- دعم استدعاء الدوال الأصلي لنماذج Gemini 1.5+ و 2.x
|
||||
- دعم أصلي لاستدعاء الدوال لنماذج Gemini المتوافقة
|
||||
- دعم البث للاستجابات في الوقت الفعلي
|
||||
- قدرات متعددة الوسائط (نص، صور، فيديو)
|
||||
- إعداد إعدادات الأمان
|
||||
@@ -563,41 +506,21 @@ mode: "wide"
|
||||
- معالجة تلقائية لتعليمات النظام
|
||||
- تتبع استخدام الرموز
|
||||
|
||||
**نماذج Gemini:**
|
||||
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|--------------------------------|-----------------|-------------------------------------------------------------------|
|
||||
| gemini-2.5-flash | 1M tokens | التفكير التكيفي، كفاءة التكلفة |
|
||||
| gemini-2.5-pro | 1M tokens | التفكير والاستدلال المحسّن، الفهم متعدد الوسائط |
|
||||
| gemini-2.0-flash | 1M tokens | ميزات الجيل التالي، السرعة، التفكير |
|
||||
| gemini-2.0-flash-thinking | 32,768 tokens | الاستدلال المتقدم مع عملية التفكير |
|
||||
| gemini-2.0-flash-lite | 1M tokens | كفاءة التكلفة ووقت الاستجابة المنخفض |
|
||||
| gemini-1.5-pro | 2M tokens | الأفضل أداءً، الاستدلال المنطقي، البرمجة |
|
||||
| gemini-1.5-flash | 1M tokens | نموذج متعدد الوسائط متوازن، جيد لمعظم المهام |
|
||||
| gemini-1.5-flash-8b | 1M tokens | الأسرع والأكثر كفاءة من حيث التكلفة |
|
||||
| gemini-1.0-pro | 32,768 tokens | نموذج الجيل السابق |
|
||||
تنشر Google معرّفات Gemini الحالية وقدراتها ومراحل دورة حياتها في [كتالوج نماذج Gemini](https://ai.google.dev/gemini-api/docs/models). تحقق من [جدول الإيقاف](https://ai.google.dev/gemini-api/docs/deprecations) قبل اختيار نموذج مستقر أو preview. وتستضيف Gemini API أيضًا [نماذج Gemma](https://ai.google.dev/gemma/docs).
|
||||
|
||||
**ملاحظة:** لاستخدام Google Gemini، ثبّت التبعيات المطلوبة:
|
||||
```bash
|
||||
uv add "crewai[google-genai]"
|
||||
```
|
||||
|
||||
القائمة الكاملة للنماذج متاحة في [وثائق نماذج Gemini](https://ai.google.dev/gemini-api/docs/models).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google (Vertex AI)">
|
||||
احصل على بيانات الاعتماد من Google Cloud Console واحفظها في ملف JSON، ثم حمّلها بالكود التالي:
|
||||
```python Code
|
||||
import json
|
||||
|
||||
file_path = 'path/to/vertex_ai_service_account.json'
|
||||
|
||||
# Load the JSON file
|
||||
with open(file_path, 'r') as file:
|
||||
vertex_credentials = json.load(file)
|
||||
|
||||
# Convert the credentials to a JSON string
|
||||
vertex_credentials_json = json.dumps(vertex_credentials)
|
||||
صادِق باستخدام [بيانات الاعتماد التلقائية للتطبيق](https://cloud.google.com/docs/authentication/provide-credentials-adc)، ثم اضبط مزود Gemini الأصلي لاستخدام Vertex AI:
|
||||
```toml .env
|
||||
GOOGLE_GENAI_USE_VERTEXAI=true
|
||||
GOOGLE_CLOUD_PROJECT=<your-project-id>
|
||||
GOOGLE_CLOUD_LOCATION=<location>
|
||||
```
|
||||
|
||||
مثال الاستخدام في مشروع CrewAI:
|
||||
@@ -605,15 +528,15 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini-1.5-pro-latest", # or vertex_ai/gemini-1.5-pro-latest
|
||||
temperature=0.7,
|
||||
vertex_credentials=vertex_credentials_json
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
تختلف إتاحة Vertex AI باختلاف المنطقة. استخدم [كتالوج نماذج Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models) للتحقق من معرّف النموذج والمنطقة قبل النشر.
|
||||
|
||||
**ملاحظة:** يستخدم هذا المسار تكامل Gemini الأصلي في CrewAI. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
uv add "crewai[google-genai]"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
@@ -664,7 +587,7 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
model="bedrock/us.anthropic.claude-sonnet-4-6",
|
||||
region_name="us-east-1"
|
||||
)
|
||||
```
|
||||
@@ -674,7 +597,7 @@ mode: "wide"
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
model="bedrock/us.anthropic.claude-sonnet-4-6",
|
||||
aws_access_key_id="your-access-key", # Or set AWS_ACCESS_KEY_ID
|
||||
aws_secret_access_key="your-secret-key", # Or set AWS_SECRET_ACCESS_KEY
|
||||
aws_session_token="your-session-token", # For temporary credentials
|
||||
@@ -719,37 +642,9 @@ mode: "wide"
|
||||
- يجب أن تكون الرسالة الأولى من المستخدم (يتم التعامل معها تلقائيًا)
|
||||
- بعض النماذج (مثل Cohere) تتطلب أن تنتهي المحادثة برسالة المستخدم
|
||||
|
||||
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) هو خدمة مُدارة توفر الوصول إلى نماذج أساسية متعددة من أبرز شركات الذكاء الاصطناعي عبر واجهة API موحدة.
|
||||
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|-------------------------|----------------------|-------------------------------------------------------------------|
|
||||
| Amazon Nova Pro | حتى 300k tokens | أداء عالٍ، نموذج يوازن بين الدقة والسرعة والفعالية من حيث التكلفة عبر مهام متنوعة. |
|
||||
| Amazon Nova Micro | حتى 128k tokens | نموذج نصي فقط عالي الأداء وفعال من حيث التكلفة ومحسّن لأقل وقت استجابة. |
|
||||
| Amazon Nova Lite | حتى 300k tokens | معالجة متعددة الوسائط بأسعار معقولة للصور والفيديو والنص مع قدرات في الوقت الفعلي. |
|
||||
| Claude 3.7 Sonnet | حتى 128k tokens | الأفضل أداءً للاستدلال المعقد والبرمجة ووكلاء الذكاء الاصطناعي |
|
||||
| Claude 3.5 Sonnet v2 | حتى 200k tokens | نموذج متطور متخصص في هندسة البرمجيات والقدرات الوكيلية والتفاعل مع الحاسوب بتكلفة محسّنة. |
|
||||
| Claude 3.5 Sonnet | حتى 200k tokens | نموذج عالي الأداء يقدم ذكاءً واستدلالًا فائقين عبر مهام متنوعة مع توازن مثالي بين السرعة والتكلفة. |
|
||||
| Claude 3.5 Haiku | حتى 200k tokens | نموذج متعدد الوسائط سريع وصغير محسّن للاستجابات السريعة والتفاعلات الشبيهة بالبشر |
|
||||
| Claude 3 Sonnet | حتى 200k tokens | نموذج متعدد الوسائط يوازن بين الذكاء والسرعة للنشر بكميات كبيرة. |
|
||||
| Claude 3 Haiku | حتى 200k tokens | نموذج متعدد الوسائط صغير وسريع محسّن للاستجابات السريعة والتفاعلات المحادثية الطبيعية |
|
||||
| Claude 3 Opus | حتى 200k tokens | أكثر النماذج متعددة الوسائط تقدمًا يتفوق في المهام المعقدة بالاستدلال الشبيه بالبشر والفهم السياقي الفائق. |
|
||||
| Claude 2.1 | حتى 200k tokens | إصدار محسّن بنافذة سياق موسّعة وموثوقية محسّنة وهلوسات أقل لتطبيقات النصوص الطويلة وRAG |
|
||||
| Claude | حتى 100k tokens | نموذج متعدد الاستخدامات يتفوق في الحوار المتقدم والمحتوى الإبداعي واتباع التعليمات الدقيقة. |
|
||||
| Claude Instant | حتى 100k tokens | نموذج سريع وفعال من حيث التكلفة للمهام اليومية مثل الحوار والتحليل والتلخيص والأسئلة والأجوبة |
|
||||
| Llama 3.1 405B Instruct | حتى 128k tokens | نموذج LLM متقدم لتوليد البيانات الاصطناعية والتقطير والاستدلال لروبوتات المحادثة والبرمجة والمهام المتخصصة. |
|
||||
| Llama 3.1 70B Instruct | حتى 128k tokens | يدعم المحادثات المعقدة مع فهم سياقي فائق واستدلال وتوليد نص. |
|
||||
| Llama 3.1 8B Instruct | حتى 128k tokens | نموذج متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| Llama 3 70B Instruct | حتى 8k tokens | يدعم المحادثات المعقدة مع فهم سياقي فائق واستدلال وتوليد نص. |
|
||||
| Llama 3 8B Instruct | حتى 8k tokens | نموذج LLM متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| Titan Text G1 - Lite | حتى 4k tokens | نموذج خفيف وفعال من حيث التكلفة محسّن لمهام اللغة الإنجليزية والضبط الدقيق مع التركيز على التلخيص وتوليد المحتوى. |
|
||||
| Titan Text G1 - Express | حتى 8k tokens | نموذج متعدد الاستخدامات لمهام اللغة العامة والمحادثة وتطبيقات RAG مع دعم الإنجليزية وأكثر من 100 لغة. |
|
||||
| Cohere Command | حتى 4k tokens | نموذج متخصص في اتباع أوامر المستخدم وتقديم حلول عملية للمؤسسات. |
|
||||
| Jurassic-2 Mid | حتى 8,191 tokens | نموذج فعال من حيث التكلفة يوازن بين الجودة والسعر لمهام اللغة المتنوعة مثل الأسئلة والأجوبة والتلخيص وتوليد المحتوى. |
|
||||
| Jurassic-2 Ultra | حتى 8,191 tokens | نموذج لتوليد النص المتقدم والفهم، يتفوق في المهام المعقدة مثل التحليل وإنشاء المحتوى. |
|
||||
| Jamba-Instruct | حتى 256k tokens | نموذج بنافذة سياق موسّعة محسّن لتوليد النص الفعال من حيث التكلفة والتلخيص والأسئلة والأجوبة. |
|
||||
| Mistral 7B Instruct | حتى 32k tokens | نموذج LLM يتبع التعليمات ويكمل الطلبات ويولد نصًا إبداعيًا. |
|
||||
| Mistral 8x7B Instruct | حتى 32k tokens | نموذج LLM بمعمارية MOE يتبع التعليمات ويكمل الطلبات ويولد نصًا إبداعيًا. |
|
||||
| DeepSeek R1 | 32,768 tokens | نموذج استدلال متقدم |
|
||||
تختلف إتاحة نماذج Amazon Bedrock ومعرّفاتها باختلاف المنطقة. استخدم مرجع
|
||||
[النماذج والمناطق المدعومة](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)
|
||||
لاختيار نموذج والتحقق من دعم Converse API.
|
||||
|
||||
**ملاحظة:** لاستخدام AWS Bedrock، ثبّت التبعيات المطلوبة:
|
||||
```bash
|
||||
@@ -806,81 +701,13 @@ mode: "wide"
|
||||
مثال الاستخدام في مشروع CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nvidia_nim/meta/llama3-70b-instruct",
|
||||
model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
يوفر Nvidia NIM مجموعة شاملة من النماذج لحالات الاستخدام المتنوعة، من المهام ذات الأغراض العامة إلى التطبيقات المتخصصة.
|
||||
يتغير كتالوج NVIDIA NIM المستضاف باستمرار. استخدم [كتالوج نماذج NVIDIA NIM](https://build.nvidia.com/models) لاختيار endpoint حالي والتحقق من معرّف النموذج والوسائط وحدود السياق.
|
||||
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|-------------------------------------------------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8,192 tokens | نموذج لغة صغير متطور يقدم دقة فائقة لروبوتات المحادثة والمساعدين الافتراضيين وتوليد المحتوى. |
|
||||
| nvidia/nemotron-4-mini-hindi-4b-instruct | 4,096 tokens | نموذج لغة صغير ثنائي اللغة هندي-إنجليزي للاستدلال على الجهاز، مصمم خصيصًا للغة الهندية. |
|
||||
| nvidia/llama-3.1-nemotron-70b-instruct | 128k tokens | مخصص لتعزيز فائدة الاستجابات |
|
||||
| nvidia/llama3-chatqa-1.5-8b | 128k tokens | نموذج LLM متقدم لتوليد استجابات عالية الجودة ومدركة للسياق لروبوتات المحادثة ومحركات البحث. |
|
||||
| nvidia/llama3-chatqa-1.5-70b | 128k tokens | نموذج LLM متقدم لتوليد استجابات عالية الجودة ومدركة للسياق لروبوتات المحادثة ومحركات البحث. |
|
||||
| nvidia/vila | 128k tokens | نموذج رؤية-لغة متعدد الوسائط يفهم النص والصور والفيديو وينشئ استجابات غنية بالمعلومات |
|
||||
| nvidia/neva-22 | 4,096 tokens | نموذج رؤية-لغة متعدد الوسائط يفهم النص والصور ويولد استجابات غنية بالمعلومات |
|
||||
| nvidia/nemotron-mini-4b-instruct | 8,192 tokens | مهام ذات أغراض عامة |
|
||||
| nvidia/usdcode-llama3-70b-instruct | 128k tokens | نموذج LLM متطور يجيب على استعلامات معرفة OpenUSD ويولد كود USD-Python. |
|
||||
| nvidia/nemotron-4-340b-instruct | 4,096 tokens | ينشئ بيانات اصطناعية متنوعة تحاكي خصائص بيانات العالم الحقيقي. |
|
||||
| meta/codellama-70b | 100k tokens | نموذج LLM قادر على توليد الكود من اللغة الطبيعية والعكس. |
|
||||
| meta/llama2-70b | 4,096 tokens | نموذج لغة كبير متطور قادر على توليد النص والكود استجابة للمطالبات. |
|
||||
| meta/llama3-8b-instruct | 8,192 tokens | نموذج LLM متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| meta/llama3-70b-instruct | 8,192 tokens | يدعم المحادثات المعقدة مع فهم سياقي فائق واستدلال وتوليد نص. |
|
||||
| meta/llama-3.1-8b-instruct | 128k tokens | نموذج متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| meta/llama-3.1-70b-instruct | 128k tokens | يدعم المحادثات المعقدة مع فهم سياقي فائق واستدلال وتوليد نص. |
|
||||
| meta/llama-3.1-405b-instruct | 128k tokens | نموذج LLM متقدم لتوليد البيانات الاصطناعية والتقطير والاستدلال لروبوتات المحادثة والبرمجة والمهام المتخصصة. |
|
||||
| meta/llama-3.2-1b-instruct | 128k tokens | نموذج لغة صغير متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| meta/llama-3.2-3b-instruct | 128k tokens | نموذج لغة صغير متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| meta/llama-3.2-11b-vision-instruct | 128k tokens | نموذج لغة صغير متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| meta/llama-3.2-90b-vision-instruct | 128k tokens | نموذج لغة صغير متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| google/gemma-7b | 8,192 tokens | نموذج متطور لتوليد النص وفهمه وتحويله وتوليد الكود. |
|
||||
| google/gemma-2b | 8,192 tokens | نموذج متطور لتوليد النص وفهمه وتحويله وتوليد الكود. |
|
||||
| google/codegemma-7b | 8,192 tokens | نموذج متطور مبني على Gemma-7B من Google متخصص في توليد الكود وإكماله. |
|
||||
| google/codegemma-1.1-7b | 8,192 tokens | نموذج برمجة متقدم لتوليد الكود وإكماله والاستدلال واتباع التعليمات. |
|
||||
| google/recurrentgemma-2b | 8,192 tokens | نموذج لغة بمعمارية تكرارية جديدة لاستدلال أسرع عند توليد تسلسلات طويلة. |
|
||||
| google/gemma-2-9b-it | 8,192 tokens | نموذج متطور لتوليد النص وفهمه وتحويله وتوليد الكود. |
|
||||
| google/gemma-2-27b-it | 8,192 tokens | نموذج متطور لتوليد النص وفهمه وتحويله وتوليد الكود. |
|
||||
| google/gemma-2-2b-it | 8,192 tokens | نموذج متطور لتوليد النص وفهمه وتحويله وتوليد الكود. |
|
||||
| google/deplot | 512 tokens | نموذج فهم لغة بصرية بلقطة واحدة يترجم صور الرسوم البيانية إلى جداول. |
|
||||
| google/paligemma | 8,192 tokens | نموذج لغة بصري بارع في استيعاب مدخلات النص والصور لإنتاج استجابات غنية بالمعلومات. |
|
||||
| mistralai/mistral-7b-instruct-v0.2 | 32k tokens | نموذج LLM يتبع التعليمات ويكمل الطلبات ويولد نصًا إبداعيًا. |
|
||||
| mistralai/mixtral-8x7b-instruct-v0.1 | 8,192 tokens | نموذج LLM بمعمارية MOE يتبع التعليمات ويكمل الطلبات ويولد نصًا إبداعيًا. |
|
||||
| mistralai/mistral-large | 4,096 tokens | ينشئ بيانات اصطناعية متنوعة تحاكي خصائص بيانات العالم الحقيقي. |
|
||||
| mistralai/mixtral-8x22b-instruct-v0.1 | 8,192 tokens | ينشئ بيانات اصطناعية متنوعة تحاكي خصائص بيانات العالم الحقيقي. |
|
||||
| mistralai/mistral-7b-instruct-v0.3 | 32k tokens | نموذج LLM يتبع التعليمات ويكمل الطلبات ويولد نصًا إبداعيًا. |
|
||||
| nv-mistralai/mistral-nemo-12b-instruct | 128k tokens | أكثر نموذج لغة تقدمًا للاستدلال والبرمجة والمهام متعددة اللغات؛ يعمل على وحدة GPU واحدة. |
|
||||
| mistralai/mamba-codestral-7b-v0.1 | 256k tokens | نموذج للكتابة والتفاعل مع الكود عبر مجموعة واسعة من لغات البرمجة والمهام. |
|
||||
| microsoft/phi-3-mini-128k-instruct | 128K tokens | نموذج LLM مفتوح خفيف ومتطور مع مهارات قوية في الرياضيات والاستدلال المنطقي. |
|
||||
| microsoft/phi-3-mini-4k-instruct | 4,096 tokens | نموذج LLM مفتوح خفيف ومتطور مع مهارات قوية في الرياضيات والاستدلال المنطقي. |
|
||||
| microsoft/phi-3-small-8k-instruct | 8,192 tokens | نموذج LLM مفتوح خفيف ومتطور مع مهارات قوية في الرياضيات والاستدلال المنطقي. |
|
||||
| microsoft/phi-3-small-128k-instruct | 128K tokens | نموذج LLM مفتوح خفيف ومتطور مع مهارات قوية في الرياضيات والاستدلال المنطقي. |
|
||||
| microsoft/phi-3-medium-4k-instruct | 4,096 tokens | نموذج LLM مفتوح خفيف ومتطور مع مهارات قوية في الرياضيات والاستدلال المنطقي. |
|
||||
| microsoft/phi-3-medium-128k-instruct | 128K tokens | نموذج LLM مفتوح خفيف ومتطور مع مهارات قوية في الرياضيات والاستدلال المنطقي. |
|
||||
| microsoft/phi-3.5-mini-instruct | 128K tokens | نموذج LLM خفيف متعدد اللغات يدعم تطبيقات الذكاء الاصطناعي في البيئات المحدودة بالكمون والذاكرة والحوسبة |
|
||||
| microsoft/phi-3.5-moe-instruct | 128K tokens | نموذج LLM متقدم يعتمد على معمارية خليط الخبراء لتوليد محتوى فعال حوسبيًا |
|
||||
| microsoft/kosmos-2 | 1,024 tokens | نموذج متعدد الوسائط رائد مصمم لفهم العناصر المرئية في الصور والاستدلال عليها. |
|
||||
| microsoft/phi-3-vision-128k-instruct | 128k tokens | نموذج متعدد الوسائط مفتوح متطور يتفوق في الاستدلال عالي الجودة من الصور. |
|
||||
| microsoft/phi-3.5-vision-instruct | 128k tokens | نموذج متعدد الوسائط مفتوح متطور يتفوق في الاستدلال عالي الجودة من الصور. |
|
||||
| databricks/dbrx-instruct | 12k tokens | نموذج LLM للأغراض العامة بأداء متطور في فهم اللغة والبرمجة وRAG. |
|
||||
| snowflake/arctic | 1,024 tokens | يقدم استدلالًا عالي الكفاءة لتطبيقات المؤسسات مع التركيز على توليد SQL والبرمجة. |
|
||||
| aisingapore/sea-lion-7b-instruct | 4,096 tokens | نموذج LLM لتمثيل وخدمة التنوع اللغوي والثقافي لجنوب شرق آسيا |
|
||||
| ibm/granite-8b-code-instruct | 4,096 tokens | نموذج LLM لبرمجة البرمجيات لتوليد الكود وإكماله وشرحه والتحويل متعدد الأدوار. |
|
||||
| ibm/granite-34b-code-instruct | 8,192 tokens | نموذج LLM لبرمجة البرمجيات لتوليد الكود وإكماله وشرحه والتحويل متعدد الأدوار. |
|
||||
| ibm/granite-3.0-8b-instruct | 4,096 tokens | نموذج لغة صغير متقدم يدعم RAG والتلخيص والتصنيف والكود والذكاء الاصطناعي الوكيلي |
|
||||
| ibm/granite-3.0-3b-a800m-instruct | 4,096 tokens | نموذج خليط خبراء عالي الكفاءة لـ RAG والتلخيص واستخراج الكيانات والتصنيف |
|
||||
| mediatek/breeze-7b-instruct | 4,096 tokens | ينشئ بيانات اصطناعية متنوعة تحاكي خصائص بيانات العالم الحقيقي. |
|
||||
| upstage/solar-10.7b-instruct | 4,096 tokens | يتفوق في مهام NLP، خاصة في اتباع التعليمات والاستدلال والرياضيات. |
|
||||
| writer/palmyra-med-70b-32k | 32k tokens | نموذج LLM رائد للاستجابات الدقيقة والمناسبة للسياق في المجال الطبي. |
|
||||
| writer/palmyra-med-70b | 32k tokens | نموذج LLM رائد للاستجابات الدقيقة والمناسبة للسياق في المجال الطبي. |
|
||||
| writer/palmyra-fin-70b-32k | 32k tokens | نموذج LLM متخصص في التحليل المالي وإعداد التقارير ومعالجة البيانات |
|
||||
| 01-ai/yi-large | 32k tokens | نموذج قوي مدرب على الإنجليزية والصينية لمهام متنوعة بما في ذلك روبوتات المحادثة والكتابة الإبداعية. |
|
||||
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k tokens | نموذج برمجة قوي يقدم قدرات متقدمة في توليد الكود وإكماله وملء الفراغات |
|
||||
| rakuten/rakutenai-7b-instruct | 1,024 tokens | نموذج LLM متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| rakuten/rakutenai-7b-chat | 1,024 tokens | نموذج LLM متطور مع فهم اللغة واستدلال فائق وتوليد النص. |
|
||||
| baichuan-inc/baichuan2-13b-chat | 4,096 tokens | يدعم المحادثة بالصينية والإنجليزية والبرمجة والرياضيات واتباع التعليمات وحل الألغاز |
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
@@ -943,15 +770,12 @@ mode: "wide"
|
||||
مثال الاستخدام في مشروع CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="groq/llama-3.2-90b-text-preview",
|
||||
model="groq/qwen/qwen3.6-27b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|-------------------|------------------|--------------------------------------------|
|
||||
| Llama 3.1 70B/8B | 131,072 tokens | مهام عالية الأداء بسياق كبير |
|
||||
| Llama 3.2 Series | 8,192 tokens | مهام ذات أغراض عامة |
|
||||
| Mixtral 8x7B | 32,768 tokens | أداء متوازن وسياق جيد |
|
||||
|
||||
تميز Groq بين نماذج production وpreview وتسحب معرّفات النماذج بانتظام. تحقق من [كتالوج نماذج Groq](https://console.groq.com/docs/models) و[صفحة الإيقاف](https://console.groq.com/docs/deprecations) قبل اختيار نموذج للإنتاج.
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
@@ -1033,11 +857,12 @@ mode: "wide"
|
||||
مثال الاستخدام في مشروع CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="llama-3.1-sonar-large-128k-online",
|
||||
base_url="https://api.perplexity.ai/"
|
||||
model="perplexity/sonar-pro"
|
||||
)
|
||||
```
|
||||
|
||||
راجع [كتالوج نماذج Perplexity](https://docs.perplexity.ai/getting-started/models) و[changelog](https://docs.perplexity.ai/docs/resources/changelog) للحصول على معرّفات النماذج الحالية وإشعارات الإيقاف.
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -1073,17 +898,12 @@ mode: "wide"
|
||||
مثال الاستخدام في مشروع CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sambanova/Meta-Llama-3.1-8B-Instruct",
|
||||
model="sambanova/Meta-Llama-3.3-70B-Instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| النموذج | نافذة السياق | الأفضل لـ |
|
||||
|--------------------|------------------------|----------------------------------------------|
|
||||
| Llama 3.1 70B/8B | حتى 131,072 tokens | مهام عالية الأداء بسياق كبير |
|
||||
| Llama 3.1 405B | 8,192 tokens | أداء عالٍ وجودة مخرجات |
|
||||
| Llama 3.2 Series | 8,192 tokens | مهام عامة ومتعددة الوسائط |
|
||||
| Llama 3.3 70B | حتى 131,072 tokens | أداء عالٍ وجودة مخرجات |
|
||||
| Qwen2 familly | 8,192 tokens | أداء عالٍ وجودة مخرجات |
|
||||
|
||||
قد تتغير النماذج المستضافة في SambaNova Cloud بصورة مستقلة عن CrewAI. استعلم من [models endpoint](https://docs.sambanova.ai/docs/api-reference/models/get-environments-available-model-list-metadata) وراجع [دليل الإيقاف](https://docs.sambanova.ai/docs/en/models/deprecations) قبل النشر.
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
@@ -1101,7 +921,7 @@ mode: "wide"
|
||||
مثال الاستخدام في مشروع CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="cerebras/llama3.1-70b",
|
||||
model="cerebras/gpt-oss-120b",
|
||||
temperature=0.7,
|
||||
max_tokens=8192
|
||||
)
|
||||
@@ -1115,6 +935,8 @@ mode: "wide"
|
||||
- دعم نوافذ سياق طويلة
|
||||
</Info>
|
||||
|
||||
راجع [كتالوج نماذج Cerebras](https://inference-docs.cerebras.ai/models/overview) و[إشعارات الإيقاف](https://inference-docs.cerebras.ai/support/deprecation) للحصول على معرّفات endpoints العامة الحالية.
|
||||
|
||||
**ملاحظة:** يستخدم هذا المزود LiteLLM. أضفه كتبعية لمشروعك:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -1189,7 +1011,7 @@ mode: "wide"
|
||||
|
||||
# Create an LLM with streaming enabled
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
stream=True # Enable streaming
|
||||
)
|
||||
```
|
||||
@@ -1239,7 +1061,7 @@ mode: "wide"
|
||||
|
||||
my_listener = MyCustomListener()
|
||||
|
||||
llm = LLM(model="gpt-4o-mini", temperature=0, stream=True)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", stream=True)
|
||||
|
||||
researcher = Agent(
|
||||
role="About User",
|
||||
@@ -1319,6 +1141,8 @@ mode: "wide"
|
||||
|
||||
يدعم CrewAI الاستجابات المهيكلة من استدعاءات LLM من خلال السماح لك بتحديد `response_format` باستخدام نموذج Pydantic. يمكّن هذا الإطار من تحليل المخرجات والتحقق منها تلقائيًا، مما يسهّل دمج الاستجابة في تطبيقك دون معالجة لاحقة يدوية.
|
||||
|
||||
يختلف دعم المخرجات المهيكلة باختلاف المزوّد والنموذج. اختبر النموذج الذي اخترته قبل الاعتماد على الاستجابات المهيكلة في بيئة الإنتاج.
|
||||
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
@@ -1328,7 +1152,7 @@ class Dog(BaseModel):
|
||||
breed: str
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o", response_format=Dog)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", response_format=Dog)
|
||||
|
||||
response = llm.call(
|
||||
"Analyze the following messages and return the name, age, and breed. "
|
||||
@@ -1357,8 +1181,8 @@ print(response)
|
||||
# 3. Task splitting for large contexts
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
max_tokens=4000, # Limit response length
|
||||
model="openai/gpt-5.6-terra",
|
||||
max_completion_tokens=4000, # Limit response length
|
||||
)
|
||||
```
|
||||
|
||||
@@ -1382,15 +1206,14 @@ print(response)
|
||||
```python
|
||||
# Configure model with appropriate settings
|
||||
llm = LLM(
|
||||
model="openai/gpt-4-turbo-preview",
|
||||
temperature=0.7, # Adjust based on task
|
||||
max_tokens=4096, # Set based on output needs
|
||||
timeout=300 # Longer timeout for complex tasks
|
||||
model="openai/gpt-5.6-terra",
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4096,
|
||||
timeout=300
|
||||
)
|
||||
```
|
||||
<Tip>
|
||||
- درجة حرارة منخفضة (0.1 إلى 0.3) للاستجابات الواقعية
|
||||
- درجة حرارة عالية (0.7 إلى 0.9) للمهام الإبداعية
|
||||
استخدم عناصر التحكم التي يدعمها النموذج المحدد. حسب المزود، قد تكون `temperature` أو مستوى reasoning أو thinking، أو تعليمات prompt تحدد الأسلوب والتباين المطلوبين.
|
||||
</Tip>
|
||||
</Step>
|
||||
|
||||
|
||||
@@ -24,15 +24,23 @@ mode: "wide"
|
||||
|
||||
## البداية السريعة
|
||||
|
||||
### 1. إنشاء مجلد المهارة
|
||||
### 1. إنشاء مهارة باستخدام سطر الأوامر (CLI)
|
||||
|
||||
واجهة سطر الأوامر هي الطريقة المدعومة لإنشاء مهارة — فهي تُنشئ لك هيكل المجلد وملف `SKILL.md` صالحًا:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create code-review
|
||||
```
|
||||
|
||||
داخل مشروع طاقم (حيث يوجد `pyproject.toml`) يُنشئ هذا الأمر `./skills/code-review/`؛ وخارج المشروع يُنشئ `./code-review/` في المجلد الحالي (يمكنك فرض هذا السلوك باستخدام `--no-project`):
|
||||
|
||||
```
|
||||
skills/
|
||||
└── code-review/
|
||||
├── SKILL.md # مطلوب — التعليمات
|
||||
├── references/ # اختياري — مستندات مرجعية
|
||||
│ └── style-guide.md
|
||||
└── scripts/ # اختياري — سكربتات قابلة للتنفيذ
|
||||
├── SKILL.md # Required — instructions (pre-filled template)
|
||||
├── references/ # Optional — reference docs
|
||||
├── scripts/ # Optional — executable scripts
|
||||
└── assets/ # Optional — static files
|
||||
```
|
||||
|
||||
### 2. كتابة SKILL.md الخاص بك
|
||||
@@ -164,6 +172,65 @@ agent = Agent(
|
||||
|
||||
---
|
||||
|
||||
## إنشاء المهارات ونشرها وتثبيتها
|
||||
|
||||
للمهارات دورة حياة كاملة تُدار عبر واجهة سطر الأوامر: **أنشئها باستخدام `crewai skill create`، وانشرها باستخدام `crewai skill publish`** — إنشاء المجلدات يدويًا يصلح للتجارب المحلية، لكن واجهة سطر الأوامر هي سير العمل المقصود، وهي تحافظ على صحة هيكل المهارة وبياناتها الوصفية.
|
||||
|
||||
### الإنشاء
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create my-skill
|
||||
```
|
||||
|
||||
يُنشئ هذا الأمر المجلد (داخل `./skills/` في مشروع الطاقم) مع قالب `SKILL.md`، بالإضافة إلى مجلدات فارغة `scripts/` و `references/` و `assets/`. عدّل `SKILL.md` لتعريف التعليمات.
|
||||
|
||||
### النشر
|
||||
|
||||
نفّذ الأمر من داخل مجلد المهارة (حيث يوجد `SKILL.md`):
|
||||
|
||||
```shell Terminal
|
||||
cd skills/my-skill
|
||||
crewai skill publish
|
||||
```
|
||||
|
||||
يقرأ النشر الحقول `name` و `description` و `metadata.version` من البيانات الوصفية في مقدمة `SKILL.md` ويدفع المهارة إلى سجل CrewAI. **المهارات المنشورة تكون دائمًا مقيّدة بنطاق مؤسستك** — مثل الأدوات، لا يستطيع رؤيتها وتثبيتها إلا أعضاء المؤسسة الناشرة؛ ولا توجد رؤية عامة. أعلام مفيدة:
|
||||
|
||||
| العلم | التأثير |
|
||||
| :--- | :--- |
|
||||
| `--org <slug>` | النشر تحت مؤسسة محددة (يتجاوز الإعدادات). |
|
||||
| `--force` | تخطي التحقق من حالة git (تغييرات غير مُثبتة، إلخ). |
|
||||
|
||||
### التثبيت
|
||||
|
||||
ثبّت مهارة منشورة عبر مرجعها `@org/name`:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill install @acme/code-review
|
||||
```
|
||||
|
||||
داخل مشروع الطاقم تُثبَّت المهارة في `./skills/{name}/`؛ وخارج المشروع تذهب إلى ذاكرة التخزين المؤقتة المشتركة في `~/.crewai/skills/{org}/{name}/`.
|
||||
|
||||
يمكن للوكلاء أيضًا الإشارة إلى مهارات السجل مباشرة — يتم حلّها من ذاكرة التخزين المؤقتة المحلية (أو من مجلد `skills/` في المشروع) وقت التشغيل:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Senior Code Reviewer",
|
||||
goal="Review pull requests for quality and security issues",
|
||||
backstory="Staff engineer with expertise in secure coding practices.",
|
||||
skills=["@acme/code-review"], # registry ref, resolved locally
|
||||
)
|
||||
```
|
||||
|
||||
### عرض القائمة
|
||||
|
||||
```shell Terminal
|
||||
crewai skill list
|
||||
```
|
||||
|
||||
يعرض المهارات المثبّتة من مجلد المشروع `./skills/` ومن ذاكرة التخزين المؤقتة العامة معًا، مع إصداراتها ومساراتها.
|
||||
|
||||
---
|
||||
|
||||
## المهارات على مستوى الطاقم
|
||||
|
||||
يمكن تعيين المهارات على الطاقم لتُطبّق على **جميع الوكلاء**:
|
||||
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
- [نظرة عامة](/ar/enterprise/features/agent-control-plane/overview)
|
||||
- **المراقبة** *(أنت هنا)*
|
||||
- [القواعد](/ar/enterprise/features/agent-control-plane/rules)
|
||||
- [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## نظرة عامة
|
||||
@@ -58,7 +58,7 @@ mode: "wide"
|
||||
| **Last execution** | الوقت المنقضي منذ آخر تنفيذ. |
|
||||
| **Health Status Breakdown** | شريط مكدّس بنسب `Critical` / `Warning` / `Healthy` لعمليات التنفيذ في النافذة. |
|
||||
| **Executions with Errors** | إجمالي عمليات التنفيذ الفاشلة في النافذة. |
|
||||
| **PII detection applied** | `Yes` إذا كان هناك تكوين PII لكل deployment أو [قاعدة PII](/ar/enterprise/features/agent-control-plane/rules) مطابِقة نشطة. |
|
||||
| **PII detection applied** | `Yes` إذا كان هناك تكوين PII لكل deployment أو [سياسة PII](/edge/ar/enterprise/features/agent-control-plane/policies) مطابِقة نشطة. |
|
||||
| **Executions** | إجمالي عمليات التنفيذ في النافذة. |
|
||||
| **Last updated** | متى أُعيد نشر الـ deployment آخر مرة. |
|
||||
| **Crew Version** | إصدار `crewai` الذي يُبلِّغ عنه الـ deployment. يشير أيقونة المعلومات بجانب الإصدارات الأقل من `1.13` إلى صفوف لا يمكنها المساهمة بالمقاييس. |
|
||||
@@ -96,8 +96,8 @@ mode: "wide"
|
||||
<Card title="Agent Control Plane — نظرة عامة" icon="book-open" href="/ar/enterprise/features/agent-control-plane/overview">
|
||||
ما هو ACP، المتطلبات، مستويات الخطط، و RBAC.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — القواعد" icon="shield-check" href="/ar/enterprise/features/agent-control-plane/rules">
|
||||
طبّق قواعد PII Redaction على مستوى المؤسسة عبر العديد من الأتمتات.
|
||||
<Card title="Agent Control Plane — السياسات" icon="shield-check" href="/edge/ar/enterprise/features/agent-control-plane/policies">
|
||||
طبّق سياسات PII Redaction على مستوى المؤسسة عبر العديد من الأتمتات.
|
||||
</Card>
|
||||
<Card title="Traces" icon="timeline" href="/ar/enterprise/features/traces">
|
||||
تعمّق في تنفيذ واحد لرؤية تفكير الوكيل واستدعاءات الأدوات واستخدام الرموز.
|
||||
|
||||
@@ -10,17 +10,17 @@ icon: "book-open"
|
||||
|
||||
- **نظرة عامة** *(أنت هنا)*
|
||||
- [المراقبة](/ar/enterprise/features/agent-control-plane/monitoring)
|
||||
- [القواعد](/ar/enterprise/features/agent-control-plane/rules)
|
||||
- [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
**Agent Control Plane** (ACP) هو مركز العمليات لكل ما يعمل لديك على CrewAI AMP. إنها شاشة واحدة — مقسّمة إلى تبويبَي **Automations** و **Rules** — تمنح فريقك القدرة على:
|
||||
**Agent Control Plane** (ACP) هو مركز العمليات لكل ما يعمل لديك على CrewAI AMP. إنها شاشة واحدة — مقسّمة إلى تبويبَي **Automations** و **Policies** — تمنح فريقك القدرة على:
|
||||
|
||||
- مراقبة **حالة (الصحة)** كل أتمتة حيّة (crew أو flow) بتفصيل `Critical` / `Warning` / `Healthy` وعدد عمليات التنفيذ.
|
||||
- تتبع **استهلاك LLM** — الرموز (tokens) والتكلفة — لكل أتمتة ولكل مزود ولكل نموذج، مع الفرق مقابل الفترة السابقة.
|
||||
- التعمّق في أي أتمتة منفردة أو مزود نماذج لرؤية المخططات الزمنية وتفصيل البيانات لكل مزود.
|
||||
- تطبيق **قواعد (Rules)** على مستوى المؤسسة (اليوم: PII Redaction) عبر العديد من الأتمتات دفعة واحدة بدلاً من تعديل كل deployment على حدة.
|
||||
- تطبيق **سياسات (Policies)** على مستوى المؤسسة (اليوم: PII Redaction) عبر العديد من الأتمتات دفعة واحدة بدلاً من تعديل كل deployment على حدة.
|
||||
|
||||
<Frame>
|
||||

|
||||
@@ -33,7 +33,7 @@ icon: "book-open"
|
||||
يجيب التبويبان عن سؤالَين مختلفَين:
|
||||
|
||||
- **Automations** — *"كيف يتصرف أسطولي الآن، وكم يكلّفني؟"* راجع [المراقبة](/ar/enterprise/features/agent-control-plane/monitoring).
|
||||
- **Rules** — *"كيف أفرض سياسة (مثل PII redaction) عبر العديد من عمليات النشر دون إعادة نشر كل واحدة؟"* راجع [القواعد](/ar/enterprise/features/agent-control-plane/rules).
|
||||
- **Policies** — *"كيف أفرض سياسة (مثل PII redaction) عبر العديد من عمليات النشر دون إعادة نشر كل واحدة؟"* راجع [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies).
|
||||
|
||||
## المتطلبات
|
||||
|
||||
@@ -42,11 +42,11 @@ icon: "book-open"
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
يُشترط **خطة Enterprise أو Ultra** لإنشاء أو تعديل [القواعد](/ar/enterprise/features/agent-control-plane/rules). يمكن للمؤسسات على الخطط الأدنى فتح تبويب Rules وعرض القواعد الموجودة، ولكن يُعرض المحرر للقراءة فقط مع شارة قفل "Enterprise" والتنبيه *"PII Redaction rules require an Enterprise plan."*. المراقبة (تبويب Automations) متاحة في جميع الخطط حيث يكون هذا الميزة مفعّلة.
|
||||
يُشترط **خطة Enterprise أو Ultra** لإنشاء أو تعديل [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies). يمكن للمؤسسات على الخطط الأدنى فتح تبويب Policies وعرض السياسات الموجودة، ولكن يُعرض المحرر للقراءة فقط مع شارة قفل "Enterprise" والتنبيه *"PII Redaction policies require an Enterprise plan."*. المراقبة (تبويب Automations) متاحة في جميع الخطط حيث يكون هذا الميزة مفعّلة.
|
||||
</Warning>
|
||||
|
||||
- يجب أن تكون ميزة **Agent Control Plane** مفعّلة لمؤسستك. إن لم ترها في الشريط الجانبي، اطلب من مالك الحساب تفعيلها.
|
||||
- داخل ACP، يحكم [RBAC](/ar/enterprise/features/rbac) الوصول: `read` للعرض في لوحة المعلومات والقواعد، و`manage` لإنشاء وتعديل وتشغيل/إيقاف وحذف القواعد.
|
||||
- داخل ACP، يحكم [RBAC](/ar/enterprise/features/rbac) الوصول: `read` للعرض في لوحة المعلومات والسياسات، و`manage` لإنشاء وتعديل وتشغيل/إيقاف وحذف السياسات.
|
||||
- يمكن ضبط نطاق جميع المخططات والجداول إلى **آخر 24 ساعة** أو **الأسبوع الماضي** أو **آخر 30 يوماً** عبر مُحدّد الوقت في أعلى اليمين. تقارن قيم الفرق (`↑ 8 vs yesterday`, `↓ $20.57 vs yesterday` وغيرها) النافذة المختارة بالنافذة السابقة بنفس الطول.
|
||||
|
||||
## ما يمكنك فعله هنا
|
||||
@@ -55,7 +55,7 @@ icon: "book-open"
|
||||
<Card title="المراقبة" icon="gauge" href="/ar/enterprise/features/agent-control-plane/monitoring">
|
||||
راقب صحة الأسطول وإنفاق LLM عبر بطاقات المقاييس و sankey التفاعلي وجداول لكل أتمتة ولوحات جانبية للتعمق في أي أتمتة أو مزود.
|
||||
</Card>
|
||||
<Card title="القواعد" icon="shield-check" href="/ar/enterprise/features/agent-control-plane/rules">
|
||||
<Card title="السياسات" icon="shield-check" href="/edge/ar/enterprise/features/agent-control-plane/policies">
|
||||
طبّق سياسات PII Redaction على مستوى المؤسسة بنطاق محدد بالأدوات والوسوم. تسري التغييرات في التنفيذ التالي — دون الحاجة لإعادة نشر.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -67,10 +67,10 @@ icon: "book-open"
|
||||
تعمّق في تنفيذ واحد لرؤية تفكير الوكيل واستدعاءات الأدوات واستخدام الرموز.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/ar/enterprise/features/rbac">
|
||||
أدِر من يمكنه قراءة Agent Control Plane ومن يمكنه تعديل القواعد.
|
||||
أدِر من يمكنه قراءة Agent Control Plane ومن يمكنه تعديل السياسات.
|
||||
</Card>
|
||||
<Card title="PII Redaction للـ Traces" icon="lock" href="/ar/enterprise/features/pii-trace-redactions">
|
||||
كتالوج الكيانات وضبط PII لكل deployment التي تستند إليها القواعد.
|
||||
كتالوج الكيانات وضبط PII لكل deployment التي تستند إليها السياسات.
|
||||
</Card>
|
||||
<Card title="النشر إلى AMP" icon="rocket" href="/ar/enterprise/guides/deploy-to-amp">
|
||||
انشر crew على إصدار crewAI يدعم Agent Control Plane.
|
||||
@@ -78,5 +78,5 @@ icon: "book-open"
|
||||
</CardGroup>
|
||||
|
||||
<Card title="تحتاج مساعدة؟" icon="headset" href="mailto:support@crewai.com">
|
||||
تواصل مع فريق الدعم للمساعدة في تفسير المقاييس أو تصميم القواعد.
|
||||
تواصل مع فريق الدعم للمساعدة في تفسير المقاييس أو تصميم السياسات.
|
||||
</Card>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "إعداد القواعد"
|
||||
title: "إعداد السياسات"
|
||||
description: "طبّق سياسات على مستوى المؤسسة عبر العديد من الأتمتات من مكان واحد."
|
||||
sidebarTitle: "القواعد"
|
||||
sidebarTitle: "السياسات"
|
||||
icon: "shield-check"
|
||||
mode: "wide"
|
||||
---
|
||||
@@ -11,50 +11,50 @@ mode: "wide"
|
||||
|
||||
- [نظرة عامة](/ar/enterprise/features/agent-control-plane/overview)
|
||||
- [المراقبة](/ar/enterprise/features/agent-control-plane/monitoring)
|
||||
- **القواعد** *(أنت هنا)*
|
||||
- **السياسات** *(أنت هنا)*
|
||||
</Info>
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
تتيح لك القواعد تطبيق سياسات — اليوم: **PII Redaction** — عبر العديد من الأتمتات دفعة واحدة، بدلاً من ضبط كل deployment على حدة. افتح تبويب **Rules** في [Agent Control Plane](/ar/enterprise/features/agent-control-plane/overview) لإدارتها.
|
||||
تتيح لك السياسات تطبيق سياسات — اليوم: **PII Redaction** — عبر العديد من الأتمتات دفعة واحدة، بدلاً من ضبط كل deployment على حدة. افتح تبويب **Policies** في [Agent Control Plane](/ar/enterprise/features/agent-control-plane/overview) لإدارتها.
|
||||
|
||||
<Frame>
|
||||

|
||||

|
||||
</Frame>
|
||||
|
||||
تعرض كل بطاقة قاعدة الاسم والوصف و**النطاق (scope)** الذي تنطبق عليه القاعدة (الأدوات والوسوم المختارة) وعدد **الأتمتات المُفعَّلة** — عمليات النشر التي تطابق النطاق حالياً. يقوم المُفتاح على اليمين بتشغيل القاعدة أو إيقافها دون حذفها.
|
||||
تعرض كل بطاقة سياسة الاسم والوصف و**النطاق (scope)** الذي تنطبق عليه السياسة (الأدوات والوسوم المختارة) وعدد **الأتمتات المُفعَّلة** — عمليات النشر التي تطابق النطاق حالياً. يقوم المُفتاح على اليمين بتشغيل السياسة أو إيقافها دون حذفها.
|
||||
|
||||
## المتطلبات
|
||||
|
||||
<Warning>
|
||||
يُشترط **خطة Enterprise أو Ultra** لإنشاء أو تعديل قواعد PII Redaction. يمكن للمؤسسات على الخطط الأدنى فتح تبويب Rules وعرض القواعد الموجودة، ولكن يُعرض المحرر للقراءة فقط مع شارة قفل "Enterprise" والتنبيه *"PII Redaction rules require an Enterprise plan."* — تواصل مع مالك حسابك أو المبيعات للترقية.
|
||||
يُشترط **خطة Enterprise أو Ultra** لإنشاء أو تعديل سياسات PII Redaction. يمكن للمؤسسات على الخطط الأدنى فتح تبويب Policies وعرض السياسات الموجودة، ولكن يُعرض المحرر للقراءة فقط مع شارة قفل "Enterprise" والتنبيه *"PII Redaction policies require an Enterprise plan."* — تواصل مع مالك حسابك أو المبيعات للترقية.
|
||||
</Warning>
|
||||
|
||||
- يجب أن تكون ميزة **Agent Control Plane** مفعّلة لمؤسستك. راجع [نظرة عامة — المتطلبات](/ar/enterprise/features/agent-control-plane/overview#المتطلبات).
|
||||
- تحتاج إلى صلاحية `manage` ضمن [RBAC](/ar/enterprise/features/rbac) على Agent Control Plane لإنشاء وتعديل وتشغيل/إيقاف وحذف القواعد. صلاحية `read` كافية لعرضها.
|
||||
- تُسجَّل جميع تغييرات القواعد بإصدارات للتدقيق.
|
||||
- تحتاج إلى صلاحية `manage` ضمن [RBAC](/ar/enterprise/features/rbac) على Agent Control Plane لإنشاء وتعديل وتشغيل/إيقاف وحذف السياسات. صلاحية `read` كافية لعرضها.
|
||||
- تُسجَّل جميع تغييرات السياسات بإصدارات للتدقيق.
|
||||
|
||||
## أنواع القواعد المتاحة
|
||||
## أنواع السياسات المتاحة
|
||||
|
||||
| النوع | ما تفعله |
|
||||
|------|---------------|
|
||||
| **PII Redaction** | تطبّق PII redaction على عمليات التنفيذ لكل أتمتة مطابِقة، باستخدام نفس كتالوج الكيانات و recognizers المخصصة الموثَّقة في [PII Redaction للـ Traces](/ar/enterprise/features/pii-trace-redactions). |
|
||||
|
||||
سيتم إضافة أنواع قواعد أخرى مع الوقت.
|
||||
سيتم إضافة أنواع سياسات أخرى مع الوقت.
|
||||
|
||||
## إنشاء قاعدة
|
||||
## إنشاء سياسة
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/acp-rules-edit-side-panel.png" alt="لوحة تعديل قاعدة جانبية بالشروط ونوع قناع PII" width="450" />
|
||||
<img src="/images/enterprise/acp-policies-new-side-panel.png" alt="لوحة تعديل سياسة جانبية بالشروط ونوع قناع PII" width="450" />
|
||||
</Frame>
|
||||
|
||||
<Steps>
|
||||
<Step title="افتح المحرر">
|
||||
انقر على **+ Create new** في أعلى يمين تبويب Rules، أو على **View Details** في بطاقة قاعدة موجودة.
|
||||
انقر على **+ Create new** في أعلى يمين تبويب Policies، أو على **View Details** في بطاقة سياسة موجودة.
|
||||
</Step>
|
||||
|
||||
<Step title="سَمِّ القاعدة وصِفها">
|
||||
أعطِ القاعدة اسماً واضحاً (مثل *Mask PII (CC)*) ووصفاً يشرح متى تنطبق. يظهر كلاهما على بطاقة القاعدة وفي مودال Engaged Automations.
|
||||
<Step title="سَمِّ السياسة وصِفها">
|
||||
أعطِ السياسة اسماً واضحاً (مثل *Mask PII (CC)*) ووصفاً يشرح متى تنطبق. يظهر كلاهما على بطاقة السياسة وفي مودال Engaged Automations.
|
||||
</Step>
|
||||
|
||||
<Step title="اختر النوع">
|
||||
@@ -62,12 +62,12 @@ mode: "wide"
|
||||
</Step>
|
||||
|
||||
<Step title="حدّد الشروط">
|
||||
تحدد الشروط الأتمتات التي تنخرط معها القاعدة. كلاهما اختياري ويستخدم دلالات **مساواة المجموعات (set-equality)**:
|
||||
تحدد الشروط الأتمتات التي تنخرط معها السياسة. كلاهما اختياري ويستخدم دلالات **مساواة المجموعات (set-equality)**:
|
||||
|
||||
- **Tools** — تنخرط فقط الأتمتات التي تتطابق مجموعة أدواتها **تطابقاً تامّاً** مع الأدوات المختارة. اختر من تطبيقات Studio و MCPs والأدوات مفتوحة المصدر وأدوات سجل Tool Repository.
|
||||
- **Automations** — تنخرط فقط الأتمتات التي تتطابق مجموعة وسومها **تطابقاً تامّاً** مع الوسوم المختارة.
|
||||
|
||||
ترك مُحدِّد فارغ يعني "بدون تصفية على هذا البعد". ترك كليهما فارغَين يعني أن القاعدة تنطبق على **كل** أتمتة في المؤسسة.
|
||||
ترك مُحدِّد فارغ يعني "بدون تصفية على هذا البعد". ترك كليهما فارغَين يعني أن السياسة تنطبق على **كل** أتمتة في المؤسسة.
|
||||
</Step>
|
||||
|
||||
<Step title="اضبط جدول PII Mask Type">
|
||||
@@ -75,30 +75,30 @@ mode: "wide"
|
||||
</Step>
|
||||
|
||||
<Step title="احفظ">
|
||||
تنطبق القاعدة على عمليات التنفيذ **المستقبلية** لكل أتمتة مُفعَّلة بمجرد الحفظ. لا حاجة لإعادة النشر.
|
||||
تنطبق السياسة على عمليات التنفيذ **المستقبلية** لكل أتمتة مُفعَّلة بمجرد الحفظ. لا حاجة لإعادة النشر.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## الأتمتات المُفعَّلة
|
||||
|
||||
انقر على **Engaged N automations** في أي بطاقة قاعدة لرؤية أي عمليات النشر تطابقها القاعدة حالياً بالضبط، إلى جانب آخر تنفيذ لكل منها.
|
||||
انقر على **Engaged N automations** في أي بطاقة سياسة لرؤية أي عمليات النشر تطابقها السياسة حالياً بالضبط، إلى جانب آخر تنفيذ لكل منها.
|
||||
|
||||
<Frame>
|
||||

|
||||

|
||||
</Frame>
|
||||
|
||||
هذه هي أسرع طريقة للتحقق من نطاق قاعدة قبل تمكينها — على سبيل المثال، للتأكد من أن قاعدة محدَّدة بنطاق وسم `production` لا تطابق عن طريق الخطأ deployment تجريبي.
|
||||
هذه هي أسرع طريقة للتحقق من نطاق سياسة قبل تمكينها — على سبيل المثال، للتأكد من أن سياسة محدَّدة بنطاق وسم `production` لا تطابق عن طريق الخطأ deployment تجريبي.
|
||||
|
||||
## قواعد على مستوى المؤسسة مقابل إعدادات لكل deployment
|
||||
## سياسات على مستوى المؤسسة مقابل إعدادات لكل deployment
|
||||
|
||||
يمكن ضبط PII Redaction في مكانين:
|
||||
|
||||
- **لكل deployment** — ضمن **Settings → PII Protection** على كل deployment على حدة ([الدليل](/ar/enterprise/features/pii-trace-redactions))
|
||||
- **على مستوى المؤسسة** — كقاعدة في هذه الصفحة
|
||||
- **على مستوى المؤسسة** — كسياسة في هذه الصفحة
|
||||
|
||||
عندما يتطابق نطاق قاعدة مُفعَّلة على مستوى المؤسسة مع deployment، يُجاوز تكوين الكيانات الخاص بالقاعدة **إعدادات PII المملوكة من قبل الـ deployment** لعمليات تنفيذ ذلك الـ deployment — تصبح القاعدة المصدر الوحيد للحقيقة طالما هي مرتبطة. عطّل القاعدة أو فُكَّ ارتباطها (أو غيِّر نطاقها بحيث لا تتطابق بعد الآن) ويعود الـ deployment إلى إعدادات PII Protection الخاصة به.
|
||||
عندما يتطابق نطاق سياسة مُفعَّلة على مستوى المؤسسة مع deployment، يُجاوز تكوين الكيانات الخاص بالسياسة **إعدادات PII المملوكة من قبل الـ deployment** لعمليات تنفيذ ذلك الـ deployment — تصبح السياسة المصدر الوحيد للحقيقة طالما هي مرتبطة. عطّل السياسة أو فُكَّ ارتباطها (أو غيِّر نطاقها بحيث لا تتطابق بعد الآن) ويعود الـ deployment إلى إعدادات PII Protection الخاصة به.
|
||||
|
||||
فضّل القواعد على مستوى المؤسسة عندما تريد فرض سياسة متسقة عبر العديد من عمليات النشر؛ احتفظ بالضبط لكل deployment للاستثناءات الفردية.
|
||||
فضّل السياسات على مستوى المؤسسة عندما تريد فرض سياسة متسقة عبر العديد من عمليات النشر؛ احتفظ بالضبط لكل deployment للاستثناءات الفردية.
|
||||
|
||||
## ذو صلة
|
||||
|
||||
@@ -113,10 +113,10 @@ mode: "wide"
|
||||
كتالوج الكيانات، recognizers المخصصة، والضبط لكل deployment.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/ar/enterprise/features/rbac">
|
||||
أدِر من يمكنه إنشاء أو تعديل القواعد.
|
||||
أدِر من يمكنه إنشاء أو تعديل السياسات.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="تحتاج مساعدة؟" icon="headset" href="mailto:support@crewai.com">
|
||||
تواصل مع فريق الدعم للمساعدة في تصميم قواعد لمؤسستك.
|
||||
تواصل مع فريق الدعم للمساعدة في تصميم سياسات لمؤسستك.
|
||||
</Card>
|
||||
123
docs/edge/ar/enterprise/features/studio-flows.mdx
Normal file
@@ -0,0 +1,123 @@
|
||||
---
|
||||
title: التدفقات في الاستوديو
|
||||
description: "أنشئ سير عمل يعتمد على الأحداث يجمع بين التحكم الحتمي خطوة بخطوة والذكاء الوكيلي — دون كتابة أي كود."
|
||||
icon: "diagram-project"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**الطرح جارٍ حاليًا**: يجري طرح التدفقات في الاستوديو تدريجيًا خلال أسبوع 20 يوليو 2026. إذا لم يظهر لك خيار Flows في الاستوديو بعد، فهذا يعني أن الميزة لم تصل إلى مؤسستك بعد — عاود التحقق قريبًا.
|
||||
</Info>
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يدعم الاستوديو الآن إنشاء **التدفقات (Flows)** إلى جانب فرق Crew. التدفقات هي سير عمل يعتمد على الأحداث تتحكم فيه بدقة في الخطوات التي تُنفَّذ وترتيبها وشروط تنفيذها — بينما تُفوِّض العمل الذكي داخل كل خطوة إلى وكلاء الذكاء الاصطناعي.
|
||||
|
||||
لإنشاء تدفق، افتح الاستوديو وصف الأتمتة التي تريدها، ثم اختر **Flows** من المحدد بجوار مربع الإدخال.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## لماذا التدفقات؟
|
||||
|
||||
فرق Crew ممتازة عندما تريد أن يتعاون فريق من الوكلاء بشكل مستقل نحو هدف. لكن كثيرًا من الأتمتة الواقعية يحتاج إلى قدر أكبر من القابلية للتنبؤ: اجلب هذه البيانات أولًا، ثم لخصها، ثم انشر النتيجة — في كل مرة وبنفس الترتيب.
|
||||
|
||||
تمنحك التدفقات الأمرين معًا:
|
||||
|
||||
- **الحتمية حيث تهم**: تُنفَّذ الخطوات وفق تسلسل محدد وتفرعات صريحة، فتكون عمليات التشغيل قابلة للتنبؤ والتكرار وسهلة التصحيح.
|
||||
- **الذكاء حيث تحتاجه**: كل خطوة يشغّلها وكيل (أو فريق Crew كامل)، لذا يستفيد العمل داخل الخطوة — التلخيص والتقييم والصياغة واتخاذ القرار — من قدرات الاستدلال الكاملة للنموذج اللغوي.
|
||||
|
||||
هذا المزيج هو ما يجعل التدفقات مناسبة للأتمتة في بيئات الإنتاج: البنية مضمونة، والاستقلالية محصورة في الخطوات التي تحتاجها.
|
||||
|
||||
## إنشاء تدفق
|
||||
|
||||
صف ما تريده بلغة طبيعية وسيصمم مساعد الاستوديو (Studio Assistant) التدفق لك — بإنشاء الخطوات وربطها ببعضها وتهيئة الوكلاء وتكاملات التطبيقات التي تحتاجها كل خطوة. تعرض اللوحة (Canvas) على اليمين سير العمل الناتج كعُقد متصلة، ويمكنك مواصلة التحسين عبر المحادثة أو تعديل أي عقدة مباشرة.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
عندما تكون جاهزًا، استخدم **Run** لاختبار التدفق من البداية إلى النهاية، وافحص النتائج في تبويبي **Output** و**Traces**، ثم نفّذ **Deploy** عندما يستقر. يمكنك أيضًا مشاركة المشروع عبر **Share** أو تنزيل الكود المصدري عبر **Download**.
|
||||
|
||||
## أنواع العُقد
|
||||
|
||||
تتكون التدفقات من ثلاثة أنواع أساسية من العُقد. كل عقدة هي خطوة في سير العمل، ويمكنك المزج بينها بحرية.
|
||||
|
||||
### الوكيل المنفرد (Single Agent)
|
||||
|
||||
تُشغِّل عقدة Single Agent وكيلًا واحدًا لمهمة واحدة مركزة — وهي مثالية للخطوات محددة النطاق مثل جلب البيانات من تكامل، أو تحويل المحتوى، أو نشر رسالة.
|
||||
|
||||
عند النقر على عقدة الوكيل تُفتح تهيئتها الكاملة:
|
||||
|
||||
- **Task**: ما ينبغي أن تنجزه هذه الخطوة والمخرجات التي يجب أن تنتجها
|
||||
- **Profile**: دور الوكيل وهدفه وخلفيته
|
||||
- **Model**: النموذج اللغوي الذي يشغّل الوكيل
|
||||
- **Apps**: التكاملات التي يمكن للوكيل استخدامها (مثل Linear وSlack وHubSpot)
|
||||
- **Runtime Controls**: خيارات التخطيط قبل التنفيذ والتفويض والذاكرة
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### فرق Crew
|
||||
|
||||
تُضمِّن عقدة Crew فريقًا كاملًا — عدة وكلاء يتعاونون عبر عدة مهام — كخطوة واحدة في تدفقك. استخدمها عندما تكون الخطوة أكبر من أن يتولاها وكيل واحد، مثل تجميع البيانات وتلخيصها حسب الفريق ثم تنسيق النتيجة للتسليم.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
يكشف فتح عقدة Crew عن بنيتها الداخلية: المهام التي تؤديها، والوكلاء المعيّنين لكل مهمة، والتطبيقات التي يستخدمونها. يعمل الفريق بشكل مستقل داخل الخطوة، ثم يسلّم مخرجاته إلى العقدة التالية في التدفق.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
هذا هو نمط الحتمية مع الذكاء الوكيلي عمليًا: يضمن التدفق *متى* يعمل الفريق، بينما يضيف الفريق ذكاءً تعاونيًا إلى *كيفية* إنجاز العمل.
|
||||
|
||||
### الموجِّه (Router)
|
||||
|
||||
تُفرِّع عقدة Router التدفق بناءً على شروط، بحيث تسلك النتائج المختلفة مسارات مختلفة. على سبيل المثال، يمكن لتدفق توجيه العملاء المحتملين تقييم العملاء الواردين ثم توجيه ذوي الجودة العالية إلى خطوة إسناد المبيعات، مع تسجيل البقية للمتابعة والرعاية لاحقًا.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
الموجِّهات هي ما يجعل التدفقات معتمدة على الأحداث فعليًا: يتعامل سير العمل نفسه مع كل الحالات، لكن كل عملية تشغيل تتبع فقط الفرع الذي تستدعيه بياناتها — بلا خطوات مهدرة ولا غموض حول ما سيحدث تاليًا.
|
||||
|
||||
## المزامنة مع مستودع الوكلاء
|
||||
|
||||
لا يلزم أن يبقى الوكلاء الذين تنشئهم في التدفقات حبيسي مشروع واحد. تتضمن كل عقدة وكيل زر **Publish to Agent Repository** الذي يحفظ الوكيل — بدوره وهدفه وخلفيته ونموذجه وتهيئته — في [مستودع الوكلاء](/ar/enterprise/features/agent-repositories) الخاص بمؤسستك.
|
||||
|
||||
يعمل هذا في الاتجاهين:
|
||||
|
||||
- **النشر**: رقِّ وكيلًا حسّنته داخل تدفق إلى المستودع ليتمكن باقي الفرق والمشاريع من إعادة استخدامه.
|
||||
- **السحب**: أدخِل وكيلًا موجودًا من المستودع إلى تدفق جديد بدلًا من إعادة بنائه من الصفر.
|
||||
|
||||
ولأن وكلاء المستودع متزامنون عبر مؤسستك كلها، فإن أي تحسين على وكيل مشترك يعود بالنفع على كل تدفق يستخدمه — مما يحافظ على سلوك وكلاء متسق وخاضع للحوكمة وخالٍ من ازدواجية الجهد.
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
- **اختر التدفق** عندما يكون للأتمتة تسلسل واضح أو منطق تفرّع؛ واختر Crew عندما يكون الطريق إلى الهدف مفتوحًا.
|
||||
- **أبقِ مهام الوكلاء مركزة** — عقدة Single Agent بوصف مهمة محكم أكثر موثوقية من وكيل مطلوب منه ثلاثة أشياء.
|
||||
- **استخدم الموجّهات لمعالجة كل حالة صراحةً**، بما في ذلك مسار "عدم فعل شيء" (مثل تسجيل العملاء المتجاوزين)، حتى تكون كل عمليات التشغيل محسوبة بالكامل.
|
||||
- **انشر الوكلاء المستقرين في مستودع الوكلاء** لتبني مؤسستك مكتبة مشتركة بدلًا من نسخ متوازية لمرة واحدة.
|
||||
- **اختبر عبر Run وافحص Traces** قبل النشر لاكتشاف مشكلات التكامل أو الموجِّهات النصية مبكرًا.
|
||||
|
||||
## ذات صلة
|
||||
|
||||
<CardGroup cols={4}>
|
||||
<Card title="استوديو الطاقم" href="/ar/enterprise/features/crew-studio" icon="pencil">
|
||||
أنشئ فرق Crew في الاستوديو.
|
||||
</Card>
|
||||
<Card title="مستودعات الوكلاء" href="/ar/enterprise/features/agent-repositories" icon="people-group">
|
||||
شارك الوكلاء وأعد استخدامهم عبر مؤسستك.
|
||||
</Card>
|
||||
<Card title="مفاهيم التدفقات" href="/ar/concepts/flows" icon="diagram-project">
|
||||
تعرّف على كيفية عمل التدفقات في إطار عمل CrewAI.
|
||||
</Card>
|
||||
<Card title="الأدوات والتكاملات" href="/ar/enterprise/features/tools-and-integrations" icon="plug">
|
||||
اربط التطبيقات التي يستخدمها وكلاؤك.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
## كيف يعمل بث التدفق
|
||||
|
||||
عند تفعيل البث في تدفق، يلتقط CrewAI ويبث المخرجات من أي أطقم أو استدعاءات LLM داخل التدفق. يقدم البث أجزاء منظمة تحتوي على المحتوى وسياق المهمة ومعلومات الوكيل مع تقدم التنفيذ.
|
||||
عند تفعيل البث في تدفق، يلتقط CrewAI ويبث المخرجات من أي أطقم أو استدعاءات LLM أو أدوات أو أحداث دورة حياة داخل التدفق. يقدم البث عناصر `StreamFrame` مرتبة تحتوي على محتوى قابل للطباعة وبيانات حدث مهيكلة مع تقدم التنفيذ.
|
||||
|
||||
## تفعيل البث
|
||||
|
||||
@@ -52,7 +52,7 @@ class ResearchFlow(Flow):
|
||||
|
||||
## البث المتزامن
|
||||
|
||||
عند استدعاء `kickoff()` على تدفق مع تفعيل البث، يُرجع كائن `FlowStreamingOutput` يمكنك التكرار عليه:
|
||||
عند استدعاء `kickoff()` على تدفق مع تفعيل البث، يُرجع جلسة stream تنتج عناصر `StreamFrame` مرتبة:
|
||||
|
||||
```python Code
|
||||
flow = ResearchFlow()
|
||||
@@ -60,44 +60,43 @@ flow = ResearchFlow()
|
||||
# Start streaming execution
|
||||
streaming = flow.kickoff()
|
||||
|
||||
# Iterate over chunks as they arrive
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
# Iterate over stream items as they arrive
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# Access the final result after streaming completes
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result}")
|
||||
```
|
||||
|
||||
### معلومات جزء البث
|
||||
### معلومات عنصر البث
|
||||
|
||||
يوفر كل جزء سياقاً حول مصدره في التدفق:
|
||||
يوفر كل عنصر محتوى قابلاً للطباعة وبيانات حدث مهيكلة:
|
||||
|
||||
```python Code
|
||||
streaming = flow.kickoff()
|
||||
|
||||
for chunk in streaming:
|
||||
print(f"Agent: {chunk.agent_role}")
|
||||
print(f"Task: {chunk.task_name}")
|
||||
print(f"Content: {chunk.content}")
|
||||
print(f"Type: {chunk.chunk_type}") # TEXT or TOOL_CALL
|
||||
for item in streaming:
|
||||
print(f"Channel: {item.channel}")
|
||||
print(f"Type: {item.type}")
|
||||
print(f"Content: {item.content}")
|
||||
print(f"Event payload: {item.event}")
|
||||
```
|
||||
|
||||
### الوصول إلى خصائص البث
|
||||
|
||||
يوفر كائن `FlowStreamingOutput` خصائص وطرق مفيدة:
|
||||
توفر جلسة stream خصائص وطرق مفيدة:
|
||||
|
||||
```python Code
|
||||
streaming = flow.kickoff()
|
||||
|
||||
# Iterate and collect chunks
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
# Iterate and collect items
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# After iteration completes
|
||||
print(f"\nCompleted: {streaming.is_completed}")
|
||||
print(f"Full text: {streaming.get_full_text()}")
|
||||
print(f"Total chunks: {len(streaming.chunks)}")
|
||||
print(f"Total frames: {len(streaming.frames)}")
|
||||
print(f"Final result: {streaming.result}")
|
||||
```
|
||||
|
||||
@@ -114,9 +113,9 @@ async def stream_flow():
|
||||
# Start async streaming
|
||||
streaming = await flow.kickoff_async()
|
||||
|
||||
# Async iteration over chunks
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
# Async iteration over stream items
|
||||
async for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# Access final result
|
||||
result = streaming.result
|
||||
@@ -181,13 +180,14 @@ flow = MultiStepFlow()
|
||||
streaming = flow.kickoff()
|
||||
|
||||
current_step = ""
|
||||
for chunk in streaming:
|
||||
for item in streaming:
|
||||
# Track which flow step is executing
|
||||
if chunk.task_name != current_step:
|
||||
current_step = chunk.task_name
|
||||
print(f"\n\n=== {chunk.task_name} ===\n")
|
||||
step_name = item.event.get("method_name") or item.event.get("task_name")
|
||||
if step_name and step_name != current_step:
|
||||
current_step = step_name
|
||||
print(f"\n\n=== {step_name} ===\n")
|
||||
|
||||
print(chunk.content, end="", flush=True)
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal analysis: {result}")
|
||||
@@ -201,7 +201,6 @@ print(f"\n\nFinal analysis: {result}")
|
||||
import asyncio
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.types.streaming import StreamChunkType
|
||||
|
||||
class ResearchPipeline(Flow):
|
||||
stream = True
|
||||
@@ -254,33 +253,35 @@ async def run_with_dashboard():
|
||||
|
||||
current_agent = ""
|
||||
current_task = ""
|
||||
chunk_count = 0
|
||||
frame_count = 0
|
||||
|
||||
async for chunk in streaming:
|
||||
chunk_count += 1
|
||||
async for item in streaming:
|
||||
frame_count += 1
|
||||
|
||||
# Display phase transitions
|
||||
if chunk.task_name != current_task:
|
||||
current_task = chunk.task_name
|
||||
current_agent = chunk.agent_role
|
||||
task_name = item.event.get("task_name", "")
|
||||
agent_role = item.event.get("agent_role", "")
|
||||
if task_name and task_name != current_task:
|
||||
current_task = task_name
|
||||
current_agent = agent_role
|
||||
print(f"\n\n📋 Phase: {current_task}")
|
||||
print(f"👤 Agent: {current_agent}")
|
||||
print("-" * 60)
|
||||
|
||||
# Display text output
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
if item.content:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# Display tool usage
|
||||
elif chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\n🔧 Tool: {chunk.tool_call.tool_name}")
|
||||
elif item.channel == "tools":
|
||||
print(f"\n🔧 Tool event: {item.type}")
|
||||
|
||||
# Show completion summary
|
||||
result = streaming.result
|
||||
print(f"\n\n{'='*60}")
|
||||
print("PIPELINE COMPLETE")
|
||||
print(f"{'='*60}")
|
||||
print(f"Total chunks: {chunk_count}")
|
||||
print(f"Total frames: {frame_count}")
|
||||
print(f"Final output length: {len(str(result))} characters")
|
||||
|
||||
asyncio.run(run_with_dashboard())
|
||||
@@ -353,8 +354,8 @@ class StatefulStreamingFlow(Flow[AnalysisState]):
|
||||
flow = StatefulStreamingFlow()
|
||||
streaming = flow.kickoff(inputs={"topic": "quantum computing"})
|
||||
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal state:")
|
||||
@@ -374,29 +375,29 @@ print(f"Insights length: {len(flow.state.insights)}")
|
||||
- **تتبع التقدم**: إظهار المرحلة الحالية من سير العمل للمستخدمين
|
||||
- **لوحات المعلومات الحية**: إنشاء واجهات مراقبة لتدفقات الإنتاج
|
||||
|
||||
## أنواع أجزاء البث
|
||||
## قنوات إطارات البث
|
||||
|
||||
مثل بث الطاقم، يمكن أن تكون أجزاء التدفق من أنواع مختلفة:
|
||||
ينتج بث التدفق عناصر `StreamFrame` عبر عدة قنوات:
|
||||
|
||||
### أجزاء TEXT
|
||||
### إطارات LLM
|
||||
|
||||
محتوى نصي قياسي من استجابات LLM:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
if item.channel == "llm" and item.content:
|
||||
print(item.content, end="", flush=True)
|
||||
```
|
||||
|
||||
### أجزاء TOOL_CALL
|
||||
### إطارات الأدوات
|
||||
|
||||
معلومات حول استدعاءات الأدوات داخل التدفق:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\nTool: {chunk.tool_call.tool_name}")
|
||||
print(f"Args: {chunk.tool_call.arguments}")
|
||||
for item in streaming:
|
||||
if item.channel == "tools":
|
||||
print(f"\nTool event: {item.type}")
|
||||
print(f"Payload: {item.event}")
|
||||
```
|
||||
|
||||
## معالجة الأخطاء
|
||||
@@ -408,8 +409,8 @@ flow = ResearchFlow()
|
||||
streaming = flow.kickoff()
|
||||
|
||||
try:
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nSuccess! Result: {result}")
|
||||
@@ -422,7 +423,7 @@ except Exception as e:
|
||||
|
||||
## الإلغاء وتنظيف الموارد
|
||||
|
||||
يدعم `FlowStreamingOutput` الإلغاء السلس بحيث يتوقف العمل الجاري فوراً عند انقطاع اتصال المستهلك.
|
||||
تدعم جلسة stream الإلغاء السلس بحيث يتوقف العمل الجاري فوراً عند انقطاع اتصال المستهلك.
|
||||
|
||||
### مدير السياق غير المتزامن
|
||||
|
||||
@@ -430,8 +431,8 @@ except Exception as e:
|
||||
streaming = await flow.kickoff_async()
|
||||
|
||||
async with streaming:
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
async for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
```
|
||||
|
||||
### الإلغاء الصريح
|
||||
@@ -439,8 +440,8 @@ async with streaming:
|
||||
```python Code
|
||||
streaming = await flow.kickoff_async()
|
||||
try:
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
async for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
finally:
|
||||
await streaming.aclose() # غير متزامن
|
||||
# streaming.close() # المكافئ المتزامن
|
||||
@@ -451,10 +452,10 @@ finally:
|
||||
## ملاحظات مهمة
|
||||
|
||||
- يفعّل البث تلقائياً بث LLM لأي أطقم مستخدمة داخل التدفق
|
||||
- يجب التكرار عبر جميع الأجزاء قبل الوصول إلى خاصية `.result`
|
||||
- يجب التكرار عبر جميع عناصر stream قبل الوصول إلى خاصية `.result`
|
||||
- يعمل البث مع كل من حالة التدفق المنظمة وغير المنظمة
|
||||
- يلتقط بث التدفق المخرجات من جميع الأطقم واستدعاءات LLM في التدفق
|
||||
- يتضمن كل جزء سياقاً حول الوكيل والمهمة التي ولدته
|
||||
- يتضمن كل إطار سياق حدث مهيكلاً مثل القناة والنوع والنطاق والحمولة
|
||||
- يضيف البث حملاً ضئيلاً لتنفيذ التدفق
|
||||
|
||||
## الدمج مع تصور التدفق
|
||||
@@ -468,8 +469,8 @@ flow.plot("research_flow") # Creates HTML visualization
|
||||
|
||||
# Run with streaming
|
||||
streaming = flow.kickoff()
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nFlow complete! View structure at: research_flow.html")
|
||||
|
||||
194
docs/edge/ar/learn/streaming-runtime-contract.mdx
Normal file
@@ -0,0 +1,194 @@
|
||||
---
|
||||
title: عقد بث وقت التشغيل
|
||||
description: بث إطارات وقت تشغيل مرتبة من التدفقات واستدعاءات LLM المباشرة ودورات المحادثة.
|
||||
icon: tower-broadcast
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يوفر CrewAI عقد بث قائمًا على الإطارات للأنظمة التي تحتاج إلى أكثر من أجزاء نصية بسيطة. يصدر العقد كائنات `StreamFrame` مرتبة لأحداث دورة حياة Flow، وتوكنات LLM المباشرة، ونشاط الأدوات، ورسائل المحادثة، والأحداث المخصصة.
|
||||
|
||||
استخدم هذه الواجهة عندما تبني واجهة مستخدم، أو جسر خدمة، أو تطبيق طرفية، أو وقت تشغيل نشر يحتاج إلى تدفق ثابت من الأحداث المهيكلة أثناء تشغيل Flow أو دورة محادثة أو استدعاء LLM مباشر.
|
||||
|
||||
## StreamFrame
|
||||
|
||||
لكل إطار نفس الغلاف:
|
||||
|
||||
```python
|
||||
from crewai.types.streaming import StreamFrame
|
||||
|
||||
frame.id # معرف إطار فريد
|
||||
frame.seq # ترتيب محلي للتنفيذ، عند توفره
|
||||
frame.type # نوع الحدث المصدر، مثل "flow_started"
|
||||
frame.channel # "llm", "flow", "tools", "messages", "lifecycle", or "custom"
|
||||
frame.namespace # نطاق المصدر/وقت التشغيل
|
||||
frame.timestamp # طابع وقت الحدث
|
||||
frame.parent_id # معرف الحدث الأب، عند توفره
|
||||
frame.previous_id # معرف الحدث السابق، عند توفره
|
||||
frame.data # حمولة الحدث
|
||||
frame.event # اسم بديل لـ frame.data
|
||||
frame.content # نص قابل للطباعة لإطارات التوكن، وإلا ""
|
||||
```
|
||||
|
||||
حقل `channel` هو أسرع طريقة لتوجيه الإطارات في المستهلكين:
|
||||
|
||||
| القناة | تحتوي على |
|
||||
|--------|-----------|
|
||||
| `llm` | توكنات وأجزاء التفكير من أحداث بث LLM |
|
||||
| `flow` | دورة حياة Flow، وتنفيذ الدوال، والتوجيه، وأحداث الإيقاف/الاستئناف |
|
||||
| `tools` | أحداث استخدام الأدوات |
|
||||
| `messages` | أحداث سجل المحادثة |
|
||||
| `lifecycle` | أحداث دورة حياة وقت التشغيل التي لا تخص قناة أخرى |
|
||||
| `custom` | أحداث لا تُطابق قناة مدمجة |
|
||||
|
||||
يحافظ `frame.type` على نوع الحدث المصدر، حتى يتمكن المستهلكون من التعامل مع أحداث محددة داخل القناة.
|
||||
|
||||
## بث Flow
|
||||
|
||||
عيّن `stream=True` على Flow لجعل `kickoff()` يعيد جلسة stream:
|
||||
|
||||
```python
|
||||
from crewai.flow import Flow, start
|
||||
|
||||
|
||||
class ReportFlow(Flow):
|
||||
@start()
|
||||
def generate(self):
|
||||
return "done"
|
||||
|
||||
|
||||
flow = ReportFlow(stream=True)
|
||||
stream = flow.kickoff()
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
if chunk.type == "tool_usage_started":
|
||||
print(chunk.event["tool_name"])
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
يجب استهلاك stream قبل قراءة `stream.result`. يؤدي الوصول إلى النتيجة مبكرًا إلى رفع `RuntimeError` حتى لا يتعامل المستهلكون بالخطأ مع تشغيل جزئي على أنه مكتمل.
|
||||
|
||||
يمكنك أيضًا استدعاء `flow.stream_events(...)` مباشرة عندما تريد البث لاستدعاء واحد بدون تعيين `stream=True` على مثيل Flow.
|
||||
|
||||
## التصفية حسب القناة
|
||||
|
||||
يوفر `StreamSession` إسقاطات حسب القناة تحافظ على ترتيب الإطارات العالمي داخل القناة المحددة:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
with stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
الإسقاطات المتاحة هي:
|
||||
|
||||
| الإسقاط | الإطارات |
|
||||
|---------|----------|
|
||||
| `stream.events` | كل الإطارات |
|
||||
| `stream.llm` | إطارات LLM |
|
||||
| `stream.messages` | إطارات رسائل المحادثة |
|
||||
| `stream.flow` | إطارات Flow |
|
||||
| `stream.tools` | إطارات الأدوات |
|
||||
| `stream.interleave([...])` | مجموعة مختارة من القنوات |
|
||||
|
||||
استخدم `stream.interleave(["flow", "llm", "messages"])` عندما يريد المستهلك بعض القنوات فقط لكنه ما زال يحتاج إلى ترتيبها النسبي.
|
||||
|
||||
## البث غير المتزامن
|
||||
|
||||
استخدم `astream()` للمستهلكين غير المتزامنين:
|
||||
|
||||
```python
|
||||
flow = ReportFlow()
|
||||
stream = flow.astream()
|
||||
|
||||
async with stream:
|
||||
async for chunk in stream.events:
|
||||
print(chunk.channel, chunk.type, chunk.content)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
تملك الجلسة غير المتزامنة نفس إسقاطات الجلسة المتزامنة.
|
||||
|
||||
## بث استدعاء LLM مباشر
|
||||
|
||||
ما زال `llm.call(...)` يعيد النتيجة النهائية المجمعة. استخدم `llm.stream_events(...)` عندما تريد التكرار على الأجزاء فور وصولها مع الحفاظ على حمولة الحدث المهيكلة:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o-mini")
|
||||
stream = llm.stream_events(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain CrewAI streaming in two short sentences.",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
يفعل `llm.stream_events(...)` البث مؤقتًا للاستدعاء المغلف ثم يستعيد إعداد `stream` السابق في LLM بعد ذلك. تستمر تكاملات المزودين في إصدار أحداث بث LLM الأساسية؛ يوفر هذا المساعد واجهة مكرر مشتركة فوق تلك الأحداث لكل مزودي LLM.
|
||||
|
||||
## دورات المحادثة
|
||||
|
||||
يمكن للتدفقات المحادثية بث دورة مستخدم واحدة باستخدام `stream_turn()`:
|
||||
|
||||
```python
|
||||
from crewai import Flow
|
||||
from crewai.experimental.conversational import ConversationConfig, ConversationState
|
||||
|
||||
|
||||
@ConversationConfig(llm="gpt-4o-mini", defer_trace_finalization=True)
|
||||
class ChatFlow(Flow[ConversationState]):
|
||||
conversational = True
|
||||
|
||||
|
||||
flow = ChatFlow()
|
||||
stream = flow.stream_turn("What can you help me with?", session_id="session-1")
|
||||
|
||||
with stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
reply = stream.result
|
||||
```
|
||||
|
||||
أثناء `stream_turn()`، يفعّل مسار الإجابة المحادثية المدمج بث توكنات LLM لذلك الدور ثم يستعيد إعداد `stream` السابق في LLM بعد ذلك. يجب على معالجات المسارات المخصصة التي تنشئ Agents أو مثيلات LLM خاصة بها تهيئة تلك النماذج للبث إذا احتاجت إلى إخراج على مستوى التوكن.
|
||||
|
||||
## التنظيف
|
||||
|
||||
استخدم الجلسة كمدير سياق عندما يكون ذلك ممكنًا. إذا انقطع اتصال العميل قبل استهلاك stream بالكامل، فأغلق الجلسة صراحة:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
try:
|
||||
for frame in stream.events:
|
||||
print(frame.type)
|
||||
finally:
|
||||
if not stream.is_exhausted:
|
||||
stream.close()
|
||||
```
|
||||
|
||||
للتدفقات غير المتزامنة، استخدم `await stream.aclose()`.
|
||||
|
||||
## بث الأجزاء القديم
|
||||
|
||||
ما زال بث Crew مع `stream=True` يعيد واجهة `CrewStreamingOutput` المعتمدة على الأجزاء والموضحة في [بث تنفيذ Crew](/ar/learn/streaming-crew-execution). وما زالت استدعاءات `llm.call(...)` المباشرة تعيد نتيجة LLM النهائية. عقد الإطارات مخصص لأوقات التشغيل التي تحتاج إلى غلاف حدث ثابت عبر Flows، واستدعاءات LLM المباشرة، ودورات المحادثة، والأدوات، والرسائل.
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
لا نزال نعمل على تحسين الأدوات، لذا قد يحدث سلوك غير متوقع أو تغييرات في المستقبل.
|
||||
</Note>
|
||||
|
||||
تمثل أداة FileReadTool مفهومياً مجموعة من الوظائف ضمن حزمة crewai_tools تهدف إلى تسهيل قراءة الملفات واسترجاع المحتوى. تتضمن هذه المجموعة أدوات لمعالجة ملفات نصية دفعية، وقراءة ملفات التكوين أثناء التشغيل، واستيراد البيانات للتحليلات. تدعم مجموعة متنوعة من صيغ الملفات النصية مثل `.txt` و `.csv` و `.json` وغيرها. اعتماداً على نوع الملف، توفر المجموعة وظائف متخصصة، مثل تحويل محتوى JSON إلى قاموس Python لسهولة الاستخدام.
|
||||
تمثل أداة FileReadTool مفهوميًا مجموعة من الوظائف ضمن حزمة crewai_tools تهدف إلى تسهيل قراءة الملفات واسترجاع المحتوى. تتضمن هذه المجموعة أدوات لمعالجة ملفات نصية دفعية، وقراءة ملفات التكوين أثناء التشغيل، واستيراد البيانات للتحليلات. تدعم مجموعة متنوعة من صيغ الملفات النصية مثل `.txt` و `.csv` و `.json` وغيرها. يُعاد المحتوى دائمًا نصًا عاديًا.
|
||||
|
||||
## التثبيت
|
||||
|
||||
|
||||
@@ -30,7 +30,11 @@ from crewai_tools import FileWriterTool
|
||||
file_writer_tool = FileWriterTool()
|
||||
|
||||
# Write content to a file in a specified directory
|
||||
result = file_writer_tool._run('example.txt', 'This is a test content.', 'test_directory')
|
||||
result = file_writer_tool.run(
|
||||
filename='example.txt',
|
||||
content='This is a test content.',
|
||||
directory='test_directory',
|
||||
)
|
||||
print(result)
|
||||
```
|
||||
|
||||
|
||||
@@ -4,6 +4,330 @@ description: "Product updates, improvements, and bug fixes for CrewAI"
|
||||
icon: "clock"
|
||||
mode: "wide"
|
||||
---
|
||||
<Update label="Jul 28, 2026">
|
||||
## v1.15.8
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.8)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Add WaitTool for pausing on long-running jobs.
|
||||
|
||||
### Bug Fixes
|
||||
- Fix FileWriterTool writes and address rough edges in file tool.
|
||||
- Mark E2B_API_KEY as a required env var for E2B tools.
|
||||
|
||||
### Documentation
|
||||
- Refresh model availability guidance.
|
||||
|
||||
## Contributors
|
||||
|
||||
@github-actions[bot], @joaomdmoura, @lucasgomide, @oalami, @thiagomoretto
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 26, 2026">
|
||||
## v1.15.7
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Bug Fixes
|
||||
- Resolve registry skills through the runtime's CrewAI+ client
|
||||
- Recover from the GPT-5.6 tools + reasoning_effort 400
|
||||
- Make tool calling work on the Responses API path
|
||||
- Route responses-only models instead of failing with 404
|
||||
- Bump bedrock-agentcore to patch CVE-2026-16796
|
||||
|
||||
### Observability
|
||||
- Emit skill usage events at runtime for observability
|
||||
|
||||
### Documentation
|
||||
- Add snapshot and changelog for v1.15.7a1
|
||||
|
||||
## Contributors
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 26, 2026">
|
||||
## v1.15.7a1
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7a1)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Bug Fixes
|
||||
- Fix registry skills resolution through the runtime's CrewAI+ client.
|
||||
- Recover from the GPT-5.6 tools and reasoning_effort 400 errors.
|
||||
- Make tool calling work on the Responses API path.
|
||||
- Route responses-only models to prevent 404 errors.
|
||||
- Bump bedrock-agentcore dependency to patch CVE-2026-16796.
|
||||
|
||||
### Observability
|
||||
- Emit skill usage events at runtime for improved observability.
|
||||
|
||||
### Documentation
|
||||
- Snapshot and changelog updates for version 1.15.6.
|
||||
|
||||
## Contributors
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 24, 2026">
|
||||
## v1.15.6
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.6)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Bug Fixes
|
||||
- Fix detection of Anthropic preview tool-use blocks.
|
||||
- Preserve strict tool schema property names.
|
||||
- Dispatch execution_end hook on failed crew and flow executions.
|
||||
- Handle async get_agent in load_agent_from_repository.
|
||||
- Fix dependency resolution issues.
|
||||
|
||||
### Documentation
|
||||
- Snapshot and changelog for v1.15.5.
|
||||
|
||||
## Contributors
|
||||
|
||||
@alex-clawd, @iris-clawd, @lorenzejay, @lucasgomide, @theCyberTech, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 20, 2026">
|
||||
## v1.15.5
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.5)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Authenticate skill registry downloads
|
||||
|
||||
### Documentation
|
||||
- Update snapshot and changelog for v1.15.4
|
||||
|
||||
## Contributors
|
||||
|
||||
@vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 17, 2026">
|
||||
## v1.15.4
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.4)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Promote Skills Repository out of experimental status
|
||||
|
||||
### Documentation
|
||||
- Add Flows in Studio documentation
|
||||
|
||||
## Contributors
|
||||
|
||||
@jessemiller, @joaomdmoura, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 16, 2026">
|
||||
## v1.15.3
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Add organization ID parameter to PlusAPI client
|
||||
- Add step interception points and rework execution hooks documentation around @on
|
||||
- Wire execution-boundary interception points
|
||||
- Add generic interception-hook dispatcher
|
||||
- Run declarative flows on the TUI (headless terminal fallback)
|
||||
|
||||
### Bug Fixes
|
||||
- Sync kickoff-completed event with OUTPUT hook result
|
||||
- Fix null repository agent attributes
|
||||
- Ensure after_llm_call hooks do not break native tool execution
|
||||
- Avoid double-append of the turn reply when a handler trims history
|
||||
- Make tool-result caching opt-in instead of on by default
|
||||
- Stop rewriting the authored tool description at construction
|
||||
- Expose token usage under both names on agent and crew results
|
||||
- Report per-call usage metrics on kickoff results
|
||||
- Stop replaying previous turn's intent when route_turn() returns falsy
|
||||
|
||||
### Documentation
|
||||
- Update execution hooks grouping and document all hook contexts
|
||||
|
||||
## Contributors
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 16, 2026">
|
||||
## v1.15.3a2
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a2)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Bug Fixes
|
||||
- Fix synchronization of kickoff-completed event with OUTPUT hook result
|
||||
|
||||
### Documentation
|
||||
- Update snapshot and changelog for v1.15.3a1
|
||||
|
||||
### Dependency Updates
|
||||
- Bump setuptools to 0.83.0 to address PYSEC-2026-3447
|
||||
|
||||
## Contributors
|
||||
|
||||
@lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 16, 2026">
|
||||
## v1.15.3a1
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a1)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Add organization ID parameter to PlusAPI client.
|
||||
- Add step interception points and rework execution hooks documentation around `@on`.
|
||||
- Wire execution-boundary interception points.
|
||||
- Add generic interception-hook dispatcher.
|
||||
- Run declarative flows on the TUI (headless terminal fallback).
|
||||
- Improve custom OpenAI URLs.
|
||||
|
||||
### Bug Fixes
|
||||
- Fix null repository agent attributes.
|
||||
- Fix `after_llm_call` hooks to prevent breaking native tool execution.
|
||||
- Stop double-appending the turn reply when a handler trims history.
|
||||
- Make tool-result caching opt-in instead of on by default.
|
||||
- Stop rewriting the authored tool description at construction.
|
||||
- Expose token usage under both names on agent and crew results.
|
||||
- Report per-call usage metrics on kickoff results.
|
||||
- Stop replaying the previous turn's intent when `route_turn()` returns falsy.
|
||||
- Drain memory writes before kickoff and flow completion events.
|
||||
|
||||
### Documentation
|
||||
- Group execution hooks and document all hook contexts.
|
||||
- Update documentation for execution hooks.
|
||||
|
||||
## Contributors
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 07, 2026">
|
||||
## v1.15.2
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Pull latest LLM models dynamically in the crew wizard.
|
||||
- Support inline skill definitions.
|
||||
- Add generated Flow Definition authoring skill.
|
||||
- Support templated Flow action inputs.
|
||||
- Add text helper for flow CEL prompts.
|
||||
- Add text helper to flow skill example.
|
||||
- Implement message setup and feedback handling in AgentExecutor.
|
||||
- Add repository agents to flow definitions.
|
||||
- Define stream frame protocol for flows.
|
||||
- Type tool and app in CrewDefinition.
|
||||
- Repoint template commands to crewAIInc-fde org.
|
||||
|
||||
### Bug Fixes
|
||||
- Key model-catalog cache by exact API key, shorten TTL, and skip Ollama.
|
||||
- Unify `crewai run` flow input resolution and prompt from the state schema.
|
||||
- Resolve pip-audit failures for onnx 1.22.0 and nltk PYSEC-2026-597.
|
||||
- Ensure we are writing version for flows.
|
||||
- Include aiobotocore in the bedrock extra.
|
||||
- Reject self-listening flow methods.
|
||||
- Cut docs version nav from Edge so new pages aren't dropped.
|
||||
|
||||
### Documentation
|
||||
- Update language from Rules to Policies to match new dashboard changes.
|
||||
- Document flow agent options.
|
||||
- Add streaming docs to the navigation.
|
||||
- Document Cost Limit rule type in Agent Control Plane.
|
||||
- Drop CREWAI_LOG_FORMAT references from Datadog guide.
|
||||
|
||||
## Contributors
|
||||
|
||||
@akaKuruma, @danielfsbarreto, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @manisrinivasan2k1, @renatonitta, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jul 01, 2026">
|
||||
## v1.15.2a2
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a2)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Add aiobotocore to the bedrock extra
|
||||
- Document flow agent options
|
||||
- Add text helper to flow skill example
|
||||
- Add text helper for flow CEL prompts
|
||||
- Add streaming docs to the navigation
|
||||
|
||||
### Bug Fixes
|
||||
- Reject self-listening flow methods
|
||||
|
||||
### Documentation
|
||||
- Update snapshot and changelog for v1.15.2a1
|
||||
- Squeeze AGENTS.md file
|
||||
|
||||
## Contributors
|
||||
|
||||
@akaKuruma, @github-code-quality[bot], @lorenzejay, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jun 30, 2026">
|
||||
## v1.15.2a1
|
||||
|
||||
[View release on GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a1)
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Features
|
||||
- Repoint template commands to crewAIInc-fde org
|
||||
- Support inline skill definitions
|
||||
- Define stream frame protocol for flows
|
||||
- Add type tool and app in CrewDefinition
|
||||
- Add generated Flow Definition authoring skill
|
||||
|
||||
### Bug Fixes
|
||||
- Cut docs version navigation from Edge to prevent new pages from being dropped
|
||||
|
||||
### Documentation
|
||||
- Document Cost Limit rule type in Agent Control Plane
|
||||
- Drop CREWAI_LOG_FORMAT references from Datadog guide
|
||||
|
||||
## Contributors
|
||||
|
||||
@danielfsbarreto, @joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="Jun 26, 2026">
|
||||
## v1.15.1
|
||||
|
||||
|
||||
@@ -22,7 +22,10 @@ Large Language Models (LLMs) are the core intelligence behind CrewAI agents. The
|
||||
The context window determines how much text an LLM can process at once. Larger windows (e.g., 128K tokens) allow for more context but may be more expensive and slower.
|
||||
</Card>
|
||||
<Card title="Temperature" icon="temperature-three-quarters">
|
||||
Temperature (0.0 to 1.0) controls response randomness. Lower values (e.g., 0.2) produce more focused, deterministic outputs, while higher values (e.g., 0.8) increase creativity and variability.
|
||||
Temperature is a sampling control supported by some models. Lower values
|
||||
generally make sampling more focused, while higher values increase
|
||||
variability. Some newer reasoning models ignore, deprecate, or reject this
|
||||
parameter, so check the selected model's documentation before setting it.
|
||||
</Card>
|
||||
<Card title="Provider Selection" icon="server">
|
||||
Each LLM provider (e.g., OpenAI, Anthropic, Google) offers different models with varying capabilities, pricing, and features. Choose based on your needs for accuracy, speed, and cost.
|
||||
@@ -38,7 +41,7 @@ There are different places in CrewAI code where you can specify the model to use
|
||||
The simplest way to get started. Set the model in your environment directly, through an `.env` file or in your app code. If you used `crewai create` to bootstrap your project, it will be set already.
|
||||
|
||||
```bash .env
|
||||
MODEL=model-id # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...
|
||||
MODEL=provider/model-id # e.g. openai/gpt-5.6-terra
|
||||
|
||||
# Be sure to set your API keys here too. See the Provider
|
||||
# section below.
|
||||
@@ -57,7 +60,7 @@ There are different places in CrewAI code where you can specify the model to use
|
||||
goal: Conduct comprehensive research and analysis
|
||||
backstory: A dedicated research professional with years of experience
|
||||
verbose: true
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
llm: provider/model-id # e.g. anthropic/claude-sonnet-4-6
|
||||
# (see provider configuration examples below for more)
|
||||
```
|
||||
|
||||
@@ -76,32 +79,27 @@ There are different places in CrewAI code where you can specify the model to use
|
||||
from crewai import LLM
|
||||
|
||||
# Basic configuration
|
||||
llm = LLM(model="model-id-here") # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
llm = LLM(model="provider/model-id") # e.g. gemini/gemini-3.6-flash
|
||||
|
||||
# Advanced configuration with detailed parameters
|
||||
llm = LLM(
|
||||
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
temperature=0.7, # Higher for more creative outputs
|
||||
timeout=120, # Seconds to wait for response
|
||||
max_tokens=4000, # Maximum length of response
|
||||
top_p=0.9, # Nucleus sampling parameter
|
||||
frequency_penalty=0.1 , # Reduce repetition
|
||||
presence_penalty=0.1, # Encourage topic diversity
|
||||
model="provider/model-id",
|
||||
timeout=120,
|
||||
max_tokens=4000,
|
||||
response_format={"type": "json"}, # For structured outputs
|
||||
seed=42 # For reproducible results
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Parameter explanations:
|
||||
- `temperature`: Controls randomness (0.0-1.0)
|
||||
- `timeout`: Maximum wait time for response
|
||||
- `max_tokens`: Limits response length
|
||||
- `top_p`: Alternative to temperature for sampling
|
||||
- `frequency_penalty`: Reduces word repetition
|
||||
- `presence_penalty`: Encourages new topics
|
||||
- `response_format`: Specifies output structure
|
||||
- `seed`: Ensures consistent outputs
|
||||
|
||||
Sampling controls such as `temperature` and `top_p`, penalty parameters,
|
||||
token-limit names, and reasoning controls are model-specific. Add them
|
||||
only when the selected provider and model support them. See the provider
|
||||
examples below and the provider's model documentation.
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -120,6 +118,13 @@ There are different places in CrewAI code where you can specify the model to use
|
||||
CrewAI supports a multitude of LLM providers, each offering unique features, authentication methods, and model capabilities.
|
||||
In this section, you'll find detailed examples that help you select, configure, and optimize the LLM that best fits your project's needs.
|
||||
|
||||
<Warning>
|
||||
Model availability changes frequently and can vary by account, region, and
|
||||
cloud platform. The examples below use models that are current at the time of
|
||||
writing, but they are not exhaustive support lists. Before deploying, verify
|
||||
the model ID and lifecycle status in the provider's linked model catalog.
|
||||
</Warning>
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI">
|
||||
CrewAI provides native integration with OpenAI through the OpenAI Python SDK.
|
||||
@@ -137,10 +142,22 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
api_key="your-api-key", # Or set OPENAI_API_KEY
|
||||
temperature=0.7,
|
||||
max_tokens=4000
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4000
|
||||
)
|
||||
```
|
||||
|
||||
**Custom OpenAI-Compatible Endpoint:**
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
custom_openai=True,
|
||||
base_url="https://your-gateway.example.com/v1",
|
||||
api_key="your-gateway-api-key",
|
||||
)
|
||||
```
|
||||
|
||||
@@ -149,25 +166,16 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
api_key="your-api-key",
|
||||
base_url="https://api.openai.com/v1", # Optional custom endpoint
|
||||
organization="org-...", # Optional organization ID
|
||||
project="proj_...", # Optional project ID
|
||||
temperature=0.7,
|
||||
max_tokens=4000,
|
||||
max_completion_tokens=4000, # For newer models
|
||||
top_p=0.9,
|
||||
frequency_penalty=0.1,
|
||||
presence_penalty=0.1,
|
||||
stop=["END"],
|
||||
seed=42, # For reproducible outputs
|
||||
max_completion_tokens=4000,
|
||||
reasoning_effort="medium",
|
||||
stream=True, # Enable streaming
|
||||
timeout=60.0, # Request timeout in seconds
|
||||
max_retries=3, # Maximum retry attempts
|
||||
logprobs=True, # Return log probabilities
|
||||
top_logprobs=5, # Number of most likely tokens
|
||||
reasoning_effort="medium" # For o1 models: low, medium, high
|
||||
max_retries=3 # Maximum retry attempts
|
||||
)
|
||||
```
|
||||
|
||||
@@ -182,7 +190,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
summary: str
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
)
|
||||
```
|
||||
|
||||
@@ -191,30 +199,18 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- `OPENAI_BASE_URL`: Custom base URL for OpenAI API (optional)
|
||||
|
||||
**Features:**
|
||||
- Native function calling support (except o1 models)
|
||||
- Native function calling support
|
||||
- Structured outputs with JSON schema
|
||||
- Streaming support for real-time responses
|
||||
- Token usage tracking
|
||||
- Stop sequences support (except o1 models)
|
||||
- Provider-specific generation controls
|
||||
- Log probabilities for token-level insights
|
||||
- Reasoning effort control for o1 models
|
||||
- Reasoning effort control for supported models
|
||||
|
||||
**Supported Models:**
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|---------------------|------------------|-----------------------------------------------|
|
||||
| gpt-4.1 | 1M tokens | Latest model with enhanced capabilities |
|
||||
| gpt-4.1-mini | 1M tokens | Efficient version with large context |
|
||||
| gpt-4.1-nano | 1M tokens | Ultra-efficient variant |
|
||||
| gpt-4o | 128,000 tokens | Optimized for speed and intelligence |
|
||||
| gpt-4o-mini | 200,000 tokens | Cost-effective with large context |
|
||||
| gpt-4-turbo | 128,000 tokens | Long-form content, document analysis |
|
||||
| gpt-4 | 8,192 tokens | High-accuracy tasks, complex reasoning |
|
||||
| o1 | 200,000 tokens | Advanced reasoning, complex problem-solving |
|
||||
| o1-preview | 128,000 tokens | Preview of reasoning capabilities |
|
||||
| o1-mini | 128,000 tokens | Efficient reasoning model |
|
||||
| o3-mini | 200,000 tokens | Lightweight reasoning model |
|
||||
| o4-mini | 200,000 tokens | Next-gen efficient reasoning |
|
||||
OpenAI regularly adds models and retires older snapshots. See the
|
||||
[OpenAI model catalog](https://developers.openai.com/api/docs/models) for
|
||||
current model IDs, context windows, endpoint compatibility, and lifecycle
|
||||
information.
|
||||
|
||||
**Responses API:**
|
||||
|
||||
@@ -276,14 +272,8 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
)
|
||||
```
|
||||
|
||||
All models listed here https://llama.developer.meta.com/docs/models/ are supported.
|
||||
|
||||
| Model ID | Input context length | Output context length | Input Modalities | Output Modalities |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8` | 128k | 4028 | Text, Image | Text |
|
||||
| `meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 128k | 4028 | Text, Image | Text |
|
||||
| `meta_llama/Llama-3.3-70B-Instruct` | 128k | 4028 | Text | Text |
|
||||
| `meta_llama/Llama-3.3-8B-Instruct` | 128k | 4028 | Text | Text |
|
||||
See the [Meta Llama model overview](https://ai.meta.com/llama/get-started/)
|
||||
for current model families, modalities, and context guidance.
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
```bash
|
||||
@@ -353,7 +343,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-5-sonnet-20241022",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
api_key="your-api-key", # Or set ANTHROPIC_API_KEY
|
||||
max_tokens=4096 # Required for Anthropic
|
||||
)
|
||||
@@ -364,12 +354,10 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-5-sonnet-20241022",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
api_key="your-api-key",
|
||||
base_url="https://api.anthropic.com", # Optional custom endpoint
|
||||
temperature=0.7,
|
||||
max_tokens=4096, # Required parameter
|
||||
top_p=0.9,
|
||||
stop_sequences=["END", "STOP"], # Anthropic uses stop_sequences
|
||||
stream=True, # Enable streaming
|
||||
timeout=60.0, # Request timeout in seconds
|
||||
@@ -377,7 +365,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
)
|
||||
```
|
||||
|
||||
**Extended Thinking (Claude Sonnet 4 and Beyond):**
|
||||
**Extended Thinking:**
|
||||
|
||||
CrewAI supports Anthropic's Extended Thinking feature, which allows Claude to think through problems in a more human-like way before responding. This is particularly useful for complex reasoning, analysis, and problem-solving tasks.
|
||||
|
||||
@@ -386,14 +374,14 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
|
||||
# Enable extended thinking with default settings
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
thinking={"type": "enabled"},
|
||||
max_tokens=10000
|
||||
)
|
||||
|
||||
# Configure thinking with budget control
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
thinking={
|
||||
"type": "enabled",
|
||||
"budget_tokens": 5000 # Limit thinking tokens
|
||||
@@ -406,9 +394,8 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- `type`: Set to `"enabled"` to activate extended thinking mode
|
||||
- `budget_tokens` (optional): Maximum tokens to use for thinking (helps control costs)
|
||||
|
||||
**Models Supporting Extended Thinking:**
|
||||
- `claude-sonnet-4` and newer models
|
||||
- `claude-3-7-sonnet` (with extended thinking capabilities)
|
||||
Thinking modes and accepted parameters vary across Claude generations.
|
||||
Check the selected model's capabilities before enabling `thinking`.
|
||||
|
||||
**When to Use Extended Thinking:**
|
||||
- Complex reasoning and multi-step problem solving
|
||||
@@ -424,7 +411,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
|
||||
**Features:**
|
||||
- Native tool use support for Claude 3+ models
|
||||
- Extended Thinking support for Claude Sonnet 4+
|
||||
- Extended Thinking support for compatible Claude models
|
||||
- Streaming support for real-time responses
|
||||
- Automatic system message handling
|
||||
- Stop sequences for controlled output
|
||||
@@ -438,20 +425,10 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- First message must be from the user (automatically handled)
|
||||
- Messages must alternate between user and assistant
|
||||
|
||||
**Supported Models:**
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|------------------------------|----------------|-----------------------------------------------|
|
||||
| claude-sonnet-4 | 200,000 tokens | Latest with extended thinking capabilities |
|
||||
| claude-3-7-sonnet | 200,000 tokens | Advanced reasoning and agentic tasks |
|
||||
| claude-3-5-sonnet-20241022 | 200,000 tokens | Latest Sonnet with best performance |
|
||||
| claude-3-5-haiku | 200,000 tokens | Fast, compact model for quick responses |
|
||||
| claude-3-opus | 200,000 tokens | Most capable for complex tasks |
|
||||
| claude-3-sonnet | 200,000 tokens | Balanced intelligence and speed |
|
||||
| claude-3-haiku | 200,000 tokens | Fastest for simple tasks |
|
||||
| claude-2.1 | 200,000 tokens | Extended context, reduced hallucinations |
|
||||
| claude-2 | 100,000 tokens | Versatile model for various tasks |
|
||||
| claude-instant | 100,000 tokens | Fast, cost-effective for everyday tasks |
|
||||
See Anthropic's [models overview](https://platform.claude.com/docs/en/about-claude/models/overview)
|
||||
for current model IDs and capabilities, and review the
|
||||
[model deprecation table](https://platform.claude.com/docs/en/about-claude/model-deprecations)
|
||||
before pinning a model in production.
|
||||
|
||||
**Note:** To use Anthropic, install the required dependencies:
|
||||
```bash
|
||||
@@ -483,9 +460,8 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
model="gemini/gemini-3.6-flash",
|
||||
api_key="your-api-key", # Or set GOOGLE_API_KEY/GEMINI_API_KEY
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
@@ -494,11 +470,8 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.5-flash",
|
||||
model="gemini/gemini-3.6-flash",
|
||||
api_key="your-api-key",
|
||||
temperature=0.7,
|
||||
top_p=0.9,
|
||||
top_k=40, # Top-k sampling parameter
|
||||
max_output_tokens=8192,
|
||||
stop_sequences=["END", "STOP"],
|
||||
stream=True, # Enable streaming
|
||||
@@ -524,8 +497,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -542,7 +514,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-1.5-pro",
|
||||
model="gemini/gemini-3.6-flash",
|
||||
project="your-gcp-project-id",
|
||||
location="us-central1" # GCP region
|
||||
)
|
||||
@@ -555,7 +527,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- `GOOGLE_CLOUD_LOCATION`: GCP location (defaults to `us-central1`)
|
||||
|
||||
**Features:**
|
||||
- Native function calling support for Gemini 1.5+ and 2.x models
|
||||
- Native function calling support for compatible Gemini models
|
||||
- Streaming support for real-time responses
|
||||
- Multimodal capabilities (text, images, video)
|
||||
- Safety settings configuration
|
||||
@@ -563,53 +535,24 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- Automatic system instruction handling
|
||||
- Token usage tracking
|
||||
|
||||
**Gemini Models:**
|
||||
|
||||
Google offers a range of powerful models optimized for different use cases.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|--------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| gemini-2.5-flash | 1M tokens | Adaptive thinking, cost efficiency |
|
||||
| gemini-2.5-pro | 1M tokens | Enhanced thinking and reasoning, multimodal understanding |
|
||||
| gemini-2.0-flash | 1M tokens | Next generation features, speed, thinking |
|
||||
| gemini-2.0-flash-thinking | 32,768 tokens | Advanced reasoning with thinking process |
|
||||
| gemini-2.0-flash-lite | 1M tokens | Cost efficiency and low latency |
|
||||
| gemini-1.5-pro | 2M tokens | Best performing, logical reasoning, coding |
|
||||
| gemini-1.5-flash | 1M tokens | Balanced multimodal model, good for most tasks |
|
||||
| gemini-1.5-flash-8b | 1M tokens | Fastest, most cost-efficient |
|
||||
| gemini-1.0-pro | 32,768 tokens | Earlier generation model |
|
||||
|
||||
**Gemma Models:**
|
||||
|
||||
The Gemini API also supports [Gemma models](https://ai.google.dev/gemma/docs) hosted on Google infrastructure.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|----------------|----------------|------------------------------------|
|
||||
| gemma-3-1b | 32,000 tokens | Ultra-lightweight tasks |
|
||||
| gemma-3-4b | 128,000 tokens | Efficient general-purpose tasks |
|
||||
| gemma-3-12b | 128,000 tokens | Balanced performance and efficiency|
|
||||
| gemma-3-27b | 128,000 tokens | High-performance tasks |
|
||||
Google publishes current Gemini IDs, capabilities, and lifecycle stages in
|
||||
the [Gemini model catalog](https://ai.google.dev/gemini-api/docs/models).
|
||||
Check the [deprecation schedule](https://ai.google.dev/gemini-api/docs/deprecations)
|
||||
before choosing a stable or preview model. The Gemini API also hosts
|
||||
[Gemma models](https://ai.google.dev/gemma/docs).
|
||||
|
||||
**Note:** To use Google Gemini, install the required dependencies:
|
||||
```bash
|
||||
uv add "crewai[google-genai]"
|
||||
```
|
||||
|
||||
The full list of models is available in the [Gemini model docs](https://ai.google.dev/gemini-api/docs/models).
|
||||
</Accordion>
|
||||
<Accordion title="Google (Vertex AI)">
|
||||
Get credentials from your Google Cloud Console and save it to a JSON file, then load it with the following code:
|
||||
```python Code
|
||||
import json
|
||||
|
||||
file_path = 'path/to/vertex_ai_service_account.json'
|
||||
|
||||
# Load the JSON file
|
||||
with open(file_path, 'r') as file:
|
||||
vertex_credentials = json.load(file)
|
||||
|
||||
# Convert the credentials to a JSON string
|
||||
vertex_credentials_json = json.dumps(vertex_credentials)
|
||||
Authenticate with [Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc), then configure the native Gemini provider for Vertex AI:
|
||||
```toml .env
|
||||
GOOGLE_GENAI_USE_VERTEXAI=true
|
||||
GOOGLE_CLOUD_PROJECT=<your-project-id>
|
||||
GOOGLE_CLOUD_LOCATION=<location>
|
||||
```
|
||||
|
||||
Example usage in your CrewAI project:
|
||||
@@ -617,27 +560,17 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini-1.5-pro-latest", # or vertex_ai/gemini-1.5-pro-latest
|
||||
temperature=0.7,
|
||||
vertex_credentials=vertex_credentials_json
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
Google offers a range of powerful models optimized for different use cases:
|
||||
Vertex AI availability varies by region. Use the
|
||||
[Vertex AI model catalog](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models)
|
||||
to verify the model ID and location before deployment.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|--------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M tokens | Adaptive thinking, cost efficiency |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M tokens | Enhanced thinking and reasoning, multimodal understanding, advanced coding, and more |
|
||||
| gemini-2.0-flash | 1M tokens | Next generation features, speed, thinking, and realtime streaming |
|
||||
| gemini-2.0-flash-lite | 1M tokens | Cost efficiency and low latency |
|
||||
| gemini-1.5-flash | 1M tokens | Balanced multimodal model, good for most tasks |
|
||||
| gemini-1.5-flash-8B | 1M tokens | Fastest, most cost-efficient, good for high-frequency tasks |
|
||||
| gemini-1.5-pro | 2M tokens | Best performing, wide variety of reasoning tasks including logical reasoning, coding, and creative collaboration |
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
**Note:** This route uses CrewAI's native Gemini integration. Add it as a dependency to your project:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
uv add "crewai[google-genai]"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
@@ -728,7 +661,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
model="bedrock/us.anthropic.claude-sonnet-4-6",
|
||||
region_name="us-east-1"
|
||||
)
|
||||
```
|
||||
@@ -738,7 +671,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
model="bedrock/us.anthropic.claude-sonnet-4-6",
|
||||
aws_access_key_id="your-access-key", # Or set AWS_ACCESS_KEY_ID
|
||||
aws_secret_access_key="your-secret-key", # Or set AWS_SECRET_ACCESS_KEY
|
||||
aws_session_token="your-session-token", # For temporary credentials
|
||||
@@ -783,38 +716,9 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- First message must be from user (automatically handled)
|
||||
- Some models (like Cohere) require conversation to end with user message
|
||||
|
||||
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) is a managed service that provides access to multiple foundation models from top AI companies through a unified API.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|-------------------------|----------------------|-------------------------------------------------------------------|
|
||||
| Amazon Nova Pro | Up to 300k tokens | High-performance, model balancing accuracy, speed, and cost-effectiveness across diverse tasks. |
|
||||
| Amazon Nova Micro | Up to 128k tokens | High-performance, cost-effective text-only model optimized for lowest latency responses. |
|
||||
| Amazon Nova Lite | Up to 300k tokens | High-performance, affordable multimodal processing for images, video, and text with real-time capabilities. |
|
||||
| Claude 3.7 Sonnet | Up to 128k tokens | High-performance, best for complex reasoning, coding & AI agents |
|
||||
| Claude 3.5 Sonnet v2 | Up to 200k tokens | State-of-the-art model specialized in software engineering, agentic capabilities, and computer interaction at optimized cost. |
|
||||
| Claude 3.5 Sonnet | Up to 200k tokens | High-performance model delivering superior intelligence and reasoning across diverse tasks with optimal speed-cost balance. |
|
||||
| Claude 3.5 Haiku | Up to 200k tokens | Fast, compact multimodal model optimized for quick responses and seamless human-like interactions |
|
||||
| Claude 3 Sonnet | Up to 200k tokens | Multimodal model balancing intelligence and speed for high-volume deployments. |
|
||||
| Claude 3 Haiku | Up to 200k tokens | Compact, high-speed multimodal model optimized for quick responses and natural conversational interactions |
|
||||
| Claude 3 Opus | Up to 200k tokens | Most advanced multimodal model exceling at complex tasks with human-like reasoning and superior contextual understanding. |
|
||||
| Claude 2.1 | Up to 200k tokens | Enhanced version with expanded context window, improved reliability, and reduced hallucinations for long-form and RAG applications |
|
||||
| Claude | Up to 100k tokens | Versatile model excelling in sophisticated dialogue, creative content, and precise instruction following. |
|
||||
| Claude Instant | Up to 100k tokens | Fast, cost-effective model for everyday tasks like dialogue, analysis, summarization, and document Q&A |
|
||||
| Llama 3.1 405B Instruct | Up to 128k tokens | Advanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks. |
|
||||
| Llama 3.1 70B Instruct | Up to 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| Llama 3.1 8B Instruct | Up to 128k tokens | Advanced state-of-the-art model with language understanding, superior reasoning, and text generation. |
|
||||
| Llama 3 70B Instruct | Up to 8k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| Llama 3 8B Instruct | Up to 8k tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| Titan Text G1 - Lite | Up to 4k tokens | Lightweight, cost-effective model optimized for English tasks and fine-tuning with focus on summarization and content generation. |
|
||||
| Titan Text G1 - Express | Up to 8k tokens | Versatile model for general language tasks, chat, and RAG applications with support for English and 100+ languages. |
|
||||
| Cohere Command | Up to 4k tokens | Model specialized in following user commands and delivering practical enterprise solutions. |
|
||||
| Jurassic-2 Mid | Up to 8,191 tokens | Cost-effective model balancing quality and affordability for diverse language tasks like Q&A, summarization, and content generation. |
|
||||
| Jurassic-2 Ultra | Up to 8,191 tokens | Model for advanced text generation and comprehension, excelling in complex tasks like analysis and content creation. |
|
||||
| Jamba-Instruct | Up to 256k tokens | Model with extended context window optimized for cost-effective text generation, summarization, and Q&A. |
|
||||
| Mistral 7B Instruct | Up to 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| Mistral 8x7B Instruct | Up to 32k tokens | An MOE LLM that follows instructions, completes requests, and generates creative text. |
|
||||
| DeepSeek R1 | 32,768 tokens | Advanced reasoning model |
|
||||
|
||||
Amazon Bedrock model access and IDs vary by region. Use AWS's
|
||||
[supported models and regions](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)
|
||||
reference to select a model and verify Converse API support.
|
||||
**Note:** To use AWS Bedrock, install the required dependencies:
|
||||
```bash
|
||||
uv add "crewai[bedrock]"
|
||||
@@ -870,81 +774,14 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nvidia_nim/meta/llama3-70b-instruct",
|
||||
model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
Nvidia NIM provides a comprehensive suite of models for various use cases, from general-purpose tasks to specialized applications.
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|-------------------------------------------------------------------------|----------------|-------------------------------------------------------------------|
|
||||
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8,192 tokens | State-of-the-art small language model delivering superior accuracy for chatbot, virtual assistants, and content generation. |
|
||||
| nvidia/nemotron-4-mini-hindi-4b-instruct | 4,096 tokens | A bilingual Hindi-English SLM for on-device inference, tailored specifically for Hindi Language. |
|
||||
| nvidia/llama-3.1-nemotron-70b-instruct | 128k tokens | Customized for enhanced helpfulness in responses |
|
||||
| nvidia/llama3-chatqa-1.5-8b | 128k tokens | Advanced LLM to generate high-quality, context-aware responses for chatbots and search engines. |
|
||||
| nvidia/llama3-chatqa-1.5-70b | 128k tokens | Advanced LLM to generate high-quality, context-aware responses for chatbots and search engines. |
|
||||
| nvidia/vila | 128k tokens | Multi-modal vision-language model that understands text/img/video and creates informative responses |
|
||||
| nvidia/neva-22 | 4,096 tokens | Multi-modal vision-language model that understands text/images and generates informative responses |
|
||||
| nvidia/nemotron-mini-4b-instruct | 8,192 tokens | General-purpose tasks |
|
||||
| nvidia/usdcode-llama3-70b-instruct | 128k tokens | State-of-the-art LLM that answers OpenUSD knowledge queries and generates USD-Python code. |
|
||||
| nvidia/nemotron-4-340b-instruct | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| meta/codellama-70b | 100k tokens | LLM capable of generating code from natural language and vice versa. |
|
||||
| meta/llama2-70b | 4,096 tokens | Cutting-edge large language AI model capable of generating text and code in response to prompts. |
|
||||
| meta/llama3-8b-instruct | 8,192 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama3-70b-instruct | 8,192 tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| meta/llama-3.1-8b-instruct | 128k tokens | Advanced state-of-the-art model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.1-70b-instruct | 128k tokens | Powers complex conversations with superior contextual understanding, reasoning and text generation. |
|
||||
| meta/llama-3.1-405b-instruct | 128k tokens | Advanced LLM for synthetic data generation, distillation, and inference for chatbots, coding, and domain-specific tasks. |
|
||||
| meta/llama-3.2-1b-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-3b-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-11b-vision-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| meta/llama-3.2-90b-vision-instruct | 128k tokens | Advanced state-of-the-art small language model with language understanding, superior reasoning, and text generation. |
|
||||
| google/gemma-7b | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2b | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/codegemma-7b | 8,192 tokens | Cutting-edge model built on Google's Gemma-7B specialized for code generation and code completion. |
|
||||
| google/codegemma-1.1-7b | 8,192 tokens | Advanced programming model for code generation, completion, reasoning, and instruction following. |
|
||||
| google/recurrentgemma-2b | 8,192 tokens | Novel recurrent architecture based language model for faster inference when generating long sequences. |
|
||||
| google/gemma-2-9b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2-27b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/gemma-2-2b-it | 8,192 tokens | Cutting-edge text generation model text understanding, transformation, and code generation. |
|
||||
| google/deplot | 512 tokens | One-shot visual language understanding model that translates images of plots into tables. |
|
||||
| google/paligemma | 8,192 tokens | Vision language model adept at comprehending text and visual inputs to produce informative responses. |
|
||||
| mistralai/mistral-7b-instruct-v0.2 | 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| mistralai/mixtral-8x7b-instruct-v0.1 | 8,192 tokens | An MOE LLM that follows instructions, completes requests, and generates creative text. |
|
||||
| mistralai/mistral-large | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| mistralai/mixtral-8x22b-instruct-v0.1 | 8,192 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| mistralai/mistral-7b-instruct-v0.3 | 32k tokens | This LLM follows instructions, completes requests, and generates creative text. |
|
||||
| nv-mistralai/mistral-nemo-12b-instruct | 128k tokens | Most advanced language model for reasoning, code, multilingual tasks; runs on a single GPU. |
|
||||
| mistralai/mamba-codestral-7b-v0.1 | 256k tokens | Model for writing and interacting with code across a wide range of programming languages and tasks. |
|
||||
| microsoft/phi-3-mini-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-mini-4k-instruct | 4,096 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-small-8k-instruct | 8,192 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-small-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-medium-4k-instruct | 4,096 tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3-medium-128k-instruct | 128K tokens | Lightweight, state-of-the-art open LLM with strong math and logical reasoning skills. |
|
||||
| microsoft/phi-3.5-mini-instruct | 128K tokens | Lightweight multilingual LLM powering AI applications in latency bound, memory/compute constrained environments |
|
||||
| microsoft/phi-3.5-moe-instruct | 128K tokens | Advanced LLM based on Mixture of Experts architecture to deliver compute efficient content generation |
|
||||
| microsoft/kosmos-2 | 1,024 tokens | Groundbreaking multimodal model designed to understand and reason about visual elements in images. |
|
||||
| microsoft/phi-3-vision-128k-instruct | 128k tokens | Cutting-edge open multimodal model exceling in high-quality reasoning from images. |
|
||||
| microsoft/phi-3.5-vision-instruct | 128k tokens | Cutting-edge open multimodal model exceling in high-quality reasoning from images. |
|
||||
| databricks/dbrx-instruct | 12k tokens | A general-purpose LLM with state-of-the-art performance in language understanding, coding, and RAG. |
|
||||
| snowflake/arctic | 1,024 tokens | Delivers high efficiency inference for enterprise applications focused on SQL generation and coding. |
|
||||
| aisingapore/sea-lion-7b-instruct | 4,096 tokens | LLM to represent and serve the linguistic and cultural diversity of Southeast Asia |
|
||||
| ibm/granite-8b-code-instruct | 4,096 tokens | Software programming LLM for code generation, completion, explanation, and multi-turn conversion. |
|
||||
| ibm/granite-34b-code-instruct | 8,192 tokens | Software programming LLM for code generation, completion, explanation, and multi-turn conversion. |
|
||||
| ibm/granite-3.0-8b-instruct | 4,096 tokens | Advanced Small Language Model supporting RAG, summarization, classification, code, and agentic AI |
|
||||
| ibm/granite-3.0-3b-a800m-instruct | 4,096 tokens | Highly efficient Mixture of Experts model for RAG, summarization, entity extraction, and classification |
|
||||
| mediatek/breeze-7b-instruct | 4,096 tokens | Creates diverse synthetic data that mimics the characteristics of real-world data. |
|
||||
| upstage/solar-10.7b-instruct | 4,096 tokens | Excels in NLP tasks, particularly in instruction-following, reasoning, and mathematics. |
|
||||
| writer/palmyra-med-70b-32k | 32k tokens | Leading LLM for accurate, contextually relevant responses in the medical domain. |
|
||||
| writer/palmyra-med-70b | 32k tokens | Leading LLM for accurate, contextually relevant responses in the medical domain. |
|
||||
| writer/palmyra-fin-70b-32k | 32k tokens | Specialized LLM for financial analysis, reporting, and data processing |
|
||||
| 01-ai/yi-large | 32k tokens | Powerful model trained on English and Chinese for diverse tasks including chatbot and creative writing. |
|
||||
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k tokens | Powerful coding model offering advanced capabilities in code generation, completion, and infilling |
|
||||
| rakuten/rakutenai-7b-instruct | 1,024 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| rakuten/rakutenai-7b-chat | 1,024 tokens | Advanced state-of-the-art LLM with language understanding, superior reasoning, and text generation. |
|
||||
| baichuan-inc/baichuan2-13b-chat | 4,096 tokens | Support Chinese and English chat, coding, math, instruction following, solving quizzes |
|
||||
NVIDIA NIM's hosted catalog changes frequently. Use the
|
||||
[NVIDIA NIM model catalog](https://build.nvidia.com/models) to select a
|
||||
current endpoint and verify its model ID, modalities, and context limits.
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
```bash
|
||||
@@ -1062,15 +899,15 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="groq/llama-3.2-90b-text-preview",
|
||||
model="groq/qwen/qwen3.6-27b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| Model | Context Window | Best For |
|
||||
|-------------------|------------------|--------------------------------------------|
|
||||
| Llama 3.1 70B/8B | 131,072 tokens | High-performance, large context tasks |
|
||||
| Llama 3.2 Series | 8,192 tokens | General-purpose tasks |
|
||||
| Mixtral 8x7B | 32,768 tokens | Balanced performance and context |
|
||||
|
||||
Groq distinguishes production and preview models and retires model IDs
|
||||
regularly. Check the [Groq model catalog](https://console.groq.com/docs/models)
|
||||
and [deprecation page](https://console.groq.com/docs/deprecations) before
|
||||
selecting a model for production.
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
```bash
|
||||
@@ -1152,11 +989,14 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="llama-3.1-sonar-large-128k-online",
|
||||
base_url="https://api.perplexity.ai/"
|
||||
model="perplexity/sonar-pro"
|
||||
)
|
||||
```
|
||||
|
||||
See the [Perplexity model catalog](https://docs.perplexity.ai/getting-started/models)
|
||||
and [changelog](https://docs.perplexity.ai/docs/resources/changelog) for
|
||||
current model IDs and deprecation notices.
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -1192,17 +1032,14 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sambanova/Meta-Llama-3.1-8B-Instruct",
|
||||
model="sambanova/Meta-Llama-3.3-70B-Instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| Model | Context Window | Best For |
|
||||
|--------------------|------------------------|----------------------------------------------|
|
||||
| Llama 3.1 70B/8B | Up to 131,072 tokens | High-performance, large context tasks |
|
||||
| Llama 3.1 405B | 8,192 tokens | High-performance and output quality |
|
||||
| Llama 3.2 Series | 8,192 tokens | General-purpose, multimodal tasks |
|
||||
| Llama 3.3 70B | Up to 131,072 tokens | High-performance and output quality |
|
||||
| Qwen2 familly | 8,192 tokens | High-performance and output quality |
|
||||
SambaNova Cloud's hosted models can change independently of CrewAI. Query
|
||||
the [models endpoint](https://docs.sambanova.ai/docs/api-reference/models/get-environments-available-model-list-metadata)
|
||||
and check the [deprecation guide](https://docs.sambanova.ai/docs/en/models/deprecations)
|
||||
before deployment.
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
```bash
|
||||
@@ -1220,7 +1057,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
Example usage in your CrewAI project:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="cerebras/llama3.1-70b",
|
||||
model="cerebras/gpt-oss-120b",
|
||||
temperature=0.7,
|
||||
max_tokens=8192
|
||||
)
|
||||
@@ -1234,6 +1071,10 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
- Support for long context windows
|
||||
</Info>
|
||||
|
||||
See the [Cerebras model catalog](https://inference-docs.cerebras.ai/models/overview)
|
||||
and [deprecation notices](https://inference-docs.cerebras.ai/support/deprecation)
|
||||
for current public endpoint IDs.
|
||||
|
||||
**Note:** This provider uses LiteLLM. Add it as a dependency to your project:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -1308,7 +1149,7 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
|
||||
|
||||
# Create an LLM with streaming enabled
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
stream=True # Enable streaming
|
||||
)
|
||||
```
|
||||
@@ -1358,7 +1199,7 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
|
||||
|
||||
my_listener = MyCustomListener()
|
||||
|
||||
llm = LLM(model="gpt-4o-mini", temperature=0, stream=True)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", stream=True)
|
||||
|
||||
researcher = Agent(
|
||||
role="About User",
|
||||
@@ -1438,6 +1279,8 @@ CrewAI supports asynchronous LLM calls for improved performance and concurrency
|
||||
|
||||
CrewAI supports structured responses from LLM calls by allowing you to define a `response_format` using a Pydantic model. This enables the framework to automatically parse and validate the output, making it easier to integrate the response into your application without manual post-processing.
|
||||
|
||||
Structured output support varies by provider and model. Test your chosen model before relying on structured responses in production.
|
||||
|
||||
For example, you can define a Pydantic model to represent the expected response structure and pass it as the `response_format` when instantiating the LLM. The model will then be used to convert the LLM output into a structured Python object.
|
||||
|
||||
```python Code
|
||||
@@ -1449,7 +1292,7 @@ class Dog(BaseModel):
|
||||
breed: str
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o", response_format=Dog)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", response_format=Dog)
|
||||
|
||||
response = llm.call(
|
||||
"Analyze the following messages and return the name, age, and breed. "
|
||||
@@ -1478,8 +1321,8 @@ Learn how to get the most out of your LLM configuration:
|
||||
# 3. Task splitting for large contexts
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
max_tokens=4000, # Limit response length
|
||||
model="openai/gpt-5.6-terra",
|
||||
max_completion_tokens=4000, # Limit response length
|
||||
)
|
||||
```
|
||||
|
||||
@@ -1503,15 +1346,16 @@ Learn how to get the most out of your LLM configuration:
|
||||
```python
|
||||
# Configure model with appropriate settings
|
||||
llm = LLM(
|
||||
model="openai/gpt-4-turbo-preview",
|
||||
temperature=0.7, # Adjust based on task
|
||||
max_tokens=4096, # Set based on output needs
|
||||
timeout=300 # Longer timeout for complex tasks
|
||||
model="openai/gpt-5.6-terra",
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4096,
|
||||
timeout=300
|
||||
)
|
||||
```
|
||||
<Tip>
|
||||
- Lower temperature (0.1 to 0.3) for factual responses
|
||||
- Higher temperature (0.7 to 0.9) for creative tasks
|
||||
Use the controls supported by your selected model. Depending on the
|
||||
provider, this may be `temperature`, a reasoning or thinking level,
|
||||
or prompt instructions that define the desired style and variability.
|
||||
</Tip>
|
||||
</Step>
|
||||
|
||||
|
||||
@@ -24,15 +24,23 @@ You often need **both**: skills for expertise, tools for action. They are config
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Create a Skill Directory
|
||||
### 1. Create a Skill with the CLI
|
||||
|
||||
The CLI is the supported way to create a skill — it scaffolds the directory layout and a valid `SKILL.md` for you:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create code-review
|
||||
```
|
||||
|
||||
Inside a crew project (where `pyproject.toml` lives) this creates `./skills/code-review/`; outside a project it creates `./code-review/` in the current directory (you can force that behavior with `--no-project`):
|
||||
|
||||
```
|
||||
skills/
|
||||
└── code-review/
|
||||
├── SKILL.md # Required — instructions
|
||||
├── SKILL.md # Required — instructions (pre-filled template)
|
||||
├── references/ # Optional — reference docs
|
||||
│ └── style-guide.md
|
||||
└── scripts/ # Optional — executable scripts
|
||||
├── scripts/ # Optional — executable scripts
|
||||
└── assets/ # Optional — static files
|
||||
```
|
||||
|
||||
### 2. Write Your SKILL.md
|
||||
@@ -164,6 +172,93 @@ agent = Agent(
|
||||
|
||||
---
|
||||
|
||||
## Creating, Publishing, and Installing Skills
|
||||
|
||||
Skills have a full lifecycle managed by the CLI: **create them with `crewai skill create`, publish them with `crewai skill publish`** — hand-rolling directories works for local experiments, but the CLI is the intended workflow and keeps your skill layout and frontmatter valid.
|
||||
|
||||
### Create
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create my-skill
|
||||
```
|
||||
|
||||
Scaffolds the directory (into `./skills/` inside a crew project) with a template `SKILL.md`, plus empty `scripts/`, `references/`, and `assets/` directories. Edit `SKILL.md` to define the instructions.
|
||||
|
||||
### Publish
|
||||
|
||||
Run from inside the skill directory (where `SKILL.md` is):
|
||||
|
||||
```shell Terminal
|
||||
cd skills/my-skill
|
||||
crewai skill publish
|
||||
```
|
||||
|
||||
Publishing reads `name`, `description`, and `metadata.version` from the `SKILL.md` frontmatter and pushes the skill to the CrewAI registry. **Published skills are always scoped to your organization** — like tools, only members of the publishing org can see and install them; there is no public visibility. Useful flags:
|
||||
|
||||
| Flag | Effect |
|
||||
| :--- | :--- |
|
||||
| `--org <slug>` | Publish under a specific organization (overrides settings). |
|
||||
| `--force` | Skip git-state validation (uncommitted changes, etc.). |
|
||||
|
||||
### Install
|
||||
|
||||
Install a published skill by its `@org/name` reference:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill install @acme/code-review
|
||||
```
|
||||
|
||||
Inside a crew project the skill lands in `./skills/{name}/`; outside a project it goes to the shared cache at `~/.crewai/skills/{org}/{name}/`.
|
||||
|
||||
Agents can also reference registry skills directly — they resolve from the local cache (or project `skills/` directory) at runtime:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Senior Code Reviewer",
|
||||
goal="Review pull requests for quality and security issues",
|
||||
backstory="Staff engineer with expertise in secure coding practices.",
|
||||
skills=["@acme/code-review"], # registry ref, resolved locally
|
||||
)
|
||||
```
|
||||
|
||||
### Pin a Version
|
||||
|
||||
An unpinned reference resolves to the newest published version, so publishing a
|
||||
new version changes every agent that references it. Append `@<version>` to pin
|
||||
one instead:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Senior Code Reviewer",
|
||||
goal="Review pull requests for quality and security issues",
|
||||
backstory="Staff engineer with expertise in secure coding practices.",
|
||||
skills=["@acme/code-review@1.2.0"], # pinned; a leading "v" also works
|
||||
)
|
||||
```
|
||||
|
||||
A pinned reference re-downloads unless the copy it finds is that exact version —
|
||||
a pin asks for a specific version rather than hinting at one. A cached skill is
|
||||
matched on the version recorded when it was installed, so it needs nothing in
|
||||
its frontmatter; a project-local copy under `skills/` has no such record, so it
|
||||
is matched on `metadata.version` in its `SKILL.md` frontmatter. Pinning an
|
||||
unpublished version fails rather than falling back to the latest.
|
||||
|
||||
<Note>
|
||||
Agents from the **Agent Repository** are pinned automatically: the repository
|
||||
records a version alongside each skill it assigns, and the runtime applies those
|
||||
pins when it loads the agent.
|
||||
</Note>
|
||||
|
||||
### List
|
||||
|
||||
```shell Terminal
|
||||
crewai skill list
|
||||
```
|
||||
|
||||
Shows installed skills from both the project `./skills/` directory and the global cache, with their versions and paths.
|
||||
|
||||
---
|
||||
|
||||
## Crew-Level Skills
|
||||
|
||||
Skills can be set on a crew to apply to **all agents**:
|
||||
|
||||
137
docs/edge/en/concepts/streaming.mdx
Normal file
@@ -0,0 +1,137 @@
|
||||
---
|
||||
title: Streaming
|
||||
description: Understand CrewAI's streaming model for Flows, direct LLM calls, tools, and conversational turns.
|
||||
icon: radio
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Streaming lets your application receive execution updates while work is still running. Instead of waiting for the final result, you can render LLM tokens, tool activity, Flow lifecycle events, and conversation messages as they happen.
|
||||
|
||||
CrewAI has two streaming surfaces:
|
||||
|
||||
| Surface | Used by | Output |
|
||||
|---------|---------|--------|
|
||||
| Frame streaming | Flows, direct LLM calls, conversational turns | Ordered `StreamFrame` objects |
|
||||
| Crew chunk streaming | Crews with `stream=True` | `CrewStreamingOutput` chunks |
|
||||
|
||||
For new runtime integrations, UIs, terminal apps, service bridges, and conversational surfaces, use frame streaming. It provides one stable event envelope across the runtime.
|
||||
|
||||
## StreamFrame
|
||||
|
||||
A `StreamFrame` is the common object emitted by streamable runtimes:
|
||||
|
||||
```python
|
||||
frame.id # unique frame id
|
||||
frame.seq # execution-local order, when available
|
||||
frame.type # source event type, such as "llm_stream_chunk"
|
||||
frame.channel # "llm", "flow", "tools", "messages", "lifecycle", or "custom"
|
||||
frame.namespace # source/runtime namespace
|
||||
frame.timestamp # event timestamp
|
||||
frame.parent_id # parent event id, when available
|
||||
frame.previous_id # previous event id, when available
|
||||
frame.data # structured event payload
|
||||
frame.event # alias for frame.data
|
||||
frame.content # printable text for token-like frames, otherwise ""
|
||||
```
|
||||
|
||||
The important fields for most consumers are:
|
||||
|
||||
| Field | Use it for |
|
||||
|-------|------------|
|
||||
| `channel` | Routing frames to the right UI region |
|
||||
| `type` | Handling a specific event inside a channel |
|
||||
| `content` | Printing token-like text |
|
||||
| `event` | Reading structured metadata, such as tool names or message roles |
|
||||
| `seq` | Preserving execution order |
|
||||
|
||||
## Channels
|
||||
|
||||
Frames are grouped into high-level channels:
|
||||
|
||||
| Channel | Contains |
|
||||
|---------|----------|
|
||||
| `llm` | LLM call lifecycle, text chunks, and thinking chunks |
|
||||
| `flow` | Flow lifecycle, method execution, routing, pause, and resume events |
|
||||
| `tools` | Tool usage start, finish, and error events |
|
||||
| `messages` | Conversation transcript events |
|
||||
| `lifecycle` | Runtime lifecycle events that do not belong to another channel |
|
||||
| `custom` | Events that do not map to a built-in channel |
|
||||
|
||||
The stream itself remains one ordered timeline. Channel projections let consumers focus on only part of that timeline.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["flow<br/>flow_started"] --> B["llm<br/>llm_call_started"]
|
||||
B --> C["llm<br/>llm_stream_chunk"]
|
||||
C --> D["tools<br/>tool_usage_started"]
|
||||
D --> E["tools<br/>tool_usage_finished"]
|
||||
E --> F["llm<br/>llm_stream_chunk"]
|
||||
F --> G["flow<br/>flow_finished"]
|
||||
```
|
||||
|
||||
## Stream Sessions
|
||||
|
||||
Frame streaming returns a stream session:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events(inputs={"topic": "AI agents"})
|
||||
```
|
||||
|
||||
The session is both an iterator and the holder for the final result:
|
||||
|
||||
```python
|
||||
with stream:
|
||||
for frame in stream:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
Consume the stream before reading `stream.result`. Reading the result too early raises an error because the runtime may still be producing frames.
|
||||
|
||||
## Channel Projections
|
||||
|
||||
Use channel projections when you only need one kind of frame:
|
||||
|
||||
```python
|
||||
with flow.stream_events(inputs={"topic": "AI agents"}) as stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
Available projections:
|
||||
|
||||
| Projection | Frames |
|
||||
|------------|--------|
|
||||
| `stream.events` | All frames |
|
||||
| `stream.llm` | LLM frames |
|
||||
| `stream.flow` | Flow frames |
|
||||
| `stream.tools` | Tool frames |
|
||||
| `stream.messages` | Conversation message frames |
|
||||
| `stream.interleave([...])` | Selected channels in relative order |
|
||||
|
||||
## Entrypoints
|
||||
|
||||
Use the entrypoint that matches the runtime you are streaming:
|
||||
|
||||
| Runtime | Streaming entrypoint |
|
||||
|---------|----------------------|
|
||||
| Flow | `flow.stream_events(...)` |
|
||||
| Flow with `stream=True` | `flow.kickoff(...)` returns a stream session |
|
||||
| Async Flow | `flow.astream(...)` or `await flow.kickoff_async(...)` when `stream=True` |
|
||||
| Direct LLM call | `llm.stream_events(...)` |
|
||||
| Conversational Flow turn | `flow.stream_turn(...)` |
|
||||
| Crew | `Crew(..., stream=True).kickoff(...)` returns `CrewStreamingOutput` |
|
||||
|
||||
Direct `llm.call(...)` still returns the final assembled LLM result. Use `llm.stream_events(...)` when you want to iterate over LLM chunks as they arrive.
|
||||
|
||||
## Related Guides
|
||||
|
||||
- [Consuming Streams](/edge/en/learn/consuming-streams)
|
||||
- [Streaming Runtime Contract](/edge/en/learn/streaming-runtime-contract)
|
||||
- [Streaming Flow Execution](/edge/en/learn/streaming-flow-execution)
|
||||
- [Streaming Crew Execution](/edge/en/learn/streaming-crew-execution)
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
- [Overview](/en/enterprise/features/agent-control-plane/overview)
|
||||
- **Monitoring** *(you are here)*
|
||||
- [Rules](/en/enterprise/features/agent-control-plane/rules)
|
||||
- [Policies](/edge/en/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## Overview
|
||||
@@ -58,7 +58,7 @@ The **Automations** sub-tab is the per-deployment breakdown of fleet health. Eac
|
||||
| **Last execution** | Time since the most recent run. |
|
||||
| **Health Status Breakdown** | Stacked bar of `Critical` / `Warning` / `Healthy` percentages for executions in the window. |
|
||||
| **Executions with Errors** | Total failed executions in the window. |
|
||||
| **PII detection applied** | `Yes` if a per-deployment PII config or a matching [PII rule](/en/enterprise/features/agent-control-plane/rules) is active. |
|
||||
| **PII detection applied** | `Yes` if a per-deployment PII config or a matching [PII policy](/edge/en/enterprise/features/agent-control-plane/policies) is active. |
|
||||
| **Executions** | Total executions in the window. |
|
||||
| **Last updated** | When the deployment was last re-deployed. |
|
||||
| **Crew Version** | The `crewai` version reported by the deployment. An info icon next to versions below `1.13` flags rows that can't contribute metrics. |
|
||||
@@ -96,8 +96,8 @@ Filter by **LLM provider** and sort by `Cost`, `Executions`, or `Last run`.
|
||||
<Card title="Agent Control Plane — Overview" icon="book-open" href="/en/enterprise/features/agent-control-plane/overview">
|
||||
What ACP is, requirements, plan tiers, and RBAC.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — Rules" icon="shield-check" href="/en/enterprise/features/agent-control-plane/rules">
|
||||
Apply organization-wide PII Redaction rules across many automations.
|
||||
<Card title="Agent Control Plane — Policies" icon="shield-check" href="/edge/en/enterprise/features/agent-control-plane/policies">
|
||||
Apply organization-wide PII Redaction policies across many automations.
|
||||
</Card>
|
||||
<Card title="Traces" icon="timeline" href="/en/enterprise/features/traces">
|
||||
Drill into a single execution to see agent reasoning, tool calls, and token usage.
|
||||
|
||||
@@ -10,17 +10,17 @@ icon: "book-open"
|
||||
|
||||
- **Overview** *(you are here)*
|
||||
- [Monitoring](/en/enterprise/features/agent-control-plane/monitoring)
|
||||
- [Rules](/en/enterprise/features/agent-control-plane/rules)
|
||||
- [Policies](/edge/en/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## Overview
|
||||
|
||||
The **Agent Control Plane** (ACP) is the operations hub for everything you have running on CrewAI AMP. It is a single screen — split into **Automations** and **Rules** tabs — that lets your team:
|
||||
The **Agent Control Plane** (ACP) is the operations hub for everything you have running on CrewAI AMP. It is a single screen — split into **Automations** and **Policies** tabs — that lets your team:
|
||||
|
||||
- Monitor the **health** of every live automation (crew or flow), with `Critical` / `Warning` / `Healthy` breakdowns and execution counts.
|
||||
- Track **LLM consumption** — tokens and cost — per automation, per provider, and per model, with a delta vs the previous period.
|
||||
- Drill into any single automation or model provider for time-series charts and per-provider breakdowns.
|
||||
- Apply organization-wide **Rules** (today: PII Redaction and Cost Limit) across many automations at once instead of editing each deployment individually.
|
||||
- Apply organization-wide **Policies** (today: PII Redaction and Cost Limit) across many automations at once instead of editing each deployment individually.
|
||||
|
||||
<Frame>
|
||||

|
||||
@@ -33,7 +33,7 @@ The **Agent Control Plane** (ACP) is the operations hub for everything you have
|
||||
The two tabs answer two different questions:
|
||||
|
||||
- **Automations** — *"How is my fleet behaving right now, and what is it costing me?"* See [Monitoring](/en/enterprise/features/agent-control-plane/monitoring).
|
||||
- **Rules** — *"How do I enforce a policy (e.g. PII redaction or a spend budget) across many deployments without re-deploying each one?"* See [Rules](/en/enterprise/features/agent-control-plane/rules).
|
||||
- **Policies** — *"How do I enforce a policy (e.g. PII redaction or a spend budget) across many deployments without re-deploying each one?"* See [Policies](/edge/en/enterprise/features/agent-control-plane/policies).
|
||||
|
||||
## Requirements
|
||||
|
||||
@@ -42,11 +42,11 @@ The two tabs answer two different questions:
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
**Enterprise Plan or Ultra Plan** is required to create or edit **PII Redaction** [Rules](/en/enterprise/features/agent-control-plane/rules). Lower-tier organizations can open the Rules tab and view existing rules, but the PII editor renders read-only with an "Enterprise" lock pill and the alert *"PII Redaction rules require an Enterprise plan."* **Cost Limit** rules and Monitoring (the Automations tab) are available on all plans where the feature is enabled.
|
||||
**Enterprise Plan or Ultra Plan** is required to create or edit **PII Redaction** [Policies](/edge/en/enterprise/features/agent-control-plane/policies). Lower-tier organizations can open the Policies tab and view existing policies, but the PII editor renders read-only with an "Enterprise" lock pill and the alert *"PII Redaction policies require an Enterprise plan."* **Cost Limit** policies and Monitoring (the Automations tab) are available on all plans where the feature is enabled.
|
||||
</Warning>
|
||||
|
||||
- The **Agent Control Plane** feature must be enabled for your organization. If you don't see it in the sidebar, ask your account owner to request enablement.
|
||||
- Inside ACP, [RBAC](/en/enterprise/features/rbac) governs access: `read` to view the dashboard and rules, `manage` to create, edit, toggle, or delete rules.
|
||||
- Inside ACP, [RBAC](/en/enterprise/features/rbac) governs access: `read` to view the dashboard and policies, `manage` to create, edit, toggle, or delete policies.
|
||||
- All charts and tables can be scoped to the **Last 24 hours**, **Last Week**, or **Last 30 days** using the time selector at the top right. Deltas (`↑ 8 vs yesterday`, `↓ $20.57 vs yesterday`, etc.) compare the selected window against the previous one of the same length.
|
||||
|
||||
## What you can do here
|
||||
@@ -55,7 +55,7 @@ The two tabs answer two different questions:
|
||||
<Card title="Monitoring" icon="gauge" href="/en/enterprise/features/agent-control-plane/monitoring">
|
||||
Watch fleet health and LLM spend with metric cards, an interactive sankey, per-automation tables, and drill-down side panels for any automation or provider.
|
||||
</Card>
|
||||
<Card title="Rules" icon="shield-check" href="/en/enterprise/features/agent-control-plane/rules">
|
||||
<Card title="Policies" icon="shield-check" href="/edge/en/enterprise/features/agent-control-plane/policies">
|
||||
Apply organization-wide PII Redaction and Cost Limit policies scoped by tools and tags. Changes take effect on the next execution — no re-deploy required.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -67,10 +67,10 @@ The two tabs answer two different questions:
|
||||
Drill into a single execution to see agent reasoning, tool calls, and token usage.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/en/enterprise/features/rbac">
|
||||
Manage who can read the Agent Control Plane and who can edit rules.
|
||||
Manage who can read the Agent Control Plane and who can edit policies.
|
||||
</Card>
|
||||
<Card title="PII Redaction for Traces" icon="lock" href="/en/enterprise/features/pii-trace-redactions">
|
||||
Entity catalog and per-deployment PII configuration referenced by Rules.
|
||||
Entity catalog and per-deployment PII configuration referenced by Policies.
|
||||
</Card>
|
||||
<Card title="Deploy to AMP" icon="rocket" href="/en/enterprise/guides/deploy-to-amp">
|
||||
Deploy a crew on a crewAI version that supports the Agent Control Plane.
|
||||
@@ -78,5 +78,5 @@ The two tabs answer two different questions:
|
||||
</CardGroup>
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for help interpreting metrics or designing rules.
|
||||
Contact our support team for help interpreting metrics or designing policies.
|
||||
</Card>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "Set up the Rules"
|
||||
title: "Set up the Policies"
|
||||
description: "Apply organization-wide policies across many automations from a single place."
|
||||
sidebarTitle: "Rules"
|
||||
sidebarTitle: "Policies"
|
||||
icon: "shield-check"
|
||||
mode: "wide"
|
||||
---
|
||||
@@ -11,39 +11,39 @@ mode: "wide"
|
||||
|
||||
- [Overview](/en/enterprise/features/agent-control-plane/overview)
|
||||
- [Monitoring](/en/enterprise/features/agent-control-plane/monitoring)
|
||||
- **Rules** *(you are here)*
|
||||
- **Policies** *(you are here)*
|
||||
</Info>
|
||||
|
||||
## Overview
|
||||
|
||||
Rules let you apply policies — today **PII Redaction** and **Cost Limit** — across many automations at once, instead of configuring each deployment individually. Open the **Rules** tab in the [Agent Control Plane](/en/enterprise/features/agent-control-plane/overview) to manage them.
|
||||
Policies let you enforce organization-wide controls — today **PII Redaction** and **Cost Limit** — across many automations at once, instead of configuring each deployment individually. Open the **Policies** tab in the [Agent Control Plane](/en/enterprise/features/agent-control-plane/overview) to manage them.
|
||||
|
||||
<Frame>
|
||||

|
||||

|
||||
</Frame>
|
||||
|
||||
Each rule card shows the name, description, the **scope** the rule applies to (selected tools and tags), and a count of **engaged automations** — deployments that currently match the scope. The toggle on the right enables or disables the rule without deleting it.
|
||||
Each policy card shows the name, description, the **scope** the policy applies to (selected tools and tags), and a count of **engaged automations** — deployments that currently match the scope. The toggle on the right enables or disables the policy without deleting it.
|
||||
|
||||
## Requirements
|
||||
|
||||
<Warning>
|
||||
**Enterprise Plan or Ultra Plan** is required to create or edit **PII Redaction** rules. Lower-tier organizations can still open the Rules tab and view existing rules, but the PII editor renders read-only with an "Enterprise" lock pill and the alert *"PII Redaction rules require an Enterprise plan."* — contact your account owner or sales to upgrade. **Cost Limit** rules are **not** plan-gated and can be created on any plan where the Agent Control Plane is enabled.
|
||||
**Enterprise Plan or Ultra Plan** is required to create or edit **PII Redaction** policies. Lower-tier organizations can still open the Policies tab and view existing policies, but the PII editor renders read-only with an "Enterprise" lock pill and the alert *"PII Redaction policies require an Enterprise plan."* — contact your account owner or sales to upgrade. **Cost Limit** policies are **not** plan-gated and can be created on any plan where the Agent Control Plane is enabled.
|
||||
</Warning>
|
||||
|
||||
- The **Agent Control Plane** feature must be enabled for your organization. See [Overview — Requirements](/en/enterprise/features/agent-control-plane/overview#requirements).
|
||||
- The `manage` [RBAC permission](/en/enterprise/features/rbac) on Agent Control Plane is required to create, edit, toggle, or delete rules. The `read` permission is enough to view them.
|
||||
- All rule changes are versioned for auditing.
|
||||
- The `manage` [RBAC permission](/en/enterprise/features/rbac) on Agent Control Plane is required to create, edit, toggle, or delete policies. The `read` permission is enough to view them.
|
||||
- All policy changes are versioned for auditing.
|
||||
|
||||
## Rule types
|
||||
## Policy types
|
||||
|
||||
Every rule is one of the types below. Open the tab for the policy you want to enforce.
|
||||
Every policy is one of the types below. Open the tab for the policy you want to enforce.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="PII Redaction">
|
||||
Applies PII redaction to executions of every matching automation, using the same entity catalog and custom recognizers documented in [PII Redaction for Traces](/en/enterprise/features/pii-trace-redactions).
|
||||
|
||||
<Warning>
|
||||
Creating or editing PII Redaction rules requires an **Enterprise** or **Ultra** plan. On lower tiers the PII editor renders read-only with an "Enterprise" lock pill.
|
||||
Creating or editing PII Redaction policies requires an **Enterprise** or **Ultra** plan. On lower tiers the PII editor renders read-only with an "Enterprise" lock pill.
|
||||
</Warning>
|
||||
|
||||
**Configuration** — in the **PII Mask Type** table, check each entity type you want covered and choose how to handle it:
|
||||
@@ -58,7 +58,7 @@ See [PII Redaction for Traces](/en/enterprise/features/pii-trace-redactions) for
|
||||
Emails the recipients you choose when a matching automation's LLM spend exceeds a budget threshold in the selected period. Available on **all plans** where the Agent Control Plane is enabled — it is not Enterprise-gated.
|
||||
|
||||
<Warning>
|
||||
Cost Limit rules are **notify-only**. They never pause, throttle, or stop a run — they only send an email so a human can decide what to do. Adjust the budget or remove the rule if you no longer want the alert.
|
||||
Cost Limit policies are **notify-only**. They never pause, throttle, or stop a run — they only send an email so a human can decide what to do. Adjust the budget or remove the policy if you no longer want the alert.
|
||||
</Warning>
|
||||
|
||||
**Configuration**
|
||||
@@ -74,7 +74,7 @@ Cost Limit rules are **notify-only**. They never pause, throttle, or stop a run
|
||||
**How spend is measured and matched**
|
||||
|
||||
- The threshold is evaluated **per automation**, not summed across the whole scope. Each engaged automation has its own running total for the period.
|
||||
- A rule can match many automations via its conditions (tools/tags), and a single automation can be covered by **multiple** Cost Limit rules at once. Each rule tracks its own budget and alert state independently — they don't merge.
|
||||
- A policy can match many automations via its conditions (tools/tags), and a single automation can be covered by **multiple** Cost Limit policies at once. Each policy tracks its own budget and alert state independently — they don't merge.
|
||||
- A background check compares each engaged automation's period-to-date spend against the threshold and sends the email when it's exceeded. Because the check runs periodically, expect a short delay between crossing the threshold and the email arriving.
|
||||
|
||||
**The alert email**
|
||||
@@ -83,76 +83,76 @@ When an automation goes over budget, recipients get an email summarizing the ove
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
More rule types will be added over time.
|
||||
More policy types will be added over time.
|
||||
|
||||
## Creating a rule
|
||||
## Creating a policy
|
||||
|
||||
<Tabs>
|
||||
<Tab title="PII Redaction">
|
||||
<Frame>
|
||||
<img src="/images/enterprise/acp-rules-edit-side-panel.png" alt="New Rule side panel configured for PII Redaction with the PII mask type table" width="450" />
|
||||
<img src="/images/enterprise/acp-policies-new-side-panel.png" alt="New Policy side panel configured for PII Redaction with the PII mask type table" width="450" />
|
||||
</Frame>
|
||||
</Tab>
|
||||
<Tab title="Cost Limit">
|
||||
<Frame>
|
||||
<img src="/images/enterprise/acp-rules-edit-cost-limit.png" alt="New Rule side panel configured for Cost Limit with budget period, threshold, and recipient emails" width="450" />
|
||||
<img src="/images/enterprise/acp-policies-edit-cost-limit.png" alt="New Policy side panel configured for Cost Limit with budget period, threshold, and recipient emails" width="450" />
|
||||
</Frame>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Steps>
|
||||
<Step title="Open the editor">
|
||||
Click **+ Create new** at the top-right of the Rules tab, or **View Details** on an existing rule card.
|
||||
Click **+ Create new** at the top-right of the Policies tab, or **View Details** on an existing policy card.
|
||||
</Step>
|
||||
|
||||
<Step title="Name and describe the rule">
|
||||
Give the rule a clear name (e.g. *Mask PII (CC)* or *Monthly $100 budget*) and a description explaining when it applies. Both show up on the rule card and in the Engaged Automations modal.
|
||||
<Step title="Name and describe the policy">
|
||||
Give the policy a clear name (e.g. *Mask PII (CC)* or *Monthly $100 budget*) and a description explaining when it applies. Both show up on the policy card and in the Engaged Automations modal.
|
||||
</Step>
|
||||
|
||||
<Step title="Pick the type">
|
||||
Choose **PII Redaction** or **Cost Limit**. The type determines which configuration section appears below the conditions. The type is fixed once the rule is created — to switch, create a new rule.
|
||||
Choose **PII Redaction** or **Cost Limit**. The type determines which configuration section appears below the conditions. The type is fixed once the policy is created — to switch, create a new policy.
|
||||
</Step>
|
||||
|
||||
<Step title="Set the conditions">
|
||||
Conditions decide which automations the rule engages with. Both are optional and use **set-equality** semantics:
|
||||
Conditions decide which automations the policy engages with. Both are optional and use **set-equality** semantics:
|
||||
|
||||
- **Tools** — only automations whose tool set **exactly matches** the selected tools will engage. Picks from Studio apps, MCPs, OSS tools, and Tool Repository registry tools.
|
||||
- **Automations** — only automations whose tag set **exactly matches** the selected tags will engage.
|
||||
|
||||
Leaving a picker empty means "no filter on this dimension". Leaving both empty means the rule applies to **every** automation in the organization.
|
||||
Leaving a picker empty means "no filter on this dimension". Leaving both empty means the policy applies to **every** automation in the organization.
|
||||
</Step>
|
||||
|
||||
<Step title="Configure the type-specific section">
|
||||
The editor shows the configuration for the type you picked — the **PII Mask Type** table for PII Redaction, or the budget fields for Cost Limit. See [Rule types](#rule-types) for what each field does.
|
||||
The editor shows the configuration for the type you picked — the **PII Mask Type** table for PII Redaction, or the budget fields for Cost Limit. See [Policy types](#policy-types) for what each field does.
|
||||
</Step>
|
||||
|
||||
<Step title="Save">
|
||||
The rule applies to **future** executions of every engaged automation as soon as you save. No re-deploy is needed.
|
||||
The policy applies to **future** executions of every engaged automation as soon as you save. No re-deploy is needed.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Engaged automations
|
||||
|
||||
Click **Engaged N automations** on any rule card to see exactly which deployments the rule is currently matching, along with each one's last execution.
|
||||
Click **Engaged N automations** on any policy card to see exactly which deployments the policy is currently matching, along with each one's last execution.
|
||||
|
||||
<Frame>
|
||||

|
||||

|
||||
</Frame>
|
||||
|
||||
This is the fastest way to sanity-check a rule's scope before enabling it — for example, to confirm that a rule scoped to the `production` tag isn't accidentally matching a staging deployment.
|
||||
This is the fastest way to sanity-check a policy's scope before enabling it — for example, to confirm that a policy scoped to the `production` tag isn't accidentally matching a staging deployment.
|
||||
|
||||
## Org-wide rules vs per-deployment settings
|
||||
## Org-wide policies vs per-deployment settings
|
||||
|
||||
Both PII Redaction and Cost Limit can be configured in two places: org-wide as a Rule on this page, or per-deployment under that deployment's **Settings**. When an enabled org-wide rule's scope matches a deployment, the rule takes precedence over the deployment-owned setting while it's attached.
|
||||
Both PII Redaction and Cost Limit can be configured in two places: org-wide as a Policy on this page, or per-deployment under that deployment's **Settings**. When an enabled org-wide policy's scope matches a deployment, the policy takes precedence over the deployment-owned setting while it's attached.
|
||||
|
||||
| Policy | Per-deployment setting | What an attached org-wide rule does |
|
||||
| Policy | Per-deployment setting | What an attached org-wide policy does |
|
||||
|--------|------------------------|-------------------------------------|
|
||||
| **PII Redaction** | **Settings → PII Protection** ([guide](/en/enterprise/features/pii-trace-redactions)) | The rule's entity configuration **overrides** the deployment's PII settings for that deployment's executions. |
|
||||
| **Cost Limit** | **Settings → Cost Alerts** | The deployment's manual cost alert is **paused** and the attached cost rule(s) fire instead. The per-deployment form stays editable as a fallback. |
|
||||
| **PII Redaction** | **Settings → PII Protection** ([guide](/en/enterprise/features/pii-trace-redactions)) | The policy's entity configuration **overrides** the deployment's PII settings for that deployment's executions. |
|
||||
| **Cost Limit** | **Settings → Cost Alerts** | The deployment's manual cost alert is **paused** and the attached cost policy(s) fire instead. The per-deployment form stays editable as a fallback. |
|
||||
|
||||
Disable or detach the rule (or change its scope so it no longer matches) and the deployment falls back to its own per-deployment settings.
|
||||
Disable or detach the policy (or change its scope so it no longer matches) and the deployment falls back to its own per-deployment settings.
|
||||
|
||||
Prefer org-wide rules when you want to enforce a consistent policy across many deployments; reserve per-deployment configuration for one-off exceptions.
|
||||
Prefer org-wide policies when you want to enforce a consistent policy across many deployments; reserve per-deployment configuration for one-off exceptions.
|
||||
|
||||
## Related
|
||||
|
||||
@@ -167,10 +167,10 @@ Prefer org-wide rules when you want to enforce a consistent policy across many d
|
||||
Entity catalog, custom recognizers, and per-deployment configuration.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/en/enterprise/features/rbac">
|
||||
Manage who can create or edit rules.
|
||||
Manage who can create or edit policies.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
|
||||
Contact our support team for help designing rules for your organization.
|
||||
Contact our support team for help designing policies for your organization.
|
||||
</Card>
|
||||
123
docs/edge/en/enterprise/features/studio-flows.mdx
Normal file
@@ -0,0 +1,123 @@
|
||||
---
|
||||
title: Flows in Studio
|
||||
description: "Build event-driven workflows that combine deterministic, step-by-step control with agentic intelligence — no code required."
|
||||
icon: "diagram-project"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**Rolling out now**: Flows in Studio is being rolled out gradually during the week of July 20th, 2026. If you don't see the Flows option in Studio yet, it hasn't reached your organization — check back soon.
|
||||
</Info>
|
||||
|
||||
## Overview
|
||||
|
||||
Studio now supports building **Flows** in addition to Crews. Flows are event-driven workflows where you control exactly which steps run, in what order, and under what conditions — while still delegating the intelligent work within each step to AI agents.
|
||||
|
||||
To build a Flow, open Studio, describe your automation, and select **Flows** from the selector next to the prompt box.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## Why Flows?
|
||||
|
||||
Crews are great when you want a team of agents to collaborate autonomously toward a goal. But many real-world automations need more predictability: fetch this data first, then summarize it, then post the result — every time, in that order.
|
||||
|
||||
Flows give you both:
|
||||
|
||||
- **Determinism where it matters**: steps execute in a defined sequence with explicit branching, so runs are predictable, repeatable, and easy to debug.
|
||||
- **Intelligence where you need it**: each step is powered by an agent (or an entire crew), so the work inside a step — summarizing, scoring, drafting, deciding — benefits from full LLM reasoning.
|
||||
|
||||
This mix is what makes Flows well suited for production automations: the structure is guaranteed, and the agency is scoped to the steps that need it.
|
||||
|
||||
## Building a Flow
|
||||
|
||||
Describe what you want in natural language and the Studio Assistant designs the Flow for you — creating the steps, wiring them together, and configuring the agents and app integrations each step needs. The canvas on the right shows the resulting workflow as connected nodes, and you can keep iterating conversationally or edit any node directly.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
When you're ready, use **Run** to test the Flow end-to-end, inspect results in the **Output** and **Traces** tabs, and **Deploy** when it's stable. You can also **Share** the project or **Download** the source code.
|
||||
|
||||
## Node Types
|
||||
|
||||
Flows are composed from three core node types. Each node is a step in the workflow, and you can mix them freely.
|
||||
|
||||
### Single Agent
|
||||
|
||||
A Single Agent node runs one agent against one focused task — ideal for well-scoped steps like fetching data from an integration, transforming content, or posting a message.
|
||||
|
||||
Clicking into an agent node opens its full configuration:
|
||||
|
||||
- **Task**: what this step should accomplish and what output it should produce
|
||||
- **Profile**: the agent's role, goal, and backstory
|
||||
- **Model**: which LLM powers the agent
|
||||
- **Apps**: the integrations the agent can use (e.g. Linear, Slack, HubSpot)
|
||||
- **Runtime Controls**: toggles for planning before executing, delegation, and memory
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### Crews
|
||||
|
||||
A Crew node embeds an entire crew — multiple agents collaborating across multiple tasks — as a single step in your Flow. Use it when a step is too rich for one agent, like grouping and summarizing data by team and then formatting the result for delivery.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Opening a Crew node reveals its internal structure: the tasks it performs, the agents assigned to each, and the apps they use. The crew runs autonomously within the step, then hands its output to the next node in the Flow.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
This is the deterministic-plus-agentic pattern in action: the Flow guarantees *when* the crew runs, and the crew brings collaborative intelligence to *how* the work gets done.
|
||||
|
||||
### Router
|
||||
|
||||
A Router node branches the Flow based on conditions, so different outcomes take different paths. For example, a lead-routing Flow can score incoming leads and then route high-quality leads to a sales-assignment step while logging the rest for future nurturing.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Routers are what make Flows genuinely event-driven: the same workflow handles every case, but each run follows only the branch its data warrants — no wasted steps, no ambiguity about what happens next.
|
||||
|
||||
## Agent Repository Sync
|
||||
|
||||
Agents you build in Flows don't have to stay locked inside a single project. Every agent node includes a **Publish to Agent Repository** button that saves the agent — its role, goal, backstory, model, and configuration — to your organization's [Agent Repository](/en/enterprise/features/agent-repositories).
|
||||
|
||||
This works in both directions:
|
||||
|
||||
- **Publish**: promote an agent you've refined in a Flow to the repository so other teams and projects can reuse it.
|
||||
- **Pull**: bring an existing repository agent into a new Flow instead of rebuilding it from scratch.
|
||||
|
||||
Because repository agents are synced across your organization, an improvement made to a shared agent benefits every Flow that uses it — keeping agent behavior consistent, governed, and free of duplicated effort.
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Reach for a Flow** when the automation has a clear sequence or branching logic; reach for a Crew when the path to the goal is open-ended.
|
||||
- **Keep agent tasks focused** — a Single Agent node with a tight task description is more reliable than one asked to do three things.
|
||||
- **Use Routers to handle every case explicitly**, including the "do nothing" path (e.g. logging skipped leads), so runs are fully accounted for.
|
||||
- **Publish stable agents to the Agent Repository** so your organization builds a shared library instead of parallel one-offs.
|
||||
- **Test with Run and inspect Traces** before deploying to catch integration or prompt issues early.
|
||||
|
||||
## Related
|
||||
|
||||
<CardGroup cols={4}>
|
||||
<Card title="Crew Studio" href="/en/enterprise/features/crew-studio" icon="pencil">
|
||||
Build Crews in Studio.
|
||||
</Card>
|
||||
<Card title="Agent Repositories" href="/en/enterprise/features/agent-repositories" icon="people-group">
|
||||
Share and reuse agents across your organization.
|
||||
</Card>
|
||||
<Card title="Flows Concepts" href="/en/concepts/flows" icon="diagram-project">
|
||||
Learn how Flows work in the CrewAI framework.
|
||||
</Card>
|
||||
<Card title="Tools & Integrations" href="/en/enterprise/features/tools-and-integrations" icon="plug">
|
||||
Connect the apps your agents use.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -25,6 +25,7 @@ Use **`flow.handle_turn(message, session_id=...)`** for every user message from
|
||||
| API | Use for |
|
||||
|-----|---------|
|
||||
| `handle_turn(message, session_id=...)` | Ergonomic one-turn wrapper for conversational `Flow` |
|
||||
| `stream_turn(message, session_id=...)` | Stream one conversational turn as ordered runtime frames |
|
||||
| `chat()` | Local terminal REPL for conversational `Flow` |
|
||||
| `kickoff(inputs={...})` | Advanced flow execution without conversational turn handling |
|
||||
| `ask()` | Blocking prompt **inside** one step (wizard, clarification) |
|
||||
@@ -85,6 +86,23 @@ finally:
|
||||
flow.finalize_session_traces() # one trace link for the whole chat
|
||||
```
|
||||
|
||||
## Streaming a turn
|
||||
|
||||
Use `stream_turn()` when a UI or runtime needs structured events for one chat turn. It returns a stream session with ordered frames for Flow routing, LLM chunks, tool activity, and conversation messages.
|
||||
|
||||
```python
|
||||
stream = flow.stream_turn("Where is my order?", session_id=session_id)
|
||||
|
||||
with stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
|
||||
print(frame.data.get("chunk", ""), end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
For the full frame contract, channel list, and async API, see [Streaming Runtime Contract](/edge/en/learn/streaming-runtime-contract).
|
||||
|
||||
## Turn lifecycle
|
||||
|
||||
Each `handle_turn` runs this pipeline:
|
||||
|
||||
177
docs/edge/en/learn/consuming-streams.mdx
Normal file
@@ -0,0 +1,177 @@
|
||||
---
|
||||
title: Consuming Streams
|
||||
description: Print LLM chunks, observe tool events, and read final results from CrewAI streams.
|
||||
icon: square-terminal
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Use this guide when you want to subscribe to a CrewAI stream and print or route frames as they arrive.
|
||||
|
||||
The basic pattern is:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events(inputs={"topic": "AI agents"})
|
||||
|
||||
with stream:
|
||||
for frame in stream:
|
||||
...
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
Always consume the stream before reading `stream.result`.
|
||||
|
||||
## Print LLM Output
|
||||
|
||||
If you only care about text generated by LLM calls, subscribe to the `llm` projection and print `frame.content`:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events(inputs={"topic": "AI agents"})
|
||||
|
||||
with stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
print()
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
`frame.content` is an empty string for frames that do not carry printable text, so this is also safe:
|
||||
|
||||
```python
|
||||
with flow.stream_events(inputs={"topic": "AI agents"}) as stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.content:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
## Print Tool Activity
|
||||
|
||||
Tool events arrive on the `tools` channel. Use `frame.type` to distinguish starts, finishes, and errors.
|
||||
|
||||
```python
|
||||
with flow.stream_events(inputs={"topic": "AI agents"}) as stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.content:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
if frame.channel == "tools" and frame.type == "tool_usage_started":
|
||||
print(f"\nTool started: {frame.event.get('tool_name')}")
|
||||
|
||||
if frame.channel == "tools" and frame.type == "tool_usage_finished":
|
||||
print(f"\nTool finished: {frame.event.get('tool_name')}")
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
`frame.event` is the structured payload for the source event. Use it for metadata such as tool names, arguments, message roles, and runtime identifiers.
|
||||
|
||||
## Watch Flow Progress
|
||||
|
||||
Flow lifecycle and method execution frames arrive on the `flow` channel:
|
||||
|
||||
```python
|
||||
with flow.stream_events(inputs={"topic": "AI agents"}) as stream:
|
||||
for frame in stream.flow:
|
||||
print(frame.type, frame.namespace)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
Use this when you want a progress log instead of token-level output.
|
||||
|
||||
## Interleave Selected Channels
|
||||
|
||||
Use `interleave()` when you want a subset of channels while preserving their relative order:
|
||||
|
||||
```python
|
||||
with flow.stream_events(inputs={"topic": "AI agents"}) as stream:
|
||||
for frame in stream.interleave(["llm", "tools"]):
|
||||
if frame.channel == "llm":
|
||||
print(frame.content, end="", flush=True)
|
||||
elif frame.type == "tool_usage_started":
|
||||
print(f"\nTool: {frame.event.get('tool_name')}")
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
## Stream a Direct LLM Call
|
||||
|
||||
Direct `llm.call(...)` returns the final assembled result. To stream a direct LLM call, use `llm.stream_events(...)`:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o-mini")
|
||||
stream = llm.stream_events("Explain streaming in one sentence.")
|
||||
|
||||
with stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
print()
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
## Stream a Conversational Turn
|
||||
|
||||
Conversational Flows expose `stream_turn()` for one user message:
|
||||
|
||||
```python
|
||||
stream = flow.stream_turn(
|
||||
"What can you help me with?",
|
||||
session_id="session-1",
|
||||
)
|
||||
|
||||
with stream:
|
||||
for frame in stream.interleave(["llm", "messages"]):
|
||||
if frame.channel == "llm":
|
||||
print(frame.content, end="", flush=True)
|
||||
elif frame.channel == "messages":
|
||||
print(f"\n{frame.event.get('role')}: {frame.event.get('content')}")
|
||||
|
||||
reply = stream.result
|
||||
```
|
||||
|
||||
## Async Consumers
|
||||
|
||||
Async streams use the same channel projections:
|
||||
|
||||
```python
|
||||
stream = flow.astream(inputs={"topic": "AI agents"})
|
||||
|
||||
async with stream:
|
||||
async for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
Use the stream as a context manager when possible. If a client disconnects or you stop consuming early, close the stream:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events(inputs={"topic": "AI agents"})
|
||||
|
||||
try:
|
||||
for frame in stream.events:
|
||||
print(frame.content, end="", flush=True)
|
||||
finally:
|
||||
if not stream.is_exhausted:
|
||||
stream.close()
|
||||
```
|
||||
|
||||
For async streams, call `await stream.aclose()`.
|
||||
|
||||
## See Also
|
||||
|
||||
- [Streaming](/edge/en/concepts/streaming)
|
||||
- [Streaming Runtime Contract](/edge/en/learn/streaming-runtime-contract)
|
||||
- [Streaming Flow Execution](/edge/en/learn/streaming-flow-execution)
|
||||
- [Streaming Crew Execution](/edge/en/learn/streaming-crew-execution)
|
||||
187
docs/edge/en/learn/execution-boundary-hooks.mdx
Normal file
@@ -0,0 +1,187 @@
|
||||
---
|
||||
title: Execution Boundary Hooks
|
||||
description: Intercept the start, inputs, output, and end of crew and flow executions with the @on decorator
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Execution boundary hooks intercept the outermost edges of a run — before any
|
||||
work starts, when inputs are resolved, when the final result is ready, and when
|
||||
the execution finishes. They fire for both crews and flows and are the right
|
||||
place for run-level policy checks, input rewriting, and output sanitization.
|
||||
|
||||
## Overview
|
||||
|
||||
Four interception points cover the boundaries:
|
||||
|
||||
| Point | When | `ctx.payload` |
|
||||
|-------|------|---------------|
|
||||
| `EXECUTION_START` | A crew or flow is about to begin | inputs `dict` |
|
||||
| `INPUT` | Resolved inputs for the execution | inputs `dict` |
|
||||
| `OUTPUT` | The final result is ready | the output object |
|
||||
| `EXECUTION_END` | The execution has finished (success or failure) | the output object, or `None` on failure |
|
||||
|
||||
For a crew, the output payload is a `CrewOutput`. For a flow, it is the final
|
||||
flow-method result.
|
||||
|
||||
## Hook Signature
|
||||
|
||||
```python
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint
|
||||
|
||||
@on(InterceptionPoint.EXECUTION_START)
|
||||
def boundary_hook(ctx) -> Any | None:
|
||||
# Mutate ctx.payload in place, or
|
||||
# return a non-None value to replace it, or
|
||||
# raise HookAborted(reason, source) to stop the run
|
||||
return None
|
||||
```
|
||||
|
||||
Boundary hooks follow the standard contract: proceed (`return None`), mutate in
|
||||
place, replace by returning, or abort by raising
|
||||
[`HookAborted`](/edge/en/learn/execution-hooks#aborting-an-operation). An abort at any
|
||||
boundary propagates out of `kickoff()` with its reason.
|
||||
|
||||
## Context Schema
|
||||
|
||||
Each point receives a typed context. All contexts share the base fields:
|
||||
|
||||
```python
|
||||
class InterceptionContext:
|
||||
payload: Any # The interceptable value (see table above)
|
||||
agent: Any = None # Not populated at execution boundaries
|
||||
agent_role: str | None # Not populated at execution boundaries
|
||||
task: Any = None # Not populated at execution boundaries
|
||||
crew: Any = None # The Crew instance (crew runs only)
|
||||
flow: Any = None # The Flow instance (flow runs only)
|
||||
```
|
||||
|
||||
The per-point contexts add a named alias for the payload:
|
||||
|
||||
```python
|
||||
class ExecutionStartContext(InterceptionContext):
|
||||
inputs: dict # Same dict as payload
|
||||
|
||||
class InputContext(InterceptionContext):
|
||||
inputs: dict # Same dict as payload
|
||||
|
||||
class OutputContext(InterceptionContext):
|
||||
output: Any # The output object
|
||||
|
||||
class ExecutionEndContext(InterceptionContext):
|
||||
output: Any # The output object (None when status == "failed")
|
||||
status: str # "completed" or "failed"
|
||||
error: BaseException | None # The exception when status == "failed"
|
||||
```
|
||||
|
||||
<Note>
|
||||
`ctx.inputs` aliases the **original** inputs dict, so in-place edits through
|
||||
either name are equivalent. If an earlier hook *replaced* the payload by
|
||||
returning a new dict, only `ctx.payload` is rebound — always read and write
|
||||
`ctx.payload` when hooks might chain.
|
||||
</Note>
|
||||
|
||||
## Crew Runs vs. Flow Runs
|
||||
|
||||
Boundary hooks fire on both runtimes, and crew execution internally rides on a
|
||||
flow runtime. During a `crew.kickoff()`, a global boundary hook therefore fires
|
||||
for the crew boundary (`ctx.crew` set, `ctx.flow` `None`) **and** for the
|
||||
internal flow (`ctx.flow` set, `ctx.crew` `None`). Discriminate by runtime:
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.OUTPUT)
|
||||
def crew_output_only(ctx):
|
||||
if ctx.crew is None:
|
||||
return None # Skip the internal flow (or a bare flow)
|
||||
ctx.payload.raw = ctx.payload.raw.strip()
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Policy Check at Start
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.EXECUTION_START)
|
||||
def enforce_policy(ctx):
|
||||
if ctx.crew is not None and not ctx.payload.get("authorized"):
|
||||
raise HookAborted(reason="unauthorized execution", source="access-control")
|
||||
```
|
||||
|
||||
### Input Rewriting
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.INPUT)
|
||||
def add_defaults(ctx):
|
||||
if ctx.crew is None:
|
||||
return None
|
||||
ctx.payload.setdefault("locale", "en-US")
|
||||
ctx.payload["topic"] = ctx.payload["topic"].strip().lower()
|
||||
```
|
||||
|
||||
Rewritten inputs flow into task interpolation, so the run behaves as if it was
|
||||
kicked off with the modified dict.
|
||||
|
||||
### Output Sanitization
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
@on(InterceptionPoint.OUTPUT)
|
||||
def redact_emails(ctx):
|
||||
if ctx.crew is None:
|
||||
return None
|
||||
ctx.payload.raw = re.sub(
|
||||
r"\b[\w.+-]+@[\w-]+\.[\w.]+\b", "[EMAIL-REDACTED]", ctx.payload.raw
|
||||
)
|
||||
```
|
||||
|
||||
`OUTPUT` runs before `EXECUTION_END`, and both see the (possibly replaced)
|
||||
payload from earlier hooks; the final rewritten value is what `kickoff()`
|
||||
returns.
|
||||
|
||||
### Observing Failures
|
||||
|
||||
`EXECUTION_END` fires exactly once per execution, on success and on failure
|
||||
alike. When the run raises — a task error, a flow-method exception, or a
|
||||
`HookAborted` from an earlier point — the hook receives `status="failed"` with
|
||||
the exception in `ctx.error`, and the original exception still propagates out
|
||||
of `kickoff()` unchanged:
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.EXECUTION_END)
|
||||
def report_outcome(ctx):
|
||||
if ctx.status == "failed":
|
||||
notify_policy_engine(status="failed", error=repr(ctx.error))
|
||||
else:
|
||||
notify_policy_engine(status="completed")
|
||||
```
|
||||
|
||||
Two caveats: `EXECUTION_END` does not fire when `EXECUTION_START` never
|
||||
dispatched (an abort at start counts as the execution never beginning), and
|
||||
raising `HookAborted` from a failure-path `EXECUTION_END` dispatch is ignored —
|
||||
there is nothing left to abort, and the original error wins.
|
||||
|
||||
## Ordering
|
||||
|
||||
For a crew run the boundary order is:
|
||||
|
||||
```
|
||||
EXECUTION_START → before_kickoff callbacks → INPUT → tasks execute → OUTPUT → EXECUTION_END
|
||||
```
|
||||
|
||||
Hooks at the same point run in registration order, global hooks first, then
|
||||
crew-scoped hooks. Telemetry (`HookDispatchedEvent`) is emitted per dispatch.
|
||||
|
||||
## Managing Hooks in Tests
|
||||
|
||||
```python
|
||||
from crewai.hooks import clear_all_hooks
|
||||
|
||||
clear_all_hooks() # Clears every point, including boundaries
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Execution Hooks Overview →](/edge/en/learn/execution-hooks)
|
||||
- [Step Hooks →](/edge/en/learn/step-hooks)
|
||||
- [LLM Call Hooks →](/edge/en/learn/llm-hooks)
|
||||
- [Tool Call Hooks →](/edge/en/learn/tool-hooks)
|
||||
@@ -1,525 +1,281 @@
|
||||
---
|
||||
title: Execution Hooks Overview
|
||||
description: Understanding and using execution hooks in CrewAI for fine-grained control over agent operations
|
||||
title: Execution Hooks
|
||||
description: Intercept, modify, and control CrewAI's runtime with the @on decorator - one contract covering every interception point
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Execution Hooks provide fine-grained control over the runtime behavior of your CrewAI agents. Unlike kickoff hooks that run before and after crew execution, execution hooks intercept specific operations during agent execution, allowing you to modify behavior, implement safety checks, and add comprehensive monitoring.
|
||||
Execution hooks provide fine-grained control over the runtime behavior of your
|
||||
CrewAI agents. Unlike kickoff hooks that run before and after crew execution,
|
||||
execution hooks intercept specific operations during execution — from the moment
|
||||
a run starts, through every model call, tool call, and task or flow-method step,
|
||||
down to the final output.
|
||||
|
||||
## Types of Execution Hooks
|
||||
Hooks are written with the `@on` decorator: one registration API and one
|
||||
contract cover every interception point in the framework.
|
||||
|
||||
CrewAI provides two main categories of execution hooks:
|
||||
```python
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint
|
||||
|
||||
### 1. [LLM Call Hooks](/learn/llm-hooks)
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["delete_file"])
|
||||
def guard_deletes(ctx):
|
||||
raise HookAborted(reason="file deletion is not allowed", source="policy")
|
||||
```
|
||||
|
||||
Control and monitor language model interactions:
|
||||
- **Before LLM Call**: Modify prompts, validate inputs, implement approval gates
|
||||
- **After LLM Call**: Transform responses, sanitize outputs, update conversation history
|
||||
<Note>
|
||||
The point-specific decorators (`@before_llm_call`, `@after_tool_call`, ...) keep
|
||||
working unchanged — they are adapters over the same engine. See
|
||||
[Point-specific decorators (legacy)](#point-specific-decorators-legacy) at the
|
||||
end of this page.
|
||||
</Note>
|
||||
|
||||
**Use Cases:**
|
||||
- Iteration limiting
|
||||
- Cost tracking and token usage monitoring
|
||||
- Response sanitization and content filtering
|
||||
- Human-in-the-loop approval for LLM calls
|
||||
- Adding safety guidelines or context
|
||||
- Debug logging and request/response inspection
|
||||
## The contract
|
||||
|
||||
[View LLM Hooks Documentation →](/learn/llm-hooks)
|
||||
Every hook is a **synchronous** callable that receives a single typed context:
|
||||
|
||||
### 2. [Tool Call Hooks](/learn/tool-hooks)
|
||||
```python
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint
|
||||
|
||||
Control and monitor tool execution:
|
||||
- **Before Tool Call**: Modify inputs, validate parameters, block dangerous operations
|
||||
- **After Tool Call**: Transform results, sanitize outputs, log execution details
|
||||
@on(InterceptionPoint.INPUT)
|
||||
def add_defaults(ctx):
|
||||
# 1. Observe: read anything off the context.
|
||||
# 2. Mutate in place: change ctx.payload or nested fields directly.
|
||||
ctx.payload.setdefault("locale", "en-US")
|
||||
# 3. Or replace: return a new value to swap ctx.payload.
|
||||
# 4. Or abort: raise HookAborted(reason, source) to stop the operation.
|
||||
return None
|
||||
```
|
||||
|
||||
**Use Cases:**
|
||||
- Safety guardrails for destructive operations
|
||||
- Human approval for sensitive actions
|
||||
- Input validation and sanitization
|
||||
- Result caching and rate limiting
|
||||
- Tool usage analytics
|
||||
- Debug logging and monitoring
|
||||
A hook may do any of four things:
|
||||
|
||||
[View Tool Hooks Documentation →](/learn/tool-hooks)
|
||||
| Action | How | Effect |
|
||||
|--------|-----|--------|
|
||||
| **Proceed** | `return None` (or nothing) | Operation continues unchanged |
|
||||
| **Mutate** | Change `ctx.payload` / fields in place | Change is visible downstream |
|
||||
| **Replace** | `return new_payload` | A non-`None` return replaces `ctx.payload` |
|
||||
| **Abort** | `raise HookAborted(reason, source)` | Operation is stopped; the reason propagates |
|
||||
|
||||
## Hook Registration Methods
|
||||
## Registering hooks
|
||||
|
||||
### 1. Decorator-Based Hooks (Recommended)
|
||||
Use `@on` for global hooks. It accepts `agents=` / `tools=` filters to scope a
|
||||
hook to specific agent roles or tool names:
|
||||
|
||||
The cleanest and most Pythonic way to register hooks:
|
||||
```python
|
||||
from crewai.hooks import on, InterceptionPoint
|
||||
|
||||
@on(InterceptionPoint.POST_TOOL_CALL, agents=["researcher"], tools=["web_search"])
|
||||
def log_search_results(ctx):
|
||||
print(f"search returned: {(ctx.tool_result or '')[:80]}")
|
||||
```
|
||||
|
||||
Applied to a method inside a `@CrewBase` class, `@on` registers a
|
||||
**crew-scoped** hook, active only while that crew runs:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.hooks import on, InterceptionPoint
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def validate_inputs(self, ctx):
|
||||
# Only applies to this crew
|
||||
return None
|
||||
```
|
||||
|
||||
## Interception point catalog
|
||||
|
||||
Each family has a detailed guide covering its context schema, payload
|
||||
semantics, and examples.
|
||||
|
||||
### [Execution boundaries](/edge/en/learn/execution-boundary-hooks)
|
||||
|
||||
| Point | When | `ctx.payload` |
|
||||
|-------|------|---------------|
|
||||
| `EXECUTION_START` | A crew or flow is about to begin | inputs `dict` |
|
||||
| `INPUT` | Resolved inputs for the execution | inputs `dict` |
|
||||
| `OUTPUT` | Final result is ready | the output object |
|
||||
| `EXECUTION_END` | A crew or flow has finished | the output object |
|
||||
|
||||
### [Model boundaries](/edge/en/learn/llm-hooks) & [tool boundaries](/edge/en/learn/tool-hooks)
|
||||
|
||||
| Point | When | Hook receives |
|
||||
|-------|------|---------------|
|
||||
| `PRE_MODEL_CALL` | Before an LLM call | `LLMCallHookContext` |
|
||||
| `POST_MODEL_CALL` | After an LLM call | `LLMCallHookContext` (with `response` set) |
|
||||
| `PRE_TOOL_CALL` | Before a tool runs | `ToolCallHookContext` |
|
||||
| `POST_TOOL_CALL` | After a tool runs | `ToolCallHookContext` (with results set) |
|
||||
|
||||
At these four points the hook receives the rich legacy context **directly** as
|
||||
its argument — there is no separate `ctx.payload`. Mutate `ctx.messages` /
|
||||
`ctx.tool_input` in place, and return a string from a post hook to replace the
|
||||
response / tool result.
|
||||
|
||||
### [Step points](/edge/en/learn/step-hooks)
|
||||
|
||||
| Point | When | `ctx.payload` |
|
||||
|-------|------|---------------|
|
||||
| `PRE_STEP` | Before a task or flow-method step | step input |
|
||||
| `POST_STEP` | After a task or flow-method step | step output |
|
||||
|
||||
`PRE_STEP` / `POST_STEP` carry `ctx.kind` (`"task"` or `"flow_method"`) and
|
||||
`ctx.step_name`.
|
||||
|
||||
## Aborting an operation
|
||||
|
||||
`HookAborted` carries a `reason` and an optional `source`. The `source` defaults
|
||||
to the aborting hook when omitted, which is useful for telemetry and failure
|
||||
messages:
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.EXECUTION_START)
|
||||
def enforce_policy(ctx):
|
||||
if not ctx.payload.get("authorized"):
|
||||
raise HookAborted(reason="unauthorized execution", source="access-control")
|
||||
```
|
||||
|
||||
## Composition, ordering, and fail-open
|
||||
|
||||
- Multiple hooks on the same point run in **registration order**, global hooks
|
||||
first, then execution-scoped hooks. Legacy hooks registered for the same point
|
||||
participate in the same chain.
|
||||
- The (possibly mutated) payload flows from one hook to the next.
|
||||
- `HookAborted` **propagates by design** and stops the chain.
|
||||
- Any *other* exception raised by a hook is **swallowed** (fail-open) so a single
|
||||
buggy hook can't crash a run.
|
||||
- When no hook is registered for a point, dispatch is a single dict lookup
|
||||
(no-op fast path), so unused points cost effectively nothing.
|
||||
|
||||
## Common patterns
|
||||
|
||||
### Safety guardrails
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def block_dangerous_tools(ctx):
|
||||
dangerous = {"delete_file", "drop_table", "system_shutdown"}
|
||||
if ctx.tool_name in dangerous:
|
||||
raise HookAborted(reason=f"{ctx.tool_name} is blocked", source="safety-policy")
|
||||
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def iteration_limit(ctx):
|
||||
if ctx.iterations > 15:
|
||||
raise HookAborted(reason="maximum iterations exceeded", source="loop-guard")
|
||||
```
|
||||
|
||||
### Human-in-the-loop approval
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email", "make_payment"])
|
||||
def require_approval(ctx):
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Approve {ctx.tool_name}?",
|
||||
default_message="Type 'yes' to approve:",
|
||||
)
|
||||
if response.lower() != "yes":
|
||||
raise HookAborted(reason="rejected by operator", source="approval-gate")
|
||||
```
|
||||
|
||||
### Sanitizing outputs
|
||||
|
||||
A non-`None` return value replaces the interceptable value, so transformations
|
||||
are plain return statements:
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
@on(InterceptionPoint.POST_MODEL_CALL)
|
||||
def redact_keys(ctx):
|
||||
return re.sub(
|
||||
r'(api[_-]?key)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r"\1: [REDACTED]",
|
||||
ctx.response,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
```
|
||||
|
||||
### Observing steps
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.POST_STEP)
|
||||
def trace_steps(ctx):
|
||||
print(f"{ctx.kind} '{ctx.step_name}' finished")
|
||||
```
|
||||
|
||||
## Telemetry
|
||||
|
||||
Whenever a point actually dispatches to at least one hook, CrewAI emits a
|
||||
`HookDispatchedEvent` on the event bus with the point, the outcome
|
||||
(`proceeded` / `modified` / `aborted`), the hook count, the duration, and — for
|
||||
aborts — the reason and source. The no-op fast path emits nothing.
|
||||
|
||||
## Managing hooks in tests
|
||||
|
||||
Global hooks persist for the lifetime of the process. Reset them between tests:
|
||||
|
||||
```python
|
||||
import pytest
|
||||
from crewai.hooks import clear_all_hooks
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_hooks():
|
||||
clear_all_hooks()
|
||||
yield
|
||||
clear_all_hooks()
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
1. **Keep hooks focused** — one clear responsibility per hook; register several
|
||||
small hooks rather than one that does everything.
|
||||
2. **Keep hooks fast** — hooks run on every dispatch of their point; avoid heavy
|
||||
computation and lazy-import heavy dependencies.
|
||||
3. **Prefer scoping** — use `agents=` / `tools=` filters and crew-scoped
|
||||
registration instead of unconditional global hooks.
|
||||
4. **Abort loudly** — raise `HookAborted` with a meaningful `reason` and
|
||||
`source`; that context surfaces in error messages and telemetry. Remember
|
||||
that any other exception is swallowed (fail-open), so don't rely on raising
|
||||
`ValueError` to stop a run.
|
||||
|
||||
## Point-specific decorators (legacy)
|
||||
|
||||
Before `@on`, LLM and tool calls were hooked with dedicated decorator pairs.
|
||||
These keep working unchanged — they are adapters over the same dispatcher, so
|
||||
they compose with `@on` hooks in the same registration-order chain:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call, before_tool_call, after_tool_call
|
||||
|
||||
@before_llm_call
|
||||
def limit_iterations(context):
|
||||
"""Prevent infinite loops by limiting iterations."""
|
||||
if context.iterations > 10:
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
"""Remove sensitive data from LLM responses."""
|
||||
if "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
"""Block destructive operations."""
|
||||
if context.tool_name == "delete_database":
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def log_tool_result(context):
|
||||
"""Log tool execution."""
|
||||
print(f"Tool {context.tool_name} completed")
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. Crew-Scoped Hooks
|
||||
|
||||
Apply hooks only to specific crew instances:
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
# Only applies to this crew
|
||||
print(f"LLM call in {self.__class__.__name__}")
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_results(self, context):
|
||||
# Crew-specific logging
|
||||
print(f"Tool result: {context.tool_result[:50]}...")
|
||||
return None
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential
|
||||
)
|
||||
```
|
||||
|
||||
## Hook Execution Flow
|
||||
|
||||
### LLM Call Flow
|
||||
|
||||
```
|
||||
Agent needs to call LLM
|
||||
↓
|
||||
[Before LLM Call Hooks Execute]
|
||||
├→ Hook 1: Validate iteration count
|
||||
├→ Hook 2: Add safety context
|
||||
└→ Hook 3: Log request
|
||||
↓
|
||||
If any hook returns False:
|
||||
├→ Block LLM call
|
||||
└→ Raise ValueError
|
||||
↓
|
||||
If all hooks return True/None:
|
||||
├→ LLM call proceeds
|
||||
└→ Response generated
|
||||
↓
|
||||
[After LLM Call Hooks Execute]
|
||||
├→ Hook 1: Sanitize response
|
||||
├→ Hook 2: Log response
|
||||
└→ Hook 3: Update metrics
|
||||
↓
|
||||
Final response returned
|
||||
```
|
||||
|
||||
### Tool Call Flow
|
||||
|
||||
```
|
||||
Agent needs to execute tool
|
||||
↓
|
||||
[Before Tool Call Hooks Execute]
|
||||
├→ Hook 1: Check if tool is allowed
|
||||
├→ Hook 2: Validate inputs
|
||||
└→ Hook 3: Request approval if needed
|
||||
↓
|
||||
If any hook returns False:
|
||||
├→ Block tool execution
|
||||
└→ Return error message
|
||||
↓
|
||||
If all hooks return True/None:
|
||||
├→ Tool execution proceeds
|
||||
└→ Result generated
|
||||
↓
|
||||
[After Tool Call Hooks Execute]
|
||||
├→ Hook 1: Sanitize result
|
||||
├→ Hook 2: Cache result
|
||||
└→ Hook 3: Log metrics
|
||||
↓
|
||||
Final result returned
|
||||
```
|
||||
|
||||
## Hook Context Objects
|
||||
|
||||
### LLMCallHookContext
|
||||
|
||||
Provides access to LLM execution state:
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # Full executor access
|
||||
messages: list # Mutable message list
|
||||
agent: Agent # Current agent
|
||||
task: Task # Current task
|
||||
crew: Crew # Crew instance
|
||||
llm: BaseLLM # LLM instance
|
||||
iterations: int # Current iteration
|
||||
response: str | None # LLM response (after hooks)
|
||||
```
|
||||
|
||||
### ToolCallHookContext
|
||||
|
||||
Provides access to tool execution state:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
tool_name: str # Tool being called
|
||||
tool_input: dict # Mutable input parameters
|
||||
tool: CrewStructuredTool # Tool instance
|
||||
agent: Agent | None # Agent executing
|
||||
task: Task | None # Current task
|
||||
crew: Crew | None # Crew instance
|
||||
tool_result: str | None # Agent-facing result string (after hooks)
|
||||
raw_tool_result: Any | None # Raw Python result (after hooks)
|
||||
```
|
||||
|
||||
For typed tool outputs, `tool_result` is the string the agent sees. By default, this is JSON. If the tool uses custom formatting, it can be Markdown or another string. `raw_tool_result` is the original Python value returned by the tool.
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Safety and Validation
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context):
|
||||
"""Block destructive operations."""
|
||||
dangerous = ['delete_file', 'drop_table', 'system_shutdown']
|
||||
if context.tool_name in dangerous:
|
||||
print(f"🛑 Blocked: {context.tool_name}")
|
||||
return False
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def iteration_limit(context):
|
||||
"""Prevent infinite loops."""
|
||||
if context.iterations > 15:
|
||||
print("⛔ Maximum iterations exceeded")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### Human-in-the-Loop
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval(context):
|
||||
"""Require approval for sensitive operations."""
|
||||
sensitive = ['send_email', 'make_payment', 'post_message']
|
||||
|
||||
if context.tool_name in sensitive:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Approve {context.tool_name}?",
|
||||
default_message="Type 'yes' to approve:"
|
||||
)
|
||||
|
||||
if response.lower() != 'yes':
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Monitoring and Analytics
|
||||
|
||||
```python
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
metrics = defaultdict(lambda: {'count': 0, 'total_time': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context):
|
||||
context.tool_input['_start'] = time.time()
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def track_metrics(context):
|
||||
start = context.tool_input.get('_start', time.time())
|
||||
duration = time.time() - start
|
||||
|
||||
metrics[context.tool_name]['count'] += 1
|
||||
metrics[context.tool_name]['total_time'] += duration
|
||||
|
||||
return None
|
||||
|
||||
# View metrics
|
||||
def print_metrics():
|
||||
for tool, data in metrics.items():
|
||||
avg = data['total_time'] / data['count']
|
||||
print(f"{tool}: {data['count']} calls, {avg:.2f}s avg")
|
||||
```
|
||||
|
||||
### Response Sanitization
|
||||
|
||||
```python
|
||||
import re
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_llm_response(context):
|
||||
"""Remove sensitive data from LLM responses."""
|
||||
if not context.response:
|
||||
return None
|
||||
|
||||
result = context.response
|
||||
result = re.sub(r'(api[_-]?key)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r'\1: [REDACTED]', result, flags=re.IGNORECASE)
|
||||
return result
|
||||
|
||||
@after_tool_call
|
||||
def sanitize_tool_result(context):
|
||||
"""Remove sensitive data from tool results."""
|
||||
if not context.tool_result:
|
||||
return None
|
||||
|
||||
result = context.tool_result
|
||||
result = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
'[EMAIL-REDACTED]', result)
|
||||
return result
|
||||
```
|
||||
|
||||
## Hook Management
|
||||
|
||||
### Clearing All Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
# Clear all hooks at once
|
||||
result = clear_all_global_hooks()
|
||||
print(f"Cleared {result['total']} hooks")
|
||||
# Output: {'llm_hooks': (2, 1), 'tool_hooks': (1, 2), 'total': (3, 3)}
|
||||
```
|
||||
|
||||
### Clearing Specific Hook Types
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks
|
||||
)
|
||||
|
||||
# Clear specific types
|
||||
llm_before_count = clear_before_llm_call_hooks()
|
||||
tool_after_count = clear_after_tool_call_hooks()
|
||||
```
|
||||
|
||||
### Unregistering Individual Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_tool_call_hook
|
||||
)
|
||||
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
# Register
|
||||
register_before_llm_call_hook(my_hook)
|
||||
|
||||
# Later, unregister
|
||||
success = unregister_before_llm_call_hook(my_hook)
|
||||
print(f"Unregistered: {success}")
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Keep Hooks Focused
|
||||
Each hook should have a single, clear responsibility:
|
||||
|
||||
```python
|
||||
# ✅ Good - focused responsibility
|
||||
@before_tool_call
|
||||
def validate_file_path(context):
|
||||
if context.tool_name == 'read_file':
|
||||
if '..' in context.tool_input.get('path', ''):
|
||||
return False
|
||||
return None
|
||||
|
||||
# ❌ Bad - too many responsibilities
|
||||
@before_tool_call
|
||||
def do_everything(context):
|
||||
# Validation + logging + metrics + approval...
|
||||
...
|
||||
```
|
||||
|
||||
### 2. Handle Errors Gracefully
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context):
|
||||
try:
|
||||
# Your logic
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Hook error: {e}")
|
||||
return None # Allow execution despite error
|
||||
```
|
||||
|
||||
### 3. Modify Context In-Place
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
@before_llm_call
|
||||
def add_context(context):
|
||||
context.messages.append({"role": "system", "content": "Be concise"})
|
||||
|
||||
# ❌ Wrong - replaces reference
|
||||
@before_llm_call
|
||||
def wrong_approach(context):
|
||||
context.messages = [{"role": "system", "content": "Be concise"}]
|
||||
```
|
||||
|
||||
### 4. Use Type Hints
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, ToolCallHookContext
|
||||
|
||||
def my_llm_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# IDE autocomplete and type checking
|
||||
return None
|
||||
|
||||
def my_tool_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
```
|
||||
|
||||
### 5. Clean Up in Tests
|
||||
|
||||
```python
|
||||
import pytest
|
||||
from crewai.hooks import clear_all_global_hooks
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_hooks():
|
||||
"""Reset hooks before each test."""
|
||||
yield
|
||||
clear_all_global_hooks()
|
||||
```
|
||||
|
||||
## When to Use Which Hook
|
||||
|
||||
### Use LLM Hooks When:
|
||||
- Implementing iteration limits
|
||||
- Adding context or safety guidelines to prompts
|
||||
- Tracking token usage and costs
|
||||
- Sanitizing or transforming responses
|
||||
- Implementing approval gates for LLM calls
|
||||
- Debugging prompt/response interactions
|
||||
|
||||
### Use Tool Hooks When:
|
||||
- Blocking dangerous or destructive operations
|
||||
- Validating tool inputs before execution
|
||||
- Implementing approval gates for sensitive actions
|
||||
- Caching tool results
|
||||
- Tracking tool usage and performance
|
||||
- Sanitizing tool outputs
|
||||
- Rate limiting tool calls
|
||||
|
||||
### Use Both When:
|
||||
Building comprehensive observability, safety, or approval systems that need to monitor all agent operations.
|
||||
|
||||
## Alternative Registration Methods
|
||||
|
||||
### Programmatic Registration (Advanced)
|
||||
|
||||
For dynamic hook registration or when you need to register hooks programmatically:
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
register_before_llm_call_hook,
|
||||
register_after_tool_call_hook
|
||||
)
|
||||
|
||||
def my_hook(context):
|
||||
return None
|
||||
|
||||
# Register programmatically
|
||||
register_before_llm_call_hook(my_hook)
|
||||
|
||||
# Useful for:
|
||||
# - Loading hooks from configuration
|
||||
# - Conditional hook registration
|
||||
# - Plugin systems
|
||||
```
|
||||
|
||||
**Note:** For most use cases, decorators are cleaner and more maintainable.
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
1. **Keep Hooks Fast**: Hooks execute on every call - avoid heavy computation
|
||||
2. **Cache When Possible**: Store expensive validations or lookups
|
||||
3. **Be Selective**: Use crew-scoped hooks when global hooks aren't needed
|
||||
4. **Monitor Hook Overhead**: Profile hook execution time in production
|
||||
5. **Lazy Import**: Import heavy dependencies only when needed
|
||||
|
||||
## Debugging Hooks
|
||||
|
||||
### Enable Debug Logging
|
||||
|
||||
```python
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@before_llm_call
|
||||
def debug_hook(context):
|
||||
logger.debug(f"LLM call: {context.agent.role}, iteration {context.iterations}")
|
||||
return None
|
||||
```
|
||||
|
||||
### Hook Execution Order
|
||||
|
||||
Hooks execute in registration order. If a before hook returns `False`, subsequent hooks don't execute:
|
||||
|
||||
```python
|
||||
# Register order matters!
|
||||
register_before_tool_call_hook(hook1) # Executes first
|
||||
register_before_tool_call_hook(hook2) # Executes second
|
||||
register_before_tool_call_hook(hook3) # Executes third
|
||||
|
||||
# If hook2 returns False:
|
||||
# - hook1 executed
|
||||
# - hook2 executed and returned False
|
||||
# - hook3 NOT executed
|
||||
# - Tool call blocked
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [LLM Call Hooks →](/learn/llm-hooks) - Detailed LLM hook documentation
|
||||
- [Tool Call Hooks →](/learn/tool-hooks) - Detailed tool hook documentation
|
||||
- [Before and After Kickoff Hooks →](/learn/before-and-after-kickoff-hooks) - Crew lifecycle hooks
|
||||
- [Human-in-the-Loop →](/learn/human-in-the-loop) - Human input patterns
|
||||
|
||||
## Conclusion
|
||||
|
||||
Execution hooks provide powerful control over agent runtime behavior. Use them to implement safety guardrails, approval workflows, comprehensive monitoring, and custom business logic. Combined with proper error handling, type safety, and performance considerations, hooks enable production-ready, secure, and observable agent systems.
|
||||
Differences from `@on`:
|
||||
|
||||
- They cover **only** the four model/tool points — no execution boundaries, no
|
||||
steps.
|
||||
- Blocking is `return False`, with no abort reason or source attached.
|
||||
- They receive the same rich contexts — `LLMCallHookContext` (with full
|
||||
executor access) and `ToolCallHookContext` — that `@on` hooks receive at the
|
||||
model/tool points.
|
||||
- Crew-scoping works the same way: apply the decorator to a method inside a
|
||||
`@CrewBase` class.
|
||||
- They support the same `agents=` / `tools=` filters.
|
||||
|
||||
You might still prefer them for existing codebases that already use
|
||||
`return False` semantics, or when you want the point-specific typed signatures.
|
||||
For the detailed guides — context attributes, patterns, and management APIs
|
||||
(`register_*` / `unregister_*` / `clear_*`) — see:
|
||||
|
||||
- [LLM Call Hooks →](/edge/en/learn/llm-hooks)
|
||||
- [Tool Call Hooks →](/edge/en/learn/tool-hooks)
|
||||
|
||||
## Related documentation
|
||||
|
||||
- [Before and After Kickoff Hooks →](/edge/en/learn/before-and-after-kickoff-hooks)
|
||||
- [Human-in-the-Loop →](/edge/en/learn/human-in-the-loop)
|
||||
|
||||
@@ -240,14 +240,15 @@ from crewai import LLM
|
||||
|
||||
# After (OpenAI-compatible mode, no LiteLLM needed):
|
||||
llm = LLM(
|
||||
model="openai/llama3",
|
||||
model="llama3",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama" # Ollama doesn't require a real API key
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Many local inference servers (Ollama, vLLM, LM Studio, llama.cpp) expose an OpenAI-compatible API. You can use the `openai/` prefix with a custom `base_url` to connect to any of them natively.
|
||||
Many local inference servers (Ollama, vLLM, LM Studio, llama.cpp) expose an OpenAI-compatible API. You can use `custom_openai=True` with a custom `base_url` to connect to any of them natively while keeping the model ID your gateway expects.
|
||||
</Tip>
|
||||
|
||||
### Step 4: Update your YAML configs
|
||||
@@ -295,6 +296,92 @@ crewai run
|
||||
uv run pytest
|
||||
```
|
||||
|
||||
## Custom OpenAI-Compatible Endpoints
|
||||
|
||||
Many providers and local servers (Ollama, vLLM, LM Studio, llama.cpp, LiteLLM proxies, and hosted gateways) expose an **OpenAI-compatible** API. Instead of routing these through LiteLLM, you can talk to them directly with CrewAI's native OpenAI integration by setting `custom_openai=True`.
|
||||
|
||||
This is the recommended replacement for any LiteLLM provider that offers an OpenAI-compatible endpoint.
|
||||
|
||||
### How it works
|
||||
|
||||
- `custom_openai=True` forces CrewAI to use the native OpenAI SDK, regardless of the model name.
|
||||
- The model ID is passed to the endpoint without validation against OpenAI's known-model list. This lets you use arbitrary model IDs your gateway expects (for example, `anthropic/claude-sonnet-4-6` served behind an OpenAI-compatible proxy). An optional leading `openai/` routing prefix is stripped.
|
||||
- A base URL is **required**. CrewAI resolves it, in order, from:
|
||||
1. `base_url=...`
|
||||
2. `api_base=...`
|
||||
3. `OPENAI_BASE_URL` environment variable
|
||||
4. `OPENAI_API_BASE` environment variable (legacy)
|
||||
|
||||
If none are set, CrewAI raises a `ValueError` so misconfiguration fails fast instead of silently hitting `api.openai.com`.
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4-6", # passed through as-is
|
||||
custom_openai=True,
|
||||
base_url="https://your-gateway.example/v1",
|
||||
api_key="your-key",
|
||||
)
|
||||
```
|
||||
|
||||
### Connect to common servers
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Ollama">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="llama3.2:latest",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama", # Ollama ignores it, but the client requires a value
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="vLLM">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:8000/v1",
|
||||
api_key="not-needed",
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="LM Studio">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="your-loaded-model",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:1234/v1",
|
||||
api_key="lm-studio",
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Env vars">
|
||||
```bash
|
||||
export OPENAI_BASE_URL="https://your-gateway.example/v1"
|
||||
export OPENAI_API_KEY="your-key"
|
||||
```
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# base_url is picked up from OPENAI_BASE_URL / OPENAI_API_BASE
|
||||
llm = LLM(model="anthropic/claude-sonnet-4-6", custom_openai=True)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Tip>
|
||||
If you use the `openai/` prefix with a model that isn't a known OpenAI model and pass `base_url` or `api_base` directly, CrewAI automatically treats it as a custom OpenAI-compatible endpoint. Environment variables alone do not enable automatic routing for unknown models; set `custom_openai=True` when configuring the endpoint through `OPENAI_BASE_URL` or `OPENAI_API_BASE`.
|
||||
</Tip>
|
||||
|
||||
## Quick Reference: Model String Mapping
|
||||
|
||||
Here are common migration paths from LiteLLM-dependent providers to native ones:
|
||||
@@ -321,7 +408,8 @@ llm = LLM(model="anthropic/claude-sonnet-4-20250514") # High quality
|
||||
# Ollama → OpenAI-compatible (keep using local models)
|
||||
# llm = LLM(model="ollama/llama3")
|
||||
llm = LLM(
|
||||
model="openai/llama3",
|
||||
model="llama3",
|
||||
custom_openai=True,
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama"
|
||||
)
|
||||
@@ -349,6 +437,9 @@ llm = LLM(
|
||||
<Accordion title="What about environment variables like OPENAI_API_KEY?">
|
||||
Native providers use the same environment variables you're already familiar with. No changes needed for `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, etc.
|
||||
</Accordion>
|
||||
<Accordion title="How do I connect to Groq, Together AI, or other OpenAI-compatible providers without LiteLLM?">
|
||||
Most of these providers expose an OpenAI-compatible API. Use `custom_openai=True` with their base URL and API key — see [Custom OpenAI-Compatible Endpoints](#custom-openai-compatible-endpoints). For example, Groq: `LLM(model="llama-3.1-70b-versatile", custom_openai=True, base_url="https://api.groq.com/openai/v1", api_key="...")`. The model ID is passed through untouched, so use whatever ID the provider expects.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Related Resources
|
||||
|
||||
@@ -4,49 +4,51 @@ description: Learn how to use LLM call hooks to intercept, modify, and control l
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
LLM Call Hooks provide fine-grained control over language model interactions during agent execution. These hooks allow you to intercept LLM calls, modify prompts, transform responses, implement approval gates, and add custom logging or monitoring.
|
||||
LLM Call Hooks provide fine-grained control over language model interactions
|
||||
during agent execution. These hooks allow you to intercept LLM calls, modify
|
||||
prompts, transform responses, implement approval gates, and add custom logging
|
||||
or monitoring.
|
||||
|
||||
## Overview
|
||||
|
||||
LLM hooks are executed at two critical points:
|
||||
- **Before LLM Call**: Modify messages, validate inputs, or block execution
|
||||
- **After LLM Call**: Transform responses, sanitize outputs, or modify conversation history
|
||||
LLM hooks are executed at two interception points:
|
||||
|
||||
## Hook Types
|
||||
| Point | When | Hook receives |
|
||||
|-------|------|---------------|
|
||||
| `PRE_MODEL_CALL` | Before every LLM call | `LLMCallHookContext` |
|
||||
| `POST_MODEL_CALL` | After every LLM call | `LLMCallHookContext` (with `response` set) |
|
||||
|
||||
### Before LLM Call Hooks
|
||||
Write them with the [`@on` decorator](/edge/en/learn/execution-hooks). The
|
||||
[legacy `@before_llm_call` / `@after_llm_call` decorators](#legacy-decorators)
|
||||
keep working unchanged — both styles register on the same engine and run in one
|
||||
ordered chain.
|
||||
|
||||
Executed before every LLM call, these hooks can:
|
||||
- Inspect and modify messages sent to the LLM
|
||||
- Block LLM execution based on conditions
|
||||
- Implement rate limiting or approval gates
|
||||
- Add context or system messages
|
||||
- Log request details
|
||||
## Hook Signature
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# Return False to block execution
|
||||
# Return True or None to allow execution
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint, LLMCallHookContext
|
||||
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def before_hook(ctx: LLMCallHookContext) -> None:
|
||||
# Mutate ctx.messages in place, or
|
||||
# raise HookAborted(reason, source) to block the call
|
||||
...
|
||||
|
||||
@on(InterceptionPoint.POST_MODEL_CALL)
|
||||
def after_hook(ctx: LLMCallHookContext) -> str | None:
|
||||
# Return a string to replace ctx.response
|
||||
# Return None to keep the original response
|
||||
...
|
||||
```
|
||||
|
||||
### After LLM Call Hooks
|
||||
Unlike the boundary and step points, the model-call points pass the rich
|
||||
`LLMCallHookContext` directly as the hook argument (there is no separate
|
||||
`ctx.payload`): mutate `ctx.messages` in place before the call, and return a
|
||||
string to replace the response after it.
|
||||
|
||||
Executed after every LLM call, these hooks can:
|
||||
- Modify or sanitize LLM responses
|
||||
- Add metadata or formatting
|
||||
- Log response details
|
||||
- Update conversation history
|
||||
- Implement content filtering
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def after_hook(context: LLMCallHookContext) -> str | None:
|
||||
# Return modified response string
|
||||
# Return None to keep original response
|
||||
...
|
||||
```
|
||||
Blocking a call raises `ValueError("LLM call blocked by before_llm_call hook")`
|
||||
inside the executor; the `HookAborted` reason and source are recorded in
|
||||
[telemetry](/edge/en/learn/execution-hooks#telemetry).
|
||||
|
||||
## LLM Hook Context
|
||||
|
||||
@@ -54,95 +56,74 @@ The `LLMCallHookContext` object provides comprehensive access to execution state
|
||||
|
||||
```python
|
||||
class LLMCallHookContext:
|
||||
executor: CrewAgentExecutor # Full executor reference
|
||||
executor: CrewAgentExecutor | LiteAgent | None # Executor (None for direct LLM calls)
|
||||
messages: list # Mutable message list
|
||||
agent: Agent # Current agent
|
||||
task: Task # Current task
|
||||
crew: Crew # Crew instance
|
||||
llm: BaseLLM # LLM instance
|
||||
iterations: int # Current iteration count
|
||||
response: str | None # LLM response (after hooks only)
|
||||
agent: Agent | None # Current agent (None for direct LLM calls)
|
||||
task: Task | None # Current task (None for direct calls or LiteAgent)
|
||||
crew: Crew | None # Crew instance (None for direct calls or LiteAgent)
|
||||
llm: BaseLLM | None # LLM instance
|
||||
iterations: int # Current iteration count (0 for direct calls)
|
||||
response: str | None # LLM response (POST_MODEL_CALL only)
|
||||
```
|
||||
|
||||
The context also exposes `request_human_input(prompt, default_message)`, which
|
||||
pauses live console updates and collects input from the terminal — useful for
|
||||
approval gates.
|
||||
|
||||
### Modifying Messages
|
||||
|
||||
**Important:** Always modify messages in-place:
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
def add_context(context: LLMCallHookContext) -> None:
|
||||
context.messages.append({"role": "system", "content": "Be concise"})
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def add_context(ctx: LLMCallHookContext) -> None:
|
||||
ctx.messages.append({"role": "system", "content": "Be concise"})
|
||||
|
||||
# ❌ Wrong - replaces list reference
|
||||
def wrong_approach(context: LLMCallHookContext) -> None:
|
||||
context.messages = [{"role": "system", "content": "Be concise"}]
|
||||
# ❌ Wrong - replaces list reference and breaks the executor
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def wrong_approach(ctx: LLMCallHookContext) -> None:
|
||||
ctx.messages = [{"role": "system", "content": "Be concise"}]
|
||||
```
|
||||
|
||||
## Registration Methods
|
||||
|
||||
### 1. Global Hook Registration
|
||||
### 1. Global Hooks
|
||||
|
||||
Register hooks that apply to all LLM calls across all crews:
|
||||
Apply to all LLM calls across all crews. Use the `agents=` filter to scope a
|
||||
hook to specific agent roles:
|
||||
|
||||
```python
|
||||
from crewai.hooks import register_before_llm_call_hook, register_after_llm_call_hook
|
||||
from crewai.hooks import on, InterceptionPoint
|
||||
|
||||
def log_llm_call(context):
|
||||
print(f"LLM call by {context.agent.role} at iteration {context.iterations}")
|
||||
return None # Allow execution
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def log_llm_call(ctx):
|
||||
print(f"LLM call by {ctx.agent.role} at iteration {ctx.iterations}")
|
||||
|
||||
register_before_llm_call_hook(log_llm_call)
|
||||
@on(InterceptionPoint.POST_MODEL_CALL, agents=["Researcher"])
|
||||
def log_researcher_responses(ctx):
|
||||
print(f"Response length: {len(ctx.response)}")
|
||||
```
|
||||
|
||||
### 2. Decorator-Based Registration
|
||||
### 2. Crew-Scoped Hooks
|
||||
|
||||
Use decorators for cleaner syntax:
|
||||
Apply the same decorator to a method inside a `@CrewBase` class to scope the
|
||||
hook to that crew only:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call
|
||||
from crewai.hooks import on, InterceptionPoint
|
||||
|
||||
@before_llm_call
|
||||
def validate_iteration_count(context):
|
||||
if context.iterations > 10:
|
||||
print("⚠️ Exceeded maximum iterations")
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
if context.response and "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Crew-Scoped Hooks
|
||||
|
||||
Register hooks for a specific crew instance:
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def validate_inputs(self, ctx):
|
||||
# Only applies to this crew
|
||||
if context.iterations == 0:
|
||||
print(f"Starting task: {context.task.description}")
|
||||
return None
|
||||
|
||||
@after_llm_call_crew
|
||||
def log_responses(self, context):
|
||||
# Crew-specific response logging
|
||||
print(f"Response length: {len(context.response)}")
|
||||
return None
|
||||
if ctx.iterations == 0:
|
||||
print(f"Starting task: {ctx.task.description}")
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
return Crew(agents=self.agents, tasks=self.tasks, process=Process.sequential)
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
@@ -150,278 +131,152 @@ class MyProjCrew:
|
||||
### 1. Iteration Limiting
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def limit_iterations(context: LLMCallHookContext) -> bool | None:
|
||||
max_iterations = 15
|
||||
if context.iterations > max_iterations:
|
||||
print(f"⛔ Blocked: Exceeded {max_iterations} iterations")
|
||||
return False # Block execution
|
||||
return None
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def limit_iterations(ctx: LLMCallHookContext) -> None:
|
||||
if ctx.iterations > 15:
|
||||
raise HookAborted(reason="exceeded 15 iterations", source="loop-guard")
|
||||
```
|
||||
|
||||
### 2. Human Approval Gate
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def require_approval(context: LLMCallHookContext) -> bool | None:
|
||||
if context.iterations > 5:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Iteration {context.iterations}: Approve LLM call?",
|
||||
default_message="Press Enter to approve, or type 'no' to block:"
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def require_approval(ctx: LLMCallHookContext) -> None:
|
||||
if ctx.iterations > 5:
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Iteration {ctx.iterations}: Approve LLM call?",
|
||||
default_message="Press Enter to approve, or type 'no' to block:",
|
||||
)
|
||||
if response.lower() == "no":
|
||||
print("🚫 LLM call blocked by user")
|
||||
return False
|
||||
return None
|
||||
raise HookAborted(reason="blocked by user", source="approval-gate")
|
||||
```
|
||||
|
||||
### 3. Adding System Context
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def add_guardrails(context: LLMCallHookContext) -> None:
|
||||
# Add safety guidelines to every LLM call
|
||||
context.messages.append({
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def add_guardrails(ctx: LLMCallHookContext) -> None:
|
||||
ctx.messages.append({
|
||||
"role": "system",
|
||||
"content": "Ensure responses are factual and cite sources when possible."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### 4. Response Sanitization
|
||||
|
||||
```python
|
||||
@after_llm_call
|
||||
def sanitize_sensitive_data(context: LLMCallHookContext) -> str | None:
|
||||
if not context.response:
|
||||
import re
|
||||
|
||||
@on(InterceptionPoint.POST_MODEL_CALL)
|
||||
def sanitize_sensitive_data(ctx: LLMCallHookContext) -> str | None:
|
||||
if not ctx.response:
|
||||
return None
|
||||
|
||||
# Remove sensitive patterns
|
||||
import re
|
||||
sanitized = context.response
|
||||
sanitized = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN-REDACTED]', sanitized)
|
||||
sanitized = re.sub(r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b', '[CARD-REDACTED]', sanitized)
|
||||
|
||||
return sanitized
|
||||
sanitized = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN-REDACTED]', ctx.response)
|
||||
return re.sub(r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b', '[CARD-REDACTED]', sanitized)
|
||||
```
|
||||
|
||||
### 5. Cost Tracking
|
||||
### 5. Debug Logging
|
||||
|
||||
```python
|
||||
import tiktoken
|
||||
@on(InterceptionPoint.PRE_MODEL_CALL)
|
||||
def debug_request(ctx: LLMCallHookContext) -> None:
|
||||
print(f"Agent: {ctx.agent.role}, iteration {ctx.iterations}, "
|
||||
f"{len(ctx.messages)} messages")
|
||||
|
||||
@before_llm_call
|
||||
def track_token_usage(context: LLMCallHookContext) -> None:
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
total_tokens = sum(
|
||||
len(encoding.encode(msg.get("content", "")))
|
||||
for msg in context.messages
|
||||
)
|
||||
print(f"📊 Input tokens: ~{total_tokens}")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def track_response_tokens(context: LLMCallHookContext) -> None:
|
||||
if context.response:
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
tokens = len(encoding.encode(context.response))
|
||||
print(f"📊 Response tokens: ~{tokens}")
|
||||
return None
|
||||
```
|
||||
|
||||
### 6. Debug Logging
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def debug_request(context: LLMCallHookContext) -> None:
|
||||
print(f"""
|
||||
🔍 LLM Call Debug:
|
||||
- Agent: {context.agent.role}
|
||||
- Task: {context.task.description[:50]}...
|
||||
- Iteration: {context.iterations}
|
||||
- Message Count: {len(context.messages)}
|
||||
- Last Message: {context.messages[-1] if context.messages else 'None'}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def debug_response(context: LLMCallHookContext) -> None:
|
||||
if context.response:
|
||||
print(f"✅ Response Preview: {context.response[:100]}...")
|
||||
return None
|
||||
@on(InterceptionPoint.POST_MODEL_CALL)
|
||||
def debug_response(ctx: LLMCallHookContext) -> None:
|
||||
if ctx.response:
|
||||
print(f"Response preview: {ctx.response[:100]}...")
|
||||
```
|
||||
|
||||
## Hook Management
|
||||
|
||||
### Unregistering Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_llm_call_hook
|
||||
InterceptionPoint,
|
||||
clear_all_hooks,
|
||||
clear_hooks,
|
||||
get_hooks,
|
||||
unregister_hook,
|
||||
)
|
||||
|
||||
# Unregister specific hook
|
||||
def my_hook(context):
|
||||
...
|
||||
# Unregister a specific hook
|
||||
unregister_hook(InterceptionPoint.PRE_MODEL_CALL, my_hook)
|
||||
|
||||
register_before_llm_call_hook(my_hook)
|
||||
# Later...
|
||||
unregister_before_llm_call_hook(my_hook) # Returns True if found
|
||||
# Clear one point, or everything (e.g. between tests)
|
||||
clear_hooks(InterceptionPoint.POST_MODEL_CALL)
|
||||
clear_all_hooks()
|
||||
|
||||
# Inspect what's registered
|
||||
print(len(get_hooks(InterceptionPoint.PRE_MODEL_CALL)))
|
||||
```
|
||||
|
||||
### Clearing Hooks
|
||||
The legacy management API (`register_before_llm_call_hook`,
|
||||
`unregister_before_llm_call_hook`, `clear_before_llm_call_hooks`,
|
||||
`clear_all_llm_call_hooks`, `get_before_llm_call_hooks`, and their `after_`
|
||||
counterparts) operates on the same underlying registries, so either API can
|
||||
manage hooks registered by the other.
|
||||
|
||||
## Legacy Decorators
|
||||
|
||||
The original per-point decorators keep working unchanged and run in the same
|
||||
registration-order chain as `@on` hooks:
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_all_llm_call_hooks
|
||||
)
|
||||
|
||||
# Clear specific hook type
|
||||
count = clear_before_llm_call_hooks()
|
||||
print(f"Cleared {count} before hooks")
|
||||
|
||||
# Clear all LLM hooks
|
||||
before_count, after_count = clear_all_llm_call_hooks()
|
||||
print(f"Cleared {before_count} before and {after_count} after hooks")
|
||||
```
|
||||
|
||||
### Listing Registered Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
get_before_llm_call_hooks,
|
||||
get_after_llm_call_hooks
|
||||
)
|
||||
|
||||
# Get current hooks
|
||||
before_hooks = get_before_llm_call_hooks()
|
||||
after_hooks = get_after_llm_call_hooks()
|
||||
|
||||
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")
|
||||
```
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Conditional Hook Execution
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def conditional_blocking(context: LLMCallHookContext) -> bool | None:
|
||||
# Only block for specific agents
|
||||
if context.agent.role == "researcher" and context.iterations > 10:
|
||||
return False
|
||||
|
||||
# Only block for specific tasks
|
||||
if "sensitive" in context.task.description.lower() and context.iterations > 5:
|
||||
return False
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Context-Aware Modifications
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def adaptive_prompting(context: LLMCallHookContext) -> None:
|
||||
# Add different context based on iteration
|
||||
if context.iterations == 0:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Start with a high-level overview."
|
||||
})
|
||||
elif context.iterations > 3:
|
||||
context.messages.append({
|
||||
"role": "system",
|
||||
"content": "Focus on specific details and provide examples."
|
||||
})
|
||||
return None
|
||||
```
|
||||
|
||||
### Chaining Hooks
|
||||
|
||||
```python
|
||||
# Multiple hooks execute in registration order
|
||||
from crewai.hooks import before_llm_call, after_llm_call
|
||||
|
||||
@before_llm_call
|
||||
def first_hook(context):
|
||||
print("1. First hook executed")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def second_hook(context):
|
||||
print("2. Second hook executed")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def blocking_hook(context):
|
||||
def validate_iteration_count(context):
|
||||
if context.iterations > 10:
|
||||
print("3. Blocking hook - execution stopped")
|
||||
return False # Subsequent hooks won't execute
|
||||
print("3. Blocking hook - execution allowed")
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_llm_call(agents=["Researcher"])
|
||||
def sanitize_response(context):
|
||||
if context.response and "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
Differences from `@on`:
|
||||
|
||||
- **Blocking** is `return False` from a before hook — equivalent to raising
|
||||
`HookAborted`, but without a custom reason or source for telemetry.
|
||||
- **Signatures** are point-specific: before hooks return `bool | None`, after
|
||||
hooks return `str | None`. The context object is the same
|
||||
`LLMCallHookContext`.
|
||||
- **Filters and crew-scoping** work the same way: `@before_llm_call(agents=[...])`,
|
||||
and applying the decorator to a `@CrewBase` method scopes it to that crew.
|
||||
|
||||
Prefer `@on` for new code; keep the legacy style where it is already in use —
|
||||
there is no behavioral penalty.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep Hooks Focused**: Each hook should have a single responsibility
|
||||
2. **Avoid Heavy Computation**: Hooks execute on every LLM call
|
||||
3. **Handle Errors Gracefully**: Use try-except to prevent hook failures from breaking execution
|
||||
4. **Use Type Hints**: Leverage `LLMCallHookContext` for better IDE support
|
||||
5. **Document Hook Behavior**: Especially for blocking conditions
|
||||
6. **Test Hooks Independently**: Unit test hooks before using in production
|
||||
7. **Clear Hooks in Tests**: Use `clear_all_llm_call_hooks()` between test runs
|
||||
8. **Modify In-Place**: Always modify `context.messages` in-place, never replace
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def safe_hook(context: LLMCallHookContext) -> bool | None:
|
||||
try:
|
||||
# Your hook logic
|
||||
if some_condition:
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Hook error: {e}")
|
||||
# Decide: allow or block on error
|
||||
return None # Allow execution despite error
|
||||
```
|
||||
|
||||
## Type Safety
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, BeforeLLMCallHookType, AfterLLMCallHookType
|
||||
|
||||
# Explicit type annotations
|
||||
def my_before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: LLMCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Type-safe registration
|
||||
register_before_llm_call_hook(my_before_hook)
|
||||
register_after_llm_call_hook(my_after_hook)
|
||||
```
|
||||
1. **Keep hooks focused and fast** — they run on every LLM call
|
||||
2. **Modify in-place** — always mutate `ctx.messages`, never replace the list
|
||||
3. **Use type hints** — annotate with `LLMCallHookContext` for IDE support
|
||||
4. **Abort loudly** — raise `HookAborted` with a meaningful reason and source;
|
||||
any other exception is swallowed (fail-open)
|
||||
5. **Clear hooks in tests** — call `clear_all_hooks()` between test runs
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Hook Not Executing
|
||||
- Verify hook is registered before crew execution
|
||||
- Check if previous hook returned `False` (blocks subsequent hooks)
|
||||
- Ensure hook signature matches expected type
|
||||
- Verify the hook is registered before crew execution
|
||||
- Check whether an earlier hook aborted (subsequent hooks don't run)
|
||||
|
||||
### Message Modifications Not Persisting
|
||||
- Use in-place modifications: `context.messages.append()`
|
||||
- Don't replace the list: `context.messages = []`
|
||||
- Use in-place modifications: `ctx.messages.append(...)`
|
||||
- Don't replace the list: `ctx.messages = []`
|
||||
|
||||
### Response Modifications Not Working
|
||||
- Return the modified string from after hooks
|
||||
- Return the modified string from a `POST_MODEL_CALL` hook
|
||||
- Returning `None` keeps the original response
|
||||
|
||||
## Conclusion
|
||||
## Related Documentation
|
||||
|
||||
LLM Call Hooks provide powerful capabilities for controlling and monitoring language model interactions in CrewAI. Use them to implement safety guardrails, approval gates, logging, cost tracking, and response sanitization. Combined with proper error handling and type safety, hooks enable robust and production-ready agent systems.
|
||||
- [Execution Hooks Overview →](/edge/en/learn/execution-hooks)
|
||||
- [Tool Call Hooks →](/edge/en/learn/tool-hooks)
|
||||
- [Execution Boundary Hooks →](/edge/en/learn/execution-boundary-hooks)
|
||||
- [Step Hooks →](/edge/en/learn/step-hooks)
|
||||
|
||||
142
docs/edge/en/learn/step-hooks.mdx
Normal file
@@ -0,0 +1,142 @@
|
||||
---
|
||||
title: Step Hooks
|
||||
description: Intercept task and flow-method steps with PRE_STEP and POST_STEP hooks in CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Step hooks intercept each unit of work inside an execution: every crew **task**
|
||||
and every **flow method**. Use them to inspect or rewrite what goes into a
|
||||
step, transform what comes out, or trace step-by-step progress — without
|
||||
touching the level of individual LLM or tool calls.
|
||||
|
||||
## Overview
|
||||
|
||||
Two interception points cover steps:
|
||||
|
||||
| Point | When | `ctx.payload` |
|
||||
|-------|------|---------------|
|
||||
| `PRE_STEP` | Before a task or flow method runs | step input (see below) |
|
||||
| `POST_STEP` | After a task or flow method runs | step output (see below) |
|
||||
|
||||
What the payload holds depends on `ctx.kind`:
|
||||
|
||||
| `ctx.kind` | `PRE_STEP` payload | `POST_STEP` payload |
|
||||
|------------|--------------------|---------------------|
|
||||
| `"task"` | The context string passed to the agent | The `TaskOutput` object |
|
||||
| `"flow_method"` | The method's parameters as a `dict` | The method's return value |
|
||||
|
||||
For flow methods, positional arguments appear in the params dict under `_0`,
|
||||
`_1`, ... keys and keyword arguments under their own names; edits and
|
||||
replacements are mapped back onto the actual call.
|
||||
|
||||
## Hook Signature
|
||||
|
||||
```python
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint
|
||||
|
||||
@on(InterceptionPoint.PRE_STEP)
|
||||
def step_hook(ctx) -> Any | None:
|
||||
# Mutate ctx.payload in place, or
|
||||
# return a non-None value to replace it, or
|
||||
# raise HookAborted(reason, source) to stop the step
|
||||
return None
|
||||
```
|
||||
|
||||
## Context Schema
|
||||
|
||||
Both points receive a `StepContext`:
|
||||
|
||||
```python
|
||||
class StepContext(InterceptionContext):
|
||||
payload: Any # Step input (pre) or step output (post)
|
||||
kind: str | None # "task" or "flow_method"
|
||||
step_name: str | None # Task name/description, or flow method name
|
||||
output: Any # POST_STEP only: same object as payload
|
||||
agent: Any # Task steps: the executing agent (else None)
|
||||
agent_role: str | None # Task steps: the agent's role (else None)
|
||||
task: Any # Task steps: the Task instance (else None)
|
||||
crew: Any # None for step points
|
||||
flow: Any # Flow-method steps: the Flow instance (else None)
|
||||
```
|
||||
|
||||
For task steps, `step_name` is the task's `name` (falling back to its
|
||||
description). For flow-method steps, it is the method name.
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Step Tracing
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.POST_STEP)
|
||||
def trace_steps(ctx):
|
||||
print(f"{ctx.kind} '{ctx.step_name}' finished")
|
||||
```
|
||||
|
||||
### Rewriting Task Context
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.PRE_STEP)
|
||||
def inject_disclaimer(ctx):
|
||||
if ctx.kind != "task":
|
||||
return None
|
||||
return f"{ctx.payload}\n\nNote: treat all figures as estimates."
|
||||
```
|
||||
|
||||
### Transforming Task Output
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.POST_STEP)
|
||||
def normalize_output(ctx):
|
||||
if ctx.kind != "task":
|
||||
return None
|
||||
ctx.payload.raw = ctx.payload.raw.strip()
|
||||
```
|
||||
|
||||
<Note>
|
||||
`POST_STEP` runs before the task's output is stored, so rewrites propagate
|
||||
everywhere the output is used: downstream task context, callbacks, the final
|
||||
crew output, and the task's `output_file` on disk.
|
||||
</Note>
|
||||
|
||||
### Guarding Flow Methods
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.PRE_STEP)
|
||||
def guard_publish(ctx):
|
||||
if ctx.kind == "flow_method" and ctx.step_name == "publish":
|
||||
if not ctx.flow.state.get("reviewed"):
|
||||
raise HookAborted(reason="publish requires review", source="review-gate")
|
||||
```
|
||||
|
||||
### Filtering by Agent
|
||||
|
||||
Step hooks support the same `agents=` filter as the other points (matched
|
||||
against the executing agent's role on task steps):
|
||||
|
||||
```python
|
||||
@on(InterceptionPoint.POST_STEP, agents=["Researcher"])
|
||||
def log_research_steps(ctx):
|
||||
print(f"research step done: {ctx.step_name}")
|
||||
```
|
||||
|
||||
## Aborting a Step
|
||||
|
||||
Raising `HookAborted` in `PRE_STEP` stops the step before any agent or method
|
||||
work happens, and the abort propagates out of the execution with its reason —
|
||||
it is not swallowed. Any other exception raised by a step hook is swallowed
|
||||
(fail-open), like at every other point.
|
||||
|
||||
## Managing Hooks in Tests
|
||||
|
||||
```python
|
||||
from crewai.hooks import clear_all_hooks
|
||||
|
||||
clear_all_hooks() # Clears every point, including steps
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [Execution Hooks Overview →](/edge/en/learn/execution-hooks)
|
||||
- [Execution Boundary Hooks →](/edge/en/learn/execution-boundary-hooks)
|
||||
- [LLM Call Hooks →](/edge/en/learn/llm-hooks)
|
||||
- [Tool Call Hooks →](/edge/en/learn/tool-hooks)
|
||||
@@ -11,7 +11,7 @@ CrewAI Flows support streaming output, allowing you to receive real-time updates
|
||||
|
||||
## How Flow Streaming Works
|
||||
|
||||
When streaming is enabled on a Flow, CrewAI captures and streams output from any crews or LLM calls within the flow. The stream delivers structured chunks containing the content, task context, and agent information as execution progresses.
|
||||
When streaming is enabled on a Flow, CrewAI captures and streams output from any crews, LLM calls, tools, and lifecycle events within the flow. The stream delivers ordered `StreamFrame` items with printable content plus structured event data as execution progresses.
|
||||
|
||||
## Enabling Streaming
|
||||
|
||||
@@ -52,7 +52,7 @@ class ResearchFlow(Flow):
|
||||
|
||||
## Synchronous Streaming
|
||||
|
||||
When you call `kickoff()` on a flow with streaming enabled, it returns a `FlowStreamingOutput` object that you can iterate over:
|
||||
When you call `kickoff()` on a flow with streaming enabled, it returns a stream session that yields ordered `StreamFrame` items:
|
||||
|
||||
```python Code
|
||||
flow = ResearchFlow()
|
||||
@@ -60,44 +60,43 @@ flow = ResearchFlow()
|
||||
# Start streaming execution
|
||||
streaming = flow.kickoff()
|
||||
|
||||
# Iterate over chunks as they arrive
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
# Iterate over stream items as they arrive
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# Access the final result after streaming completes
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result}")
|
||||
```
|
||||
|
||||
### Stream Chunk Information
|
||||
### Stream Item Information
|
||||
|
||||
Each chunk provides context about where it originated in the flow:
|
||||
Each item provides both printable content and structured event data:
|
||||
|
||||
```python Code
|
||||
streaming = flow.kickoff()
|
||||
|
||||
for chunk in streaming:
|
||||
print(f"Agent: {chunk.agent_role}")
|
||||
print(f"Task: {chunk.task_name}")
|
||||
print(f"Content: {chunk.content}")
|
||||
print(f"Type: {chunk.chunk_type}") # TEXT or TOOL_CALL
|
||||
for item in streaming:
|
||||
print(f"Channel: {item.channel}")
|
||||
print(f"Type: {item.type}")
|
||||
print(f"Content: {item.content}")
|
||||
print(f"Event payload: {item.event}")
|
||||
```
|
||||
|
||||
### Accessing Streaming Properties
|
||||
|
||||
The `FlowStreamingOutput` object provides useful properties and methods:
|
||||
The stream session provides useful properties and methods:
|
||||
|
||||
```python Code
|
||||
streaming = flow.kickoff()
|
||||
|
||||
# Iterate and collect chunks
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
# Iterate and collect items
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# After iteration completes
|
||||
print(f"\nCompleted: {streaming.is_completed}")
|
||||
print(f"Full text: {streaming.get_full_text()}")
|
||||
print(f"Total chunks: {len(streaming.chunks)}")
|
||||
print(f"Total frames: {len(streaming.frames)}")
|
||||
print(f"Final result: {streaming.result}")
|
||||
```
|
||||
|
||||
@@ -114,9 +113,9 @@ async def stream_flow():
|
||||
# Start async streaming
|
||||
streaming = await flow.kickoff_async()
|
||||
|
||||
# Async iteration over chunks
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
# Async iteration over stream items
|
||||
async for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# Access final result
|
||||
result = streaming.result
|
||||
@@ -181,13 +180,14 @@ flow = MultiStepFlow()
|
||||
streaming = flow.kickoff()
|
||||
|
||||
current_step = ""
|
||||
for chunk in streaming:
|
||||
for item in streaming:
|
||||
# Track which flow step is executing
|
||||
if chunk.task_name != current_step:
|
||||
current_step = chunk.task_name
|
||||
print(f"\n\n=== {chunk.task_name} ===\n")
|
||||
step_name = item.event.get("method_name") or item.event.get("task_name")
|
||||
if step_name and step_name != current_step:
|
||||
current_step = step_name
|
||||
print(f"\n\n=== {step_name} ===\n")
|
||||
|
||||
print(chunk.content, end="", flush=True)
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal analysis: {result}")
|
||||
@@ -201,7 +201,6 @@ Here's a complete example showing how to build a progress dashboard with streami
|
||||
import asyncio
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.types.streaming import StreamChunkType
|
||||
|
||||
class ResearchPipeline(Flow):
|
||||
stream = True
|
||||
@@ -254,33 +253,35 @@ async def run_with_dashboard():
|
||||
|
||||
current_agent = ""
|
||||
current_task = ""
|
||||
chunk_count = 0
|
||||
frame_count = 0
|
||||
|
||||
async for chunk in streaming:
|
||||
chunk_count += 1
|
||||
async for item in streaming:
|
||||
frame_count += 1
|
||||
|
||||
# Display phase transitions
|
||||
if chunk.task_name != current_task:
|
||||
current_task = chunk.task_name
|
||||
current_agent = chunk.agent_role
|
||||
task_name = item.event.get("task_name", "")
|
||||
agent_role = item.event.get("agent_role", "")
|
||||
if task_name and task_name != current_task:
|
||||
current_task = task_name
|
||||
current_agent = agent_role
|
||||
print(f"\n\n📋 Phase: {current_task}")
|
||||
print(f"👤 Agent: {current_agent}")
|
||||
print("-" * 60)
|
||||
|
||||
# Display text output
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
if item.content:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
# Display tool usage
|
||||
elif chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\n🔧 Tool: {chunk.tool_call.tool_name}")
|
||||
elif item.channel == "tools":
|
||||
print(f"\n🔧 Tool event: {item.type}")
|
||||
|
||||
# Show completion summary
|
||||
result = streaming.result
|
||||
print(f"\n\n{'='*60}")
|
||||
print("PIPELINE COMPLETE")
|
||||
print(f"{'='*60}")
|
||||
print(f"Total chunks: {chunk_count}")
|
||||
print(f"Total frames: {frame_count}")
|
||||
print(f"Final output length: {len(str(result))} characters")
|
||||
|
||||
asyncio.run(run_with_dashboard())
|
||||
@@ -353,8 +354,8 @@ class StatefulStreamingFlow(Flow[AnalysisState]):
|
||||
flow = StatefulStreamingFlow()
|
||||
streaming = flow.kickoff(inputs={"topic": "quantum computing"})
|
||||
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal state:")
|
||||
@@ -374,29 +375,29 @@ Flow streaming is particularly valuable for:
|
||||
- **Progress Tracking**: Show users which stage of the workflow is currently executing
|
||||
- **Live Dashboards**: Create monitoring interfaces for production flows
|
||||
|
||||
## Stream Chunk Types
|
||||
## Stream Frame Channels
|
||||
|
||||
Like crew streaming, flow chunks can be of different types:
|
||||
Flow streaming yields `StreamFrame` items across several channels:
|
||||
|
||||
### TEXT Chunks
|
||||
### LLM Frames
|
||||
|
||||
Standard text content from LLM responses:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
if item.channel == "llm" and item.content:
|
||||
print(item.content, end="", flush=True)
|
||||
```
|
||||
|
||||
### TOOL_CALL Chunks
|
||||
### Tool Frames
|
||||
|
||||
Information about tool calls within the flow:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\nTool: {chunk.tool_call.tool_name}")
|
||||
print(f"Args: {chunk.tool_call.arguments}")
|
||||
for item in streaming:
|
||||
if item.channel == "tools":
|
||||
print(f"\nTool event: {item.type}")
|
||||
print(f"Payload: {item.event}")
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
@@ -408,8 +409,8 @@ flow = ResearchFlow()
|
||||
streaming = flow.kickoff()
|
||||
|
||||
try:
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nSuccess! Result: {result}")
|
||||
@@ -422,7 +423,7 @@ except Exception as e:
|
||||
|
||||
## Cancellation and Resource Cleanup
|
||||
|
||||
`FlowStreamingOutput` supports graceful cancellation so that in-flight work stops promptly when the consumer disconnects.
|
||||
The stream session supports graceful cancellation so that in-flight work stops promptly when the consumer disconnects.
|
||||
|
||||
### Async Context Manager
|
||||
|
||||
@@ -430,8 +431,8 @@ except Exception as e:
|
||||
streaming = await flow.kickoff_async()
|
||||
|
||||
async with streaming:
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
async for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
```
|
||||
|
||||
### Explicit Cancellation
|
||||
@@ -439,8 +440,8 @@ async with streaming:
|
||||
```python Code
|
||||
streaming = await flow.kickoff_async()
|
||||
try:
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
async for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
finally:
|
||||
await streaming.aclose() # async
|
||||
# streaming.close() # sync equivalent
|
||||
@@ -451,10 +452,10 @@ After cancellation, `streaming.is_cancelled` and `streaming.is_completed` are bo
|
||||
## Important Notes
|
||||
|
||||
- Streaming automatically enables LLM streaming for any crews used within the flow
|
||||
- You must iterate through all chunks before accessing the `.result` property
|
||||
- You must iterate through all stream items before accessing the `.result` property
|
||||
- Streaming works with both structured and unstructured flow state
|
||||
- Flow streaming captures output from all crews and LLM calls in the flow
|
||||
- Each chunk includes context about which agent and task generated it
|
||||
- Each frame includes structured event context such as channel, type, namespace, and payload
|
||||
- Streaming adds minimal overhead to flow execution
|
||||
|
||||
## Combining with Flow Visualization
|
||||
@@ -468,11 +469,11 @@ flow.plot("research_flow") # Creates HTML visualization
|
||||
|
||||
# Run with streaming
|
||||
streaming = flow.kickoff()
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
for item in streaming:
|
||||
print(item.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nFlow complete! View structure at: research_flow.html")
|
||||
```
|
||||
|
||||
By leveraging flow streaming, you can build sophisticated, responsive applications that provide users with real-time visibility into complex multi-stage workflows, making your AI automations more transparent and engaging.
|
||||
By leveraging flow streaming, you can build sophisticated, responsive applications that provide users with real-time visibility into complex multi-stage workflows, making your AI automations more transparent and engaging.
|
||||
|
||||
194
docs/edge/en/learn/streaming-runtime-contract.mdx
Normal file
@@ -0,0 +1,194 @@
|
||||
---
|
||||
title: Streaming Runtime Contract
|
||||
description: Stream ordered runtime frames from Flows, direct LLM calls, and conversational turns.
|
||||
icon: tower-broadcast
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CrewAI exposes a frame-based streaming contract for runtimes that need more than plain text chunks. The contract emits ordered `StreamFrame` objects for Flow lifecycle events, direct LLM tokens, tool activity, conversation messages, and custom events.
|
||||
|
||||
Use this API when you are building a UI, service bridge, terminal app, or deployment runtime that needs a stable stream of structured events while a Flow, chat turn, or direct LLM call is running.
|
||||
|
||||
## StreamFrame
|
||||
|
||||
Every frame has the same envelope:
|
||||
|
||||
```python
|
||||
from crewai.types.streaming import StreamFrame
|
||||
|
||||
frame.id # unique frame id
|
||||
frame.seq # execution-local order, when available
|
||||
frame.type # source event type, such as "flow_started"
|
||||
frame.channel # "llm", "flow", "tools", "messages", "lifecycle", or "custom"
|
||||
frame.namespace # source/runtime namespace
|
||||
frame.timestamp # event timestamp
|
||||
frame.parent_id # parent event id, when available
|
||||
frame.previous_id # previous event id, when available
|
||||
frame.data # event payload
|
||||
frame.event # alias for frame.data
|
||||
frame.content # printable text for token-like frames, otherwise ""
|
||||
```
|
||||
|
||||
The `channel` field is the fastest way to route frames in consumers:
|
||||
|
||||
| Channel | Contains |
|
||||
|---------|----------|
|
||||
| `llm` | Token and thinking chunks from LLM streaming events |
|
||||
| `flow` | Flow lifecycle, method execution, routing, and pause/resume events |
|
||||
| `tools` | Tool usage events |
|
||||
| `messages` | Conversation transcript events |
|
||||
| `lifecycle` | Runtime lifecycle events that are not specific to another channel |
|
||||
| `custom` | Events that do not map to a built-in channel |
|
||||
|
||||
`frame.type` preserves the source event type, so consumers can handle specific events inside a channel.
|
||||
|
||||
## Stream a Flow
|
||||
|
||||
Set `stream=True` on a Flow to make `kickoff()` return a stream session:
|
||||
|
||||
```python
|
||||
from crewai.flow import Flow, start
|
||||
|
||||
|
||||
class ReportFlow(Flow):
|
||||
@start()
|
||||
def generate(self):
|
||||
return "done"
|
||||
|
||||
|
||||
flow = ReportFlow(stream=True)
|
||||
stream = flow.kickoff()
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
if chunk.type == "tool_usage_started":
|
||||
print(chunk.event["tool_name"])
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
You must consume the stream before reading `stream.result`. Accessing the result early raises a `RuntimeError` so consumers do not accidentally treat a partial run as complete.
|
||||
|
||||
You can also call `flow.stream_events(...)` directly when you want streaming for a single invocation without setting `stream=True` on the Flow instance.
|
||||
|
||||
## Filter by Channel
|
||||
|
||||
`StreamSession` exposes channel projections that preserve global frame order within the selected channel:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
with stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
Available projections are:
|
||||
|
||||
| Projection | Frames |
|
||||
|------------|--------|
|
||||
| `stream.events` | All frames |
|
||||
| `stream.llm` | LLM frames |
|
||||
| `stream.messages` | Conversation message frames |
|
||||
| `stream.flow` | Flow frames |
|
||||
| `stream.tools` | Tool frames |
|
||||
| `stream.interleave([...])` | A selected set of channels |
|
||||
|
||||
Use `stream.interleave(["flow", "llm", "messages"])` when a consumer wants only some channels but still needs their relative order.
|
||||
|
||||
## Async Streaming
|
||||
|
||||
Use `astream()` for async consumers:
|
||||
|
||||
```python
|
||||
flow = ReportFlow()
|
||||
stream = flow.astream()
|
||||
|
||||
async with stream:
|
||||
async for chunk in stream.events:
|
||||
print(chunk.channel, chunk.type, chunk.content)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
The async session has the same projections as the sync session.
|
||||
|
||||
## Stream a Direct LLM Call
|
||||
|
||||
`llm.call(...)` still returns the final assembled result. Use `llm.stream_events(...)` when you want to iterate over chunks as they arrive while keeping the structured event payload:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o-mini")
|
||||
stream = llm.stream_events(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain CrewAI streaming in two short sentences.",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
`llm.stream_events(...)` temporarily enables streaming for the wrapped call and restores the LLM's previous `stream` setting afterward. Provider integrations continue to emit the underlying LLM stream events; this helper provides a common iterator API over those events for every LLM provider.
|
||||
|
||||
## Conversational Turns
|
||||
|
||||
Conversational Flows can stream one user turn with `stream_turn()`:
|
||||
|
||||
```python
|
||||
from crewai import Flow
|
||||
from crewai.experimental.conversational import ConversationConfig, ConversationState
|
||||
|
||||
|
||||
@ConversationConfig(llm="gpt-4o-mini", defer_trace_finalization=True)
|
||||
class ChatFlow(Flow[ConversationState]):
|
||||
conversational = True
|
||||
|
||||
|
||||
flow = ChatFlow()
|
||||
stream = flow.stream_turn("What can you help me with?", session_id="session-1")
|
||||
|
||||
with stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
reply = stream.result
|
||||
```
|
||||
|
||||
During `stream_turn()`, the built-in conversational answer path enables LLM token streaming for that turn and restores the LLM's previous `stream` setting afterward. Custom route handlers that create their own agents or LLM instances should configure those LLMs for streaming if they need token-level output.
|
||||
|
||||
## Cleanup
|
||||
|
||||
Use the session as a context manager when possible. If a client disconnects before the stream is exhausted, close the session explicitly:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
try:
|
||||
for frame in stream.events:
|
||||
print(frame.type)
|
||||
finally:
|
||||
if not stream.is_exhausted:
|
||||
stream.close()
|
||||
```
|
||||
|
||||
For async streams, use `await stream.aclose()`.
|
||||
|
||||
## Legacy Chunk Streaming
|
||||
|
||||
Crew streaming with `stream=True` still returns the chunk-oriented `CrewStreamingOutput` API described in [Streaming Crew Execution](/en/learn/streaming-crew-execution). Direct `llm.call(...)` still returns the final LLM result. The frame contract is intended for runtimes that need a stable event envelope across Flows, direct LLM calls, conversational turns, tools, and messages.
|
||||
@@ -4,53 +4,57 @@ description: Learn how to use tool call hooks to intercept, modify, and control
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
Tool Call Hooks provide fine-grained control over tool execution during agent operations. These hooks allow you to intercept tool calls, modify inputs, transform outputs, implement safety checks, and add comprehensive logging or monitoring.
|
||||
Tool Call Hooks provide fine-grained control over tool execution during agent
|
||||
operations. These hooks allow you to intercept tool calls, modify inputs,
|
||||
transform outputs, implement safety checks, and add comprehensive logging or
|
||||
monitoring.
|
||||
|
||||
## Overview
|
||||
|
||||
Tool hooks are executed at two critical points:
|
||||
- **Before Tool Call**: Modify inputs, validate parameters, or block execution
|
||||
- **After Tool Call**: Transform results, sanitize outputs, or log execution details
|
||||
Tool hooks are executed at two interception points:
|
||||
|
||||
## Hook Types
|
||||
| Point | When | Hook receives |
|
||||
|-------|------|---------------|
|
||||
| `PRE_TOOL_CALL` | Before every tool execution | `ToolCallHookContext` |
|
||||
| `POST_TOOL_CALL` | After every tool execution | `ToolCallHookContext` (with results set) |
|
||||
|
||||
### Before Tool Call Hooks
|
||||
Write them with the [`@on` decorator](/edge/en/learn/execution-hooks). The
|
||||
[legacy `@before_tool_call` / `@after_tool_call` decorators](#legacy-decorators)
|
||||
keep working unchanged — both styles register on the same engine and run in one
|
||||
ordered chain.
|
||||
|
||||
Executed before every tool execution, these hooks can:
|
||||
- Inspect and modify tool inputs
|
||||
- Block tool execution based on conditions
|
||||
- Implement approval gates for dangerous operations
|
||||
- Validate parameters
|
||||
- Log tool invocations
|
||||
## Hook Signature
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
# Return False to block execution
|
||||
# Return True or None to allow execution
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint, ToolCallHookContext
|
||||
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def before_hook(ctx: ToolCallHookContext) -> None:
|
||||
# Mutate ctx.tool_input in place, or
|
||||
# raise HookAborted(reason, source) to block the call
|
||||
...
|
||||
|
||||
@on(InterceptionPoint.POST_TOOL_CALL)
|
||||
def after_hook(ctx: ToolCallHookContext) -> str | None:
|
||||
# Return a string to replace ctx.tool_result
|
||||
# Return None to keep the original result
|
||||
...
|
||||
```
|
||||
|
||||
### After Tool Call Hooks
|
||||
Unlike the boundary and step points, the tool-call points pass the rich
|
||||
`ToolCallHookContext` directly as the hook argument (there is no separate
|
||||
`ctx.payload`): mutate `ctx.tool_input` in place before the call, and return a
|
||||
string to replace the result after it.
|
||||
|
||||
Executed after every tool execution, these hooks can:
|
||||
- Modify or sanitize tool results
|
||||
- Add metadata or formatting
|
||||
- Log execution results
|
||||
- Implement result validation
|
||||
- Transform output formats
|
||||
|
||||
**Signature:**
|
||||
```python
|
||||
def after_hook(context: ToolCallHookContext) -> str | None:
|
||||
# Return modified result string
|
||||
# Return None to keep original result
|
||||
...
|
||||
```
|
||||
When a call is blocked, the tool does not run and the agent receives
|
||||
`"Tool execution blocked by hook. Tool: <name>"` as the result — the run
|
||||
continues. `POST_TOOL_CALL` hooks still fire on blocked calls, so monitoring
|
||||
hooks see every attempt.
|
||||
|
||||
## Tool Hook Context
|
||||
|
||||
The `ToolCallHookContext` object provides comprehensive access to tool execution state:
|
||||
The `ToolCallHookContext` object provides comprehensive access to tool
|
||||
execution state:
|
||||
|
||||
```python
|
||||
class ToolCallHookContext:
|
||||
@@ -60,11 +64,18 @@ class ToolCallHookContext:
|
||||
agent: Agent | BaseAgent | None # Agent executing the tool
|
||||
task: Task | None # Current task
|
||||
crew: Crew | None # Crew instance
|
||||
tool_result: str | None # Agent-facing result string (after hooks only)
|
||||
raw_tool_result: Any | None # Raw Python result (after hooks only)
|
||||
tool_result: str | None # Agent-facing result string (POST_TOOL_CALL only)
|
||||
raw_tool_result: Any | None # Raw Python result (POST_TOOL_CALL only)
|
||||
```
|
||||
|
||||
For typed tool outputs, `tool_result` is the string the agent sees. By default, this is JSON. If the tool uses custom formatting, it can be Markdown or another string. Use `raw_tool_result` when your hook needs the typed object or dictionary.
|
||||
For typed tool outputs, `tool_result` is the string the agent sees. By default,
|
||||
this is JSON. If the tool uses custom formatting, it can be Markdown or another
|
||||
string. Use `raw_tool_result` when your hook needs the typed object or
|
||||
dictionary; it is not affected by result replacement.
|
||||
|
||||
The context also exposes `request_human_input(prompt, default_message)`, which
|
||||
pauses live console updates and collects input from the terminal — useful for
|
||||
approval gates.
|
||||
|
||||
### Modifying Tool Inputs
|
||||
|
||||
@@ -72,83 +83,58 @@ For typed tool outputs, `tool_result` is the string the agent sees. By default,
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
def sanitize_input(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['query'] = context.tool_input['query'].lower()
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def sanitize_input(ctx: ToolCallHookContext) -> None:
|
||||
ctx.tool_input['query'] = ctx.tool_input['query'].lower()
|
||||
|
||||
# ❌ Wrong - replaces dict reference
|
||||
def wrong_approach(context: ToolCallHookContext) -> None:
|
||||
context.tool_input = {'query': 'new query'}
|
||||
# ❌ Wrong - replaces dict reference; the tool never sees it
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def wrong_approach(ctx: ToolCallHookContext) -> None:
|
||||
ctx.tool_input = {'query': 'new query'}
|
||||
```
|
||||
|
||||
## Registration Methods
|
||||
|
||||
### 1. Global Hook Registration
|
||||
### 1. Global Hooks
|
||||
|
||||
Register hooks that apply to all tool calls across all crews:
|
||||
Apply to all tool calls across all crews. Use `tools=` / `agents=` filters to
|
||||
scope a hook:
|
||||
|
||||
```python
|
||||
from crewai.hooks import register_before_tool_call_hook, register_after_tool_call_hook
|
||||
from crewai.hooks import on, HookAborted, InterceptionPoint
|
||||
|
||||
def log_tool_call(context):
|
||||
print(f"Tool: {context.tool_name}")
|
||||
print(f"Input: {context.tool_input}")
|
||||
return None # Allow execution
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def log_tool_call(ctx):
|
||||
print(f"Tool: {ctx.tool_name}, input: {ctx.tool_input}")
|
||||
|
||||
register_before_tool_call_hook(log_tool_call)
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["delete_file", "drop_table"])
|
||||
def block_destructive(ctx):
|
||||
raise HookAborted(reason=f"{ctx.tool_name} is not allowed", source="safety-policy")
|
||||
|
||||
@on(InterceptionPoint.POST_TOOL_CALL, tools=["web_search"], agents=["Researcher"])
|
||||
def log_search_results(ctx):
|
||||
print(f"search returned {len(ctx.tool_result or '')} chars")
|
||||
```
|
||||
|
||||
### 2. Decorator-Based Registration
|
||||
### 2. Crew-Scoped Hooks
|
||||
|
||||
Use decorators for cleaner syntax:
|
||||
Apply the same decorator to a method inside a `@CrewBase` class to scope the
|
||||
hook to that crew only:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_tool_call, after_tool_call
|
||||
from crewai.hooks import on, InterceptionPoint
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
dangerous_tools = ['delete_database', 'drop_table', 'rm_rf']
|
||||
if context.tool_name in dangerous_tools:
|
||||
print(f"⛔ Blocked dangerous tool: {context.tool_name}")
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def sanitize_results(context):
|
||||
if context.tool_result and "password" in context.tool_result.lower():
|
||||
return context.tool_result.replace("password", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. Crew-Scoped Hooks
|
||||
|
||||
Register hooks for a specific crew instance:
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_tool_call_crew
|
||||
def validate_tool_inputs(self, context):
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def validate_tool_inputs(self, ctx):
|
||||
# Only applies to this crew
|
||||
if context.tool_name == "web_search":
|
||||
if not context.tool_input.get('query'):
|
||||
print("❌ Invalid search query")
|
||||
return False
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_tool_results(self, context):
|
||||
# Crew-specific tool logging
|
||||
print(f"✅ {context.tool_name} completed")
|
||||
return None
|
||||
if ctx.tool_name == "web_search" and not ctx.tool_input.get("query"):
|
||||
raise HookAborted(reason="empty search query", source="input-validation")
|
||||
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
return Crew(agents=self.agents, tasks=self.tasks, process=Process.sequential)
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
@@ -156,112 +142,63 @@ class MyProjCrew:
|
||||
### 1. Safety Guardrails
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safety_check(context: ToolCallHookContext) -> bool | None:
|
||||
# Block tools that could cause harm
|
||||
destructive_tools = [
|
||||
'delete_file',
|
||||
'drop_table',
|
||||
'remove_user',
|
||||
'system_shutdown'
|
||||
]
|
||||
|
||||
if context.tool_name in destructive_tools:
|
||||
print(f"🛑 Blocked destructive tool: {context.tool_name}")
|
||||
return False
|
||||
|
||||
# Warn on sensitive operations
|
||||
sensitive_tools = ['send_email', 'post_to_social_media', 'charge_payment']
|
||||
if context.tool_name in sensitive_tools:
|
||||
print(f"⚠️ Executing sensitive tool: {context.tool_name}")
|
||||
|
||||
return None
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def safety_check(ctx: ToolCallHookContext) -> None:
|
||||
destructive = {'delete_file', 'drop_table', 'remove_user', 'system_shutdown'}
|
||||
if ctx.tool_name in destructive:
|
||||
raise HookAborted(reason=f"{ctx.tool_name} is destructive", source="safety-policy")
|
||||
```
|
||||
|
||||
### 2. Human Approval Gate
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def require_approval_for_actions(context: ToolCallHookContext) -> bool | None:
|
||||
approval_required = [
|
||||
'send_email',
|
||||
'make_purchase',
|
||||
'delete_file',
|
||||
'post_message'
|
||||
]
|
||||
|
||||
if context.tool_name in approval_required:
|
||||
response = context.request_human_input(
|
||||
prompt=f"Approve {context.tool_name}?",
|
||||
default_message=f"Input: {context.tool_input}\nType 'yes' to approve:"
|
||||
)
|
||||
|
||||
if response.lower() != 'yes':
|
||||
print(f"❌ Tool execution denied: {context.tool_name}")
|
||||
return False
|
||||
|
||||
return None
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email", "make_purchase", "delete_file"])
|
||||
def require_approval(ctx: ToolCallHookContext) -> None:
|
||||
response = ctx.request_human_input(
|
||||
prompt=f"Approve {ctx.tool_name}?",
|
||||
default_message=f"Input: {ctx.tool_input}\nType 'yes' to approve:",
|
||||
)
|
||||
if response.lower() != 'yes':
|
||||
raise HookAborted(reason="denied by operator", source="approval-gate")
|
||||
```
|
||||
|
||||
### 3. Input Validation and Sanitization
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def validate_and_sanitize_inputs(context: ToolCallHookContext) -> bool | None:
|
||||
# Validate search queries
|
||||
if context.tool_name == 'web_search':
|
||||
query = context.tool_input.get('query', '')
|
||||
if len(query) < 3:
|
||||
print("❌ Search query too short")
|
||||
return False
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["web_search"])
|
||||
def validate_query(ctx: ToolCallHookContext) -> None:
|
||||
query = ctx.tool_input.get('query', '')
|
||||
if len(query) < 3:
|
||||
raise HookAborted(reason="search query too short", source="input-validation")
|
||||
ctx.tool_input['query'] = query.strip().lower()
|
||||
|
||||
# Sanitize query
|
||||
context.tool_input['query'] = query.strip().lower()
|
||||
|
||||
# Validate file paths
|
||||
if context.tool_name == 'read_file':
|
||||
path = context.tool_input.get('path', '')
|
||||
if '..' in path or path.startswith('/'):
|
||||
print("❌ Invalid file path")
|
||||
return False
|
||||
|
||||
return None
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL, tools=["read_file"])
|
||||
def validate_path(ctx: ToolCallHookContext) -> None:
|
||||
path = ctx.tool_input.get('path', '')
|
||||
if '..' in path or path.startswith('/'):
|
||||
raise HookAborted(reason="invalid file path", source="input-validation")
|
||||
```
|
||||
|
||||
### 4. Result Sanitization
|
||||
|
||||
```python
|
||||
@after_tool_call
|
||||
def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
|
||||
if not context.tool_result:
|
||||
import re
|
||||
|
||||
@on(InterceptionPoint.POST_TOOL_CALL)
|
||||
def sanitize_sensitive_data(ctx: ToolCallHookContext) -> str | None:
|
||||
if not ctx.tool_result:
|
||||
return None
|
||||
|
||||
import re
|
||||
result = context.tool_result
|
||||
|
||||
# Remove API keys
|
||||
result = re.sub(
|
||||
r'(api[_-]?key|token)["\']?\s*[:=]\s*["\']?[\w-]+',
|
||||
r'\1: [REDACTED]',
|
||||
result,
|
||||
flags=re.IGNORECASE
|
||||
ctx.tool_result,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Remove email addresses
|
||||
result = re.sub(
|
||||
return re.sub(
|
||||
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
||||
'[EMAIL-REDACTED]',
|
||||
result
|
||||
result,
|
||||
)
|
||||
|
||||
# Remove credit card numbers
|
||||
result = re.sub(
|
||||
r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b',
|
||||
'[CARD-REDACTED]',
|
||||
result
|
||||
)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
### 5. Tool Usage Analytics
|
||||
@@ -270,32 +207,17 @@ def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0, 'failures': 0})
|
||||
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0})
|
||||
|
||||
@before_tool_call
|
||||
def start_timer(context: ToolCallHookContext) -> None:
|
||||
context.tool_input['_start_time'] = time.time()
|
||||
return None
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def start_timer(ctx: ToolCallHookContext) -> None:
|
||||
ctx.tool_input['_start_time'] = time.time()
|
||||
|
||||
@after_tool_call
|
||||
def track_tool_usage(context: ToolCallHookContext) -> None:
|
||||
start_time = context.tool_input.get('_start_time', time.time())
|
||||
duration = time.time() - start_time
|
||||
|
||||
tool_stats[context.tool_name]['count'] += 1
|
||||
tool_stats[context.tool_name]['total_time'] += duration
|
||||
|
||||
if not context.tool_result or 'error' in context.tool_result.lower():
|
||||
tool_stats[context.tool_name]['failures'] += 1
|
||||
|
||||
print(f"""
|
||||
📊 Tool Stats for {context.tool_name}:
|
||||
- Executions: {tool_stats[context.tool_name]['count']}
|
||||
- Avg Time: {tool_stats[context.tool_name]['total_time'] / tool_stats[context.tool_name]['count']:.2f}s
|
||||
- Failures: {tool_stats[context.tool_name]['failures']}
|
||||
""")
|
||||
|
||||
return None
|
||||
@on(InterceptionPoint.POST_TOOL_CALL)
|
||||
def track_tool_usage(ctx: ToolCallHookContext) -> None:
|
||||
start_time = ctx.tool_input.pop('_start_time', time.time())
|
||||
tool_stats[ctx.tool_name]['count'] += 1
|
||||
tool_stats[ctx.tool_name]['total_time'] += time.time() - start_time
|
||||
```
|
||||
|
||||
### 6. Rate Limiting
|
||||
@@ -306,298 +228,113 @@ from datetime import datetime, timedelta
|
||||
|
||||
tool_call_history = defaultdict(list)
|
||||
|
||||
@before_tool_call
|
||||
def rate_limit_tools(context: ToolCallHookContext) -> bool | None:
|
||||
tool_name = context.tool_name
|
||||
@on(InterceptionPoint.PRE_TOOL_CALL)
|
||||
def rate_limit_tools(ctx: ToolCallHookContext) -> None:
|
||||
now = datetime.now()
|
||||
|
||||
# Clean old entries (older than 1 minute)
|
||||
tool_call_history[tool_name] = [
|
||||
call_time for call_time in tool_call_history[tool_name]
|
||||
if now - call_time < timedelta(minutes=1)
|
||||
]
|
||||
|
||||
# Check rate limit (max 10 calls per minute)
|
||||
if len(tool_call_history[tool_name]) >= 10:
|
||||
print(f"🚫 Rate limit exceeded for {tool_name}")
|
||||
return False
|
||||
|
||||
# Record this call
|
||||
tool_call_history[tool_name].append(now)
|
||||
return None
|
||||
```
|
||||
|
||||
### 7. Caching Tool Results
|
||||
|
||||
```python
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
tool_cache = {}
|
||||
|
||||
def cache_key(tool_name: str, tool_input: dict) -> str:
|
||||
"""Generate cache key from tool name and input."""
|
||||
input_str = json.dumps(tool_input, sort_keys=True)
|
||||
return hashlib.md5(f"{tool_name}:{input_str}".encode()).hexdigest()
|
||||
|
||||
@before_tool_call
|
||||
def check_cache(context: ToolCallHookContext) -> bool | None:
|
||||
key = cache_key(context.tool_name, context.tool_input)
|
||||
if key in tool_cache:
|
||||
print(f"💾 Cache hit for {context.tool_name}")
|
||||
# Note: Can't return cached result from before hook
|
||||
# Would need to implement this differently
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def cache_result(context: ToolCallHookContext) -> None:
|
||||
if context.tool_result:
|
||||
key = cache_key(context.tool_name, context.tool_input)
|
||||
tool_cache[key] = context.tool_result
|
||||
print(f"💾 Cached result for {context.tool_name}")
|
||||
return None
|
||||
```
|
||||
|
||||
### 8. Debug Logging
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def debug_tool_call(context: ToolCallHookContext) -> None:
|
||||
print(f"""
|
||||
🔍 Tool Call Debug:
|
||||
- Tool: {context.tool_name}
|
||||
- Agent: {context.agent.role if context.agent else 'Unknown'}
|
||||
- Task: {context.task.description[:50] if context.task else 'Unknown'}...
|
||||
- Input: {context.tool_input}
|
||||
""")
|
||||
return None
|
||||
|
||||
@after_tool_call
|
||||
def debug_tool_result(context: ToolCallHookContext) -> None:
|
||||
if context.tool_result:
|
||||
result_preview = context.tool_result[:200]
|
||||
print(f"✅ Result Preview: {result_preview}...")
|
||||
else:
|
||||
print("⚠️ No result returned")
|
||||
return None
|
||||
history = tool_call_history[ctx.tool_name]
|
||||
history[:] = [t for t in history if now - t < timedelta(minutes=1)]
|
||||
if len(history) >= 10:
|
||||
raise HookAborted(reason=f"rate limit exceeded for {ctx.tool_name}",
|
||||
source="rate-limiter")
|
||||
history.append(now)
|
||||
```
|
||||
|
||||
## Hook Management
|
||||
|
||||
### Unregistering Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_tool_call_hook,
|
||||
unregister_after_tool_call_hook
|
||||
InterceptionPoint,
|
||||
clear_all_hooks,
|
||||
clear_hooks,
|
||||
get_hooks,
|
||||
unregister_hook,
|
||||
)
|
||||
|
||||
# Unregister specific hook
|
||||
def my_hook(context):
|
||||
...
|
||||
# Unregister a specific hook
|
||||
unregister_hook(InterceptionPoint.PRE_TOOL_CALL, my_hook)
|
||||
|
||||
register_before_tool_call_hook(my_hook)
|
||||
# Later...
|
||||
success = unregister_before_tool_call_hook(my_hook)
|
||||
print(f"Unregistered: {success}")
|
||||
# Clear one point, or everything (e.g. between tests)
|
||||
clear_hooks(InterceptionPoint.POST_TOOL_CALL)
|
||||
clear_all_hooks()
|
||||
|
||||
# Inspect what's registered
|
||||
print(len(get_hooks(InterceptionPoint.PRE_TOOL_CALL)))
|
||||
```
|
||||
|
||||
### Clearing Hooks
|
||||
The legacy management API (`register_before_tool_call_hook`,
|
||||
`unregister_before_tool_call_hook`, `clear_before_tool_call_hooks`,
|
||||
`clear_all_tool_call_hooks`, `get_before_tool_call_hooks`, and their `after_`
|
||||
counterparts) operates on the same underlying registries, so either API can
|
||||
manage hooks registered by the other.
|
||||
|
||||
## Legacy Decorators
|
||||
|
||||
The original per-point decorators keep working unchanged and run in the same
|
||||
registration-order chain as `@on` hooks:
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_tool_call_hooks,
|
||||
clear_after_tool_call_hooks,
|
||||
clear_all_tool_call_hooks
|
||||
)
|
||||
from crewai.hooks import before_tool_call, after_tool_call
|
||||
|
||||
# Clear specific hook type
|
||||
count = clear_before_tool_call_hooks()
|
||||
print(f"Cleared {count} before hooks")
|
||||
|
||||
# Clear all tool hooks
|
||||
before_count, after_count = clear_all_tool_call_hooks()
|
||||
print(f"Cleared {before_count} before and {after_count} after hooks")
|
||||
```
|
||||
|
||||
### Listing Registered Hooks
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
get_before_tool_call_hooks,
|
||||
get_after_tool_call_hooks
|
||||
)
|
||||
|
||||
# Get current hooks
|
||||
before_hooks = get_before_tool_call_hooks()
|
||||
after_hooks = get_after_tool_call_hooks()
|
||||
|
||||
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")
|
||||
```
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Conditional Hook Execution
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def conditional_blocking(context: ToolCallHookContext) -> bool | None:
|
||||
# Only block for specific agents
|
||||
if context.agent and context.agent.role == "junior_agent":
|
||||
if context.tool_name in ['delete_file', 'send_email']:
|
||||
print(f"❌ Junior agents cannot use {context.tool_name}")
|
||||
return False
|
||||
|
||||
# Only block during specific tasks
|
||||
if context.task and "sensitive" in context.task.description.lower():
|
||||
if context.tool_name == 'web_search':
|
||||
print("❌ Web search blocked for sensitive tasks")
|
||||
return False
|
||||
def block_dangerous_tools(context):
|
||||
if context.tool_name in ('delete_database', 'drop_table'):
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_tool_call(tools=["web_search"])
|
||||
def sanitize_results(context):
|
||||
if context.tool_result and "password" in context.tool_result.lower():
|
||||
return context.tool_result.replace("password", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
### Context-Aware Input Modification
|
||||
Differences from `@on`:
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def enhance_tool_inputs(context: ToolCallHookContext) -> None:
|
||||
# Add context based on agent role
|
||||
if context.agent and context.agent.role == "researcher":
|
||||
if context.tool_name == 'web_search':
|
||||
# Add domain restrictions for researchers
|
||||
context.tool_input['domains'] = ['edu', 'gov', 'org']
|
||||
- **Blocking** is `return False` from a before hook — equivalent to raising
|
||||
`HookAborted`, but without a custom reason or source for telemetry. The agent
|
||||
sees the same `"Tool execution blocked by hook"` message.
|
||||
- **Signatures** are point-specific: before hooks return `bool | None`, after
|
||||
hooks return `str | None`. The context object is the same
|
||||
`ToolCallHookContext`.
|
||||
- **Filters and crew-scoping** work the same way:
|
||||
`@before_tool_call(tools=[...], agents=[...])`, and applying the decorator to
|
||||
a `@CrewBase` method scopes it to that crew.
|
||||
|
||||
# Add context based on task
|
||||
if context.task and "urgent" in context.task.description.lower():
|
||||
if context.tool_name == 'send_email':
|
||||
context.tool_input['priority'] = 'high'
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### Tool Chain Monitoring
|
||||
|
||||
```python
|
||||
tool_call_chain = []
|
||||
|
||||
@before_tool_call
|
||||
def track_tool_chain(context: ToolCallHookContext) -> None:
|
||||
tool_call_chain.append({
|
||||
'tool': context.tool_name,
|
||||
'timestamp': time.time(),
|
||||
'agent': context.agent.role if context.agent else 'Unknown'
|
||||
})
|
||||
|
||||
# Detect potential infinite loops
|
||||
recent_calls = tool_call_chain[-5:]
|
||||
if len(recent_calls) == 5 and all(c['tool'] == context.tool_name for c in recent_calls):
|
||||
print(f"⚠️ Warning: {context.tool_name} called 5 times in a row")
|
||||
|
||||
return None
|
||||
```
|
||||
Prefer `@on` for new code; keep the legacy style where it is already in use —
|
||||
there is no behavioral penalty.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep Hooks Focused**: Each hook should have a single responsibility
|
||||
2. **Avoid Heavy Computation**: Hooks execute on every tool call
|
||||
3. **Handle Errors Gracefully**: Use try-except to prevent hook failures
|
||||
4. **Use Type Hints**: Leverage `ToolCallHookContext` for better IDE support
|
||||
5. **Document Blocking Conditions**: Make it clear when/why tools are blocked
|
||||
6. **Test Hooks Independently**: Unit test hooks before using in production
|
||||
7. **Clear Hooks in Tests**: Use `clear_all_tool_call_hooks()` between test runs
|
||||
8. **Modify In-Place**: Always modify `context.tool_input` in-place, never replace
|
||||
9. **Log Important Decisions**: Especially when blocking tool execution
|
||||
10. **Consider Performance**: Cache expensive validations when possible
|
||||
|
||||
## Error Handling
|
||||
|
||||
```python
|
||||
@before_tool_call
|
||||
def safe_validation(context: ToolCallHookContext) -> bool | None:
|
||||
try:
|
||||
# Your validation logic
|
||||
if not validate_input(context.tool_input):
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"⚠️ Hook error: {e}")
|
||||
# Decide: allow or block on error
|
||||
return None # Allow execution despite error
|
||||
```
|
||||
|
||||
## Type Safety
|
||||
|
||||
```python
|
||||
from crewai.hooks import ToolCallHookContext, BeforeToolCallHookType, AfterToolCallHookType
|
||||
|
||||
# Explicit type annotations
|
||||
def my_before_hook(context: ToolCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: ToolCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Type-safe registration
|
||||
register_before_tool_call_hook(my_before_hook)
|
||||
register_after_tool_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## Integration with Existing Tools
|
||||
|
||||
### Wrapping Existing Validation
|
||||
|
||||
```python
|
||||
def existing_validator(tool_name: str, inputs: dict) -> bool:
|
||||
"""Your existing validation function."""
|
||||
# Your validation logic
|
||||
return True
|
||||
|
||||
@before_tool_call
|
||||
def integrate_validator(context: ToolCallHookContext) -> bool | None:
|
||||
if not existing_validator(context.tool_name, context.tool_input):
|
||||
print(f"❌ Validation failed for {context.tool_name}")
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### Logging to External Systems
|
||||
|
||||
```python
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@before_tool_call
|
||||
def log_to_external_system(context: ToolCallHookContext) -> None:
|
||||
logger.info(f"Tool call: {context.tool_name}", extra={
|
||||
'tool_name': context.tool_name,
|
||||
'tool_input': context.tool_input,
|
||||
'agent': context.agent.role if context.agent else None
|
||||
})
|
||||
return None
|
||||
```
|
||||
1. **Keep hooks focused and fast** — they run on every tool call
|
||||
2. **Modify in-place** — always mutate `ctx.tool_input`, never replace the dict
|
||||
3. **Prefer filters over conditionals** — `tools=` / `agents=` keep hook bodies small
|
||||
4. **Abort loudly** — raise `HookAborted` with a meaningful reason and source;
|
||||
any other exception is swallowed (fail-open)
|
||||
5. **Use type hints** — annotate with `ToolCallHookContext` for IDE support
|
||||
6. **Clear hooks in tests** — call `clear_all_hooks()` between test runs
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Hook Not Executing
|
||||
- Verify hook is registered before crew execution
|
||||
- Check if previous hook returned `False` (blocks execution and subsequent hooks)
|
||||
- Ensure hook signature matches expected type
|
||||
- Verify the hook is registered before crew execution
|
||||
- Check whether an earlier hook blocked the call (subsequent pre hooks don't run)
|
||||
- Check `tools=` / `agents=` filters against the actual tool name and agent role
|
||||
|
||||
### Input Modifications Not Working
|
||||
- Use in-place modifications: `context.tool_input['key'] = value`
|
||||
- Don't replace the dict: `context.tool_input = {}`
|
||||
- Use in-place modifications: `ctx.tool_input['key'] = value`
|
||||
- Don't replace the dict: `ctx.tool_input = {}`
|
||||
|
||||
### Result Modifications Not Working
|
||||
- Return the modified string from after hooks
|
||||
- Return the modified string from a `POST_TOOL_CALL` hook
|
||||
- Returning `None` keeps the original result
|
||||
- Ensure the tool actually returned a result
|
||||
|
||||
### Tool Blocked Unexpectedly
|
||||
- Check all before hooks for blocking conditions
|
||||
- Verify hook execution order
|
||||
- Add debug logging to identify which hook is blocking
|
||||
- Check all pre hooks for `HookAborted` / `return False` conditions
|
||||
- The abort reason and source appear on the `HookDispatchedEvent` telemetry
|
||||
|
||||
## Conclusion
|
||||
## Related Documentation
|
||||
|
||||
Tool Call Hooks provide powerful capabilities for controlling and monitoring tool execution in CrewAI. Use them to implement safety guardrails, approval gates, input validation, result sanitization, logging, and analytics. Combined with proper error handling and type safety, hooks enable secure and production-ready agent systems with comprehensive observability.
|
||||
- [Execution Hooks Overview →](/edge/en/learn/execution-hooks)
|
||||
- [LLM Call Hooks →](/edge/en/learn/llm-hooks)
|
||||
- [Execution Boundary Hooks →](/edge/en/learn/execution-boundary-hooks)
|
||||
- [Step Hooks →](/edge/en/learn/step-hooks)
|
||||
|
||||
@@ -22,6 +22,10 @@ These tools enable your agents to automate workflows, integrate with external pl
|
||||
Automate browser interactions and web-based workflows.
|
||||
</Card>
|
||||
|
||||
<Card title="Wait Tool" icon="hourglass-half" href="/edge/en/tools/automation/waittool">
|
||||
Pause before re-checking a long-running job such as a build or deployment.
|
||||
</Card>
|
||||
|
||||
<Card title="Zapier Actions Adapter" icon="bolt" href="/en/tools/automation/zapieractionstool">
|
||||
Expose Zapier Actions as CrewAI tools for automation across thousands of apps.
|
||||
</Card>
|
||||
|
||||
124
docs/edge/en/tools/automation/waittool.mdx
Normal file
@@ -0,0 +1,124 @@
|
||||
---
|
||||
title: Wait Tool
|
||||
description: The `WaitTool` lets an agent pause before checking a long-running job again.
|
||||
icon: hourglass-half
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The `WaitTool` pauses execution for a given number of seconds. It exists because agents that
|
||||
kick off long-running work — a sandbox build, a deployment, a batch import, an async API job —
|
||||
otherwise have no way to let time pass. Without it, an agent either polls in a tight loop or
|
||||
gives up before the work finishes.
|
||||
|
||||
The tool takes no API key and has no dependencies beyond the standard library.
|
||||
|
||||
## When to Use It
|
||||
|
||||
The tool's description tells the model to reach for it when out-of-band work needs real time
|
||||
to progress:
|
||||
|
||||
- A sandbox build, test run, or script that is still executing
|
||||
- A deployment or provisioning step that is still rolling out
|
||||
- A batch import, export, or training job
|
||||
- An async API that returned a job id to poll later
|
||||
- A rate limit or backoff that has to cool down before retrying
|
||||
|
||||
The pattern the model is steered toward is: start the job, wait, check status, wait again if it
|
||||
is still running. The description also tells it *not* to wait to pace a conversation or when the
|
||||
information it needs is already available — waiting only lets clock time pass, it does not
|
||||
advance or check the job.
|
||||
|
||||
## Installation
|
||||
|
||||
The tool ships with `crewai-tools`:
|
||||
|
||||
```shell
|
||||
uv add crewai-tools
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.tools import tool
|
||||
from crewai_tools import WaitTool
|
||||
|
||||
wait_tool = WaitTool()
|
||||
|
||||
|
||||
@tool("Check build status")
|
||||
def check_build_status_tool(build_id: str) -> str:
|
||||
"""Return the current status of a build: queued, running, passed, or failed."""
|
||||
# Replace this with a call to your own build system.
|
||||
return my_ci_client.get_build(build_id).status
|
||||
|
||||
|
||||
build_agent = Agent(
|
||||
role="Build Monitor",
|
||||
goal="Start the build and report its final status",
|
||||
backstory="An engineer who knows that builds take time.",
|
||||
tools=[wait_tool, check_build_status_tool],
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
monitor_task = Task(
|
||||
description=(
|
||||
"Start the build, then wait and re-check its status until it finishes."
|
||||
),
|
||||
expected_output="The final build status.",
|
||||
agent=build_agent,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[build_agent], tasks=[monitor_task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
| Argument | Type | Required | Description |
|
||||
| :-------- | :------ | :------- | :----------------------------------------------------------------------------- |
|
||||
| `seconds` | `float` | ✅ | How many seconds to wait. Must be zero or greater. |
|
||||
| `reason` | `str` | ❌ | Optional note on what is being waited for. Echoed back in the tool's result. |
|
||||
|
||||
## Initialization Parameters
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
| :------------ | :------ | :------ | :----------------------------------------------------------------------------------- |
|
||||
| `max_seconds` | `float` | `300` | Upper bound for a single wait. Longer requests are capped to this value, not rejected. |
|
||||
|
||||
## Capping Long Waits
|
||||
|
||||
A single call waits at most `max_seconds`. If an agent asks for more, the tool waits the
|
||||
maximum and says so in its result, so the agent can call it again rather than fail:
|
||||
|
||||
```python Code
|
||||
wait_tool = WaitTool()
|
||||
wait_tool.run(seconds=3600)
|
||||
# 'Waited 300 seconds. Requested 3600 seconds, capped at 300 seconds per call -
|
||||
# call this tool again if more waiting is needed.'
|
||||
```
|
||||
|
||||
Raise the cap when a workflow genuinely needs longer single pauses:
|
||||
|
||||
```python Code
|
||||
wait_tool = WaitTool(max_seconds=1800)
|
||||
```
|
||||
|
||||
## Async Support
|
||||
|
||||
The tool implements both sync and async execution, so it does not block the event loop when
|
||||
awaited:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
|
||||
async def main():
|
||||
result = await wait_tool.arun(seconds=30, reason="waiting for the sandbox build")
|
||||
print(result)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
@@ -11,10 +11,12 @@ mode: "wide"
|
||||
We are still working on improving tools, so there might be unexpected behavior or changes in the future.
|
||||
</Note>
|
||||
|
||||
The FileReadTool conceptually represents a suite of functionalities within the crewai_tools package aimed at facilitating file reading and content retrieval.
|
||||
This suite includes tools for processing batch text files, reading runtime configuration files, and importing data for analytics.
|
||||
It supports a variety of text-based file formats such as `.txt`, `.csv`, `.json`, and more. Depending on the file type, the suite offers specialized functionality,
|
||||
such as converting JSON content into a Python dictionary for ease of use.
|
||||
The `FileReadTool` reads the contents of a file from the local file system and returns it as text.
|
||||
It is useful for batch text file processing, reading runtime configuration files, and importing data for analytics.
|
||||
It supports any text-based file format, such as `.txt`, `.csv`, `.json`, and `.md`.
|
||||
Content is always returned as plain text — parsing it (for example, `json.loads` on a `.json` file) is up to the agent or your own code.
|
||||
|
||||
For large files, `start_line` and `line_count` read just a window of lines instead of loading the whole file.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -31,15 +33,48 @@ To get started with the FileReadTool:
|
||||
```python Code
|
||||
from crewai_tools import FileReadTool
|
||||
|
||||
# Initialize the tool to read any files the agents knows or lean the path for
|
||||
# Initialize the tool to read any file the agent knows or learns the path for
|
||||
file_read_tool = FileReadTool()
|
||||
|
||||
# OR
|
||||
|
||||
# Initialize the tool with a specific file path, so the agent can only read the content of the specified file
|
||||
# Initialize with a specific file path, so the agent reads that file by default
|
||||
file_read_tool = FileReadTool(file_path='path/to/your/file.txt')
|
||||
|
||||
# Read a window of lines (lines 100-149) instead of the whole file
|
||||
partial_content = file_read_tool.run(
|
||||
file_path='path/to/your/file.txt',
|
||||
start_line=100,
|
||||
line_count=50,
|
||||
)
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
- `file_path`: The path to the file you want to read. It accepts both absolute and relative paths. Ensure the file exists and you have the necessary permissions to access it.
|
||||
The agent supplies these at runtime:
|
||||
|
||||
- `file_path`: (Optional) The path to the file you want to read. Accepts absolute and relative paths. Ensure the file exists and you have the necessary permissions to access it. Omit it to read the default file configured at construction; if there is no default, the tool reports that no path was provided.
|
||||
- `start_line`: (Optional) The line number to start reading from (1-indexed). Defaults to `1`.
|
||||
- `line_count`: (Optional) The number of lines to read. If omitted, reads from `start_line` to the end of the file.
|
||||
|
||||
You set these when constructing the tool:
|
||||
|
||||
- `file_path`: (Optional) A default file to read when the agent calls the tool with no arguments.
|
||||
- `base_dir`: (Optional) The directory that runtime paths must stay inside. Defaults to the current working directory.
|
||||
- `encoding`: (Optional) Text encoding used to decode the file. Defaults to `utf-8`.
|
||||
|
||||
## Allowed paths
|
||||
|
||||
Because the file path is usually chosen by an LLM at runtime, reads are confined to a sandbox:
|
||||
|
||||
- Paths supplied at runtime must resolve inside `base_dir`, which defaults to the current working directory. `..` segments and symlinks are resolved before the check, so they cannot be used to escape.
|
||||
- A `file_path` passed to the constructor is developer-declared intent, so it is always allowed past the containment check — even outside `base_dir`. The read itself can still fail if the file is missing, is a directory, or is not permitted. It is pinned when the tool is built, so a later change of working directory cannot repoint it, and the agent can address it either by omitting `file_path` or by using the name shown in the tool's description. Declaring one file does not expose its siblings.
|
||||
|
||||
To let an agent read a directory tree outside the working directory, point `base_dir` at it:
|
||||
|
||||
```python Code
|
||||
# The agent may read anything under /data, and nothing outside it
|
||||
file_read_tool = FileReadTool(base_dir='/data')
|
||||
```
|
||||
|
||||
As a last resort, setting `CREWAI_TOOLS_ALLOW_UNSAFE_PATHS=true` disables path validation. This applies process-wide to every crewai-tools tool, including the SSRF protections on URL-fetching tools, so prefer `base_dir`.
|
||||
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
The `FileWriterTool` is a component of the crewai_tools package, designed to simplify the process of writing content to files with cross-platform compatibility (Windows, Linux, macOS).
|
||||
It is particularly useful in scenarios such as generating reports, saving logs, creating configuration files, and more.
|
||||
This tool handles path differences across operating systems, supports UTF-8 encoding, and automatically creates directories if they don't exist, making it easier to organize your output reliably across different platforms.
|
||||
This tool handles path differences across operating systems, writes UTF-8 by default rather than the platform's locale encoding, and automatically creates directories if they don't exist, making it easier to organize your output reliably across different platforms.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -32,15 +32,45 @@ from crewai_tools import FileWriterTool
|
||||
file_writer_tool = FileWriterTool()
|
||||
|
||||
# Write content to a file in a specified directory
|
||||
result = file_writer_tool._run('example.txt', 'This is a test content.', 'test_directory')
|
||||
result = file_writer_tool.run(
|
||||
filename='example.txt',
|
||||
content='This is a test content.',
|
||||
directory='test_directory',
|
||||
)
|
||||
print(result)
|
||||
```
|
||||
|
||||
## Arguments
|
||||
|
||||
- `filename`: The name of the file you want to create or overwrite.
|
||||
- `content`: The content to write into the file.
|
||||
- `directory` (optional): The path to the directory where the file will be created. Defaults to the current directory (`.`). If the directory does not exist, it will be created.
|
||||
The agent supplies these at runtime:
|
||||
|
||||
- `filename`: The name of the file to write, relative to `directory`. May include subdirectories, which are created if they don't exist.
|
||||
- `content`: The text content to write into the file.
|
||||
- `directory` (optional): The path to the directory where the file will be created. A relative path resolves inside the tool's allowed directory — `base_dir` when set, the current working directory otherwise — and defaults to its root. If the directory does not exist, it will be created.
|
||||
- `overwrite` (optional): Whether to replace the file when it already exists. Accepts `true`/`false` (also `yes`/`no`, `on`/`off`, `1`/`0`). Defaults to `false`, which reports an error instead of replacing existing content.
|
||||
|
||||
You set these when constructing the tool:
|
||||
|
||||
- `base_dir` (optional): The directory that writes must stay inside. Defaults to the current working directory.
|
||||
- `encoding` (optional): Text encoding used to write the file. Defaults to `utf-8`.
|
||||
|
||||
## Allowed paths
|
||||
|
||||
Because both the directory and the filename are usually chosen by an LLM at runtime, writes are confined to a sandbox:
|
||||
|
||||
- The resolved `directory` must be inside `base_dir`, which defaults to the current working directory.
|
||||
- The resolved file must then be inside that `directory`. `..` segments, absolute paths, and symlinks are resolved before both checks, so they cannot be used to escape.
|
||||
|
||||
To let an agent write outside the working directory, point `base_dir` at the target tree:
|
||||
|
||||
```python Code
|
||||
# The agent may write anywhere under /var/output, and nowhere outside it
|
||||
file_writer_tool = FileWriterTool(base_dir='/var/output')
|
||||
```
|
||||
|
||||
<Note>
|
||||
Previously an absolute `directory` could write anywhere the process had permission to. If you relied on that, set `base_dir` to the tree you want to allow. Setting `CREWAI_TOOLS_ALLOW_UNSAFE_PATHS=true` restores the old behavior, but it applies process-wide to every crewai-tools tool, including the SSRF protections on URL-fetching tools, so prefer `base_dir`.
|
||||
</Note>
|
||||
|
||||
## Conclusion
|
||||
|
||||
|
||||
@@ -4,6 +4,330 @@ description: "CrewAI의 제품 업데이트, 개선 사항 및 버그 수정"
|
||||
icon: "clock"
|
||||
mode: "wide"
|
||||
---
|
||||
<Update label="2026년 7월 28일">
|
||||
## v1.15.8
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.8)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- 장시간 실행되는 작업에서 일시 중지를 위한 WaitTool 추가.
|
||||
|
||||
### 버그 수정
|
||||
- FileWriterTool의 쓰기 기능 수정 및 파일 도구의 거친 부분 해결.
|
||||
- E2B 도구에 대해 E2B_API_KEY를 필수 환경 변수로 표시.
|
||||
|
||||
### 문서
|
||||
- 모델 가용성 안내 새로 고침.
|
||||
|
||||
## 기여자
|
||||
|
||||
@github-actions[bot], @joaomdmoura, @lucasgomide, @oalami, @thiagomoretto
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 26일">
|
||||
## v1.15.7
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 버그 수정
|
||||
- 런타임의 CrewAI+ 클라이언트를 통해 레지스트리 기술 해결
|
||||
- GPT-5.6 도구 + reasoning_effort 400에서 복구
|
||||
- Responses API 경로에서 도구 호출 작동
|
||||
- 404 오류 대신 응답 전용 모델 라우팅
|
||||
- CVE-2026-16796 패치를 위해 bedrock-agentcore 버전 업그레이드
|
||||
|
||||
### 관찰 가능성
|
||||
- 관찰 가능성을 위해 런타임에서 기술 사용 이벤트 발행
|
||||
|
||||
### 문서
|
||||
- v1.15.7a1에 대한 스냅샷 및 변경 로그 추가
|
||||
|
||||
## 기여자
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 26일">
|
||||
## v1.15.7a1
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7a1)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 버그 수정
|
||||
- 런타임의 CrewAI+ 클라이언트를 통한 레지스트리 기술 해결 문제 수정.
|
||||
- GPT-5.6 도구 및 reasoning_effort 400 오류에서 복구.
|
||||
- Responses API 경로에서 도구 호출이 작동하도록 수정.
|
||||
- 404 오류를 방지하기 위해 응답 전용 모델을 라우팅.
|
||||
- CVE-2026-16796 패치를 위해 bedrock-agentcore 의존성 버전 증가.
|
||||
|
||||
### 관찰 가능성
|
||||
- 향상된 관찰 가능성을 위해 런타임에서 기술 사용 이벤트 방출.
|
||||
|
||||
### 문서
|
||||
- 버전 1.15.6에 대한 스냅샷 및 변경 로그 업데이트.
|
||||
|
||||
## 기여자
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 24일">
|
||||
## v1.15.6
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.6)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 버그 수정
|
||||
- Anthropic 미리보기 도구 사용 차단 감지 수정.
|
||||
- 엄격한 도구 스키마 속성 이름 유지.
|
||||
- 실패한 크루 및 흐름 실행에서 execution_end 후크 전송.
|
||||
- load_agent_from_repository에서 비동기 get_agent 처리.
|
||||
- 의존성 해결 문제 수정.
|
||||
|
||||
### 문서
|
||||
- v1.15.5에 대한 스냅샷 및 변경 로그.
|
||||
|
||||
## 기여자
|
||||
|
||||
@alex-clawd, @iris-clawd, @lorenzejay, @lucasgomide, @theCyberTech, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 20일">
|
||||
## v1.15.5
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.5)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- 기술 레지스트리 다운로드 인증
|
||||
|
||||
### 문서
|
||||
- v1.15.4에 대한 스냅샷 및 변경 로그 업데이트
|
||||
|
||||
## 기여자
|
||||
|
||||
@vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 17일">
|
||||
## v1.15.4
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.4)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- 기술 저장소를 실험적 상태에서 벗어나도록 승격
|
||||
|
||||
### 문서
|
||||
- Studio 문서에 흐름 추가
|
||||
|
||||
## 기여자
|
||||
|
||||
@jessemiller, @joaomdmoura, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 16일">
|
||||
## v1.15.3
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- PlusAPI 클라이언트에 조직 ID 매개변수 추가
|
||||
- @on을 중심으로 단계 가로채기 포인트 및 실행 훅 문서 재작업
|
||||
- 실행 경계 가로채기 포인트 연결
|
||||
- 일반 가로채기 훅 디스패처 추가
|
||||
- TUI(헤드리스 터미널 대체)에서 선언적 흐름 실행
|
||||
|
||||
### 버그 수정
|
||||
- OUTPUT 훅 결과와 kickoff-completed 이벤트 동기화
|
||||
- null 리포지토리 에이전트 속성 수정
|
||||
- after_llm_call 훅이 네이티브 도구 실행을 방해하지 않도록 보장
|
||||
- 핸들러가 히스토리를 잘라낼 때 턴 응답의 중복 추가 방지
|
||||
- 도구 결과 캐싱을 기본값이 아닌 선택 사항으로 설정
|
||||
- 생성 시 작성된 도구 설명 재작성 중지
|
||||
- 에이전트 및 크루 결과에서 두 이름 아래의 토큰 사용량 노출
|
||||
- kickoff 결과에 대한 호출당 사용 메트릭 보고
|
||||
- route_turn()이 falsy를 반환할 때 이전 턴의 의도를 재생하지 않도록 중지
|
||||
|
||||
### 문서화
|
||||
- 실행 훅 그룹화 업데이트 및 모든 훅 컨텍스트 문서화
|
||||
|
||||
## 기여자
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 16일">
|
||||
## v1.15.3a2
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a2)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 버그 수정
|
||||
- OUTPUT 훅 결과와 kickoff-completed 이벤트의 동기화 수정
|
||||
|
||||
### 문서
|
||||
- v1.15.3a1에 대한 스냅샷 및 변경 로그 업데이트
|
||||
|
||||
### 의존성 업데이트
|
||||
- PYSEC-2026-3447 문제를 해결하기 위해 setuptools를 0.83.0으로 업데이트
|
||||
|
||||
## 기여자
|
||||
|
||||
@lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 16일">
|
||||
## v1.15.3a1
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a1)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- PlusAPI 클라이언트에 조직 ID 매개변수 추가.
|
||||
- `@on` 주위의 실행 후크 문서를 재작업하고 단계 가로채기 포인트 추가.
|
||||
- 실행 경계 가로채기 포인트 연결.
|
||||
- 일반 가로채기 후크 디스패처 추가.
|
||||
- TUI(헤드리스 터미널 대체)에서 선언적 흐름 실행.
|
||||
- 사용자 정의 OpenAI URL 개선.
|
||||
|
||||
### 버그 수정
|
||||
- null 리포지토리 에이전트 속성 수정.
|
||||
- 기본 도구 실행이 중단되지 않도록 `after_llm_call` 후크 수정.
|
||||
- 핸들러가 기록을 잘라낼 때 턴 응답을 이중으로 추가하는 것을 중지.
|
||||
- 도구 결과 캐싱을 기본값이 아닌 선택적으로 설정.
|
||||
- 생성 시 작성된 도구 설명을 재작성하는 것을 중지.
|
||||
- 에이전트 및 크루 결과에서 두 이름으로 토큰 사용량 노출.
|
||||
- 시작 결과에서 호출당 사용 메트릭 보고.
|
||||
- `route_turn()`이 falsy를 반환할 때 이전 턴의 의도를 재생하지 않도록 중지.
|
||||
- 시작 및 흐름 완료 이벤트 전에 메모리 쓰기 배수.
|
||||
|
||||
### 문서
|
||||
- 실행 후크를 그룹화하고 모든 후크 컨텍스트 문서화.
|
||||
- 실행 후크에 대한 문서 업데이트.
|
||||
|
||||
## 기여자
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 7일">
|
||||
## v1.15.2
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- 크루 마법사에서 최신 LLM 모델을 동적으로 가져옵니다.
|
||||
- 인라인 기술 정의를 지원합니다.
|
||||
- 생성된 흐름 정의 작성 기술을 추가합니다.
|
||||
- 템플릿화된 흐름 액션 입력을 지원합니다.
|
||||
- 흐름 CEL 프롬프트를 위한 텍스트 도우미를 추가합니다.
|
||||
- 흐름 기술 예제를 위한 텍스트 도우미를 추가합니다.
|
||||
- AgentExecutor에서 메시지 설정 및 피드백 처리를 구현합니다.
|
||||
- 흐름 정의에 리포지토리 에이전트를 추가합니다.
|
||||
- 흐름을 위한 스트림 프레임 프로토콜을 정의합니다.
|
||||
- CrewDefinition에서 도구 및 앱 유형을 지정합니다.
|
||||
- 템플릿 명령을 crewAIInc-fde 조직으로 다시 포인팅합니다.
|
||||
|
||||
### 버그 수정
|
||||
- 정확한 API 키로 모델 카탈로그 캐시를 키하고 TTL을 단축하며 Ollama를 건너뜁니다.
|
||||
- `crewai run` 흐름 입력 해상도 및 상태 스키마에서 프롬프트를 통합합니다.
|
||||
- onnx 1.22.0 및 nltk PYSEC-2026-597에 대한 pip-audit 실패를 해결합니다.
|
||||
- 흐름에 대한 버전을 작성하고 있는지 확인합니다.
|
||||
- bedrock 추가에 aiobotocore를 포함합니다.
|
||||
- 자기 청취 흐름 메서드를 거부합니다.
|
||||
- Edge에서 문서 버전 내비게이션을 제거하여 새 페이지가 누락되지 않도록 합니다.
|
||||
|
||||
### 문서
|
||||
- 새로운 대시보드 변경 사항에 맞추어 규칙에서 정책으로 언어를 업데이트합니다.
|
||||
- 흐름 에이전트 옵션을 문서화합니다.
|
||||
- 내비게이션에 스트리밍 문서를 추가합니다.
|
||||
- 에이전트 제어 평면에서 비용 제한 규칙 유형을 문서화합니다.
|
||||
- Datadog 가이드에서 CREWAI_LOG_FORMAT 참조를 제거합니다.
|
||||
|
||||
## 기여자
|
||||
|
||||
@akaKuruma, @danielfsbarreto, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @manisrinivasan2k1, @renatonitta, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 7월 1일">
|
||||
## v1.15.2a2
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a2)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- bedrock 추가에 aiobotocore 추가
|
||||
- 흐름 에이전트 옵션 문서화
|
||||
- 흐름 기술 예제에 텍스트 도우미 추가
|
||||
- 흐름 CEL 프롬프트를 위한 텍스트 도우미 추가
|
||||
- 탐색에 스트리밍 문서 추가
|
||||
|
||||
### 버그 수정
|
||||
- 자기 청취 흐름 메서드 거부
|
||||
|
||||
### 문서
|
||||
- v1.15.2a1에 대한 스냅샷 및 변경 로그 업데이트
|
||||
- AGENTS.md 파일 압축
|
||||
|
||||
## 기여자
|
||||
|
||||
@akaKuruma, @github-code-quality[bot], @lorenzejay, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 6월 30일">
|
||||
## v1.15.2a1
|
||||
|
||||
[GitHub 릴리스 보기](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a1)
|
||||
|
||||
## 변경 사항
|
||||
|
||||
### 기능
|
||||
- 템플릿 명령을 crewAIInc-fde 조직으로 재지정
|
||||
- 인라인 기술 정의 지원
|
||||
- 흐름을 위한 스트림 프레임 프로토콜 정의
|
||||
- CrewDefinition에 타입 도구 및 앱 추가
|
||||
- 생성된 흐름 정의 저작 기술 추가
|
||||
|
||||
### 버그 수정
|
||||
- 새로운 페이지가 삭제되는 것을 방지하기 위해 Edge에서 문서 버전 탐색 제거
|
||||
|
||||
### 문서
|
||||
- 에이전트 제어 평면에서 비용 한도 규칙 유형 문서화
|
||||
- Datadog 가이드에서 CREWAI_LOG_FORMAT 참조 제거
|
||||
|
||||
## 기여자
|
||||
|
||||
@danielfsbarreto, @joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026년 6월 26일">
|
||||
## v1.15.1
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ Large Language Models(LLM)는 CrewAI 에이전트의 핵심 지능입니다. 에
|
||||
컨텍스트 윈도우는 LLM이 한 번에 처리할 수 있는 텍스트 양을 결정합니다. 더 큰 윈도우(예: 128K 토큰)는 더 많은 문맥을 다룰 수 있지만, 비용과 속도 면에서 더 부담이 될 수 있습니다.
|
||||
</Card>
|
||||
<Card title="Temperature" icon="temperature-three-quarters">
|
||||
Temperature(0.0에서 1.0)는 응답의 무작위성을 조절합니다. 낮은 값(예: 0.2)은 더 집중적이고 결정적인 결과를, 높은 값(예: 0.8)은 창의성과 다양성을 높입니다.
|
||||
Temperature는 일부 모델이 지원하는 샘플링 제어 옵션입니다. 값이 낮을수록 일반적으로 샘플링이 더 집중되고, 값이 높을수록 변동성이 커집니다. 일부 최신 추론 모델은 이 파라미터를 무시하거나 더 이상 권장하지 않거나 거부하므로, 설정하기 전에 선택한 모델의 문서를 확인하세요.
|
||||
</Card>
|
||||
<Card title="제공자 선택" icon="server">
|
||||
각 LLM 제공자(예: OpenAI, Anthropic, Google)는 다양한 기능, 가격, 특성을 가진 모델을 제공합니다. 정확성, 속도, 비용 등 요구 사항에 따라 선택하세요.
|
||||
@@ -37,7 +37,7 @@ CrewAI 코드 내에는 사용할 모델을 지정할 수 있는 여러 위치
|
||||
가장 간단하게 시작할 수 있는 방법입니다. `.env` 파일이나 앱 코드에서 환경 변수로 직접 모델을 설정할 수 있습니다. `crewai create`를 사용해 프로젝트를 부트스트랩했다면 이미 설정되어 있을 수 있습니다.
|
||||
|
||||
```bash .env
|
||||
MODEL=model-id # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...
|
||||
MODEL=provider/model-id # e.g. openai/gpt-5.6-terra
|
||||
|
||||
# 반드시 여기에서 API 키도 설정하세요. 아래 제공자
|
||||
# 섹션을 참고하세요.
|
||||
@@ -56,7 +56,7 @@ CrewAI 코드 내에는 사용할 모델을 지정할 수 있는 여러 위치
|
||||
goal: Conduct comprehensive research and analysis
|
||||
backstory: A dedicated research professional with years of experience
|
||||
verbose: true
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
llm: provider/model-id # e.g. anthropic/claude-sonnet-4-6
|
||||
# (아래 제공자 구성 예제 참고)
|
||||
```
|
||||
|
||||
@@ -75,32 +75,24 @@ CrewAI 코드 내에는 사용할 모델을 지정할 수 있는 여러 위치
|
||||
from crewai import LLM
|
||||
|
||||
# 기본 설정
|
||||
llm = LLM(model="model-id-here") # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
llm = LLM(model="provider/model-id") # e.g. gemini/gemini-3.6-flash
|
||||
|
||||
# 자세한 파라미터로 고급 설정
|
||||
llm = LLM(
|
||||
model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
temperature=0.7, # 더욱 창의적인 결과를 원할 때 높게 설정
|
||||
timeout=120, # 응답을 기다릴 최대 초
|
||||
max_tokens=4000, # 응답의 최대 길이
|
||||
top_p=0.9, # 누클리어스 샘플링 파라미터
|
||||
frequency_penalty=0.1 , # 반복 줄이기
|
||||
presence_penalty=0.1, # 주제 다양성 높이기
|
||||
model="provider/model-id",
|
||||
timeout=120,
|
||||
max_tokens=4000,
|
||||
response_format={"type": "json"}, # 구조화된 출력용
|
||||
seed=42 # 결과 재현성 확보용
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
파라미터 설명:
|
||||
- `temperature`: 랜덤성 제어 (0.0-1.0)
|
||||
- `timeout`: 응답 대기 최대 시간
|
||||
- `max_tokens`: 응답 길이 제한
|
||||
- `top_p`: 샘플링 시 temperature의 대체값
|
||||
- `frequency_penalty`: 단어 반복 감소
|
||||
- `presence_penalty`: 새로운 주제 생성 유도
|
||||
- `response_format`: 출력 구조 지정
|
||||
- `seed`: 일관된 출력 보장
|
||||
|
||||
`temperature`, `top_p` 같은 샘플링 제어, 페널티 파라미터, 토큰 제한 파라미터 이름, 추론 제어는 모델별로 다릅니다. 선택한 제공자와 모델이 지원하는 경우에만 추가하세요. 아래 제공자 예시와 해당 제공자의 모델 문서를 참고하세요.
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -119,6 +111,10 @@ CrewAI 코드 내에는 사용할 모델을 지정할 수 있는 여러 위치
|
||||
CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양한 LLM 공급자를 지원합니다.
|
||||
이 섹션에서는 프로젝트의 요구에 가장 적합한 LLM을 선택, 구성, 최적화하는 데 도움이 되는 자세한 예시를 제공합니다.
|
||||
|
||||
<Warning>
|
||||
모델 가용성은 자주 변경되며 계정, 리전, 클라우드 플랫폼에 따라 달라질 수 있습니다. 아래 예시는 작성 시점에 제공되는 모델을 사용하지만 전체 지원 목록은 아닙니다. 배포하기 전에 연결된 제공자 모델 카탈로그에서 모델 ID와 수명 주기 상태를 확인하세요.
|
||||
</Warning>
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI">
|
||||
`.env` 파일에 다음 환경 변수를 설정하십시오:
|
||||
@@ -137,28 +133,13 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4", # call model by provider/model_name
|
||||
temperature=0.8,
|
||||
max_tokens=150,
|
||||
top_p=0.9,
|
||||
frequency_penalty=0.1,
|
||||
presence_penalty=0.1,
|
||||
stop=["END"],
|
||||
seed=42
|
||||
model="openai/gpt-5.6-terra",
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4000
|
||||
)
|
||||
```
|
||||
|
||||
OpenAI는 다양한 모델과 기능을 제공하는 대표적인 LLM 공급자 중 하나입니다.
|
||||
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|-------------------|-------------------|-----------------------------------------------|
|
||||
| GPT-4 | 8,192 토큰 | 고정확도 작업, 복잡한 추론 |
|
||||
| GPT-4 Turbo | 128,000 토큰 | 장문 콘텐츠, 문서 분석 |
|
||||
| GPT-4o & GPT-4o-mini | 128,000 토큰 | 비용 효율적인 대용량 컨텍스트 처리 |
|
||||
| o3-mini | 200,000 토큰 | 빠른 추론, 복잡한 추론 |
|
||||
| o1-mini | 128,000 토큰 | 빠른 추론, 복잡한 추론 |
|
||||
| o1-preview | 128,000 토큰 | 빠른 추론, 복잡한 추론 |
|
||||
| o1 | 200,000 토큰 | 빠른 추론, 복잡한 추론 |
|
||||
OpenAI는 정기적으로 모델을 추가하고 이전 스냅샷을 폐기합니다. 현재 모델 ID, 컨텍스트 윈도우, 엔드포인트 호환성, 수명 주기 정보는 [OpenAI 모델 카탈로그](https://developers.openai.com/api/docs/models)를 확인하세요.
|
||||
|
||||
**Responses API:**
|
||||
|
||||
@@ -215,14 +196,7 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
)
|
||||
```
|
||||
|
||||
https://llama.developer.meta.com/docs/models/ 에 기재된 모든 모델이 지원됩니다.
|
||||
|
||||
| 모델 ID | 입력 컨텍스트 길이 | 출력 컨텍스트 길이 | 입력 모달리티 | 출력 모달리티 |
|
||||
| ------- | ------------------ | ------------------ | ---------------- | ---------------- |
|
||||
| `meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8` | 128k | 4028 | 텍스트, 이미지 | 텍스트 |
|
||||
| `meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 128k | 4028 | 텍스트, 이미지 | 텍스트 |
|
||||
| `meta_llama/Llama-3.3-70B-Instruct` | 128k | 4028 | 텍스트 | 텍스트 |
|
||||
| `meta_llama/Llama-3.3-8B-Instruct` | 128k | 4028 | 텍스트 | 텍스트 |
|
||||
현재 모델 제품군, 모달리티, 컨텍스트 지침은 [Meta Llama 모델 개요](https://ai.meta.com/llama/get-started/)를 확인하세요.
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
@@ -291,10 +265,12 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-sonnet-20240229-v1:0",
|
||||
temperature=0.7
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
max_tokens=4096
|
||||
)
|
||||
```
|
||||
|
||||
현재 모델 ID와 기능은 Anthropic의 [모델 개요](https://platform.claude.com/docs/en/about-claude/models/overview)를 확인하고, 프로덕션에서 모델을 고정하기 전에 [모델 지원 중단 표](https://platform.claude.com/docs/en/about-claude/model-deprecations)를 검토하세요.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google (Gemini API)">
|
||||
@@ -319,8 +295,7 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7,
|
||||
model="gemini/gemini-3.6-flash",
|
||||
)
|
||||
```
|
||||
|
||||
@@ -339,8 +314,7 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -352,47 +326,15 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
자세한 내용은 [Vertex AI Express 모드 문서](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/start/quickstart?usertype=apikey)를 참조하세요.
|
||||
</Info>
|
||||
|
||||
### Gemini 모델
|
||||
|
||||
Google은 다양한 용도에 최적화된 강력한 모델을 제공합니다.
|
||||
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|----------------------------------|-----------------|------------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M 토큰 | 적응형 사고, 비용 효율성 |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M 토큰 | 향상된 사고 및 추론, 멀티모달 이해, 고급 코딩 등 |
|
||||
| gemini-2.0-flash | 1M 토큰 | 차세대 기능, 속도, 사고, 실시간 스트리밍 |
|
||||
| gemini-2.0-flash-lite | 1M 토큰 | 비용 효율성과 낮은 대기 시간 |
|
||||
| gemini-1.5-flash | 1M 토큰 | 밸런스 잡힌 멀티모달 모델, 대부분의 작업에 적합 |
|
||||
| gemini-1.5-flash-8B | 1M 토큰 | 가장 빠르고, 비용 효율적, 고빈도 작업에 적합 |
|
||||
| gemini-1.5-pro | 2M 토큰 | 최고의 성능, 논리적 추론, 코딩, 창의적 협업 등 다양한 추론 작업에 적합 |
|
||||
|
||||
전체 모델 목록은 [Gemini 모델 문서](https://ai.google.dev/gemini-api/docs/models)에서 확인할 수 있습니다.
|
||||
|
||||
### Gemma
|
||||
|
||||
Gemini API를 통해 Google 인프라에서 호스팅되는 [Gemma 모델](https://ai.google.dev/gemma/docs)도 API 키를 이용해 사용할 수 있습니다.
|
||||
|
||||
| 모델 | 컨텍스트 윈도우 |
|
||||
|----------------|----------------|
|
||||
| gemma-3-1b-it | 32k 토큰 |
|
||||
| gemma-3-4b-it | 32k 토큰 |
|
||||
| gemma-3-12b-it | 32k 토큰 |
|
||||
| gemma-3-27b-it | 128k 토큰 |
|
||||
Google은 현재 Gemini ID, 기능, 수명 주기 단계를 [Gemini 모델 카탈로그](https://ai.google.dev/gemini-api/docs/models)에 게시합니다. 안정 또는 preview 모델을 선택하기 전에 [지원 중단 일정](https://ai.google.dev/gemini-api/docs/deprecations)을 확인하세요. Gemini API는 [Gemma 모델](https://ai.google.dev/gemma/docs)도 호스팅합니다.
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Google (Vertex AI)">
|
||||
Google Cloud Console에서 자격증명을 받아 JSON 파일로 저장한 후, 다음 코드로 로드하세요:
|
||||
```python Code
|
||||
import json
|
||||
|
||||
file_path = 'path/to/vertex_ai_service_account.json'
|
||||
|
||||
# Load the JSON file
|
||||
with open(file_path, 'r') as file:
|
||||
vertex_credentials = json.load(file)
|
||||
|
||||
# Convert the credentials to a JSON string
|
||||
vertex_credentials_json = json.dumps(vertex_credentials)
|
||||
[애플리케이션 기본 사용자 인증 정보](https://cloud.google.com/docs/authentication/provide-credentials-adc)로 인증한 다음, Vertex AI를 사용하도록 네이티브 Gemini 제공업체를 구성하세요:
|
||||
```toml .env
|
||||
GOOGLE_GENAI_USE_VERTEXAI=true
|
||||
GOOGLE_CLOUD_PROJECT=<your-project-id>
|
||||
GOOGLE_CLOUD_LOCATION=<location>
|
||||
```
|
||||
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
@@ -400,27 +342,15 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini-1.5-pro-latest", # or vertex_ai/gemini-1.5-pro-latest
|
||||
temperature=0.7,
|
||||
vertex_credentials=vertex_credentials_json
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
Google은 다양한 용도에 최적화된 강력한 모델들을 제공합니다:
|
||||
사용 가능한 Vertex AI 모델과 리전은 [Vertex AI 모델 정보](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models)를 확인하세요.
|
||||
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|----------------------------------|-----------------|------------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M 토큰 | 적응형 사고, 비용 효율성 |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M 토큰 | 향상된 사고 및 추론, 멀티모달 이해, 고급 코딩 등 |
|
||||
| gemini-2.0-flash | 1M 토큰 | 차세대 기능, 속도, 사고, 실시간 스트리밍 |
|
||||
| gemini-2.0-flash-lite | 1M 토큰 | 비용 효율성과 낮은 대기 시간 |
|
||||
| gemini-1.5-flash | 1M 토큰 | 밸런스 잡힌 멀티모달 모델, 대부분의 작업에 적합 |
|
||||
| gemini-1.5-flash-8B | 1M 토큰 | 가장 빠르고, 비용 효율적, 고빈도 작업에 적합 |
|
||||
| gemini-1.5-pro | 2M 토큰 | 최고의 성능, 논리적 추론, 코딩, 창의적 협업 등 다양한 추론 작업에 적합 |
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
**참고:** 이 경로는 CrewAI의 네이티브 Gemini 통합을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
uv add "crewai[google-genai]"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
@@ -455,7 +385,7 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
|
||||
model="bedrock/us.anthropic.claude-sonnet-4-6"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -463,34 +393,6 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
|
||||
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)은 대표적인 AI 회사들의 여러 파운데이션 모델에 통합 API를 통해 접근할 수 있는 매니지드 서비스로, 안전하고 책임감 있는 AI 응용프로그램 개발을 가능하게 해줍니다.
|
||||
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|-----------------------------|--------------------|------------------------------------------------------------------------|
|
||||
| Amazon Nova Pro | 최대 300k 토큰 | 다양한 작업에서 정확성, 속도, 비용을 균형 있게 제공하는 고성능 모델 |
|
||||
| Amazon Nova Micro | 최대 128k 토큰 | 텍스트 전용, 최소 레이턴시 응답에 최적화된 비용 효율적 고성능 모델 |
|
||||
| Amazon Nova Lite | 최대 300k 토큰 | 이미지, 비디오, 텍스트를 아우르는 실시간 멀티모달 처리 |
|
||||
| Claude 3.7 Sonnet | 최대 128k 토큰 | 복잡한 추론, 코딩 및 AI 에이전트에 적합한 고성능 모델 |
|
||||
| Claude 3.5 Sonnet v2 | 최대 200k 토큰 | 소프트웨어 공학, 에이전트 기능, 컴퓨터 상호작용에 특화된 최신 모델 |
|
||||
| Claude 3.5 Sonnet | 최대 200k 토큰 | 다양한 작업에 탁월한 지능 및 추론 제공, 최적의 속도·비용 모델 |
|
||||
| Claude 3.5 Haiku | 최대 200k 토큰 | 빠르고 컴팩트한 멀티모달 모델, 신속하고 자연스러운 대화에 최적 |
|
||||
| Claude 3 Sonnet | 최대 200k 토큰 | 지능과 속도의 균형 잡힌 멀티모달 모델, 대규모 배포에 적합 |
|
||||
| Claude 3 Haiku | 최대 200k 토큰 | 컴팩트한 고속 멀티모달 모델, 신속한 응답과 자연스러운 대화형 상호작용 |
|
||||
| Claude 3 Opus | 최대 200k 토큰 | 인간 같은 추론과 우수한 문맥 이해로 복잡한 작업 수행 |
|
||||
| Claude 2.1 | 최대 200k 토큰 | 확장된 컨텍스트, 신뢰도 개선, 로봇화 감소, 장문 및 RAG 적용에 적합 |
|
||||
| Claude | 최대 100k 토큰 | 복잡한 대화, 창의적 콘텐츠 생성, 정교한 지시 수행에 탁월 |
|
||||
| Claude Instant | 최대 100k 토큰 | 일상 대화, 분석, 요약, 문서 Q&A 등 빠르고 비용 효율적인 모델 |
|
||||
| Llama 3.1 405B Instruct | 최대 128k 토큰 | 챗봇, 코딩, 도메인 특화 작업을 위한 합성 데이터 생성 및 추론용 첨단 LLM |
|
||||
| Llama 3.1 70B Instruct | 최대 128k 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 능력 강화 |
|
||||
| Llama 3.1 8B Instruct | 최대 128k 토큰 | 우수한 언어 이해, 추론, 텍스트 생성 기능의 최첨단 모델 |
|
||||
| Llama 3 70B Instruct | 최대 8k 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 기능 강화 |
|
||||
| Llama 3 8B Instruct | 최대 8k 토큰 | 첨단 언어 이해력, 추론, 텍스트 생성이 가능한 최첨단 LLM |
|
||||
| Titan Text G1 - Lite | 최대 4k 토큰 | 영어 과제 및 요약, 콘텐츠 생성에 최적화된 경량 비용 효율적 모델 |
|
||||
| Titan Text G1 - Express | 최대 8k 토큰 | 일반 언어, 대화, RAG 지원, 영어 및 100여 개 언어 지원 |
|
||||
| Cohere Command | 최대 4k 토큰 | 사용자의 명령 수행, 실질적 기업 솔루션 제공에 특화된 모델 |
|
||||
| Jurassic-2 Mid | 최대 8,191 토큰 | 다양한 언어 과제(Q&A, 요약, 생성 등)에 적합한 품질-비용 균형 모델 |
|
||||
| Jurassic-2 Ultra | 최대 8,191 토큰 | 고급 텍스트 생성과 이해, 분석 및 콘텐츠 제작 등 복잡한 작업 수행 |
|
||||
| Jamba-Instruct | 최대 256k 토큰 | 비용 효율적인 대용량 문맥 창작, 요약, Q&A에 최적화된 모델 |
|
||||
| Mistral 7B Instruct | 최대 32k 토큰 | 명령을 따르고, 요청을 완성하며, 창의적 텍스트를 생성하는 LLM |
|
||||
| Mistral 8x7B Instruct | 최대 32k 토큰 | 명령 및 요청 완성, 창의적 텍스트 생성이 가능한 MOE LLM |
|
||||
|
||||
</Accordion>
|
||||
|
||||
@@ -543,81 +445,13 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nvidia_nim/meta/llama3-70b-instruct",
|
||||
model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
Nvidia NIM은 일반 목적 작업부터 특수 목적 응용까지 다양한 용도를 위한 모델 제품군을 제공합니다.
|
||||
NVIDIA NIM의 호스팅 카탈로그는 자주 변경됩니다. 현재 endpoint를 선택하고 모델 ID, 모달리티, 컨텍스트 제한을 확인하려면 [NVIDIA NIM 모델 카탈로그](https://build.nvidia.com/models)를 사용하세요.
|
||||
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|------------------------------------------------------------------------|----------------|---------------------------------------------------------------------|
|
||||
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8,192 토큰 | 챗봇, 가상 비서, 콘텐츠 생성을 위한 최신형 소형 언어 모델 |
|
||||
| nvidia/nemotron-4-mini-hindi-4b-instruct | 4,096 토큰 | 힌디-영어 SLM, 힌디 언어 전용 온디바이스 추론 |
|
||||
| nvidia/llama-3.1-nemotron-70b-instruct | 128k 토큰 | 더욱 도움이 되는 답변을 위해 커스터마이즈됨 |
|
||||
| nvidia/llama3-chatqa-1.5-8b | 128k 토큰 | 챗봇, 검색엔진용 맥락 인식 응답 생성에 탁월한 고급 LLM |
|
||||
| nvidia/llama3-chatqa-1.5-70b | 128k 토큰 | 챗봇, 검색엔진용 맥락 인식 응답 생성에 탁월한 고급 LLM |
|
||||
| nvidia/vila | 128k 토큰 | 텍스트/이미지/비디오 이해 및 정보성 응답 생성을 지원하는 멀티모달 모델 |
|
||||
| nvidia/neva-22 | 4,096 토큰 | 텍스트/이미지 이해 및 정보성 응답 생성을 지원하는 멀티모달 모델 |
|
||||
| nvidia/nemotron-mini-4b-instruct | 8,192 토큰 | 일반 목적 작업 |
|
||||
| nvidia/usdcode-llama3-70b-instruct | 128k 토큰 | OpenUSD 지식 질의 응답, USD-Python 코드 생성이 가능한 최신 LLM |
|
||||
| nvidia/nemotron-4-340b-instruct | 4,096 토큰 | 실제 데이터를 모사하는 다양한 합성 데이터 생성 |
|
||||
| meta/codellama-70b | 100k 토큰 | 자연어 → 코드 및 코드 → 자연어 전환 가능한 LLM |
|
||||
| meta/llama2-70b | 4,096 토큰 | 텍스트, 코드 생성에 최적화된 최첨단 대형 언어 모델 |
|
||||
| meta/llama3-8b-instruct | 8,192 토큰 | 최첨단 언어 이해 및 추론, 텍스트 생성 기능 모델 |
|
||||
| meta/llama3-70b-instruct | 8,192 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 |
|
||||
| meta/llama-3.1-8b-instruct | 128k 토큰 | 최첨단 언어 이해 및 추론, 텍스트 생성 기능의 첨단 모델 |
|
||||
| meta/llama-3.1-70b-instruct | 128k 토큰 | 복잡한 대화, 우수한 문맥 및 추론, 텍스트 생성 |
|
||||
| meta/llama-3.1-405b-instruct | 128k 토큰 | 챗봇, 코딩, 도메인 특화 작업 합성 데이터 생성 및 추론 |
|
||||
| meta/llama-3.2-1b-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 모델 |
|
||||
| meta/llama-3.2-3b-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 |
|
||||
| meta/llama-3.2-11b-vision-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 |
|
||||
| meta/llama-3.2-90b-vision-instruct | 128k 토큰 | 최첨단 소형 언어 이해, 추론, 텍스트 생성 |
|
||||
| google/gemma-7b | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
|
||||
| google/gemma-2b | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
|
||||
| google/codegemma-7b | 8,192 토큰 | 코드 생성 및 보완에 특화된 Google Gemma-7B 기반 모델 |
|
||||
| google/codegemma-1.1-7b | 8,192 토큰 | 코드 생성, 보완, 추론, 명령 수행에 강점을 가진 고급 프로그래밍 모델 |
|
||||
| google/recurrentgemma-2b | 8,192 토큰 | 긴 시퀀스 생성 시 빠른 추론을 가능케 하는 순환 아키텍처 LLM |
|
||||
| google/gemma-2-9b-it | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
|
||||
| google/gemma-2-27b-it | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
|
||||
| google/gemma-2-2b-it | 8,192 토큰 | 문자열의 이해, 변환, 코드 생성을 지원하는 최첨단 텍스트 생성 모델 |
|
||||
| google/deplot | 512 토큰 | 플롯 이미지를 표로 변환하는 원샷 비주얼 언어 이해 모델 |
|
||||
| google/paligemma | 8,192 토큰 | 텍스트, 이미지 입력 이해 및 정보성 응답 생성에 능한 비전 언어 모델 |
|
||||
| mistralai/mistral-7b-instruct-v0.2 | 32k 토큰 | 명령을 따르고, 요청을 완성하며, 창의적 텍스트 생성이 가능한 LLM |
|
||||
| mistralai/mixtral-8x7b-instruct-v0.1 | 8,192 토큰 | 명령 및 요청 완성, 창의 텍스트 생성이 가능한 MOE LLM |
|
||||
| mistralai/mistral-large | 4,096 토큰 | 실제 데이터 특성을 모방하는 다양한 합성 데이터 생성 |
|
||||
| mistralai/mixtral-8x22b-instruct-v0.1 | 8,192 토큰 | 실제 데이터 특성을 모방하는 다양한 합성 데이터 생성 |
|
||||
| mistralai/mistral-7b-instruct-v0.3 | 32k 토큰 | 명령을 따르고, 요청을 완성하며, 창의적 텍스트 생성이 가능한 LLM |
|
||||
| nv-mistralai/mistral-nemo-12b-instruct | 128k 토큰 | 추론, 코드, 다국어 작업에 적합한 최첨단 언어 모델; 단일 GPU에서 구동 |
|
||||
| mistralai/mamba-codestral-7b-v0.1 | 256k 토큰 | 광범위한 프로그래밍 언어 및 작업에서 코드 작성 및 상호작용 전용 모델 |
|
||||
| microsoft/phi-3-mini-128k-instruct | 128K 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
|
||||
| microsoft/phi-3-mini-4k-instruct | 4,096 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
|
||||
| microsoft/phi-3-small-8k-instruct | 8,192 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
|
||||
| microsoft/phi-3-small-128k-instruct | 128K 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
|
||||
| microsoft/phi-3-medium-4k-instruct | 4,096 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
|
||||
| microsoft/phi-3-medium-128k-instruct | 128K 토큰 | 수학·논리 추론에 강한 경량 최신 공개 LLM |
|
||||
| microsoft/phi-3.5-mini-instruct | 128K 토큰 | 지연, 메모리/컴퓨트 한계 환경에서 AI 응용프로그램 구동 가능한 다국어 LLM |
|
||||
| microsoft/phi-3.5-moe-instruct | 128K 토큰 | 연산 효율적 콘텐츠 생성을 위한 Mixture of Experts 기반 첨단 LLM |
|
||||
| microsoft/kosmos-2 | 1,024 토큰 | 이미지의 시각적 요소 이해 및 추론을 위한 획기적 멀티모달 모델 |
|
||||
| microsoft/phi-3-vision-128k-instruct | 128k 토큰 | 이미지에서 고품질 추론이 가능한 최첨단 공개 멀티모달 모델 |
|
||||
| microsoft/phi-3.5-vision-instruct | 128k 토큰 | 이미지에서 고품질 추론이 가능한 최첨단 공개 멀티모달 모델 |
|
||||
| databricks/dbrx-instruct | 12k 토큰 | 언어 이해, 코딩, RAG에 최신 성능을 제공하는 범용 LLM |
|
||||
| snowflake/arctic | 1,024 토큰 | SQL 생성 및 코딩에 집중한 기업용 고효율 추론 모델 |
|
||||
| aisingapore/sea-lion-7b-instruct | 4,096 토큰 | 동남아 언어 및 문화 다양성을 반영하는 LLM |
|
||||
| ibm/granite-8b-code-instruct | 4,096 토큰 | 소프트웨어 프로그래밍 LLM, 코드 생성, 완성, 설명, 멀티턴 전환 |
|
||||
| ibm/granite-34b-code-instruct | 8,192 토큰 | 소프트웨어 프로그래밍 LLM, 코드 생성, 완성, 설명, 멀티턴 전환 |
|
||||
| ibm/granite-3.0-8b-instruct | 4,096 토큰 | RAG, 요약, 분류, 코드, 에이전틱AI 지원 첨단 소형 언어 모델 |
|
||||
| ibm/granite-3.0-3b-a800m-instruct | 4,096 토큰 | RAG, 요약, 엔터티 추출, 분류에 최적화된 고효율 Mixture of Experts 모델 |
|
||||
| mediatek/breeze-7b-instruct | 4,096 토큰 | 실제 데이터 특성을 모방하는 다양한 합성 데이터 생성 |
|
||||
| upstage/solar-10.7b-instruct | 4,096 토큰 | 지시 따르기, 추론, 수학 등에서 뛰어난 NLP 작업 수행 |
|
||||
| writer/palmyra-med-70b-32k | 32k 토큰 | 의료 분야에서 정확하고 문맥에 맞는 응답 생성에 선도적인 LLM |
|
||||
| writer/palmyra-med-70b | 32k 토큰 | 의료 분야에서 정확하고 문맥에 맞는 응답 생성에 선도적인 LLM |
|
||||
| writer/palmyra-fin-70b-32k | 32k 토큰 | 금융 분석, 보고, 데이터 처리에 특화된 LLM |
|
||||
| 01-ai/yi-large | 32k 토큰 | 영어, 중국어로 훈련, 챗봇 및 창의적 글쓰기 등 다양한 작업에 사용 |
|
||||
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k 토큰 | 고급 코드 생성, 완성, 인필링 등의 기능을 제공하는 강력한 코딩 모델 |
|
||||
| rakuten/rakutenai-7b-instruct | 1,024 토큰 | 언어 이해, 추론, 텍스트 생성이 탁월한 최첨단 LLM |
|
||||
| rakuten/rakutenai-7b-chat | 1,024 토큰 | 언어 이해, 추론, 텍스트 생성이 탁월한 최첨단 LLM |
|
||||
| baichuan-inc/baichuan2-13b-chat | 4,096 토큰 | 중국어 및 영어 대화, 코딩, 수학, 지시 따르기, 퀴즈 풀이 지원 |
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
@@ -680,15 +514,12 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="groq/llama-3.2-90b-text-preview",
|
||||
model="groq/qwen/qwen3.6-27b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|-----------------|-------------------|----------------------------------|
|
||||
| Llama 3.1 70B/8B| 131,072 토큰 | 고성능, 대용량 문맥 작업 |
|
||||
| Llama 3.2 Series| 8,192 토큰 | 범용 작업 |
|
||||
| Mixtral 8x7B | 32,768 토큰 | 성능과 문맥의 균형 |
|
||||
|
||||
Groq는 production 모델과 preview 모델을 구분하며 모델 ID를 정기적으로 폐기합니다. 프로덕션 모델을 선택하기 전에 [Groq 모델 카탈로그](https://console.groq.com/docs/models)와 [지원 중단 페이지](https://console.groq.com/docs/deprecations)를 확인하세요.
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
@@ -770,11 +601,12 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="llama-3.1-sonar-large-128k-online",
|
||||
base_url="https://api.perplexity.ai/"
|
||||
model="perplexity/sonar-pro"
|
||||
)
|
||||
```
|
||||
|
||||
현재 모델 ID와 지원 중단 공지는 [Perplexity 모델 카탈로그](https://docs.perplexity.ai/getting-started/models)와 [changelog](https://docs.perplexity.ai/docs/resources/changelog)를 확인하세요.
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -810,17 +642,12 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sambanova/Meta-Llama-3.1-8B-Instruct",
|
||||
model="sambanova/Meta-Llama-3.3-70B-Instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| 모델 | 컨텍스트 윈도우 | 최적 용도 |
|
||||
|-----------------|---------------------|--------------------------------------|
|
||||
| Llama 3.1 70B/8B| 최대 131,072 토큰 | 고성능, 대용량 문맥 작업 |
|
||||
| Llama 3.1 405B | 8,192 토큰 | 고성능, 높은 출력 품질 |
|
||||
| Llama 3.2 Series| 8,192 토큰 | 범용, 멀티모달 작업 |
|
||||
| Llama 3.3 70B | 최대 131,072 토큰 | 고성능, 높은 출력 품질 |
|
||||
| Qwen2 familly | 8,192 토큰 | 고성능, 높은 출력 품질 |
|
||||
|
||||
SambaNova Cloud의 호스팅 모델은 CrewAI와 별도로 변경될 수 있습니다. 배포 전에 [models endpoint](https://docs.sambanova.ai/docs/api-reference/models/get-environments-available-model-list-metadata)를 조회하고 [지원 중단 가이드](https://docs.sambanova.ai/docs/en/models/deprecations)를 확인하세요.
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
@@ -838,7 +665,7 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
CrewAI 프로젝트에서의 예시 사용법:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="cerebras/llama3.1-70b",
|
||||
model="cerebras/gpt-oss-120b",
|
||||
temperature=0.7,
|
||||
max_tokens=8192
|
||||
)
|
||||
@@ -852,6 +679,8 @@ CrewAI는 고유한 기능, 인증 방법, 모델 역량을 제공하는 다양
|
||||
- 긴 컨텍스트 윈도우 지원
|
||||
</Info>
|
||||
|
||||
현재 공개 endpoint ID는 [Cerebras 모델 카탈로그](https://inference-docs.cerebras.ai/models/overview)와 [지원 중단 공지](https://inference-docs.cerebras.ai/support/deprecation)를 확인하세요.
|
||||
|
||||
**참고:** 이 제공자는 LiteLLM을 사용합니다. 프로젝트에 의존성으로 추가하세요:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -926,7 +755,7 @@ CrewAI는 LLM의 스트리밍 응답을 지원하여, 애플리케이션이 출
|
||||
|
||||
# 스트리밍이 활성화된 LLM 생성
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
stream=True # 스트리밍 활성화
|
||||
)
|
||||
```
|
||||
@@ -976,7 +805,7 @@ CrewAI는 LLM의 스트리밍 응답을 지원하여, 애플리케이션이 출
|
||||
|
||||
my_listener = MyCustomListener()
|
||||
|
||||
llm = LLM(model="gpt-4o-mini", temperature=0, stream=True)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", stream=True)
|
||||
|
||||
researcher = Agent(
|
||||
role="About User",
|
||||
@@ -1012,6 +841,8 @@ CrewAI는 LLM의 스트리밍 응답을 지원하여, 애플리케이션이 출
|
||||
|
||||
CrewAI는 Pydantic 모델을 사용하여 `response_format`을 정의함으로써 LLM 호출에서 구조화된 응답을 지원합니다. 이를 통해 프레임워크가 출력을 자동으로 파싱하고 검증할 수 있어, 수동 후처리 없이도 응답을 애플리케이션에 쉽게 통합할 수 있습니다.
|
||||
|
||||
구조화된 출력 지원은 제공업체와 모델에 따라 다릅니다. 프로덕션에서 구조화된 응답에 의존하기 전에 선택한 모델을 테스트하세요.
|
||||
|
||||
예를 들어, 예상되는 응답 구조를 나타내는 Pydantic 모델을 정의하고 LLM을 인스턴스화할 때 `response_format`으로 전달할 수 있습니다. 이 모델은 LLM 출력을 구조화된 Python 객체로 변환하는 데 사용됩니다.
|
||||
|
||||
```python Code
|
||||
@@ -1023,7 +854,7 @@ class Dog(BaseModel):
|
||||
breed: str
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o", response_format=Dog)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", response_format=Dog)
|
||||
|
||||
response = llm.call(
|
||||
"Analyze the following messages and return the name, age, and breed. "
|
||||
@@ -1052,8 +883,8 @@ LLM 설정을 최대한 활용하는 방법을 알아보세요:
|
||||
# 3. 큰 컨텍스트에 대한 작업 분할
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
max_tokens=4000, # 응답 길이 제한
|
||||
model="openai/gpt-5.6-terra",
|
||||
max_completion_tokens=4000, # 응답 길이 제한
|
||||
)
|
||||
```
|
||||
|
||||
@@ -1077,15 +908,14 @@ LLM 설정을 최대한 활용하는 방법을 알아보세요:
|
||||
```python
|
||||
# 모델을 적절한 설정으로 구성
|
||||
llm = LLM(
|
||||
model="openai/gpt-4-turbo-preview",
|
||||
temperature=0.7, # 작업에 따라 조정
|
||||
max_tokens=4096, # 출력 요구 사항에 맞게 설정
|
||||
timeout=300 # 복잡한 작업을 위한 더 긴 타임아웃
|
||||
model="openai/gpt-5.6-terra",
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4096,
|
||||
timeout=300
|
||||
)
|
||||
```
|
||||
<Tip>
|
||||
- 사실 기반 응답에는 낮은 temperature(0.1~0.3)
|
||||
- 창의적인 작업에는 높은 temperature(0.7~0.9)
|
||||
선택한 모델이 지원하는 제어 옵션을 사용하세요. 제공자에 따라 `temperature`, reasoning 또는 thinking 수준, 혹은 원하는 스타일과 변동성을 정의하는 프롬프트 지침을 사용할 수 있습니다.
|
||||
</Tip>
|
||||
</Step>
|
||||
|
||||
|
||||
@@ -24,15 +24,23 @@ mode: "wide"
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
### 1. 스킬 디렉터리 생성
|
||||
### 1. CLI로 스킬 생성
|
||||
|
||||
CLI는 스킬을 생성하는 공식 지원 방식입니다 — 디렉터리 레이아웃과 유효한 `SKILL.md`를 자동으로 스캐폴딩해 줍니다:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create code-review
|
||||
```
|
||||
|
||||
크루 프로젝트 내부(`pyproject.toml`이 있는 곳)에서는 `./skills/code-review/`가 생성되고, 프로젝트 외부에서는 현재 디렉터리에 `./code-review/`가 생성됩니다 (`--no-project`로 이 동작을 강제할 수 있습니다):
|
||||
|
||||
```
|
||||
skills/
|
||||
└── code-review/
|
||||
├── SKILL.md # 필수 — 지침
|
||||
├── SKILL.md # 필수 — 지침 (미리 채워진 템플릿)
|
||||
├── references/ # 선택 — 참조 문서
|
||||
│ └── style-guide.md
|
||||
└── scripts/ # 선택 — 실행 가능한 스크립트
|
||||
├── scripts/ # 선택 — 실행 가능한 스크립트
|
||||
└── assets/ # 선택 — 정적 파일
|
||||
```
|
||||
|
||||
### 2. SKILL.md 작성
|
||||
@@ -164,6 +172,65 @@ agent = Agent(
|
||||
|
||||
---
|
||||
|
||||
## 스킬 생성, 게시 및 설치
|
||||
|
||||
스킬은 CLI로 관리되는 전체 라이프사이클을 갖습니다: **`crewai skill create`로 생성하고, `crewai skill publish`로 게시하세요** — 디렉터리를 직접 만드는 방식도 로컬 실험에는 사용할 수 있지만, CLI가 의도된 워크플로우이며 스킬 레이아웃과 프론트매터를 유효하게 유지해 줍니다.
|
||||
|
||||
### 생성
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create my-skill
|
||||
```
|
||||
|
||||
디렉터리를 스캐폴딩하고 (크루 프로젝트 내부에서는 `./skills/`에 생성) 템플릿 `SKILL.md`와 함께 빈 `scripts/`, `references/`, `assets/` 디렉터리를 만듭니다. `SKILL.md`를 편집하여 지침을 정의하세요.
|
||||
|
||||
### 게시
|
||||
|
||||
스킬 디렉터리 내부(`SKILL.md`가 있는 곳)에서 실행하세요:
|
||||
|
||||
```shell Terminal
|
||||
cd skills/my-skill
|
||||
crewai skill publish
|
||||
```
|
||||
|
||||
게시 시 `SKILL.md` 프론트매터에서 `name`, `description`, `metadata.version`을 읽어 스킬을 CrewAI 레지스트리로 푸시합니다. **게시된 스킬은 항상 조직 범위로 제한됩니다** — 도구와 마찬가지로 게시한 조직의 멤버만 스킬을 보고 설치할 수 있으며, 공개 가시성은 없습니다. 유용한 플래그:
|
||||
|
||||
| 플래그 | 효과 |
|
||||
| :--- | :--- |
|
||||
| `--org <slug>` | 특정 조직으로 게시합니다 (설정을 재정의). |
|
||||
| `--force` | git 상태 검증을 건너뜁니다 (커밋되지 않은 변경 사항 등). |
|
||||
|
||||
### 설치
|
||||
|
||||
게시된 스킬을 `@org/name` 참조로 설치합니다:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill install @acme/code-review
|
||||
```
|
||||
|
||||
크루 프로젝트 내부에서는 스킬이 `./skills/{name}/`에 설치되고, 프로젝트 외부에서는 공유 캐시인 `~/.crewai/skills/{org}/{name}/`에 저장됩니다.
|
||||
|
||||
에이전트는 레지스트리 스킬을 직접 참조할 수도 있습니다 — 런타임에 로컬 캐시(또는 프로젝트 `skills/` 디렉터리)에서 해석됩니다:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Senior Code Reviewer",
|
||||
goal="Review pull requests for quality and security issues",
|
||||
backstory="Staff engineer with expertise in secure coding practices.",
|
||||
skills=["@acme/code-review"], # registry ref, resolved locally
|
||||
)
|
||||
```
|
||||
|
||||
### 목록 조회
|
||||
|
||||
```shell Terminal
|
||||
crewai skill list
|
||||
```
|
||||
|
||||
프로젝트 `./skills/` 디렉터리와 전역 캐시 양쪽에 설치된 스킬을 버전 및 경로와 함께 보여줍니다.
|
||||
|
||||
---
|
||||
|
||||
## 크루 레벨 스킬
|
||||
|
||||
스킬을 크루에 설정하여 **모든 에이전트**에 적용할 수 있습니다:
|
||||
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
- [개요](/ko/enterprise/features/agent-control-plane/overview)
|
||||
- **모니터링** *(현재 페이지)*
|
||||
- [규칙](/ko/enterprise/features/agent-control-plane/rules)
|
||||
- [정책](/edge/ko/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## 개요
|
||||
@@ -58,7 +58,7 @@ mode: "wide"
|
||||
| **Last execution** | 가장 최근 실행 이후 경과 시간. |
|
||||
| **Health Status Breakdown** | 윈도우 내 실행에 대한 `Critical` / `Warning` / `Healthy` 비율의 누적 막대. |
|
||||
| **Executions with Errors** | 윈도우 내 총 실패 실행 수. |
|
||||
| **PII detection applied** | deployment별 PII 설정 또는 일치하는 [PII 규칙](/ko/enterprise/features/agent-control-plane/rules)이 활성화된 경우 `Yes`. |
|
||||
| **PII detection applied** | deployment별 PII 설정 또는 일치하는 [PII 정책](/edge/ko/enterprise/features/agent-control-plane/policies)이 활성화된 경우 `Yes`. |
|
||||
| **Executions** | 윈도우 내 총 실행 수. |
|
||||
| **Last updated** | deployment의 마지막 재배포 시점. |
|
||||
| **Crew Version** | deployment가 보고한 `crewai` 버전. `1.13` 미만 버전 옆의 정보 아이콘은 메트릭에 기여할 수 없는 행을 표시합니다. |
|
||||
@@ -96,8 +96,8 @@ mode: "wide"
|
||||
<Card title="Agent Control Plane — 개요" icon="book-open" href="/ko/enterprise/features/agent-control-plane/overview">
|
||||
ACP란 무엇이며, 요구사항, 플랜 등급, RBAC에 대해.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — 규칙" icon="shield-check" href="/ko/enterprise/features/agent-control-plane/rules">
|
||||
조직 단위 PII Redaction 규칙을 여러 자동화에 적용합니다.
|
||||
<Card title="Agent Control Plane — 정책" icon="shield-check" href="/edge/ko/enterprise/features/agent-control-plane/policies">
|
||||
조직 단위 PII Redaction 정책을 여러 자동화에 적용합니다.
|
||||
</Card>
|
||||
<Card title="Traces" icon="timeline" href="/ko/enterprise/features/traces">
|
||||
개별 실행을 드릴다운하여 에이전트의 추론, 도구 호출, 토큰 사용량을 확인합니다.
|
||||
|
||||
@@ -10,17 +10,17 @@ icon: "book-open"
|
||||
|
||||
- **개요** *(현재 페이지)*
|
||||
- [모니터링](/ko/enterprise/features/agent-control-plane/monitoring)
|
||||
- [규칙](/ko/enterprise/features/agent-control-plane/rules)
|
||||
- [정책](/edge/ko/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## 개요
|
||||
|
||||
**Agent Control Plane**(ACP)은 CrewAI AMP에서 실행 중인 모든 워크로드를 위한 운영 허브입니다. **Automations**와 **Rules** 두 개의 탭으로 구성된 단일 화면에서 다음 작업을 할 수 있습니다:
|
||||
**Agent Control Plane**(ACP)은 CrewAI AMP에서 실행 중인 모든 워크로드를 위한 운영 허브입니다. **Automations**와 **Policies** 두 개의 탭으로 구성된 단일 화면에서 다음 작업을 할 수 있습니다:
|
||||
|
||||
- 모든 라이브 자동화(crew 또는 flow)의 **상태(health)**를 `Critical` / `Warning` / `Healthy` 분포와 실행 횟수로 모니터링합니다.
|
||||
- 자동화별·공급자별·모델별 **LLM 소비**(토큰 및 비용)를 추적하고, 이전 기간 대비 변화량을 확인합니다.
|
||||
- 임의의 자동화 또는 모델 공급자를 드릴다운하여 시계열 차트와 공급자별 분해를 살펴봅니다.
|
||||
- 조직 전체에 **규칙(Rules)**(현재: PII Redaction)을 적용하여 각 deployment를 개별 편집하지 않고 한 번에 여러 자동화에 정책을 강제합니다.
|
||||
- 조직 전체에 **정책(Policies)**(현재: PII Redaction)을 적용하여 각 deployment를 개별 편집하지 않고 한 번에 여러 자동화에 정책을 강제합니다.
|
||||
|
||||
<Frame>
|
||||

|
||||
@@ -33,7 +33,7 @@ icon: "book-open"
|
||||
두 탭은 서로 다른 두 가지 질문에 답합니다:
|
||||
|
||||
- **Automations** — *"지금 내 플릿은 어떻게 동작하고 있고, 얼마나 비용이 들고 있는가?"* [모니터링](/ko/enterprise/features/agent-control-plane/monitoring)을 참고하세요.
|
||||
- **Rules** — *"정책(예: PII redaction)을 매번 재배포하지 않고 여러 deployment에 어떻게 강제할 수 있는가?"* [규칙](/ko/enterprise/features/agent-control-plane/rules)을 참고하세요.
|
||||
- **Policies** — *"정책(예: PII redaction)을 매번 재배포하지 않고 여러 deployment에 어떻게 강제할 수 있는가?"* [정책](/edge/ko/enterprise/features/agent-control-plane/policies)을 참고하세요.
|
||||
|
||||
## 요구사항
|
||||
|
||||
@@ -42,11 +42,11 @@ icon: "book-open"
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
[규칙](/ko/enterprise/features/agent-control-plane/rules)을 생성하거나 편집하려면 **Enterprise 또는 Ultra 플랜**이 필요합니다. 하위 플랜의 조직도 Rules 탭을 열고 기존 규칙을 볼 수 있지만, 편집기는 "Enterprise" 잠금 핀과 *"PII Redaction rules require an Enterprise plan."* 경고와 함께 읽기 전용으로 표시됩니다. 모니터링(Automations 탭)은 기능이 활성화된 모든 플랜에서 사용할 수 있습니다.
|
||||
[정책](/edge/ko/enterprise/features/agent-control-plane/policies)을 생성하거나 편집하려면 **Enterprise 또는 Ultra 플랜**이 필요합니다. 하위 플랜의 조직도 Policies 탭을 열고 기존 정책을 볼 수 있지만, 편집기는 "Enterprise" 잠금 핀과 *"PII Redaction policies require an Enterprise plan."* 경고와 함께 읽기 전용으로 표시됩니다. 모니터링(Automations 탭)은 기능이 활성화된 모든 플랜에서 사용할 수 있습니다.
|
||||
</Warning>
|
||||
|
||||
- **Agent Control Plane** 기능이 조직에 대해 활성화되어 있어야 합니다. 사이드바에 보이지 않으면 계정 오너에게 활성화를 요청하세요.
|
||||
- ACP 내부에서는 [RBAC](/ko/enterprise/features/rbac)가 접근 권한을 관리합니다: 대시보드 및 규칙을 보려면 `read`, 규칙을 생성·편집·토글·삭제하려면 `manage` 권한이 필요합니다.
|
||||
- ACP 내부에서는 [RBAC](/ko/enterprise/features/rbac)가 접근 권한을 관리합니다: 대시보드 및 정책을 보려면 `read`, 정책을 생성·편집·토글·삭제하려면 `manage` 권한이 필요합니다.
|
||||
- 모든 차트와 테이블은 오른쪽 상단의 시간 선택기를 통해 **지난 24시간**, **지난 1주**, **지난 30일**로 범위를 조정할 수 있습니다. 변화량(`↑ 8 vs yesterday`, `↓ $20.57 vs yesterday` 등)은 선택한 윈도우를 같은 길이의 이전 윈도우와 비교합니다.
|
||||
|
||||
## 여기에서 할 수 있는 일
|
||||
@@ -55,7 +55,7 @@ icon: "book-open"
|
||||
<Card title="모니터링" icon="gauge" href="/ko/enterprise/features/agent-control-plane/monitoring">
|
||||
메트릭 카드, 인터랙티브 sankey, 자동화별 테이블, 자동화 또는 공급자별 드릴다운 사이드 패널로 플릿 상태와 LLM 지출을 살펴봅니다.
|
||||
</Card>
|
||||
<Card title="규칙" icon="shield-check" href="/ko/enterprise/features/agent-control-plane/rules">
|
||||
<Card title="정책" icon="shield-check" href="/edge/ko/enterprise/features/agent-control-plane/policies">
|
||||
도구와 태그로 범위를 지정한 PII Redaction 정책을 조직 단위로 적용합니다. 변경 사항은 다음 실행부터 적용되며 재배포가 필요 없습니다.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -67,10 +67,10 @@ icon: "book-open"
|
||||
개별 실행을 드릴다운하여 에이전트의 추론, 도구 호출, 토큰 사용량을 확인합니다.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/ko/enterprise/features/rbac">
|
||||
누가 Agent Control Plane을 읽을 수 있고 누가 규칙을 편집할 수 있는지 관리합니다.
|
||||
누가 Agent Control Plane을 읽을 수 있고 누가 정책을 편집할 수 있는지 관리합니다.
|
||||
</Card>
|
||||
<Card title="Traces용 PII Redaction" icon="lock" href="/ko/enterprise/features/pii-trace-redactions">
|
||||
규칙이 참조하는 엔티티 카탈로그 및 deployment 단위 PII 설정.
|
||||
정책이 참조하는 엔티티 카탈로그 및 deployment 단위 PII 설정.
|
||||
</Card>
|
||||
<Card title="AMP에 배포" icon="rocket" href="/ko/enterprise/guides/deploy-to-amp">
|
||||
Agent Control Plane을 지원하는 crewAI 버전으로 crew를 배포합니다.
|
||||
@@ -78,5 +78,5 @@ icon: "book-open"
|
||||
</CardGroup>
|
||||
|
||||
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
|
||||
메트릭 해석 또는 규칙 설계에 도움이 필요하시면 지원 팀에 문의하세요.
|
||||
메트릭 해석 또는 정책 설계에 도움이 필요하시면 지원 팀에 문의하세요.
|
||||
</Card>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "규칙 설정하기"
|
||||
title: "정책 설정하기"
|
||||
description: "한 곳에서 조직 단위 정책을 여러 자동화에 적용합니다."
|
||||
sidebarTitle: "규칙"
|
||||
sidebarTitle: "정책"
|
||||
icon: "shield-check"
|
||||
mode: "wide"
|
||||
---
|
||||
@@ -11,50 +11,50 @@ mode: "wide"
|
||||
|
||||
- [개요](/ko/enterprise/features/agent-control-plane/overview)
|
||||
- [모니터링](/ko/enterprise/features/agent-control-plane/monitoring)
|
||||
- **규칙** *(현재 페이지)*
|
||||
- **정책** *(현재 페이지)*
|
||||
</Info>
|
||||
|
||||
## 개요
|
||||
|
||||
규칙(Rules)은 각 deployment를 개별 설정하는 대신, 정책 — 현재: **PII Redaction** — 을 한 번에 여러 자동화에 적용할 수 있게 해줍니다. 관리하려면 [Agent Control Plane](/ko/enterprise/features/agent-control-plane/overview)에서 **Rules** 탭을 엽니다.
|
||||
정책(Policies)은 각 deployment를 개별 설정하는 대신, 정책 — 현재: **PII Redaction** — 을 한 번에 여러 자동화에 적용할 수 있게 해줍니다. 관리하려면 [Agent Control Plane](/ko/enterprise/features/agent-control-plane/overview)에서 **Policies** 탭을 엽니다.
|
||||
|
||||
<Frame>
|
||||

|
||||

|
||||
</Frame>
|
||||
|
||||
각 규칙 카드에는 이름, 설명, 규칙이 적용되는 **범위(scope)**(선택된 도구와 태그), 그리고 현재 범위와 일치하는 deployment의 수인 **engaged automations**가 표시됩니다. 오른쪽 토글로 규칙을 삭제하지 않고 활성/비활성할 수 있습니다.
|
||||
각 정책 카드에는 이름, 설명, 정책이 적용되는 **범위(scope)**(선택된 도구와 태그), 그리고 현재 범위와 일치하는 deployment의 수인 **engaged automations**가 표시됩니다. 오른쪽 토글로 정책을 삭제하지 않고 활성/비활성할 수 있습니다.
|
||||
|
||||
## 요구사항
|
||||
|
||||
<Warning>
|
||||
PII Redaction 규칙을 생성하거나 편집하려면 **Enterprise 또는 Ultra 플랜**이 필요합니다. 하위 플랜의 조직도 Rules 탭을 열고 기존 규칙을 볼 수는 있지만, 편집기는 "Enterprise" 잠금 핀과 *"PII Redaction rules require an Enterprise plan."* 경고와 함께 읽기 전용으로 렌더링됩니다. 업그레이드하려면 계정 오너 또는 영업팀에 문의하세요.
|
||||
PII Redaction 정책을 생성하거나 편집하려면 **Enterprise 또는 Ultra 플랜**이 필요합니다. 하위 플랜의 조직도 Policies 탭을 열고 기존 정책을 볼 수는 있지만, 편집기는 "Enterprise" 잠금 핀과 *"PII Redaction policies require an Enterprise plan."* 경고와 함께 읽기 전용으로 렌더링됩니다. 업그레이드하려면 계정 오너 또는 영업팀에 문의하세요.
|
||||
</Warning>
|
||||
|
||||
- **Agent Control Plane** 기능이 조직에 대해 활성화되어 있어야 합니다. [개요 — 요구사항](/ko/enterprise/features/agent-control-plane/overview#요구사항)을 참고하세요.
|
||||
- 규칙을 생성·편집·토글·삭제하려면 Agent Control Plane에 대한 [RBAC](/ko/enterprise/features/rbac)의 `manage` 권한이 필요합니다. 보려면 `read` 권한만으로 충분합니다.
|
||||
- 모든 규칙 변경은 감사를 위해 버전 관리됩니다.
|
||||
- 정책을 생성·편집·토글·삭제하려면 Agent Control Plane에 대한 [RBAC](/ko/enterprise/features/rbac)의 `manage` 권한이 필요합니다. 보려면 `read` 권한만으로 충분합니다.
|
||||
- 모든 정책 변경은 감사를 위해 버전 관리됩니다.
|
||||
|
||||
## 사용 가능한 규칙 유형
|
||||
## 사용 가능한 정책 유형
|
||||
|
||||
| 유형 | 동작 |
|
||||
|------|---------------|
|
||||
| **PII Redaction** | 일치하는 모든 자동화의 실행에 PII redaction을 적용합니다. [Traces용 PII Redaction](/ko/enterprise/features/pii-trace-redactions)에 문서화된 동일한 엔티티 카탈로그와 커스텀 recognizer를 사용합니다. |
|
||||
|
||||
향후 더 많은 규칙 유형이 추가될 예정입니다.
|
||||
향후 더 많은 정책 유형이 추가될 예정입니다.
|
||||
|
||||
## 규칙 만들기
|
||||
## 정책 만들기
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/acp-rules-edit-side-panel.png" alt="조건 및 PII 마스크 유형이 있는 규칙 편집 사이드 패널" width="450" />
|
||||
<img src="/images/enterprise/acp-policies-new-side-panel.png" alt="조건 및 PII 마스크 유형이 있는 정책 편집 사이드 패널" width="450" />
|
||||
</Frame>
|
||||
|
||||
<Steps>
|
||||
<Step title="편집기 열기">
|
||||
Rules 탭 오른쪽 상단의 **+ Create new**를 클릭하거나, 기존 규칙 카드의 **View Details**를 클릭합니다.
|
||||
Policies 탭 오른쪽 상단의 **+ Create new**를 클릭하거나, 기존 정책 카드의 **View Details**를 클릭합니다.
|
||||
</Step>
|
||||
|
||||
<Step title="규칙 이름과 설명 작성">
|
||||
규칙에 명확한 이름(예: *Mask PII (CC)*)과 적용 시점을 설명하는 description을 부여합니다. 둘 다 규칙 카드와 Engaged Automations 모달에 표시됩니다.
|
||||
<Step title="정책 이름과 설명 작성">
|
||||
정책에 명확한 이름(예: *Mask PII (CC)*)과 적용 시점을 설명하는 description을 부여합니다. 둘 다 정책 카드와 Engaged Automations 모달에 표시됩니다.
|
||||
</Step>
|
||||
|
||||
<Step title="유형 선택">
|
||||
@@ -62,12 +62,12 @@ mode: "wide"
|
||||
</Step>
|
||||
|
||||
<Step title="조건 설정">
|
||||
조건은 규칙이 어떤 자동화에 engage 할지 결정합니다. 둘 다 선택 사항이며 **집합 동일성(set-equality)** 의미론을 사용합니다:
|
||||
조건은 정책이 어떤 자동화에 engage 할지 결정합니다. 둘 다 선택 사항이며 **집합 동일성(set-equality)** 의미론을 사용합니다:
|
||||
|
||||
- **Tools** — 도구 집합이 선택된 도구와 **정확히 일치**하는 자동화만 engage 됩니다. Studio 앱, MCP, OSS 도구, Tool Repository registry 도구 중에서 선택합니다.
|
||||
- **Automations** — 태그 집합이 선택된 태그와 **정확히 일치**하는 자동화만 engage 됩니다.
|
||||
|
||||
피커를 비워두면 "이 차원에서 필터링하지 않음"을 의미합니다. 두 피커를 모두 비워두면 규칙이 조직의 **모든** 자동화에 적용됩니다.
|
||||
피커를 비워두면 "이 차원에서 필터링하지 않음"을 의미합니다. 두 피커를 모두 비워두면 정책이 조직의 **모든** 자동화에 적용됩니다.
|
||||
</Step>
|
||||
|
||||
<Step title="PII Mask Type 테이블 구성">
|
||||
@@ -75,30 +75,30 @@ mode: "wide"
|
||||
</Step>
|
||||
|
||||
<Step title="저장">
|
||||
저장하는 즉시 engage 된 모든 자동화의 **향후** 실행에 규칙이 적용됩니다. 재배포는 필요 없습니다.
|
||||
저장하는 즉시 engage 된 모든 자동화의 **향후** 실행에 정책이 적용됩니다. 재배포는 필요 없습니다.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Engaged automations
|
||||
|
||||
규칙 카드의 **Engaged N automations**를 클릭하면 현재 규칙이 일치시키고 있는 deployment와 각 deployment의 마지막 실행을 정확히 확인할 수 있습니다.
|
||||
정책 카드의 **Engaged N automations**를 클릭하면 현재 정책이 일치시키고 있는 deployment와 각 deployment의 마지막 실행을 정확히 확인할 수 있습니다.
|
||||
|
||||
<Frame>
|
||||

|
||||

|
||||
</Frame>
|
||||
|
||||
규칙을 활성화하기 전에 범위를 빠르게 점검하는 가장 좋은 방법입니다. 예를 들어, `production` 태그로 범위를 지정한 규칙이 의도치 않게 staging deployment를 일치시키지 않는지 확인할 수 있습니다.
|
||||
정책을 활성화하기 전에 범위를 빠르게 점검하는 가장 좋은 방법입니다. 예를 들어, `production` 태그로 범위를 지정한 정책이 의도치 않게 staging deployment를 일치시키지 않는지 확인할 수 있습니다.
|
||||
|
||||
## 조직 단위 규칙 vs deployment 단위 설정
|
||||
## 조직 단위 정책 vs deployment 단위 설정
|
||||
|
||||
PII Redaction은 두 곳에서 설정할 수 있습니다:
|
||||
|
||||
- **deployment 단위** — 각 deployment의 **Settings → PII Protection** ([가이드](/ko/enterprise/features/pii-trace-redactions))
|
||||
- **조직 단위** — 이 페이지의 규칙
|
||||
- **조직 단위** — 이 페이지의 정책
|
||||
|
||||
활성화된 조직 단위 규칙의 범위가 어떤 deployment와 일치하면, 규칙의 엔티티 구성이 그 deployment의 실행에 대해 **deployment가 소유한 PII 설정을 덮어씁니다**. 규칙이 연결된 동안에는 규칙이 단일 진실 공급원이 됩니다. 규칙을 비활성화하거나 분리하면(또는 범위를 변경하여 더 이상 일치하지 않게 만들면) deployment는 자체 PII Protection 설정으로 되돌아갑니다.
|
||||
활성화된 조직 단위 정책의 범위가 어떤 deployment와 일치하면, 정책의 엔티티 구성이 그 deployment의 실행에 대해 **deployment가 소유한 PII 설정을 덮어씁니다**. 정책이 연결된 동안에는 정책이 단일 진실 공급원이 됩니다. 정책을 비활성화하거나 분리하면(또는 범위를 변경하여 더 이상 일치하지 않게 만들면) deployment는 자체 PII Protection 설정으로 되돌아갑니다.
|
||||
|
||||
여러 deployment에 걸쳐 일관된 정책을 강제하고 싶을 때는 조직 단위 규칙을 선호하고, 일회성 예외에 대해서는 deployment 단위 설정을 사용하세요.
|
||||
여러 deployment에 걸쳐 일관된 정책을 강제하고 싶을 때는 조직 단위 정책을 선호하고, 일회성 예외에 대해서는 deployment 단위 설정을 사용하세요.
|
||||
|
||||
## 관련 문서
|
||||
|
||||
@@ -113,10 +113,10 @@ PII Redaction은 두 곳에서 설정할 수 있습니다:
|
||||
엔티티 카탈로그, 커스텀 recognizer, deployment 단위 구성.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/ko/enterprise/features/rbac">
|
||||
누가 규칙을 만들거나 편집할 수 있는지 관리합니다.
|
||||
누가 정책을 만들거나 편집할 수 있는지 관리합니다.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="도움이 필요하신가요?" icon="headset" href="mailto:support@crewai.com">
|
||||
조직의 규칙을 설계하는 데 도움이 필요하시면 지원 팀에 문의하세요.
|
||||
조직의 정책을 설계하는 데 도움이 필요하시면 지원 팀에 문의하세요.
|
||||
</Card>
|
||||
123
docs/edge/ko/enterprise/features/studio-flows.mdx
Normal file
@@ -0,0 +1,123 @@
|
||||
---
|
||||
title: "Studio의 Flows"
|
||||
description: "결정론적인 단계별 제어와 에이전트 지능을 결합한 이벤트 기반 워크플로우를 코드 없이 구축하세요."
|
||||
icon: "diagram-project"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**점진적 출시 중**: Studio의 Flows는 2026년 7월 20일 주간에 걸쳐 순차적으로 출시됩니다. Studio에서 아직 Flows 옵션이 보이지 않는다면 소속 조직에 아직 배포되지 않은 것이니 곧 다시 확인해 주세요.
|
||||
</Info>
|
||||
|
||||
## 개요
|
||||
|
||||
이제 Studio에서 Crew뿐 아니라 **Flows**도 구축할 수 있습니다. Flows는 어떤 단계가 어떤 순서로, 어떤 조건에서 실행될지를 직접 제어하는 이벤트 기반 워크플로우이며, 각 단계 내부의 지능적인 작업은 AI 에이전트에게 맡길 수 있습니다.
|
||||
|
||||
Flow를 만들려면 Studio를 열고 자동화를 설명한 뒤, 프롬프트 입력창 옆의 선택기에서 **Flows**를 선택하세요.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## 왜 Flows인가?
|
||||
|
||||
Crew는 에이전트 팀이 목표를 향해 자율적으로 협업하도록 할 때 매우 유용합니다. 하지만 실제 자동화 중 상당수는 더 높은 예측 가능성이 필요합니다. 먼저 이 데이터를 가져오고, 그다음 요약하고, 마지막으로 결과를 게시하는 식으로 — 매번 같은 순서로요.
|
||||
|
||||
Flows는 두 가지를 모두 제공합니다:
|
||||
|
||||
- **필요한 곳의 결정론**: 단계가 정의된 순서와 명시적인 분기에 따라 실행되므로, 실행 결과가 예측 가능하고 반복 가능하며 디버깅하기 쉽습니다.
|
||||
- **필요한 곳의 지능**: 각 단계는 에이전트(또는 전체 crew)가 수행하므로, 요약·평가·작성·판단 같은 단계 내부의 작업은 LLM의 추론 능력을 온전히 활용합니다.
|
||||
|
||||
이 조합 덕분에 Flows는 프로덕션 자동화에 적합합니다. 구조는 보장되고, 에이전트의 자율성은 그것이 필요한 단계로만 한정됩니다.
|
||||
|
||||
## Flow 구축하기
|
||||
|
||||
원하는 것을 자연어로 설명하면 Studio Assistant가 Flow를 설계해 줍니다. 단계를 만들고, 서로 연결하고, 각 단계에 필요한 에이전트와 앱 연동을 구성합니다. 오른쪽 캔버스에는 완성된 워크플로우가 연결된 노드로 표시되며, 대화를 이어가며 반복 수정하거나 노드를 직접 편집할 수 있습니다.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
준비가 되면 **Run**으로 Flow를 처음부터 끝까지 테스트하고, **Output** 및 **Traces** 탭에서 결과를 확인한 뒤, 안정화되면 **Deploy**하세요. 프로젝트를 **Share**하거나 소스 코드를 **Download**할 수도 있습니다.
|
||||
|
||||
## 노드 유형
|
||||
|
||||
Flows는 세 가지 핵심 노드 유형으로 구성됩니다. 각 노드는 워크플로우의 한 단계이며 자유롭게 조합할 수 있습니다.
|
||||
|
||||
### Single Agent
|
||||
|
||||
Single Agent 노드는 하나의 에이전트가 하나의 집중된 작업을 수행합니다. 연동 서비스에서 데이터 가져오기, 콘텐츠 변환, 메시지 게시처럼 범위가 명확한 단계에 적합합니다.
|
||||
|
||||
에이전트 노드를 클릭하면 전체 구성이 열립니다:
|
||||
|
||||
- **Task**: 이 단계가 달성해야 할 목표와 생성해야 할 출력
|
||||
- **Profile**: 에이전트의 role, goal, backstory
|
||||
- **Model**: 에이전트를 구동하는 LLM
|
||||
- **Apps**: 에이전트가 사용할 수 있는 연동 서비스(예: Linear, Slack, HubSpot)
|
||||
- **Runtime Controls**: 실행 전 계획 수립, 위임, 메모리에 대한 토글
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### Crews
|
||||
|
||||
Crew 노드는 여러 에이전트가 여러 작업을 협업으로 수행하는 전체 crew를 Flow의 단일 단계로 포함합니다. 데이터를 팀별로 그룹화·요약한 뒤 전달용으로 포맷을 정리하는 것처럼, 하나의 에이전트로 감당하기 어려운 단계에 사용하세요.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Crew 노드를 열면 내부 구조가 표시됩니다. 수행하는 작업, 각 작업에 배정된 에이전트, 사용하는 앱을 확인할 수 있습니다. crew는 해당 단계 내에서 자율적으로 실행된 뒤 결과를 Flow의 다음 노드로 전달합니다.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
이것이 결정론과 에이전트 지능이 결합된 패턴입니다. Flow는 crew가 *언제* 실행될지를 보장하고, crew는 작업을 *어떻게* 수행할지에 협업 지능을 더합니다.
|
||||
|
||||
### Router
|
||||
|
||||
Router 노드는 조건에 따라 Flow를 분기시켜 결과에 따라 서로 다른 경로를 따르게 합니다. 예를 들어 리드 라우팅 Flow는 유입 리드를 평가한 뒤, 고품질 리드는 영업 배정 단계로 보내고 나머지는 향후 육성을 위해 기록만 남길 수 있습니다.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Router가 있기에 Flows는 진정한 이벤트 기반 워크플로우가 됩니다. 하나의 워크플로우가 모든 경우를 처리하되, 각 실행은 데이터에 해당하는 분기만 따라갑니다 — 불필요한 단계도, 다음에 무슨 일이 일어날지에 대한 모호함도 없습니다.
|
||||
|
||||
## Agent Repository 동기화
|
||||
|
||||
Flows에서 만든 에이전트를 하나의 프로젝트에 가둘 필요가 없습니다. 모든 에이전트 노드에는 **Publish to Agent Repository** 버튼이 있어, 에이전트의 role, goal, backstory, 모델, 구성을 조직의 [Agent Repository](/ko/enterprise/features/agent-repositories)에 저장할 수 있습니다.
|
||||
|
||||
양방향으로 동작합니다:
|
||||
|
||||
- **게시(Publish)**: Flow에서 다듬은 에이전트를 리포지토리로 승격하여 다른 팀과 프로젝트에서 재사용할 수 있게 합니다.
|
||||
- **가져오기(Pull)**: 처음부터 다시 만드는 대신 리포지토리의 기존 에이전트를 새 Flow로 가져옵니다.
|
||||
|
||||
리포지토리 에이전트는 조직 전체에 동기화되므로, 공유 에이전트를 한 번 개선하면 이를 사용하는 모든 Flow가 혜택을 받습니다. 에이전트 동작을 일관되고 관리 가능하게 유지하며 중복 작업을 없앨 수 있습니다.
|
||||
|
||||
## 모범 사례
|
||||
|
||||
- 자동화에 명확한 순서나 분기 로직이 있다면 **Flow를 선택**하고, 목표까지의 경로가 열려 있다면 Crew를 선택하세요.
|
||||
- **에이전트 작업은 집중적으로 유지하세요** — 작업 설명이 명확한 Single Agent 노드가 세 가지 일을 한꺼번에 맡은 에이전트보다 안정적입니다.
|
||||
- **Router로 모든 경우를 명시적으로 처리하세요.** "아무것도 하지 않는" 경로(예: 건너뛴 리드 기록)까지 포함해 모든 실행이 빠짐없이 처리되도록 합니다.
|
||||
- **안정화된 에이전트는 Agent Repository에 게시**하여 조직이 일회성 복사본 대신 공유 라이브러리를 구축하도록 하세요.
|
||||
- **배포 전에 Run으로 테스트하고 Traces를 확인**하여 연동이나 프롬프트 문제를 조기에 발견하세요.
|
||||
|
||||
## 관련 문서
|
||||
|
||||
<CardGroup cols={4}>
|
||||
<Card title="Crew Studio" href="/ko/enterprise/features/crew-studio" icon="pencil">
|
||||
Studio에서 Crew를 구축하세요.
|
||||
</Card>
|
||||
<Card title="Agent Repositories" href="/ko/enterprise/features/agent-repositories" icon="people-group">
|
||||
조직 전체에서 에이전트를 공유하고 재사용하세요.
|
||||
</Card>
|
||||
<Card title="Flows 개념" href="/ko/concepts/flows" icon="diagram-project">
|
||||
CrewAI 프레임워크에서 Flows가 동작하는 방식을 알아보세요.
|
||||
</Card>
|
||||
<Card title="Tools & Integrations" href="/ko/enterprise/features/tools-and-integrations" icon="plug">
|
||||
에이전트가 사용할 앱을 연결하세요.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
194
docs/edge/ko/learn/streaming-runtime-contract.mdx
Normal file
@@ -0,0 +1,194 @@
|
||||
---
|
||||
title: 스트리밍 런타임 계약
|
||||
description: Flow, 직접 LLM 호출, 대화 턴에서 정렬된 런타임 프레임을 스트리밍합니다.
|
||||
icon: tower-broadcast
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## 개요
|
||||
|
||||
CrewAI는 단순한 텍스트 청크보다 더 많은 정보가 필요한 런타임을 위해 프레임 기반 스트리밍 계약을 제공합니다. 이 계약은 Flow 생명주기 이벤트, 직접 LLM 토큰, 도구 활동, 대화 메시지, 사용자 지정 이벤트에 대해 정렬된 `StreamFrame` 객체를 방출합니다.
|
||||
|
||||
UI, 서비스 브리지, 터미널 앱, 배포 런타임을 만들 때 Flow, 채팅 턴, 직접 LLM 호출이 실행되는 동안 안정적인 구조화 이벤트 스트림이 필요하다면 이 API를 사용하세요.
|
||||
|
||||
## StreamFrame
|
||||
|
||||
모든 프레임은 같은 envelope를 가집니다:
|
||||
|
||||
```python
|
||||
from crewai.types.streaming import StreamFrame
|
||||
|
||||
frame.id # 고유 프레임 id
|
||||
frame.seq # 사용 가능한 경우 실행 로컬 순서
|
||||
frame.type # "flow_started" 같은 원본 이벤트 타입
|
||||
frame.channel # "llm", "flow", "tools", "messages", "lifecycle", "custom"
|
||||
frame.namespace # 소스/런타임 namespace
|
||||
frame.timestamp # 이벤트 timestamp
|
||||
frame.parent_id # 사용 가능한 경우 부모 이벤트 id
|
||||
frame.previous_id # 사용 가능한 경우 이전 이벤트 id
|
||||
frame.data # 이벤트 payload
|
||||
frame.event # frame.data의 alias
|
||||
frame.content # 토큰류 프레임의 출력 가능한 텍스트, 그 외에는 ""
|
||||
```
|
||||
|
||||
`channel` 필드는 소비자에서 프레임을 라우팅하는 가장 빠른 방법입니다:
|
||||
|
||||
| 채널 | 포함 내용 |
|
||||
|------|-----------|
|
||||
| `llm` | LLM 스트리밍 이벤트의 토큰 및 thinking 청크 |
|
||||
| `flow` | Flow 생명주기, 메서드 실행, 라우팅, pause/resume 이벤트 |
|
||||
| `tools` | 도구 사용 이벤트 |
|
||||
| `messages` | 대화 transcript 이벤트 |
|
||||
| `lifecycle` | 다른 채널에 속하지 않는 런타임 생명주기 이벤트 |
|
||||
| `custom` | 내장 채널에 매핑되지 않는 이벤트 |
|
||||
|
||||
`frame.type`은 원본 이벤트 타입을 보존하므로, 소비자는 채널 안에서 특정 이벤트를 처리할 수 있습니다.
|
||||
|
||||
## Flow 스트리밍
|
||||
|
||||
Flow에 `stream=True`를 설정하면 `kickoff()`가 stream session을 반환합니다:
|
||||
|
||||
```python
|
||||
from crewai.flow import Flow, start
|
||||
|
||||
|
||||
class ReportFlow(Flow):
|
||||
@start()
|
||||
def generate(self):
|
||||
return "done"
|
||||
|
||||
|
||||
flow = ReportFlow(stream=True)
|
||||
stream = flow.kickoff()
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
if chunk.type == "tool_usage_started":
|
||||
print(chunk.event["tool_name"])
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
`stream.result`를 읽기 전에 stream을 소비해야 합니다. 결과를 너무 일찍 접근하면 `RuntimeError`가 발생하여, 소비자가 부분 실행을 완료된 실행으로 잘못 처리하지 않도록 합니다.
|
||||
|
||||
Flow 인스턴스에 `stream=True`를 설정하지 않고 단일 호출만 스트리밍하려면 `flow.stream_events(...)`를 직접 호출할 수도 있습니다.
|
||||
|
||||
## 채널별 필터링
|
||||
|
||||
`StreamSession`은 선택한 채널 안에서 전역 프레임 순서를 보존하는 채널 projection을 제공합니다:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
with stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
사용 가능한 projection은 다음과 같습니다:
|
||||
|
||||
| Projection | 프레임 |
|
||||
|------------|--------|
|
||||
| `stream.events` | 모든 프레임 |
|
||||
| `stream.llm` | LLM 프레임 |
|
||||
| `stream.messages` | 대화 메시지 프레임 |
|
||||
| `stream.flow` | Flow 프레임 |
|
||||
| `stream.tools` | 도구 프레임 |
|
||||
| `stream.interleave([...])` | 선택한 채널 집합 |
|
||||
|
||||
소비자가 일부 채널만 원하지만 상대 순서도 필요하다면 `stream.interleave(["flow", "llm", "messages"])`를 사용하세요.
|
||||
|
||||
## 비동기 스트리밍
|
||||
|
||||
비동기 소비자는 `astream()`을 사용하세요:
|
||||
|
||||
```python
|
||||
flow = ReportFlow()
|
||||
stream = flow.astream()
|
||||
|
||||
async with stream:
|
||||
async for chunk in stream.events:
|
||||
print(chunk.channel, chunk.type, chunk.content)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
비동기 세션은 동기 세션과 같은 projection을 제공합니다.
|
||||
|
||||
## 직접 LLM 호출 스트리밍
|
||||
|
||||
`llm.call(...)`은 계속 최종 조립 결과를 반환합니다. 구조화된 이벤트 payload를 유지하면서 청크가 도착하는 대로 반복 처리하려면 `llm.stream_events(...)`를 사용하세요:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o-mini")
|
||||
stream = llm.stream_events(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain CrewAI streaming in two short sentences.",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
`llm.stream_events(...)`는 감싼 호출 동안 일시적으로 streaming을 활성화하고, 이후 LLM의 이전 `stream` 설정을 복원합니다. provider 통합은 계속 기본 LLM stream 이벤트를 방출하며, 이 helper는 모든 LLM provider에서 그 이벤트 위에 공통 iterator API를 제공합니다.
|
||||
|
||||
## 대화 턴
|
||||
|
||||
대화형 Flow는 `stream_turn()`으로 사용자 턴 하나를 스트리밍할 수 있습니다:
|
||||
|
||||
```python
|
||||
from crewai import Flow
|
||||
from crewai.experimental.conversational import ConversationConfig, ConversationState
|
||||
|
||||
|
||||
@ConversationConfig(llm="gpt-4o-mini", defer_trace_finalization=True)
|
||||
class ChatFlow(Flow[ConversationState]):
|
||||
conversational = True
|
||||
|
||||
|
||||
flow = ChatFlow()
|
||||
stream = flow.stream_turn("What can you help me with?", session_id="session-1")
|
||||
|
||||
with stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
reply = stream.result
|
||||
```
|
||||
|
||||
`stream_turn()` 중에는 내장 대화 응답 경로가 해당 턴에 대해 LLM 토큰 스트리밍을 활성화하고 이후 LLM의 이전 `stream` 설정을 복원합니다. 자체 agent 또는 LLM 인스턴스를 만드는 사용자 지정 route handler는 토큰 단위 출력이 필요하다면 해당 LLM을 streaming으로 구성해야 합니다.
|
||||
|
||||
## 정리
|
||||
|
||||
가능하면 세션을 context manager로 사용하세요. stream이 끝나기 전에 클라이언트 연결이 끊기면 세션을 명시적으로 닫으세요:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
try:
|
||||
for frame in stream.events:
|
||||
print(frame.type)
|
||||
finally:
|
||||
if not stream.is_exhausted:
|
||||
stream.close()
|
||||
```
|
||||
|
||||
비동기 stream에서는 `await stream.aclose()`를 사용하세요.
|
||||
|
||||
## 레거시 청크 스트리밍
|
||||
|
||||
`stream=True`를 사용하는 Crew 스트리밍은 계속 [스트리밍 Crew 실행](/ko/learn/streaming-crew-execution)에 설명된 청크 중심 `CrewStreamingOutput` API를 반환합니다. 직접 `llm.call(...)` 호출도 계속 최종 LLM 결과를 반환합니다. 프레임 계약은 Flow, 직접 LLM 호출, 대화 턴, 도구, 메시지 전반에서 안정적인 이벤트 envelope가 필요한 런타임을 위한 것입니다.
|
||||
@@ -13,8 +13,7 @@ mode: "wide"
|
||||
|
||||
FileReadTool은 crewai_tools 패키지 내에서 파일 읽기와 콘텐츠 검색을 용이하게 하는 기능 모음입니다.
|
||||
이 모음에는 배치 텍스트 파일 처리, 런타임 구성 파일 읽기, 분석을 위한 데이터 가져오기 등 다양한 도구가 포함되어 있습니다.
|
||||
`.txt`, `.csv`, `.json` 등 다양한 텍스트 기반 파일 형식을 지원합니다. 파일 유형에 따라 이 모음은
|
||||
JSON 콘텐츠를 Python 딕셔너리로 변환하여 사용을 쉽게 하는 등 특화된 기능을 제공합니다.
|
||||
`.txt`, `.csv`, `.json` 등 다양한 텍스트 기반 파일 형식을 지원합니다. 콘텐츠는 항상 일반 텍스트로 반환됩니다.
|
||||
|
||||
## 설치
|
||||
|
||||
|
||||
@@ -32,7 +32,11 @@ from crewai_tools import FileWriterTool
|
||||
file_writer_tool = FileWriterTool()
|
||||
|
||||
# Write content to a file in a specified directory
|
||||
result = file_writer_tool._run('example.txt', 'This is a test content.', 'test_directory')
|
||||
result = file_writer_tool.run(
|
||||
filename='example.txt',
|
||||
content='This is a test content.',
|
||||
directory='test_directory',
|
||||
)
|
||||
print(result)
|
||||
```
|
||||
|
||||
|
||||
@@ -4,6 +4,330 @@ description: "Atualizações de produto, melhorias e correções do CrewAI"
|
||||
icon: "clock"
|
||||
mode: "wide"
|
||||
---
|
||||
<Update label="28 jul 2026">
|
||||
## v1.15.8
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.8)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Funcionalidades
|
||||
- Adicionar WaitTool para pausar em trabalhos de longa duração.
|
||||
|
||||
### Correções de Bugs
|
||||
- Corrigir FileWriterTool para gravações e abordar problemas no arquivo ferramenta.
|
||||
- Marcar E2B_API_KEY como uma variável de ambiente obrigatória para ferramentas E2B.
|
||||
|
||||
### Documentação
|
||||
- Atualizar orientações sobre a disponibilidade do modelo.
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@github-actions[bot], @joaomdmoura, @lucasgomide, @oalami, @thiagomoretto
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="26 jul 2026">
|
||||
## v1.15.7
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Correções de Bugs
|
||||
- Resolver habilidades de registro através do cliente CrewAI+ do runtime
|
||||
- Recuperar das ferramentas GPT-5.6 + reasoning_effort 400
|
||||
- Fazer chamadas de ferramentas funcionarem no caminho da API de Respostas
|
||||
- Roteirizar modelos apenas de respostas em vez de falhar com 404
|
||||
- Atualizar bedrock-agentcore para corrigir CVE-2026-16796
|
||||
|
||||
### Observabilidade
|
||||
- Emitir eventos de uso de habilidades em tempo de execução para observabilidade
|
||||
|
||||
### Documentação
|
||||
- Adicionar snapshot e changelog para v1.15.7a1
|
||||
|
||||
## Contributors
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="26 jul 2026">
|
||||
## v1.15.7a1
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.7a1)
|
||||
|
||||
## O Que Mudou
|
||||
|
||||
### Correções de Bugs
|
||||
- Corrigir a resolução de habilidades do registro através do cliente CrewAI+ do runtime.
|
||||
- Recuperar dos erros 400 de tools e reasoning_effort do GPT-5.6.
|
||||
- Fazer a chamada de ferramentas funcionar no caminho da API de Respostas.
|
||||
- Roteirizar modelos apenas de respostas para evitar erros 404.
|
||||
- Atualizar a dependência bedrock-agentcore para corrigir o CVE-2026-16796.
|
||||
|
||||
### Observabilidade
|
||||
- Emitir eventos de uso de habilidades em tempo de execução para melhorar a observabilidade.
|
||||
|
||||
### Documentação
|
||||
- Atualizações de snapshot e changelog para a versão 1.15.6.
|
||||
|
||||
## Contributors
|
||||
|
||||
@alex-clawd, @joaomdmoura, @lorenzejay
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="24 jul 2026">
|
||||
## v1.15.6
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.6)
|
||||
|
||||
## O que mudou
|
||||
|
||||
### Correções de Bugs
|
||||
- Corrigir a detecção de blocos de uso da ferramenta de pré-visualização da Anthropic.
|
||||
- Preservar os nomes das propriedades do esquema de ferramenta estrito.
|
||||
- Disparar o hook execution_end em execuções de equipe e fluxo com falha.
|
||||
- Lidar com get_agent assíncrono em load_agent_from_repository.
|
||||
- Corrigir problemas de resolução de dependências.
|
||||
|
||||
### Documentação
|
||||
- Snapshot e changelog para v1.15.5.
|
||||
|
||||
## Contributors
|
||||
|
||||
@alex-clawd, @iris-clawd, @lorenzejay, @lucasgomide, @theCyberTech, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="20 jul 2026">
|
||||
## v1.15.5
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.5)
|
||||
|
||||
## O Que Mudou
|
||||
|
||||
### Funcionalidades
|
||||
- Autenticar downloads do registro de habilidades
|
||||
|
||||
### Documentação
|
||||
- Atualizar snapshot e changelog para v1.15.4
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="17 jul 2026">
|
||||
## v1.15.4
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.4)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Funcionalidades
|
||||
- Promover o Repositório de Habilidades para fora do status experimental
|
||||
|
||||
### Documentação
|
||||
- Adicionar Fluxos na documentação do Studio
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@jessemiller, @joaomdmoura, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="16 jul 2026">
|
||||
## v1.15.3
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Funcionalidades
|
||||
- Adicionar parâmetro de ID da organização ao cliente PlusAPI
|
||||
- Adicionar pontos de interceptação de etapas e reformular a documentação dos hooks de execução em torno de @on
|
||||
- Conectar pontos de interceptação de limite de execução
|
||||
- Adicionar despachador de hook de interceptação genérico
|
||||
- Executar fluxos declarativos na TUI (fallback de terminal sem interface gráfica)
|
||||
|
||||
### Correções de Bugs
|
||||
- Sincronizar evento de kickoff-completed com o resultado do hook OUTPUT
|
||||
- Corrigir atributos de agente de repositório nulos
|
||||
- Garantir que os hooks after_llm_call não quebrem a execução de ferramentas nativas
|
||||
- Evitar duplicação da resposta da rodada quando um manipulador corta o histórico
|
||||
- Tornar o cache de resultados de ferramentas opcional em vez de ativado por padrão
|
||||
- Parar de reescrever a descrição da ferramenta criada na construção
|
||||
- Expor o uso de tokens sob ambos os nomes nos resultados de agente e equipe
|
||||
- Relatar métricas de uso por chamada nos resultados de kickoff
|
||||
- Parar de reproduzir a intenção da rodada anterior quando route_turn() retorna um valor falso
|
||||
|
||||
### Documentação
|
||||
- Atualizar o agrupamento de hooks de execução e documentar todos os contextos de hooks
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="16 jul 2026">
|
||||
## v1.15.3a2
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a2)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Correções de Bugs
|
||||
- Corrigir a sincronização do evento kickoff-completed com o resultado do hook OUTPUT
|
||||
|
||||
### Documentação
|
||||
- Atualizar snapshot e changelog para v1.15.3a1
|
||||
|
||||
### Atualizações de Dependências
|
||||
- Atualizar setuptools para 0.83.0 para resolver PYSEC-2026-3447
|
||||
|
||||
## Contributors
|
||||
|
||||
@lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="16 jul 2026">
|
||||
## v1.15.3a1
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.3a1)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Recursos
|
||||
- Adicionar parâmetro de ID da organização ao cliente PlusAPI.
|
||||
- Adicionar pontos de interceptação de etapas e reformular a documentação dos hooks de execução em torno de `@on`.
|
||||
- Conectar pontos de interceptação de limites de execução.
|
||||
- Adicionar despachador genérico de hooks de interceptação.
|
||||
- Executar fluxos declarativos na TUI (fallback de terminal sem cabeça).
|
||||
- Melhorar URLs personalizadas do OpenAI.
|
||||
|
||||
### Correções de Bugs
|
||||
- Corrigir atributos de agente de repositório nulos.
|
||||
- Corrigir hooks `after_llm_call` para evitar quebrar a execução de ferramentas nativas.
|
||||
- Parar de adicionar a resposta da rodada duas vezes quando um manipulador reduz o histórico.
|
||||
- Tornar o cache de resultados de ferramentas opcional em vez de ativado por padrão.
|
||||
- Parar de reescrever a descrição da ferramenta autoral na construção.
|
||||
- Expor o uso de tokens sob ambos os nomes nos resultados de agente e equipe.
|
||||
- Relatar métricas de uso por chamada nos resultados de início.
|
||||
- Parar de reproduzir a intenção da rodada anterior quando `route_turn()` retorna um valor falso.
|
||||
- Esvaziar gravações de memória antes dos eventos de início e conclusão de fluxo.
|
||||
|
||||
### Documentação
|
||||
- Agrupar hooks de execução e documentar todos os contextos de hooks.
|
||||
- Atualizar a documentação para hooks de execução.
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="07 jul 2026">
|
||||
## v1.15.2
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Recursos
|
||||
- Puxe os modelos LLM mais recentes dinamicamente no assistente de equipe.
|
||||
- Suporte a definições de habilidades inline.
|
||||
- Adicione habilidade de autoria de definição de fluxo gerada.
|
||||
- Suporte a entradas de ação de fluxo template.
|
||||
- Adicione um helper de texto para prompts CEL de fluxo.
|
||||
- Adicione um helper de texto para exemplo de habilidade de fluxo.
|
||||
- Implemente configuração de mensagem e tratamento de feedback no AgentExecutor.
|
||||
- Adicione agentes de repositório às definições de fluxo.
|
||||
- Defina o protocolo de quadro de stream para fluxos.
|
||||
- Tipo de ferramenta e aplicativo em CrewDefinition.
|
||||
- Reponha comandos de template para a organização crewAIInc-fde.
|
||||
|
||||
### Correções de Bugs
|
||||
- Chaveie o cache do catálogo de modelos pela chave de API exata, reduza o TTL e ignore Ollama.
|
||||
- Unifique a resolução de entrada de fluxo e prompt do comando `crewai run` a partir do esquema de estado.
|
||||
- Resolva falhas de pip-audit para onnx 1.22.0 e nltk PYSEC-2026-597.
|
||||
- Garanta que estamos escrevendo a versão para fluxos.
|
||||
- Inclua aiobotocore no extra do bedrock.
|
||||
- Rejeite métodos de fluxo de autoescuta.
|
||||
- Remova a navegação de versão de docs do Edge para que novas páginas não sejam descartadas.
|
||||
|
||||
### Documentação
|
||||
- Atualize a linguagem de Regras para Políticas para corresponder às novas mudanças do painel.
|
||||
- Documente opções de agente de fluxo.
|
||||
- Adicione documentação de streaming à navegação.
|
||||
- Documente o tipo de regra Limite de Custo no Planejamento de Controle do Agente.
|
||||
- Remova referências a CREWAI_LOG_FORMAT do guia Datadog.
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@akaKuruma, @danielfsbarreto, @github-code-quality[bot], @joaomdmoura, @lorenzejay, @lucasgomide, @manisrinivasan2k1, @renatonitta, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="01 jul 2026">
|
||||
## v1.15.2a2
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a2)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Recursos
|
||||
- Adicionar aiobotocore ao extra bedrock
|
||||
- Documentar opções do agente de fluxo
|
||||
- Adicionar helper de texto ao exemplo de habilidade de fluxo
|
||||
- Adicionar helper de texto para prompts CEL de fluxo
|
||||
- Adicionar documentação de streaming à navegação
|
||||
|
||||
### Correções de Bugs
|
||||
- Rejeitar métodos de fluxo de autoescuta
|
||||
|
||||
### Documentação
|
||||
- Atualizar snapshot e changelog para v1.15.2a1
|
||||
- Compactar arquivo AGENTS.md
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@akaKuruma, @github-code-quality[bot], @lorenzejay, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="30 jun 2026">
|
||||
## v1.15.2a1
|
||||
|
||||
[Ver release no GitHub](https://github.com/crewAIInc/crewAI/releases/tag/1.15.2a1)
|
||||
|
||||
## O que Mudou
|
||||
|
||||
### Recursos
|
||||
- Reapontar comandos de template para a organização crewAIInc-fde
|
||||
- Suporte a definições de habilidades inline
|
||||
- Definir protocolo de quadro de fluxo para fluxos
|
||||
- Adicionar ferramenta de tipo e aplicativo em CrewDefinition
|
||||
- Adicionar habilidade de autoria de Definição de Fluxo gerada
|
||||
|
||||
### Correções de Bugs
|
||||
- Remover a navegação de versão de docs do Edge para evitar que novas páginas sejam descartadas
|
||||
|
||||
### Documentação
|
||||
- Documentar o tipo de regra Limite de Custo no Painel de Controle do Agente
|
||||
- Remover referências a CREWAI_LOG_FORMAT do guia Datadog
|
||||
|
||||
## Contribuidores
|
||||
|
||||
@danielfsbarreto, @joaomdmoura, @lorenzejay, @lucasgomide, @vinibrsl
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="26 jun 2026">
|
||||
## v1.15.1
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ Modelos de Linguagem de Grande Escala (LLMs) são a inteligência central por tr
|
||||
A janela de contexto determina quanto texto um LLM pode processar de uma só vez. Janelas maiores (por exemplo, 128K tokens) permitem mais contexto, porém podem ser mais caras e lentas.
|
||||
</Card>
|
||||
<Card title="Temperatura" icon="temperature-three-quarters">
|
||||
A temperatura (0.0 a 1.0) controla a aleatoriedade das respostas. Valores mais baixos (ex.: 0.2) produzem respostas mais focadas e determinísticas, enquanto valores mais altos (ex.: 0.8) aumentam criatividade e variabilidade.
|
||||
A temperatura é um controle de amostragem compatível com alguns modelos. Valores mais baixos geralmente tornam a amostragem mais focada, enquanto valores mais altos aumentam a variabilidade. Alguns modelos de raciocínio mais recentes ignoram, desaconselham ou rejeitam esse parâmetro; consulte a documentação do modelo escolhido antes de defini-lo.
|
||||
</Card>
|
||||
<Card title="Seleção de Provedor" icon="server">
|
||||
Cada provedor de LLM (ex.: OpenAI, Anthropic, Google) oferece modelos diferentes, com capacidades, preços e recursos variados. Escolha conforme suas necessidades de precisão, velocidade e custo.
|
||||
@@ -37,7 +37,7 @@ Existem diferentes locais no código do CrewAI onde você pode especificar o mod
|
||||
A maneira mais simples de começar. Defina o modelo diretamente em seu ambiente, usando um arquivo `.env` ou no código do seu aplicativo. Se você utilizou `crewai create` para iniciar seu projeto, já estará configurado.
|
||||
|
||||
```bash .env
|
||||
MODEL=model-id # e.g. gpt-4o, gemini-2.0-flash, claude-3-sonnet-...
|
||||
MODEL=provider/model-id # e.g. openai/gpt-5.6-terra
|
||||
|
||||
# Lembre-se de definir suas chaves de API aqui também. Veja a seção
|
||||
# do Provedor abaixo.
|
||||
@@ -56,7 +56,7 @@ Existem diferentes locais no código do CrewAI onde você pode especificar o mod
|
||||
goal: Conduct comprehensive research and analysis
|
||||
backstory: A dedicated research professional with years of experience
|
||||
verbose: true
|
||||
llm: provider/model-id # e.g. openai/gpt-4o, google/gemini-2.0-flash, anthropic/claude...
|
||||
llm: provider/model-id # e.g. anthropic/claude-sonnet-4-6
|
||||
# (veja exemplos de configuração de provedores abaixo para mais)
|
||||
```
|
||||
|
||||
@@ -75,32 +75,24 @@ Existem diferentes locais no código do CrewAI onde você pode especificar o mod
|
||||
from crewai import LLM
|
||||
|
||||
# Configuração básica
|
||||
llm = LLM(model="model-id-here") # gpt-4o, gemini-2.0-flash, anthropic/claude...
|
||||
llm = LLM(model="provider/model-id") # e.g. gemini/gemini-3.6-flash
|
||||
|
||||
# Configuração avançada com parâmetros detalhados
|
||||
llm = LLM(
|
||||
model="openai/gpt-4",
|
||||
temperature=0.8,
|
||||
max_tokens=150,
|
||||
top_p=0.9,
|
||||
frequency_penalty=0.1,
|
||||
presence_penalty=0.1,
|
||||
response_format={"type":"json"},
|
||||
stop=["FIM"],
|
||||
seed=42
|
||||
model="provider/model-id",
|
||||
timeout=120,
|
||||
max_tokens=4000,
|
||||
response_format={"type": "json"}, # Para saídas estruturadas
|
||||
)
|
||||
```
|
||||
|
||||
<Info>
|
||||
Explicações dos parâmetros:
|
||||
- `temperature`: Controla a aleatoriedade (0.0-1.0)
|
||||
- `timeout`: Tempo máximo de espera pela resposta
|
||||
- `max_tokens`: Limita o comprimento da resposta
|
||||
- `top_p`: Alternativa à temperatura para amostragem
|
||||
- `frequency_penalty`: Reduz repetição de palavras
|
||||
- `presence_penalty`: Incentiva novos tópicos
|
||||
- `response_format`: Especifica formato de saída
|
||||
- `seed`: Garante resultados consistentes
|
||||
|
||||
Controles de amostragem como `temperature` e `top_p`, parâmetros de penalidade, nomes de limites de tokens e controles de raciocínio são específicos de cada modelo. Adicione-os somente quando o provedor e o modelo escolhidos oferecerem suporte. Consulte os exemplos de provedores abaixo e a documentação do modelo do provedor.
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
@@ -119,6 +111,10 @@ Existem diferentes locais no código do CrewAI onde você pode especificar o mod
|
||||
O CrewAI suporta uma grande variedade de provedores de LLM, cada um com recursos, métodos de autenticação e capacidades de modelo únicos.
|
||||
Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, configurar e otimizar o LLM que melhor atende às necessidades do seu projeto.
|
||||
|
||||
<Warning>
|
||||
A disponibilidade dos modelos muda com frequência e pode variar por conta, região e plataforma de nuvem. Os exemplos abaixo usam modelos atuais no momento da redação, mas não são listas completas de suporte. Antes de implantar, confirme o ID e o estado do ciclo de vida do modelo no catálogo vinculado do provedor.
|
||||
</Warning>
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI">
|
||||
Defina as seguintes variáveis de ambiente no seu arquivo `.env`:
|
||||
@@ -137,28 +133,13 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="openai/gpt-4",
|
||||
temperature=0.8,
|
||||
max_tokens=150,
|
||||
top_p=0.9,
|
||||
frequency_penalty=0.1,
|
||||
presence_penalty=0.1,
|
||||
stop=["FIM"],
|
||||
seed=42
|
||||
model="openai/gpt-5.6-terra",
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4000
|
||||
)
|
||||
```
|
||||
|
||||
OpenAI é um dos líderes em modelos LLM com uma ampla gama de modelos e recursos.
|
||||
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|----------------------|---------------------|------------------------------------------|
|
||||
| GPT-4 | 8.192 tokens | Tarefas de alta precisão, raciocínio complexo |
|
||||
| GPT-4 Turbo | 128.000 tokens | Conteúdo longo, análise de documentos |
|
||||
| GPT-4o & GPT-4o-mini | 128.000 tokens | Processamento de contexto amplo com bom custo-benefício |
|
||||
| o3-mini | 200.000 tokens | Raciocínio rápido, tarefas complexas |
|
||||
| o1-mini | 128.000 tokens | Raciocínio rápido, tarefas complexas |
|
||||
| o1-preview | 128.000 tokens | Raciocínio rápido, tarefas complexas |
|
||||
| o1 | 200.000 tokens | Raciocínio rápido, tarefas complexas |
|
||||
A OpenAI adiciona modelos e desativa snapshots antigos regularmente. Consulte o [catálogo de modelos da OpenAI](https://developers.openai.com/api/docs/models) para obter IDs atuais, janelas de contexto, compatibilidade com endpoints e informações de ciclo de vida.
|
||||
|
||||
**Responses API:**
|
||||
|
||||
@@ -215,14 +196,7 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
)
|
||||
```
|
||||
|
||||
Todos os modelos listados em https://llama.developer.meta.com/docs/models/ são suportados.
|
||||
|
||||
| ID do Modelo | Comprimento contexto entrada | Comprimento contexto saída | Modalidades de entrada | Modalidades de saída |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8` | 128k | 4028 | Texto, Imagem | Texto |
|
||||
| `meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8` | 128k | 4028 | Texto, Imagem | Texto |
|
||||
| `meta_llama/Llama-3.3-70B-Instruct` | 128k | 4028 | Texto | Texto |
|
||||
| `meta_llama/Llama-3.3-8B-Instruct` | 128k | 4028 | Texto | Texto |
|
||||
Consulte a [visão geral dos modelos Meta Llama](https://ai.meta.com/llama/get-started/) para conhecer as famílias de modelos, modalidades e orientações de contexto atuais.
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
```bash
|
||||
@@ -291,10 +265,12 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="anthropic/claude-3-sonnet-20240229-v1:0",
|
||||
temperature=0.7
|
||||
model="anthropic/claude-sonnet-4-6",
|
||||
max_tokens=4096
|
||||
)
|
||||
```
|
||||
|
||||
Consulte a [visão geral dos modelos](https://platform.claude.com/docs/en/about-claude/models/overview) da Anthropic para obter IDs e capacidades atuais e revise a [tabela de descontinuação](https://platform.claude.com/docs/en/about-claude/model-deprecations) antes de fixar um modelo em produção.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google (Gemini API)">
|
||||
@@ -319,8 +295,7 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7,
|
||||
model="gemini/gemini-3.6-flash",
|
||||
)
|
||||
```
|
||||
|
||||
@@ -339,8 +314,7 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini/gemini-2.0-flash",
|
||||
temperature=0.7
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -352,47 +326,15 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Para mais detalhes, consulte a [documentação do Vertex AI Express mode](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/start/quickstart?usertype=apikey).
|
||||
</Info>
|
||||
|
||||
### Modelos Gemini
|
||||
|
||||
O Google oferece uma variedade de modelos poderosos otimizados para diferentes casos de uso.
|
||||
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|----------------------------------|--------------------|---------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M tokens | Pensamento adaptativo, eficiência de custo |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M tokens | Pensamento e raciocínio avançados, compreensão multimodal, codificação avançada, etc. |
|
||||
| gemini-2.0-flash | 1M tokens | Próxima geração de recursos, velocidade, raciocínio e streaming em tempo real |
|
||||
| gemini-2.0-flash-lite | 1M tokens | Eficiência de custo e baixa latência |
|
||||
| gemini-1.5-flash | 1M tokens | Modelo multimodal equilibrado, bom para maioria das tarefas |
|
||||
| gemini-1.5-flash-8B | 1M tokens | Mais rápido, mais eficiente em custo, adequado para tarefas de alta frequência |
|
||||
| gemini-1.5-pro | 2M tokens | Melhor desempenho para uma ampla variedade de tarefas de raciocínio, incluindo lógica, codificação e colaboração criativa |
|
||||
|
||||
A lista completa de modelos está disponível na [documentação dos modelos Gemini](https://ai.google.dev/gemini-api/docs/models).
|
||||
|
||||
### Gemma
|
||||
|
||||
A API Gemini também permite uso de sua chave de API para acessar [modelos Gemma](https://ai.google.dev/gemma/docs) hospedados na infraestrutura Google.
|
||||
|
||||
| Modelo | Janela de Contexto |
|
||||
|----------------|-------------------|
|
||||
| gemma-3-1b-it | 32k tokens |
|
||||
| gemma-3-4b-it | 32k tokens |
|
||||
| gemma-3-12b-it | 32k tokens |
|
||||
| gemma-3-27b-it | 128k tokens |
|
||||
O Google publica IDs atuais, capacidades e estágios do ciclo de vida no [catálogo de modelos Gemini](https://ai.google.dev/gemini-api/docs/models). Consulte o [cronograma de descontinuação](https://ai.google.dev/gemini-api/docs/deprecations) antes de escolher um modelo estável ou preview. A API Gemini também hospeda [modelos Gemma](https://ai.google.dev/gemma/docs).
|
||||
|
||||
</Accordion>
|
||||
<Accordion title="Google (Vertex AI)">
|
||||
Obtenha as credenciais pelo Google Cloud Console, salve em um arquivo JSON e carregue com o código a seguir:
|
||||
```python Code
|
||||
import json
|
||||
|
||||
file_path = 'path/to/vertex_ai_service_account.json'
|
||||
|
||||
# Carregar o arquivo JSON
|
||||
with open(file_path, 'r') as file:
|
||||
vertex_credentials = json.load(file)
|
||||
|
||||
# Converter credenciais em string JSON
|
||||
vertex_credentials_json = json.dumps(vertex_credentials)
|
||||
Autentique-se com as [Credenciais Padrão do Aplicativo](https://cloud.google.com/docs/authentication/provide-credentials-adc) e configure o provedor Gemini nativo para usar o Vertex AI:
|
||||
```toml .env
|
||||
GOOGLE_GENAI_USE_VERTEXAI=true
|
||||
GOOGLE_CLOUD_PROJECT=<your-project-id>
|
||||
GOOGLE_CLOUD_LOCATION=<location>
|
||||
```
|
||||
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
@@ -400,27 +342,15 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
from crewai import LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gemini-1.5-pro-latest", # or vertex_ai/gemini-1.5-pro-latest
|
||||
temperature=0.7,
|
||||
vertex_credentials=vertex_credentials_json
|
||||
model="gemini/gemini-3.6-flash"
|
||||
)
|
||||
```
|
||||
|
||||
O Google oferece uma variedade de modelos poderosos otimizados para diferentes casos de uso:
|
||||
Consulte as [informações de modelos do Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models) para verificar modelos e regiões disponíveis.
|
||||
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|----------------------------------|--------------------|---------------------------------------------------------------------|
|
||||
| gemini-2.5-flash-preview-04-17 | 1M tokens | Pensamento adaptativo, eficiência de custo |
|
||||
| gemini-2.5-pro-preview-05-06 | 1M tokens | Pensamento e raciocínio avançados, compreensão multimodal, codificação avançada, etc. |
|
||||
| gemini-2.0-flash | 1M tokens | Próxima geração de recursos, velocidade, raciocínio e streaming em tempo real |
|
||||
| gemini-2.0-flash-lite | 1M tokens | Eficiência de custo e baixa latência |
|
||||
| gemini-1.5-flash | 1M tokens | Modelo multimodal equilibrado, bom para maioria das tarefas |
|
||||
| gemini-1.5-flash-8B | 1M tokens | Mais rápido, mais eficiente em custo, adequado para tarefas de alta frequência |
|
||||
| gemini-1.5-pro | 2M tokens | Melhor desempenho para uma ampla variedade de tarefas de raciocínio, incluindo lógica, codificação e colaboração criativa |
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
**Nota:** Esta configuração usa a integração Gemini nativa do CrewAI. Adicione-a como dependência ao seu projeto:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
uv add "crewai[google-genai]"
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
@@ -455,7 +385,7 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
|
||||
model="bedrock/us.anthropic.claude-sonnet-4-6"
|
||||
)
|
||||
```
|
||||
|
||||
@@ -463,34 +393,6 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
|
||||
[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) é um serviço gerenciado que fornece acesso a múltiplos modelos fundamentais dos principais provedores de IA através de uma API unificada, permitindo o desenvolvimento seguro e responsável de aplicações de IA.
|
||||
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|--------------------------|------------------------|---------------------------------------------------------------------|
|
||||
| Amazon Nova Pro | Até 300k tokens | Alto desempenho, equilíbrio entre precisão, velocidade e custo em tarefas diversas. |
|
||||
| Amazon Nova Micro | Até 128k tokens | Modelo texto-only de alta performance, custo-benefício, otimizado para baixa latência. |
|
||||
| Amazon Nova Lite | Até 300k tokens | Alto desempenho, processamento multimodal acessível para texto, imagem, vídeo em tempo real. |
|
||||
| Claude 3.7 Sonnet | Até 128k tokens | Alto desempenho para raciocínio complexo, programação & agentes de IA|
|
||||
| Claude 3.5 Sonnet v2 | Até 200k tokens | Modelo avançado especializado em engenharia de software, capacidades agenticas e interação computacional com custo otimizado. |
|
||||
| Claude 3.5 Sonnet | Até 200k tokens | Alto desempenho com inteligência e raciocínio excepcionais, equilíbrio entre velocidade-custo. |
|
||||
| Claude 3.5 Haiku | Até 200k tokens | Modelo multimodal rápido e compacto, otimizado para respostas rápidas e interações humanas naturais |
|
||||
| Claude 3 Sonnet | Até 200k tokens | Modelo multimodal equilibrando inteligência e velocidade para grandes volumes de uso. |
|
||||
| Claude 3 Haiku | Até 200k tokens | Compacto, multimodal, otimizado para respostas rápidas e diálogo natural |
|
||||
| Claude 3 Opus | Até 200k tokens | Modelo multimodal mais avançado para tarefas complexas com raciocínio humano e entendimento contextual superior. |
|
||||
| Claude 2.1 | Até 200k tokens | Versão aprimorada com janela de contexto aumentada, maior confiabilidade, menos alucinações para aplicações longas e RAG |
|
||||
| Claude | Até 100k tokens | Modelo versátil para diálogos sofisticados, conteúdo criativo e instruções precisas. |
|
||||
| Claude Instant | Até 100k tokens | Modelo rápido e de baixo custo para tarefas diárias, como diálogos, análise, sumarização e Q&A em documentos |
|
||||
| Llama 3.1 405B Instruct | Até 128k tokens | LLM avançado para geração de dados sintéticos, distilação e inferência para chatbots, programação, tarefas de domínio específico. |
|
||||
| Llama 3.1 70B Instruct | Até 128k tokens | Potencializa conversas complexas com entendimento contextual superior, raciocínio e geração de texto. |
|
||||
| Llama 3.1 8B Instruct | Até 128k tokens | Modelo de última geração, entendimento de linguagem, raciocínio e geração de texto. |
|
||||
| Llama 3 70B Instruct | Até 8k tokens | Potencializa conversas complexas com entendimento contextual superior, raciocínio e geração de texto. |
|
||||
| Llama 3 8B Instruct | Até 8k tokens | LLM de última geração com excelente desempenho em linguagem e geração de texto. |
|
||||
| Titan Text G1 - Lite | Até 4k tokens | Modelo leve e econômico para tarefas em inglês e ajuste fino, focado em sumarização e geração de conteúdo. |
|
||||
| Titan Text G1 - Express | Até 8k tokens | Modelo versátil para tarefas gerais de linguagem, chat e aplicações RAG com suporte a inglês e 100+ línguas. |
|
||||
| Cohere Command | Até 4k tokens | Modelo especializado em seguir comandos do usuário e entregar soluções empresariais práticas. |
|
||||
| Jurassic-2 Mid | Até 8.191 tokens | Modelo econômico equilibrando qualidade e custo para tarefas como Q&A, sumarização e geração de conteúdo. |
|
||||
| Jurassic-2 Ultra | Até 8.191 tokens | Geração avançada de texto e compreensão, excelente em análise e criação de conteúdo complexo. |
|
||||
| Jamba-Instruct | Até 256k tokens | Modelo com janela de contexto extendida para geração de texto, sumarização e Q&A de baixo custo. |
|
||||
| Mistral 7B Instruct | Até 32k tokens | LLM atende instruções, solicitações e gera texto criativo. |
|
||||
| Mistral 8x7B Instruct | Até 32k tokens | MOE LLM que atende instruções, solicitações e gera texto criativo. |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Amazon SageMaker">
|
||||
@@ -542,81 +444,13 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="nvidia_nim/meta/llama3-70b-instruct",
|
||||
model="nvidia_nim/nvidia/nvidia-nemotron-3-ultra-550b-a55b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
|
||||
O Nvidia NIM oferece uma suíte abrangente de modelos para diversos usos, desde tarefas gerais até aplicações especializadas.
|
||||
O catálogo hospedado do NVIDIA NIM muda com frequência. Use o [catálogo de modelos NVIDIA NIM](https://build.nvidia.com/models) para escolher um endpoint atual e confirmar o ID, as modalidades e os limites de contexto.
|
||||
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|--------------------------------------------------------------------------|--------------------|---------------------------------------------------------------------|
|
||||
| nvidia/mistral-nemo-minitron-8b-8k-instruct | 8.192 tokens | Modelo pequeno de linguagem topo de linha para chatbots, assistentes virtuais e geração de conteúdo. |
|
||||
| nvidia/nemotron-4-mini-hindi-4b-instruct | 4.096 tokens | SLM bilíngue Hindi-Inglês para inferência no dispositivo, específico para língua hindi. |
|
||||
| nvidia/llama-3.1-nemotron-70b-instruct | 128k tokens | Personalizado para respostas mais úteis |
|
||||
| nvidia/llama3-chatqa-1.5-8b | 128k tokens | LLM avançado para respostas contextuais de alta qualidade em chatbots e mecanismos de busca. |
|
||||
| nvidia/llama3-chatqa-1.5-70b | 128k tokens | LLM avançado para respostas contextuais de alta qualidade para chatbots e mecanismos de busca. |
|
||||
| nvidia/vila | 128k tokens | Modelo multmodal visão-linguagem para compreensão de texto/img/vídeo com respostas informativas |
|
||||
| nvidia/neva-22 | 4.096 tokens | Modelo de visão-linguagem multimodal para compreensão textos/imagens e respostas informativas |
|
||||
| nvidia/nemotron-mini-4b-instruct | 8.192 tokens | Tarefas gerais |
|
||||
| nvidia/usdcode-llama3-70b-instruct | 128k tokens | LLM de ponta para queries OpenUSD e geração de código USD-Python. |
|
||||
| nvidia/nemotron-4-340b-instruct | 4.096 tokens | Gera dados sintéticos diversos simulando características reais. |
|
||||
| meta/codellama-70b | 100k tokens | LLM capaz de gerar código a partir de linguagem natural e vice-versa.|
|
||||
| meta/llama2-70b | 4.096 tokens | Modelo de IA avançado para geração de textos e códigos. |
|
||||
| meta/llama3-8b-instruct | 8.192 tokens | LLM de última geração, entendimento de linguagem, raciocínio e geração de texto. |
|
||||
| meta/llama3-70b-instruct | 8.192 tokens | Potencializa conversas complexas com entendimento contextual superior, raciocínio e geração de texto.|
|
||||
| meta/llama-3.1-8b-instruct | 128k tokens | Modelo compacto de última geração, com compreensão, raciocínio e geração de texto superior. |
|
||||
| meta/llama-3.1-70b-instruct | 128k tokens | Potencializa conversas complexas com entendimento contextual superior, raciocínio e geração de texto. |
|
||||
| meta/llama-3.1-405b-instruct | 128k tokens | LLM avançado para geração sintética de dados, destilação e inferência para chatbots, código, tarefas de domínio específico. |
|
||||
| meta/llama-3.2-1b-instruct | 128k tokens | Pequeno modelo de linguagem de última geração, entendimento, raciocínio e geração textual.|
|
||||
| meta/llama-3.2-3b-instruct | 128k tokens | Pequeno modelo de linguagem de última geração, entendimento, raciocínio e geração textual.|
|
||||
| meta/llama-3.2-11b-vision-instruct | 128k tokens | Pequeno modelo de linguagem de última geração, entendimento, raciocínio e geração textual multimodal.|
|
||||
| meta/llama-3.2-90b-vision-instruct | 128k tokens | Pequeno modelo de linguagem de última geração, entendimento, raciocínio e geração textual multimodal.|
|
||||
| google/gemma-7b | 8.192 tokens | Modelo avançado de geração de texto, compreensão, transformação e programação.|
|
||||
| google/gemma-2b | 8.192 tokens | Modelo avançado de geração de texto, compreensão, transformação e programação.|
|
||||
| google/codegemma-7b | 8.192 tokens | Modelo avançado baseado no Gemma-7B do Google, especializado em geração de códigos e autocomplete.|
|
||||
| google/codegemma-1.1-7b | 8.192 tokens | Modelo avançado para geração, complemento, raciocínio e instrução em código.|
|
||||
| google/recurrentgemma-2b | 8.192 tokens | Modelo baseado em arquitetura recorrente para inferência mais rápida em sequências longas.|
|
||||
| google/gemma-2-9b-it | 8.192 tokens | Modelo avançado de geração de texto, compreensão, transformação e programação.|
|
||||
| google/gemma-2-27b-it | 8.192 tokens | Modelo avançado de geração de texto, compreensão, transformação e programação.|
|
||||
| google/gemma-2-2b-it | 8.192 tokens | Modelo avançado de geração de texto, compreensão, transformação e programação.|
|
||||
| google/deplot | 512 tokens | Modelo visual por linguagem para entender gráficos e converter em tabelas.|
|
||||
| google/paligemma | 8.192 tokens | Modelo visão-linguagem experto em compreender texto e visual, gerando respostas informativas.|
|
||||
| mistralai/mistral-7b-instruct-v0.2 | 32k tokens | LLM que segue instruções, completa pedidos e gera texto criativo. |
|
||||
| mistralai/mixtral-8x7b-instruct-v0.1 | 8.192 tokens | MOE LLM para seguir instruções e gerar versões criativas de texto. |
|
||||
| mistralai/mistral-large | 4.096 tokens | Geração de dados sintéticos. |
|
||||
| mistralai/mixtral-8x22b-instruct-v0.1 | 8.192 tokens | Geração de dados sintéticos. |
|
||||
| mistralai/mistral-7b-instruct-v0.3 | 32k tokens | LLM que segue instruções, completa pedidos e gera texto criativo. |
|
||||
| nv-mistralai/mistral-nemo-12b-instruct | 128k tokens | Modelo de linguagem avançado para raciocínio, código, tarefas multilíngues; roda em uma única GPU.|
|
||||
| mistralai/mamba-codestral-7b-v0.1 | 256k tokens | Modelo para escrita e interação com código em múltiplas linguagens e tarefas.|
|
||||
| microsoft/phi-3-mini-128k-instruct | 128K tokens | LLM leve, de última geração, com habilidades de lógica e matemática.|
|
||||
| microsoft/phi-3-mini-4k-instruct | 4.096 tokens | LLM leve, de última geração, com habilidades de lógica e matemática.|
|
||||
| microsoft/phi-3-small-8k-instruct | 8.192 tokens | LLM leve, de última geração, com habilidades de lógica e matemática.|
|
||||
| microsoft/phi-3-small-128k-instruct | 128K tokens | LLM leve, de última geração, com habilidades de lógica e matemática.|
|
||||
| microsoft/phi-3-medium-4k-instruct | 4.096 tokens | LLM leve, de última geração, com habilidades de lógica e matemática.|
|
||||
| microsoft/phi-3-medium-128k-instruct | 128K tokens | LLM leve, de última geração, com habilidades de lógica e matemática.|
|
||||
| microsoft/phi-3.5-mini-instruct | 128K tokens | LLM multilíngue leve para aplicações de IA restritas em memória e tempo.|
|
||||
| microsoft/phi-3.5-moe-instruct | 128K tokens | LLM avançada baseada em Mixture of Experts para geração eficiente de conteúdo.|
|
||||
| microsoft/kosmos-2 | 1.024 tokens | Modelo multimodal revolucionário para compreender e raciocinar elementos visuais em imagens.|
|
||||
| microsoft/phi-3-vision-128k-instruct | 128k tokens | Modelo multimodal aberto de ponta para raciocínio de alta qualidade a partir de imagens.|
|
||||
| microsoft/phi-3.5-vision-instruct | 128k tokens | Modelo multimodal aberto de ponta para raciocínio de alta qualidade a partir de imagens.|
|
||||
| databricks/dbrx-instruct | 12k tokens | LLM de uso geral com desempenho no estado da arte para linguagem, programação e RAG.|
|
||||
| snowflake/arctic | 1.024 tokens | Inferência eficiente para aplicações empresariais focadas em SQL e programação.|
|
||||
| aisingapore/sea-lion-7b-instruct | 4.096 tokens | LLM para representação e diversidade linguística e cultural do sudeste asiático.|
|
||||
| ibm/granite-8b-code-instruct | 4.096 tokens | LLM para programação: geração, explicação e diálogo multi-turn de código.|
|
||||
| ibm/granite-34b-code-instruct | 8.192 tokens | LLM para programação: geração, explicação e diálogo multi-turn de código.|
|
||||
| ibm/granite-3.0-8b-instruct | 4.096 tokens | Pequeno modelo avançado, com suporte a RAG, sumário, classificação, código e IA agentica.|
|
||||
| ibm/granite-3.0-3b-a800m-instruct | 4.096 tokens | Modelo Mixture of Experts eficiente para RAG, sumário, extração de entidades, classificação.|
|
||||
| mediatek/breeze-7b-instruct | 4.096 tokens | Gera dados sintéticos diversos.|
|
||||
| upstage/solar-10.7b-instruct | 4.096 tokens | Excelente em tarefas de PLN, especialmente seguir instruções, raciocínio e matemática.|
|
||||
| writer/palmyra-med-70b-32k | 32k tokens | LLM líder para respostas médicas precisas e contextuais.|
|
||||
| writer/palmyra-med-70b | 32k tokens | LLM líder para respostas médicas precisas e contextuais.|
|
||||
| writer/palmyra-fin-70b-32k | 32k tokens | LLM especializada em análise financeira, relatórios e processamento de dados.|
|
||||
| 01-ai/yi-large | 32k tokens | Poderoso para inglês e chinês, incluindo chatbot e escrita criativa.|
|
||||
| deepseek-ai/deepseek-coder-6.7b-instruct | 2k tokens | Modelo avançado para geração de código, autocomplete, infilling.|
|
||||
| rakuten/rakutenai-7b-instruct | 1.024 tokens | LLM topo de linha, compreensão, raciocínio e geração textual.|
|
||||
| rakuten/rakutenai-7b-chat | 1.024 tokens | LLM topo de linha, compreensão, raciocínio e geração textual.|
|
||||
| baichuan-inc/baichuan2-13b-chat | 4.096 tokens | Suporte a chat em chinês/inglês, programação, matemática, seguir instruções, resolver quizzes.|
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
```bash
|
||||
@@ -679,15 +513,12 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="groq/llama-3.2-90b-text-preview",
|
||||
model="groq/qwen/qwen3.6-27b",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|-------------------|---------------------|------------------------------------------|
|
||||
| Llama 3.1 70B/8B | 131.072 tokens | Alta performance e tarefas de contexto grande|
|
||||
| Llama 3.2 Série | 8.192 tokens | Tarefas gerais |
|
||||
| Mixtral 8x7B | 32.768 tokens | Equilíbrio entre performance e contexto |
|
||||
|
||||
A Groq diferencia modelos production e preview e desativa IDs regularmente. Consulte o [catálogo de modelos da Groq](https://console.groq.com/docs/models) e a [página de descontinuações](https://console.groq.com/docs/deprecations) antes de escolher um modelo para produção.
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
```bash
|
||||
@@ -769,11 +600,12 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="llama-3.1-sonar-large-128k-online",
|
||||
base_url="https://api.perplexity.ai/"
|
||||
model="perplexity/sonar-pro"
|
||||
)
|
||||
```
|
||||
|
||||
Consulte o [catálogo de modelos da Perplexity](https://docs.perplexity.ai/getting-started/models) e o [changelog](https://docs.perplexity.ai/docs/resources/changelog) para obter IDs atuais e avisos de descontinuação.
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -809,17 +641,12 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="sambanova/Meta-Llama-3.1-8B-Instruct",
|
||||
model="sambanova/Meta-Llama-3.3-70B-Instruct",
|
||||
temperature=0.7
|
||||
)
|
||||
```
|
||||
| Modelo | Janela de Contexto | Melhor Para |
|
||||
|-------------------|---------------------------|----------------------------------------------|
|
||||
| Llama 3.1 70B/8B | Até 131.072 tokens | Alto desempenho, tarefas com grande contexto |
|
||||
| Llama 3.1 405B | 8.192 tokens | Desempenho e qualidade de saída elevada |
|
||||
| Llama 3.2 Série | 8.192 tokens | Tarefas gerais e multimodais |
|
||||
| Llama 3.3 70B | Até 131.072 tokens | Desempenho e qualidade de saída elevada |
|
||||
| Família Qwen2 | 8.192 tokens | Desempenho e qualidade de saída elevada |
|
||||
|
||||
Os modelos hospedados no SambaNova Cloud podem mudar independentemente do CrewAI. Consulte o [endpoint de modelos](https://docs.sambanova.ai/docs/api-reference/models/get-environments-available-model-list-metadata) e o [guia de descontinuação](https://docs.sambanova.ai/docs/en/models/deprecations) antes de implantar.
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
```bash
|
||||
@@ -837,7 +664,7 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
Exemplo de uso em seu projeto CrewAI:
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="cerebras/llama3.1-70b",
|
||||
model="cerebras/gpt-oss-120b",
|
||||
temperature=0.7,
|
||||
max_tokens=8192
|
||||
)
|
||||
@@ -851,6 +678,8 @@ Nesta seção, você encontrará exemplos detalhados que ajudam a selecionar, co
|
||||
- Suporte a longas janelas de contexto
|
||||
</Info>
|
||||
|
||||
Consulte o [catálogo de modelos Cerebras](https://inference-docs.cerebras.ai/models/overview) e os [avisos de descontinuação](https://inference-docs.cerebras.ai/support/deprecation) para obter os IDs atuais dos endpoints públicos.
|
||||
|
||||
**Nota:** Este provedor usa o LiteLLM. Adicione-o como dependência ao seu projeto:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
@@ -898,7 +727,7 @@ O CrewAI suporta respostas em streaming de LLMs, permitindo que sua aplicação
|
||||
|
||||
# Crie um LLM com streaming ativado
|
||||
llm = LLM(
|
||||
model="openai/gpt-4o",
|
||||
model="openai/gpt-5.6-terra",
|
||||
stream=True # Ativar streaming
|
||||
)
|
||||
```
|
||||
@@ -935,6 +764,8 @@ O CrewAI suporta respostas em streaming de LLMs, permitindo que sua aplicação
|
||||
|
||||
O CrewAI suporta respostas estruturadas de LLMs permitindo que você defina um `response_format` usando um modelo Pydantic. Isso permite que o framework automaticamente faça o parsing e valide a saída, facilitando a integração da resposta em sua aplicação sem pós-processamento manual.
|
||||
|
||||
O suporte a saídas estruturadas varia de acordo com o provedor e o modelo. Teste o modelo escolhido antes de depender de respostas estruturadas em produção.
|
||||
|
||||
Por exemplo, é possível definir um modelo Pydantic para representar a resposta esperada e passá-lo como `response_format` ao instanciar o LLM. O modelo será utilizado para converter a resposta do LLM em um objeto Python estruturado.
|
||||
|
||||
```python Code
|
||||
@@ -946,7 +777,7 @@ class Dog(BaseModel):
|
||||
breed: str
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o", response_format=Dog)
|
||||
llm = LLM(model="openai/gpt-5.6-terra", response_format=Dog)
|
||||
|
||||
response = llm.call(
|
||||
"Analyze the following messages and return the name, age, and breed. "
|
||||
@@ -975,8 +806,8 @@ Saiba como obter o máximo da configuração do seu LLM:
|
||||
# 3. Divisão de tarefas para grandes contextos
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
max_tokens=4000, # Limitar tamanho da resposta
|
||||
model="openai/gpt-5.6-terra",
|
||||
max_completion_tokens=4000, # Limitar tamanho da resposta
|
||||
)
|
||||
```
|
||||
|
||||
@@ -1000,15 +831,14 @@ Saiba como obter o máximo da configuração do seu LLM:
|
||||
```python
|
||||
# Configure o modelo com as opções certas
|
||||
llm = LLM(
|
||||
model="openai/gpt-4-turbo-preview",
|
||||
temperature=0.7, # Ajuste conforme a tarefa
|
||||
max_tokens=4096, # Defina conforme a necessidade da saída
|
||||
timeout=300 # Timeout maior para tarefas complexas
|
||||
model="openai/gpt-5.6-terra",
|
||||
reasoning_effort="medium",
|
||||
max_completion_tokens=4096,
|
||||
timeout=300
|
||||
)
|
||||
```
|
||||
<Tip>
|
||||
- Temperaturas baixas (0.1 a 0.3) para respostas factuais
|
||||
- Temperaturas altas (0.7 a 0.9) para tarefas criativas
|
||||
Use os controles compatíveis com o modelo escolhido. Dependendo do provedor, isso pode ser `temperature`, um nível de reasoning ou thinking, ou instruções no prompt que definam o estilo e a variabilidade desejados.
|
||||
</Tip>
|
||||
</Step>
|
||||
|
||||
|
||||
@@ -24,15 +24,23 @@ Frequentemente você precisa de **ambos**: skills para expertise, ferramentas pa
|
||||
|
||||
## Início Rápido
|
||||
|
||||
### 1. Crie um Diretório de Skill
|
||||
### 1. Crie uma Skill com a CLI
|
||||
|
||||
A CLI é a forma suportada de criar uma skill — ela gera a estrutura de diretórios e um `SKILL.md` válido para você:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create code-review
|
||||
```
|
||||
|
||||
Dentro de um projeto de crew (onde o `pyproject.toml` está) isso cria `./skills/code-review/`; fora de um projeto, cria `./code-review/` no diretório atual (você pode forçar esse comportamento com `--no-project`):
|
||||
|
||||
```
|
||||
skills/
|
||||
└── code-review/
|
||||
├── SKILL.md # Obrigatório — instruções
|
||||
├── SKILL.md # Obrigatório — instruções (template pré-preenchido)
|
||||
├── references/ # Opcional — documentos de referência
|
||||
│ └── style-guide.md
|
||||
└── scripts/ # Opcional — scripts executáveis
|
||||
├── scripts/ # Opcional — scripts executáveis
|
||||
└── assets/ # Opcional — arquivos estáticos
|
||||
```
|
||||
|
||||
### 2. Escreva seu SKILL.md
|
||||
@@ -164,6 +172,65 @@ agent = Agent(
|
||||
|
||||
---
|
||||
|
||||
## Criando, Publicando e Instalando Skills
|
||||
|
||||
Skills têm um ciclo de vida completo gerenciado pela CLI: **crie-as com `crewai skill create`, publique-as com `crewai skill publish`** — criar diretórios à mão funciona para experimentos locais, mas a CLI é o fluxo de trabalho pretendido e mantém a estrutura e o frontmatter da sua skill válidos.
|
||||
|
||||
### Criar
|
||||
|
||||
```shell Terminal
|
||||
crewai skill create my-skill
|
||||
```
|
||||
|
||||
Gera o diretório (em `./skills/` dentro de um projeto de crew) com um `SKILL.md` de template, além dos diretórios vazios `scripts/`, `references/` e `assets/`. Edite o `SKILL.md` para definir as instruções.
|
||||
|
||||
### Publicar
|
||||
|
||||
Execute de dentro do diretório da skill (onde o `SKILL.md` está):
|
||||
|
||||
```shell Terminal
|
||||
cd skills/my-skill
|
||||
crewai skill publish
|
||||
```
|
||||
|
||||
A publicação lê `name`, `description` e `metadata.version` do frontmatter do `SKILL.md` e envia a skill para o registro da CrewAI. **Skills publicadas são sempre escopadas à sua organização** — assim como ferramentas, apenas membros da organização que publicou podem vê-las e instalá-las; não há visibilidade pública. Flags úteis:
|
||||
|
||||
| Flag | Efeito |
|
||||
| :--- | :--- |
|
||||
| `--org <slug>` | Publica sob uma organização específica (sobrepõe as configurações). |
|
||||
| `--force` | Pula a validação de estado do git (alterações não commitadas, etc.). |
|
||||
|
||||
### Instalar
|
||||
|
||||
Instale uma skill publicada pela sua referência `@org/name`:
|
||||
|
||||
```shell Terminal
|
||||
crewai skill install @acme/code-review
|
||||
```
|
||||
|
||||
Dentro de um projeto de crew, a skill é colocada em `./skills/{name}/`; fora de um projeto, vai para o cache compartilhado em `~/.crewai/skills/{org}/{name}/`.
|
||||
|
||||
Agentes também podem referenciar skills do registro diretamente — elas são resolvidas a partir do cache local (ou do diretório `skills/` do projeto) em tempo de execução:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Senior Code Reviewer",
|
||||
goal="Review pull requests for quality and security issues",
|
||||
backstory="Staff engineer with expertise in secure coding practices.",
|
||||
skills=["@acme/code-review"], # registry ref, resolved locally
|
||||
)
|
||||
```
|
||||
|
||||
### Listar
|
||||
|
||||
```shell Terminal
|
||||
crewai skill list
|
||||
```
|
||||
|
||||
Mostra as skills instaladas tanto do diretório `./skills/` do projeto quanto do cache global, com suas versões e caminhos.
|
||||
|
||||
---
|
||||
|
||||
## Skills no Nível do Crew
|
||||
|
||||
Skills podem ser definidas no crew para aplicar a **todos os agentes**:
|
||||
|
||||
@@ -11,7 +11,7 @@ mode: "wide"
|
||||
|
||||
- [Visão Geral](/pt-BR/enterprise/features/agent-control-plane/overview)
|
||||
- **Monitoramento** *(você está aqui)*
|
||||
- [Regras](/pt-BR/enterprise/features/agent-control-plane/rules)
|
||||
- [Políticas](/edge/pt-BR/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## Visão Geral
|
||||
@@ -58,7 +58,7 @@ A sub-aba **Automações** é o detalhamento por deployment da saúde da frota.
|
||||
| **Última execução** | Tempo decorrido desde a execução mais recente. |
|
||||
| **Health Status Breakdown** | Barra empilhada com percentuais de `Critical` / `Warning` / `Healthy` para as execuções na janela. |
|
||||
| **Executions with Errors** | Total de execuções com falha na janela. |
|
||||
| **PII detection applied** | `Yes` se houver configuração de PII por deployment ou uma [regra de PII](/pt-BR/enterprise/features/agent-control-plane/rules) correspondente ativa. |
|
||||
| **PII detection applied** | `Yes` se houver configuração de PII por deployment ou uma [política de PII](/edge/pt-BR/enterprise/features/agent-control-plane/policies) correspondente ativa. |
|
||||
| **Executions** | Total de execuções na janela. |
|
||||
| **Last updated** | Quando o deployment foi re-implantado pela última vez. |
|
||||
| **Crew Version** | A versão do `crewai` reportada pelo deployment. Um ícone de informação ao lado de versões abaixo de `1.13` indica linhas que não conseguem contribuir com métricas. |
|
||||
@@ -96,8 +96,8 @@ Filtre por **LLM provider** e ordene por `Cost`, `Executions` ou `Last run`.
|
||||
<Card title="Agent Control Plane — Visão Geral" icon="book-open" href="/pt-BR/enterprise/features/agent-control-plane/overview">
|
||||
O que é o ACP, requisitos, planos suportados e RBAC.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — Regras" icon="shield-check" href="/pt-BR/enterprise/features/agent-control-plane/rules">
|
||||
Aplique regras de PII Redaction em nível de organização em muitas automações.
|
||||
<Card title="Agent Control Plane — Políticas" icon="shield-check" href="/edge/pt-BR/enterprise/features/agent-control-plane/policies">
|
||||
Aplique políticas de PII Redaction em nível de organização em muitas automações.
|
||||
</Card>
|
||||
<Card title="Traces" icon="timeline" href="/pt-BR/enterprise/features/traces">
|
||||
Aprofunde em uma única execução para ver o raciocínio do agente, chamadas de ferramentas e uso de tokens.
|
||||
|
||||
@@ -10,17 +10,17 @@ icon: "book-open"
|
||||
|
||||
- **Visão Geral** *(você está aqui)*
|
||||
- [Monitoramento](/pt-BR/enterprise/features/agent-control-plane/monitoring)
|
||||
- [Regras](/pt-BR/enterprise/features/agent-control-plane/rules)
|
||||
- [Políticas](/edge/pt-BR/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## Visão Geral
|
||||
|
||||
O **Agent Control Plane** (ACP) é o hub de operações para tudo que você tem rodando no CrewAI AMP. É uma tela única — dividida nas abas **Automações** e **Regras** — que permite à sua equipe:
|
||||
O **Agent Control Plane** (ACP) é o hub de operações para tudo que você tem rodando no CrewAI AMP. É uma tela única — dividida nas abas **Automações** e **Políticas** — que permite à sua equipe:
|
||||
|
||||
- Monitorar a **saúde** de cada automação ao vivo (crew ou flow), com detalhamentos `Critical` / `Warning` / `Healthy` e contagem de execuções.
|
||||
- Acompanhar o **consumo de LLM** — tokens e custo — por automação, por provedor e por modelo, com a variação em relação ao período anterior.
|
||||
- Aprofundar em qualquer automação ou provedor de modelo para ver gráficos de série temporal e detalhamentos por provedor.
|
||||
- Aplicar **Regras** em nível de organização (hoje: PII Redaction) em muitas automações de uma só vez, em vez de editar cada deployment individualmente.
|
||||
- Aplicar **Políticas** em nível de organização (hoje: PII Redaction) em muitas automações de uma só vez, em vez de editar cada deployment individualmente.
|
||||
|
||||
<Frame>
|
||||

|
||||
@@ -33,7 +33,7 @@ O **Agent Control Plane** (ACP) é o hub de operações para tudo que você tem
|
||||
As duas abas respondem a duas perguntas distintas:
|
||||
|
||||
- **Automações** — *"Como minha frota está se comportando agora e quanto está me custando?"* Veja [Monitoramento](/pt-BR/enterprise/features/agent-control-plane/monitoring).
|
||||
- **Regras** — *"Como aplico uma política (por exemplo, PII redaction) em muitos deployments sem precisar reimplantar cada um?"* Veja [Regras](/pt-BR/enterprise/features/agent-control-plane/rules).
|
||||
- **Políticas** — *"Como aplico uma política (por exemplo, PII redaction) em muitos deployments sem precisar reimplantar cada um?"* Veja [Políticas](/edge/pt-BR/enterprise/features/agent-control-plane/policies).
|
||||
|
||||
## Requisitos
|
||||
|
||||
@@ -42,11 +42,11 @@ As duas abas respondem a duas perguntas distintas:
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
**Plano Enterprise ou Ultra** é necessário para criar ou editar [Regras](/pt-BR/enterprise/features/agent-control-plane/rules). Organizações em planos inferiores ainda podem abrir a aba Regras e visualizar regras existentes, mas o editor é renderizado em modo somente leitura, com um selo "Enterprise" de bloqueio e o alerta *"PII Redaction rules require an Enterprise plan."* O Monitoramento (a aba Automações) está disponível em todos os planos em que o recurso esteja habilitado.
|
||||
**Plano Enterprise ou Ultra** é necessário para criar ou editar [Políticas](/edge/pt-BR/enterprise/features/agent-control-plane/policies). Organizações em planos inferiores ainda podem abrir a aba Políticas e visualizar políticas existentes, mas o editor é renderizado em modo somente leitura, com um selo "Enterprise" de bloqueio e o alerta *"PII Redaction policies require an Enterprise plan."* O Monitoramento (a aba Automações) está disponível em todos os planos em que o recurso esteja habilitado.
|
||||
</Warning>
|
||||
|
||||
- O recurso **Agent Control Plane** precisa estar habilitado para sua organização. Se você não o vê na barra lateral, peça ao owner da conta para solicitar a habilitação.
|
||||
- Dentro do ACP, o [RBAC](/pt-BR/enterprise/features/rbac) controla o acesso: `read` para visualizar o dashboard e as regras, `manage` para criar, editar, ligar/desligar ou excluir regras.
|
||||
- Dentro do ACP, o [RBAC](/pt-BR/enterprise/features/rbac) controla o acesso: `read` para visualizar o dashboard e as políticas, `manage` para criar, editar, ligar/desligar ou excluir políticas.
|
||||
- Todos os gráficos e tabelas podem ser ajustados para **Últimas 24 horas**, **Última Semana** ou **Últimos 30 dias** usando o seletor de tempo no canto superior direito. As variações (`↑ 8 vs ontem`, `↓ $20.57 vs ontem`, etc.) comparam a janela selecionada com a janela anterior de mesma duração.
|
||||
|
||||
## O que você pode fazer aqui
|
||||
@@ -55,7 +55,7 @@ As duas abas respondem a duas perguntas distintas:
|
||||
<Card title="Monitoramento" icon="gauge" href="/pt-BR/enterprise/features/agent-control-plane/monitoring">
|
||||
Acompanhe a saúde da frota e o gasto com LLM com cards de métricas, um sankey interativo, tabelas por automação e painéis laterais de detalhamento para qualquer automação ou provedor.
|
||||
</Card>
|
||||
<Card title="Regras" icon="shield-check" href="/pt-BR/enterprise/features/agent-control-plane/rules">
|
||||
<Card title="Políticas" icon="shield-check" href="/edge/pt-BR/enterprise/features/agent-control-plane/policies">
|
||||
Aplique políticas de PII Redaction em nível de organização, com escopo por ferramentas e tags. As mudanças entram em vigor na próxima execução — sem necessidade de re-implantação.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
@@ -67,10 +67,10 @@ As duas abas respondem a duas perguntas distintas:
|
||||
Aprofunde em uma única execução para ver o raciocínio do agente, chamadas de ferramentas e uso de tokens.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/pt-BR/enterprise/features/rbac">
|
||||
Gerencie quem pode ler o Agent Control Plane e quem pode editar regras.
|
||||
Gerencie quem pode ler o Agent Control Plane e quem pode editar políticas.
|
||||
</Card>
|
||||
<Card title="PII Redaction para Traces" icon="lock" href="/pt-BR/enterprise/features/pii-trace-redactions">
|
||||
Catálogo de entidades e configuração de PII por deployment, referenciados pelas Regras.
|
||||
Catálogo de entidades e configuração de PII por deployment, referenciados pelas Políticas.
|
||||
</Card>
|
||||
<Card title="Deploy no AMP" icon="rocket" href="/pt-BR/enterprise/guides/deploy-to-amp">
|
||||
Implante uma crew em uma versão do crewAI que suporta o Agent Control Plane.
|
||||
@@ -78,5 +78,5 @@ As duas abas respondem a duas perguntas distintas:
|
||||
</CardGroup>
|
||||
|
||||
<Card title="Precisa de ajuda?" icon="headset" href="mailto:support@crewai.com">
|
||||
Entre em contato com nosso time de suporte para interpretar métricas ou desenhar regras.
|
||||
Entre em contato com nosso time de suporte para interpretar métricas ou desenhar políticas.
|
||||
</Card>
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
---
|
||||
title: "Configure as Políticas"
|
||||
description: "Aplique políticas em nível de organização em muitas automações a partir de um único lugar."
|
||||
sidebarTitle: "Políticas"
|
||||
icon: "shield-check"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**Navegação da Documentação do ACP (Beta)**
|
||||
|
||||
- [Visão Geral](/pt-BR/enterprise/features/agent-control-plane/overview)
|
||||
- [Monitoramento](/pt-BR/enterprise/features/agent-control-plane/monitoring)
|
||||
- **Políticas** *(você está aqui)*
|
||||
</Info>
|
||||
|
||||
## Visão Geral
|
||||
|
||||
As Políticas permitem aplicar políticas — hoje: **PII Redaction** — em muitas automações de uma só vez, em vez de configurar cada deployment individualmente. Abra a aba **Políticas** no [Agent Control Plane](/pt-BR/enterprise/features/agent-control-plane/overview) para gerenciá-las.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Cada card de política mostra o nome, a descrição, o **escopo** ao qual a política se aplica (ferramentas e tags selecionadas) e a contagem de **automações engajadas** — deployments que atualmente correspondem ao escopo. O toggle à direita ativa ou desativa a política sem excluí-la.
|
||||
|
||||
## Requisitos
|
||||
|
||||
<Warning>
|
||||
**Plano Enterprise ou Ultra** é necessário para criar ou editar políticas de PII Redaction. Organizações em planos inferiores ainda podem abrir a aba Políticas e visualizar políticas existentes, mas o editor é renderizado em modo somente leitura, com um selo "Enterprise" de bloqueio e o alerta *"PII Redaction policies require an Enterprise plan."* — entre em contato com o owner da sua conta ou com vendas para fazer upgrade.
|
||||
</Warning>
|
||||
|
||||
- O recurso **Agent Control Plane** precisa estar habilitado para sua organização. Veja [Visão Geral — Requisitos](/pt-BR/enterprise/features/agent-control-plane/overview#requisitos).
|
||||
- A permissão `manage` no [RBAC](/pt-BR/enterprise/features/rbac) sobre o Agent Control Plane é necessária para criar, editar, ligar/desligar ou excluir políticas. A permissão `read` é suficiente para visualizá-las.
|
||||
- Todas as mudanças de políticas são versionadas para auditoria.
|
||||
|
||||
## Tipos de política disponíveis
|
||||
|
||||
| Tipo | O que faz |
|
||||
|------|---------------|
|
||||
| **PII Redaction** | Aplica PII redaction às execuções de cada automação correspondente, usando o mesmo catálogo de entidades e recognizers customizados documentados em [PII Redaction para Traces](/pt-BR/enterprise/features/pii-trace-redactions). |
|
||||
|
||||
Mais tipos de políticas serão adicionados ao longo do tempo.
|
||||
|
||||
## Criando uma política
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/acp-policies-new-side-panel.png" alt="Painel lateral de edição de política com condições e tipo de máscara de PII" width="450" />
|
||||
</Frame>
|
||||
|
||||
<Steps>
|
||||
<Step title="Abra o editor">
|
||||
Clique em **+ Create new** no canto superior direito da aba Políticas, ou em **View Details** em um card de política existente.
|
||||
</Step>
|
||||
|
||||
<Step title="Dê um nome e descreva a política">
|
||||
Dê à política um nome claro (ex.: *Mask PII (CC)*) e uma descrição explicando quando ela se aplica. Ambos aparecem no card da política e no modal de Automações Engajadas.
|
||||
</Step>
|
||||
|
||||
<Step title="Escolha o tipo">
|
||||
Hoje só **PII Redaction** está disponível.
|
||||
</Step>
|
||||
|
||||
<Step title="Defina as condições">
|
||||
As condições decidem quais automações a política engaja. Ambas são opcionais e usam a semântica de **igualdade de conjuntos**:
|
||||
|
||||
- **Tools** — apenas automações cujo conjunto de ferramentas **corresponde exatamente** às ferramentas selecionadas serão engajadas. Selecione entre apps do Studio, MCPs, ferramentas OSS e ferramentas do Tool Repository.
|
||||
- **Automations** — apenas automações cujo conjunto de tags **corresponde exatamente** às tags selecionadas serão engajadas.
|
||||
|
||||
Deixar um seletor vazio significa "sem filtro nesta dimensão". Deixar ambos vazios significa que a política se aplica a **todas** as automações da organização.
|
||||
</Step>
|
||||
|
||||
<Step title="Configure a tabela PII Mask Type">
|
||||
Marque cada tipo de entidade que deseja cobrir e escolha **Mask** (substitui pelo rótulo da entidade, ex.: `<CREDIT_CARD>`) ou **Redact** (remove o texto correspondente por completo). Veja [PII Redaction para Traces](/pt-BR/enterprise/features/pii-trace-redactions) para o catálogo completo de entidades e como adicionar recognizers customizados em nível de organização.
|
||||
</Step>
|
||||
|
||||
<Step title="Salve">
|
||||
A política se aplica a **futuras** execuções de cada automação engajada assim que você salva. Nenhuma re-implantação é necessária.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Automações engajadas
|
||||
|
||||
Clique em **Engaged N automations** em qualquer card de política para ver exatamente quais deployments a política está correspondendo no momento, junto com a última execução de cada um.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Esta é a forma mais rápida de validar o escopo de uma política antes de habilitá-la — por exemplo, para confirmar que uma política com escopo na tag `production` não está acidentalmente correspondendo a um deployment de staging.
|
||||
|
||||
## Políticas em nível de organização vs configurações por deployment
|
||||
|
||||
A PII Redaction pode ser configurada em dois lugares:
|
||||
|
||||
- **Por deployment** — em **Settings → PII Protection** em cada deployment individual ([guia](/pt-BR/enterprise/features/pii-trace-redactions))
|
||||
- **Em nível de organização** — como uma Política nesta página
|
||||
|
||||
Quando o escopo de uma política habilitada em nível de organização corresponde a um deployment, a configuração de entidades da política **sobrescreve** as configurações de PII pertencentes ao deployment para as execuções daquele deployment — a política se torna a fonte única da verdade enquanto está vinculada. Desabilite ou desvincule a política (ou altere o escopo para que ela não corresponda mais) e o deployment volta às suas próprias configurações de PII Protection.
|
||||
|
||||
Prefira políticas em nível de organização quando quiser impor uma política consistente em muitos deployments; reserve a configuração por deployment para exceções pontuais.
|
||||
|
||||
## Relacionados
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent Control Plane — Visão Geral" icon="book-open" href="/pt-BR/enterprise/features/agent-control-plane/overview">
|
||||
O que é o ACP, requisitos, planos suportados e RBAC.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — Monitoramento" icon="gauge" href="/pt-BR/enterprise/features/agent-control-plane/monitoring">
|
||||
Acompanhe automações e consumo de LLM em toda a sua frota.
|
||||
</Card>
|
||||
<Card title="PII Redaction para Traces" icon="lock" href="/pt-BR/enterprise/features/pii-trace-redactions">
|
||||
Catálogo de entidades, recognizers customizados e configuração por deployment.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/pt-BR/enterprise/features/rbac">
|
||||
Gerencie quem pode criar ou editar políticas.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="Precisa de ajuda?" icon="headset" href="mailto:support@crewai.com">
|
||||
Entre em contato com nosso time de suporte para ajudar a desenhar políticas para a sua organização.
|
||||
</Card>
|
||||
@@ -1,122 +0,0 @@
|
||||
---
|
||||
title: "Configure as Regras"
|
||||
description: "Aplique políticas em nível de organização em muitas automações a partir de um único lugar."
|
||||
sidebarTitle: "Regras"
|
||||
icon: "shield-check"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**Navegação da Documentação do ACP (Beta)**
|
||||
|
||||
- [Visão Geral](/pt-BR/enterprise/features/agent-control-plane/overview)
|
||||
- [Monitoramento](/pt-BR/enterprise/features/agent-control-plane/monitoring)
|
||||
- **Regras** *(você está aqui)*
|
||||
</Info>
|
||||
|
||||
## Visão Geral
|
||||
|
||||
As Regras permitem aplicar políticas — hoje: **PII Redaction** — em muitas automações de uma só vez, em vez de configurar cada deployment individualmente. Abra a aba **Regras** no [Agent Control Plane](/pt-BR/enterprise/features/agent-control-plane/overview) para gerenciá-las.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Cada card de regra mostra o nome, a descrição, o **escopo** ao qual a regra se aplica (ferramentas e tags selecionadas) e a contagem de **automações engajadas** — deployments que atualmente correspondem ao escopo. O toggle à direita ativa ou desativa a regra sem excluí-la.
|
||||
|
||||
## Requisitos
|
||||
|
||||
<Warning>
|
||||
**Plano Enterprise ou Ultra** é necessário para criar ou editar regras de PII Redaction. Organizações em planos inferiores ainda podem abrir a aba Regras e visualizar regras existentes, mas o editor é renderizado em modo somente leitura, com um selo "Enterprise" de bloqueio e o alerta *"PII Redaction rules require an Enterprise plan."* — entre em contato com o owner da sua conta ou com vendas para fazer upgrade.
|
||||
</Warning>
|
||||
|
||||
- O recurso **Agent Control Plane** precisa estar habilitado para sua organização. Veja [Visão Geral — Requisitos](/pt-BR/enterprise/features/agent-control-plane/overview#requisitos).
|
||||
- A permissão `manage` no [RBAC](/pt-BR/enterprise/features/rbac) sobre o Agent Control Plane é necessária para criar, editar, ligar/desligar ou excluir regras. A permissão `read` é suficiente para visualizá-las.
|
||||
- Todas as mudanças de regras são versionadas para auditoria.
|
||||
|
||||
## Tipos de regra disponíveis
|
||||
|
||||
| Tipo | O que faz |
|
||||
|------|---------------|
|
||||
| **PII Redaction** | Aplica PII redaction às execuções de cada automação correspondente, usando o mesmo catálogo de entidades e recognizers customizados documentados em [PII Redaction para Traces](/pt-BR/enterprise/features/pii-trace-redactions). |
|
||||
|
||||
Mais tipos de regras serão adicionados ao longo do tempo.
|
||||
|
||||
## Criando uma regra
|
||||
|
||||
<Frame>
|
||||
<img src="/images/enterprise/acp-rules-edit-side-panel.png" alt="Painel lateral de edição de regra com condições e tipo de máscara de PII" width="450" />
|
||||
</Frame>
|
||||
|
||||
<Steps>
|
||||
<Step title="Abra o editor">
|
||||
Clique em **+ Create new** no canto superior direito da aba Regras, ou em **View Details** em um card de regra existente.
|
||||
</Step>
|
||||
|
||||
<Step title="Dê um nome e descreva a regra">
|
||||
Dê à regra um nome claro (ex.: *Mask PII (CC)*) e uma descrição explicando quando ela se aplica. Ambos aparecem no card da regra e no modal de Automações Engajadas.
|
||||
</Step>
|
||||
|
||||
<Step title="Escolha o tipo">
|
||||
Hoje só **PII Redaction** está disponível.
|
||||
</Step>
|
||||
|
||||
<Step title="Defina as condições">
|
||||
As condições decidem quais automações a regra engaja. Ambas são opcionais e usam a semântica de **igualdade de conjuntos**:
|
||||
|
||||
- **Tools** — apenas automações cujo conjunto de ferramentas **corresponde exatamente** às ferramentas selecionadas serão engajadas. Selecione entre apps do Studio, MCPs, ferramentas OSS e ferramentas do Tool Repository.
|
||||
- **Automations** — apenas automações cujo conjunto de tags **corresponde exatamente** às tags selecionadas serão engajadas.
|
||||
|
||||
Deixar um seletor vazio significa "sem filtro nesta dimensão". Deixar ambos vazios significa que a regra se aplica a **todas** as automações da organização.
|
||||
</Step>
|
||||
|
||||
<Step title="Configure a tabela PII Mask Type">
|
||||
Marque cada tipo de entidade que deseja cobrir e escolha **Mask** (substitui pelo rótulo da entidade, ex.: `<CREDIT_CARD>`) ou **Redact** (remove o texto correspondente por completo). Veja [PII Redaction para Traces](/pt-BR/enterprise/features/pii-trace-redactions) para o catálogo completo de entidades e como adicionar recognizers customizados em nível de organização.
|
||||
</Step>
|
||||
|
||||
<Step title="Salve">
|
||||
A regra se aplica a **futuras** execuções de cada automação engajada assim que você salva. Nenhuma re-implantação é necessária.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Automações engajadas
|
||||
|
||||
Clique em **Engaged N automations** em qualquer card de regra para ver exatamente quais deployments a regra está correspondendo no momento, junto com a última execução de cada um.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Esta é a forma mais rápida de validar o escopo de uma regra antes de habilitá-la — por exemplo, para confirmar que uma regra com escopo na tag `production` não está acidentalmente correspondendo a um deployment de staging.
|
||||
|
||||
## Regras em nível de organização vs configurações por deployment
|
||||
|
||||
A PII Redaction pode ser configurada em dois lugares:
|
||||
|
||||
- **Por deployment** — em **Settings → PII Protection** em cada deployment individual ([guia](/pt-BR/enterprise/features/pii-trace-redactions))
|
||||
- **Em nível de organização** — como uma Regra nesta página
|
||||
|
||||
Quando o escopo de uma regra habilitada em nível de organização corresponde a um deployment, a configuração de entidades da regra **sobrescreve** as configurações de PII pertencentes ao deployment para as execuções daquele deployment — a regra se torna a fonte única da verdade enquanto está vinculada. Desabilite ou desvincule a regra (ou altere o escopo para que ela não corresponda mais) e o deployment volta às suas próprias configurações de PII Protection.
|
||||
|
||||
Prefira regras em nível de organização quando quiser impor uma política consistente em muitos deployments; reserve a configuração por deployment para exceções pontuais.
|
||||
|
||||
## Relacionados
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent Control Plane — Visão Geral" icon="book-open" href="/pt-BR/enterprise/features/agent-control-plane/overview">
|
||||
O que é o ACP, requisitos, planos suportados e RBAC.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — Monitoramento" icon="gauge" href="/pt-BR/enterprise/features/agent-control-plane/monitoring">
|
||||
Acompanhe automações e consumo de LLM em toda a sua frota.
|
||||
</Card>
|
||||
<Card title="PII Redaction para Traces" icon="lock" href="/pt-BR/enterprise/features/pii-trace-redactions">
|
||||
Catálogo de entidades, recognizers customizados e configuração por deployment.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/pt-BR/enterprise/features/rbac">
|
||||
Gerencie quem pode criar ou editar regras.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="Precisa de ajuda?" icon="headset" href="mailto:support@crewai.com">
|
||||
Entre em contato com nosso time de suporte para ajudar a desenhar regras para a sua organização.
|
||||
</Card>
|
||||
123
docs/edge/pt-BR/enterprise/features/studio-flows.mdx
Normal file
@@ -0,0 +1,123 @@
|
||||
---
|
||||
title: Flows no Studio
|
||||
description: "Crie fluxos de trabalho orientados a eventos que combinam controle determinístico passo a passo com inteligência agêntica — sem escrever código."
|
||||
icon: "diagram-project"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**Lançamento em andamento**: Flows no Studio está sendo liberado gradualmente durante a semana de 20 de julho de 2026. Se você ainda não vê a opção Flows no Studio, o recurso ainda não chegou à sua organização — volte em breve.
|
||||
</Info>
|
||||
|
||||
## Visão geral
|
||||
|
||||
O Studio agora permite criar **Flows** além de Crews. Flows são fluxos de trabalho orientados a eventos em que você controla exatamente quais etapas são executadas, em que ordem e sob quais condições — enquanto delega o trabalho inteligente dentro de cada etapa a agentes de IA.
|
||||
|
||||
Para criar um Flow, abra o Studio, descreva sua automação e selecione **Flows** no seletor ao lado da caixa de prompt.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## Por que Flows?
|
||||
|
||||
Crews são ótimos quando você quer que uma equipe de agentes colabore de forma autônoma em direção a um objetivo. Mas muitas automações do mundo real precisam de mais previsibilidade: buscar estes dados primeiro, depois resumi-los, depois publicar o resultado — sempre, nessa ordem.
|
||||
|
||||
Flows oferecem os dois:
|
||||
|
||||
- **Determinismo onde importa**: as etapas são executadas em uma sequência definida com ramificações explícitas, tornando as execuções previsíveis, repetíveis e fáceis de depurar.
|
||||
- **Inteligência onde você precisa**: cada etapa é executada por um agente (ou por um crew inteiro), então o trabalho dentro da etapa — resumir, pontuar, redigir, decidir — se beneficia de todo o raciocínio do LLM.
|
||||
|
||||
Essa combinação é o que torna os Flows adequados para automações em produção: a estrutura é garantida e a agência fica restrita às etapas que precisam dela.
|
||||
|
||||
## Criando um Flow
|
||||
|
||||
Descreva o que você quer em linguagem natural e o Studio Assistant projeta o Flow para você — criando as etapas, conectando-as e configurando os agentes e as integrações de apps de que cada etapa precisa. O canvas à direita mostra o fluxo resultante como nós conectados, e você pode continuar iterando por conversa ou editar qualquer nó diretamente.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Quando estiver pronto, use **Run** para testar o Flow de ponta a ponta, inspecione os resultados nas abas **Output** e **Traces** e faça o **Deploy** quando estiver estável. Você também pode compartilhar o projeto (**Share**) ou baixar o código-fonte (**Download**).
|
||||
|
||||
## Tipos de nós
|
||||
|
||||
Flows são compostos por três tipos principais de nós. Cada nó é uma etapa do fluxo de trabalho, e você pode combiná-los livremente.
|
||||
|
||||
### Single Agent
|
||||
|
||||
Um nó Single Agent executa um agente em uma única tarefa focada — ideal para etapas bem delimitadas, como buscar dados de uma integração, transformar conteúdo ou publicar uma mensagem.
|
||||
|
||||
Ao clicar em um nó de agente, você abre sua configuração completa:
|
||||
|
||||
- **Task**: o que essa etapa deve realizar e qual saída deve produzir
|
||||
- **Profile**: o papel (role), o objetivo (goal) e a história (backstory) do agente
|
||||
- **Model**: qual LLM alimenta o agente
|
||||
- **Apps**: as integrações que o agente pode usar (ex.: Linear, Slack, HubSpot)
|
||||
- **Runtime Controls**: opções para planejar antes de executar, delegação e memória
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
### Crews
|
||||
|
||||
Um nó Crew incorpora um crew inteiro — múltiplos agentes colaborando em múltiplas tarefas — como uma única etapa do seu Flow. Use-o quando uma etapa for rica demais para um único agente, como agrupar e resumir dados por equipe e depois formatar o resultado para entrega.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Ao abrir um nó Crew, você vê sua estrutura interna: as tarefas que ele executa, os agentes atribuídos a cada uma e os apps que eles usam. O crew é executado de forma autônoma dentro da etapa e entrega sua saída ao próximo nó do Flow.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Esse é o padrão determinístico-mais-agêntico em ação: o Flow garante *quando* o crew é executado, e o crew traz inteligência colaborativa para *como* o trabalho é feito.
|
||||
|
||||
### Router
|
||||
|
||||
Um nó Router ramifica o Flow com base em condições, para que resultados diferentes sigam caminhos diferentes. Por exemplo, um Flow de roteamento de leads pode pontuar os leads recebidos e encaminhar os de alta qualidade para uma etapa de atribuição de vendas, enquanto registra os demais para nutrição futura.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
Os Routers são o que torna os Flows verdadeiramente orientados a eventos: o mesmo fluxo de trabalho lida com todos os casos, mas cada execução segue apenas o ramo que seus dados justificam — sem etapas desperdiçadas, sem ambiguidade sobre o que acontece a seguir.
|
||||
|
||||
## Sincronização com o Agent Repository
|
||||
|
||||
Os agentes que você cria em Flows não precisam ficar presos a um único projeto. Todo nó de agente inclui um botão **Publish to Agent Repository**, que salva o agente — papel, objetivo, história, modelo e configuração — no [Agent Repository](/pt-BR/enterprise/features/agent-repositories) da sua organização.
|
||||
|
||||
Isso funciona nos dois sentidos:
|
||||
|
||||
- **Publicar**: promova um agente refinado em um Flow para o repositório, para que outras equipes e projetos possam reutilizá-lo.
|
||||
- **Importar**: traga um agente existente do repositório para um novo Flow em vez de recriá-lo do zero.
|
||||
|
||||
Como os agentes do repositório são sincronizados em toda a organização, uma melhoria feita em um agente compartilhado beneficia todos os Flows que o utilizam — mantendo o comportamento dos agentes consistente, governado e sem duplicação de esforço.
|
||||
|
||||
## Boas práticas
|
||||
|
||||
- **Escolha um Flow** quando a automação tiver uma sequência clara ou lógica de ramificação; escolha um Crew quando o caminho até o objetivo for aberto.
|
||||
- **Mantenha as tarefas dos agentes focadas** — um nó Single Agent com uma descrição de tarefa enxuta é mais confiável do que um agente encarregado de três coisas.
|
||||
- **Use Routers para tratar todos os casos explicitamente**, inclusive o caminho "não fazer nada" (ex.: registrar leads ignorados), para que as execuções fiquem totalmente contabilizadas.
|
||||
- **Publique agentes estáveis no Agent Repository** para que sua organização construa uma biblioteca compartilhada em vez de cópias paralelas.
|
||||
- **Teste com Run e inspecione os Traces** antes do deploy para detectar problemas de integração ou de prompt com antecedência.
|
||||
|
||||
## Relacionados
|
||||
|
||||
<CardGroup cols={4}>
|
||||
<Card title="Crew Studio" href="/pt-BR/enterprise/features/crew-studio" icon="pencil">
|
||||
Crie Crews no Studio.
|
||||
</Card>
|
||||
<Card title="Agent Repositories" href="/pt-BR/enterprise/features/agent-repositories" icon="people-group">
|
||||
Compartilhe e reutilize agentes em toda a sua organização.
|
||||
</Card>
|
||||
<Card title="Conceitos de Flows" href="/pt-BR/concepts/flows" icon="diagram-project">
|
||||
Saiba como os Flows funcionam no framework CrewAI.
|
||||
</Card>
|
||||
<Card title="Tools & Integrations" href="/pt-BR/enterprise/features/tools-and-integrations" icon="plug">
|
||||
Conecte os apps que seus agentes usam.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
194
docs/edge/pt-BR/learn/streaming-runtime-contract.mdx
Normal file
@@ -0,0 +1,194 @@
|
||||
---
|
||||
title: Contrato de Streaming do Runtime
|
||||
description: Transmita frames ordenados do runtime a partir de Flows, chamadas diretas de LLM e turnos conversacionais.
|
||||
icon: tower-broadcast
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## Visão geral
|
||||
|
||||
O CrewAI expõe um contrato de streaming baseado em frames para runtimes que precisam de mais do que chunks de texto simples. O contrato emite objetos `StreamFrame` ordenados para eventos de ciclo de vida de Flow, tokens de LLM diretos, atividade de ferramentas, mensagens de conversa e eventos personalizados.
|
||||
|
||||
Use esta API ao criar uma UI, ponte de serviço, aplicativo de terminal ou runtime de implantação que precise de um fluxo estável de eventos estruturados enquanto um Flow, turno de chat ou chamada direta de LLM está em execução.
|
||||
|
||||
## StreamFrame
|
||||
|
||||
Todo frame tem o mesmo envelope:
|
||||
|
||||
```python
|
||||
from crewai.types.streaming import StreamFrame
|
||||
|
||||
frame.id # id único do frame
|
||||
frame.seq # ordem local da execução, quando disponível
|
||||
frame.type # tipo do evento de origem, como "flow_started"
|
||||
frame.channel # "llm", "flow", "tools", "messages", "lifecycle" ou "custom"
|
||||
frame.namespace # namespace de origem/runtime
|
||||
frame.timestamp # timestamp do evento
|
||||
frame.parent_id # id do evento pai, quando disponível
|
||||
frame.previous_id # id do evento anterior, quando disponível
|
||||
frame.data # payload do evento
|
||||
frame.event # alias para frame.data
|
||||
frame.content # texto imprimível para frames de token, caso contrário ""
|
||||
```
|
||||
|
||||
O campo `channel` é a forma mais rápida de rotear frames em consumidores:
|
||||
|
||||
| Canal | Contém |
|
||||
|-------|--------|
|
||||
| `llm` | Tokens e chunks de raciocínio de eventos de streaming de LLM |
|
||||
| `flow` | Ciclo de vida do Flow, execução de métodos, roteamento e eventos de pausa/retomada |
|
||||
| `tools` | Eventos de uso de ferramentas |
|
||||
| `messages` | Eventos do transcript da conversa |
|
||||
| `lifecycle` | Eventos de ciclo de vida do runtime que não pertencem a outro canal |
|
||||
| `custom` | Eventos que não mapeiam para um canal integrado |
|
||||
|
||||
`frame.type` preserva o tipo do evento de origem, para que consumidores possam tratar eventos específicos dentro de um canal.
|
||||
|
||||
## Transmitir um Flow
|
||||
|
||||
Defina `stream=True` em um Flow para fazer `kickoff()` retornar uma sessão de stream:
|
||||
|
||||
```python
|
||||
from crewai.flow import Flow, start
|
||||
|
||||
|
||||
class ReportFlow(Flow):
|
||||
@start()
|
||||
def generate(self):
|
||||
return "done"
|
||||
|
||||
|
||||
flow = ReportFlow(stream=True)
|
||||
stream = flow.kickoff()
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
if chunk.type == "tool_usage_started":
|
||||
print(chunk.event["tool_name"])
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
Você deve consumir o stream antes de ler `stream.result`. Acessar o resultado cedo demais gera um `RuntimeError`, para que consumidores não tratem uma execução parcial como concluída.
|
||||
|
||||
Você também pode chamar `flow.stream_events(...)` diretamente quando quiser streaming para uma única invocação sem definir `stream=True` na instância do Flow.
|
||||
|
||||
## Filtrar por canal
|
||||
|
||||
`StreamSession` expõe projeções por canal que preservam a ordem global dos frames dentro do canal selecionado:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
with stream:
|
||||
for frame in stream.llm:
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
As projeções disponíveis são:
|
||||
|
||||
| Projeção | Frames |
|
||||
|----------|--------|
|
||||
| `stream.events` | Todos os frames |
|
||||
| `stream.llm` | Frames de LLM |
|
||||
| `stream.messages` | Frames de mensagens de conversa |
|
||||
| `stream.flow` | Frames de Flow |
|
||||
| `stream.tools` | Frames de ferramentas |
|
||||
| `stream.interleave([...])` | Um conjunto selecionado de canais |
|
||||
|
||||
Use `stream.interleave(["flow", "llm", "messages"])` quando um consumidor quiser apenas alguns canais, mas ainda precisar da ordem relativa entre eles.
|
||||
|
||||
## Streaming assíncrono
|
||||
|
||||
Use `astream()` para consumidores assíncronos:
|
||||
|
||||
```python
|
||||
flow = ReportFlow()
|
||||
stream = flow.astream()
|
||||
|
||||
async with stream:
|
||||
async for chunk in stream.events:
|
||||
print(chunk.channel, chunk.type, chunk.content)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
A sessão assíncrona tem as mesmas projeções da sessão síncrona.
|
||||
|
||||
## Transmitir uma chamada direta de LLM
|
||||
|
||||
`llm.call(...)` ainda retorna o resultado final montado. Use `llm.stream_events(...)` quando quiser iterar pelos chunks conforme eles chegam, mantendo o payload estruturado do evento:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
|
||||
llm = LLM(model="gpt-4o-mini")
|
||||
stream = llm.stream_events(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain CrewAI streaming in two short sentences.",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
with stream:
|
||||
for chunk in stream:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = stream.result
|
||||
```
|
||||
|
||||
`llm.stream_events(...)` ativa temporariamente o streaming para a chamada encapsulada e restaura a configuração anterior de `stream` do LLM depois. As integrações de provedores continuam emitindo os eventos de stream de LLM subjacentes; esse helper fornece uma API de iterador comum sobre esses eventos para todos os provedores de LLM.
|
||||
|
||||
## Turnos conversacionais
|
||||
|
||||
Flows conversacionais podem transmitir um turno de usuário com `stream_turn()`:
|
||||
|
||||
```python
|
||||
from crewai import Flow
|
||||
from crewai.experimental.conversational import ConversationConfig, ConversationState
|
||||
|
||||
|
||||
@ConversationConfig(llm="gpt-4o-mini", defer_trace_finalization=True)
|
||||
class ChatFlow(Flow[ConversationState]):
|
||||
conversational = True
|
||||
|
||||
|
||||
flow = ChatFlow()
|
||||
stream = flow.stream_turn("What can you help me with?", session_id="session-1")
|
||||
|
||||
with stream:
|
||||
for frame in stream.events:
|
||||
if frame.channel == "llm" and frame.type == "llm_stream_chunk":
|
||||
print(frame.content, end="", flush=True)
|
||||
|
||||
reply = stream.result
|
||||
```
|
||||
|
||||
Durante `stream_turn()`, o caminho de resposta conversacional integrado ativa o streaming de tokens de LLM para esse turno e restaura a configuração anterior de `stream` do LLM depois. Handlers de rota personalizados que criam seus próprios agentes ou instâncias de LLM devem configurar esses LLMs para streaming se precisarem de saída em nível de token.
|
||||
|
||||
## Limpeza
|
||||
|
||||
Use a sessão como gerenciador de contexto quando possível. Se um cliente se desconectar antes de o stream ser esgotado, feche a sessão explicitamente:
|
||||
|
||||
```python
|
||||
stream = flow.stream_events()
|
||||
|
||||
try:
|
||||
for frame in stream.events:
|
||||
print(frame.type)
|
||||
finally:
|
||||
if not stream.is_exhausted:
|
||||
stream.close()
|
||||
```
|
||||
|
||||
Para streams assíncronos, use `await stream.aclose()`.
|
||||
|
||||
## Streaming de chunks legado
|
||||
|
||||
O streaming de Crew com `stream=True` ainda retorna a API orientada a chunks `CrewStreamingOutput` descrita em [Streaming da Execução de Crew](/pt-BR/learn/streaming-crew-execution). Chamadas diretas `llm.call(...)` ainda retornam o resultado final do LLM. O contrato de frames é destinado a runtimes que precisam de um envelope de evento estável em Flows, chamadas diretas de LLM, turnos conversacionais, ferramentas e mensagens.
|
||||
@@ -13,8 +13,7 @@ mode: "wide"
|
||||
|
||||
O FileReadTool representa conceitualmente um conjunto de funcionalidades dentro do pacote crewai_tools voltadas para facilitar a leitura e a recuperação de conteúdo de arquivos.
|
||||
Esse conjunto inclui ferramentas para processar arquivos de texto em lote, ler arquivos de configuração em tempo de execução e importar dados para análise.
|
||||
Ele suporta uma variedade de formatos de arquivo baseados em texto, como `.txt`, `.csv`, `.json` e outros. Dependendo do tipo de arquivo, o conjunto oferece funcionalidades especializadas,
|
||||
como converter conteúdo JSON em um dicionário Python para facilitar o uso.
|
||||
Ele suporta uma variedade de formatos de arquivo baseados em texto, como `.txt`, `.csv`, `.json` e outros. O conteúdo é sempre retornado como texto simples.
|
||||
|
||||
## Instalação
|
||||
|
||||
|
||||
@@ -32,7 +32,11 @@ from crewai_tools import FileWriterTool
|
||||
file_writer_tool = FileWriterTool()
|
||||
|
||||
# Escreva conteúdo em um arquivo em um diretório especificado
|
||||
result = file_writer_tool._run('example.txt', 'This is a test content.', 'test_directory')
|
||||
result = file_writer_tool.run(
|
||||
filename='example.txt',
|
||||
content='This is a test content.',
|
||||
directory='test_directory',
|
||||
)
|
||||
print(result)
|
||||
```
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 343 KiB After Width: | Height: | Size: 303 KiB |
|
Before Width: | Height: | Size: 327 KiB After Width: | Height: | Size: 365 KiB |
BIN
docs/images/enterprise/acp-policies-edit-cost-limit.png
Normal file
|
After Width: | Height: | Size: 168 KiB |
BIN
docs/images/enterprise/acp-policies-engaged-modal.png
Normal file
|
After Width: | Height: | Size: 221 KiB |
BIN
docs/images/enterprise/acp-policies-list.png
Normal file
|
After Width: | Height: | Size: 155 KiB |
BIN
docs/images/enterprise/acp-policies-new-side-panel.png
Normal file
|
After Width: | Height: | Size: 164 KiB |
BIN
docs/images/enterprise/studio-flows-agent-config.png
Normal file
|
After Width: | Height: | Size: 2.2 MiB |
BIN
docs/images/enterprise/studio-flows-agent-node.png
Normal file
|
After Width: | Height: | Size: 2.2 MiB |
BIN
docs/images/enterprise/studio-flows-crew-detail.png
Normal file
|
After Width: | Height: | Size: 2.2 MiB |
BIN
docs/images/enterprise/studio-flows-crew-node.png
Normal file
|
After Width: | Height: | Size: 2.2 MiB |
BIN
docs/images/enterprise/studio-flows-router-node.png
Normal file
|
After Width: | Height: | Size: 2.3 MiB |
BIN
docs/images/enterprise/studio-flows-selector.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
8
docs/v1.15.2/ar/api-reference/inputs.mdx
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
title: "GET /inputs"
|
||||
description: "الحصول على المدخلات المطلوبة لطاقمك"
|
||||
openapi: "/v1.15.2/enterprise-api.en.yaml GET /inputs"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
|
||||
135
docs/v1.15.2/ar/api-reference/introduction.mdx
Normal file
@@ -0,0 +1,135 @@
|
||||
---
|
||||
title: "مقدمة"
|
||||
description: "المرجع الكامل لواجهة برمجة تطبيقات CrewAI AMP REST"
|
||||
icon: "code"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
# واجهة برمجة تطبيقات CrewAI AMP
|
||||
|
||||
مرحبًا بك في مرجع واجهة برمجة تطبيقات CrewAI AMP. تتيح لك هذه الواجهة التفاعل برمجيًا مع الأطقم المنشورة، مما يمكّنك من دمجها مع تطبيقاتك وسير عملك وخدماتك.
|
||||
|
||||
## البدء السريع
|
||||
|
||||
<Steps>
|
||||
<Step title="الحصول على بيانات اعتماد API">
|
||||
انتقل إلى صفحة تفاصيل طاقمك في لوحة تحكم CrewAI AMP وانسخ رمز Bearer من علامة تبويب الحالة.
|
||||
</Step>
|
||||
|
||||
<Step title="اكتشاف المدخلات المطلوبة">
|
||||
استخدم نقطة النهاية `GET /inputs` لمعرفة المعاملات التي يتوقعها طاقمك.
|
||||
</Step>
|
||||
|
||||
<Step title="بدء تنفيذ الطاقم">
|
||||
استدعِ `POST /kickoff` مع مدخلاتك لبدء تنفيذ الطاقم واستلام
|
||||
`kickoff_id`.
|
||||
</Step>
|
||||
|
||||
<Step title="مراقبة التقدم">
|
||||
استخدم `GET /status/{kickoff_id}` للتحقق من حالة التنفيذ واسترجاع النتائج.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## المصادقة
|
||||
|
||||
تتطلب جميع طلبات API المصادقة باستخدام رمز Bearer. أدرج رمزك في ترويسة `Authorization`:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer YOUR_CREW_TOKEN" \
|
||||
https://your-crew-url.crewai.com/inputs
|
||||
```
|
||||
|
||||
### أنواع الرموز
|
||||
|
||||
| نوع الرمز | النطاق | حالة الاستخدام |
|
||||
| :-------------------- | :------------------------ | :----------------------------------------------------------- |
|
||||
| **Bearer Token** | وصول على مستوى المؤسسة | عمليات الطاقم الكاملة، مثالي للتكامل بين الخوادم |
|
||||
| **User Bearer Token** | وصول محدد بالمستخدم | صلاحيات محدودة، مناسب للعمليات الخاصة بالمستخدم |
|
||||
|
||||
<Tip>
|
||||
يمكنك العثور على كلا نوعي الرموز في علامة تبويب الحالة من صفحة تفاصيل طاقمك في
|
||||
لوحة تحكم CrewAI AMP.
|
||||
</Tip>
|
||||
|
||||
## عنوان URL الأساسي
|
||||
|
||||
لكل طاقم منشور نقطة نهاية API فريدة خاصة به:
|
||||
|
||||
```
|
||||
https://your-crew-name.crewai.com
|
||||
```
|
||||
|
||||
استبدل `your-crew-name` بعنوان URL الفعلي لطاقمك من لوحة التحكم.
|
||||
|
||||
## سير العمل النموذجي
|
||||
|
||||
1. **الاكتشاف**: استدعِ `GET /inputs` لفهم ما يحتاجه طاقمك
|
||||
2. **التنفيذ**: أرسل المدخلات عبر `POST /kickoff` لبدء المعالجة
|
||||
3. **المراقبة**: استعلم عن `GET /status/{kickoff_id}` حتى الاكتمال
|
||||
4. **النتائج**: استخرج المخرجات النهائية من الاستجابة المكتملة
|
||||
|
||||
## معالجة الأخطاء
|
||||
|
||||
تستخدم الواجهة أكواد حالة HTTP القياسية:
|
||||
|
||||
| الكود | المعنى |
|
||||
| ----- | :----------------------------------------- |
|
||||
| `200` | نجاح |
|
||||
| `400` | طلب غير صالح - تنسيق مدخلات غير صحيح |
|
||||
| `401` | غير مصرّح - رمز bearer غير صالح |
|
||||
| `404` | غير موجود - المورد غير موجود |
|
||||
| `422` | خطأ في التحقق - مدخلات مطلوبة مفقودة |
|
||||
| `500` | خطأ في الخادم - تواصل مع الدعم |
|
||||
|
||||
## الاختبار التفاعلي
|
||||
|
||||
<Info>
|
||||
**لماذا لا يوجد زر "إرسال"؟** نظرًا لأن كل مستخدم CrewAI AMP لديه عنوان URL
|
||||
فريد للطاقم، نستخدم **وضع المرجع** بدلاً من بيئة تفاعلية لتجنب
|
||||
الالتباس. يوضح لك هذا بالضبط كيف يجب أن تبدو الطلبات بدون
|
||||
أزرار إرسال غير فعالة.
|
||||
</Info>
|
||||
|
||||
تعرض لك كل صفحة نقطة نهاية:
|
||||
|
||||
- **تنسيق الطلب الدقيق** مع جميع المعاملات
|
||||
- **أمثلة الاستجابة** لحالات النجاح والخطأ
|
||||
- **عينات الكود** بلغات متعددة (cURL، Python، JavaScript، إلخ)
|
||||
- **أمثلة المصادقة** بتنسيق رمز Bearer الصحيح
|
||||
|
||||
### **لاختبار واجهتك الفعلية:**
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="نسخ أمثلة cURL" icon="terminal">
|
||||
انسخ أمثلة cURL واستبدل العنوان URL + الرمز بقيمك الحقيقية
|
||||
</Card>
|
||||
<Card title="استخدام Postman/Insomnia" icon="play">
|
||||
استورد الأمثلة في أداة اختبار API المفضلة لديك
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
**مثال على سير العمل:**
|
||||
|
||||
1. **انسخ مثال cURL هذا** من أي صفحة نقطة نهاية
|
||||
2. **استبدل `your-actual-crew-name.crewai.com`** بعنوان URL الحقيقي لطاقمك
|
||||
3. **استبدل رمز Bearer** برمزك الحقيقي من لوحة التحكم
|
||||
4. **نفّذ الطلب** في طرفيتك أو عميل API
|
||||
|
||||
## هل تحتاج مساعدة؟
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="دعم المؤسسات"
|
||||
icon="headset"
|
||||
href="mailto:support@crewai.com"
|
||||
>
|
||||
احصل على مساعدة في تكامل API واستكشاف الأخطاء وإصلاحها
|
||||
</Card>
|
||||
<Card
|
||||
title="لوحة تحكم المؤسسات"
|
||||
icon="chart-line"
|
||||
href="https://app.crewai.com"
|
||||
>
|
||||
إدارة أطقمك وعرض سجلات التنفيذ
|
||||
</Card>
|
||||
</CardGroup>
|
||||
8
docs/v1.15.2/ar/api-reference/kickoff.mdx
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
title: "POST /kickoff"
|
||||
description: "بدء تنفيذ الطاقم"
|
||||
openapi: "/v1.15.2/enterprise-api.en.yaml POST /kickoff"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
|
||||
6
docs/v1.15.2/ar/api-reference/resume.mdx
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: "POST /resume"
|
||||
description: "استئناف تنفيذ الطاقم مع التغذية الراجعة البشرية"
|
||||
openapi: "/v1.15.2/enterprise-api.en.yaml POST /resume"
|
||||
mode: "wide"
|
||||
---
|
||||
6
docs/v1.15.2/ar/api-reference/status.mdx
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: "GET /status/{kickoff_id}"
|
||||
description: "الحصول على حالة التنفيذ"
|
||||
openapi: "/v1.15.2/enterprise-api.en.yaml GET /status/{kickoff_id}"
|
||||
mode: "wide"
|
||||
---
|
||||
2035
docs/v1.15.2/ar/changelog.mdx
Normal file
147
docs/v1.15.2/ar/concepts/agent-capabilities.mdx
Normal file
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: "قدرات الوكيل"
|
||||
description: "فهم الطرق الخمس لتوسيع وكلاء CrewAI: الأدوات، MCP، التطبيقات، المهارات، والمعرفة."
|
||||
icon: puzzle-piece
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يمكن توسيع وكلاء CrewAI بـ **خمسة أنواع مميزة من القدرات**، كل منها يخدم غرضًا مختلفًا. فهم متى تستخدم كل نوع — وكيف يعملون معًا — هو المفتاح لبناء وكلاء فعّالين.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="الأدوات" icon="wrench" href="/ar/concepts/tools" color="#3B82F6">
|
||||
**دوال قابلة للاستدعاء** — تمنح الوكلاء القدرة على اتخاذ إجراءات. البحث على الويب، عمليات الملفات، استدعاءات API، تنفيذ الكود.
|
||||
</Card>
|
||||
<Card title="خوادم MCP" icon="plug" href="/ar/mcp/overview" color="#8B5CF6">
|
||||
**خوادم أدوات عن بُعد** — تربط الوكلاء بخوادم أدوات خارجية عبر Model Context Protocol. نفس تأثير الأدوات، لكن مستضافة خارجيًا.
|
||||
</Card>
|
||||
<Card title="التطبيقات" icon="grid-2" color="#EC4899">
|
||||
**تكاملات المنصة** — تربط الوكلاء بتطبيقات SaaS (Gmail، Slack، Jira، Salesforce) عبر منصة CrewAI. تعمل محليًا مع رمز تكامل المنصة.
|
||||
</Card>
|
||||
<Card title="المهارات" icon="bolt" href="/ar/concepts/skills" color="#F59E0B">
|
||||
**خبرة المجال** — تحقن التعليمات والإرشادات والمواد المرجعية في إرشادات الوكلاء. المهارات تخبر الوكلاء *كيف يفكرون*.
|
||||
</Card>
|
||||
<Card title="المعرفة" icon="book" href="/ar/concepts/knowledge" color="#10B981">
|
||||
**حقائق مُسترجعة** — توفر للوكلاء بيانات من المستندات والملفات وعناوين URL عبر البحث الدلالي (RAG). المعرفة تعطي الوكلاء *ما يحتاجون معرفته*.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
---
|
||||
|
||||
## التمييز الأساسي
|
||||
|
||||
أهم شيء يجب فهمه: **هذه القدرات تنقسم إلى فئتين**.
|
||||
|
||||
### قدرات الإجراء (الأدوات، MCP، التطبيقات)
|
||||
|
||||
تمنح الوكلاء القدرة على **فعل أشياء** — استدعاء APIs، قراءة الملفات، البحث على الويب، إرسال رسائل البريد الإلكتروني. عند التنفيذ، تتحول الأنواع الثلاثة إلى نفس التنسيق الداخلي (مثيلات `BaseTool`) وتظهر في قائمة أدوات موحدة يمكن للوكيل استدعاؤها.
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai_tools import SerperDevTool, FileReadTool
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Find and compile market data",
|
||||
backstory="Expert market analyst",
|
||||
tools=[SerperDevTool(), FileReadTool()], # أدوات محلية
|
||||
mcps=["https://mcp.example.com/sse"], # أدوات خادم MCP عن بُعد
|
||||
apps=["gmail", "google_sheets"], # تكاملات المنصة
|
||||
)
|
||||
```
|
||||
|
||||
### قدرات السياق (المهارات، المعرفة)
|
||||
|
||||
تُعدّل **إرشادات** الوكيل — بحقن الخبرة أو التعليمات أو البيانات المُسترجعة قبل أن يبدأ الوكيل في التفكير. لا تمنح الوكلاء إجراءات جديدة؛ بل تُشكّل كيف يفكر الوكلاء وما هي المعلومات التي يمكنهم الوصول إليها.
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
agent = Agent(
|
||||
role="Security Auditor",
|
||||
goal="Audit cloud infrastructure for vulnerabilities",
|
||||
backstory="Expert in cloud security with 10 years of experience",
|
||||
skills=["./skills/security-audit"], # تعليمات المجال
|
||||
knowledge_sources=[pdf_source, url_source], # حقائق مُسترجعة
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## متى تستخدم ماذا
|
||||
|
||||
| تحتاج إلى... | استخدم | مثال |
|
||||
| :------------------------------------------------------- | :---------------- | :--------------------------------------- |
|
||||
| الوكيل يبحث على الويب | **الأدوات** | `tools=[SerperDevTool()]` |
|
||||
| الوكيل يستدعي API عن بُعد عبر MCP | **MCP** | `mcps=["https://api.example.com/sse"]` |
|
||||
| الوكيل يرسل بريد إلكتروني عبر Gmail | **التطبيقات** | `apps=["gmail"]` |
|
||||
| الوكيل يتبع إجراءات محددة | **المهارات** | `skills=["./skills/code-review"]` |
|
||||
| الوكيل يرجع لمستندات الشركة | **المعرفة** | `knowledge_sources=[pdf_source]` |
|
||||
| الوكيل يبحث على الويب ويتبع إرشادات المراجعة | **الأدوات + المهارات** | استخدم كليهما معًا |
|
||||
|
||||
---
|
||||
|
||||
## دمج القدرات
|
||||
|
||||
في الممارسة العملية، غالبًا ما يستخدم الوكلاء **أنواعًا متعددة من القدرات معًا**. إليك مثال واقعي:
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai_tools import SerperDevTool, FileReadTool, CodeInterpreterTool
|
||||
|
||||
# وكيل بحث مجهز بالكامل
|
||||
researcher = Agent(
|
||||
role="Senior Research Analyst",
|
||||
goal="Produce comprehensive market analysis reports",
|
||||
backstory="Expert analyst with deep industry knowledge",
|
||||
|
||||
# الإجراء: ما يمكن للوكيل فعله
|
||||
tools=[
|
||||
SerperDevTool(), # البحث على الويب
|
||||
FileReadTool(), # قراءة الملفات المحلية
|
||||
CodeInterpreterTool(), # تشغيل كود Python للتحليل
|
||||
],
|
||||
mcps=["https://data-api.example.com/sse"], # الوصول لـ API بيانات عن بُعد
|
||||
apps=["google_sheets"], # الكتابة في Google Sheets
|
||||
|
||||
# السياق: ما يعرفه الوكيل
|
||||
skills=["./skills/research-methodology"], # كيفية إجراء البحث
|
||||
knowledge_sources=[company_docs], # بيانات خاصة بالشركة
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## جدول المقارنة
|
||||
|
||||
| الميزة | الأدوات | MCP | التطبيقات | المهارات | المعرفة |
|
||||
| :--- | :---: | :---: | :---: | :---: | :---: |
|
||||
| **يمنح الوكيل إجراءات** | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| **يُعدّل الإرشادات** | ❌ | ❌ | ❌ | ✅ | ✅ |
|
||||
| **يتطلب كود** | نعم | إعداد فقط | إعداد فقط | Markdown فقط | إعداد فقط |
|
||||
| **يعمل محليًا** | نعم | يعتمد | نعم (مع متغير بيئة) | غير متاح | نعم |
|
||||
| **يحتاج مفاتيح API** | لكل أداة | لكل خادم | رمز التكامل | لا | المُضمّن فقط |
|
||||
| **يُعيَّن على Agent** | `tools=[]` | `mcps=[]` | `apps=[]` | `skills=[]` | `knowledge_sources=[]` |
|
||||
| **يُعيَّن على Crew** | ❌ | ❌ | ❌ | `skills=[]` | `knowledge_sources=[]` |
|
||||
|
||||
---
|
||||
|
||||
## تعمّق أكثر
|
||||
|
||||
هل أنت مستعد لمعرفة المزيد عن كل نوع من أنواع القدرات؟
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="الأدوات" icon="wrench" href="/ar/concepts/tools">
|
||||
إنشاء أدوات مخصصة، استخدام كتالوج OSS مع أكثر من 75 خيارًا، تكوين التخزين المؤقت والتنفيذ غير المتزامن.
|
||||
</Card>
|
||||
<Card title="تكامل MCP" icon="plug" href="/ar/mcp/overview">
|
||||
الاتصال بخوادم MCP عبر stdio أو SSE أو HTTP. تصفية الأدوات، تكوين المصادقة.
|
||||
</Card>
|
||||
<Card title="المهارات" icon="bolt" href="/ar/concepts/skills">
|
||||
بناء حزم المهارات مع SKILL.md، حقن خبرة المجال، استخدام الكشف التدريجي.
|
||||
</Card>
|
||||
<Card title="المعرفة" icon="book" href="/ar/concepts/knowledge">
|
||||
إضافة المعرفة من ملفات PDF وCSV وعناوين URL والمزيد. تكوين المُضمّنات والاسترجاع.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
383
docs/v1.15.2/ar/concepts/agents.mdx
Normal file
@@ -0,0 +1,383 @@
|
||||
---
|
||||
title: الوكلاء
|
||||
description: دليل تفصيلي حول إنشاء وإدارة الوكلاء ضمن إطار عمل CrewAI.
|
||||
icon: robot
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة على الوكيل
|
||||
|
||||
في إطار عمل CrewAI، الـ `Agent` هو وحدة مستقلة يمكنها:
|
||||
|
||||
- أداء مهام محددة
|
||||
- اتخاذ قرارات بناءً على دوره وهدفه
|
||||
- استخدام الأدوات لتحقيق الأهداف
|
||||
- التواصل والتعاون مع وكلاء آخرين
|
||||
- الاحتفاظ بذاكرة التفاعلات
|
||||
- تفويض المهام عند السماح بذلك
|
||||
|
||||
<Tip>
|
||||
فكّر في الوكيل كعضو فريق متخصص بمهارات وخبرات ومسؤوليات محددة.
|
||||
على سبيل المثال، قد يتفوق وكيل `Researcher` في جمع وتحليل المعلومات،
|
||||
بينما قد يكون وكيل `Writer` أفضل في إنشاء المحتوى.
|
||||
</Tip>
|
||||
|
||||
<Note type="info" title="تحسين المؤسسات: منشئ الوكلاء المرئي">
|
||||
يتضمن CrewAI AMP منشئ وكلاء مرئي يبسّط إنشاء وتهيئة الوكلاء بدون كتابة كود. صمم وكلاءك بصريًا واختبرهم في الوقت الفعلي.
|
||||
|
||||

|
||||
|
||||
يُمكّن منشئ الوكلاء المرئي من:
|
||||
|
||||
- تهيئة وكلاء بديهية بواجهات نماذج
|
||||
- اختبار والتحقق في الوقت الفعلي
|
||||
- مكتبة قوالب مع أنواع وكلاء مهيأة مسبقًا
|
||||
- تخصيص سهل لخصائص وسلوكيات الوكيل
|
||||
</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` المختار يدعم الميزات التي تحتاجها
|
||||
423
docs/v1.15.2/ar/concepts/checkpointing.mdx
Normal file
@@ -0,0 +1,423 @@
|
||||
---
|
||||
title: Checkpointing
|
||||
description: حفظ حالة التنفيذ تلقائيا حتى تتمكن الطواقم والتدفقات والوكلاء من الاستئناف بعد الفشل.
|
||||
icon: floppy-disk
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
الـ Checkpointing يحفظ لقطة من حالة التنفيذ أثناء التشغيل بحيث يمكن لطاقم أو تدفق أو وكيل الاستئناف بعد الفشل أو التفرع إلى فرع بديل.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="الشرح" icon="lightbulb" href="#الشرح">
|
||||
كيف يعمل الـ Checkpointing: الأحداث والتخزين والوراثة.
|
||||
</Card>
|
||||
<Card title="درس تطبيقي" icon="graduation-cap" href="#درس-تطبيقي-استئناف-طاقم-فاشل">
|
||||
دليل 5 دقائق: تشغيل، إيقاف، استئناف.
|
||||
</Card>
|
||||
<Card title="ادلة عملية" icon="screwdriver-wrench" href="#ادلة-عملية">
|
||||
وصفات مركزة على المهام لسير العمل الشائع.
|
||||
</Card>
|
||||
<Card title="المرجع" icon="book" href="#المرجع">
|
||||
`CheckpointConfig` والأحداث والمزودات وسطر الأوامر.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## الشرح
|
||||
|
||||
### ما هي نقطة الحفظ
|
||||
|
||||
تلتقط نقطة الحفظ كل ما يحتاجه CrewAI لإعادة إنشاء تشغيل أثناء سيره: الحالة الكاملة للطاقم أو التدفق أو الوكيل — التكوين، وذاكرة الوكلاء ومصادر المعرفة، وتقدم المهام، والمخرجات الوسيطة، والحالة الداخلية والسمات — إلى جانب مدخلات الـ kickoff، وسجل الأحداث حتى تلك النقطة، ومعرف نسب يربط نقطة الحفظ بالتشغيل الذي جاءت منه.
|
||||
|
||||
الاستعادة تعيد بناء تلك الحالة وتستمر. تتخطى المهام المكتملة، وتعاد ترطيب الذاكرة والمعرفة، ويعمل العمل التابع على نفس المخرجات التي أنتجها التشغيل الأصلي. التفرع يجري نفس الاستعادة تحت نسب جديد، بحيث يكتب الفرع الجديد والتشغيل الأصلي نقاط الحفظ جنبا إلى جنب دون أن يطمس أحدهما الآخر.
|
||||
|
||||
### متى تكتب نقاط الحفظ
|
||||
|
||||
الـ Checkpointing مدفوع بالأحداث. يشترك وقت التشغيل في الأحداث التي تحددها عبر `on_events` ويكتب نقطة حفظ عند إطلاق أحدها. الافتراضي `task_completed` ينتج نقطة حفظ لكل مهمة منتهية — توازن معقول بين الدقة واستخدام القرص. الأحداث عالية التردد مثل `llm_call_completed` متاحة للاستعادة الدقيقة لكنها تكتب ملفات أكثر بكثير.
|
||||
|
||||
### التخزين
|
||||
|
||||
يتضمن CrewAI مزودين:
|
||||
|
||||
- `JsonProvider` يكتب ملفا لكل نقطة حفظ. قابل للقراءة وسهل التفقد.
|
||||
- `SqliteProvider` يكتب إلى قاعدة بيانات SQLite واحدة. أفضل لنقاط الحفظ عالية التردد.
|
||||
|
||||
كلاهما يحذف أقدم نقاط الحفظ عند تحديد `max_checkpoints`.
|
||||
|
||||
<Note>
|
||||
كتابة نقاط الحفظ بأفضل جهد. فشل نقطة حفظ يسجل لكنه لا يقاطع التشغيل.
|
||||
</Note>
|
||||
|
||||
### نموذج الوراثة
|
||||
|
||||
`Crew` و`Flow` و`Agent` كلها تقبل وسيط `checkpoint`. يرث الأبناء من الأب ما لم يحددوا قيمتهم الخاصة أو يمرروا `False` للانسحاب. فعل الـ Checkpointing مرة واحدة على الطاقم وتشارك كل الوكلاء، أو استبعد وكيلا واحدا بشكل انتقائي.
|
||||
|
||||
## درس تطبيقي: استئناف طاقم فاشل
|
||||
|
||||
هذا الدليل يستغرق حوالي 5 دقائق. ستشغل طاقما بمهمتين، توقفه في المنتصف، ثم تستأنف من نقطة الحفظ المحفوظة.
|
||||
|
||||
<Steps>
|
||||
<Step title="أنشئ الطاقم مع تفعيل الـ Checkpointing">
|
||||
```python
|
||||
from crewai import Agent, Crew, Task
|
||||
|
||||
researcher = Agent(role="Researcher", goal="Research", backstory="Expert")
|
||||
writer = Agent(role="Writer", goal="Write", backstory="Expert")
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[
|
||||
Task(description="Research AI trends", agent=researcher, expected_output="bullets"),
|
||||
Task(description="Write a summary", agent=writer, expected_output="paragraph"),
|
||||
],
|
||||
checkpoint=True,
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
<Step title="شغله وأوقفه بعد المهمة الأولى">
|
||||
```python
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
اضغط `Ctrl+C` بعد انتهاء المهمة الأولى. في `./.checkpoints/`، الملف بصيغة `<timestamp>_<uuid>.json` هو نقطة الحفظ.
|
||||
</Step>
|
||||
<Step title="استأنف من نقطة الحفظ">
|
||||
```python
|
||||
from crewai import CheckpointConfig
|
||||
|
||||
result = crew.kickoff(
|
||||
from_checkpoint=CheckpointConfig(
|
||||
restore_from="./.checkpoints/<timestamp>_<uuid>.json",
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
يتم تخطي مهمة البحث، ويعمل الكاتب على مخرجات البحث المحفوظة، وينتهي الطاقم.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## ادلة عملية
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="تفعيل الـ Checkpointing بالإعدادات الافتراضية" icon="play">
|
||||
```python
|
||||
crew = Crew(agents=[...], tasks=[...], checkpoint=True)
|
||||
```
|
||||
|
||||
يكتب إلى `./.checkpoints/` عند كل `task_completed`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="تخصيص التخزين والتردد" icon="sliders">
|
||||
```python
|
||||
from crewai import Crew, CheckpointConfig
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
checkpoint=CheckpointConfig(
|
||||
location="./my_checkpoints",
|
||||
on_events=["task_completed", "crew_kickoff_completed"],
|
||||
max_checkpoints=5,
|
||||
),
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="اختيار مزود التخزين" icon="database">
|
||||
<CodeGroup>
|
||||
```python JsonProvider
|
||||
from crewai import Crew, CheckpointConfig
|
||||
from crewai.state import JsonProvider
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
checkpoint=CheckpointConfig(
|
||||
location="./my_checkpoints",
|
||||
provider=JsonProvider(),
|
||||
max_checkpoints=5,
|
||||
),
|
||||
)
|
||||
```
|
||||
```python SqliteProvider
|
||||
from crewai import Crew, CheckpointConfig
|
||||
from crewai.state import SqliteProvider
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
checkpoint=CheckpointConfig(
|
||||
location="./.checkpoints.db",
|
||||
provider=SqliteProvider(),
|
||||
max_checkpoints=50,
|
||||
),
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Tip>
|
||||
SQLite يفعل وضع journal WAL للقراءات المتزامنة. يفضل لنقاط الحفظ عالية التردد.
|
||||
</Tip>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="استبعاد وكيل واحد" icon="user-slash">
|
||||
```python
|
||||
crew = Crew(
|
||||
agents=[
|
||||
Agent(role="Researcher", ...),
|
||||
Agent(role="Writer", ..., checkpoint=False),
|
||||
],
|
||||
tasks=[...],
|
||||
checkpoint=True,
|
||||
)
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="التفرع إلى فرع جديد" icon="code-branch">
|
||||
`fork()` يستعيد نقطة حفظ تحت نسب جديد بحيث لا يتصادم التشغيل الجديد مع الأصلي.
|
||||
|
||||
```python
|
||||
config = CheckpointConfig(restore_from="./my_checkpoints/<file>.json")
|
||||
crew = Crew.fork(config, branch="experiment-a")
|
||||
result = crew.kickoff(inputs={"strategy": "aggressive"})
|
||||
```
|
||||
|
||||
تسمية `branch` اختيارية؛ يتم إنشاء واحدة إذا أغفلت.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Checkpointing لـ Crew أو Flow أو Agent" icon="cubes">
|
||||
<Tabs>
|
||||
<Tab title="Crew">
|
||||
```python
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, write_task, review_task],
|
||||
checkpoint=CheckpointConfig(location="./crew_cp"),
|
||||
)
|
||||
```
|
||||
|
||||
المشغل الافتراضي: `task_completed`.
|
||||
</Tab>
|
||||
<Tab title="Flow">
|
||||
```python
|
||||
from crewai.flow.flow import Flow, start, listen
|
||||
from crewai import CheckpointConfig
|
||||
|
||||
class MyFlow(Flow):
|
||||
@start()
|
||||
def step_one(self):
|
||||
return "data"
|
||||
|
||||
@listen(step_one)
|
||||
def step_two(self, data):
|
||||
return process(data)
|
||||
|
||||
flow = MyFlow(
|
||||
checkpoint=CheckpointConfig(
|
||||
location="./flow_cp",
|
||||
on_events=["method_execution_finished"],
|
||||
),
|
||||
)
|
||||
result = flow.kickoff()
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Agent">
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Research topics",
|
||||
backstory="Expert researcher",
|
||||
checkpoint=CheckpointConfig(
|
||||
location="./agent_cp",
|
||||
on_events=["lite_agent_execution_completed"],
|
||||
),
|
||||
)
|
||||
result = agent.kickoff(messages=[{"role": "user", "content": "Research AI trends"}])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="كتابة نقطة حفظ يدويا" icon="code">
|
||||
سجل معالجا على أي حدث واستدع `state.checkpoint()`.
|
||||
|
||||
<CodeGroup>
|
||||
```python Sync
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from crewai.events.event_bus import crewai_event_bus
|
||||
from crewai.events.types.llm_events import LLMCallCompletedEvent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crewai.state.runtime import RuntimeState
|
||||
|
||||
|
||||
@crewai_event_bus.on(LLMCallCompletedEvent)
|
||||
def on_llm_done(source: Any, event: LLMCallCompletedEvent, state: RuntimeState) -> None:
|
||||
path = state.checkpoint("./my_checkpoints")
|
||||
print(f"تم حفظ نقطة الحفظ: {path}")
|
||||
```
|
||||
```python Async
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from crewai.events.event_bus import crewai_event_bus
|
||||
from crewai.events.types.llm_events import LLMCallCompletedEvent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crewai.state.runtime import RuntimeState
|
||||
|
||||
|
||||
@crewai_event_bus.on(LLMCallCompletedEvent)
|
||||
async def on_llm_done_async(source: Any, event: LLMCallCompletedEvent, state: RuntimeState) -> None:
|
||||
path = await state.acheckpoint("./my_checkpoints")
|
||||
print(f"تم حفظ نقطة الحفظ: {path}")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
يتم تمرير وسيط `state` تلقائيا عندما يقبل المعالج ثلاثة معاملات. راجع [Event Listeners](/ar/concepts/event-listener) لقائمة الأحداث الكاملة.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="التصفح والاستئناف والتفرع من سطر الأوامر" icon="terminal">
|
||||
```bash
|
||||
crewai checkpoint
|
||||
crewai checkpoint --location ./my_checkpoints
|
||||
crewai checkpoint --location ./.checkpoints.db
|
||||
```
|
||||
|
||||
<Frame caption="شجرة نقاط الحفظ — الفروع والتفرعات تتداخل تحت أبيها.">
|
||||
<img src="/images/checkpoint-tui-tree.png" alt="Checkpoint TUI tree view" />
|
||||
</Frame>
|
||||
|
||||
اللوحة اليسرى تجمع نقاط الحفظ حسب الفرع؛ التفرعات تتداخل تحت أبيها. اختيار نقطة حفظ يفتح لوحة التفاصيل مع بياناتها الوصفية وحالة الكيان وتقدم المهام. **Resume** يكمل التشغيل؛ **Fork** يبدأ فرعا جديدا.
|
||||
|
||||
<Frame caption="تبويب النظرة العامة — البيانات الوصفية وحالة الكيان وملخص التشغيل.">
|
||||
<img src="/images/checkpoint-tui-detail-overview.png" alt="Checkpoint detail overview tab" />
|
||||
</Frame>
|
||||
|
||||
لوحة التفاصيل تعرض منطقتين قابلتين للتحرير:
|
||||
|
||||
- **Inputs** — مدخلات الـ kickoff الأصلية، معبأة مسبقا وقابلة للتحرير.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/checkpoint-tui-detail-inputs.png" alt="Editable kickoff inputs" />
|
||||
</Frame>
|
||||
|
||||
- **مخرجات المهام** — مخرجات المهام المكتملة. تحرير مخرج والضغط على **Fork** يبطل المهام التابعة لتعاد بالسياق المعدل.
|
||||
|
||||
<Frame>
|
||||
<img src="/images/checkpoint-tui-detail-tasks.png" alt="Editable task outputs" />
|
||||
</Frame>
|
||||
|
||||
<Frame caption="عرض التفرع — تأكيد فرع جديد من نقطة الحفظ المختارة.">
|
||||
<img src="/images/checkpoint-tui-details-fork.png" alt="Fork confirmation panel" />
|
||||
</Frame>
|
||||
|
||||
<Tip>
|
||||
مفيد لاستكشاف "ماذا لو": تفرع، عدل، راقب.
|
||||
</Tip>
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="تفقد نقاط الحفظ بدون TUI" icon="magnifying-glass">
|
||||
```bash
|
||||
crewai checkpoint list ./my_checkpoints
|
||||
crewai checkpoint info ./my_checkpoints/<file>.json
|
||||
crewai checkpoint info ./.checkpoints.db
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## المرجع
|
||||
|
||||
### `CheckpointConfig`
|
||||
|
||||
<ParamField path="location" type="str" default='"./.checkpoints"'>
|
||||
وجهة التخزين. مجلد لـ `JsonProvider`، مسار ملف قاعدة بيانات لـ `SqliteProvider`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="on_events" type='list[CheckpointEventType | Literal["*"]]' default='["task_completed"]'>
|
||||
أنواع الأحداث التي تطلق نقطة حفظ. `CheckpointEventType` هو `Literal` — مدقق الأنواع يكمل تلقائيا ويرفض القيم غير المدعومة. راجع [أنواع الأحداث](#أنواع-الأحداث) للقائمة الكاملة.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="provider" type="BaseProvider" default="JsonProvider()">
|
||||
واجهة التخزين. `JsonProvider` أو `SqliteProvider`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="max_checkpoints" type="int | None" default="None">
|
||||
الحد الاقصى لنقاط الحفظ المحتفظ بها. الأقدم تحذف بعد كل كتابة.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="restore_from" type="Path | str | None" default="None">
|
||||
نقطة الحفظ المراد استعادتها عند تمريرها عبر `from_checkpoint`.
|
||||
</ParamField>
|
||||
|
||||
### قيم حقل `checkpoint`
|
||||
|
||||
مقبولة في `Crew` و`Flow` و`Agent`.
|
||||
|
||||
<ParamField path="None" type="افتراضي">
|
||||
يرث من الأب.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="True" type="bool">
|
||||
تفعيل بالإعدادات الافتراضية.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="False" type="bool">
|
||||
انسحاب صريح. يوقف الوراثة.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="CheckpointConfig(...)" type="CheckpointConfig">
|
||||
إعدادات مخصصة.
|
||||
</ParamField>
|
||||
|
||||
### أنواع الأحداث
|
||||
|
||||
يقبل `on_events` أي مجموعة من قيم `CheckpointEventType`. الافتراضي `["task_completed"]` يكتب نقطة حفظ لكل مهمة منتهية، و`["*"]` يطابق جميع الأحداث.
|
||||
|
||||
<Warning>
|
||||
`["*"]` والأحداث عالية التردد مثل `llm_call_completed` تكتب نقاط حفظ كثيرة وقد تضر بالاداء. استخدمها مع `max_checkpoints`.
|
||||
</Warning>
|
||||
|
||||
<Expandable title="جميع الأحداث المدعومة">
|
||||
|
||||
- **Task** — `task_started`, `task_completed`, `task_failed`, `task_evaluation`
|
||||
- **Crew** — `crew_kickoff_started`, `crew_kickoff_completed`, `crew_kickoff_failed`, `crew_train_started`, `crew_train_completed`, `crew_train_failed`, `crew_test_started`, `crew_test_completed`, `crew_test_failed`, `crew_test_result`
|
||||
- **Agent** — `agent_execution_started`, `agent_execution_completed`, `agent_execution_error`, `lite_agent_execution_started`, `lite_agent_execution_completed`, `lite_agent_execution_error`, `agent_evaluation_started`, `agent_evaluation_completed`, `agent_evaluation_failed`
|
||||
- **Flow** — `flow_created`, `flow_started`, `flow_finished`, `flow_paused`, `method_execution_started`, `method_execution_finished`, `method_execution_failed`, `method_execution_paused`, `human_feedback_requested`, `human_feedback_received`, `flow_input_requested`, `flow_input_received`
|
||||
- **LLM** — `llm_call_started`, `llm_call_completed`, `llm_call_failed`, `llm_stream_chunk`, `llm_thinking_chunk`
|
||||
- **LLM Guardrail** — `llm_guardrail_started`, `llm_guardrail_completed`, `llm_guardrail_failed`
|
||||
- **Tool** — `tool_usage_started`, `tool_usage_finished`, `tool_usage_error`, `tool_validate_input_error`, `tool_selection_error`, `tool_execution_error`
|
||||
- **Memory** — `memory_save_started`, `memory_save_completed`, `memory_save_failed`, `memory_query_started`, `memory_query_completed`, `memory_query_failed`, `memory_retrieval_started`, `memory_retrieval_completed`, `memory_retrieval_failed`
|
||||
- **Knowledge** — `knowledge_search_query_started`, `knowledge_search_query_completed`, `knowledge_query_started`, `knowledge_query_completed`, `knowledge_query_failed`, `knowledge_search_query_failed`
|
||||
- **Reasoning** — `agent_reasoning_started`, `agent_reasoning_completed`, `agent_reasoning_failed`
|
||||
- **MCP** — `mcp_connection_started`, `mcp_connection_completed`, `mcp_connection_failed`, `mcp_tool_execution_started`, `mcp_tool_execution_completed`, `mcp_tool_execution_failed`, `mcp_config_fetch_failed`
|
||||
- **Observation** — `step_observation_started`, `step_observation_completed`, `step_observation_failed`, `plan_refinement`, `plan_replan_triggered`, `goal_achieved_early`
|
||||
- **Skill** — `skill_discovery_started`, `skill_discovery_completed`, `skill_loaded`, `skill_activated`, `skill_load_failed`
|
||||
- **Logging** — `agent_logs_started`, `agent_logs_execution`
|
||||
- **A2A** — `a2a_delegation_started`, `a2a_delegation_completed`, `a2a_conversation_started`, `a2a_conversation_completed`, `a2a_message_sent`, `a2a_response_received`, `a2a_polling_started`, `a2a_polling_status`, `a2a_push_notification_registered`, `a2a_push_notification_received`, `a2a_push_notification_sent`, `a2a_push_notification_timeout`, `a2a_streaming_started`, `a2a_streaming_chunk`, `a2a_agent_card_fetched`, `a2a_authentication_failed`, `a2a_artifact_received`, `a2a_connection_error`, `a2a_server_task_started`, `a2a_server_task_completed`, `a2a_server_task_canceled`, `a2a_server_task_failed`, `a2a_parallel_delegation_started`, `a2a_parallel_delegation_completed`, `a2a_transport_negotiated`, `a2a_content_type_negotiated`, `a2a_context_created`, `a2a_context_expired`, `a2a_context_idle`, `a2a_context_completed`, `a2a_context_pruned`
|
||||
- **إشارات النظام** — `SIGTERM`, `SIGINT`, `SIGHUP`, `SIGTSTP`, `SIGCONT`
|
||||
- **حرف بدل** — `"*"` يطابق جميع الأحداث.
|
||||
|
||||
</Expandable>
|
||||
|
||||
### مزودات التخزين
|
||||
|
||||
<ParamField path="JsonProvider" type="provider">
|
||||
ملف واحد لكل نقطة حفظ بصيغة `<timestamp>_<uuid>.json` داخل `location`.
|
||||
</ParamField>
|
||||
|
||||
<ParamField path="SqliteProvider" type="provider">
|
||||
ملف قاعدة بيانات واحد في `location` مع journaling WAL.
|
||||
</ParamField>
|
||||
|
||||
### سطر الأوامر
|
||||
|
||||
| الامر | الغرض |
|
||||
|:------|:------|
|
||||
| `crewai checkpoint` | تشغيل TUI؛ كشف التخزين تلقائيا. |
|
||||
| `crewai checkpoint --location <path>` | تشغيل TUI على موقع محدد. |
|
||||
| `crewai checkpoint list <path>` | سرد نقاط الحفظ. |
|
||||
| `crewai checkpoint info <path>` | تفقد ملف نقطة حفظ أو آخر مدخل في قاعدة بيانات SQLite. |
|
||||
302
docs/v1.15.2/ar/concepts/cli.mdx
Normal 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>
|
||||
363
docs/v1.15.2/ar/concepts/collaboration.mdx
Normal file
@@ -0,0 +1,363 @@
|
||||
---
|
||||
title: التعاون
|
||||
description: كيفية تمكين الوكلاء من العمل معًا وتفويض المهام والتواصل بفعالية داخل فرق CrewAI.
|
||||
icon: screen-users
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يُمكّن التعاون في CrewAI الوكلاء من العمل معًا كفريق عن طريق تفويض المهام وطرح الأسئلة للاستفادة من خبرات بعضهم البعض. عندما يكون `allow_delegation=True`، يحصل الوكلاء تلقائيًا على أدوات تعاون قوية.
|
||||
|
||||
## البدء السريع: تفعيل التعاون
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task
|
||||
|
||||
# تفعيل التعاون للوكلاء
|
||||
researcher = Agent(
|
||||
role="Research Specialist",
|
||||
goal="Conduct thorough research on any topic",
|
||||
backstory="Expert researcher with access to various sources",
|
||||
allow_delegation=True, # الإعداد الرئيسي للتعاون
|
||||
verbose=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role="Content Writer",
|
||||
goal="Create engaging content based on research",
|
||||
backstory="Skilled writer who transforms research into compelling content",
|
||||
allow_delegation=True, # يُمكّن طرح الأسئلة على الوكلاء الآخرين
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# يمكن للوكلاء الآن التعاون تلقائيًا
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[...],
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## كيف يعمل تعاون الوكلاء
|
||||
|
||||
عندما يكون `allow_delegation=True`، يوفر CrewAI تلقائيًا للوكلاء أداتين قويتين:
|
||||
|
||||
### 1. **أداة تفويض العمل**
|
||||
تسمح للوكلاء بتعيين مهام لزملاء الفريق ذوي الخبرة المحددة.
|
||||
|
||||
```python
|
||||
# يحصل الوكيل تلقائيًا على هذه الأداة:
|
||||
# Delegate work to coworker(task: str, context: str, coworker: str)
|
||||
```
|
||||
|
||||
### 2. **أداة طرح الأسئلة**
|
||||
تُمكّن الوكلاء من طرح أسئلة محددة لجمع المعلومات من الزملاء.
|
||||
|
||||
```python
|
||||
# يحصل الوكيل تلقائيًا على هذه الأداة:
|
||||
# Ask question to coworker(question: str, context: str, coworker: str)
|
||||
```
|
||||
|
||||
## التعاون في الممارسة
|
||||
|
||||
إليك مثالًا كاملًا يوضح تعاون الوكلاء في مهمة إنشاء المحتوى:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task, Process
|
||||
|
||||
# إنشاء وكلاء تعاونيين
|
||||
researcher = Agent(
|
||||
role="Research Specialist",
|
||||
goal="Find accurate, up-to-date information on any topic",
|
||||
backstory="""You're a meticulous researcher with expertise in finding
|
||||
reliable sources and fact-checking information across various domains.""",
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role="Content Writer",
|
||||
goal="Create engaging, well-structured content",
|
||||
backstory="""You're a skilled content writer who excels at transforming
|
||||
research into compelling, readable content for different audiences.""",
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
editor = Agent(
|
||||
role="Content Editor",
|
||||
goal="Ensure content quality and consistency",
|
||||
backstory="""You're an experienced editor with an eye for detail,
|
||||
ensuring content meets high standards for clarity and accuracy.""",
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# إنشاء مهمة تشجع التعاون
|
||||
article_task = Task(
|
||||
description="""Write a comprehensive 1000-word article about 'The Future of AI in Healthcare'.
|
||||
|
||||
The article should include:
|
||||
- Current AI applications in healthcare
|
||||
- Emerging trends and technologies
|
||||
- Potential challenges and ethical considerations
|
||||
- Expert predictions for the next 5 years
|
||||
|
||||
Collaborate with your teammates to ensure accuracy and quality.""",
|
||||
expected_output="A well-researched, engaging 1000-word article with proper structure and citations",
|
||||
agent=writer # الكاتب يقود، لكن يمكنه تفويض البحث إلى الباحث
|
||||
)
|
||||
|
||||
# إنشاء طاقم تعاوني
|
||||
crew = Crew(
|
||||
agents=[researcher, writer, editor],
|
||||
tasks=[article_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## أنماط التعاون
|
||||
|
||||
### النمط 1: بحث ← كتابة ← تحرير
|
||||
```python
|
||||
research_task = Task(
|
||||
description="Research the latest developments in quantum computing",
|
||||
expected_output="Comprehensive research summary with key findings and sources",
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
writing_task = Task(
|
||||
description="Write an article based on the research findings",
|
||||
expected_output="Engaging 800-word article about quantum computing",
|
||||
agent=writer,
|
||||
context=[research_task] # يحصل على مخرجات البحث كسياق
|
||||
)
|
||||
|
||||
editing_task = Task(
|
||||
description="Edit and polish the article for publication",
|
||||
expected_output="Publication-ready article with improved clarity and flow",
|
||||
agent=editor,
|
||||
context=[writing_task] # يحصل على مسودة المقال كسياق
|
||||
)
|
||||
```
|
||||
|
||||
### النمط 2: مهمة واحدة تعاونية
|
||||
```python
|
||||
collaborative_task = Task(
|
||||
description="""Create a marketing strategy for a new AI product.
|
||||
|
||||
Writer: Focus on messaging and content strategy
|
||||
Researcher: Provide market analysis and competitor insights
|
||||
|
||||
Work together to create a comprehensive strategy.""",
|
||||
expected_output="Complete marketing strategy with research backing",
|
||||
agent=writer # الوكيل القائد، لكن يمكنه التفويض إلى الباحث
|
||||
)
|
||||
```
|
||||
|
||||
## التعاون الهرمي
|
||||
|
||||
للمشاريع المعقدة، استخدم عملية هرمية مع وكيل مدير:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task, Process
|
||||
|
||||
# وكيل المدير ينسق الفريق
|
||||
manager = Agent(
|
||||
role="Project Manager",
|
||||
goal="Coordinate team efforts and ensure project success",
|
||||
backstory="Experienced project manager skilled at delegation and quality control",
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# وكلاء متخصصون
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Provide accurate research and analysis",
|
||||
backstory="Expert researcher with deep analytical skills",
|
||||
allow_delegation=False, # المتخصصون يركزون على خبرتهم
|
||||
verbose=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role="Writer",
|
||||
goal="Create compelling content",
|
||||
backstory="Skilled writer who creates engaging content",
|
||||
allow_delegation=False,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# مهمة يقودها المدير
|
||||
project_task = Task(
|
||||
description="Create a comprehensive market analysis report with recommendations",
|
||||
expected_output="Executive summary, detailed analysis, and strategic recommendations",
|
||||
agent=manager # المدير سيفوّض إلى المتخصصين
|
||||
)
|
||||
|
||||
# طاقم هرمي
|
||||
crew = Crew(
|
||||
agents=[manager, researcher, writer],
|
||||
tasks=[project_task],
|
||||
process=Process.hierarchical, # المدير ينسق كل شيء
|
||||
manager_llm="gpt-4o", # تحديد LLM للمدير
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## أفضل ممارسات التعاون
|
||||
|
||||
### 1. **تحديد الأدوار بوضوح**
|
||||
```python
|
||||
# جيد: أدوار محددة ومتكاملة
|
||||
researcher = Agent(role="Market Research Analyst", ...)
|
||||
writer = Agent(role="Technical Content Writer", ...)
|
||||
|
||||
# تجنب: أدوار متداخلة أو غامضة
|
||||
agent1 = Agent(role="General Assistant", ...)
|
||||
agent2 = Agent(role="Helper", ...)
|
||||
```
|
||||
|
||||
### 2. **تفعيل التفويض الاستراتيجي**
|
||||
```python
|
||||
# فعّل التفويض للمنسقين والعامين
|
||||
lead_agent = Agent(
|
||||
role="Content Lead",
|
||||
allow_delegation=True, # يمكنه التفويض إلى المتخصصين
|
||||
...
|
||||
)
|
||||
|
||||
# عطّل للمتخصصين المركّزين (اختياري)
|
||||
specialist_agent = Agent(
|
||||
role="Data Analyst",
|
||||
allow_delegation=False, # يركز على الخبرة الأساسية
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### 3. **مشاركة السياق**
|
||||
```python
|
||||
# استخدم معامل context لاعتماديات المهام
|
||||
writing_task = Task(
|
||||
description="Write article based on research",
|
||||
agent=writer,
|
||||
context=[research_task], # يشارك نتائج البحث
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### 4. **أوصاف المهام الواضحة**
|
||||
```python
|
||||
# أوصاف محددة وقابلة للتنفيذ
|
||||
Task(
|
||||
description="""Research competitors in the AI chatbot space.
|
||||
Focus on: pricing models, key features, target markets.
|
||||
Provide data in a structured format.""",
|
||||
...
|
||||
)
|
||||
|
||||
# تجنب: أوصاف غامضة لا توجه التعاون
|
||||
Task(description="Do some research about chatbots", ...)
|
||||
```
|
||||
|
||||
## استكشاف أخطاء التعاون وإصلاحها
|
||||
|
||||
### المشكلة: الوكلاء لا يتعاونون
|
||||
**الأعراض:** يعمل الوكلاء بمعزل، لا يحدث تفويض
|
||||
```python
|
||||
# الحل: تأكد من تفعيل التفويض
|
||||
agent = Agent(
|
||||
role="...",
|
||||
allow_delegation=True, # هذا مطلوب!
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### المشكلة: كثرة الذهاب والإياب
|
||||
**الأعراض:** يطرح الوكلاء أسئلة مفرطة، تقدم بطيء
|
||||
```python
|
||||
# الحل: وفّر سياقًا أفضل وأدوارًا محددة
|
||||
Task(
|
||||
description="""Write a technical blog post about machine learning.
|
||||
|
||||
Context: Target audience is software developers with basic ML knowledge.
|
||||
Length: 1200 words
|
||||
Include: code examples, practical applications, best practices
|
||||
|
||||
If you need specific technical details, delegate research to the researcher.""",
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
### المشكلة: حلقات التفويض
|
||||
**الأعراض:** يفوّض الوكلاء ذهابًا وإيابًا بلا نهاية
|
||||
```python
|
||||
# الحل: تسلسل هرمي واضح ومسؤوليات
|
||||
manager = Agent(role="Manager", allow_delegation=True)
|
||||
specialist1 = Agent(role="Specialist A", allow_delegation=False) # لا إعادة تفويض
|
||||
specialist2 = Agent(role="Specialist B", allow_delegation=False)
|
||||
```
|
||||
|
||||
## ميزات التعاون المتقدمة
|
||||
|
||||
### قواعد التعاون المخصصة
|
||||
```python
|
||||
# تعيين إرشادات تعاون محددة في خلفية الوكيل
|
||||
agent = Agent(
|
||||
role="Senior Developer",
|
||||
backstory="""You lead development projects and coordinate with team members.
|
||||
|
||||
Collaboration guidelines:
|
||||
- Delegate research tasks to the Research Analyst
|
||||
- Ask the Designer for UI/UX guidance
|
||||
- Consult the QA Engineer for testing strategies
|
||||
- Only escalate blocking issues to the Project Manager""",
|
||||
allow_delegation=True
|
||||
)
|
||||
```
|
||||
|
||||
### مراقبة التعاون
|
||||
```python
|
||||
def track_collaboration(output):
|
||||
"""تتبع أنماط التعاون"""
|
||||
if "Delegate work to coworker" in output.raw:
|
||||
print("Delegation occurred")
|
||||
if "Ask question to coworker" in output.raw:
|
||||
print("Question asked")
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
step_callback=track_collaboration, # مراقبة التعاون
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
## الذاكرة والتعلم
|
||||
|
||||
تمكين الوكلاء من تذكر التعاونات السابقة:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Content Lead",
|
||||
memory=True, # يتذكر التفاعلات السابقة
|
||||
allow_delegation=True,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
مع تفعيل الذاكرة، يتعلم الوكلاء من التعاونات السابقة ويحسّنون قرارات التفويض بمرور الوقت.
|
||||
|
||||
## الخطوات التالية
|
||||
|
||||
- **جرّب الأمثلة**: ابدأ بمثال التعاون الأساسي
|
||||
- **جرّب أدوارًا مختلفة**: اختبر تركيبات أدوار وكلاء مختلفة
|
||||
- **راقب التفاعلات**: استخدم `verbose=True` لرؤية التعاون في العمل
|
||||
- **حسّن أوصاف المهام**: المهام الواضحة تؤدي إلى تعاون أفضل
|
||||
- **وسّع النطاق**: جرّب العمليات الهرمية للمشاريع المعقدة
|
||||
|
||||
يحوّل التعاون وكلاء الذكاء الاصطناعي الفرديين إلى فرق قوية يمكنها معالجة التحديات المعقدة ومتعددة الأوجه معًا.
|
||||
245
docs/v1.15.2/ar/concepts/crews.mdx
Normal 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>
|
||||
```
|
||||
236
docs/v1.15.2/ar/concepts/event-listener.mdx
Normal file
@@ -0,0 +1,236 @@
|
||||
---
|
||||
title: "مستمعو الأحداث"
|
||||
description: "الاستفادة من أحداث CrewAI لبناء تكاملات مخصصة ومراقبة"
|
||||
icon: spinner
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يوفر CrewAI نظام أحداث قوي يتيح لك الاستماع والتفاعل مع الأحداث المختلفة التي تحدث أثناء تنفيذ طاقمك. تُمكّنك هذه الميزة من بناء تكاملات مخصصة وحلول مراقبة وأنظمة تسجيل أو أي وظائف أخرى تحتاج للتشغيل بناءً على أحداث CrewAI الداخلية.
|
||||
|
||||
## كيف يعمل
|
||||
|
||||
يستخدم CrewAI بنية ناقل أحداث لإرسال الأحداث طوال دورة حياة التنفيذ. يُبنى نظام الأحداث على المكونات التالية:
|
||||
|
||||
1. **CrewAIEventsBus**: ناقل أحداث فريد يدير تسجيل الأحداث وإرسالها
|
||||
2. **BaseEvent**: الفئة الأساسية لجميع الأحداث في النظام
|
||||
3. **BaseEventListener**: فئة أساسية مجردة لإنشاء مستمعي أحداث مخصصين
|
||||
|
||||
عندما تحدث إجراءات محددة في CrewAI (مثل بدء تنفيذ طاقم، أو إكمال وكيل لمهمة، أو استخدام أداة)، يرسل النظام أحداثًا مقابلة. يمكنك تسجيل معالجات لهذه الأحداث لتنفيذ كود مخصص عند حدوثها.
|
||||
|
||||
<Note type="info" title="تحسين المؤسسات: تتبع الأوامر">
|
||||
يوفر CrewAI AMP ميزة تتبع أوامر مدمجة تستفيد من نظام الأحداث لتتبع وتخزين وتصور جميع الأوامر والاستكمالات والبيانات الوصفية المرتبطة.
|
||||
|
||||

|
||||
|
||||
مع تتبع الأوامر يمكنك:
|
||||
|
||||
- عرض السجل الكامل لجميع الأوامر المرسلة إلى LLM
|
||||
- تتبع استخدام الرموز والتكاليف
|
||||
- تصحيح إخفاقات استدلال الوكيل
|
||||
- مشاركة تسلسلات الأوامر مع فريقك
|
||||
- مقارنة استراتيجيات الأوامر المختلفة
|
||||
- تصدير التتبعات للامتثال والتدقيق
|
||||
</Note>
|
||||
|
||||
## إنشاء مستمع أحداث مخصص
|
||||
|
||||
لإنشاء مستمع أحداث مخصص، تحتاج إلى:
|
||||
|
||||
1. إنشاء فئة ترث من `BaseEventListener`
|
||||
2. تنفيذ طريقة `setup_listeners`
|
||||
3. تسجيل معالجات للأحداث التي تهمك
|
||||
4. إنشاء مثيل من مستمعك في الملف المناسب
|
||||
|
||||
إليك مثالًا بسيطًا:
|
||||
|
||||
```python
|
||||
from crewai.events import (
|
||||
CrewKickoffStartedEvent,
|
||||
CrewKickoffCompletedEvent,
|
||||
AgentExecutionCompletedEvent,
|
||||
)
|
||||
from crewai.events import BaseEventListener
|
||||
|
||||
class MyCustomListener(BaseEventListener):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
||||
def on_crew_started(source, event):
|
||||
print(f"Crew '{event.crew_name}' has started execution!")
|
||||
|
||||
@crewai_event_bus.on(CrewKickoffCompletedEvent)
|
||||
def on_crew_completed(source, event):
|
||||
print(f"Crew '{event.crew_name}' has completed execution!")
|
||||
print(f"Output: {event.output}")
|
||||
|
||||
@crewai_event_bus.on(AgentExecutionCompletedEvent)
|
||||
def on_agent_execution_completed(source, event):
|
||||
print(f"Agent '{event.agent.role}' completed task")
|
||||
print(f"Output: {event.output}")
|
||||
```
|
||||
|
||||
## تسجيل المستمع بشكل صحيح
|
||||
|
||||
مجرد تعريف فئة المستمع ليس كافيًا. تحتاج لإنشاء مثيل منه والتأكد من استيراده في تطبيقك.
|
||||
|
||||
```python
|
||||
# في ملف crew.py
|
||||
from crewai import Agent, Crew, Task
|
||||
from my_listeners import MyCustomListener
|
||||
|
||||
# إنشاء مثيل من المستمع
|
||||
my_listener = MyCustomListener()
|
||||
|
||||
class MyCustomCrew:
|
||||
def crew(self):
|
||||
return Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
)
|
||||
```
|
||||
|
||||
## أنواع الأحداث المتاحة
|
||||
|
||||
يوفر CrewAI مجموعة واسعة من الأحداث يمكنك الاستماع إليها:
|
||||
|
||||
### أحداث الطاقم
|
||||
|
||||
- **CrewKickoffStartedEvent**: يُرسل عند بدء تنفيذ الطاقم
|
||||
- **CrewKickoffCompletedEvent**: يُرسل عند اكتمال تنفيذ الطاقم
|
||||
- **CrewKickoffFailedEvent**: يُرسل عند فشل تنفيذ الطاقم
|
||||
- **CrewTestStartedEvent**: يُرسل عند بدء اختبار الطاقم
|
||||
- **CrewTestCompletedEvent**: يُرسل عند اكتمال اختبار الطاقم
|
||||
- **CrewTestFailedEvent**: يُرسل عند فشل اختبار الطاقم
|
||||
- **CrewTrainStartedEvent**: يُرسل عند بدء تدريب الطاقم
|
||||
- **CrewTrainCompletedEvent**: يُرسل عند اكتمال تدريب الطاقم
|
||||
- **CrewTrainFailedEvent**: يُرسل عند فشل تدريب الطاقم
|
||||
|
||||
### أحداث الوكيل
|
||||
|
||||
- **AgentExecutionStartedEvent**: يُرسل عند بدء تنفيذ وكيل لمهمة
|
||||
- **AgentExecutionCompletedEvent**: يُرسل عند اكتمال تنفيذ وكيل لمهمة
|
||||
- **AgentExecutionErrorEvent**: يُرسل عند مواجهة وكيل لخطأ أثناء التنفيذ
|
||||
- **LiteAgentExecutionStartedEvent**: يُرسل عند بدء تنفيذ LiteAgent
|
||||
- **LiteAgentExecutionCompletedEvent**: يُرسل عند اكتمال تنفيذ LiteAgent
|
||||
|
||||
### أحداث المهام
|
||||
|
||||
- **TaskStartedEvent**: يُرسل عند بدء تنفيذ مهمة
|
||||
- **TaskCompletedEvent**: يُرسل عند اكتمال تنفيذ مهمة
|
||||
- **TaskFailedEvent**: يُرسل عند فشل تنفيذ مهمة
|
||||
|
||||
### أحداث استخدام الأدوات
|
||||
|
||||
- **ToolUsageStartedEvent**: يُرسل عند بدء تنفيذ أداة
|
||||
- **ToolUsageFinishedEvent**: يُرسل عند اكتمال تنفيذ أداة
|
||||
- **ToolUsageErrorEvent**: يُرسل عند مواجهة خطأ في تنفيذ أداة
|
||||
|
||||
### أحداث MCP
|
||||
|
||||
- **MCPConnectionStartedEvent**: يُرسل عند بدء الاتصال بخادم MCP
|
||||
- **MCPConnectionCompletedEvent**: يُرسل عند اكتمال الاتصال بخادم MCP
|
||||
- **MCPConnectionFailedEvent**: يُرسل عند فشل الاتصال بخادم MCP
|
||||
- **MCPToolExecutionStartedEvent**: يُرسل عند بدء تنفيذ أداة MCP
|
||||
- **MCPToolExecutionCompletedEvent**: يُرسل عند اكتمال تنفيذ أداة MCP
|
||||
- **MCPToolExecutionFailedEvent**: يُرسل عند فشل تنفيذ أداة MCP
|
||||
|
||||
### أحداث المعرفة
|
||||
|
||||
- **KnowledgeRetrievalStartedEvent**: يُرسل عند بدء استرجاع المعرفة
|
||||
- **KnowledgeRetrievalCompletedEvent**: يُرسل عند اكتمال استرجاع المعرفة
|
||||
- **KnowledgeQueryStartedEvent**: يُرسل عند بدء استعلام المعرفة
|
||||
- **KnowledgeQueryCompletedEvent**: يُرسل عند اكتمال استعلام المعرفة
|
||||
- **KnowledgeQueryFailedEvent**: يُرسل عند فشل استعلام المعرفة
|
||||
|
||||
### أحداث حواجز LLM
|
||||
|
||||
- **LLMGuardrailStartedEvent**: يُرسل عند بدء التحقق من الحاجز
|
||||
- **LLMGuardrailCompletedEvent**: يُرسل عند اكتمال التحقق من الحاجز
|
||||
- **LLMGuardrailFailedEvent**: يُرسل عند فشل التحقق من الحاجز
|
||||
|
||||
### أحداث التدفق
|
||||
|
||||
- **FlowCreatedEvent**: يُرسل عند إنشاء تدفق
|
||||
- **FlowStartedEvent**: يُرسل عند بدء تنفيذ تدفق
|
||||
- **FlowFinishedEvent**: يُرسل عند اكتمال تنفيذ تدفق
|
||||
- **FlowPausedEvent**: يُرسل عند إيقاف تدفق مؤقتًا بانتظار ملاحظات بشرية
|
||||
|
||||
### أحداث LLM
|
||||
|
||||
- **LLMCallStartedEvent**: يُرسل عند بدء استدعاء LLM
|
||||
- **LLMCallCompletedEvent**: يُرسل عند اكتمال استدعاء LLM
|
||||
- **LLMCallFailedEvent**: يُرسل عند فشل استدعاء LLM
|
||||
- **LLMStreamChunkEvent**: يُرسل لكل جزء مستلم أثناء بث استجابات LLM
|
||||
|
||||
### أحداث الذاكرة
|
||||
|
||||
- **MemoryQueryStartedEvent**: يُرسل عند بدء استعلام الذاكرة
|
||||
- **MemoryQueryCompletedEvent**: يُرسل عند اكتمال استعلام الذاكرة
|
||||
- **MemorySaveStartedEvent**: يُرسل عند بدء حفظ الذاكرة
|
||||
- **MemorySaveCompletedEvent**: يُرسل عند اكتمال حفظ الذاكرة
|
||||
|
||||
### أحداث الاستدلال
|
||||
|
||||
- **AgentReasoningStartedEvent**: يُرسل عند بدء وكيل الاستدلال حول مهمة
|
||||
- **AgentReasoningCompletedEvent**: يُرسل عند انتهاء عملية الاستدلال
|
||||
- **AgentReasoningFailedEvent**: يُرسل عند فشل عملية الاستدلال
|
||||
|
||||
### أحداث A2A (وكيل إلى وكيل)
|
||||
|
||||
- **A2ADelegationStartedEvent**: يُرسل عند بدء تفويض A2A
|
||||
- **A2ADelegationCompletedEvent**: يُرسل عند اكتمال تفويض A2A
|
||||
- **A2AConversationStartedEvent**: يُرسل عند بدء محادثة A2A متعددة الأدوار
|
||||
- **A2AConversationCompletedEvent**: يُرسل عند انتهاء محادثة A2A
|
||||
|
||||
## هيكل معالج الأحداث
|
||||
|
||||
يستقبل كل معالج حدث معاملين:
|
||||
|
||||
1. **source**: الكائن الذي أرسل الحدث
|
||||
2. **event**: مثيل الحدث، يحتوي على بيانات خاصة بالحدث
|
||||
|
||||
هيكل كائن الحدث يعتمد على نوع الحدث، لكن جميع الأحداث ترث من `BaseEvent` وتتضمن:
|
||||
|
||||
- **timestamp**: الوقت الذي أُرسل فيه الحدث
|
||||
- **type**: معرّف نصي لنوع الحدث
|
||||
|
||||
## الاستخدام المتقدم: المعالجات المحددة النطاق
|
||||
|
||||
لمعالجة الأحداث المؤقتة، يمكنك استخدام مدير سياق `scoped_handlers`:
|
||||
|
||||
```python
|
||||
from crewai.events import crewai_event_bus, CrewKickoffStartedEvent
|
||||
|
||||
with crewai_event_bus.scoped_handlers():
|
||||
@crewai_event_bus.on(CrewKickoffStartedEvent)
|
||||
def temp_handler(source, event):
|
||||
print("This handler only exists within this context")
|
||||
|
||||
# قم بشيء يرسل أحداثًا
|
||||
|
||||
# خارج السياق، يتم إزالة المعالج المؤقت
|
||||
```
|
||||
|
||||
## حالات الاستخدام
|
||||
|
||||
يمكن استخدام مستمعي الأحداث لأغراض متنوعة:
|
||||
|
||||
1. **التسجيل والمراقبة**: تتبع تنفيذ طاقمك وتسجيل الأحداث المهمة
|
||||
2. **التحليلات**: جمع بيانات عن أداء وسلوك طاقمك
|
||||
3. **التصحيح**: إعداد مستمعين مؤقتين لتصحيح مشاكل محددة
|
||||
4. **التكامل**: ربط CrewAI بأنظمة خارجية مثل منصات المراقبة وقواعد البيانات أو خدمات الإشعارات
|
||||
5. **السلوك المخصص**: تشغيل إجراءات مخصصة بناءً على أحداث محددة
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
1. **اجعل المعالجات خفيفة**: يجب أن تكون معالجات الأحداث خفيفة وتتجنب العمليات الحاجبة
|
||||
2. **معالجة الأخطاء**: أدرج معالجة أخطاء مناسبة في معالجات الأحداث لمنع الاستثناءات من التأثير على التنفيذ الرئيسي
|
||||
3. **التنظيف**: إذا خصص مستمعك موارد، تأكد من تنظيفها بشكل صحيح
|
||||
4. **الاستماع الانتقائي**: استمع فقط للأحداث التي تحتاج فعلاً لمعالجتها
|
||||
5. **الاختبار**: اختبر مستمعي الأحداث بمعزل لضمان سلوكهم كما هو متوقع
|
||||
|
||||
بالاستفادة من نظام أحداث CrewAI، يمكنك توسيع وظائفه ودمجه بسلاسة مع بنيتك التحتية الحالية.
|
||||
267
docs/v1.15.2/ar/concepts/files.mdx
Normal file
@@ -0,0 +1,267 @@
|
||||
---
|
||||
title: الملفات
|
||||
description: تمرير الصور وملفات PDF والصوت والفيديو والنصوص إلى وكلائك للمعالجة متعددة الوسائط.
|
||||
icon: file-image
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يدعم CrewAI مدخلات الملفات متعددة الوسائط الأصلية، مما يتيح لك تمرير الصور وملفات PDF والصوت والفيديو والنصوص مباشرة إلى وكلائك. يتم تنسيق الملفات تلقائيًا وفقًا لمتطلبات API لكل مزود LLM.
|
||||
|
||||
<Note type="info" title="اعتمادية اختيارية">
|
||||
يتطلب دعم الملفات حزمة `crewai-files` الاختيارية. ثبّتها بـ:
|
||||
|
||||
```bash
|
||||
uv add 'crewai[file-processing]'
|
||||
```
|
||||
</Note>
|
||||
|
||||
<Note type="warning" title="وصول مبكر">
|
||||
واجهة معالجة الملفات حاليًا في مرحلة الوصول المبكر.
|
||||
</Note>
|
||||
|
||||
## أنواع الملفات
|
||||
|
||||
يدعم CrewAI خمسة أنواع ملفات محددة بالإضافة إلى فئة `File` العامة التي تكتشف النوع تلقائيًا:
|
||||
|
||||
| النوع | الفئة | حالات الاستخدام |
|
||||
|:-----|:------|:----------|
|
||||
| **صورة** | `ImageFile` | صور، لقطات شاشة، مخططات، رسوم بيانية |
|
||||
| **PDF** | `PDFFile` | مستندات، تقارير، أوراق بحثية |
|
||||
| **صوت** | `AudioFile` | تسجيلات صوتية، بودكاست، اجتماعات |
|
||||
| **فيديو** | `VideoFile` | تسجيلات شاشة، عروض تقديمية |
|
||||
| **نص** | `TextFile` | ملفات كود، سجلات، ملفات بيانات |
|
||||
| **عام** | `File` | اكتشاف تلقائي للنوع من المحتوى |
|
||||
|
||||
```python
|
||||
from crewai_files import File, ImageFile, PDFFile, AudioFile, VideoFile, TextFile
|
||||
|
||||
image = ImageFile(source="screenshot.png")
|
||||
pdf = PDFFile(source="report.pdf")
|
||||
audio = AudioFile(source="meeting.mp3")
|
||||
video = VideoFile(source="demo.mp4")
|
||||
text = TextFile(source="data.csv")
|
||||
|
||||
file = File(source="document.pdf")
|
||||
```
|
||||
|
||||
## مصادر الملفات
|
||||
|
||||
يقبل معامل `source` أنواع إدخال متعددة ويكتشف تلقائيًا المعالج المناسب:
|
||||
|
||||
### من مسار
|
||||
|
||||
```python
|
||||
from crewai_files import ImageFile
|
||||
|
||||
image = ImageFile(source="./images/chart.png")
|
||||
```
|
||||
|
||||
### من عنوان URL
|
||||
|
||||
```python
|
||||
from crewai_files import ImageFile
|
||||
|
||||
image = ImageFile(source="https://example.com/image.png")
|
||||
```
|
||||
|
||||
### من بايتات
|
||||
|
||||
```python
|
||||
from crewai_files import ImageFile, FileBytes
|
||||
|
||||
image_bytes = download_image_from_api()
|
||||
image = ImageFile(source=FileBytes(data=image_bytes, filename="downloaded.png"))
|
||||
image = ImageFile(source=image_bytes)
|
||||
```
|
||||
|
||||
## استخدام الملفات
|
||||
|
||||
يمكن تمرير الملفات على مستويات متعددة، حيث تأخذ المستويات الأكثر تحديدًا الأولوية.
|
||||
|
||||
### مع الأطقم
|
||||
|
||||
مرر الملفات عند تشغيل طاقم:
|
||||
|
||||
```python
|
||||
from crewai import Crew
|
||||
from crewai_files import ImageFile
|
||||
|
||||
crew = Crew(agents=[analyst], tasks=[analysis_task])
|
||||
|
||||
result = crew.kickoff(
|
||||
inputs={"topic": "Q4 Sales"},
|
||||
input_files={
|
||||
"chart": ImageFile(source="sales_chart.png"),
|
||||
"report": PDFFile(source="quarterly_report.pdf"),
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### مع المهام
|
||||
|
||||
أرفق الملفات بمهام محددة:
|
||||
|
||||
```python
|
||||
from crewai import Task
|
||||
from crewai_files import ImageFile
|
||||
|
||||
task = Task(
|
||||
description="Analyze the sales chart and identify trends in {chart}",
|
||||
expected_output="A summary of key trends",
|
||||
input_files={
|
||||
"chart": ImageFile(source="sales_chart.png"),
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### مع التدفقات
|
||||
|
||||
مرر الملفات إلى التدفقات، والتي تنتقل تلقائيًا إلى الأطقم:
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, start
|
||||
from crewai_files import ImageFile
|
||||
|
||||
class AnalysisFlow(Flow):
|
||||
@start()
|
||||
def analyze(self):
|
||||
return self.analysis_crew.kickoff()
|
||||
|
||||
flow = AnalysisFlow()
|
||||
result = flow.kickoff(
|
||||
input_files={"image": ImageFile(source="data.png")}
|
||||
)
|
||||
```
|
||||
|
||||
### مع الوكلاء المستقلين
|
||||
|
||||
مرر الملفات مباشرة إلى تشغيل الوكيل:
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai_files import ImageFile
|
||||
|
||||
agent = Agent(
|
||||
role="Image Analyst",
|
||||
goal="Analyze images",
|
||||
backstory="Expert at visual analysis",
|
||||
llm="gpt-4o",
|
||||
)
|
||||
|
||||
result = agent.kickoff(
|
||||
messages="What's in this image?",
|
||||
input_files={"photo": ImageFile(source="photo.jpg")},
|
||||
)
|
||||
```
|
||||
|
||||
## أولوية الملفات
|
||||
|
||||
عند تمرير الملفات على مستويات متعددة، تتجاوز المستويات الأكثر تحديدًا المستويات الأوسع:
|
||||
|
||||
```
|
||||
Flow input_files < Crew input_files < Task input_files
|
||||
```
|
||||
|
||||
على سبيل المثال، إذا عرّف كل من التدفق والمهمة ملفًا باسم `"chart"`، تُستخدم نسخة المهمة.
|
||||
|
||||
## دعم المزودين
|
||||
|
||||
تدعم المزودات المختلفة أنواع ملفات مختلفة. يقوم CrewAI تلقائيًا بتنسيق الملفات وفقًا لواجهة كل مزود.
|
||||
|
||||
| المزود | صورة | PDF | صوت | فيديو | نص |
|
||||
|:---------|:-----:|:---:|:-----:|:-----:|:----:|
|
||||
| **OpenAI** (completions API) | ✓ | | | | |
|
||||
| **OpenAI** (responses API) | ✓ | ✓ | ✓ | | |
|
||||
| **Anthropic** (claude-3.x) | ✓ | ✓ | | | |
|
||||
| **Google Gemini** (gemini-1.5, 2.0, 2.5) | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| **AWS Bedrock** (claude-3) | ✓ | ✓ | | | |
|
||||
| **Azure OpenAI** (gpt-4o) | ✓ | | ✓ | | |
|
||||
|
||||
<Note type="info" title="Gemini لأقصى دعم للملفات">
|
||||
تدعم نماذج Google Gemini جميع أنواع الملفات بما في ذلك الفيديو (حتى ساعة واحدة، 2 جيجابايت). استخدم Gemini عندما تحتاج لمعالجة محتوى الفيديو.
|
||||
</Note>
|
||||
|
||||
<Note type="warning" title="أنواع الملفات غير المدعومة">
|
||||
إذا مررت نوع ملف لا يدعمه المزود (مثل الفيديو إلى OpenAI)، ستتلقى خطأ `UnsupportedFileTypeError`. اختر مزودك بناءً على أنواع الملفات التي تحتاج لمعالجتها.
|
||||
</Note>
|
||||
|
||||
## كيف تُرسل الملفات
|
||||
|
||||
يختار CrewAI تلقائيًا الطريقة المثلى لإرسال الملفات إلى كل مزود:
|
||||
|
||||
| الطريقة | الوصف | متى تُستخدم |
|
||||
|:-------|:------------|:----------|
|
||||
| **Inline Base64** | الملف مضمّن مباشرة في الطلب | ملفات صغيرة (< 5 ميجابايت عادة) |
|
||||
| **File Upload API** | الملف يُرفع بشكل منفصل، يُشار إليه بمعرّف | ملفات كبيرة تتجاوز العتبة |
|
||||
| **URL Reference** | عنوان URL مباشر يُمرر إلى النموذج | مصدر الملف هو عنوان URL بالفعل |
|
||||
|
||||
### طرق الإرسال حسب المزود
|
||||
|
||||
| المزود | Inline Base64 | File Upload API | URL References |
|
||||
|:---------|:-------------:|:---------------:|:--------------:|
|
||||
| **OpenAI** | ✓ | ✓ (> 5 MB) | ✓ |
|
||||
| **Anthropic** | ✓ | ✓ (> 5 MB) | ✓ |
|
||||
| **Google Gemini** | ✓ | ✓ (> 20 MB) | ✓ |
|
||||
| **AWS Bedrock** | ✓ | | ✓ (S3 URIs) |
|
||||
| **Azure OpenAI** | ✓ | | ✓ |
|
||||
|
||||
<Note type="info" title="تحسين تلقائي">
|
||||
لا تحتاج لإدارة هذا بنفسك. يستخدم CrewAI تلقائيًا الطريقة الأكثر كفاءة بناءً على حجم الملف وقدرات المزود. المزودات بدون واجهات رفع الملفات تستخدم inline base64 لجميع الملفات.
|
||||
</Note>
|
||||
|
||||
## أوضاع معالجة الملفات
|
||||
|
||||
تحكم في كيفية معالجة الملفات عندما تتجاوز حدود المزود:
|
||||
|
||||
```python
|
||||
from crewai_files import ImageFile, PDFFile
|
||||
|
||||
image = ImageFile(source="large.png", mode="strict")
|
||||
image = ImageFile(source="large.png", mode="auto")
|
||||
image = ImageFile(source="large.png", mode="warn")
|
||||
pdf = PDFFile(source="large.pdf", mode="chunk")
|
||||
```
|
||||
|
||||
## قيود المزودين
|
||||
|
||||
لكل مزود حدود محددة لأحجام الملفات والأبعاد:
|
||||
|
||||
### OpenAI
|
||||
- **الصور**: حد أقصى 20 ميجابايت، حتى 10 صور لكل طلب
|
||||
- **PDF**: حد أقصى 32 ميجابايت، حتى 100 صفحة
|
||||
- **الصوت**: حد أقصى 25 ميجابايت، حتى 25 دقيقة
|
||||
|
||||
### Anthropic
|
||||
- **الصور**: حد أقصى 5 ميجابايت، أقصى 8000x8000 بكسل، حتى 100 صورة
|
||||
- **PDF**: حد أقصى 32 ميجابايت، حتى 100 صفحة
|
||||
|
||||
### Google Gemini
|
||||
- **الصور**: حد أقصى 100 ميجابايت
|
||||
- **PDF**: حد أقصى 50 ميجابايت
|
||||
- **الصوت**: حد أقصى 100 ميجابايت، حتى 9.5 ساعة
|
||||
- **الفيديو**: حد أقصى 2 جيجابايت، حتى ساعة واحدة
|
||||
|
||||
### AWS Bedrock
|
||||
- **الصور**: حد أقصى 4.5 ميجابايت، أقصى 8000x8000 بكسل
|
||||
- **PDF**: حد أقصى 3.75 ميجابايت، حتى 100 صفحة
|
||||
|
||||
## الإشارة إلى الملفات في الأوامر
|
||||
|
||||
استخدم اسم مفتاح الملف في أوصاف المهام للإشارة إلى الملفات:
|
||||
|
||||
```python
|
||||
task = Task(
|
||||
description="""
|
||||
Analyze the provided materials:
|
||||
1. Review the chart in {sales_chart}
|
||||
2. Cross-reference with data in {quarterly_report}
|
||||
3. Summarize key findings
|
||||
""",
|
||||
expected_output="Analysis summary with key insights",
|
||||
input_files={
|
||||
"sales_chart": ImageFile(source="chart.png"),
|
||||
"quarterly_report": PDFFile(source="report.pdf"),
|
||||
}
|
||||
)
|
||||
```
|
||||
1163
docs/v1.15.2/ar/concepts/flows.mdx
Normal file
1095
docs/v1.15.2/ar/concepts/knowledge.mdx
Normal file
1513
docs/v1.15.2/ar/concepts/llms.mdx
Normal file
878
docs/v1.15.2/ar/concepts/memory.mdx
Normal file
@@ -0,0 +1,878 @@
|
||||
---
|
||||
title: الذاكرة
|
||||
description: الاستفادة من نظام الذاكرة الموحد في CrewAI لتعزيز قدرات الوكلاء.
|
||||
icon: database
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يوفر CrewAI **نظام ذاكرة موحد** -- فئة `Memory` واحدة تستبدل أنواع الذاكرة المنفصلة (قصيرة المدى، طويلة المدى، ذاكرة الكيانات، والخارجية) بواجهة برمجة تطبيقات ذكية واحدة. تستخدم الذاكرة LLM لتحليل المحتوى عند الحفظ (استنتاج النطاق والفئات والأهمية) وتدعم الاسترجاع متعدد العمق مع تسجيل مركب يمزج بين التشابه الدلالي والحداثة والأهمية.
|
||||
|
||||
يمكنك استخدام الذاكرة بأربع طرق: **مستقلة** (سكربتات، دفاتر ملاحظات)، **مع فرق Crew**، **مع Agents**، أو **داخل التدفقات**.
|
||||
|
||||
## البدء السريع
|
||||
|
||||
```python
|
||||
from crewai import Memory
|
||||
|
||||
memory = Memory()
|
||||
|
||||
# Store -- the LLM infers scope, categories, and importance
|
||||
memory.remember("We decided to use PostgreSQL for the user database.")
|
||||
|
||||
# Retrieve -- results ranked by composite score (semantic + recency + importance)
|
||||
matches = memory.recall("What database did we choose?")
|
||||
for m in matches:
|
||||
print(f"[{m.score:.2f}] {m.record.content}")
|
||||
|
||||
# Tune scoring for a fast-moving project
|
||||
memory = Memory(recency_weight=0.5, recency_half_life_days=7)
|
||||
|
||||
# Forget
|
||||
memory.forget(scope="/project/old")
|
||||
|
||||
# Explore the self-organized scope tree
|
||||
print(memory.tree())
|
||||
print(memory.info("/"))
|
||||
```
|
||||
|
||||
## أربع طرق لاستخدام الذاكرة
|
||||
|
||||
### مستقلة
|
||||
|
||||
استخدم الذاكرة في السكربتات ودفاتر الملاحظات وأدوات سطر الأوامر أو كقاعدة معرفة مستقلة -- لا حاجة لوكلاء أو فرق Crew.
|
||||
|
||||
```python
|
||||
from crewai import Memory
|
||||
|
||||
memory = Memory()
|
||||
|
||||
# Build up knowledge
|
||||
memory.remember("The API rate limit is 1000 requests per minute.")
|
||||
memory.remember("Our staging environment uses port 8080.")
|
||||
memory.remember("The team agreed to use feature flags for all new releases.")
|
||||
|
||||
# Later, recall what you need
|
||||
matches = memory.recall("What are our API limits?", limit=5)
|
||||
for m in matches:
|
||||
print(f"[{m.score:.2f}] {m.record.content}")
|
||||
|
||||
# Extract atomic facts from a longer text
|
||||
raw = """Meeting notes: We decided to migrate from MySQL to PostgreSQL
|
||||
next quarter. The budget is $50k. Sarah will lead the migration."""
|
||||
|
||||
facts = memory.extract_memories(raw)
|
||||
# ["Migration from MySQL to PostgreSQL planned for next quarter",
|
||||
# "Database migration budget is $50k",
|
||||
# "Sarah will lead the database migration"]
|
||||
|
||||
for fact in facts:
|
||||
memory.remember(fact)
|
||||
```
|
||||
|
||||
### مع فرق Crew
|
||||
|
||||
مرّر `memory=True` للإعدادات الافتراضية، أو مرّر مثيل `Memory` مُعدّ للسلوك المخصص.
|
||||
|
||||
```python
|
||||
from crewai import Crew, Agent, Task, Process, Memory
|
||||
|
||||
# Option 1: Default memory
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, writing_task],
|
||||
process=Process.sequential,
|
||||
memory=True,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
# Option 2: Custom memory with tuned scoring
|
||||
memory = Memory(
|
||||
recency_weight=0.4,
|
||||
semantic_weight=0.4,
|
||||
importance_weight=0.2,
|
||||
recency_half_life_days=14,
|
||||
)
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research_task, writing_task],
|
||||
memory=memory,
|
||||
)
|
||||
```
|
||||
|
||||
عند استخدام `memory=True`، ينشئ الفريق مثيل `Memory()` افتراضيًا ويمرر إعداد `embedder` الخاص بالفريق تلقائيًا. يشترك جميع الوكلاء في الفريق في ذاكرة الفريق ما لم يكن لدى الوكيل ذاكرته الخاصة.
|
||||
|
||||
بعد كل مهمة، يستخرج الفريق تلقائيًا حقائق منفصلة من مخرجات المهمة ويخزّنها. قبل كل مهمة، يسترجع الوكيل السياق ذا الصلة من الذاكرة ويحقنه في موجّه المهمة.
|
||||
|
||||
### مع Agents
|
||||
|
||||
يمكن للوكلاء استخدام ذاكرة الفريق المشتركة (افتراضيًا) أو تلقي عرض محدد النطاق للسياق الخاص.
|
||||
|
||||
```python
|
||||
from crewai import Agent, Memory
|
||||
|
||||
memory = Memory()
|
||||
|
||||
# Researcher gets a private scope -- only sees /agent/researcher
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Find and analyze information",
|
||||
backstory="Expert researcher with attention to detail",
|
||||
memory=memory.scope("/agent/researcher"),
|
||||
)
|
||||
|
||||
# Writer uses crew shared memory (no agent-level memory set)
|
||||
writer = Agent(
|
||||
role="Writer",
|
||||
goal="Produce clear, well-structured content",
|
||||
backstory="Experienced technical writer",
|
||||
# memory not set -- uses crew._memory when crew has memory enabled
|
||||
)
|
||||
```
|
||||
|
||||
يمنح هذا النمط الباحث نتائج خاصة بينما يقرأ الكاتب من ذاكرة الفريق المشتركة.
|
||||
|
||||
### مع التدفقات
|
||||
|
||||
كل تدفق يحتوي على ذاكرة مدمجة. استخدم `self.remember()` و `self.recall()` و `self.extract_memories()` داخل أي دالة تدفق.
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
|
||||
class ResearchFlow(Flow):
|
||||
@start()
|
||||
def gather_data(self):
|
||||
findings = "PostgreSQL handles 10k concurrent connections. MySQL caps at 5k."
|
||||
self.remember(findings, scope="/research/databases")
|
||||
return findings
|
||||
|
||||
@listen(gather_data)
|
||||
def write_report(self, findings):
|
||||
# Recall past research to provide context
|
||||
past = self.recall("database performance benchmarks")
|
||||
context = "\n".join(f"- {m.record.content}" for m in past)
|
||||
return f"Report:\nNew findings: {findings}\nPrevious context:\n{context}"
|
||||
```
|
||||
|
||||
انظر [وثائق التدفقات](/concepts/flows) لمزيد من المعلومات حول الذاكرة في التدفقات.
|
||||
|
||||
|
||||
## النطاقات الهرمية
|
||||
|
||||
### ما هي النطاقات
|
||||
|
||||
يتم تنظيم الذكريات في شجرة هرمية من النطاقات، مشابهة لنظام الملفات. كل نطاق هو مسار مثل `/` أو `/project/alpha` أو `/agent/researcher/findings`.
|
||||
|
||||
```
|
||||
/
|
||||
/company
|
||||
/company/engineering
|
||||
/company/product
|
||||
/project
|
||||
/project/alpha
|
||||
/project/beta
|
||||
/agent
|
||||
/agent/researcher
|
||||
/agent/writer
|
||||
```
|
||||
|
||||
توفر النطاقات **ذاكرة تعتمد على السياق** -- عند الاسترجاع ضمن نطاق، تبحث فقط في ذلك الفرع من الشجرة، مما يحسّن كلًا من الدقة والأداء.
|
||||
|
||||
### كيف يعمل استنتاج النطاق
|
||||
|
||||
عند استدعاء `remember()` دون تحديد نطاق، يحلل LLM المحتوى وشجرة النطاقات الحالية، ثم يقترح أفضل موضع. إذا لم يكن هناك نطاق حالي مناسب، ينشئ واحدًا جديدًا. بمرور الوقت، تنمو شجرة النطاقات عضويًا من المحتوى نفسه -- لا تحتاج إلى تصميم مخطط مسبقًا.
|
||||
|
||||
```python
|
||||
memory = Memory()
|
||||
|
||||
# LLM infers scope from content
|
||||
memory.remember("We chose PostgreSQL for the user database.")
|
||||
# -> might be placed under /project/decisions or /engineering/database
|
||||
|
||||
# You can also specify scope explicitly
|
||||
memory.remember("Sprint velocity is 42 points", scope="/team/metrics")
|
||||
```
|
||||
|
||||
### تصوير شجرة النطاقات
|
||||
|
||||
```python
|
||||
print(memory.tree())
|
||||
# / (15 records)
|
||||
# /project (8 records)
|
||||
# /project/alpha (5 records)
|
||||
# /project/beta (3 records)
|
||||
# /agent (7 records)
|
||||
# /agent/researcher (4 records)
|
||||
# /agent/writer (3 records)
|
||||
|
||||
print(memory.info("/project/alpha"))
|
||||
# ScopeInfo(path='/project/alpha', record_count=5,
|
||||
# categories=['architecture', 'database'],
|
||||
# oldest_record=datetime(...), newest_record=datetime(...),
|
||||
# child_scopes=[])
|
||||
```
|
||||
|
||||
### MemoryScope: عروض الأشجار الفرعية
|
||||
|
||||
يقيّد `MemoryScope` جميع العمليات على فرع من الشجرة. يمكن للوكيل أو الكود الذي يستخدمه الرؤية والكتابة فقط ضمن تلك الشجرة الفرعية.
|
||||
|
||||
```python
|
||||
memory = Memory()
|
||||
|
||||
# Create a scope for a specific agent
|
||||
agent_memory = memory.scope("/agent/researcher")
|
||||
|
||||
# Everything is relative to /agent/researcher
|
||||
agent_memory.remember("Found three relevant papers on LLM memory.")
|
||||
# -> stored under /agent/researcher
|
||||
|
||||
agent_memory.recall("relevant papers")
|
||||
# -> searches only under /agent/researcher
|
||||
|
||||
# Narrow further with subscope
|
||||
project_memory = agent_memory.subscope("project-alpha")
|
||||
# -> /agent/researcher/project-alpha
|
||||
```
|
||||
|
||||
### أفضل الممارسات لتصميم النطاقات
|
||||
|
||||
- **ابدأ بشكل مسطح، ودع LLM ينظّم.** لا تبالغ في هندسة تسلسل النطاقات مسبقًا. ابدأ بـ `memory.remember(content)` ودع استنتاج النطاق في LLM ينشئ الهيكل مع تراكم المحتوى.
|
||||
|
||||
- **استخدم أنماط `/{entity_type}/{identifier}`.** تنشأ التسلسلات الطبيعية من أنماط مثل `/project/alpha` و `/agent/researcher` و `/company/engineering` و `/customer/acme-corp`.
|
||||
|
||||
- **حدد النطاق حسب الاهتمام، وليس حسب نوع البيانات.** استخدم `/project/alpha/decisions` بدلاً من `/decisions/project/alpha`. هذا يبقي المحتوى ذا الصلة معًا.
|
||||
|
||||
- **حافظ على العمق ضحلًا (2-3 مستويات).** النطاقات المتداخلة بعمق تصبح متفرقة جدًا. `/project/alpha/architecture` جيد؛ `/project/alpha/architecture/decisions/databases/postgresql` عميق جدًا.
|
||||
|
||||
- **استخدم النطاقات الصريحة عندما تعرف، ودع LLM يستنتج عندما لا تعرف.** إذا كنت تخزّن قرار مشروع معروف، مرّر `scope="/project/alpha/decisions"`. إذا كنت تخزّن مخرجات وكيل حرة الشكل، اترك النطاق ودع LLM يحدده.
|
||||
|
||||
### أمثلة حالات الاستخدام
|
||||
|
||||
**فريق متعدد المشاريع:**
|
||||
```python
|
||||
memory = Memory()
|
||||
# Each project gets its own branch
|
||||
memory.remember("Using microservices architecture", scope="/project/alpha/architecture")
|
||||
memory.remember("GraphQL API for client apps", scope="/project/beta/api")
|
||||
|
||||
# Recall across all projects
|
||||
memory.recall("API design decisions")
|
||||
|
||||
# Or within a specific project
|
||||
memory.recall("API design", scope="/project/beta")
|
||||
```
|
||||
|
||||
**سياق خاص لكل وكيل مع معرفة مشتركة:**
|
||||
```python
|
||||
memory = Memory()
|
||||
|
||||
# Researcher has private findings
|
||||
researcher_memory = memory.scope("/agent/researcher")
|
||||
|
||||
# Writer can read from both its own scope and shared company knowledge
|
||||
writer_view = memory.slice(
|
||||
scopes=["/agent/writer", "/company/knowledge"],
|
||||
read_only=True,
|
||||
)
|
||||
```
|
||||
|
||||
**دعم العملاء (سياق لكل عميل):**
|
||||
```python
|
||||
memory = Memory()
|
||||
|
||||
# Each customer gets isolated context
|
||||
memory.remember("Prefers email communication", scope="/customer/acme-corp")
|
||||
memory.remember("On enterprise plan, 50 seats", scope="/customer/acme-corp")
|
||||
|
||||
# Shared product docs are accessible to all agents
|
||||
memory.remember("Rate limit is 1000 req/min on enterprise plan", scope="/product/docs")
|
||||
```
|
||||
|
||||
|
||||
## شرائح الذاكرة
|
||||
|
||||
### ما هي الشرائح
|
||||
|
||||
`MemorySlice` هو عرض عبر نطاقات متعددة، ربما متباعدة. على عكس النطاق (الذي يقيّد على شجرة فرعية واحدة)، تتيح لك الشريحة الاسترجاع من عدة فروع في وقت واحد.
|
||||
|
||||
### متى تستخدم الشرائح مقابل النطاقات
|
||||
|
||||
- **النطاق**: استخدمه عندما يجب تقييد وكيل أو كتلة كود على شجرة فرعية واحدة. مثال: وكيل يرى فقط `/agent/researcher`.
|
||||
- **الشريحة**: استخدمها عندما تحتاج إلى دمج السياق من عدة فروع. مثال: وكيل يقرأ من نطاقه الخاص بالإضافة إلى معرفة الشركة المشتركة.
|
||||
|
||||
### شرائح القراءة فقط
|
||||
|
||||
النمط الأكثر شيوعًا: منح وكيل إمكانية القراءة من فروع متعددة دون السماح له بالكتابة في المناطق المشتركة.
|
||||
|
||||
```python
|
||||
memory = Memory()
|
||||
|
||||
# Agent can recall from its own scope AND company knowledge,
|
||||
# but cannot write to company knowledge
|
||||
agent_view = memory.slice(
|
||||
scopes=["/agent/researcher", "/company/knowledge"],
|
||||
read_only=True,
|
||||
)
|
||||
|
||||
matches = agent_view.recall("company security policies", limit=5)
|
||||
# Searches both /agent/researcher and /company/knowledge, merges and ranks results
|
||||
|
||||
agent_view.remember("new finding") # Raises PermissionError (read-only)
|
||||
```
|
||||
|
||||
### شرائح القراءة والكتابة
|
||||
|
||||
عند تعطيل القراءة فقط، يمكنك الكتابة في أي من النطاقات المضمّنة، لكن يجب تحديد النطاق صراحة.
|
||||
|
||||
```python
|
||||
view = memory.slice(scopes=["/team/alpha", "/team/beta"], read_only=False)
|
||||
|
||||
# Must specify scope when writing
|
||||
view.remember("Cross-team decision", scope="/team/alpha", categories=["decisions"])
|
||||
```
|
||||
|
||||
|
||||
## التسجيل المركب
|
||||
|
||||
يتم ترتيب نتائج الاسترجاع بواسطة مزيج مرجّح من ثلاث إشارات:
|
||||
|
||||
```
|
||||
composite = semantic_weight * similarity + recency_weight * decay + importance_weight * importance
|
||||
```
|
||||
|
||||
حيث:
|
||||
- **similarity** = `1 / (1 + distance)` من فهرس المتجهات (0 إلى 1)
|
||||
- **decay** = `0.5^(age_days / half_life_days)` -- اضمحلال أُسي (1.0 لليوم، 0.5 عند نصف العمر)
|
||||
- **importance** = درجة أهمية السجل (0 إلى 1)، يتم تعيينها وقت الترميز
|
||||
|
||||
قم بإعدادها مباشرة على منشئ `Memory`:
|
||||
|
||||
```python
|
||||
# Sprint retrospective: favor recent memories, short half-life
|
||||
memory = Memory(
|
||||
recency_weight=0.5,
|
||||
semantic_weight=0.3,
|
||||
importance_weight=0.2,
|
||||
recency_half_life_days=7,
|
||||
)
|
||||
|
||||
# Architecture knowledge base: favor important memories, long half-life
|
||||
memory = Memory(
|
||||
recency_weight=0.1,
|
||||
semantic_weight=0.5,
|
||||
importance_weight=0.4,
|
||||
recency_half_life_days=180,
|
||||
)
|
||||
```
|
||||
|
||||
يتضمن كل `MemoryMatch` قائمة `match_reasons` حتى تتمكن من رؤية سبب ترتيب نتيجة معينة في موضعها (مثل `["semantic", "recency", "importance"]`).
|
||||
|
||||
|
||||
## طبقة تحليل LLM
|
||||
|
||||
تستخدم الذاكرة LLM بثلاث طرق:
|
||||
|
||||
1. **عند الحفظ** -- عندما تحذف النطاق أو الفئات أو الأهمية، يحلل LLM المحتوى ويقترح النطاق والفئات والأهمية والبيانات الوصفية (الكيانات والتواريخ والموضوعات).
|
||||
2. **عند الاسترجاع** -- للاسترجاع العميق/التلقائي، يحلل LLM الاستعلام (الكلمات المفتاحية، تلميحات الوقت، النطاقات المقترحة، التعقيد) لتوجيه الاسترجاع.
|
||||
3. **استخراج الذكريات** -- `extract_memories(content)` يقسم النص الخام (مثل مخرجات المهمة) إلى عبارات ذاكرة منفصلة. يستخدم الوكلاء هذا قبل استدعاء `remember()` على كل عبارة حتى يتم تخزين حقائق ذرية بدلاً من كتلة كبيرة واحدة.
|
||||
|
||||
جميع التحليلات تتدهور بسلاسة عند فشل LLM -- انظر [سلوك الفشل](#سلوك-الفشل).
|
||||
|
||||
|
||||
## توحيد الذاكرة
|
||||
|
||||
عند حفظ محتوى جديد، يتحقق خط أنابيب الترميز تلقائيًا من وجود سجلات مماثلة في التخزين. إذا كان التشابه أعلى من `consolidation_threshold` (الافتراضي 0.85)، يقرر LLM ما يجب فعله:
|
||||
|
||||
- **keep** -- السجل الحالي لا يزال دقيقًا وغير مكرر.
|
||||
- **update** -- يجب تحديث السجل الحالي بمعلومات جديدة (يوفر LLM المحتوى المدمج).
|
||||
- **delete** -- السجل الحالي قديم أو تم استبداله أو تناقضه.
|
||||
- **insert_new** -- ما إذا كان يجب إدراج المحتوى الجديد أيضًا كسجل منفصل.
|
||||
|
||||
هذا يمنع تراكم النسخ المكررة. على سبيل المثال، إذا حفظت "CrewAI ensures reliable operation" ثلاث مرات، يتعرف التوحيد على النسخ المكررة ويحتفظ بسجل واحد فقط.
|
||||
|
||||
### إزالة التكرار داخل الدفعة
|
||||
|
||||
عند استخدام `remember_many()`، تتم مقارنة العناصر داخل نفس الدفعة مع بعضها البعض قبل الوصول إلى التخزين. إذا كان تشابه جيب التمام >= `batch_dedup_threshold` (الافتراضي 0.98)، يتم إسقاط العنصر الأحدث بصمت. هذا يلتقط النسخ المكررة الدقيقة أو شبه الدقيقة داخل دفعة واحدة دون أي استدعاءات LLM (رياضيات متجهات خالصة).
|
||||
|
||||
```python
|
||||
# Only 2 records are stored (the third is a near-duplicate of the first)
|
||||
memory.remember_many([
|
||||
"CrewAI supports complex workflows.",
|
||||
"Python is a great language.",
|
||||
"CrewAI supports complex workflows.", # dropped by intra-batch dedup
|
||||
])
|
||||
```
|
||||
|
||||
|
||||
## الحفظ غير الحاجب
|
||||
|
||||
`remember_many()` **غير حاجب** -- يقدم خط أنابيب الترميز إلى خيط خلفي ويعود فورًا. هذا يعني أن الوكيل يمكنه المتابعة إلى المهمة التالية بينما يتم حفظ الذكريات.
|
||||
|
||||
```python
|
||||
# Returns immediately -- save happens in background
|
||||
memory.remember_many(["Fact A.", "Fact B.", "Fact C."])
|
||||
|
||||
# recall() automatically waits for pending saves before searching
|
||||
matches = memory.recall("facts") # sees all 3 records
|
||||
```
|
||||
|
||||
### حاجز القراءة
|
||||
|
||||
كل استدعاء `recall()` يستدعي تلقائيًا `drain_writes()` قبل البحث، مما يضمن أن الاستعلام يرى دائمًا أحدث السجلات المستمرة. هذا شفاف -- لا تحتاج أبدًا إلى التفكير فيه.
|
||||
|
||||
### إيقاف الفريق
|
||||
|
||||
عند انتهاء الفريق، يستنزف `kickoff()` جميع عمليات حفظ الذاكرة المعلقة في كتلة `finally` الخاصة به، لذا لا تُفقد أي عمليات حفظ حتى لو اكتمل الفريق بينما عمليات الحفظ الخلفية قيد التنفيذ.
|
||||
|
||||
### الاستخدام المستقل
|
||||
|
||||
للسكربتات أو دفاتر الملاحظات حيث لا توجد دورة حياة فريق، استدعِ `drain_writes()` أو `close()` صراحة:
|
||||
|
||||
```python
|
||||
memory = Memory()
|
||||
memory.remember_many(["Fact A.", "Fact B."])
|
||||
|
||||
# Option 1: Wait for pending saves
|
||||
memory.drain_writes()
|
||||
|
||||
# Option 2: Drain and shut down the background pool
|
||||
memory.close()
|
||||
```
|
||||
|
||||
|
||||
## المصدر والخصوصية
|
||||
|
||||
يمكن لكل سجل ذاكرة أن يحمل علامة `source` لتتبع المصدر وعلامة `private` للتحكم في الوصول.
|
||||
|
||||
### تتبع المصدر
|
||||
|
||||
يحدد معامل `source` من أين جاءت الذاكرة:
|
||||
|
||||
```python
|
||||
# Tag memories with their origin
|
||||
memory.remember("User prefers dark mode", source="user:alice")
|
||||
memory.remember("System config updated", source="admin")
|
||||
memory.remember("Agent found a bug", source="agent:debugger")
|
||||
|
||||
# Recall only memories from a specific source
|
||||
matches = memory.recall("user preferences", source="user:alice")
|
||||
```
|
||||
|
||||
### الذكريات الخاصة
|
||||
|
||||
الذكريات الخاصة مرئية فقط للاسترجاع عندما يتطابق `source`:
|
||||
|
||||
```python
|
||||
# Store a private memory
|
||||
memory.remember("Alice's API key is sk-...", source="user:alice", private=True)
|
||||
|
||||
# This recall sees the private memory (source matches)
|
||||
matches = memory.recall("API key", source="user:alice")
|
||||
|
||||
# This recall does NOT see it (different source)
|
||||
matches = memory.recall("API key", source="user:bob")
|
||||
|
||||
# Admin access: see all private records regardless of source
|
||||
matches = memory.recall("API key", include_private=True)
|
||||
```
|
||||
|
||||
هذا مفيد بشكل خاص في النشرات متعددة المستخدمين أو المؤسسية حيث يجب عزل ذكريات المستخدمين المختلفين.
|
||||
|
||||
|
||||
## RecallFlow (الاسترجاع العميق)
|
||||
|
||||
يدعم `recall()` عمقين:
|
||||
|
||||
- **`depth="shallow"`** -- بحث متجهي مباشر مع تسجيل مركب. سريع (~200 مللي ثانية)، بدون استدعاءات LLM.
|
||||
- **`depth="deep"` (افتراضي)** -- يشغل RecallFlow متعدد الخطوات: تحليل الاستعلام، اختيار النطاق، بحث متجهي متوازٍ، توجيه قائم على الثقة، واستكشاف متكرر اختياري عندما تكون الثقة منخفضة.
|
||||
|
||||
**تخطي LLM الذكي**: الاستعلامات الأقصر من `query_analysis_threshold` (الافتراضي 200 حرف) تتخطى تحليل LLM للاستعلام بالكامل، حتى في الوضع العميق. الاستعلامات القصيرة مثل "ما قاعدة البيانات التي نستخدمها؟" هي بالفعل عبارات بحث جيدة -- تحليل LLM يضيف قيمة قليلة. هذا يوفر ~1-3 ثوانٍ لكل استرجاع للاستعلامات القصيرة النموذجية. فقط الاستعلامات الأطول (مثل أوصاف المهام الكاملة) تمر عبر تقطير LLM إلى استعلامات فرعية مستهدفة.
|
||||
|
||||
```python
|
||||
# Shallow: pure vector search, no LLM
|
||||
matches = memory.recall("What did we decide?", limit=10, depth="shallow")
|
||||
|
||||
# Deep (default): intelligent retrieval with LLM analysis for long queries
|
||||
matches = memory.recall(
|
||||
"Summarize all architecture decisions from this quarter",
|
||||
limit=10,
|
||||
depth="deep",
|
||||
)
|
||||
```
|
||||
|
||||
عتبات الثقة التي تتحكم في موجّه RecallFlow قابلة للإعداد:
|
||||
|
||||
```python
|
||||
memory = Memory(
|
||||
confidence_threshold_high=0.9, # Only synthesize when very confident
|
||||
confidence_threshold_low=0.4, # Explore deeper more aggressively
|
||||
exploration_budget=2, # Allow up to 2 exploration rounds
|
||||
query_analysis_threshold=200, # Skip LLM for queries shorter than this
|
||||
)
|
||||
```
|
||||
|
||||
|
||||
## إعداد المُضمِّن
|
||||
|
||||
تحتاج الذاكرة إلى نموذج تضمين لتحويل النص إلى متجهات للبحث الدلالي. يمكنك إعداده بثلاث طرق.
|
||||
|
||||
### التمرير إلى Memory مباشرة
|
||||
|
||||
```python
|
||||
from crewai import Memory
|
||||
|
||||
# As a config dict
|
||||
memory = Memory(embedder={"provider": "openai", "config": {"model_name": "text-embedding-3-small"}})
|
||||
|
||||
# As a pre-built callable
|
||||
from crewai.rag.embeddings.factory import build_embedder
|
||||
embedder = build_embedder({"provider": "ollama", "config": {"model_name": "mxbai-embed-large"}})
|
||||
memory = Memory(embedder=embedder)
|
||||
```
|
||||
|
||||
### عبر إعداد مُضمِّن Crew
|
||||
|
||||
عند استخدام `memory=True`، يتم تمرير إعداد `embedder` الخاص بالفريق:
|
||||
|
||||
```python
|
||||
from crewai import Crew
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True,
|
||||
embedder={"provider": "openai", "config": {"model_name": "text-embedding-3-small"}},
|
||||
)
|
||||
```
|
||||
|
||||
### أمثلة المزودين
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="OpenAI (افتراضي)">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model_name": "text-embedding-3-small",
|
||||
# "api_key": "sk-...", # or set OPENAI_API_KEY env var
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Ollama (محلي، خاص)">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "ollama",
|
||||
"config": {
|
||||
"model_name": "mxbai-embed-large",
|
||||
"url": "http://localhost:11434/api/embeddings",
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Azure OpenAI">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "azure",
|
||||
"config": {
|
||||
"deployment_id": "your-embedding-deployment",
|
||||
"api_key": "your-azure-api-key",
|
||||
"api_base": "https://your-resource.openai.azure.com",
|
||||
"api_version": "2024-02-01",
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google AI">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "google-generativeai",
|
||||
"config": {
|
||||
"model_name": "gemini-embedding-001",
|
||||
# "api_key": "...", # or set GOOGLE_API_KEY env var
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Google Vertex AI">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "google-vertex",
|
||||
"config": {
|
||||
"model_name": "gemini-embedding-001",
|
||||
"project_id": "your-gcp-project-id",
|
||||
"location": "us-central1",
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Cohere">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "cohere",
|
||||
"config": {
|
||||
"model_name": "embed-english-v3.0",
|
||||
# "api_key": "...", # or set COHERE_API_KEY env var
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="VoyageAI">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "voyageai",
|
||||
"config": {
|
||||
"model": "voyage-3",
|
||||
# "api_key": "...", # or set VOYAGE_API_KEY env var
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="AWS Bedrock">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "amazon-bedrock",
|
||||
"config": {
|
||||
"model_name": "amazon.titan-embed-text-v1",
|
||||
# Uses default AWS credentials (boto3 session)
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Hugging Face">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "huggingface",
|
||||
"config": {
|
||||
"model_name": "sentence-transformers/all-MiniLM-L6-v2",
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Jina">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "jina",
|
||||
"config": {
|
||||
"model_name": "jina-embeddings-v2-base-en",
|
||||
# "api_key": "...", # or set JINA_API_KEY env var
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="IBM WatsonX">
|
||||
```python
|
||||
memory = Memory(embedder={
|
||||
"provider": "watsonx",
|
||||
"config": {
|
||||
"model_id": "ibm/slate-30m-english-rtrvr",
|
||||
"api_key": "your-watsonx-api-key",
|
||||
"project_id": "your-project-id",
|
||||
"url": "https://us-south.ml.cloud.ibm.com",
|
||||
},
|
||||
})
|
||||
```
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="مُضمِّن مخصص">
|
||||
```python
|
||||
# Pass any callable that takes a list of strings and returns a list of vectors
|
||||
def my_embedder(texts: list[str]) -> list[list[float]]:
|
||||
# Your embedding logic here
|
||||
return [[0.1, 0.2, ...] for _ in texts]
|
||||
|
||||
memory = Memory(embedder=my_embedder)
|
||||
```
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### مرجع المزودين
|
||||
|
||||
| المزود | المفتاح | النموذج النموذجي | ملاحظات |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| OpenAI | `openai` | `text-embedding-3-small` | افتراضي. عيّن `OPENAI_API_KEY`. |
|
||||
| Ollama | `ollama` | `mxbai-embed-large` | محلي، لا حاجة لمفتاح API. |
|
||||
| Azure OpenAI | `azure` | `text-embedding-ada-002` | يتطلب `deployment_id`. |
|
||||
| Google AI | `google-generativeai` | `gemini-embedding-001` | عيّن `GOOGLE_API_KEY`. |
|
||||
| Google Vertex | `google-vertex` | `gemini-embedding-001` | يتطلب `project_id`. |
|
||||
| Cohere | `cohere` | `embed-english-v3.0` | دعم قوي متعدد اللغات. |
|
||||
| VoyageAI | `voyageai` | `voyage-3` | محسّن للاسترجاع. |
|
||||
| AWS Bedrock | `amazon-bedrock` | `amazon.titan-embed-text-v1` | يستخدم بيانات اعتماد boto3. |
|
||||
| Hugging Face | `huggingface` | `all-MiniLM-L6-v2` | sentence-transformers محلي. |
|
||||
| Jina | `jina` | `jina-embeddings-v2-base-en` | عيّن `JINA_API_KEY`. |
|
||||
| IBM WatsonX | `watsonx` | `ibm/slate-30m-english-rtrvr` | يتطلب `project_id`. |
|
||||
| Sentence Transformer | `sentence-transformer` | `all-MiniLM-L6-v2` | محلي، لا حاجة لمفتاح API. |
|
||||
| مخصص | `custom` | -- | يتطلب `embedding_callable`. |
|
||||
|
||||
|
||||
## إعداد LLM
|
||||
|
||||
تستخدم الذاكرة LLM لتحليل الحفظ (استنتاج النطاق والفئات والأهمية)، وقرارات التوحيد، وتحليل استعلام الاسترجاع العميق. يمكنك إعداد النموذج المُستخدم.
|
||||
|
||||
```python
|
||||
from crewai import Memory, LLM
|
||||
|
||||
# Default: gpt-4o-mini
|
||||
memory = Memory()
|
||||
|
||||
# Use a different OpenAI model
|
||||
memory = Memory(llm="gpt-4o")
|
||||
|
||||
# Use Anthropic
|
||||
memory = Memory(llm="anthropic/claude-3-haiku-20240307")
|
||||
|
||||
# Use Ollama for fully local/private analysis
|
||||
memory = Memory(llm="ollama/llama3.2")
|
||||
|
||||
# Use Google Gemini
|
||||
memory = Memory(llm="gemini/gemini-2.0-flash")
|
||||
|
||||
# Pass a pre-configured LLM instance with custom settings
|
||||
llm = LLM(model="gpt-4o", temperature=0)
|
||||
memory = Memory(llm=llm)
|
||||
```
|
||||
|
||||
يتم تهيئة LLM **بشكل كسول** -- يتم إنشاؤه فقط عند الحاجة لأول مرة. هذا يعني أن `Memory()` لا يفشل أبدًا في وقت الإنشاء، حتى لو لم تكن مفاتيح API مُعيّنة. تظهر الأخطاء فقط عند استدعاء LLM فعليًا (مثلاً عند الحفظ بدون نطاق/فئات صريحة، أو أثناء الاسترجاع العميق).
|
||||
|
||||
للتشغيل المحلي/الخاص بالكامل، استخدم نموذجًا محليًا لكل من LLM والمُضمِّن:
|
||||
|
||||
```python
|
||||
memory = Memory(
|
||||
llm="ollama/llama3.2",
|
||||
embedder={"provider": "ollama", "config": {"model_name": "mxbai-embed-large"}},
|
||||
)
|
||||
```
|
||||
|
||||
|
||||
## واجهة التخزين
|
||||
|
||||
- **الافتراضي**: LanceDB، مخزّن تحت `./.crewai/memory` (أو `$CREWAI_STORAGE_DIR/memory` إذا تم تعيين متغير البيئة، أو المسار الذي تمرره كـ `storage="path/to/dir"`).
|
||||
- **واجهة مخصصة**: نفّذ بروتوكول `StorageBackend` (انظر `crewai.memory.storage.backend`) ومرّر مثيلًا إلى `Memory(storage=your_backend)`.
|
||||
|
||||
|
||||
## الاستكشاف
|
||||
|
||||
فحص التسلسل الهرمي للنطاقات والفئات والسجلات:
|
||||
|
||||
```python
|
||||
memory.tree() # Formatted tree of scopes and record counts
|
||||
memory.tree("/project", max_depth=2) # Subtree view
|
||||
memory.info("/project") # ScopeInfo: record_count, categories, oldest/newest
|
||||
memory.list_scopes("/") # Immediate child scopes
|
||||
memory.list_categories() # Category names and counts
|
||||
memory.list_records(scope="/project/alpha", limit=20) # Records in a scope, newest first
|
||||
```
|
||||
|
||||
|
||||
## سلوك الفشل
|
||||
|
||||
إذا فشل LLM أثناء التحليل (خطأ شبكة، حد معدل، استجابة غير صالحة)، تتدهور الذاكرة بسلاسة:
|
||||
|
||||
- **تحليل الحفظ** -- يتم تسجيل تحذير ولا يزال يتم تخزين الذاكرة مع النطاق الافتراضي `/`، فئات فارغة، وأهمية `0.5`.
|
||||
- **استخراج الذكريات** -- يتم تخزين المحتوى الكامل كذاكرة واحدة حتى لا يُفقد شيء.
|
||||
- **تحليل الاستعلام** -- يتراجع الاسترجاع إلى اختيار نطاق بسيط وبحث متجهي حتى تستمر في الحصول على نتائج.
|
||||
|
||||
لا يتم رفع أي استثناء لفشل التحليل هذه؛ فقط فشل التخزين أو المُضمِّن سيرفع استثناءً.
|
||||
|
||||
|
||||
## ملاحظة حول الخصوصية
|
||||
|
||||
يتم إرسال محتوى الذاكرة إلى LLM المُعدّ للتحليل (النطاق/الفئات/الأهمية عند الحفظ، تحليل الاستعلام والاسترجاع العميق الاختياري). للبيانات الحساسة، استخدم LLM محليًا (مثل Ollama) أو تأكد من أن مزودك يلبي متطلبات الامتثال الخاصة بك.
|
||||
|
||||
|
||||
## أحداث الذاكرة
|
||||
|
||||
جميع عمليات الذاكرة تُصدر أحداثًا مع `source_type="unified_memory"`. يمكنك الاستماع للتوقيت والأخطاء والمحتوى.
|
||||
|
||||
| الحدث | الوصف | الخصائص الرئيسية |
|
||||
| :---- | :---------- | :------------- |
|
||||
| **MemoryQueryStartedEvent** | بداية الاستعلام | `query`, `limit` |
|
||||
| **MemoryQueryCompletedEvent** | نجاح الاستعلام | `query`, `results`, `query_time_ms` |
|
||||
| **MemoryQueryFailedEvent** | فشل الاستعلام | `query`, `error` |
|
||||
| **MemorySaveStartedEvent** | بداية الحفظ | `value`, `metadata` |
|
||||
| **MemorySaveCompletedEvent** | نجاح الحفظ | `value`, `save_time_ms` |
|
||||
| **MemorySaveFailedEvent** | فشل الحفظ | `value`, `error` |
|
||||
| **MemoryRetrievalStartedEvent** | بداية استرجاع الوكيل | `task_id` |
|
||||
| **MemoryRetrievalCompletedEvent** | اكتمال استرجاع الوكيل | `task_id`, `memory_content`, `retrieval_time_ms` |
|
||||
|
||||
مثال: مراقبة وقت الاستعلام:
|
||||
|
||||
```python
|
||||
from crewai.events import BaseEventListener, MemoryQueryCompletedEvent
|
||||
|
||||
class MemoryMonitor(BaseEventListener):
|
||||
def setup_listeners(self, crewai_event_bus):
|
||||
@crewai_event_bus.on(MemoryQueryCompletedEvent)
|
||||
def on_done(source, event):
|
||||
if getattr(event, "source_type", None) == "unified_memory":
|
||||
print(f"Query '{event.query}' completed in {event.query_time_ms:.0f}ms")
|
||||
```
|
||||
|
||||
|
||||
## استكشاف المشاكل
|
||||
|
||||
**الذاكرة لا تستمر؟**
|
||||
- تأكد من أن مسار التخزين قابل للكتابة (الافتراضي `./.crewai/memory`). مرّر `storage="./your_path"` لاستخدام مجلد مختلف، أو عيّن متغير البيئة `CREWAI_STORAGE_DIR`.
|
||||
- عند استخدام فريق، تأكد من تعيين `memory=True` أو `memory=Memory(...)`.
|
||||
|
||||
**الاسترجاع بطيء؟**
|
||||
- استخدم `depth="shallow"` لسياق الوكيل الروتيني. احتفظ بـ `depth="deep"` للاستعلامات المعقدة.
|
||||
- زد `query_analysis_threshold` لتخطي تحليل LLM لمزيد من الاستعلامات.
|
||||
|
||||
**أخطاء تحليل LLM في السجلات؟**
|
||||
- لا تزال الذاكرة تحفظ/تسترجع بإعدادات افتراضية آمنة. تحقق من مفاتيح API وحدود المعدل وتوفر النموذج إذا كنت تريد تحليل LLM كاملاً.
|
||||
|
||||
**أخطاء حفظ خلفية في السجلات؟**
|
||||
- عمليات حفظ الذاكرة تعمل في خيط خلفي. تُصدر الأخطاء كـ `MemorySaveFailedEvent` لكنها لا تعطل الوكيل. تحقق من السجلات للسبب الجذري (عادة مشاكل اتصال LLM أو المُضمِّن).
|
||||
|
||||
**تعارضات الكتابة المتزامنة؟**
|
||||
- عمليات LanceDB مُتسلسلة بقفل مشترك وتُعاد تلقائيًا عند التعارض. هذا يتعامل مع مثيلات `Memory` المتعددة التي تشير إلى نفس قاعدة البيانات (مثل ذاكرة وكيل + ذاكرة فريق). لا حاجة لإجراء.
|
||||
|
||||
**تصفح الذاكرة من الطرفية:**
|
||||
```bash
|
||||
crewai memory # Opens the TUI browser
|
||||
crewai memory --storage-path ./my_memory # Point to a specific directory
|
||||
```
|
||||
|
||||
**إعادة تعيين الذاكرة (مثلاً للاختبارات):**
|
||||
```python
|
||||
crew.reset_memories(command_type="memory") # Resets unified memory
|
||||
# Or on a Memory instance:
|
||||
memory.reset() # All scopes
|
||||
memory.reset(scope="/project/old") # Only that subtree
|
||||
```
|
||||
|
||||
|
||||
## مرجع الإعداد
|
||||
|
||||
جميع الإعدادات تُمرر كمعاملات كلمة مفتاحية إلى `Memory(...)`. كل معامل له قيمة افتراضية معقولة.
|
||||
|
||||
| المعامل | الافتراضي | الوصف |
|
||||
| :--- | :--- | :--- |
|
||||
| `llm` | `"gpt-4o-mini"` | LLM للتحليل (اسم نموذج أو مثيل `BaseLLM`). |
|
||||
| `storage` | `"lancedb"` | واجهة التخزين (`"lancedb"`، سلسلة مسار، أو مثيل `StorageBackend`). |
|
||||
| `embedder` | `None` (افتراضي OpenAI) | المُضمِّن (قاموس إعداد، دالة قابلة للاستدعاء، أو `None` لافتراضي OpenAI). |
|
||||
| `recency_weight` | `0.3` | وزن الحداثة في الدرجة المركبة. |
|
||||
| `semantic_weight` | `0.5` | وزن التشابه الدلالي في الدرجة المركبة. |
|
||||
| `importance_weight` | `0.2` | وزن الأهمية في الدرجة المركبة. |
|
||||
| `recency_half_life_days` | `30` | أيام لتنصيف درجة الحداثة (اضمحلال أُسي). |
|
||||
| `consolidation_threshold` | `0.85` | التشابه الذي يُشغّل فوقه التوحيد عند الحفظ. عيّن إلى `1.0` للتعطيل. |
|
||||
| `consolidation_limit` | `5` | أقصى عدد سجلات حالية للمقارنة أثناء التوحيد. |
|
||||
| `default_importance` | `0.5` | الأهمية المُعيّنة عندما لا تُوفَّر ويتم تخطي تحليل LLM. |
|
||||
| `batch_dedup_threshold` | `0.98` | تشابه جيب التمام لإسقاط النسخ شبه المكررة داخل دفعة `remember_many()`. |
|
||||
| `confidence_threshold_high` | `0.8` | ثقة الاسترجاع التي تُعاد فوقها النتائج مباشرة. |
|
||||
| `confidence_threshold_low` | `0.5` | ثقة الاسترجاع التي يُشغّل تحتها استكشاف أعمق. |
|
||||
| `complex_query_threshold` | `0.7` | للاستعلامات المعقدة، استكشف أعمق تحت هذه الثقة. |
|
||||
| `exploration_budget` | `1` | عدد جولات الاستكشاف المدفوعة بـ LLM أثناء الاسترجاع العميق. |
|
||||
| `query_analysis_threshold` | `200` | الاستعلامات الأقصر من هذا (بالأحرف) تتخطى تحليل LLM أثناء الاسترجاع العميق. |
|
||||
155
docs/v1.15.2/ar/concepts/planning.mdx
Normal file
@@ -0,0 +1,155 @@
|
||||
---
|
||||
title: التخطيط
|
||||
description: تعرّف على كيفية إضافة التخطيط إلى طاقم CrewAI وتحسين أدائه.
|
||||
icon: ruler-combined
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
تتيح لك ميزة التخطيط في CrewAI إضافة قدرة التخطيط إلى طاقمك. عند تفعيلها، قبل كل تكرار للطاقم،
|
||||
يتم إرسال جميع معلومات الطاقم إلى AgentPlanner الذي يخطط للمهام خطوة بخطوة، ويُضاف هذا المخطط إلى وصف كل مهمة.
|
||||
|
||||
### استخدام ميزة التخطيط
|
||||
|
||||
البدء بميزة التخطيط سهل جدًا، الخطوة الوحيدة المطلوبة هي إضافة `planning=True` إلى طاقمك:
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
# تجميع طاقمك مع قدرات التخطيط
|
||||
my_crew = Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
planning=True,
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
من هذه النقطة فصاعدًا، سيكون التخطيط مفعّلًا في طاقمك، وسيتم تخطيط المهام قبل كل تكرار.
|
||||
|
||||
<Warning>
|
||||
عند تفعيل التخطيط، سيستخدم CrewAI `gpt-4o-mini` كنموذج LLM افتراضي للتخطيط، مما يتطلب مفتاح API صالحًا من OpenAI. نظرًا لأن وكلاءك قد يستخدمون نماذج LLM مختلفة، فقد يسبب ذلك ارتباكًا إذا لم يكن لديك مفتاح OpenAI API مهيأ أو إذا كنت تواجه سلوكًا غير متوقع متعلقًا باستدعاءات LLM API.
|
||||
</Warning>
|
||||
|
||||
#### LLM التخطيط
|
||||
|
||||
يمكنك الآن تحديد نموذج LLM الذي سيُستخدم لتخطيط المهام.
|
||||
|
||||
عند تشغيل مثال الحالة الأساسية، سترى شيئًا مشابهًا للمخرجات أدناه، والتي تمثل مخرجات `AgentPlanner`
|
||||
المسؤول عن إنشاء المنطق التدريجي لإضافته إلى مهام الوكلاء.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task, Process
|
||||
|
||||
# تجميع طاقمك مع قدرات التخطيط ونموذج LLM مخصص
|
||||
my_crew = Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
planning=True,
|
||||
planning_llm="gpt-4o"
|
||||
)
|
||||
|
||||
# تشغيل الطاقم
|
||||
my_crew.kickoff()
|
||||
```
|
||||
|
||||
```markdown Result
|
||||
[2024-07-15 16:49:11][INFO]: Planning the crew execution
|
||||
**Step-by-Step Plan for Task Execution**
|
||||
|
||||
**Task Number 1: Conduct a thorough research about AI LLMs**
|
||||
|
||||
**Agent:** AI LLMs Senior Data Researcher
|
||||
|
||||
**Agent Goal:** Uncover cutting-edge developments in AI LLMs
|
||||
|
||||
**Task Expected Output:** A list with 10 bullet points of the most relevant information about AI LLMs
|
||||
|
||||
**Task Tools:** None specified
|
||||
|
||||
**Agent Tools:** None specified
|
||||
|
||||
**Step-by-Step Plan:**
|
||||
|
||||
1. **Define Research Scope:**
|
||||
|
||||
- Determine the specific areas of AI LLMs to focus on, such as advancements in architecture, use cases, ethical considerations, and performance metrics.
|
||||
|
||||
2. **Identify Reliable Sources:**
|
||||
|
||||
- List reputable sources for AI research, including academic journals, industry reports, conferences (e.g., NeurIPS, ACL), AI research labs (e.g., OpenAI, Google AI), and online databases (e.g., IEEE Xplore, arXiv).
|
||||
|
||||
3. **Collect Data:**
|
||||
|
||||
- Search for the latest papers, articles, and reports published in 2024 and early 2025.
|
||||
- Use keywords like "Large Language Models 2025", "AI LLM advancements", "AI ethics 2025", etc.
|
||||
|
||||
4. **Analyze Findings:**
|
||||
|
||||
- Read and summarize the key points from each source.
|
||||
- Highlight new techniques, models, and applications introduced in the past year.
|
||||
|
||||
5. **Organize Information:**
|
||||
|
||||
- Categorize the information into relevant topics (e.g., new architectures, ethical implications, real-world applications).
|
||||
- Ensure each bullet point is concise but informative.
|
||||
|
||||
6. **Create the List:**
|
||||
|
||||
- Compile the 10 most relevant pieces of information into a bullet point list.
|
||||
- Review the list to ensure clarity and relevance.
|
||||
|
||||
**Expected Output:**
|
||||
|
||||
A list with 10 bullet points of the most relevant information about AI LLMs.
|
||||
|
||||
---
|
||||
|
||||
**Task Number 2: Review the context you got and expand each topic into a full section for a report**
|
||||
|
||||
**Agent:** AI LLMs Reporting Analyst
|
||||
|
||||
**Agent Goal:** Create detailed reports based on AI LLMs data analysis and research findings
|
||||
|
||||
**Task Expected Output:** A fully fledged report with the main topics, each with a full section of information. Formatted as markdown without '```'
|
||||
|
||||
**Task Tools:** None specified
|
||||
|
||||
**Agent Tools:** None specified
|
||||
|
||||
**Step-by-Step Plan:**
|
||||
|
||||
1. **Review the Bullet Points:**
|
||||
- Carefully read through the list of 10 bullet points provided by the AI LLMs Senior Data Researcher.
|
||||
|
||||
2. **Outline the Report:**
|
||||
- Create an outline with each bullet point as a main section heading.
|
||||
- Plan sub-sections under each main heading to cover different aspects of the topic.
|
||||
|
||||
3. **Research Further Details:**
|
||||
- For each bullet point, conduct additional research if necessary to gather more detailed information.
|
||||
- Look for case studies, examples, and statistical data to support each section.
|
||||
|
||||
4. **Write Detailed Sections:**
|
||||
- Expand each bullet point into a comprehensive section.
|
||||
- Ensure each section includes an introduction, detailed explanation, examples, and a conclusion.
|
||||
- Use markdown formatting for headings, subheadings, lists, and emphasis.
|
||||
|
||||
5. **Review and Edit:**
|
||||
- Proofread the report for clarity, coherence, and correctness.
|
||||
- Make sure the report flows logically from one section to the next.
|
||||
- Format the report according to markdown standards.
|
||||
|
||||
6. **Finalize the Report:**
|
||||
- Ensure the report is complete with all sections expanded and detailed.
|
||||
- Double-check formatting and make any necessary adjustments.
|
||||
|
||||
**Expected Output:**
|
||||
A fully fledged report with the main topics, each with a full section of information. Formatted as markdown without '```'.
|
||||
```
|
||||
</CodeGroup>
|
||||
66
docs/v1.15.2/ar/concepts/processes.mdx
Normal file
@@ -0,0 +1,66 @@
|
||||
---
|
||||
title: العمليات
|
||||
description: دليل تفصيلي حول إدارة سير العمل من خلال العمليات في CrewAI، مع تفاصيل التنفيذ المحدّثة.
|
||||
icon: bars-staggered
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
<Tip>
|
||||
تنسّق العمليات تنفيذ المهام بواسطة الوكلاء، على غرار إدارة المشاريع في الفرق البشرية.
|
||||
تضمن هذه العمليات توزيع المهام وتنفيذها بكفاءة، وفقًا لاستراتيجية محددة مسبقًا.
|
||||
</Tip>
|
||||
|
||||
## تنفيذات العمليات
|
||||
|
||||
- **تسلسلي**: ينفذ المهام بالتتابع، مما يضمن إكمال المهام بتقدم منظم.
|
||||
- **هرمي**: ينظم المهام في تسلسل إداري هرمي، حيث يتم تفويض المهام وتنفيذها بناءً على سلسلة أوامر منظمة. يجب تحديد نموذج لغة المدير (`manager_llm`) أو وكيل مدير مخصص (`manager_agent`) في الطاقم لتفعيل العملية الهرمية، مما يسهّل إنشاء وإدارة المهام من قبل المدير.
|
||||
|
||||
## دور العمليات في العمل الجماعي
|
||||
تُمكّن العمليات الوكلاء الأفراد من العمل كوحدة متماسكة، مما يبسّط جهودهم لتحقيق أهداف مشتركة بكفاءة وتناسق.
|
||||
|
||||
## تعيين العمليات للطاقم
|
||||
لتعيين عملية لطاقم، حدد نوع العملية عند إنشاء الطاقم لتعيين استراتيجية التنفيذ. للعملية الهرمية، تأكد من تحديد `manager_llm` أو `manager_agent` لوكيل المدير.
|
||||
|
||||
```python
|
||||
from crewai import Crew, Process
|
||||
|
||||
# مثال: إنشاء طاقم بعملية تسلسلية
|
||||
crew = Crew(
|
||||
agents=my_agents,
|
||||
tasks=my_tasks,
|
||||
process=Process.sequential
|
||||
)
|
||||
|
||||
# مثال: إنشاء طاقم بعملية هرمية
|
||||
# تأكد من توفير manager_llm أو manager_agent
|
||||
crew = Crew(
|
||||
agents=my_agents,
|
||||
tasks=my_tasks,
|
||||
process=Process.hierarchical,
|
||||
manager_llm="gpt-4o"
|
||||
# أو
|
||||
# manager_agent=my_manager_agent
|
||||
)
|
||||
```
|
||||
**ملاحظة:** تأكد من تعريف `my_agents` و `my_tasks` قبل إنشاء كائن `Crew`، وللعملية الهرمية، يُعد `manager_llm` أو `manager_agent` مطلوبًا أيضًا.
|
||||
|
||||
## العملية التسلسلية
|
||||
|
||||
تعكس هذه الطريقة سير عمل الفريق الديناميكي، وتتقدم عبر المهام بطريقة مدروسة ومنهجية. يتبع تنفيذ المهام الترتيب المحدد مسبقًا في قائمة المهام، حيث يعمل ناتج مهمة واحدة كسياق للمهمة التالية.
|
||||
|
||||
لتخصيص سياق المهمة، استخدم معامل `context` في فئة `Task` لتحديد المخرجات التي يجب استخدامها كسياق للمهام اللاحقة.
|
||||
|
||||
## العملية الهرمية
|
||||
|
||||
تحاكي التسلسل الهرمي المؤسسي، حيث يسمح CrewAI بتحديد وكيل مدير مخصص أو إنشاء واحد تلقائيًا، مما يتطلب تحديد نموذج لغة المدير (`manager_llm`). يشرف هذا الوكيل على تنفيذ المهام، بما في ذلك التخطيط والتفويض والتحقق. لا يتم تعيين المهام مسبقًا؛ يخصص المدير المهام للوكلاء بناءً على قدراتهم، ويراجع المخرجات، ويقيّم اكتمال المهام.
|
||||
|
||||
## فئة Process: نظرة عامة مفصلة
|
||||
|
||||
تم تنفيذ فئة `Process` كتعداد (`Enum`)، مما يضمن أمان الأنواع ويقيّد قيم العملية على الأنواع المحددة (`sequential`، `hierarchical`).
|
||||
|
||||
## الخلاصة
|
||||
|
||||
التعاون المنظم الذي تسهّله العمليات داخل CrewAI ضروري لتمكين العمل الجماعي المنهجي بين الوكلاء.
|
||||
تم تحديث هذه الوثائق لتعكس أحدث الميزات والتحسينات، مما يضمن وصول المستخدمين إلى أحدث المعلومات وأكثرها شمولاً.
|
||||
162
docs/v1.15.2/ar/concepts/production-architecture.mdx
Normal file
@@ -0,0 +1,162 @@
|
||||
---
|
||||
title: بنية الإنتاج
|
||||
description: أفضل الممارسات لبناء تطبيقات ذكاء اصطناعي جاهزة للإنتاج مع CrewAI
|
||||
icon: server
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
# عقلية التدفق أولاً
|
||||
|
||||
عند بناء تطبيقات ذكاء اصطناعي إنتاجية مع CrewAI، **نوصي بالبدء بتدفق (Flow)**.
|
||||
|
||||
بينما يمكن تشغيل أطقم أو وكلاء فرديين، فإن تغليفهم في تدفق يوفر الهيكل اللازم لتطبيق متين وقابل للتوسع.
|
||||
|
||||
## لماذا التدفقات؟
|
||||
|
||||
1. **إدارة الحالة**: توفر التدفقات طريقة مدمجة لإدارة الحالة عبر مراحل مختلفة من تطبيقك. هذا ضروري لتمرير البيانات بين الأطقم والحفاظ على السياق ومعالجة مدخلات المستخدم.
|
||||
2. **التحكم**: تتيح لك التدفقات تحديد مسارات تنفيذ دقيقة، بما في ذلك الحلقات والشرطيات ومنطق التفريع. هذا أساسي لمعالجة الحالات الاستثنائية وضمان سلوك تطبيقك بشكل متوقع.
|
||||
3. **المراقبة**: توفر التدفقات هيكلًا واضحًا يسهّل تتبع التنفيذ وتصحيح الأخطاء ومراقبة الأداء. نوصي باستخدام [تتبع CrewAI](/ar/observability/tracing) للحصول على رؤى تفصيلية. ما عليك سوى تشغيل `crewai login` لتفعيل ميزات المراقبة المجانية.
|
||||
|
||||
## البنية
|
||||
|
||||
يبدو تطبيق CrewAI الإنتاجي النموذجي هكذا:
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Start((Start)) --> Flow[Flow Orchestrator]
|
||||
Flow --> State{State Management}
|
||||
State --> Step1[Step 1: Data Gathering]
|
||||
Step1 --> Crew1[Research Crew]
|
||||
Crew1 --> State
|
||||
State --> Step2{Condition Check}
|
||||
Step2 -- "Valid" --> Step3[Step 3: Execution]
|
||||
Step3 --> Crew2[Action Crew]
|
||||
Step2 -- "Invalid" --> End((End))
|
||||
Crew2 --> End
|
||||
```
|
||||
|
||||
### 1. فئة التدفق
|
||||
فئة `Flow` هي نقطة الدخول. تحدد مخطط الحالة والطرق التي تنفذ منطقك.
|
||||
|
||||
```python
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from pydantic import BaseModel
|
||||
|
||||
class AppState(BaseModel):
|
||||
user_input: str = ""
|
||||
research_results: str = ""
|
||||
final_report: str = ""
|
||||
|
||||
class ProductionFlow(Flow[AppState]):
|
||||
@start()
|
||||
def gather_input(self):
|
||||
# ... منطق الحصول على المدخلات ...
|
||||
pass
|
||||
|
||||
@listen(gather_input)
|
||||
def run_research_crew(self):
|
||||
# ... تشغيل طاقم ...
|
||||
pass
|
||||
```
|
||||
|
||||
### 2. إدارة الحالة
|
||||
استخدم نماذج Pydantic لتعريف حالتك. يضمن هذا أمان الأنواع ويوضح البيانات المتاحة في كل مرحلة.
|
||||
|
||||
- **اجعلها بسيطة**: خزّن فقط ما تحتاجه للاستمرار بين المراحل.
|
||||
- **استخدم بيانات منظمة**: تجنب القواميس غير المنظمة قدر الإمكان.
|
||||
|
||||
### 3. الأطقم كوحدات عمل
|
||||
فوّض المهام المعقدة إلى الأطقم. يجب أن يكون الطاقم مركّزًا على هدف محدد (مثل "البحث في موضوع"، "كتابة مقال مدونة").
|
||||
|
||||
- **لا تبالغ في هندسة الأطقم**: اجعلها مركّزة.
|
||||
- **مرر الحالة بشكل صريح**: مرر البيانات الضرورية من حالة التدفق إلى مدخلات الطاقم.
|
||||
|
||||
```python
|
||||
@listen(gather_input)
|
||||
def run_research_crew(self):
|
||||
crew = ResearchCrew()
|
||||
result = crew.kickoff(inputs={"topic": self.state.user_input})
|
||||
self.state.research_results = result.raw
|
||||
```
|
||||
|
||||
## عناصر التحكم الأولية
|
||||
|
||||
استفد من عناصر التحكم الأولية في CrewAI لإضافة المتانة والتحكم إلى أطقمك.
|
||||
|
||||
### 1. حواجز المهام
|
||||
استخدم [حواجز المهام](/ar/concepts/tasks#task-guardrails) للتحقق من مخرجات المهام قبل قبولها. يضمن هذا أن وكلاءك ينتجون نتائج عالية الجودة.
|
||||
|
||||
```python
|
||||
def validate_content(result: TaskOutput) -> Tuple[bool, Any]:
|
||||
if len(result.raw) < 100:
|
||||
return (False, "Content is too short. Please expand.")
|
||||
return (True, result.raw)
|
||||
|
||||
task = Task(
|
||||
...,
|
||||
guardrail=validate_content
|
||||
)
|
||||
```
|
||||
|
||||
### 2. المخرجات المنظمة
|
||||
استخدم دائمًا المخرجات المنظمة (`output_pydantic` أو `output_json`) عند تمرير البيانات بين المهام أو إلى تطبيقك. يمنع هذا أخطاء التحليل ويضمن أمان الأنواع.
|
||||
|
||||
```python
|
||||
class ResearchResult(BaseModel):
|
||||
summary: str
|
||||
sources: List[str]
|
||||
|
||||
task = Task(
|
||||
...,
|
||||
output_pydantic=ResearchResult
|
||||
)
|
||||
```
|
||||
|
||||
### 3. خطافات LLM
|
||||
استخدم [خطافات LLM](/ar/learn/llm-hooks) لفحص أو تعديل الرسائل قبل إرسالها إلى LLM، أو لتنقية الاستجابات.
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def log_request(context):
|
||||
print(f"Agent {context.agent.role} is calling the LLM...")
|
||||
```
|
||||
|
||||
## أنماط النشر
|
||||
|
||||
عند نشر تدفقك، ضع في اعتبارك ما يلي:
|
||||
|
||||
### CrewAI Enterprise
|
||||
أسهل طريقة لنشر تدفقك هي استخدام CrewAI Enterprise. تتعامل مع البنية التحتية والمصادقة والمراقبة نيابة عنك.
|
||||
|
||||
راجع [دليل النشر](/ar/enterprise/guides/deploy-to-amp) للبدء.
|
||||
|
||||
```bash
|
||||
crewai deploy create
|
||||
```
|
||||
|
||||
### التنفيذ غير المتزامن
|
||||
للمهام طويلة التشغيل، استخدم `kickoff_async` لتجنب حظر واجهتك البرمجية.
|
||||
|
||||
### الاستمرارية
|
||||
استخدم مزيّن `@persist` لحفظ حالة تدفقك في قاعدة بيانات. يتيح لك هذا استئناف التنفيذ إذا تعطلت العملية أو إذا كنت بحاجة لانتظار مدخلات بشرية.
|
||||
|
||||
```python
|
||||
@persist
|
||||
class ProductionFlow(Flow[AppState]):
|
||||
# ...
|
||||
```
|
||||
|
||||
افتراضيًا، يستأنف `@persist` تدفقًا عند توفير `kickoff(inputs={"id": <uuid>})`، مما يمدّ نفس تاريخ `flow_uuid`. لـ **تفرع** تدفق مستمر إلى نسبٍ جديد — ترطيب الحالة من تشغيل سابق ولكن الكتابة تحت `state.id` جديد — مرّر `restore_from_state_id`:
|
||||
|
||||
```python
|
||||
flow.kickoff(restore_from_state_id="<previous-run-state-id>")
|
||||
```
|
||||
|
||||
يحصل التشغيل الجديد على `state.id` جديد (مولّد تلقائيًا، أو `inputs["id"]` إذا تم تثبيته) لذا لا تمتد كتابات `@persist` الخاصة به إلى تاريخ المصدر. الجمع مع `from_checkpoint` يطلق `ValueError`؛ اختر مصدر ترطيب واحدًا.
|
||||
|
||||
## الخلاصة
|
||||
|
||||
- **ابدأ بتدفق.**
|
||||
- **حدد حالة واضحة.**
|
||||
- **استخدم الأطقم للمهام المعقدة.**
|
||||
- **انشر مع API واستمرارية.**
|
||||
148
docs/v1.15.2/ar/concepts/reasoning.mdx
Normal file
@@ -0,0 +1,148 @@
|
||||
---
|
||||
title: الاستدلال
|
||||
description: "تعرّف على كيفية تفعيل واستخدام استدلال الوكيل لتحسين تنفيذ المهام."
|
||||
icon: brain
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
استدلال الوكيل هو ميزة تتيح للوكلاء التأمل في المهمة وإنشاء خطة قبل التنفيذ. يساعد هذا الوكلاء على التعامل مع المهام بشكل أكثر منهجية ويضمن استعدادهم لأداء العمل المطلوب.
|
||||
|
||||
## الاستخدام
|
||||
|
||||
لتفعيل الاستدلال لوكيل، ما عليك سوى تعيين `reasoning=True` عند إنشاء الوكيل:
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze complex datasets and provide insights",
|
||||
backstory="You are an experienced data analyst with expertise in finding patterns in complex data.",
|
||||
reasoning=True, # تفعيل الاستدلال
|
||||
max_reasoning_attempts=3 # اختياري: تعيين حد أقصى لمحاولات الاستدلال
|
||||
)
|
||||
```
|
||||
|
||||
## كيف يعمل
|
||||
|
||||
عند تفعيل الاستدلال، قبل تنفيذ المهمة، سيقوم الوكيل بما يلي:
|
||||
|
||||
1. التأمل في المهمة وإنشاء خطة مفصلة
|
||||
2. تقييم ما إذا كان مستعدًا لتنفيذ المهمة
|
||||
3. تحسين الخطة حسب الحاجة حتى يصبح مستعدًا أو يصل إلى max_reasoning_attempts
|
||||
4. حقن خطة الاستدلال في وصف المهمة قبل التنفيذ
|
||||
|
||||
تساعد هذه العملية الوكيل على تقسيم المهام المعقدة إلى خطوات يمكن إدارتها وتحديد التحديات المحتملة قبل البدء.
|
||||
|
||||
## خيارات التهيئة
|
||||
|
||||
<ParamField body="reasoning" type="bool" default="False">
|
||||
تفعيل أو تعطيل الاستدلال
|
||||
</ParamField>
|
||||
|
||||
<ParamField body="max_reasoning_attempts" type="int" default="None">
|
||||
الحد الأقصى لعدد المحاولات لتحسين الخطة قبل المتابعة بالتنفيذ. إذا كانت القيمة None (الافتراضي)، سيستمر الوكيل في التحسين حتى يصبح مستعدًا.
|
||||
</ParamField>
|
||||
|
||||
## مثال
|
||||
|
||||
إليك مثالًا كاملًا:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
# إنشاء وكيل مع تفعيل الاستدلال
|
||||
analyst = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze data and provide insights",
|
||||
backstory="You are an expert data analyst.",
|
||||
reasoning=True,
|
||||
max_reasoning_attempts=3 # اختياري: تعيين حد لمحاولات الاستدلال
|
||||
)
|
||||
|
||||
# إنشاء مهمة
|
||||
analysis_task = Task(
|
||||
description="Analyze the provided sales data and identify key trends.",
|
||||
expected_output="A report highlighting the top 3 sales trends.",
|
||||
agent=analyst
|
||||
)
|
||||
|
||||
# إنشاء طاقم وتشغيل المهمة
|
||||
crew = Crew(agents=[analyst], tasks=[analysis_task])
|
||||
result = crew.kickoff()
|
||||
|
||||
print(result)
|
||||
```
|
||||
|
||||
## معالجة الأخطاء
|
||||
|
||||
صُممت عملية الاستدلال لتكون متينة، مع معالجة أخطاء مدمجة. إذا حدث خطأ أثناء الاستدلال، سيتابع الوكيل تنفيذ المهمة بدون خطة الاستدلال. يضمن هذا إمكانية تنفيذ المهام حتى في حالة فشل عملية الاستدلال.
|
||||
|
||||
إليك كيفية التعامل مع الأخطاء المحتملة في الكود الخاص بك:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task
|
||||
import logging
|
||||
|
||||
# إعداد التسجيل لالتقاط أي أخطاء في الاستدلال
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
# إنشاء وكيل مع تفعيل الاستدلال
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze data and provide insights",
|
||||
reasoning=True,
|
||||
max_reasoning_attempts=3
|
||||
)
|
||||
|
||||
# إنشاء مهمة
|
||||
task = Task(
|
||||
description="Analyze the provided sales data and identify key trends.",
|
||||
expected_output="A report highlighting the top 3 sales trends.",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# تنفيذ المهمة
|
||||
# إذا حدث خطأ أثناء الاستدلال، سيتم تسجيله وسيستمر التنفيذ
|
||||
result = agent.execute_task(task)
|
||||
```
|
||||
|
||||
## مثال على مخرجات الاستدلال
|
||||
|
||||
إليك مثالًا على شكل خطة الاستدلال لمهمة تحليل البيانات:
|
||||
|
||||
```
|
||||
Task: Analyze the provided sales data and identify key trends.
|
||||
|
||||
Reasoning Plan:
|
||||
I'll analyze the sales data to identify the top 3 trends.
|
||||
|
||||
1. Understanding of the task:
|
||||
I need to analyze sales data to identify key trends that would be valuable for business decision-making.
|
||||
|
||||
2. Key steps I'll take:
|
||||
- First, I'll examine the data structure to understand what fields are available
|
||||
- Then I'll perform exploratory data analysis to identify patterns
|
||||
- Next, I'll analyze sales by time periods to identify temporal trends
|
||||
- I'll also analyze sales by product categories and customer segments
|
||||
- Finally, I'll identify the top 3 most significant trends
|
||||
|
||||
3. Approach to challenges:
|
||||
- If the data has missing values, I'll decide whether to fill or filter them
|
||||
- If the data has outliers, I'll investigate whether they're valid data points or errors
|
||||
- If trends aren't immediately obvious, I'll apply statistical methods to uncover patterns
|
||||
|
||||
4. Use of available tools:
|
||||
- I'll use data analysis tools to explore and visualize the data
|
||||
- I'll use statistical tools to identify significant patterns
|
||||
- I'll use knowledge retrieval to access relevant information about sales analysis
|
||||
|
||||
5. Expected outcome:
|
||||
A concise report highlighting the top 3 sales trends with supporting evidence from the data.
|
||||
|
||||
READY: I am ready to execute the task.
|
||||
```
|
||||
|
||||
تساعد خطة الاستدلال هذه الوكيل على تنظيم نهجه تجاه المهمة، والنظر في التحديات المحتملة، وضمان تقديم المخرجات المتوقعة.
|
||||
306
docs/v1.15.2/ar/concepts/skills.mdx
Normal file
@@ -0,0 +1,306 @@
|
||||
---
|
||||
title: المهارات
|
||||
description: حزم المهارات المبنية على نظام الملفات التي تحقن خبرة المجال والتعليمات في إرشادات الوكلاء.
|
||||
icon: bolt
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
المهارات هي مجلدات مستقلة توفر للوكلاء **تعليمات وإرشادات ومواد مرجعية خاصة بالمجال**. تُعرّف كل مهارة بملف `SKILL.md` يحتوي على بيانات وصفية YAML ومحتوى Markdown.
|
||||
|
||||
عند التفعيل، يتم حقن تعليمات المهارة مباشرة في إرشادات مهمة الوكيل — مما يمنح الوكيل خبرة دون الحاجة لأي تغييرات في الكود.
|
||||
|
||||
<Note type="info" title="المهارات مقابل الأدوات — التمييز الأساسي">
|
||||
**المهارات ليست أدوات.** هذه هي نقطة الارتباك الأكثر شيوعًا.
|
||||
|
||||
- **المهارات** تحقن *تعليمات وسياق* في إرشادات الوكيل. تخبر الوكيل *كيف يفكر* في مشكلة ما.
|
||||
- **الأدوات** تمنح الوكيل *دوال قابلة للاستدعاء* لاتخاذ إجراءات (البحث، قراءة الملفات، استدعاء APIs).
|
||||
|
||||
غالبًا ما تحتاج **كليهما**: مهارات للخبرة، وأدوات للإجراء. يتم تكوينهما بشكل مستقل ويُكمّلان بعضهما.
|
||||
</Note>
|
||||
|
||||
---
|
||||
|
||||
## البداية السريعة
|
||||
|
||||
### 1. إنشاء مجلد المهارة
|
||||
|
||||
```
|
||||
skills/
|
||||
└── code-review/
|
||||
├── SKILL.md # مطلوب — التعليمات
|
||||
├── references/ # اختياري — مستندات مرجعية
|
||||
│ └── style-guide.md
|
||||
└── scripts/ # اختياري — سكربتات قابلة للتنفيذ
|
||||
```
|
||||
|
||||
### 2. كتابة SKILL.md الخاص بك
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: code-review
|
||||
description: Guidelines for conducting thorough code reviews with focus on security and performance.
|
||||
metadata:
|
||||
author: your-team
|
||||
version: "1.0"
|
||||
---
|
||||
|
||||
## إرشادات مراجعة الكود
|
||||
|
||||
عند مراجعة الكود، اتبع قائمة التحقق هذه:
|
||||
|
||||
1. **الأمان**: تحقق من ثغرات الحقن وتجاوز المصادقة وكشف البيانات
|
||||
2. **الأداء**: ابحث عن استعلامات N+1 والتخصيصات غير الضرورية والاستدعاءات المحظورة
|
||||
3. **القابلية للقراءة**: تأكد من وضوح التسمية والتعليقات المناسبة والأسلوب المتسق
|
||||
4. **الاختبارات**: تحقق من تغطية اختبار كافية للوظائف الجديدة
|
||||
|
||||
### مستويات الخطورة
|
||||
- **حرج**: ثغرات أمنية، مخاطر فقدان البيانات → حظر الدمج
|
||||
- **رئيسي**: مشاكل أداء، أخطاء منطقية → طلب تغييرات
|
||||
- **ثانوي**: مسائل أسلوبية، اقتراحات تسمية → الموافقة مع تعليقات
|
||||
```
|
||||
|
||||
### 3. ربطها بوكيل
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
from crewai_tools import GithubSearchTool, FileReadTool
|
||||
|
||||
reviewer = Agent(
|
||||
role="Senior Code Reviewer",
|
||||
goal="Review pull requests for quality and security issues",
|
||||
backstory="Staff engineer with expertise in secure coding practices.",
|
||||
skills=["./skills"], # يحقن إرشادات المراجعة
|
||||
tools=[GithubSearchTool(), FileReadTool()], # يسمح للوكيل بقراءة الكود
|
||||
)
|
||||
```
|
||||
|
||||
الوكيل الآن لديه **خبرة** (من المهارة) و**قدرات** (من الأدوات) معًا.
|
||||
|
||||
---
|
||||
|
||||
## المهارات + الأدوات: العمل معًا
|
||||
|
||||
إليك أنماط شائعة توضح كيف تُكمّل المهارات والأدوات بعضهما:
|
||||
|
||||
### النمط 1: مهارات فقط (خبرة المجال، بدون إجراءات مطلوبة)
|
||||
|
||||
استخدم عندما يحتاج الوكيل لتعليمات محددة لكن لا يحتاج لاستدعاء خدمات خارجية:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Technical Writer",
|
||||
goal="Write clear API documentation",
|
||||
backstory="Expert technical writer",
|
||||
skills=["./skills/api-docs-style"], # إرشادات وقوالب الكتابة
|
||||
# لا حاجة لأدوات — الوكيل يكتب بناءً على السياق المقدم
|
||||
)
|
||||
```
|
||||
|
||||
### النمط 2: أدوات فقط (إجراءات، بدون خبرة خاصة)
|
||||
|
||||
استخدم عندما يحتاج الوكيل لاتخاذ إجراءات لكن لا يحتاج لتعليمات مجال محددة:
|
||||
|
||||
```python
|
||||
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
|
||||
|
||||
agent = Agent(
|
||||
role="Web Researcher",
|
||||
goal="Find information about a topic",
|
||||
backstory="Skilled at finding information online",
|
||||
tools=[SerperDevTool(), ScrapeWebsiteTool()], # يمكنه البحث والاستخراج
|
||||
# لا حاجة لمهارات — البحث العام لا يحتاج إرشادات خاصة
|
||||
)
|
||||
```
|
||||
|
||||
### النمط 3: مهارات + أدوات (خبرة وإجراءات)
|
||||
|
||||
النمط الأكثر شيوعًا في العالم الحقيقي. المهارة توفر *كيف* تقترب من العمل؛ الأدوات توفر *ما* يمكن للوكيل فعله:
|
||||
|
||||
```python
|
||||
from crewai_tools import SerperDevTool, FileReadTool, CodeInterpreterTool
|
||||
|
||||
analyst = Agent(
|
||||
role="Security Analyst",
|
||||
goal="Audit infrastructure for vulnerabilities",
|
||||
backstory="Expert in cloud security and compliance",
|
||||
skills=["./skills/security-audit"], # منهجية وقوائم تحقق التدقيق
|
||||
tools=[
|
||||
SerperDevTool(), # البحث عن ثغرات معروفة
|
||||
FileReadTool(), # قراءة ملفات التكوين
|
||||
CodeInterpreterTool(), # تشغيل سكربتات التحليل
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
### النمط 4: مهارات + MCP
|
||||
|
||||
المهارات تعمل مع خوادم MCP بنفس الطريقة التي تعمل بها مع الأدوات:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze customer data and generate reports",
|
||||
backstory="Expert data analyst with strong statistical background",
|
||||
skills=["./skills/data-analysis"], # منهجية التحليل
|
||||
mcps=["https://data-warehouse.example.com/sse"], # وصول بيانات عن بُعد
|
||||
)
|
||||
```
|
||||
|
||||
### النمط 5: مهارات + تطبيقات
|
||||
|
||||
المهارات يمكن أن توجّه كيف يستخدم الوكيل تكاملات المنصة:
|
||||
|
||||
```python
|
||||
agent = Agent(
|
||||
role="Customer Support Agent",
|
||||
goal="Respond to customer inquiries professionally",
|
||||
backstory="Experienced support representative",
|
||||
skills=["./skills/support-playbook"], # قوالب الردود وقواعد التصعيد
|
||||
apps=["gmail", "zendesk"], # يمكنه إرسال رسائل بريد وتحديث التذاكر
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## المهارات على مستوى الطاقم
|
||||
|
||||
يمكن تعيين المهارات على الطاقم لتُطبّق على **جميع الوكلاء**:
|
||||
|
||||
```python
|
||||
from crewai import Crew
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher, writer, reviewer],
|
||||
tasks=[research_task, write_task, review_task],
|
||||
skills=["./skills"], # جميع الوكلاء يحصلون على هذه المهارات
|
||||
)
|
||||
```
|
||||
|
||||
المهارات على مستوى الوكيل لها الأولوية — إذا تم اكتشاف نفس المهارة في كلا المستويين، يتم استخدام نسخة الوكيل.
|
||||
|
||||
---
|
||||
|
||||
## تنسيق SKILL.md
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: my-skill
|
||||
description: وصف قصير لما تفعله هذه المهارة ومتى تُستخدم.
|
||||
license: Apache-2.0 # اختياري
|
||||
compatibility: crewai>=0.1.0 # اختياري
|
||||
metadata: # اختياري
|
||||
author: your-name
|
||||
version: "1.0"
|
||||
allowed-tools: web-search file-read # اختياري، تجريبي
|
||||
---
|
||||
|
||||
التعليمات للوكيل تُكتب هنا. يتم حقن محتوى Markdown هذا
|
||||
في إرشادات الوكيل عند تفعيل المهارة.
|
||||
```
|
||||
|
||||
### حقول البيانات الوصفية
|
||||
|
||||
| الحقل | مطلوب | الوصف |
|
||||
| :-------------- | :------- | :----------------------------------------------------------------------- |
|
||||
| `name` | نعم | 1-64 حرف. أحرف صغيرة أبجدية رقمية وشرطات. يجب أن يطابق اسم المجلد. |
|
||||
| `description` | نعم | 1-1024 حرف. يصف ما تفعله المهارة ومتى تُستخدم. |
|
||||
| `license` | لا | اسم الترخيص أو مرجع لملف ترخيص مضمّن. |
|
||||
| `compatibility` | لا | حد أقصى 500 حرف. متطلبات البيئة (منتجات، حزم، شبكة). |
|
||||
| `metadata` | لا | تعيين مفتاح-قيمة نصي عشوائي. |
|
||||
| `allowed-tools` | لا | قائمة أدوات معتمدة مسبقًا مفصولة بمسافات. تجريبي. |
|
||||
|
||||
---
|
||||
|
||||
## هيكل المجلد
|
||||
|
||||
```
|
||||
my-skill/
|
||||
├── SKILL.md # مطلوب — البيانات الوصفية + التعليمات
|
||||
├── scripts/ # اختياري — سكربتات قابلة للتنفيذ
|
||||
├── references/ # اختياري — مستندات مرجعية
|
||||
└── assets/ # اختياري — ملفات ثابتة (إعدادات، بيانات)
|
||||
```
|
||||
|
||||
يجب أن يتطابق اسم المجلد مع حقل `name` في `SKILL.md`. مجلدات `scripts/` و `references/` و `assets/` متاحة في مسار المهارة `path` للوكلاء الذين يحتاجون للإشارة إلى الملفات مباشرة.
|
||||
|
||||
---
|
||||
|
||||
## المهارات المحمّلة مسبقًا
|
||||
|
||||
للمزيد من التحكم، يمكنك اكتشاف المهارات وتفعيلها برمجيًا:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
from crewai.skills import discover_skills, activate_skill
|
||||
|
||||
# اكتشاف جميع المهارات في مجلد
|
||||
skills = discover_skills(Path("./skills"))
|
||||
|
||||
# تفعيلها (تحميل محتوى SKILL.md الكامل)
|
||||
activated = [activate_skill(s) for s in skills]
|
||||
|
||||
# تمرير إلى وكيل
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Find relevant information",
|
||||
backstory="An expert researcher.",
|
||||
skills=activated,
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## كيف يتم تحميل المهارات
|
||||
|
||||
تستخدم المهارات **الكشف التدريجي** — تحمّل فقط ما هو مطلوب في كل مرحلة:
|
||||
|
||||
| المرحلة | ما يتم تحميله | متى |
|
||||
| :--------- | :------------------------------------ | :------------------ |
|
||||
| الاكتشاف | الاسم، الوصف، حقول البيانات الوصفية | `discover_skills()` |
|
||||
| التفعيل | نص محتوى SKILL.md الكامل | `activate_skill()` |
|
||||
|
||||
أثناء التنفيذ العادي للوكيل (تمرير مسارات المجلدات عبر `skills=["./skills"]`)، يتم اكتشاف المهارات وتفعيلها تلقائيًا. التحميل التدريجي مهم فقط عند استخدام الواجهة البرمجية.
|
||||
|
||||
---
|
||||
|
||||
## المهارات مقابل المعرفة
|
||||
|
||||
كلا المهارات والمعرفة تُعدّل إرشادات الوكيل، لكنهما يخدمان أغراضًا مختلفة:
|
||||
|
||||
| الجانب | المهارات | المعرفة |
|
||||
| :--- | :--- | :--- |
|
||||
| **ما توفره** | تعليمات، إجراءات، إرشادات | حقائق، بيانات، معلومات |
|
||||
| **كيف تُخزّن** | ملفات Markdown (SKILL.md) | مُضمّنة في مخزن متجهي (ChromaDB) |
|
||||
| **كيف تُسترجع** | يتم حقن المحتوى الكامل في الإرشادات | البحث الدلالي يجد الأجزاء ذات الصلة |
|
||||
| **الأفضل لـ** | المنهجيات، قوائم التحقق، أدلة الأسلوب | مستندات الشركة، معلومات المنتج، بيانات مرجعية |
|
||||
| **يُعيّن عبر** | `skills=["./skills"]` | `knowledge_sources=[source]` |
|
||||
|
||||
**القاعدة العامة:** إذا كان الوكيل يحتاج لاتباع *عملية*، استخدم مهارة. إذا كان يحتاج للرجوع إلى *بيانات*، استخدم المعرفة.
|
||||
|
||||
---
|
||||
|
||||
## الأسئلة الشائعة
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="هل أحتاج لتعيين المهارات والأدوات معًا؟">
|
||||
يعتمد على حالة الاستخدام. المهارات والأدوات **مستقلتان** — يمكنك استخدام أيّ منهما أو كليهما أو لا شيء.
|
||||
|
||||
- **مهارات فقط**: عندما يحتاج الوكيل خبرة لكن لا يحتاج إجراءات خارجية (مثال: الكتابة بإرشادات أسلوبية)
|
||||
- **أدوات فقط**: عندما يحتاج الوكيل إجراءات لكن لا يحتاج منهجية خاصة (مثال: بحث بسيط على الويب)
|
||||
- **كليهما**: عندما يحتاج الوكيل خبرة وإجراءات (مثال: تدقيق أمني بقوائم تحقق محددة وقدرة على فحص الكود)
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="هل توفر المهارات أدوات تلقائيًا؟">
|
||||
**لا.** حقل `allowed-tools` في SKILL.md هو بيانات وصفية تجريبية فقط — لا يُنشئ أو يحقن أي أدوات. يجب عليك دائمًا تعيين الأدوات بشكل منفصل عبر `tools=[]` أو `mcps=[]` أو `apps=[]`.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ماذا يحدث إذا عيّنت نفس المهارة على كل من الوكيل والطاقم؟">
|
||||
المهارة على مستوى الوكيل لها الأولوية. يتم إزالة التكرار حسب الاسم — مهارات الوكيل تُعالج أولاً، لذا إذا ظهر نفس اسم المهارة في كلا المستويين، تُستخدم نسخة الوكيل.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="ما الحجم الأقصى لمحتوى SKILL.md؟">
|
||||
هناك تحذير ناعم عند 50,000 حرف، لكن بدون حد صارم. حافظ على تركيز المهارات وإيجازها للحصول على أفضل النتائج — الحقن الكبيرة في الإرشادات قد تُشتت انتباه الوكيل.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
1120
docs/v1.15.2/ar/concepts/tasks.mdx
Normal file
49
docs/v1.15.2/ar/concepts/testing.mdx
Normal file
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: الاختبار
|
||||
description: تعرّف على كيفية اختبار طاقم CrewAI وتقييم أدائه.
|
||||
icon: vial
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يُعد الاختبار جزءًا حيويًا من عملية التطوير، ومن الضروري التأكد من أن طاقمك يعمل كما هو متوقع. مع CrewAI، يمكنك اختبار طاقمك وتقييم أدائه بسهولة باستخدام إمكانيات الاختبار المدمجة.
|
||||
|
||||
### استخدام ميزة الاختبار
|
||||
|
||||
أضفنا أمر CLI `crewai test` لتسهيل اختبار طاقمك. سيقوم هذا الأمر بتشغيل طاقمك لعدد محدد من التكرارات وتوفير مقاييس أداء مفصلة. المعاملات هي `n_iterations` و `model`، وهي اختيارية وتكون قيمها الافتراضية 2 و `gpt-4o-mini` على التوالي. حاليًا، المزود الوحيد المتاح هو OpenAI.
|
||||
|
||||
```bash
|
||||
crewai test
|
||||
```
|
||||
|
||||
إذا أردت تشغيل المزيد من التكرارات أو استخدام نموذج مختلف، يمكنك تحديد المعاملات هكذا:
|
||||
|
||||
```bash
|
||||
crewai test --n_iterations 5 --model gpt-4o
|
||||
```
|
||||
|
||||
أو باستخدام الصيغة المختصرة:
|
||||
|
||||
```bash
|
||||
crewai test -n 5 -m gpt-4o
|
||||
```
|
||||
|
||||
عند تشغيل أمر `crewai test`، سيتم تنفيذ الطاقم للعدد المحدد من التكرارات، وستُعرض مقاييس الأداء في نهاية التشغيل.
|
||||
|
||||
سيظهر جدول الدرجات في النهاية لعرض أداء الطاقم من حيث المقاييس التالية:
|
||||
|
||||
<center>**درجات المهام (1-10 الأعلى أفضل)**</center>
|
||||
|
||||
| المهام/الطاقم/الوكلاء | التشغيل 1 | التشغيل 2 | المجموع المتوسط | الوكلاء | معلومات إضافية |
|
||||
|:------------------|:-----:|:-----:|:----------:|:------------------------------:|:---------------------------------|
|
||||
| المهمة 1 | 9.0 | 9.5 | **9.2** | Professional Insights | |
|
||||
| | | | | Researcher | |
|
||||
| المهمة 2 | 9.0 | 10.0 | **9.5** | Company Profile Investigator | |
|
||||
| المهمة 3 | 9.0 | 9.0 | **9.0** | Automation Insights | |
|
||||
| | | | | Specialist | |
|
||||
| المهمة 4 | 9.0 | 9.0 | **9.0** | Final Report Compiler | Automation Insights Specialist |
|
||||
| الطاقم | 9.00 | 9.38 | **9.2** | | |
|
||||
| زمن التنفيذ (ثانية) | 126 | 145 | **135** | | |
|
||||
|
||||
يوضح المثال أعلاه نتائج الاختبار لتشغيلين للطاقم مع مهمتين، مع الدرجة الإجمالية المتوسطة لكل مهمة والطاقم ككل.
|
||||
290
docs/v1.15.2/ar/concepts/tools.mdx
Normal file
@@ -0,0 +1,290 @@
|
||||
---
|
||||
title: الأدوات
|
||||
description: فهم واستخدام الأدوات ضمن إطار عمل CrewAI لتعاون الوكلاء وتنفيذ المهام.
|
||||
icon: screwdriver-wrench
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
تُمكّن أدوات CrewAI الوكلاء بقدرات تتراوح من البحث على الويب وتحليل البيانات إلى التعاون وتفويض المهام بين الزملاء.
|
||||
توضح هذه الوثائق كيفية إنشاء هذه الأدوات ودمجها والاستفادة منها ضمن إطار عمل CrewAI، بما في ذلك التركيز على أدوات التعاون.
|
||||
|
||||
<Note type="info" title="الأدوات هي أحد أنواع قدرات الوكيل الخمسة">
|
||||
الأدوات تمنح الوكلاء **دوال قابلة للاستدعاء** لاتخاذ إجراءات. تعمل جنبًا إلى جنب مع [MCP](/ar/mcp/overview) (خوادم أدوات عن بُعد) و[التطبيقات](/ar/concepts/agent-capabilities) (تكاملات المنصة) و[المهارات](/ar/concepts/skills) (خبرة المجال) و[المعرفة](/ar/concepts/knowledge) (حقائق مُسترجعة). راجع نظرة عامة على [قدرات الوكيل](/ar/concepts/agent-capabilities) لفهم متى تستخدم كل نوع.
|
||||
</Note>
|
||||
|
||||
## ما هي الأداة؟
|
||||
|
||||
الأداة في CrewAI هي مهارة أو وظيفة يمكن للوكلاء استخدامها لأداء إجراءات مختلفة.
|
||||
يشمل ذلك أدوات من [مجموعة أدوات CrewAI](https://github.com/joaomdmoura/crewai-tools) و[أدوات LangChain](https://python.langchain.com/docs/integrations/tools)،
|
||||
مما يُمكّن كل شيء من عمليات البحث البسيطة إلى التفاعلات المعقدة والعمل الجماعي الفعال بين الوكلاء.
|
||||
|
||||
<Note type="info" title="تحسين المؤسسات: مستودع الأدوات">
|
||||
يوفر CrewAI AMP مستودع أدوات شامل مع تكاملات جاهزة لأنظمة الأعمال الشائعة وواجهات API. انشر الوكلاء مع أدوات المؤسسة في دقائق بدلاً من أيام.
|
||||
|
||||
يتضمن مستودع أدوات المؤسسة:
|
||||
|
||||
- موصلات جاهزة لأنظمة المؤسسة الشائعة
|
||||
- واجهة إنشاء أدوات مخصصة
|
||||
- إمكانيات التحكم في الإصدارات والمشاركة
|
||||
- ميزات الأمان والامتثال
|
||||
</Note>
|
||||
|
||||
## الخصائص الرئيسية للأدوات
|
||||
|
||||
- **المنفعة**: مصممة لمهام مثل البحث على الويب وتحليل البيانات وإنشاء المحتوى وتعاون الوكلاء.
|
||||
- **التكامل**: تعزز قدرات الوكلاء من خلال دمج الأدوات بسلاسة في سير عملهم.
|
||||
- **القابلية للتخصيص**: توفر المرونة لتطوير أدوات مخصصة أو استخدام الأدوات الموجودة، لتلبية الاحتياجات المحددة للوكلاء.
|
||||
- **معالجة الأخطاء**: تتضمن آليات معالجة أخطاء قوية لضمان التشغيل السلس.
|
||||
- **آلية التخزين المؤقت**: تتميز بتخزين مؤقت ذكي لتحسين الأداء وتقليل العمليات المتكررة.
|
||||
- **الدعم غير المتزامن**: تتعامل مع الأدوات المتزامنة وغير المتزامنة، مما يُمكّن العمليات غير الحاجبة.
|
||||
|
||||
## استخدام أدوات CrewAI
|
||||
|
||||
لتعزيز قدرات وكلائك بأدوات CrewAI، ابدأ بتثبيت حزمة الأدوات الإضافية:
|
||||
|
||||
```bash
|
||||
pip install 'crewai[tools]'
|
||||
```
|
||||
|
||||
إليك مثالًا يوضح استخدامها:
|
||||
|
||||
```python Code
|
||||
import os
|
||||
from crewai import Agent, Task, Crew
|
||||
# استيراد أدوات crewAI
|
||||
from crewai_tools import (
|
||||
DirectoryReadTool,
|
||||
FileReadTool,
|
||||
SerperDevTool,
|
||||
WebsiteSearchTool
|
||||
)
|
||||
|
||||
# إعداد مفاتيح API
|
||||
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
|
||||
os.environ["OPENAI_API_KEY"] = "Your Key"
|
||||
|
||||
# إنشاء الأدوات
|
||||
docs_tool = DirectoryReadTool(directory='./blog-posts')
|
||||
file_tool = FileReadTool()
|
||||
search_tool = SerperDevTool()
|
||||
web_rag_tool = WebsiteSearchTool()
|
||||
|
||||
# إنشاء الوكلاء
|
||||
researcher = Agent(
|
||||
role='Market Research Analyst',
|
||||
goal='Provide up-to-date market analysis of the AI industry',
|
||||
backstory='An expert analyst with a keen eye for market trends.',
|
||||
tools=[search_tool, web_rag_tool],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role='Content Writer',
|
||||
goal='Craft engaging blog posts about the AI industry',
|
||||
backstory='A skilled writer with a passion for technology.',
|
||||
tools=[docs_tool, file_tool],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# تعريف المهام
|
||||
research = Task(
|
||||
description='Research the latest trends in the AI industry and provide a summary.',
|
||||
expected_output='A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.',
|
||||
agent=researcher
|
||||
)
|
||||
|
||||
write = Task(
|
||||
description='Write an engaging blog post about the AI industry, based on the research analyst\'s summary. Draw inspiration from the latest blog posts in the directory.',
|
||||
expected_output='A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.',
|
||||
agent=writer,
|
||||
output_file='blog-posts/new_post.md'
|
||||
)
|
||||
|
||||
# تجميع طاقم مع تفعيل التخطيط
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[research, write],
|
||||
verbose=True,
|
||||
planning=True,
|
||||
)
|
||||
|
||||
# تنفيذ المهام
|
||||
crew.kickoff()
|
||||
```
|
||||
|
||||
## أدوات CrewAI المتاحة
|
||||
|
||||
- **معالجة الأخطاء**: جميع الأدوات مبنية بقدرات معالجة الأخطاء، مما يسمح للوكلاء بإدارة الاستثناءات بسلاسة ومتابعة مهامهم.
|
||||
- **آلية التخزين المؤقت**: جميع الأدوات تدعم التخزين المؤقت، مما يُمكّن الوكلاء من إعادة استخدام النتائج المحصلة سابقًا بكفاءة، مما يقلل الحمل على الموارد الخارجية ويسرّع وقت التنفيذ. يمكنك أيضًا تحديد تحكم أدق في آلية التخزين المؤقت باستخدام خاصية `cache_function` على الأداة.
|
||||
|
||||
إليك قائمة بالأدوات المتاحة وأوصافها:
|
||||
|
||||
| الأداة | الوصف |
|
||||
| :------------------------------- | :--------------------------------------------------------------------------------------------- |
|
||||
| **ApifyActorsTool** | أداة تدمج Apify Actors مع سير عملك لمهام استخراج البيانات من الويب والأتمتة. |
|
||||
| **BrowserbaseLoadTool** | أداة للتفاعل مع المتصفحات واستخراج البيانات منها. |
|
||||
| **CodeDocsSearchTool** | أداة RAG محسّنة للبحث في وثائق الكود والمستندات التقنية ذات الصلة. |
|
||||
| **CodeInterpreterTool** | أداة لتفسير كود Python. |
|
||||
| **ComposioTool** | تُمكّن استخدام أدوات Composio. |
|
||||
| **CSVSearchTool** | أداة RAG مصممة للبحث في ملفات CSV، مخصصة للتعامل مع البيانات المنظمة. |
|
||||
| **DALL-E Tool** | أداة لإنشاء الصور باستخدام DALL-E API. |
|
||||
| **DirectorySearchTool** | أداة RAG للبحث في المجلدات، مفيدة للتنقل في أنظمة الملفات. |
|
||||
| **DOCXSearchTool** | أداة RAG للبحث في مستندات DOCX، مثالية لمعالجة ملفات Word. |
|
||||
| **DirectoryReadTool** | تسهّل قراءة ومعالجة هياكل المجلدات ومحتوياتها. |
|
||||
| **ExaSearchTool** | أداة مصممة لإجراء عمليات بحث شاملة عبر مصادر بيانات متنوعة. |
|
||||
| **FileReadTool** | تُمكّن قراءة واستخراج البيانات من الملفات، مع دعم تنسيقات ملفات متنوعة. |
|
||||
| **FirecrawlSearchTool** | أداة للبحث في صفحات الويب باستخدام Firecrawl وإرجاع النتائج. |
|
||||
| **FirecrawlCrawlWebsiteTool** | أداة لزحف صفحات الويب باستخدام Firecrawl. |
|
||||
| **FirecrawlScrapeWebsiteTool** | أداة لاستخراج محتوى عناوين URL لصفحات الويب باستخدام Firecrawl. |
|
||||
| **GithubSearchTool** | أداة RAG للبحث في مستودعات GitHub، مفيدة لبحث الكود والوثائق. |
|
||||
| **SerperDevTool** | أداة متخصصة لأغراض التطوير، مع وظائف محددة قيد التطوير. |
|
||||
| **TXTSearchTool** | أداة RAG مركّزة على البحث في ملفات النص (.txt)، مناسبة للبيانات غير المنظمة. |
|
||||
| **JSONSearchTool** | أداة RAG مصممة للبحث في ملفات JSON، تخدم التعامل مع البيانات المنظمة. |
|
||||
| **LlamaIndexTool** | تُمكّن استخدام أدوات LlamaIndex. |
|
||||
| **MDXSearchTool** | أداة RAG مخصصة للبحث في ملفات Markdown (MDX)، مفيدة للوثائق. |
|
||||
| **PDFSearchTool** | أداة RAG للبحث في مستندات PDF، مثالية لمعالجة المستندات الممسوحة ضوئيًا. |
|
||||
| **PGSearchTool** | أداة RAG محسّنة للبحث في قواعد بيانات PostgreSQL، مناسبة لاستعلامات قواعد البيانات. |
|
||||
| **Vision Tool** | أداة لإنشاء الصور باستخدام DALL-E API. |
|
||||
| **RagTool** | أداة RAG للأغراض العامة قادرة على التعامل مع مصادر وأنواع بيانات متنوعة. |
|
||||
| **ScrapeElementFromWebsiteTool** | تُمكّن استخراج عناصر محددة من المواقع، مفيدة لاستخراج البيانات المستهدف. |
|
||||
| **ScrapeWebsiteTool** | تسهّل استخراج المواقع بالكامل، مثالية لجمع البيانات الشامل. |
|
||||
| **WebsiteSearchTool** | أداة RAG للبحث في محتوى المواقع، محسّنة لاستخراج بيانات الويب. |
|
||||
| **XMLSearchTool** | أداة RAG مصممة للبحث في ملفات XML، مناسبة لتنسيقات البيانات المنظمة. |
|
||||
| **YoutubeChannelSearchTool** | أداة RAG للبحث في قنوات YouTube، مفيدة لتحليل محتوى الفيديو. |
|
||||
| **YoutubeVideoSearchTool** | أداة RAG للبحث في مقاطع فيديو YouTube، مثالية لاستخراج بيانات الفيديو. |
|
||||
|
||||
## إنشاء أدواتك الخاصة
|
||||
|
||||
<Tip>
|
||||
يمكن للمطورين إنشاء `أدوات مخصصة` مصممة خصيصًا لاحتياجات وكلائهم أو
|
||||
استخدام الخيارات الجاهزة.
|
||||
</Tip>
|
||||
|
||||
هناك طريقتان رئيسيتان لإنشاء أداة CrewAI:
|
||||
|
||||
### الوراثة من `BaseTool`
|
||||
|
||||
```python Code
|
||||
from crewai.tools import BaseTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class MyToolInput(BaseModel):
|
||||
"""Input schema for MyCustomTool."""
|
||||
argument: str = Field(..., description="Description of the argument.")
|
||||
|
||||
class MyCustomTool(BaseTool):
|
||||
name: str = "Name of my tool"
|
||||
description: str = "What this tool does. It's vital for effective utilization."
|
||||
args_schema: Type[BaseModel] = MyToolInput
|
||||
|
||||
def _run(self, argument: str) -> str:
|
||||
# منطق أداتك هنا
|
||||
return "Tool's result"
|
||||
```
|
||||
|
||||
## دعم الأدوات غير المتزامنة
|
||||
|
||||
يدعم CrewAI الأدوات غير المتزامنة، مما يتيح لك تنفيذ أدوات تجري عمليات غير حاجبة مثل طلبات الشبكة وعمليات الإدخال/الإخراج على الملفات أو عمليات async أخرى بدون حجب مسار التنفيذ الرئيسي.
|
||||
|
||||
### إنشاء أدوات غير متزامنة
|
||||
|
||||
يمكنك إنشاء أدوات غير متزامنة بطريقتين:
|
||||
|
||||
#### 1. استخدام مزيّن `tool` مع دوال Async
|
||||
|
||||
```python Code
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("fetch_data_async")
|
||||
async def fetch_data_async(query: str) -> str:
|
||||
"""Asynchronously fetch data based on the query."""
|
||||
# محاكاة عملية غير متزامنة
|
||||
await asyncio.sleep(1)
|
||||
return f"Data retrieved for {query}"
|
||||
```
|
||||
|
||||
#### 2. تنفيذ طرق Async في فئات الأدوات المخصصة
|
||||
|
||||
```python Code
|
||||
from crewai.tools import BaseTool
|
||||
|
||||
class AsyncCustomTool(BaseTool):
|
||||
name: str = "async_custom_tool"
|
||||
description: str = "An asynchronous custom tool"
|
||||
|
||||
async def _run(self, query: str = "") -> str:
|
||||
"""Asynchronously run the tool"""
|
||||
# تنفيذك غير المتزامن هنا
|
||||
await asyncio.sleep(1)
|
||||
return f"Processed {query} asynchronously"
|
||||
```
|
||||
|
||||
### استخدام الأدوات غير المتزامنة
|
||||
|
||||
تعمل الأدوات غير المتزامنة بسلاسة في كل من سير عمل الطاقم القياسي وسير عمل التدفق:
|
||||
|
||||
```python Code
|
||||
# في طاقم قياسي
|
||||
agent = Agent(role="researcher", tools=[async_custom_tool])
|
||||
|
||||
# في تدفق
|
||||
class MyFlow(Flow):
|
||||
@start()
|
||||
async def begin(self):
|
||||
crew = Crew(agents=[agent])
|
||||
result = await crew.kickoff_async()
|
||||
return result
|
||||
```
|
||||
|
||||
يتعامل إطار عمل CrewAI تلقائيًا مع تنفيذ الأدوات المتزامنة وغير المتزامنة، لذا لا تحتاج للقلق بشأن كيفية استدعائها بشكل مختلف.
|
||||
|
||||
### استخدام مزيّن `tool`
|
||||
|
||||
```python Code
|
||||
from crewai.tools import tool
|
||||
@tool("Name of my tool")
|
||||
def my_tool(question: str) -> str:
|
||||
"""Clear description for what this tool is useful for, your agent will need this information to use it."""
|
||||
# منطق الدالة هنا
|
||||
return "Result from your custom tool"
|
||||
```
|
||||
|
||||
### آلية التخزين المؤقت المخصصة
|
||||
|
||||
<Tip>
|
||||
يمكن للأدوات اختياريًا تنفيذ `cache_function` لضبط سلوك
|
||||
التخزين المؤقت. تحدد هذه الدالة متى يتم تخزين النتائج مؤقتًا بناءً على شروط
|
||||
محددة، مما يوفر تحكمًا دقيقًا في منطق التخزين المؤقت.
|
||||
</Tip>
|
||||
|
||||
```python Code
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool
|
||||
def multiplication_tool(first_number: int, second_number: int) -> str:
|
||||
"""Useful for when you need to multiply two numbers together."""
|
||||
return first_number * second_number
|
||||
|
||||
def cache_func(args, result):
|
||||
# في هذه الحالة، نخزّن النتيجة مؤقتًا فقط إذا كانت من مضاعفات 2
|
||||
cache = result % 2 == 0
|
||||
return cache
|
||||
|
||||
multiplication_tool.cache_function = cache_func
|
||||
|
||||
writer1 = Agent(
|
||||
role="Writer",
|
||||
goal="You write lessons of math for kids.",
|
||||
backstory="You're an expert in writing and you love to teach kids but you know nothing of math.",
|
||||
tools=[multiplication_tool],
|
||||
allow_delegation=False,
|
||||
)
|
||||
#...
|
||||
```
|
||||
|
||||
## الخلاصة
|
||||
|
||||
الأدوات محورية في توسيع قدرات وكلاء CrewAI، مما يمكّنهم من تنفيذ مجموعة واسعة من المهام والتعاون بفعالية.
|
||||
عند بناء حلول مع CrewAI، استفد من كل من الأدوات المخصصة والموجودة لتمكين وكلائك وتعزيز نظام الذكاء الاصطناعي البيئي. فكّر في استخدام معالجة الأخطاء وآليات التخزين المؤقت ومرونة معاملات الأدوات لتحسين أداء وقدرات وكلائك.
|
||||
197
docs/v1.15.2/ar/concepts/training.mdx
Normal file
@@ -0,0 +1,197 @@
|
||||
---
|
||||
title: التدريب
|
||||
description: تعرّف على كيفية تدريب وكلاء CrewAI من خلال تقديم ملاحظات مبكرة والحصول على نتائج متسقة.
|
||||
icon: dumbbell
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
تتيح لك ميزة التدريب في CrewAI تدريب وكلاء الذكاء الاصطناعي باستخدام واجهة سطر الأوامر (CLI).
|
||||
بتشغيل الأمر `crewai train -n <n_iterations>`، يمكنك تحديد عدد التكرارات لعملية التدريب.
|
||||
|
||||
أثناء التدريب، يستخدم CrewAI تقنيات لتحسين أداء وكلائك مع التغذية الراجعة البشرية.
|
||||
يساعد هذا الوكلاء على تحسين فهمهم واتخاذ القرارات وحل المشكلات.
|
||||
|
||||
### تدريب طاقمك باستخدام CLI
|
||||
|
||||
لاستخدام ميزة التدريب، اتبع الخطوات التالية:
|
||||
|
||||
1. افتح الطرفية أو موجه الأوامر.
|
||||
2. انتقل إلى المجلد حيث يقع مشروع CrewAI.
|
||||
3. شغّل الأمر التالي:
|
||||
|
||||
```shell
|
||||
crewai train -n <n_iterations> -f <filename.pkl>
|
||||
```
|
||||
<Tip>
|
||||
استبدل `<n_iterations>` بعدد تكرارات التدريب المرغوب و`<filename>` باسم الملف المناسب المنتهي بـ `.pkl`.
|
||||
</Tip>
|
||||
|
||||
<Note>
|
||||
إذا حذفت `-f`، فإن المخرجات تُحفظ افتراضيًا في `trained_agents_data.pkl` في مجلد العمل الحالي. يمكنك تمرير مسار مطلق للتحكم في مكان كتابة الملف.
|
||||
</Note>
|
||||
|
||||
### تدريب طاقمك برمجيًا
|
||||
|
||||
لتدريب طاقمك برمجيًا، استخدم الخطوات التالية:
|
||||
|
||||
1. حدد عدد التكرارات للتدريب.
|
||||
2. حدد معاملات الإدخال لعملية التدريب.
|
||||
3. نفّذ أمر التدريب داخل كتلة try-except للتعامل مع الأخطاء المحتملة.
|
||||
|
||||
```python Code
|
||||
n_iterations = 2
|
||||
inputs = {"topic": "CrewAI Training"}
|
||||
filename = "your_model.pkl"
|
||||
|
||||
try:
|
||||
YourCrewName_Crew().crew().train(
|
||||
n_iterations=n_iterations,
|
||||
inputs=inputs,
|
||||
filename=filename
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"An error occurred while training the crew: {e}")
|
||||
```
|
||||
|
||||
## كيف تُستخدم بيانات التدريب من قبل الوكلاء
|
||||
|
||||
يستخدم CrewAI مخرجات التدريب بطريقتين: أثناء التدريب لدمج ملاحظاتك البشرية، وبعد التدريب لتوجيه الوكلاء باقتراحات موحدة.
|
||||
|
||||
### تدفق بيانات التدريب
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["Start training<br/>CLI: crewai train -n -f<br/>or Python: crew.train(...)"] --> B["Setup training mode<br/>- task.human_input = true<br/>- disable delegation<br/>- init training_data.pkl + trained file"]
|
||||
|
||||
subgraph "Iterations"
|
||||
direction LR
|
||||
C["Iteration i<br/>initial_output"] --> D["User human_feedback"]
|
||||
D --> E["improved_output"]
|
||||
E --> F["Append to training_data.pkl<br/>by agent_id and iteration"]
|
||||
end
|
||||
|
||||
B --> C
|
||||
F --> G{"More iterations?"}
|
||||
G -- "Yes" --> C
|
||||
G -- "No" --> H["Evaluate per agent<br/>aggregate iterations"]
|
||||
|
||||
H --> I["Consolidate<br/>suggestions[] + quality + final_summary"]
|
||||
I --> J["Save by agent role to trained file<br/>(default: trained_agents_data.pkl)"]
|
||||
|
||||
J --> K["Normal (non-training) runs"]
|
||||
K --> L["Auto-load suggestions<br/>from trained_agents_data.pkl"]
|
||||
L --> M["Append to prompt<br/>for consistent improvements"]
|
||||
```
|
||||
|
||||
### أثناء تشغيلات التدريب
|
||||
|
||||
- في كل تكرار، يسجل النظام لكل وكيل:
|
||||
- `initial_output`: الإجابة الأولى للوكيل
|
||||
- `human_feedback`: ملاحظاتك المضمّنة عند الطلب
|
||||
- `improved_output`: إجابة المتابعة للوكيل بعد الملاحظات
|
||||
- تُخزن هذه البيانات في ملف عمل باسم `training_data.pkl` مفهرس بمعرّف الوكيل الداخلي والتكرار.
|
||||
- أثناء نشاط التدريب، يُلحق الوكيل تلقائيًا ملاحظاتك البشرية السابقة بأمره لتطبيق تلك التعليمات في المحاولات اللاحقة ضمن جلسة التدريب.
|
||||
التدريب تفاعلي: تُعيّن المهام `human_input = true`، لذا سيتوقف التشغيل في بيئة غير تفاعلية بانتظار مدخلات المستخدم.
|
||||
|
||||
### بعد اكتمال التدريب
|
||||
|
||||
- عند انتهاء `train(...)`، يقيّم CrewAI بيانات التدريب المجمعة لكل وكيل وينتج نتيجة موحدة تحتوي على:
|
||||
- `suggestions`: تعليمات واضحة وقابلة للتنفيذ مستخلصة من ملاحظاتك والفرق بين المخرجات الأولية/المحسنة
|
||||
- `quality`: درجة من 0-10 تعكس التحسن
|
||||
- `final_summary`: مجموعة خطوات عمل تفصيلية للمهام المستقبلية
|
||||
- تُحفظ هذه النتائج الموحدة في اسم الملف الذي تمرره إلى `train(...)` (الافتراضي عبر CLI هو `trained_agents_data.pkl`). تُفهرس الإدخالات بدور الوكيل `role` لتطبيقها عبر الجلسات.
|
||||
- أثناء التنفيذ العادي (غير التدريب)، يحمّل كل وكيل تلقائيًا `suggestions` الموحدة ويلحقها بأمر المهمة كتعليمات إلزامية. يمنحك هذا تحسينات متسقة بدون تغيير تعريفات الوكلاء.
|
||||
|
||||
### ملخص الملفات
|
||||
|
||||
- `training_data.pkl` (مؤقت، لكل جلسة):
|
||||
- الهيكل: `agent_id -> { iteration_number: { initial_output, human_feedback, improved_output } }`
|
||||
- الغرض: التقاط البيانات الخام والملاحظات البشرية أثناء التدريب
|
||||
- الموقع: يُحفظ في مجلد العمل الحالي (CWD)
|
||||
- `trained_agents_data.pkl` (أو اسم ملفك المخصص):
|
||||
- الهيكل: `agent_role -> { suggestions: string[], quality: number, final_summary: string }`
|
||||
- الغرض: استمرار التوجيه الموحد للتشغيلات المستقبلية
|
||||
- الموقع: يُكتب في CWD افتراضيًا؛ استخدم `-f` لتعيين مسار مخصص (بما في ذلك المطلق)
|
||||
|
||||
## اعتبارات نماذج اللغة الصغيرة
|
||||
|
||||
<Warning>
|
||||
عند استخدام نماذج لغة أصغر (≤7 مليار معامل) لتقييم بيانات التدريب، كن على علم أنها قد تواجه تحديات في إنتاج مخرجات منظمة واتباع التعليمات المعقدة.
|
||||
</Warning>
|
||||
|
||||
### قيود النماذج الصغيرة في تقييم التدريب
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="دقة مخرجات JSON" icon="triangle-exclamation">
|
||||
غالبًا ما تواجه النماذج الأصغر صعوبة في إنتاج استجابات JSON صالحة مطلوبة لتقييمات التدريب المنظمة، مما يؤدي إلى أخطاء تحليل وبيانات غير مكتملة.
|
||||
</Card>
|
||||
<Card title="جودة التقييم" icon="chart-line">
|
||||
قد توفر النماذج تحت 7 مليار معامل تقييمات أقل دقة مع عمق استدلال محدود مقارنة بالنماذج الأكبر.
|
||||
</Card>
|
||||
<Card title="اتباع التعليمات" icon="list-check">
|
||||
قد لا تُتبع معايير تقييم التدريب المعقدة بالكامل أو تُراعى من قبل النماذج الأصغر.
|
||||
</Card>
|
||||
<Card title="الاتساق" icon="rotate">
|
||||
قد تفتقر التقييمات عبر تكرارات تدريب متعددة إلى الاتساق مع النماذج الأصغر.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### توصيات للتدريب
|
||||
|
||||
<Tabs>
|
||||
<Tab title="أفضل ممارسة">
|
||||
لجودة تدريب مثالية وتقييمات موثوقة، نوصي بشدة باستخدام نماذج بحد أدنى 7 مليار معامل أو أكبر:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Crew, Task, LLM
|
||||
|
||||
# الحد الأدنى الموصى به لتقييم التدريب
|
||||
llm = LLM(model="mistral/open-mistral-7b")
|
||||
|
||||
# خيارات أفضل لتقييم تدريب موثوق
|
||||
llm = LLM(model="anthropic/claude-3-sonnet-20240229-v1:0")
|
||||
llm = LLM(model="gpt-4o")
|
||||
|
||||
# استخدم هذا LLM مع وكلائك
|
||||
agent = Agent(
|
||||
role="Training Evaluator",
|
||||
goal="Provide accurate training feedback",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
توفر النماذج الأكثر قوة ملاحظات أعلى جودة مع استدلال أفضل، مما يؤدي إلى تكرارات تدريب أكثر فعالية.
|
||||
</Tip>
|
||||
</Tab>
|
||||
<Tab title="استخدام النماذج الصغيرة">
|
||||
إذا كان يجب عليك استخدام نماذج أصغر لتقييم التدريب، كن على علم بهذه القيود:
|
||||
|
||||
```python
|
||||
# استخدام نموذج أصغر (توقع بعض القيود)
|
||||
llm = LLM(model="huggingface/microsoft/Phi-3-mini-4k-instruct")
|
||||
```
|
||||
|
||||
<Warning>
|
||||
بينما يتضمن CrewAI تحسينات للنماذج الصغيرة، توقع نتائج تقييم أقل موثوقية ودقة قد تتطلب تدخلاً بشريًا أكبر أثناء التدريب.
|
||||
</Warning>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### نقاط مهمة يجب ملاحظتها
|
||||
|
||||
- **متطلب العدد الصحيح الموجب:** تأكد من أن عدد التكرارات (`n_iterations`) هو عدد صحيح موجب. سيرمي الكود `ValueError` إذا لم يتحقق هذا الشرط.
|
||||
- **متطلب اسم الملف:** تأكد من أن اسم الملف ينتهي بـ `.pkl`. سيرمي الكود `ValueError` إذا لم يتحقق هذا الشرط.
|
||||
- **معالجة الأخطاء:** يتعامل الكود مع أخطاء العمليات الفرعية والاستثناءات غير المتوقعة، ويوفر رسائل خطأ للمستخدم.
|
||||
- يُطبق التوجيه المدرّب في وقت الأمر؛ لا يعدّل تهيئة وكيل Python/YAML.
|
||||
- يحمّل الوكلاء تلقائيًا الاقتراحات المدربة من ملف باسم `trained_agents_data.pkl` الموجود في مجلد العمل الحالي. إذا درّبت إلى اسم ملف مختلف، أعد تسميته إلى `trained_agents_data.pkl` قبل التشغيل، أو اضبط المحمّل في الكود.
|
||||
- يمكنك تغيير اسم ملف المخرجات عند استدعاء `crewai train` بـ `-f/--filename`. المسارات المطلقة مدعومة إذا أردت الحفظ خارج CWD.
|
||||
|
||||
من المهم ملاحظة أن عملية التدريب قد تستغرق بعض الوقت، اعتمادًا على تعقيد وكلائك وستتطلب أيضًا ملاحظاتك في كل تكرار.
|
||||
|
||||
بمجرد اكتمال التدريب، سيكون وكلاؤك مجهزين بقدرات ومعرفة محسّنة، وجاهزين لمعالجة المهام المعقدة وتقديم رؤى أكثر اتساقًا وقيمة.
|
||||
|
||||
تذكر تحديث وإعادة تدريب وكلائك بانتظام لضمان بقائهم على اطلاع بأحدث المعلومات والتطورات في المجال.
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
title: "راقب أتمتاتك"
|
||||
description: "راقب صحة الأسطول واستهلاك LLM وسلوك كل أتمتة من تبويب Automations."
|
||||
sidebarTitle: "المراقبة"
|
||||
icon: "gauge"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**تنقل وثائق ACP (إصدار تجريبي)**
|
||||
|
||||
- [نظرة عامة](/ar/enterprise/features/agent-control-plane/overview)
|
||||
- **المراقبة** *(أنت هنا)*
|
||||
- [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
تبويب **Automations** هو عرض العمليات للقراءة فقط في [Agent Control Plane](/ar/enterprise/features/agent-control-plane/overview). يجمع بين بطاقتَي مقاييس و sankey تفاعلي وجدولين فرعيين — **Automations** و **Consumption** — يمكنك البحث والتصفية والفرز فيهما.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
تحترم جميع المخططات والجداول مُحدّد **آخر 24 ساعة / الأسبوع الماضي / آخر 30 يوماً** في أعلى اليمين. تقارن قيم الفرق النافذة المختارة بالنافذة السابقة بنفس الطول.
|
||||
|
||||
<Note>
|
||||
تعرض الصفوف بيانات فقط لعمليات النشر على **crewAI v1.13 أو أحدث** — تظهر عمليات النشر الأقدم في لافتة *"We've detected N other automations that we can't display"* أسفل sankey ولا تساهم بأي مقاييس حتى يتم تحديثها وإعادة نشرها. راجع [نظرة عامة — المتطلبات](/ar/enterprise/features/agent-control-plane/overview#المتطلبات).
|
||||
</Note>
|
||||
|
||||
## لوحة المعلومات
|
||||
|
||||
يحتوي رأس الصفحة على بطاقتَي مقاييس و sankey تفاعلي. النقر على أي من البطاقتين يبدّل sankey بين وضعَين:
|
||||
|
||||
- **وضع الصحة** — `إجمالي الأتمتات → حِزم الحالة (Critical / Warning / Healthy)`. انقر على حِزمة لتصفية جدول Automations إلى عمليات النشر تلك فقط.
|
||||
- **وضع الاستهلاك** — `مزودو النماذج → الأتمتات → التكلفة الإجمالية`. انقر على مزود لتصفية جدول Consumption إلى ذلك المزود.
|
||||
|
||||
| البطاقة | ما تعرضه |
|
||||
|------|---------------|
|
||||
| **Automations** | الأتمتات `active` (والعدد الإجمالي)، إجمالي `errors` في النافذة، `active executions` الحالية (والإجمالي في النافذة)، مع الفرق مقابل الفترة السابقة. |
|
||||
| **Consumption** | إجمالي `cost` و `tokens used`، مع فرق التكلفة مقابل الفترة السابقة. |
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
## جدول Automations
|
||||
|
||||
التبويب الفرعي **Automations** هو تفصيل صحة الأسطول لكل deployment. كل صف هو crew أو flow منشور.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
| العمود | ما يعرضه |
|
||||
|--------|---------------|
|
||||
| **Automation** | اسم الـ deployment وأي وسوم مُسنَدة إليه (مثل `production`، `financial`). |
|
||||
| **Last execution** | الوقت المنقضي منذ آخر تنفيذ. |
|
||||
| **Health Status Breakdown** | شريط مكدّس بنسب `Critical` / `Warning` / `Healthy` لعمليات التنفيذ في النافذة. |
|
||||
| **Executions with Errors** | إجمالي عمليات التنفيذ الفاشلة في النافذة. |
|
||||
| **PII detection applied** | `Yes` إذا كان هناك تكوين PII لكل deployment أو [سياسة PII](/edge/ar/enterprise/features/agent-control-plane/policies) مطابِقة نشطة. |
|
||||
| **Executions** | إجمالي عمليات التنفيذ في النافذة. |
|
||||
| **Last updated** | متى أُعيد نشر الـ deployment آخر مرة. |
|
||||
| **Crew Version** | إصدار `crewai` الذي يُبلِّغ عنه الـ deployment. يشير أيقونة المعلومات بجانب الإصدارات الأقل من `1.13` إلى صفوف لا يمكنها المساهمة بالمقاييس. |
|
||||
|
||||
ابحث بالاسم، صفِّ حسب `Status` (`Healthy` / `Warning` / `Critical`)، وافرز بأي رأس عمود. انقر على اسم الـ deployment لفتح **لوحة الأتمتة**.
|
||||
|
||||
## جدول Consumption
|
||||
|
||||
التبويب الفرعي **Consumption** هو تفصيل إنفاق LLM واستخدام الرموز لكل deployment.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
| العمود | ما يعرضه |
|
||||
|--------|---------------|
|
||||
| **Automation** | اسم الـ deployment. |
|
||||
| **Last execution** | الوقت المنقضي منذ آخر تنفيذ. |
|
||||
| **Tokens used** | صف واحد لكل مزود LLM تستخدمه هذه الأتمتة، مع الفرق مقابل الفترة السابقة. |
|
||||
| **Cost** | التكلفة لكل مزود LLM، مع الفرق مقابل الفترة السابقة. |
|
||||
| **Total cost** | المجموع عبر جميع المزودين، مع الفرق. |
|
||||
| **Executions** | إجمالي عمليات التنفيذ في النافذة. |
|
||||
| **Last updated** | متى أُعيد نشر الـ deployment آخر مرة. |
|
||||
| **Crew Version** | إصدار `crewai` الذي يُبلِّغ عنه الـ deployment. |
|
||||
|
||||
صفِّ حسب **LLM provider** وافرز حسب `Cost` أو `Executions` أو `Last run`.
|
||||
|
||||
<Info>
|
||||
**عادة ما تعني الخلايا الفارغة (`—` أو `$0.00`) أن الـ deployment أدنى من crewAI v1.13.** في اللقطة أعلاه، تظهر *Automation F* (`1.7.0`) و *Automation I* (`1.12.2`) فارغة في الرموز والتكلفة — لا تزال عمليات التنفيذ تعمل، لكنها لا تُصدِر التليمتري على مستوى المزود الذي يُغذِّي هذا الجدول. حدّث هذه الـ crews وأعد نشرها لبدء جمع بيانات الاستهلاك.
|
||||
</Info>
|
||||
|
||||
## ذو صلة
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent Control Plane — نظرة عامة" icon="book-open" href="/ar/enterprise/features/agent-control-plane/overview">
|
||||
ما هو ACP، المتطلبات، مستويات الخطط، و RBAC.
|
||||
</Card>
|
||||
<Card title="Agent Control Plane — السياسات" icon="shield-check" href="/edge/ar/enterprise/features/agent-control-plane/policies">
|
||||
طبّق سياسات PII Redaction على مستوى المؤسسة عبر العديد من الأتمتات.
|
||||
</Card>
|
||||
<Card title="Traces" icon="timeline" href="/ar/enterprise/features/traces">
|
||||
تعمّق في تنفيذ واحد لرؤية تفكير الوكيل واستدعاءات الأدوات واستخدام الرموز.
|
||||
</Card>
|
||||
<Card title="النشر إلى AMP" icon="rocket" href="/ar/enterprise/guides/deploy-to-amp">
|
||||
انشر crew على إصدار crewAI يدعم Agent Control Plane.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="تحتاج مساعدة؟" icon="headset" href="mailto:support@crewai.com">
|
||||
تواصل مع فريق الدعم للمساعدة في تفسير المقاييس داخل Agent Control Plane.
|
||||
</Card>
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: نظرة عامة على Agent Control Plane
|
||||
description: "مركز عمليات موحّد للأتمتات الجارية — صحة الأسطول واستهلاك LLM والسياسات على مستوى المؤسسة في مكان واحد."
|
||||
sidebarTitle: نظرة عامة
|
||||
icon: "book-open"
|
||||
---
|
||||
|
||||
<Info>
|
||||
**تنقل وثائق ACP (إصدار تجريبي)**
|
||||
|
||||
- **نظرة عامة** *(أنت هنا)*
|
||||
- [المراقبة](/ar/enterprise/features/agent-control-plane/monitoring)
|
||||
- [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies)
|
||||
</Info>
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
**Agent Control Plane** (ACP) هو مركز العمليات لكل ما يعمل لديك على CrewAI AMP. إنها شاشة واحدة — مقسّمة إلى تبويبَي **Automations** و **Policies** — تمنح فريقك القدرة على:
|
||||
|
||||
- مراقبة **حالة (الصحة)** كل أتمتة حيّة (crew أو flow) بتفصيل `Critical` / `Warning` / `Healthy` وعدد عمليات التنفيذ.
|
||||
- تتبع **استهلاك LLM** — الرموز (tokens) والتكلفة — لكل أتمتة ولكل مزود ولكل نموذج، مع الفرق مقابل الفترة السابقة.
|
||||
- التعمّق في أي أتمتة منفردة أو مزود نماذج لرؤية المخططات الزمنية وتفصيل البيانات لكل مزود.
|
||||
- تطبيق **سياسات (Policies)** على مستوى المؤسسة (اليوم: PII Redaction) عبر العديد من الأتمتات دفعة واحدة بدلاً من تعديل كل deployment على حدة.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
<Note>
|
||||
Agent Control Plane مُوسوم حالياً بـ **Beta** في CrewAI Platform.
|
||||
</Note>
|
||||
|
||||
يجيب التبويبان عن سؤالَين مختلفَين:
|
||||
|
||||
- **Automations** — *"كيف يتصرف أسطولي الآن، وكم يكلّفني؟"* راجع [المراقبة](/ar/enterprise/features/agent-control-plane/monitoring).
|
||||
- **Policies** — *"كيف أفرض سياسة (مثل PII redaction) عبر العديد من عمليات النشر دون إعادة نشر كل واحدة؟"* راجع [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies).
|
||||
|
||||
## المتطلبات
|
||||
|
||||
<Warning>
|
||||
يُشترط **crewAI v1.13 أو أحدث** ليتمكن أي أتمتة من تعبئة أي بيانات على هذه الصفحة — تمر بيانات الصحة وعمليات التنفيذ والأخطاء والرموز والتكلفة عبر التليمتري الذي تم تفعيله في `crewai==1.13`. تظهر عمليات النشر الأقدم في لافتة *"We've detected N other automations that we can't display"* ولا تساهم بأي صفوف حتى يتم تحديثها وإعادة نشرها.
|
||||
</Warning>
|
||||
|
||||
<Warning>
|
||||
يُشترط **خطة Enterprise أو Ultra** لإنشاء أو تعديل [السياسات](/edge/ar/enterprise/features/agent-control-plane/policies). يمكن للمؤسسات على الخطط الأدنى فتح تبويب Policies وعرض السياسات الموجودة، ولكن يُعرض المحرر للقراءة فقط مع شارة قفل "Enterprise" والتنبيه *"PII Redaction policies require an Enterprise plan."*. المراقبة (تبويب Automations) متاحة في جميع الخطط حيث يكون هذا الميزة مفعّلة.
|
||||
</Warning>
|
||||
|
||||
- يجب أن تكون ميزة **Agent Control Plane** مفعّلة لمؤسستك. إن لم ترها في الشريط الجانبي، اطلب من مالك الحساب تفعيلها.
|
||||
- داخل ACP، يحكم [RBAC](/ar/enterprise/features/rbac) الوصول: `read` للعرض في لوحة المعلومات والسياسات، و`manage` لإنشاء وتعديل وتشغيل/إيقاف وحذف السياسات.
|
||||
- يمكن ضبط نطاق جميع المخططات والجداول إلى **آخر 24 ساعة** أو **الأسبوع الماضي** أو **آخر 30 يوماً** عبر مُحدّد الوقت في أعلى اليمين. تقارن قيم الفرق (`↑ 8 vs yesterday`, `↓ $20.57 vs yesterday` وغيرها) النافذة المختارة بالنافذة السابقة بنفس الطول.
|
||||
|
||||
## ما يمكنك فعله هنا
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="المراقبة" icon="gauge" href="/ar/enterprise/features/agent-control-plane/monitoring">
|
||||
راقب صحة الأسطول وإنفاق LLM عبر بطاقات المقاييس و sankey التفاعلي وجداول لكل أتمتة ولوحات جانبية للتعمق في أي أتمتة أو مزود.
|
||||
</Card>
|
||||
<Card title="السياسات" icon="shield-check" href="/edge/ar/enterprise/features/agent-control-plane/policies">
|
||||
طبّق سياسات PII Redaction على مستوى المؤسسة بنطاق محدد بالأدوات والوسوم. تسري التغييرات في التنفيذ التالي — دون الحاجة لإعادة نشر.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## ذو صلة
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Traces" icon="timeline" href="/ar/enterprise/features/traces">
|
||||
تعمّق في تنفيذ واحد لرؤية تفكير الوكيل واستدعاءات الأدوات واستخدام الرموز.
|
||||
</Card>
|
||||
<Card title="RBAC" icon="users" href="/ar/enterprise/features/rbac">
|
||||
أدِر من يمكنه قراءة Agent Control Plane ومن يمكنه تعديل السياسات.
|
||||
</Card>
|
||||
<Card title="PII Redaction للـ Traces" icon="lock" href="/ar/enterprise/features/pii-trace-redactions">
|
||||
كتالوج الكيانات وضبط PII لكل deployment التي تستند إليها السياسات.
|
||||
</Card>
|
||||
<Card title="النشر إلى AMP" icon="rocket" href="/ar/enterprise/guides/deploy-to-amp">
|
||||
انشر crew على إصدار crewAI يدعم Agent Control Plane.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Card title="تحتاج مساعدة؟" icon="headset" href="mailto:support@crewai.com">
|
||||
تواصل مع فريق الدعم للمساعدة في تفسير المقاييس أو تصميم السياسات.
|
||||
</Card>
|
||||