Leveonas Developer Documentation · SDK v0.6.0

Cut AI code generation tokens by up to 70% with zero boilerplate rewrites.

Leveonas sits between your backend and your LLM provider. Models emit compact Leveonas Markup (LM), and Leveonas compiles it deterministically into production React, Next.js, Vue, Python, SQL, and 43 more targets.

Which Integration Should You Choose?

Leveonas offers one recommended starting path for 90% of teams plus specialized APIs if you already emit LM directly or require a private VPC compiler. Pick your exact match below:

Your Use CaseRecommended PathWhat You Integrate
Existing app using OpenAI SDK, fetch, or an AI builder (Recommended)OpenAI-Compatible ProxyPoint baseURL to https://leveonas.ainot.site/api/v1. Zero architecture changes.
Need live streaming UI previews in a browser iframeStreaming SDK + RuntimeCall createSession() from leveonas/sdk or POST /api/generate with /leveonas.js.
Already have LM source strings to convert to TSX/Vue/SQLCompiler API / SDKCall await compile(source) or POST /api/compile. No external LLM key needed.
Apply surgical follow-up edits to existing multi-file codePatch APISend <PATCH> SEARCH/REPLACE blocks + files map to POST /api/patch.
Strict data residency inside a private VPC or containerSelf-Hosted CLI ServerRun npx leveonas serve --port=4321 on your own server.

Two Credentials, Zero Surprise Billing

CredentialRequired?How to Provide It
Leveonas API Key (lv_live_...)Always requiredCreated in Dashboard → API Keys. Sent via Authorization: Bearer or X-Leveonas-Key.
Model Provider Key (OpenAI, Gemini, Anthropic, etc.)Required only for /v1/chat/completions & /api/generateProvide once via encrypted Dashboard Vault, host environment variables, OR per-request x-user-llm-key header. You pay your LLM provider directly at your own negotiated rate.

Block Tags vs. framework vs. target

Across the CLI, REST API, and TypeScript SDK, three separate concepts control how source code is parsed and emitted:

ConceptWhere UsedExample ValuesPurpose
Source Block TagInside LM string<REACT>, <PYTHON>Identifies which of the 48 language interpreters parses that block. Supports multiple blocks per payload.
frameworkSDK compile(), REST, CLI --frameworkreact | nextjs | vue | html | autoExplicit fallback or target dialect when blocks lack tags. On POST /api/compile, legacy target is accepted as an alias for framework.
target (Artifact)SDK CompileOptions, CLI --targetall | ui-ir | dom | patchesSelects which compilation artifact to emit (full result, framework-neutral Common UI IR, static DOM HTML, or incremental PatchOperation[]).

End-to-End Tutorial · Zero to Working App

Build a Progressive React Pricing Card with Gemini

Follow this complete walkthrough to connect installation, server-side secret protection, real-time SSE streaming (createSession()), and sandboxed DOMPatchApplier rendering in one working feature.

1. Install & configure
Run npm install leveonas@0.6.0 and add LEVEONAS_API_KEY + GEMINI_API_KEY to .env.local (or save Gemini in Dashboard Vault).
2. Proxy SSE route
Create app/api/generate-stream/route.ts to inject your secrets server-side and pipe the POST /api/generate SSE response to your React client.
3. Sandboxed UI bridge
Consume generation:patch events via createSession() and forward validated patches via postMessage to an <iframe sandbox="allow-scripts"> running /leveonas-runtime.js.
1. app/api/generate-stream/route.ts (Server Route)typescript
// app/api/generate-stream/route.ts — Next.js App Router SSE proxy
// Keeps LEVEONAS_API_KEY & GEMINI_API_KEY strictly on the server
import { NextRequest } from "next/server";

export async function POST(req: NextRequest) {
  const { prompt } = await req.json();
  if (!prompt || typeof prompt !== "string") {
    return new Response(JSON.stringify({ error: "prompt is required" }), { status: 400 });
  }

  const upstream = await fetch("https://leveonas.ainot.site/api/generate", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-Leveonas-Key": process.env.LEVEONAS_API_KEY!,
      ...(process.env.GEMINI_API_KEY ? { "x-gemini-key": process.env.GEMINI_API_KEY } : {}),
    },
    body: JSON.stringify({
      provider: "gemini",
      model: "gemini-4-carbon",
      prompt: `Create a React pricing card with Monthly/Annual toggle: ${prompt}`,
    }),
    signal: req.signal,
  });

  if (!upstream.ok || !upstream.body) {
    return new Response(await upstream.text(), { status: upstream.status });
  }

  return new Response(upstream.body, {
    headers: {
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
    },
  });
}
2. app/pricing-demo/page.tsx (createSession + DOMPatchApplier + Cancellation)tsx
'use client';
// app/pricing-demo/page.tsx — Connects createSession() to sandboxed DOMPatchApplier
import React, { useEffect, useRef, useState } from "react";
import { createSession } from "leveonas/sdk";

const IFRAME_SHELL = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://leveonas.ainot.site/leveonas-runtime.js"></script>
</head>
<body class="p-6 bg-white">
  <div id="leveonas-root" data-ast-id="leveonas-root"></div>
  <script>
    var root = document.getElementById("leveonas-root");
    var applier = null;
    window.addEventListener("message", function (event) {
      if (event.source !== window.parent) return;
      if (!event.data || event.data.type !== "leveonas:patch") return;
      var rt = window.LeveonasRuntime;
      if (!rt) return;
      if (!applier) {
        applier = new rt.DOMPatchApplier(root, document);
        applier.registerNode("leveonas-root", root);
      }
      var valid = rt.validatePatches(event.data.patches);
      applier.apply(valid);
    });
  </script>
