mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-06 09:55:21 +03:00
Currently, table information is gathered through SQLAlchemy as complete table DDL and a user-selected number of sample rows from each table. This PR adds the option to use user-defined table information instead of automatically collecting it. This will use the provided table information and fall back to the automatic gathering for tables that the user didn't provide information for. Off the top of my head, there are a few cases where this can be quite useful: - The first n rows of a table are uninformative, or very similar to one another. In this case, hand-crafting example rows for a table such that they provide the good, diverse information can be very helpful. Another approach we can think about later is getting a random sample of n rows instead of the first n rows, but there are some performance considerations that need to be taken there. Even so, hand-crafting the sample rows is useful and can guarantee the model sees informative data. - The user doesn't want every column to be available to the model. This is not an elegant way to fulfill this specific need since the user would have to provide the table definition instead of a simple list of columns to include or ignore, but it does work for this purpose. - For the developers, this makes it a lot easier to compare/benchmark the performance of different prompting structures for providing table information in the prompt. These are cases I've run into myself (particularly cases 1 and 3) and I've found these changes useful. Personally, I keep custom table info for a few tables in a yaml file for versioning and easy loading. Definitely open to other opinions/approaches though!
22 KiB
22 KiB
In [1]:
from langchain import OpenAI, SQLDatabase, SQLDatabaseChainIn [2]:
db = SQLDatabase.from_uri("sqlite:///../../../../notebooks/Chinook.db")
llm = OpenAI(temperature=0)In [3]:
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)In [4]:
db_chain.run("How many employees are there?")Out [4]:
[1m> Entering new SQLDatabaseChain chain...[0m How many employees are there? SQLQuery:
/Users/harrisonchase/workplace/langchain/langchain/sql_database.py:120: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage. sample_rows = connection.execute(command)
[32;1m[1;3m SELECT COUNT(*) FROM Employee;[0m SQLResult: [33;1m[1;3m[(8,)][0m Answer:[32;1m[1;3m There are 8 employees.[0m [1m> Finished chain.[0m
' There are 8 employees.'
In [5]:
from langchain.prompts.prompt import PromptTemplate
_DEFAULT_TEMPLATE = """Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.
Use the following format:
Question: "Question here"
SQLQuery: "SQL Query to run"
SQLResult: "Result of the SQLQuery"
Answer: "Final answer here"
Only use the following tables:
{table_info}
If someone asks for the table foobar, they really mean the employee table.
Question: {input}"""
PROMPT = PromptTemplate(
input_variables=["input", "table_info", "dialect"], template=_DEFAULT_TEMPLATE
)In [6]:
db_chain = SQLDatabaseChain(llm=llm, database=db, prompt=PROMPT, verbose=True)In [7]:
db_chain.run("How many employees are there in the foobar table?")Out [7]:
[1m> Entering new SQLDatabaseChain chain...[0m How many employees are there in the foobar table? SQLQuery:[32;1m[1;3m SELECT COUNT(*) FROM Employee;[0m SQLResult: [33;1m[1;3m[(8,)][0m Answer:[32;1m[1;3m There are 8 employees in the foobar table.[0m [1m> Finished chain.[0m
' There are 8 employees in the foobar table.'
In [8]:
db_chain = SQLDatabaseChain(llm=llm, database=db, prompt=PROMPT, verbose=True, return_intermediate_steps=True)In [9]:
result = db_chain("How many employees are there in the foobar table?")
result["intermediate_steps"]Out [9]:
[1m> Entering new SQLDatabaseChain chain...[0m How many employees are there in the foobar table? SQLQuery:[32;1m[1;3m SELECT COUNT(*) FROM Employee;[0m SQLResult: [33;1m[1;3m[(8,)][0m Answer:[32;1m[1;3m There are 8 employees in the foobar table.[0m [1m> Finished chain.[0m
[' SELECT COUNT(*) FROM Employee;', '[(8,)]']
In [10]:
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True, top_k=3)In [11]:
db_chain.run("What are some example tracks by composer Johann Sebastian Bach?")Out [11]:
[1m> Entering new SQLDatabaseChain chain...[0m
What are some example tracks by composer Johann Sebastian Bach?
SQLQuery:[32;1m[1;3m SELECT Name, Composer FROM Track WHERE Composer LIKE '%Johann Sebastian Bach%' LIMIT 3;[0m
SQLResult: [33;1m[1;3m[('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Johann Sebastian Bach'), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Johann Sebastian Bach'), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude', 'Johann Sebastian Bach')][0m
Answer:[32;1m[1;3m Some example tracks by composer Johann Sebastian Bach are 'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', and 'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude'.[0m
[1m> Finished chain.[0m
' Some example tracks by composer Johann Sebastian Bach are \'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace\', \'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria\', and \'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude\'.'
In [12]:
db = SQLDatabase.from_uri(
"sqlite:///../../../../notebooks/Chinook.db",
include_tables=['Track'], # we include only one table to save tokens in the prompt :)
sample_rows_in_table_info=2)In [13]:
print(db.table_info)
CREATE TABLE "Track" (
"TrackId" INTEGER NOT NULL,
"Name" NVARCHAR(200) NOT NULL,
"AlbumId" INTEGER,
"MediaTypeId" INTEGER NOT NULL,
"GenreId" INTEGER,
"Composer" NVARCHAR(220),
"Milliseconds" INTEGER NOT NULL,
"Bytes" INTEGER,
"UnitPrice" NUMERIC(10, 2) NOT NULL,
PRIMARY KEY ("TrackId"),
FOREIGN KEY("MediaTypeId") REFERENCES "MediaType" ("MediaTypeId"),
FOREIGN KEY("GenreId") REFERENCES "Genre" ("GenreId"),
FOREIGN KEY("AlbumId") REFERENCES "Album" ("AlbumId")
)
SELECT * FROM 'Track' LIMIT 2;
TrackId Name AlbumId MediaTypeId GenreId Composer Milliseconds Bytes UnitPrice
1 For Those About To Rock (We Salute You) 1 1 1 Angus Young, Malcolm Young, Brian Johnson 343719 11170334 0.99
2 Balls to the Wall 2 2 1 None 342562 5510424 0.99
In [14]:
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)In [15]:
db_chain.run("What are some example tracks by Bach?")Out [15]:
[1m> Entering new SQLDatabaseChain chain...[0m
What are some example tracks by Bach?
SQLQuery:[32;1m[1;3m SELECT Name FROM Track WHERE Composer LIKE '%Bach%' LIMIT 5;[0m
SQLResult: [33;1m[1;3m[('American Woman',), ('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace',), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria',), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude',), ('Toccata and Fugue in D Minor, BWV 565: I. Toccata',)][0m
Answer:[32;1m[1;3m Some example tracks by Bach are 'American Woman', 'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude', and 'Toccata and Fugue in D Minor, BWV 565: I. Toccata'.[0m
[1m> Finished chain.[0m
' Some example tracks by Bach are \'American Woman\', \'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace\', \'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria\', \'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude\', and \'Toccata and Fugue in D Minor, BWV 565: I. Toccata\'.'
In [16]:
custom_table_info = {
"Track": """CREATE TABLE Track (
"TrackId" INTEGER NOT NULL,
"Name" NVARCHAR(200) NOT NULL,
"Composer" NVARCHAR(220),
PRIMARY KEY ("TrackId")
)
SELECT * FROM 'Track' LIMIT 3;
TrackId Name Composer
1 For Those About To Rock (We Salute You) Angus Young, Malcolm Young, Brian Johnson
2 Balls to the Wall None
3 My favorite song ever The coolest composer of all time"""
}In [17]:
db = SQLDatabase.from_uri(
"sqlite:///../../../../notebooks/Chinook.db",
include_tables=['Track', 'Playlist'],
sample_rows_in_table_info=2,
custom_table_info=custom_table_info)
print(db.table_info)
CREATE TABLE "Playlist" (
"PlaylistId" INTEGER NOT NULL,
"Name" NVARCHAR(120),
PRIMARY KEY ("PlaylistId")
)
SELECT * FROM 'Playlist' LIMIT 2;
PlaylistId Name
1 Music
2 Movies
CREATE TABLE Track (
"TrackId" INTEGER NOT NULL,
"Name" NVARCHAR(200) NOT NULL,
"Composer" NVARCHAR(220),
PRIMARY KEY ("TrackId")
)
SELECT * FROM 'Track' LIMIT 3;
TrackId Name Composer
1 For Those About To Rock (We Salute You) Angus Young, Malcolm Young, Brian Johnson
2 Balls to the Wall None
3 My favorite song ever The coolest composer of all time
In [18]:
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)
db_chain.run("What are some example tracks by Bach?")Out [18]:
[1m> Entering new SQLDatabaseChain chain...[0m
What are some example tracks by Bach?
SQLQuery:[32;1m[1;3m SELECT Name, Composer FROM Track WHERE Composer LIKE '%Bach%' LIMIT 5;[0m
SQLResult: [33;1m[1;3m[('American Woman', 'B. Cummings/G. Peterson/M.J. Kale/R. Bachman'), ('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Johann Sebastian Bach'), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Johann Sebastian Bach'), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude', 'Johann Sebastian Bach'), ('Toccata and Fugue in D Minor, BWV 565: I. Toccata', 'Johann Sebastian Bach')][0m
Answer:[32;1m[1;3m Some example tracks by Bach are 'American Woman', 'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude', and 'Toccata and Fugue in D Minor, BWV 565: I. Toccata'.[0m
[1m> Finished chain.[0m
' Some example tracks by Bach are \'American Woman\', \'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace\', \'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria\', \'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude\', and \'Toccata and Fugue in D Minor, BWV 565: I. Toccata\'.'
In [20]:
from langchain.chains import SQLDatabaseSequentialChain
db = SQLDatabase.from_uri("sqlite:///../../../../notebooks/Chinook.db")In [21]:
chain = SQLDatabaseSequentialChain.from_llm(llm, db, verbose=True)In [22]:
chain.run("How many employees are also customers?")Out [22]:
[1m> Entering new SQLDatabaseSequentialChain chain...[0m Table names to use: [33;1m[1;3m['Customer', 'Employee'][0m [1m> Entering new SQLDatabaseChain chain...[0m How many employees are also customers? SQLQuery:[32;1m[1;3m SELECT COUNT(*) FROM Employee INNER JOIN Customer ON Employee.EmployeeId = Customer.SupportRepId;[0m SQLResult: [33;1m[1;3m[(59,)][0m Answer:[32;1m[1;3m 59 employees are also customers.[0m [1m> Finished chain.[0m [1m> Finished chain.[0m
' 59 employees are also customers.'
In [ ]: