Using Open AI and LangSmith connect to SQL Server

This post is self explanotory where using Open AI api and LangSmith, I connected to my local SQL server and get the data from my local SQL table and finally print the data in command prompt.

You need to have one Open API and LangSmith key to get this work. Just replace the keys on the respective code block.

Commented lines represents different ways to connect SQL server using Open AI and LangSmith.

import os
import pyodbc

os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = "YOUR LANGSMITH KEY GOES HERE"

if not os.environ.get("OPENAI_API_KEY"):
  os.environ["OPENAI_API_KEY"] = "YOUR OPENAI KEY GOES HERE"

#from langchain_community.utilities import SQLDatabase

#conn_str = "mssql+pyodbc:///?odbc_connect=DRIVER={SQL Server};SERVER=TUKAI\MSSQLSERVER01;DATABASE=EASY_DATE;Trusted_Connection=yes;"
#db = SQLDatabase.from_uri(conn_str)

#print(db.dialect)
#print(db.get_usable_table_names())
#response = db.run("SELECT * FROM Users LIMIT 10;")
#print(response.content)

#print(pyodbc.drivers())

#CASE-1 where SQL credential (UserId, and Password) is required to be used
#conn = pyodbc.connect(
#    "DRIVER={ODBC Driver 17 for SQL Server};"
#    "SERVER=TUKAI\MSSQLSERVER01;"
#    "DATABASE=EasyDate;"
#    "UID=Test;"
#    "PWD=Test4321!;"
#    "TrustServerCertificate=yes;"
#)

#CASE-2 where windows credential is being use
conn = pyodbc.connect(
    "DRIVER={ODBC Driver 17 for SQL Server};"
    "SERVER=TUKAI\MSSQLSERVER01;"
    "DATABASE=EasyDate;"
    "Trusted_Connection=yes;"
)

cursor = conn.cursor()
cursor.execute("SELECT TOP 5 * FROM dbo.Users")
for row in cursor:
    print(row)



The last but not the least - there is one warning and to overcome this, you need to use double '\' in the code - TUKAI\\MSSQLSERVER01


Enjoy coding :)

Comments

Popular posts from this blog

SharePoint Framework Reference Guide

SharePoint Admin Center

How to fix Azure DevOps error MSB4126