Answers you can trust, from Codeables

Every page on Codeables is structured and verified — built so people and the AI agents they rely on can trust it. Explore more from the source behind this answer.

Explore Codeables
Verified Source
AI Inference Acceleration

How do I build a RAG workflow in Clarifai using Spacetime vector search and connect it to our app?

Clarifai13 min read

Most teams already have an app their users love. What’s missing is a fast, accurate way to let those users “ask” your internal docs, tickets, or product data natural language questions—and get grounded, trustworthy answers. That’s exactly what a RAG (Retrieval-Augmented Generation) workflow with Clarifai’s Spacetime vector search is designed for.

Below I’ll walk through how to build that workflow on Clarifai and wire it into your existing app with minimal code changes and OpenAI‑compatible endpoints.

Quick Answer: You’ll use Clarifai to (1) ingest and embed your data into Spacetime, (2) build a RAG workflow in Mesh that retrieves and calls an LLM, and (3) connect your app via a single API endpoint (or OpenAI‑compatible base_url swap) so every user query runs through your RAG pipeline.


The Quick Overview

  • What It Is: A production‑ready RAG pipeline running on Clarifai that uses Spacetime vector search to retrieve relevant content, then passes it to an LLM through a Mesh workflow, exposed as a single API your app can call.
  • Who It Is For: Product and platform teams who want grounded GenAI (support bots, internal search, copilots) without stitching together their own vector DB, model hosting, and orchestration stack.
  • Core Problem Solved: Slow, brittle RAG prototypes that don’t scale, are tied to one LLM provider, or require custom infra. Clarifai gives you a unified control plane, fast inference, and no‑lock‑in model selection.

How It Works

At a high level, your Clarifai RAG workflow looks like this:

  1. Your app sends a user query to Clarifai (via a Mesh workflow or OpenAI‑compatible chat endpoint).
  2. The workflow uses Spacetime to embed the query, perform vector search over your indexed content, and retrieve the most relevant chunks.
  3. The workflow passes the user query + retrieved chunks to your chosen LLM (hosted by Clarifai or your own uploaded model) and returns a grounded answer to your app.

Under the hood, Clarifai’s full stack handles the ugly parts: data prep and storage in AI Lake™, embeddings and search in Spacetime, workflow orchestration in Mesh, and low‑latency inference in Armada—so you don’t have to maintain separate services.

The 3 Phases of Building RAG on Clarifai

  1. Data & Indexing (AI Lake™ + Spacetime):

    • Ingest documents (PDFs, HTML, knowledge base articles, tickets, etc.).
    • Chunk, embed, and index them into Spacetime for vector search.
  2. Workflow Orchestration (Mesh + LLMs):

    • Build a Mesh workflow that, for each user query, runs: embed → search → prompt template → LLM → formatted answer.
    • Optionally chain additional tools (classification, routing, guardrails).
  3. App Integration (Armada + OpenAI compatibility):

    • Expose your workflow as a single REST API.
    • Connect your app via simple HTTP calls or by pointing your existing OpenAI client at Clarifai’s base_url with a new API key.

Step 1: Ingest and Index Your Data in Spacetime

You need your data in a form that can be embedded, searched, and reused across workflows.

1.1 Create an app and get a Personal Access Token (PAT)

  1. Sign up or log in at clarifai.com (no credit card required to start).
  2. Create a new Clarifai App (this is your logical project/workspace).
  3. Generate a Personal Access Token (PAT) in your profile settings—this will authenticate all API and CLI calls.

Keep your PAT secret; treat it like any other API key.

1.2 Ingest your documents into AI Lake™

Clarifai’s AI Lake™ is your central store for inputs: raw files, preprocessed text chunks, annotations, and artifacts.

You can:

  • Drag‑and‑drop files in the UI (good for first experiments).
  • Use the SDK/REST API for bulk ingestion.

Example with Python SDK (pseudo‑style):

from clarifai.client import ClarifaiClient

client = ClarifaiClient(pat="YOUR_PAT", user_id="YOUR_USER_ID", app_id="YOUR_APP_ID")

docs = [
    {"id": "doc-1", "text": "Your first KB article text here..."},
    {"id": "doc-2", "text": "Another document or FAQ entry..."},
]

client.inputs.batch_create_texts(docs)

