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 Case | Recommended Path | What You Integrate |
|---|---|---|
| Existing app using OpenAI SDK, fetch, or an AI builder (Recommended) | OpenAI-Compatible Proxy | Point baseURL to https://leveonas.ainot.site/api/v1. Zero architecture changes. |
| Need live streaming UI previews in a browser iframe | Streaming SDK + Runtime | Call createSession() from leveonas/sdk or POST /api/generate with /leveonas.js. |
| Already have LM source strings to convert to TSX/Vue/SQL | Compiler API / SDK | Call await compile(source) or POST /api/compile. No external LLM key needed. |
| Apply surgical follow-up edits to existing multi-file code | Patch API | Send <PATCH> SEARCH/REPLACE blocks + files map to POST /api/patch. |
| Strict data residency inside a private VPC or container | Self-Hosted CLI Server | Run npx leveonas serve --port=4321 on your own server. |
Two Credentials, Zero Surprise Billing
| Credential | Required? | How to Provide It |
|---|---|---|
Leveonas API Key (lv_live_...) | Always required | Created 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/generate | Provide 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:
| Concept | Where Used | Example Values | Purpose |
|---|---|---|---|
| Source Block Tag | Inside LM string | <REACT>, <PYTHON> | Identifies which of the 48 language interpreters parses that block. Supports multiple blocks per payload. |
framework | SDK compile(), REST, CLI --framework | react | nextjs | vue | html | auto | Explicit 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 --target | all | ui-ir | dom | patches | Selects 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.
npm install leveonas@0.6.0 and add LEVEONAS_API_KEY + GEMINI_API_KEY to .env.local (or save Gemini in Dashboard Vault).app/api/generate-stream/route.ts to inject your secrets server-side and pipe the POST /api/generate SSE response to your React client.generation:patch events via createSession() and forward validated patches via postMessage to an <iframe sandbox="allow-scripts"> running /leveonas-runtime.js.// 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",
},
});
}'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
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.
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().
# 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.0Golden 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.
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.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.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.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 — 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.
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 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"))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:
Interactive Request Builder
Select a provider keyword and model ID to generate an exact request with zero spelling mismatches.
Exact provider string: openai
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:
| Priority | Credential Source | Behavior & Precedence |
|---|---|---|
| 1 (Highest) | x-user-llm-key / x-provider-key | Per-request header. Overrides any key saved in environment variables or Dashboard Vault. Ideal for multi-tenant SaaS apps bringing user keys. |
| 2 | x-<provider>-key | Provider-scoped header (x-openai-key, x-gemini-key, x-anthropic-key, x-xai-key, x-meta-key). |
| 3 | Server Environment | Host environment fallback (OPENAI_API_KEY, GEMINI_API_KEY, ANTHROPIC_API_KEY, XAI_API_KEY, META_API_KEY) when running self-hosted. |
| 4 (Fallback) | Dashboard Vault | AES-256-GCM encrypted key stored for your account under Settings → Provider API keys. |
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.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.
| Provider | Exact keyword | Alias | Key header | Do not pass |
|---|---|---|---|---|
| OpenAI | openai | — | x-openai-key | open-ai, open_ai, OpenAI |
| Google Gemini | gemini | — | x-gemini-key | google, google-gemini, google_ai |
| Anthropic | anthropic | — | x-anthropic-key | claude, anthropic-ai, claude-sonnet-5.5 |
| xAI (Grok) | xai | grok | x-xai-key | x-ai, x_ai, x.ai |
| Meta Llama | meta | llama | x-meta-key | meta-ai, facebook, meta_llama |
OpenAI
Provider keyword: openai · Header: x-openai-key · Protocol: OpenAI Chat Completions JSON / SSE
https://api.openai.com/v1/chat/completions| Model ID | Series | Status | Tier | Notes |
|---|---|---|---|---|
gpt-6.2-astra | GPT-6.2 | Recommended | Frontier | Flagship OpenAI reasoning, multi-step coding, and agentic workflows (Nov 2026) |
gpt-6.2-sol | GPT-6.2 | Recommended | Balanced Frontier | Recommended balanced model for fast UI generation, coding, and tool calls |
gpt-6-sol | GPT-6 | Legacy | Previous Gen | Earlier GPT-6 Sol checkpoint; prefer gpt-6.2-sol for new integrations |
gpt-6-luna | GPT-6 | Available | Fast / Value | Cost-efficient high-throughput UI & LM streaming |
gpt-5 | GPT-5 | Legacy | Standard | Base alias (dated snapshot: gpt-5-2025-08-07) |
gpt-5-codex | GPT-5 | Legacy | Coding | Specialized GPT-5 variant for agentic code generation |
gpt-4.1 | GPT-4.1 | Legacy | Long Context | Non-reasoning flagship (dated: gpt-4.1-2025-04-14, plus gpt-4.1-mini) |
o3 | o-Series | Available | Reasoning | High-depth reasoning (also o3-pro and compact o4-mini) |
gpt-4o | GPT-4o | Legacy | Legacy Default | Legacy compatibility alias (also gpt-4o-mini) |
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
https://generativelanguage.googleapis.com/v1beta/models/{model}:streamGenerateContent| Model ID | Series | Status | Tier | Notes |
|---|---|---|---|---|
gemini-4-carbon | Gemini 4 | Recommended | Frontier | Highest-capability frontier model for multi-step engineering |
gemini-4-neon | Gemini 4 | Recommended | Balanced Frontier | Frontier reasoning tuned for fast production execution |
gemini-4-hydrogen | Gemini 4 | Recommended | Fast / Everyday | Low-latency daily coding, LM emission, and progressive UI generation |
gemini-4-argon | Gemini 4 | Available | Analytical | Deep analytical & scientific problem-solving variant |
gemini-3.8-flash | Gemini 3.8 | Available | Workhorse | High-intelligence workhorse for long-horizon coding loops |
gemini-3.8-live | Gemini 3.8 | Available | Live Realtime | Low-latency multimodal live session model |
gemini-3.5-flash-lite | Gemini 3.5 | Legacy | Ultra-Light | High-throughput lightweight tasks and fast patching |
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)
https://api.anthropic.com/v1/messages| Model ID | Series | Status | Tier | Notes |
|---|---|---|---|---|
claude-opus-5-5 | Claude 5.5 | Recommended | Frontier | Top-tier Claude intelligence for full-stack architecture |
claude-sonnet-5-5 | Claude 5.5 | Recommended | Balanced Flagship | Recommended default for builders, tool calls, and clean LM |
claude-haiku-5-5 | Claude 5.5 | Recommended | Fast / Value | Sub-second responses for patches and rapid UI iteration |
claude-fable-5-2 | Claude 5.2 | Available | Extended Synthesis | Specialized long-form structured generation and documentation |
claude-opus-4-6 | Claude 4 | Legacy | Legacy Frontier | Claude Opus 4.6 identifier (also claude-opus-4-5) |
claude-sonnet-4-20250514 | Claude 4 | Legacy | Dated Snapshot | Pinned Claude Sonnet 4 snapshot (alias: claude-sonnet-4) |
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
https://api.x.ai/v1/chat/completions| Model ID | Series | Status | Tier | Notes |
|---|---|---|---|---|
grok-4.7 | Grok 4 | Recommended | Flagship | Latest xAI flagship API model string (uses dot: 4.7) |
grok-4.6 | Grok 4 | Available | Production | High-speed Grok 4.6 release string (uses dot: 4.6) |
grok-4.5 | Grok 4 | Available | Standard | Balanced Grok 4.5 checkpoint (uses dot: 4.5) |
grok-4 | Grok 4 | Legacy | Base Alias | Unversioned Grok 4 routing alias |
grok-3-reasoning | Grok 3 | Legacy | Reasoning | Extended chain-of-thought variant (base: grok-3) |
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
https://api.llama.com/compat/v1/chat/completions| Model ID | Series | Status | Tier | Notes |
|---|---|---|---|---|
Llama-4-Maverick-17B-128E-Instruct-FP8 | Llama 4 | Recommended | Flagship MoE | 128-expert Mixture-of-Experts model; exact TitleCase + FP8 suffix required |
Llama-4-Scout-17B-16E-Instruct-FP8 | Llama 4 | Recommended | Long Context MoE | 16-expert fast long-context model on api.llama.com/compat/v1 |
Llama-3.3-70B-Instruct | Llama 3.3 | Available | Dense 70B | Instruction-tuned 70B checkpoint on native Llama API |
Llama-3.3-8B-Instruct | Llama 3.3 | Available | Fast 8B | Low-latency compact instruction checkpoint |
meta-llama/Meta-Llama-3.1-405B-Instruct | Llama 3.1 | Legacy | Dense 405B | HuggingFace / OpenAI-compat full namespace identifier |
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.
openai-compatible (Groq, Together, OpenRouter, vLLM), anthropic-messages, or gemini-generate.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).x-leveonas-provider: groq and your provider model ID (for example llama-3.3-70b-versatile).// 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",
},
}
);// 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.
# 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.
# 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.
| Distribution | How to Load | Primary Exports / Global | Best For |
|---|---|---|---|
| leveonas/runtime | npm ESM subpath import | DOMPatchApplier, JSPatchApplier, validatePatches | Bundled React / Next.js / Vite apps validating patches before postMessage |
| /leveonas-runtime.js | IIFE <script> tag | window.LeveonasRuntime.DOMPatchApplier | Sandboxed <iframe sandbox="allow-scripts"> preview shells receiving patches |
| /leveonas.js | IIFE <script> tag | window.Leveonas.Engine (+ Runtime) | Zero-bundler HTML pages streaming directly from /api/generate |
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.
'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.
# 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 VaultHTTP 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.
| Endpoint | Upstream Key Needed? | Key Scope | Purpose |
|---|---|---|---|
| POST /api/v1/chat/completions | Yes (Header / Vault) | write:stream | OpenAI-compatible proxy with auto LM compilation & token telemetry |
| POST /api/generate | Yes (Header / Vault) | write:stream | Direct SSE pipeline emitting real-time patch & telemetry events |
| POST /api/compile | No (Leveonas key only) | read:compile | Deterministically compiles LM source across 48 targets into code, HTML, AST & UI IR |
| POST /api/patch | No (Leveonas key only) | read:compile | Parses or applies <PATCH> SEARCH/REPLACE blocks against virtual files map |
| POST /api/validate & /api/verify | No (Leveonas key only) | read:compile | Syntax validation, security audit, and post-compile output verification |
| GET /api/models | No (Optional session/key) | Public / Auth | Live model catalog with status, lastVerified, and user custom providers |
// 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
}
}// 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"
}
}// 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 Parameter | Support Status | Cross-Provider Translation Notes |
|---|---|---|
| messages (system, developer, user, assistant) | Supported | Mapped 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) | Supported | Translated to Anthropic tool_use and Gemini functionDeclarations; responses normalize back to OpenAI tool_calls. |
| tool_choice | Partial | Forwarded verbatim to OpenAI, xAI, Meta, and custom OpenAI-compat servers; not forwarded to Anthropic/Gemini adapters. |
| temperature, max_tokens | Supported | Forwarded across all providers (mapped to maxOutputTokens on Gemini). |
| seed | Partial | Supported on OpenAI, xAI, Meta, and Gemini; ignored by Anthropic Messages API. |
| response_format, n > 1, image_url parts | Not Supported | Not 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 ID | LM Block Tag | Stability | Compiled Output |
|---|---|---|---|
| react | <REACT> | Stable | React TSX + DOM + JS |
| nextjs | <NEXTJS> | Stable | Next.js TSX + DOM + JS |
| vue | <VUE> | Stable | Vue 3 SFC + DOM + JS |
| svelte | <SVELTE> | Stable | Svelte Component + DOM + JS |
| angular | <ANGULAR> | Stable | Angular TS + DOM + JS |
Web Core & Styling (9 Targets) · Stable
Framework AST / Direct Target Emitter| Target ID | LM Block Tag | Stability | Compiled Output |
|---|---|---|---|
| html | <HTML> | Stable | Semantic HTML5 (+ Document Mode) |
| tailwind | <TAILWIND> | Stable | HTML5 + Tailwind classes |
| css | <CSS> | Stable | Stylesheet (.css) |
| scss | <SCSS> | Stable | Sass/SCSS (.scss) |
| js | <JS> | Stable | JavaScript ES module |
| ts | <TS> | Stable | TypeScript or lowered JS |
| solid | <SOLID> | Stable | SolidJS TSX |
| astro | <ASTRO> | Stable | Astro component (.astro) |
| svg | <SVG> | Stable | Vector SVG markup |
Backend & Databases (8 Targets) · Stable
Dedicated LM Interpreters| Target ID | LM Block Tag | Stability | Compiled Output |
|---|---|---|---|
| python | <PYTHON> | Stable | FastAPI / Python |
| node | <NODE> | Stable | Express / Hono / Node TS |
| sql | <SQL> | Stable | PostgreSQL / RLS DDL |
| prisma | <PRISMA> | Stable | schema.prisma |
| drizzle | <DRIZZLE> | Stable | Drizzle ORM TypeScript |
| mongo | <MONGO> | Stable | Mongoose / Mongo schema |
| graphql | <GRAPHQL> | Stable | GraphQL SDL |
| rules | <RULES> | Stable | Firestore / Storage Rules |
Mobile & Polyglot Languages (13 Targets) · Beta
Dedicated LM Interpreters (Codegen & Syntax Parity)| Target ID | LM Block Tag | Stability | Compiled Output |
|---|---|---|---|
| react-native | <REACT-NATIVE> | Beta | Expo / React Native TSX |
| dart | <DART> | Beta | Flutter / Dart widget |
| swift | <SWIFT> | Beta | SwiftUI view |
| kotlin | <KOTLIN> | Beta | Jetpack Compose / Kotlin |
| go | <GO> | Beta | Go source (.go) |
| rust | <RUST> | Beta | Rust / Axum (.rs) |
| java | <JAVA> | Beta | Java / Spring (.java) |
| php | <PHP> | Beta | PHP / Laravel (.php) |
| csharp | <CSHARP> | Beta | C# / .NET (.cs) |
| ruby | <RUBY> | Beta | Ruby / Rails (.rb) |
| cpp | <CPP> | Beta | C / C++ (.cpp) |
| elixir | <ELIXIR> | Beta | Elixir / Phoenix (.ex) |
| lua | <LUA> | Beta | Lua script (.lua) |
Config, Infrastructure, Templates & Patches (13 Targets) · Stable
Structured Emitters & Diff Patch Engine| Target ID | LM Block Tag | Stability | Compiled Output |
|---|---|---|---|
| patch | <PATCH> | Stable | SEARCH/REPLACE file patch |
| json | <JSON> | Stable | Formatted JSON |
| yaml | <YAML> | Stable | YAML manifest |
| toml | <TOML> | Stable | TOML config |
| env | <ENV> | Stable | Dotenv (.env) |
| dockerfile | <DOCKERFILE> | Stable | Dockerfile |
| shell | <SHELL> | Stable | POSIX / Bash script |
| terraform | <TERRAFORM> | Stable | Terraform HCL (.tf) |
| protobuf | <PROTOBUF> | Stable | Protocol Buffers (.proto) |
| makefile | <MAKEFILE> | Stable | Makefile |
| xml | <XML> | Stable | XML / Manifest / Plist |
| markdown | <MARKDOWN> | Stable | Markdown / MDX |
| template | <TEMPLATE> | Stable | Jinja2 / 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 / Entry | Execution | Network / Key Required | Returns |
|---|---|---|---|
| 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 keys | StreamingEvent stream + abort() |
| parse(source, opts) | Sync | No (Offline local) | Typed framework ParsedAST union |
| lower(astOrSource, fw) | Sync | No (Offline local) | Framework-neutral UIIRProgramNode |
| inspect(source) | Sync | No (Offline local) | Reactivity Graph, symbols, AST, DOM patches |
| format(source, opts) | Sync | No (Offline local) | Canonical formatted LM string |
| diagnose(source, opts) | Sync | No (Offline local) | LSPDiagnostic[] errors & warnings |
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;
}
}// 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.
| Capability | Cloud (leveonas.ainot.site) | Self-Hosted (leveonas serve) |
|---|---|---|
| 48-Target Compile / Validate / Verify / Patch | Included | Included (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) | Included | Cloud only (or run full Next.js app) |
| Key Store & Vault Analytics | Managed Dashboard + AES-256-GCM Vault | Local hashed JSON file (~/.leveonas/api-keys.json) |
# 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# 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.
| Guardrail | Default Limit | Environment Override |
|---|---|---|
| Max prompt length | 32,768 chars | LEVEONAS_MAX_PROMPT_LENGTH |
| Max upstream token ceiling | 8,192 tokens | LEVEONAS_MAX_TOKENS_CEILING |
| Max request JSON body / postMessage payload | 1,048,576 bytes (1 MB) | LEVEONAS_MAX_MESSAGE_BYTES |
| Max cumulative stream output | 5,242,880 bytes (5 MB) | LEVEONAS_MAX_STREAM_BYTES |
| Max AST/DOM nodes & nesting depth | 10,000 nodes · 64 levels | LEVEONAS_MAX_NODE_COUNT / TREE_DEPTH |
| Stream & session timeouts | 60s stream · 5m session | LEVEONAS_MAX_GENERATION_DURATION_MS |
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.postMessageallow-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().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.DELETE /api/history.AbortSignal to stop upstream LLM billing.Error Codes & Developer FAQ
| HTTP / Code | Cause | Resolution |
|---|---|---|
| 401 LM-AUTH-001 | Missing, expired, or revoked lv_live_... key. | Pass an active key via Authorization: Bearer or X-Leveonas-Key. |
| 401 missing_provider_api_key | No upstream provider credential found in headers, env, or Vault. | Pass x-user-llm-key or save your key in Dashboard → Settings. |
| 400 LM-DIALECT-001 | Legacy Lisp S-expression syntax (di cs:"...") passed to /api/compile. | Place tag before parens: di(cs(...) ...). |
| 400 Unsupported provider | Typo such as open-ai, google, x-ai, or meta-ai. | Use openai, gemini, anthropic, xai, meta, or add a custom provider. |
| 404 model_not_found | Punctuation 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. |
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.
No. POST /api/compile, POST /api/patch, parse(), format(), and diagnose() are 100% deterministic compilers running with zero LLM calls.
/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.
Leveonas detects valid native TSX/Vue/Svelte/Python/SQL code and passes it through cleanly (mode: "passthrough") without breaking your application.