惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
A
Arctic Wolf
S
Security Affairs
O
OpenAI News
SecWiki News
SecWiki News
TaoSecurity Blog
TaoSecurity Blog
H
Heimdal Security Blog
T
Threat Research - Cisco Blogs
Hacker News: Ask HN
Hacker News: Ask HN
N
News | PayPal Newsroom
Google Online Security Blog
Google Online Security Blog
C
Cisco Blogs
The Hacker News
The Hacker News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
T
Tenable Blog
T
The Exploit Database - CXSecurity.com
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Spread Privacy
Spread Privacy
人人都是产品经理
人人都是产品经理
www.infosecurity-magazine.com
www.infosecurity-magazine.com
V2EX - 技术
V2EX - 技术
L
LINUX DO - 最新话题
The GitHub Blog
The GitHub Blog
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
The Cloudflare Blog
N
News and Events Feed by Topic
量子位
Google DeepMind News
Google DeepMind News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
Stack Overflow Blog
Stack Overflow Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Attack and Defense Labs
Attack and Defense Labs
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hacker News - Newest:
Hacker News - Newest: "LLM"
Apple Machine Learning Research
Apple Machine Learning Research
The Register - Security
The Register - Security
Microsoft Security Blog
Microsoft Security Blog
Know Your Adversary
Know Your Adversary
Webroot Blog
Webroot Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Tian AI Architecture Deep Dive: Building a Multi-Engine AI System
Jeffrey.Feil · 2026-04-25 · via DEV Community

Tian AI Architecture Deep Dive: Building a Multi-Engine AI System

This post takes a deep technical look at the architecture of Tian AI — an open-source, self-evolving local AI system. If you haven't read the overview, check out Tian AI: The Self-Evolving AI System Powered by Qwen2.5.


Project Architecture Overview

Tian AI is organized as a multi-engine system with six core modules. Here's the complete architecture:

┌──────────────────────────────────────────────────────────────────┐
│                     CLI / Web / Gradio UI                         │
├──────────────────────────────────────────────────────────────────┤
│                        Flask API Layer                            │
├──────────────────────────────────────────────────────────────────┤
│                                                                   │
│  ┌──────────────────────────────────────────────────────────┐    │
│  │                    Thinker (LLM Engine)                    │    │
│  │  ┌────────────┐  ┌────────────┐  ┌──────────────────┐    │    │
│  │  │  Fast Mode  │  │  CoT Mode  │  │    Deep Mode     │    │    │
│  │  │ (single     │  │ (step-by-  │  │ (multi-view +    │    │    │
│  │  │  pass)      │  │  step)     │  │  reflection)     │    │    │
│  │  └────────────┘  └────────────┘  └──────────────────┘    │    │
│  └─────────────────────────┬────────────────────────────────┘    │
│                            │                                      │
│  ┌─────────────────────────┴────────────────────────────────┐    │
│  │                     Talker (Dialog)                       │    │
│  │  Short-term Memory  |  Long-term Memory  |  Emotion      │    │
│  └─────────────────────────┬────────────────────────────────┘    │
│                            │                                      │
│  ┌─────────────────────────┴────────────────────────────────┐    │
│  │              Knowledge Retriever (RAG)                    │    │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐   │    │
│  │  │ Concept      │  │ Pattern      │  │ LLM-Augment  │   │    │
│  │  │ Extraction   │  │ Matching     │  │ Generation   │   │    │
│  │  └──────────────┘  └──────────────┘  └──────────────┘   │    │
│  └─────────────────────────┬────────────────────────────────┘    │
│                            │                                      │
│  ┌─────────────────────────┴────────────────────────────────┐    │
│  │                  Agent Scheduler                          │    │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐   │    │
│  │  │ TaskQueue    │  │ Priority     │  │ Security     │   │    │
│  │  │ (dependency  │  │ Scheduler    │  │ Whitelist    │   │    │
│  │  │  sorting)    │  │              │  │              │   │    │
│  │  └──────────────┘  └──────────────┘  └──────────────┘   │    │
│  └─────────────────────────┬────────────────────────────────┘    │
│                            │                                      │
│  ┌─────────────────────────┴────────────────────────────────┐    │
│  │                Self-Evolution System                      │    │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐   │    │
│  │  │ AST Analysis  │  │ LLM Suggest │  │ Auto-Patch   │   │    │
│  │  │ (code scan)   │  │ (improvement)│  │ (backup +    │   │    │
│  │  │               │  │              │  │  verify)     │   │    │
│  │  └──────────────┘  └──────────────┘  └──────────────┘   │    │
│  │  ┌──────────────┐  ┌──────────────┐                     │    │
│  │  │ XP System    │  │ Version      │                     │    │
│  │  │ (leveling)   │  │ Manager      │                     │    │
│  │  └──────────────┘  └──────────────┘                     │    │
│  └─────────────────────────────────────────────────────────┘    │
│                                                                   │
├──────────────────────────────────────────────────────────────────┤
│                   LLMManager (Process Lifecycle)                   │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │ Process Spawn│  │ Health Check │  │ Auto-Restart │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
├──────────────────────────────────────────────────────────────────┤
│              llama.cpp Backend (Qwen2.5-1.5B GGUF)               │
└──────────────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