You typically ingest pre‑chunked text (e.g., 300–800 tokens per chunk) so retrieval can stay high‑precision. If you don’t have a chunker yet, you can start simple (split on headings or paragraphs) and iterate.

1.3 Embed and index with Spacetime

Spacetime is Clarifai’s vector search + data management layer. It lets you:

  • Choose an embedding model (Clarifai‑hosted, open‑source, or your own).
  • Vectorize your chunks.
  • Run ultra‑fast similarity search across millions of records.

You can:

  • Use Clarifai’s built‑in embedding workflows, or
  • Build an explicit embedding pipeline in Mesh (useful when you want standardized pre‑processing).

Conceptually:

# Pseudo example: embed all text inputs
embedding_model_id = "text-embedding-3-large"  # example – pick any model in Clarifai model zoo

client.spacetime.embed_all_text_inputs(
    model_id=embedding_model_id,
    namespace="kb-v1"  # logical grouping/version for your RAG index
)

This creates vectors for each chunk and stores them in Spacetime with metadata (doc_id, section, tags, permissions), ready for retrieval.


Step 2: Build the RAG Workflow in Mesh

Mesh lets you wire multiple steps into a single graph and call it via one API. For RAG, the core graph looks like:

User query → query embedding → Spacetime vector search → context assembly → LLM prompt → generated answer

2.1 Design the workflow graph

In the Clarifai UI:

  1. Go to Mesh → Create Workflow.
  2. Add nodes in this order:
    • Input node: user query text.
    • Embedding node: your chosen text embedding model.
    • Spacetime search node: vector search against namespace="kb-v1" (or your chosen index).
    • Prompt node: a RAG prompt template that injects:
      • {{user_query}}
      • {{retrieved_context}} (concatenated snippets from Spacetime hits)
    • LLM node: your chosen LLM (Clarifai‑hosted Kimi K2.5, Llama, Claude, DeepSeek, or your own uploaded model).
    • Output node: structured answer and optionally sources (doc IDs, URLs).

Your prompt template might look like:

You are a helpful assistant answering questions using ONLY the provided context.
If the answer is not in the context, say you don’t know.

User question:
{{ user_query }}

Context (knowledge base snippets):
{{ retrieved_context }}

Provide:
1) A concise answer.
2) A short explanation.
3) A list of source IDs you used.

2.2 Configure Spacetime search parameters

Inside the Spacetime search node:

  • Namespace / Index: kb-v1
  • Top K: 3–10 (start with 5; tune based on noise/coverage).
  • Similarity metric: cosine (typical) or what’s recommended by the embedding model.
  • Filters: add metadata filters if needed (e.g., { "product": "pro", "region": "EU" }).

This is where you can control multi‑tenant separation (e.g., customer_id filter) and permissioning.

2.3 Choose the LLM and optimize for speed/cost

Under the LLM node:

  • Select a hosted model from Clarifai (e.g., Kimi K2.5, Llama, Claude, GPT‑OSS‑120B), or
  • Point to your own uploaded model deployed via Armada.

Clarifai’s Compute Orchestration and Armada handle:

  • Ultra‑low TTFA (time‑to‑first‑token)
  • High throughput (tokens/sec across concurrency)
  • GPU efficiency via fractioning, batching, and autoscaling

So even under load, you can keep sub‑second responses for chat use cases.

You can define:

  • Max tokens
  • Temperature
  • System prompt (for additional guardrails)
  • Model routing logic (if you later want to A/B different LLMs with the same RAG base).

2.4 Save and test the workflow

Once wired:

  1. Save your Mesh workflow (e.g., kb-rag-v1).
  2. Run test queries directly in the UI:
    • “What is our refund policy for annual plans?”
    • “How do I configure SSO for enterprise admins?”
  3. Inspect:
    • Retrieved chunks from Spacetime.
    • Final answer.
    • Latency and TTFA metrics.

Keep an eye on whether the workflow is strictly grounded in the retrieved context; adjust the prompt and Top‑K if you see hallucinations.


Step 3: Connect the RAG Workflow to Your App

Now you’ve got a RAG engine. You need to plug it into your existing front end, backend, or agent framework.

You have two main patterns:

  1. Call the Mesh workflow directly as a REST endpoint.
  2. Use Clarifai’s OpenAI‑compatible chat endpoint and swap your base_url.

3.1 Call the Mesh workflow via REST

