-
Notifications
You must be signed in to change notification settings - Fork 8.4k
new features #7240
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ablaze005
wants to merge
2
commits into
crewAIInc:main
Choose a base branch
from
Ablaze005:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
new features #7240
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| # SupabaseTool | ||
|
|
||
| The `SupabaseTool` allows CrewAI agents to interact with Supabase databases. | ||
|
|
||
| ## Supported Actions | ||
| - `select` | ||
| - `insert` | ||
| - `update` | ||
| - `delete` | ||
|
|
||
| ## Environment Variables | ||
| - SUPABASE_URL | ||
| - SUPABASE_KEY | ||
|
|
||
| ## Example Usage | ||
|
|
||
| ```python | ||
| from crewai.tools import SupabaseTool | ||
|
|
||
| tool = SupabaseTool() | ||
|
|
||
| result = tool.run({ | ||
| "action": "select", | ||
| "table": "messages", | ||
| "filters": {"id": "eq.1"} | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from crewai.tools import BaseTool | ||
|
|
||
| if TYPE_CHECKING: | ||
| from supabase import Client | ||
|
|
||
|
|
||
| class SupabaseTool(BaseTool): | ||
| name: str = "SupabaseTool" | ||
| description: str = ( | ||
| "A tool for performing Supabase database operations such as " | ||
| "select, insert, update, and delete." | ||
| ) | ||
|
|
||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| url = os.getenv("SUPABASE_URL") | ||
| key = os.getenv("SUPABASE_KEY") | ||
|
|
||
| if not url or not key: | ||
| raise ValueError( | ||
| "SUPABASE_URL and SUPABASE_KEY must be set in environment variables" | ||
| ) | ||
| if not url.startswith("https://"): | ||
| raise ValueError("SUPABASE_URL must start with 'https://'") | ||
|
|
||
| from supabase import create_client | ||
|
|
||
| self.client: Client = create_client(url, key) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| def run(self, *args: Any, **kwargs: Any) -> Any: | ||
| """Execute the tool and return its operation result. | ||
|
|
||
| Args: | ||
| *args: Positional arguments passed to the tool. | ||
| **kwargs: Keyword arguments passed to the tool. | ||
|
|
||
| Returns: | ||
| A normalized JSON-like operation response. | ||
|
|
||
| Raises: | ||
| ValueError: If the tool configuration or operation input is invalid. | ||
| TypeError: If filters is not a dictionary. | ||
| """ | ||
| return super().run(*args, **kwargs) | ||
|
|
||
| def _run(self, params: dict[str, Any]) -> dict[str, Any]: | ||
| """Dispatch an operation described by ``params``. | ||
|
|
||
| Args: | ||
| params: Operation name, table name, optional filters, and data. | ||
|
|
||
| Returns: | ||
| A normalized response containing ``data`` and ``error`` keys, or | ||
| an ``error`` key for invalid operation input. | ||
|
|
||
| Raises: | ||
| ValueError: If ``params`` is not a dictionary or filters use an | ||
| unsupported operator format. | ||
| TypeError: If filters is not a dictionary. | ||
| """ | ||
| if not isinstance(params, dict): | ||
| raise ValueError("SupabaseTool parameters must be a dictionary") | ||
|
|
||
| action = params.get("action") | ||
| table = params.get("table") | ||
| if not action or not table: | ||
| return {"data": None, "error": "Missing required fields: action, table"} | ||
|
|
||
| if action == "select": | ||
| return self.select(table, params.get("filters")) | ||
| if action == "insert": | ||
| return self.insert(table, params.get("data")) | ||
| if action == "update": | ||
| return self.update(table, params.get("data"), params.get("filters")) | ||
| if action == "delete": | ||
| return self.delete(table, params.get("filters")) | ||
| return {"data": None, "error": f"Unknown action: {action}"} | ||
|
|
||
| def _apply_filters(self, operation: Any, filters: Any) -> Any: | ||
| """Apply validated filters to a Supabase operation.""" | ||
| if filters is None or filters == {}: | ||
| return operation | ||
| if not isinstance(filters, dict): | ||
| raise TypeError("filters must be a dictionary") | ||
|
|
||
| operators = { | ||
| "eq": "eq", | ||
| "neq": "neq", | ||
| "gt": "gt", | ||
| "gte": "gte", | ||
| "lt": "lt", | ||
| "lte": "lte", | ||
| } | ||
| for column, value in filters.items(): | ||
| operator = "eq" | ||
| filter_value = value | ||
| if isinstance(value, dict): | ||
| operator = value.get("operator") | ||
| if operator not in operators or "value" not in value: | ||
| raise ValueError( | ||
| "Filter descriptors must contain a supported operator " | ||
| "and a value" | ||
| ) | ||
| filter_value = value["value"] | ||
| elif isinstance(value, str) and value.startswith( | ||
| ("eq.", "neq.", "gt.", "gte.", "lt.", "lte.") | ||
| ): | ||
| raise ValueError( | ||
| "Filter values must be direct values or descriptors like " | ||
| "{'operator': 'neq', 'value': 1}; do not use 'eq.1'" | ||
| ) | ||
| operation = getattr(operation, operators[operator])(column, filter_value) | ||
| return operation | ||
|
|
||
| @staticmethod | ||
| def _normalize_response(response: Any) -> dict[str, Any]: | ||
| """Convert a Supabase response into a JSON-like dictionary.""" | ||
| if isinstance(response, dict): | ||
| return response | ||
| return { | ||
| "data": getattr(response, "data", None), | ||
| "error": getattr(response, "error", None), | ||
| } | ||
|
|
||
| def select(self, table: str, filters: dict[str, Any] | None = None) -> dict[str, Any]: | ||
| """Select rows from a table. | ||
|
|
||
| Args: | ||
| table: Supabase table name. | ||
| filters: Optional column-to-value equality filters. | ||
|
|
||
| Returns: | ||
| A normalized response containing selected rows and any error. | ||
|
|
||
| Raises: | ||
| TypeError: If filters is not a dictionary. | ||
| """ | ||
| operation = self.client.table(table).select("*") | ||
| operation = self._apply_filters(operation, filters) | ||
| return self._normalize_response(operation.execute()) | ||
|
|
||
| def insert(self, table: str, data: Any) -> dict[str, Any]: | ||
| """Insert data into a table. | ||
|
|
||
| Args: | ||
| table: Supabase table name. | ||
| data: Row dictionary or list of row dictionaries to insert. | ||
|
|
||
| Returns: | ||
| A normalized response containing inserted rows and any error. | ||
|
|
||
| Raises: | ||
| ValueError: If data is missing. | ||
| """ | ||
| if data is None: | ||
| return {"data": None, "error": "Missing data for insert"} | ||
| return self._normalize_response(self.client.table(table).insert(data).execute()) | ||
|
|
||
| def update( | ||
| self, | ||
| table: str, | ||
| data: Any, | ||
| filters: dict[str, Any] | None = None, | ||
| ) -> dict[str, Any]: | ||
| """Update rows in a table. | ||
|
|
||
| Args: | ||
| table: Supabase table name. | ||
| data: Column values to update. | ||
| filters: Optional column-to-value equality filters. | ||
|
|
||
| Returns: | ||
| A normalized response containing updated rows and any error. | ||
|
|
||
| Raises: | ||
| TypeError: If filters is not a dictionary. | ||
| ValueError: If data is missing. | ||
| """ | ||
| if data is None: | ||
| return {"data": None, "error": "Missing data for update"} | ||
| operation = self.client.table(table).update(data) | ||
| operation = self._apply_filters(operation, filters) | ||
| return self._normalize_response(operation.execute()) | ||
|
|
||
| def delete( | ||
| self, | ||
| table: str, | ||
| filters: dict[str, Any] | None = None, | ||
| ) -> dict[str, Any]: | ||
| """Delete rows from a table. | ||
|
|
||
| Args: | ||
| table: Supabase table name. | ||
| filters: Optional column-to-value equality filters. | ||
|
|
||
| Returns: | ||
| A normalized response containing deleted rows and any error. | ||
|
|
||
| Raises: | ||
| TypeError: If filters is not a dictionary. | ||
| """ | ||
| operation = self.client.table(table).delete() | ||
| operation = self._apply_filters(operation, filters) | ||
| return self._normalize_response(operation.execute()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import os | ||
| import pytest | ||
|
|
||
| from crewai.tools.supabase_tool import SupabaseTool | ||
|
|
||
| def test_missing_env_vars(): | ||
| # Temporarily remove env vars | ||
| os.environ.pop("SUPABASE_URL", None) | ||
| os.environ.pop("SUPABASE_KEY", None) | ||
|
|
||
| with pytest.raises(ValueError): | ||
| SupabaseTool() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.