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] RAG query endpoint - Add RAG Search / Query endpoint (#18376)

Ishaan Jaff4f7682f67061
diff --git a/docs/my-website/docs/rag_ingest.md b/docs/my-website/docs/rag_ingest.md
index 536151febdc..1133b85f206 100644
--- a/docs/my-website/docs/rag_ingest.md
+++ b/docs/my-website/docs/rag_ingest.md
@@ -4,9 +4,13 @@ All-in-one document ingestion pipeline: **Upload → Chunk → Embed → Vector
| Feature | Supported |
|---------|-----------|
-| Logging | ✅ |
+| Logging | Yes |
| Supported Providers | `openai`, `bedrock`, `vertex_ai`, `gemini` |
+:::tip
+After ingesting documents, use [/rag/query](./rag_query.md) to search and generate responses with your ingested content.
+:::
+
## Quick Start
### OpenAI
@@ -82,9 +86,33 @@ curl -X POST "http://localhost:4000/v1/rag/ingest" \
}
```
-## Query the Vector Store
+## Query with RAG
+
+After ingestion, use the [/rag/query](./rag_query.md) endpoint to search and generate LLM responses:
+
+```bash showLineNumbers title="RAG Query"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "What is the main topic?"}],
+ "retrieval_config": {
+ "vector_store_id": "vs_xyz789",
+ "custom_llm_provider": "openai",
+ "top_k": 5
+ }
+ }'
+```
+
+This will:
+1. Search the vector store for relevant context
+2. Prepend the context to your messages
+3. Generate an LLM response
+
+### Direct Vector Store Search
-After ingestion, query with `/vector_stores/{vector_store_id}/search`:
+Alternatively, search the vector store directly 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" \
diff --git a/docs/my-website/docs/rag_query.md b/docs/my-website/docs/rag_query.md
new file mode 100644
index 00000000000..2ae030880d6
--- /dev/null
+++ b/docs/my-website/docs/rag_query.md
@@ -0,0 +1,273 @@
+# /rag/query
+
+RAG Query endpoint: **Search Vector Store → (Rerank) → LLM Completion**
+
+| Feature | Supported |
+|---------|-----------|
+| Logging | Yes |
+| Streaming | Yes |
+| Reranking | Yes (optional) |
+| Supported Providers | `openai`, `bedrock`, `vertex_ai` |
+
+## Quick Start
+
+```bash showLineNumbers title="RAG Query with OpenAI"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "vs_abc123",
+ "custom_llm_provider": "openai",
+ "top_k": 5
+ }
+ }'
+```
+
+## How It Works
+
+The RAG query endpoint performs the following steps:
+
+1. **Extract Query**: Extracts the query text from the last user message
+2. **Search Vector Store**: Searches the specified vector store for relevant context
+3. **Rerank (Optional)**: Reranks the search results using a reranking model
+4. **Generate Response**: Calls the LLM with the retrieved context prepended to the messages
+
+## Response
+
+The response follows the standard OpenAI chat completion format, with additional search metadata:
+
+```json
+{
+ "id": "chatcmpl-abc123",
+ "object": "chat.completion",
+ "created": 1703123456,
+ "model": "gpt-4o-mini",
+ "choices": [
+ {
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": "LiteLLM is a unified interface for 100+ LLMs..."
+ },
+ "finish_reason": "stop"
+ }
+ ],
+ "usage": {
+ "prompt_tokens": 150,
+ "completion_tokens": 50,
+ "total_tokens": 200
+ },
+ "_hidden_params": {
+ "search_results": {...},
+ "rerank_results": {...}
+ }
+}
+```
+
+## With Reranking
+
+Add a `rerank` configuration to improve result quality:
+
+```bash showLineNumbers title="RAG Query with Reranking"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "vs_abc123",
+ "custom_llm_provider": "openai",
+ "top_k": 10
+ },
+ "rerank": {
+ "enabled": true,
+ "model": "cohere/rerank-english-v3.0",
+ "top_n": 3
+ }
+ }'
+```
+
+## Streaming
+
+Enable streaming for real-time responses:
+
+```bash showLineNumbers title="RAG Query with Streaming"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "vs_abc123",
+ "custom_llm_provider": "openai"
+ },
+ "stream": true
+ }'
+```
+
+## Request Parameters
+
+### Top-Level
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `model` | string | Yes | The LLM model to use for generation |
+| `messages` | array | Yes | Array of chat messages (OpenAI format) |
+| `retrieval_config` | object | Yes | Vector store search configuration |
+| `rerank` | object | No | Reranking configuration |
+| `stream` | boolean | No | Enable streaming (default: `false`) |
+
+### retrieval_config
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `vector_store_id` | string | **required** | ID of the vector store to search |
+| `custom_llm_provider` | string | `"openai"` | Vector store provider |
+| `top_k` | integer | `10` | Number of results to retrieve |
+
+### rerank
+
+| Parameter | Type | Default | Description |
+|-----------|------|---------|-------------|
+| `enabled` | boolean | `false` | Enable reranking |
+| `model` | string | - | Reranking model (e.g., `cohere/rerank-english-v3.0`) |
+| `top_n` | integer | `5` | Number of results after reranking |
+
+## End-to-End Example
+
+### 1. Ingest a Document
+
+First, ingest a document using the [/rag/ingest](./rag_ingest.md) endpoint:
+
+```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\": \"company_docs.txt\",
+ \"content\": \"$(base64 -i company_docs.txt)\",
+ \"content_type\": \"text/plain\"
+ },
+ \"ingest_options\": {
+ \"vector_store\": {
+ \"custom_llm_provider\": \"openai\"
+ }
+ }
+ }"
+```
+
+Response:
+```json
+{
+ "id": "ingest_abc123",
+ "status": "completed",
+ "vector_store_id": "vs_xyz789",
+ "file_id": "file-123"
+}
+```
+
+### 2. Query with RAG
+
+Now query the ingested documents:
+
+```bash showLineNumbers title="Step 2: Query"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [
+ {"role": "user", "content": "What products does the company offer?"}
+ ],
+ "retrieval_config": {
+ "vector_store_id": "vs_xyz789",
+ "custom_llm_provider": "openai",
+ "top_k": 5
+ }
+ }'
+```
+
+Response:
+```json
+{
+ "id": "chatcmpl-abc123",
+ "object": "chat.completion",
+ "model": "gpt-4o-mini",
+ "choices": [
+ {
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": "Based on the company documents, the company offers..."
+ },
+ "finish_reason": "stop"
+ }
+ ]
+}
+```
+
+## Provider Examples
+
+### Bedrock
+
+```bash showLineNumbers title="RAG Query with Bedrock"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "KNOWLEDGE_BASE_ID",
+ "custom_llm_provider": "bedrock",
+ "top_k": 5
+ }
+ }'
+```
+
+### Vertex AI
+
+```bash showLineNumbers title="RAG Query with Vertex AI"
+curl -X POST "http://localhost:4000/v1/rag/query" \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "vertex_ai/gemini-1.5-pro",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "your-corpus-id",
+ "custom_llm_provider": "vertex_ai",
+ "top_k": 5
+ }
+ }'
+```
+
+## Python SDK
+
+```python showLineNumbers title="Using litellm.aquery()"
+import litellm
+
+response = await litellm.aquery(
+ model="gpt-4o-mini",
+ messages=[{"role": "user", "content": "What is LiteLLM?"}],
+ retrieval_config={
+ "vector_store_id": "vs_abc123",
+ "custom_llm_provider": "openai",
+ "top_k": 5,
+ },
+ rerank={
+ "enabled": True,
+ "model": "cohere/rerank-english-v3.0",
+ "top_n": 3,
+ },
+)
+
+print(response.choices[0].message.content)
+```
+
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index ae63bade025..948014a792b 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -528,7 +528,14 @@ const sidebars = {
"proxy/pass_through_guardrails"
]
},
- "rag_ingest",
+ {
+ type: "category",
+ label: "/rag",
+ items: [
+ "rag_ingest",
+ "rag_query",
+ ]
+ },
"realtime",
"rerank",
"response_api",
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 06067035c18..e29d4301744 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -388,6 +388,8 @@ class LiteLLMRoutes(enum.Enum):
litellm_native_routes = [
"/rag/ingest",
"/v1/rag/ingest",
+ "/rag/query",
+ "/v1/rag/query",
]
anthropic_routes = [
diff --git a/litellm/proxy/rag_endpoints/endpoints.py b/litellm/proxy/rag_endpoints/endpoints.py
index c0b5103f47f..79b4fd6873d 100644
--- a/litellm/proxy/rag_endpoints/endpoints.py
+++ b/litellm/proxy/rag_endpoints/endpoints.py
@@ -1,8 +1,9 @@
"""
-RAG Ingest Endpoints for LiteLLM Proxy.
+RAG Endpoints for LiteLLM Proxy.
-Provides an all-in-one API for document ingestion:
-Upload -> (OCR) -> Chunk -> Embed -> Vector Store
+Provides:
+- /rag/ingest: All-in-one document ingestion pipeline (Upload -> Chunk -> Embed -> Vector Store)
+- /rag/query: RAG query pipeline (Search -> Rerank -> LLM Completion)
"""
import base64
@@ -198,3 +199,145 @@ async def rag_ingest(
status_code=500,
detail={"error": str(e)},
)
+
+
+ "/v1/rag/query",
+ dependencies=[Depends(user_api_key_auth)],
+ response_class=ORJSONResponse,
+ tags=["rag"],
+)
+ "/rag/query",
+ dependencies=[Depends(user_api_key_auth)],
+ response_class=ORJSONResponse,
+ tags=["rag"],
+)
+async def rag_query(
+ request: Request,
+ fastapi_response: Response,
+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),
+):
+ """
+ RAG Query endpoint - search vector store, optionally rerank, and generate LLM response.
+
+ This endpoint:
+ 1. Extracts the query from the last user message
+ 2. Searches the vector store for relevant context
+ 3. Optionally reranks the results
+ 4. Generates an LLM response with the retrieved context
+
+ ## Example Request:
+ ```bash
+ curl -X POST "http://localhost:4000/v1/rag/query" \\
+ -H "Authorization: Bearer sk-1234" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "vs_abc123",
+ "custom_llm_provider": "openai",
+ "top_k": 5
+ }
+ }'
+ ```
+
+ ## With Reranking:
+ ```bash
+ curl -X POST "http://localhost:4000/v1/rag/query" \\
+ -H "Authorization: Bearer sk-1234" \\
+ -H "Content-Type: application/json" \\
+ -d '{
+ "model": "gpt-4o-mini",
+ "messages": [{"role": "user", "content": "What is LiteLLM?"}],
+ "retrieval_config": {
+ "vector_store_id": "vs_abc123",
+ "custom_llm_provider": "openai",
+ "top_k": 10
+ },
+ "rerank": {
+ "enabled": true,
+ "model": "cohere/rerank-english-v3.0",
+ "top_n": 3
+ }
+ }'
+ ```
+ """
+ from litellm.proxy.proxy_server import (
+ add_litellm_data_to_request,
+ general_settings,
+ llm_router,
+ proxy_config,
+ version,
+ )
+
+ try:
+ # Parse request body
+ data = await _read_request_body(request)
+
+ # Extract required fields
+ model = data.get("model")
+ messages = data.get("messages")
+ retrieval_config = data.get("retrieval_config")
+ rerank = data.get("rerank")
+ stream = data.get("stream", False)
+
+ # Validate required fields
+ if not model:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "model is required"},
+ )
+ if not messages:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "messages is required"},
+ )
+ if not retrieval_config:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "retrieval_config is required"},
+ )
+ if "vector_store_id" not in retrieval_config:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": "retrieval_config must contain 'vector_store_id'"},
+ )
+
+ # 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 Query - model: {model}, retrieval_config: {retrieval_config}"
+ )
+
+ # Call query
+ response = await litellm.aquery(
+ model=model,
+ messages=messages,
+ retrieval_config=retrieval_config,
+ rerank=rerank,
+ stream=stream,
+ router=llm_router,
+ **request_data,
+ )
+
+ return response
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ verbose_proxy_logger.exception(f"RAG Query failed: {e}")
+ raise HTTPException(
+ status_code=500,
+ detail={"error": str(e)},
+ )