Installation
pip install pipbit
An agent on the connect transport (see
Connect transport below) installs the
[connect] extra, which adds the websockets
package:
pip install 'pipbit[connect]'
The SDK requires Python 3.9 or later. It installs Flask as a dependency
and provides a lightweight framework for receiving webhook calls from the
Pipbit platform and responding with spoken text. This page documents
pipbit 0.10.0. When you upgrade the package, restart your
serving process — a long-lived worker keeps the old module in memory.
One brand, three hosts: these docs live on pipworks.ai,
your agent calls the API at api.pipbit.ai, and users
confirm account links at verify.pipbit.ai. The PyPI
package is pipbit.
Quick start
from pipbit import Agent
agent = Agent(
name="my-agent", # your lowercase canonical handle (see below)
secret="pb_live_sk_your_secret_here",
base_url="https://api.pipbit.ai",
)
@agent.handle
def handle(req):
if req.is_connect_intro():
# The hand-off arrives as a marker turn (the text is the token
# __pipbit_agent_connected__, never the user's words). Greet here;
# echoing the marker would have the device read the underscores aloud.
return "Hello! I'm your agent. How can I help?"
if req.is_environment_event():
# A subscribed event arrives the same way, with its own marker as
# the text. Say nothing: a deferred turn with no reply.
return req.defer()
return f"You said: {req.text}"
agent.run(host="0.0.0.0", port=3002)
That is the webhook shape: the platform POSTs each turn to your public
HTTPS address. An agent with no public address (a laptop at home) keeps
the same handler and swaps agent.run(...) for
transport="connect" and agent.serve() — see
Connect transport below.
Agent.from_env() builds the same agent from the standard
environment variables PIPBIT_AGENT_NAME,
PIPBIT_AGENT_SECRET, and optionally
PIPBIT_BASE_URL / PIPBIT_API_VERSION /
PIPBIT_TRANSPORT / PIPBIT_CONNECT_URL; extra
keyword arguments pass through.
Registration and the canonical name
Register your agent in the developer portal.
The portal derives a lowercase canonical handle from your
suggested name ("Sonos" becomes sonos) — that handle is your
webhook identity. Users reach your agent by the suggested name or, if you
register one, its trademarked name; the handle itself never changes and is
what your code and the webhook headers use. Your pb_live_sk_... secret is shown exactly
once at creation. Point your webhook URL at the route the SDK serves,
https://your-host/pipbit/agent, over HTTPS. An agent on the
connect transport (beta) has no webhook
URL to set: it dials out to the platform instead.
The handle must match exactly. Every webhook carries
X-Pipbit-Agent set to the lowercase handle, and the SDK
rejects anything not byte-identical to Agent(name=...) —
Agent(name="Sonos") against a registered sonos
fails authentication on every turn.
Webhook protocol
Every turn is a signed POST /pipbit/agent with three headers:
X-Pipbit-Agent: my-agent # your canonical handle
X-Pipbit-Timestamp: 1753212345 # unix seconds
X-Pipbit-Signature: v1=<hex digest>
The signature is HMAC-SHA256, keyed by your agent secret, over the exact
bytes "<timestamp>." + raw_request_body. The SDK verifies
the name, the signature, and a 60-second replay window
before your handler runs — if every webhook 401s with a timestamp error,
check your server's clock sync. To hand-build a signed request in tests,
the SDK exports build_signature and the
PIPBIT_*_HEADER constants.
Connect transport (beta)
Webhooks need a public HTTPS address. Connect is the second transport for the same contract: your agent dials out to the platform over one persistent WebSocket (a two-way connection carried over HTTPS) and receives its turns on it, so a laptop behind a home router can host an agent with no public URL, no TLS certificate and no open port. The handler is the same code — the turn it sees is the webhook body byte for byte.
pip install 'pipbit[connect]'
from pipbit import Agent
agent = Agent(
name="my-agent",
secret="pb_live_sk_your_secret_here",
base_url="https://api.pipbit.ai",
transport="connect",
)
@agent.handle
def handle(req):
if req.is_connect_intro():
return "Hello! I'm your agent. How can I help?"
return f"You said: {req.text}"
agent.serve()
serve() opens the link and blocks until stop()
is called from another thread, or until the platform refuses the link
for good (then it raises ConnectUnavailableError, whose
.reason says why). Programs with their own main loop call
start() and stop() instead.
connection_state() returns the link's state
(connecting, connected,
reconnecting, stopped or failed)
and the platform's last reason.
With Agent.from_env(), set
PIPBIT_TRANSPORT=connect. The socket URL is derived from
PIPBIT_BASE_URL (https://api.pipbit.ai becomes
wss://api.pipbit.ai/v1/connect); set
PIPBIT_CONNECT_URL (or pass connect_url=) only
when it differs.
Connect access is a per-agent grant during the beta. An
admin enables connect_policy for your agent; until then the
first hello is refused with connect_not_enabled and
serve() raises. transport_mismatch means the
agent is registered as a webhook agent.
What connect mode does not have
- No HTTP server:
app()andrun()raiseConfigurationError. -
No public URL and no
/healthroute: readhealth_report()orconnection_state()yourself (a requiredconnect_linkcheck replacesplatform_health). -
No OAuth account linking in this release: the callback needs a public
URL, so
oauth=raisesConfigurationError.
Timing, pushes and reconnects
The platform waits 3 s for the SDK to acknowledge a turn (the SDK does
that on its own, before your handler runs) and then up to 6 s for the
answer: answer inline within those 6 s, or return req.defer()
and call push_reply when the work is done, exactly as over
webhooks. push_reply and push_message ride the
same socket and return the same bodies and raise the same errors as over
HTTPS; a push while the link is down raises
ConnectUnavailableError with reason
not_connected, and nothing is sent.
If the link drops, the SDK dials again on its own after a short random
wait that grows with each failure, up to a minute. If a second copy of
your agent connects, the newer one takes the link and the older one
waits at least 30 s before trying again. When the platform revokes the
link for good (a suspended, unpublished or deleted agent, a rotated
secret, or an operator's explicit revoke) the SDK stops and
serve() raises ConnectUnavailableError with
reason revoked; the platform's finer word rides as
.detail (secret_rotated,
suspended, grant_revoked, ...), and only
secret_rotated is yours to fix — restart with the new
secret. A grant merely switched off by a policy edit is gentler: the SDK
holds off, dials again, and is told connect_not_enabled at
the next hello until an admin re-enables it. The platform can also withdraw a turn your handler is still
working on (the user moved on): req.is_cancelled() turns
True then, and whatever the handler returns afterwards is
dropped.
The shipped hello_world example runs the same handler on
either transport — start it with PIPBIT_TRANSPORT=connect
to watch the link come up. See
Agent Examples.
The Request object
Your handler receives a Request with these fields:
| Field | Type | Description |
|---|---|---|
text | str | The user's utterance (wire field utterance), or the connect-intro marker __pipbit_agent_connected__ on the hand-off turn |
conversation | list | Recent conversation history (role + text pairs) |
subject_id | str | Persistent user identity across sessions |
agent_session_id | str | Current agent session identifier |
device_shadow | dict | Device state snapshot (sensors, network, location) |
device_id | str | Device identifier (always present for environment events) |
handoff_context | str | Free-text context from Pip describing why the user was handed off |
environment_event | dict | Structured event payload (type, data, timestamp) — only for environment events |
manager_name | str | The user's chosen name for their manager assistant (e.g. "Pippa"). Use it in send-offs instead of "the manager". None on older platforms |
reply_token | str | One-shot token for deferred replies via push_reply(); expires about 15 minutes after the turn |
multi_user | bool | True on turns from a device in Family Mode ("Multi-user" in the developer portal): the speaker is an anonymous household member, possibly a child, acting under the owner's subject — avoid personal names and be conservative with account-specific or spending actions. family_mode remains as a read-only alias for one release; the wire field is still named family_mode |
speaker_verified | bool | None | True / False when the bridge judged the voice, None when it sent no verdict. True only when this turn's own voice evidence admitted it; False means a verdict, and it was not the owner's verified voice (see below) |
speaker_basis | str | None | The bridge's one word for why the turn was admitted (see below); None whenever speaker_verified is |
on_wifi | bool | True when the device shadow reports Wi-Fi as the active radio; a missing shadow reads as False |
is_connect_intro() | method | True on the hand-off turn: the text is the marker, never the user's words — greet, do not echo |
is_environment_event() | method | True when the turn is a subscribed environment event; the event itself is in environment_event |
is_cancelled() | method | Connect transport only: True once the platform withdrew the turn (the user moved on) and a reply would no longer be spoken. Always False over webhooks |
defer() | method | Return it to acknowledge the turn now and answer later with push_reply(), or to say nothing at all |
On the wire the user's words arrive in a field named utterance;
the SDK exposes it as req.text.
req.conversation carries the last few turns of the routed
conversation (user turns, and on current platforms your agent's replies
too), but it is short and resets when a new agent session starts — agents
that reason over context should keep their own per-subject_id
history of what they said.
The speaker verdict
Speaker verification is a user-experience filter so your agent can
ignore the neighbour at the café or a voice on the TV; it is never a
security control, so do not gate money or personal data on it.
speaker_verified is True only when this turn's
own voice evidence admitted it, and False on every other
admit — the turn was let through for a reason other than the owner's
verified voice. speaker_basis names that reason with one of
ten words. Two come with True: voiceprint (the
turn's voice matched the owner's stored voiceprint) and
post_wake_trust (it matched closely enough inside the short
trust window a verified or name-addressed turn opens). Eight come with
False: name_addressed,
recent_owner_voice, repeat_grace,
strike_grace, not_armed,
admin_override, multi_user and
abstain. The SDK checks the types only, never the
vocabulary: a word you do not know, from a newer bridge, is legal and
means unverified, so gate on speaker_verified alone. Both
are None when the platform sent no verdict — an older
bridge, an environment event, or a turn that came by Pip's own audio
path ("George, are you there?").
Reply modes
Immediate reply
Return a string from your handler. Pip speaks it immediately.
@agent.handle
def handle(req):
return "Got it, checking now."
Deferred reply
For longer operations, return req.defer() to acknowledge the turn,
then call push_reply() when you have the answer.
@agent.handle
def handle(req):
threading.Thread(target=do_work, args=(req.reply_token, req.text)).start()
return req.defer()
def do_work(reply_token, text):
result = slow_api_call(text)
agent.push_reply(reply_token=reply_token, text=result)
Reply tokens are one-shot: a second push_reply on the same
token is rejected, which makes a network-error retry always safe — if the
first attempt landed, the retry fails instead of speaking twice. A
202 means the platform owns delivery from there: it retries
transient device conditions itself and holds the reply for a quiet moment
rather than talking over the user. Do not re-send after a 202.
Handing back (ending your turn)
When the user is done, send the reply with handback=True.
That reply is your send-off: after it is delivered, control returns to the
user's manager assistant automatically. The platform adds no farewell on
your behalf — say the goodbye yourself (the manager then acknowledges her
return in her own voice). Have your LLM word it for the moment — naming
req.manager_name — rather than using a fixed string. The flag
is omitted from the payload when False, so older platforms
are unaffected.
agent.push_reply(
reply_token=reply_token,
text=send_off, # your LLM's own goodbye, naming req.manager_name
handback=True,
)
Proactive messaging
Send messages to a user outside of an active conversation.
agent.push_message(
text="Your garage door has been open for 30 minutes.",
subject_id="user_abc123",
)
A pushed message is spoken right away when the user has a live session;
when the device is busy the platform retries for about a minute and can
hold it for the next quiet moment. If the user is not around it lands in
the device inbox rather than being spoken later — treat
push_message as "say this now if possible", and do not
blind-retry it (there is no idempotency key).
When the session is gone
If a deferred reply arrives after the conversational moment has passed
(the token expired or is unknown), push_reply raises
SessionGoneError — a subclass of
InvalidRequestError, so existing handlers keep working.
Platform-originated errors also carry .code and
.status_code.
from pipbit import SessionGoneError
try:
agent.push_reply(reply_token=reply_token, text=answer)
except SessionGoneError:
# The moment is gone. If it is still worth saying, queue it:
agent.push_message(subject_id=subject_id, text=answer)
Environment events
Agents can subscribe to real-time environment events (audio scene
classification, sensor data, etc.) by including
event_subscriptions during registration:
{"event_subscriptions": ["audio_scene"]}
Events arrive as normal webhook calls. Detect them with
req.is_environment_event():
@agent.handle
def handle(req):
if req.is_environment_event():
event = req.environment_event
if req.agent_session_id:
return "I heard something." # active session
else:
agent.push_message( # background
text="Alert from my agent.",
device_id=req.device_id,
)
return req.defer()
# ... normal handler
When agent_session_id is present your agent has an active
conversation — reply directly. When it's None the user is
talking to Pip; use push_message() to signal Pip instead.
Health checks
Register health checks so your infrastructure knows if your
agent is ready: while a required check fails, the agent's own
/health endpoint returns 503 — wire it to your load balancer
or monitoring. (The platform does not probe your health endpoint;
webhooks are delivered regardless.)
def check_api_key():
if os.getenv("API_KEY"):
return True, "ok"
return False, "API_KEY not configured"
agent.add_health_check("api_key", check_api_key, required=True)
The built-in checks are a required agent_secret check and,
on the webhook transport, a non-required platform_health
check against the platform's own /health. In connect mode
there is no HTTP server and so no /health route: read
agent.health_report() (or agent.is_ready())
yourself, from your own status page or a supervisor probe. There the
platform_health check is replaced by a required
connect_link check that passes only while the link's state
is connected; its details block says why when
the link is down.
Metrics
The SDK automatically tracks request counts. Access them at
/pipbit/metrics on your agent's server. In connect mode
there is no /metrics route — read
agent.metrics_snapshot() yourself; connect mode adds its own
connect_* counters (turns, reconnects, redeliveries,
cancelled turns, reply and message frames) beside the webhook ones.
Production serving
agent.app() returns a standard Flask WSGI app. The shipped
examples serve it with gunicorn:
# my_agent.py
app = agent.app()
gunicorn my_agent:app --bind 0.0.0.0:3002 --workers 1 --threads 8
Use exactly one worker: in-process state (conversation
history, pending link confirmations, MemoryTokenStore tokens)
is per-process, and extra workers shard it — the agent gets amnesia
between turns. One worker is enough because handlers defer instantly and
do real work on background threads; --threads 8 keeps a slow
in-request path (like the OAuth callback's token exchange) from blocking
the webhook. To scale past one process, move per-user state to shared
storage first. Use /health for load-balancer readiness — it
returns 503 until required checks pass.
Connect mode
Connect mode has no WSGI app to hand to gunicorn: the agent is one
long-lived process that calls agent.serve() (or
start() inside your own main loop) and holds the link. Run
exactly one copy — a second copy under the same agent name supersedes
the first, which then waits 30 s and takes the link back, so two copies
fight over the link instead of sharing the load. Let a supervisor keep
the process up: a systemd unit with Restart=always and
RestartSec=30 is enough, and that pause keeps an agent the
platform keeps refusing under its limit of ten proven hellos a minute.
There is no /health route to point a load balancer at, and
none is needed; readiness is
agent.health_report()["ready"], or more directly
agent.connection_state().state == "connected". A refusal
the platform will not lift makes serve() raise
ConnectUnavailableError; let the process exit non-zero on
it (the hello_world example exits with status 2) and let
the supervisor's restart policy decide how often to try again.