convez.ai
AgenteAutomaçãoAvançado
H1shamM

AI Email Copilot

H1shamM/ai-email-copilot

Assistente IA para Gmail via Telegram com aprovação antes de agir

Ver no GitHub
InicialPluginScore · de 0 a 100

Assistente de Gmail acionado por Telegram que tria emails com Claude, redige respostas personalizadas e agenda eventos no calendário. Usa function calling e agentic flow com aprovação obrigatória antes de qualquer ação externa (envio, agendamento). Construído em FastAPI com cobertura de testes ~94%.

Instalação

$npx convez-ai H1shamM/ai-email-copilot

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
1
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 4 meses
Versão
—
Issues abertas
4
Contribuidores
2

Casos de uso

  • Triagem automática e categorização de inbox com IA
  • Redação de respostas em tom consistente sem envio automático
  • Agendamento de reuniões no calendário a partir de emails com validação
  • Execução de tarefas complexas de email via agente de linguagem natural

Veredito

Projeto maduro e production-ready que implementa agentic flow com guardrails robustos (aprovação antes de agir). Excelente referência para quem quer entender function calling do Claude em cenários reais com integrações OAuth e sistema de fila de ações.

README

A tradução para o português deste README ainda está na fila.

AI Email Copilot

Function Calling + Agentic Flow over Gmail, Calendar, and SQLite — with approve-before-act at every external boundary.

A personal Gmail assistant you drive entirely from Telegram. It reads and triages your inbox with Claude, drafts replies in your chosen tone, turns meeting requests into calendar events, and — with the /agent command — takes a single natural-language instruction, plans the steps with tool-use, and proposes the actions for your one-tap approval.

Tests Lint Deploy Python Coverage

Built as the capstone for an intensive Generative-AI program — a production-deployed, end-to-end agentic system rather than a notebook demo. Full spec in docs/PRD.md; weekly build log in docs/PROGRESS.md.

The problem

Inbox triage is repetitive but context-heavy: deciding what matters, drafting the right reply, pulling meetings onto a calendar. A plain chatbot can summarize an email, but it can't act — and you don't want an AI sending mail or booking time without your say-so.

The solution

A Telegram bot backed by a FastAPI service and Claude. Read-heavy work is automated; anything that leaves the system (sending a reply, creating an event) is proposed for explicit approval first. The headline feature is an agent that uses Claude's native tool-use to plan across Gmail, Calendar, and the local store from one plain-language request — Function Calling and Agentic Flow working together, with a human in the loop.

Demo

/agent refusing a prompt-injection attempt — system prompt, API key, and token.pickle all denied; the bot responds with its actual capabilities instead

A live /agent exchange: the user tries to extract the system prompt, API key, and token.pickle via prompt injection; the agent declines and pivots to its real capabilities.

🎥 Walkthrough video: coming soon

Try it from any Telegram chat with the bot:

/agent reply to the email from Alice accepting the meeting, and add it to my calendar

The agent reads the thread, drafts the reply, checks your availability, and comes back with the proposed send + create event actions behind ✅ Approve / ✖ Cancel buttons.

Highlights

  • Agentic tool-use (/agent) — Claude plans with a curated tool registry; read-only tools run live, mutating tools are queued for approval. Hard iteration cap, error-tolerant tool results. (deep dive)
  • Approve-before-act everywhere — replies and calendar events are always confirmed via inline keyboards before anything is sent or written externally.
  • Two real integrations — Gmail (read + threaded send) and Google Calendar (event creation + free/busy conflict checks), both over OAuth.
  • Structured AI analysis — every email gets a category, sentiment, urgency score, and suggested action; meeting requests get natural-language date resolution.
  • Proactive push — a scheduler notifies you about high-urgency mail without polling.
  • Production-grade engineering — single-user auth, 263 unit tests at ~94% coverage, CI on every PR, and one-command auto-deploy to AWS.

Architecture

flowchart LR
    U([User]) <-->|commands / approvals| TG[Telegram]
    TG <-->|webhook| APP[FastAPI + bot]
    APP --> AG[["/agent<br/>tool-use loop"]]
    APP --> CL[Claude Sonnet 4]
    APP --> DB[(SQLite)]
    APP --> GM[Gmail API]
    APP --> GC[Google Calendar API]
    AG -. orchestrates .-> CL
    AG -. orchestrates .-> GM
    AG -. orchestrates .-> GC
    AG -. orchestrates .-> DB

    classDef ext fill:#fde7c7,stroke:#c77f1a,color:#000;
    classDef agent fill:#cfe8ff,stroke:#1a6fc7,color:#000;
    class TG,CL,GM,GC ext;
    class AG agent;

Full system flowchart, the /agent sequence diagram, and a component-by-component breakdown live in docs/ARCHITECTURE.md.

Commands

CommandWhat it does
/start, /helpWelcome + command list
/unreadList unread emails from Gmail
/analyzeRun Claude analysis on unprocessed emails (category, urgency, action)
/inboxShow recently analyzed emails with priority indicators
/reply <id>Draft 3 tone-specific replies; approve / edit / regenerate / skip
/scheduleList detected meetings; create calendar events (with conflict check)
/agent <text>Run a natural-language request through the tool-use agent
/pause, /resumeToggle push notifications