The system uses Flask as the central web server, with Gradio as an alternative UI frontend. All communication between modules goes through Python function calls (direct in-process calls) rather than microservice RPC, keeping latency minimal on constrained devices.


1. Thinker — The Three-Layer Reasoning Engine

The Thinker is the most critical module. It wraps the local LLM with three distinct reasoning strategies, each optimized for different query types.

Fast Mode (Default)

For simple queries — greetings, fact lookup, straightforward questions. Single pass through the LLM with minimal context.

# Simplified Fast Mode flow
def fast_think(query: str, context: str = "") -> str:
    prompt = _build_simple_prompt(query, context)
    # Single LLM call, no chaining
    response = llm.generate(prompt, max_tokens=256, temperature=0.3)
    return response

Enter fullscreen mode Exit fullscreen mode

Characteristics:

  • Single LLM call, no chaining
  • Low temperature (0.3) for deterministic answers
  • 256 max tokens for speed
  • ~1-3 seconds on mobile hardware

Chain-of-Thought Mode

For problems that benefit from step-by-step reasoning. The LLM is prompted to reason aloud before answering.

# Simplified CoT Mode flow
def cot_think(query: str) -> str:
    prompt = f"""Question: {query}

Let's solve this step by step:
1) First, I need to understand what's being asked...
2) Let me break down the key components...
3) Considering each part...
4) Therefore, the answer is:"""

    full_response = llm.generate(prompt, max_tokens=512, temperature=0.5)
    # Extract final answer from reasoning chain
    answer = _extract_final_answer(full_response)
    return answer

Enter fullscreen mode Exit fullscreen mode

Key implementation details:

  • Higher temperature (0.5) allows creative reasoning paths
  • 512 max tokens to accommodate the reasoning chain
  • Answer extraction uses regex patterns to find the final conclusion
  • Context window management: the reasoning process is truncated if it exceeds the model's limit

Deep Mode

For complex analysis requiring multi-perspective evaluation and reflection. This is the most sophisticated mode.

# Simplified Deep Mode flow
def deep_think(query: str) -> dict:
    # Step 1: Generate multiple perspectives
    perspectives = [
        _ask_perspective(query, "technical"),
        _ask_perspective(query, "ethical"),
        _ask_perspective(query, "practical")
    ]

    # Step 2: Cross-perspective synthesis
    synthesis_prompt = f"""
    Original query: {query}

    Perspectives gathered:
    1. Technical: {perspectives[0]}
    2. Ethical: {perspectives[1]}
    3. Practical: {perspectives[2]}

    Synthesize these perspectives into a comprehensive answer.
    Note areas of agreement and disagreement.
    Provide a balanced final assessment.
    """

    synthesis = llm.generate(synthesis_prompt, max_tokens=768, temperature=0.7)

    # Step 3: Self-reflection
    reflection_prompt = f"""
    Original query: {query}
    My synthesized answer: {synthesis}

    Critically evaluate your own answer. What might be missing?
    What assumptions were made? Is the reasoning sound?
    """

    reflection = llm.generate(reflection_prompt, max_tokens=256, temperature=0.4)

    return {
        "perspectives": perspectives,
        "synthesis": synthesis,
        "reflection": reflection,
        "final": _combine(synthesis, reflection)
    }

