AhmadT198 commited on
Commit
e537b1c
·
verified ·
1 Parent(s): 06821d7

Adding SQL

Browse files
Files changed (1) hide show
  1. tools/sql.py +51 -0
tools/sql.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ from pydantic.v1 import BaseModel
3
+ from typing import List
4
+ from langchain.tools import Tool
5
+
6
+ conn = sqlite3.connect("db_2.sqlite")
7
+
8
+ def list_tables():
9
+ c= conn.cursor()
10
+ c.execute("SELECT name from sqlite_master WHERE type='table';")
11
+ rows = c.fetchall()
12
+ return "\n".join(row[0] for row in rows if row[0] is not None)
13
+
14
+
15
+ ############################# Run SQLite Query Tool ##########################################
16
+
17
+ def run_sqlite_query(query):
18
+ c = conn.cursor()
19
+ try:
20
+ c.execute(query)
21
+ return c.fetchall()
22
+ except sqlite3.OperationalError as err:
23
+ return f"The following error occured: {str}"
24
+
25
+ class RunQuaryArgsSchema(BaseModel):
26
+ query: str
27
+
28
+ run_query_tool = Tool.from_function(
29
+ name="run_sqlite_query",
30
+ description="Run an sqlite query.",
31
+ func=run_sqlite_query,
32
+ args_schema=RunQuaryArgsSchema
33
+ )
34
+
35
+ ############################# Describe Tables Tool ##########################################
36
+
37
+ def describe_tables(table_names):
38
+ c = conn.cursor()
39
+ tables = ', '.join("'" + table + "'" for table in table_names)
40
+ rows = c.execute(f"SELECT sql FROM sqlite_master WHERE type='table' and name IN ({tables});")
41
+ return "\n".join(row[0] for row in rows if row[0] is not None)
42
+
43
+ class DescribeTablesArgsSchema(BaseModel):
44
+ table_names: List[str]
45
+
46
+ describe_tables_tool = Tool.from_function(
47
+ name="describe_tables",
48
+ description="Given a list of table names, return the schema of those tables.",
49
+ func=describe_tables,
50
+ args_schema=DescribeTablesArgsSchema
51
+ )