Relevant source files
The following files were used as context for generating this wiki page:
- mem0-ts/src/oss/src/utils/factory.ts
- mem0-ts/src/oss/src/embeddings/fastembed.ts
- mem0-ts/src/oss/src/embeddings/aws_bedrock.ts
- integrations/vercel-ai-sdk/src/provider-response-provider.ts
- mem0-ts/src/oss/src/memory/index.ts
- mem0-ts/src/oss/src/embeddings/vertexai.ts
- integrations/openclaw/providers.ts
- integrations/vercel-ai-sdk/src/mem0-provider-selector.ts
- mem0-ts/src/oss/src/embeddings/lmstudio.ts
- mem0-ts/src/oss/src/llms/aws_bedrock.ts
- mem0-ts/src/oss/src/embeddings/huggingface.ts
- mem0-ts/src/oss/src/embeddings/langchain.ts
- mem0/utils/factory.py
- mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts
- mem0-ts/src/oss/src/embeddings/base.ts
- integrations/openclaw/cli/oss-wizard.ts
- mem0-ts/src/oss/src/embeddings/google.ts
- mem0-ts/src/oss/src/embeddings/ollama.ts
- integrations/vercel-ai-sdk/src/mem0-generic-language-model.ts
- mem0-ts/src/oss/src/embeddings/openai.ts
- mem0-ts/src/oss/src/embeddings/azure.ts
- mem0-ts/src/oss/src/index.ts
- mem0-ts/src/oss/src/embeddings/together.ts
- integrations/vercel-ai-sdk/src/mem0-provider.ts
- mem0-ts/src/oss/src/vector_stores/qdrant.ts
- mem0-ts/src/oss/src/vector_stores/vertex_ai_vector_search.ts
- mem0-ts/src/oss/src/vector_stores/weaviate.ts
- mem0-ts/src/oss/src/llms/langchain.ts
- mem0-ts/src/oss/src/llms/vllm.ts
- mem0/embeddings/aws_bedrock.py
Overview
TypeScript embedding adapters in Mem0 provide the foundational vector generation bridge across diverse AI providers, handling single and batch text transformations for memory storage and retrieval. Grounded in a core Embedder interface, these adapters resolve dynamically via the EmbedderFactory to support OpenAI, Azure OpenAI, Together AI, Hugging Face, LM Studio, AWS Bedrock, Google GenAI, Vertex AI, Ollama, FastEmbed, and LangChain instances. They address API divergence, credential management, dimensionality configuration, and optional peer dependency loading so that runtime vector generation remains modular and resilient.
Sources: mem0-ts/src/oss/src/utils/factory.ts:76-106, mem0-ts/src/oss/src/embeddings/fastembed.ts:24-96, mem0-ts/src/oss/src/embeddings/aws_bedrock.ts:73-115, mem0-ts/src/oss/src/embeddings/vertexai.ts:41-94, mem0-ts/src/oss/src/embeddings/base.ts:1-10, mem0-ts/src/oss/src/embeddings/openai.ts:5-56, mem0-ts/src/oss/src/embeddings/azure.ts:5-61, mem0-ts/src/oss/src/embeddings/huggingface.ts:18-77, mem0-ts/src/oss/src/embeddings/langchain.ts:5-28, mem0-ts/src/oss/src/embeddings/ollama.ts:7-22, mem0-ts/src/oss/src/embeddings/together.ts:7-30, mem0-ts/src/oss/src/embeddings/lmstudio.ts:10-19, mem0-ts/src/oss/src/embeddings/google.ts:6-16
Embedder interface and factory resolution
Core Embedder contract
The TypeScript package defines the fundamental contract for all vector generation backends through the Embedder interface. This contract specifies asynchronous methods for single text embedding and batch text transformations, both accepting an optional memoryAction parameter restricted to "add", "update", or "search".
export interface Embedder {
embed(
text: string,
memoryAction?: "add" | "update" | "search",
): Promise<number[]>;
embedBatch(
texts: string[],
memoryAction?: "add" | "update" | "search",
): Promise<number[][]>;
}Sources: mem0-ts/src/oss/src/embeddings/base.ts:1-10
Note
The memoryAction parameter on embed and embedBatch allows provider implementations to tailor tokenization, prefixing, or request routing based on whether a text is being ingested for storage or queried during retrieval.
Sources: mem0-ts/src/oss/src/embeddings/base.ts:2-9
Exported adapter modules
The core package exports all provider embeddings modules and utility resolvers from its entry point, making individual adapters and base interfaces available to consumers and factory routines.
export * from "./embeddings/base";
export * from "./embeddings/aws_bedrock";
export * from "./embeddings/huggingface";
export * from "./embeddings/openai";
export * from "./embeddings/ollama";
export * from "./embeddings/lmstudio";
export * from "./embeddings/together";
export * from "./embeddings/google";
export * from "./embeddings/azure";
export * from "./embeddings/langchain";
export * from "./embeddings/vertexai";
export * from "./embeddings/fastembed";Sources: mem0-ts/src/oss/src/index.ts:4-15
OpenAI compatible embedding adapters
OpenAI and Azure OpenAI Adapters
The OpenAIEmbedder class acts as the core implementation for OpenAI-compliant endpoints, leveraging the official openai SDK package. It accepts an EmbeddingConfig object, initializing an OpenAI client with apiKey and optional baseURL or url. The default model is text-embedding-3-small, and embedding dimensions can be explicitly configured via embeddingDims. For batch processing, it slices text inputs into chunks of maximum 100 items, sends parallel requests with encoding_format: "float", and reconstructs the ordered list by sorting response data indices.
export class OpenAIEmbedder implements Embedder {
private openai: OpenAI;
private model: string;
private embeddingDims: number | undefined;
constructor(config: EmbeddingConfig) {
this.openai = new OpenAI({
apiKey: config.apiKey,
baseURL: config.baseURL || config.url,
});
this.model = config.model || "text-embedding-3-small";
this.embeddingDims = config.embeddingDims;
}
async embed(text: string): Promise<number[]> {
const response = await this.openai.embeddings.create({
model: this.model,
input: text,
encoding_format: "float",
...(this.embeddingDims !== undefined && {
dimensions: this.embeddingDims,
}),
});
return response.data[0].embedding;
}
async embedBatch(texts: string[]): Promise<number[][]> {
const MAX_BATCH = 100;
const allEmbeddings: number[][] = [];
for (let i = 0; i < texts.length; i += MAX_BATCH) {
const chunk = texts.slice(i, i + MAX_BATCH);
const response = await this.openai.embeddings.create({
model: this.model,
input: chunk,
encoding_format: "float",
...(this.embeddingDims !== undefined && {
dimensions: this.embeddingDims,
}),
});
allEmbeddings.push(
...response.data
.sort((a, b) => a.index - b.index)
.map((item) => item.embedding),
);
}
if (allEmbeddings.length !== texts.length) {
throw new Error(
`OpenAI embedBatch() returned ${allEmbeddings.length} embeddings for ${texts.length} texts using model '${this.model}'`,
);
}
return allEmbeddings;
}Sources: mem0-ts/src/oss/src/embeddings/openai.ts:5-56
The AzureOpenAIEmbedder class extends this paradigm to Microsoft Azure OpenAI deployments by utilizing the specialized AzureOpenAI client class. It validates that both config.apiKey and config.modelProperties?.endpoint are provided during instantiation, throwing an error if either is missing. It parses endpoint properties and passes them along with the API key to the client constructor, defaulting to text-embedding-3-small when no model is specified.
export class AzureOpenAIEmbedder implements Embedder {
private client: AzureOpenAI;
private model: string;
private embeddingDims: number | undefined;
constructor(config: EmbeddingConfig) {
if (!config.apiKey || !config.modelProperties?.endpoint) {
throw new Error("Azure OpenAI requires both API key and endpoint");
}
const { endpoint, ...rest } = config.modelProperties;
this.client = new AzureOpenAI({
apiKey: config.apiKey,
endpoint: endpoint as string,
...rest,
});
this.model = config.model || "text-embedding-3-small";
this.embeddingDims = config.embeddingDims;
}Sources: mem0-ts/src/oss/src/embeddings/azure.ts:5-24
Warning
Both OpenAIEmbedder and AzureOpenAIEmbedder validate batch result lengths against input text lengths, throwing an explicit runtime error if the API returns a mismatched count during chunked embedding operations.
Sources: mem0-ts/src/oss/src/embeddings/openai.ts:50-54, mem0-ts/src/oss/src/embeddings/azure.ts:55-59
Together AI, Hugging Face, and LM Studio Adapters
Alternative OpenAI-compatible providers subclass or wrap the standard client architecture to accommodate provider-specific default URLs, authentication fallbacks, and payload normalizations. The TogetherEmbedder inherits from OpenAIEmbedder, strips out any configured embeddingDims, resolves API keys from configuration or TOGETHER_API_KEY, and falls back to https://api.together.ai/v1 or TOGETHER_API_BASE with default model intfloat/multilingual-e5-large-instruct.
export class TogetherEmbedder extends OpenAIEmbedder {
constructor(config: EmbeddingConfig) {
const openAICompatibleConfig = { ...config };
delete openAICompatibleConfig.embeddingDims;
const apiKey = config.apiKey || process.env.TOGETHER_API_KEY;
if (!apiKey) {
throw new Error("Together API key is required");
}
super({
...openAICompatibleConfig,
apiKey,
// Honor TOGETHER_API_BASE like the Together LLM does, so a user behind a
// gateway who sets it gets it for embeddings too instead of silently
// hitting api.together.ai.
baseURL:
config.baseURL ||
config.url ||
process.env.TOGETHER_API_BASE ||
DEFAULT_BASE_URL,
model: config.model || DEFAULT_MODEL,
});
}Sources: mem0-ts/src/oss/src/embeddings/together.ts:7-30
The HuggingFaceEmbedder targets hosted Text Embeddings Inference (TEI) servers or OpenAI-compatible Hugging Face endpoints. It requires a base URL supplied via config.huggingfaceBaseUrl, config.baseURL, config.url, or process.env.HUGGINGFACE_BASE_URL, defaulting the model identifier to tei.
export class HuggingFaceEmbedder implements Embedder {
private openai: OpenAI;
private model: string;
constructor(config: EmbeddingConfig) {
const baseURL =
config.huggingfaceBaseUrl ||
config.baseURL ||
config.url ||
process.env.HUGGINGFACE_BASE_URL;
if (!baseURL) {
throw new Error(
"HuggingFace embedder requires an inference endpoint. Set " +
"`huggingfaceBaseUrl` (or `baseURL`) in the embedder config, or the " +
"HUGGINGFACE_BASE_URL environment variable (e.g. a TEI server at " +
"http://localhost:8080/v1).",
);
}
this.openai = new OpenAI({
apiKey: config.apiKey || process.env.HUGGINGFACE_API_KEY || "hf",
baseURL,
});
// TEI ignores the model field; default mirrors the Python provider.
this.model = config.model || "tei";
}Sources: mem0-ts/src/oss/src/embeddings/huggingface.ts:18-44
The LMStudioEmbedder provides local inference connectivity, defaulting to http://localhost:1234/v1 for the base URL, lm-studio for the API key, and nomic-ai/nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf for the model. It automatically normalizes input texts by replacing newline characters with spaces prior to generating embeddings.
export class LMStudioEmbedder implements Embedder {
private openai: OpenAI;
private model: string;
constructor(config: EmbeddingConfig) {
const baseURL = config.baseURL ?? config.url ?? DEFAULT_BASE_URL;
const apiKey = config.apiKey || DEFAULT_LMSTUDIO_API_KEY;
this.openai = new OpenAI({ apiKey, baseURL: String(baseURL) });
this.model = config.model || DEFAULT_MODEL;
}Sources: mem0-ts/src/oss/src/embeddings/lmstudio.ts:10-19
| Adapter Class | Default Base URL | Default Model | Key Environment Variables |
|---|---|---|---|
| OpenAIEmbedder | OpenAI standard API | text-embedding-3-small | OPENAI_API_KEY |
| AzureOpenAIEmbedder | Azure endpoint property | text-embedding-3-small | AZURE_OPENAI_API_KEY |
| TogetherEmbedder | https://api.together.ai/v1 | intfloat/multilingual-e5-large-instruct | TOGETHER_API_KEY, TOGETHER_API_BASE |
| HuggingFaceEmbedder | User-configured TEI URL | tei | HUGGINGFACE_BASE_URL, HUGGINGFACE_API_KEY |
| LMStudioEmbedder | http://localhost:1234/v1 | nomic-ai/nomic-embed-text-v1.5-GGUF/... | None (defaults to lm-studio) |
Sources: mem0-ts/src/oss/src/embeddings/openai.ts:13-15, mem0-ts/src/oss/src/embeddings/azure.ts:11-23, mem0-ts/src/oss/src/embeddings/together.ts:4-29, mem0-ts/src/oss/src/embeddings/huggingface.ts:23-43, mem0-ts/src/oss/src/embeddings/lmstudio.ts:5-18
Tip
When integrating LM Studio locally, newline replacement in LMStudioEmbedder prevents formatting errors in local GGUF embedding runners that expect single-line payloads.
Sources: mem0-ts/src/oss/src/embeddings/lmstudio.ts:22-23, mem0-ts/src/oss/src/embeddings/lmstudio.ts:38-40
Cloud managed embedding adapters
AWS Bedrock Embedder
The AWSBedrockEmbedder supports the Amazon Titan and Cohere embedding model families via @aws-sdk/client-bedrock-runtime. The package is lazily imported so that importing the module does not force the SDK dependency to be installed until an embedding request is executed. Credential validation enforces that if any explicit credential field (awsAccessKeyId, awsSecretAccessKey, or awsSessionToken) is supplied, both awsAccessKeyId and awsSecretAccessKey must be present; otherwise, an error is thrown to prevent silent fallback to the default credential chain. Omitting all credential fields allows the AWS SDK to resolve credentials from its default chain including environment variables, shared configuration files, SSO, or instance roles. Client initialization is memoized via clientPromise and cleared on rejection so transient failures do not permanently disable Bedrock for the embedder's lifetime.
* Supports the Amazon Titan and Cohere embedding model families. The
* `@aws-sdk/client-bedrock-runtime` dependency is lazily imported so the
* package stays optional: importing this module never forces the SDK to be
* installed until a Bedrock embedder actually embeds something.
*/
export class AWSBedrockEmbedder implements Embedder {
private readonly model: string;
private readonly region: string;
private readonly embeddingDims?: number;
private readonly credentials?: BedrockCredentials;
private clientPromise?: Promise<{
sdk: BedrockRuntimeModule;
client: { send: (command: any) => Promise<{ body?: Uint8Array }> };
}>;
constructor(config: EmbeddingConfig) {
this.model = config.model || DEFAULT_MODEL;
this.region = config.awsRegion || process.env.AWS_REGION || DEFAULT_REGION;
this.embeddingDims = config.embeddingDims;
const hasKeyPair = Boolean(
config.awsAccessKeyId && config.awsSecretAccessKey,
);
const hasAnyCredential = Boolean(
config.awsAccessKeyId ||
config.awsSecretAccessKey ||
config.awsSessionToken,
);
// Partially configured credentials would silently fall back to the default
// chain, embedding under an identity the caller never chose.
if (hasAnyCredential && !hasKeyPair) {
throw new Error(
"AWS Bedrock requires both awsAccessKeyId and awsSecretAccessKey when any explicit credential is configured. " +
"Omit all credential fields to use the AWS default credential chain.",
);
}
// Leaving `credentials` unset lets the AWS SDK resolve them from its
// default chain: environment, shared config, SSO, or the instance role.
if (hasKeyPair) {
this.credentials = {
accessKeyId: config.awsAccessKeyId!,
secretAccessKey: config.awsSecretAccessKey!,
...(config.awsSessionToken && { sessionToken: config.awsSessionToken }),
};
}
}Sources: mem0-ts/src/oss/src/embeddings/aws_bedrock.ts:68-115
Request body construction distinguishes between Cohere and Titan model architectures. Cohere requests supply an input_type mapped from memory actions (add, update, or search), whereas Embed v4 models additionally support configurable output dimensions and embedding types. Titan models accept a single text input per invocation and restrict dimension configuration to Titan Text Embeddings V2 models.
Warning
Partially configured AWS credentials throw an explicit runtime error rather than falling back to the default chain under an unintended identity.
Sources: mem0-ts/src/oss/src/embeddings/aws_bedrock.ts:97-104
Google GenAI Embedder
The GoogleEmbedder interfaces with @google/genai to generate text embeddings using models such as gemini-embedding-001. The API key is resolved from configuration or the GOOGLE_API_KEY environment variable. The client instance is lazily instantiated via loadPeer upon the first call to embed or embedBatch.
export class GoogleEmbedder implements Embedder {
private google!: GoogleGenAI;
private model: string;
private embeddingDims: number | undefined;
private readonly apiKey: string | undefined;
constructor(config: EmbeddingConfig) {
this.apiKey = config.apiKey || process.env.GOOGLE_API_KEY;
this.model = config.model || "gemini-embedding-001";
this.embeddingDims = config.embeddingDims;
}
private async ensureClient(): Promise<void> {
if (this.google) return;
const sdk = await loadPeer(
"@google/genai",
"Google embedder",
() => import("@google/genai"),
);
this.google = new sdk.GoogleGenAI({ apiKey: this.apiKey });
}Sources: mem0-ts/src/oss/src/embeddings/google.ts:6-26
Both single-item and batch embedding methods pass contents directly to the embedContent model endpoint. When embeddingDims is configured, it is transmitted as outputDimensionality within the request configuration block.
async embed(text: string): Promise<number[]> {
await this.ensureClient();
const response = await this.google.models.embedContent({
model: this.model,
contents: text,
...(this.embeddingDims !== undefined && {
config: { outputDimensionality: this.embeddingDims },
}),
});
return response.embeddings![0].values!;
}
async embedBatch(texts: string[]): Promise<number[][]> {
await this.ensureClient();
const response = await this.google.models.embedContent({
model: this.model,
contents: texts,
...(this.embeddingDims !== undefined && {
config: { outputDimensionality: this.embeddingDims },
}),
});
return response.embeddings!.map((item) => item.values!);
}Sources: mem0-ts/src/oss/src/embeddings/google.ts:28-50
Google Cloud Vertex AI Embedder
The VertexAIEmbedder communicates with Google Cloud Vertex AI via @google-cloud/aiplatform. It resolves project IDs from configuration or environment variables including GCP_PROJECT_ID, GOOGLE_CLOUD_PROJECT, and GCLOUD_PROJECT. Service account authentication supports file paths via vertexCredentialsJson or direct credentials via googleServiceAccountJson.
export class VertexAIEmbedder implements Embedder {
private client: PredictionServiceClient | undefined;
private helpers: AIPlatform["helpers"] | undefined;
private initPromise: Promise<void> | undefined;
private clientOptions: ClientOptions;
private model: string;
private embeddingDims: number;
private location: string;
private projectId: string;
private embeddingTypes: {
add: string;
update: string;
search: string;
};
constructor(config: VertexAIConfig) {
this.model = config.model || "gemini-embedding-001";
this.embeddingDims = config.embeddingDims || 256;
this.location =
config.location || process.env.GCP_LOCATION || "us-central1";
// Left empty when unset: initClient() resolves it from Application Default
// Credentials or the service account key file, the way the Python SDK does.
this.projectId =
config.googleProjectId ||
process.env.GCP_PROJECT_ID ||
process.env.GOOGLE_CLOUD_PROJECT ||
process.env.GCLOUD_PROJECT ||
"";
this.embeddingTypes = {
add: config.memoryAddEmbeddingType || "RETRIEVAL_DOCUMENT",
update: config.memoryUpdateEmbeddingType || "RETRIEVAL_DOCUMENT",
search: config.memorySearchEmbeddingType || "RETRIEVAL_QUERY",
};
const endpoint = `${this.location}-aiplatform.googleapis.com`;
this.clientOptions = { apiEndpoint: endpoint };
if (config.vertexCredentialsJson) {
this.clientOptions.keyFilename = config.vertexCredentialsJson;
} else if (config.googleServiceAccountJson) {
try {
this.clientOptions.credentials =
typeof config.googleServiceAccountJson === "string"
? JSON.parse(config.googleServiceAccountJson)
: config.googleServiceAccountJson;
} catch (err) {
throw new Error(
"Failed to parse googleServiceAccountJson: " + (err as Error).message,
);
}
}
}Sources: mem0-ts/src/oss/src/embeddings/vertexai.ts:41-94
The embedder maps memory actions (add, update, search) to specific Vertex task types (RETRIEVAL_DOCUMENT or RETRIEVAL_QUERY). Batch requests automatically chunk input texts according to model limits: gemini-embedding models restrict requests to 1 instance per request, while other models accept up to 250 instances per request.
function maxInstancesPerRequest(model: string): number {
return model.startsWith("gemini-embedding") ? 1 : 250;
}Sources: mem0-ts/src/oss/src/embeddings/vertexai.ts:24-26
| Parameter / Option | AWS Bedrock (AWSBedrockEmbedder) | Google GenAI (GoogleEmbedder) | Vertex AI (VertexAIEmbedder) |
|---|---|---|---|
| Default Model | amazon.titan-embed-text-v1 | gemini-embedding-001 | gemini-embedding-001 |
| Auth / Key Variables | awsAccessKeyId, awsSecretAccessKey | GOOGLE_API_KEY | googleServiceAccountJson, GCP_PROJECT_ID |
| Peer Dependency | @aws-sdk/client-bedrock-runtime | @google/genai | @google-cloud/aiplatform |
| Batch Support | Model-dependent payload handling | embedBatch method | Chunked via maxInstancesPerRequest |
Sources: mem0-ts/src/oss/src/embeddings/aws_bedrock.ts:68-115, mem0-ts/src/oss/src/embeddings/google.ts:1-26, mem0-ts/src/oss/src/embeddings/vertexai.ts:24-94
Tip
In VertexAIEmbedder, task types must reside directly on the instance object in snake_case (task_type), because Vertex silently ignores unknown fields placed inside parameters.
Sources: mem0-ts/src/oss/src/embeddings/vertexai.ts:138-147
Local and peer dependency loaders
Ollama Embedding Adapter
The OllamaEmbedder communicates with local Ollama instances to generate vector embeddings. It uses a dynamic peer dependency loader (loadPeer) to import the optional ollama package only when execution requires it, allowing consumers to omit the dependency if Ollama remains unused.
private async ensureClient(): Promise<void> {
if (this.ollama) return;
const sdk = await loadPeer(
"ollama",
"Ollama embedder",
() => import("ollama"),
);
this.ollama = new sdk.Ollama({ host: this.host });
}Sources: mem0-ts/src/oss/src/embeddings/ollama.ts:24-32
Upon instantiation, the embedder configures connection parameters and automatically verifies model availability. If the target model is absent from the local Ollama registry, it initiates a model pull action.
private async ensureModelExists(): Promise<boolean> {
if (this.initialized) {
return true;
}
await this.ensureClient();
const local_models = await this.ollama.list();
const target = OllamaEmbedder.normalizeModelName(this.model);
if (
!local_models.models.find(
(m: any) => OllamaEmbedder.normalizeModelName(m.name) === target,
)
) {
logger.info(`Pulling model ${this.model}...`);
await this.ollama.pull({ model: this.model });
}
this.initialized = true;
return true;
}Sources: mem0-ts/src/oss/src/embeddings/ollama.ts:64-81
Note
OllamaEmbedder defensively coerces inputs to strings via JSON.stringify(text) when callers supply non-string values parsed from untrusted LLM outputs.
Sources: mem0-ts/src/oss/src/embeddings/ollama.ts:41-42
FastEmbed Embedding Adapter
The FastEmbedEmbedder runs local ONNX-based embedding models through the fastembed package. To prevent runtime download errors and provide immediate feedback, the constructor validates configuration against a hardcoded list of supported models before loading the peer dependency.
const SUPPORTED_MODELS = [
"fast-all-MiniLM-L6-v2",
"fast-bge-base-en",
"fast-bge-base-en-v1.5",
"fast-bge-small-en",
"fast-bge-small-en-v1.5",
"fast-bge-small-zh-v1.5",
"fast-multilingual-e5-large",
] as const;
type FastEmbedModel = (typeof SUPPORTED_MODELS)[number];
const DEFAULT_MODEL: FastEmbedModel = "fast-bge-small-en-v1.5";
export class FastEmbedEmbedder implements Embedder {
private readonly modelName: FastEmbedModel;
private embeddingModel?: Promise<FlagEmbedding>;
constructor(config: EmbeddingConfig) {
if (typeof config.model === "string" && config.model.length > 0) {
if (!SUPPORTED_MODELS.includes(config.model as FastEmbedModel)) {
throw new Error(
`Unsupported FastEmbed model "${config.model}". ` +
`Supported models: ${SUPPORTED_MODELS.join(", ")}.`,
);
}
this.modelName = config.model as FastEmbedModel;
} else {
this.modelName = DEFAULT_MODEL;
}
}Sources: mem0-ts/src/oss/src/embeddings/fastembed.ts:12-40
| Supported Model Constant | Default Model | Peer Dependency | Input Normalization |
|---|---|---|---|
| fast-all-MiniLM-L6-v2, fast-bge-base-en, fast-bge-base-en-v1.5, fast-bge-small-en, fast-bge-small-en-v1.5, fast-bge-small-zh-v1.5, fast-multilingual-e5-large | fast-bge-small-en-v1.5 | fastembed | Replaces all newline characters (\n) with spaces |
Sources: mem0-ts/src/oss/src/embeddings/fastembed.ts:12-22, mem0-ts/src/oss/src/embeddings/fastembed.ts:57-69
The embedder lazily initializes the FlagEmbedding instance via loadPeer, caching the resulting model promise to handle subsequent single and batch generation requests asynchronously.
private getEmbeddingModel(): Promise<FlagEmbedding> {
if (!this.embeddingModel) {
this.embeddingModel = this.initEmbeddingModel().catch((error) => {
this.embeddingModel = undefined;
throw error;
});
}
return this.embeddingModel;
}
/**
* Lazily import the optional `fastembed` peer and initialize the model, so
* consumers that never touch FastEmbed don't need it installed.
*/
private async initEmbeddingModel(): Promise<FlagEmbedding> {
const sdk = await loadPeer(
"fastembed",
"FastEmbed embedder",
() => import("fastembed"),
);
return sdk.FlagEmbedding.init({ model: this.modelName });
}Sources: mem0-ts/src/oss/src/embeddings/fastembed.ts:42-65
LangChain bridge and ecosystem integrations
Langchain Embedder Adapter
The LangchainEmbedder bridges @langchain/core/embeddings models into the Mem0 embedder architecture. During construction, it validates that the provided configuration contains a valid LangChain embeddings instance equipped with both embedQuery and embedDocuments methods, throwing an error if the model object is missing or invalid.
constructor(config: EmbeddingConfig) {
// Check if config.model is provided and is an object (the instance)
if (!config.model || typeof config.model !== "object") {
throw new Error(
"Langchain embedder provider requires an initialized Langchain Embeddings instance passed via the 'model' field in the embedder config.",
);
}
// Basic check for embedding methods
if (
typeof (config.model as any).embedQuery !== "function" ||
typeof (config.model as any).embedDocuments !== "function"
) {
throw new Error(
"Provided Langchain 'instance' in the 'model' field does not appear to be a valid Langchain Embeddings instance (missing embedQuery or embedDocuments method).",
);
}
this.embedderInstance = config.model as Embeddings;Sources: mem0-ts/src/oss/src/embeddings/langchain.ts:9-25
The adapter extracts and retains an optional batchSize property directly from the underlying LangChain instance if present. For execution, it delegates single-text embedding tasks to embedQuery and batch collections to embedDocuments, allowing LangChain to manage internal chunking and rate limits.
// Store batch size if the instance has it (optional)
this.batchSize = (this.embedderInstance as any).batchSize;
}
async embed(text: string): Promise<number[]> {
try {
// Use embedQuery for single text embedding
return await this.embedderInstance.embedQuery(text);
} catch (error) {
console.error("Error embedding text with Langchain Embedder:", error);
throw error;
}
}
async embedBatch(texts: string[]): Promise<number[][]> {
try {
// Use embedDocuments for batch embedding
// Langchain's embedDocuments handles batching internally if needed/supported
return await this.embedderInstance.embedDocuments(texts);
} catch (error) {
console.error("Error embedding batch with Langchain Embedder:", error);
throw error;
}
}Sources: mem0-ts/src/oss/src/embeddings/langchain.ts:26-49
Caution
LangchainEmbedder requires an already-initialized instance passed via config.model; supplying a configuration dictionary or class constructor without instantiation causes immediate validation failure.
Sources: mem0-ts/src/oss/src/embeddings/langchain.ts:11-15
Related
On This Page
OverviewEmbedder interface and factory resolutionCore Embedder contractExported adapter modulesOpenAI compatible embedding adaptersOpenAI and Azure OpenAI AdaptersTogether AI, Hugging Face, and LM Studio AdaptersCloud managed embedding adaptersAWS Bedrock EmbedderGoogle GenAI EmbedderGoogle Cloud Vertex AI EmbedderLocal and peer dependency loadersOllama Embedding AdapterFastEmbed Embedding AdapterLangChain bridge and ecosystem integrationsLangchain Embedder AdapterRelated