|
| 1 | +import os |
| 2 | +from typing import TYPE_CHECKING, Any, Dict |
| 3 | + |
| 4 | +from crewai.tools import BaseTool |
| 5 | + |
| 6 | +if TYPE_CHECKING: |
| 7 | + from supabase import Client |
| 8 | + |
| 9 | +class SupabaseTool(BaseTool): |
| 10 | + name: str = "SupabaseTool" |
| 11 | + description: str = ( |
| 12 | + "A tool for performing Supabase database operations such as " |
| 13 | + "select, insert, update, and delete." |
| 14 | + ) |
| 15 | + |
| 16 | + def __init__(self): |
| 17 | + super().__init__() |
| 18 | + url = os.getenv("SUPABASE_URL") |
| 19 | + key = os.getenv("SUPABASE_KEY") |
| 20 | + |
| 21 | + if not url or not key: |
| 22 | + raise ValueError("SUPABASE_URL and SUPABASE_KEY must be set in environment variables") |
| 23 | + |
| 24 | + from supabase import create_client |
| 25 | + |
| 26 | + self.client: Client = create_client(url, key) |
| 27 | + |
| 28 | + def _run(self, params: Dict[str, Any]) -> Any: |
| 29 | + """ |
| 30 | + params example: |
| 31 | + { |
| 32 | + "action": "select", |
| 33 | + "table": "messages", |
| 34 | + "filters": {"id": "eq.1"} |
| 35 | + } |
| 36 | + """ |
| 37 | + action = params.get("action") |
| 38 | + table = params.get("table") |
| 39 | + |
| 40 | + if not action or not table: |
| 41 | + return {"error": "Missing required fields: action, table"} |
| 42 | + |
| 43 | + query = self.client.table(table) |
| 44 | + |
| 45 | + if action == "select": |
| 46 | + filters = params.get("filters", {}) |
| 47 | + for key, condition in filters.items(): |
| 48 | + query = query.eq(key, condition) |
| 49 | + return query.select("*").execute() |
| 50 | + |
| 51 | + elif action == "insert": |
| 52 | + data = params.get("data") |
| 53 | + if not data: |
| 54 | + return {"error": "Missing data for insert"} |
| 55 | + return query.insert(data).execute() |
| 56 | + |
| 57 | + elif action == "update": |
| 58 | + filters = params.get("filters", {}) |
| 59 | + data = params.get("data") |
| 60 | + if not filters or not data: |
| 61 | + return {"error": "Missing filters or data for update"} |
| 62 | + for key, condition in filters.items(): |
| 63 | + query = query.eq(key, condition) |
| 64 | + return query.update(data).execute() |
| 65 | + |
| 66 | + elif action == "delete": |
| 67 | + filters = params.get("filters", {}) |
| 68 | + if not filters: |
| 69 | + return {"error": "Missing filters for delete"} |
| 70 | + for key, condition in filters.items(): |
| 71 | + query = query.eq(key, condition) |
| 72 | + return query.delete().execute() |
| 73 | + |
| 74 | + else: |
| 75 | + return {"error": f"Unknown action: {action}"} |
0 commit comments