Skip to content

Python API reference

ragna.local_root(path=None)

Get or set the local root directory Ragna uses for storing files.

Defaults to the value of the RAGNA_LOCAL_ROOT environment variable or otherwise to ~/.cache/ragna.

Parameters:

Name Type Description Default
path Optional[Union[str, Path]]

If passed, this is set as new local root directory.

None

Returns:

Type Description
Path

Ragna's local root directory.

ragna.core

Assistant

Abstract base class for assistants used in ragna.core.Chat

answer(messages) abstractmethod

Answer a prompt given the chat history.

Parameters:

Name Type Description Default
messages list[Message]

List of messages in the chat history. The last item is the current user prompt and has the relevant sources attached to it.

required

Returns:

Type Description
Iterator[str]

Answer.

Chat

Tip

This object is usually not instantiated manually, but rather through ragna.core.Rag.chat.

A chat needs to be prepared before prompts can be answered.

Can be used as context manager to automatically invoke prepare:

rag = Rag()

async with rag.chat(
    documents=[path],
    source_storage=ragna.core.RagnaDemoSourceStorage,
    assistant=ragna.core.RagnaDemoAssistant,
) as chat:
    print(await chat.answer("What is Ragna?"))

Parameters:

Name Type Description Default
rag Rag

The RAG workflow this chat is associated with.

required
input Union[None, MetadataFilter, Document, str, Path, Collection[Union[Document, str, Path]]]

Subject of the chat. Available options:

None
source_storage SourceStorage

Source storage to use.

required
assistant Assistant

Assistant to use.

required
corpus_name str

Corpus of documents to use.

'default'
**params Any

Additional parameters passed to the source storage and assistant.

{}

answer(prompt, *, stream=False) async

Answer a prompt.

Returns:

Type Description
Message

Answer.

Raises:

Type Description
RagnaException

If chat is not prepared.

prepare() async

Prepare the chat.

This stores the documents in the selected source storage. Afterwards prompts can be answered.

Returns:

Type Description
Message

Welcome message.

Component

Base class for RAG components.

display_name() classmethod

Returns:

Type Description
str

Component name.

Document

Abstract base class for all documents.

get_handler(name) staticmethod

Get a document handler based on a suffix.

Parameters:

Name Type Description Default
name str

Name of the document.

required

supported_suffixes() staticmethod

Returns:

Type Description
set[str]

Suffixes, i.e. ".txt", that can be handled by the builtin ragna.core.DocumentHandlers.

DocumentHandler

Base class for all document handlers.

extract_pages(document) abstractmethod

Extract pages from a document.

Parameters:

Name Type Description Default
document Document

Document to extract pages from.

required

Returns:

Type Description
Iterator[Page]

Extracted pages.

supported_suffixes() abstractmethod classmethod

Returns:

Type Description
list[str]

Suffixes supported by this document handler.

DocxDocumentHandler

Document handler for .docx documents.

Note

This does not extract text from headers or footers.

Package requirements

LocalDocument

Document class for files on the local file system.

Tip

This object is usually not instantiated manually, but rather through ragna.core.LocalDocument.from_path.

from_path(path, *, id=None, name=None, metadata=None, handler=None) classmethod

Create a ragna.core.LocalDocument from a path.

Parameters:

Name Type Description Default
path Union[str, Path]

Local path to the file.

required
id Optional[UUID]

ID of the document. If omitted, one is generated.

None
name Optional[str]

Name of the document. If omitted, defaults to the name of the path.

None
metadata Optional[dict[str, Any]]

Optional metadata of the document.

None
handler Optional[DocumentHandler]

Document handler. If omitted, a builtin handler is selected based on the suffix of the path.

None

Raises:

Type Description
RagnaException

If metadata is passed and contains a "path" key.

Message

Data class for messages.

Attributes:

Name Type Description
role

The message producer.

sources

The sources used to produce the message.

MessageRole

Message role

Attributes:

Name Type Description
SYSTEM

The message was produced by the system. This includes the welcome message when preparing a new chat as well as error messages.

USER

The message was produced by the user.

ASSISTANT

The message was produced by an assistant.

MetadataFilter

ADDME

MetadataOperator

ADDME

Page

Dataclass for pages of a document

Attributes:

Name Type Description
text str

Text included in the page.

number Optional[int]

Page number.

PdfDocumentHandler

Document handler for .pdf documents.

Package requirements

PlainTextDocumentHandler

Document handler for plain-text documents. Currently supports .txt and .md extensions.

PptxDocumentHandler

Document handler for .pptx documents.

Package requirements

Rag

RAG workflow.

Tip

This class can be imported from ragna directly, e.g.

from ragna import Rag

chat(input=None, *, source_storage, assistant, corpus_name='default', **params)

Create a new ragna.core.Chat.

Parameters:

Name Type Description Default
input Union[None, MetadataFilter, Document, str, Path, Collection[Union[Document, str, Path]]]

Subject of the chat. Available options:

None
assistant Union[Assistant, type[Assistant], str]

Assistant to use.

required
corpus_name str