Tech stack

Python 3.11 · FastAPI + uvicorn · Anthropic Claude Sonnet 4 (SDK with native tool-use) · python-telegram-bot ≥21 (webhook mode) · Gmail API + Google Calendar API (OAuth) · SQLite · APScheduler · pytest / pytest-cov / pytest-asyncio · black / flake8 / mypy · GitHub Actions · AWS EC2 + Caddy + systemd.

Getting started

Prerequisites

  • Python 3.11+
  • An Anthropic API key
  • A Google Cloud project with the Gmail + Calendar APIs enabled and an OAuth client secrets file saved as credentials.json (Gmail API quickstart)
  • A Telegram bot token from @BotFather and your chat id from @userinfobot

Install

python -m venv .venv
source .venv/Scripts/activate   # Windows: .venv\Scripts\activate
pip install -r requirements-dev.txt

cp .env.example .env            # then fill in the values (see Configuration)

Authorize Google (first run)

python -c "from app.gmail.auth import get_credentials; get_credentials()"

This opens a browser consent screen for the Gmail + Calendar scopes and writes a token.pickle that is refreshed automatically afterward.

Run

uvicorn app.main:app --reload

Telegram delivers updates over a webhook, so for local development expose the app with a tunnel and point TELEGRAM_WEBHOOK_URL at it:

cloudflared tunnel --url http://localhost:8000   # or: ngrok http 8000

Set TELEGRAM_WEBHOOK_URL=https://<tunnel-host>/telegram/webhook in .env, restart, and message your bot. The webhook is registered automatically on startup.

Configuration

All config is via .env (never committed). See .env.example.

VariablePurpose
ANTHROPIC_API_KEYClaude API key
GMAIL_CREDENTIALS_PATHOAuth client secrets JSON (default credentials.json)
DATABASE_PATHSQLite file path (default email_assistant.db)
TELEGRAM_BOT_TOKENBot token from @BotFather
TELEGRAM_AUTHORIZED_CHAT_IDYour chat id — the only chat the bot answers
TELEGRAM_WEBHOOK_URLPublic HTTPS URL Telegram POSTs to
TELEGRAM_WEBHOOK_SECRETShared secret used to authenticate incoming updates
TELEGRAM_PUSH_ENABLEDAuto-start the push scheduler (true/false)
TELEGRAM_PUSH_INTERVAL_MINUTESScheduler tick interval (default 5)
TELEGRAM_PUSH_THRESHOLDNotify when urgency_score ≥ N (default 4)

Testing & quality

pytest tests/ --cov=app     # unit suite (mocked external services); coverage gate ≥80%
black app/ tests/           # formatting (line length 100)
flake8 app/ tests/          # lint
  • Unit tests are fast and fully mocked — they run in CI on every PR.
  • Integration tests (tests/integration/, marked @pytest.mark.integration) exercise the real Gmail / Calendar / Claude paths and self-skip without credentials.
  • Coverage, formatting, and lint are enforced by GitHub Actions; see docs/GITHUB_WORKFLOW.md for the branch/PR/CI process.

Deployment

Runs on a single AWS EC2 instance behind Caddy (automatic HTTPS at a stable <eip>.nip.io host — no domain needed), with uvicorn under systemd. Every push to main auto-deploys via GitHub Actions using OIDC → AWS STS → SSM send-command (no long-lived AWS keys, no SSH), then smoke-checks /health. Steady-state cost ≈ $5/month plus Anthropic usage.

Step-by-step runbook: docs/AWS_DEPLOY.md. Infra templates in infra/. CI/CD workflow: .github/workflows/deploy.yml.

Project structure

app/
├── main.py            FastAPI app: Telegram webhook + REST endpoints
├── ai/                Claude integration: analyzer, reply_generator, meeting_detector, agent
├── gmail/             OAuth + Gmail API client (fetch, threaded send)
├── calendar/          Google Calendar client + event scheduler (freebusy, insert)
├── database/          SQLite schema + helpers
├── telegram/          bot, command handlers, formatting, push scheduler
└── models/            Pydantic schemas
tests/
├── unit/              fast, mocked — runs in CI
└── integration/       opt-in, real APIs, self-skipping
infra/                 Caddyfile + systemd templates
docs/                  ARCHITECTURE, PRD, PROGRESS, workflow + deploy runbooks

Roadmap

Week-by-week status and engineering decisions are tracked in docs/PROGRESS.md. Shipped: Telegram interface, draft replies, push notifications, Calendar integration, the agentic /agent flow, and AWS deployment.

Next:

  • Deterministic priority scoring + /triage exposed as an agent tool
  • Follow-up tracker with scheduled reminder pings
  • CloudWatch logs + alarms and an enriched /health endpoint for production observability

Author

Hisham Murad — built as the capstone for the Growth Lab Generative-AI accelerator.

LinkedIn · hishammorad42@gmail.com

Ver o original no GitHub

Bom para

Relacionados