Skip to main content

SqlDatabaseChain

The SqlDatabaseChain allows you to answer questions over a SQL database. This example uses Chinook database, which is a sample database available for SQL Server, Oracle, MySQL, etc.

Set up

First install typeorm:

npm install typeorm

Then install the dependencies needed for your database. For example, for SQLite:

npm install sqlite3

For other databases see https://typeorm.io/#installation

Finally follow the instructions on https://database.guide/2-sample-databases-sqlite/ to get the sample database for this example.

import { DataSource } from "typeorm";
import { OpenAI } from "langchain/llms/openai";
import { SqlDatabase } from "langchain/sql_db";
import { SqlDatabaseChain } from "langchain/chains";

/**
* This example uses Chinook database, which is a sample database available for SQL Server, Oracle, MySQL, etc.
* To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file
* in the examples folder.
*/
export const run = async () => {
const datasource = new DataSource({
type: "sqlite",
database: "Chinook.db",
});

const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
});

const chain = new SqlDatabaseChain({
llm: new OpenAI({ temperature: 0 }),
database: db,
});

const res = await chain.run("How many tracks are there?");
console.log(res);
// There are 3503 tracks.
};

You can include or exclude tables when creating the SqlDatabase object to help the chain focus on the tables you want. It can also reduce the number of tokens used in the chain.

const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
includeTables: ["Track"],
});