</body>
</html>`;

export default function PricingDemoPage() {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [status, setStatus] = useState("Idle");
  const [error, setError] = useState<string | null>(null);
  const sessionRef = useRef<ReturnType<typeof createSession> | null>(null);

  useEffect(() => () => { sessionRef.current?.destroy(); }, []);

  async function runGeneration() {
    setError(null);
    setStatus("Streaming...");
    // Point createSession() to your own Next.js proxy route — zero keys in the browser
    const session = createSession({ endpoint: "/api/generate-stream" });
    sessionRef.current = session;

    try {
      for await (const event of session.generate("SaaS Pro plan card with badge and CTA")) {
        if (event.type === "generation:patch") {
          iframeRef.current?.contentWindow?.postMessage(
            { type: "leveonas:patch", patches: event.patch },
            "*"
          );
        } else if (event.type === "generation:error") {
          setError(event.error.message);
        } else if (event.type === "generation:complete") {
          setStatus(`Done · saved ${event.metrics.tokensSavedPercentage.toFixed(1)}% tokens`);
        }
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Stream failed");
      setStatus("Failed");
    } finally {
      session.destroy();
    }
  }

  return (
    <div className="max-w-3xl mx-auto p-6 space-y-4">
      <div className="flex items-center gap-3">
        <button onClick={runGeneration} className="h-10 px-5 rounded-full bg-[#1A73E8] text-white text-sm font-medium">
          Generate Pricing Card
        </button>
        <button onClick={() => sessionRef.current?.abort()} className="h-10 px-4 rounded-full border border-[#DADCE0] text-sm">
          Cancel
        </button>
        <span className="text-sm text-[#5F6368]">{status}</span>
      </div>
      {error && <p className="text-sm text-[#B3261E]">{error}</p>}
      <iframe ref={iframeRef} title="Preview" sandbox="allow-scripts" srcDoc={IFRAME_SHELL} className="w-full min-h-[420px] rounded-2xl border border-[#DADCE0]" />
    </div>
  );
}

Golden Path · Step 1 of 5

Create Your Leveonas & Provider Keys

1. Create a Leveonas API Key

Sign in at leveonas.ainot.site/login, open Dashboard → API Keys, and click Create API key. Copy the generated lv_live_... secret once—only its cryptographic hash is stored.

2. Add a Provider Key (Vault or Stateless Header)

Open Dashboard → Settings → Provider API keys and save your OpenAI, Gemini, Anthropic, xAI, Meta, or custom provider key (stored encrypted with AES-256-GCM)—or skip Vault and pass x-user-llm-key per request from your server.

Golden Path · Step 2 of 5

Install into Your Backend Project

Requires Node.js 18+. For the OpenAI-Compatible Proxy path, installing openai alone is enough. Add leveonas if you call compile() or createSession().

Terminal — Backend rootbash
# 1. Inside your existing Node.js (>= 18) or Bun backend project
npm install openai leveonas@0.6.0
# Or with pnpm / yarn / Bun:
# pnpm add openai leveonas@0.6.0
# bun add openai leveonas@0.6.0

# 2. Verify installation immediately
npx leveonas --version
node -e "import('leveonas').then(m => console.log('SDK:', m.VERSION, Object.keys(m).join(', ')))"

# 3. (Optional) Global CLI for standalone compiler server
npm install -g leveonas@0.6.0

Golden Path · Step 3 of 5

Where to Keep Files & Wire Your Server Route

Keep LEVEONAS_API_KEY strictly on the backend. Notice that Next.js loads .env.local automatically, whereas standalone Express / Node apps load .env via dotenv.

Next.js repository layouttext
my-nextjs-app/
├── .env.local                  # Next.js automatically loads .env.local on the server
├── lib/
│   └── leveonas.ts             # Shared OpenAI SDK client pointed at Leveonas proxy
├── app/
│   ├── api/
│   │   └── ai/
│   │       └── route.ts        # Backend POST route (never expose keys to client)
│   └── page.tsx                # React page calling /api/ai and rendering output
└── package.json
.env.localdotenv
# .env.local (Next.js root beside package.json — keep out of git)
LEVEONAS_API_KEY="lv_live_paste_your_leveonas_key_here"

# Optional if your provider key is already saved in Dashboard -> Settings Vault:
GEMINI_API_KEY="AIzaSy..."
lib/leveonas.tstypescript
// lib/leveonas.ts — Server-only helper (never import into 'use client' files)
import OpenAI from "openai";

if (!process.env.LEVEONAS_API_KEY) {
  throw new Error("Missing LEVEONAS_API_KEY in .env.local");
}

export const leveonasAI = new OpenAI({
  baseURL: "https://leveonas.ainot.site/api/v1",
  apiKey: process.env.LEVEONAS_API_KEY,
  defaultHeaders: {
    // Omit if saved in Dashboard -> Settings -> Provider API keys
    ...(process.env.GEMINI_API_KEY
      ? { "x-gemini-key": process.env.GEMINI_API_KEY }
      : {}),
  },
});
app/api/ai/route.tstypescript
// app/api/ai/route.ts
import { NextRequest, NextResponse } from "next/server";
import { leveonasAI } from "@/lib/leveonas";

export async function POST(req: NextRequest) {
  const { prompt, provider = "gemini", model = "gemini-4-carbon" } = await req.json();

  if (!prompt || typeof prompt !== "string") {
    return NextResponse.json({ error: "prompt is required" }, { status: 400 });
  }

  const completion = await leveonasAI.chat.completions.create(
    {
      model,
      stream: false,
      messages: [
        { role: "system", content: "Return a single self-contained Tailwind HTML or React component." },
        { role: "user", content: prompt },
      ],
    },
    {
      headers: {
        // Explicit routing header — cleanly typed with zero TypeScript suppressions
        "x-leveonas-provider": provider,
      },
    }
  );

  return NextResponse.json({
    code: completion.choices[0]?.message?.content ?? "",
    leveonas: (completion as { leveonas?: unknown }).leveonas ?? null,
  });
}

Golden Path · Step 4 of 5

Render Your First Generated UI

Once your backend returns compiled output from Leveonas, render it safely inside a sandboxed iframe, stream live DOM patches with /leveonas.js, or write multi-file TSX output directly to disk.

app/page.tsx — Call /api/ai and preview safely inside <iframe sandbox='allow-scripts'>tsx
// app/page.tsx — Complete working generator + sandboxed preview UI
'use client';

import React, { useState } from "react";

export default function GeneratorPage() {
  const [prompt, setPrompt] = useState("Build a responsive SaaS pricing section with two plans");
  const [previewDoc, setPreviewDoc] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleGenerate(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    try {
      // 1. Ask your backend route (which calls /api/v1/chat/completions) for compiled UI
      const res = await fetch("/api/ai", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt }),
      });
      const { code } = await res.json();

      // 2. Wrap compiled HTML/CSS inside a standalone preview document (no allow-same-origin)
      const html = `<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body class="p-6 bg-white text-slate-900">${code}</body>
