SQLServer
Azure SQL provides a dedicated Vector data type that simplifies the creation, storage, and querying of vector embeddings directly within a relational database. This eliminates the need for separate vector databases and related integrations, increasing the security of your solutions while reducing the overall complexity.
Azure SQL is a robust service that combines scalability, security, and high availability, providing all the benefits of a modern database solution. It leverages a sophisticated query optimizer and enterprise features to perform vector similarity searches alongside traditional SQL queries, enhancing data analysis and decision-making.
Read more on using Intelligent applications with Azure SQL Database
This notebook shows you how to leverage this integrated SQLÂ vector database to store documents and perform vector search queries using Cosine (cosine distance), L2 (Euclidean distance), and IP (inner product) to locate documents close to the query vectors
Setup​
Install the langchain-sqlserver
 python package.
The code lives in an integration package called:langchain-sqlserver.
!pip install langchain-sqlserver==0.1.1
Credentials​
There are no credentials needed to run this notebook, just make sure you downloaded the langchain_sqlserver
package
If you want to get best in-class automated tracing of your model calls you can also set your LangSmith API key by uncommenting below:
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
Initialization​
from langchain_sqlserver import SQLServer_VectorStore
Find your Azure SQL DB connection string in the Azure portal under your database settings
For more info: Connect to Azure SQL DB - Python
import os
import pyodbc
# Define your SQLServer Connection String
_CONNECTION_STRING = (
"Driver={ODBC Driver 18 for SQL Server};"
"Server=<YOUR_DBSERVER>.database.windows.net,1433;"
"Database=test;"
"TrustServerCertificate=yes;"
"Connection Timeout=60;"
"LongAsMax=yes;"
)
# Connection string can vary:
# "mssql+pyodbc://<username>:<password><servername>/<dbname>?driver=ODBC+Driver+18+for+SQL+Server" -> With Username and Password specified
# "mssql+pyodbc://<servername>/<dbname>?driver=ODBC+Driver+18+for+SQL+Server&Trusted_connection=yes" -> Uses Trusted connection
# "mssql+pyodbc://<servername>/<dbname>?driver=ODBC+Driver+18+for+SQL+Server" -> Uses EntraID connection
# "mssql+pyodbc://<servername>/<dbname>?driver=ODBC+Driver+18+for+SQL+Server&Trusted_connection=no" -> Uses EntraID connection
In this example we use Azure OpenAI to generate embeddings , however you can use different embeddings provided in LangChain.
You can deploy a version of Azure OpenAI instance on Azure Portal following this guide. Once you have your instance running, make sure you have the name of your instance and key. You can find the key in the Azure Portal, under the "Keys and Endpoint" section of your instance.
!pip install langchain-openai
# Import the necessary Libraries
from langchain_openai import AzureChatOpenAI, AzureOpenAIEmbeddings
# Set your AzureOpenAI details
azure_endpoint = "https://<YOUR_ENDPOINT>.openai.azure.com/"
azure_deployment_name_embedding = "text-embedding-3-small"
azure_deployment_name_chatcompletion = "chatcompletion"
azure_api_version = "2023-05-15"
azure_api_key = "YOUR_KEY"
# Use AzureChatOpenAI for chat completions
llm = AzureChatOpenAI(
azure_endpoint=azure_endpoint,
azure_deployment=azure_deployment_name_chatcompletion,
openai_api_version=azure_api_version,
openai_api_key=azure_api_key,
)
# Use AzureOpenAIEmbeddings for embeddings
embeddings = AzureOpenAIEmbeddings(
azure_endpoint=azure_endpoint,
azure_deployment=azure_deployment_name_embedding,
openai_api_version=azure_api_version,
openai_api_key=azure_api_key,
)
Manage vector store  ​
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_sqlserver import SQLServer_VectorStore
# Initialize the vector store
vector_store = SQLServer_VectorStore(
connection_string=_CONNECTION_STRING,
distance_strategy=DistanceStrategy.COSINE, # optional, if not provided, defaults to COSINE
embedding_function=embeddings, # you can use different embeddings provided in LangChain
embedding_length=1536,
table_name="langchain_test_table", # using table with a custom name
)
Add items to vector store​
## we will use some artificial data for this example
query = [
"I have bought several of the Vitality canned dog food products and have found them all to be of good quality. The product looks more like a stew than a processed meat and it smells better. My Labrador is finicky and she appreciates this product better than most.",
"The candy is just red , No flavor . Just plan and chewy . I would never buy them again",
"Arrived in 6 days and were so stale i could not eat any of the 6 bags!!",
"Got these on sale for roughly 25 cents per cup, which is half the price of my local grocery stores, plus they rarely stock the spicy flavors. These things are a GREAT snack for my office where time is constantly crunched and sometimes you can't escape for a real meal. This is one of my favorite flavors of Instant Lunch and will be back to buy every time it goes on sale.",
"If you are looking for a less messy version of licorice for the children, then be sure to try these! They're soft, easy to chew, and they don't get your hands all sticky and gross in the car, in the summer, at the beach, etc. We love all the flavos and sometimes mix these in with the chocolate to have a very nice snack! Great item, great price too, highly recommend!",
"We had trouble finding this locally - delivery was fast, no more hunting up and down the flour aisle at our local grocery stores.",
"Too much of a good thing? We worked this kibble in over time, slowly shifting the percentage of Felidae to national junk-food brand until the bowl was all natural. By this time, the cats couldn't keep it in or down. What a mess. We've moved on.",
"Hey, the description says 360 grams - that is roughly 13 ounces at under $4.00 per can. No way - that is the approximate price for a 100 gram can.",
"The taste of these white cheddar flat breads is like a regular cracker - which is not bad, except that I bought them because I wanted a cheese taste.<br /><br />What was a HUGE disappointment? How misleading the packaging of the box is. The photo on the box (I bought these in store) makes it look like it is full of long flatbreads (expanding the length and width of the box). Wrong! The plastic tray that holds the crackers is about 2"
" smaller all around - leaving you with about 15 or so small flatbreads.<br /><br />What is also bad about this is that the company states they use biodegradable and eco-friendly packaging. FAIL! They used a HUGE box for a ridiculously small amount of crackers. Not ecofriendly at all.<br /><br />Would I buy these again? No - I feel ripped off. The other crackers (like Sesame Tarragon) give you a little<br />more bang for your buck and have more flavor.",
"I have used this product in smoothies for my son and he loves it. Additionally, I use this oil in the shower as a skin conditioner and it has made my skin look great. Some of the stretch marks on my belly has disappeared quickly. Highly recommend!!!",
"Been taking Coconut Oil for YEARS. This is the best on the retail market. I wish it was in glass, but this is the one.",
]
query_metadata = [
{"id": 1, "summary": "Good Quality Dog Food"},
{"id": 8, "summary": "Nasty No flavor"},
{"id": 4, "summary": "stale product"},
{"id": 11, "summary": "Great value and convenient ramen"},
{"id": 5, "summary": "Great for the kids!"},
{"id": 2, "summary": "yum falafel"},
{"id": 9, "summary": "Nearly killed the cats"},
{"id": 6, "summary": "Price cannot be correct"},
{"id": 3, "summary": "Taste is neutral, quantity is DECEITFUL!"},
{"id": 7, "summary": "This stuff is great"},
{"id": 10, "summary": "The reviews don't lie"},
]
vector_store.add_texts(texts=query, metadatas=query_metadata)
[1, 8, 4, 11, 5, 2, 9, 6, 3, 7, 10]