Codapult
DocsBlogPricingPluginsDemo
Get Codapult
Logo

Build your SaaS with AI. Keep the architecture under control.

Get Codapult

Product

  • Pricing
  • Architecture
  • Modules
  • AI platform
  • Plugins

Developers

  • MCP
  • CLI
  • Documentation
  • Launch your SaaS
  • Build a B2B SaaS

Resources

  • Blog
  • FAQ

Connect

  • Contact
  • GitHub

Compare

  • SaaS template comparison
  • Codapult vs Supastarter
  • Codapult vs Makerkit
  • Codapult vs ShipFast
  • Codapult vs SaaSBold
  • Codapult vs Gravity
  • Codapult vs Nextbase
  • Codapult vs BuilderKit

Featured on

Codapult on LaunchNestCodapult on LaunchNestbetterlaunch.cobetterlaunch.coFeatured on LaunchBuffFeatured on LaunchBuffCodapult on PeerPushCodapult on PeerPushFeatured on LaunchItFeatured on LaunchIt
© 2026 Codapult·All rights reserved·Privacy Policy·Terms of Service
Full source code · One-time purchase · Self-host anywhere
All articles

Getting Started

  • Introduction
  • Quick Start
  • Your First 30 Minutes
  • Project Structure
  • License and Permitted Use
  • Starter Profiles and Recipes
  • Product Recipes

Configuration

  • Environment Variables
  • App Configuration
  • Which Modules Should I Enable?
  • Provider Matrix
  • Capability Coverage

Database

  • Database and Provider Guide
  • Database
  • Migrations

Authentication

  • Authentication
  • OAuth Providers
  • Two-Factor & Passwordless
  • Enterprise SSO (SAML)

Ai

  • AI Runtime Architecture and Evals
  • AI Features
  • Streaming Chat
  • RAG and Semantic Search
  • Quotas and Memory

Teams

  • Teams & Organizations
  • Permissions & RBAC
  • SCIM Provisioning

Security

  • Data Retention Policy
  • Security

Deployment

  • Enterprise E2E Evidence
  • Enterprise Production Readiness
  • Deployment, Backup, and Restore Runbook
  • Deployment
  • Troubleshooting

Payments

  • Payments & Billing
  • Stripe Setup
  • LemonSqueezy Setup
  • Polar Setup
  • Payment Webhooks

Api

  • API Layer
  • tRPC
  • GraphQL

Email

  • Email
  • Email Templates

Infrastructure

  • Infrastructure
  • Self-Hosting
  • File Storage
  • Docker
  • Background Jobs
  • Terraform & Pulumi
  • Kubernetes

Ui

  • UI & Theming

I18n

  • Internationalization

Content Management

  • Content Management

Admin

  • Admin Panel

Monitoring

  • Analytics & Monitoring

Modules

  • Module Architecture
  • Waitlist
  • Audit Log
  • White-Labeling
  • Workflow Automation
  • A/B Testing
  • Welcome Page
  • Referrals
  • GDPR Export and Deletion
  • Promotions
  • Outgoing Webhooks

Plugins

  • Plugin System
  • CRM Plugin
  • Helpdesk Plugin
  • Email Marketing Plugin

Upgrading

  • Upgrading Codapult

Developer Tools

  • AI Agents & IDEs
  • MCP Server
  • Testing
  • Build Your First Feature with Codapult MCP
  • How Guard Blocks an Architectural Regression
Ai

AI Features

Build AI features in Codapult with streaming chat, RAG retrieval, tool calling, embedding adapters, model configuration, quotas, and conversation persistence.

Codapult provides a shared AI application layer built on the Vercel AI SDK. Chat, agents, batch jobs, playground experiments, tools, guardrails, metering, model routing, and retrieval use the same gateway instead of implementing provider calls independently.

Guides

  • Streaming Chat — chat UI, model adapters, streaming route, and tool calls.
  • RAG and Semantic Search — indexing, embeddings, vector store, and retrieval.
  • AI Runtime Architecture and Evals — request flow, extension boundaries, and deterministic runtime contracts.
  • Quotas and Memory — conversation persistence, organization request quotas, cost budgets, and rate limits.
  • AI Agents and IDEs — tools, agents, and the gateway contract for AI-powered development.

Architecture

src/lib/ai/
├── models.ts         # Client-safe model options (id, label, provider)
├── providers.ts      # getModel() — resolves modelId → LanguageModel
├── embeddings/       # Embedding adapter (OpenAI / Ollama)
├── vector-store/     # Vector store adapter (SQLite / memory)
├── rag.ts            # RAG pipeline (index → chunk → embed → store → retrieve)
├── conversations.ts  # Conversation/message CRUD
├── gateway/          # Model routing, retries, shared pipeline, and providers
├── prompts/          # Versioned prompts and A/B testing
├── tools/            # Tool definitions, built-ins, and agents
├── guardrails/       # Input/output policy evaluation
├── metering/         # Token usage, cost, and budget analytics
└── batch/             # Asynchronous batch processing