</html>`;
      setPreviewDoc(html);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="max-w-3xl mx-auto p-6 space-y-6">
      <form onSubmit={handleGenerate} className="flex gap-3">
        <input
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          className="flex-1 h-11 px-4 rounded-xl border border-slate-300"
        />
        <button
          type="submit"
          disabled={loading}
          className="h-11 px-6 rounded-full bg-[#1A73E8] text-white font-medium"
        >
          {loading ? "Generating..." : "Generate UI"}
        </button>
      </form>

      {previewDoc && (
        <iframe
          title="Generated UI Preview"
          sandbox="allow-scripts"
          srcDoc={previewDoc}
          className="w-full min-h-[420px] rounded-2xl border border-slate-200 bg-white"
        />
      )}
    </div>
  );
}

Golden Path · Step 5 of 5

Test & Verify in Dashboard

Run this smoke test command, then check Dashboard → Overview, Usage, and History to see real request counts, model latency, raw LM source, and token reduction metrics.

First smoke test requestbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-leveonas-provider: gemini" \
  -H "x-user-llm-key: AIzaSy_your_provider_key" \
  -d '{
    "model": "gemini-4-carbon",
    "stream": false,
    "messages": [
      { "role": "user", "content": "Create a minimal pricing card in React" }
    ]
  }'

Core Concepts · Docs v0.6.0 · npm leveonas@0.6.0

Canonical LM Syntax & Common UI IR

Leveonas uses Canonical LM v1 where every element places its tag before parentheses (tag(attr(val) child)) inside explicit block boundaries such as <REACT>, <HTML>, or <PYTHON>. Legacy Lisp-style leading parentheses such as (di cs:"card") are deprecated and return LM-DIALECT-001.

Canonical LM v1 vs. deprecated Lisp syntaxlm
# ✅ CANONICAL LM SYNTAX (v1) — Always place tag BEFORE parentheses
<REACT>
component(Counter)(
  state(count, 0)
  di(cs(p-6 rounded-xl border)
    h2(cs(text-lg font-semibold) Counter)
    bo(tp(button) oc(count++) Count: {count})
  )
)
</REACT>

# ❌ LEGACY / REJECTED S-EXPRESSIONS (Returns LM-DIALECT-001)
# Never wrap elements in leading parens or use attr:"value" colons:
(di cs:"p-6" (h2 "Counter") (bo oc:"count++" "Count"))
Common UI IR vs. Direct Emitters: Declarative UI frameworks (react, nextjs, vue, svelte, angular) lower through the framework-neutral Common UI IR to synchronize state, computed values, and incremental DOM patches. The other 43 targets compile directly through dedicated LM interpreters or AST serializers.

How Token Reduction Is Measured

Leveonas calculates token savings deterministically on every compiled response using exact o200k_base BPE tokenization (gpt-tokenizer), comparing the compact LM tokens generated by the upstream LLM against the full conventional source code delivered to your server:

savedTokens = compiledTokens - lmTokens
tokensSavedPercentage = ((compiledTokens - lmTokens) / compiledTokens) × 100
lmTokens
Exact BPE token count of the compact LM streamed back from OpenAI, Gemini, Anthropic, xAI, or Meta. This directly reflects your output-token spend with the upstream LLM provider.
compiledTokens
BPE token count of the compiled native code (React TSX, HTML, CSS, SQL, Python) that your backend actually receives without needing the LLM to generate boilerplate closing tags.
Typical observed range
UI markup and component code typically save 50%–72% output tokens; passthrough native blocks report 0% savings with zero quality degradation.

Interactive Request Builder

Select a provider keyword and model ID to generate an exact request with zero spelling mismatches.

Provider

Exact provider string: openai

All lowercase with dots for minor versions (e.g. gpt-6.2-sol, gpt-6.2-astra, gpt-4.1).
POST /api/v1/chat/completionsbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-leveonas-provider: openai" \
  -H "x-user-llm-key: sk-proj-..." \
  -d '{
    "provider": "openai",
    "model": "gpt-6.2-sol",
    "stream": false,
    "messages": [
      { "role": "user", "content": "Build a responsive pricing card in React" }
    ]
  }'

Authentication & Credentials

Leveonas Keys, Provider Key Resolution & Rotation

Every request to Leveonas validates your lv_live_... Leveonas API key (sent via Authorization: Bearer lv_live_... or X-Leveonas-Key). When an endpoint invokes an upstream LLM (/api/v1/chat/completions or /api/generate), Leveonas resolves the upstream model provider credential in strict priority order:

PriorityCredential SourceBehavior & Precedence
1 (Highest)x-user-llm-key / x-provider-keyPer-request header. Overrides any key saved in environment variables or Dashboard Vault. Ideal for multi-tenant SaaS apps bringing user keys.
2x-<provider>-keyProvider-scoped header (x-openai-key, x-gemini-key, x-anthropic-key, x-xai-key, x-meta-key).
3Server EnvironmentHost environment fallback (OPENAI_API_KEY, GEMINI_API_KEY, ANTHROPIC_API_KEY, XAI_API_KEY, META_API_KEY) when running self-hosted.
4 (Fallback)Dashboard VaultAES-256-GCM encrypted key stored for your account under Settings → Provider API keys.
Zero-downtime key rotation & revocation: Under Dashboard → API Keys, issue a second lv_live_... key, deploy the new key to your servers, confirm traffic on the new key prefix in Dashboard Usage, and click Revoke on the old key. Revoked keys fail immediately with 401 LM-AUTH-001.
What if both Vault and a request header exist? Header credentials (#1 and #2) always win for that specific HTTP request without overwriting your stored Vault entry.

Verified Catalog · Last verified 2026-11-29

Exact Provider Keyword Spellings

Pass one of these exact strings in the x-leveonas-provider header (recommended for typed OpenAI SDK usage) or inside the JSON provider field. To fetch this list programmatically—including your authenticated custom providers—call GET /api/models.

ProviderExact keywordAliasKey headerDo not pass
OpenAI
openai
—x-openai-keyopen-ai, open_ai, OpenAI
Google Gemini
gemini
—x-gemini-keygoogle, google-gemini, google_ai
Anthropic
anthropic
—x-anthropic-keyclaude, anthropic-ai, claude-sonnet-5.5
xAI (Grok)
xai
grokx-xai-keyx-ai, x_ai, x.ai
Meta Llama
meta
llamax-meta-keymeta-ai, facebook, meta_llama

OpenAI

Provider keyword: openai · Header: x-openai-key · Protocol: OpenAI Chat Completions JSON / SSE

Spelling rule: All lowercase with dots for minor versions (e.g. gpt-6.2-sol, gpt-6.2-astra, gpt-4.1).
Upstream endpoint: https://api.openai.com/v1/chat/completions
Model IDSeriesStatusTierNotes
gpt-6.2-astra
GPT-6.2RecommendedFrontierFlagship OpenAI reasoning, multi-step coding, and agentic workflows (Nov 2026)
gpt-6.2-sol
GPT-6.2RecommendedBalanced FrontierRecommended balanced model for fast UI generation, coding, and tool calls
gpt-6-sol
GPT-6LegacyPrevious GenEarlier GPT-6 Sol checkpoint; prefer gpt-6.2-sol for new integrations
gpt-6-luna
GPT-6AvailableFast / ValueCost-efficient high-throughput UI & LM streaming
gpt-5
GPT-5LegacyStandardBase alias (dated snapshot: gpt-5-2025-08-07)
gpt-5-codex
GPT-5LegacyCodingSpecialized GPT-5 variant for agentic code generation
gpt-4.1
GPT-4.1LegacyLong ContextNon-reasoning flagship (dated: gpt-4.1-2025-04-14, plus gpt-4.1-mini)
o3
o-SeriesAvailableReasoningHigh-depth reasoning (also o3-pro and compact o4-mini)
gpt-4o
GPT-4oLegacyLegacy DefaultLegacy compatibility alias (also gpt-4o-mini)
OpenAI requestbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-openai-key: sk-proj-your_openai_key" \
  -d '{
    "provider": "openai",
    "model": "gpt-6.2-sol",
    "messages": [{ "role": "user", "content": "Create a responsive navbar component" }]
  }'

Google Gemini

Provider keyword: gemini · Header: x-gemini-key · Protocol: Gemini v1beta generateContent / streamGenerateContent

Spelling rule: Lowercase hyphenated string without the "models/" path prefix (Leveonas inserts "models/" automatically).
Upstream endpoint: https://generativelanguage.googleapis.com/v1beta/models/{model}:streamGenerateContent
Model IDSeriesStatusTierNotes
gemini-4-carbon
Gemini 4RecommendedFrontierHighest-capability frontier model for multi-step engineering
gemini-4-neon
Gemini 4RecommendedBalanced FrontierFrontier reasoning tuned for fast production execution
gemini-4-hydrogen
Gemini 4RecommendedFast / EverydayLow-latency daily coding, LM emission, and progressive UI generation
gemini-4-argon
Gemini 4AvailableAnalyticalDeep analytical & scientific problem-solving variant
gemini-3.8-flash
Gemini 3.8AvailableWorkhorseHigh-intelligence workhorse for long-horizon coding loops
gemini-3.8-live
Gemini 3.8AvailableLive RealtimeLow-latency multimodal live session model
gemini-3.5-flash-lite
Gemini 3.5LegacyUltra-LightHigh-throughput lightweight tasks and fast patching
Google Gemini requestbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-gemini-key: AIzaSy_your_gemini_key" \
  -d '{
    "provider": "gemini",
    "model": "gemini-4-carbon",
    "messages": [{ "role": "user", "content": "Create a billing overview page in Next.js" }]
  }'

Anthropic

Provider keyword: anthropic · Header: x-anthropic-key · Protocol: Anthropic Messages API (/v1/messages)

Spelling rule: Strictly lowercase with HYPHENS between major and minor version numbers (e.g. claude-sonnet-5-5, NEVER 5.5).
Upstream endpoint: https://api.anthropic.com/v1/messages
Model IDSeriesStatusTierNotes
claude-opus-5-5
Claude 5.5RecommendedFrontierTop-tier Claude intelligence for full-stack architecture
claude-sonnet-5-5
Claude 5.5RecommendedBalanced FlagshipRecommended default for builders, tool calls, and clean LM
claude-haiku-5-5
Claude 5.5RecommendedFast / ValueSub-second responses for patches and rapid UI iteration
claude-fable-5-2
Claude 5.2AvailableExtended SynthesisSpecialized long-form structured generation and documentation
claude-opus-4-6
Claude 4LegacyLegacy FrontierClaude Opus 4.6 identifier (also claude-opus-4-5)
claude-sonnet-4-20250514
Claude 4LegacyDated SnapshotPinned Claude Sonnet 4 snapshot (alias: claude-sonnet-4)
Anthropic requestbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-anthropic-key: sk-ant-api03-your_anthropic_key" \
  -d '{
    "provider": "anthropic",
    "model": "claude-sonnet-5-5",
    "messages": [{ "role": "user", "content": "Create a multi-step checkout form" }]
  }'

xAI (Grok)

Provider keyword: xai · Header: x-xai-key · Protocol: OpenAI-Compatible Chat Completions

Spelling rule: Provider keyword is "xai" (alias "grok"). Model version numbers use DOTS (e.g. grok-4.7, NOT grok-4-7).
Upstream endpoint: https://api.x.ai/v1/chat/completions
Model IDSeriesStatusTierNotes
grok-4.7
Grok 4RecommendedFlagshipLatest xAI flagship API model string (uses dot: 4.7)
grok-4.6
Grok 4AvailableProductionHigh-speed Grok 4.6 release string (uses dot: 4.6)
grok-4.5
Grok 4AvailableStandardBalanced Grok 4.5 checkpoint (uses dot: 4.5)
grok-4
Grok 4LegacyBase AliasUnversioned Grok 4 routing alias
grok-3-reasoning
Grok 3LegacyReasoningExtended chain-of-thought variant (base: grok-3)
xAI (Grok) requestbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-xai-key: xai-your_xai_api_key" \
  -d '{
    "provider": "xai",
    "model": "grok-4.7",
    "messages": [{ "role": "user", "content": "Build an interactive SaaS metrics grid" }]
  }'

Meta Llama

Provider keyword: meta · Header: x-meta-key · Protocol: OpenAI-Compatible Chat Completions

Spelling rule: Provider keyword is lowercase "meta" (alias "llama"). Native Meta Llama API model IDs are TitleCase exact strings.
Upstream endpoint: https://api.llama.com/compat/v1/chat/completions
Model IDSeriesStatusTierNotes
Llama-4-Maverick-17B-128E-Instruct-FP8
Llama 4RecommendedFlagship MoE128-expert Mixture-of-Experts model; exact TitleCase + FP8 suffix required
Llama-4-Scout-17B-16E-Instruct-FP8
Llama 4RecommendedLong Context MoE16-expert fast long-context model on api.llama.com/compat/v1
Llama-3.3-70B-Instruct
Llama 3.3AvailableDense 70BInstruction-tuned 70B checkpoint on native Llama API
Llama-3.3-8B-Instruct
Llama 3.3AvailableFast 8BLow-latency compact instruction checkpoint
meta-llama/Meta-Llama-3.1-405B-Instruct
Llama 3.1LegacyDense 405BHuggingFace / OpenAI-compat full namespace identifier
Meta Llama requestbash
curl -X POST https://leveonas.ainot.site/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer lv_live_your_leveonas_api_key" \
  -H "x-meta-key: LLM|your_meta_llama_api_key" \
  -d '{
    "provider": "meta",
    "model": "Llama-4-Maverick-17B-128E-Instruct-FP8",
    "messages": [{ "role": "user", "content": "Generate a FastAPI CRUD router" }]
  }'

Custom AI Providers (Groq, Together, OpenRouter, Private vLLM)

Need an inference provider outside the five built-ins (such as Groq, Together AI, OpenRouter, DeepSeek, Fireworks, Mistral, or an internal vLLM/Ollama gateway)? Register it once in Dashboard Vault or route it dynamically per request via HTTP headers.

1. Open Add provider
Navigate to Dashboard → Settings → Provider API keys and click Add provider.
2. Pick wire protocol
Select openai-compatible (Groq, Together, OpenRouter, vLLM), anthropic-messages, or gemini-generate.
3. Slug & endpoint URL
Set provider slug groq and endpoint https://api.groq.com/openai/v1. For openai-compatible protocols, Leveonas automatically appends /chat/completions when a base /v1 URL is entered (or preserves the full .../chat/completions path verbatim).
4. Save & call
Your key is encrypted with AES-256-GCM. Pass x-leveonas-provider: groq and your provider model ID (for example llama-3.3-70b-versatile).
Option A — Calling a custom provider saved in Dashboard Vaulttypescript
// Calling a custom provider after saving "groq" in Dashboard -> Settings -> Add provider
const completion = await leveonas.chat.completions.create(
  {
    model: "llama-3.3-70b-versatile",
    messages: [{ role: "user", content: "Build a dashboard KPI card in React" }],
  },
  {
    headers: {
      // Matches the lowercase slug saved in Dashboard -> Settings ("groq")
      "x-leveonas-provider": "groq",
    },
  }
);
Option B — Stateless per-request custom provider routing (no Vault save required)typescript
// Calling Groq using stateless custom-provider headers (no Vault setup needed)
import OpenAI from "openai";

const leveonas = new OpenAI({
  baseURL: "https://leveonas.ainot.site/api/v1",
  apiKey: process.env.LEVEONAS_API_KEY,
});

const completion = await leveonas.chat.completions.create(
  {
    model: "llama-3.3-70b-versatile",
    stream: false,
    messages: [{ role: "user", content: "Create a clean pricing card in React" }],
  },
  {
    headers: {
      "x-leveonas-provider": "groq",
      "x-provider-sdk": "openai-compatible",
      "x-provider-endpoint": "https://api.groq.com/openai/v1/chat/completions",
      "x-user-llm-key": process.env.GROQ_API_KEY!,
    },
  }
);

console.log(completion.choices[0]?.message?.content);

Python & Non-JavaScript Backends

Any language with an OpenAI client or HTTP library works out of the box against https://leveonas.ainot.site/api/v1. Below is a verified Python example using the official openai package with python-dotenv.

app.py — Python OpenAI SDK via Leveonaspython
# pip install openai python-dotenv
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

client = OpenAI(
    base_url="https://leveonas.ainot.site/api/v1",
    api_key=os.environ["LEVEONAS_API_KEY"],
    default_headers={
        # Omit if your provider key is already saved in Dashboard -> Settings Vault
        "x-user-llm-key": os.environ["GEMINI_API_KEY"],
    },
)

completion = client.chat.completions.create(
    model="gemini-4-carbon",
    extra_headers={"x-leveonas-provider": "gemini"},
    messages=[
        {"role": "system", "content": "Generate clean responsive React components."},
        {"role": "user", "content": "Create a dark settings modal"},
    ],
)

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

Streaming & Browser Runtime

SSE Event Protocol, Cancellation & Sandboxed Preview Bridge

When calling POST /api/generate (or using createSession() from leveonas/sdk), Leveonas parses LLM tokens incrementally as they arrive, reconciles the tree in real time, and emits typed Server-Sent Events before the full response finishes.

Exact wire format emitted by POST /api/generatetext
# 1. Session initiation frame -> SDK emits "generation:start"
data: {"session":{"id":"lev_sess_m9k42a","provider":"gemini","model":"gemini-4-carbon","timestamp":"2026-11-29T00:00:00.000Z"}}

# 2. Incremental PatchOperation[] frames -> SDK emits "generation:patch"
data: {"patch":[{"operation":"CREATE_NODE","nodeId":"n1","parentId":"leveonas-root","index":0,"payload":{"node":{"id":"n1","kind":"element","name":"div","properties":{"className":{"type":"literal","value":"p-6 rounded-xl"}},"children":[]}}}]}

# 3. Optional raw LM text debug chunk (emitted when emitDebugText === true) -> SDK emits "generation:chunk"
data: {"text":"di(cs(p-6 rounded-xl) h2(Booking Summary))"}

# 4. Optional error event if stream aborts or exceeds limits -> SDK emits "generation:error"
data: {"error":"Stream size limit exceeded (5242880 bytes)"}

# 5. Final telemetry + stream sentinel -> SDK emits "generation:complete" on [DONE]
data: {"telemetry":{"lmTokens":112,"compiledTokens":398,"tokensSavedPercentage":71.9}}
data: [DONE]

Three Browser Runtime Distributions

Choose the runtime distribution that fits your architecture. When hosting in production with strict Content Security Policy headers, include script-src 'self' https://leveonas.ainot.site (no 'unsafe-eval' required for DOM patches). Always call session.destroy() and applier.reset() on unmount.

DistributionHow to LoadPrimary Exports / GlobalBest For
leveonas/runtimenpm ESM subpath importDOMPatchApplier, JSPatchApplier, validatePatchesBundled React / Next.js / Vite apps validating patches before postMessage
/leveonas-runtime.jsIIFE <script> tagwindow.LeveonasRuntime.DOMPatchApplierSandboxed <iframe sandbox="allow-scripts"> preview shells receiving patches
/leveonas.jsIIFE <script> tagwindow.Leveonas.Engine (+ Runtime)Zero-bundler HTML pages streaming directly from /api/generate
Handling createSession() events, cancellation, and cleanuptypescript
import { createSession } from "leveonas/sdk";

const session = createSession({
  endpoint: "https://leveonas.ainot.site/api/generate",
  apiKey: process.env.LEVEONAS_API_KEY,
  provider: "gemini",
  model: "gemini-4-carbon",
});

// Cancel cleanly after 15s or on user click:
const timer = setTimeout(() => session.abort(), 15_000);

try {
  for await (const event of session.generate("Build an interactive flight search bar")) {
    switch (event.type) {
      case "generation:start":
        console.log("Started at", event.timestamp);
        break;
      case "generation:patch":
        // Forward array of PatchOperation to your sandboxed iframe bridge
        applyPatchBatch(event.patch);
        break;
      case "generation:chunk":
        // Present when emitDebugText is enabled
        process.stdout.write(event.delta);
        break;
      case "generation:diagnostic":
        console.warn("Compiler diagnostic:", event.diagnostic);
        break;
      case "generation:error":
        console.error("Stream error:", event.error.message);
        break;
      case "generation:complete":
        console.log("Final metrics:", event.metrics);
        break;
    }
  }
} finally {
  clearTimeout(timer);
  session.destroy();
}

Sandboxed Iframe Bridge (/leveonas-runtime.js)

Because untrusted user prompts can emit interactive handlers, always mount DOMPatchApplier inside an iframe configured strictly with sandbox="allow-scripts" (omitting allow-same-origin) and verify event.source === window.parent before applying batches.

components/LivePatchPreview.tsxtsx
'use client';

import React, { useEffect, useRef } from "react";

interface LivePatchPreviewProps {
  patches: unknown[];
}

export function LivePatchPreview({ patches }: LivePatchPreviewProps) {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  const srcdoc = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <script src="https://leveonas.ainot.site/leveonas-runtime.js"></script>
</head>
<body>
  <div id="leveonas-root" data-ast-id="leveonas-root"></div>
  <script>
    var root = document.getElementById("leveonas-root");
    var applier = null;
    window.addEventListener("message", function (event) {
      // Security: opaque iframe origin requires verifying event.source === window.parent
      if (event.source !== window.parent) return;
      if (!event.data || event.data.type !== "leveonas:patch") return;
      var rt = window.LeveonasRuntime;
      if (!rt) return;
      if (!applier) {
        applier = new rt.DOMPatchApplier(root, document);
        applier.registerNode("leveonas-root", root);
      }
      var valid = rt.validatePatches ? rt.validatePatches(event.data.patches) : event.data.patches;
      applier.apply(valid);
    });
  </script>
</body>
</html>`;

  useEffect(() => {
    const win = iframeRef.current?.contentWindow;
    if (!win || patches.length === 0) return;
    win.postMessage({ type: "leveonas:patch", patches }, "*");
  }, [patches]);

  return (
    <iframe
      ref={iframeRef}
      title="Leveonas Live Preview"
      sandbox="allow-scripts"
      srcDoc={srcdoc}
      className="w-full min-h-[420px] border border-[#DADCE0] rounded-[16px] bg-white"
    />
  );
}

