Azure AI Search(前称为Azure Cognitive Search)是微软提供的云搜索服务,开发者可以利用其基础设施、API和工具实现对向量、关键字及混合查询的信息检索。本文将带您了解如何使用Azure AI Search Retriever模块从非结构化查询中检索文档,并基于2023年11月1日稳定版本的Azure AI Search REST API进行向量索引和查询。
技术背景介绍
Azure AI Search 是微软云服务的一部分,它为大规模信息检索提供了强大的支持。为了对非结构化数据进行高效的查询和获取结果,Azure AI Search Retriever模块因应而生,继承自BaseRetriever类。它旨在替代即将被弃用的Azure Cognitive Search Retriever版本。
核心原理解析
Azure AI Search Retriever可以处理复杂的查询并返回相关文档。它依赖于Azure AI Search提供的强大向量索引能力,以便快速检索相关内容。其工作流程通常包括创建索引、上传和分割文档以生成向量,然后根据查询检索结果。
代码实现演示
首先,确保您已拥有Azure AI Search服务,并知道您的服务名称、索引名称和API密钥。以下是使用Azure AI Search Retriever执行信息检索的完整代码:
import os
from langchain_community.retrievers import AzureAISearchRetriever
from langchain_community.vectorstores import AzureSearch
from langchain_openai import AzureOpenAIEmbeddings
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter
# 配置环境变量
os.environ["AZURE_AI_SEARCH_SERVICE_NAME"] = "<YOUR_SEARCH_SERVICE_NAME>"
os.environ["AZURE_AI_SEARCH_INDEX_NAME"] = "langchain-vector-demo"
os.environ["AZURE_AI_SEARCH_API_KEY"] = "<YOUR_SEARCH_SERVICE_ADMIN_API_KEY>"
# 配置Azure OpenAI参数
azure_endpoint: str = "<YOUR_AZURE_OPENAI_ENDPOINT>"
azure_openai_api_key: str = "<YOUR_AZURE_OPENAI_API_KEY>"
azure_deployment: str = "text-embedding-ada-002"
# 初始化嵌入模型
embeddings = AzureOpenAIEmbeddings(
model=azure_deployment,
azure_endpoint=azure_endpoint,
openai_api_key=azure_openai_api_key,
)
# 初始化向量存储
vector_store: AzureSearch = AzureSearch(
embedding_function=embeddings.embed_query,
azure_search_endpoint=os.getenv("AZURE_AI_SEARCH_SERVICE_NAME"),
azure_search_key=os.getenv("AZURE_AI_SEARCH_API_KEY"),
index_name="langchain-vector-demo",
)
# 加载数据并创建向量存储
loader = TextLoader("state_of_the_union.txt", encoding="utf-8")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=400, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
vector_store.add_documents(documents=docs)
# 创建检索器
retriever = AzureAISearchRetriever(
content_key="content", top_k=1, index_name="langchain-vector-demo"
)
# 执行查询
results = retriever.invoke("does the president have a plan for covid-19?")
print(results)
应用场景分析
Azure AI Search Retriever适用于各种需要快速从大量非结构化数据中提取信息的场合,例如:企业内部文件检索、公共信息查询、以及科研数据处理等。其优势在于处理复杂查询的能力和响应速度。
实践建议
- 使用向量索引优化查询速度: 向量化的数据能够大幅提升检索效率。
- 安全管理API密钥: 确保API密钥的安全,建议通过环境变量管理。
- 充分利用Azure AI Search的配置选项: 根据具体需求调整配置以达到最佳效果。
如果遇到问题欢迎在评论区交流。
—END—