Chat Endpoint

POST /api/ai/chat accepts a JSON body with a messages array and an optional model selector. This built-in surface is streaming by design:

{
  "messages": [{ "role": "user", "content": "How do I deploy?" }],
  "modelId": "gpt-5.6-terra"
}

The endpoint follows the standard API route pattern: auth check → rate limiting (30 requests per 60 seconds per user) → org quota check → Zod validation → RAG context injection → streaming response.

For server-to-server use, POST /api/ai/gateway supports both complete and streaming responses. Set requireCompleteResponse: true when an output guardrail must finish before any response is delivered. This forces the complete-response path even if stream: true is also present; it does not create a guardrail, so the request must reference a configured organization-scoped output rule.

Available Models

Model IDLabelProvider
gpt-5.6GPT-5.6 (alias)OpenAI
gpt-5.6-terraGPT-5.6 TerraOpenAI
gpt-5.6-lunaGPT-5.6 LunaOpenAI
claude-fable-5Claude Fable 5Anthropic
claude-opus-5Claude Opus 5Anthropic
claude-sonnet-5Claude Sonnet 5Anthropic
claude-haiku-4-5-20251001Claude Haiku 4.5Anthropic
gemini-3.7-flashGemini 3.7 FlashGoogle
gemini-3.6-flashGemini 3.6 FlashGoogle
gemini-3.5-flash-liteGemini 3.5 Flash-LiteGoogle
openai/gpt-oss-120bGPT-OSS 120B (Groq)Groq

Models are defined in src/lib/ai/models.ts. To add a model, add its complete definition there, including provider, SDK model ID, capabilities, and pricing. Unknown model IDs are rejected; provider detection by naming convention is not used.

Custom OpenAI-compatible endpoint

For a self-hosted or third-party OpenAI-compatible endpoint, keep the model definition in src/lib/ai/models.ts with provider: 'custom'. Configure only the endpoint and secret through environment variables:

CUSTOM_AI_BASE_URL="https://llm.example.com/v1"
CUSTOM_AI_API_KEY="..."
AI_DEFAULT_MODEL="your-model-id"

CUSTOM_AI_BASE_URL and CUSTOM_AI_API_KEY do not register arbitrary models. The selected model ID must still exist in models.ts and, when configured, in AI_ALLOWED_MODELS.

Configuration

Runtime AI settings live in environment variables and are exposed server-side through env.ai:

AI_DEFAULT_MODEL = 'gpt-5.6-terra';
AI_ALLOWED_MODELS = 'gpt-5.6,gpt-5.6-terra,gpt-5.6-luna,claude-sonnet-5,gemini-3.7-flash';
AI_MAX_RETRIES = '2';
AI_DEFAULT_TEMPERATURE = '0.7';
AI_DEFAULT_MAX_TOKENS = '4096';
AI_DEFAULT_TOP_P = '1';
ENABLE_AI_RAG = 'false';
AI_RAG_MAX_CHUNKS_PER_QUERY = '5';
AI_RAG_MIN_SCORE = '0.4';
SettingDescription
AI_DEFAULT_MODELModel used when the user doesn't pick one (must match an ID in models.ts)
AI_ALLOWED_MODELSComma-separated model allow-list; empty enables all catalog models
AI_DEFAULT_TEMPERATUREDefault sampling temperature for providers that support sampling
AI_DEFAULT_MAX_TOKENSDefault output token limit
AI_DEFAULT_TOP_PDefault nucleus sampling value
ENABLE_AI_RAGEnables retrieval and indexing; defaults to false
AI_RAG_MAX_CHUNKS_PER_QUERYMaximum context chunks per query
AI_RAG_MIN_SCOREMinimum cosine similarity score (0–1)

The system instruction is a source-controlled constant in src/lib/ai/system-prompt.ts. Keep product behavior there; secrets and deployment controls belong in the environment.

Tool Use

Chat supports function calling via the Vercel AI SDK. Tools are defined in /api/ai/chat/route.ts. The example below is illustrative — replace it with your own domain-specific tools:

import { z } from 'zod';
import { tool } from 'ai';

const chatTools = {
  lookupOrder: tool({
    description: 'Look up an order by ID',
    inputSchema: z.object({ orderId: z.string() }),
    execute: async ({ orderId }) => {
      // Replace with your own business logic
      const order = await db.select().from(orders).where(eq(orders.id, orderId)).limit(1);
      return order[0] ?? { error: 'Not found' };
    },
  }),
};

