Metadata-Version: 2.5
Name: viola-agent
Version: 0.2.2
Summary: Self-hosted WhatsApp AI agent (Twilio) with an OpenAI-compatible API
Project-URL: Homepage, https://github.com/virpluzteam/viola-agent
Project-URL: Source, https://github.com/virpluzteam/viola-agent
Project-URL: Issues, https://github.com/virpluzteam/viola-agent/issues
Author: Xubin Ren, the viola contributors
License-Expression: MIT
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Keywords: agent,ai,chatbot,llm,twilio,whatsapp
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.11
Requires-Dist: aiohttp<4.0.0,>=3.9.0
Requires-Dist: anthropic<1.0.0,>=0.45.0
Requires-Dist: boto3>=1.43.0
Requires-Dist: chardet<6.0.0,>=3.0.2
Requires-Dist: croniter<7.0.0,>=6.0.0
Requires-Dist: ddgs<10.0.0,>=9.5.5
Requires-Dist: dingtalk-stream<1.0.0,>=0.24.0
Requires-Dist: dulwich<1.0.0,>=0.22.0
Requires-Dist: filelock>=3.25.2
Requires-Dist: httpx<1.0.0,>=0.28.0
Requires-Dist: jinja2<4.0.0,>=3.1.0
Requires-Dist: json-repair<1.0.0,>=0.57.0
Requires-Dist: lark-oapi<2.0.0,>=1.5.0
Requires-Dist: loguru<1.0.0,>=0.7.3
Requires-Dist: mcp<2.0.0,>=1.26.0
Requires-Dist: msgpack<2.0.0,>=1.1.0
Requires-Dist: oauth-cli-kit<1.0.0,>=0.1.3
Requires-Dist: openai>=2.8.0
Requires-Dist: openpyxl<4.0.0,>=3.1.0
Requires-Dist: prompt-toolkit<4.0.0,>=3.0.50
Requires-Dist: pydantic-settings<3.0.0,>=2.12.0
Requires-Dist: pydantic<3.0.0,>=2.12.0
Requires-Dist: pypdf<6.0.0,>=5.0.0
Requires-Dist: python-docx<2.0.0,>=1.1.0
Requires-Dist: python-dotenv<2.0.0,>=1.0.0
Requires-Dist: python-pptx<2.0.0,>=1.0.0
Requires-Dist: python-socketio<6.0.0,>=5.16.0
Requires-Dist: python-socks[asyncio]<3.0.0,>=2.8.0; sys_platform != 'win32'
Requires-Dist: python-telegram-bot[socks]<23.0,>=22.6
Requires-Dist: pyyaml<7.0.0,>=6.0
Requires-Dist: qq-botpy<2.0.0,>=1.2.0
Requires-Dist: questionary<3.0.0,>=2.0.0
Requires-Dist: readability-lxml<1.0.0,>=0.8.4
Requires-Dist: redis[hiredis]<6.0.0,>=5.0.0
Requires-Dist: rich<15.0.0,>=14.0.0
Requires-Dist: slack-sdk<4.0.0,>=3.39.0
Requires-Dist: slackify-markdown<1.0.0,>=0.2.0
Requires-Dist: socksio<2.0.0,>=1.0.0
Requires-Dist: tiktoken<1.0.0,>=0.12.0
Requires-Dist: typer<1.0.0,>=0.20.0
Requires-Dist: websocket-client<2.0.0,>=1.9.0
Requires-Dist: websockets<17.0,>=16.0
Provides-Extra: twilio
Requires-Dist: twilio<10.0.0,>=9.0.0; extra == 'twilio'
Description-Content-Type: text/markdown

# viola-agent

A self-hosted WhatsApp AI agent. A company deploys one copy, fills in its own Twilio,
LLM (OpenRouter or UniAPI) and optional billing credentials, and gets an assistant its
customers and staff can message on WhatsApp. Its own backend can talk to the same agent
over an OpenAI-compatible API and send proactive WhatsApp messages.

- **One process, one port.** `viola serve` runs the Twilio webhook, the `/v1/*` API and
  `/health`. Redis holds short-lived state (de-duplication, rate limits, the 24-hour
  window); everything else lives in one data folder.
- **One deployment = one company.** Each deployment has its own `.env`, Twilio account,
  public URL and data.
- **Safe defaults.** Twilio signatures are verified, every `/v1/*` call needs a server key,
  and the agent has no tools until you list them in `config.json`.
- **WhatsApp's rules built in.** Free text inside the 24-hour window, approved templates
  outside it, idempotent sends.

**Full setup guide: [docs/getting-started.md](docs/getting-started.md)**. It goes through
every `.env` variable, HTTPS, Twilio, templates, customisation, backups and
troubleshooting. The API contract is [docs/openapi.json](docs/openapi.json).

## Quick start (Docker)

