GeniffyDocs
Changelog Log In Get a key

Twilio

Give an assistant that people text a memory of each of them. Twilio sends every message to your webhook, for SMS and for WhatsApp alike; your server puts what is known about the sender in front of Claude and answers in the same request. The next message starts knowing this one.

Install

Terminal
pip install fastapi uvicorn python-multipart anthropic twilio geniffy

Set GENIFFY_API_KEY from API keys in the Geniffy app and ANTHROPIC_API_KEY. From Twilio, set TWILIO_AUTH_TOKEN, and set TWILIO_WEBHOOK_URL to the address you give Twilio below, exactly as you give it: Twilio signs every request over that address.

Your server

server.py
import asyncio
import logging
import os
from collections import OrderedDict

from anthropic import AsyncAnthropic
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response
from geniffy import AsyncGeniffy
from twilio.request_validator import RequestValidator
from twilio.twiml.messaging_response import MessagingResponse

geniffy = AsyncGeniffy()                          # reads GENIFFY_API_KEY
claude = AsyncAnthropic()                         # reads ANTHROPIC_API_KEY
twilio = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"])
app = FastAPI()
log = logging.getLogger("twilio")
recent: OrderedDict[str, list] = OrderedDict()    # each person's last turns, for "yes" and "that one"
NOTHING = "Nothing is known about this person yet. If they mention an earlier conversation, say so rather than guessing."
UNREAD = "Their history could not be read just now. If they mention an earlier conversation, ask rather than guess."


def space_for(number: str) -> str | None:
    """The sender, by the digits of their number: the same person whether they text or use WhatsApp. None when it
    is no phone's number, such as a short code: then nothing is read or saved."""
    digits = "".join(ch for ch in number if ch.isdigit())
    return f"user_{digits}" if 7 <= len(digits) <= 15 else None


async def known_about(space: str | None, text: str) -> str:
    """What is known about the sender that bears on their message. A reply never waits on it for more than two
    seconds."""
    if space is None:
        return NOTHING
    try:
        return await asyncio.wait_for(geniffy.space(space).briefing(cue=text, budget_chars=3000), 2) or NOTHING
    except Exception as e:                        # slow or failing: the reply goes on without it
        log.warning("no briefing for this message: %r", e)
        return UNREAD


@app.post("/twilio")
async def receive(request: Request, background: BackgroundTasks):
    form = {k: str(v) for k, v in (await request.form()).items()}
    if not twilio.validate(os.environ["TWILIO_WEBHOOK_URL"], form, request.headers.get("X-Twilio-Signature", "")):
        raise HTTPException(403)
    text, reply = (form.get("Body") or "").strip(), MessagingResponse()
    if text:
        sender = form.get("From", "")
        space = space_for(sender)
        turn = {"role": "user", "content": text}
        past = recent.get(sender, [])
        response = await claude.messages.create(
            model="claude-opus-5-5",
            max_tokens=600,
            system=f"You are a helpful assistant over text messages. Keep replies short.\n\n"
                   f"<memory>\n{await known_about(space, text)}\n</memory>",
            messages=[*past, turn],
        )
        said = "".join(block.text for block in response.content if block.type == "text")
        reply.message(said)
        exchange = [turn, {"role": "assistant", "content": said}]
        recent[sender] = (past + exchange)[-10:]  # their last ten turns
        recent.move_to_end(sender)
        if len(recent) > 5000:                    # the people texting lately, not everyone who ever did
            recent.popitem(last=False)
        if space:
            background.add_task(geniffy.space(space).memories.add, messages=exchange)
    return Response(str(reply), media_type="application/xml")

Run it with uvicorn server:app, somewhere Twilio can reach over HTTPS.

Twilio waits up to 15 seconds for the answer, so the reply goes back in the same request and the exchange is saved after it has gone; a reply never waits more than two seconds for the memory. The last ten turns of the 5,000 people who texted most recently are kept in the process, which is right for one process; with more than one, keep them where every process can see them.

In Twilio

Set the address where a message comes in to https://your-server/twilio (HTTP POST):

  • SMS: on your phone number, under Messaging, A message comes in.
  • WhatsApp: on your WhatsApp sender, or the WhatsApp Sandbox while you build, under When a message comes in.

Each person is the space named by their number's digits, so the same person is one memory over SMS and WhatsApp. If you know them as customers, use your customer id instead. A number says who is probably texting, not who is, so confirm who it is before Claude shares anything private; the production checklist says how. When nothing is known about the sender, the memory says so in one sentence, so Claude says it doesn't know instead of guessing.

Last updated October 16, 2026