Dosu LogoDosu Logo
Ask
Join our Discord
ragflowPublic
InfiniFlow
Documentsragflow
Embedding Pipeline
Embedding Pipeline
Type
Topic
Status
Published
Created
Aug 7, 2026
Updated
Aug 7, 2026
Created by
Dosu Bot
Updated by
Dosu Bot

Embedding Pipeline#

Overview#

RAGFlow's embedding pipeline converts document chunks into dense vectors for storage in the search index. It spans two layers:

  1. EmbeddingService — async orchestrator that drives batch encoding for a task, handles title/content weighting, and reports progress
  2. embedding_model.py provider classes — synchronous, provider-specific adapters that implement the actual API calls

Batch Size Configuration#

The top-level batch size is read from settings.EMBEDDING_BATCH_SIZE, which defaults to 16 and can be overridden via the EMBEDDING_BATCH_SIZE environment variable . EmbeddingService.__init__ accepts an explicit embedding_batch_size override; if not supplied, it falls back to the setting .


EmbeddingService.embed_chunks Flow#

Entry point: EmbeddingService.embed_chunks(docs, embedding_model, parser_config)

  1. Text extraction — EmbeddingUtils.prepare_texts_for_embedding(docs) returns (titles, contents). Content is pulled from question_kwd > content_with_weight; titles from docnm_kwd.
  2. Title encoding — The first title is encoded once and tiled across all chunks (cost: 1 API call for the whole batch).
  3. Content batch loop — Contents are sliced into chunks of _embedding_batch_size and dispatched via thread_pool_exec(_batch_encode_wrapper, ...). Each batch is rate-limited through ctx.embed_limiter .
  4. Truncation — Before each content batch is sent to the model, every text is truncated to embedding_model.max_length - 10 tokens via truncate().
  5. Vector assembly — EmbeddingUtils.stack_vectors() vstack-combines per-batch arrays; EmbeddingUtils.combine_title_content_vectors(tts, cnts, title_weight) applies a weighted blend (DEFAULT_TITLE_WEIGHT = 0.1, i.e. 10% title / 90% content).
  6. Attachment — EmbeddingUtils.attach_vectors(docs, vects) writes each vector to the chunk dict under the key q_<N>_vec.
  7. Return — (total_token_count, vector_size)

Provider-Level: Base._batched_encode#

The shared template for OpenAI-style providers is Base._batched_encode(texts, call_fn, *, batch_size, truncate_to=None). It:

  • Optionally truncates each text to truncate_to tokens before issuing any calls.
  • Runs a loop of ceil(len(texts) / batch_size) calls to the provider-supplied call_fn(batch) -> (embeddings, token_count) closure.
  • Accumulates vectors into a single np.ndarray and sums token counts.
  • Wraps any non-ModelException in a unified EmbeddingError, ensuring callers see a consistent exception type.

Response ordering is guaranteed by _sorted_by_index(), which sorts SDK result items by their .index attribute before extracting embeddings.


Provider Batch Sizes and Truncation Limits#

ProviderBatch SizeClient-Side Truncation (truncate_to)
OpenAI / Azure / OpenAI-API-Compatible168191 tokens
ZhipuAI embedding-216512 tokens
ZhipuAI embedding-3163072 tokens
QWen (DashScope)42048 tokens (inline)
Gemini162048 tokens
Bedrock (Titan/Cohere)1DEFAULT_MAX_TOKENS (8192)
Ollama16Server-side (truncate=True)
Cohere16Server-side (truncate="END")
NVIDIA NIM16Server-side ("truncate": "END")
Jina16Server-side ("truncate": true)
SiliconFlow16Model-specific (256–4096 tokens, inline in _clean_batch)
Perplexity512None
BuiltinEmbed (TEI)16Server-side

Sources:

DEFAULT_MAX_TOKENS = 8192 is the standard ceiling for most 8K-context providers .


DashScope URL Resolution#

QWenEmbed requires the DashScope native HTTP API (/api/v1) rather than the OpenAI-compatible path. _dashscope_native_http_api_url(base_url) detects known DashScope hostnames and maps them to the correct endpoint (international: dashscope-intl.aliyuncs.com, domestic: dashscope.aliyuncs.com). A context manager _dashscope_native_api_url_scope temporarily patches dashscope.base_http_api_url to minimize concurrency exposure.


Key Source Files#

FilePurpose
rag/svr/task_executor_refactor/embedding_service.pyAsync batch orchestrator
rag/llm/embedding_model.pyAll provider adapters + Base._batched_encode
rag/svr/task_executor_refactor/embedding_utils.pyText prep, vector stacking/combining/attaching
common/settings.pyEMBEDDING_BATCH_SIZE default
Documents
Agent Import and DSL Compatibility
Agent Prompt Processing
Agent Retrieval
API Authorization
API Error Codes
Ascend Inference Pipeline
Authentication
Azure OpenAI Integration
Canvas Architecture
Chat Assistant Configuration
Chat Completion API
Chrome for Testing ARM64 Support
Chunk Metadata Extraction
Chunker Pipeline
Compilation Template Management
Component Variable Propagation
Connection and Resource Management
Connector Architecture
Connector Document Sync
Conversation Session Management
What is the complete API flow for building a frontend UI with RAGFlow, covering dialogs, conversations, message history, streaming responses, and deletion?
Database Migrations
Dataflow Pipeline Execution
Dataset Access Control
Dataset Configuration UI
Dataset Parsing Mode
DeepDoc Model Distribution
DeepDoc Model Path Resolution
DeepDoc Module
Dify External Knowledge Integration
Docker Build Configuration
Document Parsing Pipeline
Elasticsearch Index Management
Embedding Pipeline
Embedding Vector Validation
Encrypted Storage
Figure Description Language Propagation
Frontend Build and Deployment
GPU and Accelerator Support
Hybrid Search and Retrieval
Infinity Database Stability
Internal Compilation Artifact Indexing
Keyword Extraction
Knowledge Compilation Pipeline
Knowledge Graph
Knowledge Graph Retrieval
Knowledge Graph Visualization
Layout Element Overlap Detection
LLM Configuration and Selection
LLM Driver Integration
LLM Provider Integration
MCP Server Integration
Media Context Configuration
Metadata Filtering
MinerU Configuration and Provider Resolution
MinerU PDF Parsing
Model Provider Architecture
Model Selection UI
Model Thinking and Reasoning
Multi-Architecture Docker Support
Multi-Backend Object Storage
Multi-Page Table and Element Handling
Multilingual Search Tokenization
Native Library Build and Linking
OCR Backend and Model Loading
Parser Configuration
Parser Output Lifecycle
Parser-Chunk Contract
PDF Chunk Position Rendering
Picture Chunker Media Processing
Pipeline Canvas Architecture
Provider Configuration Persistence
Provider Model Discovery
Python Dependency Management
RAGFlow Python SDK
Redis Cache Architecture
Retrieval API
Retrieval Pipeline
SSRF Protection
Table Column Field Normalization
Table Structure Parsing
Task Cancellation
Tenant Model Resolution
Text2SQL
TSR Coordinate System Alignment