Skip to main content

Nexa — The AI-native programming language. model/train/predict as first-class keywords.

Project description

<<<<<<< HEAD Nexa Language

Nexa Language

The first programming language where model, train, and predict are keywords.

CI PyPI Python License: MIT Discord Registry

Website · Docs · Packages · Discord · Blog

Nexa v27

⚡ Nexa Programming Language

Modern · AI-Native · Expressive · Safe

The language where AI is a first-class citizen.
Blending the clarity of Python, the safety of Rust, and built-in AI primitives — in one clean syntax.

Build Version License Python Discord Stars


import "agent"

// Build an AI chatbot in 10 lines 🤖
let bot = agent.create("groq", model="llama-3.3-70b")
var history = []

loop {
    let input = read("You: ")
    if input == "quit" { break }
    append(history, {"role": "user", "content": input})
    let reply = await bot.chat(history)
    print(f"Bot: {reply}")
}

👆 That's it. An AI chatbot with memory. In Nexa.

📖 Documentation · 🚀 Quick Start · 💬 Community · 🗺️ Roadmap

505371e59d95447c4de1bb675f9eb2687f79f60d


<<<<<<< HEAD

🚀 Install

=======

✨ Why Nexa?

Feature Python Rust Go Nexa
Easy syntax
Type safety ⚠️
AI keywords built-in
Pattern matching ⚠️
Async/await
REPL
Built-in test framework
Pipe operators
Package manager

🚀 Quick Start

Install

505371e59d95447c4de1bb675f9eb2687f79f60d

pip install nexa-lang

<<<<<<< HEAD That's it. No build system. No dependencies. Works on Windows, Mac, Linux.


✨ What makes Nexa different?

// Train a neural network in 3 lines — no imports, no boilerplate
model Classifier {
    layers: [Dense(256), ReLU, Dropout(0.3), Dense(10)]
    optimizer: "adam"
}
train Classifier on my_dataset { epochs: 50, batch: 32 }
let prediction = predict Classifier(new_input)

No other language on Earth makes this possible. model, train, and predict are keywords — not library calls, not decorators, not framework syntax. First-class language citizens.


🌟 Language Features

Feature Nexa Python Rust Go
AI-native syntax (model/train) ✅ Native Library
Null safety ✅ Runtime+Static ✅ Option ✅ nil
Traits ✅ interface
Async generators
const enforcement ✅ Runtime const
Newtype pattern
Goroutine-style concurrency spawn()
Package signing (GPG)
One-command deploy ✅ 4 targets

📖 Quick Examples

💡 Basic Syntax
// Immutable by default — like Rust, friendly like Python
let name: String = "Alice"      // immutable
var counter: Int = 0            // explicitly mutable
const MAX: Int = 100            // compile + runtime constant

// F-strings with {{ literal brace escape
let msg = f"Hello, {name}! Max is {MAX}"
let template_msg = f"Brace: {{literal}}"  // → "Brace: {literal}"

// Null safety
let city = user?.address?.city ?? "Unknown"
let x: Int? = null    // ✅  nullable
let y: Int  = null    // ❌  NexaRuntimeError at runtime
🔧 Functions & Traits
def greet(name: String, greeting: String = "Hello") -> String {
    return f"{greeting}, {name}!"
}

// Lambda
let double = fn(x) => x * 2
let result = [1, 2, 3] |> map(double) |> filter(fn(x) => x > 2)

// Traits
trait Serializable {
    def to_json(self) -> String {}
}

class User(name: String, age: Int) {
    impl Serializable {
        def to_json(self) -> String {
            return f"{{\"name\":\"{self.name}\",\"age\":{self.age}}}"
        }
    }
}
🔀 Pattern Matching
import "result"

def safe_divide(a: Int, b: Int) -> Result<Float, String> {
    if b == 0 { return result.err("Division by zero") }
    return result.ok(a / b)
}

let r = safe_divide(10, 2)
match r {
    case Ok(val)  => print(f"Result: {val}")
    case Err(msg) => print(f"Error: {msg}")
}

// Error pipe — only runs on Err
r |? fn(e) => log(f"Pipeline failed: {e}")
=======
### Run your first Nexa program