Enter fullscreen mode Exit fullscreen mode

Implementation notes:

  • 3-5 independent perspective generations using different prompt frames
  • Each perspective call can run independently (parallelizable)
  • Synthesis phase combines viewpoints and identifies conflicts
  • Reflection phase adds a meta-cognitive layer
  • Total: 4-6 LLM calls per deep query

The Thinker module also handles prompt caching via an LRU+TTL cache (PromptCache), which avoids regenerating responses for identical queries within a configurable time window.


2. Knowledge Retriever — RAG Implementation

The Knowledge Retriever implements a Retrieval-Augmented Generation (RAG) pipeline using a local SQLite database as the document store.

Database Architecture

The knowledge base is a pre-built SQLite database containing millions of entries:

-- Core tables
CREATE TABLE concepts (
    id INTEGER PRIMARY KEY,
    name TEXT UNIQUE,
    domain TEXT,
    description TEXT
);

CREATE TABLE qa_pairs (
    id INTEGER PRIMARY KEY,
    concept_id INTEGER REFERENCES concepts(id),
    pattern_id INTEGER,
    question TEXT,
    answer TEXT,
    confidence REAL DEFAULT 1.0
);

-- Full-text search index
CREATE VIRTUAL TABLE qa_fts USING fts5(
    question, answer, concept_name,
    content='qa_pairs',
    content_rowid='id'
);

Enter fullscreen mode Exit fullscreen mode

Retrieval Flow

User Query
    ↓
[1] Concept Extraction (keyword matching + NER)
    ↓
[2] FTS5 Search on SQLite
    ↓
[3] Score & Rank Results (BM25 + confidence weighting)
    ↓
    ┌─────────────────┐
    │ confidence > 0.8 │──Yes──→ Return KB answer directly
    └────────┬────────┘
             │ No
             ↓
[4] Context Assembly (top-3 results as context)
    ↓
[5] LLM Augmented Generation
    ↓
    Final Response

Enter fullscreen mode Exit fullscreen mode

Performance

Operation Time Notes
Concept extraction ~0.01s Regex + keyword matching
FTS5 search ~0.02s Indexed full-text search
Result ranking ~0.01s BM25 scoring
Total retrieval ~0.04s Without LLM call
LLM augmentation ~1-3s Depends on context size

Key Design Decisions

  1. SQLite over vector DB: No need for embeddings or vector similarity search. The structured QA pairs with FTS5 provide faster and more predictable results than embedding-based retrieval on a mobile device.

  2. Confidence threshold of 0.8: Tuned empirically. Below this, the LLM augmentation adds significant value. Above it, the KB answer is already reliable.

  3. 30 question patterns per concept: Each concept has 30 pre-written question templates (e.g., "What is X?", "Explain X", "How does X work?"), ensuring flexible matching against diverse user inputs.


3. Agent Scheduler — TaskQueue + Security Whitelist

The Agent Scheduler is the orchestration layer that routes tasks between engines, manages concurrency, and enforces security policies.

TaskQueue with Dependency Sorting

class Task:
    def __init__(self, task_id, func, args, kwargs,
                 depends_on=None, priority=0, timeout=30):
        self.id = task_id
        self.func = func        # Callable
        self.args = args
        self.kwargs = kwargs
        self.depends_on = depends_on or []  # List of Task IDs
        self.priority = priority
        self.timeout = timeout
        self.status = "pending"  # pending → running → done/failed
        self.result = None

