一键导入
langchain-embeddings
Guide to using embedding model integrations in LangChain including OpenAI, Azure, and local embeddings
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Guide to using embedding model integrations in LangChain including OpenAI, Azure, and local embeddings
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Using the Deep Agents CLI - terminal interface, persistent memory with AGENTS.md, project conventions, skills directories, and CLI commands.
Understanding Deep Agents framework - what they are, how to create them with createDeepAgent, and the agent harness architecture with built-in middleware for planning, filesystems, and subagents.
Creating and using custom skills with progressive disclosure, SKILL.md format, and the Agent Skills protocol in Deep Agents.
Using the Deep Agents CLI - terminal interface, persistent memory with AGENTS.md, project conventions, skills directories, and CLI commands.
Using FilesystemMiddleware with virtual filesystems, backends (State, Store, Filesystem, Composite), and context management for Deep Agents.
Using FilesystemMiddleware with virtual filesystems, backends (State, Store, Filesystem, Composite), and context management for Deep Agents.
| name | langchain-embeddings |
| description | Guide to using embedding model integrations in LangChain including OpenAI, Azure, and local embeddings |
| language | python |
Embedding models convert text into numerical vector representations that capture semantic meaning. These vectors enable semantic search, similarity comparison, and are essential for building RAG (Retrieval-Augmented Generation) systems with vector databases.
| Provider | Best For | Model Examples | Dimensions | Package | Key Features |
|---|---|---|---|---|---|
| OpenAI | General purpose, high quality | text-embedding-3-small, text-embedding-3-large, text-embedding-ada-002 | 1536, 3072 | langchain-openai | High quality, reliable, flexible dimensions |
| Azure OpenAI | Enterprise, compliance | text-embedding-ada-002 (Azure) | 1536 | langchain-openai | Enterprise SLAs, data residency |
| Cohere | Multilingual, search optimization | embed-english-v3.0, embed-multilingual-v3.0 | 1024 | langchain-cohere | Search/clustering modes, multilingual |
| HuggingFace | Open source, customizable | all-MiniLM-L6-v2, BGE models | Varies | langchain-huggingface | Free, local inference, many models |
| GCP integration | textembedding-gecko | 768 | langchain-google-genai | GCP ecosystem, multimodal | |
| Ollama | Local, privacy | llama2, mistral, nomic-embed-text | Varies | langchain-ollama | Fully local, no API costs, privacy |
Choose OpenAI if:
Choose Azure OpenAI if:
Choose Cohere if:
Choose HuggingFace if:
Choose Ollama if:
from langchain_openai import OpenAIEmbeddings
import os
# Basic initialization
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
api_key=os.getenv("OPENAI_API_KEY"), # Optional if set in env
)
# Embed a single query
query_embedding = embeddings.embed_query(
"What is the capital of France?"
)
print(f"Vector dimensions: {len(query_embedding)}")
print(f"First few values: {query_embedding[:5]}")
# Embed multiple documents
documents = [
"Paris is the capital of France.",
"London is the capital of England.",
"Berlin is the capital of Germany.",
]
doc_embeddings = embeddings.embed_documents(documents)
print(f"Embedded {len(doc_embeddings)} documents")
# Using newer models with custom dimensions
small_embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
dimensions=512, # Reduce from default 1536 for efficiency
)
from langchain_openai import AzureOpenAIEmbeddings
import os
embeddings = AzureOpenAIEmbeddings(
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
azure_deployment="text-embedding-ada-002",
api_version="2024-02-01",
)
embedding = embeddings.embed_query("Hello world")
print(f"Embedding length: {len(embedding)}")
from langchain_huggingface import HuggingFaceEmbeddings
# Run embeddings locally with sentence-transformers
embeddings = HuggingFaceEmbeddings(
model_name="all-MiniLM-L6-v2", # Default model
model_kwargs={"device": "cpu"}, # or "cuda" for GPU
encode_kwargs={"normalize_embeddings": True},
)
embedding = embeddings.embed_query("This runs locally!")
print(f"Embedding dimensions: {len(embedding)}")
# Use a different model
embeddings = HuggingFaceEmbeddings(
model_name="BAAI/bge-small-en-v1.5",
)
from langchain_ollama import OllamaEmbeddings
# Requires Ollama running locally: ollama pull nomic-embed-text
embeddings = OllamaEmbeddings(
model="nomic-embed-text",
base_url="http://localhost:11434", # Default Ollama URL
)
embedding = embeddings.embed_query("Fully local embeddings")
from langchain_cohere import CohereEmbeddings
import os
embeddings = CohereEmbeddings(
cohere_api_key=os.getenv("COHERE_API_KEY"),
model="embed-english-v3.0",
)
query_embedding = embeddings.embed_query("Search query")
doc_embeddings = embeddings.embed_documents(["doc1", "doc2"])
from langchain_openai import OpenAIEmbeddings
import numpy as np
embeddings = OpenAIEmbeddings()
# Embed query and documents
query = "What is machine learning?"
docs = [
"Machine learning is a branch of AI",
"Paris is the capital of France",
"Neural networks are used in deep learning",
]
query_vec = embeddings.embed_query(query)
doc_vecs = embeddings.embed_documents(docs)
# Compute cosine similarity
def cosine_similarity(vec_a, vec_b):
"""Calculate cosine similarity between two vectors."""
return np.dot(vec_a, vec_b) / (np.linalg.norm(vec_a) * np.linalg.norm(vec_b))
# Find most similar document
similarities = [cosine_similarity(query_vec, doc_vec) for doc_vec in doc_vecs]
print("Similarities:", similarities)
most_similar_idx = np.argmax(similarities)
print("Most similar doc:", docs[most_similar_idx])
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(
chunk_size=512, # Process in batches
)
# Efficiently embed large document sets
large_doc_set = [f"Document {i}: Some content here" for i in range(1000)]
doc_embeddings = embeddings.embed_documents(large_doc_set)
print(f"Embedded {len(doc_embeddings)} documents in batches")
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
embeddings = OpenAIEmbeddings()
texts = [
"LangChain is a framework for developing applications powered by LLMs",
"Vector stores enable semantic search capabilities",
"Embeddings convert text into numerical vectors",
]
# Create vector store with embeddings
vectorstore = FAISS.from_texts(texts, embeddings)
# Perform similarity search
query = "What is LangChain?"
docs = vectorstore.similarity_search(query, k=2)
for doc in docs:
print(doc.page_content)
✅ Initialize embedding models
✅ Embed text content
embed_query()embed_documents()✅ Use embeddings with vector stores
✅ Choose appropriate models
✅ Optimize for use case
❌ Modify embedding dimensions arbitrarily
❌ Mix embeddings from different models
❌ Exceed API rate limits
❌ Generate embeddings without proper authentication
# ❌ BAD: Using different models
embeddings1 = OpenAIEmbeddings(model="text-embedding-3-small")
embeddings2 = OpenAIEmbeddings(model="text-embedding-ada-002")
query_vec = embeddings1.embed_query("query")
doc_vec = embeddings2.embed_query("document")
# Similarity comparison will be meaningless!
# ✅ GOOD: Use same model for everything
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
query_vec = embeddings.embed_query("query")
doc_vec = embeddings.embed_query("document")
# Now similarity makes sense
Fix: Always use the same embedding model for all texts you want to compare.
# ❌ OLD: Using deprecated community imports
from langchain.embeddings import OpenAIEmbeddings # Deprecated!
# ✅ NEW: Use provider-specific packages
from langchain_openai import OpenAIEmbeddings
from langchain_cohere import CohereEmbeddings
from langchain_huggingface import HuggingFaceEmbeddings
Fix: Use provider-specific packages, not langchain-community.
# ❌ Text too long
embeddings = OpenAIEmbeddings()
very_long_text = "..." * 100000
embeddings.embed_query(very_long_text) # Will fail!
# ✅ Chunk long texts first
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=8000, # OpenAI limit is ~8191 tokens
chunk_overlap=200,
)
chunks = splitter.split_text(very_long_text)
chunk_embeddings = embeddings.embed_documents(chunks)
Fix: Split long texts into chunks before embedding. Most models have 8k token limits.
# ❌ First run may be slow (downloading model)
from langchain_huggingface import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-mpnet-base-v2"
)
# Downloads ~420MB on first run!
# ✅ Be aware and cache models
# Models are cached in ~/.cache/huggingface/
# Subsequent runs will be fast
Fix: First run downloads the model. Plan for network and disk space.
# ❌ INCOMPLETE: Missing required fields
embeddings = AzureOpenAIEmbeddings(
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
)
# ✅ COMPLETE: All required fields
embeddings = AzureOpenAIEmbeddings(
azure_endpoint="https://my-instance.openai.azure.com/",
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
azure_deployment="text-embedding-ada-002",
api_version="2024-02-01",
)
Fix: Azure requires endpoint, deployment name, and API version.
# ❌ Ollama not running
from langchain_ollama import OllamaEmbeddings
embeddings = OllamaEmbeddings(model="nomic-embed-text")
embeddings.embed_query("test") # Connection error!
# ✅ Ensure Ollama is running and model is pulled
# Terminal:
# ollama pull nomic-embed-text
# ollama serve
embeddings = OllamaEmbeddings(model="nomic-embed-text")
embeddings.embed_query("test") # Works!
Fix: Start Ollama service and pull the model first.
# ❌ Inefficient: One API call per document
embeddings = OpenAIEmbeddings()
for doc in large_doc_list:
emb = embeddings.embed_query(doc) # Slow!
# ✅ Efficient: Batch processing
embeddings = OpenAIEmbeddings(chunk_size=100)
all_embeddings = embeddings.embed_documents(large_doc_list) # Fast!
Fix: Use embed_documents() for batch processing instead of calling embed_query() in a loop.
# ❌ Vector store expecting 1536 dimensions, model produces 512
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
dimensions=512,
)
# Vector store initialized with different dimensions
vectorstore = FAISS.from_texts(
["text1"],
OpenAIEmbeddings(), # Uses default 1536 dimensions
)
# Adding with 512-dim embeddings will fail!
# ✅ Consistent dimensions
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
vectorstore = FAISS.from_texts(["text1"], embeddings)
Fix: Ensure all embeddings use consistent dimensions throughout your application.
# OpenAI
pip install langchain-openai
# Cohere
pip install langchain-cohere
# HuggingFace
pip install langchain-huggingface sentence-transformers
# Ollama
pip install langchain-ollama
# Google
pip install langchain-google-genai