LangChain——Embedding 智谱AI

Embedding 嵌入

Embedding嵌入创建一段文本的矢量表示。这很有用,因为这意味着我们可以考虑向量空间中的文本,并执行语义搜索之类的操作,在其中查找向量空间中最相似的文本片段。

LangChain 中的基类 Embeddings 提供了两种方法:一种用于嵌入文档,另一种用于嵌入查询。前者 embed_documents 采用多个文本作为输入,而后者 embed_query 采用单个文本。

embed_documents

embed-documents将文本嵌入为embeddings(向量)。

python 复制代码
embeddings = embeddings_model.embed_documents(
    [
        "Hi there!",
        "Oh, hello!",
        "What's your name?",
        "My friends call me World",
        "Hello World!"
    ]
)
len(embeddings), len(embeddings[0])

embed_query

embed_query其实和embed-documents差不多,区别在于embed-query嵌入单段文本,而embed-documents嵌入的是一个文本列表。

python 复制代码
embedded_query = embeddings_model.embed_query("What was the name mentioned in the conversation?")
embedded_query[:5]

官方教程使用的openai的api作为示例,需要付费才能使用,因此我们选择使用国产的智谱ai开源的嵌入模型来进行实验。

首先我们需要获取到智谱AI的api-key,前往 https://bigmodel.cn/)https://bigmodel.cn/注册智普 AI 并生成 API 密钥。完成此操作后,设置 ZHIPUAI_API_KEY 环境变量即可。

然后我们只需要导入ZhipuAIEmbeddings,并且声名所使用的的模型即可。

python3 复制代码
from langchain_community.embeddings import ZhipuAIEmbeddings

embeddings = ZhipuAIEmbeddings(
    model="embedding-3",
)

embed_query嵌入单个文本

python3 复制代码
text = "LangChain is the framework for building context-aware reasoning applications"
single_vector = embeddings_model.embed_query(text)
len(single_vector)

2048

eimbed_documents嵌入多个文本

python3 复制代码
text2 = (
    "LangGraph is a library for building stateful, multi-actor applications with LLMs"
)
two_vectors = embeddings_model.embed_documents([text, text2])
print(len(two_vectors), len(two_vectors[0]))

2 2028
相关推荐
undsky_1 小时前
【n8n教程】:Luxon日期时间处理,打造智能时间自动化工作流
人工智能·ai·aigc·ai编程
Surmon1 小时前
基于 Cloudflare 生态的 AI Agent 实现
前端·人工智能·架构
冷小鱼7 小时前
pgvector 向量数据库完全指南:PostgreSQL 生态的 AI 增强
数据库·人工智能·postgresql
陈天伟教授7 小时前
人工智能应用- 天文学家的助手:08. 星系定位与分类
前端·javascript·数据库·人工智能·机器学习
啵啵鱼爱吃小猫咪7 小时前
机械臂阻抗控制github项目-mujoco仿真
开发语言·人工智能·python·机器人
放下华子我只抽RuiKe57 小时前
算法的试金石:模型训练、评估与调优的艺术
人工智能·深度学习·算法·机器学习·自然语言处理·数据挖掘·线性回归
songyuc7 小时前
【PyTorch】感觉`CrossEntropyLoss`和`BCELoss`很类似,为什么它们接收labels的shape常常不一样呢?
人工智能·pytorch·python
renhongxia18 小时前
如何对海洋系统进行知识图谱构建?
人工智能·学习·语言模型·自然语言处理·自动化·知识图谱
会一点点设计8 小时前
2026年设计趋势:当AI遇见人性,不完美成为新美学
人工智能