Skip to content

Mr-Dark-debug/sms-ai-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SMS AI Agent

SMS AI Agent Banner

IMPORTANT: Termux:API Setup Required For this agent to read or send SMS, you MUST install the Termux:API components:

  1. Download App: Install the Termux:API Android App from F-Droid or the Google Play Store.
  2. Install Package: Run pkg install termux-api inside your Termux terminal.
  3. Grant Permissions: Go to Android Settings β†’ Apps β†’ Termux:API β†’ Permissions and enable SMS, Phone, and Storage.
  4. Disable Battery Optimization: Ensure battery optimization is disabled for both Termux and Termux:API to prevent the background service from being killed.

A production-ready, Termux-based SMS auto-responder with AI capabilities

License: MIT Python 3.8+ Termux


πŸ“± Overview

SMS AI Agent is a modular, secure SMS auto-responder for Android devices running through Termux. It operates in two modes:

  1. Rule-based Template Responder - Pattern matching with customizable response templates
  2. AI-powered Responder - Uses LLMs (Groq/OpenRouter/Ollama) for contextual responses

Key Features

  • πŸ”’ Security First - API keys in .env, no hardcoded secrets, guardrail system
  • πŸ€– LLM Integration - Groq (Lightning fast), OpenRouter (100+ models), and Ollama (local LLM) support
  • πŸ“ Rules Engine - Regex, keyword, and pattern matching with priorities
  • ⚑ Rate Limiting - Per-recipient and global rate limits to prevent abuse
  • πŸ›‘οΈ Guardrails - PII detection, content filtering, SMS length constraints
  • πŸ–₯️ Dual UI - Web UI (FastAPI) and Terminal UI (Textual)
  • πŸ’Ύ SQLite Storage - Message history, logs, and settings persistence
  • πŸ”„ Auto-start - Termux:Boot integration for device startup
  • πŸ‘€ Contact Personalization - Set specific AI instructions, names, and relations for individual phone numbers.
  • πŸ” Loop Protection - Advanced idempotency and echo-detection to prevent infinite self-reply loops.

πŸ‘€ Contact Personalization & Per-Number AI

You can now customize how the AI interacts with specific people in your life. By setting contact-specific metadata, the AI gains awareness of who it is talking to and how it should behave.

  • Name & Relation: Tell the AI who the person is (e.g., "John - Brother").
  • Custom Prompts: Provide unique instructions per number (e.g., "Be very respectful to my Boss" or "Use lots of emojis with my Best Friend").
  • Smart Context: These details are injected directly into the system prompt for highly personalized responses.
  • Robust Tracking: The system tracks responded status for every message, ensuring it never replies twice to the same text or gets stuck in a self-reply loop.

⚠️ Important: What This App Does

This app works with SMS messages only!

It can:

  • βœ… Read incoming SMS messages
  • βœ… Generate AI-powered replies using OpenRouter/Ollama
  • βœ… Send SMS responses automatically
  • βœ… Work with rule-based responses

It cannot:

  • ❌ Read messages from WhatsApp, Instagram, Messenger, Telegram, etc.
  • ❌ Read notification content from other apps
  • ❌ Work with messaging apps that don't use SMS

Why? SMS is a system-level feature that Termux can access via Termux:API. Other messaging apps (WhatsApp, Instagram, etc.) use their own encrypted protocols and require special Android permissions (Accessibility Services or Notification Listener) to access.

To extend to other apps, you would need a separate Android app that acts as a notification listener or uses Accessibility Services to read messages and forward them to this SMS AI Agent.


πŸ“‹ Requirements

Android Device

  • Android 7.0+ (API 24+)
  • Termux app installed
  • Termux:API app installed

Termux Packages

pkg update
pkg install python python-pip termux-api git

LLM Provider (Choose One)

  • Groq (Recommended): Ultra-fast inference. API key from console.groq.com. Default model: llama-3.3-70b-versatile.
  • OpenRouter: API key from openrouter.ai
  • Ollama: Local installation at ollama.ai

Using Free Models (Recommended for Zero Cost)

The app is pre-configured to use openrouter/free which automatically selects from free models. This means:

  • No cost - Completely free AI responses
  • Auto-selection - Randomly picks from available free models each request
  • Always free - No credit card required