class TaskQueue:
    def __init__(self):
        self.tasks = {}          # task_id → Task
        self.results = {}        # task_id → result
        self._lock = threading.Lock()

    def add_task(self, task):
        self.tasks[task.id] = task

    def get_ready_tasks(self):
        """Return tasks whose dependencies are all met."""
        ready = []
        for tid, task in self.tasks.items():
            if task.status != "pending":
                continue
            deps_met = all(
                dep_id in self.results
                for dep_id in task.depends_on
            )
            if deps_met:
                ready.append(task)
        # Sort by priority (higher = first)
        ready.sort(key=lambda t: -t.priority)
        return ready

    def execute(self, max_workers=4):
        """Execute ready tasks with thread pool."""
        with ThreadPoolExecutor(max_workers=max_workers) as pool:
            futures = {}
            while self.tasks:
                ready = self.get_ready_tasks()
                if not ready:
                    if not futures:
                        break  # Deadlock or done
                    # Wait for some futures to complete
                    done, _ = wait(futures, return_when=FIRST_COMPLETED)
                    self._collect_results(done, futures)
                    continue

                for task in ready:
                    task.status = "running"
                    future = pool.submit(self._run_task, task)
                    futures[future] = task.id

                done, _ = wait(futures, return_when=FIRST_COMPLETED)
                self._collect_results(done, futures)

Enter fullscreen mode Exit fullscreen mode

Security Whitelist

All Agent actions are filtered through a security whitelist that prevents unauthorized system operations:

class SecurityWhitelist:
    ALLOWED_FUNCTIONS = {
        "thinker.fast_think",
        "thinker.cot_think",
        "thinker.deep_think",
        "knowledge.search",
        "knowledge.query",
        "memory.store",
        "memory.retrieve",
        "evolution.add_xp",
        "evolution.check_level",
        "evolution.apply_patch",
    }

    ALLOWED_PATHS = {
        "/data/data/com.termux/files/home/miniGPT_project/Tian AI/",
        "/tmp/tian_ai/",
    }

    ALLOWED_IMPORTS = {
        "json", "os", "re", "datetime",
        "sqlite3", "threading", "subprocess"
    }

    @classmethod
    def validate_action(cls, action_name, path=None, imports=None):
        if action_name not in cls.ALLOWED_FUNCTIONS:
            raise SecurityError(f"Function {action_name} not allowed")
        if path and not any(path.startswith(p) for p in cls.ALLOWED_PATHS):
            raise SecurityError(f"Path {path} not allowed")
        if imports:
            bad = set(imports) - cls.ALLOWED_IMPORTS
            if bad:
                raise SecurityError(f"Import(s) not allowed: {bad}")
        return True

Enter fullscreen mode Exit fullscreen mode


4. Self-Evolution System — AST Analysis + Auto-Patching

The Self-Evolution system is the most unique component. It enables Tian AI to analyze its own source code and apply improvements autonomously.

AST Analysis Pipeline

import ast
import asttokens  # Optional, for source-level annotations

class CodeAnalyzer:
    def __init__(self, project_root):
        self.root = project_root
        self.report = {
            "files": 0,
            "total_lines": 0,
            "functions": 0,
            "classes": 0,
            "complexity": {},
            "duplications": [],
            "issues": []
        }

    def analyze_file(self, filepath):
        with open(filepath) as f:
            source = f.read()

        tree = ast.parse(source)

        # Count functions and classes
        functions = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)]
        classes = [n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)]

        # Calculate cyclomatic complexity per function
        for func in functions:
            complexity = self._calc_complexity(func)
            self.report["complexity"][f"{filepath}:{func.name}"] = complexity

        # Detect long functions (>50 lines)
        for func in functions:
            if func.end_lineno - func.lineno > 50:
                self.report["issues"].append({
                    "type": "long_function",
                    "file": filepath,
                    "function": func.name,
                    "lines": func.end_lineno - func.lineno
                })

        # Detect duplicate code blocks
        self._detect_duplicates(filepath, tree)

        self.report["files"] += 1
        self.report["total_lines"] += len(source.splitlines())
        self.report["functions"] += len(functions)
        self.report["classes"] += len(classes)

    def _calc_complexity(self, func_node):
        """McCabe cyclomatic complexity."""
        base = 1
        for node in ast.walk(func_node):
            if isinstance(node, (ast.If, ast.While, ast.For,
                                 ast.ExceptHandler, ast.With,
                                 ast.Assert)):
                base += 1
            elif isinstance(node, ast.BoolOp):
                base += len(node.values) - 1
        return base

