跳至主要內容

TogetherEmbeddings

這將幫助您開始使用 LangChain 的 Together 嵌入模型。有關 TogetherEmbeddings 功能和配置選項的詳細文檔,請參閱API 參考文檔

概觀

整合細節

供應商套件
Togetherlangchain-together

設定

要存取 Together 嵌入模型,您需要建立 Together 帳戶、取得 API 金鑰,並安裝 langchain-together 整合套件。

憑證

前往 https://api.together.xyz/ 註冊 Together 並產生 API 金鑰。完成後,設定 TOGETHER_API_KEY 環境變數

import getpass
import os

if not os.getenv("TOGETHER_API_KEY"):
os.environ["TOGETHER_API_KEY"] = getpass.getpass("Enter your Together API key: ")

如果您想要自動追蹤您的模型呼叫,您也可以設定您的 LangSmith API 金鑰,方法是取消註解下面的內容

# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

安裝

LangChain Together 整合位於 langchain-together 套件中

%pip install -qU langchain-together

[notice] A new release of pip is available: 24.0 -> 24.2
[notice] To update, run: python -m pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.

實例化

現在我們可以實例化我們的模型物件並產生聊天完成

from langchain_together import TogetherEmbeddings

embeddings = TogetherEmbeddings(
model="togethercomputer/m2-bert-80M-8k-retrieval",
)
API 參考:TogetherEmbeddings

索引和檢索

嵌入模型通常用於檢索增強生成 (RAG) 流程中,既作為索引資料的一部分,也作為稍後檢索資料的一部分。有關更詳細的說明,請參閱我們的 RAG 教學課程

下面,了解如何使用我們上面初始化的 embeddings 物件來索引和檢索資料。在本範例中,我們將在 InMemoryVectorStore 中索引和檢索範例文件。

# Create a vector store with a sample text
from langchain_core.vectorstores import InMemoryVectorStore

text = "LangChain is the framework for building context-aware reasoning applications"

vectorstore = InMemoryVectorStore.from_texts(
[text],
embedding=embeddings,
)

# Use the vectorstore as a retriever
retriever = vectorstore.as_retriever()

# Retrieve the most similar text
retrieved_documents = retriever.invoke("What is LangChain?")

# show the retrieved document's content
retrieved_documents[0].page_content
API 參考:InMemoryVectorStore
'LangChain is the framework for building context-aware reasoning applications'

直接使用

在幕後,向量儲存庫和檢索器實作正在呼叫 embeddings.embed_documents(...)embeddings.embed_query(...),以便為 from_texts 和檢索 invoke 操作中使用的文字建立嵌入。

您可以直接呼叫這些方法來取得嵌入,以便用於您自己的使用案例。

嵌入單個文字

您可以使用 embed_query 嵌入單個文字或文件

single_vector = embeddings.embed_query(text)
print(str(single_vector)[:100]) # Show the first 100 characters of the vector
[0.3812227, -0.052848946, -0.10564975, 0.03480297, 0.2878488, 0.0084609175, 0.11605915, 0.05303011,

嵌入多個文字

您可以使用 embed_documents 嵌入多個文字

text2 = (
"LangGraph is a library for building stateful, multi-actor applications with LLMs"
)
two_vectors = embeddings.embed_documents([text, text2])
for vector in two_vectors:
print(str(vector)[:100]) # Show the first 100 characters of the vector
[0.3812227, -0.052848946, -0.10564975, 0.03480297, 0.2878488, 0.0084609175, 0.11605915, 0.05303011, 
[0.066308185, -0.032866564, 0.115751594, 0.19082588, 0.14017, -0.26976448, -0.056340694, -0.26923394

API 參考

有關 TogetherEmbeddings 功能和配置選項的詳細文檔,請參閱API 參考文檔


此頁面是否有幫助?