```bash
echo 'print("Hello, Nexa!")' > hello.nexa
nexa run hello.nexa

Or use the REPL

nexa repl

🌟 Core Features

🔒 Immutable by Default

let name = "Nexa"   // immutable — safe
var count = 0       // explicit mutability
count += 1

🤖 AI as a First-Class Citizen

// Train an ML model with language-level keywords
model Classifier {
    layer Dense(128, activation="relu")
    layer Dense(64,  activation="relu")
    layer Dense(10,  activation="softmax")
}

let clf = new Classifier()
train clf on training_data {
    epochs    = 10
    optimizer = "adam"
    loss      = "crossentropy"
}

let output = predict clf(input_features)

🔀 Pipe Operators

// Chain transformations elegantly
let result = [1, 2, 3, 4, 5]
    |> map(fn(x) => x * 2)
    |> filter(fn(x) => x > 4)
    |> sum()
// result = 24

🎯 Pattern Matching

match response {
    case {"ok": true,  "data": d} { process(d) }
    case {"ok": false, "error": e} { log_error(e) }
    default { print("unexpected response") }
}

⚡ Async / Concurrent

async def fetch_all(urls) {
    for url in urls {
        spawn fetch(url)   // concurrent tasks
    }
}

🧪 Built-in Testing

test "addition works" {
    assert 2 + 2 == 4
}

bench "list append x1000" {
    var l = []
    for i in 0..1000 { append(l, i) }
}

Run with:

nexa test myfile.nexa
nexa bench myfile.nexa

🌐 Generics (Templates)

template Stack<T> {
    var items: List = []
    def push(item: T)  { append(items, item) }
    def pop()  -> T    { return items[len(items)-1] }
    def size() -> Int  { return len(items) }
}

let s = new Stack<Int>()
s.push(42)
s.pop()   // 42

📦 Package Manager

# Install a package
nexa pkg install nexa_http

# Search packages
nexa pkg search ai

# Publish your package
nexa pkg publish

🛠️ CLI Reference

Command Description
nexa run file.nexa Execute a Nexa script
nexa repl Start the interactive REPL
nexa test file.nexa Run all tests
nexa check file.nexa Static type checking
nexa fmt file.nexa Format code
nexa bench file.nexa Run benchmarks
nexa doc file.nexa Generate documentation
nexa pkg install <pkg> Install a package
nexa pkg publish Publish a package

📚 Documentation

Resource Description
📖 The Nexa Book Complete language reference (Ch 1–20)
⚡ Nexa by Example Quick copy-paste examples
🤖 AI Tutorial Build AI apps with Nexa
🌐 Web Tutorial REST APIs and web servers
🔐 Security Guide Nexa for cybersecurity

🏗️ Real-World Examples

🌐 REST API Server
import "http"

def handle_hello(req) {
    return {"message": f"Hello, {req.params.name}!"}
}

let app = http.server()
app.get("/hello/:name", handle_hello)
app.listen(8080)
print("Server running on http://localhost:8080")
>>>>>>> 505371e59d95447c4de1bb675f9eb2687f79f60d
<<<<<<< HEAD ⚡ Concurrency
// Goroutine-style parallel tasks
let data = spawn({
    "prices": fn() => fetch("https://api.example.com/prices"),
    "news":   fn() => fetch("https://api.example.com/news"),
})
print(data["prices"])

// Async generators
async def stream_events() {
    yield fetch("/api/event/1")
    yield fetch("/api/event/2")
}
for event in stream_events() { process(event) }

// Channels
let ch = Channel()
spawn({ "sender": fn() => { ch.send(42); ch.send(99) } })
print(ch.recv())   // → 42
🧪 Testing
test "user service" {
    let user = User("Alice", 30)
    
    // Rich matchers (v27)
    expect(user.name).to_equal("Alice")
    expect(user.age).to_be_in_range(18, 120)
    expect(user.to_json()).to_contain("Alice")
    expect(fn() => validate(null)).to_throw("NullError")
    
    // ML-specific
    expect(model.accuracy).to_be_greater_than(0.9)
</details>

<details>
<summary><b>🤖 Multi-Provider AI Agents</b></summary>
=======
<summary>🤖 <strong>AI Agent with Memory</strong></summary>
>>>>>>> 505371e59d95447c4de1bb675f9eb2687f79f60d

```nexa
import "agent"

<<<<<<< HEAD
// Chat with Anthropic, OpenAI, Groq, or local Ollama models natively
let res = agent.ask("Write a Haiku about code", model="claude-3-opus", provider="anthropic")

// Enforce strict JSON output with schema parsing
let data = agent.ask_json("Extract user details", schema={"name": "str", "age": "int"})