To use specific free models instead, you can set:

  • openrouter/free - Random free model (default)
  • meta-llama/llama-3.3-70b-instruct:free - Llama model
  • google/gemma-2-9b-it:free - Gemma model
  • mistralai/mistral-7b-instruct:free - Mistral model

πŸš€ Quick Start

1. Install SMS AI Agent

# Clone or download
git clone https://github.com/your-username/sms-ai-agent.git
cd sms-ai-agent

# Run installer
chmod +x install.sh
./install.sh --first-run

2. Configure API Key

# Edit configuration
nano ~/.config/sms-ai-agent/.env

# Add your OpenRouter API key
OPENROUTER_API_KEY=sk-or-your-key-here

3. Start the Agent

# Web UI (recommended)
python main.py --web

# Terminal UI
python main.py --tui

# Background daemon
python main.py --daemon

4. Grant Permissions

When prompted, grant SMS permissions to Termux:

  1. Go to Settings β†’ Apps β†’ Termux β†’ Permissions
  2. Enable SMS permission
  3. Enable Storage permission (for configuration files)

πŸ“– Documentation

Configuration

Main configuration file: ~/.config/sms-ai-agent/config.yaml

llm:
  provider: "openrouter"
  model: "openrouter/free"  # Uses random free model - zero cost!
  temperature: 0.7
  max_tokens: 150

sms:
  auto_reply_enabled: true
  ai_mode_enabled: true
  max_response_length: 300

rate_limit:
  max_messages_per_minute: 10
  max_per_recipient_per_hour: 5

Personality Customization

You can fully customize the AI's personality and behavior by editing two key files in your config directory (~/.config/sms-ai-agent/):

1. personality.md - The "Soul" of Your AI

This file defines how the AI speaks, reacts, and behaves. You can customize:

  • Language Style: Hinglish, English, or any mix
  • Tone: Friendly, sarcastic, formal, casual
  • Behavioral Rules: How to handle flirting, abuse, confusion
  • Vocabulary: Custom slang, phrases, expressions
  • Example Dialogues: Sample conversations for reference

Edit at: ~/.config/sms-ai-agent/personality.md

2. agent.md - The "Brain" of Your AI

This file controls the operational logic:

  • Input Processing: How to clean and process incoming messages
  • Loop Prevention: Preventing infinite self-reply loops
  • Response Rules: Length limits, formatting rules
  • Fallback Behavior: How to respond when confused
  • Priority Hierarchy: Security, context, personality order

Edit at: ~/.config/sms-ai-agent/agent.md

πŸ’‘ Pro Tips for Customization:

  • Keep responses short (under 160 characters) for natural SMS feel
  • Use lowercase - real friends don't capitalize every sentence
  • Add local slang and phrases to make it feel more personal
  • The AI mirrors your energy - customize it to match your style!

Rules Engine

Add custom rules in the Web UI or edit ~/.config/sms-ai-agent/rules.yaml:

rules:
  - name: "greeting"
    patterns: ["hello", "hi", "hey"]
    match_type: "contains"
    responses:
      - "Hello! How can I help?"
      - "Hi there!"
    priority: 50

πŸ—οΈ Architecture

sms-ai-agent/
β”œβ”€β”€ core/                   # Core functionality
β”‚   β”œβ”€β”€ config.py          # Configuration management
β”‚   β”œβ”€β”€ database.py        # SQLite operations
β”‚   β”œβ”€β”€ exceptions.py      # Custom exceptions
β”‚   β”œβ”€β”€ logging.py         # Logging setup
β”‚   β”œβ”€β”€ rate_limiter.py    # Rate limiting
β”‚   └── security.py        # Security utilities
β”œβ”€β”€ llm/                    # LLM providers
β”‚   β”œβ”€β”€ base.py            # Abstract provider
β”‚   β”œβ”€β”€ openrouter.py      # OpenRouter integration
β”‚   β”œβ”€β”€ ollama.py          # Ollama integration
β”‚   └── factory.py         # Provider factory
β”œβ”€β”€ rules/                  # Rules engine
β”‚   β”œβ”€β”€ engine.py          # Pattern matching
β”‚   └── templates.py       # Template processing
β”œβ”€β”€ services/               # Core services
β”‚   β”œβ”€β”€ sms_handler.py     # Termux SMS API
β”‚   β”œβ”€β”€ guardrails.py      # Response safety
β”‚   └── ai_responder.py    # AI response generation
β”œβ”€β”€ ui/                     # User interfaces
β”‚   β”œβ”€β”€ web/               # FastAPI web UI
β”‚   β”‚   β”œβ”€β”€ app.py
β”‚   β”‚   β”œβ”€β”€ routes.py
β”‚   β”‚   └── templates/
β”‚   └── terminal/          # Textual TUI
β”‚       └── app.py
β”œβ”€β”€ config/                 # Configuration files
β”‚   β”œβ”€β”€ config.yaml        # Main config
β”‚   β”œβ”€β”€ personality.md     # AI personality
β”‚   β”œβ”€β”€ agent.md           # Agent rules
β”‚   └── .env.example       # Environment template
β”œβ”€β”€ main.py                 # Entry point
β”œβ”€β”€ install.sh              # Installation script
└── requirements.txt        # Python dependencies