AI Website Builders (Lovable, Bolt.new, v0, Replit, Cursor)

POST /api/v1/chat/completions automatically detects agentic tools (write_file, edit_file) and artifact tags (<boltAction>, <FILE>), injects LM optimization directives into the system prompt, and compiles tool call payloads back into native code before returning chunks to your builder.

Builder proxy configurationdotenv
# AI Builder Base URL Drop-in (Lovable, Bolt.new, Replit Agent, v0, Cursor)
OPENAI_BASE_URL="https://leveonas.ainot.site/api/v1"
OPENAI_API_KEY="lv_live_your_leveonas_api_key"
# Include header "x-user-llm-key: <provider_key>" OR save your provider key in Dashboard Vault

HTTP API Reference

Complete Endpoint Schemas & Payloads

All protected endpoints require a valid lv_live_... key via Authorization: Bearer or X-Leveonas-Key. Missing/invalid keys return 401 with code: "LM-AUTH-001"; malformed JSON or invalid targets return 400. See the standalone REST API Reference for complete header and body schemas.

EndpointUpstream Key Needed?Key ScopePurpose
POST /api/v1/chat/completionsYes (Header / Vault)write:streamOpenAI-compatible proxy with auto LM compilation & token telemetry
POST /api/generateYes (Header / Vault)write:streamDirect SSE pipeline emitting real-time patch & telemetry events
POST /api/compileNo (Leveonas key only)read:compileDeterministically compiles LM source across 48 targets into code, HTML, AST & UI IR
POST /api/patchNo (Leveonas key only)read:compileParses or applies <PATCH> SEARCH/REPLACE blocks against virtual files map
POST /api/validate & /api/verifyNo (Leveonas key only)read:compileSyntax validation, security audit, and post-compile output verification
GET /api/modelsNo (Optional session/key)Public / AuthLive model catalog with status, lastVerified, and user custom providers
POST /api/v1/chat/completions — Request & JSON Responsejson
// Request: POST https://leveonas.ainot.site/api/v1/chat/completions
{
  "model": "gemini-4-carbon",
  "stream": false,
  "compileOutput": true,
  "messages": [
    { "role": "user", "content": "Create a minimal pricing card in React" }
  ]
}

