You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
langchain/docs/extras/integrations/vectorstores/azuresearch.ipynb

627 lines
24 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Azure Cognitive Search\n",
"\n",
"[Azure Cognitive Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) (formerly known as `Azure Search`) is a cloud search service that gives developers infrastructure, APIs, and tools for building a rich search experience over private, heterogeneous content in web, mobile, and enterprise applications.\n",
"\n",
"Vector search is currently in public preview. It's available through the Azure portal, preview REST API and beta client libraries. [More info](https://learn.microsoft.com/en-us/azure/search/vector-search-overview) Beta client libraries are subject to potential breaking changes, please be sure to use the SDK package version identified below. azure-search-documents==11.4.0b8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Install Azure Cognitive Search SDK"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install azure-search-documents==11.4.0b8\n",
"!pip install azure-identity"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import required libraries"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import openai\n",
"import os\n",
"from langchain.embeddings import OpenAIEmbeddings\n",
"from langchain.vectorstores.azuresearch import AzureSearch"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configure OpenAI settings\n",
"Configure the OpenAI settings to use Azure OpenAI or OpenAI"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"os.environ[\"OPENAI_API_TYPE\"] = \"azure\"\n",
"os.environ[\"OPENAI_API_BASE\"] = \"YOUR_OPENAI_ENDPOINT\"\n",
"os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPENAI_API_KEY\"\n",
"os.environ[\"OPENAI_API_VERSION\"] = \"2023-05-15\"\n",
"model: str = \"text-embedding-ada-002\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Configure vector store settings\n",
" \n",
"Set up the vector store settings using environment variables:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"vector_store_address: str = \"YOUR_AZURE_SEARCH_ENDPOINT\"\n",
"vector_store_password: str = \"YOUR_AZURE_SEARCH_ADMIN_KEY\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create embeddings and vector store instances\n",
" \n",
"Create instances of the OpenAIEmbeddings and AzureSearch classes:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",
"index_name: str = \"langchain-vector-demo\"\n",
"vector_store: AzureSearch = AzureSearch(\n",
" azure_search_endpoint=vector_store_address,\n",
" azure_search_key=vector_store_password,\n",
" index_name=index_name,\n",
" embedding_function=embeddings.embed_query,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Insert text and embeddings into vector store\n",
" \n",
"Add texts and metadata from the JSON data to the vector store:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.document_loaders import TextLoader\n",
"from langchain.text_splitter import CharacterTextSplitter\n",
"\n",
"loader = TextLoader(\"../../../state_of_the_union.txt\", encoding=\"utf-8\")\n",
"\n",
"documents = loader.load()\n",
"text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
"docs = text_splitter.split_documents(documents)\n",
"\n",
"vector_store.add_documents(documents=docs)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Perform a vector similarity search\n",
" \n",
"Execute a pure vector similarity search using the similarity_search() method:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while youre at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
"\n",
"Tonight, Id like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
"\n",
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
"\n",
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nations top legal minds, who will continue Justice Breyers legacy of excellence.\n"
]
}
],
"source": [
"# Perform a similarity search\n",
"docs = vector_store.similarity_search(\n",
" query=\"What did the president say about Ketanji Brown Jackson\",\n",
" k=3,\n",
" search_type=\"similarity\",\n",
")\n",
"print(docs[0].page_content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Perform a vector similarity search with relevance scores\n",
" \n",
"Execute a pure vector similarity search using the similarity_search_with_relevance_scores() method:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[(Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while youre at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, Id like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nations top legal minds, who will continue Justice Breyers legacy of excellence.', metadata={'source': 'C:\\\\repos\\\\langchain-fruocco-acs\\\\langchain\\\\docs\\\\extras\\\\modules\\\\state_of_the_union.txt'}),\n",
" 0.8441472),\n",
" (Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while youre at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, Id like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nations top legal minds, who will continue Justice Breyers legacy of excellence.', metadata={'source': 'C:\\\\repos\\\\langchain-fruocco-acs\\\\langchain\\\\docs\\\\extras\\\\modules\\\\state_of_the_union.txt'}),\n",
" 0.8441472),\n",
" (Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since shes been nominated, shes received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \\n\\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \\n\\nWe can do both. At our border, weve installed new technology like cutting-edge scanners to better detect drug smuggling. \\n\\nWeve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \\n\\nWere putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWere securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', metadata={'source': 'C:\\\\repos\\\\langchain-fruocco-acs\\\\langchain\\\\docs\\\\extras\\\\modules\\\\state_of_the_union.txt'}),\n",
" 0.82153815),\n",
" (Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since shes been nominated, shes received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \\n\\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \\n\\nWe can do both. At our border, weve installed new technology like cutting-edge scanners to better detect drug smuggling. \\n\\nWeve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \\n\\nWere putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWere securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', metadata={'source': 'C:\\\\repos\\\\langchain-fruocco-acs\\\\langchain\\\\docs\\\\extras\\\\modules\\\\state_of_the_union.txt'}),\n",
" 0.82153815)]\n"
]
}
],
"source": [
"docs_and_scores = vector_store.similarity_search_with_relevance_scores(query=\"What did the president say about Ketanji Brown Jackson\", k=4, score_threshold=0.80)\n",
"from pprint import pprint\n",
"pprint(docs_and_scores)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Perform a Hybrid Search\n",
"\n",
"Execute hybrid search using the search_type or hybrid_search() method:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while youre at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
"\n",
"Tonight, Id like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
"\n",
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
"\n",
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nations top legal minds, who will continue Justice Breyers legacy of excellence.\n"
]
}
],
"source": [
"# Perform a hybrid search\n",
"docs = vector_store.similarity_search(\n",
" query=\"What did the president say about Ketanji Brown Jackson\",\n",
" k=3, \n",
" search_type=\"hybrid\"\n",
")\n",
"print(docs[0].page_content)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while youre at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
"\n",
"Tonight, Id like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
"\n",
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
"\n",
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nations top legal minds, who will continue Justice Breyers legacy of excellence.\n"
]
}
],
"source": [
"# Perform a hybrid search\n",
"docs = vector_store.hybrid_search(\n",
" query=\"What did the president say about Ketanji Brown Jackson\", \n",
" k=3\n",
")\n",
"print(docs[0].page_content)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Create a new index with custom filterable fields "
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"from azure.search.documents.indexes.models import (\n",
" SearchableField,\n",
" SearchField,\n",
" SearchFieldDataType,\n",
" SimpleField,\n",
" ScoringProfile,\n",
" TextWeights,\n",
")\n",
"\n",
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",
"embedding_function = embeddings.embed_query\n",
"\n",
"fields = [\n",
" SimpleField(\n",
" name=\"id\",\n",
" type=SearchFieldDataType.String,\n",
" key=True,\n",
" filterable=True,\n",
" ),\n",
" SearchableField(\n",
" name=\"content\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" SearchField(\n",
" name=\"content_vector\",\n",
" type=SearchFieldDataType.Collection(SearchFieldDataType.Single),\n",
" searchable=True,\n",
" vector_search_dimensions=len(embedding_function(\"Text\")),\n",
" vector_search_configuration=\"default\",\n",
" ),\n",
" SearchableField(\n",
" name=\"metadata\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field to store the title\n",
" SearchableField(\n",
" name=\"title\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field for filtering on document source\n",
" SimpleField(\n",
" name=\"source\",\n",
" type=SearchFieldDataType.String,\n",
" filterable=True,\n",
" ),\n",
"]\n",
"\n",
"index_name: str = \"langchain-vector-demo-custom\"\n",
"\n",
"vector_store: AzureSearch = AzureSearch(\n",
" azure_search_endpoint=vector_store_address,\n",
" azure_search_key=vector_store_password,\n",
" index_name=index_name,\n",
" embedding_function=embedding_function,\n",
" fields=fields,\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Perform a query with a custom filter"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"# Data in the metadata dictionary with a corresponding field in the index will be added to the index\n",
"# In this example, the metadata dictionary contains a title, a source and a random field\n",
"# The title and the source will be added to the index as separate fields, but the random won't. (as it is not defined in the fields list)\n",
"# The random field will be only stored in the metadata field\n",
"vector_store.add_texts(\n",
" [\"Test 1\", \"Test 2\", \"Test 3\"],\n",
" [\n",
" {\"title\": \"Title 1\", \"source\": \"A\", \"random\": \"10290\"},\n",
" {\"title\": \"Title 2\", \"source\": \"A\", \"random\": \"48392\"},\n",
" {\"title\": \"Title 3\", \"source\": \"B\", \"random\": \"32893\"},\n",
" ],\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Test 3', metadata={'title': 'Title 3', 'source': 'B', 'random': '32893'}),\n",
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'A', 'random': '10290'}),\n",
" Document(page_content='Test 2', metadata={'title': 'Title 2', 'source': 'A', 'random': '48392'})]"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res = vector_store.similarity_search(query=\"Test 3 source1\", k=3, search_type=\"hybrid\")\n",
"res"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'A', 'random': '10290'}),\n",
" Document(page_content='Test 2', metadata={'title': 'Title 2', 'source': 'A', 'random': '48392'})]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res = vector_store.similarity_search(query=\"Test 3 source1\", k=3, search_type=\"hybrid\", filters=\"source eq 'A'\")\n",
"res"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Create a new index with a Scoring Profile"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"from azure.search.documents.indexes.models import (\n",
" SearchableField,\n",
" SearchField,\n",
" SearchFieldDataType,\n",
" SimpleField,\n",
" ScoringProfile,\n",
" TextWeights,\n",
" ScoringFunction,\n",
" FreshnessScoringFunction,\n",
" FreshnessScoringParameters\n",
")\n",
"\n",
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(deployment=model, chunk_size=1)\n",
"embedding_function = embeddings.embed_query\n",
"\n",
"fields = [\n",
" SimpleField(\n",
" name=\"id\",\n",
" type=SearchFieldDataType.String,\n",
" key=True,\n",
" filterable=True,\n",
" ),\n",
" SearchableField(\n",
" name=\"content\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" SearchField(\n",
" name=\"content_vector\",\n",
" type=SearchFieldDataType.Collection(SearchFieldDataType.Single),\n",
" searchable=True,\n",
" vector_search_dimensions=len(embedding_function(\"Text\")),\n",
" vector_search_configuration=\"default\",\n",
" ),\n",
" SearchableField(\n",
" name=\"metadata\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field to store the title\n",
" SearchableField(\n",
" name=\"title\",\n",
" type=SearchFieldDataType.String,\n",
" searchable=True,\n",
" ),\n",
" # Additional field for filtering on document source\n",
" SimpleField(\n",
" name=\"source\",\n",
" type=SearchFieldDataType.String,\n",
" filterable=True,\n",
" ),\n",
" # Additional data field for last doc update\n",
" SimpleField(\n",
" name=\"last_update\",\n",
" type=SearchFieldDataType.DateTimeOffset,\n",
" searchable=True,\n",
" filterable=True\n",
" )\n",
"]\n",
"# Adding a custom scoring profile with a freshness function\n",
"sc_name = \"scoring_profile\"\n",
"sc = ScoringProfile(\n",
" name=sc_name,\n",
" text_weights=TextWeights(weights={\"title\": 5}),\n",
" function_aggregation=\"sum\",\n",
" functions=[\n",
" FreshnessScoringFunction(\n",
" field_name=\"last_update\",\n",
" boost=100,\n",
" parameters=FreshnessScoringParameters(boosting_duration=\"P2D\"),\n",
" interpolation=\"linear\"\n",
" )\n",
" ]\n",
")\n",
"\n",
"index_name = \"langchain-vector-demo-custom-scoring-profile\"\n",
"\n",
"vector_store: AzureSearch = AzureSearch(\n",
" azure_search_endpoint=vector_store_address,\n",
" azure_search_key=vector_store_password,\n",
" index_name=index_name,\n",
" embedding_function=embeddings.embed_query,\n",
" fields=fields,\n",
" scoring_profiles = [sc],\n",
" default_scoring_profile = sc_name\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['NjQyNTI5ZmMtNmVkYS00Njg5LTk2ZDgtMjM3OTY4NTJkYzFj',\n",
" 'M2M0MGExZjAtMjhiZC00ZDkwLThmMTgtODNlN2Y2ZDVkMTMw',\n",
" 'ZmFhMDE1NzMtMjZjNS00MTFiLTk0MTEtNGRkYjgwYWQwOTI0']"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Adding same data with different last_update to show Scoring Profile effect\n",
"from datetime import datetime, timedelta\n",
"\n",
"today = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",
"yesterday = (datetime.utcnow() - timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",
"one_month_ago = (datetime.utcnow() - timedelta(days=30)).strftime('%Y-%m-%dT%H:%M:%S-00:00')\n",
"\n",
"vector_store.add_texts(\n",
" [\"Test 1\", \"Test 1\", \"Test 1\"],\n",
" [\n",
" {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"10290\", \"last_update\": today},\n",
" {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"48392\", \"last_update\": yesterday},\n",
" {\"title\": \"Title 1\", \"source\": \"source1\", \"random\": \"32893\", \"last_update\": one_month_ago},\n",
" ],\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '10290', 'last_update': '2023-07-13T10:47:39-00:00'}),\n",
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '48392', 'last_update': '2023-07-12T10:47:39-00:00'}),\n",
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '32893', 'last_update': '2023-06-13T10:47:39-00:00'})]"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"res = vector_store.similarity_search(query=\"Test 1\", k=3, search_type=\"similarity\")\n",
"res"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3.9.13 ('.venv': venv)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"orig_nbformat": 4,
"vscode": {
"interpreter": {
"hash": "645053d6307d413a1a75681b5ebb6449bb2babba4bcb0bf65a1ddc3dbefb108a"
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}