合集: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的使用方法。欢迎关注,防止迷路。

相关推荐
梦在远山后3 小时前
从需求到架构:我的企业研发 Agent 整体设计
langchain·agent
听到微笑5 小时前
Elasticsearch 如何存储与检索海量向量
数据库·elasticsearch
知福致福8 小时前
【技术复盘】Git 分支污染与提交污染事故排查与解法
大数据·git·elasticsearch
敲代码的嘎仔11 小时前
互动问答系统实战:两级评论模型、ES 搜索集成、Caffeine 多级缓存全记录
java·开发语言·数据库·elasticsearch·缓存·mybatis·高并发
Warson_L21 小时前
Python的TypedDict
python·langchain·llm
OKkankan1 天前
LangChain能力详解!:从工具调用到 LangSmith——让聊天模型具备实时交互能力!
开发语言·python·langchain
彧azz1 天前
Git 入门实操实例:从安装到远程仓库全流程
大数据·笔记·git·学习·elasticsearch
醉颜凉1 天前
Canal 与 Elasticsearch 实时同步:增量索引更新、删除处理与全量重建方案
elasticsearch·canal·数据同步·增量更新·全量重建
ctlover1 天前
LangChain 概述
python·langchain
玉宇夕落1 天前
llm模块二 结构化输出 LangChain 结构化输出完全指南:从 JSON 解析到 withStructuredOutput
langchain·llm