) // Run multiple tasks/requests physically in parallel
```
### Standard Library Modules
Standard library features are available natively in **v1.2.0+** using imports:
```sesi
import { PI, sqrt } from "std/math"
import { sleep, now } from "std/time"
import { stringify, parse } from "std/json"
```
## Running Examples
Try the included examples:
```bash
# Basic examples
sesi examples/01_hello.sesi
sesi examples/02_variables.sesi
sesi examples/03_functions.sesi
sesi examples/04_conditionals.sesi
sesi examples/05_loops.sesi
sesi examples/06_arrays_objects.sesi
# Reasoning examples (automatically loads .env for Gemini API key)
sesi examples/08_model_call.sesi
sesi examples/09_structured_output.sesi
sesi examples/10_code_generation.sesi
sesi examples/11_memory_conversation.sesi
sesi examples/12_classification.sesi
sesi examples/13_data_pipeline.sesi
sesi examples/14_folder_explainer.sesi
# Image generation example
sesi examples/15_image_generation.sesi
# Advanced Version 1.2 features
sesi examples/16_modules.sesi
sesi examples/17_http_client.sesi
sesi examples/18_parallel_requests.sesi
```
## Common Patterns
### Processing Arrays
```sesi
let numbers = [1, 2, 3, 4, 5]
// Iterate
for n in numbers {print n}
// Build new array
let doubled = []
for n in numbers {push(doubled, n * 2)}
print doubled // [2, 4, 6, 8, 10]
```
### String Operations
```sesi
let text = "hello world"
// Concatenation
let greeting = "Hello," + "World!"
// Length
let len = len(text)
// Uppercase/lowercase (v2+)
// let upper = upper(text)
// let lower = lower(text)
// Split and join
let words = split(text, " ")
let rejoined = join(words, "-")
```
### Reasoning Classification
```sesi
fn classify(item: string) {print model("gemini-3-flash-preview")
{"Classify as: FRUIT, VEGETABLE, or GRAIN. Item: " item}}
classify("apple")
classify("carrot")
classify("wheat")
```
## Debugging Tips
### Print Intermediate Values
```sesi
fn complex(x: number) {
let step1 = x * 2
print "Step 1:" str(step1)
let step2 = step1 + 10
print "Step 2:" str(step2)
}
complex(5)
```
### Check Types
```sesi
let value = "hello"
print type(value) // "string"
if type(value) == "string" {print "It's a string!"}
```
### Validate Model Responses
```sesi
let response = model("gemini-3-flash-preview") {"Respond with YES or NO"}
if response == "" {print "Error: no response"}
else if len(response) > 100 {print "Warning: response too long"}
else {print "Response: " response}
```
## Performance Considerations
- **Model calls are blocking**: Each model() call waits for the API response
- **Token usage**: Larger prompts use more tokens and cost more
- **Use appropriate models**: gemini-3.1-flash-lite for most tasks, gemini-3.1-pro-preview for complex reasoning
- **Batch operations**: Ask Reasoning to process multiple items in one call instead of looping
## Next Steps
1. **Read the spec**: [SPECIFICATION.md](docs/SPECIFICATION.md)
2. **Learn about reasoning**: [SYSTEMS_REASONING.md](docs/SYSTEMS_REASONING.md)
3. **Understand architecture**: [ARCHITECTURE.md](docs/ARCHITECTURE.md)
4. **Check roadmap**: [ROADMAP.md](docs/ROADMAP.md)
5. **Study examples**: [examples/](examples/)
## Getting Help
Sesi comes with an advanced, built-in **Interactive RAG Co-Pilot** right in your command line! Instead of static help messages, you can query Sesi directly about how to use any statement, standard library, or architectural pattern:
```bash
# Ask the Sesi Co-Pilot for help directly
sesi -help "how do I parse a JSON string?"
sesi --help "explain structured_output and give an example"
sesi -h "how to spawn background processes?"
```
The co-pilot will dynamically index and train on Sesi's native repository database and retrieve full RAG context from our standard specification docs to generate a syntactically correct, 100% accurate, conversational answer in real-time!
You can also:
- Check documentation in [docs/](docs/)
- Review examples in [examples/](examples/)
- Read error messages carefully
- Try simpler programs first
## Reporting Issues
When reporting bugs:
1. Provide a minimal example
2. Show the error message
3. Include your Sesi version
4. Specify OS and Node.js version
---
Happy programming with Sesi! 🚀
---
## 8. README.md
Sesi: A High-Performance Systems Language
Pronounced "say-see" — What you say, you'll see.
Sesi is a high-performance Systems Language designed for building resilient, stateful applications. It provides first-class primitives for process management, filesystem orchestration, and integrated reasoning, enabling developers to build complex logic with a fraction of the boilerplate required by traditional languages.
Homepage
## Installation
You can install Sesi in three ways:
### 1. Global Installation via npm (Recommended)
If you have Node.js installed, download Sesi directly from the npm registry:
```bash
npm install -g sesi
```
### 2. Standalone Executables
Don't want to install Node.js? Download the standalone executables bundled for Windows, Mac, and Linux directly from our [Downloads page](https://code-with-sesi.netlify.app/downloads). Drop the executable in your system PATH and you're good to go!
For macOS users, Sesi also supports a native PKG installer flow when building from source:
```bash
npm run build:exe
npm run build:mac:pkg
```
This generates installer packages in `releases/` (for available architectures) that install `sesi` to `/usr/local/bin`.
### 3. Build from Source (For contributors)
```bash
git clone https://github.com/Misterscan/Sesi.git
cd Sesi
npm install
npm run build
npm install -g . # Unlock the `sesi` command locally
```
## Quick Start
You'll need a [Gemini API Key](https://aistudio.google.com/app/apikey) for the reasoning features. Create a `.env` file referencing your key where you run your scripts:
```env
GEMINI_API_KEY="AIzaSy..."
```
Then run any program directly:
```bash
# Standard script execution
sesi main/start.sesi
# Reasoning script example
sesi examples/08_model_call.sesi
# Run all examples
sesi examples.sesi
```
# Local Execution (Development)
If you choose not install `sesi` globally, use the helper npm scripts:
```bash
npm run example 01_hello.sesi
npm run example:ai 08_model_call.sesi
npm run example:all
```
## Language Overview
Sesi is designed for developers who want to:
- Write normal code (variables, functions, loops, etc.)
- Call Reasoning directly within code using `prompt` and `model` blocks
- Get structured outputs from Reasoning with type guarantees
- Build Reasoning agents with memory and multi-step reasoning
- Maintain full control and transparency
## Example
```sesi
// Basic computation
let x = 10
let y = 20
let result = x + y
print result // 30
// Reasoning-powered code generation
prompt generateCode {"Write a TypeScript function that reverses a string"}
let code = model("gemini-3.1-pro-preview") {generateCode}
print code
```
## Documentation
- [Getting Started](./QUICKSTART.md)
- [Examples](./examples/)
- [Language Specification](./docs/SPECIFICATION.md)
- [Language Comparison Showcase](./docs/COMPARISON.md)
- [Built-in Functions](./docs/BUILTINS.md)
- [Reasoning Guide](./docs/SYSTEMS_REASONING.md)
- [Distributed Systems](./docs/DISTRIBUTED_SYSTEMS.md)
- [Runtime Architecture](./docs/ARCHITECTURE.md)
## AI Agent Context
The root-level `SKILLS.md` file is a workspace context file for AI agents. It records repo-specific constraints such as valid Sesi syntax expectations, execution conventions, and the intended meaning of directories like `main/` and `main/tests/`.
## Project Structure
```
Sesi/
├── SKILLS.md # AI-agent workspace context and repo guardrails
├── index.html # Sesi-generated landing page
├── eslint.config.mjs # ESLint configuration
├── dist/ # Compiled TypeScript output
├── example.js # Helper script to run basic examples
├── example-ai.js # Helper script to run Reasoning examples
├── package.json # Dependencies & scripts
├── tsconfig.json # TypeScript configuration
├── QUICKSTART.md # Quick start guide
├── IMPLEMENTATION_SUMMARY.md # Progress and tracking
├── src/
│ ├── types.ts # Type system & AST nodes
│ ├── lexer.ts # Tokenization
│ ├── parser.ts # AST generation
│ ├── interpreter.ts # Execution engine
│ ├── builtins.ts # Standard library
│ ├── ai-runtime.ts # Gemini integration
│ └── index.ts # Main entry point
├── bin/
│ └── sesi.js # CLI executable
├── examples/ # 18 sample programs demonstrating all features
├── main/ # Main entry and specialized tests
│ ├── playground.sesi # Main playground script
│ ├── start.sesi # Beginner script
│ ├── build_website.sesi # Sesi-powered landing page generator
│ └── tests/ # Debug and syntax scripts
├── tests/ # Test suite
└── docs/ # Documentation (ARCHITECTURE, BUILTINS, SPECIFICATION, etc.)
```
## Version 1.2 Features (In Progress)
### Core Language ✅
- **Variables & Bindings**: `let` for all bindings (const is deprecated).
- **Functions**: Side-effect driven functions with typed parameters.
- **Control Flow**: `if/else`, `while`, `for`, and `try/catch`.
- **Collections**: Robust Arrays and Objects.
- **Error Handling**: Structured `try/catch` for both runtime and Reasoning-level errors.
- **Local Module Imports/Exports**: Import custom local `.sesi` modules cleanly using relative import/export syntax!
- **Standard Library Modules**: Native support for imported standard libraries, including:
- `std/math` (providing `PI`, `E`, `sqrt`, `pow`, `sin`, `cos`, etc.)
- `std/time` (providing `sleep` and `now`)
- `std/json` (providing JSON serialization/deserialization)
### Reasoning-Native Features ✅
- `prompt` blocks for message composition
- `model()` calls with Reasoning provider configuration
- `image()` calls with specific ratio/size generation capabilities
- `structured_output()` for typed Reasoning responses
- `tool_call()` for function calling
- Basic memory for multi-turn reasoning
- `read_file()`, `write_file()`, `to_json()`, `write_image()`, and `list_dir()` for local file I/O
- **Native Concurrency**: `spawn()` and `exec()` for concurrent process management, and `multi_req(array)` for physical parallel request execution.
- **Logic Caching**: High-efficiency Sesi Logic Caching (`.sesi_cache.json`) for local call caching.
- **Thinking Scale**: Scaled Gemini reasoning configurations using the `thinking` parameters.
- **HTTP Client**: Built-in, native HTTP client support using `web_get(url)` and `web_send(url, body, headers)` with zero external dependencies.
- **Async Polling**: Native looping to auto-resume generation when hitting `MAX_TOKENS` limit
- **Utility Builtins**: `time()` and `random()` for robust coordination
### Type System
- Static types: `number`, `string`, `bool`, `array`, `object`
- Type inference
- Union types for Reasoning response handling
## Roadmap
### V2: Advanced Reasoning
- Long-term memory and context management
- Custom tool definitions
- Streaming responses
### V3: Agents & Orchestration
- Agent definitions with state
- Tool composition and chaining
- Multi-agent collaboration
- Persistent knowledge bases
## License
MIT
---
## 9. ROADMAP.md
# Sesi Systems Language Roadmap
## Version 1.0 - Foundation (Complete)
**Status**: Complete V1.0 implementation
**Ready for**: Exploration, learning, building prototypes
**Not ready for**: Production systems (until v2.0 with error handling)
**Next milestone**: V1.1
### Core Language Features ✅
- [x] Variables and bindings (let) (const is deprecated)
- [x] Functions with parameters and types
- [x] Control flow (if/else, while, for, try/catch)
- [x] Operators (arithmetic, logical, comparison)
- [x] Arrays and objects
- [x] Type system with inference
- [x] Comments (// and /\* \*/)
- [x] String concatenation
- [x] Error handling (try/catch blocks)
### Integrated Reasoning Features ✅
- [x] Prompt blocks
- [x] Reasoning model calls (model())
- [x] Structured output (structured_output())
- [x] Tool calling (tool_call())
- [x] Stateful context management (memory)
### Built-in Functions ✅
- [x] print, type, str, num, bool
- [x] len, push, pop, join, split
- [x] range, keys, values
- [x] read_file, write_file
- [x] spawn, exec (Concurrency & Systems)
- [x] time, random (Utilities)
- [x] Array and object operations
### Tooling ✅
- [x] Lexer and parser
- [x] Tree-walking interpreter
- [x] CLI executable (sesi)
- [x] Examples (13 programs)
- [x] Documentation
### Limitations
- Interpreter is Single-threaded (use `spawn()` for concurrency)
- No async/await
- Blocking Reasoning calls
- Limited error messages
- No pattern matching
- No generics or custom types
---
## Version 1.2 - Stability & Systems Logic (In Progress)
**Status**: In Progress V1.2 implementation
**Ready for**: Distributed systems orchestration and prototypes
**Not ready for**: Massive-scale production (until v2.0 bytecode)
**Next milestone**: V2.0 (Async & advanced reasoning)
### Improvements & Features ⌛
- [x] Systems Builtins: `spawn`, `exec`, `time`, `random`
- [x] Concurrency: Async polling via file locks for completion and MAX_TOKENS
- [x] Image Generation primitive (`image`) and Config blocks (`ratio`, `size`)
- [x] File Management Builtins: `list_dir`, `write_image`
- [x] Documentation improvements (Extensive Markdown guides)
- [x] Bug fixes (tool_call argument passing resolved)
- [x] Simple error recovery (Parser synchronization)
- [x] Implicit statement termination for blocks ending in `}`
- [x] Temporal Context Injection for reasoning calls
- [x] Distributed Systems capabilities (Double-Check Write lock pattern)
- [x] API reference (`BUILTINS.md`)
- [x] Tutorial: Getting started (`QUICKSTART.md`)
- [x] Cookbook: Common patterns (`SYSTEMS_REASONING.md`)
### Deferred to V2.0 ⏳
- [ ] Better error messages with line numbers and stack traces
- [ ] REPL (Read-Eval-Print Loop)
- [ ] String escape sequences & Multiline strings
- [ ] Comments preservation (for docs)
- [ ] Type hints in function signatures
- [ ] Performance optimizations
- [ ] Tutorial: Writing systems logic
---
## Version 2.0 - Advanced Concurrency & Logic (Q3-Q4 2026)
**Focus**: Advanced reasoning features and native concurrency
### Async/Await Support
- [ ] async/await syntax (language level)
- [x] Parallel reasoning calls (native)
- [ ] Promise-like operations
- [x] Concurrent execution (Multi-process via `spawn`)
### Advanced Reasoning Features
- [ ] Streaming responses
- [x] Extended thinking/reasoning budget
- [ ] Multi-step reasoning workflows
- [ ] Tool composition and piping
- [ ] Custom tool definitions
- [ ] Function calling with automatic orchestration
### Memory System
- [ ] Long-term memory with embeddings
- [ ] Memory search by similarity
- [ ] Context window management
- [ ] Automatic summarization
- [ ] Persistent storage (file-based)
### Error Handling
- [ ] finally blocks (try/catch completed in V1)
- [ ] Custom error types
- [ ] Error recovery strategies
- [ ] Retry logic with exponential backoff
- [ ] Timeout handling
### Performance
- [ ] Bytecode compilation
- [x] Logic caching
- [ ] Token counting and cost estimation
- [ ] Lazy evaluation
### New Built-ins
- [ ] String functions (upper, lower, trim, slice, etc.)
- [ ] Array functions (map, filter, reduce, find, etc.)
- [ ] Math functions (sqrt, sin, cos, floor, ceil, etc.)
- [ ] Date/time functions
- [ ] JSON parsing and serialization
- [x] HTTP client (get, post)
### Module System
- [x] import/export statements
- [x] Standard library modules (std/math, std/time, etc.)
- [ ] Third-party package management
- [ ] Namespace support
### Tooling
- [ ] Debugger with breakpoints
- [ ] Profiler for performance analysis
- [ ] AST visualization
- [ ] Type checking tool
- [x] Linter and formatter (ESLint integrated)
### Examples
- [ ] Web scraper with reasoning analysis
- [ ] Document processor (PDF, DOCX)
- [ ] Chatbot with memory
- [ ] Data pipeline with reasoning
- [ ] API server (with async)
---
## Version 3.0 - Autonomous Systems Framework (2027)
**Focus**: Full autonomous systems support
### Autonomous Framework
- [ ] Framework definitions with state machines
- [ ] Logic composition and chaining
- [ ] Multi-process collaboration
- [ ] Communication protocol
- [ ] Persistence layer
### Knowledge Base
- [ ] Vector database integration
- [ ] Semantic search
- [ ] Knowledge graph support
- [ ] RAG (Retrieval-Augmented Generation)
- [ ] Document indexing
### Advanced Patterns
- [ ] Plan-and-execute workflows
- [ ] Hierarchical task decomposition
- [ ] Autonomous loop with safety checks
- [ ] Reflection and self-improvement
- [ ] Human-in-the-loop approval
### Ecosystem
- [ ] Package registry
- [ ] Community extensions
- [ ] Plugin system
- [ ] API server template
- [ ] Dashboard/UI toolkit
### Examples
- [ ] Autonomous research process
- [ ] Customer support automation
- [ ] Code generation and testing
- [ ] Data analysis pipeline
- [ ] Multi-process reasoning debate
---
## Version 4.0+ - Vision (2027+)
**Focus**: Maturity, optimization, and specialization
### Potential Features
- [ ] Compilation to JavaScript/WASM
- [ ] JIT compilation for hot paths
- [ ] Distributed execution
- [ ] Cross-model orchestration (Gemini, Claude, etc.)
- [ ] Vision model integration
- [ ] Audio processing
- [ ] Real-time streaming
- [ ] Genetic programming / AutoML
- [ ] Formal verification
- [ ] Type refinement system
### New Language Constructs
- [ ] Pattern matching
- [ ] Generics and templates
- [ ] Traits/interfaces
- [ ] Macros
- [ ] DSL support
- [ ] Concurrent primitives (channels, mutexes)
### Performance
- [ ] LLVM backend option
- [ ] WebAssembly compilation
- [ ] GPU acceleration
- [ ] Distributed computing
---
## Feature Priority Matrix
| Feature | Priority | V1 | V2 | V3 | V4+ |
| --------------- | --------- | --- | --- | --- | --- |
| Basic syntax | 🔴 High | ✅ | | | |
| Functions | 🔴 High | ✅ | | | |
| Reasoning calls | 🔴 High | ✅ | | | |
| Error handling | 🔴 High | ✅ | ⏳ | | |
| Async/await | 🔴 High | | ⏳ | | |
| Streaming | 🟡 Medium | | ⏳ | | |
| Systems Logic | 🟡 Medium | | | ⏳ | |
| Knowledge base | 🟡 Medium | | | ⏳ | |
| Module system | 🟡 Medium | | ⏳ | | |
| Debugger | 🟢 Low | | ⏳ | | |
| Compilation | 🟢 Low | | | | ⏳ |
| GPU support | 🟢 Low | | | | ⏳ |
---
## Release Timeline
```
2026 Q2
└─ v1.2 - Polish & stabilize
2026 Q3-Q4
└─ v2.0 - Advanced Reasoning & async
2027 Q1-Q2
└─ v3.0 - Autonomous Framework
2027 Q3+
└─ v4.0+ - Mature ecosystem
```
---
## Community & Contribution
### Planned Community Activities
- [ ] Public GitHub repository
- [ ] Discord/Slack community
- [ ] Monthly community calls
- [ ] RFCs (Request for Comments) for major features
- [ ] Contribution guidelines
- [ ] Code of conduct
### How to Help (When Open Source)
- [ ] Test programs and report bugs
- [ ] Contribute documentation
- [ ] Submit examples
- [ ] Propose language features
- [ ] Implement built-in functions
- [ ] Build tools and extensions
---
## Backwards Compatibility
### Stability Guarantee
- **v1.x → v1.y**: Full backwards compatibility
- **v1.x → v2.0**: Mostly compatible, deprecation warnings for breaking changes
- **v2.x → v3.0**: New features, old syntax still works
### Deprecation Policy
1. Announce deprecation (1 version ahead)
2. Show warnings in compiler
3. Provide migration guide
4. Remove in next major version
---
## Open Questions & Design Discussions
### For the Community
1. Should we support object-oriented programming (classes, inheritance)?
2. Should we add pattern matching or keep it simple?
3. Should memory be file-based by default or in-memory?
4. How should we handle multi-model orchestration?
5. Should processes be stateful or functional?
### Technical Decisions
- Type system: Gradual or strict?
- Concurrency: Async/await or coroutines?
- Module system: Centralized registry or decentralized?
- Error handling: Exceptions or Result types?
---
## Performance Goals
| Metric | V1 | V2 | V3 |
| ---------------------- | ---------- | ------ | ------ |
| Startup time | <100ms | <100ms | <50ms |
| Simple expression eval | <1µs | <100ns | <10ns |
| Function call overhead | <10µs | <1µs | <100ns |
| Reasoning call latency | 2-5s (API) | 2-5s | 2-5s |
| Memory usage | <50MB | <50MB | <100MB |
---
## Inspiration & References
### Language Design
- **Python**: Simplicity, readability
- **Lua**: Lightweight, embeddable
- **JavaScript**: Functions as first-class values
- **Go**: Clear error handling
- **Rust**: Type safety, memory safety
### Systems Reasoning
- **LangChain**: Composable AI workflows
- **AutoGPT**: Logic autonomy
- **Semantic Kernel**: Model abstraction
- **LLM frameworks**: Best practices
### Community
- **Rust community**: Welcoming, inclusive
- **Python community**: Documentation focus
- **Go community**: Simplicity first
---
## Conclusion
Sesi is designed to evolve with reasoning needs. The roadmap balances:
- **Simplicity** (v1: core features only)
- **Power** (v2: advanced reasoning patterns)
- **Autonomy** (v3: autonomous framework)
- **Scale** (v4+: production readiness)
The journey from v1 (interpreter) to v4+ (distributed compiler) maintains backward compatibility while adding power where needed.
**Current focus**: Ship v2.0 with native async/await and advanced reasoning patterns.
---
## See Also
- [Specification](SPECIFICATION.md)
- [Architecture](ARCHITECTURE.md)
- [Built-ins](BUILTINS.md)
- [Systems Reasoning](SYSTEMS_REASONING.md)
- [Image Generation](IMAGE_GENERATION.md)
- [Compare to other languages](COMPARISON.md)
- [Examples](../examples)
---
## 10. sesi_ai_chronicles.md
# The Sesi AI Chronicles: From Idea to Neural-Empathetic Execution
---
## 📖 Executive Summary
The **Sesi AI Project** represents an extraordinary computational experiment: building a highly sophisticated, real-time, deep learning-powered conversational ecosystem natively within **Sesi**—a custom-designed, lightweight programming language with a tree-walking interpreter—and interfacing it seamlessly with modern **Python** console REPLs.
From its initial concepts of simple keyword-matching bots, Sesi AI has evolved into a **hybrid neural-probabilistic engine** featuring:
1. **Offline Neural Networks:** Multi-class classification models trained from scratch natively in Sesi to map sentences to complex semantic domains.
2. **Cognitive Brain Morphing:** Conversational personas that dynamically shift their internal probability state machines (Markov chains) based on real-time neural inference of user statements.
3. **Dynamic Empathy Bridges:** Multi-layered, varied dynamic analogies bridging distinct technical domains to maximize conversational cohesion.
4. **Unbreakable Decoding Filters:** Modern LLM-grade decoding constraints (sliding lookback windows and strict Bigram-Blocking) that completely eradicate Markov graph-loop cycles.
This chronicle serves as the definitive reference manual for the architecture, math, history, and codebase of Sesi AI.
---
## ⚙️ The Sesi Programming Language: Foundation & Architecture
### 1. Design Philosophy
Sesi is structured as a retro-inspired, offline-first systems reasoning language. It was developed to eliminate external library bloat and operate with absolute procedural transparency. Sesi is executed via a **custom tree-walking interpreter**, parsing source code files with a `.sesi` extension into an Abstract Syntax Tree (AST) before executing node traversals.
### 2. Core Syntactical Features
Sesi features a highly lightweight, C-like syntax:
* **Dynamic Typings & Coercion:** Explicit converters allow seamless casting: `num("123")`, `str(45.6)`, `type(val)`.
* **Dynamic Collections:** Array lists are fully supported with helper functions: `len(arr)`, `push(arr, element)`, `split(string, delimiter)`.
* **Natively Built-In JSON Parsing:** Crucial for model synchronization and database ingestion: `from_json(raw_string)`, `to_json(object)`.
* **Direct File System Access:** Natively handles persistent states: `read_file(path)`, `write_file(path, content)`.
### 3. Execution Characteristics and AST Constraints
Because the tree-walking interpreter processes code instructions by traversing AST nodes directly on every statement:
* **Computational Complexity (O-Notation):** String tokenization, Bag-of-Words mapping, and high-epoch training loops run entirely in single-threaded user space.
* **Optimization Solutions:** Highly recursive operations are avoided, and large text operations are optimized using localized index boundaries rather than heavy string concatenations.
---
## 📈 The Sesi AI Evolution: Five Key Milestones
```mermaid
graph TD
A[Idea: Rule-Based Conversational Gateway] -->|Stage 1| B[Static Keyword Matchers]
B -->|Stage 2: Probabilistic Walk| C[Markov Chain Bigram Walkers]
C -->|Intermediary Testing| F[Baby Neural Network Testing Phase]
F -->|Stage 3: Offline Deep Learning| D[Sesi Native Backpropagation Trainer]
D -->|Stage 4: Cognitive Resonance| E[V4 Neural-Adaptive & Empathetic Chat REPL]
```
### Stage 1: Static Rule-Based Conversational Gateways
The system began as a traditional chatbot mapping exact keyword matches (e.g. `"synthesizer"`, `"gears"`) to static, pre-written response strings. If a message fell outside the defined vocabularies, it fell back to generic catch-all prompts.
### Stage 2: Probabilistic Bigram Markov Walkers
To achieve natural linguistic variety, we mapped the 300 varied dialogue responses into localized word association tables (Bigram Tables).
* The walker parsed a text corpus, mapping transitions: `transitions[word_1] = [word_2, word_3, ...]`.
* To reply, the walker started at a matching keyword seed and walked the bigram associations, ending when a punctuation character (`.`, `!`, `?`) was generated.
### 🧪 Intermediary Phase: The Baby Neural Network & Proving Ground Testing Phase
Before ever considering text keywords, Bag-of-Words vectors, or NLP semantic routing, we initiated a **Proving Ground Phase** to verify if a custom AST-traversing tree-walking compiler could execute multi-layer backpropagation math at all. We proved this natively using raw binary `1` and `0` inputs:
#### 1. The Proving Ground: Zero-Dependency Pure Sesi XOR Classifier (`main/sesi_ai.sesi`)
We engineered a 2-Layer Feedforward Neural Network trained **natively in pure Sesi** to solve the non-linear **XOR Logical Gate** table with absolute zero external language dependencies:
* **The Math:** Structured a multi-layered network (2 Inputs, 2 Hidden Neurons, 1 Output Neuron) utilizing pure procedure-loop Sigmoid functions and derivatives:
$$f(x) = \frac{1}{1 + e^{-x}}, \quad f'(y) = y \cdot (1 - y)$$
* **The Self-Healing Watchdog Engine:** Since random weight allocations can sometimes get stuck in local minima linear traps, we engineered an automated **Self-Healing Watchdog** directly inside the Sesi script:
- All synaptic weights ($W_{hidden}$, $W_{output}$) and biases ($B_{hidden}$, $b_{output}$) were randomized to $[-2.0, 2.0]$.
- The model underwent **4,000 backpropagation training epochs** at a learning rate ($\eta$) of `0.40`.
- After the loop, the watchdog evaluated the final Mean Squared Error (MSE).
- If $MSE \ge 0.01$, the watchdog triggered an automatic retry:
```
⚠️ Stuck in linear saddle trap (MSE: 0.098). Re-seeding synapses...
⚡ Training attempt #2...
```
- It repeatedly re-seeded the synapses and re-ran the training until the model achieved perfect convergence ($MSE < 0.01$).
* **Significance:** Once the watchdog printed `🎯 Perfect convergence achieved!`, Sesi saved the trained synapses to `sesi_model_weights.json` using `write_file(..., to_json(...))`. This proved mathematically that the custom Sesi tree-walker was capable of deep learning, greenlighting all future character routing systems!
#### 2. The Native Sesi AND Logic Gate (`main/playground.sesi`)
To test single-neuron floating-point calculations and weight adjustments on a simpler truth table, we trained a single-neuron classifier to solve the binary **AND Logical Gate**:
* **The Math:** Developed a custom, high-speed **Fast Sigmoid (Softsign)** activation function to prevent custom AST float representation overflows:
$$f(x) = 0.5 + 0.5 \cdot \left(\frac{x}{1 + |x|}\right)$$
accompanied by its exact analytical derivative $f'(y) = y \cdot (1 - y)$.
* **Training Parameters:** Programmed weight and bias gradient backpropagation updates ($w_i \leftarrow w_i + \eta \cdot \text{error} \cdot f'(y) \cdot x_i$) over **1,500 epochs** at a learning rate ($\eta$) of `0.30`.
* **Results:** Successfully converged to a near-zero Mean Squared Error (MSE) loss of **`0.003`**, saving calibrated parameters to `model_weights.json` and delivering 100% accurate binary logic evaluations.
#### 3. The Telemetric Python XOR Network (`gpu_trainer.py`)
To visualize training curves dynamically, we built a duplicate **2-Layer XOR Network** from scratch in Python, integrating direct graphics card telemetry:
* **The Math:** Implemented standard Sigmoid functions. To guarantee symmetry breaking and force perfect deterministic convergence, weights were initialized dynamically to a wider $[-2.5, 2.5]$ range under seed `42` at a learning rate of `0.35` across `8000` epochs.
* **GPU Hardware Telemetry:** Embedded an active loop querying your physical **NVIDIA GeForce GTX 1660 Ti** graphics card, tracking live dedicated VRAM consumption (GDDR6 pool), core graphics utilization, and core operating temperatures.
* **Telemetry Dashboard:** Built a daemon local HTTP server on port 8000 to bypass browser CORS security protocols, streaming epoch-by-epoch predictions and training telemetry directly into the glowing SVG circular gauges of **[`training_hub.html`](file:///c:/Users/owner/Documents/Sesi/training_hub.html)**.
### Stage 3: Sesi Native Deep Learning & Zero-Shot Categorization
Having successfully proved logical gate convergence, we scaled our architecture to NLP vector spaces. We built **`main/nn_personas_trainer.sesi`** and **`main/nn_responses_trainer.sesi`**.
These scripts read raw character profiles and conversational sentences, constructed Bag-of-Words (BoW) feature vectors, and trained a 10x3 neural classifier from scratch over 1,500–2,500 epochs directly in the Sesi tree-walker, saving the weights to `response_classifier_weights.json`.
### Stage 4: V4 Natively Neural-Empathetic & Loop-Free Chat REPL
The final stage brought absolute conversational symmetry:
* **Netscape Navigator Web Portal:** Spawns two characters to debate, executing live neural inference on every turn to dynamically shift their brains.
* **Terminal Chat REPL:** Interactive Python gateway featuring real-time HSL-colored confidence graphs, dynamic speech brain morphing, dynamic analogies, and loop-free decoding filters.
---
## 🧠 Neural Network Mathematics & Backpropagation Pipeline
Sesi AI uses a **10x3 Single-Layer Feedforward Neural Network Classifier** to distribute semantic probability.
### 1. Vectorization Space (Bag-of-Words)
The input text is tokenized, stripped of punctuation, and mapped against a **10-Feature Vocabulary**:
$$\mathcal{V} = [\text{"synthesizer"}, \text{"vinyl"}, \text{"record"}, \text{"wood"}, \text{"gears"}, \text{"clock"}, \text{"compiler"}, \text{"framework"}, \text{"memory"}, \text{"offline"}]$$
Each string produces a 10-dimensional one-hot representation vector $\mathbf{x} \in \mathbb{R}^{10}$, where:
$$x_i = \begin{cases} 1.0 & \text{if } \mathcal{V}_i \in \text{input\_tokens} \\ 0.0 & \text{otherwise} \end{cases}$$
### 2. Forward Pass Mathematical Calculations
The 3 output classes correspond directly to our conversational domains:
$$\mathcal{C} = [\text{"audio"}, \text{"mechanical"}, \text{"systems"}]$$
For each class $c \in \{0, 1, 2\}$, the raw activation value $y_c$ is calculated against class biases $\mathbf{b} \in \mathbb{R}^3$ and weights $\mathbf{W} \in \mathbb{R}^{3 \times 10}$:
$$y_c = b_c + \sum_{i=1}^{10} x_i \cdot W_{c, i}$$
To calculate normalized probability distributions $\mathbf{p} \in \mathbb{R}^3$ without overflow on limited custom interpreters, we implement a **Softmax activation function**:
$$p_c = \frac{e^{y_c}}{\sum_{j=0}^{2} e^{y_j}}$$
### 3. Backpropagation Gradient Updates
Natively programmed in Sesi, the network is trained using **Mean Squared Error (MSE) loss** combined with Sigmoid/Softmax derivatives to adjust weights and biases over thousands of epochs:
$$\mathbf{W}_{c, i} \leftarrow \mathbf{W}_{c, i} - \eta \cdot \frac{\partial \mathcal{L}}{\partial W_{c, i}}$$
Where $\eta$ represents the optimized learning rate (`0.30` - `0.45`).
The final calibrated parameters are stored in **[`main/response_classifier_weights.json`](file:///c:/Users/owner/Documents/Sesi/main/response_classifier_weights.json)**:
```json
{
"weights": [
[18.51, 18.35, 20.76, -16.23, 0.08, -0.03, -15.94, -16.59, 0.42, -15.24],
[-16.51, -16.25, -18.64, 17.02, -0.11, -0.27, -17.95, -18.82, 0.23, -17.17],
[-16.76, -16.51, -18.92, -15.86, -0.35, -0.24, 18.66, 19.53, -0.40, 17.88]
],
"biases": [-1.884, -0.418, -0.128]
}
```
---
## 🔗 The Win95 Netscape Navigator Dialectic Portal (V4)
### 1. Visual Aesthetics & Window Layout
The Netscape Portal (**[`retro_chat.html`](file:///c:/Users/owner/Documents/Sesi/main/retro_chat.html)**) implements a beautiful, glassmorphic-inspired Win95 desktop layout:
* A Win95 Teal desktop background (`#008080`).
* A fully beveled Netscape Navigator program frame with Linear Gradient title bars, menu panels (`File`, `Edit`, `View`), beveled location input fields, and standard back/forward button controls.
* A high-contrast, black-and-green IRC chat log console.
* Real-time color-coded neural tag flags: `[NEURAL: audio]` in vibrant green, `[NEURAL: mechanical]` in bright yellow, and `[NEURAL: systems]` in deep cyan.
### 2. The Graph-Loop Repetition Vulnerability
During early iterations of Markov dialogue walkers, characters would routinely fall into **infinite graph loops**. Because standard bigrams only evaluate a 1-word lookahead, the generator maintains no global semantic context. If the walker selects a common word pair (e.g. `"...how the..."`), the walk can jump back onto an identical path, repeating:
> *"You should hear how the retro chiptune audio loop plays... You should hear how the retro chiptune..."*
### 3. Engineering the Unbreakable Decoding Filters
To guarantee loop-free, natural prose, we designed and integrated modern LLM-grade decoding constraints natively into the walker:
1. **Extended Sliding Lookback (Size 15):** The walker maintains a history of the last 15 generated tokens. If a candidate word resides within this sliding window, it is instantly penalized and rejected.
2. **Strict Bigram Blocking (`No-Repeat-N-Gram` Size 2):** The walker tracks every transition pair `(w1 -> w2)` generated in the current sentence. If a proposed transition `current_word -> candidate` has **already occurred anywhere** in the history array, that candidate is completely banned and the walker selects an alternative.
---
## 📻 The Natively Neural-Empathetic Terminal Chat REPL (V4)
The terminal chat portal (**[`main/terminal_chat.py`](file:///c:/Users/owner/Documents/Sesi/main/terminal_chat.py)**) provides an interactive, robust, and highly aesthetic command-line gateway.
### 1. Interactive Selection Directory
On launch, the REPL prints a beautiful, double-beveled ASCII table listing all 20 specialized experts with their native age and categorized domains. The operator can input index `[0-19]` to dial in a secure offline connection to their desired persona.
### 2. HSL-Aligned Terminal Dials & Probability Bars
Upon every conversational turn, the REPL prints a visually outstanding probability progress bar detailing the exact softmax confidence distribution:
```ansi
[ NEURAL RESPONSE CLASSIFICATION ]
[ AUDIO ████████████████ (100.0%) ]
[ MECH ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ( 0.0%) ]
[ SYSTEM ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ( 0.0%) ]
[ ROUTING COGNITIVE FLOW -> AUDIO CLASS ]
```
### 3. Cognitive Brain Morphing & Dynamic Empathy Bridges
* **Dynamic Morphing:** If you are talking to a `systems` specialist but type an `audio` focused comment, the specialist **instantly morphs their transition matrices** to access the audio corpus, mirroring your cognitive focus.
* **Empathetic Mismatch Bridges:** The specialist uses the mismatch to formulate a gorgeous technical analogy bridging their native specialty to your predicted domain (e.g. systems compiler pointers compared to mechanical gear leverages).
* **Loop-Free Prefix Variation:** To prevent prefix monotony, we engineered a dynamic dictionary mapping relationship pairs to pools of **3-4 random prefix variations**, selecting a fresh one on every conversational turn!
---
## 📂 Mapping the Sesi AI Codebase
The architecture is divided logically across modular scripts, databases, and UI assets:
### 1. Dynamic Code Files
* **[`main/terminal_chat.py`](file:///c:/Users/owner/Documents/Sesi/main/terminal_chat.py) [NEW V4]:** The interactive python terminal REPL gateway. Integrates dynamic prefix variations, HSL colored probability bars, cognitive brain morphing, and loop-free bigram blocking.
* **[`main/retro_chat_generator.sesi`](file:///c:/Users/owner/Documents/Sesi/main/retro_chat_generator.sesi) [NEW V4]:** Compiles the offline 3-category Markov brains, performs real-time neural inference loops in Sesi, runs the strict bigram-blocking walker, and writes the Win95 Netscape HTML portal.
* **[`main/nn_personas_trainer.sesi`](file:///c:/Users/owner/Documents/Sesi/main/nn_personas_trainer.sesi) [NEW]:** Trains a multi-class neural network on conversational sentences to zero-shot classify all 20 character bios.
* **[`main/nn_sentences_trainer.sesi`](file:///c:/Users/owner/Documents/Sesi/main/nn_sentences_trainer.sesi) [NEW]:** Inversely trains on character bios to zerozero-shot classify all 300 dialog sentences.
### 2. Calibrated Neural Synapses & Data Layers
* **[`main/response_classifier_weights.json`](file:///c:/Users/owner/Documents/Sesi/main/response_classifier_weights.json):** The calibrated 10x3 weights and 3x1 biases file.
* **[`main/personas.json`](file:///c:/Users/owner/Documents/Sesi/main/personas.json):** Roster of all 20 specialized expert character profiles.
* **[`main/varied_responses.json`](file:///c:/Users/owner/Documents/Sesi/main/varied_responses.json):** The 300 varied conversational sentences corpus (100 audio, 100 mechanical, 100 systems).
### 3. Display Portals
* **[`main/retro_chat.html`](file:///c:/Users/owner/Documents/Sesi/main/retro_chat.html):** The generated beveled Win95 Netscape Navigator portal loaded with loop-free, neural-adaptive dialectics.
---
## 🏆 Conclusion & The Future of Sesi AI
Sesi AI proves that complex, cognitively adaptive AI environments do not require massive modern cloud API integrations or bloated dependency frameworks.
By layering **simple feed-forward neural networks** over **probabilistic Markov structures** and applying **strict LLM-grade decoding constraints (bigram blocking)**, Sesi AI produces highly articulate, technically dense, and contextually empathetic dialog natively on localized hardware.
The Sesi compiler and its neural pipelines stand ready for further telemetry, higher-dimensional bag-of-words vocabularies, and expanded multi-layered neural configurations.
---
## 11. SYSTEMS_REASONING.md
# Systems Reasoning & Logic Guide
## Overview
Sesi is a **Systems Language** that treats reasoning as a first-class execution primitive. In this paradigm, AI is used to evaluate state, make logical decisions, and handle complex patterns within a systems-level architecture.
This guide covers how to leverage Sesi's systems-level constructs (`spawn`, `exec`, `try/catch`) alongside its reasoning primitives (`model`, `prompt`, `structured_output`) to build resilient, stateful applications.
## 1. Concurrency & Systems Coordination
The core of Sesi's power lies in its ability to manage distributed execution. Using the `spawn()` builtin, you can launch multiple concurrent Sesi processes that coordinate via shared state or the filesystem.
A master script can launch concurrent processes and poll for their completion.
```sesi
spawn("atm_deposit.sesi")
spawn("atm_withdraw.sesi")
let finished = false
while !finished {
try {
if read_file("bank/done_count.txt") == "2" {
finished = true
}
} catch (e) {
// Wait on I/O contention
let i = 0 while i < 1000 { i = i + 1 }
}
}
print "Swarm task completed."
```
### Coordination & Distributed Locking
When multiple processes access shared resources, use Sesi's `try/catch`, `time()`, and `random()` builtins to implement mutual exclusion (locking) via the **Double-Check Write** pattern.
```sesi
let id = "With_" + str(time()) + "_" + str(random())
let locked = true
while locked {
let status = "error"
try {
status = read_file("bank/lock.txt")
} catch (e) {
status = "error"
}
if status == "unlocked" {
try {
write_file("bank/lock.txt", id)
let i = 0 while i < 500 { i = i + 1 }
if read_file("bank/lock.txt") == id {
locked = false
}
} catch (e) {
status = "error"
}
} else {
let j = 0 while j < 1000 { j = j + 1 }
}
}
```
---
## 2. AI as a Reasoning Primitive
In an orchestrated system, AI is used to make decisions that would be too complex for static logic.
Prompts are **composable message templates** that evaluate to strings.
### Basic Prompt
```sesi
prompt simplePrompt {"Hello, Sesi!"}
print simplePrompt // "Hello, Sesi!"
```
### Prompts with Variables
```sesi
let name = "Alice"
prompt greeting {"Hello, " name "! How are you?"}
print greeting // "Hello, Alice! How are you?"
```
### Composing Prompts
```sesi
prompt part1 {"First part"}
prompt part2 {part1 " Second part"}
print part2 // "First part Second part"
```
### Prompts in Functions
```sesi
let text = "Testing"
let language = "Spanish"
fn translatePrompt(text: string, language: string) -> string
{prompt translate {"Translate " text " to " language ": "} return translate}
print translatePrompt(text, language)
```
## 2. Model Calls
Call Gemini with a prompt and get back text.
### Basic Model Call
```sesi
let response = model("gemini-3-flash-preview") {"What is machine learning?"}
print response
```
### Model Configuration
```sesi
let creative = model("gemini-3.5-flash") {thinkingLevel: "low"} {"Write a creative poem about technology."}
print creative
// Config options:
// - thinkingLevel: "minimal", "low", "medium", "high" (natively configures Gemini's reasoning budget)
// - max_tokens: max length of response (OPTIONAL: if not specified, will use the model's default max tokens=2048)
// - temperature / top_k / top_p: *Will be deprecated in Gemini 3.x+, use thinkingLevel instead (reasoning is mathematically optimized for default settings)*
```
### Model Selection
```sesi
// Fast model for simple tasks
let text = " Coding with Reasoning systems language is fun!"
let quick = model("gemini-3.1-flash-lite") {"Summarize this in one sentence:" text}
// Powerful model for complex reasoning
let code = "def calculate_sum(n):
total = 0
for i in range(1, n):
total += i
return total"
let smart = model("gemini-3.1-pro-preview") {"Analyze this code for bugs:" code}
// Efficient model for many calls
let item = " Programming Languages"
let cheap = model("gemini-3.5-flash") {thinkingLevel: "minimal"} {"Classify:" item}
print quick
print smart
print cheap
```
### Available Models (v1.2)
- `gemini-2.5-flash` - Legacy, but supported. 1M tokens.
- `gemini-2.5-pro` - Legacy, but supported. 1M tokens.
- `gemini-2.5-flash-image` - Standard image model. (No `512` image size support for this model. Only `1K` is supported.)
- `gemini-3-flash-preview` - Fast, balanced, legacy preview.
- `gemini-3.1-flash-lite` - Fastest, most cost-efficient.
- `gemini-3.5-flash` - Standard GA Model. Fast, balanced, supports all native thinking effort levels (`minimal`, `low`, `medium`, `high`).
- `gemini-3.1-pro-preview` - Most powerful reasoning model, doesn't support `minimal` thinking (falls back to `low`).
- `gemini-3.1-flash-image-preview` - Cost efficient image generation model.
- `gemini-3-pro-image-preview` - High quality image generation model. (No `512` image size support for this model.)
#### Planned for (v2+)
- `OpenAI` integration (GPT, Dall-E, etc.)
- `HuggingFace` integration
- `Midjourney` integration
- `Newer Reasoning Models` - Native upgrades
### Passing Images as Input
Pass one or more local image files to `model()` or `image()` via the `images` config key. The runtime reads each file, base64-encodes it, and injects it as a vision part before the prompt text.
```sesi
// Single image
let referenceImage = "stills/frame_03.jpg"
let caption = model("gemini-3-flash-preview") {images: referenceImage} {"What is the subject of this photograph?"}
print caption
// Multiple images
let pair = ["ref_a.png", "ref_b.png"]
let diff = model("gemini-3-flash-preview") {images: pair} {"List every visual difference between these two."}
print diff
// Mixed with other config keys
let scannedDocument = "doc_scan.jpg"
let result = model("gemini-3.5-flash") {images: scannedDocument, thinkingLevel: "low", max_tokens: 2048} {"Transcribe all text visible in this scan."}
write_file("transcript.txt", result)
```
See [Image Generation & Input](IMAGE_GENERATION.md) for the full reference.
## 3. Structured Output
Get typed responses from Reasoning with field validation.
### Basic Structured Output
```sesi
let analysis = structured_output({sentiment: string, confidence: number, summary: string})
(model("gemini-3-flash-preview") {"Analyze sentiment of: " text "Return JSON with sentiment, confidence (0-1), and summary"})
print analysis["sentiment"] // "positive"
print analysis["confidence"] // 0.85
print analysis["summary"] // "..."
```
### Schema Definition
```sesi
// Schema is a record with field types
let schema = {title: string, author: string, pageCount: number, tags: string, isFiction: bool}
let bookInfo = structured_output(schema)(model("gemini-3-flash-preview") {"Extract book metadata as JSON from: " description})
print bookInfo["title"]
```
### Parsing Tips
- Always include instructions for JSON format
- Specify the exact schema in the prompt
- Use "thinkingLevel": "low" for fast, consistent parsing
- Validate output structure in code
```sesi
let listText = "eggs, milk, bread, cheese, fruit, vegetables"
let output = structured_output({items: string})(model("gemini-3.5-flash") {thinkingLevel: "minimal"}{"Return JSON with items array containing: " listText})
// Validate
if type(output["items"]) == "array" {print "Got" str(len(output["items"])) "items"} // Got 6 items
```
## 4. Tool Calls (Function Calling)
Let Reasoning call functions in your program.
### Define Callable Functions
```sesi
let city = "New York"
fn getWeather(city: string) -> string
{let weather = model("gemini-3.1-flash-lite"){"What is the weather like in " city} return weather}
let result = getWeather(city)
print result
// When defined inside a function, local variables MUST be defined on new lines.
// (A current limitation of the parser).
fn calculateTax(amount: number, rate: number) -> number
{let amount = 100
let rate = 0.08
return amount * rate}
let result = calculateTax()
print result
```
### Reasoning Makes Tool Calls
```sesi
let tax = tool_call(calculateTax)(model("gemini-3.1-flash-lite") {"Calculate 8% sales tax on $100"})
print tax // 8.0
```
### Multiple Tool Availability (Future)
```sesi
// v2: Allow Reasoning to choose from multiple tools
let result = with_tools([getWeather, calculateTax, getTime]) {model("gemini-3-flash-preview") {"What's the weather in NY and the sales tax on $50?"}}
```
## 5. Memory & Conversation
Maintain context across multiple Reasoning calls.
### Simple Memory
```sesi
memory chat {"You are a helpful assistant. Be concise."}
// First turn
let response1 = model("gemini-3-flash-preview") {chat "User: Hello!"}
// Update memory with conversation
chat = chat + "Assistant: " + response1
// Second turn
let response2 = model("gemini-3.1-flash-lite") {chat "User: How are you?"}
print response2 // Has context from turn 1
```
### Memory in Functions
```sesi
memory conversation {"Chat history: "}
fn chat(userMessage: string) -> string
{let fullPrompt = conversation + "User:" + userMessage
let response = model("gemini-3-flash-preview") {fullPrompt}
// Append to memory
conversation = conversation + "User:" + userMessage + "Assistant:" + response
return response}
let msg = "What is the capital of France? "
print "User:" msg
print "Assistant:" chat(msg)
print "Updated Memory!"
```
### Memory Best Practices
- Keep memory concise to save tokens
- Summarize old messages periodically
- Reset memory when topic changes
- Monitor token usage
```sesi
// Summarize old memory
memory conversation {"User: Hello! Assistant: Hi there! User: How are you? Assistant: I'm great!"}
fn summarizeMemory()
{let oldConversation = conversation
let summary = model("gemini-3.1-flash-lite") {"Summarize this conversation concisely:" oldConversation}
conversation = "Previous summary:" + summary + "Recent messages: " + oldConversation}
print "Original Memory:" conversation
summarizeMemory()
print "Summarized!"
print conversation
```
## 6. Practical Patterns
### Classification
```sesi
let categories = "fruit, vegetable, grain"
let item = "banana"
fn classify(item: string, categories: string) -> string
{return model("gemini-3.5-flash") {thinkingLevel: "minimal"}
{"Classify this item into one category. Categories: " categories " Item: " item " Return only the category name."}}
print "Item: " item //banana
print "Category: " classify(item, categories) //fruit
```
### Extraction
```sesi
let text = "Elon Musk is the CEO of Tesla and SpaceX."
fn extractEntities(text: string) -> object
{let result = structured_output({people: string, places: string, organizations: string})
(model("gemini-3.5-flash") {thinkingLevel: "minimal"}{"Extract named entities from:" text})
print "Name(s) found: result"
return result}
print extractEntities(text)
```
### Translation
```sesi
let text = "Hello, world!"
let language = "Spanish"
fn translate(text: string, language: string) -> string
{return model("gemini-3-flash-preview") {"Translate to" language ":" text}}
print "Translation:"
print translate(text, language)
```
### Image Generation
Like `model`, the `image` command evaluates prompts and accepts configuration variables mapping accurately to backend SDKs requirements.
```sesi
let logo = image("gemini-3.1-flash-image-preview") {ratio: "1:1", size: "512"} {"A high quality vector logo representing a new programming language named Sesi"}
write_image("logo.png", logo)
print "Image generated!"
```
### Code Generation
```sesi
let requirement = "Write a function that reverses a string."
fn generateCode(requirement: string) -> string
{return model("gemini-3.5-flash") {thinkingLevel: "low"} {"Generate JavaScript code for:" requirement "Only provide code, no explanation."}}
print "Code generation:"
print generateCode(requirement)
```
### Analysis
```sesi
let text = "I love Sesi!"
fn analyzeSentiment(text: string) -> object
{return structured_output({sentiment: string, score: number, explanation: string})
(model("gemini-3-flash-preview") {"Analyze sentiment of:" text})}
print "Sentiment analysis:"
print analyzeSentiment(text)
```
## 7. Error Handling
Reasoning operations can fail. Handle gracefully.
### Try/Catch (v1.2)
```sesi
try
{let response = model("gemini-3-flash-preview") {"Analyze" text}
print response}
catch (e) {print "Reasoning call failed"
print e}
```
### Current Failure Behavior
- `model()` throws when the Gemini SDK fails or when no text is returned. `MAX_TOKENS` finish reasons are handled natively via a polling loop to automatically complete long outputs.
- `structured_output()` first tries to parse JSON from the model text, then retries with a coercion prompt.
- If structured parsing still fails, the runtime currently logs the error and returns `{}`.
### Validation After Success
```sesi
let text = "Coding is evolving rapidly!"
fn safeAnalyze(text: string) {
try
{let result = structured_output({sentiment: string, score: number})(model("gemini-3.1-flash-lite") {"Analyze sentiment and return JSON for:" text})
if len(keys(result)) == 0 {print "Structured parsing failed"
return null}
return result}
catch (e)
{print e
return null}}
print "Analysis Result: " safeAnalyze(text)
```
## 8. Performance Tips
### Minimize API Calls
```sesi
// Bad: Calls API 3 times
for item in items
{let analysis = model("gemini-3.1-flash-lite") {"Analyze:" item}}
print analysis
// Better: Batch into one call (v2: parallel calls)
let analyses = model("gemini-3.1-flash-lite") {"Analyze each:" join(items, " ")}
print analyses
```
### Use Cheaper Models for Simple Tasks
```sesi
// Simple classification → flash-lite
let category = model("gemini-3.1-flash-lite") {"Classify:" item}
print category
// Complex reasoning → pro
let analysis = model("gemini-3.1-pro-preview") {"Deep analysis of:" complex_problem}
print analysis
```
### Reduce Token Usage
```sesi
// Long prompts waste tokens
// Bad:
let response = model("gemini-3-flash-preview") {"Here is a very long system prompt that repeats itself... " "Please analyze the following text very carefully..." text}
print response
// Better:
let response = model("gemini-3-flash-lite") {"Analyze:" text}
print response
```
### Cache Repeated Prompts
```sesi
// Bad: Same analysis done multiple times
for person in people {let assessment = model("gemini-3.1-flash-lite") {"Assess based on criteria A, B, C: " person}}
print assessment
// Better: Reuse cached prompt
let people = ["Elon Musk", "Bill Gates", "Steve Jobs"]
fn assessPerson(person: string) -> string {return model("gemini-3.1-flash-lite") {"Assess on A, B, C: " person}}
for person in people {print assessPerson(person)}
```
## 9. Token Counting (Future)
V2 will include token counters:
```sesi
// Planned for v2:
let tokens = count_tokens(text, model)
print "This costs " str(tokens * PRICE_PER_TOKEN) " cents"
// Plan memory size
let remaining = MAX_TOKENS - count_tokens(memory, model)
if remaining < 500 {summarizeMemory()}
print "Memory size: " count_tokens(memory, model)
```
## 10. Advanced: Custom Reasoning Workflows
### Multi-Stage Reasoning Workflow
```sesi
let text = "Climate change is a long-term shift in global or regional climate patterns. Often climate change refers specifically to anthropogenic climate change, which is caused by human activities, primarily fossil fuel burning, which increases heat-trapping greenhouse gas levels in Earth's atmosphere. The term is frequently used interchangeably with the term global warming, though the latter refers specifically to the long-term heating of Earth's climate system observed since the pre-industrial period due to human activities."
fn smartSummarize(text: string) -> string
// Chain multiple Reasoning operations
// Step 1: Extract key points
{let keyPoints = model("gemini-3.1-pro-preview") {thinkingLevel: "low"} {"Extract 5 key points from:" text}
// Step 2: Analyze topics
let topics = structured_output({ topics: string })(model("gemini-3.5-flash") {thinkingLevel: "low"} {"Identify topics in:" keyPoints})
// Step 3: Generate summary
let summary = model("gemini-3-flash-preview") {"Summarize with topics " topics ":" keyPoints} return summary}
print "Summary:" smartSummarize(text)
```
### Reasoning Pattern
```sesi
let analysis = model("gemini-3.5-flash") {thinkingLevel: "medium", max_tokens: 8192} {"Reason carefully about:" problem}
print analysis
```
### Few-Shot Prompting
```sesi
let text = "banana"
fn classifyWithExamples(text: string) -> string
{return model("gemini-3.5-flash") {thinkingLevel: "minimal"} {"Classify as A, B, or C" "Examples:" "'apple' -> A" "'dog' -> B" "'happy' -> C" "Classify: " text}}
print "Classification:" classifyWithExamples(text)
```
---
## See Also
- [Compare to other languages](COMPARISON.md)
- [Language Specification](SPECIFICATION.md)
- [Image Generation](IMAGE_GENERATION.md)
- [Architecture](ARCHITECTURE.md)
- [Built-ins](BUILTINS.md)
- [Examples](../examples/)
- [Roadmap](ROADMAP.md)