Strategy 1
Using SQL Database Chain with a custom prompt to explain what columns mean whatunknown
python
a year ago
1.5 kB
5
Indexable
from langchain.prompts import PromptTemplate
# Define your custom prompt template
custom_prompt = PromptTemplate(
input_variables=["input", "table_info", "dialect"],
template="""
You are an assistant that translates natural language queries into SQL queries.
Given an input question, create a syntactically correct {dialect} SQL query to run against a database with the following tables:
{table_info}
Only use the tables and columns that are relevant to the question.
Additional context:
- The 'users' table contains user information, including 'id', 'email', 'name', and 'website'.
- The 'websites' table contains website information, including 'domain' and 'owner_id', which references 'users.id'.
When generating the SQL queries, make sure to:
- Use the correct table and column names based on the question.
- Include any necessary JOIN operations to combine data from multiple tables.
- Avoid using tables or columns that are not relevant to the question.
Question: {input}
SQL Query:
"""
)
Explanation:
import os
from langchain import OpenAI, SQLDatabase, SQLDatabaseChain
from langchain.memory import ConversationBufferMemory
# Initialize the conversation memory
memory = ConversationBufferMemory()
# Connect to your database
db = SQLDatabase.from_uri(os.getenv("DB_URI"))
# Initialize the language model
llm = OpenAI(temperature=0, verbose=True)
# Create the SQLDatabaseChain with the custom prompt
db_chain = SQLDatabaseChain(
llm=llm,
database=db,
prompt=custom_prompt,
verbose=True,
Editor is loading...
Leave a Comment