You need Docker Compose v2, a Twilio account with a WhatsApp sender (the sandbox is fine
for a first test), an OpenRouter or UniAPI key, and a public HTTPS address for the
server.

```bash
git clone https://github.com/virpluzteam/viola-agent.git && cd viola-agent
cp .env.example .env && chmod 600 .env
# fill in TWILIO_*, PUBLIC_BASE_URL, LLM_API_KEY, LLM_MODEL_DEFAULT (see the guide)
docker compose up -d
docker compose exec viola viola doctor     # checks every credential and service
```

`docker compose up -d` pulls `ghcr.io/virpluzteam/viola-agent` (amd64 and arm64) and starts
it with Redis. Pin a release with `VIOLA_IMAGE=ghcr.io/virpluzteam/viola-agent:0.2.2` in
`.env`. The agent listens on `127.0.0.1:8900`; the next two steps make it reachable from
Twilio.

> The repository and image are private for now. Run `docker login ghcr.io` with an
> account (or a token with `read:packages`) that can read `virpluzteam` packages first.

### Without Docker

```bash
python3 -m venv .venv && .venv/bin/pip install 'viola-agent[twilio]'
cp .env.example .env              # APP_ENV=development runs without Redis
.venv/bin/viola serve --port 8900
```

Production (`APP_ENV=production`) requires `REDIS_URL`. Background tasks (cron reminders,
proactive delivery) run only with `VIOLA_API_BACKGROUND_TASKS=true`; the Docker image sets
it for you.

## Expose the webhook over HTTPS

Twilio must reach `https://<your domain>/twilio/webhook`. Set `PUBLIC_BASE_URL` to the
public base URL first: signatures are checked against it, and a mismatch rejects every
message with `403`. Only `/twilio/*` (and `/health`) needs to be public; keep `/v1/*` for
your own backend.

| Option | When | How |
|---|---|---|
| Bundled Caddy | Server with a public IP and a domain | `COMPOSE_PROFILES=caddy` and `VIOLA_DOMAIN=agent.example.com` in `.env`. Caddy gets the certificate and publishes only `/twilio/*` and `/health`. |
| Cloudflare Tunnel | No open ports; domain on Cloudflare | Named tunnel to `http://127.0.0.1:8900`, path `^/(twilio/.*\|health)$` |
| Your own reverse proxy | nginx / Caddy already on 80/443 | Proxy `/twilio/*` and `/health` to `127.0.0.1:8900` |
| ngrok | Development only | `ngrok http 8900`. Free hostnames change on restart, so update `PUBLIC_BASE_URL` and Twilio each time. |