// 200 OK Response
{
  "id": "chatcmpl_lev_m9k42a_9b1c",
  "object": "chat.completion",
  "created": 1796025600,
  "model": "gemini-4-carbon",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "import React from 'react';\nexport function PricingCard() { ... }"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 180, "completion_tokens": 210, "total_tokens": 390 },
  "leveonas": {
    "sessionId": "lev_sess_m9k42a",
    "workflow": "chat-completions",
    "compiledUnits": 1,
    "lmTokens": 114,
    "compiledTokens": 412,
    "tokensSavedPercentage": 72.3
  }
}
POST /api/compile — Request & JSON Responsejson
// Request: POST https://leveonas.ainot.site/api/compile
// Headers: Content-Type: application/json | Authorization: Bearer lv_live_...
{
  "source": "<REACT>\ncomponent(Counter)(state(count, 0) di(cs(p-6) bo(oc(count++) Count: {count})))\n</REACT>",
  "framework": "react",
  "documentMode": true,
  "title": "Counter Preview"
}

// 200 OK Response
{
  "success": true,
  "compiledBy": "leveonas-server",
  "version": "0.6.0",
  "detectedTarget": "react",
  "code": "import React, { useState } from 'react';\nexport function Counter() { ... }",
  "html": "<div class=\"p-6\"><button>Count: 0</button></div>",
  "document": "<!DOCTYPE html>\n<html>...</html>",
  "sections": [
    { "title": "React (TSX)", "language": "tsx", "blockType": "react", "code": "...", "mode": "compiled" }
  ],
  "ast": { "kind": "ReactProgram", "components": [ "..." ] },
  "uiIR": { "kind": "UIIRProgram", "components": [ "..." ] },
  "diagnostics": [],
  "tokenStats": {
    "lmTokens": 24,
    "compiledTokens": 89,
    "savedTokens": 65,
    "savingsPercent": 73.0,
    "encoding": "o200k_base"
  }
}
POST /api/patch — Request & JSON Responsejson
// Request: POST https://leveonas.ainot.site/api/patch
// Headers: Content-Type: application/json | Authorization: Bearer lv_live_...
{
  "patch": "<PATCH file=\"app/page.tsx\">\n<<<SEARCH\n<h1>Old Title</h1>\n===\n<h1>Leveonas Production</h1>\n>>>\n</PATCH>",
  "files": {
    "app/page.tsx": "export default function Page() { return <h1>Old Title</h1>; }"
  }
}

