-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.py
98 lines (73 loc) · 2.38 KB
/
sql.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
build a research assistant that can answer questions over sqlite db
"""
from pathlib import Path
from langchain.memory import ConversationBufferMemory
from langchain_community.chat_models.ollama import ChatOllama
from langchain_community.utilities.sql_database import SQLDatabase
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
# Add the LLM downloaded from Ollama
# ollama_llm = "dolphin-llama3:8b"
# llm = ChatOllama(model=ollama_llm)
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(temperature=0)
db_path = Path(__file__).parent / "nba_roster.db"
rel = db_path.relative_to(Path.cwd())
db_string = f"sqlite:///{rel}"
db = SQLDatabase.from_uri(db_string, sample_rows_in_table_info=0)
def get_schema(_):
return db.get_table_info()
def run_query(query):
return db.run(query)
# Prompt
template = """Based on the table schema below, write a SQL query that would answer the user's question:
{schema}
Question: {question}
SQL Query:""" # noqa: E501
prompt = ChatPromptTemplate.from_messages(
[
("system", "Given an input question, convert it to a SQL query. No pre-amble."),
("human", template),
]
)
memory = ConversationBufferMemory(return_messages=True)
# Chain to query with memory
sql_chain = (
RunnablePassthrough.assign(
schema=get_schema,
)
| prompt
| llm.bind(stop=["\nSQLResult:"])
| StrOutputParser()
)
# Chain to answer
template = """Based on the table schema below, question, sql query, and sql response, write a natural language response:
{schema}
Question: {question}
SQL Query: {query}
SQL Response: {response}""" # noqa: E501
prompt_response = ChatPromptTemplate.from_messages(
[
(
"system",
"Given an input question and SQL response, convert it to a natural "
"language answer. No pre-amble.",
),
("human", template),
]
)
# Supply the input types to the prompt
class InputType(BaseModel):
question: str
sql_ans_chain = (
RunnablePassthrough.assign(query=sql_chain).with_types(input_type=InputType)
| RunnablePassthrough.assign(
schema=get_schema,
response=lambda x: db.run(x["query"]),
)
| prompt_response
| llm
)