// Or stream tokens directly to stdout
for token in agent.stream("Explain quantum physics") {
    print(token)
=======
let bot = agent.create("groq", model="llama-3.3-70b")
var history = []

loop {
    let user_input = read("You: ")
    if user_input == "quit" { break }

    append(history, {"role": "user", "content": user_input})
    let reply = await bot.chat(history)
    print(f"Bot: {reply}")
    append(history, {"role": "assistant", "content": reply})
}
🧠 ML Classifier
// AutoML — Nexa picks the best model automatically
automl target=labels from features {
    task       = "classification"
    time_limit = 60
>>>>>>> 505371e59d95447c4de1bb675f9eb2687f79f60d
}

<<<<<<< HEAD

# Core
nexa run   main.nexa           # run a program
nexa check main.nexa           # strict type check + return checking
nexa test  test_suite.nexa     # run tests
nexa bench bench.nexa          # benchmark
nexa fmt   main.nexa           # format code
nexa shell                     # smart REPL (.history, .type, multiline)

# Build
nexa build --target llvm       # compile to native binary
nexa build-vm                  # compile C VM (5-15× speedup)

# Project
nexa new my-app --template ai|web|cli|pwa
nexa deploy --target vercel|railway|hf|fly
nexa migrate existing.py       # migrate Python → Nexa

# Packages
nexa install  nexa-http        # install from registry
nexa publish  --sign           # publish with GPG signature
nexa search   "http client"    # search registry

# Help
nexa explain "result.ok"       # context-aware docs
nexa explain error E0010       # error code guide
nexa lsp                       # language server (VS Code)

📦 Package Registry

Browse and install packages at registry.nexa-lang.dev

nexa install nexa-http         # HTTP client
nexa install nexa-env          # .env file loader
nexa install nexa-log          # structured logging
nexa install nexa-retry        # retry with backoff
nexa install nexa-color        # terminal colors

⚡ Performance

Mode Speed vs Python Command
Interpreter ~0.5× nexa run
Bytecode VM ~0.9× nexa run
C VM (native) 5–15× nexa build-vm && nexa run
LLVM native 10–50× nexa build --target llvm
# Compile the native C VM once:
nexa build-vm
# From now on, nexa run automatically uses the fast VM

=======

🗺️ Roadmap

  • Lexer, Parser, Interpreter (v1–v14)
  • Type checker (nexa check)
  • Async/await, concurrency (spawn)
  • Generics / Templates, Structs, Enums, Newtypes
  • Package manager + registry
  • LSP server (VSCode extension)
  • AI keywords (model, train, predict, automl)
  • WASM bridge
  • LLVM native compilation
  • Nexa Playground (browser IDE)
  • awesome-nexa community list
  • Official nexa-lang.org website

505371e59d95447c4de1bb675f9eb2687f79f60d


🤝 Contributing

<<<<<<< HEAD We welcome contributions! See CONTRIBUTING.md.

# Clone and set up
git clone https://github.com/nexa-lang/nexa.git
cd nexa
pip install -e .

# Run the test suite
python -m pytest tests/

# Try a Nexa file
nexa run examples/hello.nexa

Good first issues are tagged good first issue.


🌍 Community

505371e59d95447c4de1bb675f9eb2687f79f60d


📄 License

<<<<<<< HEAD MIT © Yuvaraj

Built with ❤️ for the AI era ======= Nexa is open-source under the [MIT License](LICENSE.md).

Built with ❤️ for the future of programming.

If Nexa helps you, give it a ⭐ — it helps the project grow!

Star History

505371e59d95447c4de1bb675f9eb2687f79f60d

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nexa_lang-27.0.3.tar.gz (649.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nexa_lang-27.0.3-py3-none-any.whl (749.0 kB view details)

Uploaded Python 3

File details

Details for the file nexa_lang-27.0.3.tar.gz.

File metadata

  • Download URL: nexa_lang-27.0.3.tar.gz
  • Upload date:
  • Size: 649.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for nexa_lang-27.0.3.tar.gz
Algorithm Hash digest
SHA256 f18aa0df79b11abac86f7f97e9dfbfed27652263d2bf88d6c4f3a9e8c9d71c76
MD5 8a8b13748ba255d556dfda60fb837ec2
BLAKE2b-256 7a5d67843df853dae936fdf9cba0d320487035f9683214eb657fa084bb73b0ee

See more details on using hashes here.

File details

Details for the file nexa_lang-27.0.3-py3-none-any.whl.

File metadata

  • Download URL: nexa_lang-27.0.3-py3-none-any.whl
  • Upload date:
  • Size: 749.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.12

File hashes

Hashes for nexa_lang-27.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 48e67e02c3f2c05fda86e77eabeffe21d7a84068ff0d0f06d347a780b561001f
MD5 97c6e4c8046bb77d39cc61a3f51a3586
BLAKE2b-256 d56cb6c2750745621a8fc3b470edea7efbd4e9f7d31aade960e1b71b058424c3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page