Multi-step tool invocations are enabled with maxSteps: 3. To add a new tool, define it in chatTools with a Zod parameters schema and an execute function.

Organization Quotas

AI access is tracked per organization. Each plan defines an aiChat request quota with a configured time window in src/lib/org-quotas.ts. The quota is checked before chat, gateway, and batch work through checkOrgQuota(). This request quota is separate from token-cost and budget analytics; configure daily or monthly cost budgets through the AI metering settings.

Chat Memory

Conversation history is persisted in the database via src/lib/ai/conversations.ts:

EndpointMethodDescription
/api/ai/chat/conversationsGETList user conversations
/api/ai/chat/conversationsPOSTCreate a new conversation
/api/ai/chat/conversationsDELETEDelete a conversation
/api/ai/chat/conversations/[id]/messagesGETRead messages

The only connected Chat UI component (src/components/ai/ChatUI) connects to these endpoints and renders the production chat interface with model selection, conversation switching, streaming responses, and tool-call progress/results. Use ChatUI directly or compose its supporting AI components for a specialized surface. Optional agent, debug, and message-cost props are integration points for callers that already have that metadata—they are not populated automatically by the basic chat route.

RAG Pipeline

The RAG (Retrieval-Augmented Generation) pipeline lets the AI chat reference your domain-specific content — blog posts, help docs, feature requests, or any custom text.

How It Works

  1. Index — content is chunked (800 chars, 150 overlap), embedded, and stored in the vector store
  2. Retrieve — user queries are embedded and matched against stored vectors by cosine similarity
  3. Augment — matching chunks are injected into the system prompt with source citations

Indexing Content

Use the indexDocument function or the admin API:

import { indexDocument } from '@/lib/ai/rag';

await indexDocument({
  sourceType: 'help',
  sourceId: 'getting-started',
  title: 'Getting Started Guide',
  content: markdownContent,
});

For large content, use the rag-index background job:

import { enqueue } from '@/lib/jobs';

await enqueue('rag-index', {
  sourceType: 'blog',
  sourceId: 'post-123',
  title: 'My Blog Post',
  content: markdownContent,
});

Admin Indexing API

POST /api/ai/index is admin-only — requires role: "admin" session. Use it to manage the knowledge base from the admin panel or via scripts. It supports three actions:

ActionDescription
indexIndex a document (sourceType, sourceId, title, content)
searchSearch the vector store (query, optional sourceTypes, limit, minScore)
deleteDelete indexed content (sourceType, optional sourceId)

Embedding Providers

Embeddings use the adapter pattern, switched via the EMBEDDING_PROVIDER env var:

ProviderEnv ValueRequirements
OpenAIopenai (default)OPENAI_API_KEY
OllamaollamaOLLAMA_BASE_URL, OLLAMA_EMBEDDING_MODEL

Ollama enables fully self-hosted embeddings — no external API calls. The default Ollama model is nomic-embed-text.

Vector Store

Vector storage uses the adapter pattern, switched via VECTOR_STORE_PROVIDER (accessed as env.ai.vectorStoreProvider in server code):

StoreEnv ValueDescription
SQLitesqlite (default)Persisted in Turso alongside app data
MemorymemoryIn-memory store for development/testing

Source Types

Indexed content is categorized by source type:

TypeDescription
blogBlog posts
helpHelp center / documentation articles
feature_requestFeature request descriptions
customAny custom content

Environment Variables

VariableDefaultDescription
OPENAI_API_KEY—Required for OpenAI models and default embeddings
ANTHROPIC_API_KEY—Required for Anthropic models
EMBEDDING_PROVIDERopenaiEmbedding backend (openai or ollama)
VECTOR_STORE_PROVIDERsqliteVector storage backend (sqlite or memory)
OLLAMA_BASE_URLhttp://localhost:11434Ollama server URL
OLLAMA_EMBEDDING_MODELnomic-embed-textOllama model name for embeddings

Removing the Module

The AI core is a removable module that contains the shared gateway, chat, agents, batch processing, playground, tools, guardrails, metering, and RAG. Chat and RAG can be disabled independently with ENABLE_AI_CHAT="false" and ENABLE_AI_RAG="false", but both require ENABLE_AI_CORE="true". RAG is opt-in because indexing incurs embedding cost. Use the setup wizard (npx @codapult/cli setup) to remove the AI bundle, or use the feature flags for reversible runtime changes. See the Modules documentation for manual removal steps.

AI Runtime Architecture and EvalsStreaming Chat