On this page

RAG Capability

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

The rag_query capability answers a question from your documents or a vector store and returns sources alongside the answer.

Diagram

RAG Capability

lookup fails

โ“ Query

๐Ÿ” Retrieve

๐Ÿ“„ Documents

๐Ÿ—„๏ธ Vector Store

๐Ÿง  LLM

โœ… RAGResult

โŒ Exception

Quick Start#

  1. 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)
  2. 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#

Diagram
LLMvector_store_searchrag_queryUserLLMvector_store_searchrag_queryUserrag_query(query, vector_store_id, documents)search(query, max_num_results)chunks (or raises)context + questionanswerRAGResult(answer, sources, usage)
PhaseWhat happens
RetrieveSearches vector_store_id (if given) and takes up to max_results items from documents
AugmentJoins the retrieved text into a context block
GenerateSends 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#

OptionTypeDefaultDescription
querystrRequiredThe user question
documentsOptional[List[str]]NoneInline documents to use as context
vector_store_idOptional[str]NoneVector store ID to search
modelstr"gpt-4o-mini"Model used to generate the answer
max_resultsint5Max chunks from the vector store and max documents used
timeoutfloat600.0Timeout in seconds for the LLM call (the vector store search uses its own default)
api_keyOptional[str]NoneAPI key override
api_baseOptional[str]NoneAPI base URL override
metadataOptional[Dict[str, Any]]NoneMetadata returned on the result for tracing
Capabilities SDK Reference

Auto-generated reference for the capabilities module


Error Handling#

Diagram

Yes

No

Yes

No

vector_store_id set?

Search succeeds?

๐Ÿง  Generate answer

โŒ Exception raised โ€” LLM not called

โœ… RAGResult

InputsBehaviour
vector_store_id and search failsException propagates with its real type and message
documents onlyUnchanged
NeitherUnchanged โ€” 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.