# RAG Capability

> Query documents or a vector store with grounded citations; errors now surface instead of hiding

Source: https://praison.ai/docs/features/capabilities-rag/
The `rag_query` capability answers a question from your documents or a vector store and returns sources alongside the answer.

```mermaid
graph LR
    subgraph "RAG Capability"
        Q[❓ Query] --> R[🔍 Retrieve]
        D[📄 Documents] --> R
        V[🗄️ Vector Store] --> R
        R --> L[🧠 LLM]
        L --> O[✅ RAGResult]
        R -. lookup fails .-> E[❌ Exception]
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef store fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    classDef error fill:#8B0000,stroke:#7C90A0,color:#fff

    class Q,D input
    class R,L process
    class V store
    class O output
    class E error
```

## Quick Start

### Simple Usage

Give an agent knowledge and ask it a question — retrieval is handled for you.

```python
from praisonaiagents import Agent

agent = Agent(
    name="Policy Agent",
    instructions="Answer only from the provided policy documents.",
    knowledge=["policies.pdf"],
)

agent.start("What is our refund policy?")
```

Or call the capability directly with inline documents:

```python
from praisonai.capabilities import rag_query

result = rag_query(
    "What is our refund policy?",
    documents=["Refunds are accepted within 30 days of purchase with a receipt."],
)
print(result.answer)
```

### With a Vector Store

Search a pre-indexed vector store. If the lookup fails, the error is raised and the LLM is never called.

```python
from praisonai.capabilities import rag_query

try:
    result = rag_query("What is our refund policy?", vector_store_id="vs_abc123")
    print(result.answer)
    for s in result.sources or []:
        print(s["score"], s["text"])
except Exception as e:
    print(f"Retrieval failed: {type(e).__name__}: {e}")
```

---

## How It Works

```mermaid
sequenceDiagram
    participant User
    participant RAG as rag_query
    participant Store as vector_store_search
    participant LLM

    User->>RAG: rag_query(query, vector_store_id, documents)
    RAG->>Store: search(query, max_num_results)
    Store-->>RAG: chunks (or raises)
    RAG->>LLM: context + question
    LLM-->>RAG: answer
    RAG-->>User: RAGResult(answer, sources, usage)
```

| Phase | What happens |
|-------|--------------|
| **Retrieve** | Searches `vector_store_id` (if given) and takes up to `max_results` items from `documents` |
| **Augment** | Joins the retrieved text into a context block |
| **Generate** | Sends context and question to `model` via LiteLLM and returns a `RAGResult` |

`RAGResult` has `answer`, `sources` (each with `text` and either `score` or `index`, or `None` when empty), `model`, `usage`, and `metadata`.

---

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `query` | `str` | Required | The user question |
| `documents` | `Optional[List[str]]` | `None` | Inline documents to use as context |
| `vector_store_id` | `Optional[str]` | `None` | Vector store ID to search |
| `model` | `str` | `"gpt-4o-mini"` | Model used to generate the answer |
| `max_results` | `int` | `5` | Max chunks from the vector store and max documents used |
| `timeout` | `float` | `600.0` | Timeout in seconds for the LLM call (the vector store search uses its own default) |
| `api_key` | `Optional[str]` | `None` | API key override |
| `api_base` | `Optional[str]` | `None` | API base URL override |
| `metadata` | `Optional[Dict[str, Any]]` | `None` | Metadata returned on the result for tracing |

- [Capabilities SDK Reference](https://praison.ai/docs/sdk/reference/praisonai/modules/capabilities/): Auto-generated reference for the capabilities module

---

## Error Handling

> **Warning:** When you pass `vector_store_id` and the search fails (bad ID, revoked key, timeout, network error), `rag_query` and `arag_query` now raise the underlying exception. Previously the error was silently ignored and the LLM answered with no retrieved context.

```mermaid
graph TB
    S{vector_store_id set?} -->|Yes| T{Search succeeds?}
    S -->|No| G[🧠 Generate answer]
    T -->|Yes| G
    T -->|No| X[❌ Exception raised — LLM not called]
    G --> R[✅ RAGResult]

    classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    classDef error fill:#8B0000,stroke:#7C90A0,color:#fff

    class S,T,G process
    class R output
    class X error
```

| Inputs | Behaviour |
|--------|-----------|
| `vector_store_id` and search fails | Exception propagates with its real type and message |
| `documents` only | Unchanged |
| Neither | Unchanged — the model answers from its own knowledge |

### Upgrading from earlier versions

- **Before:** a failed `vector_store_id` lookup still returned a `RAGResult`, but its answer had no retrieved context.
- **Now:** the same call raises the underlying exception.
- **If you relied on the old behaviour:** wrap the call in `try/except` and choose whether to fall back to `documents=` or return a clear error to your user.

---

## Common Patterns

Combine a vector store with extra inline documents:

```python
from praisonai.capabilities import rag_query

result = rag_query(
    "What is our refund policy?",
    vector_store_id="vs_abc123",
    documents=["Holiday purchases can be refunded until January 31."],
    max_results=3,
)
print(result.answer)
```

Fall back to inline documents when the store is unreachable:

```python
from praisonai.capabilities import rag_query

question = "What is our refund policy?"
backup = ["Refunds are accepted within 30 days of purchase with a receipt."]

try:
    result = rag_query(question, vector_store_id="vs_abc123")
except Exception:
    result = rag_query(question, documents=backup)

print(result.answer)
```

Async usage with `arag_query` — same signature and same error behaviour:

```python
import asyncio
from praisonai.capabilities import arag_query

async def main():
    result = await arag_query(
        "What is our refund policy?",
        documents=["Refunds are accepted within 30 days of purchase with a receipt."],
    )
    print(result.answer)

asyncio.run(main())
```

---

## Best Practices

### Catch retrieval errors when using vector_store_id

Errors come from LiteLLM (for example `litellm.AuthenticationError`, `litellm.NotFoundError`, `litellm.Timeout`). Catch the ones you can recover from and let the rest surface.

```python
import litellm
from praisonai.capabilities import rag_query

try:
    result = rag_query("What is our refund policy?", vector_store_id="vs_abc123")
except litellm.AuthenticationError as e:
    print(f"Check your API key: {e}")
except litellm.Timeout as e:
    print(f"Vector store timed out: {e}")
```

### Pick the right source

Use `documents=` for small, static context. Use `vector_store_id=` for larger corpora you have already indexed.

### Set a realistic timeout

The default is 600 seconds. Lower `timeout=` for interactive apps so slow LLM calls fail quickly. It applies to answer generation only, not the vector store search.

### Keep auth consistent

`api_key` and `api_base` are used for both the vector store search and the LLM call — use the same values as the rest of your pipeline.

---

## Related

- [RAG](https://praison.ai/docs/features/rag/): Agent-centric RAG with `knowledge=`
- [Vector Store Files](https://praison.ai/docs/features/capabilities-vector-store-files/): Add, list, and delete files in a vector store
