Bolna
Give a Bolna voice agent a memory of each caller. Before Bolna answers an incoming call, it can ask your server about the caller; when you place a call yourself, you send what to know with it; and when a call ends, Bolna sends you its transcript. Answer the first two with what matters about the caller, and save the third. The next call starts knowing what was said in this one.
Install
pip install fastapi uvicorn httpx geniffyuv add fastapi uvicorn httpx geniffySet GENIFFY_API_KEY from API keys in the Geniffy app, BOLNA_API_KEY and BOLNA_AGENT_ID from Bolna,
and BOLNA_TOKEN to a long random secret of your own. Bolna sends it with every request, so your server can
tell Bolna's requests from anyone else's.
Your server
import asyncio
import hmac
import logging
import os
import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from geniffy import AsyncGeniffy
geniffy = AsyncGeniffy() # reads GENIFFY_API_KEY
bolna = httpx.AsyncClient(base_url="https://api.bolna.ai",
headers={"Authorization": f"Bearer {os.environ['BOLNA_API_KEY']}"})
TOKEN = os.environ["BOLNA_TOKEN"]
app = FastAPI()
log = logging.getLogger("bolna")
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 check(request: Request) -> None:
"""Bolna sends your token as a bearer token."""
given = request.headers.get("Authorization", "").removeprefix("Bearer ")
if not hmac.compare_digest(given.encode(), TOKEN.encode()):
raise HTTPException(401)
async def known_about(number: str | None) -> str:
"""The briefing on the person on the line. Bolna waits three seconds at most, so this takes two at most."""
space = space_for(number)
if space is None:
return NOTHING
try:
return await asyncio.wait_for(geniffy.space(space).briefing(cue=OPENING, budget_chars=2500), 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.get("/bolna/caller")
async def caller(request: Request, contact_number: str = ""):
"""Bolna asks this before it answers an incoming call; what it returns fills {{memory}} in the prompt."""
check(request)
return {"memory": await known_about(contact_number)}
async def place_call(number: str) -> str:
"""A call out that starts knowing the person it calls."""
r = await bolna.post("/call", json={"agent_id": os.environ["BOLNA_AGENT_ID"], "recipient_phone_number": number,
"user_data": {"memory": await known_about(number)}})
r.raise_for_status()
return r.json()["execution_id"]
@app.post("/bolna/calls")
async def calls(request: Request, background: BackgroundTasks):
"""Each update on a call. The completed one carries the transcript; Bolna can send it more than once, so
it is saved under the call's own id, and a call sent again is the same source."""
check(request)
call = await request.json()
space = space_for(call.get("user_number")) # user_number: the caller, or the person called
if call.get("status") != "completed" or space is None:
return {}
turns: list[dict] = []
for line in (call.get("transcript") or "").splitlines():
role, colon, said = line.partition(":")
if colon and role.strip() in ("assistant", "user"):
turns.append({"role": role.strip(), "content": said.strip()})
elif turns and line.strip(): # a line that carries on what was being said
turns[-1]["content"] += " " + line.strip()
turns = [t for t in turns if t["content"]]
if turns: # saved after Bolna has its answer, so it never waits on the save
background.add_task(save_call, space, f"bolna-{call['id']}", turns)
return {}Run it with uvicorn server:app, somewhere Bolna can reach over HTTPS, and call place_call(number) from
your own code to ring someone.
Bolna waits at most three seconds for an answer about a caller, so the agent is given 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 without a model call, in a fraction of a second, and past two seconds
the call goes on without it. A date that moved between calls is the new date. A call is saved once it is
completed, under its own id, so when Bolna sends the same call again, nothing is learned twice.
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 Bolna
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>- On the agent's Inbound tab, match callers through your own API: the endpoint is
https://your-server/bolna/caller, and the auth token is yourBOLNA_TOKEN. - On the agent's Extractions tab, set the Webhook URL to
https://your-server/bolna/calls. Turn on Add headers and addAuthorizationwith the valueBearerfollowed by yourBOLNA_TOKEN.
When nothing is known about a caller, the memory says so in one sentence, so the agent says it doesn't know
instead of guessing. Each call is added as one conversation titled Call. Geniffy keeps who said what, so what
the caller said becomes a fact about them, and what your agent said stays the agent's.