JamAI Base

repository·main·Indexed 22 days ago

https://github.com/embeddedllm/jamaibase

An open-source RAG backend platform that combines embedded databases (SQLite and LanceDB) with managed LLM orchestration. It provides a declarative way to build AI-powered applications via a REST API or spreadsheet-like UI, featuring Generative Tables (Action, Knowledge, and Chat tables) for chaining LLM reasoning and implementing Retrieval Augmented Generation.

Tokens
56.2K
Snippets
181
Records
243
Agent score
75%

What's inside jamaibase

  1. Overview of JamAI Base

    main
    JamAI Base is an open-source RAG (Retrieval-Augmented Generation) backend platform. It integrates an embedded SQLite database and an embedded LanceDB vector database with managed memory and RAG capabilities. The platform orchestrates LLMs, vector embeddings, and rerankers, providing access through a spreadsheet-like UI and a REST API.
  2. Understand JamAI Base Table Types

    main

    JamAI Base uses different table types to handle various AI and data workflows:

    • Generative Tables: Transform static tables into dynamic, AI-enhanced entities by automatically populating columns with LLM-generated data. Includes a built-in REST API endpoint.
    • Action Tables: Facilitate real-time interactions between a frontend and the LLM backend, enabling complex workflow orchestration and automated management of user inputs/outputs.
    • Knowledge Tables: Act as structured data and document repositories. They provide the contextual backdrop for LLM operations and support document uploading and synchronization.
    • Chat Tables: Designed for building intelligent chatbots. They support context-aware interactions and integrate with RAG by utilizing content from Knowledge Tables.
  3. How Python Columns work in Generative Tables

    main

    A Python Column allows you to generate or transform cell values using custom Python code. It operates on a row-by-row basis within a Generative Table.

    Core Mechanics

    • Input: All upstream columns (columns to the left of the Python Column) are provided in a global dictionary named row.
      • Keys: Column names (case-sensitive strings).
      • Values: The cell values for that specific row.
    • Output: To save the result, you must assign the processed value back to the row dictionary using the exact name of the Python Column.

    Implementation Pattern

    1. Read input values from row using upstream column names.
    2. Process or transform those values.
    3. Write the result back to row["Your Python Column Name"].

    Tip: Use try/except blocks and provide fallback values to ensure stability.

    # Read from upstream columns
    value_a = row["Input Column A"]
    value_b = row["Input Column B"]
    
    # Do some processing
    result = f"{value_a} - processed with {value_b}"
    
    # Write to this column
    row["Python Column Name"] = result
  4. How LLM Columns work in Generative Tables

    main

    An LLM Column in a Generative Table allows you to synthesize outputs using a Large Language Model (LLM). It functions by combining a System Prompt, a Prompt, and optional Retrieval Augmented Generation (RAG) settings to generate a value for each cell in the column.

    The LLM Column lifecycle:

    1. Gather Prompts: It collects the System Prompt (used as the system message to define role/style) and the Prompt (the main user message).
    2. Augment (Optional): If RAG is enabled, it augments the prompt with references from a Knowledge Table.
    3. Generate: It sends the combined prompt and your chosen Generation Settings (Model, temperature, max tokens, etc.) to the LLM.
    4. Write: The model's response is written as the value for that specific row in the LLM Column.
  5. Chat Message Format in JamAI Chat

    main

    When sending messages to the JamAI Chat API, a user message can be composed of multiple media types. A single message may include:

    • Text: The primary prompt or query.
    • Images: Zero or more image files.
    • Audio: Zero or more audio files.
    • Documents: Zero or more document files.

    Additionally, users can request Retrieval-Augmented Generation (RAG) to allow the model to retrieve context from a connected Knowledge Table. When RAG is active, the assistant's response will include RAG references.

  6. How JamAI Base implements RAG

    main

    JamAI Base provides built-in RAG (Retrieval-Augmented Generation) features so you don't have to build the pipeline manually. Key capabilities include:

    • Query Rewriting: Improves search query accuracy and relevance.
    • Hybrid Search & Reranking: Combines keyword-based search, structured search, and vector search.
    • Adaptive Chunking: Automatically determines optimal data chunking strategies.
    • BGE M3-Embedding: Uses multi-lingual, multi-functional, and multi-granular text embeddings.
    • Structured RAG Content Management: Seamlessly organizes and manages structured content.
  7. What are Generative Tables?

    main

    JamAI Base provides three types of Generative Tables designed for different LLM workflows:

    1. Action Tables: Used for chaining LLM reasoning steps. You define a schema where specific columns use gen_config to trigger LLM generation based on input columns.
    2. Knowledge Tables: Used for embedding external knowledge and files to power Retrieval Augmented Generation (RAG). These tables store embeddings of your data.
    3. Chat Tables: Designed for LLM agents with LLM chaining capabilities, typically involving a conversation history between a 'User' and an 'AI'.
  8. Reference upstream columns in image prompts

    main

    You can dynamically inject values from other columns into your image prompt using column references. At runtime, the placeholder is replaced with the current row's value.

    Syntax:

    • Use the visual column chips above the prompt editor.
    • Or type ${Column Name} directly into the prompt editor.

    Example Prompt: A cinematic portrait of ${Subject} in a neon city

    A cinematic portrait of ${Subject} in a neon city
  9. Use Retrieval Augmented Generation (RAG) in LLM Columns

    main

    RAG allows you to ground LLM outputs in external knowledge stored in a Knowledge Table. When enabled, the LLM Column follows these steps:

    1. Formulate Query: An LLM generates a retrieval query based on your initial Prompt.
    2. Retrieve: The system searches the Knowledge Table for relevant rows.
    3. Rerank: You can select a specific Reranking model to order references, or use the default Reciprocal Rank Fusion (RRF) Ranker.
    4. Inject: You specify a parameter k to control how many top references are injected into the prompt.
    5. Citations (Optional): You can enable pandoc style inline citations (e.g., [@ref0; @ref1]) to show which references support the generated text.

    The final prompt sent to the LLM includes your System Prompt, Prompt, and the injected references.

  10. Understand the JamAI Base SDK versioning policy

    main

    JamAI Base follows Semantic Versioning.

    Current Development (v0.x.x)

    The SDK is currently in the v0.x.x phase. During this stage, the public API is considered unstable, and breaking changes may occur at any time without notice.

    Future Stable Releases (v1.x.x)

    Once the SDK reaches version 1.x.x, version increments will follow these rules:

    • Major version (1.x.x): Incremented for backwards-incompatible updates to the Cloud service/backend that require changes to the SDK.
    • Minor version (x.y.x): Incremented for backwards-compatible feature updates or enhancements to the SDK libraries.
    • Patch version (x.x.z): Incremented for backwards-compatible bug fixes.
  11. Enable Multi-turn Chat in LLM Columns

    main

    Enabling Multi-turn Chat allows the LLM to use data from previous rows as conversation history, enabling context-aware interactions across the table.

    Behavior:

    • By default, rows are ordered from latest to oldest.
    • The LLM sees all rows from the current row downward as its context.

    Example Workflow:

    1. Row 1: Query is What is 2+2? $\rightarrow$ Output is 4.
    2. Row 2: Query is Add 3 $\rightarrow$ Because Multi-turn Chat is enabled, the LLM understands the context and returns 7.
  12. Implement RAG with Knowledge Tables

    main

    To implement Retrieval Augmented Generation (RAG):

    1. Populate Knowledge Table: Upload files using jamai.table.embed_file(file_path, table_id). This processes the file and adds it to the Knowledge Table.
    2. Configure Action Table for RAG: When creating an Action Table, include rag_params in the LLMGenConfig of your generative column.
      • table_id: The ID of the Knowledge Table to query.
      • k: The number of relevant chunks to retrieve.
    3. Retrieve References: When streaming from a RAG-enabled Action Table, the iterator may yield t.CellReferencesResponse objects. These contain the chunks retrieved from the Knowledge Table, allowing you to see the grounding context.
    # 1. Embed a file into a Knowledge Table
    response = jamai.table.embed_file("path/to/text.txt", "knowledge-simple")
    
    # 2. Create Action Table with RAG configuration
    table = jamai.table.create_action_table(
        t.ActionTableSchemaCreate(
            id="action-rag",
            cols=[
                t.ColumnSchemaCreate(id="question", dtype="str"),
                t.ColumnSchemaCreate(
                    id="answer",
                    dtype="str",
                    gen_config=t.LLMGenConfig(
                        model="openai/gpt-4o-mini",
                        prompt="${question}",
                        rag_params=t.RAGParams(
                            table_id="knowledge-simple",
                            k=2,
                        ),
                    ),
                ),
            ],
        )
    )
    
    # 3. Query with streaming to catch references
    completion = jamai.table.add_table_rows(
        "action",
        t.MultiRowAddRequest(table_id="action-rag", data=[dict(question="...")], stream=True),
    )
    for chunk in completion:
        if isinstance(chunk, t.CellReferencesResponse):
            print("Retrieved chunks:", chunk.chunks)
        elif chunk.output_column_name == "answer":
            print(chunk.text, end="", flush=True)