// 200 OK Response
{
  "success": true,
  "version": "0.6.0",
  "files": {
    "app/page.tsx": "export default function Page() { return <h1>Leveonas Production</h1>; }"
  },
  "applied": [
    { "file": "app/page.tsx", "type": "search-replace", "line": 1 }
  ],
  "failed": [],
  "diagnostics": []
}

OpenAI Feature Compatibility & Cross-Provider Translation

Requests arriving at /api/v1/chat/completions are automatically translated into native Anthropic (/v1/messages) and Google Gemini (streamGenerateContent) wire formats, while OpenAI, xAI, Meta Llama, and OpenAI-compatible gateways receive OpenAI JSON directly.

OpenAI ParameterSupport StatusCross-Provider Translation Notes
messages (system, developer, user, assistant)SupportedMapped to system for Anthropic, systemInstruction + model/user for Gemini.
stream (boolean)Supported (Cloud)Cloud emits standard OpenAI chat.completion.chunk SSE. Self-hosted leveonas serve returns non-streaming JSON.
tools (function declarations)SupportedTranslated to Anthropic tool_use and Gemini functionDeclarations; responses normalize back to OpenAI tool_calls.
tool_choicePartialForwarded verbatim to OpenAI, xAI, Meta, and custom OpenAI-compat servers; not forwarded to Anthropic/Gemini adapters.
temperature, max_tokensSupportedForwarded across all providers (mapped to maxOutputTokens on Gemini).
seedPartialSupported on OpenAI, xAI, Meta, and Gemini; ignored by Anthropic Messages API.
response_format, n > 1, image_url partsNot SupportedNot forwarded in proxy translation yet; pass text messages[].content strings and request JSON inside your prompt or compile via LM.

