Skip to content

Instantly share code, notes, and snippets.

@qlawmarq
Last active June 8, 2023 00:56
Show Gist options
  • Save qlawmarq/7763cf453ac86149382484090556dc9e to your computer and use it in GitHub Desktop.
Save qlawmarq/7763cf453ac86149382484090556dc9e to your computer and use it in GitHub Desktop.
Chat with SQL database (MySQL)
from langchain.llms import OpenAI
from langchain import OpenAI, SQLDatabase, SQLDatabaseChain
from langchain.prompts.prompt import PromptTemplate
import os
def chat_with_mysql_database(prompt: str):
"""
Args:
prompt (str): Question to ask e.g. "Generate an SQL query to retrieve all users"
Returns:
str: Answer e.g. "SELECT * from user;"
"""
db = SQLDatabase.from_uri("mysql+pymysql://your_db_user:[email protected]/db_name")
llm = OpenAI(temperature=0, verbose=True, openai_api_key=os.environ.get('OPENAI_API_KEY'))
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True, use_query_checker=True, top_k=1)
result = db_chain.run(prompt)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment