Este artículo es un sencillo ejemplo para probar SqlDatabaseChain pidiéndole a OpenAI cierta información y que escriba consultas SQL sobre una base de datos IRIS.
Quizá despierte el interés de alguno de vosotros.
Muchas gracias a sqlalchemy-iris (autor @Dmitry Maslennikov). Ese proyecto ha sido indispensable para esta prueba.
El script de este artículo usa la API de OpenAI así que tenedlo en cuenta para no compartir la información de vuestras tablas externamente en el caso de que no queráis hacerlo. Podría llegar a implementarse un modelo local en caso que lo necesitaseis.
Crear un nuevo entorno virtual
mkdir chainsql cd chainsql python -m venv . scripts\activate pip install langchain pip install wget # Need to connect to IRIS so installing a fresh python driver python -c "import wget;url='https://raw.githubusercontent.com/intersystems-community/iris-driver-distribution/main/DB-API/intersystems_irispython-3.2.0-py3-none-any.whl';wget.download(url)" # And for more magic pip install sqlalchemy-iris pip install openai set OPENAI_API_KEY=[ Your OpenAI Key ] python
Prueba inicial
from langchain import OpenAI, SQLDatabase, SQLDatabaseChain db = SQLDatabase.from_uri("iris://superuser:******@localhost:51775/USER") llm = OpenAI(temperature=0, verbose=True) db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True) db_chain.run("How many Tables are there")
Resultado (error)
sqlalchemy.exc.DatabaseError: (intersystems_iris.dbapi._DBAPI.DatabaseError) [SQLCODE: <-25>:<Input encountered after end of query>] [Location: <Prepare>] [%msg: < Input (;) encountered after end of query^SELECT COUNT ( * ) FROM information_schema . tables WHERE table_schema = :%qpar(1) ;>] [SQL: SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';] (Background on this error at: https://sqlalche.me/e/20/4xp6) ←[32;1m←[1;3mSELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';←[0m>>>
Nota para desarrolladores
A IRIS no le gusta que le pasen consultas SQL terminadas con un punto y coma. Por ese motivo está fallado.
¿Qué podemos hacer ahora?
Idea: ¿Qué tal si le digo a Langchain que lo arregle?
Vamos allá
Prueba. Segundo intento
from langchain import OpenAI, SQLDatabase, SQLDatabaseChain
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"
The SQL query should NOT end with semi-colon
Question: {input}"""
PROMPT = PromptTemplate(
input_variables=["input", "dialect"], template=_DEFAULT_TEMPLATE
)
db = SQLDatabase.from_uri("iris://superuser:******@localhost:51775/USER") llm = OpenAI(temperature=0, verbose=True)
llm = OpenAI(temperature=0, verbose=True)
db_chain = SQLDatabaseChain(llm=llm, database=db, prompt=PROMPT, verbose=True)
db_chain.run("How many Tables are there")
Resultado (segundo intento)
SQLQuery:←[32;1m←[1;3mSELECT COUNT(*) FROM information_schema.tables←[0m SQLResult: ←[33;1m←[1;3m[(499,)]←[0m Answer:←[32;1m←[1;3mThere are 499 tables.←[0m ←[1m> Finished chain.←[0m 'There are 499 tables.'
Dije que sería rápido :)
Referencias:
https://walkingtree.tech/natural-language-to-query-your-sql-database-usi...
https://python.langchain.com/en/latest/modules/chains/examples/sqlite.ht...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html