πŸ”§ Command Line Interface

# Show help
python main.py --help

# Start web UI
python main.py --web --port 8080

# Start terminal UI
python main.py --tui

# Run as daemon
python main.py --daemon

# Check status
python main.py --status

# Test message
python main.py --test "Hello, how are you?"

# Set API key
python main.py --api-key sk-or-your-key

# Run setup wizard
python main.py --setup

πŸ” Security

API Key Storage

  • API keys are stored in ~/.config/sms-ai-agent/.env
  • File permissions are set to 600 (owner read/write only)
  • Never commit .env files to version control

Guardrails

The system includes multiple safety layers:

  1. Length Constraints - Enforces 300 character SMS limit
  2. PII Detection - Blocks phone numbers, emails, credit cards
  3. Content Filtering - Blocks passwords, SSNs, bank info
  4. Pattern Blocking - Custom regex patterns
  5. Fallback Responses - Safe defaults when violations occur

Rate Limiting

Prevents abuse with configurable limits:

  • Global: 10 messages/minute
  • Per-recipient: 5/hour, 20/day
  • Burst protection: 3 messages/minute

Data Privacy

  • All data stored locally on device
  • No external data transmission (except LLM API calls)
  • Data wipe script available

πŸ“± Termux Integration

Auto-start on Boot

  1. Install Termux:Boot from F-Droid
  2. Run the installer with --first-run flag
  3. Boot script will be created at ~/.termux/boot/

Home Screen Shortcuts

  1. Install Termux:Widget from F-Droid
  2. Shortcuts are created at ~/.termux/shortcuts/
  3. Add widgets to home screen for quick access

SMS Permissions

For Android 10+:

# Request SMS permission
termux-sms-send -n 0000000000 "test"

# Or manually grant in settings
Settings β†’ Apps β†’ Termux β†’ Permissions β†’ SMS

πŸ§ͺ Testing

# Run all tests
pytest tests/

# Test SMS handler
python -c "from services.sms_handler import test_sms_handler; print(test_sms_handler())"

# Test LLM connection
python main.py --test "Hello"

πŸ› Troubleshooting

SMS Not Working

  1. Verify Termux:API is installed
  2. Grant SMS permission in Android settings
  3. Test with: termux-sms-list

LLM Connection Failed

  1. Check API key in .env file
  2. Verify internet connection
  3. Test with: python main.py --status

Web UI Not Accessible

  1. Check if port is available
  2. Try different port: python main.py --web --port 9000
  3. Use 0.0.0.0 for external access: python main.py --web --host 0.0.0.0

Rate Limit Exceeded

  • Wait for rate limit window to reset
  • Adjust limits in config.yaml
  • Check status with: python main.py --status

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run tests
  5. Submit a pull request

Code Style

  • Follow PEP 8 guidelines
  • Use type hints
  • Add docstrings to functions
  • Keep functions under 50 lines

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments


πŸ“ž Support


πŸ“Š Compatibility

Android Version Status Notes
Android 7-9 βœ… Full All features work
Android 10-11 ⚠️ Partial SMS permissions need manual grant
Android 12+ ⚠️ Partial Background restrictions may apply

Note: Some Android versions require additional setup for background SMS operations.


Made with ❀️ for the Termux community

About

AI SMS Auto-Responder for Android. Turn your Android device into an autonomous AI communication hub. A Python-based SMS auto-responder running natively on Termux, powered by LLMs (OpenRouter/Ollama) with a sleek Web & Terminal UI.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors