PascalAI
PascalAI — AI-native Pascal language compiler (Lape VM backend)
- Active · last change 4-12-2026
- ★ 3 on GitHub
README
PascalAI
A Pascal-inspired language for building LLM-powered agents and AI pipelines.
What is PascalAI?
PascalAI is a scripting language with familiar Pascal syntax extended with first-class constructs for:
- AI agents with declarative LLM routing, primary/fallback providers, and token budgets
- Graph pipelines — directed acyclic graphs of agents with dependency resolution
- Blackboard — shared typed memory for inter-agent communication
- Vector memory — semantic search with embeddings and RAG pipelines
- Async LLM calls — concurrent completions with structured typed outputs (
Completion<T>) - clib bridge — call any C/C++ shared library directly from a PAI script
- Delphi embedding — expose objects, register callbacks, and read results through a clean host API
There are three ways to use PascalAI, each covered in its own section below:
| Use case | |
|---|---|
| 1. Standalone | Download the binary and run .pai scripts directly |
| 2. Delphi embedding | Host scripts inside your Delphi app via TPAIScriptSession |
| 3. Build from source | Compile and extend the compiler/runtime itself |
1. Standalone language
The simplest way to use PascalAI: download the binary and run .pai scripts from the command line.
No Delphi required at runtime.
Download
Grab the latest PascalAI.exe (Win64) from the Releases page
and place it anywhere on your PATH.
Run a script
PascalAI.exe run scripts\hello.paiHello world
// hello.pai
program Hello;
begin
WriteLn('Hello from PascalAI!');
var x := 6 * 7;
WriteLn('6 × 7 = ' + IntToStr(x));
end.Using the LLM
program AskLLM;
begin
var answer := LLM_Complete('What is the capital of France? Answer in one word.');
WriteLn('Answer: ' + answer);
end.Agents and pipelines
program Summarizer;
agent Writer
providers begin
primary: 'openai/gpt-4o-mini'
fallback: 'anthropic/claude-haiku-4-5'
budget: 5000
end
behaviour oneshot
begin
var raw := BB.GetStr('input');
BB.SetStr('summary', LLM_Complete('Summarize in 2 sentences: ' + raw));
end
end.Typed structured output
type TProduct = record
Name : string;
Price : Double;
InStock : Boolean;
end;
var p := LLM_JSON<TProduct>('Extract product from: "Blue pen, $1.99, available"');
WriteLn(p.Name + ' $' + FloatToStr(p.Price));Async LLM calls
var h1 := LLM_Async('Translate to French: Hello world');
var h2 := LLM_Async('Translate to German: Hello world');
LLM_AwaitAll;
WriteLn('FR: ' + LLM_Await(h1));
WriteLn('DE: ' + LLM_Await(h2));Vector memory and RAG
Mem_VInit('memory');
Mem_VStore('PascalAI was created in 2025', '{"source":"docs"}');
Mem_VStore('The language compiles to Lape bytecode', '{"source":"docs"}');
var ctx := Mem_VSearchText('what VM does PascalAI use?', 3);
WriteLn(LLM_Complete('Answer using only this context: ' + ctx));clib — call C libraries directly
// Declare a function from a .dll / .so
external function sqlite3_libversion: string; from 'libpai_sqlite';
WriteLn('SQLite version: ' + sqlite3_libversion);Demos
All demos run with: PascalAI.exe run tests\examples\<file>.pai
Language basics
| Demo | Description |
|---|---|
| 01_hola_mundo.pai | Hello world, arithmetic, string interpolation |
| 02_tipos_y_control.pai | Types, if/for/while, case statement |
| 05_stdlib.pai | Standard library: strings, math, collections, JSON |
| 07_records_funciones.pai | Records, typed functions, arrays of records |
| 08_pipe_operator.pai | Pipe operator |> for data transformation chains |
| 10_manejo_errores.pai | try/except, raise, defensive patterns |
| 13_string_interp.pai | String interpolation $'Hello {name}' |
| 84_records_metodos.pai | Records with methods |
| 97_match_keyword.pai | Pattern matching with match |
| 109_utf8_lexer.pai | UTF-8 source: accented chars, Unicode in strings |
Agents and multi-agent systems
| Demo | Description |
|---|---|
| 03_agentes.pai | Agents as independent processes with messaging |
| 06_grafo_pipeline.pai | Graph pipeline with dependency resolution |
| 11_multiagente_chat.pai | Multi-agent chat with role separation |
| 101_publish_listen.pai | Publish/subscribe between agents |
| 102_supervisor_failure.pai | Supervisor pattern with failure recovery |
| 103_parallel_flow.pai | Parallel node execution in a graph |
| 184_goal_behaviour.pai | goal methods + oneshot/cyclic/timed behaviours |
| 185_provider_routing.pai | Declarative LLM routing: primary/fallback/round-robin |
| 186_budget.pai | Token budget per agent with LLM_BudgetUsed |
AI and LLM features
| Demo | Description |
|---|---|
| 04_memoria_y_llm.pai | Conversation memory + LLM integration |
| 12_structured_output.pai | Structured LLM output with records |
| 44_embeddings.pai | LLM_Embed, CosineSimilarity, EuclideanDistance |
| 179_completion_typed.pai | Completion<T> — typed structured output |
| 180_parallel_llm_batch.pai | Parallel LLM batch with concurrent TTask |
| 187_async_task.pai | LLM_Async / LLM_Await / LLM_AwaitAll |
Memory and RAG
| Demo | Description |
|---|---|
| 09_rag_basico.pai | Basic RAG: store, search, answer |
| 183_vector_memory.pai | Mem_VInit / Mem_VStore / Mem_VSearch |
| 100_vql_completo.pai | VQL — Vector Query Language, full syntax |
| 103_vql_rag_pipeline.pai | VQL in a RAG pipeline |
| 105_rag_graph.pai | RAG with graph-structured knowledge |
Blackboard and concurrency
| Demo | Description |
|---|---|
| 92_transaction.pai | Atomic transaction do...end on Blackboard |
| 94_bb_persist.pai | BB.Persist / BB.Restore — typed record persistence |
Package manager (PPM)
| Demo | Description |
|---|---|
| 86_ppm_demo.pai | Install and use a PPM package |
| 87_ppm_collections.pai | std-collections package |
| 88_ppm_datetime.pai | std-datetime package |
| 90_ppm_combinado.pai | Multiple packages in one script |
MCP (Model Context Protocol)
| Demo | Description |
|---|---|
| 176_mcp_datetime.pai | MCP datetime tool |
| 177_mcp_hash.pai | MCP hash tool |
| 181_mcp_typed_return.pai | Typed MCP return with mcp.Decode<T> |
clib ecosystem — 70+ C libraries
Call any C/C++ shared library from PAI scripts. All packages are available through the PPM registry at registry.pascalai.org.
Compression: zstd · snappy · lzma · zlib · brotli · bzip2 · lz4 · libarchive
Cryptography: libsodium · openssl · mbedtls · argon2 · blake3 · xxhash · secp256k1
Networking: curl · zeromq · nng · libevent · libuv · mosquitto · rabbitmq-c · hiredis · libmicrohttpd · civetweb · libssh2
Data: sqlite · leveldb · lmdb · duckdb · msgpack · flatcc · protobuf-c · cjson · jansson
Parsing: libxml2 · expat · yamlcpp · pcre2 · re2 · lua · libffi · tinyexpr
Images: libpng · libjpeg · libwebp · libtiff · libraw · freetype · harfbuzz · turbojpeg
Audio: opus · libsndfile · portaudio
Text: utf8proc · iconv · hunspell
System: libgit2 · libusb · libmodbus · mimalloc · pthreads · uuid
2. Embedding in Delphi
PascalAI can run as a scripting engine inside any Delphi application.
The host controls inputs, reads outputs, and registers Delphi functions that the script can call.
The export keyword is specific to this mode — it exposes values back to the host.
See the full Integration Guide for the complete API reference.
Add to your project
uses
PAI.ScriptSession, // TPAIScriptSession
PAI.Runtime; // TPAIRuntime (only if sharing a runtime)One-liner execution
// No session management needed for simple cases
var R := TPAIScriptSession.Eval('run begin export result := 6 * 7; end.');
ShowMessage(R); // '42'
var R2 := TPAIScriptSession.EvalWith(
'run begin export r := nombre + '' '' + IntToStr(edad); end.',
['nombre', 'Gustavo', 'edad', 38]
);
// R2 = 'Gustavo 38'Full session — inject inputs, run, read outputs
// script.pai
program Saludo;
run
begin
// 'nombre' and 'repeticiones' are injected by the host
var s := '';
for var i := 1 to repeticiones do
s := s + 'Hola, ' + nombre + '! ';
export saludo := Trim(s); // 'export' sends the value back to Delphi
end.// Delphi host
var Session := TPAIScriptSession.Create;
try
Session.SetStr('nombre', EditNombre.Text);
Session.SetInt('repeticiones', SpinEdit.Value);
Session.LoadFile('scripts\script.pai');
Session.Run;
ShowMessage(Session.GetOutputStr('saludo'));
finally
Session.Free;
end;Expose a Delphi object — auto-wired via RTTI
// All published properties and whitelisted methods become PAI functions
Session.ExposeObject('Bar', ProgressBar, [], {AQueueToMain=}True);
// Runs safely in a background thread — UI calls are queued to the main thread
TTask.Run(procedure begin
Session.LoadSource('run begin Bar_SetPosition(75); end.');
Session.Run;
end);Callbacks — Delphi functions callable from PAI
Session.RegisterFunc('FormatCurrency', 'amount: Double', 'string',
function(A: TArray<Variant>): Variant
begin
Result := FormatFloat('$#,##0.00', Double(A[0]));
end
);// script.pai
run begin
export precio := FormatCurrency(1234.5); // '$1,234.50'
end.Direct calls — invoke PAI functions from Delphi
// Load the script as a library (no run block)
Session.LoadSource(
'program MiLib;' + sLineBreak +
'function Cuadrado(n: Int64): Int64;' + sLineBreak +
'begin Result := n * n; end;'
);
Session.Run;
// Call specific functions directly, multiple times without recompiling
var R := Session.CallFunc<Int64>('Cuadrado', [Int64(9)]); // 81Integration test suite
| File | Covers |
|---|---|
| host/bin/test_expose.pas | Eval/EvalWith/Exec · ExposeObject · PAI_Queue · AQueueToMain |
| host/bin/test_session_api.pas | Lifecycle · inputs/outputs · callbacks · records · handles · events · CallFunc · error handling |
PAI-side scripts for each integration feature:
| Script | Demonstrates |
|---|---|
| 188_session_vars.pai | Receiving injected variables + export |
| 189_session_callbacks.pai | Calling registered Delphi functions |
| 190_session_record.pai | Working with injected records |
| 191_session_handle.pai | Handles — passing opaque Delphi objects |
| 192_session_emit.pai | PAI_Emit — sending events to the host |
| 193_session_call.pai | Library mode — functions callable via CallFunc |
3. Building from source
You need to build from source to modify the compiler, add language features, or contribute to the project.
Prerequisites
| Tool | Version | Purpose |
|---|---|---|
| Delphi / RAD Studio | 11 Alexandria or later | Compile PascalAI.dproj |
| Lape | latest | Bytecode interpreter |
| Git | any | Clone dependencies |
Clone and build
git clone https://github.com/gustavoeenriquez/PascalAI
cd PascalAI
# Clone Lape dependency
mkdir vendor
git clone https://github.com/nielsAD/lape vendor/lape
# Open host/PascalAI.dproj in the Delphi IDE and Build (Win64 Release)
# Or via MSBuild:
call "C:\Program Files (x86)\Embarcadero\Studio\23.0\bin\rsvars.bat"
msbuild host\PascalAI.dproj /t:Build /p:Config=Release /p:Platform=Win64See SETUP.md for full instructions: library paths, LLM provider configuration, Linux64 builds.
Project structure
PascalAI/
compiler/ Lexer → Parser → AST → SemanticAnalyzer → CodeGen → Compiler
runtime/
core/ Runtime, GraphEngine, AgentScheduler
memory/ Blackboard, VQL, RAG, 5 memory types
stdlib/ IO, Data, Prompts, Skills
bridge/ LapeBridge, LLMBridge, LLMProvider, ClibBridge
debug/ WebSocket debug server + viewer.html
host/ PascalAI.dpr — the pai.exe binary
docs/ Integration guide (.md + .docx + gen_docx.py)
tests/examples/ 180+ demo scripts
vendor/lape/ Lape bytecode interpreterRun the test suite
# Windows
tests\run_demos.ps1
# Linux / macOS
bash tests/run_demos.shDocumentation
- Integration Guide (Markdown) — 14-section reference for Delphi embedding
- Integration Guide (Word) — same content, formatted
- SETUP.md — build instructions, library paths, LLM provider setup
License
MIT — see LICENSE for details.

