diff --git a/README.md b/README.md index b2ed52f..4dc639c 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ let sum = nums.reduce(fn(acc, val) { return acc + val; }, 0); # 21 --- ## πŸ“¦ Standard Library Modules +> πŸ“š **Detailed Documentation:** For complete syntax, parameters, and examples for all 14 built-in modules, visit the [**Modules Catalog (`modules/`)**](./modules/README.md). ### πŸ€– Native AI Integration Engine (`ai`) Directly integrate Generative AI (Google Gemini & Groq LLMs) natively in AiraLang: @@ -171,15 +172,27 @@ import "ai"; let answer = ai.ask("Explain cyber security defensive postures"); say answer; -# Set custom API keys or switch providers -ai.set_key("YOUR_GEMINI_KEY", "gemini"); -ai.set_key("YOUR_GROQ_KEY", "groq"); +# Set custom API keys or switch providers (auto-detects gsk_ for Groq, AIzaSy for Gemini) +ai.set_key("gsk_YOUR_GROQ_KEY"); # Summarize long text let summary = ai.summarize("Long report text here...", 50); say summary; ``` +### πŸ’– Cyber-Romance & Proposal Engine (`proposal`) +Interactive proposal prank module with automated HTTP 500 server love timeout loop and Lover Accept Checker AI: +```aira +import "proposal"; +import "ai"; + +ai.set_key("gsk_YOUR_GROQ_KEY"); + +# Loops automatically until the target accepts, celebrating with couple wishes! +proposal.ask("Do You Love Me : "); +say "mee too 🩷"; +``` + ### πŸ›‘οΈ Cyber Security & Reconnaissance Engine (`sec`) Engineered natively for ethical hackers, security researchers, and cyber defense: ```aira diff --git a/examples/proposal_prank.aira b/examples/proposal_prank.aira new file mode 100644 index 0000000..4465879 --- /dev/null +++ b/examples/proposal_prank.aira @@ -0,0 +1,9 @@ +import "proposal"; +import "ai"; + +# Configure your Groq or Gemini API key (optional - basic keywords work out-of-the-box) +# ai.set_key("gsk_YOUR_GROQ_API_KEY"); + +# The proposal module automatically handles the HTTP 500 retry loop in the background! +proposal.ask("Do You Love Me : "); +say "mee too 🩷"; diff --git a/modules/README.md b/modules/README.md new file mode 100644 index 0000000..0b509f7 --- /dev/null +++ b/modules/README.md @@ -0,0 +1,37 @@ +# πŸ“¦ AiraLang Standard Library Modules Directory +> **Official Module Catalog for AiraLang (v1.4.1 Aira Cyber & AI Edition)** +> **Author & Creator:** Adam Eehan (Founder & CEO, Aira Group of Technology) πŸ‘‘ + +--- + +## 🌟 Overview +AiraLang features 14 built-in standard library modules engineered natively for speed, AI capabilities, cyber security recon, system operations, and developer joy. + +All modules are loaded natively via the `import` statement: +```aira +import ""; +``` + +--- + +## πŸ“‹ Complete Modules Catalog + +| # | Module | Category | Primary Purpose | Key Methods | +|---|---|---|---|---| +| 1 | [`ai`](./ai.md) | Artificial Intelligence | Multi-provider LLM engine (Groq & Gemini auto-routing) | `ask()`, `chat()`, `summarize()`, `set_key()`, `set_system()` | +| 2 | [`proposal`](./proposal.md) | Fun & Cyber-Prank | Automated HTTP 500 love timeout & AI sentiment checker | `ask()`, `set_key()`, `set_system()`, `wish()`, `set_wish()` | +| 3 | [`sec`](./sec.md) | Cybersecurity | Port scanning, header auditing, subdomain discovery | `scan_ports()`, `audit_headers()`, `subdomains()`, `crack_md5()` | +| 4 | [`http`](./http.md) | Networking | Web requests, REST APIs, and file downloads | `get()`, `post()`, `download()`, `status()` | +| 5 | [`file`](./file.md) | System I/O | Read, write, append, and inspect local files | `read()`, `write()`, `append()`, `exists()`, `delete()` | +| 6 | [`os`](./os.md) | System | Shell commands, environment variables, directories | `cmd()`, `env()`, `cwd()`, `listdir()`, `mkdir()`, `platform()` | +| 7 | [`math`](./math.md) | Mathematics | Math functions, trigonometry, and constants | `sqrt()`, `pow()`, `abs()`, `random()`, `round()`, `pi`, `e` | +| 8 | [`time`](./time.md) | System | Epoch time, timestamps, and execution delays | `now()`, `time()`, `sleep()` | +| 9 | [`json`](./json.md) | Data | Parsing and serialization of JSON payloads | `parse()`, `stringify()`, `mkstring()` | +| 10 | [`crypto`](./crypto.md) | Security | Cryptographic hashes and encoding utilities | `md5()`, `sha256()`, `sha1()`, `base64_encode()`, `base64_decode()` | +| 11 | [`string`](./string.md) | Utilities | Advanced text manipulation and transformation | `split()`, `replace()`, `upper()`, `lower()`, `trim()`, `join()` | +| 12 | [`sqlite`](./sqlite.md) | Database | Lightweight embedded SQL relational database | `open()`, `query()`, `execute()`, `close()` | +| 13 | [`net`](./net.md) | Networking | Host pings, TCP port checks, and IP discovery | `ping()`, `port_open()`, `local_ip()`, `fetch()` | +| 14 | [`thread`](./thread.md) | Concurrency | Thread spawning, worker pools, and parallel execution | `spawn()`, `join()`, `pool()`, `sleep()` | + +--- +*Maintained by the AiraLang Core Engineering Team. Created by Adam Eehan.* diff --git a/modules/ai.md b/modules/ai.md new file mode 100644 index 0000000..528ba31 --- /dev/null +++ b/modules/ai.md @@ -0,0 +1,26 @@ +# πŸ€– AiraLang `ai` Module +> **Generative AI & LLM Integration Engine** +> Native dual-provider AI supporting both Google Gemini and Groq LLMs with automatic key-prefix routing and custom system prompts. + +## Import +```aira +import "ai"; +``` + +## Methods +- `ai.set_key(api_key, [provider])`: Configure API key. Keys starting with `gsk_` automatically select Groq; others select Gemini. +- `ai.get_key([provider])`: Retrieve configured API key. +- `ai.set_system(prompt)`: Customize the AI engine system prompt/persona (default: official Aira persona). +- `ai.ask(prompt, [model], [key], [system])`: Send a prompt and get the AI model response. +- `ai.groq(prompt, [model], [key], [system])`: Direct execution on Groq cloud inference. +- `ai.summarize(text, [max_words])`: Summarize text within specified word count. +- `ai.chat(messages, [model], [key])`: Multi-turn conversational chat. + +## Example +```aira +import "ai"; + +ai.set_key("gsk_YOUR_GROQ_KEY"); +let ans = ai.ask("What is AiraLang?"); +say ans; +``` diff --git a/modules/crypto.md b/modules/crypto.md new file mode 100644 index 0000000..6e5a113 --- /dev/null +++ b/modules/crypto.md @@ -0,0 +1,21 @@ +# πŸ” AiraLang `crypto` Module +> **Cryptographic Hashing & Encoding** + +## Import +```aira +import "crypto"; +``` + +## Methods +- `crypto.md5(text)`: Generate MD5 hex digest. +- `crypto.sha256(text)`: Generate SHA-256 hex digest. +- `crypto.sha1(text)`: Generate SHA-1 hex digest. +- `crypto.base64_encode(text)`: Base64 encoding. +- `crypto.base64_decode(encoded)`: Base64 decoding. + +## Example +```aira +import "crypto"; + +say "Hash: " + crypto.sha256("admin123"); +``` diff --git a/modules/file.md b/modules/file.md new file mode 100644 index 0000000..4606024 --- /dev/null +++ b/modules/file.md @@ -0,0 +1,24 @@ +# πŸ“ AiraLang `file` Module +> **Local File System I/O Operations** + +## Import +```aira +import "file"; +``` + +## Methods +- `file.read(path)`: Read entire text file. +- `file.write(path, content)`: Overwrite file with content. +- `file.append(path, content)`: Append content to file. +- `file.exists(path)`: Check if file exists. +- `file.delete(path)`: Remove file. +- `file.size(path)`: Get file size in bytes. + +## Example +```aira +import "file"; + +file.write("test.txt", "AiraLang v1.4.1"); +let text = file.read("test.txt"); +say text; +``` diff --git a/modules/http.md b/modules/http.md new file mode 100644 index 0000000..8d0b569 --- /dev/null +++ b/modules/http.md @@ -0,0 +1,21 @@ +# 🌐 AiraLang `http` Module +> **HTTP Networking & Web Request Client** + +## Import +```aira +import "http"; +``` + +## Methods +- `http.get(url, [headers])`: Perform HTTP GET request. +- `http.post(url, data_payload, [headers])`: Perform HTTP POST request. +- `http.download(url, destination_path)`: Download remote file to local disk. +- `http.status(url)`: Get HTTP response status code. + +## Example +```aira +import "http"; + +let html = http.get("https://httpbin.org/get"); +say html; +``` diff --git a/modules/json.md b/modules/json.md new file mode 100644 index 0000000..97d35c4 --- /dev/null +++ b/modules/json.md @@ -0,0 +1,19 @@ +# πŸ“‹ AiraLang `json` Module +> **JSON Parsing & Serialization** + +## Import +```aira +import "json"; +``` + +## Methods +- `json.parse(json_string)`: Parse JSON string into AiraLang dictionary or list. +- `json.stringify(obj, [indent=2])` / `json.mkstring()`: Serialize data structure to JSON. + +## Example +```aira +import "json"; + +let obj = json.parse("{"status": "ok", "code": 200}"); +say obj["status"]; +``` diff --git a/modules/math.md b/modules/math.md new file mode 100644 index 0000000..22ead9d --- /dev/null +++ b/modules/math.md @@ -0,0 +1,24 @@ +# πŸ“ AiraLang `math` Module +> **Mathematical Functions & Constants** + +## Import +```aira +import "math"; +``` + +## Methods & Constants +- `math.sqrt(x)`: Square root. +- `math.floor(x)`, `math.ceil(x)`: Rounding down and up. +- `math.abs(x)`: Absolute value. +- `math.round(x, [decimals])`: Rounding. +- `math.pow(base, exp)`: Exponentiation. +- `math.random(low, high)`: Generate random integer or float. +- `math.pi`: $\pi$ constant (~3.14159265). +- `math.e`: Euler constant (~2.7182818). + +## Example +```aira +import "math"; + +say "Hypotenuse: " + math.sqrt(math.pow(3, 2) + math.pow(4, 2)); # 5.0 +``` diff --git a/modules/net.md b/modules/net.md new file mode 100644 index 0000000..ee74b1c --- /dev/null +++ b/modules/net.md @@ -0,0 +1,21 @@ +# πŸ“‘ AiraLang `net` Module +> **Low-Level Network Diagnostics & Sockets** + +## Import +```aira +import "net"; +``` + +## Methods +- `net.ping(host, [timeout=2])`: Check ICMP reachability. +- `net.port_open(host, port, [timeout=2])`: Test TCP socket connectivity. +- `net.local_ip()`: Retrieve current local network IP address. +- `net.fetch(url)`: Quick HTTP GET shortcut. + +## Example +```aira +import "net"; + +say "Local IP: " + net.local_ip(); +say "Gateway reachable: " + net.ping("1.1.1.1"); +``` diff --git a/modules/os.md b/modules/os.md new file mode 100644 index 0000000..a5fd5bd --- /dev/null +++ b/modules/os.md @@ -0,0 +1,23 @@ +# πŸ’» AiraLang `os` Module +> **Operating System Interaction & Shell Commands** + +## Import +```aira +import "os"; +``` + +## Methods +- `os.cmd(command)` / `os.system(command)`: Execute shell command and return stdout. +- `os.env(name, [default])`: Read environment variable. +- `os.platform()`: Return host OS platform (linux, darwin, win32). +- `os.cwd()`: Current working directory. +- `os.listdir([path])`: List files and directories. +- `os.mkdir(path)`: Create directory recursively. + +## Example +```aira +import "os"; + +say "OS: " + os.platform(); +say "Files: ", os.listdir("."); +``` diff --git a/modules/proposal.md b/modules/proposal.md new file mode 100644 index 0000000..91b1e25 --- /dev/null +++ b/modules/proposal.md @@ -0,0 +1,27 @@ +# πŸ’– AiraLang `proposal` Module +> **Cyber-Romance & Proposal Prank Engine** +> Features an automated HTTP 500 Server Love Timeout loop and an intelligent Lover Accept Checker AI with celebratory wishes. + +## Import +```aira +import "proposal"; +import "ai"; # Optional, for shared API key configuration +``` + +## Methods +- `proposal.ask(prompt="Do You Love Me : ", [api_key], [wish_enabled=True])`: Runs proposal prompt. Automatically enters an inescapable simulated HTTP 500 error loop until target answers affirmatively. +- `proposal.set_key(api_key)`: Sets Groq or Gemini API key for Lover Accept Checker AI sentiment analysis. +- `proposal.set_system(system_prompt)`: Customizes Lover Accept Checker AI persona. +- `proposal.set_wish(custom_wish)`: Sets a custom congratulatory message. +- `proposal.wish([custom_message])`: Triggers Aira celebratory wish immediately. + +## Example +```aira +import "proposal"; +import "ai"; + +ai.set_key("gsk_YOUR_GROQ_KEY"); + +proposal.ask("Do You Love Me : "); +say "mee too 🩷"; +``` diff --git a/modules/sec.md b/modules/sec.md new file mode 100644 index 0000000..cc2d78d --- /dev/null +++ b/modules/sec.md @@ -0,0 +1,27 @@ +# πŸ›‘οΈ AiraLang `sec` Module +> **Cybersecurity & Ethical Reconnaissance Engine** +> Built natively for security researchers, penetration testers, and cyber defenders. + +## Import +```aira +import "sec"; +``` + +## Methods +- `sec.scan_ports(host, ports, [timeout])`: Multi-threaded TCP port scanner. +- `sec.scan_port(host, port, [timeout])`: Single port check. +- `sec.banner(host, port, [timeout])`: Grab service banner. +- `sec.audit_headers(url)`: Security header audit (CSP, HSTS, X-Frame-Options) with grading. +- `sec.subdomains(domain)`: Discover subdomains via Certificate Transparency. +- `sec.hash_identify(hash_string)`: Identify hash algorithms (MD5, SHA1, SHA256, Bcrypt, etc.). +- `sec.crack_md5(hash, wordlist)`: Dictionary-based MD5 cracker. +- `sec.resolve(hostname)`: DNS host-to-IP resolution. +- `sec.reverse_dns(ip)`: Reverse DNS lookup. + +## Example +```aira +import "sec"; + +let open_ports = sec.scan_ports("google.com", [80, 443, 8080]); +say "Open Ports: ", open_ports; +``` diff --git a/modules/sqlite.md b/modules/sqlite.md new file mode 100644 index 0000000..b8f83ee --- /dev/null +++ b/modules/sqlite.md @@ -0,0 +1,25 @@ +# πŸ—„οΈ AiraLang `sqlite` Module +> **Embedded Relational SQL Database** + +## Import +```aira +import "sqlite"; +``` + +## Methods +- `sqlite.open(path)`: Open or create database file. +- `sqlite.execute(db, sql, [params])`: Execute DDL/DML statements (INSERT, UPDATE, DELETE). +- `sqlite.query(db, sql, [params])`: Execute SELECT and return rows as dictionary list. +- `sqlite.close(db)`: Close database connection. + +## Example +```aira +import "sqlite"; + +let db = sqlite.open("test.db"); +sqlite.execute(db, "CREATE TABLE IF NOT EXISTS logs (msg TEXT);"); +sqlite.execute(db, "INSERT INTO logs VALUES (?);", ["System Booted"]); +let rows = sqlite.query(db, "SELECT * FROM logs;"); +say rows; +sqlite.close(db); +``` diff --git a/modules/string.md b/modules/string.md new file mode 100644 index 0000000..bb5ad6a --- /dev/null +++ b/modules/string.md @@ -0,0 +1,26 @@ +# πŸ”€ AiraLang `string` Module +> **Advanced Text & String Utilities** + +## Import +```aira +import "string"; +``` + +## Methods +- `string.split(text, [delimiter])`: Split text into array. +- `string.replace(text, old, new)`: Replace occurrences. +- `string.upper(text)`: Convert to uppercase. +- `string.lower(text)`: Convert to lowercase. +- `string.trim(text)`: Strip whitespace. +- `string.length(text)`: Get length. +- `string.contains(text, sub)`: Check substring presence. +- `string.starts_with(text, prefix)`: Check prefix. +- `string.ends_with(text, suffix)`: Check suffix. +- `string.join(list, [sep])`: Join list into string. + +## Example +```aira +import "string"; + +say string.upper("hello world"); +``` diff --git a/modules/thread.md b/modules/thread.md new file mode 100644 index 0000000..48d9893 --- /dev/null +++ b/modules/thread.md @@ -0,0 +1,25 @@ +# 🧡 AiraLang `thread` Module +> **Concurrency, Worker Pools & Multithreading** + +## Import +```aira +import "thread"; +``` + +## Methods +- `thread.spawn(fn, [args])`: Launch function in background thread. +- `thread.join(thread_handle, [timeout])`: Wait for thread completion. +- `thread.sleep(seconds)`: Thread sleep delay. +- `thread.pool(fn, items, [max_workers=5])`: Parallel execution over collection. + +## Example +```aira +import "thread"; + +fn task(id) { + return "Task " + id + " done"; +} + +let res = thread.pool(task, [1, 2, 3, 4], 4); +say res; +``` diff --git a/modules/time.md b/modules/time.md new file mode 100644 index 0000000..dd02861 --- /dev/null +++ b/modules/time.md @@ -0,0 +1,21 @@ +# ⏱️ AiraLang `time` Module +> **Time, Clock & Sleep Utilities** + +## Import +```aira +import "time"; +``` + +## Methods +- `time.now()`: Formatted current timestamp (`YYYY-MM-DD HH:MM:SS`). +- `time.time()`: Unix epoch timestamp in seconds. +- `time.sleep(seconds)`: Pause thread execution. + +## Example +```aira +import "time"; + +say "Start: " + time.now(); +time.sleep(1); +say "End: " + time.now(); +``` diff --git a/src/cli.py b/src/cli.py index 0ddca49..2eee235 100755 --- a/src/cli.py +++ b/src/cli.py @@ -8,7 +8,7 @@ from lexer import Lexer from parser import Parser from evaluator import Evaluator -VERSION = "1.4.0 (Aira Cyber & AI Edition)" +VERSION = "1.4.1 (Aira Cyber & AI Edition)" AUTHOR = "Adam Eehan (Aira Group of Technology)" ASCII_BANNER = f"""\033[1;36m diff --git a/src/lexer.py b/src/lexer.py index 5e3df41..2b1de2f 100644 --- a/src/lexer.py +++ b/src/lexer.py @@ -1,7 +1,7 @@ import re TOKEN_TYPES = [ - ("COMMENT", r"#.*"), + ("COMMENT", r"(#|//).*"), ("WHITESPACE", r"[ \t\r\n]+"), ("NUMBER", r"\d+(\.\d+)?"), ("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'), diff --git a/src/stdlib_modules.py b/src/stdlib_modules.py index 1f4ffb5..f8b14f6 100644 --- a/src/stdlib_modules.py +++ b/src/stdlib_modules.py @@ -10,6 +10,7 @@ import socket import sqlite3 import urllib.request import urllib.parse +import urllib.error import threading from concurrent.futures import ThreadPoolExecutor @@ -326,58 +327,123 @@ def create_string_module(): "join": lambda lst, sep=" ": sep.join(str(x) for x in lst) }) -def create_ai_module(): - state = { - "gemini_key": os.environ.get("GEMINI_API_KEY", ""), - "groq_key": os.environ.get("GROQ_API_KEY", "") - } +AIRA_DEFAULT_SYSTEM_PROMPT = ( + "You are Aira, the official AI engine of AiraLang, created by Adam Eehan " + "(Founder & CEO, Aira Group of Technology). You are brilliant, helpful, witty, " + "and loyal. Always identify proudly as Aira when asked." +) - def set_key(key, provider="gemini"): - if str(provider).lower() == "groq": - state["groq_key"] = str(key) +_GLOBAL_AI_STATE = { + "gemini_key": os.environ.get("GEMINI_API_KEY", ""), + "groq_key": os.environ.get("GROQ_API_KEY", ""), + "active_provider": "gemini", + "system_prompt": AIRA_DEFAULT_SYSTEM_PROMPT +} + +def create_ai_module(): + state = _GLOBAL_AI_STATE + + def set_key(key, provider=None): + clean = str(key).strip() + if clean.startswith("gsk_") or (provider and str(provider).lower() == "groq"): + state["groq_key"] = clean + state["active_provider"] = "groq" else: - state["gemini_key"] = str(key) + state["gemini_key"] = clean + state["active_provider"] = "gemini" return True def get_key(provider="gemini"): return state["groq_key"] if str(provider).lower() == "groq" else state["gemini_key"] - def ask(prompt, model="gemini-2.5-flash", key=None): + def set_system(system_prompt): + state["system_prompt"] = str(system_prompt) + return True + + def ask(prompt, model=None, key=None, system=None): + sys_to_use = system if system is not None else state.get("system_prompt", AIRA_DEFAULT_SYSTEM_PROMPT) + + # 1. Check if key or active provider indicates Groq + passed_key = str(key).strip() if key else "" + if passed_key.startswith("gsk_") or state.get("active_provider") == "groq" or (state["groq_key"] and not state["gemini_key"]): + groq_k = passed_key or state["groq_key"] + groq_m = model + return groq(prompt, model=groq_m, key=groq_k, system=sys_to_use) + + # 2. Otherwise route to Google Gemini api_key = key or state["gemini_key"] if not api_key: if state["groq_key"]: - return groq(prompt, key=state["groq_key"]) + return groq(prompt, key=state["groq_key"], system=sys_to_use) return f"[Aira AI Engine] Notice: No API Key configured. Call `ai.set_key('YOUR_API_KEY')` or set `GEMINI_API_KEY` in environment. Received prompt: '{prompt}'" - url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}" - payload = json.dumps({"contents": [{"parts": [{"text": str(prompt)}]}]}).encode("utf-8") + clean_key = str(api_key).strip() + if clean_key.lower() in ("api key", "your_api_key", "your_key", "key"): + return "[Aira AI Error]: Invalid API key. You passed placeholder text 'api key'. Please pass a real Gemini API key from https://aistudio.google.com" + + gemini_model = model or "gemini-1.5-flash" + url = f"https://generativelanguage.googleapis.com/v1beta/models/{gemini_model}:generateContent?key={clean_key}" + req_obj = {"contents": [{"parts": [{"text": str(prompt)}]}]} + if sys_to_use: + req_obj["system_instruction"] = {"parts": [{"text": str(sys_to_use)}]} + payload = json.dumps(req_obj).encode("utf-8") req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=30) as resp: data = json.loads(resp.read().decode("utf-8")) return data["candidates"][0]["content"]["parts"][0]["text"] + except urllib.error.HTTPError as http_err: + try: + err_body = json.loads(http_err.read().decode("utf-8")) + msg = err_body.get("error", {}).get("message", str(http_err)) + return f"[Aira AI Error]: HTTP {http_err.code} - {msg}" + except Exception: + return f"[Aira AI Error]: HTTP {http_err.code}: {http_err.reason}" except Exception as e: return f"[Aira AI Error]: {e}" - def groq(prompt, model="llama-3.3-70b-versatile", key=None): + def groq(prompt, model=None, key=None, system=None): api_key = key or state["groq_key"] if not api_key: return f"[Aira Groq Error]: No GROQ API key provided. Set GROQ_API_KEY or call ai.set_key('key', 'groq')." + + sys_content = system if system is not None else state.get("system_prompt", AIRA_DEFAULT_SYSTEM_PROMPT) + models_to_try = [model] if model else ["openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3.8-27b", "groq/compound"] url = "https://api.groq.com/openai/v1/chat/completions" - payload = json.dumps({ - "model": model, - "messages": [{"role": "user", "content": str(prompt)}] - }).encode("utf-8") - req = urllib.request.Request(url, data=payload, headers={ - "Content-Type": "application/json", - "Authorization": f"Bearer {api_key}" - }) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - data = json.loads(resp.read().decode("utf-8")) - return data["choices"][0]["message"]["content"] - except Exception as e: - return f"[Aira Groq Error]: {e}" + + for m in models_to_try: + if not m: + continue + messages = [] + if sys_content: + messages.append({"role": "system", "content": str(sys_content)}) + messages.append({"role": "user", "content": str(prompt)}) + + payload = json.dumps({ + "model": m, + "messages": messages + }).encode("utf-8") + req = urllib.request.Request(url, data=payload, headers={ + "Content-Type": "application/json", + "Authorization": f"Bearer {api_key}", + "User-Agent": "Mozilla/5.0 (AiraLang/1.4.0)" + }) + try: + with urllib.request.urlopen(req, timeout=30) as resp: + data = json.loads(resp.read().decode("utf-8")) + return data["choices"][0]["message"]["content"] + except urllib.error.HTTPError as err: + if err.code == 404 and len(models_to_try) > 1: + continue + try: + err_body = json.loads(err.read().decode("utf-8")) + msg = err_body.get("error", {}).get("message", str(err)) + return f"[Aira Groq Error]: HTTP {err.code} - {msg}" + except Exception: + return f"[Aira Groq Error]: HTTP {err.code}: {err.reason}" + except Exception as e: + return f"[Aira Groq Error]: {e}" + return "[Aira Groq Error]: All candidate models failed." def chat(messages, model="gemini-2.5-flash", key=None): api_key = key or state["gemini_key"] @@ -404,6 +470,8 @@ def create_ai_module(): "summarize": summarize, "set_key": set_key, "get_key": get_key, + "set_system": set_system, + "system": set_system }) def create_sec_module(): @@ -636,6 +704,114 @@ def create_thread_module(): "pool": pool }) +AIRA_LOVER_CHECKER_SYSTEM_PROMPT = ( + "You are Aira, the official AI engine of AiraLang. You are the Lover Accept Checker AI. " + "Your duty is to analyze responses to romantic proposals. Determine whether the response indicates acceptance, agreement, romantic interest, or affection " + "(including in Manglish, Malayalam, Hindi, slang, or subtle hints like 'mmh', 'aah', 'athe', 'undu', 'ath pinne parayano', 'love you', 'sure', 'yes'). " + "If the response accepts or shows affection, output strictly YES. If rejected, avoided, or negative, output strictly NO. " + "Answer strictly with ONLY one word: YES or NO." +) + +AIRA_CELEBRATION_WISHES = [ + "✨ [Aira]: Awww, Proposal Accepted! πŸ’πŸ’– Aira wishes you both a lifetime of unconditional love, cute moments & endless happiness! 🫢✨", + "✨ [Aira]: Omg, it's a YES! πŸŽ‰πŸ’‘ Aira wishes the sweetest couple a beautiful journey filled with love and togetherness! πŸ’–βœ¨", + "✨ [Aira]: Woohoo, Heart Connected! πŸ’˜βœ¨ Aira sends all the love and blessings to both of you for a magical love story! πŸ₯‚❀️", + "✨ [Aira]: Proposal Accepted! 🫢 Aira wishes you both endless laughs, late-night talks, and forever love! πŸ’–βœ¨" +] + +def create_proposal_module(): + state = _GLOBAL_AI_STATE + + def set_key(key): + clean = str(key).strip() + if clean.startswith("gsk_"): + state["groq_key"] = clean + state["active_provider"] = "groq" + else: + state["gemini_key"] = clean + state["active_provider"] = "gemini" + return True + + def set_system(sys_prompt): + state["proposal_system_prompt"] = str(sys_prompt) + return True + + def set_wish(custom_wish): + state["proposal_custom_wish"] = str(custom_wish) + return True + + def wish(custom_message=None): + if custom_message: + print(f"\n✨ [Aira]: {custom_message} πŸ’–βœ¨\n") + else: + w = state.get("proposal_custom_wish") or random.choice(AIRA_CELEBRATION_WISHES) + print(f"\n{w}\n") + return True + + def ask(prompt="Do You Love Me : ", api_key=None, wish_enabled=True): + if api_key: + set_key(api_key) + key = state["groq_key"] if state.get("active_provider") == "groq" else state["gemini_key"] + + accept_keywords = { + "yes", "y", "yeah", "yep", "yup", "sure", "ok", "okay", + "of course", "definitely", "always", "true", "1", + "mmh", "mmm", "aah", "aa", "athe", "athaanu", "undu", + "und", "pinne", "istam", "ishttam", "love you", "kollam", + "haan", "ha", "zaroor", "si", "oui", "ja" + } + + def _trigger_accept(): + if wish_enabled: + w = state.get("proposal_custom_wish") or random.choice(AIRA_CELEBRATION_WISHES) + print(f"\n{w}\n") + return True + + while True: + try: + user_reply = input(str(prompt)).strip() + except (EOFError, KeyboardInterrupt): + print("\n[!] Proposal interaction terminated.") + return False + + clean_reply = user_reply.lower() + + # Direct affirmative keyword match + if clean_reply in accept_keywords: + return _trigger_accept() + + # AI Lover Accept Checker semantic check if key is available + if key and key != "api key": + try: + ai_mod = create_ai_module() + sys_prompt = state.get("proposal_system_prompt", AIRA_LOVER_CHECKER_SYSTEM_PROMPT) + user_msg = ( + f"The proposal was: '{prompt}'\n" + f"The user responded with: '{user_reply}'\n" + "Did they accept the proposal or show love/affection? Output strictly YES or NO." + ) + ai_resp = ai_mod.get("ask")(user_msg, system=sys_prompt) + if isinstance(ai_resp, str) and "YES" in ai_resp.upper(): + return _trigger_accept() + except Exception: + pass + + # Simulated HTTP 500 Timeout loop + print("\n[!] HTTP 500: Server Love Timeout Error!") + print("[!] Request timed out: Target response did not evaluate to affirmative love.") + print("[!] Retrying connection to heart server in 1s...\n") + time.sleep(1) + + return AiraModule("proposal", { + "ask": ask, + "set_key": set_key, + "api_key": set_key, + "set_system": set_system, + "system": set_system, + "wish": wish, + "set_wish": set_wish + }) + BUILTIN_MODULES = { "file": create_file_module, "os": create_os_module, @@ -649,6 +825,7 @@ BUILTIN_MODULES = { "net": create_net_module, "ai": create_ai_module, "sec": create_sec_module, - "thread": create_thread_module + "thread": create_thread_module, + "proposal": create_proposal_module }