{ "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" ] }, { "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.0b6\n", "!pip install azure-identity" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Import required libraries" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "import openai\n", "import os\n", "from langchain.embeddings.openai 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": 8, "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": 9, "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": 10, "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": 15, "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)" ] }, { "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": null, "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\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": null, "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\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": 16, "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": 17, "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": 18, "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": 19, "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": 20, "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": 21, "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": 23, "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=\"hybrid\")\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 }