Details: [Expose it over HTTPS](docs/getting-started.md#expose-it-over-https).

## Connect Twilio

In the Twilio Console, open your WhatsApp sender (sandbox: *Messaging → Try it out → Send
a WhatsApp message → Sandbox settings*) and set:

- **When a message comes in:** `https://<your domain>/twilio/webhook`, `POST`
- **Status callback URL** (optional): `https://<your domain>/twilio/status`

Message the number on WhatsApp; the agent answers within a few seconds. The webhook
replies `202` at once and sends the answer through Twilio when it's ready. Repeated
`MessageSid`s are ignored and each sender is rate-limited.

Each deployment uses its own domain. Two companies never share one webhook URL: a
deployment rejects signatures from any Twilio account but its own.

## Message templates

WhatsApp allows free text only within **24 hours** of the customer's last message. Outside
that window only Meta-approved templates may be sent. `/v1/notify`, cron reminders and
heartbeat all follow the same rule:

1. Window open and `fallback_text` given: the text is sent.
2. Otherwise, if the `template_id` is approved: the template is sent.
3. Otherwise nothing is sent, and the response is `422 template_required` with the reason.
   This is the rule working, not a failure.

The bundled catalogue `viola/notify/templates.yaml` has welcome, reminder, follow-up and
generic notification templates in `en` and `zh_HK`. To use your own, copy it to
`$VIOLA_DATA_DIR/templates.yaml` (Docker: `./data/templates.yaml`) and edit it. Then
create the templates in your Twilio account and submit them to Meta:

```bash
docker compose exec viola viola templates sync --dry-run   # preview
docker compose exec viola viola templates sync             # create + submit for approval
docker compose exec viola viola templates status           # check approval later
```

ContentSids and approval statuses are kept in `content_sid_map.json` in the data folder.
Only `approved` templates are used.

## Calling the agent from your backend

Set `VIOLA_API_SERVER_KEY` in `.env`. Without it every `/v1/*` route returns `404`. Only
your **backend** calls the API; never put the key in a browser. During key rotation,
`VIOLA_API_SERVER_KEY_PREVIOUS` is accepted too.

```bash
# Talk to the agent as one of your users (OpenAI-compatible; "stream": true for SSE)
curl https://agent.example.com/v1/chat/completions \
  -H "Authorization: Bearer $VIOLA_API_SERVER_KEY" -H "Content-Type: application/json" \
  -d '{"user": "u_42", "session_id": "support-7",
       "messages": [{"role": "user", "content": "What are your opening hours?"}]}'

# Send a proactive WhatsApp message
curl https://agent.example.com/v1/notify \
  -H "Authorization: Bearer $VIOLA_API_SERVER_KEY" -H "Content-Type: application/json" \
  -d '{"to": "+85212345678", "template_id": "reminder",
       "variables": {"reminder_text": "your appointment is tomorrow at 10:00"},
       "fallback_text": "Hi! Your appointment is tomorrow at 10:00.",
       "idempotency_key": "appt-123-reminder"}'
```

- **Chat:** `user` is required and is the user your backend authenticated (the agent
  doesn't check logins). History is kept per `portal:<user>:<session_id>`, and usage is
  billed to `portal:<user>`. Send only the new message; the agent keeps the history.
- **Notify:** `200` sent, `422 template_required`, `502 twilio_error`, `409` key reused
  with a different body (or still sending), `400` bad request. A repeated
  `idempotency_key` never sends twice; the first result is returned for 7 days.

Every route, body, status code and limit is described in
[docs/openapi.json](docs/openapi.json) (OpenAPI 3.1). Load it into Swagger UI, Redoc or a
client generator, or print the version you're running with `viola openapi`.

## Configuration

| Where | What |
|---|---|
| `.env` | Secrets, deployment values and switches: Twilio, LLM, billing, Redis, server key. See [`.env.example`](.env.example). |
| `config.json` in the data folder (optional) | Behaviour: tools for each channel profile (`whatsapp`, `portal`), MCP servers, transcription language. Tools are **off** until listed. |
| `workspace/` in the data folder | Persona and instructions (`SOUL.md` and friends), chat history and memory |

When `.env` and `config.json` disagree, the environment wins.

### Feature switches

Off by default. Each one makes background LLM calls, and those calls are billed.

| Variable | What it does |
|---|---|
| `VIOLA_DREAM_ENABLED` | Periodically consolidates chat history into long-term memory |
| `VIOLA_HEARTBEAT_ENABLED` | Periodically runs the tasks in `workspace/HEARTBEAT.md` |

The startup summary shows the state of each switch; `viola doctor` also lists the tools
each profile can use.

## Data and backups

Everything the agent keeps is in one folder: `./data` with Docker (`VIOLA_DATA_PATH`), or
`$VIOLA_DATA_DIR` (default `~/.viola`) without it. That's `config.json`, the workspace
(chat history, memory, persona), media, `content_sid_map.json`, and the SQLite files
(billing outbox, notification idempotency). Back it up with the agent stopped:

```bash
docker compose stop viola
tar czf viola-data-$(date +%F).tgz data/
docker compose start viola
```

Redis only holds short-lived state and needs no backup.

## Updating

```bash
git pull                       # compose file and docs
docker compose pull && docker compose up -d
```

With a pinned `VIOLA_IMAGE`, change the tag first. With pip: `pip install -U 'viola-agent[twilio]'`.

## Development

```bash
python3.13 -m venv .venv && .venv/bin/pip install -e ".[twilio]" --group dev   # pip >= 25.1; or: uv sync --all-extras
.venv/bin/ruff check viola/
.venv/bin/pytest
docker compose up -d --build   # run this checkout instead of the released image
```

Layout: `viola/` is the package (`viola/api/` has the HTTP routes, `viola/notify/` has
templates and proactive sends), `tests/` mirrors it, and `docs/` has the guides and the
OpenAPI document.

If you change a `/v1/*` route or its body, update the models in `viola/api/openapi.py` and
regenerate the document. `tests/api/test_openapi.py` fails when the document, the models
and the served routes disagree.

```bash
.venv/bin/viola openapi --output docs/openapi.json
```

CI (`.github/workflows/ci.yml`) runs ruff, pytest (Python 3.11–3.14, Linux and Windows),
a gitleaks scan of the full history (allowlist example values in `.gitleaks.toml`;
one-off false positives go in `.gitleaksignore`), a wheel
build and an image build with a smoke test (`.github/scripts/smoke-image.sh`).

### Releasing

1. Set `version` in `pyproject.toml` (e.g. `0.2.2`), regenerate `docs/openapi.json` (it
   carries the version), and merge to `main`. Wait for CI to pass.
2. Tag that commit and push the tag:

   ```bash
   git tag v0.2.2 && git push origin v0.2.2
   ```

`.github/workflows/release.yml` checks the tag matches the version and runs CI. It then
publishes the wheel and sdist to PyPI, pushes the image to GHCR as `0.2.2`, `0.2` and
`latest`, and creates a GitHub release. One-time setup is described at the top of that
file.

## License

MIT. See [LICENSE](LICENSE).