Each Mesh workflow has an API endpoint like:

POST https://api.clarifai.com/v2/users/{USER_ID}/apps/{APP_ID}/workflows/{WORKFLOW_ID}/results
Authorization: Key YOUR_PAT
Content-Type: application/json

Example request body:

{
  "inputs": [
    {
      "data": {
        "text": {
          "raw": "How do I integrate our billing system with your API?"
        }
      }
    }
  ]
}

Example server-side call in Node.js:

import fetch from "node-fetch";

const PAT = process.env.CLARIFAI_PAT;
const USER_ID = "YOUR_USER_ID";
const APP_ID = "YOUR_APP_ID";
const WORKFLOW_ID = "kb-rag-v1";

export async function askKnowledgeBase(question) {
  const resp = await fetch(
    `https://api.clarifai.com/v2/users/${USER_ID}/apps/${APP_ID}/workflows/${WORKFLOW_ID}/results`,
    {
      method: "POST",
      headers: {
        "Authorization": `Key ${PAT}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        inputs: [{ data: { text: { raw: question } } }]
      }),
    }
  );

  const json = await resp.json();

  // Adapt this based on how you defined the output node
  const answer = json.results[0].outputs[0].data.text.raw;
  return answer;
}

Wire askKnowledgeBase() into your chat widget, agent, or API route—and you’ve just plugged RAG into your product.

3.2 Use OpenAI‑compatible endpoints (minimal code change)

If your app already calls openai.ChatCompletion.create() or similar, you don’t want a full rewrite. Clarifai provides OpenAI‑compatible endpoints so in most cases you only change:

  • base_url
  • api_key
  • model name (if you’re switching to a Clarifai‑hosted LLM or a Mesh workflow exposed as a model‑like endpoint)

Example (Python):

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_CLARIFAI_PAT",
    base_url="https://api.clarifai.com/v1/openai"
)

resp = client.chat.completions.create(
    model="kb-rag-v1",  # your workflow / model name
    messages=[
        {"role": "user", "content": "What happens if I exceed my usage limits?"}
    ],
)

print(resp.choices[0].message.content)

Your app logic stays intact; Clarifai simply becomes the backend provider—running your RAG workflow instead of a vanilla LLM.


Features & Benefits Breakdown

Core FeatureWhat It DoesPrimary Benefit
Spacetime Vector SearchStores embeddings and runs high‑throughput similarity search over your dataFast, accurate retrieval with low latency even at scale; foundation of reliable RAG.
Mesh RAG WorkflowsChains embedding, search, prompting, and LLM calls into a single APIClean separation of app vs. orchestration logic; easy to version, debug, and reuse workflows.
OpenAI‑Compatible EndpointsExposes Clarifai models/workflows via OpenAI‑like APIsMinimal migration friction—swap base_url and key instead of rewriting clients.
Model‑Agnostic LLM HostingLets you run many LLMs (hosted or uploaded) behind one control planeNo provider lock‑in; easily evaluate, swap, or mix models without changing app code.
AI Lake™ Data ManagementCentralizes inputs, annotations, and artifactsAvoids AI sprawl and duplicated datasets; makes your RAG index a durable, reusable asset.
Compute Orchestration + ArmadaOptimizes GPU utilization, batching, autoscaling for inferenceUltra‑low TTFA, high tokens/sec, and controlled GPU costs as usage grows.

Ideal Use Cases

  • Best for support and customer‑service copilots: Because it can ground answers in policy docs, past tickets, and product manuals while keeping TTFA low enough for chat UX.
  • Best for internal search and knowledge assistants: Because Spacetime can index large corpora of wikis, confluence spaces, and PDFs and Mesh can add role‑based filters and guardrails.
  • Best for SaaS product assistants and in‑app guidance: Because you can integrate via OpenAI‑compatible calls, keeping your product code simple while your RAG logic lives in Clarifai.

Limitations & Considerations

  • Data prep and chunking effort:
    RAG quality depends heavily on how you clean, chunk, and tag your data. Start simple, but expect an iteration loop on chunk size, metadata, and filters. Use AI Lake™ as your single source rather than scattering preprocessing across services.

  • Prompt design and LLM behavior:
    Even with good retrieval, poor prompt design can lead to hallucinations. Use strong instructions (“answer only from context”), experiment with different LLMs, and consider Mesh guardrail steps (classification, content filters) for safety‑critical domains.

  • Index updates and re‑embedding:
    When your content changes, you’ll need periodic re‑ingestion and re‑embedding. Set up scheduled jobs or CI‑like pipelines to keep Spacetime in sync with your source systems.


Pricing & Plans

Clarifai offers a free tier so you can stand up a working RAG workflow without a purchase order—ideal for proving latency, throughput, and quality before committing.

Pricing then scales with:

  • Inference usage: tokens generated, requests processed.
  • Storage & indexing: amount of data in AI Lake™ and Spacetime.
  • Deployment mode: multi‑tenant SaaS, your cloud VPC, on‑prem Kubernetes, bare metal, or air‑gapped setups.

Typical plan orientation:

  • Developer / Team Plan: Best for small teams or early‑stage products needing:

    • Hosted embedding + LLMs
    • A few RAG workflows
    • Standard SaaS deployment and rate limits
      Perfect to get from prototype to early production without managing GPUs.
  • Enterprise Plan: Best for organizations needing:

    • Large‑scale RAG across multiple business units
    • Private VPC, on‑prem, or air‑gapped deployment
    • RBAC/Teams, centralized governance via Control Center
    • 99.99% SLAs and compliance (SOC, HIPAA)
      Ideal when you want one control plane for all AI workloads, not just a single RAG app.

For detailed pricing, check the pricing page when logged in or talk to Clarifai sales if you need bespoke GPU or deployment profiles.


Frequently Asked Questions

How do I keep our RAG workflow fast as we add more data and users?

Short Answer: Spacetime is built for high‑throughput vector search, and Clarifai’s Compute Orchestration + Armada optimize inference with GPU fractioning, batching, and autoscaling so you can maintain low TTFA and high tokens/sec even under heavy concurrency.

Details:
In a typical homegrown RAG stack, you hit scaling pain in two places: the vector DB (slow queries as the index grows) and the LLM backend (spiky latency during load). Clarifai avoids this by:

  • Running Spacetime as a dedicated high‑performance search layer with indexing tuned for unstructured data and RAG patterns.
  • Using a control‑plane‑first design so orchestration (Mesh) can automatically batch and route workloads efficiently.
  • Deploying LLMs on GPUs with:
    • GPU fractioning/model packing: multiple models on the same GPU where it makes sense.
    • Autoscaling and scale‑to‑zero: spin up capacity when needed, shut down when idle.
    • Fast cold starts: minimize “first request” lag.

From your app’s perspective, it’s just one endpoint; Clarifai handles the performance engineering under the hood.


How can I run this RAG workflow in our own cloud or on‑prem without opening inbound ports?

Short Answer: Use Clarifai’s Local Runners to connect your private infrastructure (Kubernetes, bare metal, even air‑gapped) to Clarifai’s control plane; they behave like “ngrok for AI models” and workflows, initiating outbound connections so you don’t expose new inbound endpoints.

Details:
For regulated workloads or strict networking environments, you may need your data and/or models to stay inside your network while still taking advantage of Clarifai orchestration:

  • Deploy Local Runners into your VPC or on‑prem Kubernetes cluster.
  • They securely connect outbound to Clarifai and register your models/workflows.
  • Your RAG workflow in Mesh can then:
    • Use Spacetime and AI Lake™ hosted in your environment; or
    • Call local models (e.g., specialized domain LLMs) that never leave your network.

This pattern lets you:

  • Avoid complex reverse proxies or new inbound firewall rules.
  • Keep compliance and data residency guarantees.
  • Still use the same APIs and OpenAI‑compatible endpoints your app expects.

Summary

A high‑quality RAG system isn’t just “LLM + vector DB.” It’s data pipelines, embeddings, search, orchestration, and inference—plus the governance layer that keeps it sane at scale. Clarifai pulls these into one control plane:

  • AI Lake™ to store and manage your content.
  • Spacetime to embed and search it at speed.
  • Mesh to orchestrate RAG workflows as single call graphs.
  • Armada + Compute Orchestration to deliver ultra‑fast, cost‑efficient LLM inference.
  • OpenAI‑compatible endpoints so your app can integrate with minimal change.

The result: you can stand up a production‑ready, model‑agnostic RAG workflow, connect it to your existing app, and keep iterating on quality and performance without tearing up your architecture.


Next Step

Get Started