All 48 Supported Compilation Targets & Stability Tiers

These exact 48 target identifiers match SUPPORTED_TARGETS in @leveonas/compile-service (v0.6.0): 35 Stable production targets (5 Common UI IR frameworks, 9 Web Core, 8 Backend/DB, 13 Config/Infra/Patch) and 13 Beta Mobile/Polyglot targets.

UI Frameworks (5 Common UI IR + Reconciler Targets) · Stable

Common UI IR + Codegen + DOM/JS Reconciler + Live Patches
Target IDLM Block TagStabilityCompiled Output
react<REACT>StableReact TSX + DOM + JS
nextjs<NEXTJS>StableNext.js TSX + DOM + JS
vue<VUE>StableVue 3 SFC + DOM + JS
svelte<SVELTE>StableSvelte Component + DOM + JS
angular<ANGULAR>StableAngular TS + DOM + JS

Web Core & Styling (9 Targets) · Stable

Framework AST / Direct Target Emitter
Target IDLM Block TagStabilityCompiled Output
html<HTML>StableSemantic HTML5 (+ Document Mode)
tailwind<TAILWIND>StableHTML5 + Tailwind classes
css<CSS>StableStylesheet (.css)
scss<SCSS>StableSass/SCSS (.scss)
js<JS>StableJavaScript ES module
ts<TS>StableTypeScript or lowered JS
solid<SOLID>StableSolidJS TSX
astro<ASTRO>StableAstro component (.astro)
svg<SVG>StableVector SVG markup

Backend & Databases (8 Targets) · Stable

Dedicated LM Interpreters
Target IDLM Block TagStabilityCompiled Output
python<PYTHON>StableFastAPI / Python
node<NODE>StableExpress / Hono / Node TS
sql<SQL>StablePostgreSQL / RLS DDL
prisma<PRISMA>Stableschema.prisma
drizzle<DRIZZLE>StableDrizzle ORM TypeScript
mongo<MONGO>StableMongoose / Mongo schema
graphql<GRAPHQL>StableGraphQL SDL
rules<RULES>StableFirestore / Storage Rules

Mobile & Polyglot Languages (13 Targets) · Beta

Dedicated LM Interpreters (Codegen & Syntax Parity)
Target IDLM Block TagStabilityCompiled Output
react-native<REACT-NATIVE>BetaExpo / React Native TSX
dart<DART>BetaFlutter / Dart widget
swift<SWIFT>BetaSwiftUI view
kotlin<KOTLIN>BetaJetpack Compose / Kotlin
go<GO>BetaGo source (.go)
rust<RUST>BetaRust / Axum (.rs)
java<JAVA>BetaJava / Spring (.java)
php<PHP>BetaPHP / Laravel (.php)
csharp<CSHARP>BetaC# / .NET (.cs)
ruby<RUBY>BetaRuby / Rails (.rb)
cpp<CPP>BetaC / C++ (.cpp)
elixir<ELIXIR>BetaElixir / Phoenix (.ex)
lua<LUA>BetaLua script (.lua)

Config, Infrastructure, Templates & Patches (13 Targets) · Stable

Structured Emitters & Diff Patch Engine
Target IDLM Block TagStabilityCompiled Output
patch<PATCH>StableSEARCH/REPLACE file patch
json<JSON>StableFormatted JSON
yaml<YAML>StableYAML manifest
toml<TOML>StableTOML config
env<ENV>StableDotenv (.env)
dockerfile<DOCKERFILE>StableDockerfile
shell<SHELL>StablePOSIX / Bash script
terraform<TERRAFORM>StableTerraform HCL (.tf)
protobuf<PROTOBUF>StableProtocol Buffers (.proto)
makefile<MAKEFILE>StableMakefile
xml<XML>StableXML / Manifest / Plist
markdown<MARKDOWN>StableMarkdown / MDX
template<TEMPLATE>StableJinja2 / EJS / Blade / HBS

Package Reference · v0.6.0

SDK Functions: Synchronous Offline vs. Async Server

Know at a glance which functions execute deterministically offline in Node/browser memory versus which functions open authenticated HTTP requests to Leveonas Server. See the full TypeScript SDK & Browser Runtime Reference for all exported interfaces.

Function / EntryExecutionNetwork / Key RequiredReturns
compile(source, opts)Async (Promise)Yes — POST /api/compile + lv_live_...code, html, document, sections, ast, uiIR
createSession(cfg) (leveonas/sdk)Async (AsyncIterable)Yes — POST /api/generate + both keysStreamingEvent stream + abort()
parse(source, opts)SyncNo (Offline local)Typed framework ParsedAST union
lower(astOrSource, fw)SyncNo (Offline local)Framework-neutral UIIRProgramNode
inspect(source)SyncNo (Offline local)Reactivity Graph, symbols, AST, DOM patches
format(source, opts)SyncNo (Offline local)Canonical formatted LM string
diagnose(source, opts)SyncNo (Offline local)LSPDiagnostic[] errors & warnings
Two-tier error handling for compile() (network exceptions + semantic diagnostics)typescript
import { compile, type CompileOptions, type CompileResult } from "leveonas";

async function compileSnippet(source: string): Promise<CompileResult | null> {
  const options: CompileOptions = {
    framework: "react",
    target: "all", // 'all' | 'ui-ir' | 'dom' | 'patches'
    documentMode: true,
    apiKey: process.env.LEVEONAS_API_KEY,
  };

  try {
    // Tier 1: Throws only on network failure, 401/403 HTTP error, or malformed request
    const result = await compile(source, options);

    // Tier 2: Check semantic LM syntax or validation diagnostics
    if (!result.success) {
      for (const diag of result.diagnostics) {
        console.error(`[${diag.code}] Line ${diag.line}: ${diag.message}`);
      }
      return null;
    }

    return result;
  } catch (err) {
    console.error("Transport or authentication failure:", err);
    throw err;
  }
}
Strongly typed SDK contracts exported by leveonas & leveonas/sdktypescript
// Exported directly from "leveonas" and "leveonas/sdk" (v0.6.0)
export type LMFramework = "html" | "react" | "nextjs" | "tailwind" | "vue" | "svelte" | "angular" | "auto";

