The Text2Pen Backend β powering AI features for the Text2Pen desktop application.
The Text2Pen Backend is a FastAPI-powered service that provides intelligent AI features to the Text2Pen desktop application, including:
- AI Chat β conversational assistance with image analysis support
- Text Processing β grammar correction, rephrasing, tone adjustment, and text generation
- Image Analysis β understanding images via vision models
- Rate Limiting & Telemetry β fair usage enforcement and anonymous usage tracking
The backend is hosted on Render and uses Groq Cloud for AI inference, providing fast, reliable responses with high rate limits on the free tier.
- AI Chat with Vision β chat with the assistant and upload images for analysis
- Text Actions β correct grammar, shorten text, adjust tone (formal/casual), generate content
- Smart Rate Limiting β per-IP daily limits (10 chat requests, 1000 text actions) reset at midnight UTC
- Queue Management β separate worker threads for text and vision requests to handle load gracefully
- Groq Integration β uses high-capacity Groq API with exponential backoff and automatic retries
- Anonymous Telemetry β optional, GitHub-backed event logging for error tracking (no personal data)
- Multi-format Image Support β PNG, JPEG, GIF, WebP, BMP with automatic compression and resizing
The backend uses a queue-based worker pattern to handle AI requests reliably:
| Component | Purpose |
|---|---|
| FastAPI app | HTTP endpoints for chat, text actions, telemetry, and limits |
| Large Queue | Worker thread for text-only requests (using Llama 3.3-70B) |
| Vision Queue | Worker thread for image+text requests (using Llama 4 Scout Vision) |
| Global Rate Limiter | Throttles Groq API calls (~2s between requests to stay within free tier limits) |
| Per-IP Rate Limiter | Enforces daily usage limits per client IP with midnight UTC reset |
| GitHub Integration | Stores anonymous telemetry events in repo via GitHub API |
- Python 3.9+
- API keys for:
- Groq Cloud (
GROQ_API_KEY) β for LLM inference - GitHub (
GITHUB_TOKEN) β for telemetry storage
- Groq Cloud (
- A Render account (or compatible hosting)
GROQ_API_KEY=<your-groq-api-key>
GITHUB_TOKEN=<your-github-token>-
Clone the repository:
git clone https://github.com/pythonIsFast/Text2Pen-Backend.git cd Text2Pen-Backend -
Install dependencies:
pip install fastapi uvicorn requests pillow python-multipart
-
Set environment variables in your
.envfile or hosting platform. -
Run the server:
uvicorn main:app --host 0.0.0.0 --port 8000
-
The server will start at
http://localhost:8000.
- Push your code to GitHub
- Create a new Web Service on Render
- Connect your GitHub repository
- Set the start command:
uvicorn main:app --host 0.0.0.0 --port $PORT - Add environment variables (
GROQ_API_KEY,GITHUB_TOKEN) - Deploy!
Health check endpoint.
Response:
{
"message": "All systems are up and running!"
}Chat with the AI assistant, optionally with image analysis.
Request:
{
"history": [
{"role": "assistant", "content": "Hello! How can I help?"},
{"role": "user", "content": "Hi there"}
],
"message": "Can you help me rephrase this?",
"image_b64": null
}Response:
{
"result": "Of course! I'd be happy to help you rephrase your text...",
"model": "llama-3.3-70b",
"queue_position": 1,
"chat_used": 2,
"chat_limit": 10
}Rate Limit: 10 requests per IP per day (resets at midnight UTC)
Text processing actions (grammar correction, rephrasing, tone adjustment, etc.).
Request:
{
"action": "correct",
"text": "i have a dog and a cat",
"extra": {}
}Available Actions:
| Action | Description |
|---|---|
correct |
Fix spelling and grammar |
shorten |
Reduce text length significantly |
tone_formal |
Rewrite in formal tone |
tone_casual |
Rewrite in casual/friendly tone |
generate |
Generate new text on a topic |
replace_unknown |
Replace special characters with simpler alternatives (requires known_chars in extra) |
Response:
{
"result": "I have a dog and a cat."
}Rate Limit: 1000 requests per IP per day (resets at midnight UTC)
Check current rate limits and queue status for your IP.
Response:
{
"chat_used": 2,
"chat_limit": 10,
"text_used": 45,
"text_limit": 1000,
"resets_at": "midnight UTC",
"large_queue_depth": 3,
"vision_queue_depth": 0
}Submit anonymous telemetry events (error reports, crash logs, etc.).
Request:
{
"event": "error",
"os": "Windows 10",
"timestamp": "2025-04-11T12:34:56Z",
"extra": {"error_code": "E001"}
}Response:
{
"status": "ok"
}Rate Limit: 100 telemetry events per IP per hour
Edit these constants in main.py:
CHAT_LIMIT = 10 # chat requests per day per IP
TEXT_LIMIT = 1000 # text actions per day per IP
_MIN_INTERVAL = 2.0 # seconds between Groq API calls (respect free tier)The backend uses two Groq models:
llama-3.3-70b-versatileβ text-only requests (fast, high-throughput)meta-llama/llama-4-scout-17b-16e-instructβ vision + text requests (multimodal)
You can swap these by editing the model constants at the top of main.py.
Customize the AI assistant's behavior by editing SYSTEM_PROMPT in the code. The current prompt instructs the model to:
- Act as Text2Pen AI, integrated into the desktop app
- Provide helpful writing and image analysis assistance
- Respond in the user's language
- Keep responses concise and friendly
The backend stores anonymous telemetry in your GitHub repository to help track errors and improve stability.
- Telemetry is never collected without user consent from the frontend
- Only anonymous technical data is stored: error type, OS, timestamp, sanitized error message
- No personal data is ever collected: no typed text, no images, no usernames
- Telemetry events are deduplicated by event type + OS + extra fields (keeping the most recent)
Per-IP rate limits prevent abuse:
- Daily limits reset at midnight UTC
- Limits are enforced based on the client's real IP (respects
X-Forwarded-Forheaders for proxied requests) - Exceeding limits returns a 429 (Too Many Requests) response
- Groq and GitHub API keys are stored as environment variables only (never hardcoded)
- Keys are never logged or exposed in error messages
- Communicate with Groq and GitHub over HTTPS only
Use curl or Postman to test endpoints:
# Health check
curl http://localhost:8000/ping
# Check limits
curl http://localhost:8000/ai/limits
# Chat endpoint
curl -X POST http://localhost:8000/ai/chat \
-H "Content-Type: application/json" \
-d '{"history": [], "message": "Hello!"}'
# Text action
curl -X POST http://localhost:8000/ai \
-H "Content-Type: application/json" \
-d '{"action": "correct", "text": "i love python"}'429 Rate Limit from Groq
- The backend retries with exponential backoff (up to 20 attempts)
- If retries fail, the error is returned to the client
- Check the
/ai/limitsendpoint to see queue depth
Image Upload Too Large
- Images are automatically resized to 512Γ512 JPEG (quality 60)
- This reduces token usage on Groq's vision model
- Very large images may still cause timeouts; keep them under 5 MB
Telemetry Not Storing
- Check that
GITHUB_TOKENhasreposcope permissions - Verify the token can write to the repository
- Check GitHub API rate limits (60 requests/hour for unauthenticated, 5000/hour for authenticated)
- Free Tier Limits β Groq free tier has ~30 requests/minute; backend adds 2-second global throttling
- 5-Minute Timeout β requests that don't complete within 5 minutes are canceled
- Image Compression β large/high-quality images are automatically compressed to reduce token usage
- Stateless β the backend does not persist chat history; clients must send full history each request
- No Authentication β the backend relies on IP-based rate limiting (suitable for single-user/small-scale use)
Check the /ai/limits endpoint to see how many requests are pending:
{
"large_queue_depth": 3,
"vision_queue_depth": 0
}large_queue_depth> 5 indicates the text queue is building upvision_queue_depth> 2 indicates slow vision requests (images)
The backend starts two daemon threads on startup:
- large-worker β processes text-only requests (Llama 3.3-70B)
- vision-worker β processes image+text requests (Llama 4 Scout Vision)
Both log their activity to stdout. Check your logs if requests seem stuck.
All errors are caught and returned as HTTP 500 responses. Check:
- Render logs (if hosted on Render)
- Local console output (if running locally)
- The telemetry endpoint logs any errors from the frontend app
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
feature/your-feature) - Test your changes locally
- Submit a pull request with a clear description
- Additional AI models or Groq providers
- Improved rate limiting strategies
- Better error messages and logging
- Performance optimizations
- Additional text actions
- Documentation improvements
Text2Pen Backend is licensed under the GNU General Public License v3.0 (GPL-3.0).
See the LICENSE file for details.
- Text2Pen Frontend β the Windows desktop application
If you encounter issues or have questions:
- Check the Limitations section above
- Review the Common Issues section
- Open a GitHub Issue with:
- Error message
- Steps to reproduce
- Your OS and environment details
- Contact: Text2Pen.Info@gmail.com