合集:LangChain智能体开发(四)langchain-elasticsearch

大语言模型(LLM)的崛起让智能体(AI Agent)成为技术圈的热门话题。无论是自动化客服、个性化助手,还是复杂任务求解,智能体正逐步渗透到各个领域。而LangChain作为一款强大的LLM应用框架,凭借其模块化设计和丰富的工具链,成为开发者构建智能体的首选工具之一。

本文将带你从零开始,使用LangChain开发智能体,并分享代码和实现思路。

langchain-elasticsearch

安装

bash 复制代码
pip install -qU langchain_elasticsearch
curl -fsSL https://elastic.co/start-local | sh
# 创建一个弹性启动本地文件夹。要启动Elasticsearch和Kibana:
cd elastic-start-local
./start.sh
# Elasticsearch将在http://localhost:9200.弹性用户的密码和API密钥存储在elastic-start-local文件夹的.env文件中。

创建实例

预训练嵌入模型

使用API密钥实例化

python 复制代码
from langchain_elasticsearch import ElasticsearchEmbeddings

embeddings = ElasticsearchEmbeddings(
    model_id="your_model_id",
    es_url="http://localhost:9200",
    es_api_key="your-api-key"
)

使用用户名/密码进行实例化

python 复制代码
from langchain_elasticsearch import ElasticsearchEmbeddings

embeddings = ElasticsearchEmbeddings(
    model_id="your_model_id",
    es_url="http://localhost:9200",
    es_user="elastic",
    es_password="password"
)

还可以通过客户端参数传入预先存在的Elasticsearch连接来连接到现有的Elasticspect实例。

python 复制代码
from langchain_elasticsearch import ElasticsearchEmbeddings
from elasticsearch import Elasticsearch

client = Elasticsearch("http://localhost:9200")
embeddings = ElasticsearchEmbeddings(
    model_id="your_model_id",
    client=client
)
云嵌入模型

使用API密钥实例化

python 复制代码
from langchain_elasticsearch import ElasticsearchStore
from langchain_openai import OpenAIEmbeddings

store = ElasticsearchStore(
    index_name="langchain-demo",
    embedding=OpenAIEmbeddings(),
    es_url="http://localhost:9200",
    es_api_key="your-api-key"
)

使用用户名/密码进行实例化

python 复制代码
from langchain_elasticsearch import ElasticsearchStore
from langchain_openai import OpenAIEmbeddings

store = ElasticsearchStore(
    index_name="langchain-demo",
    embedding=OpenAIEmbeddings(),
    es_url="http://localhost:9200",
    es_user="elastic",
    es_password="password"
)

还可以通过客户端参数传入预先存在的Elasticsearch连接来连接到现有的Elasticspect实例。

python 复制代码
from langchain_elasticsearch.vectorstores import ElasticsearchStore
from langchain_openai import OpenAIEmbeddings
from elasticsearch import Elasticsearch

client = Elasticsearch("http://localhost:9200")

store = ElasticsearchStore(
    embedding=OpenAIEmbeddings(),
    index_name="langchain-demo",
    client=client
)

操作实例

Add Documents

python 复制代码
from langchain_core.documents import Document

document_1 = Document(page_content="foo", metadata={"baz": "bar"})
document_2 = Document(page_content="thud", metadata={"bar": "baz"})
document_3 = Document(page_content="i will be deleted :(")

documents = [document_1, document_2, document_3]
ids = ["1", "2", "3"]
vector_store.add_documents(documents=documents, ids=ids)

Delete Documents

python 复制代码
vector_store.delete(ids=["3"])
python 复制代码
results = vector_store.similarity_search(query="thud",k=1)
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
python 复制代码
results = vector_store.similarity_search(query="thud",k=1,filter=[{"term": {"metadata.bar.keyword": "baz"}}])
for doc in results:
    print(f"* {doc.page_content} [{doc.metadata}]")
python 复制代码
results = vector_store.similarity_search_with_score(query="qux",k=1)
for doc, score in results:
    print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")

异步

python 复制代码
from langchain_elasticsearch import AsyncElasticsearchStore

vector_store = AsyncElasticsearchStore(...)

# add documents
await vector_store.aadd_documents(documents=documents, ids=ids)

# delete documents
await vector_store.adelete(ids=["3"])

# search
results = vector_store.asimilarity_search(query="thud",k=1)

# search with score
results = await vector_store.asimilarity_search_with_score(query="qux",k=1)
for doc,score in results:
    print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")

高级特性:

ElasticsearchStore默认使用ApproxRetrievalStrategy,该策略使用HNSW算法执行近似最近邻搜索。这是最快、最节省内存的算法。

如果你想使用暴力/精确策略来搜索向量,你可以将ExactRetrievalStrategy传递给ElasticsearchStore构造函数。

使用 ExactRetrievalStrategy

python 复制代码
from langchain_elasticsearch.vectorstores import ElasticsearchStore
from langchain_openai import OpenAIEmbeddings

store = ElasticsearchStore(
    embedding=OpenAIEmbeddings(),
    index_name="langchain-demo",
    es_url="http://localhost:9200",
    strategy=ElasticsearchStore.ExactRetrievalStrategy()
)

这两种策略都要求在创建索引时知道要使用的相似性度量。默认值是余弦相似性,但也可以使用点积或欧几里德距离。

总结

现在我们掌握了怎么使用langfuse-elasticsearch。后面会继续更新langchain的使用方法。欢迎关注,防止迷路。

相关推荐
草莓熊Lotso1 小时前
【Linux网络加餐】手动部署:SSH 与 Web 服务实战 + 底层原理全解析
linux·运维·网络·人工智能·python·langchain·ssh
Elasticsearch1 小时前
生产环境向量搜索的一个设置:vectordb_document 模式如何自动调优 Elasticsearch
elasticsearch
【赫兹威客】浩哥2 小时前
基于SpringBoot+Vue3的舆情文本分析系统|Elasticsearch检索+情感分析+话题热度追踪 毕设项目
spring boot·elasticsearch·课程设计
Elasticsearch4 小时前
让大模型思考,让小模型执行:在 Elastic Workflows 中拆分 LLM 成本
elasticsearch
Elastic 中国社区官方博客14 小时前
ES95:面向 Elasticsearch 时间序列指标的自适应压缩
大数据·运维·elasticsearch·搜索引擎·架构·全文检索
编程令我快乐17 小时前
模型配置及使用ccSwich管理
大数据·elasticsearch·搜索引擎
65岁退休Coder18 小时前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
前端 贾公子1 天前
第08章:中间件(8)
langchain
睡觉时不困4421 天前
15.LangChain 1.0+ 第三篇:LangSmith——给 AI 应用装上监控台.发布清单
langchain