Compare commits

...

101 Commits

Author SHA1 Message Date
Devin AI
5ec39a70a9 fix: properly test OpenMemory import error scenario
Co-Authored-By: João <joao@crewai.com>
2025-12-07 16:44:08 +00:00
Devin AI
2a62ac0a23 feat: add OpenMemory as optional memory backend
This adds OpenMemory as a pluggable storage backend for CrewAI memory,
following the existing Mem0Storage pattern.

Changes:
- Add OpenMemoryStorage class implementing the Storage interface
- Register OpenMemory provider in ExternalMemory
- Add openmemory-py as optional dependency
- Add comprehensive tests for OpenMemory integration

Closes #4039

Co-Authored-By: João <joao@crewai.com>
2025-12-07 16:39:53 +00:00
Greyson LaLonde
f2f994612c fix: ensure otel span is closed
Some checks failed
Notify Downstream / notify-downstream (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-12-05 13:23:26 -05:00
Greyson LaLonde
7fff2b654c fix: use HuggingFaceEmbeddingFunction for embeddings, update keys and add tests (#4005)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-12-04 15:05:50 -08:00
Greyson LaLonde
34e09162ba feat: async flow kickoff
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Introduces akickoff alias to flows, improves tool decorator typing, ensures _run backward compatibility, updates docs and docstrings, adds tests, and removes duplicated logic.
2025-12-04 17:08:08 -05:00
Greyson LaLonde
24d1fad7ab feat: async crew support
native async crew execution. Improves tool decorator typing, ensures _run backward compatibility, updates docs and docstrings, adds tests, and removes duplicated logic.
2025-12-04 16:53:19 -05:00
Greyson LaLonde
9b8f31fa07 feat: async task support (#4024)
* feat: add async support for tools, add async tool tests

* chore: improve tool decorator typing

* fix: ensure _run backward compat

* chore: update docs

* chore: make docstrings a little more readable

* feat: add async execution support to agent executor

* chore: add tests

* feat: add aiosqlite dep; regenerate lockfile

* feat: add async ops to memory feat; create tests

* feat: async knowledge support; add tests

* feat: add async task support

* chore: dry out duplicate logic
2025-12-04 13:34:29 -08:00
Greyson LaLonde
d898d7c02c feat: async knowledge support (#4023)
* feat: add async support for tools, add async tool tests

* chore: improve tool decorator typing

* fix: ensure _run backward compat

* chore: update docs

* chore: make docstrings a little more readable

* feat: add async execution support to agent executor

* chore: add tests

* feat: add aiosqlite dep; regenerate lockfile

* feat: add async ops to memory feat; create tests

* feat: async knowledge support; add tests

* chore: regenerate lockfile
2025-12-04 10:27:52 -08:00
Greyson LaLonde
f04c40babf feat: async memory support
Adds async support for tools with tests, async execution in the agent executor, and async operations for memory (with aiosqlite). Improves tool decorator typing, ensures _run backward compatibility, updates docs and docstrings, adds tests, and regenerates lockfiles.
2025-12-04 12:54:49 -05:00
Lorenze Jay
c456e5c5fa Lorenze/ensure hooks work with lite agents flows (#3981)
* liteagent support hooks

* wip llm.call hooks work - needs tests for this

* fix tests

* fixed more

* more tool hooks test cassettes
2025-12-04 09:38:39 -08:00
Greyson LaLonde
633e279b51 feat: add async support for tools and agent executor; improve typing and docs
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Introduces async tool support with new tests, adds async execution to the agent executor, improves tool decorator typing, ensures _run backward compatibility, updates docs and docstrings, and adds additional tests.
2025-12-03 20:13:03 -05:00
Greyson LaLonde
a25778974d feat: a2a extensions API and async agent card caching; fix task propagation & streaming
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Adds initial extensions API (with registry temporarily no-op), introduces aiocache for async caching, ensures reference task IDs propagate correctly, fixes streamed response model handling, updates streaming tests, and regenerates lockfiles.
2025-12-03 16:29:48 -05:00
Greyson LaLonde
09f1ba6956 feat: native async tool support
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
- add async support for tools
- add async tool tests
- improve tool decorator typing
- fix _run backward compatibility
- update docs and improve readability of docstrings
2025-12-02 16:39:58 -05:00
Greyson LaLonde
20704742e2 feat: async llm support
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
feat: introduce async contract to BaseLLM

feat: add async call support for:

Azure provider

Anthropic provider

OpenAI provider

Gemini provider

Bedrock provider

LiteLLM provider

chore: expand scrubbed header fields (conftest, anthropic, bedrock)

chore: update docs to cover async functionality

chore: update and harden tests to support acall; re-add uri for cassette compatibility

chore: generate missing cassette

fix: ensure acall is non-abstract and set supports_tools = true for supported Anthropic models

chore: improve Bedrock async docstring and general test robustness
2025-12-01 18:56:56 -05:00
Greyson LaLonde
59180e9c9f fix: ensure supports_tools is true for all supported anthropic models
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
2025-12-01 07:21:09 -05:00
Greyson LaLonde
3ce019b07b chore: pin dependencies in crewai, crewai-tools, devtools
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-30 19:51:20 -05:00
Greyson LaLonde
2355ec0733 feat: create sys event types and handler
feat: add system event types and handler

chore: add tests and improve signal-related error logging
2025-11-30 17:44:40 -05:00
Greyson LaLonde
c925d2d519 chore: restructure test env, cassettes, and conftest; fix flaky tests
Some checks failed
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Consolidates pytest config, standardizes env handling, reorganizes cassette layout, removes outdated VCR configs, improves sync with threading.Condition, updates event-waiting logic, ensures cleanup, regenerates Gemini cassettes, and reverts unintended test changes.
2025-11-29 16:55:24 -05:00
Lorenze Jay
bc4e6a3127 feat: bump versions to 1.6.1 (#3993)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* feat: bump versions to 1.6.1

* chore: update crewAI dependency version to 1.6.1 in project templates
2025-11-28 17:57:15 -08:00
Vidit Ostwal
37526c693b Fixing ChatCompletionsClinet call (#3910)
* Fixing ChatCompletionsClinet call

* Moving from json-object -> JsonSchemaFormat

* Regex handling

* Adding additionalProperties explicitly

* fix: ensure additionalProperties is recursive

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-11-28 17:33:53 -08:00
Greyson LaLonde
c59173a762 fix: ensure async methods are executable for annotations 2025-11-28 19:54:40 -05:00
Lorenze Jay
4d8eec96e8 refactor: enhance model validation and provider inference in LLM class (#3976)
* refactor: enhance model validation and provider inference in LLM class

- Updated the model validation logic to support pattern matching for new models and "latest" versions, improving flexibility for various providers.
- Refactored the `_validate_model_in_constants` method to first check hardcoded constants and then fall back to pattern matching.
- Introduced `_matches_provider_pattern` to streamline provider-specific model checks.
- Enhanced the `_infer_provider_from_model` method to utilize pattern matching for better provider inference.

This refactor aims to improve the extensibility of the LLM class, allowing it to accommodate new models without requiring constant updates to the hardcoded lists.

* feat: add new Anthropic model versions to constants

- Introduced "claude-opus-4-5-20251101" and "claude-opus-4-5" to the AnthropicModels and ANTHROPIC_MODELS lists for enhanced model support.
- Added "anthropic.claude-opus-4-5-20251101-v1:0" to BedrockModels and BEDROCK_MODELS to ensure compatibility with the latest model offerings.
- Updated test cases to ensure proper environment variable handling for model validation, improving robustness in testing scenarios.

* dont infer this way - dropped
2025-11-28 13:54:40 -08:00
Greyson LaLonde
2025a26fc3 fix: ensure parameters in RagTool.add, add typing, tests (#3979)
Some checks failed
Mark stale issues and pull requests / stale (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
* fix: ensure parameters in RagTool.add, add typing, tests

* feat: substitute pymupdf for pypdf, better parsing performance

---------

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-11-26 22:32:43 -08:00
Greyson LaLonde
bed9a3847a fix: remove invalid param from sse client (#3980) 2025-11-26 21:37:55 -08:00
Heitor Carvalho
5239dc9859 fix: erase 'oauth2_extra' setting on 'crewai config reset' command
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
2025-11-26 18:43:44 -05:00
Lorenze Jay
52444ad390 feat: bump versions to 1.6.0 (#3974)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
* feat: bump versions to 1.6.0

* bump project templates
2025-11-24 17:56:30 -08:00
Greyson LaLonde
f070595e65 fix: ensure custom rag store persist path is set if passed
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-11-24 20:03:57 -05:00
Lorenze Jay
69c5eace2d Update references from AMP to AOP in documentation (#3972)
- Changed "AMP" to "AOP" in multiple locations across JSON and MDX files to reflect the correct terminology for the Agent Operations Platform.
- Updated the introduction sections in English, Korean, and Portuguese to ensure consistency in the platform's naming.
2025-11-24 16:43:30 -08:00
Vidit Ostwal
d88ac338d5 Adding drop parameters in ChatCompletionsClient
* Adding drop parameters

* Adding test case

* Just some spacing addition

* Adding drop params to maintain consistency

* Changing variable name

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-11-24 19:16:36 -05:00
Lorenze Jay
4ae8c36815 feat: enhance flow event state management (#3952)
* feat: enhance flow event state management

- Added `state` attribute to `FlowFinishedEvent` to capture the flow's state as a JSON-serialized dictionary.
- Updated flow event emissions to include the serialized state, improving traceability and debugging capabilities during flow execution.

* fix: improve state serialization in Flow class

- Enhanced the `_copy_and_serialize_state` method to handle exceptions during JSON serialization of Pydantic models, ensuring robustness in state management.
- Updated test assertions to access the state as a dictionary, aligning with the new state structure.

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-11-24 15:55:49 -08:00
Greyson LaLonde
b049b73f2e fix: ensure fuzzy returns are more strict, show type warning 2025-11-24 17:35:12 -05:00
Greyson LaLonde
d2b9c54931 fix: re-add openai response_format param, add test 2025-11-24 17:13:20 -05:00
Greyson LaLonde
a928cde6ee fix: rag tool embeddings config
* fix: ensure config is not flattened, add tests

* chore: refactor inits to model_validator

* chore: refactor rag tool config parsing

* chore: add initial docs

* chore: add additional validation aliases for provider env vars

* chore: add solid docs

* chore: move imports to top

* fix: revert circular import

* fix: lazy import qdrant-client

* fix: allow collection name config

* chore: narrow model names for google

* chore: update additional docs

* chore: add backward compat on model name aliases

* chore: add tests for config changes
2025-11-24 16:51:28 -05:00
João Moura
9c84475691 Update AMP to AOP (#3941)
Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-11-24 13:15:24 -08:00
Greyson LaLonde
f3c5d1e351 feat: add streaming result support to flows and crews
* feat: add streaming result support to flows and crews
* docs: add streaming execution documentation and integration tests
2025-11-24 15:43:48 -05:00
Mark McDonald
a978267fa2 feat: Add gemini-3-pro-preview (#3950)
* Add gemini-3-pro-preview

Also refactors the tool support check for better forward compatibility.

* Add cassette for Gemini 3 Pro

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-11-24 14:49:29 -05:00
Heitor Carvalho
b759654e7d feat: support CLI login with Entra ID (#3943) 2025-11-24 15:35:59 -03:00
Greyson LaLonde
9da1f0c0aa fix: ensure flow execution start panel is not shown on plot 2025-11-24 12:50:18 -05:00
Greyson LaLonde
a559cedbd1 chore: ensure proper cassettes for agent tests
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
* chore: ensure proper cassettes for agent tests
* chore: tweak eval test to avoid race condition
2025-11-24 12:29:11 -05:00
Gil Feig
bcc3e358cb feat: Add Merge Agent Handler tool (#3911)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* feat: Add Merge Agent Handler tool

* Fix linting issues

* Empty
2025-11-20 16:58:41 -08:00
Greyson LaLonde
d160f0874a chore: don't fail on cleanup error
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
2025-11-19 01:28:25 -05:00
Lorenze Jay
9fcf55198f feat: bump versions to 1.5.0 (#3924)
Some checks failed
Update Test Durations / update-durations (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Update Test Durations / update-durations (3.10) (push) Has been cancelled
Update Test Durations / update-durations (3.11) (push) Has been cancelled
Update Test Durations / update-durations (3.12) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* feat: bump versions to 1.5.0

* chore: update crewAI tools dependency to version 1.5.0 in project templates
2025-11-15 18:00:11 -08:00
Lorenze Jay
f46a846ddc chore: remove unused hooks test file (#3923)
- Deleted the `__init__.py` file from the tests/hooks directory as it contained no tests or functionality. This cleanup helps maintain a tidy test structure.
2025-11-15 17:51:42 -08:00
Greyson LaLonde
b546982690 fix: ensure instrumentation flags 2025-11-15 20:48:40 -05:00
Greyson LaLonde
d7bdac12a2 feat: a2a trust remote completion status flag
Some checks failed
Notify Downstream / notify-downstream (push) Has been cancelled
Update Test Durations / update-durations (3.10) (push) Has been cancelled
Update Test Durations / update-durations (3.11) (push) Has been cancelled
Update Test Durations / update-durations (3.12) (push) Has been cancelled
Update Test Durations / update-durations (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
- add trust_remote_completion_status flag to A2AConfig, Adds configuration flag to control whether to trust A2A agent completion status. Resolves #3899
- update docs
2025-11-13 13:43:09 -05:00
Lorenze Jay
528d812263 Lorenze/feat hooks (#3902)
* feat: implement LLM call hooks and enhance agent execution context

- Introduced LLM call hooks to allow modification of messages and responses during LLM interactions.
- Added support for before and after hooks in the CrewAgentExecutor, enabling dynamic adjustments to the execution flow.
- Created LLMCallHookContext for comprehensive access to the executor state, facilitating in-place modifications.
- Added validation for hook callables to ensure proper functionality.
- Enhanced tests for LLM hooks and tool hooks to verify their behavior and error handling capabilities.
- Updated LiteAgent and CrewAgentExecutor to accommodate the new crew context in their execution processes.

* feat: implement LLM call hooks and enhance agent execution context

- Introduced LLM call hooks to allow modification of messages and responses during LLM interactions.
- Added support for before and after hooks in the CrewAgentExecutor, enabling dynamic adjustments to the execution flow.
- Created LLMCallHookContext for comprehensive access to the executor state, facilitating in-place modifications.
- Added validation for hook callables to ensure proper functionality.
- Enhanced tests for LLM hooks and tool hooks to verify their behavior and error handling capabilities.
- Updated LiteAgent and CrewAgentExecutor to accommodate the new crew context in their execution processes.

* fix verbose

* feat: introduce crew-scoped hook decorators and refactor hook registration

- Added decorators for before and after LLM and tool calls to enhance flexibility in modifying execution behavior.
- Implemented a centralized hook registration mechanism within CrewBase to automatically register crew-scoped hooks.
- Removed the obsolete base.py file as its functionality has been integrated into the new decorators and registration system.
- Enhanced tests for the new hook decorators to ensure proper registration and execution flow.
- Updated existing hook handling to accommodate the new decorator-based approach, improving code organization and maintainability.

* feat: enhance hook management with clear and unregister functions

- Introduced functions to unregister specific before and after hooks for both LLM and tool calls, improving flexibility in hook management.
- Added clear functions to remove all registered hooks of each type, facilitating easier state management and cleanup.
- Implemented a convenience function to clear all global hooks in one call, streamlining the process for testing and execution context resets.
- Enhanced tests to verify the functionality of unregistering and clearing hooks, ensuring robust behavior in various scenarios.

* refactor: enhance hook type management for LLM and tool hooks

- Updated hook type definitions to use generic protocols for better type safety and flexibility.
- Replaced Callable type annotations with specific BeforeLLMCallHookType and AfterLLMCallHookType for clarity.
- Improved the registration and retrieval functions for before and after hooks to align with the new type definitions.
- Enhanced the setup functions to handle hook execution results, allowing for blocking of LLM calls based on hook logic.
- Updated related tests to ensure proper functionality and type adherence across the hook management system.

* feat: add execution and tool hooks documentation

- Introduced new documentation for execution hooks, LLM call hooks, and tool call hooks to provide comprehensive guidance on their usage and implementation in CrewAI.
- Updated existing documentation to include references to the new hooks, enhancing the learning resources available for users.
- Ensured consistency across multiple languages (English, Portuguese, Korean) for the new documentation, improving accessibility for a wider audience.
- Added examples and troubleshooting sections to assist users in effectively utilizing hooks for agent operations.

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-11-13 10:11:50 -08:00
Greyson LaLonde
ffd717c51a fix: custom tool docs links, add mintlify broken links action (#3903)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Check Documentation Broken Links / Check broken links (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
* fix: update docs links to point to correct endpoints

* fix: update all broken doc links
2025-11-12 22:55:10 -08:00
Heitor Carvalho
fbe4aa4bd1 feat: fetch and store more data about okta authorization server (#3894)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-12 15:28:00 -03:00
Lorenze Jay
c205d2e8de feat: implement before and after LLM call hooks in CrewAgentExecutor (#3893)
- Added support for before and after LLM call hooks to allow modification of messages and responses during LLM interactions.
- Introduced LLMCallHookContext to provide hooks with access to the executor state, enabling in-place modifications of messages.
- Updated get_llm_response function to utilize the new hooks, ensuring that modifications persist across iterations.
- Enhanced tests to verify the functionality of the hooks and their error handling capabilities, ensuring robust execution flow.
2025-11-12 08:38:13 -08:00
Daniel Barreto
fcb5b19b2e Enhance schema description of QdrantVectorSearchTool (#3891)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-11 14:33:33 -08:00
Rip&Tear
01f0111d52 dependabot.yml creation (#3868)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* dependabot.yml creation

* Configure dependabot for pip package updates

Co-authored-by: matt <matt@crewai.com>

* Fix Dependabot package ecosystem

* Refactor: Use uv package-ecosystem in dependabot

Co-authored-by: matt <matt@crewai.com>

* fix: ensure dependabot uses uv ecosystem

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: matt <matt@crewai.com>
2025-11-11 12:14:16 +08:00
Lorenze Jay
6b52587c67 feat: expose messages to TaskOutput and LiteAgentOutputs (#3880)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
* feat: add messages to task and agent outputs

- Introduced a new  field in  and  to capture messages from the last task execution.
- Updated the  class to store the last messages and provide a property for easy access.
- Enhanced the  and  classes to include messages in their outputs.
- Added tests to ensure that messages are correctly included in task outputs and agent outputs during execution.

* using typing_extensions for 3.10 compatability

* feat: add last_messages attribute to agent for improved task tracking

- Introduced a new `last_messages` attribute in the agent class to store messages from the last task execution.
- Updated the `Crew` class to handle the new messages attribute in task outputs.
- Enhanced existing tests to ensure that the `last_messages` attribute is correctly initialized and utilized across various guardrail scenarios.

* fix: add messages field to TaskOutput in tests for consistency

- Updated multiple test cases to include the new `messages` field in the `TaskOutput` instances.
- Ensured that all relevant tests reflect the latest changes in the TaskOutput structure, maintaining consistency across the test suite.
- This change aligns with the recent addition of the `last_messages` attribute in the agent class for improved task tracking.

* feat: preserve messages in task outputs during replay

- Added functionality to the Crew class to store and retrieve messages in task outputs.
- Enhanced the replay mechanism to ensure that messages from stored task outputs are preserved and accessible.
- Introduced a new test case to verify that messages are correctly stored and replayed, ensuring consistency in task execution and output handling.
- This change improves the overall tracking and context retention of task interactions within the CrewAI framework.

* fix original test, prev was debugging
2025-11-10 17:38:30 -08:00
Lorenze Jay
629f7f34ce docs: enhance task guardrail documentation with LLM-based validation support (#3879)
- Added section on LLM-based guardrails, explaining their usage and requirements.
- Updated examples to demonstrate the implementation of multiple guardrails, including both function-based and LLM-based approaches.
- Clarified the distinction between single and multiple guardrails in task configurations.
- Improved explanations of guardrail functionality to ensure better understanding of validation processes.
2025-11-10 15:35:42 -08:00
Lorenze Jay
0f1c173d02 feat: bump versions to 1.4.1 (#3862)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
* feat: bump versions to 1.4.1

* chore: update crewAI tools dependency to version 1.4.1 in project templates
2025-11-07 11:19:07 -08:00
Greyson LaLonde
19c5b9a35e fix: properly handle agent max iterations
fixes #3847
2025-11-07 13:54:11 -05:00
Greyson LaLonde
1ed307b58c fix: route llm model syntax to litellm
* fix: route llm model syntax to litellm

* wip: add list of supported models
2025-11-07 13:34:15 -05:00
Lorenze Jay
d29867bbb6 chore: update version numbers to 1.4.0
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-06 23:04:44 -05:00
Lorenze Jay
b2c278ed22 refactor: improve MCP tool execution handling with concurrent futures (#3854)
- Enhanced the MCP tool execution in both synchronous and asynchronous contexts by utilizing  for better event loop management.
- Updated error handling to provide clearer messages for connection issues and task cancellations.
- Added tests to validate MCP tool execution in both sync and async scenarios, ensuring robust functionality across different contexts.
2025-11-06 19:28:08 -08:00
Greyson LaLonde
f6aed9798b feat: allow non-ast plot routes 2025-11-06 21:17:29 -05:00
Greyson LaLonde
40a2d387a1 fix: keep stopwords updated 2025-11-06 21:10:25 -05:00
Lorenze Jay
6f36d7003b Lorenze/feat mcp first class support (#3850)
* WIP transport support mcp

* refactor: streamline MCP tool loading and error handling

* linted

* Self type from typing with typing_extensions in MCP transport modules

* added tests for mcp setup

* added tests for mcp setup

* docs: enhance MCP overview with detailed integration examples and structured configurations

* feat: implement MCP event handling and logging in event listener and client

- Added MCP event types and handlers for connection and tool execution events.
- Enhanced MCPClient to emit events on connection status and tool execution.
- Updated ConsoleFormatter to handle MCP event logging.
- Introduced new MCP event types for better integration and monitoring.
2025-11-06 17:45:16 -08:00
Greyson LaLonde
9e5906c52f feat: add pydantic validation dunder to BaseInterceptor
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
2025-11-06 15:27:07 -05:00
Lorenze Jay
fc521839e4 Lorenze/fix duplicating doc ids for knowledge (#3840)
* fix: update document ID handling in ChromaDB utility functions to use SHA-256 hashing and include index for uniqueness

* test: add tests for hash-based ID generation in ChromaDB utility functions

* drop idx for preventing dups, upsert should handle dups

* fix: update document ID extraction logic in ChromaDB utility functions to check for doc_id at the top level of the document

* fix: enhance document ID generation in ChromaDB utility functions to deduplicate documents and ensure unique hash-based IDs without suffixes

* fix: improve error handling and document ID generation in ChromaDB utility functions to ensure robust processing and uniqueness
2025-11-06 10:59:52 -08:00
Greyson LaLonde
e4cc9a664c fix: handle unpickleable values in flow state
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-06 01:29:21 -05:00
Greyson LaLonde
7e6171d5bc fix: ensure lite agents course-correct on validation errors
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
* fix: ensure lite agents course-correct on validation errors

* chore: update cassettes and test expectations

* fix: ensure multiple guardrails propogate
2025-11-05 19:02:11 -05:00
Greyson LaLonde
61ad1fb112 feat: add support for llm message interceptor hooks 2025-11-05 11:38:44 -05:00
Greyson LaLonde
54710a8711 fix: hash callback args correctly to ensure caching works
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
2025-11-05 07:19:09 -05:00
Lucas Gomide
5abf976373 fix: allow adding RAG source content from valid URLs (#3831)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-04 07:58:40 -05:00
Greyson LaLonde
329567153b fix: make plot node selection smoother
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-11-03 07:49:31 -05:00
Greyson LaLonde
60332e0b19 feat: cache i18n prompts for efficient use 2025-11-03 07:39:05 -05:00
Lorenze Jay
40932af3fa feat: bump versions to 1.3.0 (#3820)
Some checks failed
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* feat: bump versions to 1.3.0

* chore: update crew and flow templates to use crewai[tools] version 1.3.0
2025-10-31 18:54:02 -07:00
Greyson LaLonde
e134e5305b Gl/feat/a2a refactor (#3793)
* feat: agent metaclass, refactor a2a to wrappers

* feat: a2a schemas and utils

* chore: move agent class, update imports

* refactor: organize imports to avoid circularity, add a2a to console

* feat: pass response_model through call chain

* feat: add standard openapi spec serialization to tools and structured output

* feat: a2a events

* chore: add a2a to pyproject

* docs: minimal base for learn docs

* fix: adjust a2a conversation flow, allow llm to decide exit until max_retries

* fix: inject agent skills into initial prompt

* fix: format agent card as json in prompt

* refactor: simplify A2A agent prompt formatting and improve skill display

* chore: wide cleanup

* chore: cleanup logic, add auth cache, use json for messages in prompt

* chore: update docs

* fix: doc snippets formatting

* feat: optimize A2A agent card fetching and improve error reporting

* chore: move imports to top of file

* chore: refactor hasattr check

* chore: add httpx-auth, update lockfile

* feat: create base public api

* chore: cleanup modules, add docstrings, types

* fix: exclude extra fields in prompt

* chore: update docs

* tests: update to correct import

* chore: lint for ruff, add missing import

* fix: tweak openai streaming logic for response model

* tests: add reimport for test

* tests: add reimport for test

* fix: don't set a2a attr if not set

* fix: don't set a2a attr if not set

* chore: update cassettes

* tests: fix tests

* fix: use instructor and dont pass response_format for litellm

* chore: consolidate event listeners, add typing

* fix: address race condition in test, update cassettes

* tests: add correct mocks, rerun cassette for json

* tests: update cassette

* chore: regenerate cassette after new run

* fix: make token manager access-safe

* fix: make token manager access-safe

* merge

* chore: update test and cassete for output pydantic

* fix: tweak to disallow deadlock

* chore: linter

* fix: adjust event ordering for threading

* fix: use conditional for batch check

* tests: tweak for emission

* tests: simplify api + event check

* fix: ensure non-function calling llms see json formatted string

* tests: tweak message comparison

* fix: use internal instructor for litellm structure responses

---------

Co-authored-by: Mike Plachta <mike@crewai.com>
2025-10-31 18:42:03 -07:00
Greyson LaLonde
e229ef4e19 refactor: improve flow handling, typing, and logging; update UI and tests
fix: refine nested flow conditionals and ensure router methods and routes are fully parsed
fix: improve docstrings, typing, and logging coverage across all events
feat: update flow.plot feature with new UI enhancements
chore: apply Ruff linting, reorganize imports, and remove deprecated utilities/files
chore: split constants and utils, clean JS comments, and add typing for linters
tests: strengthen test coverage for flow execution paths and router logic
2025-10-31 21:15:06 -04:00
Greyson LaLonde
2e9eb8c32d fix: refactor use_stop_words to property, add check for stop words
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
2025-10-29 19:14:01 +01:00
Lucas Gomide
4ebb5114ed Fix Firecrawl tools & adding tests (#3810)
* fix: fix Firecrawl Scrape tool

* fix: fix Firecrawl Search tool

* fix: fix Firecrawl Website tool

* tests: adding tests for Firecrawl
2025-10-29 13:37:57 -04:00
Daniel Barreto
70b083945f Enhance QdrantVectorSearchTool (#3806)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
2025-10-28 13:42:40 -04:00
Tony Kipkemboi
410db1ff39 docs: migrate embedder→embedding_model and require vectordb across tool docs; add provider examples (en/ko/pt-BR) (#3804)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* docs(tools): migrate embedder->embedding_model, require vectordb; add Chroma/Qdrant examples across en/ko/pt-BR PDF/TXT/XML/MDX/DOCX/CSV/Directory docs

* docs(observability): apply latest Datadog tweaks in ko and pt-BR
2025-10-27 13:29:21 -04:00
Lorenze Jay
5d6b4c922b feat: bump versions to 1.2.1 (#3800)
* feat: bump versions to 1.2.1

* updated templates too
2025-10-27 09:12:04 -07:00
Lucas Gomide
b07c0fc45c docs: describe mandatory env-var to call Platform tools for each integration (#3803) 2025-10-27 10:01:41 -04:00
Sam Brenner
97853199c7 Add Datadog Integration Documentation (#3642)
* add datadog llm observability integration guide

* spacing fix

* wording changes

* alphabetize docs listing

* Update docs/en/observability/datadog.mdx

Co-authored-by: Barry Eom <31739208+barieom@users.noreply.github.com>

* add translations

* fix korean code block

---------

Co-authored-by: Barry Eom <31739208+barieom@users.noreply.github.com>
Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-10-27 09:48:38 -04:00
Lorenze Jay
494ed7e671 liteagent supports apps and mcps (#3794)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
* liteagent supports apps and mcps

* generated cassettes for these
2025-10-24 18:42:08 -07:00
Lorenze Jay
a83c57a2f2 feat: bump versions to 1.2.0 (#3787)
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* feat: bump versions to 1.2.0

* also include projects
2025-10-23 18:04:34 -07:00
Lorenze Jay
08e15ab267 fix: update default LLM model and improve error logging in LLM utilities (#3785)
* fix: update default LLM model and improve error logging in LLM utilities

* Updated the default LLM model from "gpt-4o-mini" to "gpt-4.1-mini" for better performance.
* Enhanced error logging in the LLM utilities to use logger.error instead of logger.debug, ensuring that errors are properly reported and raised.
* Added tests to verify behavior when OpenAI API key is missing and when Anthropic dependency is not available, improving robustness and error handling in LLM creation.

* fix: update test for default LLM model usage

* Refactored the test_create_llm_with_none_uses_default_model to use the imported DEFAULT_LLM_MODEL constant instead of a hardcoded string.
* Ensured that the test correctly asserts the model used is the current default, improving maintainability and consistency across tests.

* change default model to gpt-4.1-mini

* change default model use defualt
2025-10-23 17:54:11 -07:00
Greyson LaLonde
9728388ea7 fix: change flow viz del dir; method inspection
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
* chore: update flow viz deletion dir, add typing
* tests: add flow viz tests to ensure lib dir is not deleted
2025-10-22 19:32:38 -04:00
Greyson LaLonde
4371cf5690 chore: remove aisuite
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Little usage + blocking some features
2025-10-21 23:18:06 -04:00
Lorenze Jay
d28daa26cd feat: bump versions to 1.1.0 (#3770)
Some checks failed
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
* feat: bump versions to 1.1.0

* chore: bump template versions

---------

Co-authored-by: Greyson Lalonde <greyson.r.lalonde@gmail.com>
2025-10-21 15:52:44 -07:00
Lorenze Jay
a850813f2b feat: enhance InternalInstructor to support multiple LLM providers (#3767)
* feat: enhance InternalInstructor to support multiple LLM providers

- Updated InternalInstructor to conditionally create an instructor client based on the LLM provider.
- Introduced a new method _create_instructor_client to handle client creation using the modern from_provider pattern.
- Added functionality to extract the provider from the LLM model name.
- Implemented tests for InternalInstructor with various LLM providers including OpenAI, Anthropic, Gemini, and Azure, ensuring robust integration and error handling.

This update improves flexibility and extensibility for different LLM integrations.

* fix test
2025-10-21 15:24:59 -07:00
Cameron Warren
5944a39629 fix: correct broken integration documentation links
Fix navigation paths for two integration tool cards that were redirecting to the
introduction page instead of their intended documentation pages.

Fixes #3516

Co-authored-by: Cwarre33 <cwarre33@charlotte.edu>
Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-10-21 18:12:08 -04:00
Greyson LaLonde
c594859ed0 feat: mypy plugin base
* feat: base mypy plugin with CrewBase

* fix: add crew method to protocol
2025-10-21 17:36:08 -04:00
Daniel Barreto
2ee27efca7 feat: improvements on QdrantVectorSearchTool
* Implement improvements on QdrantVectorSearchTool

- Allow search filters to be set at the constructor level
- Fix issue that prevented multiple records from being returned

* Implement improvements on QdrantVectorSearchTool

- Allow search filters to be set at the constructor level
- Fix issue that prevented multiple records from being returned

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-10-21 16:50:08 -04:00
Greyson LaLonde
f6e13eb890 chore: update codeql config paths to new folders
* chore: update codeql config paths to new folders

* tests: use threading.Condition for event check

---------

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-10-21 14:43:25 -04:00
Lorenze Jay
e7b3ce27ca docs: update LLM integration details and examples
* docs: update LLM integration details and examples

- Changed references from LiteLLM to native SDKs for LLM providers.
- Enhanced OpenAI and AWS Bedrock sections with new usage examples and advanced configuration options.
- Added structured output examples and supported environment variables for better clarity.
- Improved documentation on additional parameters and features for LLM configurations.

* drop this example - should use strucutred output from task instead

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-10-21 14:39:50 -04:00
Greyson LaLonde
dba27cf8b5 fix: fix double trace call; add types
* fix: fix double trace call; add types

* tests: skip long running uv install test, refactor in future

---------

Co-authored-by: Lorenze Jay <63378463+lorenzejay@users.noreply.github.com>
2025-10-21 14:15:39 -04:00
Greyson LaLonde
6469f224f6 chore: improve CrewBase typing 2025-10-21 13:58:35 -04:00
Greyson LaLonde
f3a63be215 tests: cassettes, threading for flow tests 2025-10-21 13:48:21 -04:00
Greyson LaLonde
01d8c189f0 fix: pin template versions to latest
Some checks failed
Notify Downstream / notify-downstream (push) Has been cancelled
2025-10-21 10:56:41 -04:00
Lorenze Jay
cc83c1ead5 feat: bump versions to 1.0.0
Some checks failed
Notify Downstream / notify-downstream (push) Has been cancelled
Update Test Durations / update-durations (3.10) (push) Has been cancelled
Update Test Durations / update-durations (3.11) (push) Has been cancelled
Update Test Durations / update-durations (3.12) (push) Has been cancelled
Update Test Durations / update-durations (3.13) (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
2025-10-20 17:34:38 -04:00
Greyson LaLonde
7578901f6d chore: use main for devtools branch 2025-10-20 17:29:09 -04:00
Lorenze Jay
d1343b96ed Release/v1.0.0 (#3618)
* feat: add `apps` & `actions` attributes to Agent (#3504)

* feat: add app attributes to Agent

* feat: add actions attribute to Agent

* chore: resolve linter issues

* refactor: merge the apps and actions parameters into a single one

* fix: remove unnecessary print

* feat: logging error when CrewaiPlatformTools fails

* chore: export CrewaiPlatformTools directly from crewai_tools

* style: resolver linter issues

* test: fix broken tests

* style: solve linter issues

* fix: fix broken test

* feat: monorepo restructure and test/ci updates

- Add crewai workspace member
- Fix vcr cassette paths and restore test dirs
- Resolve ci failures and update linter/pytest rules

* chore: update python version to 3.13 and package metadata

* feat: add crewai-tools workspace and fix tests/dependencies

* feat: add crewai-tools workspace structure

* Squashed 'temp-crewai-tools/' content from commit 9bae5633

git-subtree-dir: temp-crewai-tools
git-subtree-split: 9bae56339096cb70f03873e600192bd2cd207ac9

* feat: configure crewai-tools workspace package with dependencies

* fix: apply ruff auto-formatting to crewai-tools code

* chore: update lockfile

* fix: don't allow tool tests yet

* fix: comment out extra pytest flags for now

* fix: remove conflicting conftest.py from crewai-tools tests

* fix: resolve dependency conflicts and test issues

- Pin vcrpy to 7.0.0 to fix pytest-recording compatibility
- Comment out types-requests to resolve urllib3 conflict
- Update requests requirement in crewai-tools to >=2.32.0

* chore: update CI workflows and docs for monorepo structure

* chore: update CI workflows and docs for monorepo structure

* fix: actions syntax

* chore: ci publish and pin versions

* fix: add permission to action

* chore: bump version to 1.0.0a1 across all packages

- Updated version to 1.0.0a1 in pyproject.toml for crewai and crewai-tools
- Adjusted version in __init__.py files for consistency

* WIP: v1 docs (#3626)

(cherry picked from commit d46e20fa09bcd2f5916282f5553ddeb7183bd92c)

* docs: parity for all translations

* docs: full name of acronym AMP

* docs: fix lingering unused code

* docs: expand contextual options in docs.json

* docs: add contextual action to request feature on GitHub (#3635)

* chore: apply linting fixes to crewai-tools

* feat: add required env var validation for brightdata

Co-authored-by: Greyson Lalonde <greyson.r.lalonde@gmail.com>

* fix: handle properly anyOf oneOf allOf schema's props

Co-authored-by: Greyson Lalonde <greyson.r.lalonde@gmail.com>

* feat: bump version to 1.0.0a2

* Lorenze/native inference sdks (#3619)

* ruff linted

* using native sdks with litellm fallback

* drop exa

* drop print on completion

* Refactor LLM and utility functions for type consistency

- Updated `max_tokens` parameter in `LLM` class to accept `float` in addition to `int`.
- Modified `create_llm` function to ensure consistent type hints and return types, now returning `LLM | BaseLLM | None`.
- Adjusted type hints for various parameters in `create_llm` and `_llm_via_environment_or_fallback` functions for improved clarity and type safety.
- Enhanced test cases to reflect changes in type handling and ensure proper instantiation of LLM instances.

* fix agent_tests

* fix litellm tests and usagemetrics fix

* drop print

* Refactor LLM event handling and improve test coverage

- Removed commented-out event emission for LLM call failures in `llm.py`.
- Added `from_agent` parameter to `CrewAgentExecutor` for better context in LLM responses.
- Enhanced test for LLM call failure to simulate OpenAI API failure and updated assertions for clarity.
- Updated agent and task ID assertions in tests to ensure they are consistently treated as strings.

* fix test_converter

* fixed tests/agents/test_agent.py

* Refactor LLM context length exception handling and improve provider integration

- Renamed `LLMContextLengthExceededException` to `LLMContextLengthExceededExceptionError` for clarity and consistency.
- Updated LLM class to pass the provider parameter correctly during initialization.
- Enhanced error handling in various LLM provider implementations to raise the new exception type.
- Adjusted tests to reflect the updated exception name and ensure proper error handling in context length scenarios.

* Enhance LLM context window handling across providers

- Introduced CONTEXT_WINDOW_USAGE_RATIO to adjust context window sizes dynamically for Anthropic, Azure, Gemini, and OpenAI LLMs.
- Added validation for context window sizes in Azure and Gemini providers to ensure they fall within acceptable limits.
- Updated context window size calculations to use the new ratio, improving consistency and adaptability across different models.
- Removed hardcoded context window sizes in favor of ratio-based calculations for better flexibility.

* fix test agent again

* fix test agent

* feat: add native LLM providers for Anthropic, Azure, and Gemini

- Introduced new completion implementations for Anthropic, Azure, and Gemini, integrating their respective SDKs.
- Added utility functions for tool validation and extraction to support function calling across LLM providers.
- Enhanced context window management and token usage extraction for each provider.
- Created a common utility module for shared functionality among LLM providers.

* chore: update dependencies and improve context management

- Removed direct dependency on `litellm` from the main dependencies and added it under extras for better modularity.
- Updated the `litellm` dependency specification to allow for greater flexibility in versioning.
- Refactored context length exception handling across various LLM providers to use a consistent error class.
- Enhanced platform-specific dependency markers for NVIDIA packages to ensure compatibility across different systems.

* refactor(tests): update LLM instantiation to include is_litellm flag in test cases

- Modified multiple test cases in test_llm.py to set the is_litellm parameter to True when instantiating the LLM class.
- This change ensures that the tests are aligned with the latest LLM configuration requirements and improves consistency across test scenarios.
- Adjusted relevant assertions and comments to reflect the updated LLM behavior.

* linter

* linted

* revert constants

* fix(tests): correct type hint in expected model description

- Updated the expected description in the test_generate_model_description_dict_field function to use 'Dict' instead of 'dict' for consistency with type hinting conventions.
- This change ensures that the test accurately reflects the expected output format for model descriptions.

* refactor(llm): enhance LLM instantiation and error handling

- Updated the LLM class to include validation for the model parameter, ensuring it is a non-empty string.
- Improved error handling by logging warnings when the native SDK fails, allowing for a fallback to LiteLLM.
- Adjusted the instantiation of LLM in test cases to consistently include the is_litellm flag, aligning with recent changes in LLM configuration.
- Modified relevant tests to reflect these updates, ensuring better coverage and accuracy in testing scenarios.

* fixed test

* refactor(llm): enhance token usage tracking and add copy methods

- Updated the LLM class to track token usage and log callbacks in streaming mode, improving monitoring capabilities.
- Introduced shallow and deep copy methods for the LLM instance, allowing for better management of LLM configurations and parameters.
- Adjusted test cases to instantiate LLM with the is_litellm flag, ensuring alignment with recent changes in LLM configuration.

* refactor(tests): reorganize imports and enhance error messages in test cases

- Cleaned up import statements in test_crew.py for better organization and readability.
- Enhanced error messages in test cases to use `re.escape` for improved regex matching, ensuring more robust error handling.
- Adjusted comments for clarity and consistency across test scenarios.
- Ensured that all necessary modules are imported correctly to avoid potential runtime issues.

* feat: add base devtooling

* fix: ensure dep refs are updated for devtools

* fix: allow pre-release

* feat: allow release after tag

* feat: bump versions to 1.0.0a3 

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>

* fix: match tag and release title, ignore devtools build for pypi

* fix: allow failed pypi publish

* feat: introduce trigger listing and execution commands for local development (#3643)

* chore: exclude tests from ruff linting

* chore: exclude tests from GitHub Actions linter

* fix: replace print statements with logger in agent and memory handling

* chore: add noqa for intentional print in printer utility

* fix: resolve linting errors across codebase

* feat: update docs with new approach to consume Platform Actions (#3675)

* fix: remove duplicate line and add explicit env var

* feat: bump versions to 1.0.0a4 (#3686)

* Update triggers docs (#3678)

* docs: introduce triggers list & triggers run command

* docs: add KO triggers docs

* docs: ensure CREWAI_PLATFORM_INTEGRATION_TOKEN is mentioned on docs (#3687)

* Lorenze/bedrock llm (#3693)

* feat: add AWS Bedrock support and update dependencies

- Introduced BedrockCompletion class for AWS Bedrock integration in LLM.
- Added boto3 as a new dependency in both pyproject.toml and uv.lock.
- Updated LLM class to support Bedrock provider.
- Created new files for Bedrock provider implementation.

* using converse api

* converse

* linted

* refactor: update BedrockCompletion class to improve parameter handling

- Changed max_tokens from a fixed integer to an optional integer.
- Simplified model ID assignment by removing the inference profile mapping method.
- Cleaned up comments and unnecessary code related to tool specifications and model-specific parameters.

* feat: improve event bus thread safety and async support

Add thread-safe, async-compatible event bus with read–write locking and
handler dependency ordering. Remove blinker dependency and implement
direct dispatch. Improve type safety, error handling, and deterministic
event synchronization.

Refactor tests to auto-wait for async handlers, ensure clean teardown,
and add comprehensive concurrency coverage. Replace thread-local state
in AgentEvaluator with instance-based locking for correct cross-thread
access. Enhance tracing reliability and event finalization.

* feat: enhance OpenAICompletion class with additional client parameters (#3701)

* feat: enhance OpenAICompletion class with additional client parameters

- Added support for default_headers, default_query, and client_params in the OpenAICompletion class.
- Refactored client initialization to use a dedicated method for client parameter retrieval.
- Introduced new test cases to validate the correct usage of OpenAICompletion with various parameters.

* fix: correct test case for unsupported OpenAI model

- Updated the test_openai.py to ensure that the LLM instance is created before calling the method, maintaining proper error handling for unsupported models.
- This change ensures that the test accurately checks for the NotFoundError when an invalid model is specified.

* fix: enhance error handling in OpenAICompletion class

- Added specific exception handling for NotFoundError and APIConnectionError in the OpenAICompletion class to provide clearer error messages and improve logging.
- Updated the test case for unsupported models to ensure it raises a ValueError with the appropriate message when a non-existent model is specified.
- This change improves the robustness of the OpenAI API integration and enhances the clarity of error reporting.

* fix: improve test for unsupported OpenAI model handling

- Refactored the test case in test_openai.py to create the LLM instance after mocking the OpenAI client, ensuring proper error handling for unsupported models.
- This change enhances the clarity of the test by accurately checking for ValueError when a non-existent model is specified, aligning with recent improvements in error handling for the OpenAICompletion class.

* feat: bump versions to 1.0.0b1 (#3706)

* Lorenze/tools drop litellm (#3710)

* completely drop litellm and correctly pass config for qdrant

* feat: add support for additional embedding models in EmbeddingService

- Expanded the list of supported embedding models to include Google Vertex, Hugging Face, Jina, Ollama, OpenAI, Roboflow, Watson X, custom embeddings, Sentence Transformers, Text2Vec, OpenClip, and Instructor.
- This enhancement improves the versatility of the EmbeddingService by allowing integration with a wider range of embedding providers.

* fix: update collection parameter handling in CrewAIRagAdapter

- Changed the condition for setting vectors_config in the CrewAIRagAdapter to check for QdrantConfig instance instead of using hasattr. This improves type safety and ensures proper configuration handling for Qdrant integration.

* moved stagehand as optional dep (#3712)

* feat: bump versions to 1.0.0b2 (#3713)

* feat: enhance AnthropicCompletion class with additional client parame… (#3707)

* feat: enhance AnthropicCompletion class with additional client parameters and tool handling

- Added support for client_params in the AnthropicCompletion class to allow for additional client configuration.
- Refactored client initialization to use a dedicated method for retrieving client parameters.
- Implemented a new method to handle tool use conversation flow, ensuring proper execution and response handling.
- Introduced comprehensive test cases to validate the functionality of the AnthropicCompletion class, including tool use scenarios and parameter handling.

* drop print statements

* test: add fixture to mock ANTHROPIC_API_KEY for tests

- Introduced a pytest fixture to automatically mock the ANTHROPIC_API_KEY environment variable for all tests in the test_anthropic.py module.
- This change ensures that tests can run without requiring a real API key, improving test isolation and reliability.

* refactor: streamline streaming message handling in AnthropicCompletion class

- Removed the 'stream' parameter from the API call as it is set internally by the SDK.
- Simplified the handling of tool use events and response construction by extracting token usage from the final message.
- Enhanced the flow for managing tool use conversation, ensuring proper integration with the streaming API response.

* fix streaming here too

* fix: improve error handling in tool conversion for AnthropicCompletion class

- Enhanced exception handling during tool conversion by catching KeyError and ValueError.
- Added logging for conversion errors to aid in debugging and maintain robustness in tool integration.

* feat: enhance GeminiCompletion class with client parameter support (#3717)

* feat: enhance GeminiCompletion class with client parameter support

- Added support for client_params in the GeminiCompletion class to allow for additional client configuration.
- Refactored client initialization into a dedicated method for improved parameter handling.
- Introduced a new method to retrieve client parameters, ensuring compatibility with the base class.
- Enhanced error handling during client initialization to provide clearer messages for missing configuration.
- Updated documentation to reflect the changes in client parameter usage.

* add optional dependancies

* refactor: update test fixture to mock GOOGLE_API_KEY

- Renamed the fixture from `mock_anthropic_api_key` to `mock_google_api_key` to reflect the change in the environment variable being mocked.
- This update ensures that all tests in the module can run with a mocked GOOGLE_API_KEY, improving test isolation and reliability.

* fix tests

* feat: enhance BedrockCompletion class with advanced features

* feat: enhance BedrockCompletion class with advanced features and error handling

- Added support for guardrail configuration, additional model request fields, and custom response field paths in the BedrockCompletion class.
- Improved error handling for AWS exceptions and added token usage tracking with stop reason logging.
- Enhanced streaming response handling with comprehensive event management, including tool use and content block processing.
- Updated documentation to reflect new features and initialization parameters.
- Introduced a new test suite for BedrockCompletion to validate functionality and ensure robust integration with AWS Bedrock APIs.

* chore: add boto typing

* fix: use typing_extensions.Required for Python 3.10 compatibility

---------

Co-authored-by: Greyson Lalonde <greyson.r.lalonde@gmail.com>

* feat: azure native tests

* feat: add Azure AI Inference support and related tests

- Introduced the `azure-ai-inference` package with version `1.0.0b9` and its dependencies in `uv.lock` and `pyproject.toml`.
- Added new test files for Azure LLM functionality, including tests for Azure completion and tool handling.
- Implemented comprehensive test cases to validate Azure-specific behavior and integration with the CrewAI framework.
- Enhanced the testing framework to mock Azure credentials and ensure proper isolation during tests.

* feat: enhance AzureCompletion class with Azure OpenAI support

- Added support for the Azure OpenAI endpoint in the AzureCompletion class, allowing for flexible endpoint configurations.
- Implemented endpoint validation and correction to ensure proper URL formats for Azure OpenAI deployments.
- Enhanced error handling to provide clearer messages for common HTTP errors, including authentication and rate limit issues.
- Updated tests to validate the new endpoint handling and error messaging, ensuring robust integration with Azure AI Inference.
- Refactored parameter preparation to conditionally include the model parameter based on the endpoint type.

* refactor: convert project module to metaclass with full typing

* Lorenze/OpenAI base url backwards support (#3723)

* fix: enhance OpenAICompletion class base URL handling

- Updated the base URL assignment in the OpenAICompletion class to prioritize the new `api_base` attribute and fallback to the environment variable `OPENAI_BASE_URL` if both are not set.
- Added `api_base` to the list of parameters in the OpenAICompletion class to ensure proper configuration and flexibility in API endpoint management.

* feat: enhance OpenAICompletion class with api_base support

- Added the `api_base` parameter to the OpenAICompletion class to allow for flexible API endpoint configuration.
- Updated the `_get_client_params` method to prioritize `base_url` over `api_base`, ensuring correct URL handling.
- Introduced comprehensive tests to validate the behavior of `api_base` and `base_url` in various scenarios, including environment variable fallback.
- Enhanced test coverage for client parameter retrieval, ensuring robust integration with the OpenAI API.

* fix: improve OpenAICompletion class configuration handling

- Added a debug print statement to log the client configuration parameters during initialization for better traceability.
- Updated the base URL assignment logic to ensure it defaults to None if no valid base URL is provided, enhancing robustness in API endpoint configuration.
- Refined the retrieval of the `api_base` environment variable to streamline the configuration process.

* drop print

* feat: improvements on import native sdk support (#3725)

* feat: add support for Anthropic provider and enhance logging

- Introduced the `anthropic` package with version `0.69.0` in `pyproject.toml` and `uv.lock`, allowing for integration with the Anthropic API.
- Updated logging in the LLM class to provide clearer error messages when importing native providers, enhancing debugging capabilities.
- Improved error handling in the AnthropicCompletion class to guide users on installation via the updated error message format.
- Refactored import error handling in other provider classes to maintain consistency in error messaging and installation instructions.

* feat: enhance LLM support with Bedrock provider and update dependencies

- Added support for the `bedrock` provider in the LLM class, allowing integration with AWS Bedrock APIs.
- Updated `uv.lock` to replace `boto3` with `bedrock` in the dependencies, reflecting the new provider structure.
- Introduced `SUPPORTED_NATIVE_PROVIDERS` to include `bedrock` and ensure proper error handling when instantiating native providers.
- Enhanced error handling in the LLM class to raise informative errors when native provider instantiation fails.
- Added tests to validate the behavior of the new Bedrock provider and ensure fallback mechanisms work correctly for unsupported providers.

* test: update native provider fallback tests to expect ImportError

* adjust the test with the expected bevaior - raising ImportError

* this is exoecting the litellm format, all gemini native tests are in test_google.py

---------

Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>

* fix: remove stdout prints, improve test determinism, and update trace handling

Removed `print` statements from the `LLMStreamChunkEvent` handler to prevent
LLM response chunks from being written directly to stdout. The listener now
only tracks chunks internally.

Fixes #3715

Added explicit return statements for trace-related tests.

Updated cassette for `test_failed_evaluation` to reflect new behavior where
an empty trace dict is used instead of returning early.

Ensured deterministic cleanup order in test fixtures by making
`clear_event_bus_handlers` depend on `setup_test_environment`. This guarantees
event bus shutdown and file handle cleanup occur before temporary directory
deletion, resolving intermittent “Directory not empty” errors in CI.

* chore: remove lib/crewai exclusion from pre-commit hooks

* feat: enhance task guardrail functionality and validation

* feat: enhance task guardrail functionality and validation

- Introduced support for multiple guardrails in the Task class, allowing for sequential processing of guardrails.
- Added a new `guardrails` field to the Task model to accept a list of callable guardrails or string descriptions.
- Implemented validation to ensure guardrails are processed correctly, including handling of retries and error messages.
- Enhanced the `_invoke_guardrail_function` method to manage guardrail execution and integrate with existing task output processing.
- Updated tests to cover various scenarios involving multiple guardrails, including success, failure, and retry mechanisms.

This update improves the flexibility and robustness of task execution by allowing for more complex validation scenarios.

* refactor: enhance guardrail type handling in Task model

- Updated the Task class to improve guardrail type definitions, introducing GuardrailType and GuardrailsType for better clarity and type safety.
- Simplified the validation logic for guardrails, ensuring that both single and multiple guardrails are processed correctly.
- Enhanced error messages for guardrail validation to provide clearer feedback when incorrect types are provided.
- This refactor improves the maintainability and robustness of task execution by standardizing guardrail handling.

* feat: implement per-guardrail retry tracking in Task model

- Introduced a new private attribute `_guardrail_retry_counts` to the Task class for tracking retry attempts on a per-guardrail basis.
- Updated the guardrail processing logic to utilize the new retry tracking, allowing for independent retry counts for each guardrail.
- Enhanced error handling to provide clearer feedback when guardrails fail validation after exceeding retry limits.
- Modified existing tests to validate the new retry tracking behavior, ensuring accurate assertions on guardrail retries.

This update improves the robustness and flexibility of task execution by allowing for more granular control over guardrail validation and retry mechanisms.

* chore: 1.0.0b3 bump (#3734)

* chore: full ruff and mypy

improved linting, pre-commit setup, and internal architecture. Configured Ruff to respect .gitignore, added stricter rules, and introduced a lock pre-commit hook with virtualenv activation. Fixed type shadowing in EXASearchTool using a type_ alias to avoid PEP 563 conflicts and resolved circular imports in agent executor and guardrail modules. Removed agent-ops attributes, deprecated watson alias, and dropped crewai-enterprise tools with corresponding test updates. Refactored cache and memoization for thread safety and cleaned up structured output adapters and related logic.

* New MCL DSL (#3738)

* Adding MCP implementation

* New tests for MCP implementation

* fix tests

* update docs

* Revert "New tests for MCP implementation"

This reverts commit 0bbe6dee90.

* linter

* linter

* fix

* verify mcp pacakge exists

* adjust docs to be clear only remote servers are supported

* reverted

* ensure args schema generated properly

* properly close out

---------

Co-authored-by: lorenzejay <lorenzejaytech@gmail.com>
Co-authored-by: Greyson Lalonde <greyson.r.lalonde@gmail.com>

* feat: a2a experimental

experimental a2a support

---------

Co-authored-by: Lucas Gomide <lucaslg200@gmail.com>
Co-authored-by: Greyson LaLonde <greyson.r.lalonde@gmail.com>
Co-authored-by: Tony Kipkemboi <iamtonykipkemboi@gmail.com>
Co-authored-by: Mike Plachta <mplachta@users.noreply.github.com>
Co-authored-by: João Moura <joaomdmoura@gmail.com>
2025-10-20 14:10:19 -07:00
Greyson LaLonde
42f2b4d551 fix: preserve nested condition structure in Flow decorators
Some checks failed
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Notify Downstream / notify-downstream (push) Has been cancelled
Update Test Durations / update-durations (3.10) (push) Has been cancelled
Update Test Durations / update-durations (3.11) (push) Has been cancelled
Update Test Durations / update-durations (3.12) (push) Has been cancelled
Update Test Durations / update-durations (3.13) (push) Has been cancelled
Mark stale issues and pull requests / stale (push) Has been cancelled
Build uv cache / build-cache (3.10) (push) Has been cancelled
Build uv cache / build-cache (3.11) (push) Has been cancelled
Build uv cache / build-cache (3.12) (push) Has been cancelled
Build uv cache / build-cache (3.13) (push) Has been cancelled
Fixes nested boolean conditions being flattened in @listen, @start, and @router decorators. The or_() and and_() combinators now preserve their nested structure using a "conditions" key instead of flattening to a list. Added recursive evaluation logic to properly handle complex patterns like or_(and_(A, B), and_(C, D)).
2025-10-17 17:06:19 -04:00
Greyson LaLonde
0229390ad1 fix: add standard print parameters to Printer.print method
- Adds sep, end, file, and flush parameters to match Python's built-in print function signature.
2025-10-17 15:27:22 -04:00
1768 changed files with 208661 additions and 58734 deletions

161
.env.test Normal file
View File

@@ -0,0 +1,161 @@
# =============================================================================
# Test Environment Variables
# =============================================================================
# This file contains all environment variables needed to run tests locally
# in a way that mimics the GitHub Actions CI environment.
# =============================================================================
# -----------------------------------------------------------------------------
# LLM Provider API Keys
# -----------------------------------------------------------------------------
OPENAI_API_KEY=fake-api-key
ANTHROPIC_API_KEY=fake-anthropic-key
GEMINI_API_KEY=fake-gemini-key
AZURE_API_KEY=fake-azure-key
OPENROUTER_API_KEY=fake-openrouter-key
# -----------------------------------------------------------------------------
# AWS Credentials
# -----------------------------------------------------------------------------
AWS_ACCESS_KEY_ID=fake-aws-access-key
AWS_SECRET_ACCESS_KEY=fake-aws-secret-key
AWS_DEFAULT_REGION=us-east-1
AWS_REGION_NAME=us-east-1
# -----------------------------------------------------------------------------
# Azure OpenAI Configuration
# -----------------------------------------------------------------------------
AZURE_ENDPOINT=https://fake-azure-endpoint.openai.azure.com
AZURE_OPENAI_ENDPOINT=https://fake-azure-endpoint.openai.azure.com
AZURE_OPENAI_API_KEY=fake-azure-openai-key
AZURE_API_VERSION=2024-02-15-preview
OPENAI_API_VERSION=2024-02-15-preview
# -----------------------------------------------------------------------------
# Google Cloud Configuration
# -----------------------------------------------------------------------------
#GOOGLE_CLOUD_PROJECT=fake-gcp-project
#GOOGLE_CLOUD_LOCATION=us-central1
# -----------------------------------------------------------------------------
# OpenAI Configuration
# -----------------------------------------------------------------------------
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_API_BASE=https://api.openai.com/v1
# -----------------------------------------------------------------------------
# Search & Scraping Tool API Keys
# -----------------------------------------------------------------------------
SERPER_API_KEY=fake-serper-key
EXA_API_KEY=fake-exa-key
BRAVE_API_KEY=fake-brave-key
FIRECRAWL_API_KEY=fake-firecrawl-key
TAVILY_API_KEY=fake-tavily-key
SERPAPI_API_KEY=fake-serpapi-key
SERPLY_API_KEY=fake-serply-key
LINKUP_API_KEY=fake-linkup-key
PARALLEL_API_KEY=fake-parallel-key
# -----------------------------------------------------------------------------
# Exa Configuration
# -----------------------------------------------------------------------------
EXA_BASE_URL=https://api.exa.ai
# -----------------------------------------------------------------------------
# Web Scraping & Automation
# -----------------------------------------------------------------------------
BRIGHT_DATA_API_KEY=fake-brightdata-key
BRIGHT_DATA_ZONE=fake-zone
BRIGHTDATA_API_URL=https://api.brightdata.com
BRIGHTDATA_DEFAULT_TIMEOUT=600
BRIGHTDATA_DEFAULT_POLLING_INTERVAL=1
OXYLABS_USERNAME=fake-oxylabs-user
OXYLABS_PASSWORD=fake-oxylabs-pass
SCRAPFLY_API_KEY=fake-scrapfly-key
SCRAPEGRAPH_API_KEY=fake-scrapegraph-key
BROWSERBASE_API_KEY=fake-browserbase-key
BROWSERBASE_PROJECT_ID=fake-browserbase-project
HYPERBROWSER_API_KEY=fake-hyperbrowser-key
MULTION_API_KEY=fake-multion-key
APIFY_API_TOKEN=fake-apify-token
# -----------------------------------------------------------------------------
# Database & Vector Store Credentials
# -----------------------------------------------------------------------------
SINGLESTOREDB_URL=mysql://fake:fake@localhost:3306/fake
SINGLESTOREDB_HOST=localhost
SINGLESTOREDB_PORT=3306
SINGLESTOREDB_USER=fake-user
SINGLESTOREDB_PASSWORD=fake-password
SINGLESTOREDB_DATABASE=fake-database
SINGLESTOREDB_CONNECT_TIMEOUT=30
SNOWFLAKE_USER=fake-snowflake-user
SNOWFLAKE_PASSWORD=fake-snowflake-password
SNOWFLAKE_ACCOUNT=fake-snowflake-account
SNOWFLAKE_WAREHOUSE=fake-snowflake-warehouse
SNOWFLAKE_DATABASE=fake-snowflake-database
SNOWFLAKE_SCHEMA=fake-snowflake-schema
WEAVIATE_URL=http://localhost:8080
WEAVIATE_API_KEY=fake-weaviate-key
EMBEDCHAIN_DB_URI=sqlite:///test.db
# Databricks Credentials
DATABRICKS_HOST=https://fake-databricks.cloud.databricks.com
DATABRICKS_TOKEN=fake-databricks-token
DATABRICKS_CONFIG_PROFILE=fake-profile
# MongoDB Credentials
MONGODB_URI=mongodb://fake:fake@localhost:27017/fake
# -----------------------------------------------------------------------------
# CrewAI Platform & Enterprise
# -----------------------------------------------------------------------------
# setting CREWAI_PLATFORM_INTEGRATION_TOKEN causes these test to fail:
#=========================== short test summary info ============================
#FAILED tests/test_context.py::TestPlatformIntegrationToken::test_platform_context_manager_basic_usage - AssertionError: assert 'fake-platform-token' is None
# + where 'fake-platform-token' = get_platform_integration_token()
#FAILED tests/test_context.py::TestPlatformIntegrationToken::test_context_var_isolation_between_tests - AssertionError: assert 'fake-platform-token' is None
# + where 'fake-platform-token' = get_platform_integration_token()
#FAILED tests/test_context.py::TestPlatformIntegrationToken::test_multiple_sequential_context_managers - AssertionError: assert 'fake-platform-token' is None
# + where 'fake-platform-token' = get_platform_integration_token()
#CREWAI_PLATFORM_INTEGRATION_TOKEN=fake-platform-token
CREWAI_PERSONAL_ACCESS_TOKEN=fake-personal-token
CREWAI_PLUS_URL=https://fake.crewai.com
# -----------------------------------------------------------------------------
# Other Service API Keys
# -----------------------------------------------------------------------------
ZAPIER_API_KEY=fake-zapier-key
PATRONUS_API_KEY=fake-patronus-key
MINDS_API_KEY=fake-minds-key
HF_TOKEN=fake-hf-token
# -----------------------------------------------------------------------------
# Feature Flags/Testing Modes
# -----------------------------------------------------------------------------
CREWAI_DISABLE_TELEMETRY=true
OTEL_SDK_DISABLED=true
CREWAI_TESTING=true
CREWAI_TRACING_ENABLED=false
# -----------------------------------------------------------------------------
# Testing/CI Configuration
# -----------------------------------------------------------------------------
# VCR recording mode: "none" (default), "new_episodes", "all", "once"
PYTEST_VCR_RECORD_MODE=none
# Set to "true" by GitHub when running in GitHub Actions
# GITHUB_ACTIONS=false
# -----------------------------------------------------------------------------
# Python Configuration
# -----------------------------------------------------------------------------
PYTHONUNBUFFERED=1

View File

@@ -2,20 +2,27 @@ name: "CodeQL Config"
paths-ignore:
# Ignore template files - these are boilerplate code that shouldn't be analyzed
- "src/crewai/cli/templates/**"
- "lib/crewai/src/crewai/cli/templates/**"
# Ignore test cassettes - these are test fixtures/recordings
- "tests/cassettes/**"
- "lib/crewai/tests/cassettes/**"
- "lib/crewai-tools/tests/cassettes/**"
# Ignore cache and build artifacts
- ".cache/**"
# Ignore documentation build artifacts
- "docs/.cache/**"
# Ignore experimental code
- "lib/crewai/src/crewai/experimental/a2a/**"
paths:
# Include all Python source code
- "src/**"
# Include tests (but exclude cassettes)
- "tests/**"
# Include all Python source code from workspace packages
- "lib/crewai/src/**"
- "lib/crewai-tools/src/**"
- "lib/devtools/src/**"
# Include tests (but exclude cassettes via paths-ignore)
- "lib/crewai/tests/**"
- "lib/crewai-tools/tests/**"
- "lib/devtools/tests/**"
# Configure specific queries or packs if needed
# queries:
# - uses: security-and-quality
# - uses: security-and-quality

11
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: uv # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"

View File

@@ -15,11 +15,11 @@ on:
push:
branches: [ "main" ]
paths-ignore:
- "src/crewai/cli/templates/**"
- "lib/crewai/src/crewai/cli/templates/**"
pull_request:
branches: [ "main" ]
paths-ignore:
- "src/crewai/cli/templates/**"
- "lib/crewai/src/crewai/cli/templates/**"
jobs:
analyze:

35
.github/workflows/docs-broken-links.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Check Documentation Broken Links
on:
pull_request:
paths:
- "docs/**"
- "docs.json"
push:
branches:
- main
paths:
- "docs/**"
- "docs.json"
workflow_dispatch:
jobs:
check-links:
name: Check broken links
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: "latest"
- name: Install Mintlify CLI
run: npm i -g mintlify
- name: Run broken link checker
run: |
# Auto-answer the prompt with yes command
yes "" | mintlify broken-links || test $? -eq 141
working-directory: ./docs

View File

@@ -52,10 +52,11 @@ jobs:
- name: Run Ruff on Changed Files
if: ${{ steps.changed-files.outputs.files != '' }}
run: |
echo "${{ steps.changed-files.outputs.files }}" \
| tr ' ' '\n' \
| grep -v 'src/crewai/cli/templates/' \
| xargs -I{} uv run ruff check "{}"
echo "${{ steps.changed-files.outputs.files }}" \
| tr ' ' '\n' \
| grep -v 'src/crewai/cli/templates/' \
| grep -v '/tests/' \
| xargs -I{} uv run ruff check "{}"
- name: Save uv caches
if: steps.cache-restore.outputs.cache-hit != 'true'

81
.github/workflows/publish.yml vendored Normal file
View File

@@ -0,0 +1,81 @@
name: Publish to PyPI
on:
release:
types: [ published ]
workflow_dispatch:
jobs:
build:
name: Build packages
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install uv
uses: astral-sh/setup-uv@v4
- name: Build packages
run: |
uv build --all-packages
rm dist/.gitignore
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
publish:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
environment:
name: pypi
url: https://pypi.org/p/crewai
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v6
with:
version: "0.8.4"
python-version: "3.12"
enable-cache: false
- name: Download artifacts
uses: actions/download-artifact@v4
with:
name: dist
path: dist
- name: Publish to PyPI
env:
UV_PUBLISH_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
run: |
failed=0
for package in dist/*; do
if [[ "$package" == *"crewai_devtools"* ]]; then
echo "Skipping private package: $package"
continue
fi
echo "Publishing $package"
if ! uv publish "$package"; then
echo "Failed to publish $package"
failed=1
fi
done
if [ $failed -eq 1 ]; then
echo "Some packages failed to publish"
exit 1
fi

View File

@@ -5,10 +5,6 @@ on: [pull_request]
permissions:
contents: read
env:
OPENAI_API_KEY: fake-api-key
PYTHONUNBUFFERED: 1
jobs:
tests:
name: tests (${{ matrix.python-version }})
@@ -56,13 +52,13 @@ jobs:
- name: Run tests (group ${{ matrix.group }} of 8)
run: |
PYTHON_VERSION_SAFE=$(echo "${{ matrix.python-version }}" | tr '.' '_')
DURATION_FILE=".test_durations_py${PYTHON_VERSION_SAFE}"
DURATION_FILE="../../.test_durations_py${PYTHON_VERSION_SAFE}"
# Temporarily always skip cached durations to fix test splitting
# When durations don't match, pytest-split runs duplicate tests instead of splitting
echo "Using even test splitting (duration cache disabled until fix merged)"
DURATIONS_ARG=""
# Original logic (disabled temporarily):
# if [ ! -f "$DURATION_FILE" ]; then
# echo "No cached durations found, tests will be split evenly"
@@ -74,18 +70,25 @@ jobs:
# echo "No test changes detected, using cached test durations for optimal splitting"
# DURATIONS_ARG="--durations-path=${DURATION_FILE}"
# fi
uv run pytest \
--block-network \
--timeout=30 \
cd lib/crewai && uv run pytest \
-vv \
--splits 8 \
--group ${{ matrix.group }} \
$DURATIONS_ARG \
--durations=10 \
-n auto \
--maxfail=3
- name: Run tool tests (group ${{ matrix.group }} of 8)
run: |
cd lib/crewai-tools && uv run pytest \
-vv \
--splits 8 \
--group ${{ matrix.group }} \
--durations=10 \
--maxfail=3
- name: Save uv caches
if: steps.cache-restore.outputs.cache-hit != 'true'
uses: actions/cache/save@v4

1
.gitignore vendored
View File

@@ -2,7 +2,6 @@
.pytest_cache
__pycache__
dist/
lib/
.env
assets/*
.idea

View File

@@ -3,17 +3,25 @@ repos:
hooks:
- id: ruff
name: ruff
entry: uv run ruff check
entry: bash -c 'source .venv/bin/activate && uv run ruff check --config pyproject.toml "$@"' --
language: system
pass_filenames: true
types: [python]
- id: ruff-format
name: ruff-format
entry: uv run ruff format
entry: bash -c 'source .venv/bin/activate && uv run ruff format --config pyproject.toml "$@"' --
language: system
pass_filenames: true
types: [python]
- id: mypy
name: mypy
entry: uv run mypy
entry: bash -c 'source .venv/bin/activate && uv run mypy --config-file pyproject.toml "$@"' --
language: system
pass_filenames: true
types: [python]
exclude: ^tests/
exclude: ^(lib/crewai/src/crewai/cli/templates/|lib/crewai/tests/|lib/crewai-tools/tests/)
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.9.3
hooks:
- id: uv-lock

View File

@@ -62,9 +62,9 @@
With over 100,000 developers certified through our community courses at [learn.crewai.com](https://learn.crewai.com), CrewAI is rapidly becoming the
standard for enterprise-ready AI automation.
# CrewAI AMP Suite
# CrewAI AOP Suite
CrewAI AMP Suite is a comprehensive bundle tailored for organizations that require secure, scalable, and easy-to-manage agent-driven automation.
CrewAI AOP Suite is a comprehensive bundle tailored for organizations that require secure, scalable, and easy-to-manage agent-driven automation.
You can try one part of the suite the [Crew Control Plane for free](https://app.crewai.com)
@@ -76,9 +76,9 @@ You can try one part of the suite the [Crew Control Plane for free](https://app.
- **Advanced Security**: Built-in robust security and compliance measures ensuring safe deployment and management.
- **Actionable Insights**: Real-time analytics and reporting to optimize performance and decision-making.
- **24/7 Support**: Dedicated enterprise support to ensure uninterrupted operation and quick resolution of issues.
- **On-premise and Cloud Deployment Options**: Deploy CrewAI AMP on-premise or in the cloud, depending on your security and compliance requirements.
- **On-premise and Cloud Deployment Options**: Deploy CrewAI AOP on-premise or in the cloud, depending on your security and compliance requirements.
CrewAI AMP is designed for enterprises seeking a powerful, reliable solution to transform complex business processes into efficient,
CrewAI AOP is designed for enterprises seeking a powerful, reliable solution to transform complex business processes into efficient,
intelligent automations.
## Table of contents
@@ -674,9 +674,9 @@ CrewAI is released under the [MIT License](https://github.com/crewAIInc/crewAI/b
### Enterprise Features
- [What additional features does CrewAI AMP offer?](#q-what-additional-features-does-crewai-amp-offer)
- [Is CrewAI AMP available for cloud and on-premise deployments?](#q-is-crewai-amp-available-for-cloud-and-on-premise-deployments)
- [Can I try CrewAI AMP for free?](#q-can-i-try-crewai-amp-for-free)
- [What additional features does CrewAI AOP offer?](#q-what-additional-features-does-crewai-amp-offer)
- [Is CrewAI AOP available for cloud and on-premise deployments?](#q-is-crewai-amp-available-for-cloud-and-on-premise-deployments)
- [Can I try CrewAI AOP for free?](#q-can-i-try-crewai-amp-for-free)
### Q: What exactly is CrewAI?
@@ -732,17 +732,17 @@ A: Check out practical examples in the [CrewAI-examples repository](https://gith
A: Contributions are warmly welcomed! Fork the repository, create your branch, implement your changes, and submit a pull request. See the Contribution section of the README for detailed guidelines.
### Q: What additional features does CrewAI AMP offer?
### Q: What additional features does CrewAI AOP offer?
A: CrewAI AMP provides advanced features such as a unified control plane, real-time observability, secure integrations, advanced security, actionable insights, and dedicated 24/7 enterprise support.
A: CrewAI AOP provides advanced features such as a unified control plane, real-time observability, secure integrations, advanced security, actionable insights, and dedicated 24/7 enterprise support.
### Q: Is CrewAI AMP available for cloud and on-premise deployments?
### Q: Is CrewAI AOP available for cloud and on-premise deployments?
A: Yes, CrewAI AMP supports both cloud-based and on-premise deployment options, allowing enterprises to meet their specific security and compliance requirements.
A: Yes, CrewAI AOP supports both cloud-based and on-premise deployment options, allowing enterprises to meet their specific security and compliance requirements.
### Q: Can I try CrewAI AMP for free?
### Q: Can I try CrewAI AOP for free?
A: Yes, you can explore part of the CrewAI AMP Suite by accessing the [Crew Control Plane](https://app.crewai.com) for free.
A: Yes, you can explore part of the CrewAI AOP Suite by accessing the [Crew Control Plane](https://app.crewai.com) for free.
### Q: Does CrewAI support fine-tuning or training custom models?
@@ -762,7 +762,7 @@ A: CrewAI is highly scalable, supporting simple automations and large-scale ente
### Q: Does CrewAI offer debugging and monitoring tools?
A: Yes, CrewAI AMP includes advanced debugging, tracing, and real-time observability features, simplifying the management and troubleshooting of your automations.
A: Yes, CrewAI AOP includes advanced debugging, tracing, and real-time observability features, simplifying the management and troubleshooting of your automations.
### Q: What programming languages does CrewAI support?

193
conftest.py Normal file
View File

@@ -0,0 +1,193 @@
"""Pytest configuration for crewAI workspace."""
from collections.abc import Generator
import os
from pathlib import Path
import tempfile
from typing import Any
from dotenv import load_dotenv
import pytest
from vcr.request import Request # type: ignore[import-untyped]
env_test_path = Path(__file__).parent / ".env.test"
load_dotenv(env_test_path, override=True)
load_dotenv(override=True)
@pytest.fixture(autouse=True, scope="function")
def cleanup_event_handlers() -> Generator[None, Any, None]:
"""Clean up event bus handlers after each test to prevent test pollution."""
yield
try:
from crewai.events.event_bus import crewai_event_bus
with crewai_event_bus._rwlock.w_locked():
crewai_event_bus._sync_handlers.clear()
crewai_event_bus._async_handlers.clear()
except Exception: # noqa: S110
pass
@pytest.fixture(autouse=True, scope="function")
def setup_test_environment() -> Generator[None, Any, None]:
"""Setup test environment for crewAI workspace."""
with tempfile.TemporaryDirectory() as temp_dir:
storage_dir = Path(temp_dir) / "crewai_test_storage"
storage_dir.mkdir(parents=True, exist_ok=True)
if not storage_dir.exists() or not storage_dir.is_dir():
raise RuntimeError(
f"Failed to create test storage directory: {storage_dir}"
)
try:
test_file = storage_dir / ".permissions_test"
test_file.touch()
test_file.unlink()
except (OSError, IOError) as e:
raise RuntimeError(
f"Test storage directory {storage_dir} is not writable: {e}"
) from e
os.environ["CREWAI_STORAGE_DIR"] = str(storage_dir)
os.environ["CREWAI_TESTING"] = "true"
try:
yield
finally:
os.environ.pop("CREWAI_TESTING", "true")
os.environ.pop("CREWAI_STORAGE_DIR", None)
os.environ.pop("CREWAI_DISABLE_TELEMETRY", "true")
os.environ.pop("OTEL_SDK_DISABLED", "true")
os.environ.pop("OPENAI_BASE_URL", "https://api.openai.com/v1")
os.environ.pop("OPENAI_API_BASE", "https://api.openai.com/v1")
HEADERS_TO_FILTER = {
"authorization": "AUTHORIZATION-XXX",
"content-security-policy": "CSP-FILTERED",
"cookie": "COOKIE-XXX",
"set-cookie": "SET-COOKIE-XXX",
"permissions-policy": "PERMISSIONS-POLICY-XXX",
"referrer-policy": "REFERRER-POLICY-XXX",
"strict-transport-security": "STS-XXX",
"x-content-type-options": "X-CONTENT-TYPE-XXX",
"x-frame-options": "X-FRAME-OPTIONS-XXX",
"x-permitted-cross-domain-policies": "X-PERMITTED-XXX",
"x-request-id": "X-REQUEST-ID-XXX",
"x-runtime": "X-RUNTIME-XXX",
"x-xss-protection": "X-XSS-PROTECTION-XXX",
"x-stainless-arch": "X-STAINLESS-ARCH-XXX",
"x-stainless-os": "X-STAINLESS-OS-XXX",
"x-stainless-read-timeout": "X-STAINLESS-READ-TIMEOUT-XXX",
"cf-ray": "CF-RAY-XXX",
"etag": "ETAG-XXX",
"Strict-Transport-Security": "STS-XXX",
"access-control-expose-headers": "ACCESS-CONTROL-XXX",
"openai-organization": "OPENAI-ORG-XXX",
"openai-project": "OPENAI-PROJECT-XXX",
"x-ratelimit-limit-requests": "X-RATELIMIT-LIMIT-REQUESTS-XXX",
"x-ratelimit-limit-tokens": "X-RATELIMIT-LIMIT-TOKENS-XXX",
"x-ratelimit-remaining-requests": "X-RATELIMIT-REMAINING-REQUESTS-XXX",
"x-ratelimit-remaining-tokens": "X-RATELIMIT-REMAINING-TOKENS-XXX",
"x-ratelimit-reset-requests": "X-RATELIMIT-RESET-REQUESTS-XXX",
"x-ratelimit-reset-tokens": "X-RATELIMIT-RESET-TOKENS-XXX",
"x-goog-api-key": "X-GOOG-API-KEY-XXX",
"api-key": "X-API-KEY-XXX",
"User-Agent": "X-USER-AGENT-XXX",
"apim-request-id:": "X-API-CLIENT-REQUEST-ID-XXX",
"azureml-model-session": "AZUREML-MODEL-SESSION-XXX",
"x-ms-client-request-id": "X-MS-CLIENT-REQUEST-ID-XXX",
"x-ms-region": "X-MS-REGION-XXX",
"apim-request-id": "APIM-REQUEST-ID-XXX",
"x-api-key": "X-API-KEY-XXX",
"anthropic-organization-id": "ANTHROPIC-ORGANIZATION-ID-XXX",
"request-id": "REQUEST-ID-XXX",
"anthropic-ratelimit-input-tokens-limit": "ANTHROPIC-RATELIMIT-INPUT-TOKENS-LIMIT-XXX",
"anthropic-ratelimit-input-tokens-remaining": "ANTHROPIC-RATELIMIT-INPUT-TOKENS-REMAINING-XXX",
"anthropic-ratelimit-input-tokens-reset": "ANTHROPIC-RATELIMIT-INPUT-TOKENS-RESET-XXX",
"anthropic-ratelimit-output-tokens-limit": "ANTHROPIC-RATELIMIT-OUTPUT-TOKENS-LIMIT-XXX",
"anthropic-ratelimit-output-tokens-remaining": "ANTHROPIC-RATELIMIT-OUTPUT-TOKENS-REMAINING-XXX",
"anthropic-ratelimit-output-tokens-reset": "ANTHROPIC-RATELIMIT-OUTPUT-TOKENS-RESET-XXX",
"anthropic-ratelimit-tokens-limit": "ANTHROPIC-RATELIMIT-TOKENS-LIMIT-XXX",
"anthropic-ratelimit-tokens-remaining": "ANTHROPIC-RATELIMIT-TOKENS-REMAINING-XXX",
"anthropic-ratelimit-tokens-reset": "ANTHROPIC-RATELIMIT-TOKENS-RESET-XXX",
"x-amz-date": "X-AMZ-DATE-XXX",
"amz-sdk-invocation-id": "AMZ-SDK-INVOCATION-ID-XXX",
"accept-encoding": "ACCEPT-ENCODING-XXX",
"x-amzn-requestid": "X-AMZN-REQUESTID-XXX",
"x-amzn-RequestId": "X-AMZN-REQUESTID-XXX",
}
def _filter_request_headers(request: Request) -> Request: # type: ignore[no-any-unimported]
"""Filter sensitive headers from request before recording."""
for header_name, replacement in HEADERS_TO_FILTER.items():
for variant in [header_name, header_name.upper(), header_name.title()]:
if variant in request.headers:
request.headers[variant] = [replacement]
request.method = request.method.upper()
return request
def _filter_response_headers(response: dict[str, Any]) -> dict[str, Any]:
"""Filter sensitive headers from response before recording."""
for header_name, replacement in HEADERS_TO_FILTER.items():
for variant in [header_name, header_name.upper(), header_name.title()]:
if variant in response["headers"]:
response["headers"][variant] = [replacement]
return response
@pytest.fixture(scope="module")
def vcr_cassette_dir(request: Any) -> str:
"""Generate cassette directory path based on test module location.
Organizes cassettes to mirror test directory structure within each package:
lib/crewai/tests/llms/google/test_google.py -> lib/crewai/tests/cassettes/llms/google/
lib/crewai-tools/tests/tools/test_search.py -> lib/crewai-tools/tests/cassettes/tools/
"""
test_file = Path(request.fspath)
for parent in test_file.parents:
if parent.name in ("crewai", "crewai-tools") and parent.parent.name == "lib":
package_root = parent
break
else:
package_root = test_file.parent
tests_root = package_root / "tests"
test_dir = test_file.parent
if test_dir != tests_root:
relative_path = test_dir.relative_to(tests_root)
cassette_dir = tests_root / "cassettes" / relative_path
else:
cassette_dir = tests_root / "cassettes"
cassette_dir.mkdir(parents=True, exist_ok=True)
return str(cassette_dir)
@pytest.fixture(scope="module")
def vcr_config(vcr_cassette_dir: str) -> dict[str, Any]:
"""Configure VCR with organized cassette storage."""
config = {
"cassette_library_dir": vcr_cassette_dir,
"record_mode": os.getenv("PYTEST_VCR_RECORD_MODE", "once"),
"filter_headers": [(k, v) for k, v in HEADERS_TO_FILTER.items()],
"before_record_request": _filter_request_headers,
"before_record_response": _filter_response_headers,
"filter_query_parameters": ["key"],
"match_on": ["method", "scheme", "host", "port", "path"],
}
if os.getenv("GITHUB_ACTIONS") == "true":
config["record_mode"] = "none"
return config

View File

@@ -134,6 +134,7 @@
"group": "MCP Integration",
"pages": [
"en/mcp/overview",
"en/mcp/dsl-integration",
"en/mcp/stdio",
"en/mcp/sse",
"en/mcp/streamable-http",
@@ -275,6 +276,7 @@
"en/observability/overview",
"en/observability/arize-phoenix",
"en/observability/braintrust",
"en/observability/datadog",
"en/observability/langdb",
"en/observability/langfuse",
"en/observability/langtrace",
@@ -311,7 +313,10 @@
"en/learn/multimodal-agents",
"en/learn/replay-tasks-from-latest-crew-kickoff",
"en/learn/sequential-process",
"en/learn/using-annotations"
"en/learn/using-annotations",
"en/learn/execution-hooks",
"en/learn/llm-hooks",
"en/learn/tool-hooks"
]
},
{
@@ -321,7 +326,7 @@
]
},
{
"tab": "AMP",
"tab": "AOP",
"icon": "briefcase",
"groups": [
{
@@ -361,10 +366,20 @@
"en/enterprise/integrations/github",
"en/enterprise/integrations/gmail",
"en/enterprise/integrations/google_calendar",
"en/enterprise/integrations/google_contacts",
"en/enterprise/integrations/google_docs",
"en/enterprise/integrations/google_drive",
"en/enterprise/integrations/google_sheets",
"en/enterprise/integrations/google_slides",
"en/enterprise/integrations/hubspot",
"en/enterprise/integrations/jira",
"en/enterprise/integrations/linear",
"en/enterprise/integrations/microsoft_excel",
"en/enterprise/integrations/microsoft_onedrive",
"en/enterprise/integrations/microsoft_outlook",
"en/enterprise/integrations/microsoft_sharepoint",
"en/enterprise/integrations/microsoft_teams",
"en/enterprise/integrations/microsoft_word",
"en/enterprise/integrations/notion",
"en/enterprise/integrations/salesforce",
"en/enterprise/integrations/shopify",
@@ -560,6 +575,7 @@
"group": "Integração MCP",
"pages": [
"pt-BR/mcp/overview",
"pt-BR/mcp/dsl-integration",
"pt-BR/mcp/stdio",
"pt-BR/mcp/sse",
"pt-BR/mcp/streamable-http",
@@ -688,6 +704,7 @@
"pt-BR/observability/overview",
"pt-BR/observability/arize-phoenix",
"pt-BR/observability/braintrust",
"pt-BR/observability/datadog",
"pt-BR/observability/langdb",
"pt-BR/observability/langfuse",
"pt-BR/observability/langtrace",
@@ -723,7 +740,10 @@
"pt-BR/learn/multimodal-agents",
"pt-BR/learn/replay-tasks-from-latest-crew-kickoff",
"pt-BR/learn/sequential-process",
"pt-BR/learn/using-annotations"
"pt-BR/learn/using-annotations",
"pt-BR/learn/execution-hooks",
"pt-BR/learn/llm-hooks",
"pt-BR/learn/tool-hooks"
]
},
{
@@ -733,7 +753,7 @@
]
},
{
"tab": "AMP",
"tab": "AOP",
"icon": "briefcase",
"groups": [
{
@@ -773,10 +793,20 @@
"pt-BR/enterprise/integrations/github",
"pt-BR/enterprise/integrations/gmail",
"pt-BR/enterprise/integrations/google_calendar",
"pt-BR/enterprise/integrations/google_contacts",
"pt-BR/enterprise/integrations/google_docs",
"pt-BR/enterprise/integrations/google_drive",
"pt-BR/enterprise/integrations/google_sheets",
"pt-BR/enterprise/integrations/google_slides",
"pt-BR/enterprise/integrations/hubspot",
"pt-BR/enterprise/integrations/jira",
"pt-BR/enterprise/integrations/linear",
"pt-BR/enterprise/integrations/microsoft_excel",
"pt-BR/enterprise/integrations/microsoft_onedrive",
"pt-BR/enterprise/integrations/microsoft_outlook",
"pt-BR/enterprise/integrations/microsoft_sharepoint",
"pt-BR/enterprise/integrations/microsoft_teams",
"pt-BR/enterprise/integrations/microsoft_word",
"pt-BR/enterprise/integrations/notion",
"pt-BR/enterprise/integrations/salesforce",
"pt-BR/enterprise/integrations/shopify",
@@ -805,6 +835,12 @@
"group": "Triggers",
"pages": [
"pt-BR/enterprise/guides/automation-triggers",
"pt-BR/enterprise/guides/gmail-trigger",
"pt-BR/enterprise/guides/google-calendar-trigger",
"pt-BR/enterprise/guides/google-drive-trigger",
"pt-BR/enterprise/guides/outlook-trigger",
"pt-BR/enterprise/guides/onedrive-trigger",
"pt-BR/enterprise/guides/microsoft-teams-trigger",
"pt-BR/enterprise/guides/slack-trigger",
"pt-BR/enterprise/guides/hubspot-trigger",
"pt-BR/enterprise/guides/salesforce-trigger",
@@ -963,6 +999,7 @@
"group": "MCP 통합",
"pages": [
"ko/mcp/overview",
"ko/mcp/dsl-integration",
"ko/mcp/stdio",
"ko/mcp/sse",
"ko/mcp/streamable-http",
@@ -1103,6 +1140,7 @@
"ko/observability/overview",
"ko/observability/arize-phoenix",
"ko/observability/braintrust",
"ko/observability/datadog",
"ko/observability/langdb",
"ko/observability/langfuse",
"ko/observability/langtrace",
@@ -1138,7 +1176,10 @@
"ko/learn/multimodal-agents",
"ko/learn/replay-tasks-from-latest-crew-kickoff",
"ko/learn/sequential-process",
"ko/learn/using-annotations"
"ko/learn/using-annotations",
"ko/learn/execution-hooks",
"ko/learn/llm-hooks",
"ko/learn/tool-hooks"
]
},
{
@@ -1188,10 +1229,20 @@
"ko/enterprise/integrations/github",
"ko/enterprise/integrations/gmail",
"ko/enterprise/integrations/google_calendar",
"ko/enterprise/integrations/google_contacts",
"ko/enterprise/integrations/google_docs",
"ko/enterprise/integrations/google_drive",
"ko/enterprise/integrations/google_sheets",
"ko/enterprise/integrations/google_slides",
"ko/enterprise/integrations/hubspot",
"ko/enterprise/integrations/jira",
"ko/enterprise/integrations/linear",
"ko/enterprise/integrations/microsoft_excel",
"ko/enterprise/integrations/microsoft_onedrive",
"ko/enterprise/integrations/microsoft_outlook",
"ko/enterprise/integrations/microsoft_sharepoint",
"ko/enterprise/integrations/microsoft_teams",
"ko/enterprise/integrations/microsoft_word",
"ko/enterprise/integrations/notion",
"ko/enterprise/integrations/salesforce",
"ko/enterprise/integrations/shopify",
@@ -1220,6 +1271,12 @@
"group": "트리거",
"pages": [
"ko/enterprise/guides/automation-triggers",
"ko/enterprise/guides/gmail-trigger",
"ko/enterprise/guides/google-calendar-trigger",
"ko/enterprise/guides/google-drive-trigger",
"ko/enterprise/guides/outlook-trigger",
"ko/enterprise/guides/onedrive-trigger",
"ko/enterprise/guides/microsoft-teams-trigger",
"ko/enterprise/guides/slack-trigger",
"ko/enterprise/guides/hubspot-trigger",
"ko/enterprise/guides/salesforce-trigger",

View File

@@ -1,19 +1,19 @@
---
title: "Introduction"
description: "Complete reference for the CrewAI AMP REST API"
description: "Complete reference for the CrewAI AOP REST API"
icon: "code"
mode: "wide"
---
# CrewAI AMP API
# CrewAI AOP API
Welcome to the CrewAI AMP API reference. This API allows you to programmatically interact with your deployed crews, enabling integration with your applications, workflows, and services.
Welcome to the CrewAI AOP API reference. This API allows you to programmatically interact with your deployed crews, enabling integration with your applications, workflows, and services.
## Quick Start
<Steps>
<Step title="Get Your API Credentials">
Navigate to your crew's detail page in the CrewAI AMP dashboard and copy your Bearer Token from the Status tab.
Navigate to your crew's detail page in the CrewAI AOP dashboard and copy your Bearer Token from the Status tab.
</Step>
<Step title="Discover Required Inputs">
@@ -46,7 +46,7 @@ curl -H "Authorization: Bearer YOUR_CREW_TOKEN" \
| **User Bearer Token** | User-scoped access | Limited permissions, suitable for user-specific operations |
<Tip>
You can find both token types in the Status tab of your crew's detail page in the CrewAI AMP dashboard.
You can find both token types in the Status tab of your crew's detail page in the CrewAI AOP dashboard.
</Tip>
## Base URL
@@ -82,7 +82,7 @@ The API uses standard HTTP status codes:
## Interactive Testing
<Info>
**Why no "Send" button?** Since each CrewAI AMP user has their own unique crew URL, we use **reference mode** instead of an interactive playground to avoid confusion. This shows you exactly what the requests should look like without non-functional send buttons.
**Why no "Send" button?** Since each CrewAI AOP user has their own unique crew URL, we use **reference mode** instead of an interactive playground to avoid confusion. This shows you exactly what the requests should look like without non-functional send buttons.
</Info>
Each endpoint page shows you:

View File

@@ -20,7 +20,7 @@ Think of an agent as a specialized team member with specific skills, expertise,
</Tip>
<Note type="info" title="Enterprise Enhancement: Visual Agent Builder">
CrewAI AMP includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time.
CrewAI AOP includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time.
![Visual Agent Builder Screenshot](/images/enterprise/crew-studio-interface.png)

View File

@@ -5,7 +5,7 @@ icon: terminal
mode: "wide"
---
<Warning>Since release 0.140.0, CrewAI AMP started a process of migrating their login provider. As such, the authentication flow via CLI was updated. Users that use Google to login, or that created their account after July 3rd, 2025 will be unable to log in with older versions of the `crewai` library.</Warning>
<Warning>Since release 0.140.0, CrewAI AOP started a process of migrating their login provider. As such, the authentication flow via CLI was updated. Users that use Google to login, or that created their account after July 3rd, 2025 will be unable to log in with older versions of the `crewai` library.</Warning>
## Overview
@@ -186,9 +186,9 @@ def crew(self) -> Crew:
### 10. Deploy
Deploy the crew or flow to [CrewAI AMP](https://app.crewai.com).
Deploy the crew or flow to [CrewAI AOP](https://app.crewai.com).
- **Authentication**: You need to be authenticated to deploy to CrewAI AMP.
- **Authentication**: You need to be authenticated to deploy to CrewAI AOP.
You can login or create an account with:
```shell Terminal
crewai login
@@ -203,7 +203,7 @@ Deploy the crew or flow to [CrewAI AMP](https://app.crewai.com).
### 11. Organization Management
Manage your CrewAI AMP organizations.
Manage your CrewAI AOP organizations.
```shell Terminal
crewai org [COMMAND] [OPTIONS]
@@ -227,17 +227,17 @@ crewai org switch <organization_id>
```
<Note>
You must be authenticated to CrewAI AMP to use these organization management commands.
You must be authenticated to CrewAI AOP to use these organization management commands.
</Note>
- **Create a deployment** (continued):
- Links the deployment to the corresponding remote GitHub repository (it usually detects this automatically).
- **Deploy the Crew**: Once you are authenticated, you can deploy your crew or flow to CrewAI AMP.
- **Deploy the Crew**: Once you are authenticated, you can deploy your crew or flow to CrewAI AOP.
```shell Terminal
crewai deploy push
```
- Initiates the deployment process on the CrewAI AMP platform.
- Initiates the deployment process on the CrewAI AOP platform.
- Upon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID).
- **Deployment Status**: You can check the status of your deployment with:
@@ -262,7 +262,7 @@ You must be authenticated to CrewAI AMP to use these organization management com
```shell Terminal
crewai deploy remove
```
This deletes the deployment from the CrewAI AMP platform.
This deletes the deployment from the CrewAI AOP platform.
- **Help Command**: You can get help with the CLI with:
```shell Terminal
@@ -270,7 +270,7 @@ You must be authenticated to CrewAI AMP to use these organization management com
```
This shows the help message for the CrewAI Deploy CLI.
Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI AMP](http://app.crewai.com) using the CLI.
Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI AOP](http://app.crewai.com) using the CLI.
<iframe
className="w-full aspect-video rounded-xl"
@@ -283,7 +283,7 @@ Watch this video tutorial for a step-by-step demonstration of deploying your cre
### 11. Login
Authenticate with CrewAI AMP using a secure device code flow (no email entry required).
Authenticate with CrewAI AOP using a secure device code flow (no email entry required).
```shell Terminal
crewai login
@@ -354,7 +354,7 @@ crewai config reset
#### Available Configuration Parameters
- `enterprise_base_url`: Base URL of the CrewAI AMP instance
- `enterprise_base_url`: Base URL of the CrewAI AOP instance
- `oauth2_provider`: OAuth2 provider used for authentication (e.g., workos, okta, auth0)
- `oauth2_audience`: OAuth2 audience value, typically used to identify the target API or resource
- `oauth2_client_id`: OAuth2 client ID issued by the provider, used during authentication requests
@@ -370,7 +370,7 @@ crewai config list
Example output:
| Setting | Value | Description |
| :------------------ | :----------------------- | :---------------------------------------------------------- |
| enterprise_base_url | https://app.crewai.com | Base URL of the CrewAI AMP instance |
| enterprise_base_url | https://app.crewai.com | Base URL of the CrewAI AOP instance |
| org_name | Not set | Name of the currently active organization |
| org_uuid | Not set | UUID of the currently active organization |
| oauth2_provider | workos | OAuth2 provider (e.g., workos, okta, auth0) |
@@ -402,6 +402,77 @@ crewai config reset
After resetting configuration, re-run `crewai login` to authenticate again.
</Tip>
### 14. Trace Management
Manage trace collection preferences for your Crew and Flow executions.
```shell Terminal
crewai traces [COMMAND]
```
#### Commands:
- `enable`: Enable trace collection for crew/flow executions
```shell Terminal
crewai traces enable
```
- `disable`: Disable trace collection for crew/flow executions
```shell Terminal
crewai traces disable
```
- `status`: Show current trace collection status
```shell Terminal
crewai traces status
```
#### How Tracing Works
Trace collection is controlled by checking three settings in priority order:
1. **Explicit flag in code** (highest priority - can enable OR disable):
```python
crew = Crew(agents=[...], tasks=[...], tracing=True) # Always enable
crew = Crew(agents=[...], tasks=[...], tracing=False) # Always disable
crew = Crew(agents=[...], tasks=[...]) # Check lower priorities (default)
```
- `tracing=True` will **always enable** tracing (overrides everything)
- `tracing=False` will **always disable** tracing (overrides everything)
- `tracing=None` or omitted will check lower priority settings
2. **Environment variable** (second priority):
```env
CREWAI_TRACING_ENABLED=true
```
- Checked only if `tracing` is not explicitly set to `True` or `False` in code
- Set to `true` or `1` to enable tracing
3. **User preference** (lowest priority):
```shell Terminal
crewai traces enable
```
- Checked only if `tracing` is not set in code and `CREWAI_TRACING_ENABLED` is not set to `true`
- Running `crewai traces enable` is sufficient to enable tracing by itself
<Note>
**To enable tracing**, use any one of these methods:
- Set `tracing=True` in your Crew/Flow code, OR
- Add `CREWAI_TRACING_ENABLED=true` to your `.env` file, OR
- Run `crewai traces enable`
**To disable tracing**, use any ONE of these methods:
- Set `tracing=False` in your Crew/Flow code (overrides everything), OR
- Remove or set to `false` the `CREWAI_TRACING_ENABLED` env var, OR
- Run `crewai traces disable`
Higher priority settings override lower ones.
</Note>
<Tip>
For more information about tracing, see the [Tracing documentation](/observability/tracing).
</Tip>
<Tip>
CrewAI CLI handles authentication to the Tool Repository automatically when adding packages to your project. Just append `crewai` before any `uv` command to use it. E.g. `crewai uv add requests`. For more information, see [Tool Repository](https://docs.crewai.com/enterprise/features/tool-repository) docs.
</Tip>

View File

@@ -33,6 +33,7 @@ A crew in crewAI represents a collaborative group of agents working together to
| **Planning** *(optional)* | `planning` | Adds planning ability to the Crew. When activated before each Crew iteration, all Crew data is sent to an AgentPlanner that will plan the tasks and this plan will be added to each task description. |
| **Planning LLM** *(optional)* | `planning_llm` | The language model used by the AgentPlanner in a planning process. |
| **Knowledge Sources** _(optional)_ | `knowledge_sources` | Knowledge sources available at the crew level, accessible to all the agents. |
| **Stream** _(optional)_ | `stream` | Enable streaming output to receive real-time updates during crew execution. Returns a `CrewStreamingOutput` object that can be iterated for chunks. Defaults to `False`. |
<Tip>
**Crew Max RPM**: The `max_rpm` attribute sets the maximum number of requests per minute the crew can perform to avoid rate limits and will override individual agents' `max_rpm` settings if you set it.
@@ -338,6 +339,29 @@ for async_result in async_results:
These methods provide flexibility in how you manage and execute tasks within your crew, allowing for both synchronous and asynchronous workflows tailored to your needs.
### Streaming Crew Execution
For real-time visibility into crew execution, you can enable streaming to receive output as it's generated:
```python Code
# Enable streaming
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True
)
# Iterate over streaming output
streaming = crew.kickoff(inputs={"topic": "AI"})
for chunk in streaming:
print(chunk.content, end="", flush=True)
# Access final result
result = streaming.result
```
Learn more about streaming in the [Streaming Crew Execution](/en/learn/streaming-crew-execution) guide.
### Replaying from a Specific Task
You can now replay from a specific task using our CLI command `replay`.

View File

@@ -20,7 +20,7 @@ CrewAI uses an event bus architecture to emit events throughout the execution li
When specific actions occur in CrewAI (like a Crew starting execution, an Agent completing a task, or a tool being used), the system emits corresponding events. You can register handlers for these events to execute custom code when they occur.
<Note type="info" title="Enterprise Enhancement: Prompt Tracing">
CrewAI AMP provides a built-in Prompt Tracing feature that leverages the event system to track, store, and visualize all prompts, completions, and associated metadata. This provides powerful debugging capabilities and transparency into your agent operations.
CrewAI AOP provides a built-in Prompt Tracing feature that leverages the event system to track, store, and visualize all prompts, completions, and associated metadata. This provides powerful debugging capabilities and transparency into your agent operations.
![Prompt Tracing Dashboard](/images/enterprise/traces-overview.png)

View File

@@ -897,6 +897,31 @@ flow = ExampleFlow()
result = flow.kickoff()
```
### Streaming Flow Execution
For real-time visibility into flow execution, you can enable streaming to receive output as it's generated:
```python
class StreamingFlow(Flow):
stream = True # Enable streaming
@start()
def research(self):
# Your flow implementation
pass
# Iterate over streaming output
flow = StreamingFlow()
streaming = flow.kickoff()
for chunk in streaming:
print(chunk.content, end="", flush=True)
# Access final result
result = streaming.result
```
Learn more about streaming in the [Streaming Flow Execution](/en/learn/streaming-flow-execution) guide.
### Using the CLI
Starting from version 0.103.0, you can run flows using the `crewai run` command:

View File

@@ -388,8 +388,8 @@ crew = Crew(
agents=[sales_agent, tech_agent, support_agent],
tasks=[...],
embedder={ # Fallback embedder for agents without their own
"provider": "google",
"config": {"model": "text-embedding-004"}
"provider": "google-generativeai",
"config": {"model_name": "gemini-embedding-001"}
}
)
@@ -629,9 +629,9 @@ agent = Agent(
backstory="Expert researcher",
knowledge_sources=[knowledge_source],
embedder={
"provider": "google",
"provider": "google-generativeai",
"config": {
"model": "models/text-embedding-004",
"model_name": "gemini-embedding-001",
"api_key": "your-google-key"
}
}
@@ -739,7 +739,7 @@ class KnowledgeMonitorListener(BaseEventListener):
knowledge_monitor = KnowledgeMonitorListener()
```
For more information on using events, see the [Event Listeners](https://docs.crewai.com/concepts/event-listener) documentation.
For more information on using events, see the [Event Listeners](/en/concepts/event-listener) documentation.
### Custom Knowledge Sources

View File

@@ -7,7 +7,7 @@ mode: "wide"
## Overview
CrewAI integrates with multiple LLM providers through LiteLLM, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.
CrewAI integrates with multiple LLM providers through providers native sdks, giving you the flexibility to choose the right model for your specific use case. This guide will help you understand how to configure and use different LLM providers in your CrewAI projects.
## What are LLMs?
@@ -113,44 +113,104 @@ In this section, you'll find detailed examples that help you select, configure,
<AccordionGroup>
<Accordion title="OpenAI">
Set the following environment variables in your `.env` file:
CrewAI provides native integration with OpenAI through the OpenAI Python SDK.
```toml Code
# Required
OPENAI_API_KEY=sk-...
# Optional
OPENAI_API_BASE=<custom-base-url>
OPENAI_ORGANIZATION=<your-org-id>
OPENAI_BASE_URL=<custom-base-url>
```
Example usage in your CrewAI project:
**Basic Usage:**
```python Code
from crewai import LLM
llm = LLM(
model="openai/gpt-4", # call model by provider/model_name
temperature=0.8,
max_tokens=150,
model="openai/gpt-4o",
api_key="your-api-key", # Or set OPENAI_API_KEY
temperature=0.7,
max_tokens=4000
)
```
**Advanced Configuration:**
```python Code
from crewai import LLM
llm = LLM(
model="openai/gpt-4o",
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
seed=42, # For reproducible outputs
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
)
```
OpenAI is one of the leading providers of LLMs with a wide range of models and features.
**Structured Outputs:**
```python Code
from pydantic import BaseModel
from crewai import LLM
class ResponseFormat(BaseModel):
name: str
age: int
summary: str
llm = LLM(
model="openai/gpt-4o",
)
```
**Supported Environment Variables:**
- `OPENAI_API_KEY`: Your OpenAI API key (required)
- `OPENAI_BASE_URL`: Custom base URL for OpenAI API (optional)
**Features:**
- Native function calling support (except o1 models)
- Structured outputs with JSON schema
- Streaming support for real-time responses
- Token usage tracking
- Stop sequences support (except o1 models)
- Log probabilities for token-level insights
- Reasoning effort control for o1 models
**Supported Models:**
| Model | Context Window | Best For |
|---------------------|------------------|-----------------------------------------------|
| GPT-4 | 8,192 tokens | High-accuracy tasks, complex reasoning |
| GPT-4 Turbo | 128,000 tokens | Long-form content, document analysis |
| GPT-4o & GPT-4o-mini | 128,000 tokens | Cost-effective large context processing |
| o3-mini | 200,000 tokens | Fast reasoning, complex reasoning |
| o1-mini | 128,000 tokens | Fast reasoning, complex reasoning |
| o1-preview | 128,000 tokens | Fast reasoning, complex reasoning |
| o1 | 200,000 tokens | Fast reasoning, complex reasoning |
| 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 |
**Note:** To use OpenAI, install the required dependencies:
```bash
uv add "crewai[openai]"
```
</Accordion>
<Accordion title="Meta-Llama">
@@ -187,69 +247,186 @@ In this section, you'll find detailed examples that help you select, configure,
</Accordion>
<Accordion title="Anthropic">
CrewAI provides native integration with Anthropic through the Anthropic Python SDK.
```toml Code
# Required
ANTHROPIC_API_KEY=sk-ant-...
# Optional
ANTHROPIC_API_BASE=<custom-base-url>
```
Example usage in your CrewAI project:
**Basic Usage:**
```python Code
from crewai import LLM
llm = LLM(
model="anthropic/claude-3-sonnet-20240229-v1:0",
temperature=0.7
model="anthropic/claude-3-5-sonnet-20241022",
api_key="your-api-key", # Or set ANTHROPIC_API_KEY
max_tokens=4096 # Required for Anthropic
)
```
**Advanced Configuration:**
```python Code
from crewai import LLM
llm = LLM(
model="anthropic/claude-3-5-sonnet-20241022",
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
max_retries=3 # Maximum retry attempts
)
```
**Supported Environment Variables:**
- `ANTHROPIC_API_KEY`: Your Anthropic API key (required)
**Features:**
- Native tool use support for Claude 3+ models
- Streaming support for real-time responses
- Automatic system message handling
- Stop sequences for controlled output
- Token usage tracking
- Multi-turn tool use conversations
**Important Notes:**
- `max_tokens` is a **required** parameter for all Anthropic models
- Claude uses `stop_sequences` instead of `stop`
- System messages are handled separately from conversation messages
- First message must be from the user (automatically handled)
- Messages must alternate between user and assistant
**Supported Models:**
| Model | Context Window | Best For |
|------------------------------|----------------|-----------------------------------------------|
| 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 |
**Note:** To use Anthropic, install the required dependencies:
```bash
uv add "crewai[anthropic]"
```
</Accordion>
<Accordion title="Google (Gemini API)">
Set your API key in your `.env` file. If you need a key, or need to find an
existing key, check [AI Studio](https://aistudio.google.com/apikey).
CrewAI provides native integration with Google Gemini through the Google Gen AI Python SDK.
Set your API key in your `.env` file. If you need a key, check [AI Studio](https://aistudio.google.com/apikey).
```toml .env
# https://ai.google.dev/gemini-api/docs/api-key
# Required (one of the following)
GOOGLE_API_KEY=<your-api-key>
GEMINI_API_KEY=<your-api-key>
# Optional - for Vertex AI
GOOGLE_CLOUD_PROJECT=<your-project-id>
GOOGLE_CLOUD_LOCATION=<location> # Defaults to us-central1
GOOGLE_GENAI_USE_VERTEXAI=true # Set to use Vertex AI
```
Example usage in your CrewAI project:
**Basic Usage:**
```python Code
from crewai import LLM
llm = LLM(
model="gemini/gemini-2.0-flash",
temperature=0.7,
api_key="your-api-key", # Or set GOOGLE_API_KEY/GEMINI_API_KEY
temperature=0.7
)
```
### Gemini models
**Advanced Configuration:**
```python Code
from crewai import LLM
llm = LLM(
model="gemini/gemini-2.5-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
safety_settings={
"HARM_CATEGORY_HARASSMENT": "BLOCK_NONE",
"HARM_CATEGORY_HATE_SPEECH": "BLOCK_NONE"
}
)
```
**Vertex AI Configuration:**
```python Code
from crewai import LLM
llm = LLM(
model="gemini/gemini-1.5-pro",
project="your-gcp-project-id",
location="us-central1" # GCP region
)
```
**Supported Environment Variables:**
- `GOOGLE_API_KEY` or `GEMINI_API_KEY`: Your Google API key (required for Gemini API)
- `GOOGLE_CLOUD_PROJECT`: Google Cloud project ID (for Vertex AI)
- `GOOGLE_CLOUD_LOCATION`: GCP location (defaults to `us-central1`)
- `GOOGLE_GENAI_USE_VERTEXAI`: Set to `true` to use Vertex AI
**Features:**
- Native function calling support for Gemini 1.5+ and 2.x models
- Streaming support for real-time responses
- Multimodal capabilities (text, images, video)
- Safety settings configuration
- Support for both Gemini API and Vertex AI
- 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-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.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, 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 |
| 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 |
**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).
### Gemma
The Gemini API also allows you to use your API key to access [Gemma models](https://ai.google.dev/gemma/docs) hosted on Google infrastructure.
| Model | Context Window |
|----------------|----------------|
| gemma-3-1b-it | 32k tokens |
| gemma-3-4b-it | 32k tokens |
| gemma-3-12b-it | 32k tokens |
| gemma-3-27b-it | 128k tokens |
</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:
@@ -291,43 +468,146 @@ In this section, you'll find detailed examples that help you select, configure,
</Accordion>
<Accordion title="Azure">
CrewAI provides native integration with Azure AI Inference and Azure OpenAI through the Azure AI Inference Python SDK.
```toml Code
# Required
AZURE_API_KEY=<your-api-key>
AZURE_API_BASE=<your-resource-url>
AZURE_API_VERSION=<api-version>
AZURE_ENDPOINT=<your-endpoint-url>
# Optional
AZURE_AD_TOKEN=<your-azure-ad-token>
AZURE_API_TYPE=<your-azure-api-type>
AZURE_API_VERSION=<api-version> # Defaults to 2024-06-01
```
Example usage in your CrewAI project:
**Endpoint URL Formats:**
For Azure OpenAI deployments:
```
https://<resource-name>.openai.azure.com/openai/deployments/<deployment-name>
```
For Azure AI Inference endpoints:
```
https://<resource-name>.inference.azure.com
```
**Basic Usage:**
```python Code
llm = LLM(
model="azure/gpt-4",
api_version="2023-05-15"
api_key="<your-api-key>", # Or set AZURE_API_KEY
endpoint="<your-endpoint-url>",
api_version="2024-06-01"
)
```
**Advanced Configuration:**
```python Code
llm = LLM(
model="azure/gpt-4o",
temperature=0.7,
max_tokens=4000,
top_p=0.9,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["END"],
stream=True,
timeout=60.0,
max_retries=3
)
```
**Supported Environment Variables:**
- `AZURE_API_KEY`: Your Azure API key (required)
- `AZURE_ENDPOINT`: Your Azure endpoint URL (required, also checks `AZURE_OPENAI_ENDPOINT` and `AZURE_API_BASE`)
- `AZURE_API_VERSION`: API version (optional, defaults to `2024-06-01`)
**Features:**
- Native function calling support for Azure OpenAI models (gpt-4, gpt-4o, gpt-3.5-turbo, etc.)
- Streaming support for real-time responses
- Automatic endpoint URL validation and correction
- Comprehensive error handling with retry logic
- Token usage tracking
**Note:** To use Azure AI Inference, install the required dependencies:
```bash
uv add "crewai[azure-ai-inference]"
```
</Accordion>
<Accordion title="AWS Bedrock">
CrewAI provides native integration with AWS Bedrock through the boto3 SDK using the Converse API.
```toml Code
# Required
AWS_ACCESS_KEY_ID=<your-access-key>
AWS_SECRET_ACCESS_KEY=<your-secret-key>
AWS_DEFAULT_REGION=<your-region>
# Optional
AWS_SESSION_TOKEN=<your-session-token> # For temporary credentials
AWS_DEFAULT_REGION=<your-region> # Defaults to us-east-1
```
Example usage in your CrewAI project:
**Basic Usage:**
```python Code
from crewai import LLM
llm = LLM(
model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0"
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
region_name="us-east-1"
)
```
Before using Amazon Bedrock, make sure you have boto3 installed in your environment
**Advanced Configuration:**
```python Code
from crewai import LLM
[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, enabling secure and responsible AI application development.
llm = LLM(
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
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
region_name="us-east-1",
temperature=0.7,
max_tokens=4096,
top_p=0.9,
top_k=250, # For Claude models
stop_sequences=["END", "STOP"],
stream=True, # Enable streaming
guardrail_config={ # Optional content filtering
"guardrailIdentifier": "your-guardrail-id",
"guardrailVersion": "1"
},
additional_model_request_fields={ # Model-specific parameters
"top_k": 250
}
)
```
**Supported Environment Variables:**
- `AWS_ACCESS_KEY_ID`: AWS access key (required)
- `AWS_SECRET_ACCESS_KEY`: AWS secret key (required)
- `AWS_SESSION_TOKEN`: AWS session token for temporary credentials (optional)
- `AWS_DEFAULT_REGION`: AWS region (defaults to `us-east-1`)
**Features:**
- Native tool calling support via Converse API
- Streaming and non-streaming responses
- Comprehensive error handling with retry logic
- Guardrail configuration for content filtering
- Model-specific parameters via `additional_model_request_fields`
- Token usage tracking and stop reason logging
- Support for all Bedrock foundation models
- Automatic conversation format handling
**Important Notes:**
- Uses the modern Converse API for unified model access
- Automatic handling of model-specific conversation requirements
- System messages are handled separately from conversation
- 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 |
|-------------------------|----------------------|-------------------------------------------------------------------|
@@ -357,7 +637,12 @@ In this section, you'll find detailed examples that help you select, configure,
| 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 |
**Note:** To use AWS Bedrock, install the required dependencies:
```bash
uv add "crewai[bedrock]"
```
</Accordion>
<Accordion title="Amazon SageMaker">
@@ -750,7 +1035,7 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
```
<Tip>
[Click here](https://docs.crewai.com/concepts/event-listener#event-listeners) for more details
[Click here](/en/concepts/event-listener#event-listeners) for more details
</Tip>
</Tab>
@@ -804,6 +1089,50 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
</Tab>
</Tabs>
## Async LLM Calls
CrewAI supports asynchronous LLM calls for improved performance and concurrency in your AI workflows. Async calls allow you to run multiple LLM requests concurrently without blocking, making them ideal for high-throughput applications and parallel agent operations.
<Tabs>
<Tab title="Basic Usage">
Use the `acall` method for asynchronous LLM requests:
```python
import asyncio
from crewai import LLM
async def main():
llm = LLM(model="openai/gpt-4o")
# Single async call
response = await llm.acall("What is the capital of France?")
print(response)
asyncio.run(main())
```
The `acall` method supports all the same parameters as the synchronous `call` method, including messages, tools, and callbacks.
</Tab>
<Tab title="With Streaming">
Combine async calls with streaming for real-time concurrent responses:
```python
import asyncio
from crewai import LLM
async def stream_async():
llm = LLM(model="openai/gpt-4o", stream=True)
response = await llm.acall("Write a short story about AI")
print(response)
asyncio.run(stream_async())
```
</Tab>
</Tabs>
## Structured LLM Calls
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.
@@ -899,7 +1228,7 @@ Learn how to get the most out of your LLM configuration:
</Accordion>
<Accordion title="Drop Additional Parameters">
CrewAI internally uses Litellm for LLM calls, which allows you to drop additional parameters that are not needed for your specific use case. This can help simplify your code and reduce the complexity of your LLM configuration.
CrewAI internally uses native sdks for LLM calls, which allows you to drop additional parameters that are not needed for your specific use case. This can help simplify your code and reduce the complexity of your LLM configuration.
For example, if you don't need to send the <code>stop</code> parameter, you can simply omit it from your LLM call:
```python
@@ -915,6 +1244,52 @@ Learn how to get the most out of your LLM configuration:
)
```
</Accordion>
<Accordion title="Transport Interceptors">
CrewAI provides message interceptors for several providers, allowing you to hook into request/response cycles at the transport layer.
**Supported Providers:**
- ✅ OpenAI
- ✅ Anthropic
**Basic Usage:**
```python
import httpx
from crewai import LLM
from crewai.llms.hooks import BaseInterceptor
class CustomInterceptor(BaseInterceptor[httpx.Request, httpx.Response]):
"""Custom interceptor to modify requests and responses."""
def on_outbound(self, request: httpx.Request) -> httpx.Request:
"""Print request before sending to the LLM provider."""
print(request)
return request
def on_inbound(self, response: httpx.Response) -> httpx.Response:
"""Process response after receiving from the LLM provider."""
print(f"Status: {response.status_code}")
print(f"Response time: {response.elapsed}")
return response
# Use the interceptor with an LLM
llm = LLM(
model="openai/gpt-4o",
interceptor=CustomInterceptor()
)
```
**Important Notes:**
- Both methods must return the received object or type of object.
- Modifying received objects may result in unexpected behavior or application crashes.
- Not all providers support interceptors - check the supported providers list above
<Info>
Interceptors operate at the transport layer. This is particularly useful for:
- Message transformation and filtering
- Debugging API interactions
</Info>
</Accordion>
</AccordionGroup>
## Common Issues and Solutions

View File

@@ -341,7 +341,7 @@ crew = Crew(
embedder={
"provider": "openai",
"config": {
"model": "text-embedding-3-small" # or "text-embedding-3-large"
"model_name": "text-embedding-3-small" # or "text-embedding-3-large"
}
}
)
@@ -353,7 +353,7 @@ crew = Crew(
"provider": "openai",
"config": {
"api_key": "your-openai-api-key", # Optional: override env var
"model": "text-embedding-3-large",
"model_name": "text-embedding-3-large",
"dimensions": 1536, # Optional: reduce dimensions for smaller storage
"organization_id": "your-org-id" # Optional: for organization accounts
}
@@ -375,7 +375,7 @@ crew = Crew(
"api_base": "https://your-resource.openai.azure.com/",
"api_type": "azure",
"api_version": "2023-05-15",
"model": "text-embedding-3-small",
"model_name": "text-embedding-3-small",
"deployment_id": "your-deployment-name" # Azure deployment name
}
}
@@ -390,10 +390,10 @@ Use Google's text embedding models for integration with Google Cloud services.
crew = Crew(
memory=True,
embedder={
"provider": "google",
"provider": "google-generativeai",
"config": {
"api_key": "your-google-api-key",
"model": "text-embedding-004" # or "text-embedding-preview-0409"
"model_name": "gemini-embedding-001" # or "text-embedding-005", "text-multilingual-embedding-002"
}
}
)
@@ -461,7 +461,7 @@ crew = Crew(
"provider": "cohere",
"config": {
"api_key": "your-cohere-api-key",
"model": "embed-english-v3.0" # or "embed-multilingual-v3.0"
"model_name": "embed-english-v3.0" # or "embed-multilingual-v3.0"
}
}
)
@@ -478,7 +478,7 @@ crew = Crew(
"provider": "voyageai",
"config": {
"api_key": "your-voyage-api-key",
"model": "voyage-large-2", # or "voyage-code-2" for code
"model": "voyage-3", # or "voyage-3-lite", "voyage-code-3"
"input_type": "document" # or "query"
}
}
@@ -515,8 +515,7 @@ crew = Crew(
"provider": "huggingface",
"config": {
"api_key": "your-hf-token", # Optional for public models
"model": "sentence-transformers/all-MiniLM-L6-v2",
"api_url": "https://api-inference.huggingface.co" # or your custom endpoint
"model": "sentence-transformers/all-MiniLM-L6-v2"
}
}
)
@@ -912,10 +911,10 @@ crew = Crew(
crew = Crew(
memory=True,
embedder={
"provider": "google",
"provider": "google-generativeai",
"config": {
"api_key": "your-api-key",
"model": "text-embedding-004"
"model_name": "gemini-embedding-001"
}
}
)

View File

@@ -14,7 +14,7 @@ Tasks provide all necessary details for execution, such as a description, the ag
Tasks within CrewAI can be collaborative, requiring multiple agents to work together. This is managed through the task properties and orchestrated by the Crew's process, enhancing teamwork and efficiency.
<Note type="info" title="Enterprise Enhancement: Visual Task Builder">
CrewAI AMP includes a Visual Task Builder in Crew Studio that simplifies complex task creation and chaining. Design your task flows visually and test them in real-time without writing code.
CrewAI AOP includes a Visual Task Builder in Crew Studio that simplifies complex task creation and chaining. Design your task flows visually and test them in real-time without writing code.
![Task Builder Screenshot](/images/enterprise/crew-studio-interface.png)
@@ -60,6 +60,7 @@ crew = Crew(
| **Output Pydantic** _(optional)_ | `output_pydantic` | `Optional[Type[BaseModel]]` | A Pydantic model for task output. |
| **Callback** _(optional)_ | `callback` | `Optional[Any]` | Function/object to be executed after task completion. |
| **Guardrail** _(optional)_ | `guardrail` | `Optional[Callable]` | Function to validate task output before proceeding to next task. |
| **Guardrails** _(optional)_ | `guardrails` | `Optional[List[Callable] | List[str]]` | List of guardrails to validate task output before proceeding to next task. |
| **Guardrail Max Retries** _(optional)_ | `guardrail_max_retries` | `Optional[int]` | Maximum number of retries when guardrail validation fails. Defaults to 3. |
<Note type="warning" title="Deprecated: max_retries">
@@ -223,6 +224,7 @@ By default, the `TaskOutput` will only include the `raw` output. A `TaskOutput`
| **JSON Dict** | `json_dict` | `Optional[Dict[str, Any]]` | A dictionary representing the JSON output of the task. |
| **Agent** | `agent` | `str` | The agent that executed the task. |
| **Output Format** | `output_format` | `OutputFormat` | The format of the task output, with options including RAW, JSON, and Pydantic. The default is RAW. |
| **Messages** | `messages` | `list[LLMMessage]` | The messages from the last task execution. |
### Task Methods and Properties
@@ -341,7 +343,11 @@ Task guardrails provide a way to validate and transform task outputs before they
are passed to the next task. This feature helps ensure data quality and provides
feedback to agents when their output doesn't meet specific criteria.
Guardrails are implemented as Python functions that contain custom validation logic, giving you complete control over the validation process and ensuring reliable, deterministic results.
CrewAI supports two types of guardrails:
1. **Function-based guardrails**: Python functions with custom validation logic, giving you complete control over the validation process and ensuring reliable, deterministic results.
2. **LLM-based guardrails**: String descriptions that use the agent's LLM to validate outputs based on natural language criteria. These are ideal for complex or subjective validation requirements.
### Function-Based Guardrails
@@ -355,12 +361,12 @@ def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate blog content meets requirements."""
try:
# Check word count
word_count = len(result.split())
word_count = len(result.raw.split())
if word_count > 200:
return (False, "Blog content exceeds 200 words")
# Additional validation logic here
return (True, result.strip())
return (True, result.raw.strip())
except Exception as e:
return (False, "Unexpected error during validation")
@@ -372,6 +378,147 @@ blog_task = Task(
)
```
### LLM-Based Guardrails (String Descriptions)
Instead of writing custom validation functions, you can use string descriptions that leverage LLM-based validation. When you provide a string to the `guardrail` or `guardrails` parameter, CrewAI automatically creates an `LLMGuardrail` that uses the agent's LLM to validate the output based on your description.
**Requirements**:
- The task must have an `agent` assigned (the guardrail uses the agent's LLM)
- Provide a clear, descriptive string explaining the validation criteria
```python Code
from crewai import Task
# Single LLM-based guardrail
blog_task = Task(
description="Write a blog post about AI",
expected_output="A blog post under 200 words",
agent=blog_agent,
guardrail="The blog post must be under 200 words and contain no technical jargon"
)
```
LLM-based guardrails are particularly useful for:
- **Complex validation logic** that's difficult to express programmatically
- **Subjective criteria** like tone, style, or quality assessments
- **Natural language requirements** that are easier to describe than code
The LLM guardrail will:
1. Analyze the task output against your description
2. Return `(True, output)` if the output complies with the criteria
3. Return `(False, feedback)` with specific feedback if validation fails
**Example with detailed validation criteria**:
```python Code
research_task = Task(
description="Research the latest developments in quantum computing",
expected_output="A comprehensive research report",
agent=researcher_agent,
guardrail="""
The research report must:
- Be at least 1000 words long
- Include at least 5 credible sources
- Cover both technical and practical applications
- Be written in a professional, academic tone
- Avoid speculation or unverified claims
"""
)
```
### Multiple Guardrails
You can apply multiple guardrails to a task using the `guardrails` parameter. Multiple guardrails are executed sequentially, with each guardrail receiving the output from the previous one. This allows you to chain validation and transformation steps.
The `guardrails` parameter accepts:
- A list of guardrail functions or string descriptions
- A single guardrail function or string (same as `guardrail`)
**Note**: If `guardrails` is provided, it takes precedence over `guardrail`. The `guardrail` parameter will be ignored when `guardrails` is set.
```python Code
from typing import Tuple, Any
from crewai import TaskOutput, Task
def validate_word_count(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate word count is within limits."""
word_count = len(result.raw.split())
if word_count < 100:
return (False, f"Content too short: {word_count} words. Need at least 100 words.")
if word_count > 500:
return (False, f"Content too long: {word_count} words. Maximum is 500 words.")
return (True, result.raw)
def validate_no_profanity(result: TaskOutput) -> Tuple[bool, Any]:
"""Check for inappropriate language."""
profanity_words = ["badword1", "badword2"] # Example list
content_lower = result.raw.lower()
for word in profanity_words:
if word in content_lower:
return (False, f"Inappropriate language detected: {word}")
return (True, result.raw)
def format_output(result: TaskOutput) -> Tuple[bool, Any]:
"""Format and clean the output."""
formatted = result.raw.strip()
# Capitalize first letter
formatted = formatted[0].upper() + formatted[1:] if formatted else formatted
return (True, formatted)
# Apply multiple guardrails sequentially
blog_task = Task(
description="Write a blog post about AI",
expected_output="A well-formatted blog post between 100-500 words",
agent=blog_agent,
guardrails=[
validate_word_count, # First: validate length
validate_no_profanity, # Second: check content
format_output # Third: format the result
],
guardrail_max_retries=3
)
```
In this example, the guardrails execute in order:
1. `validate_word_count` checks the word count
2. `validate_no_profanity` checks for inappropriate language (using the output from step 1)
3. `format_output` formats the final result (using the output from step 2)
If any guardrail fails, the error is sent back to the agent, and the task is retried up to `guardrail_max_retries` times.
**Mixing function-based and LLM-based guardrails**:
You can combine both function-based and string-based guardrails in the same list:
```python Code
from typing import Tuple, Any
from crewai import TaskOutput, Task
def validate_word_count(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate word count is within limits."""
word_count = len(result.raw.split())
if word_count < 100:
return (False, f"Content too short: {word_count} words. Need at least 100 words.")
if word_count > 500:
return (False, f"Content too long: {word_count} words. Maximum is 500 words.")
return (True, result.raw)
# Mix function-based and LLM-based guardrails
blog_task = Task(
description="Write a blog post about AI",
expected_output="A well-formatted blog post between 100-500 words",
agent=blog_agent,
guardrails=[
validate_word_count, # Function-based: precise word count check
"The content must be engaging and suitable for a general audience", # LLM-based: subjective quality check
"The writing style should be clear, concise, and free of technical jargon" # LLM-based: style validation
],
guardrail_max_retries=3
)
```
This approach combines the precision of programmatic validation with the flexibility of LLM-based assessment for subjective criteria.
### Guardrail Function Requirements
1. **Function Signature**:

View File

@@ -17,7 +17,7 @@ This includes tools from the [CrewAI Toolkit](https://github.com/joaomdmoura/cre
enabling everything from simple searches to complex interactions and effective teamwork among agents.
<Note type="info" title="Enterprise Enhancement: Tools Repository">
CrewAI AMP provides a comprehensive Tools Repository with pre-built integrations for common business systems and APIs. Deploy agents with enterprise tools in minutes instead of days.
CrewAI AOP provides a comprehensive Tools Repository with pre-built integrations for common business systems and APIs. Deploy agents with enterprise tools in minutes instead of days.
The Enterprise Tools Repository includes:
- Pre-built connectors for popular enterprise systems

View File

@@ -37,7 +37,7 @@ you can use them locally or refine them to your needs.
<Card title="Tools & Integrations" href="/en/enterprise/features/tools-and-integrations" icon="wrench">
Connect external apps and manage internal tools your agents can use.
</Card>
<Card title="Tool Repository" href="/en/enterprise/features/tool-repository" icon="toolbox">
<Card title="Tool Repository" href="/en/enterprise/guides/tool-repository#tool-repository" icon="toolbox">
Publish and install tools to enhance your crews' capabilities.
</Card>
<Card title="Agents Repository" href="/en/enterprise/features/agent-repositories" icon="people-group">

View File

@@ -7,10 +7,10 @@ mode: "wide"
## Overview
RBAC in CrewAI AMP enables secure, scalable access management through a combination of organizationlevel roles and automationlevel visibility controls.
RBAC in CrewAI AOP enables secure, scalable access management through a combination of organizationlevel roles and automationlevel visibility controls.
<Frame>
<img src="/images/enterprise/users_and_roles.png" alt="RBAC overview in CrewAI AMP" />
<img src="/images/enterprise/users_and_roles.png" alt="RBAC overview in CrewAI AOP" />
</Frame>
@@ -28,7 +28,7 @@ You can configure users and roles in Settings → Roles.
<Steps>
<Step title="Open Roles settings">
Go to <b>Settings → Roles</b> in CrewAI AMP.
Go to <b>Settings → Roles</b> in CrewAI AOP.
</Step>
<Step title="Choose a role type">
Use a predefined role (<b>Owner</b>, <b>Member</b>) or click <b>Create role</b> to define a custom one.
@@ -93,7 +93,7 @@ The organization owner always has access. In private mode, only whitelisted user
</Tip>
<Frame>
<img src="/images/enterprise/visibility.png" alt="Automation Visibility settings in CrewAI AMP" />
<img src="/images/enterprise/visibility.png" alt="Automation Visibility settings in CrewAI AOP" />
</Frame>

View File

@@ -43,7 +43,7 @@ Tools & Integrations is the central hub for connecting thirdparty apps and ma
1. Go to <Link href="https://app.crewai.com/crewai_plus/connectors">Integrations</Link>
2. Click <b>Connect</b> on the desired service
3. Complete the OAuth flow and grant scopes
4. Copy your Enterprise Token from the <b>Integration</b> tab
4. Copy your Enterprise Token from <Link href="https://app.crewai.com/crewai_plus/settings/integrations">Integration Settings</Link>
<Frame>
![Enterprise Token](/images/enterprise/enterprise_action_auth_token.png)
@@ -57,29 +57,37 @@ Tools & Integrations is the central hub for connecting thirdparty apps and ma
uv add crewai-tools
```
### Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
### Usage Example
<Tip>
All services you have authenticated will be available as tools. Add `CrewaiEnterpriseTools` to your agent and youre set.
Use the new streamlined approach to integrate enterprise apps. Simply specify the app and its actions directly in the Agent configuration.
</Tip>
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Gmail tool will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# print the tools
print(enterprise_tools)
# Create an agent with Gmail capabilities
email_agent = Agent(
role="Email Manager",
goal="Manage and organize email communications",
backstory="An AI assistant specialized in email management and communication.",
tools=enterprise_tools
apps=['gmail', 'gmail/send_email'] # Using canonical name 'gmail'
)
# Task to send an email
@@ -102,21 +110,14 @@ Tools & Integrations is the central hub for connecting thirdparty apps and ma
### Filtering Tools
```python
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
actions_list=["gmail_find_email"] # only gmail_find_email tool will be available
)
gmail_tool = enterprise_tools["gmail_find_email"]
from crewai import Agent, Task, Crew
# Create agent with specific Gmail actions only
gmail_agent = Agent(
role="Gmail Manager",
goal="Manage gmail communications and notifications",
backstory="An AI assistant that helps coordinate gmail communications.",
tools=[gmail_tool]
apps=['gmail/fetch_emails'] # Using canonical name with specific action
)
notification_task = Task(
@@ -188,10 +189,10 @@ Tools & Integrations is the central hub for connecting thirdparty apps and ma
## Internal Tools
Create custom tools locally, publish them on CrewAI AMP Tool Repository and use them in your agents.
Create custom tools locally, publish them on CrewAI AOP Tool Repository and use them in your agents.
<Tip>
Before running the commands below, make sure you log in to your CrewAI AMP account by running this command:
Before running the commands below, make sure you log in to your CrewAI AOP account by running this command:
```bash
crewai login
```
@@ -209,13 +210,13 @@ Tools & Integrations is the central hub for connecting thirdparty apps and ma
```
</Step>
<Step title="Publish">
Publish the tool to the CrewAI AMP Tool Repository.
Publish the tool to the CrewAI AOP Tool Repository.
```bash
crewai tool publish
```
</Step>
<Step title="Install">
Install the tool from the CrewAI AMP Tool Repository.
Install the tool from the CrewAI AOP Tool Repository.
```bash
crewai tool install your-tool
```
@@ -240,7 +241,7 @@ Tools & Integrations is the central hub for connecting thirdparty apps and ma
## Related
<CardGroup cols={2}>
<Card title="Tool Repository" href="/en/enterprise/features/tool-repository" icon="toolbox">
<Card title="Tool Repository" href="/en/enterprise/guides/tool-repository#tool-repository" icon="toolbox">
Create, publish, and version custom tools for your organization.
</Card>
<Card title="Webhook Automation" href="/en/enterprise/guides/webhook-automation" icon="bolt">

View File

@@ -11,7 +11,7 @@ Traces provide comprehensive visibility into your crew executions, helping you m
## What are Traces?
Traces in CrewAI AMP are detailed execution records that capture every aspect of your crew's operation, from initial inputs to final outputs. They record:
Traces in CrewAI AOP are detailed execution records that capture every aspect of your crew's operation, from initial inputs to final outputs. They record:
- Agent thoughts and reasoning
- Task execution details
@@ -28,7 +28,7 @@ Traces in CrewAI AMP are detailed execution records that capture every aspect of
<Steps>
<Step title="Navigate to the Traces Tab">
Once in your CrewAI AMP dashboard, click on the **Traces** to view all execution records.
Once in your CrewAI AOP dashboard, click on the **Traces** to view all execution records.
</Step>
<Step title="Select an Execution">
@@ -153,5 +153,5 @@ CrewAI batches trace uploads to reduce overhead on high-volume runs:
This yields more stable tracing under load while preserving detailed task/agent telemetry.
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with trace analysis or any other CrewAI AMP features.
Contact our support team for assistance with trace analysis or any other CrewAI AOP features.
</Card>

View File

@@ -8,7 +8,7 @@ mode: "wide"
## Overview
Enterprise Event Streaming lets you receive real-time webhook updates about your crews and flows deployed to
CrewAI AMP, such as model calls, tool usage, and flow steps.
CrewAI AOP, such as model calls, tool usage, and flow steps.
## Usage

View File

@@ -1,11 +1,11 @@
---
title: "Triggers Overview"
description: "Understand how CrewAI AMP triggers work, how to manage them, and where to find integration-specific playbooks"
description: "Understand how CrewAI AOP triggers work, how to manage them, and where to find integration-specific playbooks"
icon: "face-smile"
mode: "wide"
---
CrewAI AMP triggers connect your automations to real-time events across the tools your teams already use. Instead of polling systems or relying on manual kickoffs, triggers listen for changes—new emails, calendar updates, CRM status changes—and immediately launch the crew or flow you specify.
CrewAI AOP triggers connect your automations to real-time events across the tools your teams already use. Instead of polling systems or relying on manual kickoffs, triggers listen for changes—new emails, calendar updates, CRM status changes—and immediately launch the crew or flow you specify.
<Frame>
![Automation Triggers Overview](/images/enterprise/crew_connectors.png)
@@ -117,27 +117,50 @@ Before wiring a trigger into production, make sure you:
- Decide whether to pass trigger context automatically using `allow_crewai_trigger_context`
- Set up monitoring—webhook logs, CrewAI execution history, and optional external alerting
### Payload & Crew Examples Repository
### Testing Triggers Locally with CLI
We maintain a comprehensive repository with end-to-end trigger examples to help you build and test your automations:
The CrewAI CLI provides powerful commands to help you develop and test trigger-driven automations without deploying to production.
This repository contains:
#### List Available Triggers
- **Realistic payload samples** for every supported trigger integration
- **Ready-to-run crew implementations** that parse each payload and turn it into a business workflow
- **Multiple scenarios per integration** (e.g., new events, updates, deletions) so you can match the shape of your data
View all available triggers for your connected integrations:
| Integration | When it fires | Payload Samples | Crew Examples |
| :-- | :-- | :-- | :-- |
| Gmail | New messages, thread updates | [New alerts, thread updates](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/gmail) | [`new-email-crew.py`, `gmail-alert-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/gmail) |
| Google Calendar | Event created / updated / started / ended / cancelled | [Event lifecycle payloads](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/google_calendar) | [`calendar-event-crew.py`, `calendar-meeting-crew.py`, `calendar-working-location-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/google_calendar) |
| Google Drive | File created / updated / deleted | [File lifecycle payloads](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/google_drive) | [`drive-file-crew.py`, `drive-file-deletion-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/google_drive) |
| Outlook | New email, calendar event removed | [Outlook payloads](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/outlook) | [`outlook-message-crew.py`, `outlook-event-removal-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/outlook) |
| OneDrive | File operations (create, update, share, delete) | [OneDrive payloads](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/onedrive) | [`onedrive-file-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/onedrive) |
| HubSpot | Record created / updated (contacts, companies, deals) | [HubSpot payloads](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/hubspot) | [`hubspot-company-crew.py`, `hubspot-contact-crew.py`, `hubspot-record-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/hubspot) |
| Microsoft Teams | Chat thread created | [Teams chat payload](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/microsoft-teams) | [`teams-chat-created-crew.py`](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/microsoft-teams) |
```bash
crewai triggers list
```
This command displays all triggers available based on your connected integrations, showing:
- Integration name and connection status
- Available trigger types
- Trigger names and descriptions
#### Simulate Trigger Execution
Test your crew with realistic trigger payloads before deployment:
```bash
crewai triggers run <trigger_name>
```
For example:
```bash
crewai triggers run microsoft_onedrive/file_changed
```
This command:
- Executes your crew locally
- Passes a complete, realistic trigger payload
- Simulates exactly how your crew will be called in production
<Warning>
**Important Development Notes:**
- Use `crewai triggers run <trigger>` to simulate trigger execution during development
- Using `crewai run` will NOT simulate trigger calls and won't pass the trigger payload
- After deployment, your crew will be executed with the actual trigger payload
- If your crew expects parameters that aren't in the trigger payload, execution may fail
</Warning>
Use these samples to understand payload shape, copy the matching crew, and then replace the test payload with your live trigger data.
### Triggers with Crew
@@ -241,15 +264,20 @@ def delegate_to_crew(self, crewai_trigger_payload: dict = None):
## Troubleshooting
**Trigger not firing:**
- Verify the trigger is enabled
- Check integration connection status
- Verify the trigger is enabled in your deployment's Triggers tab
- Check integration connection status under Tools & Integrations
- Ensure all required environment variables are properly configured
**Execution failures:**
- Check the execution logs for error details
- If you are developing, make sure the inputs include the `crewai_trigger_payload` parameter with the correct payload
- Use `crewai triggers run <trigger_name>` to test locally and see the exact payload structure
- Verify your crew can handle the `crewai_trigger_payload` parameter
- Ensure your crew doesn't expect parameters that aren't included in the trigger payload
**Development issues:**
- Always test with `crewai triggers run <trigger>` before deploying to see the complete payload
- Remember that `crewai run` does NOT simulate trigger calls—use `crewai triggers run` instead
- Use `crewai triggers list` to verify which triggers are available for your connected integrations
- After deployment, your crew will receive the actual trigger payload, so test thoroughly locally first
Automation triggers transform your CrewAI deployments into responsive, event-driven systems that can seamlessly integrate with your existing business processes and tools.
<Card title="CrewAI AMP Trigger Examples" href="https://github.com/crewAIInc/crewai-enterprise-trigger-examples" icon="github">
Check them out on GitHub!
</Card>

View File

@@ -19,8 +19,8 @@ This guide walks you through connecting Azure OpenAI with Crew Studio for seamle
</Frame>
</Step>
<Step title="Configure CrewAI AMP Connection">
4. In another tab, open `CrewAI AMP > LLM Connections`. Name your LLM Connection, select Azure as the provider, and choose the same model you selected in Azure.
<Step title="Configure CrewAI AOP Connection">
4. In another tab, open `CrewAI AOP > LLM Connections`. Name your LLM Connection, select Azure as the provider, and choose the same model you selected in Azure.
5. On the same page, add environment variables from step 3:
- One named `AZURE_DEPLOYMENT_TARGET_URL` (using the Target URI). The URL should look like this: https://your-deployment.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview
- Another named `AZURE_API_KEY` (using the Key).
@@ -28,7 +28,7 @@ This guide walks you through connecting Azure OpenAI with Crew Studio for seamle
</Step>
<Step title="Set Default Configuration">
7. In `CrewAI AMP > Settings > Defaults > Crew Studio LLM Settings`, set the new LLM Connection and model as defaults.
7. In `CrewAI AOP > Settings > Defaults > Crew Studio LLM Settings`, set the new LLM Connection and model as defaults.
</Step>
<Step title="Configure Network Access">

View File

@@ -7,7 +7,7 @@ mode: "wide"
## Overview
[CrewAI AMP](https://app.crewai.com) streamlines the process of **creating**, **deploying**, and **managing** your AI agents in production environments.
[CrewAI AOP](https://app.crewai.com) streamlines the process of **creating**, **deploying**, and **managing** your AI agents in production environments.
## Getting Started

View File

@@ -1,11 +1,11 @@
---
title: "Open Telemetry Logs"
description: "Understand how to capture telemetry logs from your CrewAI AMP deployments"
description: "Understand how to capture telemetry logs from your CrewAI AOP deployments"
icon: "magnifying-glass-chart"
mode: "wide"
---
CrewAI AMP provides a powerful way to capture telemetry logs from your deployments. This allows you to monitor the performance of your agents and workflows, and to debug issues that may arise.
CrewAI AOP provides a powerful way to capture telemetry logs from your deployments. This allows you to monitor the performance of your agents and workflows, and to debug issues that may arise.
## Prerequisites

View File

@@ -1,12 +1,12 @@
---
title: "Deploy Crew"
description: "Deploying a Crew on CrewAI AMP"
description: "Deploying a Crew on CrewAI AOP"
icon: "rocket"
mode: "wide"
---
<Note>
After creating a crew locally or through Crew Studio, the next step is deploying it to the CrewAI AMP platform. This guide covers multiple deployment methods to help you choose the best approach for your workflow.
After creating a crew locally or through Crew Studio, the next step is deploying it to the CrewAI AOP platform. This guide covers multiple deployment methods to help you choose the best approach for your workflow.
</Note>
## Prerequisites
@@ -39,10 +39,10 @@ The CLI provides the fastest way to deploy locally developed crews to the Enterp
</Step>
<Step title="Authenticate with the Enterprise Platform">
First, you need to authenticate your CLI with the CrewAI AMP platform:
First, you need to authenticate your CLI with the CrewAI AOP platform:
```bash
# If you already have a CrewAI AMP account, or want to create one:
# If you already have a CrewAI AOP account, or want to create one:
crewai login
```
@@ -124,7 +124,7 @@ The CrewAI CLI offers several commands to manage your deployments:
## Option 2: Deploy Directly via Web Interface
You can also deploy your crews directly through the CrewAI AMP web interface by connecting your GitHub account. This approach doesn't require using the CLI on your local machine.
You can also deploy your crews directly through the CrewAI AOP web interface by connecting your GitHub account. This approach doesn't require using the CLI on your local machine.
<Steps>
@@ -134,9 +134,9 @@ You can also deploy your crews directly through the CrewAI AMP web interface by
</Step>
<Step title="Connecting GitHub to CrewAI AMP">
<Step title="Connecting GitHub to CrewAI AOP">
1. Log in to [CrewAI AMP](https://app.crewai.com)
1. Log in to [CrewAI AOP](https://app.crewai.com)
2. Click on the button "Connect GitHub"
<Frame>
@@ -190,7 +190,7 @@ You can also deploy your crews directly through the CrewAI AMP web interface by
## ⚠️ Environment Variable Security Requirements
<Warning>
**Important**: CrewAI AMP has security restrictions on environment variable names that can cause deployment failures if not followed.
**Important**: CrewAI AOP has security restrictions on environment variable names that can cause deployment failures if not followed.
</Warning>
### Blocked Environment Variable Patterns

View File

@@ -1,6 +1,6 @@
---
title: "Enable Crew Studio"
description: "Enabling Crew Studio on CrewAI AMP"
description: "Enabling Crew Studio on CrewAI AOP"
icon: "comments"
mode: "wide"
---
@@ -24,7 +24,7 @@ With Crew Studio, you can:
- Select appropriate tools
- Configure necessary inputs
- Generate downloadable code for customization
- Deploy directly to the CrewAI AMP platform
- Deploy directly to the CrewAI AOP platform
## Configuration Steps
@@ -32,7 +32,7 @@ Before you can start using Crew Studio, you need to configure your LLM connectio
<Steps>
<Step title="Set Up LLM Connection">
Go to the **LLM Connections** tab in your CrewAI AMP dashboard and create a new LLM connection.
Go to the **LLM Connections** tab in your CrewAI AOP dashboard and create a new LLM connection.
<Note>
Feel free to use any LLM provider you want that is supported by CrewAI.
@@ -82,7 +82,7 @@ Now that you've configured your LLM connection and default settings, you're read
<Steps>
<Step title="Access Studio">
Navigate to the **Studio** section in your CrewAI AMP dashboard.
Navigate to the **Studio** section in your CrewAI AOP dashboard.
</Step>
<Step title="Start a Conversation">
@@ -110,7 +110,7 @@ Now that you've configured your LLM connection and default settings, you're read
Once you're satisfied with the configuration, you can:
- Download the generated code for local customization
- Deploy the crew directly to the CrewAI AMP platform
- Deploy the crew directly to the CrewAI AOP platform
- Modify the configuration and regenerate the crew
</Step>
@@ -162,5 +162,5 @@ Here's a typical workflow for creating a crew with Crew Studio:
</Steps>
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Crew Studio or any other CrewAI AMP features.
Contact our support team for assistance with Crew Studio or any other CrewAI AOP features.
</Card>

View File

@@ -15,7 +15,7 @@ Use the Gmail Trigger to kick off your deployed crews when Gmail events happen i
## Enabling the Gmail Trigger
1. Open your deployment in CrewAI AMP
1. Open your deployment in CrewAI AOP
2. Go to the **Triggers** tab
3. Locate **Gmail** and switch the toggle to enable
@@ -51,16 +51,25 @@ class GmailProcessingCrew:
)
```
The Gmail payload will be available via the standard context mechanisms. See the payload samples repository for structure and fields.
The Gmail payload will be available via the standard context mechanisms.
### Sample payloads & crews
### Testing Locally
The [CrewAI AMP Trigger Examples repository](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/gmail) includes:
Test your Gmail trigger integration locally using the CrewAI CLI:
- `new-email-payload-1.json` / `new-email-payload-2.json` — production-style new message alerts with matching crews in `new-email-crew.py`
- `thread-updated-sample-1.json` — follow-up messages on an existing thread, processed by `gmail-alert-crew.py`
```bash
# View all available triggers
crewai triggers list
Use these samples to validate your parsing logic locally before wiring the trigger to your live Gmail accounts.
# Simulate a Gmail trigger with realistic payload
crewai triggers run gmail/new_email
```
The `crewai triggers run` command will execute your crew with a complete Gmail payload, allowing you to test your parsing logic before deployment.
<Warning>
Use `crewai triggers run gmail/new_email` (not `crewai run`) to simulate trigger execution during development. After deployment, your crew will automatically receive the trigger payload.
</Warning>
## Monitoring Executions
@@ -70,16 +79,10 @@ Track history and performance of triggered runs:
<img src="/images/enterprise/list-executions.png" alt="List of executions triggered by automation" />
</Frame>
## Payload Reference
See the sample payloads and field descriptions:
<Card title="Gmail samples in Trigger Examples Repo" href="https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/gmail" icon="envelopes-bulk">
Gmail samples in Trigger Examples Repo
</Card>
## Troubleshooting
- Ensure Gmail is connected in Tools & Integrations
- Verify the Gmail Trigger is enabled on the Triggers tab
- Test locally with `crewai triggers run gmail/new_email` to see the exact payload structure
- Check the execution logs and confirm the payload is passed as `crewai_trigger_payload`
- Remember: use `crewai triggers run` (not `crewai run`) to simulate trigger execution

View File

@@ -15,7 +15,7 @@ Use the Google Calendar trigger to launch automations whenever calendar events c
## Enabling the Google Calendar Trigger
1. Open your deployment in CrewAI AMP
1. Open your deployment in CrewAI AOP
2. Go to the **Triggers** tab
3. Locate **Google Calendar** and switch the toggle to enable
@@ -39,16 +39,23 @@ print(result.raw)
Use `crewai_trigger_payload` exactly as it is delivered by the trigger so the crew can extract the proper fields.
## Sample payloads & crews
## Testing Locally
The [Google Calendar examples](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/google_calendar) show how to handle multiple event types:
Test your Google Calendar trigger integration locally using the CrewAI CLI:
- `new-event.json` → standard event creation handled by `calendar-event-crew.py`
- `event-updated.json` / `event-started.json` / `event-ended.json` → in-flight updates processed by `calendar-meeting-crew.py`
- `event-canceled.json` → cancellation workflow that alerts attendees via `calendar-meeting-crew.py`
- Working location events use `calendar-working-location-crew.py` to extract on-site schedules
```bash
# View all available triggers
crewai triggers list
Each crew transforms raw event metadata (attendees, rooms, working locations) into the summaries your teams need.
# Simulate a Google Calendar trigger with realistic payload
crewai triggers run google_calendar/event_changed
```
The `crewai triggers run` command will execute your crew with a complete Calendar payload, allowing you to test your parsing logic before deployment.
<Warning>
Use `crewai triggers run google_calendar/event_changed` (not `crewai run`) to simulate trigger execution during development. After deployment, your crew will automatically receive the trigger payload.
</Warning>
## Monitoring Executions
@@ -61,5 +68,7 @@ The **Executions** list in the deployment dashboard tracks every triggered run a
## Troubleshooting
- Ensure the correct Google account is connected and the trigger is enabled
- Test locally with `crewai triggers run google_calendar/event_changed` to see the exact payload structure
- Confirm your workflow handles all-day events (payloads use `start.date` and `end.date` instead of timestamps)
- Check execution logs if reminders or attendee arrays are missing—calendar permissions can limit fields in the payload
- Remember: use `crewai triggers run` (not `crewai run`) to simulate trigger execution

View File

@@ -15,7 +15,7 @@ Trigger your automations when files are created, updated, or removed in Google D
## Enabling the Google Drive Trigger
1. Open your deployment in CrewAI AMP
1. Open your deployment in CrewAI AOP
2. Go to the **Triggers** tab
3. Locate **Google Drive** and switch the toggle to enable
@@ -36,15 +36,23 @@ crew.kickoff({
})
```
## Sample payloads & crews
## Testing Locally
Explore the [Google Drive examples](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/google_drive) to cover different operations:
Test your Google Drive trigger integration locally using the CrewAI CLI:
- `new-file.json` → new uploads processed by `drive-file-crew.py`
- `updated-file.json` → file edits and metadata changes handled by `drive-file-crew.py`
- `deleted-file.json` → deletion events routed through `drive-file-deletion-crew.py`
```bash
# View all available triggers
crewai triggers list
Each crew highlights the file name, operation type, owner, permissions, and security considerations so downstream systems can respond appropriately.
# Simulate a Google Drive trigger with realistic payload
crewai triggers run google_drive/file_changed
```
The `crewai triggers run` command will execute your crew with a complete Drive payload, allowing you to test your parsing logic before deployment.
<Warning>
Use `crewai triggers run google_drive/file_changed` (not `crewai run`) to simulate trigger execution during development. After deployment, your crew will automatically receive the trigger payload.
</Warning>
## Monitoring Executions
@@ -57,5 +65,7 @@ Track history and performance of triggered runs with the **Executions** list in
## Troubleshooting
- Verify Google Drive is connected and the trigger toggle is enabled
- Test locally with `crewai triggers run google_drive/file_changed` to see the exact payload structure
- If a payload is missing permission data, ensure the connected account has access to the file or folder
- The trigger sends file IDs only; use the Drive API if you need to fetch binary content during the crew run
- Remember: use `crewai triggers run` (not `crewai run`) to simulate trigger execution

View File

@@ -5,22 +5,22 @@ icon: "hubspot"
mode: "wide"
---
This guide provides a step-by-step process to set up HubSpot triggers for CrewAI AMP, enabling you to initiate crews directly from HubSpot Workflows.
This guide provides a step-by-step process to set up HubSpot triggers for CrewAI AOP, enabling you to initiate crews directly from HubSpot Workflows.
## Prerequisites
- A CrewAI AMP account
- A CrewAI AOP account
- A HubSpot account with the [HubSpot Workflows](https://knowledge.hubspot.com/workflows/create-workflows) feature
## Setup Steps
<Steps>
<Step title="Connect your HubSpot account with CrewAI AMP">
- Log in to your `CrewAI AMP account > Triggers`
<Step title="Connect your HubSpot account with CrewAI AOP">
- Log in to your `CrewAI AOP account > Triggers`
- Select `HubSpot` from the list of available triggers
- Choose the HubSpot account you want to connect with CrewAI AMP
- Follow the on-screen prompts to authorize CrewAI AMP access to your HubSpot account
- A confirmation message will appear once HubSpot is successfully connected with CrewAI AMP
- Choose the HubSpot account you want to connect with CrewAI AOP
- Follow the on-screen prompts to authorize CrewAI AOP access to your HubSpot account
- A confirmation message will appear once HubSpot is successfully connected with CrewAI AOP
</Step>
<Step title="Create a HubSpot Workflow">
- Log in to your `HubSpot account > Automations > Workflows > New workflow`
@@ -49,16 +49,4 @@ This guide provides a step-by-step process to set up HubSpot triggers for CrewAI
</Step>
</Steps>
## Additional Resources
### Sample payloads & crews
You can jump-start development with the [HubSpot examples in the trigger repository](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/hubspot):
- `record-created-contact.json`, `record-updated-contact.json` → contact lifecycle events handled by `hubspot-contact-crew.py`
- `record-created-company.json`, `record-updated-company.json` → company enrichment flows in `hubspot-company-crew.py`
- `record-created-deals.json`, `record-updated-deals.json` → deal pipeline automation in `hubspot-record-crew.py`
Each crew demonstrates how to parse HubSpot record fields, enrich context, and return structured insights.
For more detailed information on available actions and customization options, refer to the [HubSpot Workflows Documentation](https://knowledge.hubspot.com/workflows/create-workflows).

View File

@@ -1,19 +1,19 @@
---
title: "Kickoff Crew"
description: "Kickoff a Crew on CrewAI AMP"
description: "Kickoff a Crew on CrewAI AOP"
icon: "flag-checkered"
mode: "wide"
---
## Overview
Once you've deployed your crew to the CrewAI AMP platform, you can kickoff executions through the web interface or the API. This guide covers both approaches.
Once you've deployed your crew to the CrewAI AOP platform, you can kickoff executions through the web interface or the API. This guide covers both approaches.
## Method 1: Using the Web Interface
### Step 1: Navigate to Your Deployed Crew
1. Log in to [CrewAI AMP](https://app.crewai.com)
1. Log in to [CrewAI AOP](https://app.crewai.com)
2. Click on the crew name from your projects list
3. You'll be taken to the crew's detail page
@@ -83,7 +83,7 @@ Once execution is complete:
## Method 2: Using the API
You can also kickoff crews programmatically using the CrewAI AMP REST API.
You can also kickoff crews programmatically using the CrewAI AOP REST API.
### Authentication

View File

@@ -15,7 +15,7 @@ Use the Microsoft Teams trigger to start automations whenever a new chat is crea
## Enabling the Microsoft Teams Trigger
1. Open your deployment in CrewAI AMP
1. Open your deployment in CrewAI AOP
2. Go to the **Triggers** tab
3. Locate **Microsoft Teams** and switch the toggle to enable
@@ -37,16 +37,28 @@ print(result.raw)
The crew parses thread metadata (subject, created time, roster) and generates an action plan for the receiving team.
## Sample payloads & crews
## Testing Locally
The [Microsoft Teams examples](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/microsoft-teams) include:
Test your Microsoft Teams trigger integration locally using the CrewAI CLI:
- `chat-created.json` → chat creation payload processed by `teams-chat-created-crew.py`
```bash
# View all available triggers
crewai triggers list
The crew demonstrates how to extract participants, initial messages, tenant information, and compliance metadata from the Microsoft Graph webhook payload.
# Simulate a Microsoft Teams trigger with realistic payload
crewai triggers run microsoft_teams/teams_message_created
```
The `crewai triggers run` command will execute your crew with a complete Teams payload, allowing you to test your parsing logic before deployment.
<Warning>
Use `crewai triggers run microsoft_teams/teams_message_created` (not `crewai run`) to simulate trigger execution during development. After deployment, your crew will automatically receive the trigger payload.
</Warning>
## Troubleshooting
- Ensure the Teams connection is active; it must be refreshed if the tenant revokes permissions
- Test locally with `crewai triggers run microsoft_teams/teams_message_created` to see the exact payload structure
- Confirm the webhook subscription in Microsoft 365 is still valid if payloads stop arriving
- Review execution logs for payload shape mismatches—Graph notifications may omit fields when a chat is private or restricted
- Remember: use `crewai triggers run` (not `crewai run`) to simulate trigger execution

View File

@@ -15,7 +15,7 @@ Start automations when files change inside OneDrive. You can generate audit summ
## Enabling the OneDrive Trigger
1. Open your deployment in CrewAI AMP
1. Open your deployment in CrewAI AOP
2. Go to the **Triggers** tab
3. Locate **OneDrive** and switch the toggle to enable
@@ -36,18 +36,28 @@ crew.kickoff({
The crew inspects file metadata, user activity, and permission changes to produce a compliance-friendly summary.
## Sample payloads & crews
## Testing Locally
The [OneDrive examples](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/onedrive) showcase how to:
Test your OneDrive trigger integration locally using the CrewAI CLI:
- Parse file metadata, size, and folder paths
- Track who created and last modified the file
- Highlight permission and external sharing changes
```bash
# View all available triggers
crewai triggers list
`onedrive-file-crew.py` bundles the analysis and summarization tasks so you can add remediation steps as needed.
# Simulate a OneDrive trigger with realistic payload
crewai triggers run microsoft_onedrive/file_changed
```
The `crewai triggers run` command will execute your crew with a complete OneDrive payload, allowing you to test your parsing logic before deployment.
<Warning>
Use `crewai triggers run microsoft_onedrive/file_changed` (not `crewai run`) to simulate trigger execution during development. After deployment, your crew will automatically receive the trigger payload.
</Warning>
## Troubleshooting
- Ensure the connected account has permission to read the file metadata included in the webhook
- Test locally with `crewai triggers run microsoft_onedrive/file_changed` to see the exact payload structure
- If the trigger fires but the payload is missing `permissions`, confirm the site-level sharing settings allow Graph to return this field
- For large tenants, filter notifications upstream so the crew only runs on relevant directories
- Remember: use `crewai triggers run` (not `crewai run`) to simulate trigger execution

View File

@@ -15,7 +15,7 @@ Automate responses when Outlook delivers a new message or when an event is remov
## Enabling the Outlook Trigger
1. Open your deployment in CrewAI AMP
1. Open your deployment in CrewAI AOP
2. Go to the **Triggers** tab
3. Locate **Outlook** and switch the toggle to enable
@@ -36,17 +36,28 @@ crew.kickoff({
The crew extracts sender details, subject, body preview, and attachments before generating a structured response.
## Sample payloads & crews
## Testing Locally
Review the [Outlook examples](https://github.com/crewAIInc/crewai-enterprise-trigger-examples/tree/main/outlook) for two common scenarios:
Test your Outlook trigger integration locally using the CrewAI CLI:
- `new-message.json` → new mail notifications parsed by `outlook-message-crew.py`
- `event-removed.json` → calendar cleanup handled by `outlook-event-removal-crew.py`
```bash
# View all available triggers
crewai triggers list
Each crew demonstrates how to handle Microsoft Graph payloads, normalize headers, and keep humans in-the-loop with concise summaries.
# Simulate an Outlook trigger with realistic payload
crewai triggers run microsoft_outlook/email_received
```
The `crewai triggers run` command will execute your crew with a complete Outlook payload, allowing you to test your parsing logic before deployment.
<Warning>
Use `crewai triggers run microsoft_outlook/email_received` (not `crewai run`) to simulate trigger execution during development. After deployment, your crew will automatically receive the trigger payload.
</Warning>
## Troubleshooting
- Verify the Outlook connector is still authorized; the subscription must be renewed periodically
- Test locally with `crewai triggers run microsoft_outlook/email_received` to see the exact payload structure
- If attachments are missing, confirm the webhook subscription includes the `includeResourceData` flag
- Review execution logs when events fail to match—cancellation payloads lack attendee lists by design and the crew should account for that
- Remember: use `crewai triggers run` (not `crewai run`) to simulate trigger execution

View File

@@ -1,11 +1,11 @@
---
title: "React Component Export"
description: "Learn how to export and integrate CrewAI AMP React components into your applications"
description: "Learn how to export and integrate CrewAI AOP React components into your applications"
icon: "react"
mode: "wide"
---
This guide explains how to export CrewAI AMP crews as React components and integrate them into your own applications.
This guide explains how to export CrewAI AOP crews as React components and integrate them into your own applications.
## Exporting a React Component

View File

@@ -5,7 +5,7 @@ icon: "salesforce"
mode: "wide"
---
CrewAI AMP can be triggered from Salesforce to automate customer relationship management workflows and enhance your sales operations.
CrewAI AOP can be triggered from Salesforce to automate customer relationship management workflows and enhance your sales operations.
## Overview
@@ -31,7 +31,7 @@ Salesforce is a leading customer relationship management (CRM) platform that hel
To set up Salesforce triggers:
1. **Contact Support**: Reach out to CrewAI AMP support for assistance with Salesforce trigger setup
1. **Contact Support**: Reach out to CrewAI AOP support for assistance with Salesforce trigger setup
2. **Review Requirements**: Ensure you have the necessary Salesforce permissions and API access
3. **Configure Connection**: Work with the support team to establish the connection between CrewAI and your Salesforce instance
4. **Test Triggers**: Verify the triggers work correctly with your specific use cases
@@ -47,4 +47,4 @@ Common Salesforce + CrewAI trigger scenarios include:
## Next Steps
For detailed setup instructions and advanced configuration options, please contact CrewAI AMP support who can provide tailored guidance for your specific Salesforce environment and business needs.
For detailed setup instructions and advanced configuration options, please contact CrewAI AOP support who can provide tailored guidance for your specific Salesforce environment and business needs.

View File

@@ -1,17 +1,17 @@
---
title: "Team Management"
description: "Learn how to invite and manage team members in your CrewAI AMP organization"
description: "Learn how to invite and manage team members in your CrewAI AOP organization"
icon: "users"
mode: "wide"
---
As an administrator of a CrewAI AMP account, you can easily invite new team members to join your organization. This guide will walk you through the process step-by-step.
As an administrator of a CrewAI AOP account, you can easily invite new team members to join your organization. This guide will walk you through the process step-by-step.
## Inviting Team Members
<Steps>
<Step title="Access the Settings Page">
- Log in to your CrewAI AMP account
- Log in to your CrewAI AOP account
- Look for the gear icon (⚙️) in the top right corner of the dashboard
- Click on the gear icon to access the **Settings** page:
<Frame caption="Settings page">
@@ -43,7 +43,7 @@ You can add roles to your team members to control their access to different part
<Steps>
<Step title="Access the Settings Page">
- Log in to your CrewAI AMP account
- Log in to your CrewAI AOP account
- Look for the gear icon (⚙️) in the top right corner of the dashboard
- Click on the gear icon to access the **Settings** page:
<Frame>
@@ -85,4 +85,4 @@ You can add roles to your team members to control their access to different part
- **Invitation Acceptance**: Invited members will need to accept the invitation to join your organization
- **Email Notifications**: You may want to inform your team members to check their email (including spam folders) for the invitation
By following these steps, you can easily expand your team and collaborate more effectively within your CrewAI AMP organization.
By following these steps, you can easily expand your team and collaborate more effectively within your CrewAI AOP organization.

View File

@@ -20,11 +20,11 @@ The repository is not a version control system. Use Git to track code changes an
Before using the Tool Repository, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account
- [CrewAI CLI](https://docs.crewai.com/concepts/cli#cli) installed
- A [CrewAI AOP](https://app.crewai.com) account
- [CrewAI CLI](/en/concepts/cli#cli) installed
- uv>=0.5.0 installed. Check out [how to upgrade](https://docs.astral.sh/uv/getting-started/installation/#upgrading-uv)
- [Git](https://git-scm.com) installed and configured
- Access permissions to publish or install tools in your CrewAI AMP organization
- Access permissions to publish or install tools in your CrewAI AOP organization
## Installing Tools
@@ -54,11 +54,11 @@ researcher = Agent(
## Adding other packages after installing a tool
After installing a tool from the CrewAI AMP Tool Repository, you need to use the `crewai uv` command to add other packages to your project.
After installing a tool from the CrewAI AOP Tool Repository, you need to use the `crewai uv` command to add other packages to your project.
Using pure `uv` commands will fail due to authentication to tool repository being handled by the CLI. By using the `crewai uv` command, you can add other packages to your project without having to worry about authentication.
Any `uv` command can be used with the `crewai uv` command, making it a powerful tool for managing your project's dependencies without the hassle of managing authentication through environment variables or other methods.
Say that you have installed a custom tool from the CrewAI AMP Tool Repository called "my-tool":
Say that you have installed a custom tool from the CrewAI AOP Tool Repository called "my-tool":
```bash
crewai tool install my-tool
@@ -112,7 +112,7 @@ By default, tools are published as private. To make a tool public:
crewai tool publish --public
```
For more details on how to build tools, see [Creating your own tools](https://docs.crewai.com/concepts/tools#creating-your-own-tools).
For more details on how to build tools, see [Creating your own tools](/en/concepts/tools#creating-your-own-tools).
## Updating Tools
@@ -131,7 +131,7 @@ crewai tool publish
To delete a tool:
1. Go to [CrewAI AMP](https://app.crewai.com)
1. Go to [CrewAI AOP](https://app.crewai.com)
2. Navigate to **Tools**
3. Select the tool
4. Click **Delete**
@@ -146,7 +146,7 @@ Every published version undergoes automated security checks, and are only availa
You can check the security check status of a tool at:
`CrewAI AMP > Tools > Your Tool > Versions`
`CrewAI AOP > Tools > Your Tool > Versions`
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with API integration or troubleshooting.

View File

@@ -1,12 +1,12 @@
---
title: "Update Crew"
description: "Updating a Crew on CrewAI AMP"
description: "Updating a Crew on CrewAI AOP"
icon: "pencil"
mode: "wide"
---
<Note>
After deploying your crew to CrewAI AMP, you may need to make updates to the code, security settings, or configuration.
After deploying your crew to CrewAI AOP, you may need to make updates to the code, security settings, or configuration.
This guide explains how to perform these common update operations.
</Note>
@@ -23,7 +23,7 @@ There are several reasons you might want to update your crew deployment:
When you've pushed new commits to your GitHub repository and want to update your deployment:
1. Navigate to your crew in the CrewAI AMP platform
1. Navigate to your crew in the CrewAI AOP platform
2. Click on the `Re-deploy` button on your crew details page
<Frame>
@@ -36,7 +36,7 @@ This will trigger an update that you can track using the progress bar. The syste
If you need to generate a new bearer token (for example, if you suspect the current token might have been compromised):
1. Navigate to your crew in the CrewAI AMP platform
1. Navigate to your crew in the CrewAI AOP platform
2. Find the `Bearer Token` section
3. Click the `Reset` button next to your current token

View File

@@ -1,17 +1,17 @@
---
title: "Webhook Automation"
description: "Automate CrewAI AMP workflows using webhooks with platforms like ActivePieces, Zapier, and Make.com"
description: "Automate CrewAI AOP workflows using webhooks with platforms like ActivePieces, Zapier, and Make.com"
icon: "webhook"
mode: "wide"
---
CrewAI AMP allows you to automate your workflow using webhooks. This article will guide you through the process of setting up and using webhooks to kickoff your crew execution, with a focus on integration with ActivePieces, a workflow automation platform similar to Zapier and Make.com.
CrewAI AOP allows you to automate your workflow using webhooks. This article will guide you through the process of setting up and using webhooks to kickoff your crew execution, with a focus on integration with ActivePieces, a workflow automation platform similar to Zapier and Make.com.
## Setting Up Webhooks
<Steps>
<Step title="Accessing the Kickoff Interface">
- Navigate to the CrewAI AMP dashboard
- Navigate to the CrewAI AOP dashboard
- Look for the `/kickoff` section, which is used to start the crew execution
<Frame>
<img src="/images/enterprise/kickoff-interface.png" alt="Kickoff Interface" />
@@ -44,7 +44,7 @@ CrewAI AMP allows you to automate your workflow using webhooks. This article wil
3. Add an HTTP action step
- Set the action to `Send HTTP request`
- Use `POST` as the method
- Set the URL to your CrewAI AMP kickoff endpoint
- Set the URL to your CrewAI AOP kickoff endpoint
- Add necessary headers (e.g., `Bearer Token`)
<Frame>
<img src="/images/enterprise/activepieces-headers.png" alt="ActivePieces Headers" />

View File

@@ -5,11 +5,11 @@ icon: "bolt"
mode: "wide"
---
This guide will walk you through the process of setting up Zapier triggers for CrewAI AMP, allowing you to automate workflows between CrewAI AMP and other applications.
This guide will walk you through the process of setting up Zapier triggers for CrewAI AOP, allowing you to automate workflows between CrewAI AOP and other applications.
## Prerequisites
- A CrewAI AMP account
- A CrewAI AOP account
- A Zapier account
- A Slack account (for this specific example)
@@ -32,7 +32,7 @@ This guide will walk you through the process of setting up Zapier triggers for C
- Connect your Slack account if you haven't already.
</Step>
<Step title="Configure the CrewAI AMP Action">
<Step title="Configure the CrewAI AOP Action">
- Add a new action step to your Zap.
- Choose CrewAI+ as your action app and Kickoff as the Action Event
@@ -41,8 +41,8 @@ This guide will walk you through the process of setting up Zapier triggers for C
</Frame>
</Step>
<Step title="Connect your CrewAI AMP account">
- Connect your CrewAI AMP account.
<Step title="Connect your CrewAI AOP account">
- Connect your CrewAI AOP account.
- Select the appropriate Crew for your workflow.
<Frame>
@@ -51,8 +51,8 @@ This guide will walk you through the process of setting up Zapier triggers for C
- Configure the inputs for the Crew using the data from the Slack message.
</Step>
<Step title="Format the CrewAI AMP Output">
- Add another action step to format the text output from CrewAI AMP.
<Step title="Format the CrewAI AOP Output">
- Add another action step to format the text output from CrewAI AOP.
- Use Zapier's formatting tools to convert the Markdown output to HTML.
<Frame>
@@ -67,7 +67,7 @@ This guide will walk you through the process of setting up Zapier triggers for C
- Add a final action step to send the formatted output via email.
- Choose your preferred email service (e.g., Gmail, Outlook).
- Configure the email details, including recipient, subject, and body.
- Insert the formatted CrewAI AMP output into the email body.
- Insert the formatted CrewAI AOP output into the email body.
<Frame>
<img src="/images/enterprise/zapier-7.png" alt="Zapier 7" />
@@ -97,8 +97,8 @@ This guide will walk you through the process of setting up Zapier triggers for C
## Tips for Success
- Ensure that your CrewAI AMP inputs are correctly mapped from the Slack message.
- Ensure that your CrewAI AOP inputs are correctly mapped from the Slack message.
- Test your Zap thoroughly before turning it on to catch any potential issues.
- Consider adding error handling steps to manage potential failures in the workflow.
By following these steps, you'll have successfully set up Zapier triggers for CrewAI AMP, allowing for automated workflows triggered by Slack messages and resulting in email notifications with CrewAI AMP output.
By following these steps, you'll have successfully set up Zapier triggers for CrewAI AOP, allowing for automated workflows triggered by Slack messages and resulting in email notifications with CrewAI AOP output.

View File

@@ -13,7 +13,7 @@ Enable your agents to manage tasks, projects, and team coordination through Asan
Before using the Asana integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- An Asana account with appropriate permissions
- Connected your Asana account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Asana integration, ensure you have:
### 1. Connect Your Asana Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Asana** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for task and project management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the Asana integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="ASANA_CREATE_COMMENT">
<Accordion title="asana/create_comment">
**Description:** Create a comment in Asana.
**Parameters:**
@@ -44,7 +60,7 @@ uv add crewai-tools
- `text` (string, required): Text (example: "This is a comment.").
</Accordion>
<Accordion title="ASANA_CREATE_PROJECT">
<Accordion title="asana/create_project">
**Description:** Create a project in Asana.
**Parameters:**
@@ -54,7 +70,7 @@ uv add crewai-tools
- `notes` (string, optional): Notes (example: "These are things we need to purchase.").
</Accordion>
<Accordion title="ASANA_GET_PROJECTS">
<Accordion title="asana/get_projects">
**Description:** Get a list of projects in Asana.
**Parameters:**
@@ -62,14 +78,14 @@ uv add crewai-tools
- Options: `default`, `true`, `false`
</Accordion>
<Accordion title="ASANA_GET_PROJECT_BY_ID">
<Accordion title="asana/get_project_by_id">
**Description:** Get a project by ID in Asana.
**Parameters:**
- `projectFilterId` (string, required): Project ID.
</Accordion>
<Accordion title="ASANA_CREATE_TASK">
<Accordion title="asana/create_task">
**Description:** Create a task in Asana.
**Parameters:**
@@ -83,7 +99,7 @@ uv add crewai-tools
- `gid` (string, optional): External ID - An ID from your application to associate this task with. You can use this ID to sync updates to this task later.
</Accordion>
<Accordion title="ASANA_UPDATE_TASK">
<Accordion title="asana/update_task">
**Description:** Update a task in Asana.
**Parameters:**
@@ -98,7 +114,7 @@ uv add crewai-tools
- `gid` (string, optional): External ID - An ID from your application to associate this task with. You can use this ID to sync updates to this task later.
</Accordion>
<Accordion title="ASANA_GET_TASKS">
<Accordion title="asana/get_tasks">
**Description:** Get a list of tasks in Asana.
**Parameters:**
@@ -108,21 +124,21 @@ uv add crewai-tools
- `completedSince` (string, optional): Completed since - Only return tasks that are either incomplete or that have been completed since this time (ISO or Unix timestamp). (example: "2014-04-25T16:15:47-04:00").
</Accordion>
<Accordion title="ASANA_GET_TASKS_BY_ID">
<Accordion title="asana/get_tasks_by_id">
**Description:** Get a list of tasks by ID in Asana.
**Parameters:**
- `taskId` (string, required): Task ID.
</Accordion>
<Accordion title="ASANA_GET_TASK_BY_EXTERNAL_ID">
<Accordion title="asana/get_task_by_external_id">
**Description:** Get a task by external ID in Asana.
**Parameters:**
- `gid` (string, required): External ID - The ID that this task is associated or synced with, from your application.
</Accordion>
<Accordion title="ASANA_ADD_TASK_TO_SECTION">
<Accordion title="asana/add_task_to_section">
**Description:** Add a task to a section in Asana.
**Parameters:**
@@ -132,14 +148,14 @@ uv add crewai-tools
- `afterTaskId` (string, optional): After Task ID - The ID of a task in this section that this task will be inserted after. Cannot be used with Before Task ID. (example: "1204619611402340").
</Accordion>
<Accordion title="ASANA_GET_TEAMS">
<Accordion title="asana/get_teams">
**Description:** Get a list of teams in Asana.
**Parameters:**
- `workspace` (string, required): Workspace - Returns the teams in this workspace visible to the authorized user.
</Accordion>
<Accordion title="ASANA_GET_WORKSPACES">
<Accordion title="asana/get_workspaces">
**Description:** Get a list of workspaces in Asana.
**Parameters:** None required.
@@ -152,19 +168,13 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Asana tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Asana capabilities
asana_agent = Agent(
role="Project Manager",
goal="Manage tasks and projects in Asana efficiently",
backstory="An AI assistant specialized in project management and task coordination.",
tools=[enterprise_tools]
apps=['asana'] # All Asana actions will be available
)
# Task to create a new project
@@ -186,19 +196,18 @@ crew.kickoff()
### Filtering Specific Asana Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Asana tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["asana_create_task", "asana_update_task", "asana_get_tasks"]
)
from crewai import Agent, Task, Crew
# Create agent with specific Asana actions only
task_manager_agent = Agent(
role="Task Manager",
goal="Create and manage tasks efficiently",
backstory="An AI assistant that focuses on task creation and management.",
tools=enterprise_tools
apps=[
'asana/create_task',
'asana/update_task',
'asana/get_tasks'
] # Specific Asana actions
)
# Task to create and assign a task
@@ -220,17 +229,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_coordinator = Agent(
role="Project Coordinator",
goal="Coordinate project activities and track progress",
backstory="An experienced project coordinator who ensures projects run smoothly.",
tools=[enterprise_tools]
apps=['asana']
)
# Complex task involving multiple Asana operations

View File

@@ -13,7 +13,7 @@ Enable your agents to manage files, folders, and documents through Box. Upload f
Before using the Box integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Box account with appropriate permissions
- Connected your Box account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Box integration, ensure you have:
### 1. Connect Your Box Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Box** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for file and folder management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the Box integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="BOX_SAVE_FILE">
<Accordion title="box/save_file">
**Description:** Save a file from URL in Box.
**Parameters:**
@@ -52,7 +68,7 @@ uv add crewai-tools
- `file` (string, required): File URL - Files must be smaller than 50MB in size. (example: "https://picsum.photos/200/300").
</Accordion>
<Accordion title="BOX_SAVE_FILE_FROM_OBJECT">
<Accordion title="box/save_file_from_object">
**Description:** Save a file in Box.
**Parameters:**
@@ -61,14 +77,14 @@ uv add crewai-tools
- `folder` (string, optional): Folder - Use Connect Portal Workflow Settings to allow users to select the File's Folder destination. Defaults to the user's root folder if left blank.
</Accordion>
<Accordion title="BOX_GET_FILE_BY_ID">
<Accordion title="box/get_file_by_id">
**Description:** Get a file by ID in Box.
**Parameters:**
- `fileId` (string, required): File ID - The unique identifier that represents a file. (example: "12345").
</Accordion>
<Accordion title="BOX_LIST_FILES">
<Accordion title="box/list_files">
**Description:** List files in Box.
**Parameters:**
@@ -93,7 +109,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="BOX_CREATE_FOLDER">
<Accordion title="box/create_folder">
**Description:** Create a folder in Box.
**Parameters:**
@@ -106,7 +122,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="BOX_MOVE_FOLDER">
<Accordion title="box/move_folder">
**Description:** Move a folder in Box.
**Parameters:**
@@ -120,14 +136,14 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="BOX_GET_FOLDER_BY_ID">
<Accordion title="box/get_folder_by_id">
**Description:** Get a folder by ID in Box.
**Parameters:**
- `folderId` (string, required): Folder ID - The unique identifier that represents a folder. (example: "0").
</Accordion>
<Accordion title="BOX_SEARCH_FOLDERS">
<Accordion title="box/search_folders">
**Description:** Search folders in Box.
**Parameters:**
@@ -152,7 +168,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="BOX_DELETE_FOLDER">
<Accordion title="box/delete_folder">
**Description:** Delete a folder in Box.
**Parameters:**
@@ -167,19 +183,14 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Box tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Box capabilities
box_agent = Agent(
role="Document Manager",
goal="Manage files and folders in Box efficiently",
backstory="An AI assistant specialized in document management and file organization.",
tools=[enterprise_tools]
apps=['box'] # All Box actions will be available
)
# Task to create a folder structure
@@ -201,19 +212,14 @@ crew.kickoff()
### Filtering Specific Box Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Box tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["box_create_folder", "box_save_file", "box_list_files"]
)
from crewai import Agent, Task, Crew
# Create agent with specific Box actions only
file_organizer_agent = Agent(
role="File Organizer",
goal="Organize and manage file storage efficiently",
backstory="An AI assistant that focuses on file organization and storage management.",
tools=enterprise_tools
apps=['box/create_folder', 'box/save_file', 'box/list_files'] # Specific Box actions
)
# Task to organize files
@@ -235,17 +241,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
file_manager = Agent(
role="File Manager",
goal="Maintain organized file structure and manage document lifecycle",
backstory="An experienced file manager who ensures documents are properly organized and accessible.",
tools=[enterprise_tools]
apps=['box']
)
# Complex task involving multiple Box operations

View File

@@ -13,7 +13,7 @@ Enable your agents to manage tasks, projects, and productivity workflows through
Before using the ClickUp integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A ClickUp account with appropriate permissions
- Connected your ClickUp account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the ClickUp integration, ensure you have:
### 1. Connect Your ClickUp Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **ClickUp** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for task and project management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the ClickUp integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="CLICKUP_SEARCH_TASKS">
<Accordion title="clickup/search_tasks">
**Description:** Search for tasks in ClickUp using advanced filters.
**Parameters:**
@@ -61,7 +77,7 @@ uv add crewai-tools
Available fields: `space_ids%5B%5D`, `project_ids%5B%5D`, `list_ids%5B%5D`, `statuses%5B%5D`, `include_closed`, `assignees%5B%5D`, `tags%5B%5D`, `due_date_gt`, `due_date_lt`, `date_created_gt`, `date_created_lt`, `date_updated_gt`, `date_updated_lt`
</Accordion>
<Accordion title="CLICKUP_GET_TASK_IN_LIST">
<Accordion title="clickup/get_task_in_list">
**Description:** Get tasks in a specific list in ClickUp.
**Parameters:**
@@ -69,7 +85,7 @@ uv add crewai-tools
- `taskFilterFormula` (string, optional): Search for tasks that match specified filters. For example: name=task1.
</Accordion>
<Accordion title="CLICKUP_CREATE_TASK">
<Accordion title="clickup/create_task">
**Description:** Create a task in ClickUp.
**Parameters:**
@@ -82,7 +98,7 @@ uv add crewai-tools
- `additionalFields` (string, optional): Additional Fields - Specify additional fields to include on this task as JSON.
</Accordion>
<Accordion title="CLICKUP_UPDATE_TASK">
<Accordion title="clickup/update_task">
**Description:** Update a task in ClickUp.
**Parameters:**
@@ -96,49 +112,49 @@ uv add crewai-tools
- `additionalFields` (string, optional): Additional Fields - Specify additional fields to include on this task as JSON.
</Accordion>
<Accordion title="CLICKUP_DELETE_TASK">
<Accordion title="clickup/delete_task">
**Description:** Delete a task in ClickUp.
**Parameters:**
- `taskId` (string, required): Task ID - The ID of the task to delete.
</Accordion>
<Accordion title="CLICKUP_GET_LIST">
<Accordion title="clickup/get_list">
**Description:** Get List information in ClickUp.
**Parameters:**
- `spaceId` (string, required): Space ID - The ID of the space containing the lists.
</Accordion>
<Accordion title="CLICKUP_GET_CUSTOM_FIELDS_IN_LIST">
<Accordion title="clickup/get_custom_fields_in_list">
**Description:** Get Custom Fields in a List in ClickUp.
**Parameters:**
- `listId` (string, required): List ID - The ID of the list to get custom fields from.
</Accordion>
<Accordion title="CLICKUP_GET_ALL_FIELDS_IN_LIST">
<Accordion title="clickup/get_all_fields_in_list">
**Description:** Get All Fields in a List in ClickUp.
**Parameters:**
- `listId` (string, required): List ID - The ID of the list to get all fields from.
</Accordion>
<Accordion title="CLICKUP_GET_SPACE">
<Accordion title="clickup/get_space">
**Description:** Get Space information in ClickUp.
**Parameters:**
- `spaceId` (string, optional): Space ID - The ID of the space to retrieve.
</Accordion>
<Accordion title="CLICKUP_GET_FOLDERS">
<Accordion title="clickup/get_folders">
**Description:** Get Folders in ClickUp.
**Parameters:**
- `spaceId` (string, required): Space ID - The ID of the space containing the folders.
</Accordion>
<Accordion title="CLICKUP_GET_MEMBER">
<Accordion title="clickup/get_member">
**Description:** Get Member information in ClickUp.
**Parameters:** None required.
@@ -151,19 +167,14 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
from crewai import Agent, Task, Crew
# Get enterprise tools (ClickUp tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with ClickUp capabilities
# Create an agent with Clickup capabilities
clickup_agent = Agent(
role="Task Manager",
goal="Manage tasks and projects in ClickUp efficiently",
backstory="An AI assistant specialized in task management and productivity coordination.",
tools=[enterprise_tools]
apps=['clickup'] # All Clickup actions will be available
)
# Task to create a new task
@@ -185,19 +196,12 @@ crew.kickoff()
### Filtering Specific ClickUp Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific ClickUp tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["clickup_create_task", "clickup_update_task", "clickup_search_tasks"]
)
task_coordinator = Agent(
role="Task Coordinator",
goal="Create and manage tasks efficiently",
backstory="An AI assistant that focuses on task creation and status management.",
tools=enterprise_tools
apps=['clickup/create_task']
)
# Task to manage task workflow
@@ -219,17 +223,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_manager = Agent(
role="Project Manager",
goal="Coordinate project activities and track team productivity",
backstory="An experienced project manager who ensures projects are delivered on time.",
tools=[enterprise_tools]
apps=['clickup']
)
# Complex task involving multiple ClickUp operations
@@ -256,17 +255,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
task_analyst = Agent(
role="Task Analyst",
goal="Analyze task patterns and optimize team productivity",
backstory="An AI assistant that analyzes task data to improve team efficiency.",
tools=[enterprise_tools]
apps=['clickup']
)
# Task to analyze and optimize task distribution

View File

@@ -13,7 +13,7 @@ Enable your agents to manage repositories, issues, and releases through GitHub.
Before using the GitHub integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A GitHub account with appropriate repository permissions
- Connected your GitHub account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the GitHub integration, ensure you have:
### 1. Connect Your GitHub Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **GitHub** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for repository and issue management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the GitHub integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="GITHUB_CREATE_ISSUE">
<Accordion title="github/create_issue">
**Description:** Create an issue in GitHub.
**Parameters:**
@@ -47,7 +63,7 @@ uv add crewai-tools
- `assignees` (string, optional): Assignees - Specify the assignee(s)' GitHub login as an array of strings for this issue. (example: `["octocat"]`).
</Accordion>
<Accordion title="GITHUB_UPDATE_ISSUE">
<Accordion title="github/update_issue">
**Description:** Update an issue in GitHub.
**Parameters:**
@@ -61,7 +77,7 @@ uv add crewai-tools
- Options: `open`, `closed`
</Accordion>
<Accordion title="GITHUB_GET_ISSUE_BY_NUMBER">
<Accordion title="github/get_issue_by_number">
**Description:** Get an issue by number in GitHub.
**Parameters:**
@@ -70,7 +86,7 @@ uv add crewai-tools
- `issue_number` (string, required): Issue Number - Specify the number of the issue to fetch.
</Accordion>
<Accordion title="GITHUB_LOCK_ISSUE">
<Accordion title="github/lock_issue">
**Description:** Lock an issue in GitHub.
**Parameters:**
@@ -81,7 +97,7 @@ uv add crewai-tools
- Options: `off-topic`, `too heated`, `resolved`, `spam`
</Accordion>
<Accordion title="GITHUB_SEARCH_ISSUE">
<Accordion title="github/search_issue">
**Description:** Search for issues in GitHub.
**Parameters:**
@@ -108,7 +124,7 @@ uv add crewai-tools
Available fields: `assignee`, `creator`, `mentioned`, `labels`
</Accordion>
<Accordion title="GITHUB_CREATE_RELEASE">
<Accordion title="github/create_release">
**Description:** Create a release in GitHub.
**Parameters:**
@@ -126,7 +142,7 @@ uv add crewai-tools
- Options: `true`, `false`
</Accordion>
<Accordion title="GITHUB_UPDATE_RELEASE">
<Accordion title="github/update_release">
**Description:** Update a release in GitHub.
**Parameters:**
@@ -145,7 +161,7 @@ uv add crewai-tools
- Options: `true`, `false`
</Accordion>
<Accordion title="GITHUB_GET_RELEASE_BY_ID">
<Accordion title="github/get_release_by_id">
**Description:** Get a release by ID in GitHub.
**Parameters:**
@@ -154,7 +170,7 @@ uv add crewai-tools
- `id` (string, required): Release ID - Specify the release ID of the release to fetch.
</Accordion>
<Accordion title="GITHUB_GET_RELEASE_BY_TAG_NAME">
<Accordion title="github/get_release_by_tag_name">
**Description:** Get a release by tag name in GitHub.
**Parameters:**
@@ -163,7 +179,7 @@ uv add crewai-tools
- `tag_name` (string, required): Name - Specify the tag of the release to fetch. (example: "v1.0.0").
</Accordion>
<Accordion title="GITHUB_DELETE_RELEASE">
<Accordion title="github/delete_release">
**Description:** Delete a release in GitHub.
**Parameters:**
@@ -179,19 +195,14 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
from crewai import Agent, Task, Crew
# Get enterprise tools (GitHub tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with GitHub capabilities
# Create an agent with Github capabilities
github_agent = Agent(
role="Repository Manager",
goal="Manage GitHub repositories, issues, and releases efficiently",
backstory="An AI assistant specialized in repository management and issue tracking.",
tools=[enterprise_tools]
apps=['github'] # All Github actions will be available
)
# Task to create a new issue
@@ -213,19 +224,12 @@ crew.kickoff()
### Filtering Specific GitHub Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific GitHub tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["github_create_issue", "github_update_issue", "github_search_issue"]
)
issue_manager = Agent(
role="Issue Manager",
goal="Create and manage GitHub issues efficiently",
backstory="An AI assistant that focuses on issue tracking and management.",
tools=enterprise_tools
apps=['github/create_issue']
)
# Task to manage issue workflow
@@ -247,17 +251,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
release_manager = Agent(
role="Release Manager",
goal="Manage software releases and versioning",
backstory="An experienced release manager who handles version control and release processes.",
tools=[enterprise_tools]
apps=['github']
)
# Task to create a new release
@@ -284,17 +283,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_coordinator = Agent(
role="Project Coordinator",
goal="Track and coordinate project issues and development progress",
backstory="An AI assistant that helps coordinate development work and track project progress.",
tools=[enterprise_tools]
apps=['github']
)
# Complex task involving multiple GitHub operations

View File

@@ -13,7 +13,7 @@ Enable your agents to manage emails, contacts, and drafts through Gmail. Send em
Before using the Gmail integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Gmail account with appropriate permissions
- Connected your Gmail account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Gmail integration, ensure you have:
### 1. Connect Your Gmail Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Gmail** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for email and contact management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,141 +33,122 @@ Before using the Gmail integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="GMAIL_SEND_EMAIL">
**Description:** Send an email in Gmail.
<Accordion title="gmail/fetch_emails">
**Description:** Retrieve a list of messages.
**Parameters:**
- `toRecipients` (array, required): To - Specify the recipients as either a single string or a JSON array.
```json
[
"recipient1@domain.com",
"recipient2@domain.com"
]
```
- `from` (string, required): From - Specify the email of the sender.
- `subject` (string, required): Subject - Specify the subject of the message.
- `messageContent` (string, required): Message Content - Specify the content of the email message as plain text or HTML.
- `attachments` (string, optional): Attachments - Accepts either a single file object or a JSON array of file objects.
- `additionalHeaders` (object, optional): Additional Headers - Specify any additional header fields here.
```json
{
"reply-to": "Sender Name <sender@domain.com>"
}
```
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `q` (string, optional): Search query to filter messages (e.g., 'from:someone@example.com is:unread').
- `maxResults` (integer, optional): Maximum number of messages to return (1-500). (default: 100)
- `pageToken` (string, optional): Page token to retrieve a specific page of results.
- `labelIds` (array, optional): Only return messages with labels that match all of the specified label IDs.
- `includeSpamTrash` (boolean, optional): Include messages from SPAM and TRASH in the results. (default: false)
</Accordion>
<Accordion title="GMAIL_GET_EMAIL_BY_ID">
**Description:** Get an email by ID in Gmail.
<Accordion title="gmail/send_email">
**Description:** Send an email.
**Parameters:**
- `userId` (string, required): User ID - Specify the user's email address. (example: "user@domain.com").
- `messageId` (string, required): Message ID - Specify the ID of the message to retrieve.
- `to` (string, required): Recipient email address.
- `subject` (string, required): Email subject line.
- `body` (string, required): Email message content.
- `userId` (string, optional): The user's email address or 'me' for the authenticated user. (default: "me")
- `cc` (string, optional): CC email addresses (comma-separated).
- `bcc` (string, optional): BCC email addresses (comma-separated).
- `from` (string, optional): Sender email address (if different from authenticated user).
- `replyTo` (string, optional): Reply-to email address.
- `threadId` (string, optional): Thread ID if replying to an existing conversation.
</Accordion>
<Accordion title="GMAIL_SEARCH_FOR_EMAIL">
**Description:** Search for emails in Gmail using advanced filters.
<Accordion title="gmail/delete_email">
**Description:** Delete an email by ID.
**Parameters:**
- `emailFilterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "from",
"operator": "$stringContains",
"value": "example@domain.com"
}
]
}
]
}
```
Available fields: `from`, `to`, `date`, `label`, `subject`, `cc`, `bcc`, `category`, `deliveredto:`, `size`, `filename`, `older_than`, `newer_than`, `list`, `is:important`, `is:unread`, `is:snoozed`, `is:starred`, `is:read`, `has:drive`, `has:document`, `has:spreadsheet`, `has:presentation`, `has:attachment`, `has:youtube`, `has:userlabels`
- `paginationParameters` (object, optional): Pagination Parameters.
```json
{
"pageCursor": "page_cursor_string"
}
```
- `userId` (string, required): The user's email address or 'me' for the authenticated user.
- `id` (string, required): The ID of the message to delete.
</Accordion>
<Accordion title="GMAIL_DELETE_EMAIL">
**Description:** Delete an email in Gmail.
<Accordion title="gmail/create_draft">
**Description:** Create a new draft email.
**Parameters:**
- `userId` (string, required): User ID - Specify the user's email address. (example: "user@domain.com").
- `messageId` (string, required): Message ID - Specify the ID of the message to trash.
- `userId` (string, required): The user's email address or 'me' for the authenticated user.
- `message` (object, required): Message object containing the draft content.
- `raw` (string, required): Base64url encoded email message.
</Accordion>
<Accordion title="GMAIL_CREATE_A_CONTACT">
**Description:** Create a contact in Gmail.
<Accordion title="gmail/get_message">
**Description:** Retrieve a specific message by ID.
**Parameters:**
- `givenName` (string, required): Given Name - Specify the Given Name of the Contact to create. (example: "John").
- `familyName` (string, required): Family Name - Specify the Family Name of the Contact to create. (example: "Doe").
- `email` (string, required): Email - Specify the Email Address of the Contact to create.
- `additionalFields` (object, optional): Additional Fields - Additional contact information.
```json
{
"addresses": [
{
"streetAddress": "1000 North St.",
"city": "Los Angeles"
}
]
}
```
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `id` (string, required): The ID of the message to retrieve.
- `format` (string, optional): The format to return the message in. Options: "full", "metadata", "minimal", "raw". (default: "full")
- `metadataHeaders` (array, optional): When given and format is METADATA, only include headers specified.
</Accordion>
<Accordion title="GMAIL_GET_CONTACT_BY_RESOURCE_NAME">
**Description:** Get a contact by resource name in Gmail.
<Accordion title="gmail/get_attachment">
**Description:** Retrieve a message attachment.
**Parameters:**
- `resourceName` (string, required): Resource Name - Specify the resource name of the contact to fetch.
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `messageId` (string, required): The ID of the message containing the attachment.
- `id` (string, required): The ID of the attachment to retrieve.
</Accordion>
<Accordion title="GMAIL_SEARCH_FOR_CONTACT">
**Description:** Search for a contact in Gmail.
<Accordion title="gmail/fetch_thread">
**Description:** Retrieve a specific email thread by ID.
**Parameters:**
- `searchTerm` (string, required): Term - Specify a search term to search for near or exact matches on the names, nickNames, emailAddresses, phoneNumbers, or organizations Contact properties.
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `id` (string, required): The ID of the thread to retrieve.
- `format` (string, optional): The format to return the messages in. Options: "full", "metadata", "minimal". (default: "full")
- `metadataHeaders` (array, optional): When given and format is METADATA, only include headers specified.
</Accordion>
<Accordion title="GMAIL_DELETE_CONTACT">
**Description:** Delete a contact in Gmail.
<Accordion title="gmail/modify_thread">
**Description:** Modify the labels applied to a thread.
**Parameters:**
- `resourceName` (string, required): Resource Name - Specify the resource name of the contact to delete.
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `id` (string, required): The ID of the thread to modify.
- `addLabelIds` (array, optional): A list of IDs of labels to add to this thread.
- `removeLabelIds` (array, optional): A list of IDs of labels to remove from this thread.
</Accordion>
<Accordion title="GMAIL_CREATE_DRAFT">
**Description:** Create a draft in Gmail.
<Accordion title="gmail/trash_thread">
**Description:** Move a thread to the trash.
**Parameters:**
- `toRecipients` (array, optional): To - Specify the recipients as either a single string or a JSON array.
```json
[
"recipient1@domain.com",
"recipient2@domain.com"
]
```
- `from` (string, optional): From - Specify the email of the sender.
- `subject` (string, optional): Subject - Specify the subject of the message.
- `messageContent` (string, optional): Message Content - Specify the content of the email message as plain text or HTML.
- `attachments` (string, optional): Attachments - Accepts either a single file object or a JSON array of file objects.
- `additionalHeaders` (object, optional): Additional Headers - Specify any additional header fields here.
```json
{
"reply-to": "Sender Name <sender@domain.com>"
}
```
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `id` (string, required): The ID of the thread to trash.
</Accordion>
<Accordion title="gmail/untrash_thread">
**Description:** Remove a thread from the trash.
**Parameters:**
- `userId` (string, required): The user's email address or 'me' for the authenticated user. (default: "me")
- `id` (string, required): The ID of the thread to untrash.
</Accordion>
</AccordionGroup>
@@ -177,19 +158,13 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Gmail tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Gmail capabilities
gmail_agent = Agent(
role="Email Manager",
goal="Manage email communications and contacts efficiently",
goal="Manage email communications and messages efficiently",
backstory="An AI assistant specialized in email management and communication.",
tools=[enterprise_tools]
apps=['gmail'] # All Gmail actions will be available
)
# Task to send a follow-up email
@@ -211,19 +186,18 @@ crew.kickoff()
### Filtering Specific Gmail Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Gmail tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["gmail_send_email", "gmail_search_for_email", "gmail_create_draft"]
)
from crewai import Agent, Task, Crew
# Create agent with specific Gmail actions only
email_coordinator = Agent(
role="Email Coordinator",
goal="Coordinate email communications and manage drafts",
backstory="An AI assistant that focuses on email coordination and draft management.",
tools=enterprise_tools
apps=[
'gmail/send_email',
'gmail/fetch_emails',
'gmail/create_draft'
]
)
# Task to prepare and send emails
@@ -241,57 +215,17 @@ crew = Crew(
crew.kickoff()
```
### Contact Management
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
contact_manager = Agent(
role="Contact Manager",
goal="Manage and organize email contacts efficiently",
backstory="An experienced contact manager who maintains organized contact databases.",
tools=[enterprise_tools]
)
# Task to manage contacts
contact_task = Task(
description="""
1. Search for contacts from the 'example.com' domain
2. Create new contacts for recent email senders not in the contact list
3. Update contact information with recent interaction data
""",
agent=contact_manager,
expected_output="Contact database updated with new contacts and recent interactions"
)
crew = Crew(
agents=[contact_manager],
tasks=[contact_task]
)
crew.kickoff()
```
### Email Search and Analysis
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create agent with Gmail search and analysis capabilities
email_analyst = Agent(
role="Email Analyst",
goal="Analyze email patterns and provide insights",
backstory="An AI assistant that analyzes email data to provide actionable insights.",
tools=[enterprise_tools]
apps=['gmail/fetch_emails', 'gmail/get_message'] # Specific actions for email analysis
)
# Task to analyze email patterns
@@ -313,38 +247,37 @@ crew = Crew(
crew.kickoff()
```
### Automated Email Workflows
### Thread Management
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
# Create agent with Gmail thread management capabilities
thread_manager = Agent(
role="Thread Manager",
goal="Organize and manage email threads efficiently",
backstory="An AI assistant that specializes in email thread organization and management.",
apps=[
'gmail/fetch_thread',
'gmail/modify_thread',
'gmail/trash_thread'
]
)
workflow_manager = Agent(
role="Email Workflow Manager",
goal="Automate email workflows and responses",
backstory="An AI assistant that manages automated email workflows and responses.",
tools=[enterprise_tools]
)
# Complex task involving multiple Gmail operations
workflow_task = Task(
# Task to organize email threads
thread_task = Task(
description="""
1. Search for emails with 'urgent' in the subject from the last 24 hours
2. Create draft responses for each urgent email
3. Send automated acknowledgment emails to senders
4. Create a summary report of urgent items requiring attention
1. Fetch all threads from the last month
2. Apply appropriate labels to organize threads by project
3. Archive or trash threads that are no longer relevant
""",
agent=workflow_manager,
expected_output="Urgent emails processed with automated responses and summary report"
agent=thread_manager,
expected_output="Email threads organized with appropriate labels and cleanup completed"
)
crew = Crew(
agents=[workflow_manager],
tasks=[workflow_task]
agents=[thread_manager],
tasks=[thread_task]
)
crew.kickoff()

View File

@@ -13,7 +13,7 @@ Enable your agents to manage calendar events, schedules, and availability throug
Before using the Google Calendar integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Google account with Google Calendar access
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Google Calendar integration, ensure you have:
### 1. Connect Your Google Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Google Calendar** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for calendar and contact access
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
4. Grant the necessary permissions for calendar access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,144 +33,140 @@ Before using the Google Calendar integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="GOOGLE_CALENDAR_CREATE_EVENT">
**Description:** Create an event in Google Calendar.
<Accordion title="google_calendar/get_availability">
**Description:** Get calendar availability (free/busy information).
**Parameters:**
- `eventName` (string, required): Event name.
- `startTime` (string, required): Start time - Accepts Unix timestamp or ISO8601 date formats.
- `endTime` (string, optional): End time - Defaults to one hour after the start time if left blank.
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
- `attendees` (string, optional): Attendees - Accepts an array of email addresses or email addresses separated by commas.
- `eventLocation` (string, optional): Event location.
- `eventDescription` (string, optional): Event description.
- `eventId` (string, optional): Event ID - An ID from your application to associate this event with. You can use this ID to sync updates to this event later.
- `includeMeetLink` (boolean, optional): Include Google Meet link? - Automatically creates Google Meet conference link for this event.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_UPDATE_EVENT">
**Description:** Update an existing event in Google Calendar.
**Parameters:**
- `eventId` (string, required): Event ID - The ID of the event to update.
- `eventName` (string, optional): Event name.
- `startTime` (string, optional): Start time - Accepts Unix timestamp or ISO8601 date formats.
- `endTime` (string, optional): End time - Defaults to one hour after the start time if left blank.
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
- `attendees` (string, optional): Attendees - Accepts an array of email addresses or email addresses separated by commas.
- `eventLocation` (string, optional): Event location.
- `eventDescription` (string, optional): Event description.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_LIST_EVENTS">
**Description:** List events from Google Calendar.
**Parameters:**
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
- `after` (string, optional): After - Filters events that start after the provided date (Unix in milliseconds or ISO timestamp). (example: "2025-04-12T10:00:00Z or 1712908800000").
- `before` (string, optional): Before - Filters events that end before the provided date (Unix in milliseconds or ISO timestamp). (example: "2025-04-12T10:00:00Z or 1712908800000").
</Accordion>
<Accordion title="GOOGLE_CALENDAR_GET_EVENT_BY_ID">
**Description:** Get a specific event by ID from Google Calendar.
**Parameters:**
- `eventId` (string, required): Event ID.
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_DELETE_EVENT">
**Description:** Delete an event from Google Calendar.
**Parameters:**
- `eventId` (string, required): Event ID - The ID of the calendar event to be deleted.
- `calendar` (string, optional): Calendar - Use Connect Portal Workflow Settings to allow users to select which calendar the event will be added to. Defaults to the user's primary calendar if left blank.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_GET_CONTACTS">
**Description:** Get contacts from Google Calendar.
**Parameters:**
- `paginationParameters` (object, optional): Pagination Parameters.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_SEARCH_CONTACTS">
**Description:** Search for contacts in Google Calendar.
**Parameters:**
- `query` (string, optional): Search query to search contacts.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_LIST_DIRECTORY_PEOPLE">
**Description:** List directory people.
**Parameters:**
- `paginationParameters` (object, optional): Pagination Parameters.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_SEARCH_DIRECTORY_PEOPLE">
**Description:** Search directory people.
**Parameters:**
- `query` (string, required): Search query to search contacts.
- `paginationParameters` (object, optional): Pagination Parameters.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_LIST_OTHER_CONTACTS">
**Description:** List other contacts.
**Parameters:**
- `paginationParameters` (object, optional): Pagination Parameters.
```json
{
"pageCursor": "page_cursor_string"
}
```
</Accordion>
<Accordion title="GOOGLE_CALENDAR_SEARCH_OTHER_CONTACTS">
**Description:** Search other contacts.
**Parameters:**
- `query` (string, optional): Search query to search contacts.
</Accordion>
<Accordion title="GOOGLE_CALENDAR_GET_AVAILABILITY">
**Description:** Get availability information for calendars.
**Parameters:**
- `timeMin` (string, required): The start of the interval. In ISO format.
- `timeMax` (string, required): The end of the interval. In ISO format.
- `timeZone` (string, optional): Time zone used in the response. Optional. The default is UTC.
- `items` (array, optional): List of calendars and/or groups to query. Defaults to the user default calendar.
- `timeMin` (string, required): Start time (RFC3339 format)
- `timeMax` (string, required): End time (RFC3339 format)
- `items` (array, required): Calendar IDs to check
```json
[
{
"id": "calendar_id_1"
},
{
"id": "calendar_id_2"
"id": "calendar_id"
}
]
```
- `timeZone` (string, optional): Time zone used in the response. The default is UTC.
- `groupExpansionMax` (integer, optional): Maximal number of calendar identifiers to be provided for a single group. Maximum: 100
- `calendarExpansionMax` (integer, optional): Maximal number of calendars for which FreeBusy information is to be provided. Maximum: 50
</Accordion>
<Accordion title="google_calendar/create_event">
**Description:** Create a new event in the specified calendar.
**Parameters:**
- `calendarId` (string, required): Calendar ID (use 'primary' for main calendar)
- `summary` (string, required): Event title/summary
- `start_dateTime` (string, required): Start time in RFC3339 format (e.g., 2024-01-20T10:00:00-07:00)
- `end_dateTime` (string, required): End time in RFC3339 format
- `description` (string, optional): Event description
- `timeZone` (string, optional): Time zone (e.g., America/Los_Angeles)
- `location` (string, optional): Geographic location of the event as free-form text.
- `attendees` (array, optional): List of attendees for the event.
```json
[
{
"email": "attendee@example.com",
"displayName": "Attendee Name",
"optional": false
}
]
```
- `reminders` (object, optional): Information about the event's reminders.
```json
{
"useDefault": true,
"overrides": [
{
"method": "email",
"minutes": 15
}
]
}
```
- `conferenceData` (object, optional): The conference-related information, such as details of a Google Meet conference.
```json
{
"createRequest": {
"requestId": "unique-request-id",
"conferenceSolutionKey": {
"type": "hangoutsMeet"
}
}
}
```
- `visibility` (string, optional): Visibility of the event. Options: default, public, private, confidential. Default: default
- `transparency` (string, optional): Whether the event blocks time on the calendar. Options: opaque, transparent. Default: opaque
</Accordion>
<Accordion title="google_calendar/view_events">
**Description:** Retrieve events for the specified calendar.
**Parameters:**
- `calendarId` (string, required): Calendar ID (use 'primary' for main calendar)
- `timeMin` (string, optional): Lower bound for events (RFC3339)
- `timeMax` (string, optional): Upper bound for events (RFC3339)
- `maxResults` (integer, optional): Maximum number of events (default 10). Minimum: 1, Maximum: 2500
- `orderBy` (string, optional): The order of the events returned in the result. Options: startTime, updated. Default: startTime
- `singleEvents` (boolean, optional): Whether to expand recurring events into instances and only return single one-off events and instances of recurring events. Default: true
- `showDeleted` (boolean, optional): Whether to include deleted events (with status equals cancelled) in the result. Default: false
- `showHiddenInvitations` (boolean, optional): Whether to include hidden invitations in the result. Default: false
- `q` (string, optional): Free text search terms to find events that match these terms in any field.
- `pageToken` (string, optional): Token specifying which result page to return.
- `timeZone` (string, optional): Time zone used in the response.
- `updatedMin` (string, optional): Lower bound for an event's last modification time (RFC3339) to filter by.
- `iCalUID` (string, optional): Specifies an event ID in the iCalendar format to be provided in the response.
</Accordion>
<Accordion title="google_calendar/update_event">
**Description:** Update an existing event.
**Parameters:**
- `calendarId` (string, required): Calendar ID
- `eventId` (string, required): Event ID to update
- `summary` (string, optional): Updated event title
- `description` (string, optional): Updated event description
- `start_dateTime` (string, optional): Updated start time
- `end_dateTime` (string, optional): Updated end time
</Accordion>
<Accordion title="google_calendar/delete_event">
**Description:** Delete a specified event.
**Parameters:**
- `calendarId` (string, required): Calendar ID
- `eventId` (string, required): Event ID to delete
</Accordion>
<Accordion title="google_calendar/view_calendar_list">
**Description:** Retrieve user's calendar list.
**Parameters:**
- `maxResults` (integer, optional): Maximum number of entries returned on one result page. Minimum: 1
- `pageToken` (string, optional): Token specifying which result page to return.
- `showDeleted` (boolean, optional): Whether to include deleted calendar list entries in the result. Default: false
- `showHidden` (boolean, optional): Whether to show hidden entries. Default: false
- `minAccessRole` (string, optional): The minimum access role for the user in the returned entries. Options: freeBusyReader, owner, reader, writer
</Accordion>
</AccordionGroup>
@@ -180,19 +176,13 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Google Calendar tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Google Calendar capabilities
calendar_agent = Agent(
role="Schedule Manager",
goal="Manage calendar events and scheduling efficiently",
backstory="An AI assistant specialized in calendar management and scheduling coordination.",
tools=[enterprise_tools]
apps=['google_calendar'] # All Google Calendar actions will be available
)
# Task to create a meeting
@@ -214,19 +204,11 @@ crew.kickoff()
### Filtering Specific Calendar Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Google Calendar tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["google_calendar_create_event", "google_calendar_list_events", "google_calendar_get_availability"]
)
meeting_coordinator = Agent(
role="Meeting Coordinator",
goal="Coordinate meetings and check availability",
backstory="An AI assistant that focuses on meeting scheduling and availability management.",
tools=enterprise_tools
apps=['google_calendar/create_event', 'google_calendar/get_availability']
)
# Task to schedule a meeting with availability check
@@ -248,17 +230,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
event_manager = Agent(
role="Event Manager",
goal="Manage and update calendar events efficiently",
backstory="An experienced event manager who handles event logistics and updates.",
tools=[enterprise_tools]
apps=['google_calendar']
)
# Task to manage event updates
@@ -266,10 +243,10 @@ event_management = Task(
description="""
1. List all events for this week
2. Update any events that need location changes to include video conference links
3. Send calendar invitations to new team members for recurring meetings
3. Check availability for upcoming meetings
""",
agent=event_manager,
expected_output="Weekly events updated with proper locations and new attendees added"
expected_output="Weekly events updated with proper locations and availability checked"
)
crew = Crew(
@@ -280,33 +257,28 @@ crew = Crew(
crew.kickoff()
```
### Contact and Availability Management
### Availability and Calendar Management
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
availability_coordinator = Agent(
role="Availability Coordinator",
goal="Coordinate availability and manage contacts for scheduling",
backstory="An AI assistant that specializes in availability management and contact coordination.",
tools=[enterprise_tools]
goal="Coordinate availability and manage calendars for scheduling",
backstory="An AI assistant that specializes in availability management and calendar coordination.",
apps=['google_calendar']
)
# Task to coordinate availability
availability_task = Task(
description="""
1. Search for contacts in the engineering department
2. Check availability for all engineers next Friday afternoon
1. Get the list of available calendars
2. Check availability for all calendars next Friday afternoon
3. Create a team meeting for the first available 2-hour slot
4. Include Google Meet link and send invitations
""",
agent=availability_coordinator,
expected_output="Team meeting scheduled based on availability with all engineers invited"
expected_output="Team meeting scheduled based on availability with all team members invited"
)
crew = Crew(
@@ -321,17 +293,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
scheduling_automator = Agent(
role="Scheduling Automator",
goal="Automate scheduling workflows and calendar management",
backstory="An AI assistant that automates complex scheduling scenarios and calendar workflows.",
tools=[enterprise_tools]
apps=['google_calendar']
)
# Complex scheduling automation task
@@ -365,21 +332,16 @@ crew.kickoff()
- Check if calendar sharing settings allow the required access level
**Event Creation Issues**
- Verify that time formats are correct (ISO8601 or Unix timestamps)
- Verify that time formats are correct (RFC3339 format)
- Ensure attendee email addresses are properly formatted
- Check that the target calendar exists and is accessible
- Verify time zones are correctly specified
**Availability and Time Conflicts**
- Use proper ISO format for time ranges when checking availability
- Use proper RFC3339 format for time ranges when checking availability
- Ensure time zones are consistent across all operations
- Verify that calendar IDs are correct when checking multiple calendars
**Contact and People Search**
- Ensure search queries are properly formatted
- Check that directory access permissions are granted
- Verify that contact information is up to date and accessible
**Event Updates and Deletions**
- Verify that event IDs are correct and events exist
- Ensure you have edit permissions for the events

View File

@@ -0,0 +1,418 @@
---
title: Google Contacts Integration
description: "Contact and directory management with Google Contacts integration for CrewAI."
icon: "address-book"
mode: "wide"
---
## Overview
Enable your agents to manage contacts and directory information through Google Contacts. Access personal contacts, search directory people, create and update contact information, and manage contact groups with AI-powered automation.
## Prerequisites
Before using the Google Contacts integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Google account with Google Contacts access
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Google Contacts Integration
### 1. Connect Your Google Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Google Contacts** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for contacts and directory access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="google_contacts/get_contacts">
**Description:** Retrieve user's contacts from Google Contacts.
**Parameters:**
- `pageSize` (integer, optional): Number of contacts to return (max 1000). Minimum: 1, Maximum: 1000
- `pageToken` (string, optional): The token of the page to retrieve.
- `personFields` (string, optional): Fields to include (e.g., 'names,emailAddresses,phoneNumbers'). Default: names,emailAddresses,phoneNumbers
- `requestSyncToken` (boolean, optional): Whether the response should include a sync token. Default: false
- `sortOrder` (string, optional): The order in which the connections should be sorted. Options: LAST_MODIFIED_ASCENDING, LAST_MODIFIED_DESCENDING, FIRST_NAME_ASCENDING, LAST_NAME_ASCENDING
</Accordion>
<Accordion title="google_contacts/search_contacts">
**Description:** Search for contacts using a query string.
**Parameters:**
- `query` (string, required): Search query string
- `readMask` (string, required): Fields to read (e.g., 'names,emailAddresses,phoneNumbers')
- `pageSize` (integer, optional): Number of results to return. Minimum: 1, Maximum: 30
- `pageToken` (string, optional): Token specifying which result page to return.
- `sources` (array, optional): The sources to search in. Options: READ_SOURCE_TYPE_CONTACT, READ_SOURCE_TYPE_PROFILE. Default: READ_SOURCE_TYPE_CONTACT
</Accordion>
<Accordion title="google_contacts/list_directory_people">
**Description:** List people in the authenticated user's directory.
**Parameters:**
- `sources` (array, required): Directory sources to search within. Options: DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE, DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT. Default: DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE
- `pageSize` (integer, optional): Number of people to return. Minimum: 1, Maximum: 1000
- `pageToken` (string, optional): Token specifying which result page to return.
- `readMask` (string, optional): Fields to read (e.g., 'names,emailAddresses')
- `requestSyncToken` (boolean, optional): Whether the response should include a sync token. Default: false
- `mergeSources` (array, optional): Additional data to merge into the directory people responses. Options: CONTACT
</Accordion>
<Accordion title="google_contacts/search_directory_people">
**Description:** Search for people in the directory.
**Parameters:**
- `query` (string, required): Search query
- `sources` (string, required): Directory sources (use 'DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE')
- `pageSize` (integer, optional): Number of results to return
- `readMask` (string, optional): Fields to read
</Accordion>
<Accordion title="google_contacts/list_other_contacts">
**Description:** List other contacts (not in user's personal contacts).
**Parameters:**
- `pageSize` (integer, optional): Number of contacts to return. Minimum: 1, Maximum: 1000
- `pageToken` (string, optional): Token specifying which result page to return.
- `readMask` (string, optional): Fields to read
- `requestSyncToken` (boolean, optional): Whether the response should include a sync token. Default: false
</Accordion>
<Accordion title="google_contacts/search_other_contacts">
**Description:** Search other contacts.
**Parameters:**
- `query` (string, required): Search query
- `readMask` (string, required): Fields to read (e.g., 'names,emailAddresses')
- `pageSize` (integer, optional): Number of results
</Accordion>
<Accordion title="google_contacts/get_person">
**Description:** Get a single person's contact information by resource name.
**Parameters:**
- `resourceName` (string, required): The resource name of the person to get (e.g., 'people/c123456789')
- `personFields` (string, optional): Fields to include (e.g., 'names,emailAddresses,phoneNumbers'). Default: names,emailAddresses,phoneNumbers
</Accordion>
<Accordion title="google_contacts/create_contact">
**Description:** Create a new contact in the user's address book.
**Parameters:**
- `names` (array, optional): Person's names
```json
[
{
"givenName": "John",
"familyName": "Doe",
"displayName": "John Doe"
}
]
```
- `emailAddresses` (array, optional): Email addresses
```json
[
{
"value": "john.doe@example.com",
"type": "work"
}
]
```
- `phoneNumbers` (array, optional): Phone numbers
```json
[
{
"value": "+1234567890",
"type": "mobile"
}
]
```
- `addresses` (array, optional): Postal addresses
```json
[
{
"formattedValue": "123 Main St, City, State 12345",
"type": "home"
}
]
```
- `organizations` (array, optional): Organizations/companies
```json
[
{
"name": "Company Name",
"title": "Job Title",
"type": "work"
}
]
```
</Accordion>
<Accordion title="google_contacts/update_contact">
**Description:** Update an existing contact's information.
**Parameters:**
- `resourceName` (string, required): The resource name of the person to update (e.g., 'people/c123456789')
- `updatePersonFields` (string, required): Fields to update (e.g., 'names,emailAddresses,phoneNumbers')
- `names` (array, optional): Person's names
- `emailAddresses` (array, optional): Email addresses
- `phoneNumbers` (array, optional): Phone numbers
</Accordion>
<Accordion title="google_contacts/delete_contact">
**Description:** Delete a contact from the user's address book.
**Parameters:**
- `resourceName` (string, required): The resource name of the person to delete (e.g., 'people/c123456789')
</Accordion>
<Accordion title="google_contacts/batch_get_people">
**Description:** Get information about multiple people in a single request.
**Parameters:**
- `resourceNames` (array, required): Resource names of people to get. Maximum: 200 items
- `personFields` (string, optional): Fields to include (e.g., 'names,emailAddresses,phoneNumbers'). Default: names,emailAddresses,phoneNumbers
</Accordion>
<Accordion title="google_contacts/list_contact_groups">
**Description:** List the user's contact groups (labels).
**Parameters:**
- `pageSize` (integer, optional): Number of contact groups to return. Minimum: 1, Maximum: 1000
- `pageToken` (string, optional): Token specifying which result page to return.
- `groupFields` (string, optional): Fields to include (e.g., 'name,memberCount,clientData'). Default: name,memberCount
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Google Contacts Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Google Contacts capabilities
contacts_agent = Agent(
role="Contact Manager",
goal="Manage contacts and directory information efficiently",
backstory="An AI assistant specialized in contact management and directory operations.",
apps=['google_contacts'] # All Google Contacts actions will be available
)
# Task to retrieve and organize contacts
contact_management_task = Task(
description="Retrieve all contacts and organize them by company affiliation",
agent=contacts_agent,
expected_output="Contacts retrieved and organized by company with summary report"
)
# Run the task
crew = Crew(
agents=[contacts_agent],
tasks=[contact_management_task]
)
crew.kickoff()
```
### Directory Search and Management
```python
from crewai import Agent, Task, Crew
directory_manager = Agent(
role="Directory Manager",
goal="Search and manage directory people and contacts",
backstory="An AI assistant that specializes in directory management and people search.",
apps=[
'google_contacts/search_directory_people',
'google_contacts/list_directory_people',
'google_contacts/search_contacts'
]
)
# Task to search and manage directory
directory_task = Task(
description="Search for team members in the company directory and create a team contact list",
agent=directory_manager,
expected_output="Team directory compiled with contact information"
)
crew = Crew(
agents=[directory_manager],
tasks=[directory_task]
)
crew.kickoff()
```
### Contact Creation and Updates
```python
from crewai import Agent, Task, Crew
contact_curator = Agent(
role="Contact Curator",
goal="Create and update contact information systematically",
backstory="An AI assistant that maintains accurate and up-to-date contact information.",
apps=['google_contacts']
)
# Task to create and update contacts
curation_task = Task(
description="""
1. Search for existing contacts related to new business partners
2. Create new contacts for partners not in the system
3. Update existing contact information with latest details
4. Organize contacts into appropriate groups
""",
agent=contact_curator,
expected_output="Contact database updated with new partners and organized groups"
)
crew = Crew(
agents=[contact_curator],
tasks=[curation_task]
)
crew.kickoff()
```
### Contact Group Management
```python
from crewai import Agent, Task, Crew
group_organizer = Agent(
role="Contact Group Organizer",
goal="Organize contacts into meaningful groups and categories",
backstory="An AI assistant that specializes in contact organization and group management.",
apps=['google_contacts']
)
# Task to organize contact groups
organization_task = Task(
description="""
1. List all existing contact groups
2. Analyze contact distribution across groups
3. Create new groups for better organization
4. Move contacts to appropriate groups based on their information
""",
agent=group_organizer,
expected_output="Contacts organized into logical groups with improved structure"
)
crew = Crew(
agents=[group_organizer],
tasks=[organization_task]
)
crew.kickoff()
```
### Comprehensive Contact Management
```python
from crewai import Agent, Task, Crew
contact_specialist = Agent(
role="Contact Management Specialist",
goal="Provide comprehensive contact management across all sources",
backstory="An AI assistant that handles all aspects of contact management including personal, directory, and other contacts.",
apps=['google_contacts']
)
# Complex contact management task
comprehensive_task = Task(
description="""
1. Retrieve contacts from all sources (personal, directory, other)
2. Search for duplicate contacts and merge information
3. Update outdated contact information
4. Create missing contacts for important stakeholders
5. Organize contacts into meaningful groups
6. Generate a comprehensive contact report
""",
agent=contact_specialist,
expected_output="Complete contact management performed with unified contact database and detailed report"
)
crew = Crew(
agents=[contact_specialist],
tasks=[comprehensive_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Permission Errors**
- Ensure your Google account has appropriate permissions for contacts access
- Verify that the OAuth connection includes required scopes for Google Contacts API
- Check that directory access permissions are granted for organization contacts
**Resource Name Format Issues**
- Ensure resource names follow the correct format (e.g., 'people/c123456789' for contacts)
- Verify that contact group resource names use the format 'contactGroups/groupId'
- Check that resource names exist and are accessible
**Search and Query Issues**
- Ensure search queries are properly formatted and not empty
- Use appropriate readMask fields for the data you need
- Verify that search sources are correctly specified (contacts vs profiles)
**Contact Creation and Updates**
- Ensure required fields are provided when creating contacts
- Verify that email addresses and phone numbers are properly formatted
- Check that updatePersonFields parameter includes all fields being updated
**Directory Access Issues**
- Ensure you have appropriate permissions to access organization directory
- Verify that directory sources are correctly specified
- Check that your organization allows API access to directory information
**Pagination and Limits**
- Be mindful of page size limits (varies by endpoint)
- Use pageToken for pagination through large result sets
- Respect API rate limits and implement appropriate delays
**Contact Groups and Organization**
- Ensure contact group names are unique when creating new groups
- Verify that contacts exist before adding them to groups
- Check that you have permissions to modify contact groups
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Google Contacts integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,244 @@
---
title: Google Docs Integration
description: "Document creation and editing with Google Docs integration for CrewAI."
icon: "file-lines"
mode: "wide"
---
## Overview
Enable your agents to create, edit, and manage Google Docs documents with text manipulation and formatting. Automate document creation, insert and replace text, manage content ranges, and streamline your document workflows with AI-powered automation.
## Prerequisites
Before using the Google Docs integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Google account with Google Docs access
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Google Docs Integration
### 1. Connect Your Google Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Google Docs** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for document access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="google_docs/create_document">
**Description:** Create a new Google Document.
**Parameters:**
- `title` (string, optional): The title for the new document.
</Accordion>
<Accordion title="google_docs/get_document">
**Description:** Get the contents and metadata of a Google Document.
**Parameters:**
- `documentId` (string, required): The ID of the document to retrieve.
- `includeTabsContent` (boolean, optional): Whether to include tab content. Default is `false`.
- `suggestionsViewMode` (string, optional): The suggestions view mode to apply to the document. Enum: `DEFAULT_FOR_CURRENT_ACCESS`, `PREVIEW_SUGGESTIONS_ACCEPTED`, `PREVIEW_WITHOUT_SUGGESTIONS`. Default is `DEFAULT_FOR_CURRENT_ACCESS`.
</Accordion>
<Accordion title="google_docs/batch_update">
**Description:** Apply one or more updates to a Google Document.
**Parameters:**
- `documentId` (string, required): The ID of the document to update.
- `requests` (array, required): A list of updates to apply to the document. Each item is an object representing a request.
- `writeControl` (object, optional): Provides control over how write requests are executed. Contains `requiredRevisionId` (string) and `targetRevisionId` (string).
</Accordion>
<Accordion title="google_docs/insert_text">
**Description:** Insert text into a Google Document at a specific location.
**Parameters:**
- `documentId` (string, required): The ID of the document to update.
- `text` (string, required): The text to insert.
- `index` (integer, optional): The zero-based index where to insert the text. Default is `1`.
</Accordion>
<Accordion title="google_docs/replace_text">
**Description:** Replace all instances of text in a Google Document.
**Parameters:**
- `documentId` (string, required): The ID of the document to update.
- `containsText` (string, required): The text to find and replace.
- `replaceText` (string, required): The text to replace it with.
- `matchCase` (boolean, optional): Whether the search should respect case. Default is `false`.
</Accordion>
<Accordion title="google_docs/delete_content_range">
**Description:** Delete content from a specific range in a Google Document.
**Parameters:**
- `documentId` (string, required): The ID of the document to update.
- `startIndex` (integer, required): The start index of the range to delete.
- `endIndex` (integer, required): The end index of the range to delete.
</Accordion>
<Accordion title="google_docs/insert_page_break">
**Description:** Insert a page break at a specific location in a Google Document.
**Parameters:**
- `documentId` (string, required): The ID of the document to update.
- `index` (integer, optional): The zero-based index where to insert the page break. Default is `1`.
</Accordion>
<Accordion title="google_docs/create_named_range">
**Description:** Create a named range in a Google Document.
**Parameters:**
- `documentId` (string, required): The ID of the document to update.
- `name` (string, required): The name for the named range.
- `startIndex` (integer, required): The start index of the range.
- `endIndex` (integer, required): The end index of the range.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Google Docs Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Google Docs capabilities
docs_agent = Agent(
role="Document Creator",
goal="Create and manage Google Docs documents efficiently",
backstory="An AI assistant specialized in Google Docs document creation and editing.",
apps=['google_docs'] # All Google Docs actions will be available
)
# Task to create a new document
create_doc_task = Task(
description="Create a new Google Document titled 'Project Status Report'",
agent=docs_agent,
expected_output="New Google Document 'Project Status Report' created successfully"
)
# Run the task
crew = Crew(
agents=[docs_agent],
tasks=[create_doc_task]
)
crew.kickoff()
```
### Text Editing and Content Management
```python
from crewai import Agent, Task, Crew
# Create an agent focused on text editing
text_editor = Agent(
role="Document Editor",
goal="Edit and update content in Google Docs documents",
backstory="An AI assistant skilled in precise text editing and content management.",
apps=['google_docs/insert_text', 'google_docs/replace_text', 'google_docs/delete_content_range']
)
# Task to edit document content
edit_content_task = Task(
description="In document 'your_document_id', insert the text 'Executive Summary: ' at the beginning, then replace all instances of 'TODO' with 'COMPLETED'.",
agent=text_editor,
expected_output="Document updated with new text inserted and TODO items replaced."
)
crew = Crew(
agents=[text_editor],
tasks=[edit_content_task]
)
crew.kickoff()
```
### Advanced Document Operations
```python
from crewai import Agent, Task, Crew
# Create an agent for advanced document operations
document_formatter = Agent(
role="Document Formatter",
goal="Apply advanced formatting and structure to Google Docs",
backstory="An AI assistant that handles complex document formatting and organization.",
apps=['google_docs/batch_update', 'google_docs/insert_page_break', 'google_docs/create_named_range']
)
# Task to format document
format_doc_task = Task(
description="In document 'your_document_id', insert a page break at position 100, create a named range called 'Introduction' for characters 1-50, and apply batch formatting updates.",
agent=document_formatter,
expected_output="Document formatted with page break, named range, and styling applied."
)
crew = Crew(
agents=[document_formatter],
tasks=[format_doc_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Authentication Errors**
- Ensure your Google account has the necessary permissions for Google Docs access.
- Verify that the OAuth connection includes all required scopes (`https://www.googleapis.com/auth/documents`).
**Document ID Issues**
- Double-check document IDs for correctness.
- Ensure the document exists and is accessible to your account.
- Document IDs can be found in the Google Docs URL.
**Text Insertion and Range Operations**
- When using `insert_text` or `delete_content_range`, ensure index positions are valid.
- Remember that Google Docs uses zero-based indexing.
- The document must have content at the specified index positions.
**Batch Update Request Formatting**
- When using `batch_update`, ensure the `requests` array is correctly formatted according to the Google Docs API documentation.
- Complex updates require specific JSON structures for each request type.
**Replace Text Operations**
- For `replace_text`, ensure the `containsText` parameter exactly matches the text you want to replace.
- Use `matchCase` parameter to control case sensitivity.
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Google Docs integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,229 @@
---
title: Google Drive Integration
description: "File storage and management with Google Drive integration for CrewAI."
icon: "google"
mode: "wide"
---
## Overview
Enable your agents to manage files and folders through Google Drive. Upload, download, organize, and share files, create folders, and streamline your document management workflows with AI-powered automation.
## Prerequisites
Before using the Google Drive integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Google account with Google Drive access
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Google Drive Integration
### 1. Connect Your Google Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Google Drive** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for file and folder management
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="google_drive/get_file">
**Description:** Get a file by ID from Google Drive.
**Parameters:**
- `file_id` (string, required): The ID of the file to retrieve.
</Accordion>
<Accordion title="google_drive/list_files">
**Description:** List files in Google Drive.
**Parameters:**
- `q` (string, optional): Query string to filter files (example: "name contains 'report'").
- `page_size` (integer, optional): Maximum number of files to return (default: 100, max: 1000).
- `page_token` (string, optional): Token for retrieving the next page of results.
- `order_by` (string, optional): Sort order (example: "name", "createdTime desc", "modifiedTime").
- `spaces` (string, optional): Comma-separated list of spaces to query (drive, appDataFolder, photos).
</Accordion>
<Accordion title="google_drive/upload_file">
**Description:** Upload a file to Google Drive.
**Parameters:**
- `name` (string, required): Name of the file to create.
- `content` (string, required): Content of the file to upload.
- `mime_type` (string, optional): MIME type of the file (example: "text/plain", "application/pdf").
- `parent_folder_id` (string, optional): ID of the parent folder where the file should be created.
- `description` (string, optional): Description of the file.
</Accordion>
<Accordion title="google_drive/download_file">
**Description:** Download a file from Google Drive.
**Parameters:**
- `file_id` (string, required): The ID of the file to download.
- `mime_type` (string, optional): MIME type for export (required for Google Workspace documents).
</Accordion>
<Accordion title="google_drive/create_folder">
**Description:** Create a new folder in Google Drive.
**Parameters:**
- `name` (string, required): Name of the folder to create.
- `parent_folder_id` (string, optional): ID of the parent folder where the new folder should be created.
- `description` (string, optional): Description of the folder.
</Accordion>
<Accordion title="google_drive/delete_file">
**Description:** Delete a file from Google Drive.
**Parameters:**
- `file_id` (string, required): The ID of the file to delete.
</Accordion>
<Accordion title="google_drive/share_file">
**Description:** Share a file in Google Drive with specific users or make it public.
**Parameters:**
- `file_id` (string, required): The ID of the file to share.
- `role` (string, required): The role granted by this permission (reader, writer, commenter, owner).
- `type` (string, required): The type of the grantee (user, group, domain, anyone).
- `email_address` (string, optional): The email address of the user or group to share with (required for user/group types).
- `domain` (string, optional): The domain to share with (required for domain type).
- `send_notification_email` (boolean, optional): Whether to send a notification email (default: true).
- `email_message` (string, optional): A plain text custom message to include in the notification email.
</Accordion>
<Accordion title="google_drive/update_file">
**Description:** Update an existing file in Google Drive.
**Parameters:**
- `file_id` (string, required): The ID of the file to update.
- `name` (string, optional): New name for the file.
- `content` (string, optional): New content for the file.
- `mime_type` (string, optional): New MIME type for the file.
- `description` (string, optional): New description for the file.
- `add_parents` (string, optional): Comma-separated list of parent folder IDs to add.
- `remove_parents` (string, optional): Comma-separated list of parent folder IDs to remove.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Google Drive Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Google Drive capabilities
drive_agent = Agent(
role="File Manager",
goal="Manage files and folders in Google Drive efficiently",
backstory="An AI assistant specialized in document and file management.",
apps=['google_drive'] # All Google Drive actions will be available
)
# Task to organize files
organize_files_task = Task(
description="List all files in the root directory and organize them into appropriate folders",
agent=drive_agent,
expected_output="Summary of files organized with folder structure"
)
# Run the task
crew = Crew(
agents=[drive_agent],
tasks=[organize_files_task]
)
crew.kickoff()
```
### Filtering Specific Google Drive Tools
```python
from crewai import Agent, Task, Crew
# Create agent with specific Google Drive actions only
file_manager_agent = Agent(
role="Document Manager",
goal="Upload and manage documents efficiently",
backstory="An AI assistant that focuses on document upload and organization.",
apps=[
'google_drive/upload_file',
'google_drive/create_folder',
'google_drive/share_file'
] # Specific Google Drive actions
)
# Task to upload and share documents
document_task = Task(
description="Upload the quarterly report and share it with the finance team",
agent=file_manager_agent,
expected_output="Document uploaded and sharing permissions configured"
)
crew = Crew(
agents=[file_manager_agent],
tasks=[document_task]
)
crew.kickoff()
```
### Advanced File Management
```python
from crewai import Agent, Task, Crew
file_organizer = Agent(
role="File Organizer",
goal="Maintain organized file structure and manage permissions",
backstory="An experienced file manager who ensures proper organization and access control.",
apps=['google_drive']
)
# Complex task involving multiple Google Drive operations
organization_task = Task(
description="""
1. List all files in the shared folder
2. Create folders for different document types (Reports, Presentations, Spreadsheets)
3. Move files to appropriate folders based on their type
4. Set appropriate sharing permissions for each folder
5. Create a summary document of the organization changes
""",
agent=file_organizer,
expected_output="Files organized into categorized folders with proper permissions and summary report"
)
crew = Crew(
agents=[file_organizer],
tasks=[organization_task]
)
crew.kickoff()
```

View File

@@ -13,7 +13,7 @@ Enable your agents to manage spreadsheet data through Google Sheets. Read rows,
Before using the Google Sheets integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Google account with Google Sheets access
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
- Spreadsheets with proper column headers for data operations
@@ -22,11 +22,11 @@ Before using the Google Sheets integration, ensure you have:
### 1. Connect Your Google Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Google Sheets** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for spreadsheet access
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -34,67 +34,93 @@ Before using the Google Sheets integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="GOOGLE_SHEETS_GET_ROW">
**Description:** Get rows from a Google Sheets spreadsheet.
<Accordion title="google_sheets/get_spreadsheet">
**Description:** Retrieve properties and data of a spreadsheet.
**Parameters:**
- `spreadsheetId` (string, required): Spreadsheet - Use Connect Portal Workflow Settings to allow users to select a spreadsheet. Defaults to using the first worksheet in the selected spreadsheet.
- `limit` (string, optional): Limit rows - Limit the maximum number of rows to return.
- `spreadsheetId` (string, required): The ID of the spreadsheet to retrieve.
- `ranges` (array, optional): The ranges to retrieve from the spreadsheet.
- `includeGridData` (boolean, optional): True if grid data should be returned. Default: false
- `fields` (string, optional): The fields to include in the response. Use this to improve performance by only returning needed data.
</Accordion>
<Accordion title="GOOGLE_SHEETS_CREATE_ROW">
**Description:** Create a new row in a Google Sheets spreadsheet.
<Accordion title="google_sheets/get_values">
**Description:** Returns a range of values from a spreadsheet.
**Parameters:**
- `spreadsheetId` (string, required): Spreadsheet - Use Connect Portal Workflow Settings to allow users to select a spreadsheet. Defaults to using the first worksheet in the selected spreadsheet..
- `worksheet` (string, required): Worksheet - Your worksheet must have column headers.
- `additionalFields` (object, required): Fields - Include fields to create this row with, as an object with keys of Column Names. Use Connect Portal Workflow Settings to allow users to select a Column Mapping.
- `spreadsheetId` (string, required): The ID of the spreadsheet to retrieve data from.
- `range` (string, required): The A1 notation or R1C1 notation of the range to retrieve values from.
- `valueRenderOption` (string, optional): How values should be represented in the output. Options: FORMATTED_VALUE, UNFORMATTED_VALUE, FORMULA. Default: FORMATTED_VALUE
- `dateTimeRenderOption` (string, optional): How dates, times, and durations should be represented in the output. Options: SERIAL_NUMBER, FORMATTED_STRING. Default: SERIAL_NUMBER
- `majorDimension` (string, optional): The major dimension that results should use. Options: ROWS, COLUMNS. Default: ROWS
</Accordion>
<Accordion title="google_sheets/update_values">
**Description:** Sets values in a range of a spreadsheet.
**Parameters:**
- `spreadsheetId` (string, required): The ID of the spreadsheet to update.
- `range` (string, required): The A1 notation of the range to update.
- `values` (array, required): The data to be written. Each array represents a row.
```json
{
"columnName1": "columnValue1",
"columnName2": "columnValue2",
"columnName3": "columnValue3",
"columnName4": "columnValue4"
}
[
["Value1", "Value2", "Value3"],
["Value4", "Value5", "Value6"]
]
```
- `valueInputOption` (string, optional): How the input data should be interpreted. Options: RAW, USER_ENTERED. Default: USER_ENTERED
</Accordion>
<Accordion title="GOOGLE_SHEETS_UPDATE_ROW">
**Description:** Update existing rows in a Google Sheets spreadsheet.
<Accordion title="google_sheets/append_values">
**Description:** Appends values to a spreadsheet.
**Parameters:**
- `spreadsheetId` (string, required): Spreadsheet - Use Connect Portal Workflow Settings to allow users to select a spreadsheet. Defaults to using the first worksheet in the selected spreadsheet.
- `worksheet` (string, required): Worksheet - Your worksheet must have column headers.
- `filterFormula` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions to identify which rows to update.
- `spreadsheetId` (string, required): The ID of the spreadsheet to update.
- `range` (string, required): The A1 notation of a range to search for a logical table of data.
- `values` (array, required): The data to append. Each array represents a row.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "status",
"operator": "$stringExactlyMatches",
"value": "pending"
}
]
[
["Value1", "Value2", "Value3"],
["Value4", "Value5", "Value6"]
]
```
- `valueInputOption` (string, optional): How the input data should be interpreted. Options: RAW, USER_ENTERED. Default: USER_ENTERED
- `insertDataOption` (string, optional): How the input data should be inserted. Options: OVERWRITE, INSERT_ROWS. Default: INSERT_ROWS
</Accordion>
<Accordion title="google_sheets/create_spreadsheet">
**Description:** Creates a new spreadsheet.
**Parameters:**
- `title` (string, required): The title of the new spreadsheet.
- `sheets` (array, optional): The sheets that are part of the spreadsheet.
```json
[
{
"properties": {
"title": "Sheet1"
}
]
}
```
Available operators: `$stringContains`, `$stringDoesNotContain`, `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringStartsWith`, `$stringDoesNotStartWith`, `$stringEndsWith`, `$stringDoesNotEndWith`, `$numberGreaterThan`, `$numberLessThan`, `$numberEquals`, `$numberDoesNotEqual`, `$dateTimeAfter`, `$dateTimeBefore`, `$dateTimeEquals`, `$booleanTrue`, `$booleanFalse`, `$exists`, `$doesNotExist`
- `additionalFields` (object, required): Fields - Include fields to update, as an object with keys of Column Names. Use Connect Portal Workflow Settings to allow users to select a Column Mapping.
```json
{
"columnName1": "newValue1",
"columnName2": "newValue2",
"columnName3": "newValue3",
"columnName4": "newValue4"
}
}
]
```
</Accordion>
</AccordionGroup>
@@ -105,19 +131,13 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Google Sheets tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Google Sheets capabilities
sheets_agent = Agent(
role="Data Manager",
goal="Manage spreadsheet data and track information efficiently",
backstory="An AI assistant specialized in data management and spreadsheet operations.",
tools=[enterprise_tools]
apps=['google_sheets']
)
# Task to add new data to a spreadsheet
@@ -139,19 +159,17 @@ crew.kickoff()
### Filtering Specific Google Sheets Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Google Sheets tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["google_sheets_get_row", "google_sheets_create_row"]
)
from crewai import Agent, Task, Crew
# Create agent with specific Google Sheets actions only
data_collector = Agent(
role="Data Collector",
goal="Collect and organize data in spreadsheets",
backstory="An AI assistant that focuses on data collection and organization.",
tools=enterprise_tools
apps=[
'google_sheets/get_values',
'google_sheets/update_values'
]
)
# Task to collect and organize data
@@ -173,17 +191,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
data_analyst = Agent(
role="Data Analyst",
goal="Analyze spreadsheet data and generate insights",
backstory="An experienced data analyst who extracts insights from spreadsheet data.",
tools=[enterprise_tools]
apps=['google_sheets']
)
# Task to analyze data and create reports
@@ -205,33 +218,59 @@ crew = Crew(
crew.kickoff()
```
### Spreadsheet Creation and Management
```python
from crewai import Agent, Task, Crew
spreadsheet_manager = Agent(
role="Spreadsheet Manager",
goal="Create and manage spreadsheets efficiently",
backstory="An AI assistant that specializes in creating and organizing spreadsheets.",
apps=['google_sheets']
)
# Task to create and set up new spreadsheets
setup_task = Task(
description="""
1. Create a new spreadsheet for quarterly reports
2. Set up proper headers and structure
3. Add initial data and formatting
""",
agent=spreadsheet_manager,
expected_output="New quarterly report spreadsheet created and properly structured"
)
crew = Crew(
agents=[spreadsheet_manager],
tasks=[setup_task]
)
crew.kickoff()
```
### Automated Data Updates
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
data_updater = Agent(
role="Data Updater",
goal="Automatically update and maintain spreadsheet data",
backstory="An AI assistant that maintains data accuracy and updates records automatically.",
tools=[enterprise_tools]
apps=['google_sheets']
)
# Task to update data based on conditions
update_task = Task(
description="""
1. Find all pending orders in the orders spreadsheet
2. Update their status to 'processing'
3. Add a timestamp for when the status was updated
4. Log the changes in a separate tracking sheet
1. Get spreadsheet properties and structure
2. Read current data from specific ranges
3. Update values in target ranges with new data
4. Append new records to the bottom of the sheet
""",
agent=data_updater,
expected_output="All pending orders updated to processing status with timestamps logged"
expected_output="Spreadsheet data updated successfully with new values and records"
)
crew = Crew(
@@ -246,30 +285,25 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
workflow_manager = Agent(
role="Data Workflow Manager",
goal="Manage complex data workflows across multiple spreadsheets",
backstory="An AI assistant that orchestrates complex data operations across multiple spreadsheets.",
tools=[enterprise_tools]
apps=['google_sheets']
)
# Complex workflow task
workflow_task = Task(
description="""
1. Get all customer data from the main customer spreadsheet
2. Create monthly summary entries for active customers
3. Update customer status based on activity in the last 30 days
4. Generate a monthly report with customer metrics
5. Archive inactive customer records to a separate sheet
2. Create a new monthly summary spreadsheet
3. Append summary data to the new spreadsheet
4. Update customer status based on activity metrics
5. Generate reports with proper formatting
""",
agent=workflow_manager,
expected_output="Monthly customer workflow completed with updated statuses and generated reports"
expected_output="Monthly customer workflow completed with new spreadsheet and updated data"
)
crew = Crew(
@@ -291,29 +325,28 @@ crew.kickoff()
**Spreadsheet Structure Issues**
- Ensure worksheets have proper column headers before creating or updating rows
- Verify that column names in `additionalFields` match the actual column headers
- Check that the specified worksheet exists in the spreadsheet
- Verify that range notation (A1 format) is correct for the target cells
- Check that the specified spreadsheet ID exists and is accessible
**Data Type and Format Issues**
- Ensure data values match the expected format for each column
- Use proper date formats for date columns (ISO format recommended)
- Verify that numeric values are properly formatted for number columns
**Filter Formula Issues**
- Ensure filter formulas follow the correct JSON structure for disjunctive normal form
- Use valid field names that match actual column headers
- Test simple filters before building complex multi-condition queries
- Verify that operator types match the data types in the columns
**Range and Cell Reference Issues**
- Use proper A1 notation for ranges (e.g., "A1:C10", "Sheet1!A1:B5")
- Ensure range references don't exceed the actual spreadsheet dimensions
- Verify that sheet names in range references match actual sheet names
**Row Limits and Performance**
- Be mindful of row limits when using `GOOGLE_SHEETS_GET_ROW`
- Consider pagination for large datasets
- Use specific filters to reduce the amount of data processed
**Value Input and Rendering Options**
- Choose appropriate `valueInputOption` (RAW vs USER_ENTERED) for your data
- Select proper `valueRenderOption` based on how you want data formatted
- Consider `dateTimeRenderOption` for consistent date/time handling
**Update Operations**
- Ensure filter conditions properly identify the intended rows for updates
- Test filter conditions with small datasets before large updates
- Verify that all required fields are included in update operations
**Spreadsheet Creation Issues**
- Ensure spreadsheet titles are unique and follow naming conventions
- Verify that sheet properties are properly structured when creating sheets
- Check that you have permissions to create new spreadsheets in your account
### Getting Help

View File

@@ -0,0 +1,387 @@
---
title: Google Slides Integration
description: "Presentation creation and management with Google Slides integration for CrewAI."
icon: "chart-bar"
mode: "wide"
---
## Overview
Enable your agents to create, edit, and manage Google Slides presentations. Create presentations, update content, import data from Google Sheets, manage pages and thumbnails, and streamline your presentation workflows with AI-powered automation.
## Prerequisites
Before using the Google Slides integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Google account with Google Slides access
- Connected your Google account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Google Slides Integration
### 1. Connect Your Google Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Google Slides** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for presentations, spreadsheets, and drive access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="google_slides/create_blank_presentation">
**Description:** Creates a blank presentation with no content.
**Parameters:**
- `title` (string, required): The title of the presentation.
</Accordion>
<Accordion title="google_slides/get_presentation">
**Description:** Retrieves a presentation by ID.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation to retrieve.
- `fields` (string, optional): The fields to include in the response. Use this to improve performance by only returning needed data.
</Accordion>
<Accordion title="google_slides/batch_update_presentation">
**Description:** Applies updates, add content, or remove content from a presentation.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation to update.
- `requests` (array, required): A list of updates to apply to the presentation.
```json
[
{
"insertText": {
"objectId": "slide_id",
"text": "Your text content here"
}
}
]
```
- `writeControl` (object, optional): Provides control over how write requests are executed.
```json
{
"requiredRevisionId": "revision_id_string"
}
```
</Accordion>
<Accordion title="google_slides/get_page">
**Description:** Retrieves a specific page by its ID.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation.
- `pageObjectId` (string, required): The ID of the page to retrieve.
</Accordion>
<Accordion title="google_slides/get_thumbnail">
**Description:** Generates a page thumbnail.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation.
- `pageObjectId` (string, required): The ID of the page for thumbnail generation.
</Accordion>
<Accordion title="google_slides/import_data_from_sheet">
**Description:** Imports data from a Google Sheet into a presentation.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation.
- `sheetId` (string, required): The ID of the Google Sheet to import from.
- `dataRange` (string, required): The range of data to import from the sheet.
</Accordion>
<Accordion title="google_slides/upload_file_to_drive">
**Description:** Uploads a file to Google Drive associated with the presentation.
**Parameters:**
- `file` (string, required): The file data to upload.
- `presentationId` (string, required): The ID of the presentation to link the uploaded file.
</Accordion>
<Accordion title="google_slides/link_file_to_presentation">
**Description:** Links a file in Google Drive to a presentation.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation.
- `fileId` (string, required): The ID of the file to link.
</Accordion>
<Accordion title="google_slides/get_all_presentations">
**Description:** Lists all presentations accessible to the user.
**Parameters:**
- `pageSize` (integer, optional): The number of presentations to return per page.
- `pageToken` (string, optional): A token for pagination.
</Accordion>
<Accordion title="google_slides/delete_presentation">
**Description:** Deletes a presentation by ID.
**Parameters:**
- `presentationId` (string, required): The ID of the presentation to delete.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Google Slides Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Google Slides capabilities
slides_agent = Agent(
role="Presentation Manager",
goal="Create and manage presentations efficiently",
backstory="An AI assistant specialized in presentation creation and content management.",
apps=['google_slides'] # All Google Slides actions will be available
)
# Task to create a presentation
create_presentation_task = Task(
description="Create a new presentation for the quarterly business review with key slides",
agent=slides_agent,
expected_output="Quarterly business review presentation created with structured content"
)
# Run the task
crew = Crew(
agents=[slides_agent],
tasks=[create_presentation_task]
)
crew.kickoff()
```
### Presentation Content Management
```python
from crewai import Agent, Task, Crew
content_manager = Agent(
role="Content Manager",
goal="Manage presentation content and updates",
backstory="An AI assistant that focuses on content creation and presentation updates.",
apps=[
'google_slides/create_blank_presentation',
'google_slides/batch_update_presentation',
'google_slides/get_presentation'
]
)
# Task to create and update presentations
content_task = Task(
description="Create a new presentation and add content slides with charts and text",
agent=content_manager,
expected_output="Presentation created with updated content and visual elements"
)
crew = Crew(
agents=[content_manager],
tasks=[content_task]
)
crew.kickoff()
```
### Data Integration and Visualization
```python
from crewai import Agent, Task, Crew
data_visualizer = Agent(
role="Data Visualizer",
goal="Create presentations with data imported from spreadsheets",
backstory="An AI assistant that specializes in data visualization and presentation integration.",
apps=['google_slides']
)
# Task to create data-driven presentations
visualization_task = Task(
description="""
1. Create a new presentation for monthly sales report
2. Import data from the sales spreadsheet
3. Create charts and visualizations from the imported data
4. Generate thumbnails for slide previews
""",
agent=data_visualizer,
expected_output="Data-driven presentation created with imported spreadsheet data and visualizations"
)
crew = Crew(
agents=[data_visualizer],
tasks=[visualization_task]
)
crew.kickoff()
```
### Presentation Library Management
```python
from crewai import Agent, Task, Crew
library_manager = Agent(
role="Presentation Library Manager",
goal="Manage and organize presentation libraries",
backstory="An AI assistant that manages presentation collections and file organization.",
apps=['google_slides']
)
# Task to manage presentation library
library_task = Task(
description="""
1. List all existing presentations
2. Generate thumbnails for presentation previews
3. Upload supporting files to Drive and link to presentations
4. Organize presentations by topic and date
""",
agent=library_manager,
expected_output="Presentation library organized with thumbnails and linked supporting files"
)
crew = Crew(
agents=[library_manager],
tasks=[library_task]
)
crew.kickoff()
```
### Automated Presentation Workflows
```python
from crewai import Agent, Task, Crew
presentation_automator = Agent(
role="Presentation Automator",
goal="Automate presentation creation and management workflows",
backstory="An AI assistant that automates complex presentation workflows and content generation.",
apps=['google_slides']
)
# Complex presentation automation task
automation_task = Task(
description="""
1. Create multiple presentations for different departments
2. Import relevant data from various spreadsheets
3. Update existing presentations with new content
4. Generate thumbnails for all presentations
5. Link supporting documents from Drive
6. Create a master index presentation with links to all others
""",
agent=presentation_automator,
expected_output="Automated presentation workflow completed with multiple presentations and organized structure"
)
crew = Crew(
agents=[presentation_automator],
tasks=[automation_task]
)
crew.kickoff()
```
### Template and Content Creation
```python
from crewai import Agent, Task, Crew
template_creator = Agent(
role="Template Creator",
goal="Create presentation templates and standardized content",
backstory="An AI assistant that creates consistent presentation templates and content standards.",
apps=['google_slides']
)
# Task to create templates
template_task = Task(
description="""
1. Create blank presentation templates for different use cases
2. Add standard layouts and content placeholders
3. Create sample presentations with best practices
4. Generate thumbnails for template previews
5. Upload template assets to Drive and link appropriately
""",
agent=template_creator,
expected_output="Presentation templates created with standardized layouts and linked assets"
)
crew = Crew(
agents=[template_creator],
tasks=[template_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Permission Errors**
- Ensure your Google account has appropriate permissions for Google Slides
- Verify that the OAuth connection includes required scopes for presentations, spreadsheets, and drive access
- Check that presentations are shared with the authenticated account
**Presentation ID Issues**
- Verify that presentation IDs are correct and presentations exist
- Ensure you have access permissions to the presentations you're trying to modify
- Check that presentation IDs are properly formatted
**Content Update Issues**
- Ensure batch update requests are properly formatted according to Google Slides API specifications
- Verify that object IDs for slides and elements exist in the presentation
- Check that write control revision IDs are current if using optimistic concurrency
**Data Import Issues**
- Verify that Google Sheet IDs are correct and accessible
- Ensure data ranges are properly specified using A1 notation
- Check that you have read permissions for the source spreadsheets
**File Upload and Linking Issues**
- Ensure file data is properly encoded for upload
- Verify that Drive file IDs are correct when linking files
- Check that you have appropriate Drive permissions for file operations
**Page and Thumbnail Operations**
- Verify that page object IDs exist in the specified presentation
- Ensure presentations have content before attempting to generate thumbnails
- Check that page structure is valid for thumbnail generation
**Pagination and Listing Issues**
- Use appropriate page sizes for listing presentations
- Implement proper pagination using page tokens for large result sets
- Handle empty result sets gracefully
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Google Slides integration setup or troubleshooting.
</Card>

View File

@@ -13,7 +13,7 @@ Enable your agents to manage companies and contacts within HubSpot. Create new r
Before using the HubSpot integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription.
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription.
- A HubSpot account with appropriate permissions.
- Connected your HubSpot account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors).
@@ -21,11 +21,11 @@ Before using the HubSpot integration, ensure you have:
### 1. Connect Your HubSpot Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors).
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors).
2. Find **HubSpot** in the Authentication Integrations section.
3. Click **Connect** and complete the OAuth flow.
4. Grant the necessary permissions for company and contact management.
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account).
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the HubSpot integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="HUBSPOT_CREATE_RECORD_COMPANIES">
<Accordion title="hubspot/create_company">
**Description:** Create a new company record in HubSpot.
**Parameters:**
@@ -101,7 +117,7 @@ uv add crewai-tools
- `founded_year` (string, optional): Year Founded.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_CONTACTS">
<Accordion title="hubspot/create_contact">
**Description:** Create a new contact record in HubSpot.
**Parameters:**
@@ -200,7 +216,7 @@ uv add crewai-tools
- `hs_googleplusid` (string, optional): googleplus ID.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_DEALS">
<Accordion title="hubspot/create_deal">
**Description:** Create a new deal record in HubSpot.
**Parameters:**
@@ -215,7 +231,7 @@ uv add crewai-tools
- `hs_priority` (string, optional): The priority of the deal. Available values: `low`, `medium`, `high`.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_ENGAGEMENTS">
<Accordion title="hubspot/create_record_engagements">
**Description:** Create a new engagement (e.g., note, email, call, meeting, task) in HubSpot.
**Parameters:**
@@ -232,7 +248,7 @@ uv add crewai-tools
- `hs_meeting_end_time` (string, optional): The end time of the meeting. (Used for `MEETING`)
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_COMPANIES">
<Accordion title="hubspot/update_company">
**Description:** Update an existing company record in HubSpot.
**Parameters:**
@@ -249,7 +265,7 @@ uv add crewai-tools
- `description` (string, optional): Description.
</Accordion>
<Accordion title="HUBSPOT_CREATE_RECORD_ANY">
<Accordion title="hubspot/create_record_any">
**Description:** Create a record for a specified object type in HubSpot.
**Parameters:**
@@ -257,7 +273,7 @@ uv add crewai-tools
- Additional parameters depend on the custom object's schema.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_CONTACTS">
<Accordion title="hubspot/update_contact">
**Description:** Update an existing contact record in HubSpot.
**Parameters:**
@@ -271,7 +287,7 @@ uv add crewai-tools
- `lifecyclestage` (string, optional): Lifecycle Stage.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_DEALS">
<Accordion title="hubspot/update_deal">
**Description:** Update an existing deal record in HubSpot.
**Parameters:**
@@ -284,7 +300,7 @@ uv add crewai-tools
- `dealtype` (string, optional): The type of deal.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_ENGAGEMENTS">
<Accordion title="hubspot/update_record_engagements">
**Description:** Update an existing engagement in HubSpot.
**Parameters:**
@@ -295,7 +311,7 @@ uv add crewai-tools
- `hs_task_status` (string, optional): The status of the task.
</Accordion>
<Accordion title="HUBSPOT_UPDATE_RECORD_ANY">
<Accordion title="hubspot/update_record_any">
**Description:** Update a record for a specified object type in HubSpot.
**Parameters:**
@@ -304,28 +320,28 @@ uv add crewai-tools
- Additional parameters depend on the custom object's schema.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_COMPANIES">
<Accordion title="hubspot/list_companies">
**Description:** Get a list of company records from HubSpot.
**Parameters:**
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_CONTACTS">
<Accordion title="hubspot/list_contacts">
**Description:** Get a list of contact records from HubSpot.
**Parameters:**
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_DEALS">
<Accordion title="hubspot/list_deals">
**Description:** Get a list of deal records from HubSpot.
**Parameters:**
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_ENGAGEMENTS">
<Accordion title="hubspot/get_records_engagements">
**Description:** Get a list of engagement records from HubSpot.
**Parameters:**
@@ -333,7 +349,7 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORDS_ANY">
<Accordion title="hubspot/get_records_any">
**Description:** Get a list of records for any specified object type in HubSpot.
**Parameters:**
@@ -341,35 +357,35 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_COMPANIES">
<Accordion title="hubspot/get_company">
**Description:** Get a single company record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the company to retrieve.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_CONTACTS">
<Accordion title="hubspot/get_contact">
**Description:** Get a single contact record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the contact to retrieve.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_DEALS">
<Accordion title="hubspot/get_deal">
**Description:** Get a single deal record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the deal to retrieve.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_ENGAGEMENTS">
<Accordion title="hubspot/get_record_by_id_engagements">
**Description:** Get a single engagement record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the engagement to retrieve.
</Accordion>
<Accordion title="HUBSPOT_GET_RECORD_BY_ID_ANY">
<Accordion title="hubspot/get_record_by_id_any">
**Description:** Get a single record of any specified object type by its ID.
**Parameters:**
@@ -377,7 +393,7 @@ uv add crewai-tools
- `recordId` (string, required): The ID of the record to retrieve.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_COMPANIES">
<Accordion title="hubspot/search_companies">
**Description:** Search for company records in HubSpot using a filter formula.
**Parameters:**
@@ -385,7 +401,7 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_CONTACTS">
<Accordion title="hubspot/search_contacts">
**Description:** Search for contact records in HubSpot using a filter formula.
**Parameters:**
@@ -393,7 +409,7 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_DEALS">
<Accordion title="hubspot/search_deals">
**Description:** Search for deal records in HubSpot using a filter formula.
**Parameters:**
@@ -401,7 +417,7 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_ENGAGEMENTS">
<Accordion title="hubspot/search_records_engagements">
**Description:** Search for engagement records in HubSpot using a filter formula.
**Parameters:**
@@ -409,7 +425,7 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_SEARCH_RECORDS_ANY">
<Accordion title="hubspot/search_records_any">
**Description:** Search for records of any specified object type in HubSpot.
**Parameters:**
@@ -418,35 +434,35 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` to fetch subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_COMPANIES">
<Accordion title="hubspot/delete_record_companies">
**Description:** Delete a company record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the company to delete.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_CONTACTS">
<Accordion title="hubspot/delete_record_contacts">
**Description:** Delete a contact record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the contact to delete.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_DEALS">
<Accordion title="hubspot/delete_record_deals">
**Description:** Delete a deal record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the deal to delete.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_ENGAGEMENTS">
<Accordion title="hubspot/delete_record_engagements">
**Description:** Delete an engagement record by its ID.
**Parameters:**
- `recordId` (string, required): The ID of the engagement to delete.
</Accordion>
<Accordion title="HUBSPOT_DELETE_RECORD_ANY">
<Accordion title="hubspot/delete_record_any">
**Description:** Delete a record of any specified object type by its ID.
**Parameters:**
@@ -454,7 +470,7 @@ uv add crewai-tools
- `recordId` (string, required): The ID of the record to delete.
</Accordion>
<Accordion title="HUBSPOT_GET_CONTACTS_BY_LIST_ID">
<Accordion title="hubspot/get_contacts_by_list_id">
**Description:** Get contacts from a specific list by its ID.
**Parameters:**
@@ -462,7 +478,7 @@ uv add crewai-tools
- `paginationParameters` (object, optional): Use `pageCursor` for subsequent pages.
</Accordion>
<Accordion title="HUBSPOT_DESCRIBE_ACTION_SCHEMA">
<Accordion title="hubspot/describe_action_schema">
**Description:** Get the expected schema for a given object type and operation.
**Parameters:**
@@ -477,19 +493,13 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (HubSpot tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with HubSpot capabilities
hubspot_agent = Agent(
role="CRM Manager",
goal="Manage company and contact records in HubSpot",
backstory="An AI assistant specialized in CRM management.",
tools=[enterprise_tools]
apps=['hubspot'] # All HubSpot actions will be available
)
# Task to create a new company
@@ -511,19 +521,14 @@ crew.kickoff()
### Filtering Specific HubSpot Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only the tool to create contacts
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["hubspot_create_record_contacts"]
)
from crewai import Agent, Task, Crew
# Create agent with specific HubSpot actions only
contact_creator = Agent(
role="Contact Creator",
goal="Create new contacts in HubSpot",
backstory="An AI assistant that focuses on creating new contact entries in the CRM.",
tools=[enterprise_tools]
apps=['hubspot/create_contact'] # Only contact creation action
)
# Task to create a contact
@@ -545,17 +550,13 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create agent with HubSpot contact management capabilities
crm_manager = Agent(
role="CRM Manager",
goal="Manage and organize HubSpot contacts efficiently.",
backstory="An experienced CRM manager who maintains an organized contact database.",
tools=[enterprise_tools]
apps=['hubspot'] # All HubSpot actions including contact management
)
# Task to manage contacts

View File

@@ -13,7 +13,7 @@ Enable your agents to manage issues, projects, and workflows through Jira. Creat
Before using the Jira integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Jira account with appropriate project permissions
- Connected your Jira account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Jira integration, ensure you have:
### 1. Connect Your Jira Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Jira** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for issue and project management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the Jira integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="JIRA_CREATE_ISSUE">
<Accordion title="jira/create_issue">
**Description:** Create an issue in Jira.
**Parameters:**
@@ -56,7 +72,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="JIRA_UPDATE_ISSUE">
<Accordion title="jira/update_issue">
**Description:** Update an issue in Jira.
**Parameters:**
@@ -71,14 +87,14 @@ uv add crewai-tools
- `additionalFields` (string, optional): Additional Fields - Specify any other fields that should be included in JSON format.
</Accordion>
<Accordion title="JIRA_GET_ISSUE_BY_KEY">
<Accordion title="jira/get_issue_by_key">
**Description:** Get an issue by key in Jira.
**Parameters:**
- `issueKey` (string, required): Issue Key (example: "TEST-1234").
</Accordion>
<Accordion title="JIRA_FILTER_ISSUES">
<Accordion title="jira/filter_issues">
**Description:** Search issues in Jira using filters.
**Parameters:**
@@ -104,7 +120,7 @@ uv add crewai-tools
- `limit` (string, optional): Limit results - Limit the maximum number of issues to return. Defaults to 10 if left blank.
</Accordion>
<Accordion title="JIRA_SEARCH_BY_JQL">
<Accordion title="jira/search_by_jql">
**Description:** Search issues by JQL in Jira.
**Parameters:**
@@ -117,13 +133,13 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="JIRA_UPDATE_ISSUE_ANY">
<Accordion title="jira/update_issue_any">
**Description:** Update any issue in Jira. Use DESCRIBE_ACTION_SCHEMA to get properties schema for this function.
**Parameters:** No specific parameters - use JIRA_DESCRIBE_ACTION_SCHEMA first to get the expected schema.
</Accordion>
<Accordion title="JIRA_DESCRIBE_ACTION_SCHEMA">
<Accordion title="jira/describe_action_schema">
**Description:** Get the expected schema for an issue type. Use this function first if no other function matches the issue type you want to operate on.
**Parameters:**
@@ -132,7 +148,7 @@ uv add crewai-tools
- `operation` (string, required): Operation Type value, for example CREATE_ISSUE or UPDATE_ISSUE.
</Accordion>
<Accordion title="JIRA_GET_PROJECTS">
<Accordion title="jira/get_projects">
**Description:** Get Projects in Jira.
**Parameters:**
@@ -144,27 +160,27 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="JIRA_GET_ISSUE_TYPES_BY_PROJECT">
<Accordion title="jira/get_issue_types_by_project">
**Description:** Get Issue Types by project in Jira.
**Parameters:**
- `project` (string, required): Project key.
</Accordion>
<Accordion title="JIRA_GET_ISSUE_TYPES">
<Accordion title="jira/get_issue_types">
**Description:** Get all Issue Types in Jira.
**Parameters:** None required.
</Accordion>
<Accordion title="JIRA_GET_ISSUE_STATUS_BY_PROJECT">
<Accordion title="jira/get_issue_status_by_project">
**Description:** Get issue statuses for a given project.
**Parameters:**
- `project` (string, required): Project key.
</Accordion>
<Accordion title="JIRA_GET_ALL_ASSIGNEES_BY_PROJECT">
<Accordion title="jira/get_all_assignees_by_project">
**Description:** Get assignees for a given project.
**Parameters:**
@@ -178,19 +194,14 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Jira tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Jira capabilities
jira_agent = Agent(
role="Issue Manager",
goal="Manage Jira issues and track project progress efficiently",
backstory="An AI assistant specialized in issue tracking and project management.",
tools=[enterprise_tools]
apps=['jira'] # All Jira actions will be available
)
# Task to create a bug report
@@ -212,19 +223,12 @@ crew.kickoff()
### Filtering Specific Jira Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Jira tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["jira_create_issue", "jira_update_issue", "jira_search_by_jql"]
)
issue_coordinator = Agent(
role="Issue Coordinator",
goal="Create and manage Jira issues efficiently",
backstory="An AI assistant that focuses on issue creation and management.",
tools=enterprise_tools
apps=['jira']
)
# Task to manage issue workflow
@@ -246,17 +250,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_analyst = Agent(
role="Project Analyst",
goal="Analyze project data and generate insights from Jira",
backstory="An experienced project analyst who extracts insights from project management data.",
tools=[enterprise_tools]
apps=['jira']
)
# Task to analyze project status
@@ -283,17 +282,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
automation_manager = Agent(
role="Automation Manager",
goal="Automate issue management and workflow processes",
backstory="An AI assistant that automates repetitive issue management tasks.",
tools=[enterprise_tools]
apps=['jira']
)
# Task to automate issue management
@@ -321,17 +315,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
schema_specialist = Agent(
role="Schema Specialist",
goal="Handle complex Jira operations using dynamic schemas",
backstory="An AI assistant that can work with dynamic Jira schemas and custom issue types.",
tools=[enterprise_tools]
apps=['jira']
)
# Task using schema-based operations

View File

@@ -13,7 +13,7 @@ Enable your agents to manage issues, projects, and development workflows through
Before using the Linear integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Linear account with appropriate workspace permissions
- Connected your Linear account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Linear integration, ensure you have:
### 1. Connect Your Linear Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Linear** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for issue and project management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,10 +33,26 @@ Before using the Linear integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="LINEAR_CREATE_ISSUE">
<Accordion title="linear/create_issue">
**Description:** Create a new issue in Linear.
**Parameters:**
@@ -56,7 +72,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="LINEAR_UPDATE_ISSUE">
<Accordion title="linear/update_issue">
**Description:** Update an issue in Linear.
**Parameters:**
@@ -76,21 +92,21 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="LINEAR_GET_ISSUE_BY_ID">
<Accordion title="linear/get_issue_by_id">
**Description:** Get an issue by ID in Linear.
**Parameters:**
- `issueId` (string, required): Issue ID - Specify the record ID of the issue to fetch. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
</Accordion>
<Accordion title="LINEAR_GET_ISSUE_BY_ISSUE_IDENTIFIER">
<Accordion title="linear/get_issue_by_issue_identifier">
**Description:** Get an issue by issue identifier in Linear.
**Parameters:**
- `externalId` (string, required): External ID - Specify the human-readable Issue identifier of the issue to fetch. (example: "ABC-1").
</Accordion>
<Accordion title="LINEAR_SEARCH_ISSUE">
<Accordion title="linear/search_issue">
**Description:** Search issues in Linear.
**Parameters:**
@@ -117,21 +133,21 @@ uv add crewai-tools
Available operators: `$stringExactlyMatches`, `$stringDoesNotExactlyMatch`, `$stringIsIn`, `$stringIsNotIn`, `$stringStartsWith`, `$stringDoesNotStartWith`, `$stringEndsWith`, `$stringDoesNotEndWith`, `$stringContains`, `$stringDoesNotContain`, `$stringGreaterThan`, `$stringLessThan`, `$numberGreaterThanOrEqualTo`, `$numberLessThanOrEqualTo`, `$numberGreaterThan`, `$numberLessThan`, `$dateTimeAfter`, `$dateTimeBefore`
</Accordion>
<Accordion title="LINEAR_DELETE_ISSUE">
<Accordion title="linear/delete_issue">
**Description:** Delete an issue in Linear.
**Parameters:**
- `issueId` (string, required): Issue ID - Specify the record ID of the issue to delete. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
</Accordion>
<Accordion title="LINEAR_ARCHIVE_ISSUE">
<Accordion title="linear/archive_issue">
**Description:** Archive an issue in Linear.
**Parameters:**
- `issueId` (string, required): Issue ID - Specify the record ID of the issue to archive. (example: "90fbc706-18cd-42c9-ae66-6bd344cc8977").
</Accordion>
<Accordion title="LINEAR_CREATE_SUB_ISSUE">
<Accordion title="linear/create_sub_issue">
**Description:** Create a sub-issue in Linear.
**Parameters:**
@@ -147,7 +163,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="LINEAR_CREATE_PROJECT">
<Accordion title="linear/create_project">
**Description:** Create a new project in Linear.
**Parameters:**
@@ -169,7 +185,7 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="LINEAR_UPDATE_PROJECT">
<Accordion title="linear/update_project">
**Description:** Update a project in Linear.
**Parameters:**
@@ -185,21 +201,21 @@ uv add crewai-tools
```
</Accordion>
<Accordion title="LINEAR_GET_PROJECT_BY_ID">
<Accordion title="linear/get_project_by_id">
**Description:** Get a project by ID in Linear.
**Parameters:**
- `projectId` (string, required): Project ID - Specify the Project ID of the project to fetch. (example: "a6634484-6061-4ac7-9739-7dc5e52c796b").
</Accordion>
<Accordion title="LINEAR_DELETE_PROJECT">
<Accordion title="linear/delete_project">
**Description:** Delete a project in Linear.
**Parameters:**
- `projectId` (string, required): Project ID - Specify the Project ID of the project to delete. (example: "a6634484-6061-4ac7-9739-7dc5e52c796b").
</Accordion>
<Accordion title="LINEAR_SEARCH_TEAMS">
<Accordion title="linear/search_teams">
**Description:** Search teams in Linear.
**Parameters:**
@@ -231,19 +247,14 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Linear tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Linear capabilities
linear_agent = Agent(
role="Development Manager",
goal="Manage Linear issues and track development progress efficiently",
backstory="An AI assistant specialized in software development project management.",
tools=[enterprise_tools]
apps=['linear'] # All Linear actions will be available
)
# Task to create a bug report
@@ -265,19 +276,12 @@ crew.kickoff()
### Filtering Specific Linear Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Linear tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["linear_create_issue", "linear_update_issue", "linear_search_issue"]
)
issue_manager = Agent(
role="Issue Manager",
goal="Create and manage Linear issues efficiently",
backstory="An AI assistant that focuses on issue creation and lifecycle management.",
tools=enterprise_tools
apps=['linear/create_issue']
)
# Task to manage issue workflow
@@ -299,17 +303,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
project_coordinator = Agent(
role="Project Coordinator",
goal="Coordinate projects and teams in Linear efficiently",
backstory="An experienced project coordinator who manages development cycles and team workflows.",
tools=[enterprise_tools]
apps=['linear']
)
# Task to coordinate project setup
@@ -336,17 +335,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
task_organizer = Agent(
role="Task Organizer",
goal="Organize complex issues into manageable sub-tasks",
backstory="An AI assistant that breaks down complex development work into organized sub-tasks.",
tools=[enterprise_tools]
apps=['linear']
)
# Task to create issue hierarchy
@@ -373,17 +367,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
workflow_automator = Agent(
role="Workflow Automator",
goal="Automate development workflow processes in Linear",
backstory="An AI assistant that automates repetitive development workflow tasks.",
tools=[enterprise_tools]
apps=['linear']
)
# Complex workflow automation task

View File

@@ -0,0 +1,462 @@
---
title: Microsoft Excel Integration
description: "Workbook and data management with Microsoft Excel integration for CrewAI."
icon: "table"
mode: "wide"
---
## Overview
Enable your agents to create and manage Excel workbooks, worksheets, tables, and charts in OneDrive or SharePoint. Manipulate data ranges, create visualizations, manage tables, and streamline your spreadsheet workflows with AI-powered automation.
## Prerequisites
Before using the Microsoft Excel integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Microsoft 365 account with Excel and OneDrive/SharePoint access
- Connected your Microsoft account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Microsoft Excel Integration
### 1. Connect Your Microsoft Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Microsoft Excel** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for files and Excel workbook access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="microsoft_excel/create_workbook">
**Description:** Create a new Excel workbook in OneDrive or SharePoint.
**Parameters:**
- `file_path` (string, required): Path where to create the workbook (e.g., 'MyWorkbook.xlsx')
- `worksheets` (array, optional): Initial worksheets to create
```json
[
{
"name": "Sheet1"
},
{
"name": "Data"
}
]
```
</Accordion>
<Accordion title="microsoft_excel/get_workbooks">
**Description:** Get all Excel workbooks from OneDrive or SharePoint.
**Parameters:**
- `select` (string, optional): Select specific properties to return
- `filter` (string, optional): Filter results using OData syntax
- `expand` (string, optional): Expand related resources inline
- `top` (integer, optional): Number of items to return. Minimum: 1, Maximum: 999
- `orderby` (string, optional): Order results by specified properties
</Accordion>
<Accordion title="microsoft_excel/get_worksheets">
**Description:** Get all worksheets in an Excel workbook.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `select` (string, optional): Select specific properties to return (e.g., 'id,name,position')
- `filter` (string, optional): Filter results using OData syntax
- `expand` (string, optional): Expand related resources inline
- `top` (integer, optional): Number of items to return. Minimum: 1, Maximum: 999
- `orderby` (string, optional): Order results by specified properties
</Accordion>
<Accordion title="microsoft_excel/create_worksheet">
**Description:** Create a new worksheet in an Excel workbook.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `name` (string, required): Name of the new worksheet
</Accordion>
<Accordion title="microsoft_excel/get_range_data">
**Description:** Get data from a specific range in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `range` (string, required): Range address (e.g., 'A1:C10')
</Accordion>
<Accordion title="microsoft_excel/update_range_data">
**Description:** Update data in a specific range in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `range` (string, required): Range address (e.g., 'A1:C10')
- `values` (array, required): 2D array of values to set in the range
```json
[
["Name", "Age", "City"],
["John", 30, "New York"],
["Jane", 25, "Los Angeles"]
]
```
</Accordion>
<Accordion title="microsoft_excel/add_table">
**Description:** Create a table in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `range` (string, required): Range for the table (e.g., 'A1:D10')
- `has_headers` (boolean, optional): Whether the first row contains headers. Default: true
</Accordion>
<Accordion title="microsoft_excel/get_tables">
**Description:** Get all tables in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
</Accordion>
<Accordion title="microsoft_excel/add_table_row">
**Description:** Add a new row to an Excel table.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `table_name` (string, required): Name of the table
- `values` (array, required): Array of values for the new row
```json
["John Doe", 35, "Manager", "Sales"]
```
</Accordion>
<Accordion title="microsoft_excel/create_chart">
**Description:** Create a chart in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `chart_type` (string, required): Type of chart (e.g., 'ColumnClustered', 'Line', 'Pie')
- `source_data` (string, required): Range of data for the chart (e.g., 'A1:B10')
- `series_by` (string, optional): How to interpret the data ('Auto', 'Columns', or 'Rows'). Default: Auto
</Accordion>
<Accordion title="microsoft_excel/get_cell">
**Description:** Get the value of a single cell in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `row` (integer, required): Row number (0-based)
- `column` (integer, required): Column number (0-based)
</Accordion>
<Accordion title="microsoft_excel/get_used_range">
**Description:** Get the used range of an Excel worksheet (contains all data).
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
</Accordion>
<Accordion title="microsoft_excel/list_charts">
**Description:** Get all charts in an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
</Accordion>
<Accordion title="microsoft_excel/delete_worksheet">
**Description:** Delete a worksheet from an Excel workbook.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet to delete
</Accordion>
<Accordion title="microsoft_excel/delete_table">
**Description:** Delete a table from an Excel worksheet.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
- `worksheet_name` (string, required): Name of the worksheet
- `table_name` (string, required): Name of the table to delete
</Accordion>
<Accordion title="microsoft_excel/list_names">
**Description:** Get all named ranges in an Excel workbook.
**Parameters:**
- `file_id` (string, required): The ID of the Excel file
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Excel Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Excel capabilities
excel_agent = Agent(
role="Excel Data Manager",
goal="Manage Excel workbooks and data efficiently",
backstory="An AI assistant specialized in Excel data management and analysis.",
apps=['microsoft_excel'] # All Excel actions will be available
)
# Task to create and populate a workbook
data_management_task = Task(
description="Create a new sales report workbook with data analysis and charts",
agent=excel_agent,
expected_output="Excel workbook created with sales data, analysis, and visualizations"
)
# Run the task
crew = Crew(
agents=[excel_agent],
tasks=[data_management_task]
)
crew.kickoff()
```
### Data Analysis and Reporting
```python
from crewai import Agent, Task, Crew
data_analyst = Agent(
role="Data Analyst",
goal="Analyze data in Excel and create comprehensive reports",
backstory="An AI assistant that specializes in data analysis and Excel reporting.",
apps=[
'microsoft_excel/get_workbooks',
'microsoft_excel/get_range_data',
'microsoft_excel/create_chart',
'microsoft_excel/add_table'
]
)
# Task to analyze existing data
analysis_task = Task(
description="Analyze sales data in existing workbooks and create summary charts and tables",
agent=data_analyst,
expected_output="Data analyzed with summary charts and tables created"
)
crew = Crew(
agents=[data_analyst],
tasks=[analysis_task]
)
crew.kickoff()
```
### Workbook Creation and Structure
```python
from crewai import Agent, Task, Crew
workbook_creator = Agent(
role="Workbook Creator",
goal="Create structured Excel workbooks with multiple worksheets and data organization",
backstory="An AI assistant that creates well-organized Excel workbooks for various business needs.",
apps=['microsoft_excel']
)
# Task to create structured workbooks
creation_task = Task(
description="""
1. Create a new quarterly report workbook
2. Add multiple worksheets for different departments
3. Create tables with headers for data organization
4. Set up charts for key metrics visualization
""",
agent=workbook_creator,
expected_output="Structured workbook created with multiple worksheets, tables, and charts"
)
crew = Crew(
agents=[workbook_creator],
tasks=[creation_task]
)
crew.kickoff()
```
### Data Manipulation and Updates
```python
from crewai import Agent, Task, Crew
data_manipulator = Agent(
role="Data Manipulator",
goal="Update and manipulate data in Excel worksheets efficiently",
backstory="An AI assistant that handles data updates, table management, and range operations.",
apps=['microsoft_excel']
)
# Task to manipulate data
manipulation_task = Task(
description="""
1. Get data from existing worksheets
2. Update specific ranges with new information
3. Add new rows to existing tables
4. Create additional charts based on updated data
5. Organize data across multiple worksheets
""",
agent=data_manipulator,
expected_output="Data updated across worksheets with new charts and organized structure"
)
crew = Crew(
agents=[data_manipulator],
tasks=[manipulation_task]
)
crew.kickoff()
```
### Advanced Excel Automation
```python
from crewai import Agent, Task, Crew
excel_automator = Agent(
role="Excel Automator",
goal="Automate complex Excel workflows and data processing",
backstory="An AI assistant that automates sophisticated Excel operations and data workflows.",
apps=['microsoft_excel']
)
# Complex automation task
automation_task = Task(
description="""
1. Scan all Excel workbooks for specific data patterns
2. Create consolidated reports from multiple workbooks
3. Generate charts and tables for trend analysis
4. Set up named ranges for easy data reference
5. Create dashboard worksheets with key metrics
6. Clean up unused worksheets and tables
""",
agent=excel_automator,
expected_output="Automated Excel workflow completed with consolidated reports and dashboards"
)
crew = Crew(
agents=[excel_automator],
tasks=[automation_task]
)
crew.kickoff()
```
### Financial Modeling and Analysis
```python
from crewai import Agent, Task, Crew
financial_modeler = Agent(
role="Financial Modeler",
goal="Create financial models and analysis in Excel",
backstory="An AI assistant specialized in financial modeling and analysis using Excel.",
apps=['microsoft_excel']
)
# Task for financial modeling
modeling_task = Task(
description="""
1. Create financial model workbooks with multiple scenarios
2. Set up input tables for assumptions and variables
3. Create calculation worksheets with formulas and logic
4. Generate charts for financial projections and trends
5. Add summary tables for key financial metrics
6. Create sensitivity analysis tables
""",
agent=financial_modeler,
expected_output="Financial model created with scenarios, calculations, and analysis charts"
)
crew = Crew(
agents=[financial_modeler],
tasks=[modeling_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Permission Errors**
- Ensure your Microsoft account has appropriate permissions for Excel and OneDrive/SharePoint
- Verify that the OAuth connection includes required scopes (Files.Read.All, Files.ReadWrite.All)
- Check that you have access to the specific workbooks you're trying to modify
**File ID and Path Issues**
- Verify that file IDs are correct and files exist in your OneDrive or SharePoint
- Ensure file paths are properly formatted when creating new workbooks
- Check that workbook files have the correct .xlsx extension
**Worksheet and Range Issues**
- Verify that worksheet names exist in the specified workbook
- Ensure range addresses are properly formatted (e.g., 'A1:C10')
- Check that ranges don't exceed worksheet boundaries
**Data Format Issues**
- Ensure data values are properly formatted for Excel (strings, numbers, integers)
- Verify that 2D arrays for ranges have consistent row and column counts
- Check that table data includes proper headers when has_headers is true
**Chart Creation Issues**
- Verify that chart types are supported (ColumnClustered, Line, Pie, etc.)
- Ensure source data ranges contain appropriate data for the chart type
- Check that the source data range exists and contains data
**Table Management Issues**
- Ensure table names are unique within worksheets
- Verify that table ranges don't overlap with existing tables
- Check that new row data matches the table's column structure
**Cell and Range Operations**
- Verify that row and column indices are 0-based for cell operations
- Ensure ranges contain data when using get_used_range
- Check that named ranges exist before referencing them
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Microsoft Excel integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,266 @@
---
title: Microsoft OneDrive Integration
description: "File and folder management with Microsoft OneDrive integration for CrewAI."
icon: "cloud"
mode: "wide"
---
## Overview
Enable your agents to upload, download, and manage files and folders in Microsoft OneDrive. Automate file operations, organize content, create sharing links, and streamline your cloud storage workflows with AI-powered automation.
## Prerequisites
Before using the Microsoft OneDrive integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Microsoft account with OneDrive access
- Connected your Microsoft account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Microsoft OneDrive Integration
### 1. Connect Your Microsoft Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Microsoft OneDrive** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for file access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="microsoft_onedrive/list_files">
**Description:** List files and folders in OneDrive.
**Parameters:**
- `top` (integer, optional): Number of items to retrieve (max 1000). Default is `50`.
- `orderby` (string, optional): Order by field (e.g., "name asc", "lastModifiedDateTime desc"). Default is "name asc".
- `filter` (string, optional): OData filter expression.
</Accordion>
<Accordion title="microsoft_onedrive/get_file_info">
**Description:** Get information about a specific file or folder.
**Parameters:**
- `item_id` (string, required): The ID of the file or folder.
</Accordion>
<Accordion title="microsoft_onedrive/download_file">
**Description:** Download a file from OneDrive.
**Parameters:**
- `item_id` (string, required): The ID of the file to download.
</Accordion>
<Accordion title="microsoft_onedrive/upload_file">
**Description:** Upload a file to OneDrive.
**Parameters:**
- `file_name` (string, required): Name of the file to upload.
- `content` (string, required): Base64 encoded file content.
</Accordion>
<Accordion title="microsoft_onedrive/create_folder">
**Description:** Create a new folder in OneDrive.
**Parameters:**
- `folder_name` (string, required): Name of the folder to create.
</Accordion>
<Accordion title="microsoft_onedrive/delete_item">
**Description:** Delete a file or folder from OneDrive.
**Parameters:**
- `item_id` (string, required): The ID of the file or folder to delete.
</Accordion>
<Accordion title="microsoft_onedrive/copy_item">
**Description:** Copy a file or folder in OneDrive.
**Parameters:**
- `item_id` (string, required): The ID of the file or folder to copy.
- `parent_id` (string, optional): The ID of the destination folder (optional, defaults to root).
- `new_name` (string, optional): New name for the copied item (optional).
</Accordion>
<Accordion title="microsoft_onedrive/move_item">
**Description:** Move a file or folder in OneDrive.
**Parameters:**
- `item_id` (string, required): The ID of the file or folder to move.
- `parent_id` (string, required): The ID of the destination folder.
- `new_name` (string, optional): New name for the item (optional).
</Accordion>
<Accordion title="microsoft_onedrive/search_files">
**Description:** Search for files and folders in OneDrive.
**Parameters:**
- `query` (string, required): Search query string.
- `top` (integer, optional): Number of results to return (max 1000). Default is `50`.
</Accordion>
<Accordion title="microsoft_onedrive/share_item">
**Description:** Create a sharing link for a file or folder.
**Parameters:**
- `item_id` (string, required): The ID of the file or folder to share.
- `type` (string, optional): Type of sharing link. Enum: `view`, `edit`, `embed`. Default is `view`.
- `scope` (string, optional): Scope of the sharing link. Enum: `anonymous`, `organization`. Default is `anonymous`.
</Accordion>
<Accordion title="microsoft_onedrive/get_thumbnails">
**Description:** Get thumbnails for a file.
**Parameters:**
- `item_id` (string, required): The ID of the file.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Microsoft OneDrive Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Microsoft OneDrive capabilities
onedrive_agent = Agent(
role="File Manager",
goal="Manage files and folders in OneDrive efficiently",
backstory="An AI assistant specialized in Microsoft OneDrive file operations and organization.",
apps=['microsoft_onedrive'] # All OneDrive actions will be available
)
# Task to list files and create a folder
organize_files_task = Task(
description="List all files in my OneDrive root directory and create a new folder called 'Project Documents'.",
agent=onedrive_agent,
expected_output="List of files displayed and new folder 'Project Documents' created."
)
# Run the task
crew = Crew(
agents=[onedrive_agent],
tasks=[organize_files_task]
)
crew.kickoff()
```
### File Upload and Management
```python
from crewai import Agent, Task, Crew
# Create an agent focused on file operations
file_operator = Agent(
role="File Operator",
goal="Upload, download, and manage files with precision",
backstory="An AI assistant skilled in file handling and content management.",
apps=['microsoft_onedrive/upload_file', 'microsoft_onedrive/download_file', 'microsoft_onedrive/get_file_info']
)
# Task to upload and manage a file
file_management_task = Task(
description="Upload a text file named 'report.txt' with content 'This is a sample report for the project.' Then get information about the uploaded file.",
agent=file_operator,
expected_output="File uploaded successfully and file information retrieved."
)
crew = Crew(
agents=[file_operator],
tasks=[file_management_task]
)
crew.kickoff()
```
### File Organization and Sharing
```python
from crewai import Agent, Task, Crew
# Create an agent for file organization and sharing
file_organizer = Agent(
role="File Organizer",
goal="Organize files and create sharing links for collaboration",
backstory="An AI assistant that excels at organizing files and managing sharing permissions.",
apps=['microsoft_onedrive/search_files', 'microsoft_onedrive/move_item', 'microsoft_onedrive/share_item', 'microsoft_onedrive/create_folder']
)
# Task to organize and share files
organize_share_task = Task(
description="Search for files containing 'presentation' in the name, create a folder called 'Presentations', move the found files to this folder, and create a view-only sharing link for the folder.",
agent=file_organizer,
expected_output="Files organized into 'Presentations' folder and sharing link created."
)
crew = Crew(
agents=[file_organizer],
tasks=[organize_share_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Authentication Errors**
- Ensure your Microsoft account has the necessary permissions for file access (e.g., `Files.Read`, `Files.ReadWrite`).
- Verify that the OAuth connection includes all required scopes.
**File Upload Issues**
- Ensure `file_name` and `content` are provided for file uploads.
- Content must be Base64 encoded for binary files.
- Check that you have write permissions to OneDrive.
**File/Folder ID Issues**
- Double-check item IDs for correctness when accessing specific files or folders.
- Item IDs are returned by other operations like `list_files` or `search_files`.
- Ensure the referenced items exist and are accessible.
**Search and Filter Operations**
- Use appropriate search terms for `search_files` operations.
- For `filter` parameters, use proper OData syntax.
**File Operations (Copy/Move)**
- For `move_item`, ensure both `item_id` and `parent_id` are provided.
- For `copy_item`, only `item_id` is required; `parent_id` defaults to root if not specified.
- Verify that destination folders exist and are accessible.
**Sharing Link Creation**
- Ensure the item exists before creating sharing links.
- Choose appropriate `type` and `scope` based on your sharing requirements.
- `anonymous` scope allows access without sign-in; `organization` requires organizational account.
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Microsoft OneDrive integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,248 @@
---
title: Microsoft Outlook Integration
description: "Email, calendar, and contact management with Microsoft Outlook integration for CrewAI."
icon: "envelope"
mode: "wide"
---
## Overview
Enable your agents to access and manage Outlook emails, calendar events, and contacts. Send emails, retrieve messages, manage calendar events, and organize contacts with AI-powered automation.
## Prerequisites
Before using the Microsoft Outlook integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Microsoft account with Outlook access
- Connected your Microsoft account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Microsoft Outlook Integration
### 1. Connect Your Microsoft Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Microsoft Outlook** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for mail, calendar, and contact access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="microsoft_outlook/get_messages">
**Description:** Get email messages from the user's mailbox.
**Parameters:**
- `top` (integer, optional): Number of messages to retrieve (max 1000). Default is `10`.
- `filter` (string, optional): OData filter expression (e.g., "isRead eq false").
- `search` (string, optional): Search query string.
- `orderby` (string, optional): Order by field (e.g., "receivedDateTime desc"). Default is "receivedDateTime desc".
- `select` (string, optional): Select specific properties to return.
- `expand` (string, optional): Expand related resources inline.
</Accordion>
<Accordion title="microsoft_outlook/send_email">
**Description:** Send an email message.
**Parameters:**
- `to_recipients` (array, required): Array of recipient email addresses.
- `cc_recipients` (array, optional): Array of CC recipient email addresses.
- `bcc_recipients` (array, optional): Array of BCC recipient email addresses.
- `subject` (string, required): Email subject.
- `body` (string, required): Email body content.
- `body_type` (string, optional): Body content type. Enum: `Text`, `HTML`. Default is `HTML`.
- `importance` (string, optional): Message importance level. Enum: `low`, `normal`, `high`. Default is `normal`.
- `reply_to` (array, optional): Array of reply-to email addresses.
- `save_to_sent_items` (boolean, optional): Whether to save the message to Sent Items folder. Default is `true`.
</Accordion>
<Accordion title="microsoft_outlook/get_calendar_events">
**Description:** Get calendar events from the user's calendar.
**Parameters:**
- `top` (integer, optional): Number of events to retrieve (max 1000). Default is `10`.
- `skip` (integer, optional): Number of events to skip. Default is `0`.
- `filter` (string, optional): OData filter expression (e.g., "start/dateTime ge '2024-01-01T00:00:00Z'").
- `orderby` (string, optional): Order by field (e.g., "start/dateTime asc"). Default is "start/dateTime asc".
</Accordion>
<Accordion title="microsoft_outlook/create_calendar_event">
**Description:** Create a new calendar event.
**Parameters:**
- `subject` (string, required): Event subject/title.
- `body` (string, optional): Event body/description.
- `start_datetime` (string, required): Start date and time in ISO 8601 format (e.g., '2024-01-20T10:00:00').
- `end_datetime` (string, required): End date and time in ISO 8601 format.
- `timezone` (string, optional): Time zone (e.g., 'Pacific Standard Time'). Default is `UTC`.
- `location` (string, optional): Event location.
- `attendees` (array, optional): Array of attendee email addresses.
</Accordion>
<Accordion title="microsoft_outlook/get_contacts">
**Description:** Get contacts from the user's address book.
**Parameters:**
- `top` (integer, optional): Number of contacts to retrieve (max 1000). Default is `10`.
- `skip` (integer, optional): Number of contacts to skip. Default is `0`.
- `filter` (string, optional): OData filter expression.
- `orderby` (string, optional): Order by field (e.g., "displayName asc"). Default is "displayName asc".
</Accordion>
<Accordion title="microsoft_outlook/create_contact">
**Description:** Create a new contact in the user's address book.
**Parameters:**
- `displayName` (string, required): Contact's display name.
- `givenName` (string, optional): Contact's first name.
- `surname` (string, optional): Contact's last name.
- `emailAddresses` (array, optional): Array of email addresses. Each item is an object with `address` (string) and `name` (string).
- `businessPhones` (array, optional): Array of business phone numbers.
- `homePhones` (array, optional): Array of home phone numbers.
- `jobTitle` (string, optional): Contact's job title.
- `companyName` (string, optional): Contact's company name.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Microsoft Outlook Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Microsoft Outlook capabilities
outlook_agent = Agent(
role="Email Assistant",
goal="Manage emails, calendar events, and contacts efficiently",
backstory="An AI assistant specialized in Microsoft Outlook operations and communication management.",
apps=['microsoft_outlook'] # All Outlook actions will be available
)
# Task to send an email
send_email_task = Task(
description="Send an email to 'colleague@example.com' with subject 'Project Update' and body 'Hi, here is the latest project update. Best regards.'",
agent=outlook_agent,
expected_output="Email sent successfully to colleague@example.com"
)
# Run the task
crew = Crew(
agents=[outlook_agent],
tasks=[send_email_task]
)
crew.kickoff()
```
### Email Management and Search
```python
from crewai import Agent, Task, Crew
# Create an agent focused on email management
email_manager = Agent(
role="Email Manager",
goal="Retrieve, search, and organize email messages",
backstory="An AI assistant skilled in email organization and management.",
apps=['microsoft_outlook/get_messages']
)
# Task to search and retrieve emails
search_emails_task = Task(
description="Get the latest 20 unread emails and provide a summary of the most important ones.",
agent=email_manager,
expected_output="Summary of the most important unread emails with key details."
)
crew = Crew(
agents=[email_manager],
tasks=[search_emails_task]
)
crew.kickoff()
```
### Calendar and Contact Management
```python
from crewai import Agent, Task, Crew
# Create an agent for calendar and contact management
scheduler = Agent(
role="Calendar and Contact Manager",
goal="Manage calendar events and maintain contact information",
backstory="An AI assistant that handles scheduling and contact organization.",
apps=['microsoft_outlook/create_calendar_event', 'microsoft_outlook/get_calendar_events', 'microsoft_outlook/create_contact']
)
# Task to create a meeting and add a contact
schedule_task = Task(
description="Create a calendar event for tomorrow at 2 PM titled 'Team Meeting' with location 'Conference Room A', and create a new contact for 'John Smith' with email 'john.smith@example.com' and job title 'Project Manager'.",
agent=scheduler,
expected_output="Calendar event created and new contact added successfully."
)
crew = Crew(
agents=[scheduler],
tasks=[schedule_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Authentication Errors**
- Ensure your Microsoft account has the necessary permissions for mail, calendar, and contact access.
- Required scopes include: `Mail.Read`, `Mail.Send`, `Calendars.Read`, `Calendars.ReadWrite`, `Contacts.Read`, `Contacts.ReadWrite`.
- Verify that the OAuth connection includes all required scopes.
**Email Sending Issues**
- Ensure `to_recipients`, `subject`, and `body` are provided for `send_email`.
- Check that email addresses are properly formatted.
- Verify that the account has `Mail.Send` permissions.
**Calendar Event Creation**
- Ensure `subject`, `start_datetime`, and `end_datetime` are provided.
- Use proper ISO 8601 format for datetime fields (e.g., '2024-01-20T10:00:00').
- Verify timezone settings if events appear at incorrect times.
**Contact Management**
- For `create_contact`, ensure `displayName` is provided as it's required.
- When providing `emailAddresses`, use the proper object format with `address` and `name` properties.
**Search and Filter Issues**
- Use proper OData syntax for `filter` parameters.
- For date filters, use ISO 8601 format (e.g., "receivedDateTime ge '2024-01-01T00:00:00Z'").
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Microsoft Outlook integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,404 @@
---
title: Microsoft SharePoint Integration
description: "Site, list, and document management with Microsoft SharePoint integration for CrewAI."
icon: "folder-tree"
mode: "wide"
---
## Overview
Enable your agents to access and manage SharePoint sites, lists, and document libraries. Retrieve site information, manage list items, upload and organize files, and streamline your SharePoint workflows with AI-powered automation.
## Prerequisites
Before using the Microsoft SharePoint integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Microsoft 365 account with SharePoint access
- Connected your Microsoft account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Microsoft SharePoint Integration
### 1. Connect Your Microsoft Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Microsoft SharePoint** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for SharePoint sites and content access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="microsoft_sharepoint/get_sites">
**Description:** Get all SharePoint sites the user has access to.
**Parameters:**
- `search` (string, optional): Search query to filter sites
- `select` (string, optional): Select specific properties to return (e.g., 'displayName,id,webUrl')
- `filter` (string, optional): Filter results using OData syntax
- `expand` (string, optional): Expand related resources inline
- `top` (integer, optional): Number of items to return. Minimum: 1, Maximum: 999
- `skip` (integer, optional): Number of items to skip. Minimum: 0
- `orderby` (string, optional): Order results by specified properties (e.g., 'displayName desc')
</Accordion>
<Accordion title="microsoft_sharepoint/get_site">
**Description:** Get information about a specific SharePoint site.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `select` (string, optional): Select specific properties to return (e.g., 'displayName,id,webUrl,drives')
- `expand` (string, optional): Expand related resources inline (e.g., 'drives,lists')
</Accordion>
<Accordion title="microsoft_sharepoint/get_site_lists">
**Description:** Get all lists in a SharePoint site.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
</Accordion>
<Accordion title="microsoft_sharepoint/get_list">
**Description:** Get information about a specific list.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `list_id` (string, required): The ID of the list
</Accordion>
<Accordion title="microsoft_sharepoint/get_list_items">
**Description:** Get items from a SharePoint list.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `list_id` (string, required): The ID of the list
- `expand` (string, optional): Expand related data (e.g., 'fields')
</Accordion>
<Accordion title="microsoft_sharepoint/create_list_item">
**Description:** Create a new item in a SharePoint list.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `list_id` (string, required): The ID of the list
- `fields` (object, required): The field values for the new item
```json
{
"Title": "New Item Title",
"Description": "Item description",
"Status": "Active"
}
```
</Accordion>
<Accordion title="microsoft_sharepoint/update_list_item">
**Description:** Update an item in a SharePoint list.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `list_id` (string, required): The ID of the list
- `item_id` (string, required): The ID of the item to update
- `fields` (object, required): The field values to update
```json
{
"Title": "Updated Title",
"Status": "Completed"
}
```
</Accordion>
<Accordion title="microsoft_sharepoint/delete_list_item">
**Description:** Delete an item from a SharePoint list.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `list_id` (string, required): The ID of the list
- `item_id` (string, required): The ID of the item to delete
</Accordion>
<Accordion title="microsoft_sharepoint/upload_file_to_library">
**Description:** Upload a file to a SharePoint document library.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `file_path` (string, required): The path where to upload the file (e.g., 'folder/filename.txt')
- `content` (string, required): The file content to upload
</Accordion>
<Accordion title="microsoft_sharepoint/get_drive_items">
**Description:** Get files and folders from a SharePoint document library.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
</Accordion>
<Accordion title="microsoft_sharepoint/delete_drive_item">
**Description:** Delete a file or folder from SharePoint document library.
**Parameters:**
- `site_id` (string, required): The ID of the SharePoint site
- `item_id` (string, required): The ID of the file or folder to delete
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic SharePoint Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with SharePoint capabilities
sharepoint_agent = Agent(
role="SharePoint Manager",
goal="Manage SharePoint sites, lists, and documents efficiently",
backstory="An AI assistant specialized in SharePoint content management and collaboration.",
apps=['microsoft_sharepoint'] # All SharePoint actions will be available
)
# Task to organize SharePoint content
content_organization_task = Task(
description="List all accessible SharePoint sites and organize content by department",
agent=sharepoint_agent,
expected_output="SharePoint sites listed and content organized by department"
)
# Run the task
crew = Crew(
agents=[sharepoint_agent],
tasks=[content_organization_task]
)
crew.kickoff()
```
### List Management and Data Operations
```python
from crewai import Agent, Task, Crew
list_manager = Agent(
role="List Manager",
goal="Manage SharePoint lists and data efficiently",
backstory="An AI assistant that focuses on SharePoint list management and data operations.",
apps=[
'microsoft_sharepoint/get_site_lists',
'microsoft_sharepoint/get_list_items',
'microsoft_sharepoint/create_list_item',
'microsoft_sharepoint/update_list_item'
]
)
# Task to manage list data
list_management_task = Task(
description="Get all lists from the project site, review items, and update status for completed tasks",
agent=list_manager,
expected_output="SharePoint lists reviewed and task statuses updated"
)
crew = Crew(
agents=[list_manager],
tasks=[list_management_task]
)
crew.kickoff()
```
### Document Library Management
```python
from crewai import Agent, Task, Crew
document_manager = Agent(
role="Document Manager",
goal="Manage SharePoint document libraries and files",
backstory="An AI assistant that specializes in document organization and file management.",
apps=['microsoft_sharepoint']
)
# Task to manage documents
document_task = Task(
description="""
1. Get all files from the main document library
2. Upload new policy documents to the appropriate folders
3. Organize files by department and date
4. Remove outdated documents
""",
agent=document_manager,
expected_output="Document library organized with new files uploaded and outdated files removed"
)
crew = Crew(
agents=[document_manager],
tasks=[document_task]
)
crew.kickoff()
```
### Site Administration and Analysis
```python
from crewai import Agent, Task, Crew
site_administrator = Agent(
role="Site Administrator",
goal="Administer and analyze SharePoint sites",
backstory="An AI assistant that handles site administration and provides insights on site usage.",
apps=['microsoft_sharepoint']
)
# Task for site administration
admin_task = Task(
description="""
1. Get information about all accessible SharePoint sites
2. Analyze site structure and content organization
3. Identify sites with low activity or outdated content
4. Generate recommendations for site optimization
""",
agent=site_administrator,
expected_output="Site analysis completed with optimization recommendations"
)
crew = Crew(
agents=[site_administrator],
tasks=[admin_task]
)
crew.kickoff()
```
### Automated Content Workflows
```python
from crewai import Agent, Task, Crew
workflow_automator = Agent(
role="Workflow Automator",
goal="Automate SharePoint content workflows and processes",
backstory="An AI assistant that automates complex SharePoint workflows and content management processes.",
apps=['microsoft_sharepoint']
)
# Complex workflow automation task
automation_task = Task(
description="""
1. Monitor project lists across multiple sites
2. Create status reports based on list data
3. Upload reports to designated document libraries
4. Update project tracking lists with completion status
5. Archive completed project documents
6. Send notifications for overdue items
""",
agent=workflow_automator,
expected_output="Automated workflow completed with status reports generated and project tracking updated"
)
crew = Crew(
agents=[workflow_automator],
tasks=[automation_task]
)
crew.kickoff()
```
### Data Integration and Reporting
```python
from crewai import Agent, Task, Crew
data_integrator = Agent(
role="Data Integrator",
goal="Integrate and analyze data across SharePoint sites and lists",
backstory="An AI assistant that specializes in data integration and cross-site analysis.",
apps=['microsoft_sharepoint']
)
# Task for data integration
integration_task = Task(
description="""
1. Get data from multiple SharePoint lists across different sites
2. Consolidate information into comprehensive reports
3. Create new list items with aggregated data
4. Upload analytical reports to executive document library
5. Update dashboard lists with key metrics
""",
agent=data_integrator,
expected_output="Data integrated across sites with comprehensive reports and updated dashboards"
)
crew = Crew(
agents=[data_integrator],
tasks=[integration_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Permission Errors**
- Ensure your Microsoft account has appropriate permissions for SharePoint sites
- Verify that the OAuth connection includes required scopes (Sites.Read.All, Sites.ReadWrite.All)
- Check that you have access to the specific sites and lists you're trying to access
**Site and List ID Issues**
- Verify that site IDs and list IDs are correct and properly formatted
- Ensure that sites and lists exist and are accessible to your account
- Use the get_sites and get_site_lists actions to discover valid IDs
**Field and Schema Issues**
- Ensure field names match exactly with the SharePoint list schema
- Verify that required fields are included when creating or updating list items
- Check that field types and values are compatible with the list column definitions
**File Upload Issues**
- Ensure file paths are properly formatted and don't contain invalid characters
- Verify that you have write permissions to the target document library
- Check that file content is properly encoded for upload
**OData Query Issues**
- Use proper OData syntax for filter, select, expand, and orderby parameters
- Verify that property names used in queries exist in the target resources
- Test simple queries before building complex filter expressions
**Pagination and Performance**
- Use top and skip parameters appropriately for large result sets
- Implement proper pagination for lists with many items
- Consider using select parameters to return only needed properties
**Document Library Operations**
- Ensure you have proper permissions for document library operations
- Verify that drive item IDs are correct when deleting files or folders
- Check that file paths don't conflict with existing content
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Microsoft SharePoint integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,228 @@
---
title: Microsoft Teams Integration
description: "Team collaboration and communication with Microsoft Teams integration for CrewAI."
icon: "users"
mode: "wide"
---
## Overview
Enable your agents to access Teams data, send messages, create meetings, and manage channels. Automate team communication, schedule meetings, retrieve messages, and streamline your collaboration workflows with AI-powered automation.
## Prerequisites
Before using the Microsoft Teams integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Microsoft account with Teams access
- Connected your Microsoft account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Microsoft Teams Integration
### 1. Connect Your Microsoft Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Microsoft Teams** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for Teams access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="microsoft_teams/get_teams">
**Description:** Get all teams the user is a member of.
**Parameters:**
- No parameters required.
</Accordion>
<Accordion title="microsoft_teams/get_channels">
**Description:** Get channels in a specific team.
**Parameters:**
- `team_id` (string, required): The ID of the team.
</Accordion>
<Accordion title="microsoft_teams/send_message">
**Description:** Send a message to a Teams channel.
**Parameters:**
- `team_id` (string, required): The ID of the team.
- `channel_id` (string, required): The ID of the channel.
- `message` (string, required): The message content.
- `content_type` (string, optional): Content type (html or text). Enum: `html`, `text`. Default is `text`.
</Accordion>
<Accordion title="microsoft_teams/get_messages">
**Description:** Get messages from a Teams channel.
**Parameters:**
- `team_id` (string, required): The ID of the team.
- `channel_id` (string, required): The ID of the channel.
- `top` (integer, optional): Number of messages to retrieve (max 50). Default is `20`.
</Accordion>
<Accordion title="microsoft_teams/create_meeting">
**Description:** Create a Teams meeting.
**Parameters:**
- `subject` (string, required): Meeting subject/title.
- `startDateTime` (string, required): Meeting start time (ISO 8601 format with timezone).
- `endDateTime` (string, required): Meeting end time (ISO 8601 format with timezone).
</Accordion>
<Accordion title="microsoft_teams/search_online_meetings_by_join_url">
**Description:** Search online meetings by Join Web URL.
**Parameters:**
- `join_web_url` (string, required): The join web URL of the meeting to search for.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Microsoft Teams Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Microsoft Teams capabilities
teams_agent = Agent(
role="Teams Coordinator",
goal="Manage Teams communication and meetings efficiently",
backstory="An AI assistant specialized in Microsoft Teams operations and team collaboration.",
apps=['microsoft_teams'] # All Teams actions will be available
)
# Task to list teams and channels
explore_teams_task = Task(
description="List all teams I'm a member of and then get the channels for the first team.",
agent=teams_agent,
expected_output="List of teams and channels displayed."
)
# Run the task
crew = Crew(
agents=[teams_agent],
tasks=[explore_teams_task]
)
crew.kickoff()
```
### Messaging and Communication
```python
from crewai import Agent, Task, Crew
# Create an agent focused on messaging
messenger = Agent(
role="Teams Messenger",
goal="Send and retrieve messages in Teams channels",
backstory="An AI assistant skilled in team communication and message management.",
apps=['microsoft_teams/send_message', 'microsoft_teams/get_messages']
)
# Task to send a message and retrieve recent messages
messaging_task = Task(
description="Send a message 'Hello team! This is an automated update from our AI assistant.' to the General channel of team 'your_team_id', then retrieve the last 10 messages from that channel.",
agent=messenger,
expected_output="Message sent successfully and recent messages retrieved."
)
crew = Crew(
agents=[messenger],
tasks=[messaging_task]
)
crew.kickoff()
```
### Meeting Management
```python
from crewai import Agent, Task, Crew
# Create an agent for meeting management
meeting_scheduler = Agent(
role="Meeting Scheduler",
goal="Create and manage Teams meetings",
backstory="An AI assistant that handles meeting scheduling and organization.",
apps=['microsoft_teams/create_meeting', 'microsoft_teams/search_online_meetings_by_join_url']
)
# Task to create a meeting
schedule_meeting_task = Task(
description="Create a Teams meeting titled 'Weekly Team Sync' scheduled for tomorrow at 10:00 AM lasting for 1 hour (use proper ISO 8601 format with timezone).",
agent=meeting_scheduler,
expected_output="Teams meeting created successfully with meeting details."
)
crew = Crew(
agents=[meeting_scheduler],
tasks=[schedule_meeting_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Authentication Errors**
- Ensure your Microsoft account has the necessary permissions for Teams access.
- Required scopes include: `Team.ReadBasic.All`, `Channel.ReadBasic.All`, `ChannelMessage.Send`, `ChannelMessage.Read.All`, `OnlineMeetings.ReadWrite`, `OnlineMeetings.Read`.
- Verify that the OAuth connection includes all required scopes.
**Team and Channel Access**
- Ensure you are a member of the teams you're trying to access.
- Double-check team IDs and channel IDs for correctness.
- Team and channel IDs can be obtained using the `get_teams` and `get_channels` actions.
**Message Sending Issues**
- Ensure `team_id`, `channel_id`, and `message` are provided for `send_message`.
- Verify that you have permissions to send messages to the specified channel.
- Choose appropriate `content_type` (text or html) based on your message format.
**Meeting Creation**
- Ensure `subject`, `startDateTime`, and `endDateTime` are provided.
- Use proper ISO 8601 format with timezone for datetime fields (e.g., '2024-01-20T10:00:00-08:00').
- Verify that the meeting times are in the future.
**Message Retrieval Limitations**
- The `get_messages` action can retrieve a maximum of 50 messages per request.
- Messages are returned in reverse chronological order (newest first).
**Meeting Search**
- For `search_online_meetings_by_join_url`, ensure the join URL is exact and properly formatted.
- The URL should be the complete Teams meeting join URL.
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Microsoft Teams integration setup or troubleshooting.
</Card>

View File

@@ -0,0 +1,208 @@
---
title: Microsoft Word Integration
description: "Document creation and management with Microsoft Word integration for CrewAI."
icon: "file-word"
mode: "wide"
---
## Overview
Enable your agents to create, read, and manage Word documents and text files in OneDrive or SharePoint. Automate document creation, retrieve content, manage document properties, and streamline your document workflows with AI-powered automation.
## Prerequisites
Before using the Microsoft Word integration, ensure you have:
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Microsoft account with Word and OneDrive/SharePoint access
- Connected your Microsoft account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
## Setting Up Microsoft Word Integration
### 1. Connect Your Microsoft Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Microsoft Word** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for file access
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="microsoft_word/get_documents">
**Description:** Get all Word documents from OneDrive or SharePoint.
**Parameters:**
- `select` (string, optional): Select specific properties to return.
- `filter` (string, optional): Filter results using OData syntax.
- `expand` (string, optional): Expand related resources inline.
- `top` (integer, optional): Number of items to return (min 1, max 999).
- `orderby` (string, optional): Order results by specified properties.
</Accordion>
<Accordion title="microsoft_word/create_text_document">
**Description:** Create a text document (.txt) with content. RECOMMENDED for programmatic content creation that needs to be readable and editable.
**Parameters:**
- `file_name` (string, required): Name of the text document (should end with .txt).
- `content` (string, optional): Text content for the document. Default is "This is a new text document created via API."
</Accordion>
<Accordion title="microsoft_word/get_document_content">
**Description:** Get the content of a document (works best with text files).
**Parameters:**
- `file_id` (string, required): The ID of the document.
</Accordion>
<Accordion title="microsoft_word/get_document_properties">
**Description:** Get properties and metadata of a document.
**Parameters:**
- `file_id` (string, required): The ID of the document.
</Accordion>
<Accordion title="microsoft_word/delete_document">
**Description:** Delete a document.
**Parameters:**
- `file_id` (string, required): The ID of the document to delete.
</Accordion>
</AccordionGroup>
## Usage Examples
### Basic Microsoft Word Agent Setup
```python
from crewai import Agent, Task, Crew
# Create an agent with Microsoft Word capabilities
word_agent = Agent(
role="Document Manager",
goal="Manage Word documents and text files efficiently",
backstory="An AI assistant specialized in Microsoft Word document operations and content management.",
apps=['microsoft_word'] # All Word actions will be available
)
# Task to create a new text document
create_doc_task = Task(
description="Create a new text document named 'meeting_notes.txt' with content 'Meeting Notes from January 2024: Key discussion points and action items.'",
agent=word_agent,
expected_output="New text document 'meeting_notes.txt' created successfully."
)
# Run the task
crew = Crew(
agents=[word_agent],
tasks=[create_doc_task]
)
crew.kickoff()
```
### Reading and Managing Documents
```python
from crewai import Agent, Task, Crew
# Create an agent focused on document operations
document_reader = Agent(
role="Document Reader",
goal="Retrieve and analyze document content and properties",
backstory="An AI assistant skilled in reading and analyzing document content.",
apps=['microsoft_word/get_documents', 'microsoft_word/get_document_content', 'microsoft_word/get_document_properties']
)
# Task to list and read documents
read_docs_task = Task(
description="List all Word documents in my OneDrive, then get the content and properties of the first document found.",
agent=document_reader,
expected_output="List of documents with content and properties of the first document."
)
crew = Crew(
agents=[document_reader],
tasks=[read_docs_task]
)
crew.kickoff()
```
### Document Cleanup and Organization
```python
from crewai import Agent, Task, Crew
# Create an agent for document management
document_organizer = Agent(
role="Document Organizer",
goal="Organize and clean up document collections",
backstory="An AI assistant that helps maintain organized document libraries.",
apps=['microsoft_word/get_documents', 'microsoft_word/get_document_properties', 'microsoft_word/delete_document']
)
# Task to organize documents
organize_task = Task(
description="List all documents, check their properties, and identify any documents that might be duplicates or outdated for potential cleanup.",
agent=document_organizer,
expected_output="Analysis of document library with recommendations for organization."
)
crew = Crew(
agents=[document_organizer],
tasks=[organize_task]
)
crew.kickoff()
```
## Troubleshooting
### Common Issues
**Authentication Errors**
- Ensure your Microsoft account has the necessary permissions for file access (e.g., `Files.Read.All`, `Files.ReadWrite.All`).
- Verify that the OAuth connection includes all required scopes.
**File Creation Issues**
- When creating text documents, ensure the `file_name` ends with `.txt` extension.
- Verify that you have write permissions to the target location (OneDrive/SharePoint).
**Document Access Issues**
- Double-check document IDs for correctness when accessing specific documents.
- Ensure the referenced documents exist and are accessible.
- Note that this integration works best with text files (.txt) for content operations.
**Content Retrieval Limitations**
- The `get_document_content` action works best with text files (.txt).
- For complex Word documents (.docx), consider using the document properties action to get metadata.
### Getting Help
<Card title="Need Help?" icon="headset" href="mailto:support@crewai.com">
Contact our support team for assistance with Microsoft Word integration setup or troubleshooting.
</Card>

View File

@@ -1,19 +1,19 @@
---
title: Notion Integration
description: "Page and database management with Notion integration for CrewAI."
description: "User management and commenting with Notion integration for CrewAI."
icon: "book"
mode: "wide"
---
## Overview
Enable your agents to manage pages, databases, and content through Notion. Create and update pages, manage content blocks, organize knowledge bases, and streamline your documentation workflows with AI-powered automation.
Enable your agents to manage users and create comments through Notion. Access workspace user information and create comments on pages and discussions, streamlining your collaboration workflows with AI-powered automation.
## Prerequisites
Before using the Notion integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Notion account with appropriate workspace permissions
- Connected your Notion account through the [Integrations page](https://app.crewai.com/crewai_plus/connectors)
@@ -21,11 +21,11 @@ Before using the Notion integration, ensure you have:
### 1. Connect Your Notion Account
1. Navigate to [CrewAI AMP Integrations](https://app.crewai.com/crewai_plus/connectors)
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Notion** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for page and database management
5. Copy your Enterprise Token from [Account Settings](https://app.crewai.com/crewai_plus/settings/account)
4. Grant the necessary permissions for user access and comment creation
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
@@ -33,245 +33,69 @@ Before using the Notion integration, ensure you have:
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Actions
<AccordionGroup>
<Accordion title="NOTION_CREATE_PAGE">
**Description:** Create a page in Notion.
<Accordion title="notion/list_users">
**Description:** List all users in the workspace.
**Parameters:**
- `parent` (object, required): Parent - The parent page or database where the new page is inserted, represented as a JSON object with a page_id or database_id key.
- `page_size` (integer, optional): Number of items returned in the response. Minimum: 1, Maximum: 100, Default: 100
- `start_cursor` (string, optional): Cursor for pagination. Return results after this cursor.
</Accordion>
<Accordion title="notion/get_user">
**Description:** Retrieve a specific user by ID.
**Parameters:**
- `user_id` (string, required): The ID of the user to retrieve.
</Accordion>
<Accordion title="notion/create_comment">
**Description:** Create a comment on a page or discussion.
**Parameters:**
- `parent` (object, required): The parent page or discussion to comment on.
```json
{
"database_id": "DATABASE_ID"
"type": "page_id",
"page_id": "PAGE_ID_HERE"
}
```
- `properties` (object, required): Properties - The values of the page's properties. If the parent is a database, then the schema must match the parent database's properties.
or
```json
{
"title": [
{
"text": {
"content": "My Page"
}
}
]
"type": "discussion_id",
"discussion_id": "DISCUSSION_ID_HERE"
}
```
- `icon` (object, required): Icon - The page icon.
```json
{
"emoji": "🥬"
}
```
- `children` (object, optional): Children - Content blocks to add to the page.
- `rich_text` (array, required): The rich text content of the comment.
```json
[
{
"object": "block",
"type": "heading_2",
"heading_2": {
"rich_text": [
{
"type": "text",
"text": {
"content": "Lacinato kale"
}
}
]
"type": "text",
"text": {
"content": "This is my comment text"
}
}
]
```
- `cover` (object, optional): Cover - The page cover image.
```json
{
"external": {
"url": "https://upload.wikimedia.org/wikipedia/commons/6/62/Tuscankale.jpg"
}
}
```
</Accordion>
<Accordion title="NOTION_UPDATE_PAGE">
**Description:** Update a page in Notion.
**Parameters:**
- `pageId` (string, required): Page ID - Specify the ID of the Page to Update. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
- `icon` (object, required): Icon - The page icon.
```json
{
"emoji": "🥬"
}
```
- `archived` (boolean, optional): Archived - Whether the page is archived (deleted). Set to true to archive a page. Set to false to un-archive (restore) a page.
- `properties` (object, optional): Properties - The property values to update for the page.
```json
{
"title": [
{
"text": {
"content": "My Updated Page"
}
}
]
}
```
- `cover` (object, optional): Cover - The page cover image.
```json
{
"external": {
"url": "https://upload.wikimedia.org/wikipedia/commons/6/62/Tuscankale.jpg"
}
}
```
</Accordion>
<Accordion title="NOTION_GET_PAGE_BY_ID">
**Description:** Get a page by ID in Notion.
**Parameters:**
- `pageId` (string, required): Page ID - Specify the ID of the Page to Get. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
</Accordion>
<Accordion title="NOTION_ARCHIVE_PAGE">
**Description:** Archive a page in Notion.
**Parameters:**
- `pageId` (string, required): Page ID - Specify the ID of the Page to Archive. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
</Accordion>
<Accordion title="NOTION_SEARCH_PAGES">
**Description:** Search pages in Notion using filters.
**Parameters:**
- `searchByTitleFilterSearch` (object, optional): A filter in disjunctive normal form - OR of AND groups of single conditions.
```json
{
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{
"field": "query",
"operator": "$stringExactlyMatches",
"value": "meeting notes"
}
]
}
]
}
```
Available fields: `query`, `filter.value`, `direction`, `page_size`
</Accordion>
<Accordion title="NOTION_GET_PAGE_CONTENT">
**Description:** Get page content (blocks) in Notion.
**Parameters:**
- `blockId` (string, required): Page ID - Specify a Block or Page ID to receive all of its block's children in order. (example: "59833787-2cf9-4fdf-8782-e53db20768a5").
</Accordion>
<Accordion title="NOTION_UPDATE_BLOCK">
**Description:** Update a block in Notion.
**Parameters:**
- `blockId` (string, required): Block ID - Specify the ID of the Block to Update. (example: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
- `archived` (boolean, optional): Archived - Set to true to archive (delete) a block. Set to false to un-archive (restore) a block.
- `paragraph` (object, optional): Paragraph content.
```json
{
"rich_text": [
{
"type": "text",
"text": {
"content": "Lacinato kale",
"link": null
}
}
],
"color": "default"
}
```
- `image` (object, optional): Image block.
```json
{
"type": "external",
"external": {
"url": "https://website.domain/images/image.png"
}
}
```
- `bookmark` (object, optional): Bookmark block.
```json
{
"caption": [],
"url": "https://companywebsite.com"
}
```
- `code` (object, optional): Code block.
```json
{
"rich_text": [
{
"type": "text",
"text": {
"content": "const a = 3"
}
}
],
"language": "javascript"
}
```
- `pdf` (object, optional): PDF block.
```json
{
"type": "external",
"external": {
"url": "https://website.domain/files/doc.pdf"
}
}
```
- `table` (object, optional): Table block.
```json
{
"table_width": 2,
"has_column_header": false,
"has_row_header": false
}
```
- `tableOfContent` (object, optional): Table of Contents block.
```json
{
"color": "default"
}
```
- `additionalFields` (object, optional): Additional block types.
```json
{
"child_page": {
"title": "Lacinato kale"
},
"child_database": {
"title": "My database"
}
}
```
</Accordion>
<Accordion title="NOTION_GET_BLOCK_BY_ID">
**Description:** Get a block by ID in Notion.
**Parameters:**
- `blockId` (string, required): Block ID - Specify the ID of the Block to Get. (example: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
</Accordion>
<Accordion title="NOTION_DELETE_BLOCK">
**Description:** Delete a block in Notion.
**Parameters:**
- `blockId` (string, required): Block ID - Specify the ID of the Block to Delete. (example: "9bc30ad4-9373-46a5-84ab-0a7845ee52e6").
</Accordion>
</AccordionGroup>
@@ -281,32 +105,26 @@ uv add crewai-tools
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Notion tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Notion capabilities
notion_agent = Agent(
role="Documentation Manager",
goal="Manage documentation and knowledge base in Notion efficiently",
backstory="An AI assistant specialized in content management and documentation.",
tools=[enterprise_tools]
role="Workspace Manager",
goal="Manage workspace users and facilitate collaboration through comments",
backstory="An AI assistant specialized in user management and team collaboration.",
apps=['notion'] # All Notion actions will be available
)
# Task to create a meeting notes page
create_notes_task = Task(
description="Create a new meeting notes page in the team database with today's date and agenda items",
# Task to list workspace users
user_management_task = Task(
description="List all users in the workspace and provide a summary of team members",
agent=notion_agent,
expected_output="Meeting notes page created successfully with structured content"
expected_output="Complete list of workspace users with their details"
)
# Run the task
crew = Crew(
agents=[notion_agent],
tasks=[create_notes_task]
tasks=[user_management_task]
)
crew.kickoff()
@@ -315,144 +133,116 @@ crew.kickoff()
### Filtering Specific Notion Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Notion tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["notion_create_page", "notion_update_block", "notion_search_pages"]
comment_manager = Agent(
role="Comment Manager",
goal="Create and manage comments on Notion pages",
backstory="An AI assistant that focuses on facilitating discussions through comments.",
apps=['notion/create_comment']
)
content_manager = Agent(
role="Content Manager",
goal="Create and manage content pages efficiently",
backstory="An AI assistant that focuses on content creation and management.",
tools=enterprise_tools
)
# Task to manage content workflow
content_workflow = Task(
description="Create a new project documentation page and add structured content blocks for requirements and specifications",
agent=content_manager,
expected_output="Project documentation created with organized content sections"
# Task to create comments on pages
comment_task = Task(
description="Create a summary comment on the project status page with key updates",
agent=comment_manager,
expected_output="Comment created successfully with project status updates"
)
crew = Crew(
agents=[content_manager],
tasks=[content_workflow]
agents=[comment_manager],
tasks=[comment_task]
)
crew.kickoff()
```
### Knowledge Base Management
### User Information and Team Management
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
team_coordinator = Agent(
role="Team Coordinator",
goal="Coordinate team activities and manage user information",
backstory="An AI assistant that helps coordinate team activities and manages user information.",
apps=['notion']
)
knowledge_curator = Agent(
role="Knowledge Curator",
goal="Curate and organize knowledge base content in Notion",
backstory="An experienced knowledge manager who organizes and maintains comprehensive documentation.",
tools=[enterprise_tools]
)
# Task to curate knowledge base
curation_task = Task(
# Task to coordinate team activities
coordination_task = Task(
description="""
1. Search for existing documentation pages related to our new product feature
2. Create a comprehensive feature documentation page with proper structure
3. Add code examples, images, and links to related resources
4. Update existing pages with cross-references to the new documentation
1. List all users in the workspace
2. Get detailed information for specific team members
3. Create comments on relevant pages to notify team members about updates
""",
agent=knowledge_curator,
expected_output="Feature documentation created and integrated with existing knowledge base"
agent=team_coordinator,
expected_output="Team coordination completed with user information gathered and notifications sent"
)
crew = Crew(
agents=[knowledge_curator],
tasks=[curation_task]
agents=[team_coordinator],
tasks=[coordination_task]
)
crew.kickoff()
```
### Content Structure and Organization
### Collaboration and Communication
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
collaboration_facilitator = Agent(
role="Collaboration Facilitator",
goal="Facilitate team collaboration through comments and user management",
backstory="An AI assistant that specializes in team collaboration and communication.",
apps=['notion']
)
content_organizer = Agent(
role="Content Organizer",
goal="Organize and structure content blocks for optimal readability",
backstory="An AI assistant that specializes in content structure and user experience.",
tools=[enterprise_tools]
)
# Task to organize content structure
organization_task = Task(
# Task to facilitate collaboration
collaboration_task = Task(
description="""
1. Get content from existing project pages
2. Analyze the structure and identify improvement opportunities
3. Update content blocks to use proper headings, tables, and formatting
4. Add table of contents and improve navigation between related pages
5. Create templates for future documentation consistency
1. Identify active users in the workspace
2. Create contextual comments on project pages to facilitate discussions
3. Provide status updates and feedback through comments
""",
agent=content_organizer,
expected_output="Content reorganized with improved structure and navigation"
agent=collaboration_facilitator,
expected_output="Collaboration facilitated with comments created and team members notified"
)
crew = Crew(
agents=[content_organizer],
tasks=[organization_task]
agents=[collaboration_facilitator],
tasks=[collaboration_task]
)
crew.kickoff()
```
### Automated Documentation Workflows
### Automated Team Communication
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
communication_automator = Agent(
role="Communication Automator",
goal="Automate team communication and user management workflows",
backstory="An AI assistant that automates communication workflows and manages user interactions.",
apps=['notion']
)
doc_automator = Agent(
role="Documentation Automator",
goal="Automate documentation workflows and maintenance",
backstory="An AI assistant that automates repetitive documentation tasks.",
tools=[enterprise_tools]
)
# Complex documentation automation task
# Complex communication automation task
automation_task = Task(
description="""
1. Search for pages that haven't been updated in the last 30 days
2. Review and update outdated content blocks
3. Create weekly team update pages with consistent formatting
4. Add status indicators and progress tracking to project pages
5. Generate monthly documentation health reports
6. Archive completed project pages and organize them in archive sections
1. List all workspace users and identify team roles
2. Get specific user information for project stakeholders
3. Create automated status update comments on key project pages
4. Facilitate team communication through targeted comments
""",
agent=doc_automator,
expected_output="Documentation automated with updated content, weekly reports, and organized archives"
agent=communication_automator,
expected_output="Automated communication workflow completed with user management and comments"
)
crew = Crew(
agents=[doc_automator],
agents=[communication_automator],
tasks=[automation_task]
)
@@ -464,44 +254,29 @@ crew.kickoff()
### Common Issues
**Permission Errors**
- Ensure your Notion account has edit access to the target workspace
- Verify that the OAuth connection includes required scopes for Notion API
- Check that pages and databases are shared with the authenticated integration
- Ensure your Notion account has appropriate permissions to read user information
- Verify that the OAuth connection includes required scopes for user access and comment creation
- Check that you have permissions to comment on the target pages or discussions
**Invalid Page and Block IDs**
- Double-check page IDs and block IDs for correct UUID format
- Ensure referenced pages and blocks exist and are accessible
- Verify that parent page or database IDs are valid when creating new pages
**User Access Issues**
- Ensure you have workspace admin permissions to list all users
- Verify that user IDs are correct and users exist in the workspace
- Check that the workspace allows API access to user information
**Property Schema Issues**
- Ensure page properties match the database schema when creating pages in databases
- Verify that property names and types are correct for the target database
- Check that required properties are included when creating or updating pages
**Comment Creation Issues**
- Verify that page IDs or discussion IDs are correct and accessible
- Ensure that rich text content follows Notion's API format specifications
- Check that you have comment permissions on the target pages or discussions
**Content Block Structure**
- Ensure block content follows Notion's rich text format specifications
- Verify that nested block structures are properly formatted
- Check that media URLs are accessible and properly formatted
**API Rate Limits**
- Be mindful of Notion's API rate limits when making multiple requests
- Implement appropriate delays between requests if needed
- Consider pagination for large user lists
**Search and Filter Issues**
- Ensure search queries are properly formatted and not empty
- Use valid field names in filter formulas: `query`, `filter.value`, `direction`, `page_size`
- Test simple searches before building complex filter conditions
**Parent-Child Relationships**
- Verify that parent page or database exists before creating child pages
- Ensure proper permissions exist for the parent container
- Check that database schemas allow the properties you're trying to set
**Rich Text and Media Content**
- Ensure URLs for external images, PDFs, and bookmarks are accessible
- Verify that rich text formatting follows Notion's API specifications
- Check that code block language types are supported by Notion
**Archive and Deletion Operations**
- Understand the difference between archiving (reversible) and deleting (permanent)
- Verify that you have permissions to archive or delete the target content
- Be cautious with bulk operations that might affect multiple pages or blocks
**Parent Object Specification**
- Ensure parent object type is correctly specified (page_id or discussion_id)
- Verify that the parent page or discussion exists and is accessible
- Check that the parent object ID format is correct
### Getting Help

View File

@@ -13,16 +13,48 @@ Enable your agents to manage customer relationships, sales processes, and data t
Before using the Salesforce integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Salesforce account with appropriate permissions
- Connected your Salesforce account through the [Integrations page](https://app.crewai.com/integrations)
## Setting Up Salesforce Integration
### 1. Connect Your Salesforce Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Salesforce** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for CRM and sales management
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Tools
### **Record Management**
<AccordionGroup>
<Accordion title="SALESFORCE_CREATE_RECORD_CONTACT">
<Accordion title="salesforce/create_record_contact">
**Description:** Create a new Contact record in Salesforce.
**Parameters:**
@@ -35,7 +67,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Contact fields
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_LEAD">
<Accordion title="salesforce/create_record_lead">
**Description:** Create a new Lead record in Salesforce.
**Parameters:**
@@ -51,7 +83,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Lead fields
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_OPPORTUNITY">
<Accordion title="salesforce/create_record_opportunity">
**Description:** Create a new Opportunity record in Salesforce.
**Parameters:**
@@ -66,7 +98,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Opportunity fields
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_TASK">
<Accordion title="salesforce/create_record_task">
**Description:** Create a new Task record in Salesforce.
**Parameters:**
@@ -84,7 +116,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Task fields
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_ACCOUNT">
<Accordion title="salesforce/create_record_account">
**Description:** Create a new Account record in Salesforce.
**Parameters:**
@@ -96,7 +128,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Account fields
</Accordion>
<Accordion title="SALESFORCE_CREATE_RECORD_ANY">
<Accordion title="salesforce/create_record_any">
**Description:** Create a record of any object type in Salesforce.
**Note:** This is a flexible tool for creating records of custom or unknown object types.
@@ -106,7 +138,7 @@ Before using the Salesforce integration, ensure you have:
### **Record Updates**
<AccordionGroup>
<Accordion title="SALESFORCE_UPDATE_RECORD_CONTACT">
<Accordion title="salesforce/update_record_contact">
**Description:** Update an existing Contact record in Salesforce.
**Parameters:**
@@ -120,7 +152,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Contact fields
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_LEAD">
<Accordion title="salesforce/update_record_lead">
**Description:** Update an existing Lead record in Salesforce.
**Parameters:**
@@ -137,7 +169,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Lead fields
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_OPPORTUNITY">
<Accordion title="salesforce/update_record_opportunity">
**Description:** Update an existing Opportunity record in Salesforce.
**Parameters:**
@@ -153,7 +185,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Opportunity fields
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_TASK">
<Accordion title="salesforce/update_record_task">
**Description:** Update an existing Task record in Salesforce.
**Parameters:**
@@ -171,7 +203,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Task fields
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_ACCOUNT">
<Accordion title="salesforce/update_record_account">
**Description:** Update an existing Account record in Salesforce.
**Parameters:**
@@ -184,7 +216,7 @@ Before using the Salesforce integration, ensure you have:
- `additionalFields` (object, optional): Additional fields in JSON format for custom Account fields
</Accordion>
<Accordion title="SALESFORCE_UPDATE_RECORD_ANY">
<Accordion title="salesforce/update_record_any">
**Description:** Update a record of any object type in Salesforce.
**Note:** This is a flexible tool for updating records of custom or unknown object types.
@@ -194,42 +226,42 @@ Before using the Salesforce integration, ensure you have:
### **Record Retrieval**
<AccordionGroup>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_CONTACT">
<Accordion title="salesforce/get_record_by_id_contact">
**Description:** Get a Contact record by its ID.
**Parameters:**
- `recordId` (string, required): Record ID of the Contact
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_LEAD">
<Accordion title="salesforce/get_record_by_id_lead">
**Description:** Get a Lead record by its ID.
**Parameters:**
- `recordId` (string, required): Record ID of the Lead
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_OPPORTUNITY">
<Accordion title="salesforce/get_record_by_id_opportunity">
**Description:** Get an Opportunity record by its ID.
**Parameters:**
- `recordId` (string, required): Record ID of the Opportunity
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_TASK">
<Accordion title="salesforce/get_record_by_id_task">
**Description:** Get a Task record by its ID.
**Parameters:**
- `recordId` (string, required): Record ID of the Task
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_ACCOUNT">
<Accordion title="salesforce/get_record_by_id_account">
**Description:** Get an Account record by its ID.
**Parameters:**
- `recordId` (string, required): Record ID of the Account
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_ID_ANY">
<Accordion title="salesforce/get_record_by_id_any">
**Description:** Get a record of any object type by its ID.
**Parameters:**
@@ -241,7 +273,7 @@ Before using the Salesforce integration, ensure you have:
### **Record Search**
<AccordionGroup>
<Accordion title="SALESFORCE_SEARCH_RECORDS_CONTACT">
<Accordion title="salesforce/search_records_contact">
**Description:** Search for Contact records with advanced filtering.
**Parameters:**
@@ -252,7 +284,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_LEAD">
<Accordion title="salesforce/search_records_lead">
**Description:** Search for Lead records with advanced filtering.
**Parameters:**
@@ -263,7 +295,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_OPPORTUNITY">
<Accordion title="salesforce/search_records_opportunity">
**Description:** Search for Opportunity records with advanced filtering.
**Parameters:**
@@ -274,7 +306,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_TASK">
<Accordion title="salesforce/search_records_task">
**Description:** Search for Task records with advanced filtering.
**Parameters:**
@@ -285,7 +317,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_ACCOUNT">
<Accordion title="salesforce/search_records_account">
**Description:** Search for Account records with advanced filtering.
**Parameters:**
@@ -296,7 +328,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_SEARCH_RECORDS_ANY">
<Accordion title="salesforce/search_records_any">
**Description:** Search for records of any object type.
**Parameters:**
@@ -310,7 +342,7 @@ Before using the Salesforce integration, ensure you have:
### **List View Retrieval**
<AccordionGroup>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_CONTACT">
<Accordion title="salesforce/get_record_by_view_id_contact">
**Description:** Get Contact records from a specific List View.
**Parameters:**
@@ -318,7 +350,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_LEAD">
<Accordion title="salesforce/get_record_by_view_id_lead">
**Description:** Get Lead records from a specific List View.
**Parameters:**
@@ -326,7 +358,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_OPPORTUNITY">
<Accordion title="salesforce/get_record_by_view_id_opportunity">
**Description:** Get Opportunity records from a specific List View.
**Parameters:**
@@ -334,7 +366,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_TASK">
<Accordion title="salesforce/get_record_by_view_id_task">
**Description:** Get Task records from a specific List View.
**Parameters:**
@@ -342,7 +374,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_ACCOUNT">
<Accordion title="salesforce/get_record_by_view_id_account">
**Description:** Get Account records from a specific List View.
**Parameters:**
@@ -350,7 +382,7 @@ Before using the Salesforce integration, ensure you have:
- `paginationParameters` (object, optional): Pagination settings with pageCursor
</Accordion>
<Accordion title="SALESFORCE_GET_RECORD_BY_VIEW_ID_ANY">
<Accordion title="salesforce/get_record_by_view_id_any">
**Description:** Get records of any object type from a specific List View.
**Parameters:**
@@ -363,7 +395,7 @@ Before using the Salesforce integration, ensure you have:
### **Custom Fields**
<AccordionGroup>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_CONTACT">
<Accordion title="salesforce/create_custom_field_contact">
**Description:** Deploy custom fields for Contact objects.
**Parameters:**
@@ -379,7 +411,7 @@ Before using the Salesforce integration, ensure you have:
- `defaultFieldValue` (string, optional): Default field value
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_LEAD">
<Accordion title="salesforce/create_custom_field_lead">
**Description:** Deploy custom fields for Lead objects.
**Parameters:**
@@ -395,7 +427,7 @@ Before using the Salesforce integration, ensure you have:
- `defaultFieldValue` (string, optional): Default field value
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_OPPORTUNITY">
<Accordion title="salesforce/create_custom_field_opportunity">
**Description:** Deploy custom fields for Opportunity objects.
**Parameters:**
@@ -411,7 +443,7 @@ Before using the Salesforce integration, ensure you have:
- `defaultFieldValue` (string, optional): Default field value
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_TASK">
<Accordion title="salesforce/create_custom_field_task">
**Description:** Deploy custom fields for Task objects.
**Parameters:**
@@ -427,7 +459,7 @@ Before using the Salesforce integration, ensure you have:
- `defaultFieldValue` (string, optional): Default field value
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_ACCOUNT">
<Accordion title="salesforce/create_custom_field_account">
**Description:** Deploy custom fields for Account objects.
**Parameters:**
@@ -443,7 +475,7 @@ Before using the Salesforce integration, ensure you have:
- `defaultFieldValue` (string, optional): Default field value
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_FIELD_ANY">
<Accordion title="salesforce/create_custom_field_any">
**Description:** Deploy custom fields for any object type.
**Note:** This is a flexible tool for creating custom fields on custom or unknown object types.
@@ -453,14 +485,14 @@ Before using the Salesforce integration, ensure you have:
### **Advanced Operations**
<AccordionGroup>
<Accordion title="SALESFORCE_WRITE_SOQL_QUERY">
<Accordion title="salesforce/write_soql_query">
**Description:** Execute custom SOQL queries against your Salesforce data.
**Parameters:**
- `query` (string, required): SOQL Query (e.g., "SELECT Id, Name FROM Account WHERE Name = 'Example'")
</Accordion>
<Accordion title="SALESFORCE_CREATE_CUSTOM_OBJECT">
<Accordion title="salesforce/create_custom_object">
**Description:** Deploy a new custom object in Salesforce.
**Parameters:**
@@ -470,7 +502,7 @@ Before using the Salesforce integration, ensure you have:
- `recordName` (string, required): Record Name that appears in layouts and searches (e.g., "Account Name")
</Accordion>
<Accordion title="SALESFORCE_DESCRIBE_ACTION_SCHEMA">
<Accordion title="salesforce/describe_action_schema">
**Description:** Get the expected schema for operations on specific object types.
**Parameters:**
@@ -487,19 +519,14 @@ Before using the Salesforce integration, ensure you have:
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Salesforce tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Salesforce capabilities
salesforce_agent = Agent(
role="CRM Manager",
goal="Manage customer relationships and sales processes efficiently",
backstory="An AI assistant specialized in CRM operations and sales automation.",
tools=[enterprise_tools]
apps=['salesforce'] # All Salesforce actions will be available
)
# Task to create a new lead
@@ -521,19 +548,12 @@ crew.kickoff()
### Filtering Specific Salesforce Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Salesforce tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["salesforce_create_record_lead", "salesforce_update_record_opportunity", "salesforce_search_records_contact"]
)
sales_manager = Agent(
role="Sales Manager",
goal="Manage leads and opportunities in the sales pipeline",
backstory="An experienced sales manager who handles lead qualification and opportunity management.",
tools=enterprise_tools
apps=['salesforce/create_record_lead']
)
# Task to manage sales pipeline
@@ -555,17 +575,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
account_manager = Agent(
role="Account Manager",
goal="Manage customer accounts and maintain strong relationships",
backstory="An AI assistant that specializes in account management and customer relationship building.",
tools=[enterprise_tools]
apps=['salesforce']
)
# Task to manage customer accounts
@@ -591,17 +606,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
data_analyst = Agent(
role="Sales Data Analyst",
goal="Generate insights from Salesforce data using SOQL queries",
backstory="An analytical AI that excels at extracting meaningful insights from CRM data.",
tools=[enterprise_tools]
apps=['salesforce']
)
# Complex task involving SOQL queries and data analysis

View File

@@ -13,16 +13,48 @@ Enable your agents to manage e-commerce operations through Shopify. Handle custo
Before using the Shopify integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Shopify store with appropriate admin permissions
- Connected your Shopify store through the [Integrations page](https://app.crewai.com/integrations)
## Setting Up Shopify Integration
### 1. Connect Your Shopify Store
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Shopify** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for store and product management
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Tools
### **Customer Management**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_CUSTOMERS">
<Accordion title="shopify/get_customers">
**Description:** Retrieve a list of customers from your Shopify store.
**Parameters:**
@@ -34,7 +66,7 @@ Before using the Shopify integration, ensure you have:
- `limit` (string, optional): Maximum number of customers to return (defaults to 250)
</Accordion>
<Accordion title="SHOPIFY_SEARCH_CUSTOMERS">
<Accordion title="shopify/search_customers">
**Description:** Search for customers using advanced filtering criteria.
**Parameters:**
@@ -42,7 +74,7 @@ Before using the Shopify integration, ensure you have:
- `limit` (string, optional): Maximum number of customers to return (defaults to 250)
</Accordion>
<Accordion title="SHOPIFY_CREATE_CUSTOMER">
<Accordion title="shopify/create_customer">
**Description:** Create a new customer in your Shopify store.
**Parameters:**
@@ -63,7 +95,7 @@ Before using the Shopify integration, ensure you have:
- `metafields` (object, optional): Additional metafields in JSON format
</Accordion>
<Accordion title="SHOPIFY_UPDATE_CUSTOMER">
<Accordion title="shopify/update_customer">
**Description:** Update an existing customer in your Shopify store.
**Parameters:**
@@ -89,7 +121,7 @@ Before using the Shopify integration, ensure you have:
### **Order Management**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_ORDERS">
<Accordion title="shopify/get_orders">
**Description:** Retrieve a list of orders from your Shopify store.
**Parameters:**
@@ -101,7 +133,7 @@ Before using the Shopify integration, ensure you have:
- `limit` (string, optional): Maximum number of orders to return (defaults to 250)
</Accordion>
<Accordion title="SHOPIFY_CREATE_ORDER">
<Accordion title="shopify/create_order">
**Description:** Create a new order in your Shopify store.
**Parameters:**
@@ -114,7 +146,7 @@ Before using the Shopify integration, ensure you have:
- `note` (string, optional): Order note
</Accordion>
<Accordion title="SHOPIFY_UPDATE_ORDER">
<Accordion title="shopify/update_order">
**Description:** Update an existing order in your Shopify store.
**Parameters:**
@@ -128,7 +160,7 @@ Before using the Shopify integration, ensure you have:
- `note` (string, optional): Order note
</Accordion>
<Accordion title="SHOPIFY_GET_ABANDONED_CARTS">
<Accordion title="shopify/get_abandoned_carts">
**Description:** Retrieve abandoned carts from your Shopify store.
**Parameters:**
@@ -144,7 +176,7 @@ Before using the Shopify integration, ensure you have:
### **Product Management (REST API)**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_PRODUCTS">
<Accordion title="shopify/get_products">
**Description:** Retrieve a list of products from your Shopify store using REST API.
**Parameters:**
@@ -160,7 +192,7 @@ Before using the Shopify integration, ensure you have:
- `limit` (string, optional): Maximum number of products to return (defaults to 250)
</Accordion>
<Accordion title="SHOPIFY_CREATE_PRODUCT">
<Accordion title="shopify/create_product">
**Description:** Create a new product in your Shopify store using REST API.
**Parameters:**
@@ -176,7 +208,7 @@ Before using the Shopify integration, ensure you have:
- `publishToPointToSale` (boolean, optional): Whether to publish to point of sale
</Accordion>
<Accordion title="SHOPIFY_UPDATE_PRODUCT">
<Accordion title="shopify/update_product">
**Description:** Update an existing product in your Shopify store using REST API.
**Parameters:**
@@ -197,14 +229,14 @@ Before using the Shopify integration, ensure you have:
### **Product Management (GraphQL)**
<AccordionGroup>
<Accordion title="SHOPIFY_GET_PRODUCTS_GRAPHQL">
<Accordion title="shopify/get_products_graphql">
**Description:** Retrieve products using advanced GraphQL filtering capabilities.
**Parameters:**
- `productFilterFormula` (object, optional): Advanced filter in disjunctive normal form with support for fields like id, title, vendor, status, handle, tag, created_at, updated_at, published_at
</Accordion>
<Accordion title="SHOPIFY_CREATE_PRODUCT_GRAPHQL">
<Accordion title="shopify/create_product_graphql">
**Description:** Create a new product using GraphQL API with enhanced media support.
**Parameters:**
@@ -217,7 +249,7 @@ Before using the Shopify integration, ensure you have:
- `additionalFields` (object, optional): Additional product fields like status, requiresSellingPlan, giftCard
</Accordion>
<Accordion title="SHOPIFY_UPDATE_PRODUCT_GRAPHQL">
<Accordion title="shopify/update_product_graphql">
**Description:** Update an existing product using GraphQL API with enhanced media support.
**Parameters:**
@@ -238,19 +270,14 @@ Before using the Shopify integration, ensure you have:
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Shopify tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Shopify capabilities
shopify_agent = Agent(
role="E-commerce Manager",
goal="Manage online store operations and customer relationships efficiently",
backstory="An AI assistant specialized in e-commerce operations and online store management.",
tools=[enterprise_tools]
apps=['shopify'] # All Shopify actions will be available
)
# Task to create a new customer
@@ -272,19 +299,12 @@ crew.kickoff()
### Filtering Specific Shopify Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Shopify tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["shopify_create_customer", "shopify_create_order", "shopify_get_products"]
)
store_manager = Agent(
role="Store Manager",
goal="Manage customer orders and product catalog",
backstory="An experienced store manager who handles customer relationships and inventory management.",
tools=enterprise_tools
apps=['shopify/create_customer']
)
# Task to manage store operations
@@ -306,17 +326,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
product_manager = Agent(
role="Product Manager",
goal="Manage product catalog and inventory with advanced GraphQL capabilities",
backstory="An AI assistant that specializes in product management and catalog optimization.",
tools=[enterprise_tools]
apps=['shopify']
)
# Task to manage product catalog
@@ -343,17 +358,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
analytics_agent = Agent(
role="E-commerce Analyst",
goal="Analyze customer behavior and order patterns to optimize store performance",
backstory="An analytical AI that excels at extracting insights from e-commerce data.",
tools=[enterprise_tools]
apps=['shopify']
)
# Complex task involving multiple operations

View File

@@ -13,30 +13,62 @@ Enable your agents to manage team communication through Slack. Send messages, se
Before using the Slack integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Slack workspace with appropriate permissions
- Connected your Slack workspace through the [Integrations page](https://app.crewai.com/integrations)
## Setting Up Slack Integration
### 1. Connect Your Slack Workspace
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Slack** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for team communication
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Tools
### **User Management**
<AccordionGroup>
<Accordion title="SLACK_LIST_MEMBERS">
<Accordion title="slack/list_members">
**Description:** List all members in a Slack channel.
**Parameters:**
- No parameters required - retrieves all channel members
</Accordion>
<Accordion title="SLACK_GET_USER_BY_EMAIL">
<Accordion title="slack/get_user_by_email">
**Description:** Find a user in your Slack workspace by their email address.
**Parameters:**
- `email` (string, required): The email address of a user in the workspace
</Accordion>
<Accordion title="SLACK_GET_USERS_BY_NAME">
<Accordion title="slack/get_users_by_name">
**Description:** Search for users by their name or display name.
**Parameters:**
@@ -50,7 +82,7 @@ Before using the Slack integration, ensure you have:
### **Channel Management**
<AccordionGroup>
<Accordion title="SLACK_LIST_CHANNELS">
<Accordion title="slack/list_channels">
**Description:** List all channels in your Slack workspace.
**Parameters:**
@@ -61,7 +93,7 @@ Before using the Slack integration, ensure you have:
### **Messaging**
<AccordionGroup>
<Accordion title="SLACK_SEND_MESSAGE">
<Accordion title="slack/send_message">
**Description:** Send a message to a Slack channel.
**Parameters:**
@@ -73,7 +105,7 @@ Before using the Slack integration, ensure you have:
- `authenticatedUser` (boolean, optional): If true, message appears to come from your authenticated Slack user instead of the application (defaults to false)
</Accordion>
<Accordion title="SLACK_SEND_DIRECT_MESSAGE">
<Accordion title="slack/send_direct_message">
**Description:** Send a direct message to a specific user in Slack.
**Parameters:**
@@ -89,7 +121,7 @@ Before using the Slack integration, ensure you have:
### **Search & Discovery**
<AccordionGroup>
<Accordion title="SLACK_SEARCH_MESSAGES">
<Accordion title="slack/search_messages">
**Description:** Search for messages across your Slack workspace.
**Parameters:**
@@ -150,19 +182,13 @@ Slack's Block Kit allows you to create rich, interactive messages. Here are some
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Slack tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create an agent with Slack capabilities
slack_agent = Agent(
role="Team Communication Manager",
goal="Facilitate team communication and coordinate collaboration efficiently",
backstory="An AI assistant specialized in team communication and workspace coordination.",
tools=[enterprise_tools]
apps=['slack'] # All Slack actions will be available
)
# Task to send project updates
@@ -184,19 +210,18 @@ crew.kickoff()
### Filtering Specific Slack Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Slack tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["slack_send_message", "slack_send_direct_message", "slack_search_messages"]
)
from crewai import Agent, Task, Crew
# Create agent with specific Slack actions only
communication_manager = Agent(
role="Communication Coordinator",
goal="Manage team communications and ensure important messages reach the right people",
backstory="An experienced communication coordinator who handles team messaging and notifications.",
tools=enterprise_tools
apps=[
'slack/send_message',
'slack/send_direct_message',
'slack/search_messages'
] # Using canonical action names from canonical_integrations.yml
)
# Task to coordinate team communication
@@ -218,17 +243,13 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create agent with Slack messaging capabilities
notification_agent = Agent(
role="Notification Manager",
goal="Create rich, interactive notifications and manage workspace communication",
backstory="An AI assistant that specializes in creating engaging team notifications and updates.",
tools=[enterprise_tools]
apps=['slack/send_message'] # Specific action for sending messages
)
# Task to send rich notifications
@@ -254,17 +275,17 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
# Create agent with Slack search and user management capabilities
analytics_agent = Agent(
role="Communication Analyst",
goal="Analyze team communication patterns and extract insights from conversations",
backstory="An analytical AI that excels at understanding team dynamics through communication data.",
tools=[enterprise_tools]
apps=[
'slack/search_messages',
'slack/get_user_by_email',
'slack/list_members'
] # Using canonical action names from canonical_integrations.yml
)
# Complex task involving search and analysis

View File

@@ -13,16 +13,48 @@ Enable your agents to manage payments, subscriptions, and customer billing throu
Before using the Stripe integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Stripe account with appropriate API permissions
- Connected your Stripe account through the [Integrations page](https://app.crewai.com/integrations)
## Setting Up Stripe Integration
### 1. Connect Your Stripe Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Stripe** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for payment processing
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Tools
### **Customer Management**
<AccordionGroup>
<Accordion title="STRIPE_CREATE_CUSTOMER">
<Accordion title="stripe/create_customer">
**Description:** Create a new customer in your Stripe account.
**Parameters:**
@@ -32,14 +64,14 @@ Before using the Stripe integration, ensure you have:
- `metadataCreateCustomer` (object, optional): Additional metadata as key-value pairs (e.g., `{"field1": 1, "field2": 2}`)
</Accordion>
<Accordion title="STRIPE_GET_CUSTOMER_BY_ID">
<Accordion title="stripe/get_customer_by_id">
**Description:** Retrieve a specific customer by their Stripe customer ID.
**Parameters:**
- `idGetCustomer` (string, required): The Stripe customer ID to retrieve
</Accordion>
<Accordion title="STRIPE_GET_CUSTOMERS">
<Accordion title="stripe/get_customers">
**Description:** Retrieve a list of customers with optional filtering.
**Parameters:**
@@ -49,7 +81,7 @@ Before using the Stripe integration, ensure you have:
- `limitGetCustomers` (string, optional): Maximum number of customers to return (defaults to 10)
</Accordion>
<Accordion title="STRIPE_UPDATE_CUSTOMER">
<Accordion title="stripe/update_customer">
**Description:** Update an existing customer's information.
**Parameters:**
@@ -64,7 +96,7 @@ Before using the Stripe integration, ensure you have:
### **Subscription Management**
<AccordionGroup>
<Accordion title="STRIPE_CREATE_SUBSCRIPTION">
<Accordion title="stripe/create_subscription">
**Description:** Create a new subscription for a customer.
**Parameters:**
@@ -73,7 +105,7 @@ Before using the Stripe integration, ensure you have:
- `metadataCreateSubscription` (object, optional): Additional metadata for the subscription
</Accordion>
<Accordion title="STRIPE_GET_SUBSCRIPTIONS">
<Accordion title="stripe/get_subscriptions">
**Description:** Retrieve subscriptions with optional filtering.
**Parameters:**
@@ -86,7 +118,7 @@ Before using the Stripe integration, ensure you have:
### **Product Management**
<AccordionGroup>
<Accordion title="STRIPE_CREATE_PRODUCT">
<Accordion title="stripe/create_product">
**Description:** Create a new product in your Stripe catalog.
**Parameters:**
@@ -95,14 +127,14 @@ Before using the Stripe integration, ensure you have:
- `metadataProduct` (object, optional): Additional product metadata as key-value pairs
</Accordion>
<Accordion title="STRIPE_GET_PRODUCT_BY_ID">
<Accordion title="stripe/get_product_by_id">
**Description:** Retrieve a specific product by its Stripe product ID.
**Parameters:**
- `productId` (string, required): The Stripe product ID to retrieve
</Accordion>
<Accordion title="STRIPE_GET_PRODUCTS">
<Accordion title="stripe/get_products">
**Description:** Retrieve a list of products with optional filtering.
**Parameters:**
@@ -115,7 +147,7 @@ Before using the Stripe integration, ensure you have:
### **Financial Operations**
<AccordionGroup>
<Accordion title="STRIPE_GET_BALANCE_TRANSACTIONS">
<Accordion title="stripe/get_balance_transactions">
**Description:** Retrieve balance transactions from your Stripe account.
**Parameters:**
@@ -124,7 +156,7 @@ Before using the Stripe integration, ensure you have:
- `pageCursor` (string, optional): Page cursor for pagination
</Accordion>
<Accordion title="STRIPE_GET_PLANS">
<Accordion title="stripe/get_plans">
**Description:** Retrieve subscription plans from your Stripe account.
**Parameters:**
@@ -140,19 +172,14 @@ Before using the Stripe integration, ensure you have:
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Stripe tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Stripe capabilities
stripe_agent = Agent(
role="Payment Manager",
goal="Manage customer payments, subscriptions, and billing operations efficiently",
backstory="An AI assistant specialized in payment processing and subscription management.",
tools=[enterprise_tools]
apps=['stripe'] # All Stripe actions will be available
)
# Task to create a new customer
@@ -174,19 +201,12 @@ crew.kickoff()
### Filtering Specific Stripe Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Stripe tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["stripe_create_customer", "stripe_create_subscription", "stripe_get_balance_transactions"]
)
billing_manager = Agent(
role="Billing Manager",
goal="Handle customer billing, subscriptions, and payment processing",
backstory="An experienced billing manager who handles subscription lifecycle and payment operations.",
tools=enterprise_tools
apps=['stripe']
)
# Task to manage billing operations
@@ -208,17 +228,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
subscription_manager = Agent(
role="Subscription Manager",
goal="Manage customer subscriptions and optimize recurring revenue",
backstory="An AI assistant that specializes in subscription lifecycle management and customer retention.",
tools=[enterprise_tools]
apps=['stripe']
)
# Task to manage subscription operations
@@ -245,17 +260,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
financial_analyst = Agent(
role="Financial Analyst",
goal="Analyze payment data and generate financial insights",
backstory="An analytical AI that excels at extracting insights from payment and subscription data.",
tools=[enterprise_tools]
apps=['stripe']
)
# Complex task involving financial analysis

View File

@@ -13,16 +13,48 @@ Enable your agents to manage customer support operations through Zendesk. Create
Before using the Zendesk integration, ensure you have:
- A [CrewAI AMP](https://app.crewai.com) account with an active subscription
- A [CrewAI AOP](https://app.crewai.com) account with an active subscription
- A Zendesk account with appropriate API permissions
- Connected your Zendesk account through the [Integrations page](https://app.crewai.com/integrations)
## Setting Up Zendesk Integration
### 1. Connect Your Zendesk Account
1. Navigate to [CrewAI AOP Integrations](https://app.crewai.com/crewai_plus/connectors)
2. Find **Zendesk** in the Authentication Integrations section
3. Click **Connect** and complete the OAuth flow
4. Grant the necessary permissions for ticket and user management
5. Copy your Enterprise Token from [Integration Settings](https://app.crewai.com/crewai_plus/settings/integrations)
### 2. Install Required Package
```bash
uv add crewai-tools
```
### 3. Environment Variable Setup
<Note>
To use integrations with `Agent(apps=[])`, you must set the `CREWAI_PLATFORM_INTEGRATION_TOKEN` environment variable with your Enterprise Token.
</Note>
```bash
export CREWAI_PLATFORM_INTEGRATION_TOKEN="your_enterprise_token"
```
Or add it to your `.env` file:
```
CREWAI_PLATFORM_INTEGRATION_TOKEN=your_enterprise_token
```
## Available Tools
### **Ticket Management**
<AccordionGroup>
<Accordion title="ZENDESK_CREATE_TICKET">
<Accordion title="zendesk/create_ticket">
**Description:** Create a new support ticket in Zendesk.
**Parameters:**
@@ -40,7 +72,7 @@ Before using the Zendesk integration, ensure you have:
- `ticketCustomFields` (object, optional): Custom field values in JSON format
</Accordion>
<Accordion title="ZENDESK_UPDATE_TICKET">
<Accordion title="zendesk/update_ticket">
**Description:** Update an existing support ticket in Zendesk.
**Parameters:**
@@ -58,14 +90,14 @@ Before using the Zendesk integration, ensure you have:
- `ticketCustomFields` (object, optional): Updated custom field values
</Accordion>
<Accordion title="ZENDESK_GET_TICKET_BY_ID">
<Accordion title="zendesk/get_ticket_by_id">
**Description:** Retrieve a specific ticket by its ID.
**Parameters:**
- `ticketId` (string, required): The ticket ID to retrieve (e.g., "35436")
</Accordion>
<Accordion title="ZENDESK_ADD_COMMENT_TO_TICKET">
<Accordion title="zendesk/add_comment_to_ticket">
**Description:** Add a comment or internal note to an existing ticket.
**Parameters:**
@@ -75,7 +107,7 @@ Before using the Zendesk integration, ensure you have:
- `isPublic` (boolean, optional): True for public comments, false for internal notes
</Accordion>
<Accordion title="ZENDESK_SEARCH_TICKETS">
<Accordion title="zendesk/search_tickets">
**Description:** Search for tickets using various filters and criteria.
**Parameters:**
@@ -100,7 +132,7 @@ Before using the Zendesk integration, ensure you have:
### **User Management**
<AccordionGroup>
<Accordion title="ZENDESK_CREATE_USER">
<Accordion title="zendesk/create_user">
**Description:** Create a new user in Zendesk.
**Parameters:**
@@ -113,7 +145,7 @@ Before using the Zendesk integration, ensure you have:
- `notes` (string, optional): Internal notes about the user
</Accordion>
<Accordion title="ZENDESK_UPDATE_USER">
<Accordion title="zendesk/update_user">
**Description:** Update an existing user's information.
**Parameters:**
@@ -127,14 +159,14 @@ Before using the Zendesk integration, ensure you have:
- `notes` (string, optional): Updated internal notes
</Accordion>
<Accordion title="ZENDESK_GET_USER_BY_ID">
<Accordion title="zendesk/get_user_by_id">
**Description:** Retrieve a specific user by their ID.
**Parameters:**
- `userId` (string, required): The user ID to retrieve
</Accordion>
<Accordion title="ZENDESK_SEARCH_USERS">
<Accordion title="zendesk/search_users">
**Description:** Search for users using various criteria.
**Parameters:**
@@ -150,7 +182,7 @@ Before using the Zendesk integration, ensure you have:
### **Administrative Tools**
<AccordionGroup>
<Accordion title="ZENDESK_GET_TICKET_FIELDS">
<Accordion title="zendesk/get_ticket_fields">
**Description:** Retrieve all standard and custom fields available for tickets.
**Parameters:**
@@ -158,7 +190,7 @@ Before using the Zendesk integration, ensure you have:
- `pageCursor` (string, optional): Page cursor for pagination
</Accordion>
<Accordion title="ZENDESK_GET_TICKET_AUDITS">
<Accordion title="zendesk/get_ticket_audits">
**Description:** Get audit records (read-only history) for tickets.
**Parameters:**
@@ -205,19 +237,14 @@ Standard ticket status progression:
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
# Get enterprise tools (Zendesk tools will be included)
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
from crewai import Agent, Task, Crew
# Create an agent with Zendesk capabilities
zendesk_agent = Agent(
role="Support Manager",
goal="Manage customer support tickets and provide excellent customer service",
backstory="An AI assistant specialized in customer support operations and ticket management.",
tools=[enterprise_tools]
apps=['zendesk'] # All Zendesk actions will be available
)
# Task to create a new support ticket
@@ -239,19 +266,14 @@ crew.kickoff()
### Filtering Specific Zendesk Tools
```python
from crewai_tools import CrewaiEnterpriseTools
# Get only specific Zendesk tools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token",
actions_list=["zendesk_create_ticket", "zendesk_update_ticket", "zendesk_add_comment_to_ticket"]
)
from crewai import Agent, Task, Crew
# Create agent with specific Zendesk actions only
support_agent = Agent(
role="Customer Support Agent",
goal="Handle customer inquiries and resolve support issues efficiently",
backstory="An experienced support agent who specializes in ticket resolution and customer communication.",
tools=enterprise_tools
apps=['zendesk/create_ticket'] # Specific Zendesk actions
)
# Task to manage support workflow
@@ -273,17 +295,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
ticket_manager = Agent(
role="Ticket Manager",
goal="Manage support ticket workflows and ensure timely resolution",
backstory="An AI assistant that specializes in support ticket triage and workflow optimization.",
tools=[enterprise_tools]
apps=['zendesk']
)
# Task to manage ticket lifecycle
@@ -310,17 +327,12 @@ crew.kickoff()
```python
from crewai import Agent, Task, Crew
from crewai_tools import CrewaiEnterpriseTools
enterprise_tools = CrewaiEnterpriseTools(
enterprise_token="your_enterprise_token"
)
support_analyst = Agent(
role="Support Analyst",
goal="Analyze support metrics and generate insights for team performance",
backstory="An analytical AI that excels at extracting insights from support data and ticket patterns.",
tools=[enterprise_tools]
apps=['zendesk']
)
# Complex task involving analytics and reporting

View File

@@ -1,5 +1,5 @@
---
title: "CrewAI AMP"
title: "CrewAI AOP"
description: "Deploy, monitor, and scale your AI agent workflows"
icon: "globe"
mode: "wide"
@@ -7,13 +7,13 @@ mode: "wide"
## Introduction
CrewAI AMP(Agent Management Platform) provides a platform for deploying, monitoring, and scaling your crews and agents in a production environment.
CrewAI AOP(Agent Operations Platform) provides a platform for deploying, monitoring, and scaling your crews and agents in a production environment.
<Frame>
<img src="/images/enterprise/crewai-enterprise-dashboard.png" alt="CrewAI AMP Dashboard" />
<img src="/images/enterprise/crewai-enterprise-dashboard.png" alt="CrewAI AOP Dashboard" />
</Frame>
CrewAI AMP extends the power of the open-source framework with features designed for production deployments, collaboration, and scalability. Deploy your crews to a managed infrastructure and monitor their execution in real-time.
CrewAI AOP extends the power of the open-source framework with features designed for production deployments, collaboration, and scalability. Deploy your crews to a managed infrastructure and monitor their execution in real-time.
## Key Features

View File

@@ -1,6 +1,6 @@
---
title: FAQs
description: "Frequently asked questions about CrewAI AMP"
description: "Frequently asked questions about CrewAI AOP"
icon: "circle-question"
mode: "wide"
---
@@ -49,7 +49,7 @@ mode: "wide"
To integrate human input into agent execution, set the `human_input` flag in the task definition. When enabled, the agent prompts the user for input before delivering its final answer. This input can provide extra context, clarify ambiguities, or validate the agent's output.
For detailed implementation guidance, see our [Human-in-the-Loop guide](/en/how-to/human-in-the-loop).
For detailed implementation guidance, see our [Human-in-the-Loop guide](/en/enterprise/guides/human-in-the-loop).
</Accordion>
<Accordion title="What advanced customization options are available for tailoring and enhancing agent behavior and capabilities in CrewAI?">
@@ -142,7 +142,7 @@ mode: "wide"
<Accordion title="How can I create custom tools for my CrewAI agents?">
You can create custom tools by subclassing the `BaseTool` class provided by CrewAI or by using the tool decorator. Subclassing involves defining a new class that inherits from `BaseTool`, specifying the name, description, and the `_run` method for operational logic. The tool decorator allows you to create a `Tool` object directly with the required attributes and a functional logic.
<Card href="https://docs.crewai.com/how-to/create-custom-tools" icon="code">CrewAI Tools Guide</Card>
<Card href="/en/learn/create-custom-tools" icon="code">CrewAI Tools Guide</Card>
</Accordion>
<Accordion title="How can you control the maximum number of requests per minute that the entire crew can perform?">

View File

@@ -167,7 +167,7 @@ We recommend using the `YAML` template scaffolding for a structured approach to
<Note type="info">
For teams and organizations, CrewAI offers enterprise deployment options that eliminate setup complexity:
### CrewAI AMP (SaaS)
### CrewAI AOP (SaaS)
- Zero installation required - just sign up for free at [app.crewai.com](https://app.crewai.com)
- Automatic updates and maintenance
- Managed infrastructure and scaling

View File

@@ -0,0 +1,295 @@
---
title: Agent-to-Agent (A2A) Protocol
description: Enable CrewAI agents to delegate tasks to remote A2A-compliant agents for specialized handling
icon: network-wired
mode: "wide"
---
## A2A Agent Delegation
CrewAI supports the Agent-to-Agent (A2A) protocol, allowing agents to delegate tasks to remote specialized agents. The agent's LLM automatically decides whether to handle a task directly or delegate to an A2A agent based on the task requirements.
<Note>
A2A delegation requires the `a2a-sdk` package. Install with: `uv add 'crewai[a2a]'` or `pip install 'crewai[a2a]'`
</Note>
## How It Works
When an agent is configured with A2A capabilities:
1. The LLM analyzes each task
2. It decides to either:
- Handle the task directly using its own capabilities
- Delegate to a remote A2A agent for specialized handling
3. If delegating, the agent communicates with the remote A2A agent through the protocol
4. Results are returned to the CrewAI workflow
## Basic Configuration
Configure an agent for A2A delegation by setting the `a2a` parameter:
```python Code
from crewai import Agent, Crew, Task
from crewai.a2a import A2AConfig
agent = Agent(
role="Research Coordinator",
goal="Coordinate research tasks efficiently",
backstory="Expert at delegating to specialized research agents",
llm="gpt-4o",
a2a=A2AConfig(
endpoint="https://example.com/.well-known/agent-card.json",
timeout=120,
max_turns=10
)
)
task = Task(
description="Research the latest developments in quantum computing",
expected_output="A comprehensive research report",
agent=agent
)
crew = Crew(agents=[agent], tasks=[task], verbose=True)
result = crew.kickoff()
```
## Configuration Options
The `A2AConfig` class accepts the following parameters:
<ParamField path="endpoint" type="str" required>
The A2A agent endpoint URL (typically points to `.well-known/agent-card.json`)
</ParamField>
<ParamField path="auth" type="AuthScheme" default="None">
Authentication scheme for the A2A agent. Supports Bearer tokens, OAuth2, API keys, and HTTP authentication.
</ParamField>
<ParamField path="timeout" type="int" default="120">
Request timeout in seconds
</ParamField>
<ParamField path="max_turns" type="int" default="10">
Maximum number of conversation turns with the A2A agent
</ParamField>
<ParamField path="response_model" type="type[BaseModel]" default="None">
Optional Pydantic model for requesting structured output from an A2A agent. A2A protocol does not
enforce this, so an A2A agent does not need to honor this request.
</ParamField>
<ParamField path="fail_fast" type="bool" default="True">
Whether to raise an error immediately if agent connection fails. When `False`, the agent continues with available agents and informs the LLM about unavailable ones.
</ParamField>
<ParamField path="trust_remote_completion_status" type="bool" default="False">
When `True`, returns the A2A agent's result directly when it signals completion. When `False`, allows the server agent to review the result and potentially continue the conversation.
</ParamField>
## Authentication
For A2A agents that require authentication, use one of the provided auth schemes:
<Tabs>
<Tab title="Bearer Token">
```python Code
from crewai.a2a import A2AConfig
from crewai.a2a.auth import BearerTokenAuth
agent = Agent(
role="Secure Coordinator",
goal="Coordinate tasks with secured agents",
backstory="Manages secure agent communications",
llm="gpt-4o",
a2a=A2AConfig(
endpoint="https://secure-agent.example.com/.well-known/agent-card.json",
auth=BearerTokenAuth(token="your-bearer-token"),
timeout=120
)
)
```
</Tab>
<Tab title="API Key">
```python Code
from crewai.a2a import A2AConfig
from crewai.a2a.auth import APIKeyAuth
agent = Agent(
role="API Coordinator",
goal="Coordinate with API-based agents",
backstory="Manages API-authenticated communications",
llm="gpt-4o",
a2a=A2AConfig(
endpoint="https://api-agent.example.com/.well-known/agent-card.json",
auth=APIKeyAuth(
api_key="your-api-key",
location="header", # or "query" or "cookie"
name="X-API-Key"
),
timeout=120
)
)
```
</Tab>
<Tab title="OAuth2">
```python Code
from crewai.a2a import A2AConfig
from crewai.a2a.auth import OAuth2ClientCredentials
agent = Agent(
role="OAuth Coordinator",
goal="Coordinate with OAuth-secured agents",
backstory="Manages OAuth-authenticated communications",
llm="gpt-4o",
a2a=A2AConfig(
endpoint="https://oauth-agent.example.com/.well-known/agent-card.json",
auth=OAuth2ClientCredentials(
token_url="https://auth.example.com/oauth/token",
client_id="your-client-id",
client_secret="your-client-secret",
scopes=["read", "write"]
),
timeout=120
)
)
```
</Tab>
<Tab title="HTTP Basic">
```python Code
from crewai.a2a import A2AConfig
from crewai.a2a.auth import HTTPBasicAuth
agent = Agent(
role="Basic Auth Coordinator",
goal="Coordinate with basic auth agents",
backstory="Manages basic authentication communications",
llm="gpt-4o",
a2a=A2AConfig(
endpoint="https://basic-agent.example.com/.well-known/agent-card.json",
auth=HTTPBasicAuth(
username="your-username",
password="your-password"
),
timeout=120
)
)
```
</Tab>
</Tabs>
## Multiple A2A Agents
Configure multiple A2A agents for delegation by passing a list:
```python Code
from crewai.a2a import A2AConfig
from crewai.a2a.auth import BearerTokenAuth
agent = Agent(
role="Multi-Agent Coordinator",
goal="Coordinate with multiple specialized agents",
backstory="Expert at delegating to the right specialist",
llm="gpt-4o",
a2a=[
A2AConfig(
endpoint="https://research.example.com/.well-known/agent-card.json",
timeout=120
),
A2AConfig(
endpoint="https://data.example.com/.well-known/agent-card.json",
auth=BearerTokenAuth(token="data-token"),
timeout=90
)
]
)
```
The LLM will automatically choose which A2A agent to delegate to based on the task requirements.
## Error Handling
Control how agent connection failures are handled using the `fail_fast` parameter:
```python Code
from crewai.a2a import A2AConfig
# Fail immediately on connection errors (default)
agent = Agent(
role="Research Coordinator",
goal="Coordinate research tasks",
backstory="Expert at delegation",
llm="gpt-4o",
a2a=A2AConfig(
endpoint="https://research.example.com/.well-known/agent-card.json",
fail_fast=True
)
)
# Continue with available agents
agent = Agent(
role="Multi-Agent Coordinator",
goal="Coordinate with multiple agents",
backstory="Expert at working with available resources",
llm="gpt-4o",
a2a=[
A2AConfig(
endpoint="https://primary.example.com/.well-known/agent-card.json",
fail_fast=False
),
A2AConfig(
endpoint="https://backup.example.com/.well-known/agent-card.json",
fail_fast=False
)
]
)
```
When `fail_fast=False`:
- If some agents fail, the LLM is informed which agents are unavailable and can delegate to working agents
- If all agents fail, the LLM receives a notice about unavailable agents and handles the task directly
- Connection errors are captured and included in the context for better decision-making
## Best Practices
<CardGroup cols={2}>
<Card title="Set Appropriate Timeouts" icon="clock">
Configure timeouts based on expected A2A agent response times. Longer-running tasks may need higher timeout values.
</Card>
<Card title="Limit Conversation Turns" icon="comments">
Use `max_turns` to prevent excessive back-and-forth. The agent will automatically conclude conversations before hitting the limit.
</Card>
<Card title="Use Resilient Error Handling" icon="shield-check">
Set `fail_fast=False` for production environments with multiple agents to gracefully handle connection failures and maintain workflow continuity.
</Card>
<Card title="Secure Your Credentials" icon="lock">
Store authentication tokens and credentials as environment variables, not in code.
</Card>
<Card title="Monitor Delegation Decisions" icon="eye">
Use verbose mode to observe when the LLM chooses to delegate versus handle tasks directly.
</Card>
</CardGroup>
## Supported Authentication Methods
- **Bearer Token** - Simple token-based authentication
- **OAuth2 Client Credentials** - OAuth2 flow for machine-to-machine communication
- **OAuth2 Authorization Code** - OAuth2 flow requiring user authorization
- **API Key** - Key-based authentication (header, query param, or cookie)
- **HTTP Basic** - Username/password authentication
- **HTTP Digest** - Digest authentication (requires `httpx-auth` package)
## Learn More
For more information about the A2A protocol and reference implementations:
- [A2A Protocol Documentation](https://a2a-protocol.org)
- [A2A Sample Implementations](https://github.com/a2aproject/a2a-samples)
- [A2A Python SDK](https://github.com/a2aproject/a2a-python)

View File

@@ -66,5 +66,55 @@ def my_cache_strategy(arguments: dict, result: str) -> bool:
cached_tool.cache_function = my_cache_strategy
```
### Creating Async Tools
CrewAI supports async tools for non-blocking I/O operations. This is useful when your tool needs to make HTTP requests, database queries, or other I/O-bound operations.
#### Using the `@tool` Decorator with Async Functions
The simplest way to create an async tool is using the `@tool` decorator with an async function:
```python Code
import aiohttp
from crewai.tools import tool
@tool("Async Web Fetcher")
async def fetch_webpage(url: str) -> str:
"""Fetch content from a webpage asynchronously."""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
```
#### Subclassing `BaseTool` with Async Support
For more control, subclass `BaseTool` and implement both `_run` (sync) and `_arun` (async) methods:
```python Code
import requests
import aiohttp
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
class WebFetcherInput(BaseModel):
"""Input schema for WebFetcher."""
url: str = Field(..., description="The URL to fetch")
class WebFetcherTool(BaseTool):
name: str = "Web Fetcher"
description: str = "Fetches content from a URL"
args_schema: type[BaseModel] = WebFetcherInput
def _run(self, url: str) -> str:
"""Synchronous implementation."""
return requests.get(url).text
async def _arun(self, url: str) -> str:
"""Asynchronous implementation for non-blocking I/O."""
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
```
By adhering to these guidelines and incorporating new functionalities and collaboration tools into your tool creation and management processes,
you can leverage the full capabilities of the CrewAI framework, enhancing both the development experience and the efficiency of your AI agents.

View File

@@ -0,0 +1,522 @@
---
title: Execution Hooks Overview
description: Understanding and using execution hooks in CrewAI for fine-grained control over agent operations
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.
## Types of Execution Hooks
CrewAI provides two main categories of execution hooks:
### 1. [LLM Call Hooks](/learn/llm-hooks)
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
**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
[View LLM Hooks Documentation →](/learn/llm-hooks)
### 2. [Tool Call Hooks](/learn/tool-hooks)
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
**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
[View Tool Hooks Documentation →](/learn/tool-hooks)
## Hook Registration Methods
### 1. Decorator-Based Hooks (Recommended)
The cleanest and most Pythonic way to register hooks:
```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 # Tool result (after hooks)
```
## 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.

View File

@@ -97,7 +97,7 @@ project_crew = Crew(
```
<Tip>
For more details on creating and customizing a manager agent, check out the [Custom Manager Agent documentation](https://docs.crewai.com/how-to/custom-manager-agent#custom-manager-agent).
For more details on creating and customizing a manager agent, check out the [Custom Manager Agent documentation](/en/learn/custom-manager-agent).
</Tip>

427
docs/en/learn/llm-hooks.mdx Normal file
View File

@@ -0,0 +1,427 @@
---
title: LLM Call Hooks
description: Learn how to use LLM call hooks to intercept, modify, and control language model interactions in CrewAI
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.
## 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
## Hook Types
### Before LLM Call Hooks
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
**Signature:**
```python
def before_hook(context: LLMCallHookContext) -> bool | None:
# Return False to block execution
# Return True or None to allow execution
...
```
### After LLM Call Hooks
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
...
```
## LLM Hook Context
The `LLMCallHookContext` object provides comprehensive access to execution state:
```python
class LLMCallHookContext:
executor: CrewAgentExecutor # Full executor reference
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)
```
### 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"})
# ❌ Wrong - replaces list reference
def wrong_approach(context: LLMCallHookContext) -> None:
context.messages = [{"role": "system", "content": "Be concise"}]
```
## Registration Methods
### 1. Global Hook Registration
Register hooks that apply to all LLM calls across all crews:
```python
from crewai.hooks import register_before_llm_call_hook, register_after_llm_call_hook
def log_llm_call(context):
print(f"LLM call by {context.agent.role} at iteration {context.iterations}")
return None # Allow execution
register_before_llm_call_hook(log_llm_call)
```
### 2. Decorator-Based Registration
Use decorators for cleaner syntax:
```python
from crewai.hooks import before_llm_call, after_llm_call
@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):
# 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
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
```
## Common Use Cases
### 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
```
### 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:"
)
if response.lower() == "no":
print("🚫 LLM call blocked by user")
return False
return None
```
### 3. Adding System Context
```python
@before_llm_call
def add_guardrails(context: LLMCallHookContext) -> None:
# Add safety guidelines to every LLM call
context.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:
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
```
### 5. Cost Tracking
```python
import tiktoken
@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
```
## Hook Management
### Unregistering Hooks
```python
from crewai.hooks import (
unregister_before_llm_call_hook,
unregister_after_llm_call_hook
)
# Unregister specific hook
def my_hook(context):
...
register_before_llm_call_hook(my_hook)
# Later...
unregister_before_llm_call_hook(my_hook) # Returns True if found
```
### Clearing 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
@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):
if context.iterations > 10:
print("3. Blocking hook - execution stopped")
return False # Subsequent hooks won't execute
print("3. Blocking hook - execution allowed")
return None
```
## 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)
```
## 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
### Message Modifications Not Persisting
- Use in-place modifications: `context.messages.append()`
- Don't replace the list: `context.messages = []`
### Response Modifications Not Working
- Return the modified string from after hooks
- Returning `None` keeps the original response
## Conclusion
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.

View File

@@ -394,7 +394,7 @@ Rather than repeating the strategic framework, here's a tactical checklist for i
<Step title="Validate with Enterprise Testing" icon="test-tube">
**Once you deploy your agents to production:**
- Use [CrewAI AMP platform](https://app.crewai.com) to A/B test your model selections
- Use [CrewAI AOP platform](https://app.crewai.com) to A/B test your model selections
- Run multiple iterations with real inputs to measure consistency and performance
- Compare cost vs. performance across your optimized setup
- Share results with your team for collaborative decision-making
@@ -541,7 +541,7 @@ Focus on understanding your requirements first, then select models that best mat
### Enterprise-Grade Model Validation
For teams serious about optimizing their LLM selection, the **CrewAI AMP platform** provides sophisticated testing capabilities that go far beyond basic CLI testing. The platform enables comprehensive model evaluation that helps you make data-driven decisions about your LLM strategy.
For teams serious about optimizing their LLM selection, the **CrewAI AOP platform** provides sophisticated testing capabilities that go far beyond basic CLI testing. The platform enables comprehensive model evaluation that helps you make data-driven decisions about your LLM strategy.
<Frame>
![Enterprise Testing Interface](/images/enterprise/enterprise-testing.png)

View File

@@ -0,0 +1,320 @@
---
title: Streaming Crew Execution
description: Stream real-time output from your CrewAI crew execution
icon: wave-pulse
mode: "wide"
---
## Introduction
CrewAI provides the ability to stream real-time output during crew execution, allowing you to display results as they're generated rather than waiting for the entire process to complete. This feature is particularly useful for building interactive applications, providing user feedback, and monitoring long-running processes.
## How Streaming Works
When streaming is enabled, CrewAI captures LLM responses and tool calls as they happen, packaging them into structured chunks that include context about which task and agent is executing. You can iterate over these chunks in real-time and access the final result once execution completes.
## Enabling Streaming
To enable streaming, set the `stream` parameter to `True` when creating your crew:
```python Code
from crewai import Agent, Crew, Task
# Create your agents and tasks
researcher = Agent(
role="Research Analyst",
goal="Gather comprehensive information on topics",
backstory="You are an experienced researcher with excellent analytical skills.",
)
task = Task(
description="Research the latest developments in AI",
expected_output="A detailed report on recent AI advancements",
agent=researcher,
)
# Enable streaming
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True # Enable streaming output
)
```
## Synchronous Streaming
When you call `kickoff()` on a crew with streaming enabled, it returns a `CrewStreamingOutput` object that you can iterate over to receive chunks as they arrive:
```python Code
# Start streaming execution
streaming = crew.kickoff(inputs={"topic": "artificial intelligence"})
# Iterate over chunks as they arrive
for chunk in streaming:
print(chunk.content, end="", flush=True)
# Access the final result after streaming completes
result = streaming.result
print(f"\n\nFinal output: {result.raw}")
```
### Stream Chunk Information
Each chunk provides rich context about the execution:
```python Code
streaming = crew.kickoff(inputs={"topic": "AI"})
for chunk in streaming:
print(f"Task: {chunk.task_name} (index {chunk.task_index})")
print(f"Agent: {chunk.agent_role}")
print(f"Content: {chunk.content}")
print(f"Type: {chunk.chunk_type}") # TEXT or TOOL_CALL
if chunk.tool_call:
print(f"Tool: {chunk.tool_call.tool_name}")
print(f"Arguments: {chunk.tool_call.arguments}")
```
### Accessing Streaming Results
The `CrewStreamingOutput` object provides several useful properties:
```python Code
streaming = crew.kickoff(inputs={"topic": "AI"})
# Iterate and collect chunks
for chunk in streaming:
print(chunk.content, end="", flush=True)
# After iteration completes
print(f"\nCompleted: {streaming.is_completed}")
print(f"Full text: {streaming.get_full_text()}")
print(f"All chunks: {len(streaming.chunks)}")
print(f"Final result: {streaming.result.raw}")
```
## Asynchronous Streaming
For async applications, use `kickoff_async()` with async iteration:
```python Code
import asyncio
async def stream_crew():
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True
)
# Start async streaming
streaming = await crew.kickoff_async(inputs={"topic": "AI"})
# Async iteration over chunks
async for chunk in streaming:
print(chunk.content, end="", flush=True)
# Access final result
result = streaming.result
print(f"\n\nFinal output: {result.raw}")
asyncio.run(stream_crew())
```
## Streaming with kickoff_for_each
When executing a crew for multiple inputs with `kickoff_for_each()`, streaming works differently depending on whether you use sync or async:
### Synchronous kickoff_for_each
With synchronous `kickoff_for_each()`, you get a list of `CrewStreamingOutput` objects, one for each input:
```python Code
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True
)
inputs_list = [
{"topic": "AI in healthcare"},
{"topic": "AI in finance"}
]
# Returns list of streaming outputs
streaming_outputs = crew.kickoff_for_each(inputs=inputs_list)
# Iterate over each streaming output
for i, streaming in enumerate(streaming_outputs):
print(f"\n=== Input {i + 1} ===")
for chunk in streaming:
print(chunk.content, end="", flush=True)
result = streaming.result
print(f"\n\nResult {i + 1}: {result.raw}")
```
### Asynchronous kickoff_for_each_async
With async `kickoff_for_each_async()`, you get a single `CrewStreamingOutput` that yields chunks from all crews as they arrive concurrently:
```python Code
import asyncio
async def stream_multiple_crews():
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True
)
inputs_list = [
{"topic": "AI in healthcare"},
{"topic": "AI in finance"}
]
# Returns single streaming output for all crews
streaming = await crew.kickoff_for_each_async(inputs=inputs_list)
# Chunks from all crews arrive as they're generated
async for chunk in streaming:
print(f"[{chunk.task_name}] {chunk.content}", end="", flush=True)
# Access all results
results = streaming.results # List of CrewOutput objects
for i, result in enumerate(results):
print(f"\n\nResult {i + 1}: {result.raw}")
asyncio.run(stream_multiple_crews())
```
## Stream Chunk Types
Chunks can be of different types, indicated by the `chunk_type` field:
### TEXT Chunks
Standard text content from LLM responses:
```python Code
for chunk in streaming:
if chunk.chunk_type == StreamChunkType.TEXT:
print(chunk.content, end="", flush=True)
```
### TOOL_CALL Chunks
Information about tool calls being made:
```python Code
for chunk in streaming:
if chunk.chunk_type == StreamChunkType.TOOL_CALL:
print(f"\nCalling tool: {chunk.tool_call.tool_name}")
print(f"Arguments: {chunk.tool_call.arguments}")
```
## Practical Example: Building a UI with Streaming
Here's a complete example showing how to build an interactive application with streaming:
```python Code
import asyncio
from crewai import Agent, Crew, Task
from crewai.types.streaming import StreamChunkType
async def interactive_research():
# Create crew with streaming enabled
researcher = Agent(
role="Research Analyst",
goal="Provide detailed analysis on any topic",
backstory="You are an expert researcher with broad knowledge.",
)
task = Task(
description="Research and analyze: {topic}",
expected_output="A comprehensive analysis with key insights",
agent=researcher,
)
crew = Crew(
agents=[researcher],
tasks=[task],
stream=True,
verbose=False
)
# Get user input
topic = input("Enter a topic to research: ")
print(f"\n{'='*60}")
print(f"Researching: {topic}")
print(f"{'='*60}\n")
# Start streaming execution
streaming = await crew.kickoff_async(inputs={"topic": topic})
current_task = ""
async for chunk in streaming:
# Show task transitions
if chunk.task_name != current_task:
current_task = chunk.task_name
print(f"\n[{chunk.agent_role}] Working on: {chunk.task_name}")
print("-" * 60)
# Display text chunks
if chunk.chunk_type == StreamChunkType.TEXT:
print(chunk.content, end="", flush=True)
# Display tool calls
elif chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
print(f"\n🔧 Using tool: {chunk.tool_call.tool_name}")
# Show final result
result = streaming.result
print(f"\n\n{'='*60}")
print("Analysis Complete!")
print(f"{'='*60}")
print(f"\nToken Usage: {result.token_usage}")
asyncio.run(interactive_research())
```
## Use Cases
Streaming is particularly valuable for:
- **Interactive Applications**: Provide real-time feedback to users as agents work
- **Long-Running Tasks**: Show progress for research, analysis, or content generation
- **Debugging and Monitoring**: Observe agent behavior and decision-making in real-time
- **User Experience**: Reduce perceived latency by showing incremental results
- **Live Dashboards**: Build monitoring interfaces that display crew execution status
## Important Notes
- Streaming automatically enables LLM streaming for all agents in the crew
- You must iterate through all chunks before accessing the `.result` property
- For `kickoff_for_each_async()` with streaming, use `.results` (plural) to get all outputs
- Streaming adds minimal overhead and can actually improve perceived performance
- Each chunk includes full context (task, agent, chunk type) for rich UIs
## Error Handling
Handle errors during streaming execution:
```python Code
streaming = crew.kickoff(inputs={"topic": "AI"})
try:
for chunk in streaming:
print(chunk.content, end="", flush=True)
result = streaming.result
print(f"\nSuccess: {result.raw}")
except Exception as e:
print(f"\nError during streaming: {e}")
if streaming.is_completed:
print("Streaming completed but an error occurred")
```
By leveraging streaming, you can build more responsive and interactive applications with CrewAI, providing users with real-time visibility into agent execution and results.

View File

@@ -0,0 +1,450 @@
---
title: Streaming Flow Execution
description: Stream real-time output from your CrewAI flow execution
icon: wave-pulse
mode: "wide"
---
## Introduction
CrewAI Flows support streaming output, allowing you to receive real-time updates as your flow executes. This feature enables you to build responsive applications that display results incrementally, provide live progress updates, and create better user experiences for long-running workflows.
## 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.
## Enabling Streaming
To enable streaming, set the `stream` attribute to `True` on your Flow class:
```python Code
from crewai.flow.flow import Flow, listen, start
from crewai import Agent, Crew, Task
class ResearchFlow(Flow):
stream = True # Enable streaming for the entire flow
@start()
def initialize(self):
return {"topic": "AI trends"}
@listen(initialize)
def research_topic(self, data):
researcher = Agent(
role="Research Analyst",
goal="Research topics thoroughly",
backstory="Expert researcher with analytical skills",
)
task = Task(
description="Research {topic} and provide insights",
expected_output="Detailed research findings",
agent=researcher,
)
crew = Crew(
agents=[researcher],
tasks=[task],
)
return crew.kickoff(inputs=data)
```
## Synchronous Streaming
When you call `kickoff()` on a flow with streaming enabled, it returns a `FlowStreamingOutput` object that you can iterate over:
```python Code
flow = ResearchFlow()
# Start streaming execution
streaming = flow.kickoff()
# Iterate over chunks as they arrive
for chunk in streaming:
print(chunk.content, end="", flush=True)
# Access the final result after streaming completes
result = streaming.result
print(f"\n\nFinal output: {result}")
```
### Stream Chunk Information
Each chunk provides context about where it originated in the flow:
```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
```
### Accessing Streaming Properties
The `FlowStreamingOutput` object provides useful properties and methods:
```python Code
streaming = flow.kickoff()
# Iterate and collect chunks
for chunk in streaming:
print(chunk.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"Final result: {streaming.result}")
```
## Asynchronous Streaming
For async applications, use `kickoff_async()` with async iteration:
```python Code
import asyncio
async def stream_flow():
flow = ResearchFlow()
# Start async streaming
streaming = await flow.kickoff_async()
# Async iteration over chunks
async for chunk in streaming:
print(chunk.content, end="", flush=True)
# Access final result
result = streaming.result
print(f"\n\nFinal output: {result}")
asyncio.run(stream_flow())
```
## Streaming with Multi-Step Flows
Streaming works seamlessly across multiple flow steps, including flows that execute multiple crews:
```python Code
from crewai.flow.flow import Flow, listen, start
from crewai import Agent, Crew, Task
class MultiStepFlow(Flow):
stream = True
@start()
def research_phase(self):
"""First crew: Research the topic."""
researcher = Agent(
role="Research Analyst",
goal="Gather comprehensive information",
backstory="Expert at finding relevant information",
)
task = Task(
description="Research AI developments in healthcare",
expected_output="Research findings on AI in healthcare",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
self.state["research"] = result.raw
return result.raw
@listen(research_phase)
def analysis_phase(self, research_data):
"""Second crew: Analyze the research."""
analyst = Agent(
role="Data Analyst",
goal="Analyze information and extract insights",
backstory="Expert at identifying patterns and trends",
)
task = Task(
description="Analyze this research: {research}",
expected_output="Key insights and trends",
agent=analyst,
)
crew = Crew(agents=[analyst], tasks=[task])
return crew.kickoff(inputs={"research": research_data})
# Stream across both phases
flow = MultiStepFlow()
streaming = flow.kickoff()
current_step = ""
for chunk 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")
print(chunk.content, end="", flush=True)
result = streaming.result
print(f"\n\nFinal analysis: {result}")
```
## Practical Example: Progress Dashboard
Here's a complete example showing how to build a progress dashboard with streaming:
```python Code
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
@start()
def gather_data(self):
researcher = Agent(
role="Data Gatherer",
goal="Collect relevant information",
backstory="Skilled at finding quality sources",
)
task = Task(
description="Gather data on renewable energy trends",
expected_output="Collection of relevant data points",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
self.state["data"] = result.raw
return result.raw
@listen(gather_data)
def analyze_data(self, data):
analyst = Agent(
role="Data Analyst",
goal="Extract meaningful insights",
backstory="Expert at data analysis",
)
task = Task(
description="Analyze: {data}",
expected_output="Key insights and trends",
agent=analyst,
)
crew = Crew(agents=[analyst], tasks=[task])
return crew.kickoff(inputs={"data": data})
async def run_with_dashboard():
flow = ResearchPipeline()
print("="*60)
print("RESEARCH PIPELINE DASHBOARD")
print("="*60)
streaming = await flow.kickoff_async()
current_agent = ""
current_task = ""
chunk_count = 0
async for chunk in streaming:
chunk_count += 1
# Display phase transitions
if chunk.task_name != current_task:
current_task = chunk.task_name
current_agent = chunk.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)
# Display tool usage
elif chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
print(f"\n🔧 Tool: {chunk.tool_call.tool_name}")
# 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"Final output length: {len(str(result))} characters")
asyncio.run(run_with_dashboard())
```
## Streaming with State Management
Streaming works naturally with Flow state management:
```python Code
from pydantic import BaseModel
class AnalysisState(BaseModel):
topic: str = ""
research: str = ""
insights: str = ""
class StatefulStreamingFlow(Flow[AnalysisState]):
stream = True
@start()
def research(self):
# State is available during streaming
topic = self.state.topic
print(f"Researching: {topic}")
researcher = Agent(
role="Researcher",
goal="Research topics thoroughly",
backstory="Expert researcher",
)
task = Task(
description=f"Research {topic}",
expected_output="Research findings",
agent=researcher,
)
crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
self.state.research = result.raw
return result.raw
@listen(research)
def analyze(self, research):
# Access updated state
print(f"Analyzing {len(self.state.research)} chars of research")
analyst = Agent(
role="Analyst",
goal="Extract insights",
backstory="Expert analyst",
)
task = Task(
description="Analyze: {research}",
expected_output="Key insights",
agent=analyst,
)
crew = Crew(agents=[analyst], tasks=[task])
result = crew.kickoff(inputs={"research": research})
self.state.insights = result.raw
return result.raw
# Run with streaming
flow = StatefulStreamingFlow()
streaming = flow.kickoff(inputs={"topic": "quantum computing"})
for chunk in streaming:
print(chunk.content, end="", flush=True)
result = streaming.result
print(f"\n\nFinal state:")
print(f"Topic: {flow.state.topic}")
print(f"Research length: {len(flow.state.research)}")
print(f"Insights length: {len(flow.state.insights)}")
```
## Use Cases
Flow streaming is particularly valuable for:
- **Multi-Stage Workflows**: Show progress across research, analysis, and synthesis phases
- **Complex Pipelines**: Provide visibility into long-running data processing flows
- **Interactive Applications**: Build responsive UIs that display intermediate results
- **Monitoring and Debugging**: Observe flow execution and crew interactions in real-time
- **Progress Tracking**: Show users which stage of the workflow is currently executing
- **Live Dashboards**: Create monitoring interfaces for production flows
## Stream Chunk Types
Like crew streaming, flow chunks can be of different types:
### TEXT Chunks
Standard text content from LLM responses:
```python Code
for chunk in streaming:
if chunk.chunk_type == StreamChunkType.TEXT:
print(chunk.content, end="", flush=True)
```
### TOOL_CALL Chunks
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}")
```
## Error Handling
Handle errors gracefully during streaming:
```python Code
flow = ResearchFlow()
streaming = flow.kickoff()
try:
for chunk in streaming:
print(chunk.content, end="", flush=True)
result = streaming.result
print(f"\nSuccess! Result: {result}")
except Exception as e:
print(f"\nError during flow execution: {e}")
if streaming.is_completed:
print("Streaming completed but flow encountered an error")
```
## 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
- 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
- Streaming adds minimal overhead to flow execution
## Combining with Flow Visualization
You can combine streaming with flow visualization to provide a complete picture:
```python Code
# Generate flow visualization
flow = ResearchFlow()
flow.plot("research_flow") # Creates HTML visualization
# Run with streaming
streaming = flow.kickoff()
for chunk in streaming:
print(chunk.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.

View File

@@ -0,0 +1,600 @@
---
title: Tool Call Hooks
description: Learn how to use tool call hooks to intercept, modify, and control tool execution in CrewAI
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.
## 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
## Hook Types
### Before Tool Call Hooks
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
**Signature:**
```python
def before_hook(context: ToolCallHookContext) -> bool | None:
# Return False to block execution
# Return True or None to allow execution
...
```
### After Tool Call Hooks
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
...
```
## Tool Hook Context
The `ToolCallHookContext` object provides comprehensive access to tool execution state:
```python
class ToolCallHookContext:
tool_name: str # Name of the tool being called
tool_input: dict[str, Any] # Mutable tool input parameters
tool: CrewStructuredTool # Tool instance reference
agent: Agent | BaseAgent | None # Agent executing the tool
task: Task | None # Current task
crew: Crew | None # Crew instance
tool_result: str | None # Tool result (after hooks only)
```
### Modifying Tool Inputs
**Important:** Always modify tool inputs in-place:
```python
# ✅ Correct - modify in-place
def sanitize_input(context: ToolCallHookContext) -> None:
context.tool_input['query'] = context.tool_input['query'].lower()
# ❌ Wrong - replaces dict reference
def wrong_approach(context: ToolCallHookContext) -> None:
context.tool_input = {'query': 'new query'}
```
## Registration Methods
### 1. Global Hook Registration
Register hooks that apply to all tool calls across all crews:
```python
from crewai.hooks import register_before_tool_call_hook, register_after_tool_call_hook
def log_tool_call(context):
print(f"Tool: {context.tool_name}")
print(f"Input: {context.tool_input}")
return None # Allow execution
register_before_tool_call_hook(log_tool_call)
```
### 2. Decorator-Based Registration
Use decorators for cleaner syntax:
```python
from crewai.hooks import before_tool_call, after_tool_call
@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):
# 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
@crew
def crew(self) -> Crew:
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True
)
```
## Common Use Cases
### 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
```
### 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
```
### 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
# 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
```
### 4. Result Sanitization
```python
@after_tool_call
def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
if not context.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
)
# Remove email addresses
result = re.sub(
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
'[EMAIL-REDACTED]',
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
```python
import time
from collections import defaultdict
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0, 'failures': 0})
@before_tool_call
def start_timer(context: ToolCallHookContext) -> None:
context.tool_input['_start_time'] = time.time()
return None
@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
```
### 6. Rate Limiting
```python
from collections import defaultdict
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
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
```
## Hook Management
### Unregistering Hooks
```python
from crewai.hooks import (
unregister_before_tool_call_hook,
unregister_after_tool_call_hook
)
# Unregister specific hook
def my_hook(context):
...
register_before_tool_call_hook(my_hook)
# Later...
success = unregister_before_tool_call_hook(my_hook)
print(f"Unregistered: {success}")
```
### Clearing Hooks
```python
from crewai.hooks import (
clear_before_tool_call_hooks,
clear_after_tool_call_hooks,
clear_all_tool_call_hooks
)
# 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
return None
```
### Context-Aware Input Modification
```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']
# 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
```
## 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
```
## 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
### Input Modifications Not Working
- Use in-place modifications: `context.tool_input['key'] = value`
- Don't replace the dict: `context.tool_input = {}`
### Result Modifications Not Working
- Return the modified string from after hooks
- 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
## Conclusion
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.

View File

@@ -0,0 +1,344 @@
---
title: MCP DSL Integration
description: Learn how to use CrewAI's simple DSL syntax to integrate MCP servers directly with your agents using the mcps field.
icon: code
mode: "wide"
---
## Overview
CrewAI's MCP DSL (Domain Specific Language) integration provides the **simplest way** to connect your agents to MCP (Model Context Protocol) servers. Just add an `mcps` field to your agent and CrewAI handles all the complexity automatically.
<Info>
This is the **recommended approach** for most MCP use cases. For advanced scenarios requiring manual connection management, see [MCPServerAdapter](/en/mcp/overview#advanced-mcpserveradapter).
</Info>
## Basic Usage
Add MCP servers to your agent using the `mcps` field:
```python
from crewai import Agent
agent = Agent(
role="Research Assistant",
goal="Help with research and analysis tasks",
backstory="Expert assistant with access to advanced research tools",
mcps=[
"https://mcp.exa.ai/mcp?api_key=your_key&profile=research"
]
)
# MCP tools are now automatically available!
# No need for manual connection management or tool configuration
```
## Supported Reference Formats
### External MCP Remote Servers
```python
# Basic HTTPS server
"https://api.example.com/mcp"
# Server with authentication
"https://mcp.exa.ai/mcp?api_key=your_key&profile=your_profile"
# Server with custom path
"https://services.company.com/api/v1/mcp"
```
### Specific Tool Selection
Use the `#` syntax to select specific tools from a server:
```python
# Get only the forecast tool from weather server
"https://weather.api.com/mcp#get_forecast"
# Get only the search tool from Exa
"https://mcp.exa.ai/mcp?api_key=your_key#web_search_exa"
```
### CrewAI AOP Marketplace
Access tools from the CrewAI AOP marketplace:
```python
# Full service with all tools
"crewai-amp:financial-data"
# Specific tool from AMP service
"crewai-amp:research-tools#pubmed_search"
# Multiple AMP services
mcps=[
"crewai-amp:weather-insights",
"crewai-amp:market-analysis",
"crewai-amp:social-media-monitoring"
]
```
## Complete Example
Here's a complete example using multiple MCP servers:
```python
from crewai import Agent, Task, Crew, Process
# Create agent with multiple MCP sources
multi_source_agent = Agent(
role="Multi-Source Research Analyst",
goal="Conduct comprehensive research using multiple data sources",
backstory="""Expert researcher with access to web search, weather data,
financial information, and academic research tools""",
mcps=[
# External MCP servers
"https://mcp.exa.ai/mcp?api_key=your_exa_key&profile=research",
"https://weather.api.com/mcp#get_current_conditions",
# CrewAI AOP marketplace
"crewai-amp:financial-insights",
"crewai-amp:academic-research#pubmed_search",
"crewai-amp:market-intelligence#competitor_analysis"
]
)
# Create comprehensive research task
research_task = Task(
description="""Research the impact of AI agents on business productivity.
Include current weather impacts on remote work, financial market trends,
and recent academic publications on AI agent frameworks.""",
expected_output="""Comprehensive report covering:
1. AI agent business impact analysis
2. Weather considerations for remote work
3. Financial market trends related to AI
4. Academic research citations and insights
5. Competitive landscape analysis""",
agent=multi_source_agent
)
# Create and execute crew
research_crew = Crew(
agents=[multi_source_agent],
tasks=[research_task],
process=Process.sequential,
verbose=True
)
result = research_crew.kickoff()
print(f"Research completed with {len(multi_source_agent.mcps)} MCP data sources")
```
## Tool Naming and Organization
CrewAI automatically handles tool naming to prevent conflicts:
```python
# Original MCP server has tools: "search", "analyze"
# CrewAI creates tools: "mcp_exa_ai_search", "mcp_exa_ai_analyze"
agent = Agent(
role="Tool Organization Demo",
goal="Show how tool naming works",
backstory="Demonstrates automatic tool organization",
mcps=[
"https://mcp.exa.ai/mcp?api_key=key", # Tools: mcp_exa_ai_*
"https://weather.service.com/mcp", # Tools: weather_service_com_*
"crewai-amp:financial-data" # Tools: financial_data_*
]
)
# Each server's tools get unique prefixes based on the server name
# This prevents naming conflicts between different MCP servers
```
## Error Handling and Resilience
The MCP DSL is designed to be robust and user-friendly:
### Graceful Server Failures
```python
agent = Agent(
role="Resilient Researcher",
goal="Research despite server issues",
backstory="Experienced researcher who adapts to available tools",
mcps=[
"https://primary-server.com/mcp", # Primary data source
"https://backup-server.com/mcp", # Backup if primary fails
"https://unreachable-server.com/mcp", # Will be skipped with warning
"crewai-amp:reliable-service" # Reliable AMP service
]
)
# Agent will:
# 1. Successfully connect to working servers
# 2. Log warnings for failing servers
# 3. Continue with available tools
# 4. Not crash or hang on server failures
```
### Timeout Protection
All MCP operations have built-in timeouts:
- **Connection timeout**: 10 seconds
- **Tool execution timeout**: 30 seconds
- **Discovery timeout**: 15 seconds
```python
# These servers will timeout gracefully if unresponsive
mcps=[
"https://slow-server.com/mcp", # Will timeout after 10s if unresponsive
"https://overloaded-api.com/mcp" # Will timeout if discovery takes > 15s
]
```
## Performance Features
### Automatic Caching
Tool schemas are cached for 5 minutes to improve performance:
```python
# First agent creation - discovers tools from server
agent1 = Agent(role="First", goal="Test", backstory="Test",
mcps=["https://api.example.com/mcp"])
# Second agent creation (within 5 minutes) - uses cached tool schemas
agent2 = Agent(role="Second", goal="Test", backstory="Test",
mcps=["https://api.example.com/mcp"]) # Much faster!
```
### On-Demand Connections
Tool connections are established only when tools are actually used:
```python
# Agent creation is fast - no MCP connections made yet
agent = Agent(
role="On-Demand Agent",
goal="Use tools efficiently",
backstory="Efficient agent that connects only when needed",
mcps=["https://api.example.com/mcp"]
)
# MCP connection is made only when a tool is actually executed
# This minimizes connection overhead and improves startup performance
```
## Integration with Existing Features
MCP tools work seamlessly with other CrewAI features:
```python
from crewai.tools import BaseTool
class CustomTool(BaseTool):
name: str = "custom_analysis"
description: str = "Custom analysis tool"
def _run(self, **kwargs):
return "Custom analysis result"
agent = Agent(
role="Full-Featured Agent",
goal="Use all available tool types",
backstory="Agent with comprehensive tool access",
# All tool types work together
tools=[CustomTool()], # Custom tools
apps=["gmail", "slack"], # Platform integrations
mcps=[ # MCP servers
"https://mcp.exa.ai/mcp?api_key=key",
"crewai-amp:research-tools"
],
verbose=True,
max_iter=15
)
```
## Best Practices
### 1. Use Specific Tools When Possible
```python
# Good - only get the tools you need
mcps=["https://weather.api.com/mcp#get_forecast"]
# Less efficient - gets all tools from server
mcps=["https://weather.api.com/mcp"]
```
### 2. Handle Authentication Securely
```python
import os
# Store API keys in environment variables
exa_key = os.getenv("EXA_API_KEY")
exa_profile = os.getenv("EXA_PROFILE")
agent = Agent(
role="Secure Agent",
goal="Use MCP tools securely",
backstory="Security-conscious agent",
mcps=[f"https://mcp.exa.ai/mcp?api_key={exa_key}&profile={exa_profile}"]
)
```
### 3. Plan for Server Failures
```python
# Always include backup options
mcps=[
"https://primary-api.com/mcp", # Primary choice
"https://backup-api.com/mcp", # Backup option
"crewai-amp:reliable-service" # AMP fallback
]
```
### 4. Use Descriptive Agent Roles
```python
agent = Agent(
role="Weather-Enhanced Market Analyst",
goal="Analyze markets considering weather impacts",
backstory="Financial analyst with access to weather data for agricultural market insights",
mcps=[
"https://weather.service.com/mcp#get_forecast",
"crewai-amp:financial-data#stock_analysis"
]
)
```
## Troubleshooting
### Common Issues
**No tools discovered:**
```python
# Check your MCP server URL and authentication
# Verify the server is running and accessible
mcps=["https://mcp.example.com/mcp?api_key=valid_key"]
```
**Connection timeouts:**
```python
# Server may be slow or overloaded
# CrewAI will log warnings and continue with other servers
# Check server status or try backup servers
```
**Authentication failures:**
```python
# Verify API keys and credentials
# Check server documentation for required parameters
# Ensure query parameters are properly URL encoded
```
## Advanced: MCPServerAdapter
For complex scenarios requiring manual connection management, use the `MCPServerAdapter` class from `crewai-tools`. Using a Python context manager (`with` statement) is the recommended approach as it automatically handles starting and stopping the connection to the MCP server.

View File

@@ -8,14 +8,83 @@ mode: "wide"
## Overview
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) provides a standardized way for AI agents to provide context to LLMs by communicating with external services, known as MCP Servers.
The `crewai-tools` library extends CrewAI's capabilities by allowing you to seamlessly integrate tools from these MCP servers into your agents.
This gives your crews access to a vast ecosystem of functionalities.
CrewAI offers **two approaches** for MCP integration:
### 🚀 **Simple DSL Integration** (Recommended)
Use the `mcps` field directly on agents for seamless MCP tool integration. The DSL supports both **string references** (for quick setup) and **structured configurations** (for full control).
#### String-Based References (Quick Setup)
Perfect for remote HTTPS servers and CrewAI AOP marketplace:
```python
from crewai import Agent
agent = Agent(
role="Research Analyst",
goal="Research and analyze information",
backstory="Expert researcher with access to external tools",
mcps=[
"https://mcp.exa.ai/mcp?api_key=your_key", # External MCP server
"https://api.weather.com/mcp#get_forecast", # Specific tool from server
"crewai-amp:financial-data", # CrewAI AOP marketplace
"crewai-amp:research-tools#pubmed_search" # Specific AMP tool
]
)
# MCP tools are now automatically available to your agent!
```
#### Structured Configurations (Full Control)
For complete control over connection settings, tool filtering, and all transport types:
```python
from crewai import Agent
from crewai.mcp import MCPServerStdio, MCPServerHTTP, MCPServerSSE
from crewai.mcp.filters import create_static_tool_filter
agent = Agent(
role="Advanced Research Analyst",
goal="Research with full control over MCP connections",
backstory="Expert researcher with advanced tool access",
mcps=[
# Stdio transport for local servers
MCPServerStdio(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem"],
env={"API_KEY": "your_key"},
tool_filter=create_static_tool_filter(
allowed_tool_names=["read_file", "list_directory"]
),
cache_tools_list=True,
),
# HTTP/Streamable HTTP transport for remote servers
MCPServerHTTP(
url="https://api.example.com/mcp",
headers={"Authorization": "Bearer your_token"},
streamable=True,
cache_tools_list=True,
),
# SSE transport for real-time streaming
MCPServerSSE(
url="https://stream.example.com/mcp/sse",
headers={"Authorization": "Bearer your_token"},
),
]
)
```
### 🔧 **Advanced: MCPServerAdapter** (For Complex Scenarios)
For advanced use cases requiring manual connection management, the `crewai-tools` library provides the `MCPServerAdapter` class.
We currently support the following transport mechanisms:
- **Stdio**: for local servers (communication via standard input/output between processes on the same machine)
- **Server-Sent Events (SSE)**: for remote servers (unidirectional, real-time data streaming from server to client over HTTP)
- **Streamable HTTP**: for remote servers (flexible, potentially bi-directional communication over HTTP, often utilizing SSE for server-to-client streams)
- **Streamable HTTPS**: for remote servers (flexible, potentially bi-directional communication over HTTPS, often utilizing SSE for server-to-client streams)
## Video Tutorial
Watch this video tutorial for a comprehensive guide on MCP integration with CrewAI:
@@ -31,17 +100,337 @@ Watch this video tutorial for a comprehensive guide on MCP integration with Crew
## Installation
Before you start using MCP with `crewai-tools`, you need to install the `mcp` extra `crewai-tools` dependency with the following command:
CrewAI MCP integration requires the `mcp` library:
```shell
# For Simple DSL Integration (Recommended)
uv add mcp
# For Advanced MCPServerAdapter usage
uv pip install 'crewai-tools[mcp]'
```
## Key Concepts & Getting Started
## Quick Start: Simple DSL Integration
The `MCPServerAdapter` class from `crewai-tools` is the primary way to connect to an MCP server and make its tools available to your CrewAI agents. It supports different transport mechanisms and simplifies connection management.
The easiest way to integrate MCP servers is using the `mcps` field on your agents. You can use either string references or structured configurations.
Using a Python context manager (`with` statement) is the **recommended approach** for `MCPServerAdapter`. It automatically handles starting and stopping the connection to the MCP server.
### Quick Start with String References
```python
from crewai import Agent, Task, Crew
# Create agent with MCP tools using string references
research_agent = Agent(
role="Research Analyst",
goal="Find and analyze information using advanced search tools",
backstory="Expert researcher with access to multiple data sources",
mcps=[
"https://mcp.exa.ai/mcp?api_key=your_key&profile=your_profile",
"crewai-amp:weather-service#current_conditions"
]
)
# Create task
research_task = Task(
description="Research the latest developments in AI agent frameworks",
expected_output="Comprehensive research report with citations",
agent=research_agent
)
# Create and run crew
crew = Crew(agents=[research_agent], tasks=[research_task])
result = crew.kickoff()
```
### Quick Start with Structured Configurations
```python
from crewai import Agent, Task, Crew
from crewai.mcp import MCPServerStdio, MCPServerHTTP, MCPServerSSE
# Create agent with structured MCP configurations
research_agent = Agent(
role="Research Analyst",
goal="Find and analyze information using advanced search tools",
backstory="Expert researcher with access to multiple data sources",
mcps=[
# Local stdio server
MCPServerStdio(
command="python",
args=["local_server.py"],
env={"API_KEY": "your_key"},
),
# Remote HTTP server
MCPServerHTTP(
url="https://api.research.com/mcp",
headers={"Authorization": "Bearer your_token"},
),
]
)
# Create task
research_task = Task(
description="Research the latest developments in AI agent frameworks",
expected_output="Comprehensive research report with citations",
agent=research_agent
)
# Create and run crew
crew = Crew(agents=[research_agent], tasks=[research_task])
result = crew.kickoff()
```
That's it! The MCP tools are automatically discovered and available to your agent.
## MCP Reference Formats
The `mcps` field supports both **string references** (for quick setup) and **structured configurations** (for full control). You can mix both formats in the same list.
### String-Based References
#### External MCP Servers
```python
mcps=[
# Full server - get all available tools
"https://mcp.example.com/api",
# Specific tool from server using # syntax
"https://api.weather.com/mcp#get_current_weather",
# Server with authentication parameters
"https://mcp.exa.ai/mcp?api_key=your_key&profile=your_profile"
]
```
#### CrewAI AOP Marketplace
```python
mcps=[
# Full AMP MCP service - get all available tools
"crewai-amp:financial-data",
# Specific tool from AMP service using # syntax
"crewai-amp:research-tools#pubmed_search",
# Multiple AMP services
"crewai-amp:weather-service",
"crewai-amp:market-analysis"
]
```
### Structured Configurations
#### Stdio Transport (Local Servers)
Perfect for local MCP servers that run as processes:
```python
from crewai.mcp import MCPServerStdio
from crewai.mcp.filters import create_static_tool_filter
mcps=[
MCPServerStdio(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem"],
env={"API_KEY": "your_key"},
tool_filter=create_static_tool_filter(
allowed_tool_names=["read_file", "write_file"]
),
cache_tools_list=True,
),
# Python-based server
MCPServerStdio(
command="python",
args=["path/to/server.py"],
env={"UV_PYTHON": "3.12", "API_KEY": "your_key"},
),
]
```
#### HTTP/Streamable HTTP Transport (Remote Servers)
For remote MCP servers over HTTP/HTTPS:
```python
from crewai.mcp import MCPServerHTTP
mcps=[
# Streamable HTTP (default)
MCPServerHTTP(
url="https://api.example.com/mcp",
headers={"Authorization": "Bearer your_token"},
streamable=True,
cache_tools_list=True,
),
# Standard HTTP
MCPServerHTTP(
url="https://api.example.com/mcp",
headers={"Authorization": "Bearer your_token"},
streamable=False,
),
]
```
#### SSE Transport (Real-Time Streaming)
For remote servers using Server-Sent Events:
```python
from crewai.mcp import MCPServerSSE
mcps=[
MCPServerSSE(
url="https://stream.example.com/mcp/sse",
headers={"Authorization": "Bearer your_token"},
cache_tools_list=True,
),
]
```
### Mixed References
You can combine string references and structured configurations:
```python
from crewai.mcp import MCPServerStdio, MCPServerHTTP
mcps=[
# String references
"https://external-api.com/mcp", # External server
"crewai-amp:financial-insights", # AMP service
# Structured configurations
MCPServerStdio(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem"],
),
MCPServerHTTP(
url="https://api.example.com/mcp",
headers={"Authorization": "Bearer token"},
),
]
```
### Tool Filtering
Structured configurations support advanced tool filtering:
```python
from crewai.mcp import MCPServerStdio
from crewai.mcp.filters import create_static_tool_filter, create_dynamic_tool_filter, ToolFilterContext
# Static filtering (allow/block lists)
static_filter = create_static_tool_filter(
allowed_tool_names=["read_file", "write_file"],
blocked_tool_names=["delete_file"],
)
# Dynamic filtering (context-aware)
def dynamic_filter(context: ToolFilterContext, tool: dict) -> bool:
# Block dangerous tools for certain agent roles
if context.agent.role == "Code Reviewer":
if "delete" in tool.get("name", "").lower():
return False
return True
mcps=[
MCPServerStdio(
command="npx",
args=["-y", "@modelcontextprotocol/server-filesystem"],
tool_filter=static_filter, # or dynamic_filter
),
]
```
## Configuration Parameters
Each transport type supports specific configuration options:
### MCPServerStdio Parameters
- **`command`** (required): Command to execute (e.g., `"python"`, `"node"`, `"npx"`, `"uvx"`)
- **`args`** (optional): List of command arguments (e.g., `["server.py"]` or `["-y", "@mcp/server"]`)
- **`env`** (optional): Dictionary of environment variables to pass to the process
- **`tool_filter`** (optional): Tool filter function for filtering available tools
- **`cache_tools_list`** (optional): Whether to cache the tool list for faster subsequent access (default: `False`)
### MCPServerHTTP Parameters
- **`url`** (required): Server URL (e.g., `"https://api.example.com/mcp"`)
- **`headers`** (optional): Dictionary of HTTP headers for authentication or other purposes
- **`streamable`** (optional): Whether to use streamable HTTP transport (default: `True`)
- **`tool_filter`** (optional): Tool filter function for filtering available tools
- **`cache_tools_list`** (optional): Whether to cache the tool list for faster subsequent access (default: `False`)
### MCPServerSSE Parameters
- **`url`** (required): Server URL (e.g., `"https://api.example.com/mcp/sse"`)
- **`headers`** (optional): Dictionary of HTTP headers for authentication or other purposes
- **`tool_filter`** (optional): Tool filter function for filtering available tools
- **`cache_tools_list`** (optional): Whether to cache the tool list for faster subsequent access (default: `False`)
### Common Parameters
All transport types support:
- **`tool_filter`**: Filter function to control which tools are available. Can be:
- `None` (default): All tools are available
- Static filter: Created with `create_static_tool_filter()` for allow/block lists
- Dynamic filter: Created with `create_dynamic_tool_filter()` for context-aware filtering
- **`cache_tools_list`**: When `True`, caches the tool list after first discovery to improve performance on subsequent connections
## Key Features
- 🔄 **Automatic Tool Discovery**: Tools are automatically discovered and integrated
- 🏷️ **Name Collision Prevention**: Server names are prefixed to tool names
- ⚡ **Performance Optimized**: On-demand connections with schema caching
- 🛡️ **Error Resilience**: Graceful handling of unavailable servers
- ⏱️ **Timeout Protection**: Built-in timeouts prevent hanging connections
- 📊 **Transparent Integration**: Works seamlessly with existing CrewAI features
- 🔧 **Full Transport Support**: Stdio, HTTP/Streamable HTTP, and SSE transports
- 🎯 **Advanced Filtering**: Static and dynamic tool filtering capabilities
- 🔐 **Flexible Authentication**: Support for headers, environment variables, and query parameters
## Error Handling
The MCP DSL integration is designed to be resilient and handles failures gracefully:
```python
from crewai import Agent
from crewai.mcp import MCPServerStdio, MCPServerHTTP
agent = Agent(
role="Resilient Agent",
goal="Continue working despite server issues",
backstory="Agent that handles failures gracefully",
mcps=[
# String references
"https://reliable-server.com/mcp", # Will work
"https://unreachable-server.com/mcp", # Will be skipped gracefully
"crewai-amp:working-service", # Will work
# Structured configs
MCPServerStdio(
command="python",
args=["reliable_server.py"], # Will work
),
MCPServerHTTP(
url="https://slow-server.com/mcp", # Will timeout gracefully
),
]
)
# Agent will use tools from working servers and log warnings for failing ones
```
All connection errors are handled gracefully:
- **Connection failures**: Logged as warnings, agent continues with available tools
- **Timeout errors**: Connections timeout after 30 seconds (configurable)
- **Authentication errors**: Logged clearly for debugging
- **Invalid configurations**: Validation errors are raised at agent creation time
## Advanced: MCPServerAdapter
For complex scenarios requiring manual connection management, use the `MCPServerAdapter` class from `crewai-tools`. Using a Python context manager (`with` statement) is the recommended approach as it automatically handles starting and stopping the connection to the MCP server.
## Connection Configuration
@@ -241,11 +630,19 @@ class CrewWithCustomTimeout:
## Explore MCP Integrations
<CardGroup cols={2}>
<Card
title="Simple DSL Integration"
icon="code"
href="/en/mcp/dsl-integration"
color="#3B82F6"
>
**Recommended**: Use the simple `mcps=[]` field syntax for effortless MCP integration.
</Card>
<Card
title="Stdio Transport"
icon="server"
href="/en/mcp/stdio"
color="#3B82F6"
color="#10B981"
>
Connect to local MCP servers via standard input/output. Ideal for scripts and local executables.
</Card>
@@ -253,7 +650,7 @@ class CrewWithCustomTimeout:
title="SSE Transport"
icon="wifi"
href="/en/mcp/sse"
color="#10B981"
color="#F59E0B"
>
Integrate with remote MCP servers using Server-Sent Events for real-time data streaming.
</Card>
@@ -261,7 +658,7 @@ class CrewWithCustomTimeout:
title="Streamable HTTP Transport"
icon="globe"
href="/en/mcp/streamable-http"
color="#F59E0B"
color="#8B5CF6"
>
Utilize flexible Streamable HTTP for robust communication with remote MCP servers.
</Card>
@@ -269,7 +666,7 @@ class CrewWithCustomTimeout:
title="Connecting to Multiple Servers"
icon="layer-group"
href="/en/mcp/multiple-servers"
color="#8B5CF6"
color="#EF4444"
>
Aggregate tools from several MCP servers simultaneously using a single adapter.
</Card>
@@ -277,7 +674,7 @@ class CrewWithCustomTimeout:
title="Security Considerations"
icon="lock"
href="/en/mcp/security"
color="#EF4444"
color="#DC2626"
>
Review important security best practices for MCP integration to keep your agents safe.
</Card>

View File

@@ -0,0 +1,109 @@
---
title: Datadog Integration
description: Learn how to integrate Datadog with CrewAI to submit LLM Observability traces to Datadog.
icon: dog
mode: "wide"
---
# Integrate Datadog with CrewAI
This guide will demonstrate how to integrate **[Datadog LLM Observability](https://docs.datadoghq.com/llm_observability/)** with **CrewAI** using [Datadog auto-instrumentation](https://docs.datadoghq.com/llm_observability/instrumentation/auto_instrumentation?tab=python). By the end of this guide, you will be able to submit LLM Observability traces to Datadog and view your CrewAI agent runs in Datadog LLM Observability's [Agentic Execution View](https://docs.datadoghq.com/llm_observability/monitoring/agent_monitoring).
## What is Datadog LLM Observability?
[Datadog LLM Observability](https://www.datadoghq.com/product/llm-observability/) helps AI engineers, data scientists, and application developers quickly develop, evaluate, and monitor LLM applications. Confidently improve output quality, performance, costs, and overall risk with structured experiments, end-to-end tracing across AI agents, and evaluations.
## Getting Started
### Install Dependencies
```shell
pip install ddtrace crewai crewai-tools
```
### Set Environment Variables
If you do not have a Datadog API key, you can [create an account](https://www.datadoghq.com/) and [get your API key](https://docs.datadoghq.com/account_management/api-app-keys/#api-keys).
You will also need to specify an ML Application name in the following environment variables. An ML Application is a grouping of LLM Observability traces associated with a specific LLM-based application. See [ML Application Naming Guidelines](https://docs.datadoghq.com/llm_observability/instrumentation/sdk?tab=python#application-naming-guidelines) for more information on limitations with ML Application names.
```shell
export DD_API_KEY=<YOUR_DD_API_KEY>
export DD_SITE=<YOUR_DD_SITE>
export DD_LLMOBS_ENABLED=true
export DD_LLMOBS_ML_APP=<YOUR_ML_APP_NAME>
export DD_LLMOBS_AGENTLESS_ENABLED=true
export DD_APM_TRACING_ENABLED=false
```
Additionally, configure any LLM provider API keys
```shell
export OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
export ANTHROPIC_API_KEY=<YOUR_ANTHROPIC_API_KEY>
export GEMINI_API_KEY=<YOUR_GEMINI_API_KEY>
...
```
### Create a CrewAI Agent Application
```python
# crewai_agent.py
from crewai import Agent, Task, Crew
from crewai_tools import (
WebsiteSearchTool
)
web_rag_tool = WebsiteSearchTool()
writer = Agent(
role="Writer",
goal="You make math engaging and understandable for young children through poetry",
backstory="You're an expert in writing haikus but you know nothing of math.",
tools=[web_rag_tool],
)
task = Task(
description=("What is {multiplication}?"),
expected_output=("Compose a haiku that includes the answer."),
agent=writer
)
crew = Crew(
agents=[writer],
tasks=[task],
share_crew=False
)
output = crew.kickoff(dict(multiplication="2 * 2"))
```
### Run the Application with Datadog Auto-Instrumentation
With the [environment variables](#set-environment-variables) set, you can now run the application with Datadog auto-instrumentation.
```shell
ddtrace-run python crewai_agent.py
```
### View the Traces in Datadog
After running the application, you can view the traces in [Datadog LLM Observability's Traces View](https://app.datadoghq.com/llm/traces), selecting the ML Application name you chose from the top-left dropdown.
Clicking on a trace will show you the details of the trace, including total tokens used, number of LLM calls, models used, and estimated cost. Clicking into a specific span will narrow down these details, and show related input, output, and metadata.
<Frame>
<img src="/images/datadog-llm-observability-1.png" alt="Datadog LLM Observability Trace View" />
</Frame>
Additionally, you can view the execution graph view of the trace, which shows the control and data flow of the trace, which will scale with larger agents to show handoffs and relationships between LLM calls, tool calls, and agent interactions.
<Frame>
<img src="/images/datadog-llm-observability-2.png" alt="Datadog LLM Observability Agent Execution Flow View" />
</Frame>
## References
- [Datadog LLM Observability](https://www.datadoghq.com/product/llm-observability/)
- [Datadog LLM Observability CrewAI Auto-Instrumentation](https://docs.datadoghq.com/llm_observability/instrumentation/auto_instrumentation?tab=python#crew-ai)

View File

@@ -733,9 +733,7 @@ Here's a basic configuration to route requests to OpenAI, specifically using GPT
- Collect relevant metadata to filter logs
- Enforce access permissions
Create API keys through:
- [Portkey App](https://app.portkey.ai/)
- [API Key Management API](/en/api-reference/admin-api/control-plane/api-keys/create-api-key)
Create API keys through the [Portkey App](https://app.portkey.ai/)
Example using Python SDK:
```python
@@ -758,7 +756,7 @@ Here's a basic configuration to route requests to OpenAI, specifically using GPT
)
```
For detailed key management instructions, see our [API Keys documentation](/en/api-reference/admin-api/control-plane/api-keys/create-api-key).
For detailed key management instructions, see the [Portkey documentation](https://portkey.ai/docs).
</Accordion>
<Accordion title="Step 4: Deploy & Monitor">

View File

@@ -1,6 +1,6 @@
---
title: CrewAI Tracing
description: Built-in tracing for CrewAI Crews and Flows with the CrewAI AMP platform
description: Built-in tracing for CrewAI Crews and Flows with the CrewAI AOP platform
icon: magnifying-glass-chart
mode: "wide"
---
@@ -9,7 +9,7 @@ mode: "wide"
CrewAI provides built-in tracing capabilities that allow you to monitor and debug your Crews and Flows in real-time. This guide demonstrates how to enable tracing for both **Crews** and **Flows** using CrewAI's integrated observability platform.
> **What is CrewAI Tracing?** CrewAI's built-in tracing provides comprehensive observability for your AI agents, including agent decisions, task execution timelines, tool usage, and LLM calls - all accessible through the [CrewAI AMP platform](https://app.crewai.com).
> **What is CrewAI Tracing?** CrewAI's built-in tracing provides comprehensive observability for your AI agents, including agent decisions, task execution timelines, tool usage, and LLM calls - all accessible through the [CrewAI AOP platform](https://app.crewai.com).
![CrewAI Tracing Interface](/images/crewai-tracing.png)
@@ -17,7 +17,7 @@ CrewAI provides built-in tracing capabilities that allow you to monitor and debu
Before you can use CrewAI tracing, you need:
1. **CrewAI AMP Account**: Sign up for a free account at [app.crewai.com](https://app.crewai.com)
1. **CrewAI AOP Account**: Sign up for a free account at [app.crewai.com](https://app.crewai.com)
2. **CLI Authentication**: Use the CrewAI CLI to authenticate your local environment
```bash
@@ -26,9 +26,9 @@ crewai login
## Setup Instructions
### Step 1: Create Your CrewAI AMP Account
### Step 1: Create Your CrewAI AOP Account
Visit [app.crewai.com](https://app.crewai.com) and create your free account. This will give you access to the CrewAI AMP platform where you can view traces, metrics, and manage your crews.
Visit [app.crewai.com](https://app.crewai.com) and create your free account. This will give you access to the CrewAI AOP platform where you can view traces, metrics, and manage your crews.
### Step 2: Install CrewAI CLI and Authenticate
@@ -38,7 +38,7 @@ If you haven't already, install CrewAI with the CLI tools:
uv add crewai[tools]
```
Then authenticate your CLI with your CrewAI AMP account:
Then authenticate your CLI with your CrewAI AOP account:
```bash
crewai login
@@ -47,7 +47,7 @@ crewai login
This command will:
1. Open your browser to the authentication page
2. Prompt you to enter a device code
3. Authenticate your local environment with your CrewAI AMP account
3. Authenticate your local environment with your CrewAI AOP account
4. Enable tracing capabilities for your local development
### Step 3: Enable Tracing in Your Crew
@@ -147,9 +147,9 @@ flow = ExampleFlow(tracing=True)
result = flow.kickoff()
```
### Step 5: View Traces in the CrewAI AMP Dashboard
### Step 5: View Traces in the CrewAI AOP Dashboard
After running the crew or flow, you can view the traces generated by your CrewAI application in the CrewAI AMP dashboard. You should see detailed steps of the agent interactions, tool usages, and LLM calls.
After running the crew or flow, you can view the traces generated by your CrewAI application in the CrewAI AOP dashboard. You should see detailed steps of the agent interactions, tool usages, and LLM calls.
Just click on the link below to view the traces or head over to the traces tab in the dashboard [here](https://app.crewai.com/crewai_plus/trace_batches)
![CrewAI Tracing Interface](/images/view-traces.png)
@@ -172,7 +172,7 @@ When this environment variable is set, all Crews and Flows will automatically ha
## Viewing Your Traces
### Access the CrewAI AMP Dashboard
### Access the CrewAI AOP Dashboard
1. Visit [app.crewai.com](https://app.crewai.com) and log in to your account
2. Navigate to your project dashboard

View File

@@ -209,9 +209,9 @@ Follow the steps below to get Crewing! 🚣‍♂️
</Step>
<Step title="Enterprise Alternative: Create in Crew Studio">
For CrewAI AMP users, you can create the same crew without writing code:
For CrewAI AOP users, you can create the same crew without writing code:
1. Log in to your CrewAI AMP account (create a free account at [app.crewai.com](https://app.crewai.com))
1. Log in to your CrewAI AOP account (create a free account at [app.crewai.com](https://app.crewai.com))
2. Open Crew Studio
3. Type what is the automation you're trying to build
4. Create your tasks visually and connect them in sequence
@@ -219,8 +219,8 @@ Follow the steps below to get Crewing! 🚣‍♂️
![Crew Studio Quickstart](/images/enterprise/crew-studio-interface.png)
<Card title="Try CrewAI AMP" icon="rocket" href="https://app.crewai.com">
Start your free account at CrewAI AMP
<Card title="Try CrewAI AOP" icon="rocket" href="https://app.crewai.com">
Start your free account at CrewAI AOP
</Card>
</Step>
<Step title="View your final report">
@@ -340,9 +340,9 @@ email_summarizer_task:
## Deploying Your Crew
The easiest way to deploy your crew to production is through [CrewAI AMP](http://app.crewai.com).
The easiest way to deploy your crew to production is through [CrewAI AOP](http://app.crewai.com).
Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI AMP](http://app.crewai.com) using the CLI.
Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI AOP](http://app.crewai.com) using the CLI.
<iframe
className="w-full aspect-video rounded-xl"
@@ -359,7 +359,7 @@ Watch this video tutorial for a step-by-step demonstration of deploying your cre
icon="rocket"
href="http://app.crewai.com"
>
Get started with CrewAI AMP and deploy your crew in a production environment with just a few clicks.
Get started with CrewAI AOP and deploy your crew in a production environment with just a few clicks.
</Card>
<Card
title="Join the Community"

View File

@@ -77,7 +77,7 @@ The `RagTool` accepts the following parameters:
- **summarize**: Optional. Whether to summarize the retrieved content. Default is `False`.
- **adapter**: Optional. A custom adapter for the knowledge base. If not provided, a CrewAIRagAdapter will be used.
- **config**: Optional. Configuration for the underlying CrewAI RAG system.
- **config**: Optional. Configuration for the underlying CrewAI RAG system. Accepts a `RagToolConfig` TypedDict with optional `embedding_model` (ProviderSpec) and `vectordb` (VectorDbConfig) keys. All configuration values provided programmatically take precedence over environment variables.
## Adding Content
@@ -127,26 +127,528 @@ You can customize the behavior of the `RagTool` by providing a configuration dic
```python Code
from crewai_tools import RagTool
from crewai_tools.tools.rag import RagToolConfig, VectorDbConfig, ProviderSpec
# Create a RAG tool with custom configuration
config = {
"vectordb": {
"provider": "qdrant",
"config": {
"collection_name": "my-collection"
}
},
"embedding_model": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small"
}
vectordb: VectorDbConfig = {
"provider": "qdrant",
"config": {
"collection_name": "my-collection"
}
}
embedding_model: ProviderSpec = {
"provider": "openai",
"config": {
"model_name": "text-embedding-3-small"
}
}
config: RagToolConfig = {
"vectordb": vectordb,
"embedding_model": embedding_model
}
rag_tool = RagTool(config=config, summarize=True)
```
## Embedding Model Configuration
The `embedding_model` parameter accepts a `crewai.rag.embeddings.types.ProviderSpec` dictionary with the structure:
```python
{
"provider": "provider-name", # Required
"config": { # Optional
# Provider-specific configuration
}
}
```
### Supported Providers
<AccordionGroup>
<Accordion title="OpenAI">
```python main.py
from crewai.rag.embeddings.providers.openai.types import OpenAIProviderSpec
embedding_model: OpenAIProviderSpec = {
"provider": "openai",
"config": {
"api_key": "your-api-key",
"model_name": "text-embedding-ada-002",
"dimensions": 1536,
"organization_id": "your-org-id",
"api_base": "https://api.openai.com/v1",
"api_version": "v1",
"default_headers": {"Custom-Header": "value"}
}
}
```
**Config Options:**
- `api_key` (str): OpenAI API key
- `model_name` (str): Model to use. Default: `text-embedding-ada-002`. Options: `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002`
- `dimensions` (int): Number of dimensions for the embedding
- `organization_id` (str): OpenAI organization ID
- `api_base` (str): Custom API base URL
- `api_version` (str): API version
- `default_headers` (dict): Custom headers for API requests
**Environment Variables:**
- `OPENAI_API_KEY` or `EMBEDDINGS_OPENAI_API_KEY`: `api_key`
- `OPENAI_ORGANIZATION_ID` or `EMBEDDINGS_OPENAI_ORGANIZATION_ID`: `organization_id`
- `OPENAI_MODEL_NAME` or `EMBEDDINGS_OPENAI_MODEL_NAME`: `model_name`
- `OPENAI_API_BASE` or `EMBEDDINGS_OPENAI_API_BASE`: `api_base`
- `OPENAI_API_VERSION` or `EMBEDDINGS_OPENAI_API_VERSION`: `api_version`
- `OPENAI_DIMENSIONS` or `EMBEDDINGS_OPENAI_DIMENSIONS`: `dimensions`
</Accordion>
<Accordion title="Cohere">
```python main.py
from crewai.rag.embeddings.providers.cohere.types import CohereProviderSpec
embedding_model: CohereProviderSpec = {
"provider": "cohere",
"config": {
"api_key": "your-api-key",
"model_name": "embed-english-v3.0"
}
}
```
**Config Options:**
- `api_key` (str): Cohere API key
- `model_name` (str): Model to use. Default: `large`. Options: `embed-english-v3.0`, `embed-multilingual-v3.0`, `large`, `small`
**Environment Variables:**
- `COHERE_API_KEY` or `EMBEDDINGS_COHERE_API_KEY`: `api_key`
- `EMBEDDINGS_COHERE_MODEL_NAME`: `model_name`
</Accordion>
<Accordion title="VoyageAI">
```python main.py
from crewai.rag.embeddings.providers.voyageai.types import VoyageAIProviderSpec
embedding_model: VoyageAIProviderSpec = {
"provider": "voyageai",
"config": {
"api_key": "your-api-key",
"model": "voyage-3",
"input_type": "document",
"truncation": True,
"output_dtype": "float32",
"output_dimension": 1024,
"max_retries": 3,
"timeout": 60.0
}
}
```
**Config Options:**
- `api_key` (str): VoyageAI API key
- `model` (str): Model to use. Default: `voyage-2`. Options: `voyage-3`, `voyage-3-lite`, `voyage-code-3`, `voyage-large-2`
- `input_type` (str): Type of input. Options: `document` (for storage), `query` (for search)
- `truncation` (bool): Whether to truncate inputs that exceed max length. Default: `True`
- `output_dtype` (str): Output data type
- `output_dimension` (int): Dimension of output embeddings
- `max_retries` (int): Maximum number of retry attempts. Default: `0`
- `timeout` (float): Request timeout in seconds
**Environment Variables:**
- `VOYAGEAI_API_KEY` or `EMBEDDINGS_VOYAGEAI_API_KEY`: `api_key`
- `VOYAGEAI_MODEL` or `EMBEDDINGS_VOYAGEAI_MODEL`: `model`
- `VOYAGEAI_INPUT_TYPE` or `EMBEDDINGS_VOYAGEAI_INPUT_TYPE`: `input_type`
- `VOYAGEAI_TRUNCATION` or `EMBEDDINGS_VOYAGEAI_TRUNCATION`: `truncation`
- `VOYAGEAI_OUTPUT_DTYPE` or `EMBEDDINGS_VOYAGEAI_OUTPUT_DTYPE`: `output_dtype`
- `VOYAGEAI_OUTPUT_DIMENSION` or `EMBEDDINGS_VOYAGEAI_OUTPUT_DIMENSION`: `output_dimension`
- `VOYAGEAI_MAX_RETRIES` or `EMBEDDINGS_VOYAGEAI_MAX_RETRIES`: `max_retries`
- `VOYAGEAI_TIMEOUT` or `EMBEDDINGS_VOYAGEAI_TIMEOUT`: `timeout`
</Accordion>
<Accordion title="Ollama">
```python main.py
from crewai.rag.embeddings.providers.ollama.types import OllamaProviderSpec
embedding_model: OllamaProviderSpec = {
"provider": "ollama",
"config": {
"model_name": "llama2",
"url": "http://localhost:11434/api/embeddings"
}
}
```
**Config Options:**
- `model_name` (str): Ollama model name (e.g., `llama2`, `mistral`, `nomic-embed-text`)
- `url` (str): Ollama API endpoint URL. Default: `http://localhost:11434/api/embeddings`
**Environment Variables:**
- `OLLAMA_MODEL` or `EMBEDDINGS_OLLAMA_MODEL`: `model_name`
- `OLLAMA_URL` or `EMBEDDINGS_OLLAMA_URL`: `url`
</Accordion>
<Accordion title="Amazon Bedrock">
```python main.py
from crewai.rag.embeddings.providers.aws.types import BedrockProviderSpec
embedding_model: BedrockProviderSpec = {
"provider": "amazon-bedrock",
"config": {
"model_name": "amazon.titan-embed-text-v2:0",
"session": boto3_session
}
}
```
**Config Options:**
- `model_name` (str): Bedrock model ID. Default: `amazon.titan-embed-text-v1`. Options: `amazon.titan-embed-text-v1`, `amazon.titan-embed-text-v2:0`, `cohere.embed-english-v3`, `cohere.embed-multilingual-v3`
- `session` (Any): Boto3 session object for AWS authentication
**Environment Variables:**
- `AWS_ACCESS_KEY_ID`: AWS access key
- `AWS_SECRET_ACCESS_KEY`: AWS secret key
- `AWS_REGION`: AWS region (e.g., `us-east-1`)
</Accordion>
<Accordion title="Azure OpenAI">
```python main.py
from crewai.rag.embeddings.providers.microsoft.types import AzureProviderSpec
embedding_model: AzureProviderSpec = {
"provider": "azure",
"config": {
"deployment_id": "your-deployment-id",
"api_key": "your-api-key",
"api_base": "https://your-resource.openai.azure.com",
"api_version": "2024-02-01",
"model_name": "text-embedding-ada-002",
"api_type": "azure"
}
}
```
**Config Options:**
- `deployment_id` (str): **Required** - Azure OpenAI deployment ID
- `api_key` (str): Azure OpenAI API key
- `api_base` (str): Azure OpenAI resource endpoint
- `api_version` (str): API version. Example: `2024-02-01`
- `model_name` (str): Model name. Default: `text-embedding-ada-002`
- `api_type` (str): API type. Default: `azure`
- `dimensions` (int): Output dimensions
- `default_headers` (dict): Custom headers
**Environment Variables:**
- `AZURE_OPENAI_API_KEY` or `EMBEDDINGS_AZURE_API_KEY`: `api_key`
- `AZURE_OPENAI_ENDPOINT` or `EMBEDDINGS_AZURE_API_BASE`: `api_base`
- `EMBEDDINGS_AZURE_DEPLOYMENT_ID`: `deployment_id`
- `EMBEDDINGS_AZURE_API_VERSION`: `api_version`
- `EMBEDDINGS_AZURE_MODEL_NAME`: `model_name`
- `EMBEDDINGS_AZURE_API_TYPE`: `api_type`
- `EMBEDDINGS_AZURE_DIMENSIONS`: `dimensions`
</Accordion>
<Accordion title="Google Generative AI">
```python main.py
from crewai.rag.embeddings.providers.google.types import GenerativeAiProviderSpec
embedding_model: GenerativeAiProviderSpec = {
"provider": "google-generativeai",
"config": {
"api_key": "your-api-key",
"model_name": "gemini-embedding-001",
"task_type": "RETRIEVAL_DOCUMENT"
}
}
```
**Config Options:**
- `api_key` (str): Google AI API key
- `model_name` (str): Model name. Default: `gemini-embedding-001`. Options: `gemini-embedding-001`, `text-embedding-005`, `text-multilingual-embedding-002`
- `task_type` (str): Task type for embeddings. Default: `RETRIEVAL_DOCUMENT`. Options: `RETRIEVAL_DOCUMENT`, `RETRIEVAL_QUERY`
**Environment Variables:**
- `GOOGLE_API_KEY`, `GEMINI_API_KEY`, or `EMBEDDINGS_GOOGLE_API_KEY`: `api_key`
- `EMBEDDINGS_GOOGLE_GENERATIVE_AI_MODEL_NAME`: `model_name`
- `EMBEDDINGS_GOOGLE_GENERATIVE_AI_TASK_TYPE`: `task_type`
</Accordion>
<Accordion title="Google Vertex AI">
```python main.py
from crewai.rag.embeddings.providers.google.types import VertexAIProviderSpec
embedding_model: VertexAIProviderSpec = {
"provider": "google-vertex",
"config": {
"model_name": "text-embedding-004",
"project_id": "your-project-id",
"region": "us-central1",
"api_key": "your-api-key"
}
}
```
**Config Options:**
- `model_name` (str): Model name. Default: `textembedding-gecko`. Options: `text-embedding-004`, `textembedding-gecko`, `textembedding-gecko-multilingual`
- `project_id` (str): Google Cloud project ID. Default: `cloud-large-language-models`
- `region` (str): Google Cloud region. Default: `us-central1`
- `api_key` (str): API key for authentication
**Environment Variables:**
- `GOOGLE_APPLICATION_CREDENTIALS`: Path to service account JSON file
- `GOOGLE_CLOUD_PROJECT` or `EMBEDDINGS_GOOGLE_VERTEX_PROJECT_ID`: `project_id`
- `EMBEDDINGS_GOOGLE_VERTEX_MODEL_NAME`: `model_name`
- `EMBEDDINGS_GOOGLE_VERTEX_REGION`: `region`
- `EMBEDDINGS_GOOGLE_VERTEX_API_KEY`: `api_key`
</Accordion>
<Accordion title="Jina AI">
```python main.py
from crewai.rag.embeddings.providers.jina.types import JinaProviderSpec
embedding_model: JinaProviderSpec = {
"provider": "jina",
"config": {
"api_key": "your-api-key",
"model_name": "jina-embeddings-v3"
}
}
```
**Config Options:**
- `api_key` (str): Jina AI API key
- `model_name` (str): Model name. Default: `jina-embeddings-v2-base-en`. Options: `jina-embeddings-v3`, `jina-embeddings-v2-base-en`, `jina-embeddings-v2-small-en`
**Environment Variables:**
- `JINA_API_KEY` or `EMBEDDINGS_JINA_API_KEY`: `api_key`
- `EMBEDDINGS_JINA_MODEL_NAME`: `model_name`
</Accordion>
<Accordion title="HuggingFace">
```python main.py
from crewai.rag.embeddings.providers.huggingface.types import HuggingFaceProviderSpec
embedding_model: HuggingFaceProviderSpec = {
"provider": "huggingface",
"config": {
"url": "https://api-inference.huggingface.co/models/sentence-transformers/all-MiniLM-L6-v2"
}
}
```
**Config Options:**
- `url` (str): Full URL to HuggingFace inference API endpoint
**Environment Variables:**
- `HUGGINGFACE_URL` or `EMBEDDINGS_HUGGINGFACE_URL`: `url`
</Accordion>
<Accordion title="Instructor">
```python main.py
from crewai.rag.embeddings.providers.instructor.types import InstructorProviderSpec
embedding_model: InstructorProviderSpec = {
"provider": "instructor",
"config": {
"model_name": "hkunlp/instructor-xl",
"device": "cuda",
"instruction": "Represent the document"
}
}
```
**Config Options:**
- `model_name` (str): HuggingFace model ID. Default: `hkunlp/instructor-base`. Options: `hkunlp/instructor-xl`, `hkunlp/instructor-large`, `hkunlp/instructor-base`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`, `mps`
- `instruction` (str): Instruction prefix for embeddings
**Environment Variables:**
- `EMBEDDINGS_INSTRUCTOR_MODEL_NAME`: `model_name`
- `EMBEDDINGS_INSTRUCTOR_DEVICE`: `device`
- `EMBEDDINGS_INSTRUCTOR_INSTRUCTION`: `instruction`
</Accordion>
<Accordion title="Sentence Transformer">
```python main.py
from crewai.rag.embeddings.providers.sentence_transformer.types import SentenceTransformerProviderSpec
embedding_model: SentenceTransformerProviderSpec = {
"provider": "sentence-transformer",
"config": {
"model_name": "all-mpnet-base-v2",
"device": "cuda",
"normalize_embeddings": True
}
}
```
**Config Options:**
- `model_name` (str): Sentence Transformers model name. Default: `all-MiniLM-L6-v2`. Options: `all-mpnet-base-v2`, `all-MiniLM-L6-v2`, `paraphrase-multilingual-MiniLM-L12-v2`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`, `mps`
- `normalize_embeddings` (bool): Whether to normalize embeddings. Default: `False`
**Environment Variables:**
- `EMBEDDINGS_SENTENCE_TRANSFORMER_MODEL_NAME`: `model_name`
- `EMBEDDINGS_SENTENCE_TRANSFORMER_DEVICE`: `device`
- `EMBEDDINGS_SENTENCE_TRANSFORMER_NORMALIZE_EMBEDDINGS`: `normalize_embeddings`
</Accordion>
<Accordion title="ONNX">
```python main.py
from crewai.rag.embeddings.providers.onnx.types import ONNXProviderSpec
embedding_model: ONNXProviderSpec = {
"provider": "onnx",
"config": {
"preferred_providers": ["CUDAExecutionProvider", "CPUExecutionProvider"]
}
}
```
**Config Options:**
- `preferred_providers` (list[str]): List of ONNX execution providers in order of preference
**Environment Variables:**
- `EMBEDDINGS_ONNX_PREFERRED_PROVIDERS`: `preferred_providers` (comma-separated list)
</Accordion>
<Accordion title="OpenCLIP">
```python main.py
from crewai.rag.embeddings.providers.openclip.types import OpenCLIPProviderSpec
embedding_model: OpenCLIPProviderSpec = {
"provider": "openclip",
"config": {
"model_name": "ViT-B-32",
"checkpoint": "laion2b_s34b_b79k",
"device": "cuda"
}
}
```
**Config Options:**
- `model_name` (str): OpenCLIP model architecture. Default: `ViT-B-32`. Options: `ViT-B-32`, `ViT-B-16`, `ViT-L-14`
- `checkpoint` (str): Pretrained checkpoint name. Default: `laion2b_s34b_b79k`. Options: `laion2b_s34b_b79k`, `laion400m_e32`, `openai`
- `device` (str): Device to run on. Default: `cpu`. Options: `cpu`, `cuda`
**Environment Variables:**
- `EMBEDDINGS_OPENCLIP_MODEL_NAME`: `model_name`
- `EMBEDDINGS_OPENCLIP_CHECKPOINT`: `checkpoint`
- `EMBEDDINGS_OPENCLIP_DEVICE`: `device`
</Accordion>
<Accordion title="Text2Vec">
```python main.py
from crewai.rag.embeddings.providers.text2vec.types import Text2VecProviderSpec
embedding_model: Text2VecProviderSpec = {
"provider": "text2vec",
"config": {
"model_name": "shibing624/text2vec-base-multilingual"
}
}
```
**Config Options:**
- `model_name` (str): Text2Vec model name from HuggingFace. Default: `shibing624/text2vec-base-chinese`. Options: `shibing624/text2vec-base-multilingual`, `shibing624/text2vec-base-chinese`
**Environment Variables:**
- `EMBEDDINGS_TEXT2VEC_MODEL_NAME`: `model_name`
</Accordion>
<Accordion title="Roboflow">
```python main.py
from crewai.rag.embeddings.providers.roboflow.types import RoboflowProviderSpec
embedding_model: RoboflowProviderSpec = {
"provider": "roboflow",
"config": {
"api_key": "your-api-key",
"api_url": "https://infer.roboflow.com"
}
}
```
**Config Options:**
- `api_key` (str): Roboflow API key. Default: `""` (empty string)
- `api_url` (str): Roboflow inference API URL. Default: `https://infer.roboflow.com`
**Environment Variables:**
- `ROBOFLOW_API_KEY` or `EMBEDDINGS_ROBOFLOW_API_KEY`: `api_key`
- `ROBOFLOW_API_URL` or `EMBEDDINGS_ROBOFLOW_API_URL`: `api_url`
</Accordion>
<Accordion title="WatsonX (IBM)">
```python main.py
from crewai.rag.embeddings.providers.ibm.types import WatsonXProviderSpec
embedding_model: WatsonXProviderSpec = {
"provider": "watsonx",
"config": {
"model_id": "ibm/slate-125m-english-rtrvr",
"url": "https://us-south.ml.cloud.ibm.com",
"api_key": "your-api-key",
"project_id": "your-project-id",
"batch_size": 100,
"concurrency_limit": 10,
"persistent_connection": True
}
}
```
**Config Options:**
- `model_id` (str): WatsonX model identifier
- `url` (str): WatsonX API endpoint
- `api_key` (str): IBM Cloud API key
- `project_id` (str): WatsonX project ID
- `space_id` (str): WatsonX space ID (alternative to project_id)
- `batch_size` (int): Batch size for embeddings. Default: `100`
- `concurrency_limit` (int): Maximum concurrent requests. Default: `10`
- `persistent_connection` (bool): Use persistent connections. Default: `True`
- Plus 20+ additional authentication and configuration options
**Environment Variables:**
- `WATSONX_API_KEY` or `EMBEDDINGS_WATSONX_API_KEY`: `api_key`
- `WATSONX_URL` or `EMBEDDINGS_WATSONX_URL`: `url`
- `WATSONX_PROJECT_ID` or `EMBEDDINGS_WATSONX_PROJECT_ID`: `project_id`
- `EMBEDDINGS_WATSONX_MODEL_ID`: `model_id`
- `EMBEDDINGS_WATSONX_SPACE_ID`: `space_id`
- `EMBEDDINGS_WATSONX_BATCH_SIZE`: `batch_size`
- `EMBEDDINGS_WATSONX_CONCURRENCY_LIMIT`: `concurrency_limit`
- `EMBEDDINGS_WATSONX_PERSISTENT_CONNECTION`: `persistent_connection`
</Accordion>
<Accordion title="Custom">
```python main.py
from crewai.rag.core.base_embeddings_callable import EmbeddingFunction
from crewai.rag.embeddings.providers.custom.types import CustomProviderSpec
class MyEmbeddingFunction(EmbeddingFunction):
def __call__(self, input):
# Your custom embedding logic
return embeddings
embedding_model: CustomProviderSpec = {
"provider": "custom",
"config": {
"embedding_callable": MyEmbeddingFunction
}
}
```
**Config Options:**
- `embedding_callable` (type[EmbeddingFunction]): Custom embedding function class
**Note:** Custom embedding functions must implement the `EmbeddingFunction` protocol defined in `crewai.rag.core.base_embeddings_callable`. The `__call__` method should accept input data and return embeddings as a list of numpy arrays (or compatible format that will be normalized). The returned embeddings are automatically normalized and validated.
</Accordion>
</AccordionGroup>
### Notes
- All config fields are optional unless marked as **Required**
- API keys can typically be provided via environment variables instead of config
- Default values are shown where applicable
## Conclusion
The `RagTool` provides a powerful way to create and query knowledge bases from various data sources. By leveraging Retrieval-Augmented Generation, it enables agents to access and retrieve relevant information efficiently, enhancing their ability to provide accurate and contextually appropriate responses.

View File

@@ -18,7 +18,7 @@ These tools enable your agents to interact with cloud services, access cloud sto
Write and upload files to Amazon S3 storage.
</Card>
<Card title="Bedrock Invoke Agent" icon="aws" href="/en/tools/cloud-storage/bedrockinvokeagenttool">
<Card title="Bedrock Invoke Agent" icon="aws" href="/en/tools/integration/bedrockinvokeagenttool">
Invoke Amazon Bedrock agents for AI-powered tasks.
</Card>

View File

@@ -58,10 +58,10 @@ tool = MySQLSearchTool(
),
),
embedder=dict(
provider="google",
provider="google-generativeai",
config=dict(
model="models/embedding-001",
task_type="retrieval_document",
model_name="gemini-embedding-001",
task_type="RETRIEVAL_DOCUMENT",
# title="Embeddings",
),
),

View File

@@ -71,10 +71,10 @@ tool = PGSearchTool(
),
),
embedder=dict(
provider="google", # or openai, ollama, ...
provider="google-generativeai", # or openai, ollama, ...
config=dict(
model="models/embedding-001",
task_type="retrieval_document",
model_name="gemini-embedding-001",
task_type="RETRIEVAL_DOCUMENT",
# title="Embeddings",
),
),

View File

@@ -23,13 +23,15 @@ Here's a minimal example of how to use the tool:
```python
from crewai import Agent
from crewai_tools import QdrantVectorSearchTool
from crewai_tools import QdrantVectorSearchTool, QdrantConfig
# Initialize the tool
# Initialize the tool with QdrantConfig
qdrant_tool = QdrantVectorSearchTool(
qdrant_url="your_qdrant_url",
qdrant_api_key="your_qdrant_api_key",
collection_name="your_collection"
qdrant_config=QdrantConfig(
qdrant_url="your_qdrant_url",
qdrant_api_key="your_qdrant_api_key",
collection_name="your_collection"
)
)
# Create an agent that uses the tool
@@ -82,7 +84,7 @@ def extract_text_from_pdf(pdf_path):
def get_openai_embedding(text):
response = client.embeddings.create(
input=text,
model="text-embedding-3-small"
model="text-embedding-3-large"
)
return response.data[0].embedding
@@ -90,13 +92,13 @@ def get_openai_embedding(text):
def load_pdf_to_qdrant(pdf_path, qdrant, collection_name):
# Extract text from PDF
text_chunks = extract_text_from_pdf(pdf_path)
# Create Qdrant collection
if qdrant.collection_exists(collection_name):
qdrant.delete_collection(collection_name)
qdrant.create_collection(
collection_name=collection_name,
vectors_config=VectorParams(size=1536, distance=Distance.COSINE)
vectors_config=VectorParams(size=3072, distance=Distance.COSINE)
)
# Store embeddings
@@ -120,19 +122,23 @@ pdf_path = "path/to/your/document.pdf"
load_pdf_to_qdrant(pdf_path, qdrant, collection_name)
# Initialize Qdrant search tool
from crewai_tools import QdrantConfig
qdrant_tool = QdrantVectorSearchTool(
qdrant_url=os.getenv("QDRANT_URL"),
qdrant_api_key=os.getenv("QDRANT_API_KEY"),
collection_name=collection_name,
limit=3,
score_threshold=0.35
qdrant_config=QdrantConfig(
qdrant_url=os.getenv("QDRANT_URL"),
qdrant_api_key=os.getenv("QDRANT_API_KEY"),
collection_name=collection_name,
limit=3,
score_threshold=0.35
)
)
# Create CrewAI agents
search_agent = Agent(
role="Senior Semantic Search Agent",
goal="Find and analyze documents based on semantic search",
backstory="""You are an expert research assistant who can find relevant
backstory="""You are an expert research assistant who can find relevant
information using semantic search in a Qdrant database.""",
tools=[qdrant_tool],
verbose=True
@@ -141,7 +147,7 @@ search_agent = Agent(
answer_agent = Agent(
role="Senior Answer Assistant",
goal="Generate answers to questions based on the context provided",
backstory="""You are an expert answer assistant who can generate
backstory="""You are an expert answer assistant who can generate
answers to questions based on the context provided.""",
tools=[qdrant_tool],
verbose=True
@@ -180,21 +186,82 @@ print(result)
## Tool Parameters
### Required Parameters
- `qdrant_url` (str): The URL of your Qdrant server
- `qdrant_api_key` (str): API key for authentication with Qdrant
- `collection_name` (str): Name of the Qdrant collection to search
- `qdrant_config` (QdrantConfig): Configuration object containing all Qdrant settings
### Optional Parameters
### QdrantConfig Parameters
- `qdrant_url` (str): The URL of your Qdrant server
- `qdrant_api_key` (str, optional): API key for authentication with Qdrant
- `collection_name` (str): Name of the Qdrant collection to search
- `limit` (int): Maximum number of results to return (default: 3)
- `score_threshold` (float): Minimum similarity score threshold (default: 0.35)
- `filter` (Any, optional): Qdrant Filter instance for advanced filtering (default: None)
### Optional Tool Parameters
- `custom_embedding_fn` (Callable[[str], list[float]]): Custom function for text vectorization
- `qdrant_package` (str): Base package path for Qdrant (default: "qdrant_client")
- `client` (Any): Pre-initialized Qdrant client (optional)
## Advanced Filtering
The QdrantVectorSearchTool supports powerful filtering capabilities to refine your search results:
### Dynamic Filtering
Use `filter_by` and `filter_value` parameters in your search to filter results on-the-fly:
```python
# Agent will use these parameters when calling the tool
# The tool schema accepts filter_by and filter_value
# Example: search with category filter
# Results will be filtered where category == "technology"
```
### Preset Filters with QdrantConfig
For complex filtering, use Qdrant Filter instances in your configuration:
```python
from qdrant_client.http import models as qmodels
from crewai_tools import QdrantVectorSearchTool, QdrantConfig
# Create a filter for specific conditions
preset_filter = qmodels.Filter(
must=[
qmodels.FieldCondition(
key="category",
match=qmodels.MatchValue(value="research")
),
qmodels.FieldCondition(
key="year",
match=qmodels.MatchValue(value=2024)
)
]
)
# Initialize tool with preset filter
qdrant_tool = QdrantVectorSearchTool(
qdrant_config=QdrantConfig(
qdrant_url="your_url",
qdrant_api_key="your_key",
collection_name="your_collection",
filter=preset_filter # Preset filter applied to all searches
)
)
```
### Combining Filters
The tool automatically combines preset filters from `QdrantConfig` with dynamic filters from `filter_by` and `filter_value`:
```python
# If QdrantConfig has a preset filter for category="research"
# And the search uses filter_by="year", filter_value=2024
# Both filters will be combined (AND logic)
```
## Search Parameters
The tool accepts these parameters in its schema:
- `query` (str): The search query to find similar documents
- `filter_by` (str, optional): Metadata field to filter on
- `filter_value` (str, optional): Value to filter by
- `filter_value` (Any, optional): Value to filter by
## Return Format
@@ -214,7 +281,7 @@ The tool returns results in JSON format:
## Default Embedding
By default, the tool uses OpenAI's `text-embedding-3-small` model for vectorization. This requires:
By default, the tool uses OpenAI's `text-embedding-3-large` model for vectorization. This requires:
- OpenAI API key set in environment: `OPENAI_API_KEY`
## Custom Embeddings
@@ -240,18 +307,22 @@ def custom_embeddings(text: str) -> list[float]:
# Tokenize and get model outputs
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
outputs = model(**inputs)
# Use mean pooling to get text embedding
embeddings = outputs.last_hidden_state.mean(dim=1)
# Convert to list of floats and return
return embeddings[0].tolist()
# Use custom embeddings with the tool
from crewai_tools import QdrantConfig
tool = QdrantVectorSearchTool(
qdrant_url="your_url",
qdrant_api_key="your_key",
collection_name="your_collection",
qdrant_config=QdrantConfig(
qdrant_url="your_url",
qdrant_api_key="your_key",
collection_name="your_collection"
),
custom_embedding_fn=custom_embeddings # Pass your custom function
)
```
@@ -269,4 +340,4 @@ Required environment variables:
```bash
export QDRANT_URL="your_qdrant_url" # If not provided in constructor
export QDRANT_API_KEY="your_api_key" # If not provided in constructor
export OPENAI_API_KEY="your_openai_key" # If using default embeddings
export OPENAI_API_KEY="your_openai_key" # If using default embeddings

View File

@@ -54,25 +54,25 @@ The following parameters can be used to customize the `CSVSearchTool`'s behavior
By default, the tool uses OpenAI for both embeddings and summarization. To customize the model, you can use a config dictionary as follows:
```python Code
from chromadb.config import Settings
tool = CSVSearchTool(
config=dict(
llm=dict(
provider="ollama", # or google, openai, anthropic, llama2, ...
config=dict(
model="llama2",
# temperature=0.5,
# top_p=1,
# stream=true,
),
),
embedder=dict(
provider="google", # or openai, ollama, ...
config=dict(
model="models/embedding-001",
task_type="retrieval_document",
# title="Embeddings",
),
),
)
config={
"embedding_model": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
# "api_key": "sk-...",
},
},
"vectordb": {
"provider": "chromadb", # or "qdrant"
"config": {
# "settings": Settings(persist_directory="/content/chroma", allow_reset=True, is_persistent=True),
# from qdrant_client.models import VectorParams, Distance
# "vectors_config": VectorParams(size=384, distance=Distance.COSINE),
}
},
}
)
```

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