Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[Feat] Add new RAG API on LiteLLM AI Gateway (#17109)

Ishaan Jaff5c192a23c341
diff --git a/docs/my-website/docs/rag_ingest.md b/docs/my-website/docs/rag_ingest.md
new file mode 100644
index 00000000000..5685fe63803
--- /dev/null
+++ b/docs/my-website/docs/rag_ingest.md
@@ -0,0 +1,227 @@
+# /rag/ingest
+
+All-in-one document ingestion pipeline: **Upload → Chunk → Embed → Vector Store**
+
+| Feature | Supported |
+|---------|-----------|
+| Cost Tracking | ❌ |
+| Logging | ✅ |
+| Supported Providers | `openai`, `bedrock` |
+
+## Quick Start
+
+### OpenAI
+
+```bash showLineNumbers title="Ingest to OpenAI vector store"
+curl -X POST "http://localhost:4000/v1/rag/ingest" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"file\": {
+ \"filename\": \"document.txt\",
+ \"content\": \"$(base64 -i document.txt)\",
+ \"content_type\": \"text/plain\"
+ },
+ \"ingest_options\": {
+ \"vector_store\": {
+ \"custom_llm_provider\": \"openai\"
+ }
+ }
+ }"
+```
+
+### Bedrock
+
+```bash showLineNumbers title="Ingest to Bedrock Knowledge Base"
+curl -X POST "http://localhost:4000/v1/rag/ingest" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"file\": {
+ \"filename\": \"document.txt\",
+ \"content\": \"$(base64 -i document.txt)\",
+ \"content_type\": \"text/plain\"
+ },
+ \"ingest_options\": {
+ \"vector_store\": {
+ \"custom_llm_provider\": \"bedrock\"
+ }
+ }
+ }"
+```
+
+## Response
+
+```json
+{
+ "id": "ingest_abc123",
+ "status": "completed",
+ "vector_store_id": "vs_xyz789",
+ "file_id": "file_123"
+}
+```
+
+## Query the Vector Store
+
+After ingestion, query with `/vector_stores/{vector_store_id}/search`:
+
+```bash showLineNumbers title="Search the vector store"
+curl -X POST "http://localhost:4000/v1/vector_stores/vs_xyz789/search" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "query": "What is the main topic?",
+ "max_num_results": 5
+ }'
+```
+
+## End-to-End Example
+
+### OpenAI
+
+#### 1. Ingest Document
+
+```bash showLineNumbers title="Step 1: Ingest"
+curl -X POST "http://localhost:4000/v1/rag/ingest" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d "{
+ \"file\": {
+ \"filename\": \"test_document.txt\",
+ \"content\": \"$(base64 -i test_document.txt)\",
+ \"content_type\": \"text/plain\"
+ },
+ \"ingest_options\": {
+ \"name\": \"test-basic-ingest\",
+ \"vector_store\": {
+ \"custom_llm_provider\": \"openai\"
+ }
+ }
+ }"
+```
+
+Response:
+```json
+{
+ "id": "ingest_d834f544-fc5e-4751-902d-fb0bcc183b85",
+ "status": "completed",
+ "vector_store_id": "vs_692658d337c4819183f2ad8488d12fc9",
+ "file_id": "file-M2pJJiWH56cfUP4Fe7rJay"
+}
+```
+
+#### 2. Query
+
+```bash showLineNumbers title="Step 2: Query"
+curl -X POST "http://localhost:4000/v1/vector_stores/vs_692658d337c4819183f2ad8488d12fc9/search" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "query": "What is LiteLLM?",
+ "custom_llm_provider": "openai"
+ }'
+```
+
+Response:
+```json
+{
+ "object": "vector_store.search_results.page",
+ "search_query": ["What is LiteLLM?"],
+ "data": [
+ {
+ "file_id": "file-M2pJJiWH56cfUP4Fe7rJay",
+ "filename": "test_document.txt",
+ "score": 0.4004629778869299,
+ "attributes": {},
+ "content": [
+ {
+ "type": "text",
+ "text": "Test document abc123 for RAG ingestion.\nThis is a sample document to test the RAG ingest API.\nLiteLLM provides a unified interface for vector stores."
+ }
+ ]
+ }
+ ],
+ "has_more": false,
+ "next_page": null
+}
+```
+
+## Request Parameters
+
+### Top-Level
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `file` | object | One of file/file_url/file_id required | Base64-encoded file |
+| `file.filename` | string | Yes | Filename with extension |
+| `file.content` | string | Yes | Base64-encoded content |
+| `file.content_type` | string | Yes | MIME type (e.g., `text/plain`) |
+| `file_url` | string | One of file/file_url/file_id required | URL to fetch file from |
+| `file_id` | string | One of file/file_url/file_id required | Existing file ID |
+| `ingest_options` | object | Yes | Pipeline configuration |
+
+### ingest_options
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `vector_store` | object | Yes | Vector store configuration |
+| `name` | string | No | Pipeline name for logging |
+
+### vector_store (OpenAI)
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `custom_llm_provider` | string | - | `"openai"` |
+| `vector_store_id` | string | auto-create | Existing vector store ID |
+
+### vector_store (Bedrock)
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `custom_llm_provider` | string | - | `"bedrock"` |
+| `vector_store_id` | string | auto-create | Existing Knowledge Base ID |
+| `wait_for_ingestion` | boolean | `false` | Wait for indexing to complete |
+| `ingestion_timeout` | integer | `300` | Timeout in seconds (if waiting) |
+| `s3_bucket` | string | auto-create | S3 bucket for documents |
+| `s3_prefix` | string | `"data/"` | S3 key prefix |
+| `embedding_model` | string | `amazon.titan-embed-text-v2:0` | Bedrock embedding model |
+| `aws_region_name` | string | `us-west-2` | AWS region |
+
+:::info Bedrock Auto-Creation
+When `vector_store_id` is omitted, LiteLLM automatically creates:
+- S3 bucket for document storage
+- OpenSearch Serverless collection
+- IAM role with required permissions
+- Bedrock Knowledge Base
+- Data Source
+:::
+
+## Input Examples
+
+### File (Base64)
+
+```json title="Request body"
+{
+ "file": {
+ "filename": "document.txt",
+ "content": "<base64-encoded-content>",
+ "content_type": "text/plain"
+ },
+ "ingest_options": {
+ "vector_store": {"custom_llm_provider": "openai"}
+ }
+}
+```
+
+### File URL
+
+```bash showLineNumbers title="Ingest from URL"
+curl -X POST "http://localhost:4000/v1/rag/ingest" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "file_url": "https://example.com/document.pdf",
+ "ingest_options": {"vector_store": {"custom_llm_provider": "openai"}}
+ }'
+```
+
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index 104c7541d67..e5eba82e32f 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -412,6 +412,7 @@ const sidebars = {
"proxy/pass_through"
]
},
+ "rag_ingest",
"realtime",
"rerank",
"response_api",
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 0048f4c29cf..aebf1404196 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -1434,6 +1434,7 @@ from .skills.main import (
)
from .containers.main import *
from .ocr.main import *
+from .rag.main import *
from .search.main import *
from .realtime_api.main import _arealtime
from .fine_tuning.main import *
@@ -1470,6 +1471,9 @@ from .vector_stores.vector_store_registry import (
vector_store_registry: Optional[VectorStoreRegistry] = None
vector_store_index_registry: Optional[VectorStoreIndexRegistry] = None
+### RAG ###
+from . import rag
+
### CUSTOM LLMs ###
from .types.llms.custom_llm import CustomLLMItem
from .types.utils import GenericStreamingChunk
diff --git a/litellm/constants.py b/litellm/constants.py
index 41441e21f75..cf3d4c6e742 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1211,3 +1211,7 @@ SENTRY_PII_DENYLIST = [
COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY = int(
os.getenv("COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY", 1000)
)
+
+########################### RAG Text Splitter Constants ###########################
+DEFAULT_CHUNK_SIZE = int(os.getenv("DEFAULT_CHUNK_SIZE", 1000))
+DEFAULT_CHUNK_OVERLAP = int(os.getenv("DEFAULT_CHUNK_OVERLAP", 200))
diff --git a/litellm/llms/bedrock/image/image_handler.py b/litellm/llms/bedrock/image/image_handler.py
index 0825aecc856..89e37bbdd8d 100644
--- a/litellm/llms/bedrock/image/image_handler.py
+++ b/litellm/llms/bedrock/image/image_handler.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import json
from typing import TYPE_CHECKING, Any, Optional, Union
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 0143a6e6cec..d2b04410026 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -330,6 +330,7 @@ class ProxyBaseLLMRequestProcessing:
"avideo_remix",
"acreate_container",
"alist_containers",
+ "aingest",
"aretrieve_container",
"adelete_container",
"acreate_skill",
@@ -453,6 +454,7 @@ class ProxyBaseLLMRequestProcessing:
"avideo_remix",
"acreate_container",
"alist_containers",
+ "aingest",
"aretrieve_container",
"adelete_container",
"acreate_skill",
diff --git a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
index eef8043b237..02e06acbda4 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/tool_permission.py
@@ -23,6 +23,7 @@ from litellm.types.proxy.guardrails.guardrail_hooks.tool_permission import (
ToolResult,
)
from litellm.types.utils import (
+ CallTypesLiteral,
ChatCompletionMessageToolCall,
Choices,
LLMResponseTypes,
@@ -202,16 +203,21 @@ class ToolPermissionGuardrail(CustomGuardrail):
return {}
def _collect_argument_paths(
- self, value: Any, current_path: str, collected: Dict[str, List[Any]]
+ self, value: Any, current_path: str, collected: Dict[str, List[Any]], depth: int = 0
) -> None:
+ from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH
+
+ if depth > DEFAULT_MAX_RECURSE_DEPTH:
+ return
+
if isinstance(value, dict):
for key, sub_value in value.items():
next_path = f"{current_path}.{key}" if current_path else key
- self._collect_argument_paths(sub_value, next_path, collected)
+ self._collect_argument_paths(sub_value, next_path, collected, depth + 1)
elif isinstance(value, list):
list_path = f"{current_path}[]" if current_path else "[]"
for item in value:
- self._collect_argument_paths(item, list_path, collected)
+ self._collect_argument_paths(item, list_path, collected, depth + 1)
else:
if not current_path:
return
@@ -437,18 +443,7 @@ class ToolPermissionGuardrail(CustomGuardrail):
user_api_key_dict: UserAPIKeyAuth,
cache: DualCache,
data: dict,
- call_type: Literal[
- "completion",
- "text_completion",
- "embeddings",
- "image_generation",
- "moderation",
- "audio_transcription",
- "pass_through_endpoint",
- "rerank",
- "mcp_call",
- "anthropic_messages",
- ],
+ call_type: CallTypesLiteral,
) -> Union[Exception, str, dict, None]:
""" """
verbose_proxy_logger.debug("Tool Permission Guardrail Pre-Call Hook")
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 7c415b8106e..24d8c6db91f 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -362,6 +362,7 @@ from litellm.proxy.pass_through_endpoints.pass_through_endpoints import (
)
from litellm.proxy.prompts.prompt_endpoints import router as prompts_router
from litellm.proxy.public_endpoints import router as public_endpoints_router
+from litellm.proxy.rag_endpoints.endpoints import router as rag_router
from litellm.proxy.rerank_endpoints.endpoints import router as rerank_router
from litellm.proxy.response_api_endpoints.endpoints import router as response_router
from litellm.proxy.route_llm_request import route_request
@@ -10157,6 +10158,7 @@ app.include_router(batches_router)
app.include_router(public_endpoints_router)
app.include_router(rerank_router)
app.include_router(ocr_router)
+app.include_router(rag_router)
app.include_router(video_router)
app.include_router(container_router)
app.include_router(search_router)
diff --git a/litellm/proxy/rag_endpoints/__init__.py b/litellm/proxy/rag_endpoints/__init__.py
new file mode 100644
index 00000000000..4586e4ec72a
--- /dev/null
+++ b/litellm/proxy/rag_endpoints/__init__.py
@@ -0,0 +1,6 @@
+"""RAG Endpoints for LiteLLM Proxy."""
+
+from litellm.proxy.rag_endpoints.endpoints import router
+
+__all__ = ["router"]
+
diff --git a/litellm/proxy/rag_endpoints/endpoints.py b/litellm/proxy/rag_endpoints/endpoints.py
new file mode 100644
index 00000000000..c0b5103f47f
--- /dev/null
+++ b/litellm/proxy/rag_endpoints/endpoints.py
@@ -0,0 +1,200 @@
+"""
+RAG Ingest Endpoints for LiteLLM Proxy.
+
+Provides an all-in-one API for document ingestion:
+Upload -> (OCR) -> Chunk -> Embed -> Vector Store
+"""
+
+import base64
+from typing import Any, Dict, Optional, Tuple
+
+import orjson
+from fastapi import APIRouter, Depends, HTTPException, Request, Response
+from fastapi.responses import ORJSONResponse
+
+import litellm
+from litellm._logging import verbose_proxy_logger
+from litellm.proxy._types import *
+from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth
+from litellm.proxy.common_utils.http_parsing_utils import (
+ _read_request_body,
+ _safe_get_request_headers,
+ get_form_data,
+)
+
+router = APIRouter()
+
+
+async def parse_rag_ingest_request(
+ request: Request,
+) -> Tuple[Dict[str, Any], Optional[Tuple[str, bytes, str]], Optional[str], Optional[str]]:
+ """
+ Parse RAG ingest request.
+
+ Supports:
+ - Form: file + request JSON in form field
+ - JSON body for URL-based ingestion
+
+ Returns:
+ Tuple of (ingest_options, file_data, file_url, file_id)
+ """
+ headers = _safe_get_request_headers(request)
+ content_type = headers.get("content-type", "")
+
+ file_data = None
+ file_url = None
+ file_id = None
+ ingest_options: Dict[str, Any] = {}
+
+ if "multipart/form-data" in content_type:
+ # Form upload
+ form_data = await get_form_data(request)
+
+ # Get file
+ file_obj = form_data.get("file")
+ if file_obj is not None and hasattr(file_obj, "read"):
+ file_content = await file_obj.read()
+ file_data = (file_obj.filename, file_content, file_obj.content_type)
+
+ # Parse JSON from 'request' form field (contains full request body as JSON)
+ request_json_str = form_data.get("request")
+ if request_json_str:
+ request_data = orjson.loads(request_json_str)
+ ingest_options = request_data.get("ingest_options", {})
+ file_url = request_data.get("file_url")
+ file_id = request_data.get("file_id")
+
+ else:
+ # JSON body
+ data = await _read_request_body(request)
+ ingest_options = data.get("ingest_options", {})
+ file_url = data.get("file_url")
+ file_id = data.get("file_id")
+
+ # Handle base64-encoded file in JSON body
+ file_obj = data.get("file")
+ if file_obj and isinstance(file_obj, dict):
+ filename = file_obj.get("filename")
+ content_b64 = file_obj.get("content")
+ content_type = file_obj.get("content_type", "application/octet-stream")
+
+ if filename and content_b64:
+ try:
+ file_content = base64.b64decode(content_b64)
+ file_data = (filename, file_content, content_type)
+ except Exception as e:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": f"Invalid base64 content: {e}"},
+ )
+
+ # Validate
+ if file_data is None and file_url is None and file_id is None:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "Must provide file, file_url, or file_id"},
+ )
+
+ if "vector_store" not in ingest_options:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "ingest_options must contain 'vector_store' configuration"},
+ )
+
+ return ingest_options, file_data, file_url, file_id
+
+
+ "/v1/rag/ingest",
+ dependencies=[Depends(user_api_key_auth)],
+ response_class=ORJSONResponse,
+ tags=["rag"],
+)
+ "/rag/ingest",
+ dependencies=[Depends(user_api_key_auth)],
+ response_class=ORJSONResponse,
+ tags=["rag"],
+)
+async def rag_ingest(
+ request: Request,
+ fastapi_response: Response,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ RAG Ingest endpoint - all-in-one document ingestion pipeline.
+
+ Supports form upload (for files) or JSON body (for URLs).
+
+ ## Form upload (for files):
+ ```bash
+ curl -X POST "http://localhost:4000/v1/rag/ingest" \\
+ -H "Authorization: Bearer sk-1234" \\
+ -F file="@document.pdf" \\
+ -F 'ingest_options={"vector_store": {"custom_llm_provider": "openai"}}'
+ ```
+
+ ## JSON body (for URLs):
+ ```bash
+ curl -X POST "http://localhost:4000/v1/rag/ingest" \\
+ -H "Authorization: Bearer sk-1234" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "file_url": "https://example.com/document.pdf",
+ "ingest_options": {"vector_store": {"custom_llm_provider": "openai"}}
+ }'
+ ```
+
+ ## Bedrock:
+ ```bash
+ curl -X POST "http://localhost:4000/v1/rag/ingest" \\
+ -H "Authorization: Bearer sk-1234" \\
+ -F file="@document.pdf" \\
+ -F 'ingest_options={"vector_store": {"custom_llm_provider": "bedrock"}}'
+ ```
+ """
+ from litellm.proxy.proxy_server import (
+ add_litellm_data_to_request,
+ general_settings,
+ llm_router,
+ proxy_config,
+ version,
+ )
+
+ try:
+ # Parse request
+ ingest_options, file_data, file_url, file_id = await parse_rag_ingest_request(request)
+
+ # Add litellm data
+ request_data: Dict[str, Any] = {}
+ request_data = await add_litellm_data_to_request(
+ data=request_data,
+ request=request,
+ general_settings=general_settings,
+ user_api_key_dict=user_api_key_dict,
+ version=version,
+ proxy_config=proxy_config,
+ )
+
+ verbose_proxy_logger.debug(f"RAG Ingest - options: {ingest_options}")
+
+ # Call ingest
+ response = await litellm.aingest(
+ ingest_options=ingest_options,
+ file_data=file_data,
+ file_url=file_url,
+ file_id=file_id,
+ router=llm_router,
+ **request_data,
+ )
+
+ return response
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ verbose_proxy_logger.exception(f"RAG Ingest failed: {e}")
+ raise HTTPException(
+ status_code=500,
+ detail={"error": str(e)},
+ )
diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.py
index 6b7324a60ed..79e316d4702 100644
--- a/litellm/proxy/route_llm_request.py
+++ b/litellm/proxy/route_llm_request.py
@@ -40,6 +40,7 @@ ROUTE_ENDPOINT_MAPPING = {
"alist_skills": "/skills",
"aget_skill": "/skills/{skill_id}",
"adelete_skill": "/skills/{skill_id}",
+ "aingest": "/rag/ingest",
}
@@ -134,6 +135,7 @@ async def route_request(
"alist_skills",
"aget_skill",
"adelete_skill",
+ "aingest",
],
):
"""
@@ -190,6 +192,7 @@ async def route_request(
"alist_skills",
"aget_skill",
"adelete_skill",
+ "aingest",
] and (data.get("model") is None or data.get("model") == ""):
# These endpoints don't need a model, use custom_llm_provider directly
return getattr(litellm, f"{route_type}")(**data)
diff --git a/litellm/rag/__init__.py b/litellm/rag/__init__.py
new file mode 100644
index 00000000000..f87e72f0c17
--- /dev/null
+++ b/litellm/rag/__init__.py
@@ -0,0 +1,22 @@
+"""
+LiteLLM RAG (Retrieval Augmented Generation) Module.
+
+Provides an all-in-one API for document ingestion:
+Upload -> (OCR) -> Chunk -> Embed -> Vector Store
+"""
+
+from litellm.rag.main import aingest, ingest
+
+__all__ = ["ingest", "aingest"]
+
+
+# Expose at litellm.rag level for convenience
+async def arag_ingest(*args, **kwargs):
+ """Alias for aingest."""
+ return await aingest(*args, **kwargs)
+
+
+def rag_ingest(*args, **kwargs):
+ """Alias for ingest."""
+ return ingest(*args, **kwargs)
+
diff --git a/litellm/rag/ingestion/__init__.py b/litellm/rag/ingestion/__init__.py
new file mode 100644
index 00000000000..e34a715085c
--- /dev/null
+++ b/litellm/rag/ingestion/__init__.py
@@ -0,0 +1,14 @@
+"""
+RAG Ingestion classes for different providers.
+"""
+
+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion
+from litellm.rag.ingestion.bedrock_ingestion import BedrockRAGIngestion
+from litellm.rag.ingestion.openai_ingestion import OpenAIRAGIngestion
+
+__all__ = [
+ "BaseRAGIngestion",
+ "BedrockRAGIngestion",
+ "OpenAIRAGIngestion",
+]
+
diff --git a/litellm/rag/ingestion/base_ingestion.py b/litellm/rag/ingestion/base_ingestion.py
new file mode 100644
index 00000000000..fc673ecc8da
--- /dev/null
+++ b/litellm/rag/ingestion/base_ingestion.py
@@ -0,0 +1,314 @@
+"""
+Base RAG Ingestion class.
+
+Provides abstract methods for:
+- OCR
+- Chunking
+- Embedding
+- Vector Store operations
+
+Providers can inherit and override methods as needed.
+"""
+
+from __future__ import annotations
+
+import base64
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+
+import httpx
+
+import litellm
+from litellm._logging import verbose_logger
+from litellm._uuid import uuid4
+from litellm.constants import DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE
+from litellm.rag.text_splitters import RecursiveCharacterTextSplitter
+from litellm.types.rag import RAGIngestOptions, RAGIngestResponse
+
+if TYPE_CHECKING:
+ from litellm import Router
+
+
+class BaseRAGIngestion(ABC):
+ """
+ Base class for RAG ingestion.
+
+ Providers should inherit from this class and override methods as needed.
+ For example, OpenAI handles embedding internally when attaching files to
+ vector stores, so it overrides the embedding step to be a no-op.
+ """
+
+ def __init__(
+ self,
+ ingest_options: RAGIngestOptions,
+ router: Optional["Router"] = None,
+ ):
+ self.ingest_options = ingest_options
+ self.router = router
+ self.ingest_id = f"ingest_{uuid4()}"
+
+ # Extract configs from options
+ self.ocr_config = ingest_options.get("ocr")
+ self.chunking_strategy = ingest_options.get("chunking_strategy", {"type": "auto"})
+ self.embedding_config = ingest_options.get("embedding")
+ self.vector_store_config = ingest_options.get("vector_store") or {}
+ self.ingest_name = ingest_options.get("name")
+
+ @property
+ def custom_llm_provider(self) -> str:
+ """Get the vector store provider."""
+ return self.vector_store_config.get("custom_llm_provider", "openai")
+
+ async def upload(
+ self,
+ file_data: Optional[Tuple[str, bytes, str]] = None,
+ file_url: Optional[str] = None,
+ file_id: Optional[str] = None,
+ ) -> Tuple[Optional[str], Optional[bytes], Optional[str], Optional[str]]:
+ """
+ Upload / prepare file for ingestion.
+
+ Args:
+ file_data: Tuple of (filename, content_bytes, content_type)
+ file_url: URL to fetch file from
+ file_id: Existing file ID to use
+
+ Returns:
+ Tuple of (filename, file_content, content_type, existing_file_id)
+ """
+ if file_data:
+ filename, file_content, content_type = file_data
+ return filename, file_content, content_type, None
+
+ if file_url:
+ async with httpx.AsyncClient() as http_client:
+ response = await http_client.get(file_url)
+ response.raise_for_status()
+ file_content = response.content
+ filename = file_url.split("/")[-1] or "document"
+ content_type = response.headers.get("content-type", "application/octet-stream")
+ return filename, file_content, content_type, None
+
+ if file_id:
+ return None, None, None, file_id
+
+ raise ValueError("Must provide file_data, file_url, or file_id")
+
+ async def ocr(
+ self,
+ file_content: Optional[bytes],
+ content_type: Optional[str],
+ ) -> Optional[str]:
+ """
+ Perform OCR on file content to extract text.
+
+ Args:
+ file_content: Raw file bytes
+ content_type: MIME type of the file
+
+ Returns:
+ Extracted text or None if OCR not configured/needed
+ """
+ if not self.ocr_config or not file_content:
+ return None
+
+ ocr_model = self.ocr_config.get("model", "mistral/mistral-ocr-latest")
+
+ # Determine document type
+ if content_type and "image" in content_type:
+ doc_type, url_key = "image_url", "image_url"
+ else:
+ doc_type, url_key = "document_url", "document_url"
+
+ # Encode as base64 data URL
+ b64_content = base64.b64encode(file_content).decode("utf-8")
+ data_url = f"data:{content_type};base64,{b64_content}"
+
+ # Use router if available
+ if self.router is not None:
+ ocr_response = await self.router.aocr(
+ model=ocr_model,
+ document={"type": doc_type, url_key: data_url},
+ )
+ else:
+ ocr_response = await litellm.aocr(
+ model=ocr_model,
+ document={"type": doc_type, url_key: data_url},
+ )
+
+ # Extract text from pages
+ if hasattr(ocr_response, "pages") and ocr_response.pages: # type: ignore
+ return "\n\n".join(
+ page.markdown for page in ocr_response.pages if hasattr(page, "markdown") # type: ignore
+ )
+
+ return None
+
+ def chunk(
+ self,
+ text: Optional[str],
+ file_content: Optional[bytes],
+ ocr_was_used: bool,
+ ) -> List[str]:
+ """
+ Split text into chunks using RecursiveCharacterTextSplitter.
+
+ Args:
+ text: Text from OCR (if used)
+ file_content: Raw file content bytes
+ ocr_was_used: Whether OCR was performed
+
+ Returns:
+ List of text chunks
+ """
+ # Get text to chunk
+ text_to_chunk: Optional[str] = None
+ if text:
+ text_to_chunk = text
+ elif file_content and not ocr_was_used:
+ try:
+ text_to_chunk = file_content.decode("utf-8")
+ except UnicodeDecodeError:
+ verbose_logger.debug("Binary file detected, skipping text chunking")
+ return []
+
+ if not text_to_chunk:
+ return []
+
+ # Extract RecursiveCharacterTextSplitter args
+ splitter_args = self.chunking_strategy or {}
+ chunk_size = splitter_args.get("chunk_size", DEFAULT_CHUNK_SIZE)
+ chunk_overlap = splitter_args.get("chunk_overlap", DEFAULT_CHUNK_OVERLAP)
+ separators = splitter_args.get("separators", None)
+
+ # Build splitter kwargs
+ splitter_kwargs: Dict[str, Any] = {
+ "chunk_size": chunk_size,
+ "chunk_overlap": chunk_overlap,
+ }
+ if separators:
+ splitter_kwargs["separators"] = separators
+
+ text_splitter = RecursiveCharacterTextSplitter(**splitter_kwargs)
+ return text_splitter.split_text(text_to_chunk)
+
+ async def embed(
+ self,
+ chunks: List[str],
+ ) -> Optional[List[List[float]]]:
+ """
+ Generate embeddings for text chunks.
+
+ Args:
+ chunks: List of text chunks
+
+ Returns:
+ List of embeddings or None
+ """
+ if not self.embedding_config or not chunks:
+ return None
+
+ embedding_model = self.embedding_config.get("model", "text-embedding-3-small")
+
+ if self.router is not None:
+ response = await self.router.aembedding(model=embedding_model, input=chunks)
+ else:
+ response = await litellm.aembedding(model=embedding_model, input=chunks)
+
+ return [item["embedding"] for item in response.data]
+
+ @abstractmethod
+ async def store(
+ self,
+ file_content: Optional[bytes],
+ filename: Optional[str],
+ content_type: Optional[str],
+ chunks: List[str],
+ embeddings: Optional[List[List[float]]],
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """
+ Store content in vector store.
+
+ This method must be implemented by provider-specific subclasses.
+
+ Args:
+ file_content: Raw file bytes
+ filename: Name of the file
+ content_type: MIME type
+ chunks: Text chunks (if chunking was done locally)
+ embeddings: Embeddings (if embedding was done locally)
+
+ Returns:
+ Tuple of (vector_store_id, file_id)
+ """
+ pass
+
+ async def ingest(
+ self,
+ file_data: Optional[Tuple[str, bytes, str]] = None,
+ file_url: Optional[str] = None,
+ file_id: Optional[str] = None,
+ ) -> RAGIngestResponse:
+ """
+ Execute the full ingestion pipeline.
+
+ Args:
+ file_data: Tuple of (filename, content_bytes, content_type)
+ file_url: URL to fetch file from
+ file_id: Existing file ID to use
+
+ Returns:
+ RAGIngestResponse with status and IDs
+
+ Raises:
+ ValueError: If no input source is provided
+ """
+ # Step 1: Upload (raises ValueError if no input provided)
+ filename, file_content, content_type, existing_file_id = await self.upload(
+ file_data=file_data,
+ file_url=file_url,
+ file_id=file_id,
+ )
+
+ try:
+ # Step 2: OCR (optional)
+ extracted_text = await self.ocr(
+ file_content=file_content,
+ content_type=content_type,
+ )
+
+ # Step 3: Chunking
+ chunks = self.chunk(
+ text=extracted_text,
+ file_content=file_content,
+ ocr_was_used=self.ocr_config is not None,
+ )
+
+ # Step 4: Embedding (optional - some providers handle this internally)
+ embeddings = await self.embed(chunks=chunks)
+
+ # Step 5: Store in vector store
+ vector_store_id, result_file_id = await self.store(
+ file_content=file_content,
+ filename=filename,
+ content_type=content_type,
+ chunks=chunks,
+ embeddings=embeddings,
+ )
+
+ return RAGIngestResponse(
+ id=self.ingest_id,
+ status="completed",
+ vector_store_id=vector_store_id or "",
+ file_id=result_file_id or existing_file_id,
+ )
+
+ except Exception as e:
+ verbose_logger.exception(f"RAG Pipeline failed: {e}")
+ return RAGIngestResponse(
+ id=self.ingest_id,
+ status="failed",
+ vector_store_id="",
+ file_id=None,
+ )
+
diff --git a/litellm/rag/ingestion/bedrock_ingestion.py b/litellm/rag/ingestion/bedrock_ingestion.py
new file mode 100644
index 00000000000..5fa6145e248
--- /dev/null
+++ b/litellm/rag/ingestion/bedrock_ingestion.py
@@ -0,0 +1,619 @@
+"""
+Bedrock-specific RAG Ingestion implementation.
+
+Bedrock Knowledge Bases handle embedding internally when files are ingested,
+so this implementation uploads files to S3 and triggers ingestion jobs.
+
+Supports two modes:
+1. Use existing KB: Provide vector_store_id (KB ID)
+2. Auto-create KB: Don't provide vector_store_id - creates all AWS resources automatically
+"""
+
+from __future__ import annotations
+
+import json
+import time
+import uuid
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
+
+from litellm._logging import verbose_logger
+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion
+
+if TYPE_CHECKING:
+ from litellm import Router
+ from litellm.types.rag import RAGIngestOptions
+
+
+def _get_str_or_none(value: Any) -> Optional[str]:
+ """Cast config value to Optional[str]."""
+ return str(value) if value is not None else None
+
+
+def _get_int(value: Any, default: int) -> int:
+ """Cast config value to int with default."""
+ if value is None:
+ return default
+ return int(value)
+
+
+class BedrockRAGIngestion(BaseRAGIngestion, BaseAWSLLM):
+ """
+ Bedrock Knowledge Base RAG ingestion.
+
+ Supports two modes:
+ 1. **Use existing KB**: Provide vector_store_id
+ 2. **Auto-create KB**: Don't provide vector_store_id - creates S3 bucket,
+ OpenSearch Serverless collection, IAM role, KB, and data source automatically
+
+ Optional config:
+ - vector_store_id: Existing KB ID (if not provided, auto-creates)
+ - s3_bucket: S3 bucket (auto-created if not provided)
+ - embedding_model: Bedrock embedding model (default: amazon.titan-embed-text-v2:0)
+ - wait_for_ingestion: Wait for completion (default: True)
+ - ingestion_timeout: Max seconds to wait (default: 300)
+
+ AWS Auth (uses BaseAWSLLM):
+ - aws_access_key_id, aws_secret_access_key, aws_session_token
+ - aws_region_name (default: us-west-2)
+ - aws_role_name, aws_session_name, aws_profile_name
+ - aws_web_identity_token, aws_sts_endpoint, aws_external_id
+ """
+
+ def __init__(
+ self,
+ ingest_options: "RAGIngestOptions",
+ router: Optional["Router"] = None,
+ ):
+ BaseRAGIngestion.__init__(self, ingest_options=ingest_options, router=router)
+ BaseAWSLLM.__init__(self)
+
+ # Use vector_store_id as unified param (maps to knowledge_base_id)
+ self.knowledge_base_id = self.vector_store_config.get(
+ "vector_store_id"
+ ) or self.vector_store_config.get("knowledge_base_id")
+
+ # Optional config
+ self._data_source_id = self.vector_store_config.get("data_source_id")
+ self._s3_bucket = self.vector_store_config.get("s3_bucket")
+ self._s3_prefix: Optional[str] = str(self.vector_store_config.get("s3_prefix")) if self.vector_store_config.get("s3_prefix") else None
+ self.embedding_model = self.vector_store_config.get(
+ "embedding_model"
+ ) or "amazon.titan-embed-text-v2:0"
+
+ self.wait_for_ingestion = self.vector_store_config.get("wait_for_ingestion", False)
+ self.ingestion_timeout: int = _get_int(self.vector_store_config.get("ingestion_timeout"), 300)
+
+ # Get AWS region using BaseAWSLLM method
+ _aws_region = self.vector_store_config.get("aws_region_name")
+ self.aws_region_name = self.get_aws_region_name_for_non_llm_api_calls(
+ aws_region_name=str(_aws_region) if _aws_region else None
+ )
+
+ # Will be set during initialization
+ self.data_source_id: Optional[str] = None
+ self.s3_bucket: Optional[str] = None
+ self.s3_prefix: str = self._s3_prefix or "data/"
+ self._config_initialized = False
+
+ # Track resources we create (for cleanup if needed)
+ self._created_resources: Dict[str, Any] = {}
+
+ def _ensure_config_initialized(self):
+ """Lazily initialize KB config - either detect from existing or create new."""
+ if self._config_initialized:
+ return
+
+ if self.knowledge_base_id:
+ # Use existing KB - auto-detect data source and S3 bucket
+ self._auto_detect_config()
+ else:
+ # No KB provided - create everything from scratch
+ self._create_knowledge_base_infrastructure()
+
+ self._config_initialized = True
+
+ def _auto_detect_config(self):
+ """Auto-detect data source ID and S3 bucket from existing Knowledge Base."""
+ verbose_logger.debug(
+ f"Auto-detecting data source and S3 bucket for KB={self.knowledge_base_id}"
+ )
+
+ bedrock_agent = self._get_boto3_client("bedrock-agent")
+
+ # List data sources for this KB
+ ds_response = bedrock_agent.list_data_sources(
+ knowledgeBaseId=self.knowledge_base_id
+ )
+ data_sources = ds_response.get("dataSourceSummaries", [])
+
+ if not data_sources:
+ raise ValueError(
+ f"No data sources found for Knowledge Base {self.knowledge_base_id}. "
+ "Please create a data source first or provide data_source_id and s3_bucket."
+ )
+
+ # Use first data source (or user-provided override)
+ if self._data_source_id:
+ self.data_source_id = self._data_source_id
+ else:
+ self.data_source_id = data_sources[0]["dataSourceId"]
+ verbose_logger.info(f"Auto-detected data source: {self.data_source_id}")
+
+ # Get data source details for S3 bucket
+ ds_details = bedrock_agent.get_data_source(
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceId=self.data_source_id,
+ )
+
+ s3_config = (
+ ds_details.get("dataSource", {})
+ .get("dataSourceConfiguration", {})
+ .get("s3Configuration", {})
+ )
+
+ bucket_arn = s3_config.get("bucketArn", "")
+ if bucket_arn:
+ # Extract bucket name from ARN: arn:aws:s3:::bucket-name
+ self.s3_bucket = self._s3_bucket or bucket_arn.split(":")[-1]
+ verbose_logger.info(f"Auto-detected S3 bucket: {self.s3_bucket}")
+
+ # Use inclusion prefix if available
+ prefixes = s3_config.get("inclusionPrefixes", [])
+ if prefixes and not self._s3_prefix:
+ self.s3_prefix = prefixes[0]
+ else:
+ if not self._s3_bucket:
+ raise ValueError(
+ f"Could not auto-detect S3 bucket for data source {self.data_source_id}. "
+ "Please provide s3_bucket in config."
+ )
+ self.s3_bucket = self._s3_bucket
+
+ def _create_knowledge_base_infrastructure(self):
+ """Create all AWS resources needed for a new Knowledge Base."""
+ verbose_logger.info("Creating new Bedrock Knowledge Base infrastructure...")
+
+ # Generate unique names
+ unique_id = uuid.uuid4().hex[:8]
+ kb_name = self.ingest_name or f"litellm-kb-{unique_id}"
+
+ # Get AWS account ID
+ sts = self._get_boto3_client("sts")
+ account_id = sts.get_caller_identity()["Account"]
+
+ # Step 1: Create S3 bucket (if not provided)
+ self.s3_bucket = self._s3_bucket or self._create_s3_bucket(unique_id)
+
+ # Step 2: Create OpenSearch Serverless collection
+ collection_name, collection_arn = self._create_opensearch_collection(
+ unique_id, account_id
+ )
+
+ # Step 3: Create OpenSearch index
+ self._create_opensearch_index(collection_name)
+
+ # Step 4: Create IAM role for Bedrock
+ role_arn = self._create_bedrock_role(unique_id, account_id, collection_arn)
+
+ # Step 5: Create Knowledge Base
+ self.knowledge_base_id = self._create_knowledge_base(
+ kb_name, role_arn, collection_arn
+ )
+
+ # Step 6: Create Data Source
+ self.data_source_id = self._create_data_source(kb_name)
+
+ verbose_logger.info(
+ f"Created KB infrastructure: kb_id={self.knowledge_base_id}, "
+ f"ds_id={self.data_source_id}, bucket={self.s3_bucket}"
+ )
+
+ def _create_s3_bucket(self, unique_id: str) -> str:
+ """Create S3 bucket for KB data source."""
+ s3 = self._get_boto3_client("s3")
+ bucket_name = f"litellm-kb-{unique_id}"
+
+ verbose_logger.debug(f"Creating S3 bucket: {bucket_name}")
+
+ create_params: Dict[str, Any] = {"Bucket": bucket_name}
+ if self.aws_region_name != "us-east-1":
+ create_params["CreateBucketConfiguration"] = {
+ "LocationConstraint": self.aws_region_name
+ }
+
+ s3.create_bucket(**create_params)
+ self._created_resources["s3_bucket"] = bucket_name
+
+ verbose_logger.info(f"Created S3 bucket: {bucket_name}")
+ return bucket_name
+
+ def _create_opensearch_collection(
+ self, unique_id: str, account_id: str
+ ) -> Tuple[str, str]:
+ """Create OpenSearch Serverless collection for vector storage."""
+ oss = self._get_boto3_client("opensearchserverless")
+ collection_name = f"litellm-kb-{unique_id}"
+
+ verbose_logger.debug(f"Creating OpenSearch Serverless collection: {collection_name}")
+
+ # Create encryption policy
+ oss.create_security_policy(
+ name=f"{collection_name}-enc",
+ type="encryption",
+ policy=json.dumps({
+ "Rules": [{"ResourceType": "collection", "Resource": [f"collection/{collection_name}"]}],
+ "AWSOwnedKey": True,
+ }),
+ )
+
+ # Create network policy (public access for simplicity)
+ oss.create_security_policy(
+ name=f"{collection_name}-net",
+ type="network",
+ policy=json.dumps([{
+ "Rules": [{"ResourceType": "collection", "Resource": [f"collection/{collection_name}"]},
+ {"ResourceType": "dashboard", "Resource": [f"collection/{collection_name}"]}],
+ "AllowFromPublic": True,
+ }]),
+ )
+
+ # Create data access policy
+ oss.create_access_policy(
+ name=f"{collection_name}-access",
+ type="data",
+ policy=json.dumps([{
+ "Rules": [
+ {"ResourceType": "index", "Resource": [f"index/{collection_name}/*"], "Permission": ["aoss:*"]},
+ {"ResourceType": "collection", "Resource": [f"collection/{collection_name}"], "Permission": ["aoss:*"]},
+ ],
+ "Principal": [f"arn:aws:iam::{account_id}:root"],
+ }]),
+ )
+
+ # Create collection
+ response = oss.create_collection(
+ name=collection_name,
+ type="VECTORSEARCH",
+ )
+ collection_id = response["createCollectionDetail"]["id"]
+ self._created_resources["opensearch_collection"] = collection_name
+
+ # Wait for collection to be active
+ verbose_logger.debug("Waiting for OpenSearch collection to be active...")
+ for _ in range(60): # 5 min timeout
+ status_response = oss.batch_get_collection(ids=[collection_id])
+ status = status_response["collectionDetails"][0]["status"]
+ if status == "ACTIVE":
+ break
+ time.sleep(5)
+ else:
+ raise TimeoutError("OpenSearch collection did not become active in time")
+
+ collection_arn = status_response["collectionDetails"][0]["arn"]
+ verbose_logger.info(f"Created OpenSearch collection: {collection_name}")
+
+ return collection_name, collection_arn
+
+ def _create_opensearch_index(self, collection_name: str):
+ """Create vector index in OpenSearch collection."""
+ from opensearchpy import OpenSearch, RequestsHttpConnection
+ from requests_aws4auth import AWS4Auth
+
+ # Get credentials for signing
+ credentials = self.get_credentials(
+ aws_access_key_id=_get_str_or_none(self.vector_store_config.get("aws_access_key_id")),
+ aws_secret_access_key=_get_str_or_none(self.vector_store_config.get("aws_secret_access_key")),
+ aws_session_token=_get_str_or_none(self.vector_store_config.get("aws_session_token")),
+ aws_region_name=self.aws_region_name,
+ )
+
+ # Get collection endpoint
+ oss = self._get_boto3_client("opensearchserverless")
+ collections = oss.batch_get_collection(names=[collection_name])
+ endpoint = collections["collectionDetails"][0]["collectionEndpoint"]
+ host = endpoint.replace("https://", "")
+
+ auth = AWS4Auth(
+ credentials.access_key,
+ credentials.secret_key,
+ self.aws_region_name,
+ "aoss",
+ session_token=credentials.token,
+ )
+
+ client = OpenSearch(
+ hosts=[{"host": host, "port": 443}],
+ http_auth=auth,
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ )
+
+ index_name = "bedrock-kb-index"
+ index_body = {
+ "settings": {
+ "index": {"knn": True, "knn.algo_param.ef_search": 512}
+ },
+ "mappings": {
+ "properties": {
+ "bedrock-knowledge-base-default-vector": {
+ "type": "knn_vector",
+ "dimension": 1024,
+ "method": {"engine": "faiss", "name": "hnsw", "space_type": "l2"},
+ },
+ "AMAZON_BEDROCK_METADATA": {"type": "text", "index": False},
+ "AMAZON_BEDROCK_TEXT_CHUNK": {"type": "text"},
+ }
+ },
+ }
+
+ client.indices.create(index=index_name, body=index_body)
+ verbose_logger.info(f"Created OpenSearch index: {index_name}")
+
+ def _create_bedrock_role(
+ self, unique_id: str, account_id: str, collection_arn: str
+ ) -> str:
+ """Create IAM role for Bedrock KB."""
+ iam = self._get_boto3_client("iam")
+ role_name = f"litellm-bedrock-kb-{unique_id}"
+
+ verbose_logger.debug(f"Creating IAM role: {role_name}")
+
+ trust_policy = {
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": {"Service": "bedrock.amazonaws.com"},
+ "Action": "sts:AssumeRole",
+ "Condition": {
+ "StringEquals": {"aws:SourceAccount": account_id},
+ "ArnLike": {"aws:SourceArn": f"arn:aws:bedrock:{self.aws_region_name}:{account_id}:knowledge-base/*"},
+ },
+ }],
+ }
+
+ response = iam.create_role(
+ RoleName=role_name,
+ AssumeRolePolicyDocument=json.dumps(trust_policy),
+ )
+ role_arn = response["Role"]["Arn"]
+ self._created_resources["iam_role"] = role_name
+
+ # Attach permissions policy
+ permissions_policy = {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": ["bedrock:InvokeModel"],
+ "Resource": [f"arn:aws:bedrock:{self.aws_region_name}::foundation-model/{self.embedding_model}"],
+ },
+ {
+ "Effect": "Allow",
+ "Action": ["aoss:APIAccessAll"],
+ "Resource": [collection_arn],
+ },
+ {
+ "Effect": "Allow",
+ "Action": ["s3:GetObject", "s3:ListBucket"],
+ "Resource": [f"arn:aws:s3:::{self.s3_bucket}", f"arn:aws:s3:::{self.s3_bucket}/*"],
+ },
+ ],
+ }
+
+ iam.put_role_policy(
+ RoleName=role_name,
+ PolicyName=f"{role_name}-policy",
+ PolicyDocument=json.dumps(permissions_policy),
+ )
+
+ # Wait for role to propagate
+ time.sleep(10)
+
+ verbose_logger.info(f"Created IAM role: {role_arn}")
+ return role_arn
+
+ def _create_knowledge_base(
+ self, kb_name: str, role_arn: str, collection_arn: str
+ ) -> str:
+ """Create Bedrock Knowledge Base."""
+ bedrock_agent = self._get_boto3_client("bedrock-agent")
+
+ verbose_logger.debug(f"Creating Knowledge Base: {kb_name}")
+
+ response = bedrock_agent.create_knowledge_base(
+ name=kb_name,
+ roleArn=role_arn,
+ knowledgeBaseConfiguration={
+ "type": "VECTOR",
+ "vectorKnowledgeBaseConfiguration": {
+ "embeddingModelArn": f"arn:aws:bedrock:{self.aws_region_name}::foundation-model/{self.embedding_model}",
+ },
+ },
+ storageConfiguration={
+ "type": "OPENSEARCH_SERVERLESS",
+ "opensearchServerlessConfiguration": {
+ "collectionArn": collection_arn,
+ "fieldMapping": {
+ "metadataField": "AMAZON_BEDROCK_METADATA",
+ "textField": "AMAZON_BEDROCK_TEXT_CHUNK",
+ "vectorField": "bedrock-knowledge-base-default-vector",
+ },
+ "vectorIndexName": "bedrock-kb-index",
+ },
+ },
+ )
+ kb_id = response["knowledgeBase"]["knowledgeBaseId"]
+ self._created_resources["knowledge_base"] = kb_id
+
+ # Wait for KB to be active
+ verbose_logger.debug("Waiting for Knowledge Base to be active...")
+ for _ in range(30):
+ kb_status = bedrock_agent.get_knowledge_base(knowledgeBaseId=kb_id)
+ status = kb_status["knowledgeBase"]["status"]
+ if status == "ACTIVE":
+ break
+ time.sleep(2)
+ else:
+ raise TimeoutError("Knowledge Base did not become active in time")
+
+ verbose_logger.info(f"Created Knowledge Base: {kb_id}")
+ return kb_id
+
+ def _create_data_source(self, kb_name: str) -> str:
+ """Create Data Source for the Knowledge Base."""
+ bedrock_agent = self._get_boto3_client("bedrock-agent")
+
+ verbose_logger.debug(f"Creating Data Source for KB: {self.knowledge_base_id}")
+
+ response = bedrock_agent.create_data_source(
+ knowledgeBaseId=self.knowledge_base_id,
+ name=f"{kb_name}-s3-source",
+ dataSourceConfiguration={
+ "type": "S3",
+ "s3Configuration": {
+ "bucketArn": f"arn:aws:s3:::{self.s3_bucket}",
+ "inclusionPrefixes": [self.s3_prefix],
+ },
+ },
+ )
+ ds_id = response["dataSource"]["dataSourceId"]
+ self._created_resources["data_source"] = ds_id
+
+ verbose_logger.info(f"Created Data Source: {ds_id}")
+ return ds_id
+
+ def _get_boto3_client(self, service_name: str):
+ """Get a boto3 client for the specified service using BaseAWSLLM auth."""
+ try:
+ import boto3
+ except ImportError:
+ raise ImportError("boto3 is required for Bedrock ingestion. Install with: pip install boto3")
+
+ # Get credentials using BaseAWSLLM's get_credentials method
+ credentials = self.get_credentials(
+ aws_access_key_id=_get_str_or_none(self.vector_store_config.get("aws_access_key_id")),
+ aws_secret_access_key=_get_str_or_none(self.vector_store_config.get("aws_secret_access_key")),
+ aws_session_token=_get_str_or_none(self.vector_store_config.get("aws_session_token")),
+ aws_region_name=self.aws_region_name,
+ aws_session_name=_get_str_or_none(self.vector_store_config.get("aws_session_name")),
+ aws_profile_name=_get_str_or_none(self.vector_store_config.get("aws_profile_name")),
+ aws_role_name=_get_str_or_none(self.vector_store_config.get("aws_role_name")),
+ aws_web_identity_token=_get_str_or_none(self.vector_store_config.get("aws_web_identity_token")),
+ aws_sts_endpoint=_get_str_or_none(self.vector_store_config.get("aws_sts_endpoint")),
+ aws_external_id=_get_str_or_none(self.vector_store_config.get("aws_external_id")),
+ )
+
+ # Create session with credentials
+ session = boto3.Session(
+ aws_access_key_id=credentials.access_key,
+ aws_secret_access_key=credentials.secret_key,
+ aws_session_token=credentials.token,
+ region_name=self.aws_region_name,
+ )
+
+ return session.client(service_name)
+
+ async def embed(
+ self,
+ chunks: List[str],
+ ) -> Optional[List[List[float]]]:
+ """
+ Bedrock handles embedding internally - skip this step.
+
+ Returns:
+ None (Bedrock embeds when files are ingested)
+ """
+ return None
+
+ async def store(
+ self,
+ file_content: Optional[bytes],
+ filename: Optional[str],
+ content_type: Optional[str],
+ chunks: List[str],
+ embeddings: Optional[List[List[float]]],
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """
+ Store content in Bedrock Knowledge Base.
+
+ Bedrock workflow:
+ 1. Auto-detect data source and S3 bucket (if not provided)
+ 2. Upload file to S3 bucket
+ 3. Start ingestion job
+ 4. (Optional) Wait for ingestion to complete
+
+ Args:
+ file_content: Raw file bytes
+ filename: Name of the file
+ content_type: MIME type
+ chunks: Ignored - Bedrock handles chunking
+ embeddings: Ignored - Bedrock handles embedding
+
+ Returns:
+ Tuple of (knowledge_base_id, file_key)
+ """
+ # Auto-detect data source and S3 bucket if needed
+ self._ensure_config_initialized()
+
+ if not file_content or not filename:
+ verbose_logger.warning("No file content or filename provided for Bedrock ingestion")
+ return _get_str_or_none(self.knowledge_base_id), None
+
+ # Step 1: Upload file to S3
+ s3_client = self._get_boto3_client("s3")
+ s3_key = f"{self.s3_prefix.rstrip('/')}/{filename}"
+
+ verbose_logger.debug(f"Uploading file to s3://{self.s3_bucket}/{s3_key}")
+ s3_client.put_object(
+ Bucket=self.s3_bucket,
+ Key=s3_key,
+ Body=file_content,
+ ContentType=content_type or "application/octet-stream",
+ )
+ verbose_logger.info(f"Uploaded file to s3://{self.s3_bucket}/{s3_key}")
+
+ # Step 2: Start ingestion job
+ bedrock_agent = self._get_boto3_client("bedrock-agent")
+
+ verbose_logger.debug(
+ f"Starting ingestion job for KB={self.knowledge_base_id}, DS={self.data_source_id}"
+ )
+ ingestion_response = bedrock_agent.start_ingestion_job(
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceId=self.data_source_id,
+ )
+ job_id = ingestion_response["ingestionJob"]["ingestionJobId"]
+ verbose_logger.info(f"Started ingestion job: {job_id}")
+
+ # Step 3: Wait for ingestion (optional)
+ if self.wait_for_ingestion:
+ start_time = time.time()
+ while time.time() - start_time < self.ingestion_timeout:
+ job_status = bedrock_agent.get_ingestion_job(
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceId=self.data_source_id,
+ ingestionJobId=job_id,
+ )
+ status = job_status["ingestionJob"]["status"]
+ verbose_logger.debug(f"Ingestion job {job_id} status: {status}")
+
+ if status == "COMPLETE":
+ stats = job_status["ingestionJob"].get("statistics", {})
+ verbose_logger.info(
+ f"Ingestion complete: {stats.get('numberOfNewDocumentsIndexed', 0)} docs indexed"
+ )
+ break
+ elif status == "FAILED":
+ failure_reasons = job_status["ingestionJob"].get("failureReasons", [])
+ verbose_logger.error(f"Ingestion failed: {failure_reasons}")
+ break
+ elif status in ("STARTING", "IN_PROGRESS"):
+ time.sleep(2)
+ else:
+ verbose_logger.warning(f"Unknown ingestion status: {status}")
+ break
+
+ return str(self.knowledge_base_id) if self.knowledge_base_id else None, s3_key
+
diff --git a/litellm/rag/ingestion/openai_ingestion.py b/litellm/rag/ingestion/openai_ingestion.py
new file mode 100644
index 00000000000..034ad38d466
--- /dev/null
+++ b/litellm/rag/ingestion/openai_ingestion.py
@@ -0,0 +1,111 @@
+"""
+OpenAI-specific RAG Ingestion implementation.
+
+OpenAI handles embedding internally when files are attached to vector stores,
+so this implementation skips the embedding step and directly uploads files.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast
+
+import litellm
+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion
+from litellm.vector_store_files.main import acreate as vector_store_file_acreate
+from litellm.vector_stores.main import acreate as vector_store_acreate
+
+if TYPE_CHECKING:
+ from litellm import Router
+ from litellm.types.rag import RAGIngestOptions
+
+
+class OpenAIRAGIngestion(BaseRAGIngestion):
+ """
+ OpenAI-specific RAG ingestion.
+
+ Key differences from base:
+ - Embedding is handled by OpenAI when attaching files to vector stores
+ - Files are uploaded and attached to vector stores directly
+ - Chunking is done by OpenAI's vector store (uses 'auto' strategy)
+ """
+
+ def __init__(
+ self,
+ ingest_options: "RAGIngestOptions",
+ router: Optional["Router"] = None,
+ ):
+ super().__init__(ingest_options=ingest_options, router=router)
+
+ async def embed(
+ self,
+ chunks: List[str],
+ ) -> Optional[List[List[float]]]:
+ """
+ OpenAI handles embedding internally - skip this step.
+
+ Returns:
+ None (OpenAI embeds when files are attached to vector store)
+ """
+ # OpenAI handles embedding when files are attached to vector stores
+ return None
+
+ async def store(
+ self,
+ file_content: Optional[bytes],
+ filename: Optional[str],
+ content_type: Optional[str],
+ chunks: List[str],
+ embeddings: Optional[List[List[float]]],
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """
+ Store content in OpenAI vector store.
+
+ OpenAI workflow:
+ 1. Create vector store (if not provided)
+ 2. Upload file to OpenAI
+ 3. Attach file to vector store (OpenAI handles chunking/embedding)
+
+ Args:
+ file_content: Raw file bytes
+ filename: Name of the file
+ content_type: MIME type
+ chunks: Ignored - OpenAI handles chunking
+ embeddings: Ignored - OpenAI handles embedding
+
+ Returns:
+ Tuple of (vector_store_id, file_id)
+ """
+ vector_store_id = self.vector_store_config.get("vector_store_id")
+ ttl_days = self.vector_store_config.get("ttl_days")
+
+ # Create vector store if not provided
+ if not vector_store_id:
+ expires_after = {"anchor": "last_active_at", "days": ttl_days} if ttl_days else None
+ create_response = await vector_store_acreate(
+ name=self.ingest_name or "litellm-rag-ingest",
+ custom_llm_provider="openai",
+ expires_after=expires_after,
+ )
+ vector_store_id = create_response.get("id")
+
+ # Upload file and attach to vector store
+ result_file_id = None
+ if file_content and filename and vector_store_id:
+ # Upload file to OpenAI
+ file_response = await litellm.acreate_file(
+ file=(filename, file_content, content_type or "application/octet-stream"),
+ purpose="assistants",
+ custom_llm_provider="openai",
+ )
+ result_file_id = file_response.id
+
+ # Attach file to vector store (OpenAI handles chunking/embedding)
+ await vector_store_file_acreate(
+ vector_store_id=vector_store_id,
+ file_id=result_file_id,
+ custom_llm_provider="openai",
+ chunking_strategy=cast(Optional[Dict[str, Any]], self.chunking_strategy),
+ )
+
+ return vector_store_id, result_file_id
+
diff --git a/litellm/rag/main.py b/litellm/rag/main.py
new file mode 100644
index 00000000000..c88a7339dc6
--- /dev/null
+++ b/litellm/rag/main.py
@@ -0,0 +1,240 @@
+"""
+RAG Ingest API for LiteLLM.
+
+Provides an all-in-one API for document ingestion:
+Upload -> (OCR) -> Chunk -> Embed -> Vector Store
+"""
+
+from __future__ import annotations
+
+__all__ = ["ingest", "aingest"]
+
+import asyncio
+import contextvars
+from functools import partial
+from typing import TYPE_CHECKING, Any, Coroutine, Dict, Optional, Tuple, Type, Union
+
+import httpx
+
+import litellm
+from litellm.rag.ingestion.base_ingestion import BaseRAGIngestion
+from litellm.rag.ingestion.bedrock_ingestion import BedrockRAGIngestion
+from litellm.rag.ingestion.openai_ingestion import OpenAIRAGIngestion
+from litellm.types.rag import RAGIngestOptions, RAGIngestResponse
+from litellm.utils import client
+
+if TYPE_CHECKING:
+ from litellm import Router
+
+
+# Registry of provider-specific ingestion classes
+INGESTION_REGISTRY: Dict[str, Type[BaseRAGIngestion]] = {
+ "openai": OpenAIRAGIngestion,
+ "bedrock": BedrockRAGIngestion,
+}
+
+
+def get_ingestion_class(provider: str) -> Type[BaseRAGIngestion]:
+ """
+ Get the ingestion class for a given provider.
+
+ Args:
+ provider: The vector store provider name (e.g., 'openai')
+
+ Returns:
+ The ingestion class for the provider
+
+ Raises:
+ ValueError: If provider is not supported
+ """
+ ingestion_class = INGESTION_REGISTRY.get(provider)
+ if ingestion_class is None:
+ supported = ", ".join(INGESTION_REGISTRY.keys())
+ raise ValueError(
+ f"Provider '{provider}' is not supported for RAG ingestion. "
+ f"Supported providers: {supported}"
+ )
+ return ingestion_class
+
+
+async def _execute_ingest_pipeline(
+ ingest_options: RAGIngestOptions,
+ file_data: Optional[Tuple[str, bytes, str]] = None,
+ file_url: Optional[str] = None,
+ file_id: Optional[str] = None,
+ router: Optional["Router"] = None,
+) -> RAGIngestResponse:
+ """
+ Execute the RAG ingest pipeline using provider-specific implementation.
+
+ Args:
+ ingest_options: Configuration for the ingest pipeline
+ file_data: Tuple of (filename, content_bytes, content_type)
+ file_url: URL to fetch file from
+ file_id: Existing file ID to use
+ router: Optional LiteLLM router for load balancing
+
+ Returns:
+ RAGIngestResponse with status and IDs
+ """
+ # Get provider from vector store config
+ vector_store_config = ingest_options.get("vector_store") or {}
+ provider = vector_store_config.get("custom_llm_provider", "openai")
+
+ # Get provider-specific ingestion class
+ ingestion_class = get_ingestion_class(provider)
+
+ # Create ingestion instance
+ ingestion = ingestion_class(
+ ingest_options=ingest_options,
+ router=router,
+ )
+
+ # Execute ingestion pipeline
+ return await ingestion.ingest(
+ file_data=file_data,
+ file_url=file_url,
+ file_id=file_id,
+ )
+
+
+####### PUBLIC API ###################
+
+
+@client
+async def aingest(
+ ingest_options: Dict[str, Any],
+ file_data: Optional[Tuple[str, bytes, str]] = None,
+ file: Optional[Dict[str, str]] = None,
+ file_url: Optional[str] = None,
+ file_id: Optional[str] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ **kwargs,
+) -> RAGIngestResponse:
+ """
+ Async: Ingest a document into a vector store.
+
+ Args:
+ ingest_options: Configuration for the ingest pipeline
+ file_data: Tuple of (filename, content_bytes, content_type)
+ file: Dict with {filename, content (base64), content_type} - for JSON API
+ file_url: URL to fetch file from
+ file_id: Existing file ID to use
+
+ Example:
+ ```python
+ response = await litellm.aingest(
+ ingest_options={
+ "vector_store": {"custom_llm_provider": "openai"}
+ },
+ file_url="https://example.com/doc.pdf",
+ )
+ ```
+ """
+ local_vars = locals()
+ try:
+ loop = asyncio.get_event_loop()
+ kwargs["aingest"] = True
+
+ func = partial(
+ ingest,
+ ingest_options=ingest_options,
+ file_data=file_data,
+ file=file,
+ file_url=file_url,
+ file_id=file_id,
+ timeout=timeout,
+ **kwargs,
+ )
+
+ ctx = contextvars.copy_context()
+ func_with_context = partial(ctx.run, func)
+ init_response = await loop.run_in_executor(None, func_with_context)
+
+ if asyncio.iscoroutine(init_response):
+ response = await init_response
+ else:
+ response = init_response
+
+ return response
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=ingest_options.get("vector_store", {}).get("custom_llm_provider"),
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
+
+
+@client
+def ingest(
+ ingest_options: Dict[str, Any],
+ file_data: Optional[Tuple[str, bytes, str]] = None,
+ file: Optional[Dict[str, str]] = None,
+ file_url: Optional[str] = None,
+ file_id: Optional[str] = None,
+ timeout: Optional[Union[float, httpx.Timeout]] = None,
+ **kwargs,
+) -> Union[RAGIngestResponse, Coroutine[Any, Any, RAGIngestResponse]]:
+ """
+ Ingest a document into a vector store.
+
+ Args:
+ ingest_options: Configuration for the ingest pipeline
+ file_data: Tuple of (filename, content_bytes, content_type)
+ file: Dict with {filename, content (base64), content_type} - for JSON API
+ file_url: URL to fetch file from
+ file_id: Existing file ID to use
+
+ Example:
+ ```python
+ response = litellm.ingest(
+ ingest_options={
+ "vector_store": {"custom_llm_provider": "openai"}
+ },
+ file_data=("doc.txt", b"Hello world", "text/plain"),
+ )
+ ```
+ """
+ import base64
+
+ local_vars = locals()
+ try:
+ _is_async = kwargs.pop("aingest", False) is True
+ router: Optional["Router"] = kwargs.get("router")
+
+ # Convert file dict to file_data tuple if provided
+ if file is not None and file_data is None:
+ filename = file.get("filename", "document")
+ content_b64 = file.get("content", "")
+ content_type = file.get("content_type", "application/octet-stream")
+ content_bytes = base64.b64decode(content_b64)
+ file_data = (filename, content_bytes, content_type)
+
+ if _is_async:
+ return _execute_ingest_pipeline(
+ ingest_options=ingest_options, # type: ignore
+ file_data=file_data,
+ file_url=file_url,
+ file_id=file_id,
+ router=router,
+ )
+ else:
+ return asyncio.get_event_loop().run_until_complete(
+ _execute_ingest_pipeline(
+ ingest_options=ingest_options, # type: ignore
+ file_data=file_data,
+ file_url=file_url,
+ file_id=file_id,
+ router=router,
+ )
+ )
+ except Exception as e:
+ raise litellm.exception_type(
+ model=None,
+ custom_llm_provider=ingest_options.get("vector_store", {}).get("custom_llm_provider"),
+ original_exception=e,
+ completion_kwargs=local_vars,
+ extra_kwargs=kwargs,
+ )
diff --git a/litellm/rag/text_splitters/__init__.py b/litellm/rag/text_splitters/__init__.py
new file mode 100644
index 00000000000..04802b438c7
--- /dev/null
+++ b/litellm/rag/text_splitters/__init__.py
@@ -0,0 +1,10 @@
+"""
+Text splitting utilities for RAG ingestion.
+"""
+
+from litellm.rag.text_splitters.recursive_character_text_splitter import (
+ RecursiveCharacterTextSplitter,
+)
+
+__all__ = ["RecursiveCharacterTextSplitter"]
+
diff --git a/litellm/rag/text_splitters/recursive_character_text_splitter.py b/litellm/rag/text_splitters/recursive_character_text_splitter.py
new file mode 100644
index 00000000000..2107b1f0683
--- /dev/null
+++ b/litellm/rag/text_splitters/recursive_character_text_splitter.py
@@ -0,0 +1,135 @@
+"""
+RecursiveCharacterTextSplitter for RAG ingestion.
+
+A simple implementation that splits text recursively by different separators.
+"""
+
+from typing import List, Optional
+
+from litellm.constants import DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE
+
+
+class RecursiveCharacterTextSplitter:
+ """
+ Split text recursively by different separators.
+
+ Tries to split by the first separator, then recursively splits
+ by subsequent separators if chunks are still too large.
+ """
+
+ def __init__(
+ self,
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
+ chunk_overlap: int = DEFAULT_CHUNK_OVERLAP,
+ separators: Optional[List[str]] = None,
+ ):
+ self.chunk_size = chunk_size
+ self.chunk_overlap = chunk_overlap
+ self.separators = separators or ["\n\n", "\n", " ", ""]
+
+ def split_text(self, text: str) -> List[str]:
+ """Split text into chunks."""
+ return self._split_text(text, self.separators)
+
+ def _split_text(self, text: str, separators: List[str], depth: int = 0) -> List[str]:
+ """Recursively split text using separators."""
+ from litellm.constants import DEFAULT_MAX_RECURSE_DEPTH
+
+ if depth > DEFAULT_MAX_RECURSE_DEPTH:
+ # Max depth reached, return text as-is split into chunk_size pieces
+ return [text[i:i + self.chunk_size] for i in range(0, len(text), self.chunk_size)]
+
+ final_chunks: List[str] = []
+
+ # Get the appropriate separator
+ separator = separators[-1]
+ new_separators: List[str] = []
+
+ for i, sep in enumerate(separators):
+ if sep == "":
+ separator = sep
+ break
+ if sep in text:
+ separator = sep
+ new_separators = separators[i + 1 :]
+ break
+
+ # Split by the chosen separator
+ if separator:
+ splits = text.split(separator)
+ else:
+ splits = list(text)
+
+ # Merge splits into chunks
+ good_splits: List[str] = []
+ for split in splits:
+ if len(split) < self.chunk_size:
+ good_splits.append(split)
+ else:
+ # Chunk is too big, merge what we have and recurse
+ if good_splits:
+ merged = self._merge_splits(good_splits, separator)
+ final_chunks.extend(merged)
+ good_splits = []
+
+ if new_separators:
+ # Recursively split with finer separators
+ other_chunks = self._split_text(split, new_separators, depth + 1)
+ final_chunks.extend(other_chunks)
+ else:
+ # No more separators, force split
+ final_chunks.extend(self._force_split(split))
+
+ # Merge remaining good splits
+ if good_splits:
+ merged = self._merge_splits(good_splits, separator)
+ final_chunks.extend(merged)
+
+ return final_chunks
+
+ def _merge_splits(self, splits: List[str], separator: str) -> List[str]:
+ """Merge splits into chunks respecting chunk_size and chunk_overlap."""
+ chunks: List[str] = []
+ current_chunk: List[str] = []
+ current_length = 0
+
+ for split in splits:
+ split_len = len(split)
+ sep_len = len(separator) if current_chunk else 0
+
+ if current_length + split_len + sep_len > self.chunk_size:
+ if current_chunk:
+ chunk_text = separator.join(current_chunk).strip()
+ if chunk_text:
+ chunks.append(chunk_text)
+
+ # Handle overlap
+ while current_length > self.chunk_overlap and len(current_chunk) > 1:
+ removed = current_chunk.pop(0)
+ current_length -= len(removed) + len(separator)
+
+ current_chunk.append(split)
+ current_length += split_len + sep_len
+
+ # Add remaining
+ if current_chunk:
+ chunk_text = separator.join(current_chunk).strip()
+ if chunk_text:
+ chunks.append(chunk_text)
+
+ return chunks
+
+ def _force_split(self, text: str) -> List[str]:
+ """Force split text by chunk_size when no separator works."""
+ chunks: List[str] = []
+ start = 0
+
+ while start < len(text):
+ end = start + self.chunk_size
+ chunk = text[start:end].strip()
+ if chunk:
+ chunks.append(chunk)
+ start = end - self.chunk_overlap if end < len(text) else len(text)
+
+ return chunks
+
diff --git a/litellm/types/rag.py b/litellm/types/rag.py
new file mode 100644
index 00000000000..252530c7163
--- /dev/null
+++ b/litellm/types/rag.py
@@ -0,0 +1,146 @@
+"""
+Type definitions for RAG (Retrieval Augmented Generation) Ingest API.
+"""
+
+from typing import Any, Dict, List, Literal, Optional, Union
+
+from pydantic import BaseModel
+from typing_extensions import TypedDict
+
+
+class RAGChunkingStrategy(TypedDict, total=False):
+ """
+ Chunking strategy config for RAG ingest using RecursiveCharacterTextSplitter.
+
+ See: https://docs.langchain.com/oss/python/langchain/rag
+ """
+
+ chunk_size: int # Maximum size of chunks (default: 1000)
+ chunk_overlap: int # Overlap between chunks (default: 200)
+ separators: Optional[List[str]] # Custom separators for splitting
+
+
+class RAGIngestOCROptions(TypedDict, total=False):
+ """OCR configuration for RAG ingest pipeline."""
+
+ model: str # e.g., "mistral/mistral-ocr-latest"
+
+
+class RAGIngestEmbeddingOptions(TypedDict, total=False):
+ """Embedding configuration for RAG ingest pipeline."""
+
+ model: str # e.g., "text-embedding-3-small"
+
+
+class OpenAIVectorStoreOptions(TypedDict, total=False):
+ """
+ OpenAI vector store configuration.
+
+ Example (auto-create):
+ {"custom_llm_provider": "openai"}
+
+ Example (use existing):
+ {"custom_llm_provider": "openai", "vector_store_id": "vs_xxx"}
+ """
+
+ custom_llm_provider: Literal["openai"]
+ vector_store_id: Optional[str] # Existing VS ID (auto-creates if not provided)
+ ttl_days: Optional[int] # Time-to-live in days for indexed content
+
+
+class BedrockVectorStoreOptions(TypedDict, total=False):
+ """
+ Bedrock Knowledge Base configuration.
+
+ Example (auto-create KB and all resources):
+ {"custom_llm_provider": "bedrock"}
+
+ Example (use existing KB):
+ {"custom_llm_provider": "bedrock", "vector_store_id": "KB_ID"}
+
+ Auto-creation creates: S3 bucket, OpenSearch Serverless collection,
+ IAM role, Knowledge Base, and Data Source.
+ """
+
+ custom_llm_provider: Literal["bedrock"]
+ vector_store_id: Optional[str] # Existing KB ID (auto-creates if not provided)
+
+ # Bedrock-specific options
+ s3_bucket: Optional[str] # S3 bucket (auto-created if not provided)
+ s3_prefix: Optional[str] # S3 key prefix (default: "data/")
+ embedding_model: Optional[str] # Embedding model (default: amazon.titan-embed-text-v2:0)
+ data_source_id: Optional[str] # For existing KB: override auto-detected DS
+ wait_for_ingestion: Optional[bool] # Wait for completion (default: False - returns immediately)
+ ingestion_timeout: Optional[int] # Timeout in seconds if wait_for_ingestion=True (default: 300)
+
+ # AWS auth (uses BaseAWSLLM)
+ aws_access_key_id: Optional[str]
+ aws_secret_access_key: Optional[str]
+ aws_session_token: Optional[str]
+ aws_region_name: Optional[str] # default: us-west-2
+ aws_role_name: Optional[str]
+ aws_session_name: Optional[str]
+ aws_profile_name: Optional[str]
+ aws_web_identity_token: Optional[str]
+ aws_sts_endpoint: Optional[str]
+ aws_external_id: Optional[str]
+
+
+# Union type for vector store options
+RAGIngestVectorStoreOptions = Union[OpenAIVectorStoreOptions, BedrockVectorStoreOptions]
+
+
+class RAGIngestOptions(TypedDict, total=False):
+ """
+ Combined options for RAG ingest pipeline.
+
+ Unified interface - just specify custom_llm_provider:
+
+ Example (OpenAI):
+ from litellm.types.rag import RAGIngestOptions, OpenAIVectorStoreOptions
+
+ options: RAGIngestOptions = {
+ "vector_store": OpenAIVectorStoreOptions(
+ custom_llm_provider="openai",
+ vector_store_id="vs_xxx", # optional
+ )
+ }
+
+ Example (Bedrock):
+ from litellm.types.rag import RAGIngestOptions, BedrockVectorStoreOptions
+
+ options: RAGIngestOptions = {
+ "vector_store": BedrockVectorStoreOptions(
+ custom_llm_provider="bedrock",
+ vector_store_id="KB_ID", # optional - auto-creates if not provided
+ wait_for_ingestion=True,
+ )
+ }
+ """
+
+ name: Optional[str] # Optional pipeline name for logging
+ ocr: Optional[RAGIngestOCROptions] # Optional OCR step
+ chunking_strategy: Optional[RAGChunkingStrategy] # RecursiveCharacterTextSplitter args
+ embedding: Optional[RAGIngestEmbeddingOptions] # Embedding model config
+ vector_store: RAGIngestVectorStoreOptions # OpenAI or Bedrock config
+
+class RAGIngestResponse(TypedDict, total=False):
+ """Response from RAG ingest API."""
+
+ id: str # Unique ingest job ID
+ status: Literal["completed", "in_progress", "failed"]
+ vector_store_id: str # The vector store ID (created or existing)
+ file_id: Optional[str] # The file ID in the vector store
+
+
+
+class RAGIngestRequest(BaseModel):
+ """Request body for RAG ingest API (for validation)."""
+
+ file_url: Optional[str] = None # URL to fetch file from
+ file_id: Optional[str] = None # Existing file ID
+ ingest_options: Dict[str, Any] # RAGIngestOptions as dict for flexibility
+
+ class Config:
+ extra = "allow" # Allow additional fields
+
diff --git a/tests/code_coverage_tests/recursive_detector.py b/tests/code_coverage_tests/recursive_detector.py
index cac245f8d5b..c26d1669a81 100644
--- a/tests/code_coverage_tests/recursive_detector.py
+++ b/tests/code_coverage_tests/recursive_detector.py
@@ -32,6 +32,9 @@ IGNORE_FUNCTIONS = [
"_redact_base64", # max depth set.
"_contains_vision_content", # max depth set.
"_read_all_bytes", # max depth set.
+ "_fix_enum_types", # max depth set.
+ "_collect_argument_paths", # max depth set.
+ "_split_text", # max depth set.
]
diff --git a/tests/vector_store_tests/rag/base_rag_tests.py b/tests/vector_store_tests/rag/base_rag_tests.py
new file mode 100644
index 00000000000..55b23e4e897
--- /dev/null
+++ b/tests/vector_store_tests/rag/base_rag_tests.py
@@ -0,0 +1,173 @@
+"""
+Base RAG test class that enforces common tests across all providers.
+
+Providers should inherit from BaseRAGTest and implement the abstract methods.
+"""
+
+import os
+import sys
+import uuid
+from abc import ABC, abstractmethod
+from typing import Any, Dict, Optional
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+from litellm.types.rag import (
+ RAGIngestOptions,
+ OpenAIVectorStoreOptions,
+ BedrockVectorStoreOptions,
+)
+
+
+class BaseRAGTest(ABC):
+ """
+ Abstract base test class for RAG ingestion tests.
+
+ Providers should inherit from this class and implement:
+ - get_base_ingest_options(): Returns provider-specific ingest options
+ - query_vector_store(): Queries the vector store after ingestion
+ """
+
+ @abstractmethod
+ def get_base_ingest_options(self) -> RAGIngestOptions:
+ """
+ Must return the base ingest options for the provider.
+
+ Example for OpenAI:
+ return {
+ "vector_store": OpenAIVectorStoreOptions(
+ custom_llm_provider="openai",
+ )
+ }
+
+ Example for Bedrock:
+ return {
+ "vector_store": BedrockVectorStoreOptions(
+ custom_llm_provider="bedrock",
+ )
+ }
+ """
+ pass
+
+ @abstractmethod
+ async def query_vector_store(
+ self,
+ vector_store_id: str,
+ query: str,
+ ) -> Optional[Dict[str, Any]]:
+ """
+ Query the vector store to verify ingestion.
+
+ Args:
+ vector_store_id: The ID of the vector store to query
+ query: The search query
+
+ Returns:
+ Search results dict or None if no results found
+ """
+ pass
+
+ def get_unique_filename(self, prefix: str = "test") -> str:
+ """Generate a unique filename for test documents."""
+ unique_id = uuid.uuid4().hex[:8]
+ return f"{prefix}_{unique_id}.txt", unique_id
+
+ @pytest.mark.asyncio
+ async def test_basic_ingest(self):
+ """
+ Test basic text file ingestion to vector store.
+ """
+ litellm._turn_on_debug()
+
+ filename, unique_id = self.get_unique_filename("basic_ingest")
+ text_content = f"Test document {unique_id} for RAG ingestion.".encode("utf-8")
+ file_data = (filename, text_content, "text/plain")
+
+ ingest_options = self.get_base_ingest_options()
+ ingest_options["name"] = f"test-basic-ingest-{unique_id}"
+
+ try:
+ response = await litellm.rag.aingest(
+ ingest_options=ingest_options,
+ file_data=file_data,
+ )
+
+ print(f"RAG Ingest Response: {response}")
+
+ assert "id" in response
+ assert response["id"].startswith("ingest_")
+ assert "status" in response
+ assert response["status"] in ["completed", "failed"]
+ assert "vector_store_id" in response
+
+ if response["status"] == "completed":
+ assert response["vector_store_id"]
+ print(f"Vector store ID: {response['vector_store_id']}")
+
+ except litellm.InternalServerError:
+ pytest.skip("Skipping test due to litellm.InternalServerError")
+
+ @pytest.mark.asyncio
+ async def test_ingest_and_query(self):
+ """
+ Test full RAG flow: ingest a document and then query it.
+ """
+ import asyncio
+
+ litellm._turn_on_debug()
+
+ filename, unique_id = self.get_unique_filename("ingest_query")
+ text_content = f"""
+ Test document {unique_id} for RAG ingestion and query.
+ LiteLLM provides a unified interface for 100+ LLMs.
+ This content should be retrievable via semantic search.
+ """.encode("utf-8")
+ file_data = (filename, text_content, "text/plain")
+
+ ingest_options = self.get_base_ingest_options()
+ ingest_options["name"] = f"test-ingest-query-{unique_id}"
+
+ try:
+ # Step 1: Ingest
+ ingest_response = await litellm.rag.aingest(
+ ingest_options=ingest_options,
+ file_data=file_data,
+ )
+
+ print(f"Ingest Response: {ingest_response}")
+ assert ingest_response["status"] == "completed"
+ vector_store_id = ingest_response["vector_store_id"]
+ assert vector_store_id
+
+ # Step 2: Query with retry (indexing may take time)
+ search_results = None
+ max_retries = 10
+ for attempt in range(max_retries):
+ await asyncio.sleep(3)
+
+ search_results = await self.query_vector_store(
+ vector_store_id=vector_store_id,
+ query=f"Test document {unique_id}",
+ )
+
+ if search_results:
+ break
+
+ print(
+ f"Attempt {attempt + 1}/{max_retries}: "
+ "Waiting for document to be indexed..."
+ )
+
+ print(f"Search Results: {search_results}")
+
+ # Validate search results
+ assert search_results is not None, "Document not found after retries"
+
+ print("Query successful!")
+
+ except litellm.InternalServerError:
+ pytest.skip("Skipping test due to litellm.InternalServerError")
+
diff --git a/tests/vector_store_tests/rag/test_document.txt b/tests/vector_store_tests/rag/test_document.txt
new file mode 100644
index 00000000000..3570e715e83
--- /dev/null
+++ b/tests/vector_store_tests/rag/test_document.txt
@@ -0,0 +1,4 @@
+Test document abc123 for RAG ingestion.
+This is a sample document to test the RAG ingest API.
+LiteLLM provides a unified interface for vector stores.
+
diff --git a/tests/vector_store_tests/rag/test_rag_bedrock.py b/tests/vector_store_tests/rag/test_rag_bedrock.py
new file mode 100644
index 00000000000..c991052d325
--- /dev/null
+++ b/tests/vector_store_tests/rag/test_rag_bedrock.py
@@ -0,0 +1,91 @@
+"""
+Bedrock Knowledge Base RAG ingestion tests.
+
+Requires environment variables:
+- AWS_ACCESS_KEY_ID
+- AWS_SECRET_ACCESS_KEY
+- AWS_REGION_NAME (optional, defaults to us-west-2)
+
+Optional (for using existing KB instead of auto-creating):
+- BEDROCK_KNOWLEDGE_BASE_ID
+"""
+
+import os
+import sys
+from typing import Any, Dict, Optional
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+from litellm.types.rag import RAGIngestOptions, BedrockVectorStoreOptions
+from tests.vector_store_tests.rag.base_rag_tests import BaseRAGTest
+
+
+class TestRAGBedrock(BaseRAGTest):
+ """Test RAG Ingest with Bedrock Knowledge Base."""
+
+ @pytest.fixture(autouse=True)
+ def check_env_vars(self):
+ """Check required environment variables before each test."""
+ aws_key = os.environ.get("AWS_ACCESS_KEY_ID")
+ aws_secret = os.environ.get("AWS_SECRET_ACCESS_KEY")
+
+ if not aws_key or not aws_secret:
+ pytest.skip("Skipping Bedrock test: AWS credentials required")
+
+ def get_base_ingest_options(self) -> RAGIngestOptions:
+ """
+ Return Bedrock-specific ingest options.
+
+ Uses unified interface - no vector_store_id means auto-create KB.
+ If BEDROCK_KNOWLEDGE_BASE_ID is set, uses existing KB.
+ """
+ # Use existing KB if provided, otherwise auto-create
+ existing_kb_id = os.environ.get("BEDROCK_KNOWLEDGE_BASE_ID")
+
+ return {
+ "vector_store": BedrockVectorStoreOptions(
+ custom_llm_provider="bedrock",
+ vector_store_id=existing_kb_id, # None = auto-create
+ # wait_for_ingestion defaults to False - returns immediately
+ ),
+ }
+
+ async def query_vector_store(
+ self,
+ vector_store_id: str,
+ query: str,
+ ) -> Optional[Dict[str, Any]]:
+ """Query Bedrock Knowledge Base."""
+ try:
+ import boto3
+ except ImportError:
+ pytest.skip("boto3 required for Bedrock tests")
+
+ session = boto3.Session(
+ aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"),
+ aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"),
+ region_name=os.environ.get("AWS_REGION_NAME", "us-west-2"),
+ )
+ bedrock_agent_runtime = session.client("bedrock-agent-runtime")
+
+ response = bedrock_agent_runtime.retrieve(
+ knowledgeBaseId=vector_store_id,
+ retrievalQuery={"text": query},
+ retrievalConfiguration={
+ "vectorSearchConfiguration": {"numberOfResults": 5}
+ },
+ )
+
+ if response.get("retrievalResults") and len(response["retrievalResults"]) > 0:
+ # Check if query terms appear in results
+ for result in response["retrievalResults"]:
+ # Extract unique_id from query if present
+ if query in result["content"]["text"]:
+ return response
+ # Return results even if exact match not found
+ return response
+ return None
+
diff --git a/tests/vector_store_tests/rag/test_rag_openai.py b/tests/vector_store_tests/rag/test_rag_openai.py
new file mode 100644
index 00000000000..d077ebe0cb6
--- /dev/null
+++ b/tests/vector_store_tests/rag/test_rag_openai.py
@@ -0,0 +1,45 @@
+"""
+OpenAI RAG ingestion tests.
+"""
+
+import os
+import sys
+from typing import Any, Dict, Optional
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+from litellm.types.rag import RAGIngestOptions, OpenAIVectorStoreOptions
+from tests.vector_store_tests.rag.base_rag_tests import BaseRAGTest
+
+
+class TestRAGOpenAI(BaseRAGTest):
+ """Test RAG Ingest with OpenAI provider."""
+
+ def get_base_ingest_options(self) -> RAGIngestOptions:
+ """Return OpenAI-specific ingest options."""
+ return {
+ "vector_store": OpenAIVectorStoreOptions(
+ custom_llm_provider="openai",
+ ),
+ }
+
+ async def query_vector_store(
+ self,
+ vector_store_id: str,
+ query: str,
+ ) -> Optional[Dict[str, Any]]:
+ """Query OpenAI vector store."""
+ search_response = await litellm.vector_stores.asearch(
+ vector_store_id=vector_store_id,
+ query=query,
+ custom_llm_provider="openai",
+ )
+
+ if search_response.get("data") and len(search_response["data"]) > 0:
+ return search_response
+ return None
+
+
\ No newline at end of file