Corpus of documents to use.

'default'
**params Any

Additional parameters passed to the source storage and assistant.

{}

RagnaException

Ragna exception.

Source

Data class for sources stored inside a source storage.

Attributes:

Name Type Description
id str

Unique ID of the source.

document str

Document this source belongs to.

location str

Location of the source inside the document.

content str

Content of the source.

num_tokens int

Number of tokens of the content.

SourceStorage

list_corpuses()

List available corpuses.

Returns:

Type Description
list[str]

List of available corpuses.

list_metadata(corpus_name=None)

List available metadata for corpuses.

Parameters:

Name Type Description Default
corpus_name Optional[str]

Only return metadata for this corpus.

None

Returns:

Type Description
dict[str, dict[str, tuple[str, list[Any]]]]

List of available metadata.

retrieve(corpus_name, metadata_filter, prompt) abstractmethod

Retrieve sources for a given prompt.

Parameters:

Name Type Description Default
corpus_name str

Name of the corpus to retrieve sources from.

required
metadata_filter MetadataFilter

Filter to select available sources.

required
prompt str

Prompt to retrieve sources for.

required

Returns:

Type Description
list[Source]

Matching sources for the given prompt ordered by relevance.

store(corpus_name, documents) abstractmethod

Store content of documents.

Parameters:

Name Type Description Default
corpus_name str

Name of the corpus to store the documents in.

required
documents list[Document]

Documents to store.

required

ragna.source_storages

Chroma

Chroma vector database

Required packages

  • chromadb>=0.6.0

Warning

The NE and NOT_IN metadata filter operators behave differently in Chroma than the other builtin source storages. With most other source storages, given a key-value pair (key, value), the operators NE and NOT_IN return only the sources with a metadata key key and a value not equal to or not in, respectively, value. To contrast, the NE and NOT_IN metadata filter operators in ChromaDB return everything described in the preceding sentence, together with all sources that do not have the metadata key key.

For more information, see the notes for v0.5.12 in the ChromaDB migration guide.

LanceDB

LanceDB vector database

Required packages

  • chromadb>=0.6.0
  • lancedb>=0.2
  • pyarrow

Qdrant

Qdrant vector database

Info

To connect to a Qdrant server instead of using a local database, use the QDRANT_URL and QDRANT_API_KEY environment variables. For example

$ export QDRANT_URL="https://xyz-example.eu-central.aws.cloud.qdrant.io:6333"
$ export QDRANT_API_KEY="<your-api-key-here>"

Required packages

  • qdrant-client>=1.12.0

RagnaDemoSourceStorage

Demo assistant without requirements.

Note

As the name implies, this source storage is just for demo purposes and cannot retrieve relevant sources for a given prompt. It returns a single ragna.core.Source per stored ragna.core.Document with potentially shortened text extracted from the first ragna.core.Page.

ragna.assistants

ClaudeHaiku

Claude 3 Haiku

Required environment variables

  • ANTHROPIC_API_KEY

Required packages

  • httpx_sse

ClaudeOpus

Claude 3 Opus

Required environment variables

  • ANTHROPIC_API_KEY

Required packages

  • httpx_sse

ClaudeSonnet

Claude 3 Sonnet

Required environment variables

  • ANTHROPIC_API_KEY

Required packages

  • httpx_sse

Command

Cohere Command

Required environment variables

  • COHERE_API_KEY

CommandLight

Cohere Command-Light

Required environment variables

  • COHERE_API_KEY

GeminiPro

Google Gemini Pro

Required environment variables

  • GOOGLE_API_KEY

Required packages

  • ijson

GeminiUltra

Google Gemini Ultra

Required environment variables

  • GOOGLE_API_KEY

Required packages

  • ijson

Gpt35Turbo16k

OpenAI GPT-3.5

Required environment variables

  • OPENAI_API_KEY

Required packages

  • httpx_sse

Gpt4

OpenAI GPT-4

Required environment variables

  • OPENAI_API_KEY

Required packages

  • httpx_sse

Jurassic2Ultra

AI21 Labs Jurassic-2 Ultra

Required environment variables

  • AI21_API_KEY

LlamafileAssistant

llamafile

To use this assistant, start the llamafile server manually. By default, the server is expected at http://localhost:8080. This can be changed with the RAGNA_LLAMAFILE_BASE_URL environment variable.

Required packages

  • httpx_sse

OllamaGemma2B

OllamaLlama2

OllamaLlava

OllamaMistral

OllamaMixtral

OllamaOrcaMini

OllamaPhi2

RagnaDemoAssistant

Demo assistant without requirements.

Note

As the name implies, this assistant is just for demo purposes and cannot answer any questions. By default it replies with the prompt and the given sources.

If you include the phrase "markdown" into your prompt, it will return a Markdown table including emojis.

ragna.deploy

Auth

ADDME

Config

Ragna configuration

DummyBasicAuth

Dummy OAuth2 password authentication without requirements.

Danger

As the name implies, this authentication is just testing or demo purposes and should not be used in production.

KeyValueStore

ADDME

NoAuth

ADDME