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
相关推荐
shengjk11 天前
NanoClaw 深度剖析:一个"AI 原生"架构的个人助手是如何运转的?
人工智能
西门老铁1 天前
🦞OpenClaw 让 MacMini 脱销了,而我拿出了6年陈的安卓机
人工智能
恋猫de小郭1 天前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
是一碗螺丝粉1 天前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain
是一碗螺丝粉1 天前
LangChain 核心组件深度解析:模型与提示词模板
前端·langchain·aigc
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
用户4815930195911 天前
揭秘GPT-4与LLaMA背后的加速黑科技:KV Cache、MQA、GQA、稀疏注意力与MoE全解析
人工智能
用户5191495848451 天前
Cisco SMA 暴露面检测工具 - 快速识别CVE-2025-20393风险
人工智能·aigc
碳基沙盒1 天前
AI工具的“超级外挂”:从零手把手教你搭建私人 MCP 服务器
人工智能