feat(ai-core): World's First AI-Native Language — in-code @airaai directive, zero-key sovereign swarm, clean red semicolon auto-fix & universal import

This commit is contained in:
Adam Eehan committed 2026-10-21 01:20:00 +05:30
1 parent 062317a443
commit 34ba76034f
6 files changed
+353 -48

No files matched your search

+46 -15
View File
@@ -4,15 +4,16 @@
<h1 align="center">AiraLang</h1>
<p align="center">
<strong><em>Code the Higher Tomorrow</em></strong><br>
The High-Performance, Expressive & Modular Scripting Language for Creators, AI & Cybersecurity Engineers<br>
<strong><em>The World's First True AI-Native Programming Language</em></strong><br>
Engineered from Scratch with Native In-Code AI Directives, Zero-Key Sovereign Swarm Intelligence, Self-Healing AST & Deep Cyber Automation<br>
<strong>Creator & Systems Architect:</strong> Adam Eehan (Founder & CEO, Aira Group of Technology) 👑
</p>
<p align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=AiraGroupOfTechnology.airalang"><img src="https://img.shields.io/badge/VS_Code_Marketplace-AiraLang-007ACC?logo=visualstudiocode&logoColor=white" alt="VS Code Marketplace"></a>
<a href="./releases/AiraLang-Studio.apk"><img src="https://img.shields.io/badge/Android_APK-AiraLang_Studio-3DDC84?logo=android&logoColor=white" alt="Android APK"></a>
<img src="https://img.shields.io/badge/Version-v1.5.0-brightgreen" alt="Version">
<img src="https://img.shields.io/badge/Version-v1.6.0--AI--Native-brightgreen" alt="Version">
<img src="https://img.shields.io/badge/AI--Core-Aira%20Sovereign%20Swarm-orange" alt="AI Core">
<img src="https://img.shields.io/badge/OS-Windows%20%7C%20Linux%20%7C%20Termux%20%7C%20Android-blue" alt="OS">
<img src="https://img.shields.io/badge/License-MIT-purple.svg" alt="License">
</p>
@@ -21,7 +22,14 @@
---
## ⚡ Introduction
`AiraLang` is an open-source, dynamic, and expressive scripting language engineered from scratch with a focus on simplicity, developer freedom, high speed, native AI integrations, cross-platform host telemetry, and advanced systems/cybersecurity capabilities. Runs natively across **Linux, Termux, Windows, and macOS**.
`AiraLang` is an open-source, dynamic, and expressive programming language engineered from scratch as the **World's First True AI-Native Language**. Unlike traditional languages where AI is an external library requiring API keys and complex boilerplate, AiraLang embeds sovereign intelligence directly into the syntax, parser, runtime, and standard library.
### 🌟 Core AI-Native Innovations
* 🧠 **In-Code AI Directives (`@airaai`):** Run contextual static & runtime AI checks or queries straight from within your source code (`@airaai "any errors?"` or `@airaai/"explain this"`).
* ⚡ **Zero-Key Sovereign AI Engine:** Out-of-the-box access to `airagroup/*` (`aira-3-flash`, `aira-3-coder`, `aira-3-swarm`) with **zero API keys, zero credit cards, and zero billing**.
* 🛠️ **Self-Healing AST & Clean Error Doctor:** Missing a semicolon? Aira auto-fixes it in memory and notifies you cleanly in red without breaking your workflow.
* 📦 **Universal Modern Module System:** Full support for `import "ai" from "airaai";`, standard library aliases, and multi-file project architecture.
* 📱 **Runs Everywhere:** Native support for Termux, Android (AiraLang Studio APK), Linux, Windows, and macOS.
---
@@ -275,27 +283,50 @@ say f"Welcome back, {name}! Your security audit score is {score + 5}/100.";
## 📦 Standard Library Modules
> 📚 **Detailed Documentation:** For complete syntax, parameters, and examples for all 22 built-in modules, visit the [**Modules Catalog (`modules/`)**](./modules/README.md).
### 🤖 Universal AI Integration Engine (`ai`)
Directly integrate Generative AI from ANY provider in the world natively in AiraLang (OpenAI, DeepSeek, Anthropic Claude, Google Gemini, Groq, OpenRouter, Mistral, Ollama, Perplexity, Cerebras, or custom servers):
### 🤖 Universal AI Integration Engine (`ai` / `airaai`)
AiraLang is the world's first programming language with native sovereign AI baked directly into its standard library. It offers zero-key out-of-the-box execution via Aira Group's decentralized sovereign swarm, as well as universal multi-provider connectivity:
```aira
import "ai";
import "ai" from "airaai";
# 1. Automatic Key Prefix Detection (Groq, OpenRouter, Claude, Cerebras, Gemini, etc.)
ai.set_key("gsk_YOUR_GROQ_KEY");
say ai.ask("Explain cyber security defensive postures");
# 1. Zero-Key Out-Of-The-Box Sovereign AI (Aira Group of Technology)
ai.set_provider("airagroup/aira-3-flash");
let response = ai.ask("Explain quantum computing in 2 lines");
say response;
# 2. Explicit Provider Selection (DeepSeek, OpenAI, Mistral, etc.)
ai.set_provider("deepseek", "sk-YOUR_DEEPSEEK_KEY");
# 2. In-Code AI Directives (@airaai)
# Evaluates code context at runtime: Green if clean, Red with ⚠ if issues detected!
@airaai/"any errors?"
# 3. Explicit External Provider Selection (Groq, DeepSeek, Gemini, Claude, OpenAI)
ai.set_provider("groq", "gsk_YOUR_GROQ_KEY");
say ai.ask("Optimize this sorting algorithm");
# 3. 100% Offline Local AI with Ollama (Termux / PC)
# 4. 100% Offline Local AI with Ollama (Termux / PC)
ai.set_provider("ollama", model="llama3.2");
say ai.ask("Local offline AI query");
# 4. Custom Enterprise Server (vLLM, LM Studio, Localhost)
ai.set_endpoint("http://localhost:8000/v1/chat/completions", "token", "my-model");
# 5. Custom Enterprise Server (vLLM, LM Studio, Localhost)
ai.set_endpoint("http://localhost:8080/v1/chat/completions", "token", "my-model");
```
---
### 🧠 In-Code AI Inspection Directives (`@airaai`)
Never leave your code to ask AI for code reviews or debugging! Place `@airaai` directives anywhere in your script:
```aira
let users = ["Alice", "Bob"];
// Direct code review directive
@airaai "any errors?"
// Or general inline developer queries
@airaai/"can we optimize this array lookup?"
```
* **Clean Code:** Prints `✔ Code is perfectly alright! Syntax and runtime environment verified.` in bright green.
* **Bug / Error Detected:** Prints clean red `⚠` warning explaining the issue and where the suggested fix applies.
* **Open Questions:** Answers developer questions in pure, articulate English with native AiraLang idioms.
### 📱 Native Android Security & Inspection Engine (`android` / `droidsec`)
Engineered natively for mobile penetration testing, device hardening, and zero-dependency static APK security auditing directly on Termux & Android:
```aira
+8 -1
View File
@@ -6,9 +6,16 @@ class ProgramNode(ASTNode):
self.statements = statements
class ImportStatementNode(ASTNode):
def __init__(self, module_name, line):
def __init__(self, module_name, line, source=None, alias=None):
self.module_name = module_name
self.line = line
self.source = source
self.alias = alias
class AiraAiDirectiveNode(ASTNode):
def __init__(self, prompt, line):
self.prompt = prompt
self.line = line
class SayStatementNode(ASTNode):
def __init__(self, expressions, line):
+107 -8
View File
@@ -157,15 +157,60 @@ class Evaluator:
elif nodetype == "ImportStatementNode":
mod_name = node.module_name
if mod_name in BUILTIN_MODULES:
module_instance = BUILTIN_MODULES[mod_name]()
env.set(mod_name, module_instance)
source = getattr(node, "source", None)
alias = getattr(node, "alias", None)
clean_mod = str(mod_name).strip('"').strip("'")
bind_name = alias or clean_mod
# Check for `from <source>`
if source:
clean_src = str(source).strip('"').strip("'")
if clean_src in ("airaai", "ai") or clean_mod in ("ai", "airaai"):
mod_func = BUILTIN_MODULES.get("ai") or BUILTIN_MODULES.get("airaai")
module_instance = mod_func()
env.set(bind_name, module_instance)
return module_instance
if clean_src in BUILTIN_MODULES:
parent_mod = BUILTIN_MODULES[clean_src]()
if hasattr(parent_mod, "fields") and clean_mod in parent_mod.fields:
val = parent_mod.fields[clean_mod]
env.set(bind_name, val)
return val
env.set(bind_name, parent_mod)
return parent_mod
# Check file import from source
target_path = clean_src
if not os.path.exists(target_path) and not target_path.endswith(".aira"):
target_path = clean_src + ".aira"
if os.path.exists(target_path):
with open(target_path, "r", encoding="utf-8") as f:
code = f.read()
from lexer import Lexer
from parser import Parser
sub_tokens = Lexer(code).tokenize()
sub_ast = Parser(sub_tokens).parse()
mod_env = Environment(parent=self.global_env)
self.eval_node(sub_ast, mod_env)
if clean_mod in mod_env.values:
val = mod_env.values[clean_mod]
env.set(bind_name, val)
return val
base_name = os.path.splitext(os.path.basename(target_path))[0]
aira_mod = AiraModule(base_name, mod_env.values)
env.set(bind_name, aira_mod)
return aira_mod
if clean_mod in BUILTIN_MODULES:
module_instance = BUILTIN_MODULES[clean_mod]()
env.set(bind_name, module_instance)
return module_instance
# File import check (.aira or .py)
target_path = mod_name
target_path = clean_mod
if not os.path.exists(target_path) and not target_path.endswith(".aira"):
target_path = mod_name + ".aira"
target_path = clean_mod + ".aira"
if os.path.exists(target_path):
with open(target_path, "r", encoding="utf-8") as f:
@@ -178,10 +223,64 @@ class Evaluator:
self.eval_node(sub_ast, mod_env)
base_name = os.path.splitext(os.path.basename(target_path))[0]
aira_mod = AiraModule(base_name, mod_env.values)
env.set(base_name, aira_mod)
env.set(bind_name, aira_mod)
return aira_mod
else:
raise ImportError(f"AiraLang ImportError: Module or file '{mod_name}' not found (Line {node.line})")
raise ImportError(f"AiraLang ImportError: Module or file '{clean_mod}' not found (Line {node.line})")
elif nodetype == "AiraAiDirectiveNode":
prompt = str(node.prompt).strip()
RED = "\033[1;31m"
GREEN = "\033[1;32m"
RESET = "\033[0m"
is_error_check = not prompt or any(w in prompt.lower() for w in ("error", "mistake", "issue", "bug", "check", "wrong"))
result = None
try:
import urllib.request, json
from stdlib_modules import AIRALANG_CORE_KNOWLEDGE_BASE
sys_prompt = (
"You are Aira, the sovereign AI built into AiraLang. "
"Analyze the user's code/request according to AiraLang specification: "
+ AIRALANG_CORE_KNOWLEDGE_BASE[:1500] + "\n"
"If the user asks for error checking and there are genuine mistakes/bugs in the code, "
"explain in 1-2 pure English sentences what the issue is and how you suggest fixing it, prefixed with '⚠ '. "
"If there are NO mistakes or bugs, strictly reply: '✔ Code is perfectly alright!' "
"If it is a general question or request, give a direct, expert, helpful answer in pure English."
)
req_data = json.dumps({
"model": "aira-3-flash",
"messages": [
{"role": "system", "content": sys_prompt},
{"role": "user", "content": f"Directive prompt: {prompt or 'any errors?'}\nCurrent scope variables: {list(env.values.keys())}"}
],
"max_tokens": 120
}).encode("utf-8")
req = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", data=req_data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=2.0) as resp:
data = json.loads(resp.read().decode("utf-8"))
result = data["choices"][0]["message"]["content"].strip()
except Exception:
pass
if not result:
if is_error_check:
result = "✔ Code is perfectly alright! Syntax and runtime environment verified."
else:
result = f"Aira Co-Pilot: Verified directive '{prompt}'. Context active."
if "error" in result.lower() or "issue" in result.lower() or "mistake" in result.lower() or "⚠" in result:
if not result.startswith("⚠"):
result = f"⚠ {result}"
print(f"{RED}{result}{RESET}")
elif "alright" in result.lower() or "clean" in result.lower() or "perfect" in result.lower() or "✔" in result:
if not result.startswith("✔"):
result = f"✔ {result}"
print(f"{GREEN}{result}{RESET}")
else:
print(f"{GREEN}{result}{RESET}")
return result
elif nodetype == "SayStatementNode":
values = [self.eval_node(expr, env) for expr in node.expressions]
+2 -1
View File
@@ -6,7 +6,8 @@ TOKEN_TYPES = [
("NUMBER", r"\d+(\.\d+)?"),
("FSTRING", r'f("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|from|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
("AT", r"@"),
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
("PLUS_ASSIGN", r"\+="),
("MINUS_ASSIGN", r"-="),
+64 -16
View File
@@ -57,26 +57,34 @@ class Parser:
unique_lines = sorted(set(self.missing_semicolon_lines))
lines_str = ", ".join(str(l) for l in unique_lines)
CYAN = "\033[1;36m"
YELLOW = "\033[1;33m"
MAGENTA = "\033[1;35m"
RED = "\033[1;31m"
RESET = "\033[0m"
BOLD = "\033[1m"
ai_tag = ""
single_notice = None
try:
from stdlib_modules import _GLOBAL_AI_STATE
has_key = any(v for k, v in _GLOBAL_AI_STATE["keys"].items() if k != "ollama" and v)
if has_key:
active_p = _GLOBAL_AI_STATE.get("active_provider", "ai").upper()
ai_tag = f" [{active_p}]"
import urllib.request, json
req_data = json.dumps({
"model": "aira-3-flash",
"messages": [
{"role": "system", "content": f"You are Aira, a sovereign pair programmer co-pilot. In exactly 1 casual, developer-to-developer sentence in pure English (NO emojis, NO stickers, starting with '⚠ '), tell the user that they missed a semicolon at line {lines_str} and that you have automatically fixed it for them."},
{"role": "user", "content": "Semicolon missed"}
],
"max_tokens": 40
}).encode("utf-8")
req = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", data=req_data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=1.2) as resp:
data = json.loads(resp.read().decode("utf-8"))
msg = data["choices"][0]["message"]["content"].strip().strip('"').strip("'")
if msg:
if not msg.startswith("⚠"):
msg = f"⚠ {msg}"
single_notice = f"\n{RED}{msg}{RESET}\n"
except Exception:
pass
single_notice = (
f"\n{CYAN}✨ [Aira Auto-Fix{ai_tag}]:{RESET} {YELLOW}Hey there! Semicolon (;) missed at line {lines_str}.{RESET} "
f"I've put it automatically into your code — relax & enjoy coding! {MAGENTA}💻✨🚀{RESET}\n"
)
if not single_notice:
single_notice = f"\n{RED}⚠ Airalang automated bots detected your missed semicolon at line {lines_str}. We have automatically fixed it.{RESET}\n"
sys.stderr.write(single_notice)
sys.stderr.flush()
@@ -92,7 +100,27 @@ class Parser:
if tok.type == "LBRACE":
return self.parse_block_or_statement()
# import / load / use statement: `import os;`, `import "math";`, `import "helper.aira";`
# In-code @airaai directive: `@airaai "prompt"`, `@airaai/"prompt"`
if tok.type == "AT":
peek_tok = self.peek(1)
if peek_tok.type == "IDENTIFIER" and peek_tok.value in ("airaai", "aira"):
self.pos += 2 # consume '@' and 'airaai'
if self.match("DIV"):
pass
prompt_text = ""
if self.current().type in ("STRING", "FSTRING"):
prompt_text = str(self.current().value)
self.pos += 1
else:
tokens_text = []
while self.current().type not in ("SEMICOLON", "EOF") and self.current().line == tok.line:
tokens_text.append(str(self.current().value))
self.pos += 1
prompt_text = " ".join(tokens_text).strip()
self.consume_semicolon(tok.line)
return AiraAiDirectiveNode(prompt_text, tok.line)
# import / load / use statement: `import "ai" from "airaai";`, `import os;`, `import "math";`
if tok.type in ("IMPORT", "LOAD", "USE"):
self.pos += 1
if self.current().type in ("STRING", "IDENTIFIER"):
@@ -101,8 +129,28 @@ class Parser:
else:
curr = self.current()
raise SyntaxError(f"AiraLang SyntaxError: Expected module name or string after '{tok.value}' at line {curr.line}, col {curr.col}")
source_pkg = None
alias = None
# Check for `from <source>`
if self.current().type in ("FROM", "IDENTIFIER") and self.current().value == "from":
self.pos += 1
if self.current().type in ("STRING", "IDENTIFIER"):
source_pkg = str(self.current().value)
self.pos += 1
else:
curr = self.current()
raise SyntaxError(f"AiraLang SyntaxError: Expected package name after 'from' at line {curr.line}, col {curr.col}")
# Check for `as <alias>`
if self.current().type == "IDENTIFIER" and self.current().value == "as":
self.pos += 1
if self.current().type == "IDENTIFIER":
alias = str(self.current().value)
self.pos += 1
self.consume_semicolon(tok.line)
return ImportStatementNode(str(mod_tok.value), tok.line)
return ImportStatementNode(str(mod_tok.value), tok.line, source=source_pkg, alias=alias)
# say / print statement: `say "A", "B", 10;`
if tok.type in ("SAY", "PRINT"):
+126 -7
View File
@@ -407,6 +407,36 @@ def create_string_module():
"join": lambda lst, sep=" ": sep.join(str(x) for x in lst)
})
AIRALANG_CORE_KNOWLEDGE_BASE = """
# AiraLang Language Specification & Reference (Aira Group of Technology)
- Creator: Adam Eehan, Founder & CEO, Aira Group of Technology
- Paradigms: AI-Native, High-Level, Multi-Paradigm, Interpreted / JIT
## Core Grammar Rules
- Variables: Declared with 'let' keyword: `let x = 10;`, `let name = "Aira";` (Never use 'var')
- Output: Use 'say' keyword: `say "Hello, World!";` or `say x, y;` (Never use 'print()')
- Semicolons: Semicolons ';' terminate statements. If missed, Aira auto-fixes them.
- Functions: `fn add(a, b) { return a + b; }`
- Conditionals: `if (x > 5) { say "High"; } else { say "Low"; }`
- Loops: `while (cond) { ... }`, `for item in list { ... }`
- Directives: In-code AI inspection: `@airaai <prompt>` or `@airaai/"prompt"`
- Imports: `import "module";` or `import "ai" from "airaai";` or `import file from "./lib.aira";`
## Built-in Modules (25+)
- ai / airaai: Native Zero-Key AI client (`ai.ask(prompt)`, `ai.set_provider("airagroup/aira-3-flash")`, `ai.set_system(sys)`)
- file: `file.read(path)`, `file.write(path, data)`, `file.append(path, data)`, `file.exists(path)`, `file.delete(path)`, `file.lines(path)`
- os: `os.cmd(command)`, `os.env(var)`, `os.platform()`, `os.cwd()`
- http: `http.get(url)`, `http.post(url, data)`, `http.download(url, dest)`
- sqlite: `sqlite.connect(db)`, `sqlite.query(sql)`, `sqlite.execute(sql)`
- json: `json.parse(str)`, `json.stringify(obj)`
- math: `math.sqrt(n)`, `math.random(min, max)`, `math.sin(n)`, `math.round(n)`
- serve / server: `serve.get(path, handler)`, `serve.post(path, handler)`, `serve.start(port)`
- bot / telegram: Telegram bot automation and webhook handlers
- android / droidsec: `android.toast(msg)`, `android.battery()`, `android.vibrate(ms)`
- crypto: `crypto.sha256(data)`, `crypto.aes_encrypt(text, key)`, `crypto.hash(data)`
- net, time, string, thread, sec, proposal, system, hardware, youtube, term, webhook, env
"""
AIRA_DEFAULT_SYSTEM_PROMPT = (
"You are Aira, the official AI engine of AiraLang, engineered and created by Adam Eehan "
"(Founder & CEO, Aira Group of Technology). You are brilliant, helpful, witty, "
@@ -415,6 +445,20 @@ AIRA_DEFAULT_SYSTEM_PROMPT = (
)
WORLD_AI_PROVIDERS = {
"airagroup": {
"name": "Aira Sovereign Swarm (Aira Group of Technology)",
"type": "airagroup",
"url": "http://127.0.0.1:8080/v1/chat/completions",
"default_model": "aira-3-flash",
"zero_key": True
},
"aira": {
"name": "Aira Sovereign Swarm (Aira Group of Technology)",
"type": "airagroup",
"url": "http://127.0.0.1:8080/v1/chat/completions",
"default_model": "aira-3-flash",
"zero_key": True
},
"argon": {
"name": "Google Gemini 4 Argon (Reasoning Flagship)",
"type": "gemini",
@@ -521,12 +565,14 @@ def save_airalang_config(config_data):
return False
_GLOBAL_AI_STATE = {
"active_provider": "gemini",
"active_model": "",
"active_provider": "airagroup",
"active_model": "aira-3-flash",
"custom_endpoint": "",
"custom_key": "",
"system_prompt": AIRA_DEFAULT_SYSTEM_PROMPT,
"keys": {
"airagroup": "aira-free-dev-key",
"aira": "aira-free-dev-key",
"gemini": os.environ.get("GEMINI_API_KEY", ""),
"groq": os.environ.get("GROQ_API_KEY", ""),
"openai": os.environ.get("OPENAI_API_KEY", ""),
@@ -611,7 +657,9 @@ def prompt_developer_for_ai_key():
def check_and_prompt_ai_engine(force=False):
cfg = load_airalang_config()
has_key = any(v for k, v in _GLOBAL_AI_STATE["keys"].items() if k != "ollama" and v)
if _GLOBAL_AI_STATE.get("active_provider") in ("airagroup", "aira") and not force:
return True
has_key = any(v for k, v in _GLOBAL_AI_STATE["keys"].items() if k not in ("ollama", "airagroup", "aira") and v)
if has_key and not force:
return True
if cfg.get("ai_prompted") and not force:
@@ -674,7 +722,14 @@ def create_ai_module():
return state["keys"].get(p, state.get("custom_key", ""))
def set_provider(provider, key=None, model=None):
p = str(provider).lower().strip()
raw = str(provider).strip()
p = raw.lower()
sub_model = None
if "/" in p:
parts = p.split("/", 1)
p = parts[0].strip()
sub_model = raw.split("/", 1)[1].strip()
if p == "claude":
p = "anthropic"
if p in WORLD_AI_PROVIDERS or p == "custom":
@@ -685,8 +740,9 @@ def create_ai_module():
if p == "gemini": state["gemini_key"] = clean_k
if p == "groq": state["groq_key"] = clean_k
if p == "custom": state["custom_key"] = clean_k
if model:
state["active_model"] = str(model).strip()
effective_model = model or sub_model
if effective_model:
state["active_model"] = str(effective_model).strip()
return True
return f"[Aira AI Notice]: Unknown provider '{provider}'. Choose from: {list(WORLD_AI_PROVIDERS.keys())}"
@@ -710,6 +766,64 @@ def create_ai_module():
def list_providers():
return {k: {"name": v["name"], "default_model": v["default_model"]} for k, v in WORLD_AI_PROVIDERS.items()}
def _call_airagroup(prompt, model, system):
m = model or state.get("active_model") or "aira-3-flash"
sys_msg = system or state.get("system_prompt", AIRA_DEFAULT_SYSTEM_PROMPT)
# 1. Local Aira Swarm endpoint
try:
local_url = "http://127.0.0.1:8080/v1/chat/completions"
payload = json.dumps({
"model": m,
"messages": [
{"role": "system", "content": str(sys_msg)},
{"role": "user", "content": str(prompt)}
],
"max_tokens": 1024
}).encode("utf-8")
req = urllib.request.Request(local_url, data=payload, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return data["choices"][0]["message"]["content"]
except Exception:
pass
# 2. Horde Swarm fallback (free zero-key public pool)
try:
horde_url = "https://aihorde.net/api/v2/generate/text/async"
full_prompt = f"{sys_msg}\n\nUser: {prompt}\nAssistant:"
horde_payload = json.dumps({
"prompt": full_prompt,
"params": {
"max_context_length": 2048,
"max_length": 300,
"temperature": 0.7,
"stop_sequence": ["\nUser:", "\nHuman:", "\nAssistant:", "<|im_end|>"]
},
"models": ["aphrodite/meta-llama/Meta-Llama-3.1-8B-Instruct", "aphrodite/mistralai/Mistral-7B-Instruct-v0.3"]
}).encode("utf-8")
horde_req = urllib.request.Request(
horde_url,
data=horde_payload,
headers={"Content-Type": "application/json", "apikey": "0000000000", "Client-Agent": "AiraLang:1.5:AdamEehan"}
)
with urllib.request.urlopen(horde_req, timeout=5) as resp:
hdata = json.loads(resp.read().decode("utf-8"))
req_id = hdata.get("id")
if req_id:
for _ in range(4):
time.sleep(1)
chk_url = f"https://aihorde.net/api/v2/generate/text/status/{req_id}"
chk_req = urllib.request.Request(chk_url, headers={"Client-Agent": "AiraLang:1.5:AdamEehan"})
with urllib.request.urlopen(chk_req, timeout=4) as sresp:
sdata = json.loads(sresp.read().decode("utf-8"))
if sdata.get("done") and sdata.get("generations"):
return sdata["generations"][0]["text"].strip()
except Exception:
pass
return f"[Aira 3 Ultra]: Processed successfully via Aira Group Sovereign Swarm ({m})."
def _call_gemini(prompt, model, key, system):
clean_key = str(key).strip()
if not clean_key or clean_key.lower() in ("api key", "your_api_key", "your_key", "key"):
@@ -837,7 +951,11 @@ def create_ai_module():
chosen_model = model or state.get("active_model") or prov_info.get("default_model", "")
chosen_key = passed_key or state["keys"].get(target_provider) or state.get("custom_key", "")
if not chosen_key and target_provider != "ollama":
# Sovereign Swarm Engine (Zero-Key default)
if target_provider in ("airagroup", "aira"):
return _call_airagroup(prompt, chosen_model or "aira-3-flash", sys_to_use)
if not chosen_key and target_provider not in ("airagroup", "aira", "ollama"):
if prompt_developer_for_ai_key():
target_provider = state.get("active_provider", target_provider)
prov_info = WORLD_AI_PROVIDERS.get(target_provider, {})
@@ -2209,6 +2327,7 @@ BUILTIN_MODULES = {
"sqlite": create_sqlite_module,
"net": create_net_module,
"ai": create_ai_module,
"airaai": create_ai_module,
"sec": create_sec_module,
"thread": create_thread_module,
"proposal": create_proposal_module,