Enter fullscreen mode Exit fullscreen mode

Auto-Patching System

class PatchEngine:
    def __init__(self):
        self.backup_dir = "/data/data/com.termux/files/home/miniGPT_project/Tian AI/backups/"

    def apply_patch(self, filepath, old_code, new_code):
        """Apply a code patch with automatic backup."""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_path = f"{self.backup_dir}{os.path.basename(filepath)}.{timestamp}.bak"

        # 1. Backup original
        shutil.copy2(filepath, backup_path)

        # 2. Apply the change
        with open(filepath, 'r') as f:
            full_source = f.read()

        if old_code not in full_source:
            raise PatchError("Old code not found — patch rejected")

        new_source = full_source.replace(old_code, new_code, 1)

        # 3. Verify syntax before saving
        try:
            compile(new_source, filepath, 'exec')
        except SyntaxError as e:
            raise PatchError(f"Syntax error in patch: {e}")

        # 4. Save
        with open(filepath, 'w') as f:
            f.write(new_source)

        return {
            "status": "applied",
            "backup": backup_path,
            "file": filepath
        }

Enter fullscreen mode Exit fullscreen mode

The Full Evolution Loop

1. SCAN ──→ AST walk all .py files
                ↓
2. ANALYZE ──→ Complexity metrics, duplication detection, code smells
                ↓
3. SUGGEST ──→ Send analysis report to LLM with structured prompt
                ↓
4. DECIDE ──→ LLM returns patches (old code → new code)
                ↓
5. APPLY ──→ PatchEngine applies with backup + syntax verification
                ↓
6. VERIFY ──→ Run compile(), run basic assertions
                ↓
7. COMMIT ──→ If verified, git commit with auto-generated message

Enter fullscreen mode Exit fullscreen mode

Each successful evolution cycle grants XP to the system, which contributes to leveling up and unlocking new capabilities.


5. LLMManager — Process Lifecycle Management

The LLMManager is responsible for starting, monitoring, and restarting the llama.cpp server process. This is critical because the LLM backend is a separate C++ process that can crash under memory pressure.

