Skip to content

Instantly share code, notes, and snippets.

@rajivmehtaflex
Last active May 20, 2024 13:01
Show Gist options
  • Save rajivmehtaflex/f6c36b89fdee1ead3f75162b478f3486 to your computer and use it in GitHub Desktop.
Save rajivmehtaflex/f6c36b89fdee1ead3f75162b478f3486 to your computer and use it in GitHub Desktop.
using mysql server in colab.
apt install mysql-server
service mysql start
mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'root';FLUSH PRIVILEGES;"
#username/password:root/root
mysql -u root -p
#pip install llama-index-llms-ollama llama-index SQLAlchemy pymysql llama-index-embeddings-huggingface
#curl -fsSL https://ollama.com/install.sh | sh && ollama serve
#ollama run duckdb-nsql
db_user = "root"
db_password = "root"
db_host = "localhost"
db_port = "3306"
db_name = "gdb"
from sqlalchemy import create_engine, text
from llama_index.llms.ollama import Ollama
from llama_index.core import SQLDatabase
from llama_index.core.query_engine import NLSQLTableQueryEngine
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core import Settings
def get_connection():
return create_engine(
url="mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format(
db_user, db_password, db_host, db_port, db_name
)
)
llm = Ollama(model="duckdb-nsql", request_timeout=30.0)
print("Selected Model :: ", llm.model)
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
engine = get_connection()
db_tables = ["books"]
sql_database = SQLDatabase(engine, include_tables=db_tables)
query_engine = NLSQLTableQueryEngine(sql_database=sql_database,tables=db_tables,llm=llm)
while True:
query_str = input("Enter your query ::>")
response = query_engine.query(query_str)
print(response.metadata['sql_query'])
print(response.metadata['result'])
print("Run generated SQL query on database ::>")
with engine.connect() as connection:
results = connection.execute(text(response.metadata['sql_query']))
print(results.fetchall())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment