mirror of
https://github.com/hwchase17/langchain.git
synced 2025-05-11 18:16:12 +00:00
- **Description:** Support additional kwargs options for the Azure Search client (Described here https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md#configurations) - **Issue:** N/A - **Dependencies:** No additional Dependencies ---------
801 lines
32 KiB
Plaintext
801 lines
32 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {
|
||
"collapsed": false
|
||
},
|
||
"source": [
|
||
"# Azure AI Search\n",
|
||
"\n",
|
||
"[Azure AI Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search) (formerly known as `Azure Search` and `Azure Cognitive Search`) is a cloud search service that gives developers infrastructure, APIs, and tools for information retrieval of vector, keyword, and hybrid queries at scale.\n",
|
||
"\n",
|
||
"You'll need to install `langchain-community` with `pip install -qU langchain-community` to use this integration"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Install Azure AI Search SDK\n",
|
||
"\n",
|
||
"Use azure-search-documents package version 11.4.0 or later."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"%pip install --upgrade --quiet azure-search-documents\n",
|
||
"%pip install --upgrade --quiet azure-identity"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Import required libraries\n",
|
||
"\n",
|
||
"`OpenAIEmbeddings` is assumed, but if you're using Azure OpenAI, import `AzureOpenAIEmbeddings` instead."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"import os\n",
|
||
"\n",
|
||
"from langchain_community.vectorstores.azuresearch import AzureSearch\n",
|
||
"from langchain_openai import AzureOpenAIEmbeddings, OpenAIEmbeddings"
|
||
]
|
||
},
|
||
{
|
||
"attachments": {},
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Configure OpenAI settings\n",
|
||
"Set variables for your OpenAI provider. You need either an [OpenAI account](https://platform.openai.com/docs/quickstart?context=python) or an [Azure OpenAI account](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/create-resource) to generate the embeddings. "
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Option 1: use an OpenAI account\n",
|
||
"openai_api_key: str = \"PLACEHOLDER FOR YOUR API KEY\"\n",
|
||
"openai_api_version: str = \"2023-05-15\"\n",
|
||
"model: str = \"text-embedding-ada-002\""
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 27,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Option 2: use an Azure OpenAI account with a deployment of an embedding model\n",
|
||
"azure_endpoint: str = \"PLACEHOLDER FOR YOUR AZURE OPENAI ENDPOINT\"\n",
|
||
"azure_openai_api_key: str = \"PLACEHOLDER FOR YOUR AZURE OPENAI KEY\"\n",
|
||
"azure_openai_api_version: str = \"2023-05-15\"\n",
|
||
"azure_deployment: str = \"text-embedding-ada-002\""
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Configure vector store settings\n",
|
||
"\n",
|
||
"You need an [Azure subscription](https://azure.microsoft.com/en-us/free/search) and [Azure AI Search service](https://learn.microsoft.com/azure/search/search-create-service-portal) to use this vector store integration. No-cost versions are available for small and limited workloads.\n",
|
||
" \n",
|
||
"Set variables for your Azure AI Search URL and admin API key. You can get these variables from the [Azure portal](https://portal.azure.com/#blade/HubsExtension/BrowseResourceBlade/resourceType/Microsoft.Search%2FsearchServices)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 24,
|
||
"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. When you complete this step, you should have an empty search index on your Azure AI Search resource. The integration module provides a default schema."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Option 1: Use OpenAIEmbeddings with OpenAI account\n",
|
||
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(\n",
|
||
" openai_api_key=openai_api_key, openai_api_version=openai_api_version, model=model\n",
|
||
")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 29,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Option 2: Use AzureOpenAIEmbeddings with an Azure account\n",
|
||
"embeddings: AzureOpenAIEmbeddings = AzureOpenAIEmbeddings(\n",
|
||
" azure_deployment=azure_deployment,\n",
|
||
" openai_api_version=azure_openai_api_version,\n",
|
||
" azure_endpoint=azure_endpoint,\n",
|
||
" api_key=azure_openai_api_key,\n",
|
||
")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Create vector store instance\n",
|
||
" \n",
|
||
"Create instance of the AzureSearch class using the embeddings from above"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 30,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"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": "code",
|
||
"execution_count": null,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Specify additional properties for the Azure client such as the following https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md#configurations\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",
|
||
" # Configure max retries for the Azure client\n",
|
||
" additional_search_client_options={\"retry_total\": 4},\n",
|
||
")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Insert text and embeddings into vector store\n",
|
||
" \n",
|
||
"This step loads, chunks, and vectorizes the sample document, and then indexes the content into a search index on Azure AI Search."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 31,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/plain": [
|
||
"['M2U1OGM4YzAtYjMxYS00Nzk5LTlhNDgtZTc3MGVkNTg1Mjc0',\n",
|
||
" 'N2I2MGNiZDEtNDdmZS00YWNiLWJhYTYtYWEzMmFiYzU1ZjZm',\n",
|
||
" 'YWFmNDViNTQtZTc4MS00MTdjLTkzZjQtYTJkNmY1MDU4Yzll',\n",
|
||
" 'MjgwY2ExZDctYTUxYi00NjE4LTkxMjctZDA1NDQ1MzU4NmY1',\n",
|
||
" 'NGE4NzhkNTAtZWYxOC00ZmI5LTg0MTItZDQ1NzMxMWVmMTIz',\n",
|
||
" 'MTYwMWU3YjAtZDIzOC00NTYwLTgwMmEtNDI1NzA2MWVhMDYz',\n",
|
||
" 'NGM5N2NlZjgtMTc5Ny00OGEzLWI5YTgtNDFiZWE2MjBlMzA0',\n",
|
||
" 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DFkLWJhZDQtM2UxN2RkOTU1MTdl']"
|
||
]
|
||
},
|
||
"execution_count": 31,
|
||
"metadata": {},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"source": [
|
||
"from langchain_community.document_loaders import TextLoader\n",
|
||
"from langchain_text_splitters import CharacterTextSplitter\n",
|
||
"\n",
|
||
"loader = TextLoader(\"../../how_to/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": 11,
|
||
"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 you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||
"\n",
|
||
"Tonight, I’d 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 nation’s top legal minds, who will continue Justice Breyer’s 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. Queries that don't meet the threshold requirements are exluded."
|
||
]
|
||
},
|
||
{
|
||
"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 you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d 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 nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../how_to/state_of_the_union.txt'}),\n",
|
||
" 0.84402436),\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 she’s been nominated, she’s 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, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \\n\\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \\n\\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.', metadata={'source': '../../how_to/state_of_the_union.txt'}),\n",
|
||
" 0.82128483),\n",
|
||
" (Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \\n\\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \\n\\nWhile it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. \\n\\nAnd soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \\n\\nSo tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \\n\\nFirst, beat the opioid epidemic.', metadata={'source': '../../how_to/state_of_the_union.txt'}),\n",
|
||
" 0.8151042),\n",
|
||
" (Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \\n\\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \\n\\nThat ends on my watch. \\n\\nMedicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect. \\n\\nWe’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees. \\n\\nLet’s pass the Paycheck Fairness Act and paid leave. \\n\\nRaise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty. \\n\\nLet’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.', metadata={'source': '../../how_to/state_of_the_union.txt'}),\n",
|
||
" 0.8148832)]\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"docs_and_scores = vector_store.similarity_search_with_relevance_scores(\n",
|
||
" query=\"What did the president say about Ketanji Brown Jackson\",\n",
|
||
" k=4,\n",
|
||
" score_threshold=0.80,\n",
|
||
")\n",
|
||
"from pprint import pprint\n",
|
||
"\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. Vector and nonvector text fields are queried in parallel, results are merged, and top matches of the unified result set are returned."
|
||
]
|
||
},
|
||
{
|
||
"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 you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||
"\n",
|
||
"Tonight, I’d 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 nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"# Perform a hybrid search using the search_type parameter\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 you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
|
||
"\n",
|
||
"Tonight, I’d 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 nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n"
|
||
]
|
||
}
|
||
],
|
||
"source": [
|
||
"# Perform a hybrid search using the hybrid_search method\n",
|
||
"docs = vector_store.hybrid_search(\n",
|
||
" query=\"What did the president say about Ketanji Brown Jackson\", k=3\n",
|
||
")\n",
|
||
"print(docs[0].page_content)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"## Custom schemas and queries\n",
|
||
"\n",
|
||
"This section shows you how to replace the default schema with a custom schema.\n"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### Create a new index with custom filterable fields \n",
|
||
"\n",
|
||
"This schema shows field definitions. It's the default schema, plus several new fields attributed as filterable. Because it's using the default vector configuration, you won't see vector configuration or vector profile overrides here. The name of the default vector profile is \"myHnswProfile\" and it's using a vector configuration of Hierarchical Navigable Small World (HNSW) for indexing and queries against the content_vector field.\n",
|
||
"\n",
|
||
"There's no data for this schema in this step. When you execute the cell, you should get an empty index on Azure AI Search."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 15,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from azure.search.documents.indexes.models import (\n",
|
||
" ScoringProfile,\n",
|
||
" SearchableField,\n",
|
||
" SearchField,\n",
|
||
" SearchFieldDataType,\n",
|
||
" SimpleField,\n",
|
||
" TextWeights,\n",
|
||
")\n",
|
||
"\n",
|
||
"# Replace OpenAIEmbeddings with AzureOpenAIEmbeddings if Azure OpenAI is your provider.\n",
|
||
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(\n",
|
||
" openai_api_key=openai_api_key, openai_api_version=openai_api_version, model=model\n",
|
||
")\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_profile_name=\"myHnswProfile\",\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",
|
||
")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### Add data and perform a query that includes a filter\n",
|
||
"\n",
|
||
"This example adds data to the vector store based on the custom schema. It loads text into the title and source fields. The source field is filterable. The sample query in this section filters the results based on content in the source field."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 16,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/plain": [
|
||
"['ZjhmMTg0NTEtMjgwNC00N2M0LWFiZGEtMDllMGU1Mzk1NWRm',\n",
|
||
" 'MzQwYWUwZDEtNDJkZC00MzgzLWIwMzItYzMwOGZkYTRiZGRi',\n",
|
||
" 'ZjFmOWVlYTQtODRiMC00YTY3LTk2YjUtMzY1NDBjNjY5ZmQ2']"
|
||
]
|
||
},
|
||
"execution_count": 16,
|
||
"metadata": {},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"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 are added to the index as separate fields, but the random value is ignored because it's not defined in the schema.\n",
|
||
"# The random field is 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",
|
||
")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 17,
|
||
"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": 17,
|
||
"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": 18,
|
||
"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": 18,
|
||
"metadata": {},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"source": [
|
||
"res = vector_store.similarity_search(\n",
|
||
" query=\"Test 3 source1\", k=3, search_type=\"hybrid\", filters=\"source eq 'A'\"\n",
|
||
")\n",
|
||
"res"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"metadata": {},
|
||
"source": [
|
||
"### Create a new index with a scoring profile\n",
|
||
"\n",
|
||
"Here's another custom schema that includes a scoring profile definition. A scoring profile is used for relevance tuning of nonvector content, which is helpful in hybrid search scenarios."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 19,
|
||
"metadata": {},
|
||
"outputs": [],
|
||
"source": [
|
||
"from azure.search.documents.indexes.models import (\n",
|
||
" FreshnessScoringFunction,\n",
|
||
" FreshnessScoringParameters,\n",
|
||
" ScoringProfile,\n",
|
||
" SearchableField,\n",
|
||
" SearchField,\n",
|
||
" SearchFieldDataType,\n",
|
||
" SimpleField,\n",
|
||
" TextWeights,\n",
|
||
")\n",
|
||
"\n",
|
||
"# Replace OpenAIEmbeddings with AzureOpenAIEmbeddings if Azure OpenAI is your provider.\n",
|
||
"embeddings: OpenAIEmbeddings = OpenAIEmbeddings(\n",
|
||
" openai_api_key=openai_api_key, openai_api_version=openai_api_version, model=model\n",
|
||
")\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_profile_name=\"myHnswProfile\",\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": 20,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/plain": [
|
||
"['NjUwNGQ5ZDUtMGVmMy00OGM4LWIxMGYtY2Y2MDFmMTQ0MjE5',\n",
|
||
" 'NWFjN2YwY2UtOWQ4Yi00OTNhLTg2MGEtOWE0NGViZTVjOGRh',\n",
|
||
" 'N2Y2NWUyZjctMDBjZC00OGY4LWJlZDEtNTcxYjQ1MmI1NjYx']"
|
||
]
|
||
},
|
||
"execution_count": 20,
|
||
"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(\n",
|
||
" \"%Y-%m-%dT%H:%M:%S-00:00\"\n",
|
||
")\n",
|
||
"\n",
|
||
"vector_store.add_texts(\n",
|
||
" [\"Test 1\", \"Test 1\", \"Test 1\"],\n",
|
||
" [\n",
|
||
" {\n",
|
||
" \"title\": \"Title 1\",\n",
|
||
" \"source\": \"source1\",\n",
|
||
" \"random\": \"10290\",\n",
|
||
" \"last_update\": today,\n",
|
||
" },\n",
|
||
" {\n",
|
||
" \"title\": \"Title 1\",\n",
|
||
" \"source\": \"source1\",\n",
|
||
" \"random\": \"48392\",\n",
|
||
" \"last_update\": yesterday,\n",
|
||
" },\n",
|
||
" {\n",
|
||
" \"title\": \"Title 1\",\n",
|
||
" \"source\": \"source1\",\n",
|
||
" \"random\": \"32893\",\n",
|
||
" \"last_update\": one_month_ago,\n",
|
||
" },\n",
|
||
" ],\n",
|
||
")"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 21,
|
||
"metadata": {},
|
||
"outputs": [
|
||
{
|
||
"data": {
|
||
"text/plain": [
|
||
"[Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '32893', 'last_update': '2024-01-24T22:18:51-00:00'}),\n",
|
||
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '48392', 'last_update': '2024-02-22T22:18:51-00:00'}),\n",
|
||
" Document(page_content='Test 1', metadata={'title': 'Title 1', 'source': 'source1', 'random': '10290', 'last_update': '2024-02-23T22:18:51-00:00'})]"
|
||
]
|
||
},
|
||
"execution_count": 21,
|
||
"metadata": {},
|
||
"output_type": "execute_result"
|
||
}
|
||
],
|
||
"source": [
|
||
"res = vector_store.similarity_search(query=\"Test 1\", k=3, search_type=\"similarity\")\n",
|
||
"res"
|
||
]
|
||
}
|
||
],
|
||
"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.11.7"
|
||
},
|
||
"vscode": {
|
||
"interpreter": {
|
||
"hash": "645053d6307d413a1a75681b5ebb6449bb2babba4bcb0bf65a1ddc3dbefb108a"
|
||
}
|
||
}
|
||
},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 2
|
||
}
|