export interface ParseOptions {
  framework?: LMFramework;
  strict?: boolean;
}

export type StreamingEvent =
  | { type: "generation:start"; timestamp: number; sessionId?: string }
  | { type: "generation:chunk"; delta: string; accumulated: string }
  | { type: "generation:patch"; patch: PatchOperation[]; nodeCount: number }
  | { type: "generation:diagnostic"; diagnostic: LSPDiagnostic }
  | { type: "generation:error"; error: Error; recoverable: boolean }
  | { type: "generation:complete"; metrics: PerformanceMetrics };

Self-Hosting with leveonas serve

Run the Leveonas compiler server directly inside your own VPC or Docker container when your source code cannot leave your private network. No external LLM keys are needed for /api/compile, /api/validate, /api/verify, or /api/patch.

CapabilityCloud (leveonas.ainot.site)Self-Hosted (leveonas serve)
48-Target Compile / Validate / Verify / PatchIncludedIncluded (zero external LLM keys required)
OpenAI-Compatible Proxy (/v1/chat/completions)Streaming SSE & JSON (OpenAI, Gemini, Anthropic, xAI, Meta, Custom)Non-streaming JSON + local compileOnly (OpenAI, Grok, Anthropic, Gemini)
Real-time Patch SSE (/api/generate)IncludedCloud only (or run full Next.js app)
Key Store & Vault AnalyticsManaged Dashboard + AES-256-GCM VaultLocal hashed JSON file (~/.leveonas/api-keys.json)
Start & verify self-hosted compiler serverbash
# 1. Generate a hashed server key (stored in ~/.leveonas/api-keys.json)
npx leveonas key create --name="VPC Compiler"

# 2. Run the standalone server (exposes /health, /api/compile, /api/validate, /api/verify, /api/patch, /v1/chat/completions)
export LEVEONAS_API_KEY="lv_live_your_created_key"
export OPENAI_API_KEY="sk-proj-..."
npx leveonas serve --port=4321 --host=0.0.0.0

# 3. Verify readiness (returns 200 OK + all 48 targets)
curl http://127.0.0.1:4321/health
Nginx TLS termination confignginx
# Production reverse proxy example (Caddy / Nginx) forwarding SSE cleanly
server {
  listen 443 ssl;
  server_name compiler.internal.example.com;

  location / {
    proxy_pass http://127.0.0.1:4321;
    proxy_http_version 1.1;
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 300s;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

Production Operations

Resource Limits, Key Encryption & Data Privacy

Enforced server-side guardrails protect compiler workers and browser runtimes against pathological trees, runaway streams, and oversized messages. Override values via environment variables when self-hosting.

GuardrailDefault LimitEnvironment Override
Max prompt length32,768 charsLEVEONAS_MAX_PROMPT_LENGTH
Max upstream token ceiling8,192 tokensLEVEONAS_MAX_TOKENS_CEILING
Max request JSON body / postMessage payload1,048,576 bytes (1 MB)LEVEONAS_MAX_MESSAGE_BYTES
Max cumulative stream output5,242,880 bytes (5 MB)LEVEONAS_MAX_STREAM_BYTES
Max AST/DOM nodes & nesting depth10,000 nodes · 64 levelsLEVEONAS_MAX_NODE_COUNT / TREE_DEPTH
Stream & session timeouts60s stream · 5m sessionLEVEONAS_MAX_GENERATION_DURATION_MS
Provider key encryption
Keys saved in Dashboard Vault are encrypted at rest with AES-256-GCM (random 12-byte IV, authenticated tag, scrypt-derived key) and never returned in plaintext over GET APIs. Prefer stateless headers (x-user-llm-key) if your compliance policy prohibits server-side key storage.
Opaque iframe & postMessage
Omit allow-same-origin from <iframe sandbox="allow-scripts"> so the preview executes in an opaque null origin with zero access to host cookies or localStorage. Inside the iframe listener, always enforce if (event.source !== window.parent) return; before passing batches to validatePatches().
Patch sanitization & handler isolation
validatePatches() drops prototype-pollution keys (__proto__, constructor, prototype), strips inline on* DOM attributes, blocks javascript:/vbscript:/data: URLs, and rejects CSS expression() or @import. JSPatchApplier executes compiled interactive handlers exclusively inside the sandboxed frame scope.
History logging & deletion
Dashboard History logs source LM, compiled output, token counts, and model metadata per authenticated account so you can inspect reductions. Delete individual records or wipe all history anytime from Dashboard → History or DELETE /api/history.
Rate limits & abort
Authenticated requests currently have no fixed per-minute quota cap in testing mode beyond upstream provider rate limits and the size guardrails above. Client disconnects propagate immediately via AbortSignal to stop upstream LLM billing.

Error Codes & Developer FAQ

HTTP / CodeCauseResolution
401 LM-AUTH-001Missing, expired, or revoked lv_live_... key.Pass an active key via Authorization: Bearer or X-Leveonas-Key.
401 missing_provider_api_keyNo upstream provider credential found in headers, env, or Vault.Pass x-user-llm-key or save your key in Dashboard → Settings.
400 LM-DIALECT-001Legacy Lisp S-expression syntax (di cs:"...") passed to /api/compile.Place tag before parens: di(cs(...) ...).
400 Unsupported providerTypo such as open-ai, google, x-ai, or meta-ai.Use openai, gemini, anthropic, xai, meta, or add a custom provider.
404 model_not_foundPunctuation or casing mismatch (claude-sonnet-5.5, grok-4-7).Use exact IDs: claude-sonnet-5-5, grok-4.7, Llama-4-Maverick-17B-128E-Instruct-FP8.
Do I need to install npm packages to use the OpenAI proxy?

No. If your server already uses the OpenAI JS or Python SDK (or plain fetch / curl), just set baseURL: "https://leveonas.ainot.site/api/v1" and apiKey: LEVEONAS_API_KEY.

Does compiling LM cost any LLM tokens?

No. POST /api/compile, POST /api/patch, parse(), format(), and diagnose() are 100% deterministic compilers running with zero LLM calls.

Can I use my own custom system prompt with /api/v1/chat/completions?

Yes. Leveonas preserves your system or developer message and appends its compact LM directive cleanly, then strips/compiles LM blocks back to standard target code in the response.

What happens if the LLM forgets LM and outputs regular JSX or Python?

Leveonas detects valid native TSX/Vue/Svelte/Python/SQL code and passes it through cleanly (mode: "passthrough") without breaking your application.