11import os
22from crewai_tools import tool
33from dotenv import load_dotenv
4- from neon import Neon
4+ from neon_api import NeonAPI
5+ import psycopg2
6+ from psycopg2 .extras import RealDictCursor
57
68load_dotenv ()
79
8- NEON_API_KEY = os .getenv (' NEON_API_KEY' )
9- neon_client = Neon (api_key = NEON_API_KEY )
10+ NEON_API_KEY = os .getenv (" NEON_API_KEY" )
11+ neon_client = NeonAPI (api_key = NEON_API_KEY )
1012
11- # TODO: Should I duplicate this from the web_researcher example? Or is it
12- # possible to somehow have the web_researcher example import this?
13+
14+ @tool ("Create Neon Project and Database" )
15+ def create_database (project_name : str ) -> str :
16+ """
17+ Creates a new Neon project. (this takes less than 500ms)
18+ Args:
19+ project_name: Name of the project to create
20+ Returns:
21+ the connection URI for the new project
22+ """
23+ try :
24+ project = neon_client .project_create (project = {"name" : project_name }).project
25+ connection_uri = neon_client .connection_uri (
26+ project_id = project .id , database_name = "neondb" , role_name = "neondb_owner"
27+ ).uri
28+ return f"Project/database created, connection URI: { connection_uri } "
29+ except Exception as e :
30+ return f"Failed to create project: { str (e )} "
31+
32+
33+ @tool ("Execute SQL DDL" )
34+ def execute_sql_ddl (connection_uri : str , command : str ) -> str :
35+ """
36+ Inserts data into a specified Neon database.
37+ Args:
38+ connection_uri: The connection URI for the Neon database
39+ command: The DDL SQL command to execute
40+ Returns:
41+ the result of the DDL command
42+ """
43+ conn = psycopg2 .connect (connection_uri )
44+ cur = conn .cursor (cursor_factory = RealDictCursor )
45+ try :
46+ cur .execute (command )
47+ conn .commit ()
48+ except Exception as e :
49+ conn .rollback ()
50+ return f"Failed to execute DDL command: { str (e )} "
51+ cur .close ()
52+ conn .close ()
53+ return f"Command succeeded"
54+
55+
56+ @tool ("Execute SQL DML" )
57+ def run_sql_query (connection_uri : str , query : str ) -> str :
58+ """
59+ Inserts data into a specified Neon database.
60+ Args:
61+ connection_uri: The connection URI for the Neon database
62+ query: The SQL query to execute
63+ Returns:
64+ the result of the SQL query
65+ """
66+ conn = psycopg2 .connect (connection_uri )
67+ cur = conn .cursor (cursor_factory = RealDictCursor )
68+ try :
69+ cur .execute (query )
70+ conn .commit ()
71+
72+ # Try to fetch results (for SELECT queries)
73+ try :
74+ records = cur .fetchall ()
75+ return f"Query result: { records } "
76+ except psycopg2 .ProgrammingError :
77+ # For INSERT/UPDATE/DELETE operations
78+ return f"Query executed successfully"
79+ except Exception as e :
80+ conn .rollback ()
81+ return f"Failed to execute SQL query: { str (e )} "
82+ finally :
83+ cur .close ()
84+ conn .close ()
0 commit comments