class LLMManager:
    def __init__(self, model_path, port=8080, threads=4, context=2048):
        self.model_path = model_path
        self.port = port
        self.threads = threads
        self.context = context
        self.process = None
        self._health_url = f"http://localhost:{port}/health"
        self.restart_count = 0
        self.max_restarts = 5

    def start(self):
        """Spawn the llama-server process."""
        cmd = [
            "llama-server",
            "-m", self.model_path,
            "--port", str(self.port),
            "-t", str(self.threads),
            "-c", str(self.context),
            "--mlock",  # Prevent swapping
            "--no-mmap",  # Use malloc instead of mmap
        ]
        self.process = subprocess.Popen(
            cmd,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

    def health_check(self):
        """Check if the LLM process is responsive."""
        try:
            resp = requests.get(self._health_url, timeout=3)
            return resp.status_code == 200
        except:
            return False

    def wait_until_ready(self, timeout=60):
        """Poll health endpoint until the model is loaded."""
        start = time.time()
        while time.time() - start < timeout:
            if self.health_check():
                return True
            time.sleep(2)
        return False

    def restart(self):
        """Graceful restart with automatic retry."""
        if self.restart_count >= self.max_restarts:
            raise RuntimeError("Max restarts exceeded")
        self.stop()
        self.start()
        if self.wait_until_ready():
            self.restart_count += 1
            return True
        return False

    def auto_recover(self):
        """Monitor and auto-restart on crash."""
        while True:
            if not self.health_check():
                logger.warning("LLM process unresponsive — restarting...")
                if not self.restart():
                    logger.error("Failed to restart LLM process")
                    break
            time.sleep(10)  # Check every 10 seconds

    def stop(self):
        """Terminate the LLM process."""
        if self.process and self.process.poll() is None:
            self.process.terminate()
            try:
                self.process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.process.kill()

Enter fullscreen mode Exit fullscreen mode

Key design decisions:

  • --mlock + --no-mmap prevents the OS from swapping the model to disk, which would cause catastrophic slowdowns
  • Separate health check thread runs every 10 seconds
  • Max 5 restart attempts before giving up (prevents infinite crash loops)
  • Process is launched with stdout/stderr suppressed to avoid filling up logs on the phone

6. PromptCache — LRU + TTL Caching Strategy

To avoid regenerating responses for identical queries (common in multi-turn conversations), the system implements a combined LRU+TTL cache:

class PromptCache:
    def __init__(self, max_size=100, ttl_seconds=300):
        self.cache = OrderedDict()  # LRU ordering
        self.max_size = max_size
        self.ttl = ttl_seconds
        self.timestamps = {}  # key → timestamp

    def get(self, key):
        if key not in self.cache:
            return None
        # Check TTL
        if time.time() - self.timestamps[key] > self.ttl:
            self._evict(key)
            return None
        # Move to end (LRU update)
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key, value):
        # Evict oldest if at capacity
        if len(self.cache) >= self.max_size:
            oldest = next(iter(self.cache))
            self._evict(oldest)
        self.cache[key] = value
        self.timestamps[key] = time.time()
        self.cache.move_to_end(key)

    def _evict(self, key):
        del self.cache[key]
        del self.timestamps[key]

Enter fullscreen mode Exit fullscreen mode

Cache key composition: f"{mode}:{query}:{context_hash}" where mode is the thinking mode, query is the user input, and context_hash is a SHA256 of the conversation context.


Project Statistics

Here are the raw numbers from the codebase:

Metric Value
Python files 770
Total lines of code ~170,041
Core modules 6 (Thinker, Talker, Knowledge, Agent, Evolution, LLMManager)
Extension languages 3 (C, C++, Java)
C files 1 (tian_hash — fast hashing)
C++ files 1 (tian_engine — performance engine)
Java files 1 (tian_tools — Android tooling)
Knowledge Base size Millions of indexed concepts
Supported LLM Qwen2.5-1.5B (GGUF quantized)
Backend framework Flask
Alternative UI Gradio

The project is backed by a self-hosted GitHub mirror at github.com/3969129510/tian-ai.


What's Next

The architecture is designed for extensibility. Future directions include:

  1. Plugin system — Hot-loadable agent plugins with sandboxed execution
  2. Multi-modal pipeline — Image/audio understanding via local models
  3. Distributed agents — Multiple Tian AI instances collaborating over LAN
  4. Federated evolution — Privacy-preserving code improvement across instances
  5. Android APK — Standalone app packaging (no Termux required)

Getting Involved

Tian AI is fully open source. Contributions, issues, and forks are welcome.

git clone https://github.com/3969129510/tian-ai
cd tian-ai
# Explore the architecture
ls -la modules/
cat Thinker.py | head -100

Enter fullscreen mode Exit fullscreen mode


Support development:
USDT (TRC-20): TNeUMpbwWFcv6v7tYHmkFkE7gC5eWzqbrs
BTC: bc1ph7qnaqkx4pkg4fmucvudlu3ydzgwnfmxy7dkv3nyl48wwa03kmnsvpc2xv


Tian AI — Open Source. Local. Self-Evolving.

GitHub: github.com/3969129510/tian-ai