分類目錄:《大模型從入門到應(yīng)用》總目錄
LangChain系列文章:
- 基礎(chǔ)知識
- 快速入門
- 安裝與環(huán)境配置
- 鏈(Chains)、代理(Agent:)和記憶(Memory)
- 快速開發(fā)聊天模型
- 模型(Models)
- 基礎(chǔ)知識
- 大型語言模型(LLMs)
- 基礎(chǔ)知識
- LLM的異步API、自定義LLM包裝器、虛假LLM和人類輸入LLM(Human Input LLM)
- 緩存LLM的調(diào)用結(jié)果
- 加載與保存LLM類、流式傳輸LLM與Chat Model響應(yīng)和跟蹤tokens使用情況
- 聊天模型(Chat Models)
- 基礎(chǔ)知識
- 使用少量示例和響應(yīng)流式傳輸
- 文本嵌入模型
- Aleph Alpha、Amazon Bedrock、Azure OpenAI、Cohere等
- Embaas、Fake Embeddings、Google Vertex AI PaLM等
- 提示(Prompts)
- 基礎(chǔ)知識
- 提示模板
- 基礎(chǔ)知識
- 連接到特征存儲
- 創(chuàng)建自定義提示模板和含有Few-Shot示例的提示模板
- 部分填充的提示模板和提示合成
- 序列化提示信息
- 示例選擇器(Example Selectors)
- 輸出解析器(Output Parsers)
- 記憶(Memory)
- 基礎(chǔ)知識
- 記憶的類型
- 會話緩存記憶、會話緩存窗口記憶和實(shí)體記憶
- 對話知識圖譜記憶、對話摘要記憶和會話摘要緩沖記憶
- 對話令牌緩沖存儲器和基于向量存儲的記憶
- 將記憶添加到LangChain組件中
- 自定義對話記憶與自定義記憶類
- 聊天消息記錄
- 記憶的存儲與應(yīng)用
- 索引(Indexes)
- 基礎(chǔ)知識
- 文檔加載器(Document Loaders)
- 文本分割器(Text Splitters)
- 向量存儲器(Vectorstores)
- 檢索器(Retrievers)
- 鏈(Chains)
- 基礎(chǔ)知識
- 通用功能
- 自定義Chain和Chain的異步API
- LLMChain和RouterChain
- SequentialChain和TransformationChain
- 鏈的保存(序列化)與加載(反序列化)
- 鏈與索引
- 文檔分析和基于文檔的聊天
- 問答的基礎(chǔ)知識
- 圖問答(Graph QA)和帶來源的問答(Q&A with Sources)
- 檢索式問答
- 文本摘要(Summarization)、HyDE和向量數(shù)據(jù)庫的文本生成
- 代理(Agents)
- 基礎(chǔ)知識
- 代理類型
- 自定義代理(Custom Agent)
- 自定義MRKL代理
- 帶有ChatModel的LLM聊天自定義代理和自定義多操作代理(Custom MultiAction Agent)
- 工具
- 基礎(chǔ)知識
- 自定義工具(Custom Tools)
- 多輸入工具和工具輸入模式
- 人工確認(rèn)工具驗(yàn)證和Tools作為OpenAI函數(shù)
- 工具包(Toolkit)
- 代理執(zhí)行器(Agent Executor)
- 結(jié)合使用Agent和VectorStore
- 使用Agents的異步API和創(chuàng)建ChatGPT克隆
- 處理解析錯誤、訪問中間步驟和限制最大迭代次數(shù)
- 為代理程序設(shè)置超時時間和限制最大迭代次數(shù)和為代理程序和其工具添加共享內(nèi)存
- 計劃與執(zhí)行
- 回調(diào)函數(shù)(Callbacks)
本文將介紹如何在LangChain中使用Embedding類。Embedding類是一種與嵌入交互的類。有很多嵌入提供商,如:OpenAI、Cohere、Hugging Face等,這個類旨在為所有這些提供一個標(biāo)準(zhǔn)接口。
嵌入創(chuàng)建文本的向量表示會很有用,因?yàn)檫@意味著我們可以在向量空間中表示文本,并執(zhí)行類似語義搜索這樣的操作。LangChain中的基本Embedding類公開兩種方法:
-
embed_documents
:適用于多個文檔 -
embed_query
:適用于單個文檔
將這兩種方法作為兩種不同的方法的另一個原因是一些嵌入提供商對于需要搜索的文檔和查詢(搜索查詢本身)具有不同的嵌入方法,下面是文本嵌入的集成示例:
Embaas
embaas
是一種全面托管的NLP API服務(wù),提供諸如嵌入生成、文檔文本提取、文檔轉(zhuǎn)換為嵌入等功能。我們可以選擇各種預(yù)訓(xùn)練模型。下面展示的是如何使用embaas的嵌入API為給定的文本生成嵌入:
# Set API key
embaas_api_key = "YOUR_API_KEY"
# or set environment variable
os.environ["EMBAAS_API_KEY"] = "YOUR_API_KEY"
from langchain.embeddings import EmbaasEmbeddings
embeddings = EmbaasEmbeddings()
# Create embeddings for a single document
doc_text = "This is a test document."
doc_text_embedding = embeddings.embed_query(doc_text)
# Print created embedding
print(doc_text_embedding)
# Create embeddings for multiple documents
doc_texts = ["This is a test document.", "This is another test document."]
doc_texts_embeddings = embeddings.embed_documents(doc_texts)
# Print created embeddings
for i, doc_text_embedding in enumerate(doc_texts_embeddings):
print(f"Embedding for document {i + 1}: {doc_text_embedding}")
# Using a different model and/or custom instruction
embeddings = EmbaasEmbeddings(model="instructor-large", instruction="Represent the Wikipedia document for retrieval")
Fake Embeddings
LangChain還提供了偽造嵌入(Fake Embeddings)類,我們可以使用它來測試流程:
from langchain.embeddings import FakeEmbeddings
embeddings = FakeEmbeddings(size=1352)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
Google Vertex AI PaLM
Google Vertex AI PaLM是與Google PaLM集成是分開的。Google選擇通過GCP提供PaLM的企業(yè)版,它支持通過GCP提供的模型。Vertex AI上的PaLM API是預(yù)覽版本,受GCP特定服務(wù)條款的預(yù)GA產(chǎn)品條款的約束。GA產(chǎn)品和功能具有有限的支持,并且對GA版本的產(chǎn)品和功能的更改可能與其他GA版本不兼容。有關(guān)更多信息,我們可以參閱發(fā)布階段描述。另外,使用Vertex AI上的PaLM API即表示同意生成式AI預(yù)覽版本的條款和條件(預(yù)覽版條款)。對于Vertex AI上的PaLM API,我們可以根據(jù)“云數(shù)據(jù)處理附加協(xié)議”中概述的適用限制和義務(wù),在合同(如預(yù)覽版條款中所定義)中處理個人數(shù)據(jù)。要使用Vertex AI PaLM,我們必須安裝google-cloud-aiplatform Python包,并且配置了我們的環(huán)境的憑據(jù)并將服務(wù)帳號JSON文件的路徑存儲為GOOGLE_APPLICATION_CREDENTIALS
環(huán)境變量。下面的代碼庫使用了google.auth
庫,該庫首先查找上述應(yīng)用憑據(jù)變量,然后查找系統(tǒng)級身份驗(yàn)證:
#!pip install google-cloud-aiplatform
from langchain.embeddings import VertexAIEmbeddings
embeddings = VertexAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
Hugging Face Hub
我們加載Hugging Face Embedding類:
from langchain.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings(model_name="bert-base-uncased")
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
HuggingFace Instruct
我們加載HuggingFace Instruct Embeddings類:
from langchain.embeddings import HuggingFaceInstructEmbeddings
embeddings = HuggingFaceInstructEmbeddings(
query_instruction="Represent the query for retrieval: "
)
load INSTRUCTOR_Transformer
max_seq_length 512
text = "This is a test document."
query_result = embeddings.embed_query(text)
Jina
我們加載Jina Embedding類:
from langchain.embeddings import JinaEmbeddings
embeddings = JinaEmbeddings(jina_auth_token=jina_auth_token, model_name="ViT-B-32::openai")
text = "這是一個測試文檔。"
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
Llama-cpp
這個示例介紹了如何在LangChain中使用Llama-cpp embeddings:
!pip install llama-cpp-python
from langchain.embeddings import LlamaCppEmbeddings
llama = LlamaCppEmbeddings(model_path="/path/to/model/ggml-model-q4_0.bin")
text = "這是一個測試文檔。"
query_result = llama.embed_query(text)
doc_result = llama.embed_documents([text])
MiniMax
MiniMax提供了一個嵌入服務(wù)。以下示例演示如何使用 LangChain 與 MiniMax 推理進(jìn)行文本嵌入交互:
import os
os.environ["MINIMAX_GROUP_ID"] = "MINIMAX_GROUP_ID"
os.environ["MINIMAX_API_KEY"] = "MINIMAX_API_KEY"
from langchain.embeddings import MiniMaxEmbeddings
embeddings = MiniMaxEmbeddings()
query_text = "這是一個測試查詢。"
query_result = embeddings.embed_query(query_text)
document_text = "這是一個測試文檔。"
document_result = embeddings.embed_documents([document_text])
import numpy as np
query_numpy = np.array(query_result)
document_numpy = np.array(document_result[0])
similarity = np.dot(query_numpy, document_numpy) / (np.linalg.norm(query_numpy) * np.linalg.norm(document_numpy))
print(f"文檔與查詢之間的余弦相似度:{similarity}")
輸出:
文檔與查詢之間的余弦相似度:0.1573236279277012
ModelScope
我們加載 ModelScope 嵌入類:
from langchain.embeddings import ModelScopeEmbeddings
model_id = "damo/nlp_corom_sentence-embedding_english-base"
embeddings = ModelScopeEmbeddings(model_id=model_id)
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_results = embeddings.embed_documents(["foo"])
MosaicML
MosaicML提供了一個托管的推理服務(wù)。我們可以使用各種開源模型,也可以部署我們自己的模型。以下示例演示如何使用LangChain與MosaicML推理服務(wù)進(jìn)行文本嵌入交互:
# 注冊賬號:https://forms.mosaicml.com/demo?utm_source=langchain
from getpass import getpass
MOSAICML_API_TOKEN = getpass()
import os
os.environ["MOSAICML_API_TOKEN"] = MOSAICML_API_TOKEN
from langchain.embeddings import MosaicMLInstructorEmbeddings
embeddings = MosaicMLInstructorEmbeddings(
query_instruction="Represent the query for retrieval: "
)
query_text = "This is a test query."
query_result = embeddings.embed_query(query_text)
document_text = "This is a test document."
document_result = embeddings.embed_documents([document_text])
import numpy as np
query_numpy = np.array(query_result)
document_numpy = np.array(document_result[0])
similarity = np.dot(query_numpy, document_numpy) / (np.linalg.norm(query_numpy)*np.linalg.norm(document_numpy))
print(f"Cosine similarity between document and query: {similarity}")
OpenAI
我們加載OpenAI嵌入類:
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
讓我們加載第一代模型(例如:text-search-ada-doc-001/text-search-ada-query-001)的 OpenAI 嵌入類。需要注意的是其實(shí)這些模型并不推薦使用。
from langchain.embeddings.openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
# 如果您在明確的代理后面,可以使用 OPENAI_PROXY 環(huán)境變量進(jìn)行傳遞
os.environ["OPENAI_PROXY"] = "http://proxy.yourcompany.com:8080"
SageMaker Endpoint
我們加載SageMaker Endpoint Embeddings類。如果我們在SageMaker上托管自己的Hugging Face模型,則可以使用該類。需要注意的是,為了處理批量請求,我們需要調(diào)整自定義inference.py
腳本中的predict_fn()
函數(shù)中的返回行,即從return {"vectors": sentence_embeddings[0].tolist()}
到return {"vectors": sentence_embeddings.tolist()}
:
!pip3 install langchain boto3
from typing import Dict, List
from langchain.embeddings import SagemakerEndpointEmbeddings
from langchain.llms.sagemaker_endpoint import ContentHandlerBase
import json
class ContentHandler(ContentHandlerBase):
content_type = "application/json"
accepts = "application/json"
def transform_input(self, inputs: list[str], model_kwargs: Dict) -> bytes:
input_str = json.dumps({"inputs": inputs, **model_kwargs})
return input_str.encode('utf-8')
def transform_output(self, output: bytes) -> List[List[float]]:
response_json = json.loads(output.read().decode("utf-8"))
return response_json["vectors"]
content_handler = ContentHandler()
embeddings = SagemakerEndpointEmbeddings(
# endpoint_name="endpoint-name",
# credentials_profile_name="credentials-profile-name",
endpoint_name="huggingface-pytorch-inference-2023-03-21-16-14-03-834",
region_name="us-east-1",
content_handler=content_handler
)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
SelfHostedEmbeddings
我們加載SelfHostedEmbeddings
、SelfHostedHuggingFaceEmbeddings
和 SelfHostedHuggingFaceInstructEmbeddings
類:
from langchain.embeddings import (
SelfHostedEmbeddings,
SelfHostedHuggingFaceEmbeddings,
SelfHostedHuggingFaceInstructEmbeddings,
)
import runhouse as rh
# 對于 GCP、Azure 或 Lambda 上的按需 A100
gpu = rh.cluster(name="rh-a10x", instance_type="A100:1", use_spot=False)
# 對于 AWS 上的按需 A10G(AWS 上沒有單個 A100)
# gpu = rh.cluster(name='rh-a10x', instance_type='g5.2xlarge', provider='aws')
# 對于現(xiàn)有的集群
# gpu = rh.cluster(ips=['<集群的 IP>'],
# ssh_creds={'ssh_user': '...', 'ssh_private_key':'<私鑰路徑>'},
# name='my-cluster')
embeddings = SelfHostedHuggingFaceEmbeddings(hardware=gpu)
text = "This is a test document."
query_result = embeddings.embed_query(text)
類似地,對于SelfHostedHuggingFaceInstructEmbeddings
:
embeddings = SelfHostedHuggingFaceInstructEmbeddings(hardware=gpu)
現(xiàn)在我們使用自定義加載函數(shù)加載一個嵌入模型:
def get_pipeline():
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
pipeline,
) # Must be inside the function in notebooks
model_id = "facebook/bart-base"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
return pipeline("feature-extraction", model=model, tokenizer=tokenizer)
def inference_fn(pipeline, prompt):
# Return last hidden state of the model
if isinstance(prompt, list):
return [emb[0][-1] for emb in pipeline(prompt)]
return pipeline(prompt)[0][-1]
embeddings = SelfHostedEmbeddings(
model_load_fn=get_pipeline,
hardware=gpu,
model_reqs=["./", "torch", "transformers"],
inference_fn=inference_fn,
)
query_result = embeddings.embed_query(text)
Sentence Transformers
使用HuggingFaceEmbeddings集成來調(diào)用Sentence Transformers嵌入。LangChain還為熟悉直接使用SentenceTransformer包的用戶添加了SentenceTransformerEmbeddings
的別名。SentenceTransformers是一個可以生成文本和圖像嵌入的Python包,源自于SentenceBERT:
!pip install sentence_transformers > /dev/null
from langchain.embeddings import HuggingFaceEmbeddings, SentenceTransformerEmbeddings
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
# 等同于 SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text, "This is not a test document."])
TensorFlow Hub
TensorFlow Hub是一個包含訓(xùn)練好的機(jī)器學(xué)習(xí)模型的倉庫,可隨時進(jìn)行微調(diào)并在任何地方部署。TensorFlow Hub 讓我們可以在一個地方搜索和發(fā)現(xiàn)數(shù)百個已經(jīng)訓(xùn)練好、可直接部署的機(jī)器學(xué)習(xí)模型。文章來源:http://www.zghlxwxcb.cn/news/detail-687515.html
from langchain.embeddings import TensorflowHubEmbeddings
embeddings = TensorflowHubEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_results = embeddings.embed_documents(["foo"])
參考文獻(xiàn):
[1] LangChain ????? 中文網(wǎng),跟著LangChain一起學(xué)LLM/GPT開發(fā):https://www.langchain.com.cn/
[2] LangChain中文網(wǎng) - LangChain 是一個用于開發(fā)由語言模型驅(qū)動的應(yīng)用程序的框架:http://www.cnlangchain.com/文章來源地址http://www.zghlxwxcb.cn/news/detail-687515.html
到了這里,關(guān)于自然語言處理從入門到應(yīng)用——LangChain:模型(Models)-[文本嵌入模型:Embaas、Fake Embeddings、Google Vertex AI PaLM等]的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!