GeniffyDocs
Changelog Log In Get a key

Retell

Give a Retell voice agent a memory of each caller. Retell calls your server when a call comes in, when the agent uses a custom function, and when the call ends. Answer the first with what matters about the caller, the second with a lookup, and save the call at the third. When you place a call yourself, you send what to know with it. The next call starts knowing what was said in this one.

Install

Terminal
pip install fastapi uvicorn retell-sdk geniffy

Set GENIFFY_API_KEY from API keys in the Geniffy app, RETELL_API_KEY to your Retell key, which signs every request Retell sends you, and RETELL_NUMBER to the Retell number your agent calls out from.

Your server

server.py
import asyncio
import json
import logging
import os

from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from geniffy import AsyncGeniffy
from retell import Retell

geniffy = AsyncGeniffy()                          # reads GENIFFY_API_KEY
retell = Retell(api_key=os.environ["RETELL_API_KEY"])
app = FastAPI()
log = logging.getLogger("retell")
OPENING = "A call is starting. What matters about this caller?"
NOTHING = "Nothing is known about this caller yet. If they mention an earlier call, say so rather than guessing."
UNREAD = "This caller's history could not be read just now. If they mention an earlier call, ask rather than guess."
# what Twilio sends in place of a withheld number: ANONYMOUS, RESTRICTED, BLOCKED, UNKNOWN, UNAVAILABLE
WITHHELD = {"266696687", "7378742833", "2562533", "8656696", "86282452253"}


def space_for(number: str | None) -> str | None:
    """The caller, by the digits of their number. None when it is withheld or missing: then nothing is read or
    saved, rather than one memory shared by every unknown caller. If you know callers as customers, use your
    customer id, and the same memory serves their calls, chats and emails."""
    digits = "".join(ch for ch in number or "" if ch.isdigit())
    if not 7 <= len(digits) <= 15 or digits in WITHHELD:
        return None
    return f"user_{digits}"


def customer_number(call: dict) -> str | None:
    """The person on the other end: who called in, or who your agent called."""
    return call.get("to_number") if call.get("direction") == "outbound" else call.get("from_number")


async def signed(request: Request) -> dict:
    """The request, once its X-Retell-Signature shows Retell sent it."""
    body = (await request.body()).decode()
    if not retell.verify(body, api_key=os.environ["RETELL_API_KEY"],
                         signature=request.headers.get("X-Retell-Signature", "")):
        raise HTTPException(401)
    return json.loads(body)


async def known_about(space: str | None, cue: str, budget: int) -> str:
    """The caller's briefing, for the prompt. A call 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=cue, budget_chars=budget), 2) or NOTHING
    except Exception as e:                        # slow or failing: the call goes on without it
        log.warning("no briefing for this call: %r", e)
        return UNREAD


async def save_call(space: str, call_id: str, turns: list[dict]) -> None:
    """The call as one conversation under its own id, so a call sent again is the same source. A call of more
    than 500 turns, the most one add takes, goes in parts."""
    for at in range(0, len(turns), 500):
        await geniffy.space(space).memories.add(messages=turns[at:at + 500], title="Call",
                                                external_id=call_id if at == 0 else f"{call_id}-{at // 500}")


@app.post("/retell/webhook")
async def webhook(request: Request, background: BackgroundTasks):
    event = await signed(request)
    if event.get("event") == "call_inbound":      # a call is coming in: what to know before answering
        caller = space_for((event.get("call_inbound") or {}).get("from_number"))
        return {"call_inbound": {"dynamic_variables": {"memory": await known_about(caller, OPENING, 2500)}}}
    if event.get("event") == "call_ended":        # the call is over: save who said what
        call = event.get("call") or {}
        space = space_for(customer_number(call))
        turns = [{"role": "assistant" if t["role"] == "agent" else "user", "content": t["content"]}
                 for t in call.get("transcript_object") or []
                 if t.get("role") in ("agent", "user") and t.get("content")]
        if space and turns:                       # saved after Retell has its answer, so a slow save is never resent
            background.add_task(save_call, space, f"retell-{call['call_id']}", turns)
    return {}


@app.post("/retell/recall")
async def recall(request: Request):                # the custom function the agent calls mid-call
    payload = await signed(request)
    space = space_for(customer_number(payload.get("call") or {}))
    return {"memory": await known_about(space, (payload.get("args") or {}).get("query") or OPENING, 1500)}


async def place_call(number: str) -> str:
    """A call out that starts knowing the person it calls. Retell's client blocks while it asks, so it runs in a
    thread."""
    memory = await known_about(space_for(number), OPENING, 2500)
    call = await asyncio.to_thread(retell.call.create_phone_call, from_number=os.environ["RETELL_NUMBER"],
                                   to_number=number, retell_llm_dynamic_variables={"memory": memory})
    return call.call_id

Run it with uvicorn server:app, somewhere Retell can reach over HTTPS, and call place_call(number) from your own code to ring someone.

A call coming in, a call you place and the lookup mid-call all read the caller's briefing: where things stand with them, what is due or was promised, what happened on earlier calls, then the facts, each dated. It is read, not written by a model, so it comes back in a fraction of a second, well inside a ringing phone or a pause mid-sentence; past two seconds, the call goes on without it. When something changed between calls (a payment moved from Friday to Monday), the briefing carries the new date, and the old one stays in the memory as history.

The memory is always the customer's: the person who called in, or the person your agent called. A number says which customer is probably calling, not who is: caller ID can be faked. A withheld or missing number gets no memory, and its call is not saved. Before your agent shares anything private from what it remembers, have it confirm who it is speaking with; the production checklist says how.

In Retell

In your agent's prompt, put the memory where you want it:

You are a friendly phone assistant. Keep answers short.

What is known about the caller, found by their number. Before you share anything private from it, confirm who
you are speaking with.
<memory>
{{memory}}
</memory>
  1. On your phone number, set the inbound webhook to https://your-server/retell/webhook. To ring people with place_call, bind your agent to the number for outbound calls too.
  2. On your agent, set the webhook URL to the same address, so it hears when a call ends.
  3. Add a custom function named recall, with one string parameter, query, and the description Look up what is known about the caller, each item dated. Point it at https://your-server/retell/recall.

When nothing is known about a caller, the memory says so in one sentence, and so does recall, so the agent says it doesn't know instead of guessing. Each call is added as one conversation titled Call, under the call's own id, so a call Retell sends twice is saved once. Geniffy keeps who said what, so what the caller said becomes a fact about them, and what your agent said stays the agent's.

Last updated October 17, 2026