> ## Agent Instructions
> Unmute compiles to exactly four targets. Pipecat and LiveKit are code targets: compile writes a Python project you run. SLNG is a hosted target: compile writes a deployment body and SLNG runs the agent, so it has no `unmute dev`. Twilio compiles to a small Python app that Twilio ConversationRelay calls; you host it, and it has no `unmute dev` either. Those four are the only values `provider` accepts in `targets.yaml`. Deepgram and ElevenLabs appear in these docs as model vendors, which is not the same thing as a target, and `slng` is both.
> The Go structs in `internal/spec` and `internal/ir` are the schema truth. Check a field against them, or run `unmute validate`, rather than against what you remember.
# Reduce context sharing step by step
Source: https://unmute.ai/best-practices/context-scope
Start with conversation continuity, then let each task read only the facts it needs.
Use less context when a task should receive only selected facts, or when old
conversation distracts it from a focused job. Start with the default,
`messages`, and reduce sharing at a boundary only after deciding what the
receiver needs to know.
On this page:
* [Start with messages](#1-start-with-messages) - the default, and why
* [Decide what must survive](#2-decide-what-must-survive) - list the facts needed
* [Save the selected details](#3-save-the-selected-details) - save them in a task
* [Reset the next task](#4-reset-the-next-task-and-name-its-inputs) - and name its inputs
* [Save the outcome](#5-save-the-outcome-and-let-the-owner-read-it) - what the owner reads
* [Apply the same choice to handoffs](#6-apply-the-same-choice-to-handoffs) - one receiving agent
* [Check the helpful and empty case](#7-check-both-the-helpful-and-the-empty-case) - five tests, one trace
* [Other history options](#other-history-options) - `full`, `last_n`, `summary`
The snippets below are additions or updates to an existing package. Merge them
into its current `variables:` and `agents:` blocks.
There are two independent choices:
| Choice | How you control it |
| - | - |
| Earlier conversation | `context.history` on a task or handoff |
| Saved variables | `{{state.variable}}` or `{{state.variable.field}}` in the receiving prompt |
A variable is never added to a prompt automatically. A task with `reset` can
still read the values its prompt names. A task with no placeholders can still
learn facts from the conversation when its history includes messages.
## 1. Start with messages
Omitting `context` or `history` means `messages`. You can write it explicitly:
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: reschedule_booking
when: The caller wants to move a booking.
prompt: tasks/reschedule-booking.md
tools:
- save_booking
context:
history: messages
```
The task receives caller and agent speech, including the request that caused
the task to start. Previous tool calls and replies are removed together.
The receiver uses its own instructions.
This is a good starting point for conversational tasks. The caller can say
"Move my haircut to Friday afternoon" and the task can read that sentence.
Do not reduce history just because the option exists.
## 2. Decide what must survive
Before switching to `reset`, list the facts needed to complete the job. For a
booking change, that might be:
* Which appointment to change.
* The new date and time the caller selected.
* Whether identity verification has already succeeded, if this task needs it.
A spoken request is not a saved value. An earlier task must save those facts
through `save:`, or they must already come from the call's initial values
or prefetch. Describing a variable does not fill it.
Keep requested details separate from the latest successful booking. A failed
move must not overwrite the saved appointment with an unbooked time.
## 3. Save the selected details
This example assumes the selection task has the tools needed to find the
booking and check available times. Add the following fields and `save:` rows
to that task in your package:
```python state.py theme={null}
from datetime import date, time
from pydantic import BaseModel, Field
class State(BaseModel):
appointment_id: str = ""
appointment_date: date | None = Field(
None, description="The requested new date selected for this move."
)
appointment_time: time | None = Field(
None, description="The requested new time selected for this move."
)
```
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: choose_booking
when: Select the existing booking and its requested new time.
prompt: tasks/choose-booking.md
save:
- appointment_id: result.appointment_id
- appointment_date: result.appointment_date
- appointment_time: result.appointment_time
```
```markdown tasks/choose-booking.md theme={null}
Use the caller's request to identify the appointment and check available times.
Ask only for details that are missing. Once the caller selects a new time,
finish with the appointment ID and the selected new date and time.
```
The three fields on `State` provide the finish argument types. The
selection task uses `messages` by default, so it can use "Friday afternoon"
from the caller's request. If several times are available, it asks the caller
to choose before saving an exact `time`.
In the owner's instructions, make the order clear:
```markdown instructions.md theme={null}
For a new request to move a booking, run choose_booking to select its new
date and time. When that task completes, run reschedule_booking.
```
## 4. Reset the next task and name its inputs
Update `reschedule_booking` under the same agent so it runs after selection:
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: reschedule_booking
when: Move the selected appointment after its new date and time are saved.
prompt: tasks/reschedule-booking.md
tools:
- save_booking
context:
history: reset
```
```markdown tasks/reschedule-booking.md theme={null}
Appointment to move: {{state.appointment_id}}
Requested new date: {{state.appointment_date}}
Requested new time: {{state.appointment_time}}
If any value is missing, ask the caller for it. Otherwise use these values.
Confirm the exact change before calling save_booking.
If the requested time is unavailable, ask the caller to choose another time.
After a successful change, finish immediately.
```
The task receives its own prompt with those three values. It receives no
previous messages, tool results, summary, or sentence that triggered it.
There is no automatic request passed by the owner.
For **no prior conversation and no saved values in the prompt**, use `reset`
and omit variable placeholders. The task can collect what it needs from the
caller. Review its tools too: `with:` and tool results are separate ways
data can reach a task's work.
## 5. Save the outcome and let the owner read it
Task history controls what goes **into** the task. On return, the owner gets
its pre-task conversation back plus `completed` or `unserved`. It does not
receive the task's private messages or tool results, even with `messages`.
For continuity after a move, save the successful result separately. Declare
an `Appointment` model in `state.py` with the fields your booking tool returns, as shown in
[Variables](/build/variables#group-fields-into-a-model), and add a field:
```python state.py theme={null}
class State(BaseModel):
appointment: Appointment | None = Field(
None, description="The latest appointment successfully saved by the booking tool."
)
```
```yaml theme={null}
save:
- appointment: result.appointment
```
Add the row to `reschedule_booking` and change its final instruction:
```markdown tasks/reschedule-booking.md theme={null}
After save_booking reports success, copy the saved appointment from its
result and finish immediately with appointment. Do not wait for another
caller request. Let the owner confirm the change.
```
The owner and any later agent that needs the booking should read it:
```markdown instructions.md theme={null}
Latest saved appointment: {{state.appointment}}
When a booking task completes, confirm this appointment once.
Use it instead of older dates mentioned in the conversation.
```
Verification reuses a different mechanism: mark the confirmed variable with
`confirm:` on the verification task, then put that task as a flow step
with `skip_when_confirmed:` naming the variable. The flow skips the step once
it is confirmed, and runs it again once the caller corrects the value. See
[Reuse verification deliberately](/best-practices/state-design#reuse-verification-deliberately).
Finishing with a non-empty `unserved_request` saves nothing. It also
does not undo a booking tool that already succeeded. Finish promptly after
success so a new caller request is handled by the owner, not mistaken for
unfinished booking work.
## 6. Apply the same choice to handoffs
A handoff applies its history choice to the receiving agent:
```yaml agent.yaml theme={null}
agents:
- name: concierge
handoffs:
- name: to_customer_care
to: customer_care
when: The caller needs help with a complaint.
context:
history: reset
```
Put any needed placeholders in `customer_care`'s instructions. For example,
read the latest saved appointment so the caller does not have to identify it
again. An unsaved complaint from the previous conversation will not cross a
reset handoff; save the needed facts first or keep `messages` for that handoff.
There is no automatic return from a handoff. See
[Handoffs](/build/orchestration/handoffs).
## 7. Check both the helpful and the empty case
Validate and compile before testing the conversation:
```sh theme={null}
unmute validate my-agent
unmute compile my-agent --target livekit
unmute dev my-agent --target livekit
```
Try these cases and inspect the model input in your trace:
| Test | Expected result |
| - | - |
| Caller gives the new day before a `messages` task | The task uses that speech without asking for the day again |
| Selection task saves values, then a `reset` task starts | The reset prompt contains the referenced values and no old conversation |
| Caller gives a detail that was never saved before `reset` | The task asks for the missing detail |
| A later agent needs the confirmed number and moved appointment | Its prompt references both, and it uses the latest saved facts |
| A reset prompt references no variables | No saved values are added to its prompt |
The public [salon-concierge example](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge)
uses `messages` for all tasks and handoffs. It shows how explicit saved values
support continuity alongside spoken context.
## Other history options
| Need | Choice | Tradeoff |
| - | - | - |
| Spoken continuity | `messages` (default) | Earlier speech may contain facts you did not reference as variables |
| Previous tool records too | `full` | More context, including older tool results |
| A recent window | `last_n` with `max_messages` | Older requests may fall outside the window |
| No previous conversation | `reset` | Needed facts must be explicitly saved and referenced, or asked again |
| A summary | `summary` with `summarizer`, LiveKit only | Another model request; the summary still shares prior information |
The [context reference](/reference/agent-yaml#context) covers every field and
target restriction. A summary or a short history is not a substitute for
`reset` when the receiver should inherit no conversation.
## Where to go next
Which facts to save, who saves them, and who reads them next.
What to give a task so the model enters it, and what to take off its owner.
Declaring a task, saving its result, and saying what success looks like.
Tasks in a fixed order, and skipping a step whose work is already done.
# Writing prompts for a voice
Source: https://unmute.ai/best-practices/prompt-writing
A text to speech voice reads what you write, exactly as you write it. The rules that follow from that, and the one that a model will read out loud if you break it.
Instructions guide the model; the voice speaks its replies and the configured
greeting. Write instructions that produce clear spoken replies, including
when a task or another agent takes over.
On this page:
* [Write speech, not text](#write-speech-not-text) - the voice reads your formatting
* [Never write a specimen value](#never-write-a-specimen-value) - the worst failure here
* [Say the format, do not show it](#say-the-format-do-not-show-it) - put it in the type
* [Saying a value and confirming one](#saying-a-value-and-confirming-one) - two different lines
* [Name only the values this prompt needs](#name-only-the-values-this-prompt-needs) - every placeholder is a grant
* [Set the spoken language in every role](#set-the-spoken-language-in-every-role) - each prompt that can speak
* [Avoid repeated waiting lines](#avoid-repeated-waiting-lines) - one waiting line per wait
* [Give every realism rule a budget](#give-every-realism-rule-a-budget) - how often, not just how
* [Tell the model to vary](#tell-the-model-to-vary-and-it-will) - openers callers notice
* [Keep the rules load bearing](#keep-the-rules-load-bearing) - prompt rule, or code guard
## Write speech, not text
The voice reads your formatting. Asterisks, bullet points, headings and emoji
all get pronounced or produce strange pauses. So the model's output has to be
plain spoken sentences, and the way to get that is to say so:
```md instructions.md theme={null}
A text to speech voice reads out everything you write, exactly as you write it.
So write speech, not text.
- Whole sentences in ordinary capitalization. No markdown, no asterisks, no
bullet points, no headings, no emoji, no symbols: the voice reads them out
loud.
- Never send a bare fragment. A number or an amount sits inside a sentence.
- Capitals are read letter by letter, so use them only when that is what you
want, like ATM.
- One or two short sentences a turn, one question at a time.
```
Two of those are less obvious than they look. Capitals really are spelled out,
so a prompt that writes a service name in caps gets it spelled. And a bare
fragment is the most common failure in practice: a model answering "what time"
with "11:30." gives the voice nothing to work with, where "Friday at 11:30 AM
works." reads naturally.
## Never write a specimen value
This is the rule with the worst failure, and it looks harmless.
A prompt that explains how to format a phone number and shows an example number
to make the grouping clear has put a number in front of the model. A model
cannot tell an example value from a real one. Before any tool has run, that
example is the only number the model holds, and it may read it out to the
caller as theirs. A caller who hears a confident readback says yes to it.
A model cannot tell an illustration from a value it is holding. Describe the
shape in words instead of showing one.
```md theme={null}
Write a phone number the way it is written on a phone: a plus sign, then the
country code, then the rest in groups of two to four digits.
```
This is also the one way around `confirm:`. The compiler keeps an unconfirmed
value out of every prompt except the step that asks the caller to agree to it,
and a number typed in as an example is not a value the compiler can see. The
protection is real and a hardcoded example defeats it.
The same applies to any identifier a caller might mistake for their own: account
numbers, booking references, addresses, dates of birth.
## Say the format, do not show it
A typed value has one correct spelling and the model needs to know it. Put the
format in the field's description, where it travels with the value into every
schema the model sees:
```python state.py theme={null}
class State(BaseModel):
scheduled_time: time | None = Field(
None, description="The time the caller agreed to, on the 24-hour clock, like 09:30 or 17:45."
)
```
Pydantic checks the value where it is saved, but the model only learns the
spelling from your description.
Without it, a model sends the spelling its own prompt requires out loud. A
task told to say times as "11:30 AM" to the caller will send `"11:30 AM"` to a
field that wants `11:30`. The `finish` call is refused, the model corrects
itself on the next request, and the caller hears a pause for no reason.
Say the format once, in the type. A prompt that repeats it can drift from the
validator, and then the two tell the model different things.
## Saying a value and confirming one
Ordinary speech carries a value once. Confirming it is the moment the caller
has to hear every character. Those are two lines, and a prompt that writes one
of them gets one shape used for both.
```md instructions.md theme={null}
Say an email address the ordinary way, all one piece, when you first mention
it. When you read one back to confirm it, delimit the part before the at sign
so each character is heard on its own, then say the at sign and the domain as
ordinary words. Say a reference number normally, and confirm it in the groups
it is written in. Wait for a yes before acting on a confirmed value, and
confirm it again after any correction.
```
The rule is delimiting, not spelling. Never write "spell it letter by letter":
that makes the model do its own preprocessing, and it loses to the voice's.
`A B C` is the instruction. A phone number is the exception: it stays in its
written form even when it is confirmed, because commas inside a run of digits
break it.
## Name only the values this prompt needs
Saved values reach a prompt only through placeholders you write. Keep those
references close to the instruction that uses them:
```md theme={null}
Move appointment {{state.appointment_id}} to {{state.appointment_date}} at
{{state.appointment_time}}.
```
Choose who confirms success. A simple pattern is for the task to finish
immediately after the tool succeeds and for the owner to confirm once:
```markdown tasks/booking.md theme={null}
After the booking tool reports success, finish with the saved appointment.
Let the owner confirm it to the caller.
```
```markdown instructions.md theme={null}
Latest saved appointment: {{state.appointment}}
When the booking task completes, confirm this appointment once in plain speech.
```
The owner needs the placeholder because a task's private conversation does
not return with its completion status.
Do not add saved values just because they exist. Every placeholder is an
intentional context grant to that prompt.
## Set the spoken language in every role
Set the listening and speaking model language, then put the desired language
in every agent and task prompt that can speak:
```markdown theme={null}
Speak English throughout the call, including phone-number readback and
confirmation. Use short spoken sentences without Markdown formatting.
```
The speech model's `language: en` setting does not by itself tell the thinking
model which language to write. A phone number's country code should not decide
the conversation language. A receiving task or agent has its own instructions,
so it needs the language rule too.
## Avoid repeated waiting lines
A tool's or task's `start: say:` and a handoff's `say:` are optional lines. Omit them when
there is no useful wait to explain. If you use one, tell the model to let that
line cover the wait and avoid another "let me check" before or after it.
Check adjacent steps as well. A tool line followed by a task
line can sound like repetition even when each is short.
## Give every realism rule a budget
Filler words, restarts and hesitations make an agent sound human in the right
quantity, and obviously synthetic in any other. A rule that says how to do one
and not how often gets it on every turn.
So write the frequency into the rule, and show plain speech as the good line:
```md instructions.md theme={null}
Most turns carry no filler at all. Plain, direct speech is the default, and
several turns in a row without any is right. At most one filler in a turn,
never two in a sentence, and never a run like "yeah, um, so". Once or twice in
a whole call, a better phrasing can land mid sentence: drop the first one and
carry on, without apologising. Every other turn comes out whole.
```
An example outweighs the sentence under it. A prompt showing "Yeah, um, so, I
can do that." as the good line produces that opener nearly every turn, whatever
a caveat below it says. Demote the stacked form to the bad example instead.
## Tell the model to vary, and it will
Repetition is the thing callers notice first and the easiest to fix. A prompt
that only says what to do produces the same opener every turn.
```md theme={null}
Vary your opener, and never open two turns in a row the same way. "Right, ...",
"Okay, so ...", "Mhm, ...", "Ah, ...", or no opener at all.
```
For a missed reply, ask plainly: "I missed that, could you say it again?"
Use a waiting line only when it helps the caller understand a noticeable pause.
What to leave out: apologies for the process, thanking the caller for their
patience, and "I completely understand". They read as polite and land as filler.
## Keep the rules load bearing
A prompt grows every time something goes wrong on a call, and an agent whose
prompt has accumulated forty rules starts obeying the wrong ones. One package's
prompts reached seven hundred lines and the agent's behaviour got worse, not
better, because the two rules that mattered were buried in thirty that recorded
past incidents.
When you fix something with a prompt rule, check whether it can be a code guard
instead. A duplicate entry, a missing field, a value in the wrong format: those
are guards. They run every time, and they cost no tokens on any turn.
Keep the rule in the prompt when it is genuinely a judgment call, and delete the
archaeology.
## Where the mechanics live
What to declare, and why an empty value has to read as words.
Vendors, models and the settings that change how a voice sounds.
# Designing declared state
Source: https://unmute.ai/best-practices/state-design
Choose facts that help the next task, keep requested changes separate from saved outcomes, and avoid repeated questions.
Add a field to `State` in `state.py` when another part of the call needs a reliable fact.
Then reference it only in the prompts or tools that need it. Keeping a value
in call state does not put it in every model request.
On this page:
* [One saved fact, end to end](#one-saved-fact-end-to-end) - declare, save, read
* [Start with the next reader](#start-with-the-next-reader) - who needs this value
* [Separate a request from an outcome](#separate-a-request-from-an-outcome) - asked for, not booked
* [Group fields that describe one result](#group-fields-that-describe-one-result) - when to use a model
* [Match the type to the actual value](#match-the-type-to-the-actual-value) - what your tools return
* [Choose a current value or a list](#choose-a-current-value-or-a-list) - latest record, or every one
* [Finish as soon as the work succeeds](#finish-as-soon-as-the-work-succeeds) - save, then finish at once
* [Reuse verification deliberately](#reuse-verification-deliberately) - and what confirmed means
* [Write for a missing value](#write-for-a-missing-value) - write for the empty case
* [Check the whole path](#check-the-whole-path) - both prompts, then a trace
## One saved fact, end to end
Every saved fact has the same three parts. Declare it, save it in the step
that learns it, and read it in the prompt that needs it:
```python state.py theme={null}
class State(BaseModel):
appointment: Appointment | None = Field(
None, description="The latest booking successfully saved by the booking task."
)
```
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: manage_booking
when: The caller wants to book, move, or cancel an appointment.
prompt: tasks/booking.md
save:
- appointment: result.appointment
```
```markdown instructions.md theme={null}
Latest saved appointment: {{state.appointment}}
Use it when the caller refers to a booking just made.
```
```sh theme={null}
unmute validate my-agent
```
The rest of this page is how to choose those three parts: what to declare,
who saves it, and who reads it next.
## Start with the next reader
For each value, identify who saves it and who needs it later:
| Value | Who saves it | Who reads it |
| - | - | - |
| A confirmed phone number | The verification task, through `confirm:` | `skip_when_confirmed:` on a flow step, so a second booking skips verification |
| Requested new booking time | The selection task | A reset task that performs the move |
| Successfully saved appointment | The booking task | The owner and customer care |
| A caller's preferred contact channel | The intake task | Any later task that has to reach them |
If nothing reads a value, you probably do not need it. If a later prompt needs
it, add the placeholder there. A description alone does not share the value.
## Separate a request from an outcome
A caller asking for Friday does not mean Friday is booked. Keep the requested
date separate from the successfully saved appointment. Update the saved
appointment only after the booking tool reports success.
This prevents a failed change from looking like a confirmed booking. It also
gives later tasks a clear answer when the conversation mentions both the old
and new times.
## Group fields that describe one result
Start with separate variables for independent facts, such as a caller's name
and preferred language. Use a model when the fields describe the same record
and should be saved together.
For a booking flow:
1. Look at the successful booking tool result. Identify the fields later
tasks need, such as its ID, service, date, and time.
2. Declare an `Appointment` model in `state.py` with those fields. Use `str`
for the booking ID, with a pattern only if the real ID always fits it, and
`date` and `time` for the saved time.
3. Add `appointment: Appointment | None = None` to `State`. Give it a
description such as "The latest appointment successfully saved by the
booking tool."
4. Save `appointment: result.appointment` in the booking task. Tell the task
to copy the successful result and finish immediately.
5. Reference `{{state.appointment}}` in the owner, or just `{{state.appointment.date}}`
in a prompt that needs only the date.
This keeps the booking ID and its current time together. Do not add unrelated
caller details to the model just because the booking task can see them.
The [Variables guide](/build/variables#group-fields-into-a-model)
shows the model and its field descriptions.
## Match the type to the actual value
Use a model for fields that belong together. Include fields your tools return
or the caller can supply. Do not require an ID that no tool produces.
Use `T | None = None` when a successful result may legitimately have no value.
A field with a pattern cannot be replaced by an empty string just to finish
the task. When a step may finish without a value, mark it in `save:` with
`?` after the result field, as `- callback_time: result.callback_time?`.
Otherwise the step must return every whole value it saves.
An external identifier may need a plain `str`. For example, a booking slot
containing `|` does not fit an identifier pattern. Preserve the exact value the
tool returned. The [reference](/reference/variables#what-a-field-can-be) lists
the types and their limits.
## Choose a current value or a list
Use one model-typed field for the latest successful appointment. Replacing it
makes the new date the current one.
Use a list when later tasks need several records. Append with `+`:
```yaml theme={null}
save:
- notes+: result.note
```
This needs a field declared as `list[str]`, or `list[Note]` for a model.
An identical structured item is not added twice. A changed item is added
separately; append does not find and replace an earlier record with the same
ID. Plain values may repeat.
## Finish as soon as the work succeeds
A task that performs an action and then waits for another caller turn can
accidentally absorb a new request. For example, a booking task might complete
a move, hear a complaint, and return `unserved` instead of saving the move.
Write the task prompt to save the successful result and make the `finish` call
immediately. Let the owner read the saved value and confirm it once. For a task
designed to save one record, finish after that record; run it again for another
request.
Better still, when the task's last action is a tool, give that tool an entry
under the step's `tools:` with an outcome that says `then: done`. The task then
ends on the tool's success result by itself, saves its `save:` rows from that
result, and the model never has to decide that the work is done. See
[Say what success looks like](/build/orchestration/tasks#say-what-success-looks-like).
A non-empty `unserved_request` saves nothing and returns only a status.
It does not undo an action already completed by a tool.
## Reuse verification deliberately
When verification is the first step of a flow, declare the skip rather
than asking a prompt to remember it. Put `skip_when_confirmed:` on that step,
naming the variable the step confirms. The flow then skips the step when
that variable is confirmed at the moment the flow starts, and runs it
otherwise. See
[Skip a step whose work is already done](/build/orchestration/task-groups#skip-a-step-whose-work-is-already-done).
Confirmed here is a real mark on the variable, set by `confirm:` alone: when
the task it names saves the value, and cleared by any other write. A prompt
sentence saying the caller was verified is not that mark, and neither is a
separate status variable a task saves on success. Do not also keep a
separate status variable for this: once the flow reads the confirm mark
itself, nothing needs a second copy of the same fact.
Use [`confirm:`](/build/prefetch#always-check-a-value-with-the-caller) for a
candidate value that must be checked with the caller. When that candidate
changes, prefetched values derived from the old candidate are cleared, and
the flow runs the confirming step again on its own.
## Write for a missing value
Prefer a label and a clear fallback:
```markdown theme={null}
Latest saved appointment: {{state.appointment}}
Use it to identify the booking the caller just made. If no appointment is
recorded, ask which booking they mean and look it up.
```
An unset value renders as `none recorded yet.` An empty list renders as `[]`.
Neither proves that your booking system has no records; it means the call
has not saved that information.
## Check the whole path
Read the task prompt and the owner's prompt together. Check who asks the
question, who saves the answer, and who speaks after completion. Then inspect
a trace to confirm that each receiving prompt contains the facts it needs.
## Where to go next
A practical walkthrough, one boundary at a time.
Task structure and tool placement, so the step gets entered.
How to declare a value, a model, and a list in `state.py`.
Reading a trace to see which saved value each prompt received.
# Making a task actually run
Source: https://unmute.ai/best-practices/step-scoping
A task the model can skip is a task that never writes a saved value. What to give a task so it gets entered, and what to take away from its owner.
A task is worth having when it does something its owner cannot do as well: a
narrower prompt, a smaller context, a typed result that lands in a saved
value. None of that happens if the model never enters it.
The model does not read your intent. To the model, a task is one more entry in
its function list, next to the owner's own tools, and it picks. These are the
rules that decide which way it picks.
On this page:
* [Give the task a tool the owner does not have](#give-the-task-a-tool-the-owner-does-not-have) - the one that decides entry
* [Order steps with the prompt](#order-steps-with-the-prompt) - two sentences, no gate
* [Keep a read on the owner](#keep-a-read-on-the-owner-keep-the-write-on-the-task) - and the write on the task
* [Let the tool end the task](#let-the-tool-end-the-task) - an outcome with `then: done`
* [Scope history down](#scope-history-down-and-let-saved-values-carry-the-facts) - what each scope shows
* [Give every task an escape](#give-every-task-an-escape-and-read-it) - `unserved_request`, and reading it
* [Do not let two prompts disagree](#do-not-let-two-prompts-disagree) - owner and task together
## Give the task a tool the owner does not have
If the owner already holds every tool the task holds, the owner can finish the
job without entering the task. It usually will. The task's `save:` then never
runs and nothing is saved.
This is the shape that produces it. A scheduling desk declared:
```yaml agent.yaml theme={null}
scheduling_desk:
tools:
- look_up_hours
- book_appointment # also the task's only tool
tasks:
- name: take_booking
tools:
- book_appointment
save:
- appointment: result.appointment
```
The desk books the appointment itself, because the tool is in its own list,
and `appointment` stays empty. The prompt is not the fix. A workflow that says
"then run the booking task in the same turn" is a request to the model, and a
tool within reach beats a request.
The fix is to take the tool off the owner and leave it on the task:
```yaml agent.yaml theme={null}
scheduling_desk:
tools:
- look_up_hours
tasks:
- name: take_booking
tools:
- book_appointment
```
`unmute validate` warns when an agent holds every tool of one of its tasks, and
names the tool to move. It is a warning and not a refusal because whether the
model takes the short route depends on your prompt and your `when:`, neither of
which the compiler reads. Read the warning and decide.
A task that declares no tools at all is fine. Its prompt, context choice, and
saved values are reasons to enter it that have nothing to do with tools.
## Order steps with the prompt
Step here means a task an agent runs on its own. Two tasks that must hold
their order every time belong in a [flow](/build/orchestration/task-groups),
which runs its steps in the order you list them. This section is for the
looser case: a task that usually follows another one.
A task that must run only after another one does not need a code gate for
that. It needs two sentences: one in the owner's own instructions, and one in
the task's own `when:`.
Number the flow in the owner's instructions, in the order the caller actually
moves through it:
```md instructions.md theme={null}
1. Confirm who is calling.
2. Take the booking request.
3. Hand a complaint to customer care.
```
Then give the later task a `when:` that names the situation and, in one
clause, what has to be true first:
```yaml agent.yaml theme={null}
- name: manage_booking
when: The caller wants to book, move, or cancel an appointment, once the caller is verified.
```
The model has something real to check that clause against when the owner's
prompt names the value the earlier task saved:
```md instructions.md theme={null}
The verified customer is {{state.customer_id}}. Once that value is present, verification has already
succeeded. Never run that task again unless the caller says the number is wrong.
```
A tool that silently reads a value, through `with:` or a webhook path, still
refuses to run while that value is empty or unconfirmed. The model is told
which task supplies it. When nothing supplies it, the model is told to ask the
caller.
Check the order with a scripted text conversation before you check it on the
phone. It drives the agent through a fixed script with the real model and the
real tools, so you see which task ran, and in what order, without picking up a
phone. See
[`scripts/text_run_livekit.py`](https://github.com/slng-ai/unmute/blob/main/scripts/text_run_livekit.py).
## Keep a read on the owner, keep the write on the task
The rule above has a natural shape once you apply it. Lookups that answer
questions belong on the owner, because the caller can ask at any time and
entering a task to answer a price question is slow. Anything that records,
saves, or changes something belongs on the task, alone, because that is the
action whose result you want saved.
Split that way, the model has a real reason to enter: the task holds the only
route to the thing the caller is asking for.
## Let the tool end the task
When a task's work ends on one tool, give that tool an entry in the step's
`tools:` with an outcome that says `then: done`. The task then ends on the
tool's own success result, saves its `save:` rows from that result, and never
waits for the model to end the step. A result no outcome matches goes back to
the model and the task stays open.
```yaml agent.yaml theme={null}
- name: take_booking
tools:
- name: book_appointment
outcomes:
- if:
- status: booked
then: done
save:
- appointment: result.appointment
```
The `if:` names a field of the tool's `output:`, and the tool has to return
what `save:` reads. See
[Say what success looks like](/build/orchestration/tasks#say-what-success-looks-like).
## Scope history down and let saved values carry the facts
A task may not need the transcript if its prompt names every fact it needs.
Start with `messages`. Use `reset` only when the saved inputs cover the job;
otherwise the caller will have to repeat details that were only spoken.
| Scope | What the task sees | Use it when |
| - | - | - |
| `messages` | What was said, without tool traffic | The default for normal continuity |
| `full` | Speech and paired tool records, without old instructions | The task needs earlier tool results |
| `reset` | Its own prompt and the saved values that prompt names | The package intentionally declares every fact the task needs |
`reset` is the strongest scope. A reset task never receives the turn that
triggered it. Save a fact before the boundary and reference it in the reset
prompt when the receiver needs it. If the fact was only spoken and never saved,
the reset task asks for it again.
## Give every task an escape, and read it
A task offers its own tools, its declared handoffs, and the `finish` call. When
the caller asks for something none of those cover, a task with no way out
refuses, the caller presses, and it refuses again.
Every generated task carries a reserved `unserved_request` field for this. The
task does its own work, then names the request it could not serve in its own
words, and makes the `finish` call. You do not write that rule yourself: the
compiler appends it to every task prompt.
The owner receives only an `unserved` status, not the private request text. It
asks what the caller needs and handles the new request with its own tools or
handoffs:
```md theme={null}
When a task returns unserved, ask the caller what they need and help with the
tools or handoffs available here.
```
## Do not let two prompts disagree
A task's prompt and its owner's prompt are written at different times and read
together. When they disagree, the model picks one, and you cannot tell which.
The pairing that bites most often is "do not run the same task again for a
request that just finished" on one side and "act on the unserved request" on
the other. A second booking is a new request, not a repeat of the last one, but
nothing says so unless you write it.
When you add a rule to a task, read the owner's prompt in the same sitting and
check it still agrees.
## Where the mechanics live
Declaring a task, its saved values, and what success looks like.
Tasks in a fixed order, and skipping a step whose work is already done.
What to save, and who reads it next.
What each scope costs, and what has to travel as a saved value.
# Checking what the agent did
Source: https://unmute.ai/best-practices/verifying-behaviour
A transcript tells you what the caller heard. It does not tell you what the agent recorded, and the two disagree more often than you would expect.
Checking an agent means reading what the call actually did: which steps
finished, which tools ran, and which saved values each prompt received.
An agent can hold a good conversation and record nothing. It can also record
correctly and sound broken. The transcript only shows you one of those, so
reading it is not checking.
On this page:
* [Read the trace, not the transcript](#read-the-trace-not-the-transcript) - what a transcript hides
* [Check scoping by reading the prompt](#check-scoping-by-reading-the-prompt-that-was-sent) - verifying a negative
* [Read requests in time order](#read-requests-in-time-order) - when a value was saved
* [Count tool spans, not call rows](#count-tool-spans-not-call-rows) - what ran, not what was asked
* [Find the layer the defect lives in](#find-the-layer-the-defect-lives-in) - the smallest layer that shows it
* [Do not conclude from one call](#do-not-conclude-from-one-call) - three calls, or one
* [Read the call back yourself](#read-the-call-back-yourself) - not somebody's description
## Read the trace, not the transcript
A call that reads well can still have written nothing to declared state. The
case that shows why: an agent booked two appointments, and when the caller asked
for a recap it named both correctly. That looked like proof the state was right.
It was not. The agent could have read either an explicit saved-value
placeholder or the conversation, and from the transcript alone there is no way
to tell which.
What settles it is the rendered prompt. With tracing enabled, each model request
shows which saved values its authored placeholders rendered:
```text theme={null}
Review these appointments with the caller:
[{"scheduled_date":"2026-09-05","scheduled_time":"15:00", ...},
{"scheduled_date":"2026-09-06","scheduled_time":"09:00", ...}]
```
Now you know. Two appointments, distinct, and nothing recorded against
complaints on a call where a complaint was discussed, which is a defect the
transcript hid completely.
## Check scoping by reading the prompt that was sent
The same technique is the only real check on context scoping and on `confirm:`.
Both are promises about what a given prompt does not contain, and the only place
to verify a negative is the prompt itself.
Read each complete model request and compare it. A candidate marked `confirm:`
should render only in the confirming task's prompt until that task saves
agreement. It should be absent from other prompt and router payloads.
## Read requests in time order
Do not collapse repeated model requests. A saved value may be absent before a
task finishes and present afterwards. Listing each request in order shows when
the value was saved and exactly which prompt received it through a placeholder.
## Count tool spans, not call rows
A trace shows both what the model asked for and what ran, and they are not the
same number. A model can emit the same tool call twice in one turn, and the
framework may execute it once.
Count the spans named after the tool. Two call rows and one tool span is one
execution. Two of each is two, and if both wrote something you have a duplicate
to explain.
The step's finish is the useful one. A step that never reaches its finish never
wrote to declared state, whatever else it did, so a missing finish span explains
an empty variable immediately.
## Find the layer the defect lives in
Reproduce a defect in the smallest layer that shows it. A provider rejecting a
schema is one HTTP request, so it needs no audio, no tunnel and no caller. A
prompt that reads badly needs a conversation. A carrier problem needs a real
phone.
Working in the wrong layer is what makes debugging slow. Half an hour of calls
to diagnose something a single request would have shown in seconds is a common
way to spend an afternoon.
## Do not conclude from one call
Two identical builds produce noticeably different calls. Timing, wording, and
which of several valid routes the model takes all vary run to run.
For anything about latency or about how often a behaviour happens, run three
calls before you believe a number. For a defect that is a hard failure, such as
a refused schema or a step that never runs, one call is enough, because the
mechanism is the evidence and not the frequency.
## Read the call back yourself
After somebody talks to the agent, read the call back rather than working from
what they tell you. What was said, which tools ran, which steps finished, and
where the time went are all in the trace, and a description of a call leaves out
the parts nobody heard.
The two questions worth asking of every call: did every step that should have
run reach its finish, and did each explicit placeholder render the saved value
the caller was told. A gap in either one is a defect the conversation did not
reveal.
## Where the mechanics live
Running a package in the browser, and seeding a call source.
Turning on tracing, and what each provider gives you.
# Cascade
Source: https://unmute.ai/build/architecture/cascade
Build an agent with separate listening, reasoning, and speaking models, then extend it with tasks and state.
Use separate models to choose how your agent hears a caller and speaks its answer.
In a cascade, transcription produces text, a reasoning model answers, and a synthesizer speaks.
Turn detection decides when to start the reply. Streaming lets some stages overlap.
On this page:
* [Quickstart](#quickstart) - a complete voice desk
* [Pros and cons](#pros-and-cons) - control and complexity
* [Bind the models](#1-bind-the-three-models) - one job per entry
* [Choose the turn](#2-choose-when-the-agent-replies) - defaults and selectors
* [Extend the desk](#3-add-tools-tasks-or-saved-state) - grow the workflow
* [Advanced](#advanced) - switch architecture
* [Troubleshooting](#troubleshooting) - correct common failures
* [Where to go next](#where-to-go-next) - model references
## Quickstart
Create a new package with a LiveKit target. If initialization opens the console, select LiveKit and finish creating the package.
```sh Terminal theme={null}
unmute init voice-desk
```
Replace `voice-desk/agent.yaml` with this **complete file**:
```yaml voice-desk/agent.yaml theme={null}
name: voice-desk
architecture: cascade
entry_agent: desk
secrets:
- OPENAI_API_KEY
- SLNG_API_KEY
models:
turn:
detector:
provider: livekit
model: turn-detector-mini
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
think:
reasoning:
provider: openai
model: gpt-5.6-terra
params:
reasoning_effort: none
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: aura-2-thalia-en
agents:
- name: desk
prompt: instructions.md
think: reasoning
speak: voice
```
`channels:` and `capacity:` live in targets.yaml. Set them at the top of the scaffold's file:
```yaml targets.yaml theme={null}
channels:
- name: web
kind: realtime_audio
capacity:
peak_sessions: 1
max_sessions: 2
avg_session_duration: 3m
```
Keep the scaffold's `state.py` as it is. The package needs it, and this desk saves no values.
Keep the scaffold's `targets.yaml`, but remove its target-level `models:` overrides because the model palette above replaces the scaffold's.
Keep its framework provider and version pin, and remove any phone `connection:` for this browser example. Replace `voice-desk/instructions.md` with this complete prompt:
```markdown voice-desk/instructions.md theme={null}
You are a friendly information desk. Answer in short spoken sentences.
Ask one question at a time. If you do not know an answer, say so.
```
Set `OPENAI_API_KEY` and `SLNG_API_KEY` in your shell or the package's `.env`, then run:
```sh Terminal theme={null}
unmute validate voice-desk
unmute compile voice-desk
unmute dev voice-desk --target livekit
```
Use Docker for this LiveKit run. The [Pipecat target](/targets/pipecat) is another option; it runs locally with `uv`.
The example below stays with this same `desk` agent.
## Pros and cons
### Pros
* **Control the workflow.** On LiveKit and Pipecat, combine tasks, handoffs, saved values, and tool calls. Each step can have its own instructions and access to the values it needs.
* **Choose each role.** Use a supported transcriber, reasoning model, and voice independently. Spend more on the part that needs better quality without replacing the others.
* **Find the failing stage.** Compare the recognized text, model reply, tool result, and spoken output. A wrong transcription needs a different fix from a failed tool.
### Cons
* **More sources of delay.** Turn detection, transcription, reasoning, speech generation, and tools all contribute. Streaming reduces the wait, but does not remove those costs.
* **More parts to operate.** Several integrations bring separate credentials, availability limits, and failure modes.
* **Less audio context for reasoning.** A transcript carries the words, but can lose tone, hesitation, and other clues in the caller's voice.
[LiveKit's comparison](https://livekit.com/blog/realtime-vs-cascade) explains these
component tradeoffs. [Coval's comparison](https://www.coval.ai/blog/speech-to-speech-vs-cascaded-voice-ai-which-architecture-should-you-deploy/)
shows why control and diagnosis matter when the agent must complete real work.
## 1. Bind the three models
The quickstart names the transcriber, reasoning model, and voice under `models`.
The agent binds its reasoning and voice by name. A single transcriber is selected automatically for the package; a top-level `listen:` names one when there are several.
Set `cascade`, or omit the key for the same result. Cascade is supported on all four targets, subject to each target's model and feature limits. It is the only architecture the Twilio target takes.
Agent-level reasoning binding, such as `agents.desk.think: reasoning`.
Agent-level voice binding, such as `agents.desk.speak: voice`.
Agent-level transcriber, for an agent that speaks another language. Omit it to use the package's: the top-level `listen:`, or the only `models.listen` entry. When every cascaded agent names its own, no top-level `listen:` is needed. Cascaded agents only, and its entry takes no `fallback:`. The slng and twilio targets refuse one that differs from the package's. On livekit and pipecat each agent speaks and listens with its own models after a handoff.
| Role | Where to configure it |
| - | - |
| Listening | [Transcription](/models/stt) |
| Reasoning | [Reasoning models](/models/llm) |
| Speaking | [Voices](/models/tts) |
A model name is forwarded to its provider. Validation checks the binding, not whether your account can use that model.
## 2. Choose when the agent replies
The quickstart binds LiveKit’s local turn detector. A cascade needs a turn binding.
When adding Pipecat, override `detector` for that target with `provider: local` and `model: silero`.
Follow [Turn detection](/models/turn-detection) for the target override shape and timing options.
Package-level selector. One turn entry is selected automatically. With several entries, name the one to use here.
Listen for pauses and interruptions before changing settings.
A shorter silence window can answer faster but may cut off callers who pause mid-sentence.
## 3. Add tools, tasks, or saved state
Extend the same desk with a [local tool](/build/tools/python) whose Python function has typed arguments and a Pydantic return model, then add a [task](/build/orchestration/tasks) when a job needs its own steps.
For example, the caller wants to change an existing request:
1. Look up the request with a tool.
2. Collect the change in a task and save its result.
3. Confirm the details before running the update tool.
4. Handle a refused update, or hand the call to another agent with the context it needs.
The call's `State` class in `state.py` holds values across steps. Each prompt names the values it may read; the tool checks the conditions for changing the record.
Separate steps give you places to check the behavior, but do not guarantee a correct tool call.
Test successful updates, missing inputs, and failed actions.
Tasks, flows, and handoffs are supported on LiveKit and Pipecat cascade targets.
SLNG has its own [target limits](/targets/slng#what-a-slng-package-may-not-ask-for).
Both S2S architectures support tools, but their current Unmute integrations do not support these task and state controls.
The complete [salon concierge](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge) shows booking, task return, and handoff.
Its phone routes and tracing need their own configuration and credentials.
## Advanced
Transcription can run while the caller speaks, and synthesis can begin while the model generates text.
Do not add all stage durations as though every stage waits for the previous one to finish.
Model choice, turn timing, network placement, and tools affect the wait for the first audio.
Tune the slow stage before replacing the architecture, and compare completed actions as well as response time.
See [where the time goes](/optimization/latency#where-the-time-goes) and the [architecture comparison](/build/architecture/overview#pros-and-cons).
Follow [Switch architecture](/build/architecture/overview#3-replace-the-models-and-agent-bindings).
Replace the model palette and the agent's `think:`/`speak:` bindings together.
Remove old target overrides and any features the destination refuses.
Use the quickstart's complete `agent.yaml` for a minimal cascade, keeping your prompt file.
For an existing package, copy its model palette and `think:`/`speak:` bindings instead, and add the required provider secrets.
Remove `models.live`, `models.realtime`, and the old agent binding before validating.
Do not replace a larger package's whole file if you need to retain its tools or workflow.
## Troubleshooting
### Validation rejects an agent-level listen field
Listening is selected for the package, not for each agent.
**Fix:** move the selector to the top level, or omit it when only one transcriber exists.
### The agent waits too long or cuts callers off
Turn settings or provider latency may be responsible.
**Fix:** inspect the dev measurements and follow [Turn taking](/optimization/turn-taking) before replacing all three models.
### A provider is refused for one role
Targets support different providers for each role.
**Fix:** choose a supported integration from that role's reference, then validate every declared target.
## Where to go next
Give one job its own workflow.Compare and switch pipelines.
# Live
Source: https://unmute.ai/build/architecture/live
Run an OpenAI live voice agent and give it a reasoning backend for tools and knowledge.
Let a live voice model hold the conversation while a reasoning backend handles its tools.
`models.live` names the voice model; `backend:` points to an OpenAI entry in `models.think`.
The live model decides when to speak and how to respond to interruptions.
On this page:
* [Quickstart](#quickstart) - a complete live agent
* [Pros and cons](#pros-and-cons) - strengths and limits
* [Bind the voice](#1-bind-the-live-model) - select the model
* [Attach tools](#2-give-the-backend-a-tool) - let it do useful work
* [Try the conversation](#3-try-tools-and-knowledge-in-a-call) - verify the result
* [Advanced](#advanced) - defaults and limits
* [Troubleshooting](#troubleshooting) - fix setup and call failures
* [Where to go next](#where-to-go-next) - references and alternatives
## Quickstart
Create a new package with a LiveKit target. If initialization opens the console, select LiveKit and finish creating the package.
```sh Terminal theme={null}
unmute init voice-desk
```
Replace `voice-desk/agent.yaml` with this **complete file**:
```yaml voice-desk/agent.yaml theme={null}
name: voice-desk
architecture: live
entry_agent: desk
secrets:
- OPENAI_API_KEY
models:
live:
- name: voice
provider: openai
model: gpt-live-1
voice: marin
backend: reasoning
think:
reasoning:
provider: openai
model: gpt-5.6-terra
agents:
- name: desk
prompt: instructions.md
live: voice
```
`channels:` and `capacity:` live in targets.yaml. Set them at the top of the scaffold's file:
```yaml targets.yaml theme={null}
channels:
- name: web
kind: realtime_audio
capacity:
peak_sessions: 1
max_sessions: 2
avg_session_duration: 3m
```
Keep the scaffold's `state.py` as it is. The package needs it, and this desk saves no values.
Keep the scaffold's `targets.yaml`, but remove its target-level `models:` overrides because the model palette above replaces the scaffold's.
Keep its framework provider and version pin, and remove any phone `connection:` for this browser example. Replace `voice-desk/instructions.md` with this complete prompt:
```markdown voice-desk/instructions.md theme={null}
You are a friendly information desk. Answer in short spoken sentences.
Ask one question at a time. If you do not know an answer, say so.
```
Set `OPENAI_API_KEY` in your shell or the package's `.env`, then run:
```sh Terminal theme={null}
unmute validate voice-desk
unmute compile voice-desk
unmute dev voice-desk --target livekit
```
Use Docker for this LiveKit run. The [Pipecat target](/targets/pipecat) is another option; it runs locally with `uv`.
The example below stays with this same `desk` agent.
## Pros and cons
Pick Live when you want the model to manage the spoken exchange and send
tool work to a backend. It fits an agent that can work within the model's
own turn and voice behavior.
| Pros | Cons |
| - | - |
| The model hears audio directly and manages turns and interruptions | Unmute exposes no separate turn detector or interruption settings here |
| The model can keep speaking while backend work runs | Tool completion still waits for that backend and the tools it calls |
| A dedicated backend handles tool requests and reasoning | The backend must use the same provider; it is not an unrestricted second pipeline |
| Tools and knowledge searches remain available | Unmute currently supports no tasks, handoffs, saved variables, tracing, or phone route here |
Live can respond with fewer speech-processing stages, but is not guaranteed
to beat Realtime or a tuned Cascade on every interaction. Compare both reply
time and successful tool completion.
Choose [Realtime](/build/architecture/realtime) for selectable turn modes or a
separate voice. Choose [Cascade](/build/architecture/cascade) when the workflow
needs more steps and state. The [overview](/build/architecture/overview#pros-and-cons)
compares all three and links the LiveKit and Coval articles.
## 1. Bind the live model
The quickstart's `desk` names `voice` through its `live:` binding.
That entry uses `gpt-live-1` and names `reasoning` as its backend.
Both use `OPENAI_API_KEY`; your account must have access to both models.
Set `live` explicitly. Omitted means `cascade`, which cannot use a live binding.
Agent-level binding. It replaces `think:` and `speak:` on this agent.
OpenAI reasoning entry used by the live model. Required when the agent has tools, including knowledge lookup. It cannot use `endpoint_env`.
See [Live model fields](/models/live) for the full entry reference.
Do not add separate listen, speak, or turn sections; live owns those jobs.
## 2. Give the backend a tool
Add one local tool to the same desk. Create these two **complete new files**:
```yaml voice-desk/tools/opening_hours.yaml theme={null}
description: Look up the information desk's opening hours.
local:
handler: tools/opening_hours.py:opening_hours
```
```python voice-desk/tools/opening_hours.py theme={null}
from pydantic import BaseModel
class OpeningHours(BaseModel):
hours: str
def opening_hours() -> OpeningHours:
return OpeningHours(hours="Monday to Friday, nine in the morning to five in the afternoon.")
```
The handler's signature is the tool's input, and its return model is the output. The tool file has no `input:` or `output:`.
Merge these attachments into `agent.yaml`. Keep the existing `prompt` and `live` binding under `desk`:
```yaml voice-desk/agent.yaml theme={null}
agents:
- name: desk
tools:
- opening_hours
```
Append this instruction to the existing prompt:
```markdown voice-desk/instructions.md theme={null}
Use opening_hours when asked when the desk is open. Read the returned hours.
```
The live model sends the request to its backend. The backend requests a tool call, the generated application runs the handler, and the live model speaks the result.
A tool's returned data should determine the answer; the model should not invent it.
## 3. Try tools and knowledge in a call
Stop the earlier dev run, then validate and restart:
```sh Terminal theme={null}
unmute validate voice-desk
unmute dev voice-desk --target livekit
```
Ask when the desk opens, then interrupt with a follow-up question.
Check that the dev page records the tool and that the spoken answer matches its result.
For document lookup, follow [Knowledge bases](/build/tools/knowledge) and attach the resulting search tool to this same agent.
It runs through the backend too. The complete [takeaway example](https://github.com/slng-ai/unmute/tree/main/examples/takeaway-orders) combines orders and knowledge on both frameworks.
## Advanced
The live entry's voice is optional; omitted means the provider's default.
With no tools, the backend is optional, but requests needing one may be declined.
The backend binding forwards its model name; do not rely on its `params:` being applied to the live session.
A greeting is an opening instruction, so its exact wording can change.
See [Live model](/models/live) for fields and target differences.
Use the [switching steps](/build/architecture/overview#3-replace-the-models-and-agent-bindings).
The current Live integration fixes instructions and tool setup at session start.
It supports one agent and browser audio on Pipecat and LiveKit.
These are limits of Unmute’s integration, not of every speech-to-speech API.
It does not support tasks, handoffs, variables, pre-fetch, tracing, MCP tools, or phone connections.
Remove `conversation.interruption`; the model manages interruptions itself.
Keep cascade when these features are part of your required workflow.
## Troubleshooting
### Validation says the live model needs a backend
An attached tool has no reasoning backend to run it.
**Fix:** add `backend: reasoning` to the live entry and keep the OpenAI `models.think.reasoning` entry from the quickstart.
### The model speaks but cannot use my tool
The tool may be unattached, its arguments may be wrong, or its handler may return a refusal.
**Fix:** check the dev tool row and logs, verify both tool attachments, and compare the result with what the agent said.
See [Local tools](/build/tools/python) for the tool contract.
### The call fails at session start
A configured model or voice may be unavailable to the API key.
**Fix:** read the provider error in the dev logs and verify access to the live model and its backend.
### The greeting sounds different
The live model paraphrases the opening instruction.
**Fix:** write the intended meaning in the greeting; use cascade if exact synthesized wording is required.
## Where to go next
Review fields and target support.Choose turn detection or another voice.
# Architecture
Source: https://unmute.ai/build/architecture/overview
Choose a pipeline, switch an existing agent, and check that its models and bindings agree.
Choose how your agent listens, reasons, and speaks with `architecture:` in `agent.yaml`.
The architecture chooses the pipeline; `targets.yaml` chooses the framework that runs it.
Changing one does not change the other.
On this page:
* [Quickstart](#quickstart) - run a complete example
* [Pros and cons](#pros-and-cons) - control and response time
* [Choose the pipeline](#1-choose-the-pipeline) - compare the three choices
* [Check your package](#2-check-what-your-package-needs) - keep required capabilities
* [Replace the bindings](#3-replace-the-models-and-agent-bindings) - switch the same agent
* [Validate and run](#4-validate-compile-and-start-a-new-call) - check every target
* [What compiles where](#what-compiles-where) - target support
* [Advanced](#advanced) - voices and turn settings
* [Troubleshooting](#troubleshooting) - fix a refused switch
* [Further reading](#further-reading) - LiveKit and Coval comparisons
* [Where to go next](#where-to-go-next) - build each shape
## Quickstart
From a clone of [Unmute](https://github.com/slng-ai/unmute), run the complete realtime example.
Install the [CLI and runtime prerequisites](/start/installation) first, and set `OPENAI_API_KEY` in your shell or existing repository-root `.env`.
```sh Repository root theme={null}
unmute validate examples/pharmacy-refills
unmute compile examples/pharmacy-refills
unmute dev examples/pharmacy-refills --target pipecat
```
The example compiles onto unmute-core for LiveKit and Pipecat.
Ask for a refill on the demo reference RX4821B, pausing halfway through the reference.
Stop the process before trying `--target livekit` with the same package.
Pipecat runs locally with `uv`; LiveKit uses Docker Compose.
That is the loop: **choose the architecture, bind its models, validate, talk**.
The steps below explain how to switch an existing package.
## Pros and cons
| Architecture | Pros | Cons |
| - | - | - |
| [Cascade](/build/architecture/cascade) | Independent model choices and clearer stage-by-stage diagnosis; Unmute's richest workflow controls on LiveKit and Pipecat | More components to tune and usually more latency; reasoning sees a transcript rather than the caller's tone |
| [Realtime](/build/architecture/realtime) | Direct audio understanding, potentially quicker replies, a choice of turn mode and optional separate voice | Less freedom to change the reasoning model; Unmute currently limits it to one agent without tasks or saved state |
| [Live](/build/architecture/live) | The model handles turns, with a separate backend for tool work | No authored turn controls or separate synthesizer; Unmute currently limits it to one agent without tasks or saved state |
**The extra control is often worth the latency.** If a call must collect details,
confirm them, run an action, and recover when it fails, choose the architecture
that lets you express those steps clearly. A faster first reply is only one
part of a successful call.
These are current Unmute capabilities, not universal limits of speech-to-speech APIs.
Compare completed actions, recovery from failures, and response time before choosing.
## 1. Choose the pipeline
| Value | Who does the work | Choose it when |
| - | - | - |
| `cascade` | Separate transcription, reasoning, speech synthesis, and turn detection | You need tasks, handoffs, saved state, or phone routes |
| `realtime` | One speech-to-speech model, with a choice of turn detection and voice output | You want direct audio with explicit turn settings |
| `live` | A voice model with an optional reasoning backend | You want the model to manage conversation while its backend runs tools |
Package-level pipeline choice. Omitted means `cascade`. It applies to the whole package, not to one agent or target.
Both speech-to-speech architectures support Pipecat and LiveKit browser audio.
The SLNG target supports `cascade` only. Model providers and target frameworks are separate choices.
## 2. Check what your package needs
Before switching a cascade, check this list. Removing a feature changes what your agent can do.
Keep `cascade` if any required feature is unavailable on the destination architecture.
| Capability | Cascade | Realtime | Live |
| - | - | - | - |
| Local tools and knowledge lookup | Yes | Yes | Yes, through a backend |
| Multiple agents, tasks, flows, handoffs | LiveKit and Pipecat | No | No |
| Variables and pre-fetch | Yes | No | No |
| Tracing and MCP tools | Yes on supported targets | No | No |
| Phone routes and human transfers | On supported routes | No | No |
| Separate speech synthesizer | Yes | Optional | No |
For example, `salon-concierge` uses tasks, handoffs, variables, and tracing.
Changing its architecture line cannot preserve that workflow. Start with a single-agent S2S example instead.
## 3. Replace the models and agent bindings
Switch a simple agent called `desk` by replacing its `architecture:`, entire `models:` block, and model bindings.
These are **replacement fragments**, not complete packages. Keep its `prompt`, tool attachments, and other supported settings.
Do not paste a second `models:` or `agents:` block alongside the first.
```yaml Realtime: agent.yaml theme={null}
architecture: realtime
models:
realtime:
- name: voice
provider: openai
model: gpt-realtime
voice: marin
turn_detection: semantic
agents:
- name: desk
prompt: instructions.md
realtime: voice
```
```yaml Live: agent.yaml theme={null}
architecture: live
models:
live:
- name: voice
provider: openai
model: gpt-live-1
voice: marin
backend: reasoning
think:
reasoning:
provider: openai
model: gpt-5.6-terra
agents:
- name: desk
prompt: instructions.md
live: voice
```
Use your existing agent name in place of `desk`, and keep `entry_agent` pointing to it.
The [cascade guide](/build/architecture/cascade) supplies the corresponding listening, reasoning, and speaking bindings for switching back.
| Destination | Remove or replace |
| - | - |
| Realtime | Remove `live:` or agent `think:`/`speak:` bindings; replace the live or cascade models with `models.realtime` |
| Live | Remove `realtime:` or agent `think:`/`speak:` bindings; replace their models with `models.live` and the backend's `models.think` entry |
| Cascade | Remove agent `live:`/`realtime:` and their model sections; restore `models.listen`, `models.think`, `models.speak`, `models.turn`, and agent `think:`/`speak:` |
For either S2S destination, remove package-level `listen:` and `turn:` selectors and their model sections.
For live, also remove `conversation.interruption`; the model owns interruption behavior.
Realtime can retain a separate synthesizer only through the [Advanced voice setup](/build/architecture/realtime#advanced).
Update `secrets:` to match the remaining providers. The S2S fragments above require `OPENAI_API_KEY`.
In `targets.yaml`, remove model overrides for entries you deleted. Keep target names, providers, and supported framework pins.
Remove phone connections and keep the browser channel when switching to S2S.
## 4. Validate, compile, and start a new call
Run these from the directory containing your package. `voice-desk` is its directory name here.
```sh Terminal theme={null}
unmute validate voice-desk
unmute compile voice-desk
unmute dev voice-desk --target livekit
```
Without `--target`, validate and compile check every declared target.
Use `--target pipecat` to run that framework if the package declares it.
Stop the old dev process and start a new call after switching; an active session keeps its current architecture.
Test a greeting, a tool call, knowledge lookup, and interruption.
A successful compile checks the package; it does not prove provider access or audible behavior.
## What compiles where
| Architecture | SLNG | LiveKit | Pipecat | Twilio |
| - | - | - | - | - |
| `cascade` | yes | yes | yes | yes |
| `realtime` | no | yes | yes | no |
| `live` | no | yes | yes | no |
S2S support covers browser audio. Check the feature limits in step 2 before switching.
## Advanced
Realtime supports `turn_detection` and an optional `speak:` binding.
Follow [Realtime](/build/architecture/realtime#advanced) to add them to the same agent.
Live decides turns itself and uses its own voice.
Keep the prompt and local tools as similar as the architectures allow.
Compare the dev page's reported measurements and the conversation you hear.
Speech-to-speech removes separate transcription and synthesis stages, but does not guarantee a faster call.
See [Latency](/optimization/latency).
## Troubleshooting
### Validation says a model section is not used
The architecture changed, but an old model section or selector remains.
**Fix:** replace the models and bindings together using step 3, then validate again.
### A target overrides a model that no longer exists
`targets.yaml` still names a deleted cascade or backend entry.
**Fix:** delete that override or point it at a supported remaining model. Do not add a dummy model just to satisfy it.
### Validation refuses tasks or saved variables
The destination S2S architecture does not support those capabilities.
**Fix:** keep `architecture: cascade`, or start a separate single-agent package with the supported workflow.
### The call still uses the old architecture
The running process was started from an earlier build.
**Fix:** stop it, rerun `unmute dev`, and open a new call.
## Further reading
[LiveKit's pipeline and realtime comparison](https://livekit.com/blog/realtime-vs-cascade)
explains the balance between latency, direct audio understanding, and modular
control. It also describes how streaming and hybrid designs narrow the gap.
[Coval's speech-to-speech and cascade comparison](https://www.coval.ai/blog/speech-to-speech-vs-cascaded-voice-ai-which-architecture-should-you-deploy/)
focuses on workflow control, diagnosing failures, and evaluating completed
conversations. Use the tables above for what Unmute supports today.
## Where to go next
Build with separate models.Choose the turn and voice.Add a voice model and backend.
# Realtime
Source: https://unmute.ai/build/architecture/realtime
Run one model for spoken conversation, then choose turn detection, tools, and an optional separate voice.
Let one realtime model hear the caller, answer, and use your tools.
The model takes audio directly. `turn_detection` chooses who ends the caller's turn, and the model's voice speaks the reply by default in this example.
On this page:
* [Quickstart](#quickstart) - a complete realtime agent
* [Pros and cons](#pros-and-cons) - strengths and limits
* [Bind the model](#1-bind-the-realtime-model) - choose the voice
* [Choose turn detection](#2-choose-who-ends-the-turn) - defaults and limits
* [Attach tools](#3-add-tools-and-knowledge) - extend the same desk
* [Advanced](#advanced) - a separate synthesizer
* [Troubleshooting](#troubleshooting) - fix voice and turn problems
* [Where to go next](#where-to-go-next) - examples and references
## Quickstart
Create a new package with a LiveKit target. If initialization opens the console, select LiveKit and finish creating the package.
```sh Terminal theme={null}
unmute init voice-desk
```
Replace `voice-desk/agent.yaml` with this **complete file**:
```yaml voice-desk/agent.yaml theme={null}
name: voice-desk
architecture: realtime
entry_agent: desk
secrets:
- OPENAI_API_KEY
models:
realtime:
- name: voice
provider: openai
model: gpt-realtime
voice: marin
turn_detection: semantic
agents:
- name: desk
prompt: instructions.md
realtime: voice
```
`channels:` and `capacity:` live in targets.yaml. Set them at the top of the scaffold's file:
```yaml targets.yaml theme={null}
channels:
- name: web
kind: realtime_audio
capacity:
peak_sessions: 1
max_sessions: 2
avg_session_duration: 3m
```
Keep the scaffold's `state.py` as it is. The package needs it, and this desk saves no values.
Keep the scaffold's `targets.yaml`, but remove its target-level `models:` overrides because the model palette above replaces the scaffold's.
Keep its framework provider and version pin, and remove any phone `connection:` for this browser example. Replace `voice-desk/instructions.md` with this complete prompt:
```markdown voice-desk/instructions.md theme={null}
You are a friendly information desk. Answer in short spoken sentences.
Ask one question at a time. If you do not know an answer, say so.
```
Set `OPENAI_API_KEY` in your shell or the package's `.env`, then run:
```sh Terminal theme={null}
unmute validate voice-desk
unmute compile voice-desk
unmute dev voice-desk --target livekit
```
Use Docker for this LiveKit run. The [Pipecat target](/targets/pipecat) is another option; it runs locally with `uv`.
The example below stays with this same `desk` agent.
## Pros and cons
Pick Realtime when direct audio interaction matters and the call fits one
agent with tools. It keeps more control over turn detection and voice than
Unmute's Live architecture.
| Pros | Cons |
| - | - |
| Direct audio input retains clues that may be lost in transcription | Audio understanding and reasoning stay with the chosen realtime model |
| Fewer stage boundaries can reduce response delay | Provider, turn settings, network, and tools still determine the actual wait |
| Choose a turn mode and optionally keep a separate synthesizer | A separate synthesizer adds another component and its response time |
| Tools and knowledge searches remain available | Unmute currently supports no tasks, handoffs, saved variables, tracing, or phone route here |
For a workflow that collects, confirms, and acts across several tasks, use
[Cascade](/build/architecture/cascade#3-add-tools-tasks-or-saved-state).
Its extra control can be worth a longer pause. See the
[comparison and further reading](/build/architecture/overview#pros-and-cons)
for the wider tradeoff.
## 1. Bind the realtime model
The `desk` agent names the `voice` entry through `realtime:`.
Its OpenAI model listens and speaks, so this package has no separate transcriber or reasoning binding.
An unused `models.think` entry may remain, but the agent cannot bind it with `think:`. Remove unused entries to keep the package clear.
Set `realtime` explicitly. Omitted means `cascade`.
Agent-level model binding. Replaces the agent's `think:` and its normal `speak:` binding.
Name of the realtime model entry. The agent refers to it by this name.
Supported realtime provider on Pipecat and LiveKit. The SLNG target cannot run this architecture.
Model ID forwarded to the provider. Validation does not check account access or model availability.
Voice on the realtime entry. Supply this or an agent-level `speak:` binding, never both. Omitting both is refused.
Optional author note. It does not change the runtime.
## 2. Choose who ends the turn
The quickstart writes `semantic` to make the choice explicit on both targets.
Change only that entry's `turn_detection` when comparing the options.
Optional turn choice on the realtime entry. An omitted value leaves the integration's default in place; the targets can choose differently.
| Value | What decides |
| - | - |
| `server_vad` | The provider's silence detector |
| `semantic` | The provider's detector judging whether the caller finished their thought |
| `local` | The framework's local turn handling |
| Omitted | Pipecat leaves the provider default; the LiveKit plugin supplies its default |
The current integrations default to server silence detection on Pipecat and semantic detection on LiveKit.
Write an explicit value when comparing the two frameworks.
Do not add `models.turn`, package-level `turn:`, or `listen:` to a realtime package, even with `local`.
Those cascade sections are refused. `conversation.interruption.minimum_words` requires `turn_detection: local` because it gates a local turn start.
## 3. Add tools and knowledge
Keep the same tool files and attachments described in [Add a local tool](/build/tools/python).
Add the tool name to the `tools:` list of the `desk` agent, keeping its existing `prompt` and `realtime` binding.
The realtime model requests tool calls; the generated application runs them and returns the results.
It has no separate `backend:` model.
For document questions, add a [knowledge search tool](/build/tools/knowledge) in the same way.
The [pharmacy example](https://github.com/slng-ai/unmute/tree/main/examples/pharmacy-refills) combines local tools, knowledge, and semantic turn detection.
After each change, stop the old run and check the same desk:
```sh Terminal theme={null}
unmute validate voice-desk
unmute dev voice-desk --target livekit
```
Ask a question that requires the tool. Pause in the middle of a sentence, then finish it.
Check both the spoken reply and the tool row in the dev page.
## Advanced
The realtime model can return text while a synthesizer speaks it. This is sometimes called a half cascade.
Remove `voice:` from the realtime entry named `voice`. Merge the following entries into the quickstart, keeping its existing realtime model and agent binding:
```yaml voice-desk/agent.yaml theme={null}
secrets:
- SLNG_API_KEY
models:
speak:
spoken_voice:
provider: slng
model: "deepgram/aura:2"
voice: aura-2-thalia-en
agents:
- name: desk
speak: spoken_voice
```
Append the secret name rather than replacing `OPENAI_API_KEY`, and set its value in your environment.
Validate and compile both declared targets before starting another call.
Choose other supported synthesizers from [Voices](/models/tts).
Follow [Switch architecture](/build/architecture/overview#3-replace-the-models-and-agent-bindings) to replace the models and bindings together.
The Realtime API can accept instruction updates during a call.
Unmute currently supports one agent, browser audio, tools, and knowledge; it does not provide task and handoff transitions consistently across both code targets.
Tasks, flows, handoffs, variables, pre-fetch, tracing, MCP tools, and phone connections are unavailable.
Use cascade if your workflow needs them.
## Troubleshooting
### Validation says both voice and speak are set
The realtime entry and agent both name a speaker.
**Fix:** remove the entry's `voice:` for a separate synthesizer, or remove the agent's `speak:` to use the model's voice.
### Validation says there is no voice
Neither the realtime entry nor the agent names a speaker.
**Fix:** add `voice: marin` to the OpenAI realtime entry, or configure the Advanced synthesizer setup.
### The agent cuts in while I spell a reference
A silence detector may treat the pause as the end of the turn.
**Fix:** try `turn_detection: semantic`, then retest the same phrase. Explain expected pauses in the prompt if needed.
### Local turn detection still rejects models.turn
`local` selects framework behavior; it does not enable the cascade model sections.
**Fix:** remove `models.turn` and its top-level selector. Keep the choice on the realtime entry.
## Where to go next
Use a voice model with a reasoning backend.Answer questions from documents.
# Credentials
Source: https://unmute.ai/build/credentials
Give the agent an API key without putting one in your package.
Your agent needs keys: one for the model provider, usually one more for each
API a tool calls.
A package never holds the value. It holds the **name** of an environment
variable, and the value arrives at run time from your `.env` file locally, or
your platform's secret store once you deploy.
That means `agent.yaml` is safe to commit, and the same package works on your
machine and in production without editing.
On this page:
* [Three steps](#three-steps) - write the value, declare the name, point at it
* [Where a name goes](#where-a-name-goes) - every key that takes one
* [A secret is not a variable](#a-secret-is-not-a-variable) - two things that look alike
* [What you do not declare](#what-you-do-not-declare) - the names the target owns
## Three steps
Next to `agent.yaml`, in a file git already ignores:
```sh .env theme={null}
OPENAI_API_KEY=sk-...
SALON_API_TOKEN=...
```
`unmute dev` reads `.env` and `.env.local` from both the current directory
and the package directory. Neither is ever generated with values, and
neither is committed.
```yaml agent.yaml theme={null}
secrets:
- OPENAI_API_KEY
- SALON_API_TOKEN
```
A list of names, each one UPPER\_SNAKE. This is the package's inventory of
what the generated project reads. A lower case or punctuated entry is
refused, because it is a typo that would otherwise fail at call time.
Never at the value. Each seam has its own `*_env` field:
```yaml tools/reschedule_appointment.yaml theme={null}
webhook:
url_env: SALON_API_URL
path: /customers/{{state.customer_id}}/appointments
auth:
type: bearer
token_env: SALON_API_TOKEN
```
A Python handler reads its own with `os.environ["SALON_API_TOKEN"]`.
Compile, and `build//.env.example` lists exactly the values you have to
supply for that build, ready to copy to `.env`.
### Every key a secrets block takes
One key, at the top level of `agent.yaml`.
The environment variables the generated project reads. Each entry is a
capital letter, then capitals, digits and underscores; a lower case or
punctuated entry is refused, and so is the same name twice. Left out, the
compiler still infers the names it can see and warns that the inventory is
incomplete.
## Where a name goes
### Every key a seam takes
Each one holds the name of an environment variable, never a value.
In `tools/.yaml`. The base URL of an authenticated API. A webhook tool
needs this or `base_url`, and the code targets read this one.
In `tools/.yaml`. The MCP server's address. The code targets dial the
server themselves and need it; an `slng` package leaves it out.
Under `auth:` in a `webhook:` or `mcp:` block. The bearer token or API key,
and required once `auth:` is written at all.
On a `models:` entry in `agent.yaml`. Points that model at your own gateway
instead of the provider's.
In `connections/.yaml`. The carrier account behind a phone route, one key per field the route needs.
In `agent.yaml`. The variable holding the phone number of the desk a transfer
reaches.
A `local:` handler is the one case with no key: it reads
`os.environ` itself, so the name lives in the Python you wrote rather than in
`agent.yaml`. Declare it in `secrets:` all the same, so the inventory stays
complete.
## A secret is not a variable
They look similar and they are not the same thing.
| | [Variables](/build/variables) | Credentials |
| - | - | - |
| holds | a value about this call | a key your service authenticates with |
| written as | `{{state.caller_name}}` in a prompt | a `*_env` field naming an environment variable |
| changes | during the call | never, during a call |
| reaches the model | when a prompt names it | never |
`{{...}}` renders variables only. Naming a secret in a template is a compile
error, not a value that leaks at run time. A template renders into speech, a
prompt, a tool argument or a URL, so whatever it holds gets spoken, logged or
traced. That is right for a customer's name and wrong for a token.
## What you do not declare
Some names the target supplies for you: `LIVEKIT_URL` and its key pair, `REDIS_URL`
for the phone routes that need it, the public URL and token `unmute dev` creates
for a local phone run. Leave those out of `secrets:`.
You may still have to supply some of their values when you deploy. The
generated `README.md` and `compile-report.json` list the complete set and say
who supplies each one.
## Where to go next
Every seam, every check, and what the generated files do with the inventory.
Moving these values into a platform's secret store.
# How a package fits together
Source: https://unmute.ai/build/how-a-package-fits-together
One rule explains the whole file: an agent owns what it can do, and writes each one where it uses it.
A package is one `agent.yaml` plus the prompts, tool files and knowledge
folders it points at. It answers three questions: who answers the call, what
each agent may do, and what each of those things actually is.
One rule explains the whole file:
> **An agent owns its own handoffs, transfers, flows and tasks. Each one is
> written in full inside the agent that uses it first. Any other agent names
> it with a bare name.**
On this page:
* [Quickstart](#quickstart) - the smallest package with two agents
* [The five things an agent can do](#the-five-things-an-agent-can-do) - and which give the caller back
* [Every key an agent takes](#every-key-an-agent-takes) - four required, five lists
* [Build one in three steps](#build-one-in-three-steps) - the worked version
* [How a value gets from one step to the next](#how-a-value-gets-from-one-step-to-the-next) - `variables:`, `save:`, `context:`
* [What the compiler holds for you](#what-the-compiler-holds-for-you) - the errors you cannot write past
## Quickstart
Two agents. `front_desk` answers, and can hand the caller to
`complaint_specialist`:
```yaml agent.yaml theme={null}
entry_agent: front_desk
agents:
- name: front_desk
prompt: instructions.md
think: reasoning
speak: voice
handoffs:
- name: to_complaints
to: complaint_specialist
when: The caller has a complaint.
- name: complaint_specialist
prompt: agents/complaints.md
think: reasoning
speak: voice
```
```sh theme={null}
unmute validate my-agent
```
`front_desk` writes the handoff block, so the definition sits beside the agent
that uses it. Another agent that wants the same handoff writes its bare name,
`- to_complaints`. A bare name nobody defines is refused, and so are two blocks
with one name.
The same goes for tasks, flows and transfers.
## The five things an agent can do
An agent is a person on the phone. It can do five kinds of things, and each
kind has its own list:
| List on the agent | What it means | Does the agent get the caller back? |
| - | - | - |
| [`tools:`](/build/tools/overview) | do real work: look something up, call an API | yes, a tool just returns data |
| [`tasks:`](/build/orchestration/tasks) | run a smaller job with its own prompt, and use its typed result | yes, the task finishes and reports back |
| [`flows:`](/build/orchestration/task-groups) | run several tasks in a fixed order, then use the merged result | yes, the flow finishes and reports back |
| [`handoffs:`](/build/orchestration/handoffs) | give the caller to another agent | no, the other agent takes over |
| [`transfers:`](/transfers/overview) | give the caller to a human | no, the call leaves the system |
If you remember one thing, remember the third column. Tools, tasks and flows
come back. Handoffs and transfers do not.
### Every key an agent takes
An agent has four required keys and five optional lists. There are no others.
What the agent is called. Other agents and `entry_agent:` use this name.
The Markdown file holding this agent's prompt, relative to the package root.
Which reasoning model this agent uses. Names one entry under
[`models.think`](/models/llm).
Which voice this agent speaks in. Names one entry under
[`models.speak`](/models/tts).
Which transcriber this agent hears with, for an agent that speaks another language.
Names one entry under [`models.listen`](/models/stt). Omit it to use the package's.
Tools this agent may call. Each name is a file under `tools/.yaml`.
Tasks this agent may run. Write the task in full to define it here, or write
a bare name to run a task another agent already defined.
Flows this agent may run. Write the flow in full to define it here, or write
a bare name to run a flow another agent defined.
Agents this one can hand the caller to. Write the handoff in full to define
it here, or write a bare name to use one another agent defined.
People this agent can put the caller through to. Write the transfer in full to
define it here, or write a bare name to use one another agent defined.
## Build one in three steps
Say you want two agents, and each one can run a task.
**Step 1. Say who answers.**
```yaml agent.yaml theme={null}
entry_agent: front_desk
```
**Step 2. Write the agents, with their tasks, handoffs and transfers nested
right inside.** A task carries both what it is and when to run it, so there is
one name and one place to read it.
Each handoff may choose how much conversation travels with the caller. Omitted
history means `messages`. Saved values reach the receiving model only through
placeholders in its prompt. A transfer's `to:` names the environment variable
that holds the phone number, never the number.
```yaml agent.yaml theme={null}
agents:
- name: front_desk
prompt: instructions.md
think: reasoning
speak: voice
tools:
- look_up_prices
tasks:
- name: verify_customer
when: Confirm who the caller is before anything personal.
prompt: tasks/verify-customer.md
save:
- customer_phone: result.customer_phone
- name: manage_booking
when: The caller wants to create, change, or cancel a booking, once the caller is identified.
prompt: tasks/booking.md
save:
- booking_id: result.booking_id
handoffs:
- name: to_complaints
to: complaint_specialist
when: The verified caller has a complaint.
context:
history: full
transfers:
- name: to_manager
to: MANAGER_PHONE_NUMBER
when: The caller asks for a manager.
ring_timeout: 30s
on_unavailable: hangup
- name: complaint_specialist
prompt: agents/complaints.md
think: reasoning
speak: voice
tools:
- record_complaint
# front_desk already defines these. A bare name uses the same one
# from here, so there is one definition and both agents can offer it.
tasks:
- verify_customer
handoffs:
- name: to_front_desk
to: front_desk
when: The caller is done complaining and wants something else.
context:
history: full
transfers:
- to_manager
```
Read `front_desk` top to bottom. You already know everything it can do, and
which kind of thing each one is. That glance is the point of the five lists.
**Step 3. Add the tools.** Every file under `tools/` is a tool, so there is no
list to keep. Declare `MANAGER_PHONE_NUMBER` in `secrets:`. The top-level
`tools:` list is only for a tool that needs behaviour around it on every agent,
such as a line said as it starts:
```yaml agent.yaml theme={null}
secrets:
- MANAGER_PHONE_NUMBER
tools:
- name: record_complaint
start:
say:
- Let me get that written down.
```
Done. Notice you never wrote `verify_customer` twice. It is defined once,
inside `front_desk`, and `complaint_specialist` just names it. Sharing is
naming the same thing.
## How a value gets from one step to the next
Three keys do this, and they each do one thing. Each has its own page.
Says where a value comes from and which step confirms it. The value itself,
its type and its default are a field on `State` in `state.py`, the box.
Nothing fills it by itself.
[Variables](/build/variables)
Fills a variable when the task finishes. `- customer_phone: result.phone`
means "put the task's `phone` answer into `customer_phone`".
[Tasks](/build/orchestration/tasks)
Chooses how much of the conversation so far the next step can read. It moves
the transcript, not your saved values.
[Context scope](/best-practices/context-scope)
Saved values are never added to a prompt on their own. A prompt reads a value
only when it names it, as `{{state.customer_phone}}`.
### Ordering work without a gate
In the example above, `verify_customer` fills `customer_phone` with `save:`,
and `manage_booking`'s own `when:` says it runs only once the caller is
identified. That is how "verify before booking" works: the order lives in the
prompt, not in a gate, so the caller hears nothing about it.
Put that clause on the work that needs the value, not on the route to it. And
never hold up the way to a person: somebody asking for a manager should not be
interviewed first.
## Tasks attach handoffs, and nothing else
A task has `tools:` and `handoffs:` and no other list. There is no `tasks:`,
no `flows:` and no `transfers:` key on a task, so a task cannot run
another task or flow, or reach a person directly. That is not a rule
you have to remember. The key does not exist, so the file cannot be written.
## What the compiler holds for you
* A bare name in an agent's list must be defined by some agent. A typo is a
build error, not a silent gap.
* A name listed under the wrong kind is refused, and the message names the
list it belongs on.
* All five kinds share one namespace, because every name becomes a callable
function at runtime. Two things cannot share a name, and two agents
defining the same name is refused the same way.
* A handoff, transfer, flow or tool that no agent reaches is also a
build error. There is no dead config to forget about.
* A task can list `tools:` and `handoffs:` only, enforced by the shape of the
file.
Two of those errors, as you will actually see them:
```text theme={null}
agent.yaml:31: "verify_customer" is a task, so move it out of the tools: list
and into the tasks: list
```
```text theme={null}
agent.yaml:47: transfer "to_manager" is declared but no agent reaches it; add it
to the transfers: of one of these agents: front_desk, complaint_specialist
```
## Order, and what it does not mean
Nothing an agent lists runs in list order. The model picks what to use from the
`when:` text. Two things in a package do run in a fixed order: the `steps:` of
a flow, and the entries of [`prefetch:`](/build/prefetch). Pre-fetch
entries resolve top to bottom, and an entry that reads a value only a later
entry saves stops the build.
Order is not free everywhere, though: the order of names in a list is the
order the tools are declared to the model in the generated code, so
reordering a list produces a different file. Treat that as presentation, not
as control flow.
## The order to write the file in
```
version, name, entry_agent
agents
variables
prefetch
secrets, knowledge, models, tools
conversation, tracing
```
That order is a convention, not a schema rule, and it exists so a reader meets
the agents first and the plumbing last. `unmute init` writes the shape without
`prefetch:`, since the scaffold declares none. `examples/salon-concierge` shows
where it lands once a package uses it: right after `variables:`.
`channels:` and `capacity:` are not in this file. They sit at the top of
`targets.yaml`.
Every one of those keys, with its type, whether it is required, and what values
it accepts, is in the
[`agent.yaml` key table](/reference/agent-yaml#all-keys).
## Where to go next
Add one task to the agent you just made, one key at a time.
Nested tasks and typed results.
When to split into two agents.
Tasks in a fixed order, sharing what they learn.
Cold and warm transfer to a person.
# Choosing a structure
Source: https://unmute.ai/build/orchestration/choosing-a-structure
Tools, tasks, flows, or a second agent. Which split to reach for, and when.
You have four ways to organize an agent: one agent with tools, a task, a task
group, or a second agent. Each one owns a different boundary. Choose from the
brief, before you write files.
On this page:
* [Compare the shapes](#compare-the-shapes) - the whole trade in one table
* [The symptom decides the shape](#the-symptom-decides-the-shape) - start here if something is already wrong
* [Task or handoff](#task-or-handoff) - the choice people get wrong most
* [Choosing shapes for a booking flow](#choosing-shapes-for-a-booking-flow) - one brief, worked through
In a hurry? Two rules carry most of it. **A task returns the caller and a
handoff does not.** And if one agent with good tools can do the job, use one
agent with good tools.
## Compare the shapes
Every shape trades something for control. This table is the whole trade, side
by side.
| | Holds the session | Context the receiver sees | Cost in round trips | A caller's correction | Best for |
| - | - | - | - | - | - |
| One agent with tools | the agent, for the whole call | the whole conversation | none beyond the tool call itself | ask again, same turn | one job, one set of rules |
| Task | the task, until it returns | what `context:` gives it | 2 to enter, the same as one tool call | run it again | one job with a definite, typed answer |
| Task group | the group, across its steps, until it returns | shared across steps, or isolated per step, by `context_scope` | 2 to enter the group, once, however many steps run inside | revisit a step inside the group | an order that has to hold, with shared context |
| Handoff | the receiving agent, for good | only what `context:` carries over | 1 to leave, plus the receiving agent's forced opening turn, every time control changes hands | another handoff back | two roles with genuinely different rules or permissions |
These are not exclusive. One agent can run a task in one phase and hand
off in another.
## Choose the native shape
| The brief needs | Native shape | Do not invent |
| - | - | - |
| A real external or local action | `tool` | A task used only as an API wrapper |
| One bounded step that returns | `task` | A second agent or progress flags |
| Several steps in a fixed order | `flow` | Current-step variables or transition tools |
| A lasting role or permission change | `agent handoff` | A returning task |
| A runtime value needed across a boundary | `variable` | Conversation memory or workflow state |
If none of these boundaries exists, keep one agent with a clear prompt and its
real tools. You describe the job; the coding agent should choose the shape and
tell you what it chose. You do not need to ask for a task or flow by name.
A server-directed sequence is dynamic, even when its response calls the field
`nextStep`. Put that loop in one task that asks the returned question and calls
the real domain tools. If fixed stages surround the loop, those stages can be
tasks in a flow. The server owns its dynamic order.
## Let the compiler hold the state
* Do not create current-step, happy-path, completion, or routing variables.
Tasks, flows, handoffs, and an external server already hold that state.
* Do not create advance, proceed, dispatcher, or transition tools. A tool does
real external or local work; a task, a flow or a handoff moves the
conversation.
* Keep a variable only when its value really crosses a boundary or feeds a later
tool call.
## The symptom decides the shape
| What you are seeing | The shape that fixes it |
| - | - |
| the prompt keeps growing and starts contradicting itself | split it: [tasks](/build/orchestration/tasks) if the parts serve one caller goal, a [handoff](/build/orchestration/handoffs) if they are separate roles |
| the model does things out of order | a [flow](/build/orchestration/task-groups): the order is declared, not requested |
| the model calls a tool it should not have yet | move the tool. Lists are per agent and per task, so a tool the current task does not hold cannot be called at all |
| a task runs before you have the value it needs | give the task's own `when:` the clause that names what has to be true first, "once the caller is identified" |
| you need to keep a value a task produces | `save:` on the task, into a declared variable |
| two phases need different tools or different permissions | a [handoff](/build/orchestration/handoffs) |
| the caller needs a person | none of these: that is a [human transfer](/transfers/overview), and what it can do depends on the phone route |
A prompt that says "always identify the caller first" is a request. A flow
is a guarantee. A `when:` clause naming the dependency is not a guarantee the
same way, but it is cheap: no extra task, no extra prompt site, and nothing
the caller has to be spoken through. See [Order steps with the
prompt](/best-practices/step-scoping#order-steps-with-the-prompt) for the full
pattern, including the tool-level check that catches a task run out of
order anyway.
Reach for the flow when the *order* is what must hold. Reach for a
`when:` clause when one *value* should usually be there before one task runs,
and a stray extra turn asking for it is an acceptable cost.
## Task or handoff
The difference is whether control comes back. That is why they are two kinds
of list rather than one with a kind field: which list a thing is written in is
what it is.
```yaml theme={null}
agents:
- name: appointment_desk
tasks:
- name: check_customer # runs, returns a typed result, the agent continues
when: Identify the caller before handling an appointment request.
prompt: tasks/check-customer.md
save:
- customer_id: result.customer_id
handoffs:
- name: to_appointment_manager # hands the call over, nothing returns
to: appointment_manager
when: The caller wants to reschedule or cancel an existing appointment.
```
### Order the task, not the route to it
Say the dependency on the task itself, in its own `when:`:
```yaml theme={null}
- name: send_receipt
when: The caller asks for a receipt from a past visit, once the caller is identified.
```
The model reads that clause every time it considers the task. Reference the
saved value in the owner's prompt when the model needs to check it. See [Order
steps with the prompt](/best-practices/step-scoping#order-steps-with-the-prompt)
for what still catches a task run out of order anyway, and what the caller
hears when it does.
Do not add an agent whose only job is to hold callers up in front of a task.
That agent has to be spoken through, which costs the caller a turn and buys
nothing a clause on the task does not already give. And never hold up the
route to a person: someone who asks for a manager should not be interviewed
first.
| | `tasks:` | `handoffs:` |
| - | - | - |
| returns | yes | no |
| saved typed values | yes, through `save:` | existing call state remains available to explicit prompt references |
| targets | a task, run in place | another agent |
| where context is set | `context:` on the task | `context:` on the handoff entry |
## Choosing shapes for a booking flow
A salon booking agent runs into all four decisions in one package. Each lands
on a different shape, and together they are
[`examples/salon-concierge`](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge).
**Look up services and answer questions.** One job, one set of rules: a single
agent with tools handles it. `concierge` calls `look_up_salon_info` directly,
with no task in between.
**Confirm who is calling before anything personal.** One job with a definite,
typed answer: a task. `verify_customer` holds the one tool that looks the
caller up, ends on that tool through an outcome with `then: done`, and saves
`customer_phone` with `save:`. The `customer_phone` variable carries
`confirm: verify_customer`, so until this task has heard the caller agree, the
number reaches no other prompt and every tool that needs it refuses. The task
keeps a `when:` of its own for one case only: the caller correcting their phone
number. Every other route into verification goes through the flow below.
**Does identifying the caller have to come before booking, every time?** That
is the flow question, and here the answer is yes. A booking made against
a number nobody agreed to is a booking for a stranger, so the order is not a
request to the model. It is something the package has to hold. The flow
`book` runs `verify_customer` and then `manage_booking`. A flow's defaults fit
here: its steps share one context, so the booking step hears what verification
heard, and it returns the call to the concierge:
```yaml theme={null}
flows:
- name: book
when: >-
The caller wants to create, move or cancel a booking. Includes a change to
an appointment just made.
steps:
- task: verify_customer
skip_when_confirmed: customer_phone
- manage_booking
```
Three things follow from the flow.
* The second booking on a call skips verification. `skip_when_confirmed:
customer_phone` skips the first step when the number is already confirmed,
which is every booking after the first.
* The concierge makes one call into the flow instead of choosing between two
tasks. Which step runs, and in what order, is the flow's decision.
* `manage_booking` has no `when:` of its own, because the flow decides when
it runs. A task an agent runs on its own needs a `when:`. A step inside a
flow does not.
**Hand a complaint to someone who needs a different tool list and a refund
policy the booking agent should never see.** A different role with different
permissions, not another task in the same role: a handoff. `to_complaints`
moves the caller to `complaint_specialist`, who alone holds `record_complaint`
and alone reads the refund knowledge base through `look_up_refund_policy`.
Recording a complaint is one action, not an ordered step, so it sits directly
on the specialist rather than behind a task. `to_concierge` carries the
reverse direction. The specialist does name `verify_customer`, as a bare
`- verify_customer`: the definition stays on the concierge, because a task name
is one name across the package. It needs the step in reach because
`record_complaint` takes `customer_phone` through `with:` and is refused while the caller has
not agreed to it, and a caller who opens with a complaint has never been near
the booking flow.
What is left over goes to a person. A caller who asks for a manager reaches
`to_manager`, a cold transfer, not any of the four shapes above. Both agents
hold it, so asking for a person is never gated on identifying yourself first.
## Where to go next
Why a task you declared never runs, and how to fix it.
Choosing what a task saves, and the type each value gets.
The dev loop: ports, logs, and picking a target.
The settings that cut round trips and speed up a call.
# Your first task
Source: https://unmute.ai/build/orchestration/first-task
Add one task to the agent you already have, one key at a time, until it knows for itself when its work is done.
You have one agent working from [Your first agent](/build/your-first-agent).
This page adds one task to it. Nothing here needs a second agent, a phone
number or a new account. Every change below ends with `unmute validate`, and
every change leaves you a package that compiles.
The example is a parcel tracking line. A caller reads out a tracking number,
the agent looks it up and says when the parcel is due. It is small on purpose.
The shape is what matters, and you will swap the parcel for your own thing.
**Tasks run on LiveKit, Pipecat and SLNG.** The package `unmute init`
writes targets LiveKit, so you are ready. SLNG takes most task features;
[the SLNG page](/targets/slng#tasks-and-flows) lists them.
Twilio compiles one agent with one prompt and refuses tasks. Fold the step
into the agent's instructions or use another target.
## What a task is
A task is a smaller conversation inside the call. It has its own prompt and
its own tools. To the model, a task is one more entry in its function list,
right next to the agent's tools. When the model calls it, the task's prompt
takes over. When the task is done, the agent that started it, the owner, gets
the caller back, along with whatever the task saved.
You reach for a task when part of the call needs a narrower prompt, a smaller
tool list, or an answer you want to keep. If none of those is true, stay with
one agent and its tools. Most agents should.
One word to settle before we start. A task is one step of the call. Some of
the compiler's messages say "step" for that reason. On this page the thing you
write is always a task.
On this page: nine steps, each ending with a package that validates, so you can
stop anywhere and come back.
1. **Start with no task** - confirm the package you already have still works
2. **Give the agent a tool** - a lookup, so there is something to move
3. **Say what you want to keep** - add fields to `State`
4. **Add the task** - move the tool onto it
5. **Save the answer** - `save:`
6. **Read it back** - a placeholder in the owner's prompt
7. **Say what success looks like** - an outcome, so the tool ends the step
8. **Open with the question** - `start:` with `say:` and `listen: true`
9. **Run it** - talk to it in the browser
This is the package from the last page. Make sure it still validates:
```sh theme={null}
unmute validate my-agent
```
One agent, one prompt, one built-in tool so it can hang up. Keep this
picture in mind: each change below adds one thing to it.
A tool does real work and comes back with a result. This one is a small
Python function that stands in for your delivery system. It lives in the
package, in two files.
The tool file says what the tool does and which function runs it:
```yaml tools/look_up_parcel.yaml theme={null}
description: >-
Look up a parcel by its tracking number. Call it once the caller has read
the number out and you have said it back to them.
local:
handler: tools/look_up_parcel.py:look_up_parcel
```
The file has no `input:` or `output:`. The handler is a typed Python
function, and `handler:` names it as `file.py:function`. Its arguments are
the tool's input. The Pydantic model it returns is the tool's output:
```python tools/look_up_parcel.py theme={null}
from datetime import date, timedelta
from typing import Annotated, Literal
from pydantic import BaseModel, Field
# A stand-in for your delivery system. Two parcels, due in a few days.
PARCELS = {
"AB123456": 3,
"CD789012": 1,
}
class Parcel(BaseModel):
status: Literal["found", "not_found"]
tracking_number: str
delivery_date: date | None = None
def look_up_parcel(
tracking_number: Annotated[
str,
Field(description="The tracking number as the caller gave it, letters and digits, no spaces."),
],
) -> Parcel:
number = tracking_number.replace(" ", "").upper()
days = PARCELS.get(number)
if days is None:
return Parcel(status="not_found", tracking_number=number)
return Parcel(
status="found",
tracking_number=number,
delivery_date=date.today() + timedelta(days=days),
)
```
Look at the `status` field. Its `Literal` is a fixed list of the values it
can hold. That list is what will let the task know, later, whether the
lookup worked. Write one for any tool a task will end on.
Every file in `tools/` is a tool already. Name it in the agent's own list in
`agent.yaml` to say the agent may call it.
```yaml agent.yaml theme={null}
agents:
- name: assistant
prompt: instructions.md
think: assistant_model
speak: assistant_voice
tools:
- end_call
- look_up_parcel
```
And tell the agent what to do with it, at the end of `instructions.md`:
```markdown instructions.md theme={null}
# Parcels
When the caller asks where their parcel is, ask for the tracking number, say it
back to them, and look it up. Tell them the day it is due.
```
```sh theme={null}
unmute validate my-agent
```
This already works, and for many agents it is enough. Stop here if the job
is one lookup and one answer. The rest of this page is for when you want the
lookup to be its own small conversation, and you want to keep what it
found.
A task can save what it learns. You say what that is by declaring a
field, once, with a type. `unmute init` already wrote a `state.py` next to
`agent.yaml` with an empty `State` class. Add two fields to it:
```python state.py theme={null}
from datetime import date
from pydantic import BaseModel, Field
class State(BaseModel):
"""What one call knows, shared by every agent and task in it."""
tracking_number: str = Field(
"", description="The tracking number of the parcel we found for this caller."
)
delivery_date: date | None = Field(
None, description="The day that parcel is due, written year-month-day."
)
```
`date` is a Pydantic type. A value that is not a date in that form is
refused where it enters, and the model is told the form, so it can try
again. The description is read by the model, so write it for the model.
`unmute` reads `state.py` through `uv`, so `uv` must be on your `PATH`.
Nothing reads these yet. Declaring a value and using it are two separate
things, and that is on purpose.
```sh theme={null}
unmute validate my-agent
```
A task is written inside the agent that runs it, under `tasks:`. It has a
name, a `when:` that tells the model when to run it, its own prompt file,
and its own tools.
Make a `tasks/` folder next to `agent.yaml` and put the task's prompt in it:
```markdown tasks/find-parcel.md theme={null}
# Your job
Find the caller's parcel.
Ask for the tracking number. Say it back to them in groups of two or three
characters and ask if that is right. Only then look it up.
If the parcel is not found, say so, and ask the caller to check the number and
read it again.
```
Then add the task to the agent:
```yaml agent.yaml theme={null}
agents:
- name: assistant
prompt: instructions.md
think: assistant_model
speak: assistant_voice
tools:
- end_call
- look_up_parcel
tasks:
- name: find_parcel
when: The caller wants to know where their parcel is.
prompt: tasks/find-parcel.md
tools:
- look_up_parcel
```
```sh theme={null}
unmute validate my-agent
```
It still validates, and it warns:
```text wrap theme={null}
agent "assistant" holds every tool of its step "find_parcel" (look_up_parcel), so it can do the step's work without entering it and the step's save: may never run: drop look_up_parcel from agent "assistant" tools and leave them on the step
```
Read that warning, because it is the most common mistake with a first
task. The model sees one list with the agent's tools and the task in it,
and it takes the shortest route. If the agent can call `look_up_parcel`
itself, it will, and the task never runs. The fix is to move the tool: take
it off the agent and leave it on the task.
```yaml agent.yaml theme={null}
agents:
- name: assistant
prompt: instructions.md
think: assistant_model
speak: assistant_voice
tools:
- end_call
tasks:
- name: find_parcel
when: The caller wants to know where their parcel is.
prompt: tasks/find-parcel.md
tools:
- look_up_parcel
```
The task now says who may call `look_up_parcel`.
Change the agent's prompt to match. It no longer looks parcels up itself:
```markdown instructions.md theme={null}
# Parcels
When the caller asks where their parcel is, run find_parcel.
```
```sh theme={null}
unmute validate my-agent
```
The warning is gone. The model now has one way to look up a parcel, and it
goes through the task.
Right now the task can find the parcel, but when it ends, what it found is
gone. `save:` says which values the task saves, and where. Each line is
one variable you declared, and the tool result field it takes:
```yaml agent.yaml theme={null}
tasks:
- name: find_parcel
when: The caller wants to know where their parcel is.
prompt: tasks/find-parcel.md
tools:
- look_up_parcel
save:
- tracking_number: result.tracking_number
- delivery_date: result.delivery_date
```
```sh theme={null}
unmute validate my-agent
```
Here is what that line did. Every task gets a `finish` call, a function
the model calls to say the task is done. `save:` gives that call two
arguments, `tracking_number` and `delivery_date`, typed from the `State` fields
they land in. When the model calls `finish`, each value is checked against
its type. If one is wrong, nothing is saved and the task stays open, so a
bad date never gets written down.
You do not write "call finish when you are done" in the task's prompt.
unmute-core adds that rule for you.
A wrong name on the left is refused with the line it is on:
```text theme={null}
unmute: validate my-agent: build: agent.yaml:36: task "find_parcel": save writes to "due_date", which State in state.py does not declare
```
Saving a value does not show it to anybody. A prompt sees a saved value only
when it names it, with the variable in double braces. Add this to the end
of `instructions.md`:
```markdown instructions.md theme={null}
# Parcels
When the caller asks where their parcel is, run find_parcel.
The parcel we found on this call: {{state.tracking_number}}, due {{state.delivery_date}}.
When those are filled in, tell the caller the day and do not run find_parcel
again unless they give a different number.
```
Before the task has run, an empty value renders as `none recorded yet.`, so
write the sentence so it still makes sense with those words in it. After
the task has run, the owner reads the real values on its next turn and can
answer without looking the parcel up again.
```sh theme={null}
unmute validate my-agent
```
So far the task ends when the model decides to call `finish`. That is one
more model request after the lookup, and one more chance for the model to
do something else first. The tool already knows whether it worked: its
`status` is `found` or `not_found`. An outcome on the tool lets that result
end the task. The tool becomes an entry with a `name:` and `outcomes:`:
```yaml agent.yaml theme={null}
tasks:
- name: find_parcel
when: The caller wants to know where their parcel is.
prompt: tasks/find-parcel.md
tools:
- name: look_up_parcel
outcomes:
- if:
- status:
- found
then: done
save:
- tracking_number: result.tracking_number
- delivery_date: result.delivery_date
```
```sh theme={null}
unmute validate my-agent
```
Read it as a sentence: "when `look_up_parcel` returns `status: found`, the
task is done". When that happens, the task saves its `save:` straight from
the tool result and ends. The model is not asked, and the result never
reaches it. When the status is `not_found`, no outcome matches. The result
goes back to the model as normal and the task stays open, which is exactly
when you want the prompt's "ask the caller to check the number" line to do
its job.
| | Who decides the task is finished |
| - | - |
| no `then: done` outcome | the model, by calling `finish` |
| a `then: done` outcome | the tool's own result, matched by its `if:` |
Two rules keep this honest, and the compiler holds both. An outcome starts
with an `if:` that checks the result:
```text theme={null}
unmute: validate my-agent: load: agent.yaml:36: task "find_parcel": an outcome of look_up_parcel starts with if: or else:, and this one has neither
```
And every `if:` value has to be one the tool's return type allows, here
the `Literal` on `status`, so a typo is caught here and not on a call that never ends:
```text theme={null}
unmute: validate my-agent: build: agent.yaml:36: task "find_parcel": look_up_parcel never returns status: fund; it declares found, not_found
```
The task still has a `finish` call. When the call runs, the unmute-core
library adds lines about it under your own instructions. They name the
values `finish` saves, and they say the step ends by itself when
`look_up_parcel` succeeds. See [tasks in unmute-core](/core/reference/tasks).
So the `finish` call is still there. The model uses it when the caller asks
for something the task cannot do, and for a value the task already holds.
Your own prompt should not argue with those lines.
A task's first turn is normally a model request that writes an opening
line. This task always opens the same way: it asks for the tracking
number. Say that line yourself and skip the request:
```yaml agent.yaml theme={null}
tasks:
- name: find_parcel
when: The caller wants to know where their parcel is.
prompt: tasks/find-parcel.md
start:
say:
- Sure. What is the tracking number?
listen: true
```
`start:` replaces the model's first turn. `say:` is one fixed line, spoken
exactly as written. `listen: true` says: speak it, then wait for the
caller. The line is recorded as the task's own first turn, so the caller's
answer lands in a conversation the task can see.
Update the task's prompt so it does not ask the question twice:
```markdown tasks/find-parcel.md theme={null}
# Your job
Find the caller's parcel.
You have already asked for the tracking number. Say it back to them in groups
of two or three characters and ask if that is right. Only then look it up.
If the parcel is not found, say so, and ask the caller to check the number and
read it again.
```
```sh theme={null}
unmute validate my-agent
```
```sh theme={null}
unmute dev my-agent
```
Your keys from the quickstart are still in `.env`. When the browser opens,
ask where your parcel is and read out one of the two numbers in the
handler, "A B one two three four five six".
Watch the dev page while you talk. The task shows up as its own row when
the model enters it, then `look_up_parcel` gets a row of its own, and then
the agent answers. If you never see the task's row, the model went round
it. Check two things: that the agent does not hold the task's tool, and
that the `when:` line describes what the caller actually said. [Running it
locally](/dev/overview) explains every row on that page.
## The whole file
This is `agent.yaml` at the end, with the scaffold's comments taken out. The
three lists near the top are the whole change: one tool on the agent, one task
nested under it, and the task's own tool with its outcome, `start:` and `save:`.
```yaml theme={null}
name: my-agent
entry_agent: assistant
agents:
- name: assistant
prompt: instructions.md
think: assistant_model
speak: assistant_voice
tools:
- end_call
tasks:
- name: find_parcel
when: The caller wants to know where their parcel is.
prompt: tasks/find-parcel.md
start:
say:
- Sure. What is the tracking number?
listen: true
tools:
- name: look_up_parcel
outcomes:
- if:
- status: found
then: done
save:
- tracking_number: result.tracking_number
- delivery_date: result.delivery_date
secrets:
- OPENAI_API_KEY
- SLNG_API_KEY
models:
think:
assistant_model:
description: default reasoning model
provider: openai
model: "gpt-5.6-terra"
params:
reasoning_effort: none
speak:
assistant_voice:
description: default voice
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
turn:
detector:
provider: livekit
model: turn-detector-mini
conversation:
greeting:
speaks_first: agent
say: "Hi there, I'm listening. What can I help you with?"
```
`channels:` and `capacity:` live in targets.yaml, above `targets:`.
```yaml targets.yaml theme={null}
channels:
- name: web
kind: realtime_audio
capacity:
peak_sessions: 10
max_sessions: 20
avg_session_duration: 5m
```
## What you have now
| Key | What it says | If you leave it out |
| - | - | - |
| `when:` | when the model should run the task | the task is only usable as a step of a flow |
| `tools:` on the task | what the task may call | the task talks but cannot look anything up |
| `save:` | what the task saves, and where | the task can still finish, and keeps nothing |
| `outcomes:` with `then: done` | which tool result means the task is done | the model decides, by calling `finish` |
| `start:` | a fixed first line, and no model request to write it | the model writes the opening line |
## Where to go next
Every task key in full: history, what returns, sharing a task between agents.
Two or more tasks that have to run in a fixed order.
Why the model skips a task, and what to give it so it does not.
Choosing what to save, and writing prompts that read well when it is empty.
# Handoffs
Source: https://unmute.ai/build/orchestration/handoffs
Move the caller to an agent with different instructions and tools.
A handoff moves the caller from one agent to another. The receiving agent owns
the rest of the call. Nothing returns automatically.
Use a handoff when two roles need different instructions, tools, or
permissions. Use a [task](/build/orchestration/tasks) when the work should
return control to the same agent.
On this page:
* [Declare a handoff](#declare-a-handoff) - one block on the agent
* [Every key a handoff takes](#every-key-a-handoff-takes) - all seven
* [Share only intentional saved values](#share-only-intentional-saved-values) - saving is not sharing
* [Choose conversation history](#choose-conversation-history) - what travels with the caller
* [A handoff does not return](#a-handoff-does-not-return) - the one thing to remember
## Declare a handoff
```yaml agent.yaml theme={null}
entry_agent: booking_desk
agents:
- name: booking_desk
prompt: instructions.md
think: reasoning
speak: voice
handoffs:
- name: to_appointment_manager
to: appointment_manager
when: The caller wants to change an existing appointment.
say:
- I’m connecting you with our appointment manager now.
- name: appointment_manager
prompt: agents/appointment-manager.md
think: reasoning
speak: voice
```
The agent that hands over writes the block. Another agent that wants the same
handoff lists its bare name, `- to_appointment_manager`. A bare name nobody
defines is refused.
### Every key a handoff takes
A lower snake case name, unique across the package.
An existing agent name. The conversation moves to that agent and does not return. No
destination is inferred.
The situation the model reads to decide whether to hand over. Omission supplies no
trigger guidance, so write one.
Any number of fixed lines. One is picked each time the handoff runs, never the one
said last, and the next agent's voice says it. A line takes no `{{ }}` placeholder and
a blank line is refused. Omit for a silent handoff.
Pairs of `variable: result.field` saved as the handoff happens. Omit to save nothing.
A tool of the receiving agent, run in code as it takes the call, so its first turn
comes from the tool and not from a model request. Keys `call` and `with`.
Name of the receiving agent's tool. Required inside `start`.
The tool's inputs, as `- day: state.requested_day`. A `?` after the value lets the call
run without it; a value without one is required.
The [history fields](/reference/agent-yaml#context). Omitted means `messages`. Saved
values are visible only where the receiving prompt names them.
## Share only intentional saved values
Declare a value once and reference it in the receiving prompt:
```python state.py theme={null}
class State(BaseModel):
appointment_id: str = Field(
"", description="The appointment selected during this call."
)
```
```markdown agents/appointment-manager.md theme={null}
You are handling appointment {{state.appointment_id}}.
Ask what the caller wants to change.
```
The receiving agent gets the saved `appointment_id` because its prompt names
it. It does not receive other variables automatically. A dotted placeholder
sends only that field. With `messages`, it can also read facts spoken earlier.
To avoid repeating verification or asking for an appointment already selected,
reference the saved verification status and appointment in the receiving
prompt, then explain how to use them. The [context guide](/best-practices/context-scope)
walks through this choice and the return behavior of tasks.
## Choose conversation history
History defaults to `messages` when `context` or `history` is omitted.
```yaml agent.yaml theme={null}
agents:
- name: booking_desk
handoffs:
- name: to_appointment_manager
to: appointment_manager
when: The caller wants to change an existing appointment.
context:
history: reset
```
| `history` | The receiving agent gets |
| - | - |
| `messages` | Earlier caller and agent speech, without tool records. |
| `full` | Earlier speech and paired tool records, without old instructions. |
| `last_n` | The newest bounded entries. |
| `reset` | No earlier conversation. |
| `summary` | A generated summary on LiveKit only. |
With `reset`, no trigger sentence or automatic briefing is added. Save the
needed facts before the handoff and reference them in the receiving prompt. If
a needed fact was not saved, the receiver asks the caller.
`messages` keeps spoken content. It is useful context sharing, not transcript
redaction.
## A handoff does not return
The second agent owns the call from that point. Returning to the first agent is
another declared handoff in the opposite direction.
When a task invokes a handoff, that task and the remaining flow steps end
before the receiving agent starts.
On LiveKit, the receiving agent's own handoffs are hidden for its first
automatic turn. They return on the next caller turn. This prevents two agents
from bouncing the call before the caller hears anything.
## Try it
The salon is the shipped example with a handoff in each direction between the
concierge and the complaint specialist. These commands need a clone of the
unmute repo:
```sh theme={null}
unmute validate examples/salon-concierge
unmute dev examples/salon-concierge --target pipecat
```
Tools, tasks, flows, or a second agent: which split to reach for, and what it costs.
## Where to go next
When control should come back instead.
Task, flow or handoff, and what each one costs.
Deciding what the receiving agent should be able to read.
Handing the caller to a person, which is a different thing.
# Orchestration
Source: https://unmute.ai/build/orchestration/overview
Three ways to split one agent into parts, and where each is taught.
Orchestration is how you split one agent into parts. There are three shapes,
and the difference that matters is whether control comes back.
On this page:
* [The three shapes](#the-three-shapes) - task, flow, handoff
* [What each shape does to the call](#what-each-shape-does-to-the-call) - one diagram each
* [Read one example against the other](#read-one-example-against-the-other) - the same salon, built two ways
* [Read them in order, then choose](#read-them-in-order-then-choose) - where to go
New here? Read [How a package fits together](/build/how-a-package-fits-together)
first. It is one page, it answers "I want two agents, each with tasks, where do I
start?", and everything below assumes it.
## The three shapes
| Shape | What it is | Where it is taught |
| - | - | - |
| **Task** | one step the agent runs, which saves typed values and returns | [Tasks](/build/orchestration/tasks) |
| **Flow** | several tasks in a fixed order, sharing what they learn | [Flows](/build/orchestration/task-groups) |
| **Handoff** | one agent gives the caller to another, and does not get them back | [Handoffs](/build/orchestration/handoffs) |
The difference that matters most is whether control comes back. A task returns. A
handoff does not.
Tasks and flows compile on Pipecat, LiveKit and SLNG. Handoffs need
Pipecat or LiveKit, because SLNG writes one agent. Twilio compiles one agent
with one prompt and refuses all three. `unmute validate` says so and names
the way out.
None of these is how you reach a person: that is an
[transfer](/transfers/overview), and what it can do depends on the phone route.
Whichever shape you reach for, you write it the same way: as a name in one of
the agent's five lists. [The five things an agent can
do](/build/how-a-package-fits-together#the-five-things-an-agent-can-do) shows
the lists and which ones come back.
## What each shape does to the call
Each picture answers two questions: who is talking to the caller, and does
control come back to the agent that started.
### A tool
The agent stays in charge. It calls the tool, reads the result, and keeps
talking.
```mermaid theme={null}
sequenceDiagram
participant Caller
participant Owner
participant Tool
Caller->>Owner: asks a question
Owner->>Tool: calls the tool
Tool-->>Owner: result
Owner->>Caller: answers, and keeps the call
```
### A task
The owner enters the task. The task talks to the caller with its own prompt and
tools. When the model calls `finish`, the values in `save:` are saved and the
owner continues, reading them through its own placeholders.
```mermaid theme={null}
sequenceDiagram
participant Caller
participant Owner
participant Task
Caller->>Owner: asks for something the task covers
Owner->>Task: enters the task
Task->>Caller: talks with its own prompt and tools
Caller->>Task: answers
Note over Task: the model calls finish
Task-->>Owner: status, values saved
Owner->>Caller: continues, reading the saved values
```
### A task that ends on a tool
The same, except the tool decides. When the tool's result matches an outcome
with `then: done`, the task saves and ends by itself. The model makes no `finish` call, and the
owner speaks next.
```mermaid theme={null}
sequenceDiagram
participant Caller
participant Owner
participant Task
participant Tool
Owner->>Task: enters the task
Task->>Caller: asks what it needs
Caller->>Task: answers
Task->>Tool: runs the tool
Tool-->>Task: result matches the outcome
Note over Task: the task saves and ends, no finish call
Task-->>Owner: status
Owner->>Caller: acknowledges, and keeps the call
```
### A handoff
The first agent hands the caller to a second agent. The second agent owns the
rest of the call. Nothing comes back.
```mermaid theme={null}
sequenceDiagram
participant Caller
participant Owner
participant AgentB as Agent B
Caller->>Owner: asks for something Agent B owns
Owner->>AgentB: hands the caller over
AgentB->>Caller: takes the rest of the call
Note over Owner: nothing comes back
```
## Read one example against the other
Two shipped packages are the same salon, built two ways.
[`examples/salon-concierge-single-prompt`](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge-single-prompt)
is one agent with one prompt: no tasks and no handoffs. Its tools, pre-fetch,
model and turn taking are the same as the other package's.
[`examples/salon-concierge`](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge)
is the structured one, with tasks, a flow, handoffs and saved values.
Read one against the other to see what the structure bought.
## Read them in order, then choose
Start with the first page: it adds one task to the package you already have,
one key at a time. The next three pages are one shape each, with the example
package that uses it. The last page is the one to come back to when you are
deciding: it pairs the symptom you have with the shape that fixes it, and says
what each shape costs.
From no task to a task that says what success looks like, on your own package.
Run a step, keep the answer.
A fixed order, and shared context.
Two agents, two sets of rules.
Which split to reach for, and what it costs.
# Flows
Source: https://unmute.ai/build/orchestration/task-groups
Run several tasks in a fixed order.
A flow is an ordered sequence of tasks. Use one when the order must be a
runtime guarantee. A task that runs inside a flow is called a step of that
flow. The runtime calls a flow a task group.
It also costs less than the same tasks run one at a time. The agent chooses the
flow once; each step after the first opens by itself. Two tasks the agent picks
between spend a model request on the choice between them, and that request
speaks nothing and does nothing.
On this page:
* [Declare a flow](#declare-a-flow) - steps, in order
* [Every key a flow takes](#every-key-a-flow-takes) - all ten
* [Skip a step whose work is already done](#skip-a-step-whose-work-is-already-done) - `skip_when_confirmed:`
* [What stops a flow](#what-stops-a-flow) - unserved, handoff, finish
* [Context between steps](#context-between-steps) - shared or isolated
## Declare a flow
```python state.py theme={null}
from typing import Literal
from pydantic import BaseModel
class State(BaseModel):
customer_id: str = ""
selected_slot: str = ""
booking_status: Literal["booked", "cancelled"] | None = None
```
```yaml agent.yaml theme={null}
agents:
- name: appointment_desk
prompt: instructions.md
think: reasoning
speak: voice
tasks:
- name: identify_customer
prompt: tasks/identify-customer.md
tools:
- lookup_customer
save:
- customer_id: result.customer_id
- name: select_appointment
prompt: tasks/select-appointment.md
tools:
- check_slots
save:
- selected_slot: result.selected_slot
- name: finalize_appointment
prompt: tasks/finalize-appointment.md
tools:
- book_appointment
save:
- booking_status: result.booking_status
flows:
- name: appointment_flow
when: The caller wants to book, reschedule, or cancel an appointment.
steps:
- identify_customer
- select_appointment
- finalize_appointment
```
The agent that writes the flow block defines it. Another agent runs the same
flow by listing its bare name under its own `flows:`.
These three tasks have no `when:`. The flow decides when they run, so they
need no trigger of their own. A task an agent runs on its own does need one,
and a task with no `when:` that no flow lists is refused, because nothing
would ever run it.
Each `steps` entry names a task defined in the package, under some agent's
`tasks:`. It does not have to be the agent that runs the flow: the flow is
what makes each step reachable. `save:` derives each task's finish arguments
and saves the values needed later.
### Every key a flow takes
A lower snake case name, unique across the package.
One or more task names, in execution order. An object requires `task` and may set
`skip_when_confirmed` to a variable that task confirms. Omit that condition to run the
step every time. An empty or absent steps list is refused.
The situation the model reads to decide whether to run the flow. Omission is accepted
but supplies no trigger guidance, so write one.
One fixed spoken line, with no `{{placeholders}}`, when the flow starts. Omit for no
announcement. Write several as a list and the caller hears one each time.
`State` fields the model fills from the conversation when it picks the flow. The steps
read them. Omit to fill none.
Steps that run without holding the caller. Each name must be one of `steps`. Omit to
run every step in turn.
Accepts `shared` or `isolated`. Omit it for `shared`. Each member still applies its own
`context.history`; an isolated flow cannot be widened by a member’s `full`.
Accepts `return`, `transfer`, or `end`. Omit it for `return`.
Required with `then: transfer`: an existing agent name. Refused for `return` or `end`;
there is no inferred destination.
Only `results` is accepted. Omission also means `results`.
## Skip a step whose work is already done
A step is a bare task name, or an item that says how the flow treats it:
```yaml agent.yaml theme={null}
steps:
- task: identify_customer
skip_when_confirmed: customer_id
- select_appointment
- finalize_appointment
```
The flow skips that step when the named variable is confirmed at the moment
the flow starts, and runs it otherwise. A bare step always runs. This is what
makes a second booking on one call cost nothing extra: the caller is identified
once, and the flow knows it.
`skip_when_confirmed:` names a variable the skipped step itself confirms, with
[`confirm:`](/reference/variables#confirm-marks-a-value-the-caller-has-to-agree-to)
on the variable. Confirmed here is a real mark on the variable, set when the
step named under `confirm:` saves a value. It is not the same as a prompt
sentence saying the caller was verified: the compiler reads the mark, never the
prose. Anything else is refused: a variable nobody confirms would leave the
step running forever or never, and a variable another step confirms would let
this flow skip somebody else's work.
There is a side effect, and it is the point. A step some flow names this way
withdraws the confirmation of the values it confirms every time it is entered,
including on its own outside the flow. So a caller correcting their number
re-verifies it, and the next flow run does not skip the step on the strength
of the number they just replaced. Values derived from a withdrawn one follow it.
## What stops a flow
A flow stops when a step ends unserved, whichever `context_scope` it has: the
later steps do not run, and the owner is handed the unserved status. Running
the next step would answer a question nobody asked.
A handoff can arrive while a tool that ends the step is still running, or in
the same response as one. Either way the step's own work is committed first,
and the caller moves after. The booking is not lost on the way out.
A request the caller makes at a [`reset`](/best-practices/context-scope) or an
isolated boundary reaches nobody: the step that hears it has no way to pass
words on other than
[`unserved_request`](/build/orchestration/tasks#what-returns), and an isolated
step's context does not carry back. Keep the request in the caller's own words
in `unserved_request` and let the owner act on it.
## Context between steps
`shared` lets later tasks inherit the flow's running conversation. `isolated`
starts every member without inherited flow conversation.
Each task still applies its own `context.history`. Omitted history means
`messages`. An isolated flow also prevents a member's `full` policy from
recovering conversation outside that flow.
Task results are private. The next task sees only neutral completion status,
the conversation allowed by its history choice, and saved values explicitly
referenced in its prompt.
```markdown tasks/select-appointment.md theme={null}
Find an available slot for customer {{state.customer_id}}.
```
The flow owner gets its original context back plus `completed` or `unserved`.
It reads saved values through its own placeholders.
A member task may hand off directly to another agent. That ends the current
task and skips the remaining flow steps.
## LiveKit status
Flows use a LiveKit API that upstream marks experimental. The package
still validates and compiles normally.
## Where to go next
The shape that does not return: a lasting change of role.
Compare tasks, flows, and handoffs.
Why a task you declared never runs, and how to fix it.
# Tasks
Source: https://unmute.ai/build/orchestration/tasks
Run one step of a call with its own prompt and tools, save typed values, and return control.
A task is one step of a call. It has its own instructions and tools. When it
finishes, control returns to the agent that called it. That agent is the owner.
Inside a flow, each task is one step of the flow.
To the model, a task is one more entry in its function list, next to the
agent's tools. Calling it switches to the task's prompt and tools. When the
task finishes, the owner's prompt and tools come back.
Use a task when one bounded piece of work needs a smaller prompt or a smaller
tool list. Use a [flow](/build/orchestration/task-groups) when several
tasks must run in order. Use a [handoff](/build/orchestration/handoffs) when a
different agent should own the rest of the call.
New to tasks? [Your first task](/build/orchestration/first-task) adds one to
the package `unmute init` writes, one key at a time.
On this page:
* [Quickstart](#quickstart) - one task, start to finish
* [Every key a task takes](#every-key-a-task-takes) - all nine
* [Say what success looks like](#say-what-success-looks-like) - let a tool's outcome end the step
* [Choose conversation history](#choose-conversation-history) - what the task can read
* [What returns](#what-returns) - and what does not
* [Advanced](#advanced) - lists, sharing, starting a step
* [Troubleshooting](#troubleshooting) - the two that come up most
## Quickstart
A task is one entry under an agent's `tasks:`. This one identifies the caller
and saves what it learns:
```python state.py theme={null}
class State(BaseModel):
customer_id: str = ""
```
```yaml agent.yaml theme={null}
agents:
- name: appointment_desk
tasks:
- name: verify_customer
when: Identify the caller before handling an appointment.
prompt: tasks/verify-customer.md
tools:
- lookup_customer
save:
- customer_id: result.customer_id
```
```sh theme={null}
unmute validate my-agent
```
Four keys carry it: **what it is** (`name`, `prompt`), **when to run it**
(`when`), **what it can use** (`tools`), and **what it saves** (`save`).
## Declare a task
```python state.py theme={null}
class State(BaseModel):
customer_id: str = Field("", description="The customer record selected for this call.")
customer_name: str = Field("", description="The customer's name.")
```
```yaml agent.yaml theme={null}
agents:
- name: appointment_desk
# the agent's other keys stay as they are
tasks:
- name: verify_customer
when: Identify the caller before handling an appointment.
prompt: tasks/verify-customer.md
tools:
- lookup_customer
save:
- customer_id: result.customer_id
- customer_name: result.customer_name
```
### Every key a task takes
Two are required. The rest are how you shape the step.
A lower snake case name, unique across all agents in the package. To reuse an existing
task, write its bare name instead of defining it again.
Path to the task’s Markdown prompt inside the package. No prompt is inferred.
The situation the model reads to decide whether to start the task. If omitted, the task
is a definition only and must be used in a flow; it cannot be attached elsewhere
by bare name.
Tools loaded by the package. Each item is a bare tool name, or a block that starts
`- name: ` and adds `confirm:` and `outcomes:` for this step only. Omit for no
ordinary tools in this task; it does not inherit its owner’s tools.
Lines said to read the call back before the tool runs. The tool runs on the caller’s
yes. Lines read `{{input.x}}`. Needs a `then: done` outcome on the same tool.
What the step does with each result of this tool, top to bottom, first match wins.
See [Say what success looks like](#say-what-success-looks-like).
A typed match on the result, such as `- status: booked` or `- status: [booked, moved]`.
Matches every result no `if:` above matched. Last, and at most one.
Pairs of `variable: result.field` saved only when this outcome matches.
Lines said for this result. Several lines are alternatives. Lines read `{{result.x}}`.
Accepts `done` or `failed`. Omitted means the step goes on.
Pairs of `variable: result.field`, including dotted result paths. Use `variable+` to
append one list item. Omit to save no values; the task can still finish. The destination variable already owns the type
and description, so the task does not repeat them.
What the step does as it opens: `say`, `listen`, `call` and `with`. Omitted means the
model writes the opening turn. See [Start a step](#start-a-step).
Bare names of handoffs an agent defines. Omit for no handoffs from this task.
`State` fields the model fills from the conversation when it starts the task, such as
the service the caller asked for. Omit to fill none.
The [history fields](/reference/agent-yaml#context). Omit for `history: messages`. A
returning task restores its owner’s earlier context and adds only completion or unserved
status.
A `models.think` entry name. LiveKit only. If omitted, use the entry agent’s think
profile, even when another agent defines the task.
There is no `tasks:`, no `flows:` and no `transfers:` key on a task. A
task cannot run another task or reach a person directly, and that is structure
rather than a rule to remember: there is no key to write it in.
## How a task finishes
Every task gets a `finish` call. The model uses it to say the task is done and
to hand over the values in `save:`. A tool outcome with `then: done` is
different: the tool's own result ends the task, so the model does not have to
make that call. The next section covers it.
The `finish` call for this example takes `customer_id` and `customer_name`. It
checks every value before saving any of them. If one value is invalid, the task
stays open and no value changes.
A task that saves nothing omits `save:`. The model can still call `finish`.
## Say what success looks like
How does the task know it worked? Without an outcome, the model decides. It
runs a tool, reads the result, and calls `finish`. With an outcome that says
`then: done`, the tool's own result decides. You name the tool in the step's
`tools:` and say what each result looks like.
| | Who decides the task is finished |
| - | - |
| no `then: done` outcome | the model, by calling `finish` |
| a `then: done` outcome | the tool's own result, matched by that outcome's `if:` |
This also removes a model request. A task that runs a tool and then asks the
model to call `finish` spends a whole request on a decision the tool already
made. The saving grows with the number of tasks a call runs through.
```yaml agent.yaml theme={null}
- name: manage_booking
prompt: tasks/booking.md
tools:
- find_slots
- name: save_booking
confirm:
- Shall I book {{input.service}} for {{input.date}} at {{input.time}}?
outcomes:
- if:
- status:
- booked
- cancelled
say:
- You're all set for {{result.appointment.date}}. Anything else?
then: done
- else:
say:
- That did not go through. Shall I try another time?
save:
- appointment: result.appointment
```
When `save_booking` returns a result that matches the `if:`, the step says the
line, saves its `save:` rows from that result and ends. The result never
reaches the model. Anything else falls to the next outcome, or goes back to the
model when none matches. That is what keeps a failed booking a conversation
rather than a saved one.
An outcome is how a step reacts to one tool result. These rules hold for all of
them:
* **Top to bottom, first match wins.** An outcome starts with `if:` or `else:`.
`else:` takes every result no `if:` matched, comes last, and appears once.
* **`then: done` ends the step as completed.** `then: failed` ends it as failed,
and a flow stops unless the step is non-blocking. With no `then:` the step
goes on. Only a step's outcomes take `then:`.
* **Order them `then:` first.** Write the outcomes with `then:`, then those
without, then `else:`. `else:` cannot say `then: done`. An `else:` with
`then: failed` cannot follow an outcome without `then:`.
* **No `then:` needs `say:`.** Its `save:` reads `result.` only.
* **Saving.** A `then: done` outcome with no `save:` of its own saves the step's
`save:` rows from the tool's result. A step cannot mix done outcomes with and
without their own `save:`.
* **`confirm:` needs a done outcome.** The tool entry needs at least one
`then: done` outcome. The read-back is said before the tool runs, and the
tool runs on the caller's yes.
* **What a line reads.** `{{state.x}}` reads State. A `confirm:` line reads
`{{input.x}}`. An outcome `say:` reads `{{result.x}}`. A line with no tool,
such as a greeting or a nudge, reads State only.
An `if:` item is `field: value`, or a list of values that are alternatives.
Items on different fields are all required. Every value has to be one the tool
declares in its own output `enum:`, so a typo is a refusal at compile time
rather than a task that never ends by itself.
A tool in a step is not always a bare name. A top-level `tools:` entry can
carry the same `outcomes:` for every agent that uses the tool; see
[Tools in the agent file](/reference/agent-yaml#tools).
On the [slng target](/targets/slng), a task takes one outcome with `then: done`
for now, because SLNG supports one finishing tool per task today. It may carry
up to 5 `say:` lines. SLNG says them itself when the tool's result matches. A
line may read `{{state.x}}` for a whole saved value, or `{{result.x}}` for a
field of the tool's result. SLNG ends a step only as done, so `then: failed` is
refused, and so is a `confirm:` read-back. The tool needs a known output: a
typed local tool, or a hosted `slng:` tool with a mirror.
```yaml agent.yaml theme={null}
tools:
- name: book_slot
outcomes:
- if:
- status: booked
say:
- "Thanks for having us. You're booked for {{result.booking.time}} on {{result.booking.day}}."
then: done
save:
- booking: result.booking
```
`result.` in the step's `save:` names an output property of every tool
that ends the step, so one tool returning `appointment` and another returning
nothing is refused.
Four things follow from a task that ends on its tool:
* **The ending tools close.** Once one of them succeeds, none of them runs
again in that run of the task. A new booking is a new request from the
caller, and a new run of the task.
* **The `finish` call is still there.** The model uses it for a request the
task cannot serve, for values the task already holds, and for recording a
result whose save was refused. That repair keeps the values the tool
returned, so a reference the tool handed back is never retyped by the model.
* **The appended text changes.** The text Unmute adds to your instructions
still tells the model to call `finish` when the step is complete. It then
says that the named tools end the step by themselves, and that `finish` is
not to be called after one of them succeeds. Your own instructions should not
contradict it.
* **The owner speaks.** The task says nothing after its tool unless the outcome
has a `say:`. The next step of a flow opens, or the owner speaks once when
control returns, so the acknowledgement belongs in the owner's prompt.
## What the model gets for a task
The prompt a task runs on has four parts. You write the first one.
1. **Your instructions file**, as written.
2. **The appended finish rule.** Unmute adds it after your text. It names the
`finish` call, lists the values from `save:`, and gives the model a way
out for a request the task cannot serve. You do not write "call finish when
you are done" yourself.
3. **The values your placeholders name.** Each `{{state.variable}}` in your
instructions is replaced with the saved value. No other saved value is
added.
4. **The history you chose** with `context.history`. When omitted, it is
`messages`.
For the task declared above, the appended rule reads:
```text theme={null}
When this step is complete, call `finish` with: customer_id, customer_name.
`unserved_request` is for a request this step cannot serve. Do this step's own work first, and never use it to skip that work: the caller's original reason for being here is not an unserved request. If a handoff here covers what they want, call that handoff instead. Only when no tool and no handoff here can serve what the caller is asking, call `finish` with their request in `unserved_request`, in their own words, rather than refusing or explaining what you cannot do here. The agent that owns this step reads that status and takes the caller from there.
```
With a `then: done` outcome, a sentence is added between those two paragraphs. It says the
named tools end the step by themselves and that `finish` is not to be called
after one of them succeeds. On the Pipecat target the call has a longer name
that includes the task's name. The rule is the same.
## A task's contract
Four keys make a task that knows what it saves, when it is done, and when it
can be skipped. They live in three places.
| Key | What it declares | Where it is written | If you leave it out | Taught on |
| - | - | - | - | - |
| `save:` | which values the task saves, and into which variables | on the task | the task saves nothing, and can still finish | this page, and [Variables](/reference/variables#saving-a-task-result-to-a-variable) |
| `outcomes:` with `then: done` | which tools end the task by their own result, matched by `if:` | on the tool entry in the task's `tools:` | the model decides the task is done, by calling `finish` | [Say what success looks like](#say-what-success-looks-like) |
| `confirm:` | which task has to hear the caller agree before a value is used | on the variable, naming the task | the value is settled the moment it arrives, and any prompt may read it | [Variables](/reference/variables#confirm-marks-a-value-the-caller-has-to-agree-to) |
| `skip_when_confirmed:` | which variable, once confirmed, lets a flow skip this step | on the step entry in a flow's `steps:` | the step runs every time the flow runs | [Flows](/build/orchestration/task-groups#skip-a-step-whose-work-is-already-done) |
## Read a saved value
Saving and sharing are separate choices. Put a placeholder in the prompt that
needs the value:
```markdown tasks/booking.md theme={null}
The verified customer is {{state.customer_name}} with ID {{state.customer_id}}.
Help them manage their appointment.
```
The task receives saved state only through the values its prompt names.
Its history may separately contain facts spoken earlier. A description does not
send a value to the model. An unset value renders as `none recorded yet.`
A dotted reference selects one field and does not send its siblings:
```markdown theme={null}
Move appointment {{state.appointment.id}} to {{state.appointment.date}}.
```
See [Variables](/reference/variables) for models, dotted paths, append
rows, and confirmation.
## Choose conversation history
`context.history` is optional. When omitted, it is `messages`.
| `history` | The task receives |
| - | - |
| `messages` | Earlier caller and agent speech. Tool calls and replies are removed together. |
| `full` | Earlier speech and paired tool records. Earlier instructions are removed. |
| `last_n` | The newest `max_messages` entries, without a broken tool pair. |
| `reset` | No earlier conversation. Its own instructions and explicit placeholders still apply. |
| `summary` | A generated summary. Compiles on LiveKit only; Pipecat refuses this value. |
Tasks compile on Pipecat, LiveKit and SLNG. SLNG takes every history value
except `summary`. Twilio refuses tasks, including every task history value.
```yaml agent.yaml theme={null}
- name: reschedule_booking
prompt: tasks/reschedule-booking.md
tools:
- save_booking
context:
history: reset
```
```markdown tasks/reschedule-booking.md theme={null}
Move appointment {{state.appointment_id}} to {{state.appointment_date}}
at {{state.appointment_time}}.
If the requested date or time is unavailable, ask the caller.
Confirm the change before making it.
```
This reset task sees those three saved values because its prompt names them. It
does not receive the sentence that triggered the task. If the new date was not
saved, the task must ask for it again.
History controls model input; it does not redact speech already retained in a
different context. Use `reset` when the receiver should inherit no transcript.
The [step-by-step context guide](/best-practices/context-scope) shows how to
save the request first and keep the owner informed after the task finishes.
## What returns
The owner gets its pre-task context back plus one neutral status:
```json theme={null}
{"status":"completed"}
```
or:
```json theme={null}
{"status":"unserved"}
```
Task arguments, tool results, private task turns, and the text of an unserved
request do not cross back. The owner reads saved values through its own prompt
placeholders.
Every generated `finish` call includes an optional `unserved_request`. A task
uses it when it cannot complete the request with its tools or handoffs. A
non-empty value saves nothing. The owner sees the `unserved` status and
asks the caller what they need; it does not receive the private request text.
After a tool reports success, call `finish` right away with the result to save.
Let the owner confirm it once, using its own placeholders. If the task waits
for another turn, it may receive a new request before saving the first result.
An `unserved` status does not undo an action already completed by a tool.
## A finished task will not run again until the caller speaks
A task the owner already ran is refused, not re-run, while the caller has said
nothing since it returned. A completed result with no new caller turn above it is
the model reading its own finished work as a fresh request: the owner reruns the
whole step, repeats its announcement, and answers nothing. The refusal arrives
before the step's `start:` runs, so a refused call is silent.
Nothing to configure. Write the owner's prompt to expect it: a bare "yes" above a
completed task is the caller answering the question that task already asked and
acted on, so the owner should read its saved values and reply.
Better still, let the tool end the task. See
[Say what success looks like](#say-what-success-looks-like).
For requests that another agent can handle, a task may declare `handoffs:`.
Taking one ends the task and any remaining flow steps. See
[Handoffs](/build/orchestration/handoffs).
## Advanced
### Append and project values
Append one result to a list with `+`:
```python state.py theme={null}
class State(BaseModel):
appointments: list[Appointment] = []
```
```yaml agent.yaml theme={null}
save:
- appointments+: result.appointment
```
An absent item adds nothing. Repeating the same structured item does not add a
duplicate. Plain values may repeat.
A `save:` row may select a nested field:
```yaml agent.yaml theme={null}
save:
- appointment: result.appointment
- appointment_id: result.appointment.id
```
The whole-object row establishes the result's fields. The compiler then
checks the nested path and derives its type.
A step must return every whole value it saves. Mark one it may leave out
with `?` after the result field, as `- appointment: result.appointment?`. A
path like `result.appointment.id` reads part of a value the step already
returns, so it takes no `?`.
### Share a task across agents
Define a task once. Another agent can attach it by name:
```yaml agent.yaml theme={null}
agents:
- name: appointment_desk
tasks:
- name: verify_customer
when: Identify the caller before booking.
prompt: tasks/verify-customer.md
save:
- customer_id: result.customer_id
- name: billing_desk
tasks:
- verify_customer
```
Task names are unique across the package. Share a task only when both agents
should be able to run it: a task within reach is a task the model may choose.
### Start a step
By default a task's first turn is a model request. `start:` replaces that turn
with something said or run in code. It takes four keys, and each is optional.
* `say:` is said as the step opens. Several lines are alternatives.
* `listen: true` waits for the caller after the line, with no model request.
* `call:` and `with:` run a tool in code first. `with:` lists the tool's
inputs, such as `- day: state.requested_day`.
```yaml agent.yaml theme={null}
- name: take_stylist_note
when: The caller wants a note left for the stylist.
prompt: tasks/stylist-note.md
start:
say:
- What would you like me to pass on to your stylist?
listen: true
```
The line is spoken once and recorded as the task's own first turn, so a caller
answering it is answering something the task can see. A task with `listen: true`
and no `say:` is a warning, not a refusal: the caller hears nothing until they
speak, which is occasionally what you want and usually a mistake.
A `call:` runs the tool before the model speaks:
```yaml agent.yaml theme={null}
- name: manage_booking
when: The caller wants to manage a booking.
prompt: tasks/booking.md
start:
say:
- Let me pull up the diary.
call: find_slots
with:
- service: state.requested_service?
- date: state.requested_day?
```
A `with:` value with no `?` is one the tool requires. A value with `?` lets the
call run without it. The compiler checks both against the tool's input schema.
Then the step does one of four things:
* A required value is empty: the call does not run, and the step says `say:`
and listens.
* The value is already confirmed: the step is skipped.
* The tool has a `confirm:` line: the read-back is said instead of `say:`, and
the tool runs on the caller's yes.
* Otherwise the result goes through the tool's `outcomes:`, and the line the
outcome picks is said.
If you add a `say:`, tell the model not to repeat it with a second "let me
check" line.
### Task or second agent
| | Task | Second agent |
| - | - | - |
| control returns | yes | no |
| saved values | through `save:` | already live in call state; read only by explicit placeholders |
| prompt | one step | a whole role |
## Try it
`my-agent` is the package `unmute init` wrote in
[Your first agent](/build/your-first-agent). With a task in it:
```sh theme={null}
unmute validate my-agent
unmute dev my-agent
```
In the dev page the task shows as its own row, labelled `HANDOFF`, so you can
see it was entered. [The dev loop](/dev/overview) explains the rest of that
page.
The salon is the shipped example with tasks, a flow and handoffs. These
commands need a clone of the unmute repo:
```sh theme={null}
unmute validate examples/salon-concierge
unmute dev examples/salon-concierge --target pipecat
```
## Troubleshooting
### The model does the task's work itself and never enters it
The agent holds every tool the task holds, so the model takes the short route
and the task's `save:` never runs. `unmute validate` warns and names the tool
to move.
**Fix:** take the tool off the agent and leave it on the task. A task the model
can bypass is a task it will bypass.
### A task saves nothing on a call where it clearly ran
Every `save:` value is checked before any is saved. If one value is invalid,
nothing changes and the task stays open so the model can correct it.
**Fix:** check the destination's type against what the tool actually returns.
An `object` or `array` output landing on a plain destination is refused at
compile time; a wrong value at run time keeps the task open instead.
### An older package uses a retired key
| Earlier configuration | What to do now | Why |
| - | - | - |
| A task `result:` schema | Put the types on variables and use task `save:` | One declaration defines the saved value and the `finish` argument |
| Task or handoff `expect:` | Save needed facts first and reference them in the receiving prompt | Sharing is explicit, including with `reset` |
| Task `requires:` | Put the order in the owner's prompt and the task's `when:` | The model can follow the flow; tools with `with:` values still guard missing or unconfirmed values |
| An automatically appended state block | Add placeholders to each prompt that needs saved facts | Saving a value no longer shares it with every prompt |
| A task `finish:`, `replies:`, `assign:`, `opening:`, `announce:` or `opens_with:` | Write the tool as an entry with `outcomes:`, and use `save:` and `start:` | One shape for what a tool's result does and what a step opens with |
| An omitted history choice | Review whether `messages` is appropriate | `messages` is now the default |
Ordinary tool `input:` and `output:` schemas are unchanged. Run
`unmute validate` after updating an older package; retired keys produce a
located error with migration advice.
## Where to go next
Run several tasks in a fixed order. This is the next page.
What to give a task so the model enters it, and what to take away from the owner.
Choosing what to save with `save:`, and how to type it.
# Pre-fetch
Source: https://unmute.ai/build/prefetch
Run a lookup before the call starts, when you already have everything it needs.
`prefetch:` runs a lookup once, before the greeting, and puts the answer in a
[variable](/build/variables). Today's date. Who is calling. What that person
ordered last time.
If you already have what a lookup needs, the model should not spend the call
doing it.
On this page:
* [Quickstart](#quickstart) - the smallest entry that works
* [What you can fetch](#what-you-can-fetch) - a clock, a call fact, or a tool
* [Every key an entry takes](#every-key-an-entry-takes) - the full shape
* [Always check a value with the caller](#always-check-a-value-with-the-caller) - `confirm:`, and why identity needs it
* [Where it works](#where-it-works) - which routes supply which facts
* [Troubleshooting](#troubleshooting) - what stops the build, and how to fix it
## Quickstart
Read the clock before the greeting, and save the date:
```python state.py theme={null}
from datetime import date
from pydantic import BaseModel
class State(BaseModel):
booking_date: date | None = None
```
```yaml agent.yaml theme={null}
prefetch:
- name: today
clock: now
timezone: Europe/Madrid
save:
- booking_date: result.date
```
Name it in the prompt that needs it:
```markdown tasks/booking.md theme={null}
Local date: {{state.booking_date}}
Use this as today when the caller says tomorrow or names a weekday.
```
```sh theme={null}
unmute validate my-agent
```
That is a whole pre-fetch. Everything below is the rest of what an entry can do.
A fetched value is a guess until the caller agrees to it. The phone network
says which phone called, not who is holding it. Mark anything about the
caller's identity with `confirm:` and the agent has to hear them say yes
before it acts: [Always check a value with the
caller](#always-check-a-value-with-the-caller).
## Why bother
When the model calls a tool, it thinks twice: once to decide to call it, once to
use what came back. The caller waits through both, in silence.
Prefetch moves that work before the greeting. It removes a lookup from the
conversation, but its own run time can delay the greeting. Keep it short.
Here is a good sign. If your prompt tells the model "call `get_x` first", `get_x`
is a tool to pre-fetch.
You cannot pre-fetch a tool that needs to know what the caller said. The time
they picked, the service they want, the reason they called. Those still happen
during the call.
## What you can fetch
| Write this | And you get |
| - | - |
| `clock: now` | the date, the time, and more, all from one reading of the clock |
| `source: from_number` | a fact the call carries, like the number it came from |
| `call: my_tool` | a result from a local or webhook tool; declare whether it changes data |
`clock: now` reads the clock once. Save as many of the six fields as you
want, in one entry:
| Field | Example |
| - | - |
| `result.date` | `2026-09-04` |
| `result.time` | `14:32` |
| `result.datetime` | `2026-09-04T14:32+02:00` |
| `result.day_of_week` | `Friday` |
| `result.year` | `2026` |
| `result.timezone` | `Europe/Madrid` |
All six fields are text, including `result.year`. Use `date` for
`result.date`, `time` for `result.time`, and `str` for the weekday, year,
combined datetime, or timezone.
All six come from the same reading. An entry saving `result.date` and
`result.time` cannot straddle a second, and one saving `result.date` and
`result.day_of_week` cannot straddle midnight.
A local or webhook tool can run before the greeting when every input is
already known: a fixed value, a call fact, or a value an earlier entry saved.
MCP, knowledge, prebuilt, and hosted tools cannot run as prefetch entries.
That covers a lot of tools. A customer record, looked up by phone number.
Today's opening hours, looked up by date. Someone's last order, looked up by
their customer id. What plan an account is on.
Declare `writes: false` for a lookup that only reads. `writes: true` is also
supported, but means the tool changes data on every call with usable inputs,
including wrong numbers and calls that end before a conversation. It does not
wait for the caller's agreement.
## A worked example
Three entries, in order: the clock, the caller's number, then a lookup that
uses it.
```yaml agent.yaml theme={null}
prefetch:
- name: today
clock: now
timezone: Europe/Madrid
save:
- booking_date: result.date
- booking_weekday: result.day_of_week
- name: caller
source: from_number
save:
- customer_phone: result.value
- name: profile
call: look_up_account
writes: false
with:
- phone: state.customer_phone
save:
- account_name: result.name
- account_on_file: result.status
```
`profile` reads once and saves twice. An entry can fill as many variables as
the result has fields, and a second `save:` line costs no second call.
Declare the receiving fields on `State`. Every field needs a default. Here an
empty string or `None` means the value is not known yet:
```python state.py theme={null}
from datetime import date
from typing import Annotated
import phonenumbers
from pydantic import BaseModel
from pydantic_extra_types.phone_numbers import PhoneNumberValidator
Phone = Annotated[
str | phonenumbers.PhoneNumber, PhoneNumberValidator(number_format="E164")
]
class State(BaseModel):
booking_date: date | None = None
booking_weekday: str = ""
customer_phone: Phone | None = None
account_name: str = ""
account_on_file: str = ""
```
Do not give these variables a `source:` of their own in `agent.yaml`. The pre-fetch entry is
what fills them. That is why the same package still works on a phone route
carrying no caller ID.
## Every key an entry takes
A unique entry name used in errors and logs. Use lower snake case. No name is inferred.
Only `now` is accepted. Choose exactly one of `clock`, `source`, and `call`; omitting
all three is refused.
Required with `clock`: an IANA zone such as `Europe/Madrid`. There is no default,
because the container clock is UTC. Refused on source and call entries.
One of the eight [system call facts](/reference/variables#sources). Choose exactly one
of `clock`, `source`, and `call`. An unavailable fact skips the entry and leaves its
destination values unchanged.
A declared local or webhook tool. Choose exactly one of `clock`, `source`, and `call`.
No tool runs when this key is absent.
Required with `call`: `true` if this use changes data, or `false` if it only reads.
There is no inferred answer. Refused with `clock` or `source`.
Arguments for a `call:` entry, as argument/value pairs. A value is `state.x` or a literal. Omit when the tool needs no authored arguments; required inputs must still
be supplied. Refused on clock and source entries.
One or more `variable: result.field` pairs. Every destination must be declared. Values
are checked together before any are saved. No save is inferred.
## Entries run in order
Top to bottom, in the order you wrote them. Above, `caller` gets the phone
number and then `profile` uses it.
Put them the other way round and the build stops, naming both entries and
telling you which one to move up. An entry can only read what an entry above it
has already saved.
## Always check a value with the caller
The phone network tells you which phone called. It does not tell you who is
holding it. People call from a partner's phone, or from work.
So mark the value with `confirm:`. It names the step that has to hear the caller
say yes:
```yaml agent.yaml theme={null}
variables:
- name: customer_phone
confirm: verify_customer
```
Until they say yes, the value is held back:
* no prompt can use it, except that one step's own;
* during the conversation, a tool that reads it through `with:` or a webhook
path refuses to run until it is confirmed. A prefetch lookup may still read
the candidate so it can prepare a record before the greeting.
This carries over. `account_name` was looked up from a number nobody has
confirmed yet, so it is unconfirmed too. That is what stops the agent greeting a
stranger by the account holder's name.
Then write that step to read the value back:
```md tasks/verify-customer.md theme={null}
The call came from {{state.customer_phone}}. If there is a number there, read it back
and ask if it is the right one for the booking. If it is empty, ask for a number.
```
The task must save the agreed number to clear confirmation. Add a `save:` row
to the confirming task:
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: verify_customer
when: Confirm the customer's number before using their account.
prompt: tasks/verify-customer.md
save:
- customer_phone: result.phone
```
End its instructions with:
```markdown tasks/verify-customer.md theme={null}
After the caller agrees, finish with the confirmed phone number. If they
correct it, confirm the corrected number before finishing.
```
The prompt asks for agreement; the runtime clears the confirmation mark when
that named task saves the value. It cannot infer agreement from speech alone.
Confirmation is not identity authentication; add the checks your service needs.
If the caller confirms the same number, the prefetched dependent values can
be used. If they change it, values looked up from the old number are cleared.
They are not automatically fetched again: use a task tool to look up the new
number and save its result. Unrelated facts, such as today's date, remain.
To avoid repeating verification in another task or agent, do not track a second
"is this confirmed" variable of your own: `confirm:` already marks it. A
[flow](/build/orchestration/task-groups#skip-a-step-whose-work-is-already-done)
step can name the variable in `skip_when_confirmed:` and the step is skipped
once it is confirmed. The public
[salon example](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge)
shows this: its booking flow skips the verification step entirely once
`customer_phone` is already confirmed.
## Where it works
`clock:` and `call:` entries run on every target except `slng`, which refuses
`prefetch:` and `confirm:` outright: it starts the session itself, so there is
no gap before the greeting to fetch anything in.
`source:` depends on the route, and on the direction of the call:
| Fact | `livekit sip` | `livekit connector` | `pipecat daily-sip` | `pipecat cloud-websocket` |
| - | - | - | - | - |
| `source.session_id` | in, out | in, out | | |
| `source.carrier` | in, out | in, out | | |
| `source.connection` | in, out | in, out | | |
| `source.call_id` | in, out | in, out | in, out | in, out |
| `source.stream_id` | | in, out | | in, out |
| `source.direction` | in, out | in, out | in, out | in, out |
| `source.from_number` | in, out | in, out | in | in |
| `source.to_number` | in, out | in, out | | out |
`in` means the fact resolves on an inbound call, `out` means it resolves on an
outbound call. A blank cell means the route supplies nothing there, and an
entry reading that fact is skipped on every call, with a log line saying so.
The two Pipecat rows read a phone number one way only, and that is not an
oversight. A TwiML Bin is attached to one number, so on an inbound call the
number being called is already fixed, and only the caller's number is worth
carrying. An outbound call goes out from the environment's own caller ID, so
there the number worth carrying is the one being dialled. Each direction hands
the agent the one number the carrier knows and unmute does not.
So a `source: from_number` entry gets nothing on an outbound `pipecat
daily-sip` call, and a `source: to_number` entry gets nothing anywhere on
Pipecat except an outbound `cloud-websocket` call. `unmute validate` warns
when a package declares only the direction a route does not grant.
An outbound call has nobody calling in, so the number worth carrying is the one
being dialled. It is the same shape of entry, reading the other fact:
```yaml agent.yaml theme={null}
prefetch:
- name: dialing
source: to_number
save:
- customer_phone: result.value
```
On both LiveKit routes that is all of it. The worker places the call, so it
already holds the number, and nothing else has to be set up.
On `pipecat cloud-websocket` the number has to be put into the request that
places the call, alongside the parameter naming the agent:
```xml theme={null}
```
The number goes into that request twice, once as the number Twilio dials and
once as this parameter. Twilio fills `{{To}}` in for a TwiML Bin but substitutes
nothing inside an inline `Twiml=`, so the caller of the API supplies it.
Leave the parameter out and the entry is skipped, exactly as a withheld caller
ID is skipped, and the run log names the entry and says the call carried no
`to_number`.
A phone number is a less certain fact than a call id, on every route that
supplies one. A caller can withhold their own number, and a withheld number
does not arrive as nothing:
* Twilio's own policy is to set it to the word `anonymous`.
* Where an upstream carrier sends a word such as ANONYMOUS or RESTRICTED
instead, Twilio converts it to keypad digits, which look exactly like a real
number.
* Some calls simply arrive with the field empty.
unmute treats all three the same way: absent. A number-valued fact resolves
only when it looks like a plausible E.164 number, a `+` followed by 8 to 15
digits, and a short list of known digit placeholders is rejected on top of
that check. Either way the entry is skipped, and the log names which entry and
why.
On LiveKit `sip`, the number is also absent when the dispatch rule sets
`HidePhoneNumber`. On `pipecat cloud-websocket` it can be missing for a
quieter reason: the number rides a `` in the TwiML Bin you made, so
a Bin created before this existed does not carry it. Nothing warns about that
at compile time, because checking would need carrier credentials the compiler
never asks for.
Treat the caller's number as best effort everywhere it resolves, not only on
Pipecat. A route granting the fact is not a promise that any one call will
carry it.
The same fact declared as a variable's own `source:` is stricter: a route
that cannot supply it refuses the declaration. This depends on the fact and
route, not simply on whether the target is Pipecat. A prefetch entry can
instead skip an unavailable fact and leave the variable at its default.
## Troubleshooting
### The build refuses a clock entry with no `timezone:`
Containers run on UTC time. Without a timezone, a business in Spain taking a
late evening booking for "tomorrow" writes down the wrong day.
**Fix:** put the zone on the entry, not on the package. Two entries may
honestly want two zones.
```yaml agent.yaml theme={null}
prefetch:
- name: today
clock: now
timezone: Europe/Madrid
```
### The build asks a `call:` entry to declare `writes:`
There is no default. A pre-fetch runs on every single call, whether the inputs
turn out to be right or wrong, so the build makes you say whether that is safe
before it will run the tool at all.
**Fix:** answer it. The build trusts that line; it cannot open your handler and
check.
```yaml agent.yaml theme={null}
prefetch:
- name: profile
call: look_up_account
writes: false
```
`writes: true` compiles too. It is a declaration, not a request for permission:
the entry is named in `compile-report.json` and in the runbook instead of
printing a warning. Point a pre-fetch at a lookup, and mark anything else
`writes: true` so it stays easy to find later.
### `writes:` is refused on a clock or source entry
Neither runs a tool, so the key means nothing there.
**Fix:** remove it.
### `save:` on a clock entry names a field that is not one of the six
**Fix:** use one of the six fields above. The refusal lists all six.
### A pre-fetch cannot fill a list or a model
A pre-fetch resolves before anybody speaks, so what it has is one value: a
formatted clock reading, the number the call carries, one field of a tool
result. Text is fine, and so is a `date`, a `time`, a checked phone number or an
`EmailStr`, because the type is checked where the value enters the state. A
`Literal` works when the tool's own field declares the same set.
**Fix:** run the lookup in a [task](/build/orchestration/tasks) and save the
result through the step's `save:`. The refusal names the step to save it from.
### A value arrives empty on every call
The whole prefetch list shares a two-second budget. Entries run in order, once
per call. There is no per-entry retry or automatic refresh during the call.
| Outcome | What happens |
| - | - |
| An input is missing | The entry is skipped |
| A lookup times out or raises an error | The entry is logged and skipped |
| The result fails type validation | Its saves are not made |
| An entry saves several fields | All are validated before any are saved |
| The shared budget runs out | Remaining work is skipped so the call can continue |
Skipped entries leave the destination values unchanged, usually at their
initial defaults. A later entry is skipped too if an input it needs is still
missing. If a usable default supplies that input, the later entry may run.
Write prompts to handle missing values. `none recorded yet.` means an unset
value, not proof that no customer or booking exists. Check a lookup's explicit
status before drawing that conclusion. See
[What to fetch before the call](/optimization/prefetch) for choosing useful
lookups and reading their logs.
## Try it
Your machine has no caller ID, so stand in for one:
```sh theme={null}
unmute dev examples/salon-concierge --target livekit --source from_number=+15005550006
```
The command above uses a test number. For your own lookup, use a test account
number it knows. Check four cases: the caller confirms it, corrects it, has
no record, or has no caller ID. Leave the flag off for the last case. The
agent should ask only for the missing information in each case.
Do not use `--var` for this. It writes the value straight in, skips the
pre-fetch and marks nothing as needing confirmation. Your local run would then
act on a value it never read back, and pass where a real call fails.
## Next steps
Which lookups are worth moving earlier, and the traps to avoid doing it.
Every source, every rule, every error message.
# Hosted tools
Source: https://unmute.ai/build/tools/hosted
Reference a tool your SLNG organisation already has by its exact name: no hash, no mirror, no pull required for SLNG.
A hosted tool is not defined in your package. It is defined on the SLNG
platform already, and the block just names it.
On this page:
* [The file name and the hosted name](#the-file-name-and-the-hosted-name-are-two-different-things) - two names, one reference
* [Descriptions and parameters are inherited](#descriptions-and-parameters-are-inherited) - what the platform supplies
* [What the block keeps](#what-the-block-keeps) - every key you write
* [Attaching one](#attaching-one) - the agent's list
* [Deploying to SLNG needs no mirror](#deploying-to-slng-needs-no-mirror) - what deploy checks
* [What each target does with it](#what-each-target-does-with-it) - slng, livekit, pipecat
* [Advanced](#advanced) - the legacy form and the mirrors
* [Troubleshooting](#troubleshooting) - the refusals, and their fixes
```yaml tools/check_order.yaml theme={null}
slng: check_order
```
`slng: check_order` is the whole reference. The scalar is the hosted tool's
**exact name**, as your organisation holds it. No description, no schema, no
hash, no mirror, and no `unmute pull` are required to validate, compile, or
deploy this to SLNG.
A sentence spoken before the tool runs goes on the tool's entry in
`agent.yaml`, under `start:`:
```yaml agent.yaml theme={null}
tools:
- name: check_order
start:
say:
- One moment while I look that up.
```
## Hosted reference fields
The exact published tool name. No hosted name is inferred from a scalar reference. The
legacy object accepts `hash` and resolves the hosted name from the tool file name; see
the legacy form below. A tool file must have exactly one execution block.
## The file name and the hosted name are two different things
The tool **file's** name is still the package reference: it is what an
agent's `tools:` list attaches, and what every local diagnostic calls the
tool. The `slng:` scalar is the name deployment resolves against your
organisation. They usually agree, and they do not have to:
```yaml tools/order_status.yaml theme={null}
slng: check_order
```
The agent attaches `order_status`; deployment resolves `check_order`. This
creates no tool and renames nothing in SLNG, it only lets your package call
the reference whatever reads best in the prompt and the tool list. Say the
hosted callable name out loud in a prompt that explicitly names the platform
function; the file name is a package reference, not a remote rename.
## Descriptions and parameters are inherited
A hosted tool owns its own description and schema. Omit `description:` and
the attachment uses whatever the published tool says; write one and it
**overrides** the platform's for this attachment only. Delete the field later
and inheritance comes back:
```yaml tools/check_order.yaml theme={null}
slng: check_order
description: Look up an order and tell the caller its status and delivery date.
```
Nothing here is checked offline. A compile records the description you write as
an override, and that is all it does with it. Whether the published tool still
means the same thing is a question only your organisation's copy can answer, so
it is one of the checks `unmute deploy` completes rather than one `unmute
compile` does.
## `input` and `output` still have nowhere to go
A hosted tool owns its own schema, so these fields are unwritable rather than
silently ignored:
| Field | Because |
| - | - |
| `input`, `output` | the platform published the schema; a second copy here could disagree with it |
| `handler` | the code is the platform's, not authored here |
| `url_env`, `base_url`, `path` | the platform stores the URL |
| `dependencies` | the platform installs them |
## What the block keeps
These describe how your agent uses the tool, not what the tool is, so they
stay yours to write, exactly as before:
Required for local, webhook, and knowledge tools: explains when the model should call
the tool. Builtins use their registry description if omitted; hosted `slng` tools
inherit their published description. Refused on MCP sources.
Hidden argument/value pairs. A value is `state.variable`, a scalar, or a string with
`{{state.variable}}` placeholders. Omit to pass nothing. Legal on local, webhook, and
hosted `slng` tools; builtin `send_sms` requires its literal `from_number` setting.
Accepts `provider_default`, `continue`, or `cancel`. Omitted means `provider_default`.
Refused on MCP sources. Target support is listed above.
Accepts `returns_data` or `ends_conversation`. Omitted means `returns_data`, except
builtins whose effect comes from the registry. Refused on MCP and knowledge tools.
Written on the tool's entry in `agent.yaml`, not in this file. A fixed spoken sentence
with no `{{variables}}`, legal on local, webhook, knowledge, and hosted `slng` tools.
See [the tools overview](/build/tools/overview#using-start-say).
```yaml tools/search_places_text.yaml theme={null}
slng: search_places_text
with:
- query: "state.customer_name"
```
This snippet is separate from the phone-ready `hotel-concierge` example. Declare
`customer_name` as a `str` field on `State` in `state.py`, give it
`source: call_start` under `variables:`, and supply it when starting a web session. For inbound phone calls, give it a
valid default or leave `query` to the model: carriers supply no session inputs.
Values passed through `with:` keep their exact type, including `false` and `0`, and are
never shown to the model. `{{state.customer_name}}` is resolved when a call starts;
a fixed value such as `- limit: 0` is bound as written. Full rules for the
last three fields are on
[the tools overview](/build/tools/overview#the-three-behavior-fields).
A variable does not have to land on a text parameter. SLNG stores the value as
text and converts it into the parameter's declared type, so `- limit:
"{{state.how_many}}"` works on an integer parameter as long as the stored value reads
as a number. That conversion happens when the call starts, so `unmute deploy`
checks the parameter and reports the value as deferred rather than claiming to
have validated it.
## Attaching one
No different from any other tool. The agent names it:
```yaml agent.yaml theme={null}
agents:
- name: support
prompt: instructions.md
think: reasoning
speak: front_desk
tools:
- check_order
- end_call
```
## Deploying to SLNG needs no mirror
```sh theme={null}
unmute validate examples/hotel-concierge --target slng
unmute compile examples/hotel-concierge --target slng
unmute deploy examples/hotel-concierge
```
All three work with no mirror file, no network, and no credential except the
last, which is the one step that has to reach your organisation at all. That
is the whole point of naming a tool rather than copying it: the published
version is the only copy, so there is nothing local to keep in step with it.
What an offline compile genuinely cannot check, because the answer lives in
your organisation and not in your package:
* that a tool called `check_order` exists there, and which published version
is the latest;
* that every `with` argument is a parameter of that published version, and
that a fixed value is the type it declares;
* which Vault entries the published version needs.
`build/slng/compile-report.json` names these under `deferred_checks`, against
the references they apply to. A clean compile therefore reads as "nothing wrong
yet" rather than "everything is fine." `unmute deploy` completes all three
before it changes the agent, and `--dry-run` reports them without changing
anything. See [Deploy to SLNG](/deploy/slng) for what that run checks and what
it prints.
## What each target does with it
| Target | What happens |
| - | - |
| SLNG | resolves the platform's own tool by name at deploy time. Nothing is created, nothing is uploaded, nothing local is required |
| LiveKit | refused for now |
| Pipecat | the same |
**A `slng:` tool is SLNG-only for now.** SLNG needs nothing from your package beyond
the name. Livekit and pipecat do not compile hosted tools yet. When
it does, they will need a real copy of the tool's definition, which `unmute pull`
fetches.
For a scalar reference, the pin that proves the mirror is still the one your
package means goes into a generated `tools/.slng.meta.json` beside the
mirror, never into your tool file. Commit everything `pull` writes. A package
that targets slng alone never runs this command at all.
Two things `pull` may still write into files you wrote, so you can read the
diff knowing what to expect:
* A tool file written the older `slng:` block form has its `hash:` restamped
in place, because that form keeps its pin in the tool file. A scalar
reference never gets touched.
* `secrets:` in `agent.yaml` gains any credential name a mirrored tool needs
and your package does not declare yet, and only when a target builds the
tool itself. LiveKit and Pipecat read that list to get the credential into
the generated project. A package targeting slng alone gets nothing added:
the platform reads the credential from its own vault, and `unmute deploy`
reports the same requirement from the published contract.
## A reference points at an existing tool
A hosted reference only ever points at a tool your organisation already has. A
name it does not hold is a refusal, not something a deploy creates for you.
A [`local:`](/build/tools/python#on-the-slng-target) tool is different. On an
slng target, `unmute deploy` publishes it as a code tool, so you do not write
`slng:` for it. A [`webhook:`](/build/tools/webhook) block is still refused on
an slng target. Create an API request tool in SLNG and reference it with
`slng:`. Both blocks work as before on livekit and pipecat. You can also start a
code tool by hand with `voiceai tool create`. `slng:` is how your package
reaches it once it exists there.
```sh theme={null}
voiceai tool create hosted/check_availability.py --description "..."
voiceai tool run check_availability --input sample.json --confirm-side-effects
voiceai tool publish check_availability
```
The file defines a pydantic `Input` and `Output` and a `handler(input: Input) -> Output`.
SLNG refuses a few schema keywords in `Input`, so a `Field(pattern=...)`, a
`Decimal` or a fixed-length tuple fails the build. A date, a time, a UUID or an
email address is fine.
A push attaches only a published version.
## Which block for which job
| You want | Write |
| - | - |
| a tool SLNG already hosts, with code or a request configuration | `slng:` |
| a capability SLNG curates, like ending the call or reading the clock | `builtin:` |
| tools from an MCP server your organisation registered | `mcp:` |
| your own Python, running inside a livekit or pipecat project | `local:` |
| an HTTP endpoint you host | `webhook:` |
The last two are the two that no longer reach slng.
A curated capability resolves either way: `slng: current_datetime` attaches it
by name, and so does `builtin: {id: current_datetime}`. Reach for `builtin:`
whenever the capability takes a setting of its own, because `with:` under a
`slng:` block is an argument and a curated capability publishes no argument
schema to put one in. See [prebuilt tools](/build/tools/prebuilt).
## Advanced
Neither of these comes up on a package that targets slng and writes the scalar
reference.
### The legacy form still loads
```yaml tools/check_order.yaml theme={null}
slng:
hash: 336a66b9a564f472...
```
A tool file written before this shape existed still resolves, by the
**file's** own name, and a code target still checks its mirror's pin exactly
as it always did. It is accepted, not taught: a new tool file should write
the scalar name instead. Nothing about deploying to SLNG reads this form's
mirror or its pin; SLNG resolves the reference by name either way.
### The mirrors are not yours to edit
`tools/.slng.json` and, for a code tool, `tools/.slng.py` are the
platform's copy, not yours, whichever form the reference is written in. The
`.slng.` infix marks a file as mirrored rather than authored, so one glance
answers whether you may edit it. The answer is no.
Every compile of a code target checks the mirror against its pin, with no
network at all, so a hand edit is caught the next time anybody builds the
package:
```text wrap theme={null}
tool "check_order": tools/check_order.slng.py does not match the hash tools/check_order.slng.meta.json
pins, so the committed mirror is not the one this package means: run `unmute pull` and
read the diff, or `git checkout` the mirror if the edit was a mistake
```
`unmute pull` itself refuses the same way, before it overwrites anything,
naming every changed file at once. `--force` discards the edits; the honest
fix is to change the tool on the platform and pull again.
## Troubleshooting
### The build refuses a bare `slng:` block
Leave the block bare and validation refuses before anything else runs:
```text wrap theme={null}
tools/check_order.yaml:1: `slng:` names the tool SLNG already hosts: write `slng: check_order`,
one line, the hosted tool's exact name
```
**Fix:** write the hosted tool's exact name on the same line, as your
organisation holds it.
### `unmute deploy` refuses a `with:` value
There are three cases, each naming the tool file and the published version:
* **The parameter is not declared.** An attachment pins a declared parameter.
A schema that allows extra properties lets the *model* send more; it does not
give an override anywhere to bind.
* **The parameter's type is not settled.** A parameter that could be a string
or an integer, or that declares no type, or that holds an object or a list,
cannot take a pinned value. Leave it to the model.
* **A constraint sits at the root of the schema.** A published schema may
constrain a parameter from its root, under `allOf` and friends. Checking one
supplied value against a rule written for the whole call would reject the
arguments the model fills in, so the value is not reported as checked.
**Fix:** drop that key from `with:` and let the model fill the parameter in,
or pin a different parameter whose published type is settled.
### Two tool files resolve to one hosted tool
Two tool files resolving to the same hosted tool are refused, naming
both. SLNG attaches a hosted tool once, so the two cannot carry separate
descriptions or `with:` values, and a push would silently keep one file's
settings and drop the other's.
**Fix:** keep one file per hosted tool, and attach that one file wherever both
were attached.
### A code target says no mirror is committed
Skip the pull for a code target and the refusal names the fix, and the
shortcut:
```text wrap theme={null}
livekit: tool "check_order": `slng:` names a tool SLNG hosts and this target builds a tool
out of its committed mirror, and none is committed: run `unmute pull` to fetch it and
commit what it writes, or compile this package to slng, which references the published
tool and needs no mirror
```
**Fix:** run `unmute pull` and commit everything it writes, or compile the
package to slng instead.
### A hosted tool with Python dependencies is refused on livekit and pipecat
**One limit, and it is the honest cost of "runs everywhere."** A hosted tool
that declares Python dependencies compiles to slng, which installs a per-tool
environment. It is refused on livekit and pipecat, in the same words an
authored `local:` tool's `dependencies:` already gets there:
```text wrap theme={null}
the LiveKit driver builds one dependency list for the whole generated project from the
provider catalogue and reads no per-tool pins: add the package to
build//pyproject.toml after compiling, or compile to slng which installs a
per-tool environment
```
A mirrored pin and an authored one reach nothing on those two targets for the
same reason: each builds one dependency list for the whole project, and reads
no per-tool pins. A hosted tool with no dependencies works on all three. On a
slng-only package this limit is invisible until deploy, because there is no
mirror to read it from ahead of time; deploy reports it as one of the checks
it completed.
**Fix:** add the package to `build//pyproject.toml` after compiling, or
compile that tool's package to slng.
## Where to go next
What a real deploy resolves, checks and reports.
Optional, and only for livekit or pipecat: the command, its flags, and every refusal.
The other hosted-by-name block: a server SLNG already has.
The other block that names a tool SLNG already has: a capability SLNG curates.
# Knowledge bases
Source: https://unmute.ai/build/tools/knowledge
Point a tool at a folder of your own documents, and the agent answers from them instead of guessing.
You have policies, price lists, or manuals, and you want the agent to quote them
rather than invent something close. Put the documents in a folder, name the folder
in `agent.yaml`, and give an agent a tool that searches it.
Reach for a knowledge base when the agent should quote your own documents
instead of guessing, especially when a caller's words and your document's
words differ, or a caller wants an exact string off a price list or a policy.
An API you already have is a [webhook](/build/tools/webhook) instead: a search
service is a network hop and a service to run, not a folder of documents.
On this page:
* [Which agent sees which documents](#which-agent-sees-which-documents) - the only access rule
* [Every key a base takes](#every-key-a-base-takes) - the full shape
* [The `knowledge:` block on a tool](#the-knowledge-block-on-a-tool) - what the tool file holds
* [How the search works](#how-the-search-works) - meaning, keyword, hybrid
* [What happens, and when](#what-happens-and-when) - compile, startup, lookup
* [Advanced](#advanced) - sizing, scores, embedding models
* [Troubleshooting](#troubleshooting) - the warnings and the failures
```yaml agent.yaml theme={null}
knowledge:
policies:
documents: knowledge/policies
pricing:
documents: knowledge/pricing
```
```yaml tools/look_up_policy.yaml theme={null}
description: >-
Look up the company's refund and complaints policy. Use this before you state
any refund, replacement, timescale, or goodwill offer, so you quote the policy
instead of guessing it.
knowledge:
base: policies
```
```yaml agent.yaml theme={null}
tools:
- name: look_up_policy
start:
say:
- Let me check the policy.
```
Then attach the tool to the agents that should see that folder:
```yaml agent.yaml theme={null}
agents:
- name: complaint_specialist
tools:
- look_up_policy
```
That is the whole surface. Everything below is optional tuning.
## Which agent sees which documents
**An agent reaches a knowledge base by being given its tool.** There is no allow
list and nothing else to configure.
So a tool on the wrong agent is a real leak, not an untidiness: an agent given
`look_up_policy` can quote refund policy to anyone it talks to. Two tools over one
base is fine and normal; the same tool on every agent means every agent can quote
that folder.
## Every key a base takes
Every field is **per base**, because different documents want different treatment.
A folder of prose and a folder of price rows can sit in the same package with
different settings.
3 to 64 characters of `[a-z0-9_]`. It becomes the search collection's name, and
the folder name inside the build.
Path to a folder inside the package containing `.txt`, `.md`, or `.pdf` documents. No
folder is inferred.
An [embedding service](/build/tools/knowledge#embedding-models). Omitted means `openai`.
Keyword mode makes no embedding call.
Accepts `meaning`, `keyword`, or `hybrid`. Omitted means `hybrid`.
Passage size in tokens, from 1 to 2048. Omitted means `90`.
Tokens shared by neighboring passages, from 0 through `chunk_size`. Omitted means `20`.
Maximum passages returned by a lookup, from 1 to 20. Omitted means `3`.
Minimum accepted result score, from 0 to 1. Omit for no score filtering. Scores are
similarities, not probabilities.
## The `knowledge:` block on a tool
The name of a base declared under `knowledge` in `agent.yaml`. No base is inferred.
Legal beside it: `description`, `interruption`, and a `start: say:` line on its entry in `agent.yaml`.
Refused beside it: `input`, `output`, `with`, `effect`. The tool owns both sides
of its contract, it takes one string, the caller's question, and returns passages,
so there is nothing for those to describe.
**Write a real `description`.** It is the only thing that tells the model when to
look something up instead of answering from memory. Say what is in the folder and
when to check it. **Write a `start: say:` line too**: a lookup takes a moment, and silence
sounds like a dropped call.
## How the search works
Three modes, and they answer different kinds of question.
### `mode: meaning`
Vector search. Each passage and each caller question is turned into a vector by an
embedding model, and the passages closest to the question win.
What it is for: **the caller's words and the document's words are different.**
Someone asks "when will the money land back in my account" and the document says
"five to seven working days". They share no distinctive word, so nothing that
matches on words can find it. This is the case vector search exists for.
Where it struggles: an exact string. A reference code, a surname, a part number, a
price read off a letter. It also gets weaker as a corpus grows, because more
passages of similar prose means more near neighbours competing with the right one.
Needs an embedding model, so it needs a credential and one network call per lookup.
### `mode: keyword`
BM25, a ranking function over the words themselves. A word the caller says is
matched against the words in each passage, with rarer words counting for more.
Stemming is included, so a question about "closing" still matches a passage that
says "closed".
What it is for: **the caller says the exact thing.** Codes, names, model numbers,
prices. It also holds up as a corpus grows, because a rare word stays rare.
Where it struggles: paraphrase. Nothing that matches on words can bridge two ways
of saying the same thing.
**`keyword` needs nothing.** No embedding model, no credential in `secrets:`, no
network call, and the emitted image installs no embeddings package. A lookup is
local memory access rather than a round trip, and the index builds in a fraction
of the time an embedded one takes. If your documents cannot be sent to a third
party, this is the mode that answers that.
```yaml theme={null}
knowledge:
policies:
documents: knowledge/policies
mode: keyword # offline, instant, no key
```
A `keyword` base produces **no relevance scores**. BM25 scores sit on a different
scale from vector similarities, and giving the model two incomparable numbers in
one field would be worse than giving it none. `min_score` on a `keyword` base is
refused at compile rather than silently doing nothing.
### `mode: hybrid` (the default)
Both, run separately and interleaved, so each half gets slots the other cannot
take. A question that only paraphrase can answer and a question that only an exact
term can answer both work, without you deciding in advance which kind your callers
will ask.
This is the default because it is rarely the wrong answer. It needs an embedding
model, the same as `meaning`.
### Choosing
| Your situation | Mode |
| - | - |
| Not sure yet | leave `mode` out, which gives `hybrid` |
| Callers paraphrase, and your documents use different words than they do | `meaning` |
| Callers quote codes, names, prices, part numbers | `keyword` |
| Documents cannot leave your infrastructure | `keyword` |
| You want no per-lookup network call | `keyword` |
## What happens, and when
| When | What |
| - | - |
| `unmute compile` | checks the folder exists and holds a supported file, copies the documents into `build//knowledge//` byte for byte, and records one line per base in `compile-report.json` |
| Agent startup | reads the documents, splits them into passages, indexes them, and holds the index in memory |
| Each lookup | searches the index. No file is read and nothing is re-indexed |
**Content is fixed until the next compile.** Editing a PDF in your package changes
nothing in a running agent, or in a deployed one, until you compile and deploy
again.
Indexing happens before the agent takes calls, so a caller never waits for it. It
runs once per worker process, so every worker indexes the whole corpus at start:
more workers means more startup work, with the same content in each. That is what
[baking](#skip-the-startup-embedding) removes.
## What a lookup gives the model
At most `top_k` passages, each about `chunk_size` tokens, with the source file name
and, on the modes that embed, a relevance score where a higher number is a closer
match. Results are ordered best first. With the defaults that is 3 passages of
about 90 tokens.
Nothing is filtered by score unless you set `min_score`, because a score that looks
low can still be the right answer. The tool tells the model in words that the
results may not answer the question, so it says it does not know rather than
offering the closest thing it found.
## Advanced
Everything here is tuning a first agent does not need. The defaults are a working
knowledge base.
### Sizing the passages
A document is split into passages before anything is searched, and a lookup
returns whole passages. Three fields control that.
`chunk_size` is how big a passage is, in tokens. Small passages are precise and
can cut a fact in half. Large passages keep a fact whole and dilute it with
neighbouring text.
`chunk_overlap` is how much two neighbouring passages share, so a sentence cut
across a boundary is still whole in one of them. Roughly a fifth of `chunk_size`
is a reasonable starting point. `0` is legal and means no overlap at all.
`top_k` is how many passages come back.
| Your documents | Try |
| - | - |
| Prose: policies, manuals, FAQs | the defaults |
| Lists: prices, opening hours, specifications | a wider `chunk_size`, 200 to 300, so a row stays with its own value |
| Dense reference a caller quotes from | a wider `chunk_size`, and consider `top_k: 5` |
The list case is the one that bites. At a narrow `chunk_size` a table of prices
splits mid row, so the name of a service lands in one passage and its price in the
next, and a question about the price ranks something else above it. Widening the
window keeps each row with its own value:
```yaml theme={null}
knowledge:
policies:
documents: knowledge/policies # prose: the defaults are right
pricing:
documents: knowledge/pricing
chunk_size: 220 # a price list: keep a row whole
chunk_overlap: 40
```
**`top_k` times `chunk_size` is what reaches the model on every lookup.** That is
tokens on the way in and latency on every call, during a live conversation. Above
about 1500 tokens the compiler warns:
```text theme={null}
warning: livekit: knowledge base sends the model a lot of retrieved text per
lookup, which costs latency on every call: policies (top_k 8 x chunk_size 500
= about 4000 tokens)
```
A warning, not an error. A big budget is a real choice for a dense document. Raise
one of the two rather than both.
### Filtering by score
`min_score` drops results scoring below it. It is **absent by default**, so nothing
is filtered unless you ask for it.
**These are similarity scores, not probabilities.** That is the whole difficulty
with the field. They look like confidence values, so `0.9` reads like "only very
good matches", when in practice scores land well below 1 and a cutoff that high
returns nothing at all. A genuine answer and an off-topic question are separated by
a much smaller gap than the 0 to 1 range suggests.
Above `0.25` the compiler warns:
```text theme={null}
warning: livekit: knowledge base sets min_score above 0.25, which starts dropping
real answers: policies (min_score 0.9). These are similarity scores, not
probabilities: in practice they land well below 1, so a cutoff near 1 returns
nothing at all. Check it against your own documents before shipping
```
**`min_score` is a `mode: meaning` tool.** On `hybrid` the keyword half returns
passages with no score, and a result with no score survives any cutoff. So on
`hybrid` a cutoff can take real answers away and cannot reduce noise. On `keyword`
it is refused at compile, because there are no comparable scores to compare.
Two behaviours worth knowing:
* **An exact-term hit survives any cutoff**, because it has no score to compare.
It was found because the caller said a rare word verbatim, which is better
evidence than a similarity number.
* **Every drop is logged**, with a count and never the question. Without that, a
cutoff set too high makes the agent say it does not know on every question with
nothing anywhere to explain why.
**Set it against your own documents.** The useful band is a property of a corpus,
not of the feature, and it moves when you change the documents or the passage size.
Widening `chunk_size` does not move it the way you would expect: fewer, longer
passages is fewer chances to match, so the weakest genuine score can stay where it
is while an answer disappears entirely.
Even with a cutoff, the tool still tells the model that results may not answer the
question. A surviving result is not the same as an answer.
### Embedding models
`embed:` chooses the model that turns documents and questions into vectors. It
applies to `meaning` and `hybrid`; `keyword` embeds nothing and ignores it.
| `embed:` | Model | Credential to declare in `secrets:` |
| - | - | - |
| `openai` *(default)* | `text-embedding-3-small` | `OPENAI_API_KEY` |
| `gemini` | `gemini-embedding-2-preview` | `GEMINI_API_KEY` |
| `huggingface` | `BAAI/bge-small-en-v1.5` | `HF_TOKEN` |
| `bedrock` | `cohere.embed-english-v3` | the AWS credential chain |
Switching is one line, and it is per base, so two bases in the same package can use
different services:
```yaml agent.yaml theme={null}
knowledge:
policies:
documents: knowledge/policies
embed: gemini
pricing:
documents: knowledge/pricing
mode: keyword # embeds nothing, so embed: is not read here
secrets:
- GEMINI_API_KEY
```
Naming a different service changes nothing else. The same documents, the same tool,
the same results shape. The emitted project installs the client for the services
you actually name, and nothing for the ones you do not.
Two rules the compiler enforces for you. An `embed:` value outside that table is
refused with the supported list. A service that needs a credential and does not
find it in `secrets:` is refused too, at compile, rather than failing when the
agent starts.
`bedrock` is the one that does not name a variable. It authenticates through the
AWS credential chain, so `boto3` resolves an access key pair, a profile, a role or
an instance identity, and a region, in its own order. Nothing has to be listed in
`secrets:` for it, and nothing is checked at startup, because there is no single
check that would be right for all of those paths.
`huggingface` is the hosted Inference API, not a model running inside your image.
All four services are network calls.
Documents are sent to the chosen service once, when the agent starts, and each
caller question is sent on each lookup. If that is not allowed for your documents,
use `mode: keyword`, which sends nothing anywhere.
### Skip the startup embedding
By default every worker process embeds the documents when it starts. That is
correct, and it is per process rather than per deployment, so it is paid again on
every scale-up. On a large corpus it is the difference between a process that is
ready immediately and one that spends seconds indexing first.
Building with `KNOWLEDGE_BAKE=1` does the embedding once, at image build time, and
every process then loads the finished index from disk:
```sh theme={null}
docker build --build-arg KNOWLEDGE_BAKE=1 \
--secret id=OPENAI_API_KEY,env=OPENAI_API_KEY .
```
Startup drops to a disk read, and the answers are identical. The generated
`README.md` prints the exact command for your package, with the credential your
embedding service needs.
The credential arrives as a **build secret**, so it is never written into an image
layer. Both flags are needed: the build argument is what puts the decision in
Docker's cache key, and without it a build that once ran without the secret would
keep reusing that layer and silently skip the bake.
A lookup still embeds the caller's question, so the run time needs the same
credential whether or not you bake. This removes the document cost, not the query
cost. Leave the flags off and the image still works: the startup log says it is
embedding instead, so the cost is never silent.
**Rebuild the image when the documents or the retrieval fields change.** A baked
index records the settings it was built under, and a mismatch is refused at startup
rather than answered from the wrong passages.
### Document formats
| Format | Note |
| - | - |
| `.txt` | read as written |
| `.md` | read as written, markup included |
| `.pdf` | text is extracted at startup. A PDF with no text layer is named and skipped **then**, not at compile time |
Anything else in the folder is ignored without comment, so a `.DS_Store` or a
stray image is not an error.
## Troubleshooting
### The compile warns that a base is never searched
A base that no tool searches is a warning at compile, not an error, because it is
read and indexed at every start and never queried.
**Fix:** attach a `knowledge:` tool that names it to an agent, or drop the base
from `agent.yaml`.
### The deployment stops because a base yields no text
A base where no document yields any text stops the deployment, the same as a
missing credential. A PDF with no text layer is the usual cause, and it is named
and skipped at startup rather than at compile time.
**Fix:** check the folder against the [document formats](#document-formats) above,
and replace a scanned PDF with one that carries a text layer.
### A lookup fails in the middle of a call
A lookup that fails mid-call does **not** end the call. The agent is told the
lookup is unavailable, and says so. The reason goes to the process log, not into
the model's context: a model handed a provider error can read it aloud.
**Fix:** read the process log for the reason. An embedding service that needs a
credential and a network call is the common one, and `mode: keyword` needs
neither.
## Where to go next
Split work between prompts when one agent stops being enough.
Return to all eight execution blocks.
# MCP servers
Source: https://unmute.ai/build/tools/mcp
Point the agent at a remote MCP server and let it offer that server's tools.
An MCP server already describes its own tools. So instead of writing a tool, you
name the server, and the agent offers what the server exposes.
Reach for an MCP source when a whole catalogue of tools already exists behind
one server, maintained by someone else, so attaching them one by one as
separate tool files would just be repetition. For one tool of your own, write
a [webhook](/build/tools/webhook) or a [Python handler](/build/tools/python)
instead.
`mcp:` tools compile on the SLNG target only for now. Livekit and
pipecat refuse them. The sections below that name LiveKit or Pipecat describe the
`mcp:` block for when those targets compile it.
On this page:
* [The block](#the-block) - five keys, and auth
* [The file is the block, and nothing else](#the-file-is-the-block-and-nothing-else) - what an mcp file refuses
* [Choosing which tools to offer](#choosing-which-tools-to-offer) - a filter, not a contract
* [Where the source can be listed](#where-the-source-can-be-listed) - agent or task
* [What each target needs](#what-each-target-needs) - SLNG only for now
* [Advanced](#advanced) - what the compile writes
* [Troubleshooting](#troubleshooting) - the refusal on SLNG
The file that does it holds one block and nothing else:
```yaml tools/web_search.yaml theme={null}
mcp:
server: firecrawl-mcp-2
url_env: FIRECRAWL_MCP_URL
transport: streamable_http
auth:
type: bearer
token_env: FIRECRAWL_API_KEY
tools:
- firecrawl_scrape
- firecrawl_search
```
Then the file name goes in an agent's list, the same way any tool file does:
```yaml agent.yaml theme={null}
agents:
- name: researcher
prompt: instructions.md
think: reasoning
speak: voice
tools:
- web_search
```
This is a worked example rather than a quote, with `auth:` added to show the
field. The real one ships in
[`examples/hotel-concierge`](https://github.com/slng-ai/unmute/tree/main/examples/hotel-concierge):
its `tools/web_search.yaml` names the same server and the same two tools, and
carries no `url_env`, `transport` or `auth:`. The platform reads the server by
name from its own registration, so those fields matter only for a code target.
That package deploys to slng only, agent name `hotel-concierge`, alongside four
other tools, so there was nothing for `auth:` to reach.
## The block
The server’s registered platform name. Omit to use this tool file’s name.
An UPPER\_SNAKE environment variable name holding the server URL. Required on LiveKit and
Pipecat. SLNG uses its registered server and does not read this field.
Accepts `sse` or `streamable_http`. If omitted, use the runtime’s URL-based transport
selection; a URL ending in `/mcp` selects streamable HTTP.
`type`, `token_env`, and optional `header`, as described below. Omit for no authored
authentication. SLNG uses its registered credentials and does not read this block.
Unique, non-empty server tool names. Required on SLNG. If omitted on a code target,
expose every tool the server offers.
**A package that only targets slng needs none of `url_env`, `transport` or
`auth`.** SLNG already has the server registered, with its own connection
settings and credential; those three fields exist for LiveKit and Pipecat,
which dial the server themselves. Selecting a code target still requires
them, with their existing rules and refusals.
`server` exists because the two names live in different namespaces. A tool file
name is lowercase snake\_case, and a server's name on the platform is whatever
somebody typed in a dashboard: real ones carry dashes and spaces. Without
`server`, a server called `firecrawl-mcp-2` could not be named at all. Read the
names your organisation has with `voiceai mcp list`.
`transport` is optional because both platforms already have a rule for guessing
it: a URL whose path ends in `/mcp` is streamable HTTP, anything else is SSE.
Write it when you want the choice visible instead of inferred.
`auth` is the same shape webhook tools use, so there is nothing new to learn and
no new code in the generated project. Its own three keys:
Accepts `bearer` or `api_key`. Required when `auth` is present; no scheme is inferred.
An UPPER\_SNAKE environment variable name holding the token, never the token itself.
There is no default.
An HTTP header name, legal only with `type: api_key`. Omitted means `X-API-Key`. Bearer
authentication uses `Authorization: Bearer`.
## The file is the block, and nothing else
Six fields that describe one tool to the model are illegal on an `mcp:` file.
Each is refused on its own, with the file, the line, and the reason:
```text theme={null}
tools/web_search.yaml:1: remove `description`: it is not legal on an `mcp:` tool, the
server describes each of its tools
```
```text theme={null}
tools/web_search.yaml:1: remove `input`: it is not legal on an `mcp:` tool, the server
owns each tool's parameters
```
The other four say the same thing about `output`, `with`, `interruption`, and
`effect`. In one place, so you can see the whole rule at once:
| Field | Why not here |
| - | - |
| `description` | the server describes each of its tools |
| `input` | the server owns each tool's parameters |
| `output` | the server owns each tool's result |
| `with` | an MCP call has the server's own shape, with nothing to merge into |
| `interruption` | MCP tools take the platform's default interruption policy |
| `effect` | MCP tools return data; ending the call is a `builtin:` tool |
This is the whole point of the shape. One tool file describes one tool the model
can call. An `mcp:` file is not that: it is a **source** of tools, and how many
there are, what they take, and what they return is only known once the server is
running.
## Choosing which tools to offer
```yaml theme={null}
tools:
- firecrawl_search
```
A selection filter, not a contract. Firecrawl also exposes scraping and crawling
tools; naming one keeps the rest out of a conversation that has to stay fast.
An empty list entry or a name repeated twice is still an authoring error and is
refused before the server is contacted.
On SLNG, `unmute deploy` checks every selected name against the registered
server's discovery snapshot. A missing tool blocks deployment. A real deploy
can refresh an unusable snapshot once; a dry run never refreshes it.
`url_env`, `transport`, and `auth` reach no further than that same offline
compile on SLNG. The platform already has the server registered, under
`server`, with whatever credential it needs. Nothing in this block reaches it
at run time except the tool list. Those three fields matter for the code
targets only.
## Where the source can be listed
On SLNG, the source can go on an agent or on a task. Livekit and pipecat do not
compile it yet.
## What each target needs
**An `mcp:` tool is SLNG-only for now.** Livekit and pipecat do not
compile `mcp:` tools yet, and `core_spec.go` refuses them. SLNG resolves the server
by name from its own registration, so it needs none of `url_env`, `transport` or
`auth`.
## Advanced
### What the compile does with it
On SLNG, the compile writes one reference per name in `tools` into `agent.json`.
Nothing else about the server is written, and `unmute deploy` checks each name
against the registered server's discovery snapshot.
## Troubleshooting
### The slng target asks for an explicit tool list
**SLNG has no "whole server" attachment, so `tools:` is required there.**
SLNG writes one reference per tool up front, and an offline compile cannot ask
the server what those are:
```text theme={null}
slng: slng target tool "web_search" exposes every tool on its MCP server, and SLNG
attaches one reference per tool: list the tools you want under mcp.tools
```
**Fix:** name the tools you want under `mcp.tools`. Read what the server offers
with `voiceai mcp list`.
## Where to go next
The last way a tool can run: the ones the runtime already has.
Where `url_env` and `token_env` values come from.
# Tools
Source: https://unmute.ai/build/tools/overview
What a tool is, the eight ways one can run, how each target treats them, and how you attach one to an agent.
A tool is two things: a contract the model sees, and something that runs when the
model calls it. Both live in one file, `tools/.yaml`.
The file stem is the tool name. It must be lower snake case and cannot start with
an underscore.
On this page:
* [The eight execution blocks](#the-eight-execution-blocks) - the ways a tool runs
* [How each target treats a tool](#how-each-target-treats-a-tool) - what each one supports
* [Choosing a kind](#choosing-a-kind) - stop at the first fit
* [Fields inside each execution block](#fields-inside-each-execution-block) - every key, per block
* [Which fields the block allows](#which-fields-the-block-allows) - the shared contract fields
* [The three behavior fields](#the-three-behavior-fields) - start: say, effect, interruption
* [Define once, attach by name](#define-once-attach-by-name) - one definition, one list
* [Troubleshooting](#troubleshooting) - the refusals you will meet
```yaml tools/find_slots.yaml expandable theme={null}
description: >-
List Sage and Stone slots for one service and date, and the caller's own
bookings. Call this before offering a time and before changing a booking.
local:
handler: tools/salon.py:find_slots
```
The top of the file is the contract. For a local tool the function's typed
signature in `tools/salon.py` is the input, and its Pydantic return model is the
output, so the file has no `input:` or `output:`. A webhook tool writes both as
JSON Schema instead. Write the description as an instruction rather than a
label, and let the types do real work: a `Literal["haircut", "hair-color",
"blowout"]` on the `service` argument means the model cannot ask for a service
the salon does not offer.
The signature is also the whole argument list. Generated Pipecat tools turn an
extra argument into a normal corrective tool result, so the model can retry
with only the declared fields. A handler failure before any result is returned
the same way, without exposing the private exception to the model or leaving a
call stuck in progress. Keep workflow prerequisites in the prompt; do not make
their names look like extra tool inputs in the description.
The one block near the bottom is the execution: it says how the tool runs. Every
tool file has exactly one.
## The eight execution blocks
| Block | The tool is | Where it is taught |
| - | - | - |
| `webhook:` | an HTTP call to a URL named by an environment variable | [Webhook tools](/build/tools/webhook) |
| `local:` | a Python function in your package | [Python tools](/build/tools/python) |
| `mcp:` | a remote MCP server that offers its own tools | [MCP servers](/build/tools/mcp) |
| `builtin:` | a tool the runtime already has, selected by id | [Prebuilt tools](/build/tools/prebuilt) |
| `slng:` | a tool the SLNG platform already hosts | [Hosted tools](/build/tools/hosted) |
| `client:` | a tool the caller's own application fulfils | gated, see below |
| `provider_hosted:` | a tool the model provider runs itself | gated, see below |
| `knowledge:` | a search over a folder of your own documents | [Knowledge bases](/build/tools/knowledge) |
Exactly one, and the compiler holds you to it. A file carrying two blocks, and a
file carrying none, are both refused with their line: see
[Troubleshooting](#troubleshooting).
### The two gated blocks
`client:` and `provider_hosted:` exist in the schema and no target emits them. The
capability table denies both on every provider, so writing one fails with the
target named:
```text theme={null}
livekit: LiveKit client tools are not proven by its driver
```
```text theme={null}
pipecat: Pipecat provider-hosted tools are not proven by its driver
```
These blocks are unsupported. Use a supported tool execution type instead.
Both blocks have no fields, but YAML still needs an explicit body: write
`client: {}` or `provider_hosted: {}`.
## How each target treats a tool
| Tool kind | SLNG | LiveKit | Pipecat | Twilio |
| - | - | - | - | - |
| `webhook:` | yes | yes | yes | **no** |
| `local:` | yes | yes | yes | yes |
| `builtin:` | yes | yes | yes | yes |
| `mcp:` | yes | yes | yes | **no** |
| `slng:` | yes | yes | yes | **no** |
| `knowledge:` | **no** | yes | yes | **no** |
| `client:` | no | no | no | no |
| `provider_hosted:` | no | no | no | no |
Twilio runs typed handlers, and the only builtin it takes is `end_call`. The target runs one agent with no tasks, and it refuses
`start: say` and `interruption: cancel`. [The Twilio target](/targets/twilio#what-the-package-may-carry)
lists every refusal.
On livekit and pipecat, the table is narrower: they compile only `local:`, `webhook:`, `knowledge:` and the `end_call` builtin: they refuse `mcp:`, `slng:` and every other builtin, so those are SLNG-only for now.
The same tool file compiles to three different runtimes, and they do not all
support the same things. This table is the capability table, which is what the
compiler actually reads, so a `no` here is a refusal you will meet at compile time
rather than a surprise on a call.
Three of those rows are worth a sentence.
**`local:` reaches SLNG as a code tool, and `webhook:` does not.** On an slng
target, `unmute deploy` publishes a typed `local:` tool to SLNG. It needs a
`tools/.sample.json` beside it ([details](/build/tools/python#on-the-slng-target)).
A `webhook:` block is refused. An API request tool is created in SLNG and
reached with `slng:`. Both blocks work as before on LiveKit and Pipecat.
**`mcp:` and `slng:` are SLNG-only for now.** LiveKit and Pipecat do
not compile them, and the compiler refuses them. Builtins other than `end_call` are
refused there too. SLNG resolves a hosted reference by name at deploy time: no mirror,
no hash, no `unmute pull`. See [Hosted tools](/build/tools/hosted) and
[MCP servers](/build/tools/mcp).
**`knowledge:` needs a runtime of ours to live in.** LiveKit and Pipecat compile to
a Python project, so the documents ride in the image and the search runs in the
process. The SLNG target writes a deployment body and SLNG runs the agent, so
there is no image to carry a folder and no process of ours to index it in. Put the
facts in the agent's instructions, or compile to a code target.
**`client:` and `provider_hosted:` are names with nothing behind them.** They exist
in the schema and no target emits them. They are documented so a refusal reads as
a decision rather than a bug.
### Attaching a tool to a task
| Tool kind on a task | SLNG | LiveKit | Pipecat |
| - | - | - | - |
| `mcp:` | yes | yes | **no**, list it on the agent |
| `knowledge:` | **no** | yes | **no**, list it on the agent |
| everything else | yes | yes | yes |
A tool listed on a task rather than on an agent is a narrower thing, and two kinds
are not available everywhere.
Pipecat's reason is the same for both: a task tool there is a flows handler holding
a `FlowManager`, not a decorated function holding `FunctionCallParams`. SLNG takes
no `knowledge:` tool anywhere. On SLNG a tool that only a task lists is attached
hidden from the main agent.
### The behavior fields
| Field | SLNG | LiveKit | Pipecat |
| - | - | - | - |
| `start: say` | yes | yes | yes |
| `with` | yes | yes | yes |
| `auth` | yes | yes | yes |
| `interruption` other than `provider_default` | **no** | warns | yes |
LiveKit runs a tool to completion, so a per-tool interruption value has nothing to
act on and it says so. SLNG owns its own turn taking and has no per-tool setting at
all.
Every refusal above names the target and tells you what to do instead. If you get
one you do not understand, `unmute validate` prints the same message with the tool
name attached.
## Choosing a kind
Work down this list and stop at the first one that fits.
| If the tool needs to | Use | Why not the others |
| - | - | - |
| end the call | `builtin:` | the runtime already has it; do not write your own |
| answer from your own documents | `knowledge:` | a webhook to a search service is a network hop and a service to run |
| call an API you already have | `webhook:` | no code of yours to deploy, and the URL is an environment variable |
| run logic, or touch something with no HTTP API | `local:` | it ships inside the image, so it costs no network hop |
| offer a whole catalogue of tools someone else maintains | `mcp:` | one block instead of a file per tool |
| run a tool SLNG already hosts | `slng:` | the platform owns its code and version, so there is nothing of yours to keep in step |
**Prefer fewer tools.** Every tool is text in the model's context on every turn,
and two tools with overlapping descriptions is the most common reason a model calls
the wrong one. A tool the agent list does not name is not offered at all, which is
the cheapest way to narrow a choice.
**Write the description as an instruction, not a label.** `description` and
the input types are the whole of what the model knows. Say when to call it, and say when
not to.
## Fields inside each execution block
Each tool file declares exactly one execution block. Its page lists the fields,
types, required conditions, and defaults:
* [Webhook](/build/tools/webhook#the-block): `url_env`, `base_url`, `path`, and `auth`.
* [Python](/build/tools/python#the-block): `handler` and `dependencies`.
* [MCP](/build/tools/mcp#the-block): `server`, `url_env`, `transport`, `auth`, and `tools`.
* [Prebuilt](/build/tools/prebuilt#the-block): `id` and `instructions`.
* [Knowledge](/build/tools/knowledge#the-knowledge-block-on-a-tool): `base`.
* [Hosted](/build/tools/hosted#hosted-reference-fields): `slng` names a published tool.
`client` and `provider_hosted` take an empty object and are gated on every target.
SLNG accepts published tool references and typed `local:` handlers, which deploy publishes as code tools. It refuses authored webhook bodies.
## Which fields the block allows
The contract fields are shared, with one exception that matters:
Required for local, webhook, and knowledge tools: explains when the model should call
the tool. Builtins use their registry description if omitted; hosted `slng` tools
inherit their published description. Refused on MCP sources.
Required for authored webhook contracts: a JSON Schema with `type: object`
describing model arguments. A local tool leaves it out, because its handler
signature is the input. Refused on builtin, MCP, knowledge, and hosted `slng` tools,
which own their schemas.
An author-side JSON Schema with `type: object`. Omit for no declared result schema. Used
by `save:` rows and outcome matches; it is not a general runtime result validator or a
model prompt. A local tool leaves it out, because its return model is the
output. Refused on builtin, MCP, knowledge, and hosted `slng` tools.
Hidden argument/value pairs. A value is `state.variable`, a scalar, or a string with
`{{state.variable}}` placeholders. Omit to pass nothing. Legal on local, webhook, and
hosted `slng` tools; builtin `send_sms` requires its literal `from_number` setting.
Accepts `provider_default`, `continue`, or `cancel`. Omitted means `provider_default`.
Refused on MCP sources. Target support is listed above.
Accepts `returns_data` or `ends_conversation`. Omitted means `returns_data`, except
builtins whose effect comes from the registry. Refused on MCP and knowledge tools.
Written on the tool's entry in `agent.yaml`, not in this file. A fixed spoken sentence
with no `{{variables}}`. Omit for no line. Legal on local, webhook, knowledge, and
hosted `slng` tools.
An `mcp:` file carries none of them, because the server owns each tool's contract.
A `builtin:` file takes no `input` or `output`. The registry supplies its contract
and default description, and your `description` is added on top if you write one.
A `knowledge:` file takes no `input`, `output`, `with` or `effect` either: the
tool asks for one string and returns passages, so there is nothing to describe and
nothing to merge into. It does take `description` and a `start: say:` line on its entry in `agent.yaml`, and
you should write both.
## The three behavior fields
```yaml tools/check_calendar.yaml theme={null}
interruption: provider_default
effect: returns_data
```
```yaml agent.yaml theme={null}
tools:
- name: check_calendar
start:
say:
- Let me check the calendar.
```
Accepts `provider_default`, `continue`, or `cancel`. Omitted means `provider_default`.
Refused on MCP sources. Target support is listed above.
Accepts `returns_data` or `ends_conversation`. Omitted means `returns_data`, except
builtins whose effect comes from the registry. Refused on MCP and knowledge tools.
The `start: say:` line is the one of the three written on the tool's entry in
`agent.yaml`, as in the file listing above. All three are optional, and each is honored differently per target. Pipecat maps
`interruption` onto its own cancel-on-interruption setting, while LiveKit runs
tools to completion, so a non-default value warns there. `effect` is fixed by the
registry on a `builtin:` tool, and a conflicting value fails.
### Using `start: say:`
The line is spoken once, as the tool starts, before the tool's own work. Nothing
waits for it to finish playing, so the caller hears the tool's answer no later
than they would without the line. It covers the wait, it does not add one.
**Reach for it when the tool is slow enough that the silence reads as a dropped
call.** A request to a service you do not control, a handler that queries a
database or a calendar. If the tool answers instantly, the announcement is just a
sentence in the way.
**Do not put one on every tool.** Two tools firing back to back means the caller
hears two announcements in a row, which is worse than the pause you were trying
to cover.
The sentence is fixed, so it is spoken word for word every time that tool
runs. Everything else follows from that.
| Write this | Not this | Why |
| - | - | - |
| `Let me check the calendar.` | `Let me find you some great times!` | you do not know yet what you will find |
| `One moment while I look that up.` | `I'm querying the availability API.` | the caller does not have your architecture |
| `Give me one second.` | `Please hold while I retrieve your account details from our system.` | it should be shorter than the wait it covers |
Pick something that still sounds fine the third time. If the model calls a
tool repeatedly within one conversation, that is an argument for not
announcing it at all.
If your instructions already tell the agent to say it is checking something,
delete that line when you add `start: say:`. Otherwise the model speaks its own
version, the tool speaks the fixed one, and the caller hears both.
| Rule | What happens if you break it |
| - | - |
| legal on `webhook:`, `local:`, `knowledge:`, `slng:` and `builtin:` | refused by tool name; an `mcp:` file is refused at load, with the line number |
| on a `builtin:`, the `slng` target only | refused by name on a code target, which builds the prebuilt from its own SDK and has no seam in front of it |
| a fixed sentence, no `{{variables}}` | refused by tool name |
| a blank value reads as absent | nothing is spoken and nothing is emitted |
| on Pipecat, list the tool on an agent, not on a task | refused by name, telling you to move it |
It adds no new interruption rule: if the caller speaks over the line, the
tool's own `interruption:` value decides what happens. LiveKit emits the line
for a tool listed on an agent or on a task. A target whose driver has no
lowering for the field fails validation with that driver's own reason, rather
than dropping the line quietly.
## Define once, attach by name
**Define each tool once.** The full definition exists only in
`tools/.yaml`: `description`, `input` and optional `output` on a webhook tool,
optional `with`, and one execution block. A local handler lives beside it in a
Python file, and the block names its function as `tools/.py:`.
Do not put any of those fields in `agent.yaml`.
Every file in `tools/` is a tool, so there is no list that loads them. Every `tools:` entry in an agent's or task's list in `agent.yaml` is a string name:
* `agents[].tools` grants an agent access, and
* `agents[].tasks[].tools` grants one nested task access.
A top-level `tools:` list in `agent.yaml` is only for a tool that needs behaviour on every agent. Each entry is a block with `save:`, `outcomes:`, `hidden:` or `start:`. A bare name there is refused.
```yaml agent.yaml theme={null}
agents:
- name: appointment_desk
prompt: instructions.md
think: reasoning
speak: voice
tools:
- check_slots
- cancel_appointment
```
For a task-scoped tool, attach the same loaded name to the task instead,
where the task is nested inside its agent:
```yaml agent.yaml theme={null}
agents:
- name: appointment_desk
tasks:
- name: find_slot
prompt: tasks/find-slot.md
tools:
- check_slots
```
The agent and task lists are visibility scopes. Attach a tool only where it is
called; do not grant it to both unless both really call it. Never replace a
name with an inline mapping of `description`, `input`, `output`, `local`, or
`webhook`.
A tool's optional `output:` remains its own JSON Schema. A task does not copy
that schema. Its `save:` list derives finish fields from destination
variables and saves only the values needed later.
## Troubleshooting
### A tool file has two execution blocks, or none
Every tool file runs exactly one way, so both shapes are refused. Two blocks:
```text theme={null}
tools/check_slots.yaml:7: two execution blocks (local and webhook): a tool runs
exactly one way
```
None at all, where the message is also the list:
```text wrap theme={null}
tools/check_slots.yaml: no execution block: add one of webhook, local, mcp, builtin,
client, provider_hosted, knowledge, slng
```
**Fix:** keep the block the tool really needs and delete the other, or add one of
the blocks the second message lists.
### A tool you wrote is never offered
A file in `tools/` that no agent or task lists is loaded but nobody may call it.
**Fix:** check the agent's or task's own `tools:` list.
### `output:` is refused on an slng target
A `local:` tool's `Output` comes from the return model of its Python function.
A tool SLNG hosts carries its own `Output` model. So the field has nothing to
set and is refused rather than dropped.
**Fix:** delete the field from the tool file. A hosted tool carries its own
`Output` model, written where the tool was written. Full story in [Python
tools](/build/tools/python#what-the-slng-sandbox-expects) and [Hosted
tools](/build/tools/hosted).
## Where to go next
The everyday case: call your own API.
When the call needs code of your own.
Offer a whole server's tools at once.
The ones the runtime already has.
Answer from a folder of your own documents.
# Prebuilt tools
Source: https://unmute.ai/build/tools/prebuilt
The capabilities the platform already has: a closed registry of four, and the settings you can pin on each.
Some tools need no code from you because the platform already has them. You
select one by id, and you can pin the settings it takes.
Reach for a prebuilt when the capability already exists, so writing your own
would just duplicate it. That is hanging up, reading the clock, sending a text
message, and reading the caller's number. For anything else, write a
[webhook](/build/tools/webhook), a [Python handler](/build/tools/python), or
point at an [MCP server](/build/tools/mcp).
On this page:
* [The block](#the-block) - two keys
* [The registry, in full](#the-registry-in-full) - four ids, and it is closed
* [Settings](#settings) - what `with:` pins on each capability
* [What the registry decides for you](#what-the-registry-decides-for-you) - effect, parameters, description
* [Speaking before it runs](#speaking-before-it-runs) - `start: say:` on a prebuilt
* [Turning it on](#turning-it-on) - the agent's list
* [Advanced](#advanced) - resolving on SLNG
* [Troubleshooting](#troubleshooting) - the refusals by name
```yaml tools/end_call.yaml theme={null}
description: "End the call when the caller is finished or says goodbye."
builtin:
id: end_call
```
That is the file `unmute init` scaffolds, so a new agent can hang up from its first
run.
## The block
Accepts `end_call`, `send_sms`, `current_datetime` or `user_phone_number` from the
registry below. No id is inferred. `end_call` compiles on every target; the other three
are SLNG only.
Instruction the runtime gives the model as the prebuilt runs. For `end_call`, use it for
a final line or action before ending. Omit to add no custom instructions to the
prebuilt.
## The registry, in full
| id | Effect | Settings it takes | Default description |
| - | - | - | - |
| `end_call` | `ends_conversation` | none | End the call when the caller is finished or says goodbye. |
| `send_sms` | `returns_data` | `from_number` | Send a text message to a phone number the caller has given and confirmed. |
| `current_datetime` | `returns_data` | `timezone` | Read the current date and time. |
| `user_phone_number` | `returns_data` | none | Read the number the caller is calling from. |
Four rows. The registry is **closed**: you cannot add to it from a package, and
there is no plugin seam. Adding a prebuilt means a row in the compiler plus a
lowering for each target, which is a change to Unmute, not to your agent.
`end_call` compiles on every target. The other three are capabilities SLNG
curates and compile on the `slng` target only for now. Livekit and
pipecat refuse them by name.
A capability's **settings** are written with `with:`. On a builtin that block
is the tool's own configuration, not an argument, because a curated capability
publishes no argument schema for one to go in. The model never sees a pinned
value either way.
`send_sms` takes one setting, the sender:
```yaml tools/send_sms.yaml theme={null}
description: Send a text message to the guest's confirmed mobile number.
builtin:
id: send_sms
with:
- from_number: "+447700900123"
```
`from_number` is a literal number in international format starting with a plus
sign, and it is the only key `with:` may carry here: SLNG requires the
sender on the attachment and lets the model supply the recipient and the body.
SLNG reads the Twilio credentials from your vault under `TWILIO_ACCOUNT_SID`
and `TWILIO_AUTH_TOKEN`, so `unmute deploy` checks both. Pair it with a
[`source: conversation` variable](/reference/variables#sources) so the number
the caller confirmed is recorded on the call.
`current_datetime` takes one setting, an IANA zone name:
```yaml tools/current_datetime.yaml theme={null}
description: Read the clock. Call it once at the start of the call, before any day or time is discussed.
builtin:
id: current_datetime
with:
- timezone: "America/Los_Angeles"
effect: returns_data
```
**Write the zone whenever your agent is not in UTC.** The curated tool defaults
to UTC and belongs to no organisation, so it cannot be changed on the platform.
An agent without the setting is told the wrong date for part of every day. A
zone name survives daylight saving; an offset written into the prompt does not.
`user_phone_number` takes no settings. The platform knows the number from the
call leg.
So read this page as a list of four things that exist, not as a catalog to
browse. If what you want is none of them, it is a
[webhook](/build/tools/webhook), a [Python handler](/build/tools/python), or an
[MCP server](/build/tools/mcp).
## Settings
A prebuilt's settings are written with `with:`, a list whose every item holds
one key. On a prebuilt that block is the capability's own configuration, not an
argument the model could supply, because a curated capability publishes no
argument schema. The model never sees a pinned value.
```yaml tools/current_datetime.yaml theme={null}
description: Read the clock. Call it once at the start of the call, before any day or time is discussed.
builtin:
id: current_datetime
with:
- timezone: "America/Los_Angeles"
effect: returns_data
```
A key the capability does not declare is refused, naming the ones it does:
```text theme={null}
tool "current_datetime" builtin current_datetime takes no setting "zone": it takes timezone
```
### `current_datetime`
An IANA zone name, such as `America/Los_Angeles` or `Europe/Madrid`. Omit it and the
agent reads the clock in UTC.
**Write the zone whenever your agent is not in UTC.** The curated tool defaults
to UTC and belongs to no organisation, so it cannot be changed on the platform.
An agent without the setting is told the wrong date for part of every day. A
zone name survives daylight saving; an offset written into the prompt does not.
Keep the clock a tool rather than copying its answer into a variable. A variable
is fixed when the session starts and the tool is not, so on a long call the model
ends up with two answers and trusts the one already in its prompt.
### `send_sms`
The sender, as a literal number in international format starting with a plus sign, such
as `+447700900123`. A template reference is refused: SLNG requires a literal here.
It is the only key `send_sms` takes. The model supplies the recipient and the
body itself, and SLNG reads the Twilio credentials from your vault under
`TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN`, which `unmute deploy` checks. Pair
it with a [`source: conversation` variable](/reference/variables#sources) so the
number the caller confirmed is recorded on the call.
### `end_call` and `user_phone_number`
Neither takes a setting. `user_phone_number` reads the number from the call leg.
On `slng`, `end_call` always says a goodbye before it hangs up. Without
`start: say:` it is SLNG's default line, "Thanks for calling. Goodbye!". Write
[`start: say:`](#speaking-before-it-runs) to choose your own. A goodbye set by
hand in the dashboard is removed by the next push, and
`unmute deploy --dry-run` says so before it happens.
## What the registry decides for you
**The effect.** `end_call` implies `ends_conversation`, and writing anything else
fails rather than being quietly ignored:
```text theme={null}
tool "end_call" builtin "end_call" fixes effect to ends_conversation, cannot be
"returns_data"
```
**The parameters.** A prebuilt owns its own schema, so the contract fields have
nowhere to go:
```text theme={null}
tool "end_call" builtin execution takes no input, output, handler, or url_env
```
**The description, unless you write one.** Leave `description` out and the registry
default is used.
Write your own `description` when the agent needs a narrower instruction, for
example telling it to confirm before hanging up. Yours is added on top of the
default rather than replacing the tool's behavior.
Use `builtin.instructions` when the model must do something at execution time:
```yaml theme={null}
builtin:
id: end_call
instructions: Thank the caller briefly, then end the call.
```
It does not change the tool's id, parameters, or fixed
`ends_conversation` effect.
## Speaking before it runs
On the `slng` target a prebuilt is an attachment like any other, so it can speak
a fixed line as it starts. The line goes on the tool's entry in `agent.yaml`:
```yaml agent.yaml theme={null}
tools:
- name: end_call
start:
say:
- Thanks for calling, goodbye.
```
One fixed sentence the agent speaks as the tool starts. More than one is refused here:
an attachment carries a single pre-action message. No `{{variables}}`.
On `end_call` the line is the goodbye. It replaces SLNG's own goodbye, so the
caller hears it once, then the call ends. Do not also tell the model to say
goodbye before it calls `end_call`, or the caller hears two.
Every other line runs alongside the tool, which is the point of it: a
sentence so a slow call is not silence.
A code target refuses `start: say:` on a prebuilt. It builds the capability from
its own SDK and has no seam in front of it, and the refusal says so.
## Turning it on
The agent names it, as with any other tool:
```yaml agent.yaml theme={null}
agents:
- name: greeter
prompt: instructions.md
think: reasoning
speak: voice
tools:
- end_call
```
## Advanced
### Resolving on SLNG
SLNG offers every one of these as a curated capability, so `unmute deploy`'s
preflight check has to match your reference against it before pushing. It
matches by the tool **file's** name, `tools/end_call.yaml`, never by the
`builtin.id` you selected inside it.
So **name the file after the id**. `unmute validate` refuses the mismatch on
the `slng` target and says which file to rename:
```text theme={null}
slng target: tool "hang_up" selects builtin "end_call", and this target attaches a builtin
by the tool file's own name: rename tools/hang_up.yaml to tools/end_call.yaml
```
A code target lowers the builtin to a function and does not care what the file
is called, which is why this is not a rule everywhere.
A name can also be held twice. SLNG publishes `end_call` to everybody and your
organisation can hold its own copy; `unmute deploy` attaches yours and names
both in its output, so you can see which one is running.
## Troubleshooting
### An id the registry does not hold
An id the registry does not hold is refused by name. Every line below is
prefixed with the target instance that refused it, so a fresh scaffold, which
has one `livekit` instance, reads like this:
```text theme={null}
livekit: tool "end_call" has unknown builtin "transfer_to_human"
```
**Fix:** pick one of the two ids in [the registry](#the-registry-in-full), or
write the capability yourself as a webhook, a Python handler, or an MCP source.
### The SLNG preflight says the organisation has no tool of that name
A file `tools/hang_up.yaml` holding `builtin: {id: end_call}` compiles and
validates, but the organisation has no tool named `hang_up`. The preflight then
reports it absent, even though the capability exists:
```text wrap theme={null}
this organisation has no tool of this name (it has `end_call`). A builtin reference is
the tool file's own name, so either rename the file to a capability SLNG offers, or
create the tool in the SLNG dashboard
```
**Fix:** keep a `builtin:` file's name matching its `id`.
## Where to go next
Answer from a folder of your own documents.
Return to all eight execution blocks.
# Python tools
Source: https://unmute.ai/build/tools/python
A handler of your own in the package: what it receives, what it returns, and where it is copied.
Some tools need code rather than a request. Write the function in your package and
name it from the tool file.
Reach for a Python handler when:
* the work is logic, not a request: a calculation, or a lookup in data you already have
* you are using a library already included in the generated project
* the request needs a signature, a custom header scheme, or a retry rule
If it is just an authenticated HTTP call, use
[a webhook tool](/build/tools/webhook) instead. It needs no code from you and no
code review.
A `local:` handler is a typed function. The signature is the tool's
input and the Pydantic return model is its output, so the tool file has no
`input:` or `output:`. Livekit and pipecat compile typed handlers. Twilio runs
the same typed handlers ([the Twilio target](/targets/twilio)). On an slng target,
a typed handler is wrapped into an SLNG code tool and published by
`unmute deploy` ([details](#on-the-slng-target)). SLNG refuses a handler with no
`:function`.
On this page:
* [Quickstart](#quickstart) - add one callable
* [The block](#the-block) - the one key it takes
* [The rules the function follows](#the-rules-the-function-follows) - four rules
* [When the handler is slow](#when-the-handler-is-slow) - cover the wait
* [Where it ends up](#where-it-ends-up) - inside the generated project
* [On the slng target](#on-the-slng-target) - the sample file, and what deploy publishes
* [Share a helper between tools](#share-a-helper-between-tools) - one source file, two callables
* [Credentials, when a real handler needs one](#credentials-when-a-real-handler-needs-one) - names, never values
* [Advanced](#advanced) - modules, dependencies, data, and SLNG limits
* [Troubleshooting](#troubleshooting) - the two worth reading
## Quickstart
These files extend an existing package that declares `customer_id`. Add
`cancel_appointment` to the package tool list and the agent
[tool list](/build/tools/overview#define-once-attach-by-name), then validate the package.
```yaml tools/cancel_appointment.yaml expandable wrap theme={null}
description: Cancel the appointment outright. Call it only when the customer says plainly that they want to cancel, never when they want a different time.
with:
- customer_id: "state.customer_id"
local:
handler: tools/cancel_appointment.py:cancel_appointment
```
```python tools/cancel_appointment.py theme={null}
from pydantic import BaseModel
class Cancellation(BaseModel):
cancelled: bool
customer_id: str
def cancel_appointment(customer_id: str) -> Cancellation:
return Cancellation(cancelled=True, customer_id=customer_id)
```
Those two are a worked example rather than a quote: they are the smallest shape
that shows a handler receiving a value from State. For real ones, every tool in
`examples/salon-concierge` is a local handler, and all of them share the one
`tools/salon.py`.
## The block
`file.py:function`. The path is a Python file inside the package, and the name after
the colon is the function to call. Its signature is the tool's input and its return
type is the output. A tool file with `input:` or `output:` next to a local handler
is refused.
The function does not need the tool's name, and one file can hold many tools. In
`examples/salon-concierge`, six tool files point at functions in `tools/salon.py`.
## The rules the function follows
| Rule | Why |
| - | - |
| every parameter has a type | the type becomes the model's input schema |
| the return type is a Pydantic model | its fields are the tool's output, which `save:` and `outcomes:` read |
| a `Field(description=...)` on a parameter says what it means | the model reads that text |
| a parameter named by `with:` is not the model's | it takes its value from State, so the model never sees it |
The handler above takes `customer_id` and the model is never asked for it,
because `customer_id` comes from `with:`. The model never sees that value and cannot
invent one. Put a description on a parameter with
`Annotated[str, Field(description="...")]`.
## When the handler is slow
A local handler that reads a calendar or a database keeps the caller waiting the
same way a webhook does. `start: say:` on the tool's entry in `agent.yaml` gives the agent one fixed sentence
to speak as the handler starts. It does not wait for that sentence to finish, so the
result arrives no later than it would in silence:
```yaml tools/record_complaint.yaml theme={null}
local:
handler: tools/salon.py:record_complaint
```
```yaml agent.yaml theme={null}
tools:
- name: record_complaint
start:
say:
- Let me get that written down.
```
That one is real, from `examples/salon-concierge`. Keep the line shorter than the
gap it covers: a long one runs into the answer and breaks its own promise of a
wait. The fixtures above carry no `start:`, because they return instantly and a
tool that speaks before doing nothing slow is just noise. Full rules in
[the behavior fields](/build/tools/overview#the-three-behavior-fields).
Two more things decide whether a tool should carry one at all. The line is spoken
when the tool is **called**, not when it succeeds, so a tool that can refuse the
call will sometimes promise something it then does not do. The salon's booking
tool refuses a save that arrives unconfirmed, and the caller heard "putting that
through now" followed by a question asking their permission. And only one line
belongs in a turn: a flow's own `say:` and a tool's `start: say:` fire together when
the flow's first step calls that tool, which the caller hears as two promises to
go and look.
## Where it ends up
`unmute compile` copies the file into the generated project. The generated code
hands the function to unmute-core, which reads its types and calls it as a plain
function. A function may be `async def`. The same handler file runs unchanged on
LiveKit and Pipecat.
## On the slng target
A `local:` tool works on the slng target. `unmute compile` wraps the
handler into SLNG's code tool file and writes `build/slng/tools/.json`
and `build/slng/samples/.json`.
Put a sample beside the tool file, `tools/.sample.json`. It is one JSON
object of arguments:
```json tools/book_slot.sample.json theme={null}
{"day": "2026-11-02", "time": "10:00", "service": "cut", "phone_number": "+34600111222"}
```
`unmute deploy --target slng` creates or updates the code tool, runs it once on
this sample, and publishes it. Then it attaches the tool by id and version.
SLNG publishes a code tool only after one run, so a local tool with no sample is
refused. A handler with no `:function` and an `async def` handler are refused too. SLNG
code has no internet access.
## Share a helper between tools
Keep several tool functions and their helper in **one authored file**. Each tool
file names its own function with `file.py:function`, so you maintain the helper
once. This works on LiveKit and Pipecat.
Create these three complete files in an existing package:
```python tools/text_helpers.py theme={null}
from pydantic import BaseModel
class WordCount(BaseModel):
count: int
class FirstWord(BaseModel):
word: str
def _words(text: str) -> list[str]:
return text.split()
def count_words(text: str) -> WordCount:
return WordCount(count=len(_words(text)))
def first_word(text: str) -> FirstWord:
words = _words(text)
return FirstWord(word=words[0] if words else "")
```
```yaml tools/count_words.yaml theme={null}
description: Count the words in text.
local:
handler: tools/text_helpers.py:count_words
```
```yaml tools/first_word.yaml theme={null}
description: Return the first word in text, or empty text when there are no words.
local:
handler: tools/text_helpers.py:first_word
```
Merge these names into the agent's list; keep the other agent fields:
```yaml agent.yaml theme={null}
agents:
- name: assistant
tools:
- count_words
- first_word
```
From the package directory, compile the declared targets:
```sh Terminal theme={null}
unmute validate
unmute compile
```
Import a helper from another file in the package only after you check that the
compiled project carries it. The compiler reads the file named by `local.handler`.
Keep reusable functions in that one file, or move the operation behind a
[webhook](/build/tools/webhook) or [MCP server](/build/tools/mcp).
## Credentials, when a real handler needs one
```python theme={null}
token = os.environ["CRM_API_TOKEN"]
```
Only the **name** belongs in the file. Put that name in `agent.yaml` under
`secrets:`; keep the value in your environment or secret store.
## Advanced
### Dependencies, files, and regeneration
Handlers run from the generated project root, `/app` in the emitted images.
The runtime requirement lives in generated `pyproject.toml`, and the compiler
selects dependencies from the chosen providers. Python's standard library is
available. Check that generated dependency list before importing another library.
A `local.dependencies` declaration is refused on both code targets. LiveKit's
[target pins](/targets/overview#targets-yaml) only override recognized packages;
there is no supported package field for adding arbitrary third-party dependencies.
A library installed on your laptop does not become part of the deployed image.
Adjacent JSON files, templates, certificates, and other module trees are not
copied with a handler. [Knowledge documents](/build/tools/knowledge) have their
own declared inclusion path; that is not a general-purpose file packaging hook.
For a small constant, keep it in the handler source. Otherwise use a remote service
until the package supports the files and dependencies your operation needs.
Edit the authored file and recompile to update its generated copies. Compilation
replaces added modules and changes to the generated Dockerfile or dependency
manifest. Unmute has no authored lifecycle-hook or custom build-file API.
### What the SLNG sandbox expects
A tool SLNG hosts runs under these rules. That includes a `local:` tool that
deploy publishes, and a tool you write by hand and reference with
[`slng:`](/build/tools/hosted).
**SLNG calls the handler itself, synchronously.** A plain `def` that runs its
own event loop internally, with `asyncio.run(...)`, is fine: only the entry
point has to be synchronous.
**SLNG derives the schemas by introspection.** A hosted `code` tool's module
defines an `Input` model, an `Output` model and a `handler()` taking one
`Input`, and the platform reads the parameter and result schemas off those
classes. `unmute compile` writes the same shape for a local tool: it wraps your typed
handler in an adapter like this one. Livekit and pipecat do not use it:
```python theme={null}
def check_order(order_number: str) -> dict:
status, delivers_on = ORDERS.get(order_number.strip().upper(), ("unknown", ""))
return {"status": status, "delivers_on": delivers_on}
from pydantic import BaseModel
class Input(BaseModel):
order_number: str
class Output(BaseModel):
delivers_on: str | None = None
status: str | None = None
def handler(input: Input) -> Output:
result = check_order(order_number=input.order_number)
return Output(**result)
```
`handler()` is what SLNG calls. A return value that does not fit `Output` fails
there rather than reaching the model unnoticed.
## Troubleshooting
| Symptom | Cause | Fix |
| - | - | - |
| `ModuleNotFoundError` for a helper | The imported file was not selected as a handler | Use the single-file helper pattern above |
| An SDK imports locally but fails in the image | Local installations do not enter generated dependencies | Check `pyproject.toml`; use a remote tool when a required dependency is unsupported |
| A handler cannot open an adjacent file | Arbitrary data files are not bundled | Keep small constants in source or read the data through a remote service |
| An edit disappears on compile | The edit was under `build/` | Change the authored handler and regenerate |
### `unmute validate` warns that a credential is not declared
`unmute validate` reads the handler, finds the names it looks up, and warns when
`agent.yaml` forgot to declare one:
```text wrap theme={null}
pipecat: environment variables referenced but not declared in secrets: CRM_API_TOKEN (tools/sync_customer.py os.environ)
```
The literal lookup also makes the compiler include the name in generated
environment instructions and the startup check even if the declaration is
missing.
**Fix:** add the name to `secrets:` in `agent.yaml`. Declaring it removes the
warning and keeps the explicit inventory complete.
### A hosted handler fails the moment it reaches the network
**Code on SLNG has no internet access at all.** A handler that imports
`requests`, `httpx`, `urllib`, `urllib3`, `aiohttp`, `http.client` or `socket`
and reaches the network fails at connection time inside the sandbox.
**Fix:** move that work into an API-request tool, which SLNG runs itself,
outside the sandbox.
## Where to go next
Offer a whole server's tools at once.
Every seam a credential travels through.
# Webhook tools
Source: https://unmute.ai/build/tools/webhook
Call your own API: a URL from the environment, a path that renders per call, and values the model never sees.
The everyday tool. The model decides to call it, Unmute builds the request, and
your API answers.
Reach for a webhook when:
* you already have an API to call
* the URL is a deployment choice, not something to hardcode
* you want no code of your own to write or review
If the work is logic rather than a request, or there is no API to call, write a
[Python handler](/build/tools/python) instead.
A `webhook:` tool works on livekit and pipecat. The twilio target refuses it:
move the request into a [Python handler](/build/tools/python). It is also
refused on an slng target: SLNG owns a tool's code, version and gate pipeline, so there is
nowhere in a package for a URL and its credential to write to there.
Reference a tool your organisation already has on the platform with
[`slng:`](/build/tools/hosted) instead.
On this page:
* [The block](#the-block) - the four keys
* [The path renders per call](#the-path-renders-per-call) - variables in the URL
* [Authentication](#authentication) - bearer or API key
* [What the model fills in, and what it cannot](#what-the-model-fills-in-and-what-it-cannot) - input against with
* [Advanced](#advanced) - naming the base URL, describing the result
* [Troubleshooting](#troubleshooting) - the refusals, and their fixes
```yaml tools/confirm_appointment.yaml expandable wrap theme={null}
description: Confirm that the existing appointment stays as booked. Call it when the customer says the time works.
input:
type: object
properties: {}
with:
- customer_id: "state.customer_id"
- dialed_number: "state.dialed_number"
- channel: phone
webhook:
url_env: SALON_API_URL
base_url: https://api.example.com
path: /customers/{{state.customer_id}}/appointments/confirm
auth:
type: bearer
token_env: SALON_API_TOKEN
effect: returns_data
interruption: provider_default
```
This is a worked example rather than a quote. A webhook tool naming both
`url_env` and `base_url` this way compiles to livekit and pipecat; an slng
target refuses it, for the reason in the note above. `examples/hotel-concierge`
ships no webhook tool: its places-search tool reaches SLNG through the
hosted-tool block instead.
`start: say:` on the tool's entry in `agent.yaml` is the one line worth knowing
about here, because a webhook is the tool most likely to keep the caller
waiting:
```yaml agent.yaml theme={null}
tools:
- name: confirm_appointment
start:
say:
- One moment while I confirm that.
```
The agent speaks that exact sentence as the call starts and does not wait for it to finish, so the answer arrives no
later than it would in silence. It is a fixed sentence, and `{{variables}}` are
refused. Full rules in [the behavior fields](/build/tools/overview#the-three-behavior-fields).
## The block
An UPPER\_SNAKE environment variable name holding the base URL. Required on LiveKit and
Pipecat. At least one of `url_env` and `base_url` must be present; no URL is inferred.
A literal HTTPS base URL. Omit it on code targets, which read `url_env` instead. The
SLNG target refuses authored webhooks: publish the tool on SLNG and use a hosted `slng`
reference.
Path appended to the base URL. A non-empty path starts with `/` and may use
`{{state.variable}}` tokens, whose values are URL-encoded. Omit to use the base URL alone.
Authentication using the fields below. Omit to add no authentication header.
`url_env` holds a **name**, so the base URL is a deployment choice rather than a
package one: staging and production run the same package against different APIs.
Pipecat and LiveKit read it at run time and never look at `base_url`.
## The path renders per call
```yaml theme={null}
path: /customers/{{state.customer_id}}/appointments/confirm
```
`{{state.customer_id}}` is a [variable](/build/variables), rendered when the tool is
called, and the rendered value is URL-encoded for you. Because it renders per
call rather than once at session start, a variable that only gets its value
once a task saves it partway through the call is fine here.
If the variable has no value when the model calls the tool, the call is refused
and the model is told what to ask the caller for, rather than sending a
half-formed request.
## Authentication
```yaml theme={null}
auth:
type: bearer
token_env: SALON_API_TOKEN
```
Accepts `bearer` or `api_key`. Required when `auth` is present; no scheme is inferred.
The environment variable holding the token. Always a name, never a value.
Legal on `api_key` only.
Every name you use here goes in `agent.yaml` under
[`secrets:`](/reference/secrets). The compiler also infers these fields as
required environment names, so leaving one out of `secrets:` warns without
dropping it from generated environment instructions or checks.
`api_key` and its header reach livekit and pipecat exactly as written. An
slng target never sees this field at all: `webhook:` is refused there, so
there is no bearer-only rewrite to plan around any more.
## What the model fills in, and what it cannot
`input` is the model's half of the request. `with` is yours.
```yaml theme={null}
input:
type: object
properties: {}
with:
- customer_id: "state.customer_id"
- dialed_number: "state.dialed_number"
- channel: phone
```
Values in `with:` are merged into the call and **never shown to the model**, so it
can neither see them nor overwrite them. That is the place a customer id, a
captured slot, or the number the call went out to rides along.
The tool above takes no parameters at all: everything the API needs comes from `with:`.
The model can call it or not call it, and that is the whole of its authority. It
cannot invent a customer id.
A value that is exactly one `state.x` or `{{token}}` keeps that field's type from `state.py`, so a
number stays a number.
Every `with:` value must be a scalar. Strings, numbers, booleans, and null are
legal; maps and lists are refused.
## Advanced
### Naming the base URL
`base_url` exists for a hosted target: that is where SLNG used to store the
URL in the tool body it pushed, since there was no environment for it to read
at run time there. An slng target refuses a `webhook:` block outright now,
for the reason at the top of this page, so there is no longer a target that
reads `base_url`. Name `url_env` for livekit and pipecat, which read it at
run time and never look at `base_url`.
### Describing the result
```yaml theme={null}
output:
type: object
properties:
slots:
type: array
items:
type: object
properties:
slot_id:
type: string
start_time:
type: string
required:
- slot_id
- start_time
required:
- slots
```
`output` is optional author documentation. The compiler checks that it is a
JSON Schema object, but no generator sends it to the model or writes it to the
compile report, and nothing checks the API's response against it either. The
example records the shape the API is expected to return; teach the model how
to use that data in the tool description or prompt.
A [`local:`](/build/tools/python) handler's `output:` was the one exception,
checked on an slng target because SLNG ran that handler itself. That block is
refused there now, and the check moved with the code: a hosted `code` tool's
module carries its own `Output` model, and SLNG reads the result shape off
that. See [Python tools](/build/tools/python#what-the-slng-sandbox-expects)
and [Hosted tools](/build/tools/hosted).
## Troubleshooting
### Both code targets refuse a tool with no `url_env`
Drop `url_env` and both code targets refuse, and the message still names a
hosted target as the reason the field exists at all:
```text theme={null}
livekit: livekit target reads a webhook base URL from the environment: tool
"confirm_appointment" needs url_env, keeping base_url for a hosted target
```
**Fix:** add `url_env` with the UPPER\_SNAKE name of the variable that holds the
base URL, and keep `base_url` if the package also has a hosted build.
### A `{{token}}` in the path names nothing
A token that names nothing at all fails at compile time:
```text theme={null}
tools/confirm_appointment.yaml:7: tool "confirm_appointment" webhook.path references
{{not_a_variable}}, which State in state.py does not declare
```
**Fix:** declare the field on `State` in `state.py`, or correct the spelling in the
path.
### `token_env` holds a value instead of a name
Again a name, never a value. A token written in place of a name is refused:
```text theme={null}
livekit: tool "confirm_appointment" auth token_env must be an UPPER_SNAKE environment
variable name, never a secret value
```
**Fix:** put the variable's name here and the token itself in your environment or
secret store.
### An `auth` field belongs to the other scheme
A field from the other scheme is refused too, and the message says why:
```text wrap theme={null}
livekit: tool "confirm_appointment" auth header is not a bearer field: bearer always sends
Authorization
```
**Fix:** drop `header` from a `bearer` block, or switch `type` to `api_key` if
the API really wants a named header.
### A key is in both `input` and `with`
A key cannot be in both lists, and the refusal explains the reason rather than
just the rule:
```text wrap theme={null}
tools/confirm_appointment.yaml:5: tool "confirm_appointment" passes "customer_id" in with:, which
is also an input property; a with: value is hidden from the model, so it cannot
double as a parameter the model fills in
```
**Fix:** decide who supplies it. Leave it in `with:` for a value the model must
never see, or in `input:` for one the model fills in.
## Where to go next
When the request needs code of your own, like a signature.
Where `{{state.customer_id}}` comes from.
# Variables
Source: https://unmute.ai/build/variables
Declare a value once in state.py, fill it during the call, and read it only where it is needed.
A variable is a named value the call holds onto. You declare what it holds in
`state.py`, something fills it during the call, and the prompts that need it
name it.
On this page:
* [Quickstart](#quickstart) - declare, fill and read one value
* [Declare it](#1-declare-it) - the `State` class, and the `variables:` list
* [Fill it](#2-fill-it) - a task, a pre-fetch, or the call itself
* [Read it](#3-read-it-where-it-is-needed) - placeholders, and the greeting
* [The types you can declare](#the-types-you-can-declare) - Pydantic types, plus lists and your own models
* [Advanced](#advanced) - models, passing values to a tool, and seeding a value locally
* [Troubleshooting](#troubleshooting) - the four that come up most
## Keep only the values the call needs
**Keep state small.** Declare a variable when a value must survive a task or
handoff, feed a later tool, or supply a needed call fact to a prompt. Before
adding one used by only one prompt, check whether the agent needs the fact at
all. Prefer fewer values that each represent one useful fact or result; do not
split a timestamp into date and time just because both fields are available.
For a clock, replace `current_date`, `current_weekday`, and `current_time` with
`current_datetime` and `current_weekday`. The timestamp already carries the
date and time. Keep the weekday only if the prompt must name it; reading the
clock's answer avoids asking the model to calculate it. If nobody needs the
weekday, keep just the timestamp.
Merge these entries into an existing package:
```python state.py theme={null}
class State(BaseModel):
current_datetime: str = ""
current_weekday: str = ""
```
```yaml agent.yaml theme={null}
prefetch:
- name: local_clock
clock: now
timezone: Europe/Madrid
save:
- current_datetime: result.datetime
- current_weekday: result.day_of_week
```
Use a model for fields that travel together as a task result. Pre-fetch fills
plain values, so it cannot save the clock into a model. Keep separate values
when they have different confirmation steps or different readers.
## Quickstart
Declare a value, save it when a task finishes, and read it in a later prompt:
```python state.py theme={null}
from pydantic import BaseModel, Field
class State(BaseModel):
requested_service: str = Field(
"", description="The service the caller chose for this booking."
)
```
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: choose_service
when: Find out which service the caller wants.
prompt: tasks/choose-service.md
save:
- requested_service: result.service
```
```markdown tasks/booking.md theme={null}
Requested service: {{state.requested_service}}
If no service is recorded, ask which service the caller wants.
```
```sh theme={null}
unmute validate my-agent
```
That is the whole loop: **declare, fill, read.** The rest of this page is each
step in full.
The snippets below extend an existing package. Merge them into the matching
blocks in `state.py` and `agent.yaml`.
## 1. Declare it
Write a `State` class in `state.py`, next to `agent.yaml`. Each field is one
variable. Start with plain text:
```python state.py theme={null}
from pydantic import BaseModel, Field
class State(BaseModel):
requested_service: str = Field(
"", description="The service the caller chose for this booking."
)
```
That is the whole declaration. `requested_service` is the name you will use
everywhere else, and `str` means it holds text. The default is what the value
starts as. Every field needs one: `= ""` for text, `= None` with `| None`, and
`= []` for a list.
`Field(description=...)` is what the model reads when a task asks it for this
value. Write it for the model, short, and so it reads whole when the value is
empty. The reasoning you want to keep for the next author goes in a `#` comment,
which reaches nothing.
`agent.yaml` lists a value under `variables:` only when it needs a `source:` or
a `confirm:`. It is a list, with one entry per value:
```yaml agent.yaml theme={null}
variables:
- name: caller_name
source: call_start
```
The field on `State` this entry configures. An entry naming no field is refused.
Accepts `call_start`, `conversation` (SLNG only), or a [system call
fact](/reference/variables#sources). If omitted, the variable has no automatic call-fact
source; a task, pre-fetch, or session payload can still fill it. Route support is
checked for system sources. `conversation` requires a `Field(description=...)` and an
`= None` default in `state.py`. Inbound code-target calls require a default for
`call_start`.
The name of the task that must hear the caller agree to a pre-fetched value. Until
confirmed, only that task can read it in a prompt and tools cannot silently use it. If
omitted, the value is usable as soon as it arrives.
A variable starts at its default. An unset value renders as `none recorded yet.`
in a prompt.
`unmute validate` and `unmute compile` read `state.py` by running it through
`uv`, so `uv` must be on your `PATH` for a package that has one. The first run
needs network. A package without a `state.py` needs no `uv`.
## 2. Fill it
Declaring a variable creates the box. Something still has to put a value in it.
There are three ways, and each has its own page:
| How | When it happens | Written where |
| - | - | - |
| A task's `save:` | when that task finishes | on the [task](/build/orchestration/tasks) |
| [`prefetch:`](/build/prefetch) | once, before the greeting | in a top-level `prefetch:` entry |
| `source:` | as the call starts | on the variable itself |
The common one is a task. Add `save:` to the task that learns the value:
```yaml agent.yaml theme={null}
agents:
- name: concierge
tasks:
- name: choose_service
when: Find out which service the caller wants.
prompt: tasks/choose-service.md
save:
- requested_service: result.service
```
```markdown tasks/choose-service.md theme={null}
Find out which salon service the caller wants. Use what they have already
said and ask only if the service is missing or unclear. Then finish with
that service.
```
`save:` creates a finish argument named `service` from the
`requested_service` field. The field already owns the type and the description,
so the task does not repeat them.
A step must return every whole value it saves. Mark one it may leave out with
a `?` after the result field, as `- callback_time: result.callback_time?`.
All saved values are checked before any are saved. If one is invalid, the
task stays open so the model can correct its answer, and nothing changes.
## 3. Read it where it is needed
Saving a value does not put it in any prompt. A prompt reads a value only when
it names it, as `{{state.name}}`:
```markdown tasks/booking.md theme={null}
Requested service: {{state.requested_service}}
Use it if present. If no service is recorded, ask which service the caller wants.
```
An unset value renders as `none recorded yet.`, so write the sentence to read
whole either way. The instructions above work before and after the earlier task
saves the service.
A bare `{{requested_service}}` is refused, with the fix: `write {{state.requested_service}}`.
The agent that owns a task needs its own placeholder to remember the result
after the task returns. It gets a completion status and its own earlier
conversation back, not the private conversation inside the task.
### Use one in the greeting
The greeting renders once, before anyone speaks, so it can only name a value
that is already settled: one supplied at session start, a default, or a
prefetch save.
```python state.py theme={null}
class State(BaseModel):
caller_name: str = "there"
```
```yaml agent.yaml theme={null}
variables:
- name: caller_name
source: call_start
conversation:
greeting:
speaks_first: agent
say: "Hi {{state.caller_name}}, how can I help?"
```
Do not greet a caller by a name you have not checked with them. A name looked
up from the number that called is a guess: people call from a partner's
phone. Mark it with
[`confirm:`](/build/prefetch#always-check-a-value-with-the-caller) and the
greeting cannot use it until they say yes.
## The types you can declare
The type is what the call checks a value against before saving it. A task's
finish argument is built from it too, so the model is told what shape of answer
is wanted. `state.py` is ordinary Pydantic, so the types are Pydantic's.
| Type | What it holds |
| - | - |
| `str` | Free text, such as names and notes |
| `int` | A whole number |
| `float` | A number that may have a decimal part |
| `bool` | `true` or `false` |
| `date` | A calendar date, shown in a prompt as `2026-10-02` |
| `time` | A time of day, shown in a prompt as `16:30:00` |
| `EmailStr` | A valid email address, saved as plain text |
| `Annotated[str, StringConstraints(pattern=...)]` | Text that matches a pattern, such as an identifier |
Those cover most packages. The forms below are for when they do not.
### A phone number
`pydantic_extra_types.phone_numbers` has a `PhoneNumber`, which on its own saves
`tel:+34-600-111-222`. Wrap it so the saved value is E.164, `+34600111222`:
```python state.py theme={null}
from typing import Annotated
import phonenumbers
from pydantic_extra_types.phone_numbers import PhoneNumberValidator
Phone = Annotated[
str | phonenumbers.PhoneNumber, PhoneNumberValidator(number_format="E164")
]
class State(BaseModel):
caller_phone: Phone | None = None
```
Besides `phone_numbers`, two more `pydantic_extra_types` modules are open to
you: `currency_code` and `language_code`. Any other is refused. The
[reference](/reference/variables#what-a-field-can-be) lists the types in each.
### A fixed set of choices
```python state.py theme={null}
class State(BaseModel):
booking_status: Literal["booked", "cancelled", "pending"] | None = None
```
Anything outside the set is refused where it enters, and the refusal lists what
was allowed. The default is `None`, because an empty string is not one of the
three words.
### A value that may be absent
`T | None` says `null` is a valid answer, not a failure. Use it when a lookup
can honestly come back with nothing.
### Several values of the same type
`list[T]` holds many. See [Keep several records](#keep-several-records) below.
LiveKit and Pipecat support every type on this page. On the SLNG target, a
value a task saves, or one with `source: conversation`, can use most of them.
[Tasks and flows](/targets/slng#tasks-and-flows) lists which. A
value the dispatch fills stays plain `str`, because SLNG holds it as text. The
[Twilio target](/targets/twilio) refuses a `state.py`.
The [reference](/reference/variables#the-state-class-holds-the-types)
has the full list, what is refused, and how a type is enforced. Your tools
still check business rules, such as whether a record exists and whether a slot
is free.
Every kind of type on this page appears once in
[`examples/customer-intake`](https://github.com/slng-ai/unmute/tree/main/examples/customer-intake),
one agent that collects a caller's details and hands them to a tool.
## Keep several records
Declare `list[T]` when later steps need several values of the same type. A list
starts as `[]`.
In a task's `save:`, `variable+:` appends one item and `variable:` replaces
the whole list:
```python state.py theme={null}
class State(BaseModel):
notes: list[str] = []
```
```yaml agent.yaml theme={null}
save:
- notes+: result.note
```
Appending skips `null` and skips an identical structured item. See
[saving rules](/reference/variables#saving-a-task-result-to-a-variable),
and [state design](/best-practices/state-design#choose-a-current-value-or-a-list)
to choose between a current value and a list.
## Advanced
Three things you will not need on your first agent.
### Group fields into a model
Skip this until you need it. A model is worth declaring when several fields
always travel together and one tool fills all of them at once. Until then,
separate variables are simpler to read and simpler to prompt.
A pre-fetch cannot fill a model or a list. Use a task to produce grouped fields;
use separate scalar variables for clock and lookup pre-fetch results. A single
pre-fetch may save several scalar variables from one result.
A model is a Pydantic class in `state.py`. Declare its fields, then use the
class as a field's type on `State`.
One model can be used by several fields. Each field holds its own value, and a
a task `save:` row saves all of the object's fields together.
For example, this package defines an object type called `Appointment` and
uses it for the variable `appointment`:
```python state.py theme={null}
from datetime import date, time
from typing import Literal
from pydantic import BaseModel, Field
class Appointment(BaseModel):
booking_id: str
service: Literal["haircut", "hair-color", "blowout"]
date: date
time: time
class State(BaseModel):
appointment: Appointment | None = Field(
None, description="The latest appointment successfully saved by the booking tool."
)
```
Give a model field a `Field(description=...)` when it needs explaining to the
model. Its `description` is sent with the field in the finish argument.
Declare a field only when something in the package can fill it. A field no
tool returns leaves the model inventing a value or sending an empty one, and
it renders empty in every prompt that names it for the rest of the call.
#### Reading one field
`{{state.appointment}}` renders the whole object as compact JSON.
`{{state.appointment.date}}` reads one field, and a dotted path can follow nested
models. To read fields from a list item, save that item into its own variable
first.
For a name and an email address, use a two-field model such as
`Contact(name: str, email: EmailStr)`, so `{{state.contact.name}}` and
`{{state.contact.email}}` work. Pydantic's own `NameEmail` is one string, so a
prompt cannot read `.name` from it.
For deciding which fields belong together, separating a requested change from a
saved result, and choosing one record or a list, see
[Designing declared state](/best-practices/state-design#group-fields-that-describe-one-result).
### Hand a value to a tool
Sometimes the tool needs a value the model does not need to read or type. Use
`with:` for that argument:
```yaml tools/check_slots.yaml theme={null}
with:
- service: "state.requested_service"
local:
handler: tools/check_slots.py:check_slots
```
```python tools/check_slots.py theme={null}
def check_slots(date: str, service: str) -> Slots:
...
```
The model supplies `date`. The handler receives both `date` and the current
`service`. The handler's signature is the tool's input, so the model is asked
only for the arguments that `with:` does not name.
If the value is missing or unconfirmed, the tool stops before it runs. The
error names the task that supplies or confirms the value when one is declared,
and otherwise asks the model to collect it.
Injection is not the same as keeping a value private: tool results and spoken
messages can still contain it. See
[Reduce context sharing step by step](/best-practices/context-scope).
### Try it locally
```sh theme={null}
unmute dev my-agent --var caller_name=Priya
```
`--var` works for a declared variable with `source: call_start` or no `source:`
at all. Values are parsed against the field's type; pass JSON for a model or a
list, quoted for your shell. A value that does not fit its type stops the call
start, and the error names the field.
A system source such as `from_number` comes from the phone route instead, and
your machine is not one. To exercise prefetch and confirmation locally, stand
in for the network:
```sh theme={null}
unmute dev my-agent --source from_number=+15005550006
```
Which facts a route supplies, and in which direction, is in the
[source reference](/reference/variables#sources).
## Troubleshooting
### A prompt renders `none recorded yet.` on every call
The variable is unset. Either nothing has filled it yet, or the prompt that
reads it runs before the step that fills it.
**Fix:** check which step owns the `save:`, and write the sentence so it reads
whole either way. An unset value is normal early in a call, so the prompt should
say what to do about it:
```markdown theme={null}
Requested service: {{state.requested_service}}
If no service is recorded, ask which service the caller wants.
```
### The owning agent forgets a value after its task returns
A task returns a completion status and the owner's own earlier conversation. It
does not hand back the private conversation inside the task.
**Fix:** put a placeholder in the **owner's** prompt too. Saving is not sharing.
### A tool refuses to run, naming a value
The tool reads that value through `with:` or a webhook path, and the value is
empty or still unconfirmed.
**Fix:** the refusal names the task that supplies or confirms it. Run that step
first, or, when nothing supplies the value, have the model ask the caller.
### `--var` is refused for a variable
`--var` works only for a variable with `source: call_start` or no `source:` at
all. A system source such as `from_number` comes from the phone route, and your
machine is not one.
**Fix:** use `--source` instead, which stands in for the network:
```sh theme={null}
unmute dev my-agent --source from_number=+15005550006
```
## Where to go next
The usual way a variable gets filled: `save:` on the task that learns it.
Fill a value before the greeting, and confirm the ones about the caller.
Who can read what, and how to share less as the call goes on.
Which fields belong together, and when a list beats a current value.
API keys and tokens, which are not variables.
Every type, field, source and assignment option.
# Your first agent
Source: https://unmute.ai/build/your-first-agent
The smallest real agent: a prompt, four models, and one file that says who is answering.
An Unmute package is a directory. The agent lives in `agent.yaml`, the prompt
lives in a Markdown file next to it, the call state lives in `state.py`, and the
target choice lives in `targets.yaml`. This page walks that file, key by key. Everything else in this
section adds to it.
Make one now, then read along in the file it writes. Already ran this in the
quickstart? You are sitting inside that `my-agent/` directory: `cd ..` first,
or skip the command and read along in the file already on disk.
```sh theme={null}
unmute init my-agent
```
```text theme={null}
created my-agent/agent.yaml
created my-agent/.env.example
created my-agent/.gitignore
created my-agent/instructions.md
created my-agent/state.py
created my-agent/targets.yaml
created my-agent/tools/end_call.yaml
```
That package already validates and already runs. One agent, browser audio, one
built-in tool so it can hang up, no phone number and no third-party account.
Everything below is a tour of what is in it, so nothing here is a detour.
On this page:
* [The agent file](#the-agent-file) - every top-level key `unmute init` writes
* [The state file](#the-state-file) - what one call knows
* [The target file](#the-target-file) - where this package compiles to
* [Try it](#try-it) - validate, then compile
## The agent file
The small snippets below keep one block on screen at a time. Expand the full
file when you want to see how they fit together. This is
`my-agent/agent.yaml` as the scaffold wrote it, with its explanatory comments
taken out so the shape is visible.
```yaml theme={null}
name: my-agent
entry_agent: assistant
agents:
- name: assistant
prompt: instructions.md
think: assistant_model
speak: assistant_voice
tools:
- end_call
secrets:
- OPENAI_API_KEY
- SLNG_API_KEY
models:
think:
assistant_model:
description: default reasoning model
provider: openai
model: "gpt-5.6-terra"
params:
reasoning_effort: none
speak:
assistant_voice:
description: default voice
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
turn:
detector:
provider: livekit
model: turn-detector-mini
conversation:
greeting:
speaks_first: agent
say: "Hi there, I'm listening. What can I help you with?"
```
Now each block.
### `name`
```yaml theme={null}
name: my-agent
```
What this agent is called. The deployed name is this joined to the target it was
compiled for, so on a target called `livekit` it deploys as
`my-agent-livekit`. Required, lowercase letters, digits and single
hyphens, and it must not be a name another package in your organisation already
uses: a deploy replaces the agent whose name it matches. The
[`name` reference](/reference/agent-yaml#name) has the whole rule.
### `entry_agent`
```yaml theme={null}
entry_agent: assistant
```
Which agent answers. A package can hold several agents; exactly one starts the
call. The name has to be a key in the `agents:` map.
### `agents`
```yaml theme={null}
agents:
- name: assistant
prompt: instructions.md
think: assistant_model
speak: assistant_voice
```
An agent is a name, a prompt and the models it speaks and thinks with. `prompt`
is a path to a Markdown file in the package. Writing the prompt in its own file
means it reviews like prose, not like YAML.
### `secrets`
```yaml theme={null}
secrets:
- OPENAI_API_KEY
- SLNG_API_KEY
```
A list of environment variable names. Never values. Unmute writes these into
the generated `.env.example` and into a startup check inside the generated
project, so a missing key stops the container with a clear message instead of
failing on the first spoken word.
There is no way to write a secret's value in the package, on purpose. See
[secrets](/reference/secrets).
### `models`
Four kinds of model, grouped by what they do:
| Section | Job | Common name |
| - | - | - |
| `think` | decides what to say and which tool to call | LLM |
| `speak` | turns text into audio | TTS |
| `listen` | turns audio into text | STT |
| `turn` | decides when the caller has finished speaking | turn detection or VAD |
Each section holds named entries. The name is yours: `assistant_model`,
`assistant_voice`, `transcriber`, `detector` above. An agent then points at the
entries it wants by name.
```yaml theme={null}
models:
think:
assistant_model:
provider: openai
model: "gpt-5.6-terra"
params:
reasoning_effort: none
```
`provider` names the integration; `model` and `voice` are passed to that
provider exactly as you wrote them. Unmute does not keep a list of valid model
ids, so a typo shows up as a provider error at run time, not at compile time.
`params:` is normally passthrough for anything else the provider takes. The one
line here earns its place: `gpt-5.6-terra` is a reasoning model, and OpenAI
refuses a chat request that carries function tools unless it sets
`reasoning_effort`. This package has a tool, `end_call`, so the line is doing
real work from the first run. The LiveKit Responses compiler directive is the
narrow exception; [Reasoning model](/models/llm) has both forms.
You can define more entries than you use. Unused entries are legal
alternates, which makes swapping a voice a one line change.
The `listen` and `turn` sections have one entry each here, so nothing needs to
select them. With two or more entries you add a top level `listen:` or `turn:`
line naming the one to use.
### `conversation`
```yaml theme={null}
conversation:
greeting:
speaks_first: agent
say: "Hi there, I'm listening. What can I help you with?"
```
Who speaks first and what they say. The greeting is spoken word for word without
going through the model, so changing it changes nothing else. `conversation` also
holds `interruption:`, `inactivity:` and `max_duration:`, which the scaffold
leaves out; the
[`conversation` reference](/reference/agent-yaml#conversation) has them.
## The state file
```python state.py theme={null}
from pydantic import BaseModel
class State(BaseModel):
"""What one call knows, shared by every agent and task in it."""
```
`State` is empty at first. A call keeps its values here, and prompts and spoken
lines read them as `{{state.x}}`. Add a field with a default when a task or a
tool needs to save something. A local tool needs no schema in YAML: its Python
function's typed signature is the input, and its Pydantic return model is the
output. See [Python tools](/build/tools/python).
## The target file
```yaml targets.yaml theme={null}
channels:
- name: web
kind: realtime_audio
capacity:
peak_sessions: 10
max_sessions: 20
avg_session_duration: 5m
targets:
livekit:
provider: livekit
version: "1.8.8"
sdk_language: python
```
`channels` says how people reach this agent. The `web` channel, `kind: realtime_audio`, is browser
audio, which is what `unmute dev` serves. Phones come later, in
[Telephony](/telephony/overview).
`capacity` is your traffic estimate. The compiler turns it into worker counts
and quota numbers in the generated project, and marks them unbenchmarked
because they come from a conservative assumption, not from a measurement of
your agent. Both keys sit above `targets:` and apply to every target.
One target. Nothing in `agent.yaml` names a target, so this file is the only
place the choice lives, and one package can declare several. A second instance
here compiles a second complete project from the same agent, and a target that
cannot run a model entry as written overrides that entry by name rather than
changing the agent. [Targets](/targets/overview) has both.
## Try it
```sh theme={null}
unmute validate my-agent
```
The scaffolded package validates clean. A warning, when you do get one, does
not stop the command: it names a real difference worth reading. Now talk to
the agent in your browser:
```sh theme={null}
unmute dev my-agent
```
## Agent fields
A lower snake case name, unique across the package.
Path to a Markdown prompt inside the package. No prompt is inferred.
Name of an entry in `models.think`. No profile is inferred.
Name of an entry in `models.speak`. No profile is inferred.
Names of loaded tool files this agent may call. Omit for no ordinary tools.
Nested task definitions or bare names of tasks defined by another agent. Omit for no
tasks. See [task fields](/build/orchestration/tasks#every-key-a-task-takes).
Ordered task sequences this agent defines or names. Omit for no flows.
Agents this one can hand the caller to, defined here or named. Omit for no agent
handoffs.
People this agent can put the caller through to, defined here or named. Omit for no
human transfers.
## Where to go next
One rule that gets you from this agent to several.
Personalize each call and pass values without exposing them to the model.
Every supported `agent.yaml` key and value.
# Changelog
Source: https://unmute.ai/changelog
What changed in each release of the Unmute CLI, newest first.
Every release of the Unmute CLI, newest first. Each entry is that release's
notes as published, and it links to the release on GitHub, where the binaries,
the checksums and the full commit list live.
An entry describes the release it shipped with, not how Unmute behaves today.
The guide is the current answer. Where an entry mentions the Context Router, the
[Context Router page](/optimization/context-router) is the page that explains
how the router decides which turns to treat as repeatable, and which upstream
kinds were validated live here.
Dev page Metrics fixes and a working Claude skill install.
How to upgrade:
1. Upgrade unmute: `brew upgrade --cask slng-ai/tap/unmute`.
2. If you use Claude, run `unmute skill install --agent claude` again.
You do not need to compile your agents again.
Fixes:
* Metrics view: each reply now sits on the caller turn it answers.
Before, a reply was shown on the turn before it, and the last turn
showed ", ". This affected typed calls and mic calls on LiveKit.
* Metrics view: when you open a turn, its parts are now listed in the
order they started. Before, they were grouped by type. A tool turn
now reads the way it ran: LLM, tool, filler speech, LLM, tool, reply.
* `unmute skill install --agent claude` now also writes the shared
skill files under `.agents/skills/`. Before, it wrote only the
`.claude` pointers, and they pointed at files that did not exist.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.7.3)
A new dev page with metrics, state and text chat, plus runtime fixes.
How to upgrade:
1. Upgrade unmute: `brew upgrade --cask slng-ai/tap/unmute`.
2. Compile your agents again. The generated Pipecat and LiveKit
projects changed: `call_state.py`, `pyproject.toml` and the
LiveKit `agent.py`.
Highlights:
* The `unmute dev` page has a new look, in the style of SLNG Studio.
It has a top bar, a call bar, a transcript with a speaker column, and
a side panel with call details.
* New Metrics view. It shows p90 tiles and one row per caller turn,
with the time for each part: STT, LLM, TTS and tools. Open a turn to
see each part on its own row. Latency by model is grouped by STT,
LLM, TTS, and tools and handoffs.
* Reply latency colours: green up to 900ms, yellow up to 1200ms,
orange above. Red now means failed only. Turns with tool calls are
not rated. A legend explains the colours.
* Live call state. Every save to `State` shows as a row in the
conversation, with what set it and the value before. A new State
panel lists every field from `state.py` with its current value.
* Type to the agent. During a call, a text box under the conversation
sends a line as the caller's turn. A new **Text only** button starts
a call with no microphone.
* A start screen shows progress while the agent starts. If the start
fails, it shows the first error and a link to Logs.
Fixes:
* `unmute dev --target pipecat` no longer fails at startup for a
package with `knowledge:` on Linux. Generated projects now tell uv
to copy packages, not hard-link them.
* A LiveKit worker behind `HTTPS_PROXY` now connects to its server
directly when `NO_PROXY` lists the server. Before, the proxy
answered 405 and the worker gave up.
* Pipecat reply latency is now linked to its reply. Before, every
Pipecat turn in Metrics showed ", ".
* On LiveKit, a hang-up during a task is now recorded as `cancelled`,
not `failed`.
* The docs changelog workflow works again. It now opens a pull request
after each release.
Examples:
* New `examples/salon-concierge-unoptimized`. All three salon examples
now use the same model, tools and turn-taking. You can compare their
token use directly. salon-concierge uses 36 to 45% fewer tokens than
the unoptimized one.
* `scripts/text_run_livekit.py` now prints token usage.
Privacy note: the dev page and `build//dev.log` now show state
values. These can include tool results and caller details. They stay
on your machine.
Run `unmute skill install` to refresh the bundled assistant guidance.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.7.2)
SLNG deploy fixes.
How to upgrade:
1. Upgrade voiceai: `brew upgrade slng-ai/tap/voiceai`. Deploy needs
voiceai 0.1.22 or later.
2. Upgrade unmute: `brew upgrade --cask slng-ai/tap/unmute`.
3. Compile and deploy your SLNG agents again.
Fixes:
* end\_call: the caller hears one goodbye, not two. The `announce:` on
end\_call is now the goodbye line itself.
* Inbound calls no longer fail when a prompt uses a call fact, such as
`from_number`.
* A package that also targets LiveKit or Pipecat no longer fails to
deploy because of `world_part`.
* Deploy works again after api.slng.ai went offline.
* A dry run no longer refuses an MCP server whose snapshot is old.
New:
* Deploy warns you when inbound phone calls are not ready.
Changed:
* The deploy report drops `organisation` (report\_version 2).
Run `unmute skill install` to refresh the bundled assistant guidance.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.7.1)
Call state in state.py, and tasks on SLNG managed agents.
How to upgrade:
1. Upgrade voiceai: `brew upgrade slng-ai/tap/voiceai`. Deploying a
task that lists tools needs voiceai 0.1.20 or later.
2. Upgrade unmute: `brew upgrade --cask slng-ai/tap/unmute`.
3. Install uv ([https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)) if a package has variables.
unmute now reads state.py with it. The first run needs network.
4. Run `unmute validate` on each package. Every old form is refused
with its file, its line and where it moved. The fixes are below.
5. Run `unmute compile` and deploy.
Breaking changes:
* The call state is a Pydantic model in state.py. Why: types,
defaults and descriptions are now real Python that Pydantic checks,
not a type grammar inside YAML. How: move each variable's `type:`,
`default:` and `description:` to a field on `class State(BaseModel)`
in `/state.py`. `variables:` in agent.yaml is now a list. It
keeps only the values that need `source:` or `confirm:`.
```yaml theme={null}
# before, agent.yaml
variables:
caller_phone:
type: Phone
default: ""
confirm: verify_contact
description: The caller's number in E.164.
# after, agent.yaml
variables:
- name: caller_phone
confirm: verify_contact
```
```python theme={null}
# after, state.py
class State(BaseModel):
caller_phone: Phone | None = Field(None, description="The caller's number in E.164.")
```
The old form fails with:
`variables: is a list now. Types, defaults and descriptions live on State in state.py`.
* `shapes:` is gone. Why: a shape is a type, and types now live in
state.py. How: write each shape as a `BaseModel` class in state.py
and use it as a field type on State.
* Templates name a saved value as `{{state.x}}`. Why: the name now says
where the value lives, a field on State in state.py. How: change
`{{x}}` to `{{state.x}}` in the greeting, prompts, tool `inject:`,
webhook `path:` and prefetch `args:`. `{{$NAME}}` is unchanged. The
old form fails with:
`{{x}} names a value on State; write {{state.x}}`.
* A step must return every value its `assign:` names. Why: every field
that starts empty is now `| None`, so `| None` can no longer mean
"the step may leave this out". How: add `?` to a value the step may
skip: `- callback_time: result.callback_time?`. Lists (`x+:`) stay
optional. Nothing fails at validate, so read each `assign:` once.
* Pipecat needs `params.world_part` on SLNG speech. Why: pipecat-slng
0.6.0 made it required, and a Pipecat bot without it failed at
start. How: add `world_part: eu-north` (or your region) under
`params:` on each SLNG `listen` and `speak` binding. `unmute validate`
refuses a Pipecat package without it. LiveKit is unchanged. The SLNG
target drops `world_part`, so one package can target Pipecat and SLNG.
New:
* Tasks and task groups on SLNG managed agents. Why: SLNG managed
agents now run tasks. How: write tasks the same way as for LiveKit
and Pipecat, and add `slng` to the targets. A tool that only a task
uses is attached hidden from the main agent. `unmute validate` names
what SLNG still refuses: a model per task, `finish:` rules,
`history: summary`, a group ending in anything but `return`, and
handoffs.
* Typed values on SLNG. A value a task saves, or one the model records
with `source: conversation`, can be a phone number, email, date,
time, `Literal`, list or model. A value the dispatch fills stays
plain text.
* Logfire tracing on LiveKit and Pipecat: `tracing.provider: logfire`
with `LOGFIRE_TOKEN`. Langfuse and Coval settings are unchanged.
LiveKit no longer installs the langfuse SDK, and its traces drop the
empty wrapper rows.
Generated code:
* Generated Python passes its own ruff and ty rules. Each project
carries them in pyproject.toml.
* Each code target writes a small project instead of one big file:
settings.py, session.py, agents.py, call.py, utils/, and prompts in
prompts/\*.md. Twilio splits app.py the same way. The entry file
keeps its name (bot.py, agent.py, app.py), so deploy commands do not
change. If you edited a generated file by hand, find your edit in
the new layout.
* The saved call state is a real Pydantic model at runtime. A saved
model holds a model, not a dict. Call-start values and carrier
facts now go through the same check as every other save.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.7.0)
Voice agents on Twilio, with SLNG optimization by default.
Highlights:
* Twilio is now a compilation target. Turn your agent spec into a
standalone FastAPI application for inbound ConversationRelay calls.
Twilio handles speech recognition and synthesis; your app manages
conversation history, tools, and streamed model responses.
* Start with `unmute init my-agent --target twilio`. The starter uses
SLNG Context Router with OpenAI upstream to reuse eligible responses
and send other requests to the model. Direct OpenAI and Gemini
bindings are also supported.
* Host the generated app wherever you choose, then connect your number
with `unmute deploy --target twilio`. Deployment checks the hosted
build and signed webhook, saves the previous route, and updates the
number. Use `--dry-run` to check before making changes.
* The generated app includes signature validation, streamed replies,
interruption handling, local tools, end\_call, health checks, and
graceful shutdown. Custom Python logic and post-session TwiML let
you control what happens during and after a conversation.
* A first-call walkthrough covers Twilio account setup, getting a
number, compiling locally, publishing the app, and connecting it.
Hosting examples show container services, a VM, and a laptop tunnel.
* The shipped example was verified on a deployed application with a
real phone call through SLNG, including an opening-hours tool call
and a clean hangup.
Getting started:
unmute init my-agent --target twilio
cd my-agent
unmute validate
unmute compile
Follow the guide to host the app and connect your number:
[https://unmute.ai/telephony/twilio-conversation-relay](https://unmute.ai/telephony/twilio-conversation-relay)
Run `unmute skill install` to refresh the bundled assistant guidance.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.6.1)
Pipecat steps that start on the caller's words, one trace per call, and prompts checked against replayed calls.
Highlights:
* Pipecat: a task step now opens on an instruction. It speaks its
opening line first, then gives the model an instruction that points at
what the caller already said. Before, the request ended on the model's
own sentence. The model then asked again for details it had, sometimes
invented a value, and sometimes returned nothing. That last case left
the caller in silence. Without any instruction, a step acted on a
request before asking for a yes.
* Pipecat tracing: two calls on one worker stay apart. Per-call state
lives in a context variable now. A warm worker no longer files one
call's spans under another call's session.
* LiveKit tracing: one call is one trace again. The event loop monitor
sent an `event_loop_blocked` span with no parent when the loop stalled
for more than 100 ms. That span could split a call into two traces.
It is no longer exported.
* Every Pipecat build answers the Twilio route of the runner. A
browser-only example can now take a simulated phone call too.
* `{{$NAME}}` in a prompt or greeting now fails `unmute validate` on
every target. On `slng` it used to pass validation and then fail at
push, because the backend removed org variables on 2026-09-02. The
error says where a Vault token still works: an MCP server URL. A tool
still names its secret by bare name in `auth:`.
* The salon prompts were fixed where replayed calls showed them wrong.
The agent asks for a number it does not have instead of inventing
one. It reads back a number given in pieces once, whole. It runs
verification before it records a complaint, so it never says it saved
something it did not. It no longer offers a transfer nobody asked for.
For contributors:
* `make sim TEST_SET=` runs one Coval test set against the examples
running on your laptop, on both LiveKit and Pipecat. It exits 1 when a
call did not finish, the agent never spoke, or a metric said NO. See
`utils/coval_sim/README.md`.
* `scripts/text_run_pipecat.py` drives a compiled Pipecat bot through
scripted caller lines. It uses the real model and the local tools, with
no audio. It takes the same flags as `text_run_livekit.py`.
Upgrade notes:
* Recompile. The Pipecat bot template and both tracing templates
changed.
* If a prompt or greeting uses `{{$NAME}}`, move the value into a
package variable (`{{name}}`) or into the MCP server URL. It was already
refused at push on `slng`. Now `validate` says so first.
* Run `unmute skill install` again. The skill's package and deploy
references changed with the Vault token rule.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.6.0)
Task groups that speak on Pipecat, a booking turn that costs one request less, and a docs tree that stopped rotting.
Highlights:
* Task groups work on Pipecat. A step's opening line was emitted as a
Flows `tts_say` pre-action, and a pre-action holds the node until the
frame behind it reaches the worker sink, a frame this worker queues
does not move until the tool call building the flow returns. The
first node of every flow waited on itself: nothing spoken, nothing
asked of the model, the caller left hanging. It is a queued
`TTSSpeakFrame` now, so nothing waits. `opening: listen` was broken
the same way and is fixed by the same change. Two runtime smokes
hold it; both time out on the old template.
* The salon's `book` group is back, and a booking turn spends one model
request fewer. `manage_booking` loses its `when:`, so the group is
the only way in, and `skip_when_confirmed:` decides verification
again. That is the general shape, now written down at
/build/orchestration/task-groups and in the skill: two tasks an agent
chooses between spend a request on the choice, and that request
speaks nothing and does nothing. A group is chosen once, and every
step after the first opens by itself.
* The Vertex bridge emits `HttpOptions` with the enum. `ty` reads a
plain dict as `dict[str, str]` and refuses `"COLLECTION"` where a
`ResourceScope` belongs, which is what turned the salon's static
check red. One `const`, so Pipecat gets it too, and the request on
the wire is the same string it was.
* `docs/` is one file. `GATES.md`, `HARNESS_TEST.md` and
`SELF_VERIFY.md` each restated something the code, the tests or
CLAUDE.md already said, so they rotted against it instead of holding
it. `ARCHITECTURE.md` stays, it is the one file that describes the
system boundary, the four compiler stages and each target's runtime
topology in one place, minus the interactive console. The allow-list
test now refuses any other tracked file under `docs/`, so a second
one stays a deliberate decision.
Upgrade notes:
* Recompile. The Pipecat template changed, and a package built before
this still has a first node that waits on itself.
* Run `unmute skill install` again. The skill now says to reach for a
group before two tasks with a `when:` each, and says why.
* Nothing in `agent.yaml` has to change. If you split a group into
separate tasks to work around the silence, put the group back.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.6)
A skill for the push, curated capabilities from the package, and telephony you can read.
Highlights:
* A third skill, `unmute-deploy`. Pushing is a different job from
building, done at a different time and often by somebody who did not
write the package. It carries the command loop, what each of the two
dry runs checks, how to read the detach list, and what a push
replaces against what it leaves alone. That last list is the fourteen
fields of the compiled body, held to the code both ways.
* `unmute deploy` attaches a curated capability named by a `slng:`
reference. It used to refuse, send the author to the dashboard, and
the next push detached what the dashboard attached. `voiceai agents
push` accepted the same body all along, so the refusal was ours:
three gates, and the organisation-only scope filter alone was enough
to stop a curated record, which is global.
* `current_datetime` and `user_phone_number` join the prebuilt
registry, now four ids, and `inject:` pins the settings each one
takes. A package can pin a timezone the curated tool cannot carry.
`announce:` is legal on a prebuilt on SLNG. The registry and its
settings are written down at /build/tools/prebuilt.
* A tool that ends the conversation waits for its own `announce:` line.
`end_call` hangs up the moment it runs, so a goodbye spoken alongside
it was cut off mid-word. Every other announcement still runs
alongside the tool.
* Seven refusals found by deploying one package: a `{{placeholder}}`
for a `source: conversation` variable (it reached SLNG as a fieldless
422\), an omitted `provider:` under a manifest, a prebuilt whose id is
not its file's name, one name held at two scopes, and a placeholder
in a prompt now names its line. The deploy preview compares every
setting the package pins, so pinning a timezone no longer reads as
deleting it.
* `telephony-setup.sh` is gone. It called bare `lk`, which has no
project flag, so on a machine pointed at another project it created
the trunk and the dispatch rule in the wrong account and printed
success. Compile still writes the two JSON files; the runbook prints
the two commands that send them, each naming its project. The Twilio
and LiveKit pages are rewritten in step order, with a symptom table,
a teardown and a what-to-redo table.
* The salon concierge sounds like a person. Nine passages read like
incident reports written to the model on every turn; every rule
stayed, every incident went to the README. Behind it, the realism
guidance now puts a frequency budget on each technique: at most one
filler in a turn, none in most, and a clean grammatical sentence is
no longer labelled bad.
Upgrade notes:
* The company contract is `manifest.yaml` now, in a package and in the
saved library. A package still holding the old extensionless
`manifest` is refused by name. A library saved before this keeps
loading.
* Run `unmute skill install` again. The bundle writes three skills.
* If you ever ran `telephony-setup.sh`, check which LiveKit project
holds the inbound trunk and the dispatch rule before you dial.
* Recompile to pick up the goodbye before the hangup and the new
refusals. Nothing in `agent.yaml` has to change.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.5)
Plain init, a skill for company rules, and templates in their own repo.
Highlights:
* `unmute init ` writes six files and asks nothing again. A
saved default manifest was routing every new package into guided
setup, so a new agent could not be created without answering for a
contract nobody had asked about. `--from-manifest` is now the one
way a contract reaches a new package.
* A second skill, `unmute-manifest`, writes the company contract. An
assistant cannot run the picker, so it does the part that is words:
ask what the company allows and write the YAML. `unmute manifest
create --file draft.yaml` saves it, validates before it
saves, and writes nothing when it refuses.
* The salon concierge thinks with Gemini 3.1 Flash-Lite on Vertex in
eu, at thinking\_level MINIMAL to keep the first token fast. The old
OpenAI block stays commented in the file, so switching back is one
edit.
* Templates live in slng-ai/unmute-templates. The single copy kept
here is gone, and the README, CONTRIBUTING.md and the skill a
coding agent reads point at that repo and say what a template
carries.
Upgrade notes:
* Replace `unmute init --manifest ` with
`unmute init --from-manifest` and pick from the list. The
`--draft` flag is gone, along with the assistant draft flow it
served. The `unmute` console and `manifest use` keep the default.
* Run `unmute skill install` again to pick up `unmute-manifest`. The
bundle now writes two skills.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.4)
Alternating announce lines, a reworked salon, and steps that don't repeat.
Highlights:
* announce: takes a list. The caller hears one of those lines each
time it fires, never the one that site used last, so a flow
entered twice in a call does not sound like a recording. A single
line still works and needs no change.
* A task speaks its announce as the step is entered, whichever way
the step was reached. On a tool the line sits in the tool body and
fires once per call, so two calls in one turn played it twice.
* A step the caller has not spoken since is refused instead of run
again, on LiveKit and Pipecat. A finished result with no new
caller turn above it is the model re-reading its own work.
* LiveKit sessions retry the model once instead of four times. The
default sleeps 4.1 seconds before it gives up.
* Rework the salon concierge: seven tools instead of eleven, two
plain tasks instead of a task group, and the saved booking now
carries the sentence the agent reads out loud.
* Fix a LiveKit call arriving as two Langfuse traces, and name a
tool call after its tool on both targets.
Upgrade notes:
* Recompile to pick up the refusal and the retry cap. Nothing in
agent.yaml has to change.
* A task group still compiles but speaks nothing on Pipecat. Use
plain tasks there until that is fixed.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.3)
Speech-to-speech agents, better manifests, and clearer deployment guides.
Highlights:
* Add realtime and live architectures on LiveKit and Pipecat.
Run speech-to-speech agents, or pair a realtime model with a
separate speech synthesizer. Existing packages default to cascade.
* Add pharmacy-refills and takeaway-orders examples with local
tools and knowledge lookup.
* Improve the manifest editor and create agents from saved company
rules with unmute init --manifest or --from-manifest.
* Fix LiveKit tool inputs, Pipecat task history, delegated tool
timing in the browser, and the Homebrew postflight warning.
* Explain architecture choices, workflow limits, and deployment
steps for LiveKit Cloud, Pipecat Cloud, and SLNG.
Upgrade notes:
* Set the LiveKit framework version to 1.8.1 and Pipecat to 1.10.0
in targets.yaml.
* Realtime and live currently support single-agent browser calls.
Keep cascade for tasks, saved state, tracing, and phone routes.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.2)
Google inference locations on LiveKit and Pipecat.
Highlights:
* Choose Google Vertex inference locations with params.location.
US, EU, individual regions and explicit global routing now select
the corresponding Google endpoint on both LiveKit and Pipecat.
* Keep GOOGLE\_API\_KEY authentication and provider parameters,
including thinking\_config. Existing EU routing and Gemini
Developer API configurations continue to work.
* Follow Google's endpoint rules without a compiler region allowlist.
Unsupported locations and unavailable models fail at the requested
endpoint, with no fallback to global or another region.
* Verify real US requests through both generated native clients.
Regression checks cover endpoint selection, parameter forwarding,
mixed locations, Developer API behavior and provider errors.
* Update the model guide and coding-agent skill reference with
location examples and routing behavior.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.1)
Reusable company rules, native Gemini, and unified regions.
Highlights:
* Reuse company rules with unmute manifest. Guide new agents through
allowed models, languages, regions, targets and tools. Each package
carries its own manifest for offline validation and compilation.
* Run native Gemini on LiveKit and Pipecat, including Vertex EU access
with an API key. EU requests use the regional endpoint with no global
fallback.
* Use one set of 13 SLNG regions across deployment, speech and the
Context Router. Listening, thinking and speaking now share
params.world\_part.
* Build with clearer guides: a first-task walkthrough, complete field
references, practical credential setup and example troubleshooting.
New checks catch broken links, invalid MDX and missing field docs.
Upgrade notes:
* Replace the Context Router's params.world\_part\_override with
params.world\_part. Choose a current region such as eu-west or
us-east; the old eu, us, india and indonesia values are refused.
* Update SLNG deployment\_region values any, eu-central and ap-south
to a supported region. LiveKit now rejects unknown worker regions
and media region groups used as deployment regions.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.5.0)
Regional speech, live transcripts, and typed contacts.
Highlights:
* Choose where SLNG speech requests go. Set params.world\_part on each
SLNG listen or speak model to select one of 13 regional gateways,
including eu-north, eu-west, us-east and us-west. Unmute generates
the matching endpoint on both LiveKit and Pipecat. Gateway location
and worker deployment region are configured separately.
* See every turn in unmute dev. Streaming transcripts show the caller's
words and the agent's reply as they arrive. Model requests, tool calls
and handoffs get their own rows, with per-request latency and audio
timings to help explain where the wait comes from.
* Collect typed contact details on LiveKit and Pipecat. EmailStr checks
and normalizes email addresses before saving them. NameEmail keeps a
name and address together, with dotted references for either field.
Invalid values leave saved state untouched and tell the model what
to correct.
* Deploy SLNG tools by name. Reference published hosted tools and named
MCP tools without pulling a mirror first. Deployment checks published
contracts, injected arguments and required credentials before pushing.
A dry run previews the versions and attachment changes.
* Record conversation values and send SMS on SLNG. The new
source: conversation lets the model save values during a call.
The send\_sms builtin sends a message to the caller's number on
phone calls, with the sender fixed by the package.
* Two new examples to build from. customer-intake shows typed details,
caller confirmation and saved values passed into a local tool.
hotel-concierge replaces slng-support with hosted lookups, MCP web
search, conversation memory and SMS summaries.
* Run local dev sessions side by side. Busy default ports are selected
automatically, LiveKit stacks are isolated, and shutdown cleans up
the session. Transcript handling, worker startup and Pipecat hangups
also get fixes.
* Updated dependencies and clearer guides. pipecat-slng moves to 0.5.2,
generated Python supports ty 0.0.40, and the docs expand SLNG deployment,
typed state, regional model settings and latency measurement.
Upgrade notes:
* For SLNG listen and speak models, replace params.world\_part\_override
and params.region\_override with params.world\_part and a specific
gateway, such as eu-north. Legacy values na, eu and ap are refused.
Omit world\_part to keep the default endpoint. SLNG think models
keep the Context Router's existing world\_part\_override setting.
* SLNG deployment requires voiceai support for checked, resolved pushes
(verified with 0.1.18). Validation and compilation remain offline.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.4.2)
Simpler SLNG deploys, live transcripts, and a hotel concierge.
Highlights:
* Reference SLNG hosted tools and MCP tools by name. Deployment checks published bindings and credentials, previews attachment changes, and pushes only after checks pass.
* Follow conversations as they happen in unmute dev, with streaming transcripts, tool activity, and per-request latency.
* Meet hotel-concierge: a new SLNG example combining hosted tools, web search, conversation memory, and SMS summaries.
* Improve local worker startup, transcript handling, and graceful Pipecat hangups, with regression coverage for LiveKit task handoffs.
* Update pipecat-slng to 0.5.2 and keep generated Python compatible with ty 0.0.40.
* Expand the SLNG deployment walkthrough and clarify tool setup, testing, and latency measurement.
Upgrade note:
SLNG deployment now requires voiceai support for checked, resolved pushes
(verified with 0.1.18). Validation and compilation remain offline.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.4.1)
Typed state, simpler tasks, and portable hosted tools.
Highlights:
* Typed session state on LiveKit and Pipecat. Declare reusable shapes,
lists, optional values and fixed choices. Task finish arguments come
from the variables they assign, so each type is declared once.
Results are validated together before any value is saved.
* Explicit context sharing. Prompts read saved values with \{\{variable}}
or \{\{variable.field}}. Tasks restore the owner's earlier context and
return a completion status; saved results reach only prompts that
name them. List assignments can append records across several tasks.
* Simpler task definitions. Tasks live inside the agent that owns them,
with their trigger, announcement and assignments in one place.
Other agents can reuse a task by name.
* Hosted SLNG tools. The new `slng:` block references an existing tool,
and `unmute pull` saves its definition and hash into the package.
Validation and compilation check the committed mirror offline.
Supported mirrors also run in generated LiveKit and Pipecat projects.
* Langfuse v4 tracing on both code targets. Each call stays in one trace,
with the full conversation on its root and both sides of each exchange
on a turn span. Tool spans carry their names, arguments and results;
session IDs and trace names reach every observation.
* More reliable conversations. Pipecat settles task tool calls before
returning to the owner, starts replies after empty-history handoffs,
and removes tool calls together with their replies when trimming history.
Salon examples preserve verified identity and booking details across
changes. A new text harness exercises generated LiveKit agents with
real models and local tools.
* Clearer CLI output and docs. Commands print what they did and what
needs fixing; compile details live in compile-report.json.
New guides cover state design, context sharing and verification.
Shared OpenAI bindings can select LiveKit's Responses API; Pipecat
warns and drops the options it cannot use.
Breaking changes and migration:
* Replace agent `model:` and `voice:` selectors with `think:` and `speak:`.
Task model overrides also use `think:`.
* Move top-level task definitions into an agent's `tasks:` list.
Replace `delegates:` with `tasks:` or `task_groups:` attachments,
moving triggers and announcements onto the task or group.
* Replace task `result:` schemas with typed variables and task `assign:`.
Write `assign:` and tool `inject:` as lists of single-key entries.
* Remove `requires:` and handoff `context.variables:`.
Put step ordering in prompts and reference saved values explicitly.
Tools still refuse missing or unconfirmed injected values.
* Omitted task and handoff history now means `messages`.
Use `full` when the receiver needs earlier tool calls and results.
* Move package-level `timezone:` onto each clock pre-fetch entry.
Replace tool `read_only:` with an explicit `writes: false` or
`writes: true` on each tool pre-fetch entry.
* SLNG deployment no longer creates tools from `local:` or `webhook:`.
Create the tool on SLNG, reference it with `slng:`, run `unmute pull`,
and commit the generated mirror. Local and webhook tools remain
supported on LiveKit and Pipecat.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.4.0)
Pre-fetch known facts, and a deploy that checks the account first.
Highlights:
* `prefetch:` resolves known facts before the greeting. A package declares an
ordered list that reads three sources: `clock:` (a date under the package's
`timezone:`), `source:` (a call fact the carrier supplies) and `tool:` (one
read-only lookup, keyed on a value an earlier entry assigned). Each entry gets
a 2s budget and cannot raise: a skip leaves the variable on its default and the
existing guard runs the step that asks. `confirm:` marks a value the caller has
not agreed to yet, so it renders in no prompt but its confirming step's and
satisfies no gate until it is settled. `announce:` on a delegate covers the
entry gap, spoken after the guard so a refused step stays silent.
`unmute dev --source from_number=...` seeds a call fact into the browser loop,
which has no carrier. Salon is rebuilt around it and `get_current_date` is gone.
A package declaring none of the new fields emits byte-identical output.
* `unmute deploy` checks the account before it writes anything. It asks the
organisation what it already has, compares it with what the package needs, and
reports every gap in one pass with the line that asked for it and the one action
that fixes it. Checked: every `builtin:` tool, every MCP server and exposed
server tool, and every vault secret and variable including whether it holds a
value. A code or webhook tool is never reported missing because the push creates
it. Secrets are filled by handing the prompt to `voiceai secret create`, so no
value enters unmute or reaches argv. A refused run leaves build/ and the account
untouched. Adds `unmute resources` and `--call`.
* `mcp:` is core on slng. voiceai 0.1.16 resolves a reference by server name and
copies each tool's schema hash from the platform's own snapshot, so nothing
connects to the server; unmute warned the opposite and told authors an `mcp:`
package could not deploy at all. Both were wrong. Adds `mcp.server` for a
platform name carrying a dash or a space. Proven on a live deploy.
* An agent declares what it can do in `tools:`, `delegates:`, `handoffs:` and
`escalations:`. The block a thing is written in is its kind, so `kind:` and
`controls:` are gone. A strict re-spelling: every package compiles byte for byte
identical on every target.
* Tracing: salon-concierge moves to Langfuse, and `scripts/read_langfuse_trace.py`
reads a `unmute dev` call back out of it, transcript, tool calls and per-span
latency, newest trace by default. Coval self-verification is push-based and is
unaffected.
* Docs: two new pre-fetch pages (the primitive, and how to decide what to
pre-fetch), one page that explains the shape of a package before Orchestration
needs it, and our own measured costs are out of the reader-facing pages.
Breaking:
* `controls:` and `kind:` are removed with no alias. An old package fails as an
unknown key, with file, line and column.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.3.2)
One deploy command, deployment names that stop colliding, and honest Coval traces.
Highlights:
* `unmute deploy [package-dir]` validates, compiles and pushes a package to
SLNG in one command. It shells out to `voiceai agents push --json`, so the
push contract stays in one released binary. A refused push relays every
problem with the fix line and the dashboard page. Credentials come from
SLNG\_API\_KEY, then VOICEAI\_API\_KEY, then a stored `voiceai login` profile,
read from the package's own .env, and the organisation is printed every run.
* Deployments are now named after the package, not the target. Before this,
every package deployed as `slng`, `livekit` or `pipecat`, so a second package
replaced the first one's live agent and two LiveKit packages split one
worker's dispatch. `agent.yaml` now requires `name:`, and a deployment is
that name joined to its target. This also fixes `unmute dev`, which minted a
browser token for a room nothing ever joined.
* Coval traces are per call again. Pipecat Cloud serves many calls from one
warm container, and every call after the first was filed under the first
call's conversation with nothing logged either way. Correlation now resets on
every call, late spans are dropped instead of misfiled, local runs label
themselves `-local`, and one accurate log line replaces the message
that claimed no trace was exported when one was.
* Pipecat support raised to 1.8.0, with pipecat-slng >= 0.5.1. 0.5.0 imported a
private name that 1.8.0 renamed, which broke every emitted bot at import.
* The salon concierge example sounds like a person. Prompts now separate the
speech contract from the personality, leave numbers, money and times in plain
written form so the voice engine normalizes them, and drop the second
acknowledgment that talked over each tool's announce line. Three defects came
off a live call, and the evidence sits next to each rule. The skill teaches
the same shape.
* Docs: a runbook for the second deploy, including the routing records a rename
strands, on every target's own page.
Breaking:
* `agent.yaml` must carry a `name:`. A package without one is refused with the
shape and an example.
* Deployed identities change name, so the first deploy after this upgrade
creates a new agent and leaves the old one live. Delete the old one.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.3.1)
Compile to SLNG, knowledge search, and turn timing you can set.
Highlights:
* New `slng` target: compile a package straight to the SLNG platform.
* Knowledge bases: point a tool at your own documents - txt, md or pdf files.
* Turn timing is yours to set. `endpointing_delay` is the silence floor, `pace`
is the ceiling, and `semantic_endpointing` can switch the turn model off.
* Pipecat phone calls are faster and quieter: `warm_instances` keeps containers
warm, and the agent no longer interrupts its own greeting on speakerphone.
* Faster turns on both targets, from pipecat-slng 0.5.0 and the quicker SLNG route.
* Context Router sends model settings per request, and `prompt_suffix` adds one
line to every prompt in a package.
* Task groups: a step that returns can carry its own prerequisites.
* Console rebuilt on Bubble Tea and Lip Gloss, with one owner for colour.
* Versioned docs, a full carrier setup guide, and a changelog that writes itself.
Breaking:
* The `vapi` and `deepgram` targets are retired. deepgram is still a model
vendor.
* Local telephony testing is gone. Test phone calls on a deployed agent.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.3.0)
Per-site Context Router cache scopes.
Fixes a cache collision where agents sharing one authored agent\_id could be
served each other's cached replies. The router keys its cache on the last
exchange with no system prompt, so in a multi-agent package a specialist's
opening turn could get the concierge's cached line.
Highlights:
* Every prompt site now gets its own cache scope derived from the authored
id: "\:\", "\:task.\", "\:summary". Authoring is
unchanged: still one agent\_id per package.
* LiveKit sets the header per request in an emitted \_slng\_llm\_node, since
constructor-level extra\_headers would replace per-request values.
* Pipecat switches scope on task entry and restores the owner's scope on
every exit path: finish, next step, transfers, terminal node, and error
rollback.
* New gates: one scope per prompt site on every target, no constructor
extra\_headers on LiveKit, scope restore on each Pipecat exit path, and
the name pattern excludes the scope separator.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.2.5)
A phone call that works, a dev loop that shows the numbers, and a faster LiveKit turn.
Highlights:
Local telephony you can test end to end
The (pipecat, sip) inbound route compiled and passed its goldens but could
not answer a phone. Six defects, each found by placing a real call against
the local SIP plane: no telephony.py for the containers uvicorn CMD, no
route telling the bot about a call, telephony-setup.sh emitted without the
JSON files it reads, a two-phase startup that created trunk records against
a server that was not running, a greeting that waited on an RTVI handshake
no phone call fires, and a hangup handler installed on an event the
transport does not have. Cold transfer now reads the participant identity
off the room instead of passing a sid the platform answers 404 for.
salon-concierge ships a pipecat\_sip target on the same trunk as its livekit
target, so the docs are one command again instead of "copy this other
example and edit two files". Three telephony pages merged into one
dev/local-telephony page with redirects, and first-phone-call is now
inbound-calls to pair with outbound-calls. Two test gates got honest: the
live-call banner test no longer reads the real PATH for sox, and the
barge-in gate reads its counters under the lock that writes them, so it
stops failing a call where the barge-in actually worked.
Metrics, logs, and tool timings in the dev UI
Every emitted project now carries dev\_metrics.py and prints one framed JSON
line per turn to stdout. No collector, no exporter, nothing over the
network. internal/devmetrics owns the lines shape and is the only decoder.
The producers stay inert unless UNMUTE\_DEV\_METRICS is set, and the artifact
is byte-identical with the switch on and off. The switch now also reaches
the containers that run an agent, which is why the LiveKit half shipped
wired correctly and never switched on.
The dev page gained a logs view fed by server-sent events, and the listener
now binds before the target starts, so a failed container build is visible
instead of invisible on exactly the runs whose output you need. Output
produced before the browser loads is replayed on connect, and Last-EventID
is honoured so a reconnect resumes rather than repeats.
Each agent turn carries its own timing line: end to end, time to first byte
per service, and how long the reply took to stream. Every tool the turn
called gets its own row above the reply it delayed, which is where it
happened in the timeline. Handoffs are no longer reported as tools: a
LiveKit delegate that does not return until its whole flow finishes was
reporting as a single 51-second tool call. An unreported value renders as a
dash and never as 0.00.
The transcript shows one row per spoken turn instead of one per recognizer
fragment, which was nine rows for one sentence on gradium/stt:default. The
mic control states which of three things is true, M toggles it, and holding
SPACE talks, so barge-in can be tested deliberately. New docs page under
Develop and test explains where the time goes in a voice turn, with field
meanings read from pipecat 1.7.0 and livekit-agents 1.6.10 themselves.
Coval as a first-class tracing integration
tracing: provider: coval compiles to a project that sends Covals canonical
spans on both code targets, with no correlation code written by the package
author. Both of Covals correlation routes are used: a call Coval placed
exports against the simulation ID on the call, and any other call is
registered as a Coval conversation when it ends and exports against the
conversation ID that comes back. That second route is what puts a local
unmute dev run in Covals Trace Search. Spans are held, capped, and flushed
once an ID arrives, so nothing before correlation is lost.
The two targets reach the span tree differently, because the frameworks
differ. Pipecat already nests its spans the way Coval wants, so they are
renamed in flight. LiveKits shape cannot be fixed by renaming, since a
spans parent is fixed when it starts, so the LiveKit module leaves
LiveKits own OpenTelemetry off and builds Covals tree from session
events, using only numbers LiveKit measured itself. Each llm span carries
the prompt that round actually ran on, under the same attribute names on
both targets. A number that was never measured is left off rather than sent
as zero.
LiveKit turn latency, measured across three calls per setting
A session of live latency work on salon-concierge, with every claim taken
from three calls rather than one, because two calls on an identical build
differed by 1.1s of mean silence.
* The transcriber, not any endpointing number, was buying a two-second
penalty per turn: a turn whose transcription\_delay reached 1.0s got the
2.5s max\_delay instead of the 0.58s floor. deepgram/nova:3 finalises in
0.159s mean against gradiums 0.999s, with the same words in every
transcript.
* endpointing\_delay now sets the silence window it always claimed to. On
LiveKit it renders as the prewarmed Silero VADs min\_silence\_duration
instead of an endpointing min\_delay that could never fire before the VAD
reported end of speech, so every authored value under 0.55s used to be
silently inert. Under 250ms is now a compile error, not a first-call
crash. Unset stays byte-identical and no golden moved.
* Warm TTS standby stays, with the claim corrected: it is worth about 40ms
of caller-visible time, not the 610ms first reported, plus a real floor
improvement from 221ms to 58ms on the best segment. The earlier number
was the websocket handshake, which was already off the callers path.
* Control hops came out of the turn. Verification asks for a phone number
only, booking is one task instead of a three-step group, and finish calls
in a scripted booking drop from 7 to 2. Tool state moved from SQLite to
memory, so get\_current\_date went from 245ms to 7.7us. llm ttfb over ten
samples: 1.212s to 0.895s. Authored prompt text is down 61%.
* A delegated task no longer answers its parents in-flight call. LiveKit
injects the still-running delegate call and a placeholder result into the
context the task generates from, so the caller heard an apology for a
failure that had not happened. The strip keys on the SDKs own
**lk\_running\_placeholder** marker. Scripted bookings went from eleven or
twelve agent turns to seven.
* announce: is a new optional scalar on a webhook or local tool file: one
fixed sentence the agent speaks as the tool starts. The wait is not the
tool, which returns in 1 to 14ms here, it is the second LLM round trip
and the TTS after it. Works on both code drivers, including tools listed
on a Pipecat task, which a wrong capability claim had refused.
* docs-site gained a top-level Optimization group and the skill gained
references/latency.md, both carrying the seven settings that looked
promising and were not, with reasons, so nobody repeats that day.
The SLNG Context Router, fully integrated
provider: slng on the think role puts the Context Router in front of your
own reasoning model. A repeated turn is answered from cache; a miss goes to
the upstream you name, so you keep your model, your provider, and the bill
for turns that reach it. Authoring is agent\_id, upstream, and
params.world\_part\_override for the regional base URL, over five upstream
spellings across openai, openai-compat, azure, vertex and bedrock.
On LiveKit it lowers to extra\_headers and extra\_body on openai.LLM; on
Pipecat it merges through OpenAILLMService.Settings.extra. No subclass
ships on either. A router-bound system prompt keeps its \{\{placeholders}}
and the values ride alongside in template\_variables, so a personalised
prompt can still be a cache hit.
salon-concierge is now the one place the binding is demonstrated, and it
runs in slng\_pure\_proxy, which keeps every cache write so the cache still
warms while nothing is replayed. That is load-bearing rather than belt and
braces: the cache key is the (assistant speech, user speech) pair with no
system prompt, so two agents in one package can share an entry, and a live
call had one agent served anothers line.
Also in this release:
* A locked-down step can hand the caller back instead of refusing. Every
task prompt now ends with the compilers own escape, and every generated
finish takes a reserved optional unserved\_request that the owning agent
is told to read.
* A receiving agent gets its handoffs back after the opening turn. The loop
guard used LiveKits IGNORE\_ON\_ENTER, whose filter leaks into everything
the opening reply starts, so one call offered the booking specialist a
single tool for ten turns.
* The pipecat delegate history snapshot is a deep copy, so a history entry
that is not a plain dict survives the snapshot and restore round trip.
* The (pipecat, carrier-websocket, \*) routes stop teaching a Pipecat Cloud
deploy they have no manifest for, and carry the self-hosted section they
were missing.
* Firecrawl MCP is fully out of both salon examples, gradium STT is in the
catalog, and the examples are down to five: four structural packages plus
salon-concierge, which keeps the only shipped telephony route.
* The SLNG marks are replaced with the Unmute brand.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.2.4)
Fix for local dev and docs update.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.2.3)
Hardened orchestration, production-ready examples, and regional deployments.
Highlights:
* Hardens task orchestration across LiveKit and Pipecat, including shared task results, response handling, and session isolation.
* Strengthens telephony and cold transfers with validated phone routes, call-scoped environment variables, idle-resume handling, and safer local cleanup.
* Makes Pipecat startup and observability safer with ordered workers, process-safe Langfuse and MCP tracing, and clearer default logging.
* Adds the full salon concierge example with browser and telephony flows, booking tools, runtime date handling, and release smoke gates.
* Adds a regional speech infrastructure example and deployment guidance for choosing provider regions.
* Fixes scaffold environment keys and dotenv loading.
* Makes the public docs easier to navigate and aligns task, tool, onboarding, and installed-skill guidance.
Included pull requests: #92 to #96 and #98 to #119.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.2.2)
Upgraded runtimes, verified examples, and clearer docs.
Highlights:
* Upgrades and pins LiveKit Agents 1.6.10 and pipecat-ai 1.7.0, while removing deprecated run modes.
* Restructures the public documentation into a clearer user journey and corrects CLI, deployment, telephony, secrets, variables, and schema guidance.
* Makes the CLI easier to use from an agent folder, defaults new packages to LiveKit, and improves phone-route setup guidance.
* Completes a fresh live sweep of every supported example across browser, outbound, inbound, SIP, Twilio, tasks, handoffs, and transfers.
* Fixes task-context restoration, repeated delegation, LiveKit handoff loops, outbound call-start variables, LiveKit SIP dispatch authorization, and Pipecat Twilio cold-transfer shutdown.
* Makes the outbound reminder self-contained and removes the unverified Pipecat Daily transfer example.
Included pull requests: #84, #85, #86, #90, and #91.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.2.1)
Unmute 0.2.0 makes the first agent run reliable, adds coding-agent
support, and opens Windows installation.
**Highlights**
* Update through Homebrew on macOS or install through Scoop on Windows.
* Install the bundled coding-agent skill with `unmute skill install`.
* LiveKit and Pipecat examples now complete real provider-backed
conversations.
* Agent handoffs are more reliable.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.2.0)
`brew install slng-ai/tap/unmute` works.
v0.1.1 published every archive but never pushed the cask. The tap upload was
still switched off, and a skipped step does not fail a run, so the release went
green with nothing to install. This turns it on.
Nothing in the CLI changed. On an archive or a clone of v0.1.1 you are not
missing a fix.
`winget install slng.unmute` is still closed and will say so.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.1.2)
The first release of Unmute, a command line compiler for voice agents.
You write a small package of YAML and Markdown that says who the agent is, which
models it uses, and which tools it can call. Unmute turns that into a real Python
project for the orchestrator you picked. The project it writes is yours: pinned
dependencies, a Dockerfile, a runbook, and no dependency on Unmute at runtime.
Unmute compiles ahead of time and is never in the call path.
**What is in this release**
**Four commands.** `init` scaffolds a package, `validate` checks it against its
targets and names the file and the line when a field is wrong, `compile` writes
one project per target under `build/`, and `dev` compiles, runs the agent locally
and lets you talk to it in the browser. Add `--console` and you talk over the
terminal mic and speaker with no Docker in the way. `validate` prints one status
line per target, and every refusal names the fix.
**Two code targets, one agent.** The same package compiles for Pipecat and for
LiveKit. Nothing in `agent.yaml` mentions either one. Where a runtime cannot run
a model as defined, `targets.yaml` overrides that single entry by name and the
agent itself does not change.
**Models named once.** Every listen, think, speak and turn model is declared once
and referenced by name. Point `brain` at a different model and every agent using
it follows. A provider catalogue turns each binding into code, so the emitted
service carries its own import, its dependency pin and its required environment
variable, and a provider with no slot on a framework fails by name instead of
quietly emitting the wrong class. Pipecat covers anthropic, assemblyai, cartesia,
deepgram, deepseek, elevenlabs, google, gradium, groq, inworld, mistral, openai,
openrouter, qwen, rime, sarvam, slng, soniox and speechmatics. LiveKit covers the
same ground through its native per vendor plugins, plus aws, azure and gemini. An
unknown vendor is still legal as a custom OpenAI compatible endpoint, and
`provider: local` runs the Silero turn detector on your own machine.
**Multi-agent, tasks and task groups.** Any number of agents, with
`agent_transfer` between them and history you control per transfer (full,
messages, last n, summary or reset). Delegates run a single task or a task group
and return where the contract says they return. Task groups can chain, hand over
or end. A task can name its own model, so one stage can be cheaper or stronger
than the rest of the conversation. Both drivers lower all of this to native
primitives: Pipecat Flows on the owning agent, and LiveKit AgentTask sequences
with typed session state.
**Tools, four ways.** A webhook tool with bearer or API key auth. A local Python
handler in `tools/.py`, copied in beside the agent. An MCP server as a tool
source on both code targets, with optional transport and an optional list of the
server tools to offer. And prebuilt tools from the registry, `end_call` in v1,
with an optional closing line. `inject` adds values to a tool call that the model
never sees and cannot overwrite, which is where a user id or a captured slot
rides along.
**Variables and secrets.** Typed input variables, usable in templates, injected
into tool calls and captured back out of the conversation. `secrets` lists every
environment name the author wrote, and the compiler cross checks the secrets your
local handlers actually read. Every `*_env` field is a name and never a value, so
a pasted URL or key fails validation instead of landing in the spec. Seed a
variable for a local session with `unmute dev --var name=value`, the stand in for
a real dispatch payload.
**Telephony.** Real phone calls on the routes each platform ships: LiveKit SIP
with a Twilio trunk, the LiveKit Twilio connector, the Pipecat carrier WebSocket
route, and Pipecat on Daily, either with a Daily number or with your own carrier.
`unmute dev --telephony` runs the resolved route end to end from your laptop:
it brings up the routes Compose graph, opens a managed tunnel, points the Twilio
webhook at it and writes the local LiveKit SIP trunk records, so a first phone
call takes no manual setup. `--to` places an outbound test call, and
`--public-url` or `--no-webhook` hand the carrier callback back to you. Local
runs need no cloud account, only a carrier account and what runs on your machine.
**Human transfer.** Cold and warm handoffs written as `cold:` and `warm:` blocks,
with their parameters in the shape block. Each route uses the platforms own
primitive and the generated code never owns the audio path: SIP REFER on LiveKit
SIP, Dailys room reroute on both Daily number forms, and a carrier markup
replacement on the Pipecat carrier stream. Warm transfer lands on LiveKit SIP,
with your briefing and the transcript going to the person who picks up. Where a
platform has no primitive, `validate` refuses and names the routes that work.
Generated transfer tools log which control fired, and a cold transfer refuses in
words when the session is not a phone call.
**Tracing.** A `tracing` block that lowers to each platforms native
integration, with Langfuse examples on both targets.
**Secrets that match reality.** Compiled output carries a `.env.example` holding
exactly the variables that agent needs, and the generated project checks them at
startup instead of failing mid call.
**A runbook per build.** Each `build//` gets its own `README.md`,
`Dockerfile`, `compose.dev.yaml`, the platform deploy file, and a
`compile-report.json` recording what was resolved, which catalogue entry produced
each service and when that entry was last checked against upstream docs.
**Examples that run.** `examples/` holds packages that each compile for both
targets: `salon-support` needs nothing but a browser and two keys,
`twilio-telephony-hello` places a real phone call, `multi-task`, `task-groups`
and `subagents` cover staged conversations, `mcp-example` wires an MCP server,
and three transfer examples cover the three mechanisms.
**Getting it**
One static binary for darwin, linux and windows, on amd64 and arm64.
```sh theme={null}
brew install slng-ai/tap/unmute # macOS
winget install slng.unmute # Windows
go install github.com/slng-ai/unmute@latest # anywhere with Go 1.24+
```
Archives are on the release page, each holding the binary, the LICENSE and the
README, alongside a signed `checksums.txt` and one SBOM per archive.
`unmute --version` reports its own commit and build date.
MIT licensed.
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.1.1)
One tag push releases unmute
[Full notes and downloads](https://github.com/slng-ai/unmute/releases/tag/v0.1.0)
# Contributing
Source: https://unmute.ai/community/contributing
What a pull request to Unmute needs: the issue, an example that uses your feature, a video, a README and updated docs.
Contributions are welcome. Unmute is MIT licensed and open all the way
through: the compiler, the four targets, the examples, the coding agent skill
and this site. You do not need permission to open a pull request.
The full guide is
[CONTRIBUTING.md](https://github.com/slng-ai/unmute/blob/main/CONTRIBUTING.md)
on GitHub. This page is the short version.
## What a pull request needs
Search the [open issues](https://github.com/slng-ai/unmute/issues) first.
If it is already filed, add what you know to that thread instead of opening
a second. If it is not, open a
[bug report](https://github.com/slng-ai/unmute/issues/new?template=1-bug.yml),
an [improvement](https://github.com/slng-ai/unmute/issues/new?template=2-improvement.yml)
or a [feature request](https://github.com/slng-ai/unmute/issues/new?template=3-feature-request.yml),
and link it from the pull request. A field has to mean something on
Pipecat, on LiveKit and on SLNG, or be refused by name where it
cannot. Settling that on the issue takes a day. Finding it out on a
finished branch costs you the branch.
Ship a package in the same branch, shaped like the ones in
[`examples/`](https://github.com/slng-ai/unmute/tree/main/examples), that
**uses the thing you added**. Your new key appears in its authored files,
the code path runs on a real call, and the package declares every target
the feature claims. A package that compiles but never touches your new
field cannot be reviewed. Extending an existing example counts.
Record your screen with sound while you talk to the agent. Drive it to the
point where the feature fires. Say which target and which route, and what
to listen for. Audio is the part that matters: the pause, the interruption,
the value the agent did not have to ask for. A minute or two is enough.
What the agent does, which targets and transports it declares, what it
needs before it runs, how to run it, and which part of it is your feature.
Every example already carries one. Copy the closest.
A feature nobody can find is a feature nobody uses. Write the page in
`docs-site/` in the same pull request, and update the coding agent skill so
an assistant knows the feature exists.
## Explain the logic, not just the key
A page that lists a field name and its type has not explained anything. Write
what somebody needs in order to predict the behaviour:
| Say | Why it matters |
| - | - |
| What it does, in one sentence | A reader has to be able to repeat it back |
| When to reach for it, and when not to | Name the problem it solves |
| What it compiles to on each target | Say plainly where the targets differ, and when one refuses it |
| What happens if you leave it out | The default, and the reason for that default |
| What happens when it goes wrong | The timeout, the skip, the refusal, and what the caller hears meanwhile |
| A snippet a reader can paste | Take it from the example you added, so the page and the package cannot drift |
A change to emitted behaviour touches four surfaces in the same commit: the
generated runbook template, the example's own README, the page here that
teaches it, and the coding agent skill. A fact that is only true in generated
output is a fact no reader ever sees.
## Where the package goes
| Put it here | When |
| - | - |
| [`examples/`](https://github.com/slng-ai/unmute/tree/main/examples) | The package teaches something a user should read. It joins the public set, so it carries every example gate. |
| `internal/voice-agents-tests/` | The package exists to be deployed and called against real providers, not read as a tutorial. |
| `internal/testdata/` | The package is the smallest thing that makes one unit test possible. |
Adding a directory under `examples/` fails the suite until its name is written
into the hardcoded list in `internal/generate/examples_test.go`. That is the
moment somebody decides the public set grew.
## Run the checks before you push
```sh theme={null}
make fmt # gofmt and go vet
make test # go test -race ./... , no Python, no network, no accounts
make lint # golangci-lint
ruff check . # checked-in Python, including an example's tool handlers
```
`make test` is the gate. `make smoke` proves the emitted Python actually runs,
needs Python installed, and is opt-in. Run it yourself if you changed what
gets emitted.
## What happens next
A maintainer reads the issue, runs your example, watches the video, then reads
the diff. Expect questions about the call rather than about the code.
Say hello on [Discord](https://discord.gg/kxZactmWj) before you start something
large. It is the fastest way to find out whether somebody is already on it.
# Community
Source: https://unmute.ai/community/overview
Where to ask a question, where to file an issue, and how to contribute to Unmute.
Unmute is open source and MIT licensed. Anyone can read it, run it, change it,
and send the change back. Contributions are welcome, and the
[contributing guide](/community/contributing) says exactly what a good one
looks like.
Ask a question, show what you built, and talk to the people who maintain
Unmute.
Read the source, file an issue, and open a pull request.
## Where to take what
| What you have | Where it goes |
| - | - |
| A question about authoring a package, or a call that did not go the way you expected | [Discord](https://discord.gg/kxZactmWj) |
| Something broken: a wrong refusal, a bad compile, an agent that misbehaves | [Bug report](https://github.com/slng-ai/unmute/issues/new?template=1-bug.yml) |
| Something that works, but not well enough: latency, cost, a rough error message | [Improvement](https://github.com/slng-ai/unmute/issues/new?template=2-improvement.yml) |
| Something that does not exist yet: a target, a provider, a transport, a tool kind | [Feature request](https://github.com/slng-ai/unmute/issues/new?template=3-feature-request.yml) |
| Code you want merged | [Contributing](/community/contributing) |
Search the [open issues](https://github.com/slng-ai/unmute/issues) before you
file a new one. Adding what you know to an issue that already exists moves it
faster than a second copy of it.
## What is worth sharing
A voice agent is hard to judge from a diff. What it sounds like on a real call
is the part that matters, and that part travels badly in text. So the things
most worth posting are the ones a reader can hear or run:
* A package you built, and a recording of it answering a call.
* A route, a provider or a carrier you got working.
* A prompt that fixed a behaviour you could not fix with a field.
* A number: how long your agent waits before it answers, and on which target.
## Contribute
The issue, an example that uses your feature, a video, a README and the
docs page. What a change needs before it can be merged.
What shipped in each release, newest first.
# The call's life
Source: https://unmute.ai/core/build/call-lifecycle
What happens around a call: start values, the greeting, checks, tools on events, a failure and the end.
The library runs what happens around a call. It saves the values the call starts with, greets the caller, runs tools on events, handles a failure and closes the call. It works the same on LiveKit and Pipecat.
In the salon tutorial, [Quiet callers and long calls](/core/tutorial/quiet-callers) builds this step by step.
## Open a call
Build one `CallHooks` per call. Give it to the agent, then open the call with a greeting.
```python LiveKit theme={null}
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.livekit import UnmuteAgent, open_call
async def entrypoint(ctx: JobContext) -> None:
state = CallState(State)
call = CallHooks(state, hooks=hooks, prefetch=prefetch)
session = AgentSession(...) # your STT, LLM, TTS and VAD
agent = UnmuteAgent(AgentSpec(PROMPT), state=state, call=call)
await session.start(agent=agent, room=ctx.room)
await open_call(session, Greeting(text="Hi, thanks for calling."), call)
```
```python Pipecat theme={null}
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.pipecat import GreetingHold, fill_prompt, open_call
state = CallState(State)
call = CallHooks(state, hooks=hooks, prefetch=prefetch)
hold = GreetingHold() # also give it to the user aggregator: user_mute_strategies=[hold]
await fill_prompt(llm, worker, PROMPT, state)
@transport.event_handler("on_client_connected")
async def on_connected(transport, client):
greeting = Greeting(text="Hi, thanks for calling.")
await open_call(worker, greeting, call, context=context, llm=llm, hold=hold, transport=transport)
await runner.run()
end = await call.end("ended")
```
1. `open_call` holds the caller's audio, so the greeting is not talked over.
2. It runs your checks and the [prefetch](/core/build/prefetch), then greets.
3. On LiveKit the session's close ends the call. On Pipecat, call `await call.end(...)` after `runner.run()`.
On a plain agent, with no `UnmuteAgent` or `UnmuteFlows`, each piece still works on its own. See [Add one piece to your agent](/core/frameworks/standalone).
## Start values
Name the values a dispatch must send, then save them before the session starts.
```python theme={null}
from unmute_core.call import CallStartError, save_call_start
state = CallState(State, call_start={"customer_id": "required", "plan": "optional"})
try:
saved = save_call_start(state, dispatched)
except CallStartError as error:
...
```
1. `dispatched` is the dispatch's `call_start` object. On LiveKit it is `json.loads(ctx.job.metadata or "{}").get("call_start")`. On Pipecat it is `runner_args.body.get("call_start")`.
2. A missing required value, or one of the wrong type, raises `CallStartError`. Nothing is saved.
3. For a local run, set `UNMUTE_CALL_START` to a JSON object. The dispatch's values win over it.
## Greet the caller
A `Greeting` says how the call opens.
```python theme={null}
from unmute_core.greeting import Greeting
Greeting(text="Hello {{customer.name}}, how can I help?") # a fixed line
Greeting() # the model words a greeting
Greeting(speaks_first="user") # the agent waits for the caller
```
1. A fixed line may name State values that prefetch or `call_start` fills before the greeting.
2. If a named value is still empty when the call opens, the model words the greeting instead.
3. `Greeting(interruptible=False)` keeps the caller from cutting the greeting off.
## Check services before the greeting
Add a `before_call` hook for each service the call needs.
```python theme={null}
hooks.before_call(check_crm)
hooks.before_call(check_calendar)
call = CallHooks(state, hooks=hooks, ready_timeout_s=10)
```
1. The checks run in order, before the prefetch. They share `ready_timeout_s`.
2. A check that raises or runs out of time plays the failure line and hangs up.
## Tools on events
An `EventTool` runs a tool without the model. This one sends the call to a CRM when it ends.
```python theme={null}
from unmute_core.call import EventTool
from unmute_core.hooks import Hooks
from unmute_core.tools import Transcript, webhook_tool
log_call = webhook_tool(
"log_call",
"Send the call to the CRM.",
"https://crm.example.com/calls",
input=CallLog,
output=Done,
locked={"customer_id": "{{customer_id}}", "transcript": Transcript(max_messages=50)},
)
hooks = Hooks(EventTool(log_call, on=["call_end"]))
```
1. The events are `first_user_message`, `call_end`, `tool_succeeded:` and `tool_failed:`.
2. Every required argument must be locked. The model never fills one.
3. `assign={"booking_ref": "ref"}` saves a key of the result into the State. `note=True` shows the result to the model.
## Handle a failure
When the model or the speech to text fails for good, the call says a short line and hangs up.
```python theme={null}
@hooks.wrap_failure
async def page_then_hang_up(component: str, error: BaseException, handler) -> None:
await pager.notify(component, error)
await handler()
call = CallHooks(state, hooks=hooks, failure_line="Sorry, we have a problem. Goodbye.")
```
1. `handler()` says `failure_line` and hangs up. A hook that never calls it keeps the call going.
2. A voice failure alone only logs a warning. The call stays open.
3. On Pipecat, keep the worker's `processor_unusable_policy` at `CONTINUE`, so the line can play.
## Act when the call ends
Watch `call.ended` to save what happened.
```python theme={null}
@hooks.on("call.ended")
async def save_summary(event: str, ended: CallEnd) -> None:
await crm.save(ended.reason, ended.values, ended.transcript)
call = CallHooks(state, hooks=hooks, end_timeout_s=5)
```
1. The end runs once. It settles held saves and runs the `call_end` tools first.
2. Then it tells the `call.ended` observers and waits for each.
3. `CallEnd` holds `reason`, `values`, `confirmed`, `transcript` and `duration_s`.
## Why the call ended
`CallEnd.reason` and `{{call.end_reason}}` hold one word. It is the same on LiveKit and Pipecat.
| Cause | Reason |
| - | - |
| The caller hung up | `caller_hung_up` |
| An end tool, a tool with `ends_conversation`, a voicemail tool or a group with `then: end` | `agent_ended` |
| A cold or warm transfer that went through | `transferred` |
| `max_duration` ran out | `max_duration` |
| `idle_nudges` hung up | `idle` |
| A part failed for good | `error` |
| Anything else | `ended` |
When your own code ends the call, say why first. The first reason wins.
```python theme={null}
call.caller_left() # your own transport code
call.end_requested("agent_ended") # your own code, before it ends the call
```
Pass `call=` to `max_duration`, `idle_nudges`, `end_call_tool` and the other helpers. Without it, the end reads `ended`.
## Where to go next
Every argument, the order of a call, and each rule in detail.
The work at call start, before and beside the greeting.
Your code around prompts, model requests and tools.
How `agent.yaml` declares the greeting and idle nudges.
# Handoffs in code
Source: https://unmute.ai/core/build/handoffs
Give the call to another main agent, with a line said first and a choice of what the next agent hears.
A handoff gives the call to another main agent. You choose a line said first, and what the next agent hears of the call so far. Each agent is its own [`AgentSpec`](/core/reference/agent-spec), with its own prompt, tools, tasks, model and voice, and all of them share one `CallState`.
In the salon tutorial, [Hand off complaints](/core/tutorial/hand-off-complaints) builds this step by step.
## Hand the call to another agent
Give the model a handoff tool. Its handler calls `hand_off`.
```python LiveKit theme={null}
from livekit.agents import function_tool
from unmute_core.agent import AgentSpec
from unmute_core.handoff import HandoffContext
from unmute_core.livekit import UnmuteAgent
concierge = AgentSpec(
"You book appointments.", name="concierge", tasks=concierge_plan, handoffs=("to_complaints",)
)
specialist = AgentSpec("You take complaints down.", name="complaints", tasks=specialist_plan)
class Concierge(UnmuteAgent):
@function_tool
async def to_complaints(self) -> UnmuteAgent | str:
"""The caller has a complaint."""
return await self.hand_off(
UnmuteAgent(specialist, state=self.state),
announce="Putting you through to our complaints desk.",
context=HandoffContext(history="last_n", max_messages=6),
)
agent = Concierge(concierge, state=state, telemetry=telemetry)
```
```python Pipecat theme={null}
from pipecat.adapters.schemas.function_schema import FunctionSchema
from pipecat.services.llm_service import FunctionCallParams
from unmute_core.agent import AgentSpec
from unmute_core.handoff import HandoffContext
from unmute_core.pipecat import UnmuteFlows
concierge = AgentSpec(
"You book appointments.", name="concierge", tasks=concierge_plan, handoffs=("to_complaints",)
)
specialist = AgentSpec("You take complaints down.", name="complaints", tasks=specialist_plan)
async def to_complaints(params: FunctionCallParams) -> None:
await flows.hand_off(
params,
specialist,
announce="Putting you through to our complaints desk.",
context=HandoffContext(history="last_n", max_messages=6),
)
handoff = FunctionSchema("to_complaints", "The caller has a complaint.", {}, [], handler=to_complaints)
flows = UnmuteFlows(
concierge, llm=llm, context=context, aggregators=aggregators,
state=state, telemetry=telemetry, native_tools=[handoff],
)
```
1. The `announce` line plays first, and the handoff waits for it. The caller cannot cut it off.
2. On LiveKit, build the next agent on `self.state` and without `telemetry`. On Pipecat, pass its spec, and `UnmuteFlows` swaps the prompt, tools, tasks and model.
3. The next agent replies first. Name each agent's handoff tools in its spec's `handoffs`, so that first reply cannot hand the call straight back.
## What the next agent hears
Pass a `HandoffContext` as `context`. With none, the next agent hears what was said, without tool calls.
```python theme={null}
HandoffContext(history="last_n", max_messages=6)
```
| `history` | What the next agent hears |
| - | - |
| `messages` (default) | What the caller and the agent said. No tool calls, no prompts. |
| `full` | Everything, with tool calls and their results. No prompts. |
| `last_n` | The newest `max_messages` items. A call and its result stay together. |
| `summary` | One message: "Summary of the conversation so far: ..." |
| `reset` | Nothing. The next agent answers on its prompt alone. |
1. Calls to tools the next agent does not have are dropped, with their results.
2. The `announce` line is the last thing the next agent hears, except with `summary` and `reset`.
3. On a realtime model, only `full` works. See [Realtime models](/core/models/realtime).
## Summarize the call for the next agent
```python theme={null}
HandoffContext(history="summary", summarizer=my_model_call)
```
1. The summary is asked for while the `announce` line plays, so it does not hold up the handoff.
2. `summarizer` is any `ModelCall`. Without one, the spec's `summarizer` answers, else the model of the agent that hands off.
3. A summary that fails, comes back empty, or takes longer than 8 seconds is dropped. The next agent then hears `messages`.
## Give the next agent its own model and voice
Give the spec a `model`, and pass the agent its own voice.
```python LiveKit theme={null}
from livekit.agents import function_tool
from livekit.plugins import openai, slng
from unmute_core.agent import AgentSpec
from unmute_core.livekit import LiveKitModel, UnmuteAgent
billing_model = LiveKitModel(openai.LLM(model="gpt-5.6-terra"))
billing = AgentSpec(
"You answer billing questions.",
name="billing",
tasks=billing_plan,
model=billing_model,
handoffs=("to_front_desk",),
)
class FrontDesk(UnmuteAgent):
@function_tool
async def to_billing(self) -> UnmuteAgent | str:
"""The caller has a billing question."""
voice = slng.TTS(
api_key=SLNG_KEY, slng_base_url=SLNG_HOST, model="slng/fish/tts:s2.1-pro", voice=BILLING_VOICE
)
return await self.hand_off(Billing(billing, state=self.state, tts=voice))
```
```python Pipecat theme={null}
from pipecat_slng import SlngTTSService
from unmute_core.agent import AgentSpec
from unmute_core.model import OpenAIModelCall
from unmute_core.pipecat import ModelCallLLMService, UnmuteFlows, VoiceSwitcher
billing_model = OpenAIModelCall("gpt-5.6-terra")
billing = AgentSpec(
"You answer billing questions.",
name="billing",
tasks=billing_plan,
model=billing_model,
handoffs=("to_front_desk",),
)
front_voice = SlngTTSService(
api_key=SLNG_KEY, world_part=WORLD_PART, model="slng/fish/tts:s2.1-pro", voice=FRONT_VOICE
)
billing_voice = SlngTTSService(
api_key=SLNG_KEY, world_part=WORLD_PART, model="slng/fish/tts:s2.1-pro", voice=BILLING_VOICE
)
voices = VoiceSwitcher([front_voice, billing_voice])
llm = ModelCallLLMService(front_model, settings=...)
flows = UnmuteFlows(front_desk, llm=llm, context=context, aggregators=aggregators, tts=voices)
pipeline = Pipeline(
[transport.input(), stt, aggregators.user(), llm, voices, transport.output(), aggregators.assistant()]
)
async def to_billing(params: FunctionCallParams) -> None:
await flows.hand_off(params, billing, tts=billing_voice, native_tools=[to_front_desk_tool])
```
`FRONT_VOICE` and `BILLING_VOICE` are two Fish Audio voice ids on SLNG. `SLNG_KEY`, `SLNG_HOST` and `WORLD_PART` come from your environment, as in the [quickstart](/core/start/quickstart).
1. The `announce` line plays in the old voice. Then the new model and voice take over.
2. An agent whose spec has no `model` runs on the call's first model. The same holds for the voice.
3. On Pipecat, a spec with a `model` needs a `ModelCallLLMService`, and the voices go through a `VoiceSwitcher`.
## Open the next agent on a tool
The next agent's first reply comes from the model. When it must start with something code
already knows, run a tool in code instead. Pass `opens_with`:
```python theme={null}
from unmute_core.tasks import OpeningTool
await self.hand_off(tutor, opens_with=OpeningTool(tool="continue_lesson")) # LiveKit
await flows.hand_off(params, tutor_spec, opens_with=OpeningTool(tool="continue_lesson")) # Pipecat
```
1. The tool runs through the next agent's `ToolRegistry`, so its `assign` rows save values.
2. Its line is the first of the opening's `say` lines that fills, else the registry's `ToolReply` for the result.
3. When a line fills, it is the agent's first reply. The tool call and its result join the history, and no model request is made.
4. When no line fills, or the tool is refused or fails, the model replies first as before.
5. `arguments` maps tool parameters to State values, as on a [task step's opening](/core/reference/tasks#openingtool). The tool does not run while one of them is unset.
6. A realtime model refuses `opens_with`: it keeps the history on its server.
## A handoff from a task step
A task can offer the agent's handoff tools to its steps:
```json theme={null}
{"name": "find_order", "tools": ["lookup_order"], "handoffs": ["to_notes"], "...": "..."}
```
1. The handoff tool must be one of the agent's own tools: a `native_tools` entry, or a LiveKit `@function_tool` method.
2. When the step's model calls it, the step ends with `task.handed_off`, and nothing is saved.
3. The next agent hears the step's own chat, shaped by the handoff's `context`.
A task group can hand the call off too, once it finishes. See [Group transfer rules](/core/reference/handoffs#group-transfer-rules).
## Hand off from a plain agent
You can hand off without `UnmuteAgent` or tasks.
```python LiveKit theme={null}
from livekit.agents import Agent, function_tool
from unmute_core.handoff import HandoffContext
from unmute_core.livekit import shape_chat_ctx
class Front(Agent):
@function_tool
async def to_billing(self) -> Agent:
"""Hand the call to billing."""
context = HandoffContext(history="last_n", max_messages=6)
return Billing(chat_ctx=shape_chat_ctx(self.chat_ctx, context))
```
```python Pipecat theme={null}
flows = UnmuteFlows(AgentSpec(PROMPT), llm=llm, context=context, aggregators=aggregators)
flows.install()
# inside the handoff tool's handler
await flows.hand_off(params, AgentSpec(NEXT_PROMPT, name="next"), announce="One moment.")
```
1. On LiveKit, `shape_chat_ctx` gives the next agent the history the library keeps. It does not say a line or write a summary.
2. On Pipecat, a spec with only a prompt is enough for a full handoff.
## Where to go next
Every argument, history rule, helper and error.
Steps and groups that offer or run a handoff.
What `UnmuteAgent` does on a LiveKit session.
What `UnmuteFlows` does in a Pipecat pipeline.
How `agent.yaml` declares a handoff.
# Hooks
Source: https://unmute.ai/core/build/hooks
Run your code before, around and after each prompt, model request and tool call, and on call events.
Hooks run your code before, around and after each prompt, model request and tool call, and on the call's events. You write them once, and they run the same way on LiveKit and Pipecat.
## Add hooks to a call
Build one `Hooks` at import. Build one `CallHooks` per call, and pass it to the agent as `call=`.
```python LiveKit theme={null}
from unmute_core.call import CallHooks
from unmute_core.hooks import Hooks
from unmute_core.livekit import UnmuteAgent
hooks = Hooks()
async def entrypoint(ctx: JobContext) -> None:
call = CallHooks(state, hooks=hooks)
agent = UnmuteAgent(spec, call=call)
```
```python Pipecat theme={null}
from unmute_core.call import CallHooks
from unmute_core.hooks import Hooks
from unmute_core.pipecat import UnmuteFlows
hooks = Hooks()
async def bot(runner_args: RunnerArguments) -> None:
call = CallHooks(state, hooks=hooks)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, call=call)
```
1. Many calls may share one `Hooks`. It holds only your functions.
2. A `CallHooks` binds to one call. Build a new one for each call.
3. A hook may be sync or async, except a `prompt` hook, which must be a plain function, and a `wrap_*` hook, which must be async.
## Add a line after every prompt
```python theme={null}
from unmute_core.hooks import PromptSuffix
hooks.add(PromptSuffix("/no_think"))
hooks.add(PromptSuffix("/no_think", model="qwen/qwen3-32b"))
```
1. The suffix goes after the agent's prompt, every task step's, the finish checks' and the summaries', after a blank line.
2. With `model=`, only prompts that model reads get it.
3. It refuses blank text, more than 512 characters, and a `{{...}}` placeholder.
## Change a model request
```python theme={null}
from dataclasses import replace
from unmute_core.model import ModelRequest
@hooks.before_model
def calm(request: ModelRequest) -> ModelRequest | None:
if "nemotron" not in request.model:
return None
return replace(request, params=request.params | {"temperature": 0})
```
1. `request.model` names the model that answers, like `gpt-5.6-luna`. Return None to keep the request as it is.
2. `request.params` are extra body fields for this request only.
3. `wrap_model` hooks run around the request, and `after_model` hooks hear the answer.
## Refuse or change a tool call
```python theme={null}
from unmute_core.hooks import Refuse, ToolRun
@hooks.before_tool
def no_refunds_at_night(run: ToolRun) -> Refuse | None:
if run.name == "refund" and closed_now():
return Refuse("Refunds open at 9.")
return None
```
1. `Refuse(message)` stops the call. The tool never runs, and the model reads the message.
2. Return a changed `ToolRun` to change the arguments. They are checked against the schema again.
3. `wrap_tool` hooks run around the tool, as `async (run, handler)`. Call `await handler(run)` to run it.
## Run code when a tool ends
```python theme={null}
@hooks.after_tool
def audit_refund(run: ToolRun, result: object) -> None:
if run.name == "refund":
audit.write(run.arguments, result)
```
1. Return None to keep the result. Return something else to replace what the model reads.
2. An `after_tool` hook that raises is logged, and the model reads the tool's own result.
## Watch call events
```python theme={null}
from unmute_core.call import CallEnd
@hooks.on("tool.*")
def log_tool(event: str, data: dict) -> None:
logger.info("%s %s", event, data["name"])
@hooks.on("call.ended")
async def report(event: str, end: CallEnd) -> None:
await crm.save(end.reason, end.values)
```
1. A pattern may hold `*`, like `task.*`. A pattern that matches no event raises `ValueError`.
2. Observers only watch. One that raises is only logged.
3. The end of the call waits for `call.ended` observers, up to `end_timeout_s`.
## Where the model hooks run
The `prompt`, `before_model`, `wrap_model` and `after_model` hooks run only where the library sends the model request. The tool hooks and the event hooks do not depend on this.
| Framework | The hooks run | They do not run |
| - | - | - |
| LiveKit | In `UnmuteAgent`. In a plain `Agent` whose `llm_node` calls `filled_llm` or `traced_llm`. With a `ModelCallLLM`. | In a plain `Agent` that keeps LiveKit's default `llm_node` with a plugin. |
| Pipecat | In `UnmuteFlows(call=call)`. In a plain pipeline with `llm=` passed to `attach_call` or `open_call`. | In a plain pipeline with no `llm=` and no `UnmuteFlows`. |
When a call has model hooks and no request goes through the library, the adapter logs one warning that says what to change. `wrap_model` reaches only a request that a `ModelCall` answers.
## Run tool hooks on a plain agent
`UnmuteAgent` and `UnmuteFlows` pass the call's hooks to every tool. On a plain agent, pass them yourself.
```python LiveKit theme={null}
from unmute_core.livekit import function_tools
agent = Agent(instructions=PROMPT, tools=function_tools(registry, state, hooks=call))
```
```python Pipecat theme={null}
from unmute_core.pipecat import tools_schema
tools = tools_schema(registry, state, hooks=call)
```
1. `hooks=call` runs the tool hooks, and fires the `tool.*` events for your tools.
2. Framework tools skip the tool hooks: end call, handoffs and `native_tools`. So do prefetch lookups.
## Where to go next
Every point, event, rule, argument and error.
`CallHooks`, tools on events, the failure line and the end.
The tools your hooks run around.
The `ModelCall` that `wrap_model` reaches.
Where Unmute declares `prompt_suffix`.
# Knowledge
Source: https://unmute.ai/core/build/knowledge
Search a folder of documents from a tool, so the agent answers from your own text.
`KnowledgeBase` searches a folder of documents. The agent calls it as a tool and
answers from the passages it gets back. It works the same on LiveKit and Pipecat.
On this page:
* [What it gives you](#what-it-gives-you) - what goes wrong without it
* [Quickstart](#quickstart) - a base, a tool and `start()`
* [How it works](#how-it-works) - bake, start, look up
* [What a lookup returns](#what-a-lookup-returns) - three shapes
* [Every argument KnowledgeBase takes](#every-argument-knowledgebase-takes) - modes and limits
* [Use it in an agent](#use-it-in-an-agent) - the tool description and both frameworks
* [Advanced](#advanced) - keyword mode and your own code
* [Troubleshooting](#troubleshooting) - the errors you may see
It needs the `[knowledge]` extra. See [Install](/core/start/installation) for the
install line and the one setting Linux needs.
## What it gives you
| On a call without it | What the library does |
| - | - |
| Every process embeds the documents again at startup. | `bake()` builds the index once. Startup only loads it. [How it works](#how-it-works) |
| The index was built with other settings and returns the wrong passages. | A mismatch fails at load. |
| Meaning search misses exact names and codes. | Hybrid search mixes meaning and keywords. |
| Long passages are slow to say and to send. | Passages are about 65 words, 3 per lookup. [Every argument KnowledgeBase takes](#every-argument-knowledgebase-takes) |
| The model offers the closest passage as if it answered. | The tool tells the model results may not answer the question. [Use it in an agent](#use-it-in-an-agent) |
## Quickstart
```python agent.py theme={null}
from pathlib import Path
from llama_index.embeddings.openai import OpenAIEmbedding
from unmute_core.knowledge import KnowledgeBase
from unmute_core.tools import ToolRegistry
REFUNDS = KnowledgeBase(
"refunds",
Path("knowledge/refunds"),
index_dir=Path("knowledge/.index/refunds"),
embed=lambda: OpenAIEmbedding(model="text-embedding-3-small"),
credential_env="OPENAI_API_KEY",
)
registry = ToolRegistry(
[
REFUNDS.tool(
"look_up_refund_policy",
"Look up the refund and complaints policy. Use it before you state any refund "
"or timescale.",
)
]
)
REFUNDS.start() # once per process, before the first call
```
The embedder package, here `llama-index-embeddings-openai`, is yours to install.
Keyword mode needs none.
## How it works
```mermaid theme={null}
flowchart LR
B[bake at image build] --> I[(Index folder)]
I --> S[start at process start]
S --> L[look_up in a call]
L --> R[Passages]
```
1. The folder holds `.txt`, `.md` and `.pdf` files.
2. `bake()` reads them, splits them into passages, and writes the index to `index_dir`. Run it when you build the image.
3. `start()` loads the index when the process starts. It never runs during a call.
4. `await look_up(query)` searches the index and returns at most `top_k` passages.
5. The content is fixed at start. A lookup never reads a file and never builds the index again.
Without a baked index, `start()` reads and embeds the documents in memory. That
works. But every worker process pays the full cost, and the log warns about it.
So call `bake()` at build time:
```bash theme={null}
python -c "from agent import REFUNDS; REFUNDS.bake()"
```
## What a lookup returns
`look_up` never raises. It returns one of three shapes, so the model can tell
them apart.
| Result | Meaning |
| - | - |
| `{"results": [{"text": ..., "source": ..., "score": ...}]}` | It found passages |
| `{"results": []}` | It found nothing |
| `{"error": "lookup unavailable"}` | It could not search. It was called before `start()`, or the search failed. |
1. `source` is the file name, never the path. The agent may say it aloud.
2. `score` is a similarity from the meaning search. Keyword hits have no score.
3. The query and the passages never go to the log.
## Every argument KnowledgeBase takes
### KnowledgeBase
The base name. It appears in log lines and errors.
The folder that holds the documents.
Where `bake()` writes the index and `start()` looks for it. `None` never bakes.
`meaning` uses embeddings. `keyword` uses BM25. `hybrid` runs both and interleaves the hits.
Passage size in tokens. 90 tokens is about 65 words. From 1 to 2048.
Tokens that neighbouring passages share. From 0 to `chunk_size`.
How many passages a lookup returns. From 1 to 20.
Drop meaning hits below this score. From 0 to 1. Keyword hits are always kept.
A function that builds the llama-index embedder. Needed for `meaning` and `hybrid`.
The environment variable the embedder needs.
1. `embed` is a function, not an embedder. It runs at `start()` or `bake()`.
2. A `keyword` base takes no `embed` and needs `min_score` at 0. A base that embeds needs `embed`. A wrong mix, a bad `mode`, `chunk_size`, `top_k` or `min_score`, or a `chunk_overlap` above `chunk_size` raises a Pydantic `ValidationError` when you build it. It is a `ValueError`. It names the field and the allowed values.
3. `credential_env` is checked at `start()` and `bake()`. A missing key stops the process at once and names the variable.
4. A baked index remembers the settings it was built with. `start()` refuses an index built with other settings. Bake it again.
5. `start()` and `bake()` raise `KnowledgeError` for a missing folder, a folder with no text, or a PDF with no text layer.
Let the process stop on a `KnowledgeError`. An agent that knows nothing should
not take calls.
## Use it in an agent
`KnowledgeBase.tool(name, description)` builds the tool for you. The model reads its description, so say when to use it. The library adds a note on weak results, so you need not write one.
1. `description` is up to you. It says when to look up.
2. The tool ends the description with: "The results may not answer the question. They are ordered best first, and each carries a relevance score where a higher number means a closer match. If nothing returned actually answers what was asked, say you do not have that information rather than offering the closest result."
3. The tool has one parameter, `query`. The model reads it as "What to look up. Use the caller's own words."
4. `name` defaults to `look_up`. With no `description`, the description is the note alone.
5. The tool is a `ToolSpec`. Pass it to `ToolRegistry`.
For a task step, list the tool in the step's `tools`. See
[Tasks](/core/build/tasks) and [Tools](/core/build/tools).
```python LiveKit theme={null}
# An agent without tasks takes the registry. With tasks, the TaskPlan holds it.
spec = AgentSpec(PROMPT, tools=registry)
agent = UnmuteAgent(spec, state=state)
```
```python Pipecat theme={null}
# An agent without tasks takes the registry. With tasks, the TaskPlan holds it.
spec = AgentSpec(PROMPT, tools=registry)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
```
## Advanced
### Keyword mode
Keyword mode needs no embedder and no API key.
```python theme={null}
from pathlib import Path
from unmute_core.knowledge import KnowledgeBase
from unmute_core.tools import ToolRegistry
kb = KnowledgeBase("faq", Path("knowledge/faq"), mode="keyword")
kb.start()
registry = ToolRegistry([kb.tool("look_up_faq", "Search the FAQ.")])
```
### Use a lookup in your own code
You can call `await REFUNDS.look_up(question)` in your own code. Put the
passages in a prompt you write yourself.
## Troubleshooting
### `PermissionError: Security Violation [pathsec.open]` on the first lookup
llama-index reads NLTK data files. NLTK refuses a file with more than one
hardlink, and uv makes hardlinks on Linux by default.
**Fix:** install with copies. [Install](/core/start/installation) has the
details, also for a Dockerfile.
```bash theme={null}
UV_LINK_MODE=copy uv sync
```
### The log warns that every worker embeds the documents
There is no baked index, so each process embeds the folder at start.
**Fix:** run `bake()` when you build the image and set `index_dir`.
### `start()` refuses the index
The index was built with other settings.
**Fix:** bake it again.
```bash theme={null}
python -c "from agent import REFUNDS; REFUNDS.bake()"
```
### The model gets `{"error": "lookup unavailable"}`
`look_up` ran before `start()`, or the search failed.
**Fix:** call `start()` once at process start, before the first call.
## Where to go next
The tool that wraps a lookup, and its announce line.
Offer a lookup to one step of a task.
The `[knowledge]` extra and `UV_LINK_MODE`.
How `agent.yaml` declares a knowledge base.
# Prefetch
Source: https://unmute.ai/core/build/prefetch
Fill the call state before the greeting: the clock, the call's numbers, and lookups.
`unmute_core.prefetch` fills the call state before the greeting. It reads the clock, the call's numbers and the result of a lookup. If you already have what a lookup needs, the model should not spend the call doing it.
In the salon tutorial, [Know the time before hello](/core/tutorial/know-the-time) builds this step by step.
## Fill values before the greeting
List the entries. Each one saves values into the call state.
```python agent.py theme={null}
from unmute_core.prefetch import CallValue, Clock, Lookup, Prefetch
from unmute_core.state import CallState
prefetch = Prefetch(
[
Clock("today", "Europe/Madrid", {"booking_date": "date", "weekday": "day_of_week"}),
CallValue("caller", "calling_number", ["caller_phone"]),
Lookup(
"customer", find_customer, assign={"customer_name": "name"}, inputs=["caller_phone"]
),
],
state=State,
)
state = CallState(State)
await prefetch.run(state)
```
1. `Clock` reads the time in the zone you name. `CallValue` copies a value the call carries. `Lookup` runs your function, which takes the call state and returns a mapping, like `{"name": "Ana Ruiz"}`.
2. All entries share one budget, 2 seconds by default. A late or failed entry keeps its default, and the call greets on time.
3. With `state=State`, a mistake in an entry raises `ValueError` when you build it, not during a call.
## Look up with a tool
A lookup may run a tool instead of a function. Lock every argument the tool needs.
```python theme={null}
find = local_tool(find_customer, locked={"phone": "{{caller_phone}}"})
Lookup("customer", find, {"customer_name": "name"})
```
1. The model never fills an argument. An open required one raises `ValueError` when you build the entry.
2. A tool that is refused or fails keeps the values at their defaults.
## Run a slow lookup beside the greeting
Mark a slow lookup `background=True`, so it does not delay the greeting.
```python theme={null}
Lookup("hours", local_tool(store_hours), {"closes_at": "close"}, background=True)
```
1. `prefetch.run` skips it. `CallHooks` runs it beside the greeting.
2. Every model request waits for it, up to `first_request_timeout_s` (10 seconds). A fixed greeting plays at once.
3. A greeting line may not name a value that only a background lookup fills.
## Use it in a call
Give the prefetch to `CallHooks`. `open_call` runs it for you.
```python LiveKit theme={null}
info = sip_call_info(participant, json.loads(ctx.job.metadata or "{}"))
state = CallState(State, call=info)
call = CallHooks(state, prefetch=prefetch)
spec = AgentSpec(PROMPT, tasks=plan)
agent = UnmuteAgent(spec, call=call)
await session.start(agent=agent, room=ctx.room)
await open_call(session, greeting, call)
```
```python Pipecat theme={null}
info = telephony_call_info(runner_args.call_data)
state = CallState(State, call=info)
call = CallHooks(state, prefetch=prefetch)
spec = AgentSpec(PROMPT, tasks=plan)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, call=call)
# on client connected
await open_call(worker, greeting, call, context=context, hold=hold)
```
```python Plain agent theme={null}
state = CallState(State)
await prefetch.run(state) # before the session starts, so the first reply sees the values
instructions = render_prompt(PROMPT, state)
```
1. `open_call` runs your checks first, then `prefetch.run`, then the background lookups and the greeting.
2. Each lookup's result goes to `call.results`, so a task step can read it.
3. On a plain agent, run `await prefetch.run(state)` yourself before the session starts. `render_prompt` comes from `unmute_core.model`.
## What a call carries
A phone number with no plus is read in the call's country. Enter `use_phone_region` around the call, so the state can read a national number.
```python LiveKit theme={null}
from unmute_core.state import call_phone_region, use_phone_region
with use_phone_region(lambda: call_phone_region(state.call)):
await session.start(agent=agent, room=ctx.room)
```
```python Pipecat theme={null}
from unmute_core.state import call_phone_region, use_phone_region
with use_phone_region(lambda: call_phone_region(state.call)):
await runner.run()
```
1. `call_phone_region(state.call)` gives the call's country, like `"ES"`, or `None` for a call without numbers.
2. `sip_call_info` (LiveKit) and `telephony_call_info` (Pipecat) build what the call carries. See [Telephony](/core/telephony).
## Try a phone call locally
A web session has no phone line. To try a phone call, simulate one with `UNMUTE_CALL_START`:
```bash theme={null}
UNMUTE_CALL_START='{"call": {"direction": "inbound", "calling_number": "+34612345678"}}' uv run python agent.py
```
`CallValue` then copies the simulated number, as it would copy a real one. See [State](/core/build/state#values-the-call-carries-state-call) for the rules.
## Where to go next
Every entry, argument, check and rule.
How saved values read in a prompt, and when the caller confirms them.
The order of a whole call, and the greeting.
The same entries, declared in `agent.yaml`.
# State
Source: https://unmute.ai/core/build/state
Typed call values, confirmation, prompt placeholders and the save_values tool, on any Pydantic model.
`CallState` holds what one call knows. It keeps typed values, tracks which ones the caller confirmed, and fills them into your prompts. It works on any Pydantic model, on LiveKit and on Pipecat.
In the salon tutorial, [Remember the caller](/core/tutorial/remember-the-caller) builds this step by step.
## Define what the call remembers
```python state.py theme={null}
from pydantic import BaseModel
from unmute_core.state import CallState, Phone
class State(BaseModel):
caller_phone: Phone | None = None
note: str | None = None
state = CallState(State, confirm={"caller_phone": "verify_phone"})
```
1. Every field needs a default, because every value starts the call empty. A field with no default raises `TypeError`.
2. `confirm` maps a value to the task step that must hear the caller agree to it.
3. Every call needs an agent id. Set `UNMUTE_AGENT_ID`, or pass `call=` with an `agent_id`. With neither, `CallState` raises `SettingsError`.
## Save a value
```python theme={null}
from unmute_core.state import StateRefused
try:
state.save({"caller_phone": "+34 612 345 678", "note": "call back"})
except StateRefused as refused:
print(refused.message) # worded for the model, so it can ask the caller again
```
1. `save` checks the whole batch first. One bad value refuses all of it, and nothing is saved.
2. A good value is saved in its clean form. The phone number above is saved as `+34612345678`.
3. `save` is the one way in. Read `state.values` or `state.plain("note")`, but never write to them.
Task steps, [prefetch](/core/build/prefetch) and the `save_values` tool all save through the same `save`.
## Ask the caller to confirm a value
```python theme={null}
state.save({"caller_phone": "+34 612 345 678"}, step="verify_phone")
state.is_confirmed("caller_phone") # True, the confirming step saved it
state.save({"caller_phone": "+34 612 345 679"})
state.is_confirmed("caller_phone") # False, the caller must agree again
state.render("caller_phone") # "none recorded yet."
```
1. A value in `confirm` is confirmed only when its own step saves it.
2. Any other save makes it unconfirmed again.
3. Until it is confirmed, prompts show `none recorded yet.`, so the model never reads a misheard value back as fact. The confirming step still sees it, so it can read it back.
## Filling a prompt
```python theme={null}
from unmute_core.model import render_prompt
prompt = render_prompt("Help the caller on {{caller_phone}}.", state)
```
1. `{{name}}` names a value. `{{customer.status}}` reads a path into a shape.
2. A name the state does not hold raises `MissingVariablesError`.
3. Call it again after a save, so the prompt shows the new values.
With `UnmuteAgent`, `UnmuteFlows` or a `ModelCall`, you do not call it. The library fills the prompt on every request.
## Values the call starts with
```python theme={null}
from unmute_core.call import save_call_start
state = CallState(State, call_start={"customer_id": "required", "brand": "optional"})
save_call_start(state, dispatched)
render_prompt("Welcome to {{brand}}.", state) # "Welcome to Salon Sol." or "Welcome to ."
```
1. `call_start` names the values the dispatch sets. A `required` one must be there, or `save_call_start` raises `CallStartError`.
2. `dispatched` is the `call_start` object of the dispatch. For a local run, set `UNMUTE_CALL_START` to the same JSON.
3. The caller is never asked for these values, and the model cannot change them.
[The call's life](/core/build/call-lifecycle#start-values) shows where `save_call_start` runs.
## Values the call carries: `state.call`
```python theme={null}
state.call.session_id # one id for the whole call
state.call.calling_number # "+34612345678", or None
render_prompt("The caller is {{call.calling_number}}.", state)
```
The library fills `state.call` from the line. Your State class does not declare it, and only the library writes it.
| Field | What it holds |
| - | - |
| `agent_id` | One id per agent. Your code or the dispatch sets it. |
| `session_id` | One id per call. It is the same on every turn, task and handoff. |
| `channel` | `phone` or `web`. The default is `web`. |
| `direction` | `inbound` or `outbound`. It is `None` on a web call. |
| `calling_number` | The party that placed the call. |
| `called_number` | The party that was dialled. |
| `remote_number` | The other party. The library works it out from `direction`. |
| `carrier_call_id` | The carrier's id for the call, like the SIP Call-ID or the Twilio CallSid. |
| `first_user_message` | What the caller said first. |
| `end_reason` | Why the call ended. |
The inbound, outbound and web cases, a test phone call from a web session and the read-only rules are in the [State reference](/core/reference/state#values-the-call-carries-state-call).
## Saving values no task saves
Some values belong to no task. The model learns them in free talk. Turn on `save_values` to give it a tool for them.
```python LiveKit theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent
spec = AgentSpec(PROMPT, tasks=plan, save_values=True)
agent = UnmuteAgent(spec, state=state)
```
```python Pipecat theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows
spec = AgentSpec(PROMPT, tasks=plan, save_values=True)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
```
1. Each request ends with a short block that lists every value and what it holds now.
2. The model saves with the `save_values` tool. `null` puts a value back to its default.
3. A value a task saves, or a call-start value, is refused with a reason the model can act on.
## Listen to changes
```python theme={null}
def show(event) -> None:
for change in event.changes:
print(change.field, change.value, change.confirmed, change.by.kind)
stop = state.listen(show)
```
1. A listener gets one event per save that changed something.
2. `listen(show, replay=True)` first sends the values already set.
3. Call `stop()` to stop listening. A listener that raises is logged and removed.
## Value types
Use these classes from `unmute_core.state` as field types. Each one cleans and checks the value, and refuses a bad one with a reason the model can act on.
| Type | Saved as |
| - | - |
| `Phone` | E.164 text, like `+34612345678` |
| `Date` | `YYYY-MM-DD` text |
| `BirthDate` | `YYYY-MM-DD` text |
| `Time` | `HH:MM` text on the 24-hour clock |
| `Id` | Text of letters, digits, and `. _ : -` |
| `Spelled` | The code as given, trimmed |
| `NameEmail` | A shape with `name` and `email` |
Every rule of each type is in the [State reference](/core/reference/state#value-types).
## Where to go next
Every argument, rule and error, and State from type text.
Steps that save values, and the held save at the end of a call.
Fill values before the greeting.
Where call-start values are saved.
How `agent.yaml` declares the same values.
# Tasks in code
Source: https://unmute.ai/core/build/tasks
Define tasks and task groups that save values step by step, with the same rules on LiveKit and Pipecat.
A task is a step that saves values to the call state. A task group runs several
tasks in order. The rules live in the core, so LiveKit and Pipecat behave the same.
Use it when:
* The call must collect several values in a set order, like a name, a service and a day.
* A value must be confirmed before a tool uses it, like a booking.
* A step needs its own short prompt and its own tools.
* You want a broken flow to fail at startup, not in the middle of a call.
```mermaid theme={null}
flowchart TD
G[Task group] --> S1[Step: ask, then save values]
S1 --> F{Finish check}
F -->|finish| S2[Next step]
F -->|not yet| S1
S2 --> R[Back to the main agent]
```
## Choose a shape
| You need | Use |
| - | - |
| One behaviour, a few tools, no fixed order | A single prompt with [tools](/core/build/tools) |
| Several values in order, each saved and checked | Tasks and a task group |
| A different agent, with its own prompt, for the rest of the call | A [handoff](/core/build/handoffs) |
## What it handles for you
| On a call without it | What the library does |
| - | - |
| A broken flow shows up in the middle of a call. | `TaskPlan` checks tasks, values and tools at startup, and names what to fix. [Your first task](/core/build/tasks/first-task#troubleshooting) |
| A weak model says "Noted, thank you" and never finishes. The step waits forever. | The finish check asks the model: finish, or not yet. [How a step ends](/core/build/tasks/how-a-step-ends) |
| The model saves a guess, or an answer from an earlier step. | A save before the caller spoke in the step is held, and the model asks. [Held saves](/core/build/tasks/held-saves) |
| The caller answers, then hangs up before the step ends. The answer is lost. | Held answers are settled when the call ends. [Held saves](/core/build/tasks/held-saves) |
| A booking tool runs on what the model guessed. | Code asks "Shall I book Friday, October 16?" and books only what the caller heard. [Reply and confirm](/core/build/tasks/confirm-in-code) |
| The caller corrects an earlier answer and the flow cannot go back. | `go_back_to_step` runs the earlier step again. [How a step ends](/core/build/tasks/how-a-step-ends#going-back-to-an-earlier-step) |
| The model returns nothing and the step dies in silence. | On LiveKit, the model tries up to 3 times, then a fallback line plays. [How a step ends](/core/build/tasks/how-a-step-ends#when-the-reply-is-empty) |
Build it step by step in the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
## In this section
Define one task, check it with `TaskPlan` and run it on each framework.
Run several tasks in order, and decide what follows.
The finish check, a held finish, going back and the empty-reply retry.
What happens to a save made before the caller spoke.
Fixed lines for a tool result, and a question before a tool runs.
History, small results and placeholder names.
Every argument of every task class.
How `agent.yaml` declares the same tasks and groups.
# Reply and confirm in code
Source: https://unmute.ai/core/build/tasks/confirm-in-code
Say fixed lines for a tool result, ask the caller before a closing tool runs, and open a step with a tool.
A step can speak fixed lines from code, so the words a caller hears do not depend on the model. A `ToolReply` speaks for a tool result. A `FinishRule` with `confirm` lines asks before a tool runs.
## Quickstart
```python agent.py theme={null}
from unmute_core.tasks import Assign, FinishRule, TaskSpec
TaskSpec(
name="find_slot",
when="The caller wants to book a time.",
instructions="Find a free time, then book the one the caller picks.",
tools=["list_times", "book_slot"],
assign=[Assign(variable="slot", path=("slot",))],
finish=[
FinishRule(
tool="book_slot",
success={"booked": [True]},
confirm=["Shall I book {{input.slot}}?"],
say=["Booked for {{result.slot}}."],
)
],
)
```
The model calls `book_slot` with `{"slot": "2026-10-16"}`. The tool does not run. The caller hears "Shall I book Friday, October 16?" On a yes, the model calls it again, the tool runs, and the caller hears "Booked for Friday, October 16."
## Why use unmute for this
A booking tool should run on what the caller heard, not on what the model guessed. Code asks the question, checks that the caller heard it, and runs the tool only on the same input. The line is word for word, the same on both frameworks.
## Say a fixed reply to a tool result
A `ToolReply` is a line code speaks when one of the step's tools returns a matching result.
```python theme={null}
from unmute_core.tasks import Assign, FinishRule, TaskSpec, ToolReply
TaskSpec(
name="find_slot",
when="The caller wants to book a time.",
instructions="Find a free time, then book the one the caller picks.",
tools=["list_times", "book_slot"],
assign=[Assign(variable="slot", path=("slot",))],
finish=[FinishRule(tool="book_slot", success={"booked": [True]})],
replies=[
ToolReply(
tool="list_times",
when={"found": [True]},
say=["I have {{result.times}}. Which suits you?"],
)
],
)
```
When `list_times` returns `{"found": true, "times": "10:00, 11:30 or 14:00"}`, the
caller hears "I have 10:00, 11:30 or 14:00. Which suits you?" The model is asked
for no reply. Use a `ToolReply` for a line that must come out word for word, like
the times on offer.
```mermaid theme={null}
flowchart LR
T[Step tool returns] --> M{A reply matches?}
M -->|yes| S[Code says the line]
M -->|no| A[Model answers as usual]
```
1. The model calls one of the step's tools. The tool returns a result.
2. Each `ToolReply` of that tool is checked in order. The first whose `when` and `state` match is used.
3. The line is spoken. The model reads the result, but is asked for no reply.
4. When none matches, the model replies as usual.
5. Both frameworks speak the line, so the call sounds the same.
Rules for the lines:
1. A line fills from the tool's result and the State. `{{result.times}}` reads a field of the result. `{{slot}}` reads a State value.
2. A result value is said by its output field's JSON Schema `format`, in the call's language, as a confirm line says an input. A `date` field reads "tomorrow, October 16".
3. `when` matches result fields. `state` matches State values, like `state={"vip": [True]}`. A reply with neither is spoken for every result of the tool.
4. The plan checks each `{{result.}}` and `when` field against the tool's output model. A field the tool does not return fails when the plan is built.
5. When a line cannot fill, because a field is missing or empty, it is skipped. The next line is tried.
6. When no line fills, the model replies as usual.
7. With several lines, the next call says the next one, so the agent does not repeat itself.
8. A question the caller must answer before a tool runs belongs in `FinishRule.confirm`, not here.
An agent without tasks lists the same `ToolReply` rows on its `ToolRegistry`. See
[Save a result and speak it](/core/build/tools#save-a-result-and-speak-it).
**Why it works this way.** A model may reword a list of times. A line from code comes out word for word, and the model is not asked for a reply.
**Best practice.**
1. Use a `ToolReply` for a line that must come out word for word.
2. Give several lines when the same reply may repeat, so the agent does not repeat itself.
## Ask before a closing tool runs
A `FinishRule` ends a step by itself when its tool returns a result the rule calls a success. Its `confirm` lines ask the caller first.
```python theme={null}
FinishRule(
tool="book_slot",
success={"booked": [True]},
confirm=["Shall I book {{input.slot}}?"],
say=["Booked for {{result.slot}}."],
)
```
```mermaid theme={null}
flowchart TD
C[Model calls the tool] --> A[Code asks the confirm line]
A --> W[Caller answers]
W -->|same input again| R[Tool runs]
W -->|changed input| A
R --> D[Step ends, receipt said]
```
1. The model calls the closing tool. Code does not run it.
2. Code fills a `confirm` line from that call's input and says it. No model reply is asked for.
3. The model reads that the tool has not run, and waits for the caller.
4. On a yes, the model calls the tool again with the same input. The tool runs.
5. If the caller changes something, the model calls it with the new input. Code asks again, with the new values.
6. A successful result ends the step. The `say` lines are the receipt.
The rules:
1. `confirm` takes up to five lines. They may use `{{input.}}`, `{{variable}}` and a field of a shape in the State, like `{{account.amount_words}}`. A path that does not exist fails when the agent is built. A line that cannot fill is skipped. When none can, the tool is refused and the model is told what to get from the caller.
2. `confirm` belongs to the tool. Every rule of that tool must give the same lines.
3. The tool runs only when the caller heard the line. A line cut off after it said every value it holds counts as heard, where the adapter knows the words that played. LiveKit knows them. A line cut off sooner is asked again.
4. The input must be the same as the one asked about, and so must the tool's locked values. Any other input, or a locked value that changed since, like a report the caller corrected, is asked again.
5. An input is said by its JSON Schema `format`, in the call's language. A `date` is named from today: "today, October 8", "tomorrow, October 9", "Friday, October 16". So put a date after "for" or "to", never after "on". An `enum` value is said as words: `hair-color` is "hair color".
6. A step may open on a closing tool that has `confirm` lines. See [Open a step with a tool](#open-a-step-with-a-tool). The opening asks the line about State values. It is skipped when every value is one a step confirms and is already confirmed. A tool with no `arguments` always asks.
**Why it works this way.** The tool runs only when the caller heard the line and the input is the same. A booking then matches what the caller agreed to.
**Best practice.**
1. Put a date after "for" or "to" in a line, never after "on".
2. Give every rule of one tool the same `confirm` lines.
**On each framework.** LiveKit knows the words that played, so a line cut off after every value counts as heard. A line cut off sooner is asked again.
## Open a step with a tool
An `OpeningTool` is a tool a step runs in code as it opens, before any model request. Its `arguments` map a tool parameter to the State value it takes. The tool runs only when every value is set. A parameter the tool's schema declares and does not require is left out of the call when its value is not set.
```python theme={null}
TaskSpec(
name="manage_booking",
instructions="Offer the times, then book the one the caller picks.",
tools=["find_slots"],
opens_with=OpeningTool(
tool="find_slots",
arguments={"service": "requested_service", "date": "requested_day"},
say=["{{result.offer}}"],
),
)
```
When a `say` line fills, the step speaks it and waits for the caller. No model
request is made. Use a tool that only reads, because the model may call it again.
A tool the step ends on may open it too, when it has `confirm` lines. Then code
asks the confirm line about the State values and waits for the caller's yes. Give no `say` for a tool with `confirm` lines. The first `say` line that fills is spoken.
## What a step can offer
### A step that reads a prefetch lookup
A `TaskInput` is something a step reads at the end of its prompt. Its `kind` is `memory` (a State value), `input` (a fixed text, in `value`, up to 4000 characters) or `tool` (what a prefetch lookup returned, recorded by name).
```python theme={null}
prefetch = Prefetch([Lookup("load_customer", local_tool(load_customer), {}, background=True)])
call = CallHooks(state, prefetch=prefetch)
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan), call=call) # or UnmuteFlows(..., call=call)
```
```python theme={null}
TaskSpec(name="greet_member", instructions="...", inputs=[TaskInput(kind="tool", name="load_customer")])
```
1. A `tool` input must name a prefetch `Lookup`. The adapter checks this when the agent is built with the call's `CallHooks`. A name no `Lookup` runs raises `ValueError`, and so does any `tool` input when the hooks have no prefetch. An agent built without hooks is not checked. A tool lookup may have an empty `assign`. `CallHooks` records its result as JSON in `call.results`, by entry name.
2. Give the adapter `call=call`. It passes `call.results` to the steps, so a step reads the same text at the end of its prompt. In your own host, pass `call.results` to `CallTasks(call_start=...)`.
3. Until the tool has finished, the step reads that the input is not available yet.
4. See [Prefetch](/core/build/prefetch) and [The call's life](/core/build/call-lifecycle).
### A step that hands off
`TaskSpec.handoffs` names handoff tools of the agent that the step offers too.
The step's opening reply leaves them out. They come back once the caller speaks
in the step. Calling one ends the step and its task or group, and gives the call
to the other agent. See [Handoffs](/core/build/handoffs#a-handoff-from-a-task-step).
### A step that offers the agent's native tools
```python theme={null}
TaskSpec(
name="look_up_customer",
when="The caller asks about their account.",
instructions="Find the customer, then confirm the account.",
native_tools=("crm",),
# more fields
)
```
1. On LiveKit, a toolset is named by its id. The tools come from `UnmuteAgent(native_tools=...)`.
2. On Pipecat, the names are `FunctionSchema`s in `UnmuteFlows(native_tools=...)`.
3. An unknown name raises when the plan is built.
4. A name may not also be a tool or a handoff of the same task.
5. A step gets only the native tools it lists.
### A task on its own model
```python theme={null}
TaskSpec(name="summarize_order", instructions="...", model="fast")
AgentSpec(PROMPT, tasks=plan, task_models={"fast": LiveKitModel(fast_llm)})
```
`TaskSpec.model` names the model a task's steps run on. The agent's spec maps the
name to a model.
1. On LiveKit, `AgentSpec(task_models=...)` maps each name to a `ModelCall`. A LiveKit LLM plugin goes in as `LiveKitModel(plugin)`. A step of that task sends its requests there. The main agent keeps its own model.
2. A name `task_models` does not hold raises `ValueError` when the spec is built.
3. On Pipecat, `UnmuteFlows` refuses a task with a model when it is built. Every step runs on the agent's LLM service there, as in Unmute.
## Troubleshooting
### The model books before the caller agreed
The closing tool has no `confirm` line, so code does not ask first.
**Fix:** add `confirm` lines to the `FinishRule` of the tool.
### A confirm line is skipped and the tool is refused
No `confirm` line could fill from the call's input.
**Fix:** write the lines with `{{input.}}` for fields the tool takes, and check the names.
### A tool input raises `ValueError` when the agent is built
A `tool` input names a lookup that no prefetch `Lookup` runs, or the hooks have no prefetch.
**Fix:** add the `Lookup` to `Prefetch`, and build the agent with the call's `CallHooks`.
In the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
Every argument: [Tasks reference](/core/reference/tasks#finishrule).
## Where to go next
The small results a task sends to the model.
The tools a step lists in `tools`.
Give the call to another agent.
# Your first task in code
Source: https://unmute.ai/core/build/tasks/first-task
Define one task, check it with TaskPlan and run it on LiveKit and Pipecat.
A task is a step that saves values to the call state, on its own prompt. The rules live in the core, so LiveKit and Pipecat behave the same.
## Quickstart
```python agent.py theme={null}
from typing import Literal
from pydantic import BaseModel
from unmute_core.state import CallState
from unmute_core.tasks import TaskPlan, TasksSpec
from unmute_core.tools import ToolRegistry
class State(BaseModel):
requested_service: Literal["haircut", "hair-color", "blowout"] | None = None
spec = TasksSpec.model_validate(
{
"mode": "record",
"tasks": [
{
"name": "choose_service",
"when": "The caller wants to book an appointment.",
"instructions": "Ask which service they want: a haircut, hair color or a blowout. Then save it.",
"assign": [{"variable": "requested_service", "path": ["requested_service"]}],
}
],
}
)
plan = TaskPlan(spec, state=State, tools=ToolRegistry([]))
```
```python LiveKit theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent
state = CallState(State)
spec = AgentSpec(PROMPT, tasks=plan)
agent = UnmuteAgent(spec, state=state)
```
```python Pipecat theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows
state = CallState(State)
spec = AgentSpec(PROMPT, tasks=plan)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
flows.install()
```
The main agent now has a `choose_service` tool. When the model calls it, a step
runs on its own prompt. The step saves `requested_service` and hands the call
back. A value outside the three services is refused, and the model asks again.
## Why use unmute for this
A task is data. You describe the step, and the library checks it at startup, runs it the same way on both frameworks and saves the values it collects. A broken flow fails the deploy, not the call.
## Name a task
A task or group name is lower snake case. It becomes the prompt site
`task:`. A prompt site is the place in the agent where a prompt is used: the
main prompt, or the prompt of one task step. Three names are taken:
* `finish` and `go_back_to_step`, the step's own tools.
* `summary`, because a handoff summary uses the prompt site `task:summary`.
A task is also a tool of the main agent. A task with the same name as another tool
of the agent, like `end_call`, is refused when the agent is built. This is the same
on LiveKit and Pipecat.
## Define a task
Every spec class is immutable and refuses keys it does not know. They are
Pydantic models, so you can build them as literals or from JSON with
`model_validate`. Import them from `unmute_core.tasks`. A step that checks the caller's phone number looks like this:
```python agent.py theme={null}
from unmute_core.tasks import TasksSpec
CONCIERGE_TASKS = TasksSpec.model_validate(
{
"mode": "record",
"tasks": [
{
"name": "verify_customer",
"when": "Run this when the caller corrects their phone number.",
"instructions": "Confirm the number, then save it.",
"tools": ["find_or_create_customer"],
"assign": [
{"variable": "customer_phone", "path": ["customer_phone"]},
{"variable": "customer_verified", "path": ["status"]},
],
}
],
"task_only_tools": ["find_or_create_customer"],
}
)
```
The main fields of a `TaskSpec` are:
1. `name`: lower snake case.
2. `instructions`: the step's prompt.
3. `when`: when the main agent starts it.
4. `tools`: the tools the step may call.
5. `assign`: the values it saves.
[Tasks reference](/core/reference/tasks#taskspec) lists the rest.
### Instructions
A step's `instructions` may hold `{{name}}` placeholders and plain text, including JSON.
1. A lone `}}` is plain text. `{"a": {"b": 1}}` passes.
2. A `{{...}}` that is not a valid placeholder is refused, and so is a `{{` that never closes.
3. Blank instructions are refused.
4. Spoken lines, announce lines, locked arguments and the greeting keep a stricter rule: they take only placeholders.
### Assign
One value a step saves. An `Assign` has a `variable` and a `path`. The `path` says where the value sits in the step's result, like `("order", "id")`.
```python theme={null}
from unmute_core.tasks import Assign
Assign(variable="appointment", path=("appointment",))
```
An empty `path`, `()`, saves the whole result, into a State value typed as the
tool's output model. The finish parameter is the field itself for a one-part path.
For a longer or an empty path it is the variable name. Two assignments may not share a finish parameter. `append` adds one entry onto a list instead of replacing it. This is Unmute's `+`. `optional` lets the step finish without the value. This is Unmute's `?`. Otherwise a served finish must carry it, unless it appends.
### Modes
`TasksSpec.mode` is `status` or `record`. Everything on these pages describes `record` mode. `status` mode keeps Unmute's older behaviour: a run hands the main agent a status, and a hand-back saves nothing.
## Run the tasks
### TaskPlan
`TaskPlan` holds the tasks and groups of one agent, checked once and read by every call.
It checks the spec against the State and the tools. It raises
`ValueError` and names the first task, group or value that does not fit.
`TaskPlan.check_then_targets(known)` refuses a group that transfers to an agent
the adapter was not given. The adapters call it when they are built.
```python theme={null}
plan.check_native_tools(["crm"])
plan.check_handoff_tools(["to_notes"], fix="Add it to native_tools.")
```
1. `check_native_tools(names)` refuses a task that lists a native tool the agent does not have. It raises `ValueError` and names the first task and the missing tool.
2. `check_handoff_tools(names, fix=)` refuses a task whose `handoffs` names a tool the agent has no handoff for. `fix` is the end of the message. Say how to add the tool.
3. Both take `task=` to check one task. Without it, they check every task.
4. The adapters call them when the agent is built. Call them yourself when you write your own host.
### CallTasks
`CallTasks` holds the tasks of one call: the main agent's task tools, and every run they start.
Both adapters build their own from the spec, once per call: read it as `agent.tasks` on LiveKit and `flows.tasks` on Pipecat. Build one yourself only when you write your own host.
`CallTasks.empty(state, tools=...)` gives the tasks of an agent
that has none. Use it in your own host when it needs a stack and you have no tasks.
`TasksSpec.owners()` returns each State value that a task saves, with the first
task that saves it. The save tool for values no task saves uses it. See
[State](/core/build/state).
## Troubleshooting
### `ValueError` names a task, group or value when the plan is built
`TaskPlan` checks every name a task reads against the State and the tools.
**Fix:** read the message. It names the first thing that does not fit, like a
`{{name}}` the State does not have, a tool the task does not list, or a group
that transfers to a target `then_targets` does not hold.
```python theme={null}
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan), state=state, then_targets={"billing": to_billing})
```
### A task has no `when`, and nothing can start it
A task with no `when` must be a step of a group, or be entered by a `via` tool.
**Fix:** add a `when`, put the task in a group, or add a `via` tool.
### A task name is refused
`finish`, `go_back_to_step`, the built-in tool names and `summary` are taken.
**Fix:** rename the task or group.
In the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
Every argument: [Tasks reference](/core/reference/tasks#taskspec).
## Where to go next
Run several tasks in order, and decide what follows.
Every argument of every task class.
The tools a step lists in `tools`.
# Task groups in code
Source: https://unmute.ai/core/build/tasks/groups
Run several tasks in order as one flow, and decide what happens when the flow finishes.
A task group runs several tasks in order, as one flow the main agent starts.
## Quickstart
```python agent.py theme={null}
from unmute_core.tasks import TaskGroupSpec
TaskGroupSpec(
name="book",
when="The caller wants to create, move or cancel a booking.",
steps=("verify_customer", "manage_booking"),
context_scope="shared",
skip_when_confirmed={"verify_customer": "customer_phone"},
arguments=("requested_service", "requested_day", "requested_intent"),
)
```
This is the salon's `book` group. It runs `verify_customer`, then `manage_booking`. The group names its steps in order. Each step is a task of the same `TasksSpec`. The main agent gets one tool for the whole group, and a step runs when the one before it ends. When the caller's phone is already confirmed, the group skips `verify_customer`.
## Why use unmute for this
You list the steps and the library runs them in order. It carries what each step saved to the next one, skips a step whose value is already confirmed, and always hands the caller back to the main agent when a step fails.
## Group fields
`name` is lower snake case, and a task and a group may not share a name. `steps` are the task names, in order. There must be at least one. Each runs at most once in the group.
`context_scope` is required:
* `shared`: each step hears the steps before it.
* `isolated`: each step starts fresh.
Other fields:
1. `when` says when the main agent starts the group.
2. `announce` holds lines spoken as it starts.
3. `non_blocking` names steps whose failure the group records and carries on past. Each must be one of its steps.
4. `skip_when_confirmed` maps a step to the State value whose confirmation lets the group skip it. The step must be the one that confirms that value.
5. `inputs` is what every step reads at the end of its prompt, before its own inputs.
6. `arguments` are State values the main agent passes when it starts the group. Each call saves all of them.
[Tasks reference](/core/reference/tasks#taskgroupspec) lists every argument.
## What a group does when it finishes
`then` sets what follows a group that completes.
| `then` | When the group completes |
| - | - |
| `return` (default) | The main agent gets the result and replies. |
| `end` | The call ends once the last step's words have played. The main agent is not asked for a reply. |
| `transfer` | The call goes to the agent `then_target` names, once the last step's words have played. The main agent is not asked for a reply. |
1. `then_target` is required with `transfer`, and refused with `return` or `end`.
2. The adapter's `then_targets` maps each target to the handoff that gives it the call. A target it does not name is refused when the agent is built. See [Handoffs](/core/build/handoffs).
3. A group that hands the caller back, or fails, always returns to the main agent. So the caller is never dropped mid-request.
4. The main agent's tool description says that the flow ends the call, or hands the caller on.
**Why it works this way.** A group that fails or hands back must never leave the caller in silence, so it always returns to the main agent.
**Best practice.**
1. Use `shared` when a later step needs what an earlier one heard.
2. Use `transfer` only with a `then_target` the adapter's `then_targets` holds.
```python theme={null}
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan), state=state, then_targets={"billing": to_billing})
```
## Troubleshooting
### A group that transfers is refused when the agent is built
The group's `then_target` is not a key of `then_targets`.
**Fix:** add the target to the adapter's `then_targets`, as shown above.
### A step of a group never starts by itself
A task with no `when` must be a step of a group, or be entered by a `via` tool.
**Fix:** put the task in a group's `steps`.
In the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
Every argument: [Tasks reference](/core/reference/tasks#taskgroupspec).
## Where to go next
The finish check, a held finish and going back.
Give the call to another agent from a step or a group.
Define a task and check it with TaskPlan.
# Held saves
Source: https://unmute.ai/core/build/tasks/held-saves
What happens when a step tries to save before the caller spoke in it, and how the call end settles the save.
A held save is a save a step tried before the caller said anything in that step. The library refuses it, keeps the values aside and settles them when the call ends.
## Quickstart
```python agent.py theme={null}
await state.settle_held()
```
Adapters do this for you. A host without an adapter calls `CallState.settle_held()` directly, as above.
## Why use unmute for this
A model sometimes saves a guess, or an answer from an earlier step. The library refuses that save and makes the model ask. It still keeps the answer the caller gave before the step began, in case the call ends first.
## What a held save is
A step's first reply may try to save values before the caller said anything in
that step. To settle a held save is to decide, when the call ends, whether to keep it. The save is refused, because the model guessed or reused an old answer.
```mermaid theme={null}
flowchart TD
A[Step saves before the caller spoke] --> R[Save is refused]
R --> M[Model asks the caller]
R --> H[Values are held]
H --> E{Call ends}
E -->|caller said nothing| K[Held values are saved as written]
E -->|caller spoke| D[Step is asked once: finish or not_yet]
```
1. The model reads the refusal and asks the caller.
2. When the refused reply already spoke, like "Your note: a call back. Is that right?", no second reply follows. The caller answers next.
3. The refused values are held for the end of the call. The caller may have given the answer before the step began, and heard the agent take it.
4. When the call ends with a save still held, the result depends on what the caller did after the hold.
| What the caller did after the hold | What is saved |
| - | - |
| Said nothing | The held values, as written |
| Spoke | The step is asked once, `finish` or `not_yet`, on what the caller said. "Thanks, bye" keeps the values. "No, make it an email" saves the correction. A doubt or a no saves nothing. |
1. A value saved this way is never marked confirmed. No step was left to confirm it.
2. The step's next finish releases the hold, so a step that goes on normally never uses it.
3. The decision waits at most 4 seconds. One that fails or runs out of time saves nothing.
4. A step whose values come from its own tool holds nothing. The caller cannot have given those before the step began.
**Why it works this way.** The caller may have given the answer before the step began and heard the agent take it. Dropping it would lose a real answer. Marking it confirmed would hide that nobody checked it.
**Best practice.**
1. Let the adapter settle held saves when you can.
2. Read a value saved this way as unconfirmed.
## Settle held saves on each framework
**On each framework.** Each adapter settles held saves when the call ends:
* **LiveKit:** automatic, when the session closes.
* **Pipecat:** with `UnmuteFlows(call=...)`, `await call.end(...)` after `runner.run()` settles them. Without hooks, call `await flows.settle()` when the caller hangs up, before the `EndFrame`. The decision is then traced in the last turn.
`CallState.settle_held()` does the work. A host without an adapter calls it
directly:
```python theme={null}
await state.settle_held()
```
## Troubleshooting
### A value is saved but never marked confirmed
It was saved from a hold. No step was left to confirm it.
**Fix:** none is needed. Ask the caller again in a later step if you need it confirmed.
### Held values are lost on Pipecat
Nothing settled them when the caller hung up.
**Fix:** pass `call=` to `UnmuteFlows` and call `await call.end(...)` after `runner.run()`. Without hooks, call `await flows.settle()` before the `EndFrame`.
In the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
Every argument: [Tasks reference](/core/reference/tasks#calltasks).
## Where to go next
Ask the caller before a closing tool runs.
How the call state keeps held values.
The finish check that a held save uses.
# How a task step ends
Source: https://unmute.ai/core/build/tasks/how-a-step-ends
The finish check, the held finish, going back to an earlier step and the retry after an empty reply.
A step ends when the model calls its `finish` tool with the values, or when a
closing tool's result matches a `FinishRule`. Weak models sometimes skip that.
## Quickstart
```python agent.py theme={null}
from unmute_core.tasks import Assign, TaskSpec
TaskSpec(
name="choose_service",
when="The caller wants to book an appointment.",
instructions="Ask which service they want, then save it.",
assign=[Assign(variable="requested_service", path=("requested_service",))],
)
```
When the model has the service, it calls `finish` with `{"requested_service": "haircut"}`. When it only says "Noted, thank you", the finish check steps in. The sections below explain both cases.
## Why use unmute for this
A weak model often says "Noted, thank you" and never finishes. The library asks the model one narrow question after such a reply, so the step does not wait forever.
## The finish check
Weak models often say "Noted, thank you" and stop, without calling `finish`.
The step then waits for a save that never comes.
After a step's reply that spoke and called nothing, once the caller has said
something new in the step, the runtime asks the model one narrow question:
`finish` with the values, or `not_yet`. The request offers only those two tools,
and a tool call is required.
1. A `finish` is sent as that reply's own call. The step ends as if the model had called it.
2. `not_yet` changes nothing. The step goes on.
3. The check runs at most once per caller turn, and waits at most 8 seconds.
4. A step with tools of its own is checked only after one of them succeeded, because its values come from that result.
**On each framework.** On Pipecat, the check goes to the call's LLM when it can be asked: a `ModelCallLLMService`, an OpenAI-compatible service or a `GoogleLLMService`. For any other LLM, the spec's `AgentSpec(summarizer=...)` answers the check. With no summarizer, there is no check.
**Why it works this way.** The check offers only `finish` and `not_yet`, so a weak model cannot wander off. It runs once per caller turn and has a time limit, so it never holds up the call.
**Best practice.**
1. On Pipecat with a custom LLM, give the spec a `summarizer`, or the check does not run.
## The held finish
A finish is refused when the caller has not heard a tool's result yet. The model
reads "tell them what it means first". That finish is held. When the next reply
says the result and calls nothing, the runtime sends the held finish for it.
**Why it works this way.** The caller hears a result before the step ends on it.
## Going back to an earlier step
While a step runs, the caller may change an earlier answer. The model then calls
`go_back_to_step` with the names in `steps`. A name the run cannot go back to is
refused as `{"refused": ...}`. The text lists the steps it can go back to:
```text theme={null}
cannot go back to 'take_card'. Go back to one of: confirm_amount
```
When no step ran before the current one, the list reads `none, no step ran
before this one`. A call with an empty list is refused with `name at least one
earlier step`.
## When the reply is empty
A model sometimes returns nothing: no words and no tool call. On LiveKit, a step then asks again, up to `EMPTY_REPLY_ATTEMPTS` times, which is 3. Each retry adds a different note to the step's prompt.
1. The note says the previous response was empty and asks for the step's next valid response. It tells the model to use what the caller already said and never to ask again for it.
2. Each retry reads a different note, because the Responses API reuses an earlier answer when the request has not changed.
3. When the empty reply followed a step tool's result, the retry offers only `finish`, and the note says to use the tool result already in context.
4. When all tries are empty, a step its group can do without fails and the group carries on. Any other step stays open and says a short apology: `gave_up_line`, or `gave_up_after_tool_line` after a tool result.
Set both lines on `CallTasks`, in the call's language. Each adapter builds its own `CallTasks` from the spec, as `agent.tasks` on LiveKit and `flows.tasks` on Pipecat. So set `agent.tasks.gave_up_line` after you build the agent.
```python theme={null}
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan, language="es-ES"), state=state)
agent.tasks.gave_up_line = "Lo siento, no pude completarlo. Inténtalo otra vez."
```
## Troubleshooting
### The step says it could not complete and the caller must try again
Every retry after an empty reply came back empty, and the step said its `gave_up_line`.
**Fix:** set `gave_up_line` and `gave_up_after_tool_line` to lines in the call's language. Then check the step's `instructions`, so the model knows what to reply.
### The caller changed an answer, and the step cannot go back
The model asked for a name the run cannot go back to. The refusal lists the steps it can.
**Fix:** put the earlier step in the same group, and read the refusal text for the names it allows.
In the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
Every argument: [Tasks reference](/core/reference/tasks#steprun).
## Where to go next
What happens to a save made before the caller spoke.
Run several tasks in order.
# What the model reads in a task
Source: https://unmute.ai/core/build/tasks/what-the-model-reads
What a step hears of the call, the small results a task sends to the model, and the limits on placeholder names.
A task answers the model with a few small results, and a step opens on a chosen part of the call so far. This page lists both.
## Quickstart
```python agent.py theme={null}
from unmute_core.tasks import REFUSED_BUSY, Refused, ToolDeclaration, ToolStatus
Refused(refused="Run take_order first.").model_dump() # {"refused": "Run take_order first."}
ToolStatus(status="completed").model_dump() # {"status": "completed"}
```
## Why use unmute for this
The results are small and frozen, and `unmute_core.tasks` names them. Your code can build the same JSON the adapters send, so a test or a custom host reads what the model reads.
## What the model reads when a task runs
| Name | What it is |
| - | - |
| `Refused` | The result of a refused call: one sentence that says why and what to do. |
| `ToolStatus` | A result that says how a call stands, like `completed` or `not_run_yet`. |
| `ToolDeclaration` | A tool as the model reads it: `name`, `description` and `parameters`. `to_dict()` gives the dict a model call takes. Its parameters are a copy, so editing one declaration never changes another. |
| `REFUSED_BUSY` | The result the model reads when it starts a task while another one runs. It is a `Refused` as a dict. |
All of them are frozen. An unknown field raises a `ValidationError`.
## What a step hears of the call
`TaskSpec.history` sets what a step opens on: `messages` (default), `full`,
`last_n`, `summary` or `reset`. A handoff takes the same values. [Handoffs](/core/build/handoffs#what-the-next-agent-hears)
explains each one.
* `include_tool_calls: false` leaves tool calls and results out of `full` and `last_n`.
* `last_n` needs `max_messages`, from 1 to 200, and any other history refuses it.
* A `summary` step asks for its summary as it opens. A summary that fails gives the step `messages`.
* In an `isolated` group, every step starts fresh, whatever its `history`.
```python theme={null}
TaskSpec(name="confirm_order", instructions="...", history="last_n", max_messages=6)
```
## Placeholder names
A plan or a spec that does not fit raises `ValueError` when it is built.
A native model call has no limit on a placeholder name. A model call that fills the prompt on its own side can name a limit in `variable_key_max`. The SLNG Context Router names 64. The check runs at build, against the call's model.
1. A placeholder name becomes a template-variable key. `a.b` is `a__b`.
2. When the model call names a limit, a key over it is refused, with a message that names the placeholder.
3. The check covers a task's instructions, and the agent's main prompt when the adapter builds the agent.
4. A model call with no `variable_key_max`, like a framework's own LLM plugin, checks nothing.
## Troubleshooting
### A placeholder name is refused when the agent is built
The model call names a `variable_key_max`, and the key of a placeholder is longer.
**Fix:** shorten the State value name that the placeholder reads. `a.b` counts as `a__b`.
In the salon tutorial: [Book step by step](/core/tutorial/book-step-by-step).
Every argument: [Tasks reference](/core/reference/tasks#taskspec).
## Where to go next
What the next agent hears when a step hands off.
Define a task and check it with TaskPlan.
The model call that names a placeholder limit.
# Tools in code
Source: https://unmute.ai/core/build/tools
Give the model tools to call: Python functions, webhooks and built-ins that work the same on LiveKit and Pipecat.
A tool is something the model can call during a call: a Python function, a
webhook or a built-in. You write a typed function. The library checks every
argument before your code runs and every result after it, the same way on
LiveKit and Pipecat.
In the salon tutorial, [Check the diary](/core/tutorial/check-the-diary) builds this step by step.
## Add a tool
```python tools.py theme={null}
from datetime import date
from typing import Annotated
from pydantic import BaseModel, Field
from unmute_core.tools import ToolRegistry, local_tool
class Booking(BaseModel):
reference: str
day: date
def book_table(
day: Annotated[date, Field(description="The day the caller wants.")],
party: Annotated[int, Field(ge=1, le=12)] = 2,
) -> Booking:
"""Book a table."""
return Booking(reference="B-12", day=day)
registry = ToolRegistry([local_tool(book_table, announce="One moment, let me book that.")])
```
1. `local_tool` turns a typed Python function into a tool. The docstring tells the model what it does, and `Field` limits go into its schema.
2. A bad argument goes back to the model with what to fix. Your function gets real Python types.
3. The return annotation, `Booking`, is the output. A result that does not fit fails the call, and the model reads which field is wrong.
## Use it in your agent
The same registry works in a full agent and in a plain one.
```python LiveKit theme={null}
from livekit.agents import Agent
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent, function_tools
agent = UnmuteAgent(AgentSpec(PROMPT, tools=registry), state=state, call=call)
# Or on a plain LiveKit Agent:
agent = Agent(instructions=PROMPT, tools=function_tools(registry, state, hooks=call))
```
```python Pipecat theme={null}
from pipecat.processors.aggregators.llm_context import LLMContext
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows, tools_schema
spec = AgentSpec(PROMPT, tools=registry)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state, call=call)
flows.install()
# Or on a plain Pipecat pipeline:
context = LLMContext(tools=tools_schema(registry, state, hooks=call))
```
1. Build the tools once per call. They read that call's state.
2. `call` is the call's `CallHooks`. It runs your [tool hooks](/core/build/hooks) and lets background webhooks finish when the call ends.
3. Set `language=` and `timezone=` on `AgentSpec`, or on `function_tools` and `tools_schema`, so spoken dates follow the call.
## Say a line while it works
```python theme={null}
local_tool(check_day, announce=["One moment, let me check {{day}}.", "Let me look at {{day}}."])
```
1. The agent says one line as the tool starts, never the same one twice in a row. A refused call says nothing.
2. `{{day}}` reads an argument or a State value. `{{call.session_id}}` reads what the call carries.
3. `announce_wait=True` runs the tool only after the line has played, for a line like "Putting you through now."
## Keep a tool running when the caller talks
```python theme={null}
local_tool(book_table, interruption="continue")
```
1. Pipecat cancels a running tool when the caller speaks. `continue` lets it finish, as LiveKit always does.
2. Use it for a tool that changes something, like a booking or a payment. A lookup can keep the default.
3. A plain Pipecat pipeline also needs `attach_call(..., llm=llm)`, so the prompt stays the same as on LiveKit.
## Tell the model a tool failed
```python theme={null}
def book_table(day: date) -> Booking:
"""Book a table."""
if day.weekday() == 0:
raise ToolError("We are closed on Mondays. Offer another day.")
return Booking(reference="B-12", day=day)
```
1. `ToolError` comes from `unmute_core.tools`. The model reads your words and acts on them.
2. Any other error tells the model the tool failed and not to claim success. The log keeps the details.
3. A call that reads a value not set yet does not run. The model gets a hint instead. See [A call that is refused](/core/reference/tools#a-call-that-is-refused).
## Save a result and speak it
```python theme={null}
from unmute_core.tools import Assign, ToolRegistry, ToolReply, local_tool
registry = ToolRegistry(
[local_tool(find_order)],
state=State,
assign={"find_order": [Assign(variable="order", path=())]},
replies=[
ToolReply(tool="find_order", when={"status": ["held"]}, say=["{{result.order_id}} is held."]),
ToolReply(tool="find_order", say=["Your order arrives {{result.arrives}}."]),
],
)
```
1. `assign` saves the result into State values. `path=()` saves the whole result, and `path=("order_id",)` one field.
2. `replies` are tried in order. Code speaks the first one that matches and fills, and the model is asked for no reply.
3. A date reads "tomorrow, October 16" in the call's language. A task step lists the same rows on its `TaskSpec`. See [Confirm in code](/core/build/tasks/confirm-in-code).
## Locked arguments
```python theme={null}
webhook_tool(..., locked={"customer_id": "{{customer.id}}", "call": "{{call.session_id}}"})
```
1. The model never sees a locked argument. A value it sends is replaced.
2. `{{customer.id}}` reads the call state, and `{{call.session_id}}` what the call carries. The tool is refused, with a hint, while a value is unset.
3. `Transcript()` sends the call's transcript so far. See [Send the transcript](/core/reference/tools#send-the-transcript).
## Call a webhook
```python theme={null}
from unmute_core.tools import Accepted, WebhookAuth, webhook_tool
webhook_tool(
"notify_crm",
"Tell the CRM about the booking.",
"https://crm.example.com/hooks/booking",
input=BookingNote,
output=Accepted,
auth=WebhookAuth.api_key("CRM_KEY", header="X-API-Key"),
wait_for_response=False,
)
```
1. `input` is the model of what the model sends, and `output` the model of the answer. With `wait_for_response=False`, the output is `Accepted`, and the request runs in the background.
2. The token is read from `CRM_KEY` at each call. One 10 second deadline covers the whole request, and each body is capped at 64 KiB.
3. Each address must be public. Set `allow_private_network=True` only for your own service, or for `localhost` while you develop.
## End the call
```python theme={null}
hang_up = local_tool(hang_up_handler, effect="ends_conversation")
```
1. The call ends once the tool succeeds. The model is not asked for another reply, so the goodbye goes in the reply that calls the tool.
2. A failed tool never ends the call.
3. On Pipecat, `end_call_tool` ends the call with no second model request. See [End the call](/core/reference/tools#end-the-call).
## Add the date or the caller number
```python theme={null}
from unmute_core.tools import ToolRegistry, current_datetime_tool, user_phone_number_tool
registry = ToolRegistry([current_datetime_tool("Europe/Madrid"), user_phone_number_tool()])
```
1. `current_datetime_tool` takes an IANA zone and returns the local date, time and day of the week.
2. `user_phone_number_tool` reads the number from `state.call`. On a call with no number, it returns `"available": false`.
## Watch tool calls
```python theme={null}
def show(stage: str, data: dict) -> None:
print(stage, data)
registry.listen(show)
```
1. The sink hears each stage, like `tool.started`, `tool.failed` or `tool.refused`, with names and timing only. It never gets argument values.
2. In a call, use the call's hooks instead. See [Hooks](/core/build/hooks).
## Where to go next
Every option, webhook argument, rule and edge case.
Search a folder of documents from a tool.
Run your code around each tool call.
How `agent.yaml` declares the same tools.
# Turn taking
Source: https://unmute.ai/core/build/turn-taking
Set how fast the agent takes its turn, what speech over a line does, and what happens when the caller goes quiet.
Turn taking is when the agent speaks, when it stops, and when it checks the caller is still there. You set it with a few small helpers. The same names work on LiveKit and Pipecat.
In the salon tutorial, [Quiet callers and long calls](/core/tutorial/quiet-callers) builds this step by step.
## Set the turn pace
A caller pauses mid-sentence. The pace says how long the agent waits before it decides the turn is over.
```python LiveKit theme={null}
from unmute_core.livekit import endpointing
from unmute_core.turn import turn_window
window = turn_window("balanced", "livekit")
vad = silero.VAD.load(min_silence_duration=window.vad_silence)
turns = TurnHandlingOptions(endpointing=endpointing(window))
```
```python Pipecat theme={null}
from unmute_core.pipecat import smart_turn_params, vad_params
from unmute_core.turn import turn_window
window = turn_window("balanced", "pipecat")
vad = SileroVADAnalyzer(params=vad_params(window))
turn = LocalSmartTurnAnalyzerV3(params=smart_turn_params(window))
```
1. Pick `snappy`, `balanced` or `patient`. `balanced` is the default.
2. `turn_window` returns the wait that framework uses for that pace.
3. The framework's helper turns the window into its own options.
## Drop a reply the caller spoke over
A caller says "Hi.", pauses, then says "I'd like to book a haircut". LiveKit ends their turn at the pause, and plays the reply over them. `yield_to_caller` drops that reply.
```python LiveKit theme={null}
from unmute_core.livekit import yield_to_caller
yield_to_caller(session)
```
```python Pipecat theme={null}
# Nothing to call. A new caller turn interrupts
# whatever the bot is thinking, saying or running.
```
1. Call it once, after you build the session.
2. The next reply answers everything the caller said.
3. A reply with a tool running is kept, because dropping it would cancel the tool.
## Choose what speech over a line does
A "mm-hm" or a "yes" over the agent can mean "go on" or "that is my answer". The `interruption` rule picks which.
| Value | The agent | The caller's words |
| - | - | - |
| `keep` | Finishes the line | Answered once it ends. A "yes" over a question is the answer. |
| `drop` | Finishes the line | Dropped. Right for an agent that reads long text. |
| `stop` | Stops on speech | Answered. No detector. |
```python LiveKit theme={null}
from unmute_core.livekit import interruption
AgentSession(..., turn_handling=TurnHandlingOptions(..., interruption=interruption("keep")))
```
```python Pipecat theme={null}
from unmute_core.pipecat import interruption
LLMUserAggregatorParams(
user_turn_strategies=interruption("keep", stop=[TurnAnalyzerUserTurnStopStrategy(...)]),
)
```
1. On LiveKit, `keep` and `drop` use LiveKit's detector. It needs `LIVEKIT_API_KEY` or `LIVEKIT_INFERENCE_API_KEY`. Without one, the agent stops on any speech, as with `stop`.
2. On Pipecat, `keep` counts words. Fewer than 3 words wait for the line to end. 3 or more stop the agent.
## Turn off interruption or protect a line
```python LiveKit theme={null}
from unmute_core.livekit import interruption
interruption("keep", enabled=False) # the agent finishes every line
interruption("keep", min_words=2) # two words before speech counts
```
```python Pipecat theme={null}
from unmute_core.pipecat import interruption, user_mute_strategies
LLMUserAggregatorParams(
user_turn_strategies=interruption("drop", stop=[...], min_words=2),
user_mute_strategies=user_mute_strategies(protect=["greeting", "tool_calls"]),
)
```
1. On Pipecat, `protect` names what the caller cannot cut off: the greeting, or a running tool.
2. `user_mute_strategies(enabled=False)` mutes the caller while the agent speaks, so no line is cut off.
3. On LiveKit, a greeting nobody may cut off is `Greeting(interruptible=False)`. A tool call that runs always finishes.
## Nudge a quiet caller
`IdleNudges` holds up to two nudges and a final line. After the last one, the call ends.
```python theme={null}
from unmute_core.idle import IdleNudges
IDLE = IdleNudges(
first_nudge_delay_seconds=20,
first_nudge_text="Are you still there?",
second_nudge_delay_seconds=15,
second_nudge_text="I'm still here whenever you're ready.",
hangup_delay_seconds=10,
final_hangup_text="I'll let you go for now. Call us back any time. Goodbye.",
)
```
```python LiveKit theme={null}
from livekit.agents.voice import room_io
from unmute_core.livekit import idle_nudges
session = AgentSession(..., user_away_timeout=None)
idle_nudges(session, IDLE)
await session.start(
agent, room=ctx.room, room_options=room_io.RoomOptions(delete_room_on_close=True)
)
```
```python Pipecat theme={null}
from unmute_core.pipecat import IdleNudgeObserver
worker.add_observer(IdleNudgeObserver(IDLE, worker))
```
1. The timer runs only while the agent listens. Any word from the caller, or any reply from the agent, starts it again from the first nudge.
2. The lines are spoken by code, with no model request. A nudge with no text is worded by the model.
3. On LiveKit, leave `user_away_timeout` at `None`, and set `delete_room_on_close=True` so a phone caller is hung up. On Pipecat, leave the user aggregator's `user_idle_timeout` unset.
## Cap the call length
```python theme={null}
from unmute_core.idle import CallLimit
limit = CallLimit(20 * 60, session.shutdown)
limit.start()
```
1. `CallLimit` ends the call after the longest allowed length, with no closing line.
2. `cancel()` stops the count.
3. The adapters also take it as `max_duration`, on [LiveKit](/core/frameworks/livekit) and on [Pipecat](/core/frameworks/pipecat).
## Where to go next
Every argument, pace window, rule and error.
The session, the greeting and the call limit on LiveKit.
The pipeline, the greeting hold and the call limit on Pipecat.
The greeting, the failure line and the end of the call.
Where the idle nudge and interruption events show.
# Faro, a bilingual language tutor
Source: https://unmute.ai/core/examples/faro
Two agents, one per explanation language, share one set of typed tools. The model grades each answer, and code teaches, records progress and says the next exercise.
Faro is a language companion on the phone. It knows learners by their number,
signs new ones up, and teaches short lessons in English or Spanish. It explains
in the learner's own language, puts each exercise, judges the answer, and
carries on from where they stopped, across calls. The code is in
`examples/faro`.
```mermaid theme={null}
flowchart TD
G[Greeting reads the caller's number back] -->|yes| K{Known?}
G -->|wrong, or no caller ID| O[other_number: number read back by code]
O --> K
K -->|known| S[code: where they stopped]
K -->|new| U[sign_up: profile read back by code]
S --> L[continue_lesson: code says the exercise]
U --> L
L --> A[grade_answer: the model grades, code moves on]
A --> L
L -.->|"Can you explain in English?"| H[handoff to the other language's agent]
```
## The model grades, code teaches
The lesson needs no task. Five main-agent tools carry it, and each result says
its own line:
| The learner | The model calls | Code says |
| - | - | - |
| answers the exercise | `grade_answer(answer, grade, feedback)` | the feedback, then the next exercise, the retry, or "Lesson complete" |
| asks for help | `give_hint(hint)` | the hint. The next right answer counts as practised with help. |
| wants to go on | `continue_lesson()` | the exercise, in their language |
| wants a recap | `read_progress()` | what is done, what to review, what is next |
| says something about themselves | `remember(key, text)` | "Noted." |
```python faro/agent.py theme={null}
learner = {"learner_id": "{{learner_id}}", "explanation": "{{explanation}}"}
local_tool(
desk.grade_answer,
locked={**learner, "waiting": "{{waiting}}", "helped": "{{helped}}"},
interruption="continue",
)
```
The learner, the language and the exercise waiting are locked. The model sends
only the answer, a grade of four (`correct`, `partly`, `wrong`, `unclear`) and
one line of feedback. Code turns the grade into a result, records the attempt
in SQLite, moves the learner on or not, and says the next line.
**Why it works this way.** The model cannot finish a lesson by saying so. Only
graded answers move progress, and an answer to an exercise that is not waiting
is refused. Grading is the one judgement only a model can make, so it is the
one thing the model decides.
## Two agents, one per language
The library says some lines itself: a read-back, a step's first question. Those
lines belong to an `AgentSpec`, so Faro is two agents built from one template,
`faro_en` and `faro_es`. They share the prompt and the tools.
```python faro/agent.py theme={null}
def agents(self, state: CallState) -> dict[str, AgentSpec]:
return {
f"faro_{lang.lower()}": AgentSpec(
PROMPT,
name=f"faro_{lang.lower()}",
tasks=self.plans[lang],
language=lang.lower(),
timezone=TIMEZONE,
handoffs=("to_spanish",) if lang == "EN" else ("to_english",),
)
for lang in LINES
}
```
A learner who asks to switch is handed to the other agent. The handoff saves
the new `explanation`, so every line code says from then on is in that
language. See [Handoffs](/core/build/handoffs).
A known caller is greeted by the agent of their own language. A `Lookup` in the
prefetch reads the language from their number before the greeting. Nothing
about them is said until they say the number is theirs.
## Read back before it is used
Two tasks hold what must be read back first:
1. `other_number`: a number the caller says. It takes the number as a task `argument` and opens on `check_number`, so code reads it back with no model request.
2. `sign_up`: a new profile. Code reads back the name, the language, the goal and the level, and creates the profile on a yes.
```python faro/agent.py theme={null}
"confirm": ["Shall I create your profile as {{input.name}}, learning {{input.learn}} for {{input.goal}}, at level {{input.level}}?"]
```
`learn`, `goal` and `level` are `Literal`s. A number from outside Spain is
refused by the `Phone` type.
## What a call costs
| Caller says | Who speaks | Model requests |
| - | - | - |
| (call opens) | code: "is your number +34 600 555 666?" | 0 |
| "Yes, that's me." | code: "Hi, Emma" and where she stopped | 1 |
| "Let's carry on." | code: the first exercise | 1 |
| "Un kilo de manzanas, por favor." | code: the model's feedback, then the next exercise | 1 |
| "¿Cuánto cuesta?" | code: feedback and the third exercise | 1 |
| "Quiero pan y leche." | code: "Lesson complete: shopping." | 1 |
## The parts
| unmute-core | Used for |
| - | - |
| Two `AgentSpec`s, `language="en"` and `"es"` | The library's own lines in the learner's language |
| `hand_off` on both adapters | Switching language mid-call |
| `Prefetch`: `CallValue` and a `Lookup` | The caller's number, and the language to greet them in |
| `Greeting` with a fallback `instruction` | The number read back. With no caller ID, the model asks for it. |
| `ToolRegistry(assign=..., replies=...)` | The whole lesson, with no task |
| Locked `{{learner_id}}`, `{{waiting}}`, `{{helped}}` | The model never names the learner or the exercise |
| `TasksSpec` with `arguments`, `opens_with` and `confirm` | A spoken number and a new profile, read back first |
**Best practice.**
1. Keep the lines code says in a table per language, and build one agent per language from it.
2. Save the language in the State on the handoff. Every line code says can then read it.
3. Let the model make only the judgement a model must make. Give it a closed set of answers.
## Try it
The store has three learners. Call as Emma with
`UNMUTE_CALL_START={"call": {"direction": "inbound", "calling_number": "+34600555666"}}`.
1. "Yes." Code greets Emma and says where she stopped.
2. "Let's carry on." Code says the first exercise of "shopping".
3. "Un kilo de manzanas, por favor." Then "¿Cuánto cuesta?" Then "Quiero pan y leche. ¿Cuánto es en total?"
4. "Can you explain in Spanish?" The other agent takes over and puts the exercise again.
Lucía (+34 600 111 222) explains in Spanish. Any other Spanish number is a new
caller, who gets a profile read back and then the first lesson.
## Troubleshooting
### After a switch, the model says the exercise in its own words
The model wrote the first reply after the switch. **Fix:** give each `Handoff`
`opens_with=OpeningTool(tool="continue_lesson")`. Code then puts the exercise again
in the new language, with no model request.
### A hint is said twice
The model said the hint and passed it to `give_hint`. **Fix:** tell it to call
`give_hint` "with no words of your own". Code says the hint from the result.
## Where to go next
Back to the overview, and how to run and check each example.
Every argument of a handoff, on both frameworks.
# Kestrel, a claim intake line
Source: https://unmute.ai/core/examples/kestrel
A task group finds the caller's policy, then code asks every question of a car accident report and reads the whole claim back before filing it.
Kestrel is an inbound claims line for a motor insurer. Sam answers, finds the
caller's policy, takes the report of what happened one question at a time,
reads the whole claim back and files it on the caller's yes. The code is in
`examples/kestrel`.
```mermaid theme={null}
flowchart TD
G[Greeting asks for the policy number] --> M[Main agent: Sam]
M -->|claim group, with what the caller gave| F[find_policy]
F -->|code reads number and birth date back, lookup on yes| T[take_report]
T -->|code asks each question, the model notes answers| T
T -->|code reads the claim back, files on yes| D[Claim number, said by code]
```
## The group
One group, `claim`, runs two steps. The group's `arguments` carry what the
caller said before the group started, so a caller who gives everything at once
hears the read-back at once.
```python kestrel/agent.py theme={null}
{
"name": "claim",
"when": "The caller gives a policy number or a date of birth, or wants to report an accident.",
"steps": ["find_policy", "take_report"],
"context_scope": "shared",
"arguments": ["policy_number", "birth_date"],
}
```
`find_policy` opens with `lookup_policy` on those two values. The lookup has a
`confirm` line, so code asks before it runs:
```python kestrel/agent.py theme={null}
"opens_with": {
"tool": "lookup_policy",
"arguments": {"policy_number": "policy_number", "birth_date": "birth_date"},
},
"finish": [{
"tool": "lookup_policy",
"success": {"found": [True]},
"confirm": ["Is your policy number {{input.policy_number}}, with a date of birth of {{input.birth_date}}?"],
"say": ["Thank you, {{result.first_name}}, I have your policy."],
}],
```
## Code asks every question
`take_report` holds two tools. The model calls `note_facts` with whatever the
caller just said, as typed arguments. Code saves the facts, picks the next
missing one, and says its question.
```python kestrel/agent.py theme={null}
{
"name": "take_report",
"tools": ["note_facts", "file_claim"],
"opens_with": {"tool": "note_facts", "say": ["{{result.next_question}}"]},
"replies": [{"tool": "note_facts", "when": {"complete": [False]}, "say": ["{{result.next_question}}"]}],
"finish": [{
"tool": "file_claim",
"success": {"filed": [True]},
"confirm": ["{{read_back}}"],
"say": [FILED],
}],
}
```
1. The step opens on `note_facts` with nothing noted. Its result's `next_question` is the first question. No model request.
2. The caller answers. The model calls `note_facts(incident_day=..., place=...)` with only what they said. A caller who tells it all in one breath fills several facts in one call.
3. When the report is complete, the model calls `file_claim`. Code says the whole claim, from `read_back` in the State, and files it only on the caller's yes.
The questions come in a fixed order: when, where, what happened, anyone hurt,
police, another driver, which car, can it be driven. A car is picked only from
the cars on the policy.
## Why it works this way
**The model only fills typed fields.** `incident_day` is a date. `injuries` is a
`bool`. `incident_time` is a time or one of four parts of the day.
**Code decides, and code says it.** A day in the future is the tool's rule, not
the argument's. `note_facts` keeps it out of the report and returns
`status: "future_day"`. A reply on the tool turns that into "That day hasn't
happened yet. On which day did it happen?" The model makes one request for the
turn, the call, and says nothing.
**Every read-back is code's.** The caller hears the same claim read-back on
every call. The model never paraphrases the report it is about to file.
**Nothing the caller did not hear is filed.** `file_claim` locks the report,
the policy number and the call's id, and takes nothing from the model. A yes
runs it only while its locked values are the ones read back. A correction
after the read-back changes the report, so code reads the claim back again.
**Each answer is saved as it comes.** `note_facts` merges the new facts into
the report and returns it. Its `assign` rows on the registry save the report
and the read-back as soon as it returns, inside the step:
```python kestrel/agent.py theme={null}
local_tool(
desk.note_facts,
locked={"report": "{{report}}", "policy": "{{policy}}"},
hidden=("report", "read_back"),
),
...
assign={
"note_facts": [
Assign(variable="report", path=("report",)),
Assign(variable="read_back", path=("read_back",)),
]
},
```
The model reads `complete` and `next_question` only. The report and the
read-back are `hidden`: a model that sees the read-back says it in its own
words, before code reads it back.
**Codes and birthdays are typed for speech.** The policy and claim numbers are
`Spelled`, so code says them a character at a time: "K C, 1 0 0, 2 3 1". The
date of birth is a `BirthDate`, said with its year: "5 June 1979".
## What a call costs
| Turn | Who speaks | Model requests |
| - | - | - |
| Greeting | code | 0 |
| Policy number and date of birth read back | code (`confirm`) | 1 |
| "Thank you, Daniel, I have your policy." | code (`say`) | 1 |
| Each of the eight report questions | code (`ToolReply` on `note_facts`) | 1 |
| The whole claim read back | code (`confirm`, from the State) | 1 or 2 |
| "Your claim is filed. Your claim number is K C, 1 0 0, 2 3 1..." | code (`say`) | 1 |
A whole 13 turn claim costs 15 model requests, on both frameworks.
## The parts
| unmute-core | Used for |
| - | - |
| A Pydantic `State` with validators | `PolicyNumber` (one spelling), `Policy`, `Report`, the claim number |
| `local_tool(precheck=...)` | "KP and six digits", answered in code before the number is read back |
| `TasksSpec` in `record` mode, one group | `claim` runs `find_policy` then `take_report` |
| Group `arguments` and `OpeningTool` | What the caller already said opens the first step with its read-back |
| `FinishRule` `confirm` and `say` | Both read-backs, and the lines after the lookup and the filing |
| `ToolReply` | The next question after each answer, and "I can't find a policy" |
| Locked arguments | The call id, the report and the policy number never come from the model |
| `Prefetch` with a `Clock` | Today on the London clock, so "yesterday" becomes a date |
| `IdleNudges` | A patient nudge for a shaken caller who goes quiet |
**Best practice.**
1. When a step asks many questions, keep the order in code and give the model one tool that takes them all as optional typed fields.
2. Say codes letter by letter in code, like "K P, four eight two, nine one three". A model reading "KP482913" may say it as a word.
3. Save a long read-back to the State and use it as the `confirm` line, `{{read_back}}`.
## Try it
The demo desk has two policies. KP482913 is Daniel, born 5 June 1979, with a
blue Toyota Corolla. KP731508 is Priya, born 23 January 1992, with two cars.
1. "It's KP482913, and I was born on the fifth of June 1979." Code reads both back.
2. "Yes." Code says "Thank you, Daniel" and asks when it happened.
3. Answer each question. Try "Yesterday afternoon on the high street, someone reversed into me."
4. After the read-back, say "Actually it was the morning." Code reads the changed claim back.
## Troubleshooting
### The step asks the first question twice
The prompt also tells the model to ask. **Fix:** tell the model the
application asks the next question itself, in the step prompt and in the
tool's docstring.
## Where to go next
Verify a person before saying anything about their account.
Group fields, arguments and what follows a group.
# Nosh, a tools-only finder
Source: https://unmute.ai/core/examples/nosh
One agent and three typed tools find a restaurant near the caller. Code speaks every result, so each caller turn costs one model request.
Nosh rings someone who asked for help finding a place to eat. It finds the area
they mean, reads it back, lists places there, and says a picked place's
address, price and today's hours. It changes nothing anywhere, so nothing needs
a yes. The code is in `examples/nosh`.
```mermaid theme={null}
flowchart LR
G[Greeting asks where] --> A[find_area]
A -->|"code: So that's Barri Gòtic, right?"| P[find_places]
A -->|"code: no craving yet, asks for one"| P
P -->|"code: I found A, B and C"| D[place_details]
D -->|"code: address, price, hours"| D
D --> E[end_call: code says goodbye]
```
## Who asked for the call
Nosh rings someone back, so it must know who. The dispatch sends their name as a
required start value:
```python nosh/agent.py theme={null}
GREETING = Greeting(text=f"Hey {{{{customer_name}}}}, it's Nosh! You wanted a hand finding somewhere good. {ASK_WHERE}")
CALL_START = {"customer_name": "required"}
GREETING.check(None, CALL_START)
state = CallState(State, call_start=CALL_START, call=call)
save_call_start(state, dispatched)
```
`customer_name` is a `str` of 1 to 40 characters, trimmed. A dispatch without
it is refused with `Missing call_start fields: customer_name`, and an empty or
too long one with `call_start: customer_name: ...`. The call never reaches the
greeting. The prompt reads the name too: `you rang {{customer_name}}`.
`GREETING.check(None, CALL_START)` runs at import: a greeting that names a value
nothing fills before it fails then, not on a call.
## The registry
Nosh has no tasks. It is one `AgentSpec` with a `ToolRegistry`. The registry
holds the tools, what each result saves, and the line code says for it.
```python nosh/agent.py theme={null}
ToolRegistry(
[
local_tool(finder.find_area, announce=["Let me see.", "Hmm, let me look."]),
local_tool(finder.find_places, locked={"spot": "{{spot}}"}),
local_tool(finder.place_details, locked={"offer": "{{offer}}"}),
local_tool(end_call, effect="ends_conversation", announce=GOODBYE, announce_wait=True),
],
state=State,
assign={
"find_area": [Assign(variable="spot", path=("spot",)), Assign(variable="offer", path=("offer",))],
"find_places": [Assign(variable="offer", path=("offer",))],
"place_details": [Assign(variable="details", path=("details",))],
},
replies=[
ToolReply(tool="find_area", when={"found": [True], "ask_craving": [False]}, say=["So that's {{result.formatted_address}}, right?"]),
ToolReply(tool="find_area", when={"found": [True], "ask_craving": [True]}, say=["So that's {{result.formatted_address}}. What are you in the mood for? ..."]),
ToolReply(tool="find_places", when={"found": [True]}, say=["I found {{result.listed}}. Do any of those sound good?"]),
ToolReply(tool="place_details", when={"found": [True]}, say=["{{result.spoken}}"]),
],
)
```
The real file has a reply for every result shape, the "not found" ones too.
## Why it works this way
**Every result speaks.** Each tool returns a Pydantic model that carries the
next line. The registry checks the result, saves its values and says the line.
The model is asked for no reply. So a caller turn costs one model request: the
one that picks the tool.
**What the caller agreed to is locked.** A search runs only on the spot read
back to the caller: `find_places` locks `{{spot}}`. The model cannot search
somewhere else by mistake. A new area replaces the spot, and its result clears
the old offer.
**The read-back carries the next step.** With no craving and no exact address,
`find_area` returns `ask_craving: true`, and its line asks for one. A "yes" to
the read-back never makes the model invent a craving. A craving said with the
area rides on the spot, so `find_places` needs no craving on the caller's yes.
**A pick must have been offered.** `place_details` locks `{{offer}}` and takes
only an id like `p1`. An id that was never offered raises `ToolError`, with the
offer listed, so the model can ask the caller again.
**Words come from data.** Prices and hours are never worded by the model.
`speech.py` turns the place service's fields into words. Nothing is said that
the service did not return.
**The goodbye is code's.** `end_call` has an `announce` line and
`announce_wait=True`. The line plays in full, then the call ends.
## What a call costs
| Caller says | Who speaks | Model requests |
| - | - | - |
| (call opens) | code: the greeting names them and asks where | 0 |
| "Tapas in the Gothic Quarter." | code: the area read back | 1 |
| "Yes." | code: three places | 1 |
| "The first one." | code: address, price, hours | 1 |
| "What's their number?" | the model, from the saved details | 1 |
| "That's all, thanks." | code: the goodbye | 1 |
## The parts
| unmute-core | Used for |
| - | - |
| `CallState(call_start=...)` | The caller's name, required from the dispatch |
| `AgentSpec(tools=...)` | An agent with no tasks |
| `ToolRegistry(assign=..., replies=...)` | What each result saves, and the line code says for it |
| `local_tool(..., locked=...)` | The spot and the offer go to the tools whole, never from the model |
| `ToolError` | An id that was never offered, in words the model acts on |
| `local_tool(..., announce=...)` | A short line while the place service answers |
| `effect="ends_conversation"` with `announce_wait=True` | The goodbye, then the end of the call |
**Best practice.**
1. Give each result shape its own `ToolReply`, keyed by a field like `found`.
2. Save the result as a typed value, then lock it into the next tool. The model never copies an id.
3. Keep the spoken text in the result, and say it with `{{result.spoken}}`. Build it in code from the data.
## Try it
Without `TOOLS_API_KEY`, Nosh answers from demo places in Barcelona. The
project's `.env.example` sets `UNMUTE_CALL_START` to `{"customer_name": "Sam"}`.
1. "Tapas in the Gothic Quarter, Barcelona." Code reads the area back.
2. "Yes." Code lists three places.
3. "The first one." Code says its address, price and today's hours.
4. "Actually, what about the Born instead?" A new area takes back the old list.
5. "Sushi." Nothing is found, on purpose. Code offers to look wider.
## Troubleshooting
### The model lists the places in its own words
The tool's docstring does not say who speaks the result. **Fix:** end the
docstring with "The application says them." The model reads it as the tool's
description.
### A pick of "the second one" is refused
The model sent the place's name, not its id. **Fix:** describe the parameter as
"The id of the place they picked from the offer, like p1." The refusal lists
the offer, so the model corrects itself on the same turn.
## Where to go next
Tasks that ask every question in code, and a read-back before filing.
Every rule of `Assign` and `ToolReply` on a registry.
# Example agents
Source: https://unmute.ai/core/examples/overview
Four working voice agents on unmute-core, each a different shape of call, each on LiveKit and Pipecat.
Four example agents show unmute-core on calls that are nothing like the salon.
Each one is a real project in the repo's `examples/` folder. Each one runs on
LiveKit and on Pipecat from the same code, and each one is checked with whole
scripted calls on its real model.
Use them when:
* You want to see a whole agent, not one feature.
* Your call has a shape the salon does not have: a long intake, an outbound call, a tools-only finder, two languages.
* You want to copy a working setup for SLNG speech and Gemini in the EU.
## Pick the closest one
| Example | The call | The shape | What to copy |
| - | - | - | - |
| [Nosh](/core/examples/nosh) | Find a restaurant or bar near the caller | One agent, three tools, no tasks | Results that save values and speak their own line |
| [Kestrel](/core/examples/kestrel) | Report a car accident to an insurer | A task group: find the policy, then a long report | Code asks every question, the model only notes answers |
| [Wasla](/core/examples/wasla) | Remind a customer of an overdue payment | Outbound, three task groups | Verify first, say nothing about the account before |
| [Faro](/core/examples/faro) | A language lesson on the phone | Two agents, one per language, with handoffs | The model grades, code teaches and keeps progress |
All four follow one idea: **type the agent's path**. The model reads what the
caller meant and turns it into a typed tool call. Code checks it, saves it,
and says the next line. [Type the path](/core/examples/typed-path) explains it
and how to apply it to your own agent.
## What they have in common
```mermaid theme={null}
flowchart TD
P["Shared package: state, tools, tasks, prompts, APP"] --> L["livekit/agent.py"]
P --> C["pipecat/bot.py"]
V["voice-stack: speech, model, pace, greeting"] --> L
V --> C
```
1. **One package per agent.** It holds the `State`, the tools, the tasks and the prompts. It imports no framework.
2. **Two small projects.** `livekit/agent.py` and `pipecat/bot.py` are about 20 lines each. They import the package's `APP` and run it.
3. **One voice stack.** `examples/voice-stack` builds the framework side once: SLNG speech to text and text to speech, Gemini on Vertex AI, the turn pace, the greeting and the handoffs. Use it as a starting point for your own pipeline.
| Part | Default |
| - | - |
| Speech to text | Soniox `soniox/speech-ai:rt-v5`, through SLNG |
| Text to speech | Fish Audio `slng/fish/tts:s2.1-pro`, through SLNG |
| SLNG region | `eu-north`. Set `SLNG_WORLD_PART` to change it. |
| Model | Gemini Flash Lite on Vertex AI's `eu` endpoint, with a Vertex API key |
Every value can be changed in the project's `.env`. The `.env.example` of each
project lists them.
## Run one
```bash LiveKit theme={null}
cd examples/nosh/livekit
cp .env.example .env # SLNG_API_KEY and GOOGLE_API_KEY
uv sync
lk agent console agent.py
```
```bash Pipecat theme={null}
cd examples/nosh/pipecat
cp .env.example .env # SLNG_API_KEY and GOOGLE_API_KEY
uv sync
uv run bot.py -t webrtc # then open http://localhost:7860
```
Each example's README lists what to say on a call, and the demo data it ships with.
## Check one
Every example has whole calls written as JSON in its `scenarios/` folder. A
scripted caller says each line, and the check reads what the agent said, the
tools it called, the model requests each turn made, and the state at the end.
```bash theme={null}
scripts/converse-examples.sh examples/kestrel/livekit # typed caller, real model
scripts/converse-examples.sh --audio examples/kestrel/pipecat # spoken caller, the whole voice pipeline
```
A scenario can also send its start values the way a real dispatch does: in the
LiveKit job's metadata, or in the Pipecat runner's request body. A scenario
with `refused` checks that a call with a missing or wrong start value never
starts, and that the log says why.
The `--audio` run speaks each caller line with SLNG text to speech and sends it
through the real pipeline: voice detection, turn detection, speech to text, the
model and text to speech.
## In this section
Spend the model on understanding, and let code do the rest.
One agent, three tools, and one model request per caller turn.
Code asks every question and reads the whole claim back.
Verify the person first, then record a promise or a concern.
One agent per language, and a handoff to switch.
# Type the agent's path
Source: https://unmute.ai/core/examples/typed-path
Let the model understand the caller, and let typed tools and code decide, save and speak. Fewer tokens, the same call every time.
A typed path is an agent where every step that changes the call is a typed
tool call, and code says what comes next. The model reads what the caller
meant. Code checks it, saves it and speaks the next line.
```python grade.py theme={null}
from typing import Annotated, Literal
from pydantic import BaseModel, Field
from unmute_core.tools import Assign, ToolRegistry, ToolReply, local_tool
class Graded(BaseModel):
said: str
waiting: str | None
def grade_answer(
answer: Annotated[str, Field(min_length=1, max_length=600)],
grade: Literal["correct", "partly", "wrong", "unclear"],
waiting: str,
) -> Graded:
"""Grade the learner's answer to the exercise waiting."""
...
registry = ToolRegistry(
[local_tool(grade_answer, locked={"waiting": "{{waiting}}"})],
state=State,
assign={"grade_answer": [Assign(variable="waiting", path=("waiting",))]},
replies=[ToolReply(tool="grade_answer", say=["{{result.said}}"])],
)
```
The model sends one value it must choose, a grade of four. Code knows which
exercise is waiting, records the result, picks the next exercise and says it.
The caller hears the next line with no second model request.
## Why type the path
1. **Fewer tokens.** A tool result with a `ToolReply` asks the model for no reply. Most caller turns cost one model request: the one that reads the caller.
2. **The same call every time.** A receipt, a read-back or a question said by code has the same words on every call, and on both frameworks.
3. **The model cannot invent an outcome.** A booking, a claim or a promise exists only when a tool returned it. The model can only ask for it.
4. **An open standard.** The path is data: Pydantic types, task rows and reply rows. Another runner, a test or a tool can read it without a model.
## Who decides what
| Decision | Who makes it | With |
| - | - | - |
| What the caller meant | the model | its tool call |
| A value from a closed set | the model, typed | `Literal`, `Enum` |
| Whether a value is valid | code | Pydantic constraints and validators |
| Values the call starts with | the dispatch, typed | `call_start` values marked `required` |
| Values the caller never says | code | [locked arguments](/core/build/tools#locked-arguments) |
| What a result saves | code | `Assign` rows |
| The next line | code | `ToolReply`, `OpeningTool`, `announce` |
| Whether an effect happens | the caller | a `FinishRule` `confirm` line and their yes |
| A short answer to a side question | the model | its own words |
## The rules the examples follow
**Require what the call cannot run without.** Values the call starts with, like
an account id or a customer's name, are `call_start` values marked `required`,
with a type. A dispatch that lacks one, or sends a wrong one, never reaches the
greeting. See [Start values](/core/build/call-lifecycle#start-values).
**Type every argument.** A tool's parameters are Pydantic types with a
description the model reads. A wrong value is refused before the tool runs, and
the reason goes back to the model so it can ask again.
```python state.py theme={null}
PolicyNumber = Annotated[
Spelled,
AfterValidator(policy_number),
Field(description="The policy number: KP and six digits, like KP482913. Never guess a digit."),
]
```
A type also says how code speaks a value. `Spelled` is said a character at a
time, `BirthDate` with its year, `Phone` in its groups, a `date` from today. See
[Value types](/core/build/state#value-types).
Kestrel types the policy number's spelling. Faro types a grade, a level and a
learning goal as `Literal`s. A rule about the request, like Wasla's payment
window, is not a type: it is the tool's, as below.
**Let the result speak.** Give each result a `ToolReply`. The line can read
`{{result.}}` and State values. A value is said by its JSON Schema
`format`, so a date reads as a day. See [Save a result and speak it](/core/build/tools#save-a-result-and-speak-it).
Hide the words a reply says from the model with `hidden=("said",)` on the tool.
A model that reads a line may say it again in its own words.
**Let the result save.** An `Assign` row saves a result field into the State.
The next tool reads it as a locked argument, so the model never carries it.
Nosh saves the places it offered, and `place_details` refuses any id that was
not offered.
**Lock what the caller does not choose.** Account ids, the call's id, the
report so far and the exercise waiting are `locked`. The model never sees them
and cannot change them.
**Read back before an effect.** A tool that changes something has a
`FinishRule` with a `confirm` line. Code says it, and the tool runs only on the
caller's yes to the same input. See [Ask before a closing tool runs](/core/build/tasks/confirm-in-code#ask-before-a-closing-tool-runs).
**Open each step in code.** A step that opens with an `OpeningTool`, or with
`opening: listen` and an `announce` line, says its first line with no model
request. A group's `arguments` carry what the caller already said into the
first step, so its read-back can play at once.
**Decide in the tool, say it in code.** An argument type says what the caller
meant: a date, a phone number, a spelled id. A rule about the request, like
"not in the future", belongs to the tool. The tool returns a typed outcome, a
`Literal` field, and a reply on the tool turns each outcome into a line. Code
says it, and the turn costs one model request: the call. A validator that
raises would cost two more: one for the model to say the error, and a finish
check after it. See [Replies on the tool itself](/core/reference/tools#replies-on-the-tool-itself).
A tool that reads its input back for a yes checks the rule in a `precheck`, so
it answers before the read-back. See [Check a rule before the tool runs](/core/reference/tools#check-a-rule-before-the-tool-runs).
```python claims.py theme={null}
future = incident_day is not None and incident_day > today()
...
if future:
noted.status = "future_day"
```
**Refuse in code when the model must decide.** Raise `ToolError` with a
message that names what to do next. The model reads it and chooses what to ask.
```python finder.py theme={null}
if picked is None:
ids = ", ".join(f"{p.id} ({p.name})" for p in offer.places)
raise ToolError(f"{place} was never offered. The offer is: {ids}.")
```
## What it costs
Each example's scenarios count the model requests of every caller turn. These
are the whole scripted calls, typed by the caller, on the real model.
| Example | Calls | Caller turns | Model requests, LiveKit | Model requests, Pipecat |
| - | - | - | - | - |
| Nosh | 3 | 15 | 15 | 15 |
| Kestrel | 3 | 24 | 29 | 28 |
| Wasla | 5 | 26 | 28 | 27 |
| Faro | 4 | 21 | 22 | 22 |
A request above one per turn is a turn where the model asked for a tool, read
the refusal, and asked again, or where a step opened with a model reply.
## Where the model still talks
1. A question off the path, like "Do you take cards?" Keep these short in the prompt.
2. A goodbye. Or give the end tool an `announce` line with `announce_wait=True`, and the model says nothing.
3. A step whose first line depends on what was said. Prefer an `OpeningTool` when a tool can compute it.
## Troubleshooting
### The model says the line code already said
The prompt tells the model to say something a reply also says. **Fix:** tell
the model in the tool's docstring that the application says the result. The
model reads the docstring as the tool's description.
```python theme={null}
def find_places(...) -> FoundPlaces:
"""Search places at the location the caller agreed to. The application says them."""
```
### A turn makes two requests where you expected one
The tool was refused, or no `ToolReply` matched its result. **Fix:** give every
result shape a reply, including the "not found" one. Read the refusal from the
`tool.refused` event. See [Watch tool calls](/core/build/tools#watch-tool-calls).
## Where to go next
The smallest typed path: three tools and their replies.
Every rule of `ToolReply`, `FinishRule` and `OpeningTool`.
# Wasla, an outbound payment reminder
Source: https://unmute.ai/core/examples/wasla
An outbound call that verifies the person first, says nothing about the account before, and records one outcome only on the holder's yes.
Wasla calls the holder of one overdue payment. Lina checks it is them by their
date of birth, says what is overdue, and records one outcome: a promise to pay,
a callback, a wrong number, or a concern in the holder's own words. The code is
in `examples/wasla`.
```mermaid theme={null}
flowchart TD
G["Greeting: Am I speaking with Layla Haddad?"] --> M[Main agent: Lina]
M -->|it's them| I[identify: date of birth, read back by code]
I -->|matched: account details saved| T[talk_account]
T --> P[promise, read back, recorded]
T --> C[concern, read back, recorded]
T --> B[callback, read back, recorded]
M -->|someone else| CB[callback, then the call ends]
M -->|wrong number| W[off the list on a yes, then the call ends]
```
## The account is a required input
An outbound call about nothing must never ring anyone. So the account id is a
required start value, typed as `WA` and four digits.
```python wasla/agent.py theme={null}
AccountId = Annotated[str, StringConstraints(pattern=r"^WA-\d{4}$")]
state = CallState(State, confirm=CONFIRM, call_start={"account_id": "required"}, call=call)
save_call_start(state, dispatched)
await self.prefetch.run(state)
if state.plain("first_name") is None:
raise CallStartError(f"call_start: account_id: no account {state.plain('account_id')}")
```
| The dispatch sends | What happens |
| - | - |
| `{"account_id": "WA-1001"}` | The call starts. The greeting names Layla Haddad. |
| `{}`, or no `call_start` | Refused: `Missing call_start fields: account_id` |
| `{"account_id": "1001"}` | Refused: `call_start: account_id: String should match pattern ...` |
| `{"account_id": "WA-9999"}` | Refused: `call_start: account_id: no account WA-9999` |
A refused call never reaches the greeting. The voice stack logs the reason and
ends the job on LiveKit, or builds no pipeline on Pipecat. See
[Start values](/core/build/call-lifecycle#start-values).
## Nothing before the check
The call is about money, so nothing may reach the wrong person. Only the
holder's name is read before the greeting:
```python wasla/agent.py theme={null}
Prefetch(
[
Clock("today", TIMEZONE, {"today": "date", "weekday": "day_of_week"}),
Lookup("account", opened, {name: name for name in ("first_name", "last_name", "deadline")}, inputs=["account_id"]),
],
state=State,
)
```
The amount, the shop and the dates come back only from a matching date of
birth. The `identify` step saves them from `verify_holder`'s result:
```python wasla/agent.py theme={null}
"assign": [
{"variable": "birth_date", "path": ["birth_date"]},
{"variable": "amount_words", "path": ["amount_words"]},
{"variable": "merchant", "path": ["merchant"]},
],
```
Until then, every prompt reads those values as empty. A relative who answers
cannot hear them, whatever the model does.
**Why it works this way.** A prompt rule like "do not say the amount before the
check" can fail. A value the State does not hold cannot be said. The check is a
tool: three wrong dates lock the account, and code says the support line.
## Every outcome is read back
Each write has a `FinishRule` with a `confirm` line. Code says it, and the
write runs only when the holder heard it and said yes.
```python wasla/agent.py theme={null}
{
"tool": "record_promise",
"success": {"status": ["PTP"]},
"confirm": ["Shall I record your promise to pay {{amount_words}} for {{input.day}}?"],
"say": ["Thank you. Your promise to pay {{result.when}} is recorded. ..."],
}
```
A concern is one tool with four kinds. One `confirm` line serves them all, and
each kind gets its own receipt, picked by the result's `kind`:
```python wasla/agent.py theme={null}
def concern_rule(kind: str) -> dict[str, Any]:
return {
"tool": "note_concern",
"success": {"kind": [kind]},
"confirm": ["Shall I pass this to our team as a {{input.kind}}: {{input.note}}?"],
"say": [CONCERN_SAID[kind]],
}
```
## The window is the tool's rule
```python wasla/ledger.py theme={null}
def outside_window(day: date) -> Recorded | None:
if day < today():
return Recorded(status="past_day")
deadline = today() + timedelta(days=WINDOW_DAYS)
if day > deadline:
return Recorded(status="after_deadline", when=words.day(deadline))
return None
```
```python wasla/agent.py theme={null}
local_tool(ledger.record_promise, locked=LOCKED, precheck=outside_window, replies=OUTSIDE_WINDOW)
```
A day outside the ten-day window is answered by the tool's `precheck`, before
the promise is read back. Its reply says "I can only note a day up to Sunday
the 25th of October", with no model request. A concern is a `Literal` of four
kinds. The amount is said by code as "four hundred thirty-four dirhams and fifty
fils". The model never turns a number into speech.
## Three groups
| Group | Steps | Then |
| - | - | - |
| `account` | `identify`, then `talk_account` | back to Lina |
| `callback` | `take_callback`, with `arguments` for a day and time already said | the call ends |
| `wrong_number` | `take_off_list` | the call ends |
1. `identify` opens with `opening: listen` and an `announce` line. Code asks for the date of birth, with no model request.
2. `skip_when_confirmed` skips `identify` when the date of birth is already confirmed in this call.
3. A group with `then: "end"` ends the call once its receipt has played.
## The parts
| unmute-core | Used for |
| - | - |
| `Prefetch` with a `Clock` and a `Lookup` | Today in Dubai, and whose account it is, before the greeting |
| `Greeting` with placeholders | `Am I speaking with {{first_name}} {{last_name}}?`, checked against the prefetch |
| `CallState(call_start=...)` and `save_call_start` | The account the call is about, required and typed |
| `CallState(confirm=...)` | Only `identify` confirms the date of birth |
| `FinishRule` per kind | One read-back, four receipts |
| Group `arguments` and `OpeningTool` | A callback day and time already given are read back at once |
| Locked `{{account_id}}` and `{{call.session_id}}` | The model never names the account or the call a write goes to |
**Best practice.**
1. Keep sensitive values out of the State until a tool proves who is on the line. Then save them from that tool's result.
2. Put business rules in argument types, with an error message that says what to tell the caller.
3. One tool with a `Literal` kind and one `FinishRule` per kind beats one tool per kind. The model picks among fewer tools.
## Try it
The project's `.env.example` sets `UNMUTE_CALL_START` to
`{"account_id": "WA-1001"}`: Layla Haddad, born 14 March 1990. Use
`{"account_id": "WA-1002"}` for Omar Khalil, born 2 November 1985.
1. "Yes, speaking." Code asks for the date of birth.
2. "The fourteenth of March, 1990." Code reads it back.
3. "Yes." Then "Yes, go ahead." Code says the amount.
4. "Can I pay this Sunday?" Code reads the promise back, and records it on your yes.
5. Call again and say "He's not here, call back tomorrow at five." Code reads the callback back and ends the call.
## Troubleshooting
### The step that confirms a value is never reached
A step that confirms a value needs a `when`, even inside a group. **Fix:** give
it a `when` that says it is only for a correction.
## Where to go next
One agent per language, and a handoff to switch.
Read values in before the greeting.
# LiveKit
Source: https://unmute.ai/core/frameworks/livekit
UnmuteAgent runs tools, tasks, the model call and telemetry on a LiveKit AgentSession.
`unmute_core.livekit` puts the library's tools, tasks, model call and telemetry on LiveKit Agents. Its main class, `UnmuteAgent`, is a LiveKit `Agent`, so you start it on your own `AgentSession`. You keep your room, your speech and your model.
Install the library and the plugins the quickstart uses:
```bash theme={null}
uv add "unmute-core[livekit]" livekit-plugins-google livekit-plugins-silero livekit-plugins-slng
```
## Quickstart
```python agent.py theme={null}
import os
from livekit.agents import AgentServer, AgentSession, JobContext, cli
from livekit.plugins import google, silero, slng
from pydantic import BaseModel
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent
from unmute_core.state import CallState
from unmute_core.tasks import TaskPlan, TasksSpec
from unmute_core.telemetry import Langfuse, Telemetry
from unmute_core.tools import ToolRegistry
SLNG_KEY = os.environ["SLNG_API_KEY"]
SLNG_HOST = f"{os.environ['SLNG_WORLD_PART']}.api.slng.ai"
VOICE = "8d8aec63a56c460cb7def795bdf754fa"
class State(BaseModel):
note: str | None = None
tasks_spec = TasksSpec.model_validate(
{
"mode": "record",
"tasks": [
{
"name": "take_note",
"when": "The caller wants to leave a note.",
"instructions": "Ask what the note says, then save it.",
"assign": [{"variable": "note", "path": ["note"]}],
}
],
}
)
plan = TaskPlan(tasks_spec, state=State, tools=ToolRegistry([]))
server = AgentServer()
@server.rtc_session()
async def entrypoint(ctx: JobContext) -> None:
state = CallState(State)
spec = AgentSpec("You are the receptionist of a hair salon.", tasks=plan)
agent = UnmuteAgent(
spec,
state=state,
telemetry=Telemetry(Langfuse.from_env(), agent="salon", call_id=state.call.session_id),
)
stt = slng.STT(
api_key=SLNG_KEY, slng_base_url=SLNG_HOST, model="soniox/speech-ai:rt-v5", language="en"
)
session = AgentSession(
stt=stt,
llm=google.LLM(model="gemini-3.1-flash-lite"),
tts=slng.TTS(
api_key=SLNG_KEY,
slng_base_url=SLNG_HOST,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language="en",
),
vad=silero.VAD.load(),
)
stt.attach_to_session(session)
await session.start(agent=agent, room=ctx.room)
if __name__ == "__main__":
cli.run_app(server)
```
1. The `AgentSpec` says what the agent is, the same way on LiveKit and Pipecat. See [AgentSpec](/core/reference/agent-spec).
2. `UnmuteAgent` adds the call's state, hooks and telemetry. It takes LiveKit's own `Agent` options too.
3. The library builds no part of the pipeline. You choose the speech to text, the text to speech and the model. Here speech runs on SLNG: Soniox hears the caller and Fish Audio speaks. See [SLNG](/core/models/slng).
For a realtime model, see [Realtime](/core/models/realtime).
## Use your own model call
With no `model` in the spec, the agent runs on the session's LLM. To use another provider, give the spec a `ModelCall` and leave `llm` out of the session. This is the SLNG Context Router:
```python theme={null}
from unmute_core.slng import OpenAIEndpoint, RouterConfig, RouterModelCall
config = RouterConfig.single(
"gpt-5.6-luna",
OpenAIEndpoint(url="https://api.openai.com/v1", api_key=os.environ["OPENAI_API_KEY"]),
)
model = RouterModelCall(state.call, model="gpt-5.6-luna", config=config)
agent = UnmuteAgent(AgentSpec("...", tasks=plan, model=model), state=state)
```
1. Each request carries your own router config, so the model runs on your own OpenAI key.
2. The session retries the model call as it retries its own LLM. The agent closes it when the session closes.
3. To keep a LiveKit plugin instead, pass `AgentSpec(model=LiveKitModel(plugin))`.
See [Model call](/core/models/model-call) for the interface and [SLNG](/core/models/slng) for the router.
## Open and end the call
```python theme={null}
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.livekit import max_duration, open_call
call = CallHooks(state, hooks=hooks, prefetch=prefetch)
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan), call=call)
await session.start(agent=agent, room=ctx.room)
await open_call(session, Greeting(text="Hi, thanks for calling.", interruptible=False), call)
max_duration(session, 20 * 60, call=call)
```
1. `open_call` turns the caller's audio off, runs the `before_call` hooks and the prefetch, then greets. A failed check says the failure line and hangs up instead.
2. The caller's audio comes back when the agent starts to speak, or when the greeting ends with `interruptible=False`.
3. The session's close ends the call. The job's shutdown waits for the held saves, the models and the telemetry to close. The end reads `caller_hung_up`, `agent_ended` or `max_duration`.
On a phone call, read the caller's number with `sip_call_info`. See [Phone calls](/core/telephony). The events and the failure line are in [The call's life](/core/build/call-lifecycle).
## Add LiveKit tools and MCP
`native_tools` gives the main agent LiveKit tools as they are. A LiveKit MCP toolset is one:
```python theme={null}
from livekit.agents import mcp
crm = mcp.MCPToolset(id="crm", mcp_server=mcp.MCPServerHTTP(url="https://crm.example.com/mcp"))
agent = UnmuteAgent(spec, state=state, native_tools=[crm])
```
1. The main agent gets every tool you pass.
2. A step gets only the toolsets its task lists, by id: `TaskSpec(native_tools=("crm",), ...)`.
## Before you ship
1. Build one `AgentSpec`, one `UnmuteAgent`, one `Telemetry` and one `ModelCall` per call. A model call shared across calls is closed under the others.
2. A subclass that overrides `on_enter` or `tts_node` calls `super()`, or the spans stop.
3. Give the spec `tools` or `tasks`, not both. The task plan holds every tool.
Every other rule is in [Rules to know](/core/reference/livekit#rules-to-know).
## Where to go next
Every argument, how a call runs inside, and every rule.
Turn pace, interruption and idle nudges on LiveKit.
Move the call between agents, each with its own model and voice.
Call start values, events, the failure line and the end.
Use one piece on a plain Agent.
# Pipecat
Source: https://unmute.ai/core/frameworks/pipecat
UnmuteFlows runs tools, tasks, the model call and telemetry in a Pipecat pipeline.
`unmute_core.pipecat` puts the library's tools, tasks, model call and telemetry in a Pipecat pipeline. Its main class, `UnmuteFlows`, runs the tasks of one call. You keep your transport, your speech and your model.
Install the library and the plugins the quickstart uses:
```bash theme={null}
uv add "unmute-core[pipecat]" "pipecat-ai[openai,runner,silero,webrtc]" pipecat-slng
```
## Quickstart
```python agent.py theme={null}
import os
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.frames.frames import LLMUpdateSettingsFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
LLMContextAggregatorPair,
LLMUserAggregatorParams,
)
from pipecat.runner.types import RunnerArguments
from pipecat.runner.utils import create_transport
from pipecat.services.openai.llm import OpenAILLMService
from pipecat.services.settings import LLMSettings
from pipecat.transcriptions.language import Language
from pipecat.transports.base_transport import TransportParams
from pipecat.workers.runner import WorkerRunner
from pipecat_slng import SlngSTTService, SlngTTSService
from pydantic import BaseModel
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows
from unmute_core.state import CallState
from unmute_core.tasks import TaskPlan, TasksSpec
from unmute_core.tools import ToolRegistry
SLNG_KEY = os.environ["SLNG_API_KEY"]
WORLD_PART = os.getenv("SLNG_WORLD_PART", "eu-north")
class State(BaseModel):
note: str | None = None
tasks_spec = TasksSpec.model_validate(
{
"mode": "record",
"tasks": [
{
"name": "take_note",
"when": "The caller wants to leave a note.",
"instructions": "Ask what the note says, then save it.",
"assign": [{"variable": "note", "path": ["note"]}],
}
],
}
)
plan = TaskPlan(tasks_spec, state=State, tools=ToolRegistry([]))
async def bot(runner_args: RunnerArguments) -> None:
params = TransportParams(audio_in_enabled=True, audio_out_enabled=True)
transport = await create_transport(runner_args, {"webrtc": lambda: params})
state = CallState(State)
settings = OpenAILLMService.Settings(model="gpt-5.6-terra", system_instruction="")
llm = OpenAILLMService(settings=settings)
context = LLMContext()
aggregators = LLMContextAggregatorPair(
context, user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer())
)
spec = AgentSpec("You are the receptionist of a hair salon.", tasks=plan)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
flows.install()
pipeline = Pipeline(
[
transport.input(),
SlngSTTService(
api_key=SLNG_KEY,
world_part=WORLD_PART,
model="soniox/speech-ai:rt-v5",
language=Language.EN,
),
aggregators.user(),
llm,
SlngTTSService(
api_key=SLNG_KEY,
world_part=WORLD_PART,
model="slng/fish/tts:s2.1-pro",
voice="8d8aec63a56c460cb7def795bdf754fa",
language=Language.EN,
),
transport.output(),
aggregators.assistant(),
]
)
worker = PipelineWorker(pipeline)
@transport.event_handler("on_client_connected")
async def on_connected(transport, client):
delta = LLMSettings(system_instruction=flows.main_instruction())
await worker.queue_frame(LLMUpdateSettingsFrame(delta=delta))
runner = WorkerRunner(handle_sigint=runner_args.handle_sigint)
await runner.add_workers(worker)
await runner.run()
if __name__ == "__main__":
from pipecat.runner.run import main
main()
```
1. The `AgentSpec` says what the agent is, the same way on Pipecat and LiveKit. See [AgentSpec](/core/reference/agent-spec).
2. `UnmuteFlows` adds the call's state, hooks and telemetry. `install()` puts its tools on the context, and `main_instruction()` is the prompt the LLM starts with.
3. The library builds no part of the pipeline. Here speech runs on SLNG: Soniox hears the caller and Fish Audio speaks. See [SLNG](/core/models/slng).
To trace the call, add `telemetry=` and a `TelemetryObserver`, as [Telemetry](/core/observe/telemetry) shows. For OpenAI's realtime or live service, see [Realtime](/core/models/realtime).
## Use your own model call
A native Pipecat LLM service gets its prompts filled by `UnmuteFlows`. To send each request through a `ModelCall`, like the SLNG Context Router, use `ModelCallLLMService` as the LLM:
```python theme={null}
from unmute_core.pipecat import ModelCallLLMService
llm = ModelCallLLMService(router, state=state)
```
1. The service gets the prompts unfilled, with the prompt site of each request. The `ModelCall` decides who fills them.
2. A model error after the reply began does not fail the call. The reply ends as it stands.
3. The service closes each model call it was given when the pipeline ends.
See [Model call](/core/models/model-call) for the interface and [SLNG](/core/models/slng) for the router.
## Open and end the call
```python theme={null}
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.pipecat import max_duration, open_call
call = CallHooks(state, prefetch=prefetch)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, call=call)
@transport.event_handler("on_client_connected")
async def on_connected(transport, client):
greeting = Greeting(text="Hi, thanks for calling.")
await open_call(worker, greeting, call, context=context, transport=transport)
max_duration(worker, 20 * 60, call=call)
await runner.run()
end = await call.end("ended")
await telemetry.close(state=state, reason=end.reason)
```
1. `open_call` runs the `ready` checks and the prefetch, then queues the greeting. A failed check says the failure line and ends the call.
2. `transport=` notes the caller hanging up, so the end reads `caller_hung_up`. Your own `on_client_disconnected` handler still ends the pipeline.
3. `call.end` settles the steps' held saves. Call it after `runner.run()` and before the telemetry closes.
To hold the caller until the greeting plays, add a `GreetingHold`. On a phone call, read the caller's number with `telephony_call_info`. See [Phone calls](/core/telephony) and [The call's life](/core/build/call-lifecycle).
## Add Pipecat tools, MCP and an end-call tool
`native_tools` are Pipecat `FunctionSchema`s with their own handlers. A Pipecat MCP client needs no new class:
```python theme={null}
from pipecat.services.mcp_service import MCPClient
from unmute_core.pipecat import end_call_tool
tools = await MCPClient(...).tools()
ending = end_call_tool(
"End the call once the caller says they are done. In the same reply as this call, "
"and before it, say one short goodbye in your own words.",
"Thanks for calling. Goodbye.",
lambda: flows.reply_text,
)
flows = UnmuteFlows(..., native_tools=[*tools.standard_tools, ending])
```
1. The main agent gets every tool you pass, like a handoff tool. A step gets only the names its task lists: `TaskSpec(native_tools=("get_customer",), ...)`.
2. The end-call tool ends the call after one model request. The goodbye rides in the reply that calls it.
3. When that reply has no words, the tool says the goodbye you give it.
## Before you ship
1. Build one `UnmuteFlows`, one `Telemetry` and one `ModelCall` per call. A model call shared across calls is closed under the others.
2. With telemetry, set `PipelineParams(enable_metrics=True, enable_usage_metrics=True)` and keep Pipecat's own `enable_tracing` off.
3. On a phone call over a carrier line, set the pipeline's audio in and out sample rates to 8000.
Every other rule is in [Rules to know](/core/reference/pipecat#rules-to-know).
## Where to go next
Every argument, how a call runs inside, and every rule.
Turn pace, interruption and idle nudges on Pipecat.
Move the call between agents, each with its own model and voice.
Call start values, events, the failure line and the end.
Use one piece on a plain pipeline.
# Add one piece to your agent
Source: https://unmute.ai/core/frameworks/standalone
Use one part of unmute-core on a plain LiveKit Agent or a plain Pipecat pipeline.
You can use each part of unmute-core on its own. Your agent stays a plain LiveKit `Agent` or a plain Pipecat pipeline. You add only what you need.
On this page:
* [Quickstart](#quickstart) - one tool on a plain agent
* [What works where](#what-works-where) - each piece, and its page
* [What still needs UnmuteAgent or UnmuteFlows](#what-still-needs-unmuteagent-or-unmuteflows) - the short list
* [Where to go next](#where-to-go-next)
## Quickstart
```python agent.py theme={null}
import os
from livekit.agents import Agent, AgentSession, JobContext
from livekit.plugins import openai, silero, slng
from pydantic import BaseModel
from unmute_core.livekit import function_tools
from unmute_core.tools import ToolRegistry, local_tool
class Order(BaseModel):
status: str
def lookup_order(order_id: str) -> Order:
"""Look up an order by its id."""
return Order(status="shipped")
registry = ToolRegistry([local_tool(lookup_order, announce="One moment.")])
SLNG_KEY = os.environ["SLNG_API_KEY"]
SLNG_HOST = f"{os.environ['SLNG_WORLD_PART']}.api.slng.ai"
VOICE = "8d8aec63a56c460cb7def795bdf754fa"
async def entrypoint(ctx: JobContext) -> None:
agent = Agent(instructions="You help with orders.", tools=function_tools(registry))
stt = slng.STT(
api_key=SLNG_KEY, slng_base_url=SLNG_HOST, model="soniox/speech-ai:rt-v5", language="en"
)
session = AgentSession(
stt=stt,
llm=openai.LLM(model="gpt-5.6-terra"),
tts=slng.TTS(
api_key=SLNG_KEY,
slng_base_url=SLNG_HOST,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language="en",
),
vad=silero.VAD.load(),
)
stt.attach_to_session(session)
await session.start(agent=agent, room=ctx.room)
```
The agent keeps its own LLM plugin, its own speech to text and text to speech, and its own pipeline. Here speech runs on SLNG: Soniox hears the caller and Fish Audio speaks. See [SLNG](/core/models/slng). The library adds the tool, with its announce line.
Working files for every piece are in `examples/minimal/livekit/` and `examples/minimal/pipecat/`:
| File | Piece |
| - | - |
| `tools.py` | Tools and the announce line |
| `router.py` | The Context Router |
| `telemetry.py` | Spans |
| `greeting.py` | The greeting |
| `idle.py` | Idle nudges |
| `handoff.py` | Handoff |
| `tasks.py` | Tasks |
## What works where
Each row links to the page that holds the recipe.
| Piece | LiveKit | Pipecat | What it needs |
| - | - | - | - |
| [Your own LLM](/core/models/model-call) | Yes | Yes | Nothing. The plugin keeps its client and retries. |
| [Any other model call](/core/models/model-call) | `ModelCallLLM` | `ModelCallLLMService` | A `ModelCall`, like `OpenAIModelCall` |
| [SLNG Context Router](/core/models/slng) | `ModelCallLLM` | `ModelCallLLMService` | The `slng` extra |
| [Tools](/core/build/tools) | `function_tools` | `tools_schema` | A `ToolRegistry` |
| [A line said by a tool](/core/build/tools) | Yes | Yes | `announce` on the tool |
| [Built-in tools](/core/build/tools) | `function_tools` | `tools_schema` | `current_datetime_tool`, `user_phone_number_tool` |
| [Save tool for values](/core/build/state) | `function_tools`, `filled_llm(save_values=True)` | `tools_schema`, `fill_prompt(save_values=True)` | `values_tool` |
| [`llm` span for a native LLM](/core/reference/telemetry#on-a-plain-agent) | `traced_llm` | `TelemetryObserver` | A `Telemetry` with a sink |
| [One agent description](/core/reference/agent-spec) | `UnmuteAgent(spec)` | `UnmuteFlows(spec, ...)` | An `AgentSpec`, the same on both |
| [Tasks and groups](/core/build/tasks) | `UnmuteAgent` | `UnmuteFlows` | An `AgentSpec` with a `TaskPlan` |
| [Handoff](/core/build/handoffs) | `agent.hand_off`, or `shape_chat_ctx` on a plain agent | `flows.hand_off` | The next agent's `AgentSpec`. See below |
| [Typed state and prompt filling](/core/build/state) | `filled_llm` | `fill_prompt` | A `CallState` |
| [Model hooks](/core/build/hooks#where-the-model-hooks-run) | `filled_llm(call=call)` | `attach_call(llm=llm)` | A `CallHooks` |
| [Greeting](/core/build/call-lifecycle) | `greet` | `greeting_frames` | A `Greeting` |
| [Call start values, prefetch, events, failure, end](/core/build/call-lifecycle) | `open_call`, `attach_call` | `open_call`, `attach_call` | A `CallHooks` |
| [Idle nudges](/core/build/turn-taking) | `idle_nudges` | `IdleNudgeObserver` | An `IdleNudges` config |
| [Turn pace](/core/build/turn-taking) | `endpointing` | `vad_params`, `smart_turn_params` | `turn_window(pace, framework)` |
| [Interruption](/core/build/turn-taking) | `interruption`, `yield_to_caller` | `interruption`, `user_mute_strategies` | Nothing |
| [Telemetry](/core/observe/telemetry) | `trace_session` | `TelemetryObserver` | A `Telemetry` with a sink |
| [Prefetch](/core/build/prefetch) | `Prefetch.run`. `filled_llm(call=call)` waits for the background lookups. | `Prefetch.run`. `attach_call(llm=llm)` waits for them. | A `CallState`, and a `CallHooks` to wait |
| [Knowledge](/core/build/knowledge) | `KnowledgeBase` as a tool | `KnowledgeBase` as a tool | The `knowledge` extra |
| [End call](/core/build/tools) | A tool with `effect="ends_conversation"` | The same, or [`end_call_tool`](/core/frameworks/pipecat) | A tool |
On Pipecat, pass `transport=` to `attach_call` or `open_call`, so the transport's hang-up makes the call's end read `caller_hung_up`. Pass `call=` to `max_duration`, `idle_nudges`, `IdleNudgeObserver`, `SipLine`, `end_call_tool`, `voicemail_tool` and `dial_out` so the end reads the right reason. See [Why the call ended](/core/build/call-lifecycle#why-the-call-ended).
`max_duration` and the call info builders (`sip_call_info`, `telephony_call_info`) also work on a plain agent. See [LiveKit](/core/frameworks/livekit) and [Pipecat](/core/frameworks/pipecat).
### A handoff on a plain agent
On Pipecat, `UnmuteFlows` works without tasks. Give each agent a spec with only its prompt. The next agent runs on the same `CallState`:
```python theme={null}
flows = UnmuteFlows(AgentSpec(PROMPT), llm=llm, context=context, aggregators=aggregators)
flows.install()
# inside the handoff tool's handler
await flows.hand_off(params, AgentSpec(NEXT_PROMPT, name="next"), announce="One moment.")
```
On LiveKit, a plain `Agent` hands off the LiveKit way, by returning a new agent from a tool. Build it with `Agent(chat_ctx=shape_chat_ctx(self.chat_ctx, HandoffContext(...)))` to keep the library's history rules. See [Handoffs](/core/build/handoffs).
## What still needs UnmuteAgent or UnmuteFlows
* **Tasks and groups on LiveKit** need `UnmuteAgent`. It runs each step as its own agent.
* **Tasks and groups on Pipecat** need `UnmuteFlows`, with the plan in the spec's `tasks`.
* **A full handoff on LiveKit** (announce line, model and voice switch, summary) needs `UnmuteAgent.hand_off`. The history rules work on a plain agent through `shape_chat_ctx`.
* **Model hooks** run only where the library sends the model request. A plain agent keeps them by calling `filled_llm` or `traced_llm` in its `llm_node` on LiveKit, or by passing `llm=` to `attach_call` on Pipecat. Without that, the adapter logs one warning. See [Hooks](/core/build/hooks#where-the-model-hooks-run).
* **A held save at the end of a call** is settled by `call.end`, or by `UnmuteAgent` on LiveKit and `flows.settle()` on Pipecat.
Everything else works on a plain agent.
## Where to go next
The full agent on LiveKit.
The full flow on Pipecat.
The tool registry that both frameworks share.
Turn pace, interruption and idle nudges.
# Unmute Core
Source: https://unmute.ai/core/index
The Python library that runs a voice agent's behaviour the same way on LiveKit and Pipecat.
unmute-core is a Python library. It holds the voice-agent behaviour that must be
the same on every framework: typed call state, tasks, tools, handoffs, the model
call and telemetry.
You keep LiveKit or Pipecat, your speech and model plugins, and your pipeline.
The library adds what a real call needs on top. [Why Unmute Core](/core/start/why-unmute-core)
follows one salon call and shows what each part fixes.
## Unmute and unmute-core
```mermaid theme={null}
flowchart TD
Y["agent.yaml, prompts, tools"] -->|unmute compile| P[Generated Python project]
H["Your own agent.py"] --> L
P --> L[unmute-core]
L --> K[LiveKit Agents]
L --> C[Pipecat]
```
1. **Unmute** is a compiler. You describe an agent in `agent.yaml`, and Unmute
writes a Python project for LiveKit or Pipecat.
2. **unmute-core** is the library that project imports. It runs the call: it
saves values, steps through tasks, runs tools and sends spans.
3. **Your own agent** can import the same library. You build the pipeline in
your `agent.py`, and call the library where you need it.
4. The library never reads `agent.yaml` and never builds the pipeline. The
framework still owns speech, turn detection and the model plugins.
A fix in the library reaches every agent: the ones Unmute generates and the
ones you write by hand. [How Unmute uses the library](/core/start/unmute-and-core)
shows which `agent.yaml` key turns into which class.
## Plug points
Four interfaces let your code add a capability without changing the library.
| Plug point | What you replace | Page |
| - | - | - |
| `ModelCall` | how one model request is sent | [Model call](/core/models/model-call) |
| `ToolExecutor` | how one kind of tool runs | [Tools](/core/build/tools) |
| `Sink` | where spans go | [Telemetry](/core/observe/telemetry) |
| `Hooks` | code before, around and after prompts, model requests and tools | [Hooks](/core/build/hooks) |
A plug point may add a capability. It never changes how the rest of the
library behaves.
## How to read these docs
1. **[Quickstart](/core/start/quickstart).** Run the smallest agent in a few minutes.
2. **[Build a salon agent](/core/tutorial/overview).** Grow one agent, one piece per page. Each page says what the piece is, why it is there, and how to use it.
3. **[On your framework](/core/frameworks/standalone).** Already have a LiveKit or Pipecat agent? Add one piece at a time.
4. **Guides.** One section per topic, such as [State](/core/build/state) or [Tasks](/core/build/tasks). Each starts with what the topic is and when to use it, then goes deeper one page at a time.
5. **[Example agents](/core/examples/overview).** Four whole agents with a different shape of call each: a finder, a long intake, an outbound reminder and a bilingual tutor. Each runs on both frameworks.
6. **Reference.** Every argument of every class, such as the [Tasks reference](/core/reference/tasks).
## Where to go next
Run the smallest agent on LiveKit or Pipecat.
Grow one agent, one piece per page.
Use only the parts you need on a plain agent.
Which `agent.yaml` key becomes which library class.
Four whole agents, each a different shape of call.
Let the model understand, and let code decide and speak.
# The model call
Source: https://unmute.ai/core/models/model-call
ModelCall, the one interface every model request goes through, and the classes that implement it.
Every model request goes through one small interface, `ModelCall`. Pick a class that implements it, give it to your framework's adapter, and the library fills the prompt, streams the answer and records the tokens. The model sees the same final prompt whichever class you pick.
## Use any OpenAI-compatible model
`OpenAIModelCall` sends each request to any OpenAI-compatible chat endpoint. Give it to the adapter for your framework.
```python LiveKit theme={null}
from unmute_core.livekit import ModelCallLLM
from unmute_core.model import OpenAIModelCall
model = OpenAIModelCall("gpt-5.6-terra") # reads OPENAI_API_KEY
session = AgentSession(llm=ModelCallLLM(model, state=state), ...)
```
```python Pipecat theme={null}
from unmute_core.model import OpenAIModelCall
from unmute_core.pipecat import ModelCallLLMService
model = OpenAIModelCall("gpt-5.6-terra") # reads OPENAI_API_KEY
llm = ModelCallLLMService(model, state=state)
```
1. The library fills the prompt's `{{placeholders}}` from `state`, then sends it.
2. Pass `base_url=` and `api_key=` to reach another OpenAI-compatible endpoint.
3. It needs the `openai` package, which comes with the `slng` extra and with Pipecat.
With `UnmuteAgent`, give the call to the agent's spec instead: `AgentSpec(PROMPT, model=model)`. Build it per call: the agent closes it when the call ends.
## Use your own framework LLM
On LiveKit, `LiveKitModel` wraps any LLM plugin. The library fills the prompt, and the plugin keeps its own client, settings and retries.
```python theme={null}
from livekit.plugins import openai
from unmute_core.livekit import LiveKitModel
model = LiveKitModel(openai.LLM(model="gpt-5.6-terra"))
```
Give it to an `AgentSpec` as its `model`, or to a `FallbackModelCall`. On Pipecat, pass a native LLM service, like `OpenAILLMService`, to `UnmuteFlows` as it is. `UnmuteFlows` fills its prompts. See [LiveKit](/core/frameworks/livekit) and [Pipecat](/core/frameworks/pipecat).
## Use the Context Router
`RouterModelCall` sends the prompt unfilled to the SLNG Context Router, which fills it and picks the model. See [Use the Context Router](/core/models/slng#use-the-context-router).
## Fall back to another model
`FallbackModelCall` tries several calls in order. It is a `ModelCall` too, so the adapter takes it as it is.
```python theme={null}
from unmute_core.model import FallbackModelCall, OpenAIModelCall
model = FallbackModelCall(
[OpenAIModelCall("gpt-5.6-terra"), OpenAIModelCall("gpt-5.6-luna")],
first_event_timeout_s=10,
)
```
1. It moves to the next call when one fails before it answers. It never moves on once the caller has part of the answer, so no sentence is said twice.
2. Errors every model would give, like 400, 401 or 422, stop the chain at once.
3. A rate limit with a short `Retry-After` waits on the same model, then fails over.
Build one per call of the agent, since it remembers which call answered last.
## Write your own ModelCall
Any class with an async `stream(request)` method is a `ModelCall`. This one answers from the last user message:
```python theme={null}
from collections.abc import AsyncIterator
from unmute_core.model import ModelEvent, ModelRequest, TextDelta, fill_messages
class Echo:
"""A model call that repeats the last user message."""
model = "echo"
provider = "local"
async def stream(self, request: ModelRequest) -> AsyncIterator[ModelEvent]:
"""Fill the prompt, then say the last user message back."""
messages = fill_messages(request.messages, request.variables)
last = next(m["content"] for m in reversed(messages) if m["role"] == "user")
yield TextDelta(f"You said: {last}")
```
Give it to an adapter the way you give it any call: `ModelCallLLM(Echo())` on LiveKit or `ModelCallLLMService(Echo())` on Pipecat.
1. Call `fill_messages` with `request.variables`, as above, unless a router fills the prompt for you.
2. Yield `TextDelta` and `ToolCall` events. Yield a `Usage` last when you know the token counts.
3. Raise the error of a failed request. `FallbackModelCall` reads its status and code from it.
## Read a whole answer
For a side request, like a summary, read the whole answer at once with `collect`:
```python theme={null}
from unmute_core.model import collect
answer = await collect(model.stream(request))
answer.text # every text piece, joined
answer.calls # the ToolCall events, in order
answer.usage # the Usage event, or None
```
## Where to go next
ModelRequest, events, placeholders, every FallbackModelCall argument and Gemini.
RouterModelCall, SLNG speech and your own router config.
Change or wrap a model request with your own code.
Models that hear and speak over one connection.
# Realtime and live models
Source: https://unmute.ai/core/models/realtime
Run an agent on a model that hears the caller, thinks and speaks over one connection.
A realtime model hears the caller, thinks and speaks over one connection to its own server. There is no STT, LLM or TTS. The library's greeting, tools, values and handoffs still work on it.
On this page:
* [What it gives you](#what-it-gives-you) - what goes wrong without it
* [Quickstart](#quickstart) - an agent on a realtime model
* [What is supported](#what-is-supported) - features by framework and model kind
* [How a fixed line is said](#how-a-fixed-line-is-said) - lines with no TTS
* [Instructions and values](#instructions-and-values) - what the model reads
* [Handoffs](#handoffs) - keep the whole conversation
* [What is refused](#what-is-refused-and-why) - and the words you will see
* [Turn detection](#turn-detection) - set in your own code
* [On Pipecat](#on-pipecat) - extra wiring
* [What is not here](#what-is-not-here) - gaps
* [Where to go next](#where-to-go-next)
## What it gives you
| On a call without it | What the library does |
| - | - |
| A realtime model has no voice to say a fixed line, like the greeting or an apology. | The model is asked to say the line. [How a fixed line is said](#how-a-fixed-line-is-said) |
| The model keeps the prompt from before a value was saved. | Instructions are sent again after each save. [Instructions and values](#instructions-and-values) |
| A feature the model cannot run does nothing, silently. | The agent refuses to start and names what to remove. [What is refused](#what-is-refused-and-why) |
## Quickstart
```python LiveKit theme={null}
from livekit.agents import AgentSession, JobContext
from livekit.plugins import openai
from pydantic import BaseModel
from unmute_core.agent import AgentSpec
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.livekit import UnmuteAgent, open_call
from unmute_core.state import CallState
from unmute_core.tools import ToolRegistry, local_tool
PROMPT = "You answer calls for a corner shop. Keep replies short: they are spoken aloud."
class State(BaseModel):
order_id: str | None = None
class OrderStatus(BaseModel):
order_id: str
status: str
def order_status(order_id: str) -> OrderStatus:
"""Look up an order by its id and return where it is."""
return OrderStatus(order_id=order_id, status="out for delivery")
async def entrypoint(ctx: JobContext) -> None:
session = AgentSession(llm=openai.realtime.RealtimeModel(voice="marin"))
state = CallState(State)
call = CallHooks(state)
tools = ToolRegistry([local_tool(order_status)])
spec = AgentSpec(PROMPT, tools=tools, save_values=True)
agent = UnmuteAgent(spec, state=state, call=call)
await session.start(agent=agent, room=ctx.room)
await open_call(session, Greeting(text="Hi, how can I help?"), call)
```
```python Pipecat theme={null}
import os
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import LLMContextAggregatorPair
from pipecat.services.openai.realtime.llm import OpenAIRealtimeLLMService
from pydantic import BaseModel
from unmute_core.agent import AgentSpec
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.pipecat import UnmuteFlows, open_call
from unmute_core.state import CallState
from unmute_core.tools import ToolRegistry, local_tool
PROMPT = "You answer calls for a corner shop. Keep replies short: they are spoken aloud."
class State(BaseModel):
order_id: str | None = None
class OrderStatus(BaseModel):
order_id: str
status: str
def order_status(order_id: str) -> OrderStatus:
"""Look up an order by its id and return where it is."""
return OrderStatus(order_id=order_id, status="out for delivery")
async def run_call(transport) -> None:
# transport comes from your own Pipecat runner
llm = OpenAIRealtimeLLMService(api_key=os.environ["OPENAI_API_KEY"])
context = LLMContext()
aggregators = LLMContextAggregatorPair(context)
state = CallState(State)
call = CallHooks(state)
tools = ToolRegistry([local_tool(order_status)])
spec = AgentSpec(PROMPT, tools=tools, save_values=True)
flows = UnmuteFlows(
spec, llm=llm, context=context, aggregators=aggregators, state=state, call=call
)
flows.install()
pipeline = Pipeline(
[transport.input(), aggregators.user(), llm, transport.output(), aggregators.assistant()]
)
worker = PipelineWorker(pipeline)
@transport.event_handler("on_client_connected")
async def greet(transport, client) -> None:
await open_call(
worker, Greeting(text="Hi, how can I help?"), call, context=context, llm=llm
)
# run the worker with your own WorkerRunner, then: await call.end("ended")
```
On LiveKit, any `RealtimeModel` is the session's LLM. On Pipecat, OpenAI's realtime service takes the place of STT, LLM and TTS. The full examples are `examples/minimal/livekit/realtime.py` and `examples/minimal/pipecat/realtime.py`.
## What is supported
A live model is one that fixes its instructions when the session starts. On LiveKit that is any `RealtimeModel` whose capabilities say `mutable_instructions=False`, like OpenAI's GPT-Live. On Pipecat it is `OpenAILiveLLMService`.
| Feature | LiveKit, realtime | LiveKit, live | Pipecat, realtime | Pipecat, live |
| - | - | - | - | - |
| Models | any `RealtimeModel`: OpenAI, Gemini, xAI and others | any model whose instructions are fixed | `OpenAIRealtimeLLMService` and its Azure subclass | `OpenAILiveLLMService` |
| Fixed greeting | yes, the model says it | yes | yes | yes, in its own words |
| Tools | yes | yes | yes | yes |
| A tool's announce line | skipped, the model words its own | skipped | skipped | skipped |
| A registry `ToolReply` line | yes, the model says it | yes | skipped, the model words its own reply | skipped |
| `{{placeholders}}` in the prompt | yes, filled again after each save | yes, filled once, as the agent starts | yes, filled again after each save | yes, filled once, as the agent is built |
| Tools on events at the caller's first message | yes, beside the reply | yes, beside the reply, no note | yes, beside the reply | yes, beside the reply, no note |
| `save_values` | yes | refused | yes | refused |
| Handoffs | yes, with `history="full"` | refused | yes, with `history="full"` | refused |
| Tasks | refused | refused | refused | refused |
| `prompt` hooks | yes | yes | yes | yes |
| `before_model`, `wrap_model`, `after_model` hooks | refused | refused | refused | refused |
| Idle nudges | yes | yes | yes, with `IdleNudgeObserver(llm=...)` | yes, as commentary, with `llm=...` |
| Failure line | yes | yes | yes, with `open_call(llm=...)` | yes, with `open_call(llm=...)` |
| `llm` span with tokens | yes, with time to first token | yes | yes | yes |
| `ModelCall` and the SLNG Context Router | no, the model talks to its own server | no | no | no |
## How a fixed line is said
```mermaid theme={null}
flowchart LR
L[a fixed line] --> Q{TTS on the call?}
Q -->|yes, half cascade| S[the TTS says it]
Q -->|no| M[the model is told to say it]
M --> R[a reply of its own, in these words as far as it can]
```
1. The library has fixed lines: the greeting, an idle nudge, the failure line, the goodbye of `end_call_tool`, a handoff's line, and the lines a transfer says once it is over.
2. With a TTS on the call, as in a half cascade, the TTS says them. Nothing changes from a cascade call.
3. A realtime model with no TTS beside it speaks itself. LiveKit's `session.say` would raise, and Pipecat's `TTSSpeakFrame` would play nothing.
4. So the model is told to say the line: "Say this to the caller now, in these words as far as you can: ...". This text is `SAY_LINE` in `unmute_core.realtime`.
5. The line is a reply of the model's own. It joins the model's conversation.
A line can come out a little different from the text. A live model says it in its own words.
A worded greeting waits for the background lookups on both frameworks, and for the instructions they change, so the model words it from the filled prompt. A fixed greeting does not wait.
A tool's announce line is the one fixed line a realtime model does not say, a transfer's "Putting you through" among them. The model words its own line as it calls the tool. A second reply with the library's line would come while the tool's result is still out, and the result would wait for it.
On Pipecat, a realtime model does not say a registry `ToolReply` line either, even with a TTS after it. A tool's result starts the model's own reply there, and a second spoken line would talk over it. The model reads the result and words its reply. See [Save a result and speak it](/core/build/tools#save-a-result-and-speak-it).
## Instructions and values
The model reads one text: the prompt, filled, then the notes of the tools on events, then the values block with `save_values`. The values block is a system message that lists the State values. A cascade request sends the notes and the values as messages of their own. A realtime model has no requests, so they follow the prompt. `realtime_instructions` builds that text.
* The `prompt` hooks run on the prompt before it is filled, as on a cascade call. See [Hooks](/core/build/hooks).
* After each save, the model gets the instructions again: LiveKit's `update_instructions`, or Pipecat's `LLMUpdateSettingsFrame`. A value a background prefetch saves arrives the same way.
* Each caller message runs the call's tools on events. The model answers that message meanwhile and nothing waits for them. Their notes reach the model with the next instructions. See [The call's life](/core/build/call-lifecycle).
* A live model gets the instructions once. On LiveKit that is as the agent starts. On Pipecat it is as `UnmuteFlows` or `attach_realtime` is set up. A value saved later never reaches it, prefetch included, and neither do the notes of tools on events.
* A plain Pipecat pipeline without `UnmuteFlows` gets the same with `attach_realtime`, before the pipeline runs.
### attach\_realtime
Runs OpenAI's realtime or live service as the agent on Pipecat. Await it before the pipeline runs. It refuses what the model cannot do, then queues the filled instructions on the service.
The call's realtime or live service.
The call's worker. Its end stops following the state.
The agent's prompt, placeholders still in it.
The call state the placeholders read.
The call's hooks. Its `prompt` hooks and the notes of its tools on events apply.
The agent has the `save_values` tool. Its values follow the prompt.
Value name to the task that saves it, for the values block.
```python theme={null}
await attach_realtime(llm, worker, PROMPT, state, call=call)
```
## Handoffs
A realtime model keeps the whole conversation on its own server. A handoff keeps it too. The [Handoffs page](/core/build/handoffs) covers handoffs in general.
```python theme={null}
return await self.hand_off(
UnmuteAgent(billing, state=self.state), context=HandoffContext(history="full")
)
```
1. Pass `HandoffContext(history="full")`. Any other history is refused, because the library cannot reshape what the model holds. Tool calls must stay in, which is the default.
2. The model says the handoff's line first.
3. The next agent's instructions and tools replace the first agent's, on the same connection.
4. The next agent speaks first.
A live model refuses every handoff, because its instructions are fixed.
## What is refused and why
Each refusal has the same words on both frameworks. `UnmuteFlows` refuses when it is built. `UnmuteAgent` refuses as it enters the session, and closes the session, because the agent would run without what was refused. Each message names what to remove or what to run instead.
* **Tasks.** A step needs its own history and a finish check. Both are requests the library sends, and a realtime model has none.
* **`before_model`, `wrap_model` and `after_model` hooks.** No model request passes through the library, so they would never run. The `prompt` hooks do run.
* **`save_values` on a live model.** Its instructions are fixed.
* **A handoff on a live model, or one without `history="full"`.** See above.
## Turn detection
Turn detection is part of building the model, so it stays in your code. These are the settings for OpenAI's models. On LiveKit, `ServerVad` and `SemanticVad` come from `openai.types.realtime.realtime_audio_input_turn_detection`.
| Mode | LiveKit | Pipecat |
| - | - | - |
| `server_vad` | `RealtimeModel(turn_detection=ServerVad(type="server_vad"))` | `events.AudioInput(turn_detection=events.TurnDetection())` |
| `semantic` | `RealtimeModel(turn_detection=SemanticVad(type="semantic_vad"))` | `events.AudioInput(turn_detection=events.SemanticTurnDetection())` |
| `local` | `RealtimeModel(turn_detection=None)`, with a VAD and `turn_handling` on the session | `events.AudioInput(turn_detection=False)`, with a VAD on the user aggregator |
| left out | semantic VAD | server VAD |
When the model decides the turn, some [turn-taking](/core/build/turn-taking) settings do nothing:
* `endpointing()`, `vad_params()` and `smart_turn_params()`. The model's own VAD sets the pace.
* `interruption(enabled=False)` on LiveKit. It raises when the session starts, because LiveKit cannot stop the model from being cut off.
* Pipecat's interruption strategies, like `Backchannels`. They act on local VAD frames, and the server cancels its reply itself.
## On Pipecat
* Pass the service to `open_call(llm=...)`, with `UnmuteFlows` too, and to `IdleNudgeObserver(llm=...)`. They then say the greeting, the failure line and the nudges through the model. Left out, these lines become `TTSSpeakFrame`s that nothing plays, and nothing reports it.
* Any other realtime service, like Gemini Live, is taken for a cascade LLM. Its fixed lines are not said.
* A greeting goes to the model as a developer message. Pipecat drops a first system message when the service has its own instructions.
* When the caller speaks first, `open_call` gives the service its context and tools at once. Without that, Pipecat sets the conversation up in the middle of the caller's first turn. It sends the turn again as a "previously saved conversation", asks for a second reply, and the model gets its tools only then.
* A live service opens its session on a first request. When the caller speaks first, `open_call` still sends one.
* A line said while the model replies waits for the reply to end. The server refuses a second reply while one runs.
* `TelemetryObserver` records one `llm` span per reply. Pipecat starts a realtime reply twice, and starts none for a reply that only calls a tool. The observer handles both.
## What is not here
* Gemini Live, Nova Sonic, Ultravox, Grok and Inworld on Pipecat. Their services take instructions, tools and replies in other ways. On LiveKit any `RealtimeModel` works.
* The SLNG Context Router. It has no realtime endpoint.
* Building the model. Its voice, its turn detection and its transcription stay in your code.
## Where to go next
Give the call to another agent.
Pace, interruption and idle nudges on a cascade call.
The plug point a realtime model does not use.
The compiler side, on the Unmute tab.
# SLNG speech and the Context Router
Source: https://unmute.ai/core/models/slng
Use SLNG speech-to-text, text-to-speech and the Context Router with a native LiveKit or Pipecat agent.
SLNG gives you speech to text, text to speech and the Context Router. You can use each one alone, or all three together. The library does not wrap the speech plugins. It only reads their metrics for [telemetry](/core/observe/telemetry).
## Install
Add the `slng` extra beside your framework extra:
```bash theme={null}
uv add "unmute-core[livekit,slng]"
```
The speech plugins are separate packages: `livekit-plugins-slng` for LiveKit and `pipecat-slng` for Pipecat. The [installation page](/core/start/installation) lists every extra.
## Speech only
Use SLNG speech to text and text to speech with any LLM. This example uses Soniox to hear the caller and Fish Audio to speak.
```python LiveKit theme={null}
import os
from livekit.plugins import slng
from unmute_core.slng import tracking_ids
world_part = os.environ["SLNG_WORLD_PART"] # your SLNG project's region, like eu-north
stt = slng.STT(
api_key=os.environ["SLNG_API_KEY"],
slng_base_url=f"{world_part}.api.slng.ai",
model="soniox/speech-ai:rt-v5",
language="en",
**tracking_ids(state.call),
)
tts = slng.TTS(
api_key=os.environ["SLNG_API_KEY"],
slng_base_url=f"{world_part}.api.slng.ai",
voice="8d8aec63a56c460cb7def795bdf754fa",
model="slng/fish/tts:s2.1-pro",
language="en",
**tracking_ids(state.call),
)
```
```python Pipecat theme={null}
import os
from pipecat.transcriptions.language import Language
from pipecat_slng import SlngSTTService, SlngTTSService
from unmute_core.slng import tracking_ids
world_part = os.environ["SLNG_WORLD_PART"] # your SLNG project's region, like eu-north
stt = SlngSTTService(
api_key=os.environ["SLNG_API_KEY"],
model="soniox/speech-ai:rt-v5",
language=Language("en"),
world_part=world_part,
**tracking_ids(state.call),
)
tts = SlngTTSService(
api_key=os.environ["SLNG_API_KEY"],
voice="8d8aec63a56c460cb7def795bdf754fa",
model="slng/fish/tts:s2.1-pro",
language=Language("en"),
world_part=world_part,
**tracking_ids(state.call),
)
```
1. `tracking_ids(state.call)` gives both plugins the agent's id and the call's session id. SLNG groups usage by them. Build the call state first, so the ids exist.
2. Put both services in the session or the pipeline. On LiveKit, also call `stt.attach_to_session(session)` after you build the session.
3. `SLNG_WORLD_PART` must be your SLNG project's region. A key used in another region gets 401 from the router.
## Use the Context Router
`RouterModelCall` sends each model request to the SLNG Context Router. Give it to your framework through a small adapter.
```python LiveKit theme={null}
from unmute_core.livekit import ModelCallLLM
from unmute_core.slng import RouterModelCall
router = RouterModelCall(
state.call,
model="gpt-5.6-luna",
config=config,
body={"reasoning_effort": "none"},
)
session = AgentSession(llm=ModelCallLLM(router, state=state), ...)
```
```python Pipecat theme={null}
from unmute_core.pipecat import ModelCallLLMService
from unmute_core.slng import RouterModelCall
router = RouterModelCall(
state.call,
model="gpt-5.6-luna",
config=config,
body={"reasoning_effort": "none"},
)
llm = ModelCallLLMService(router, state=state)
```
1. The adapter sends the prompt with its `{{placeholders}}` still in it, and the values from `state` beside it. The router fills the prompt, so the model sees the same text it would see on a native LLM.
2. The router retries and fails over by its own rules. `config` names the models and your keys: see the next section.
3. OpenAI refuses function tools with reasoning on, so an agent with tools sends `reasoning_effort` `"none"`. An agent with no tools may leave it out.
With `UnmuteAgent`, give the router to the agent's spec instead: `AgentSpec(PROMPT, model=router)`. Build the router per call, after the state, because it reads `state.call`. Arguments you leave out are read from the `SLNG_*` [settings](/core/reference/settings).
## Bring your own model key
Send your own router config with every request. It names the model the router uses and holds your own provider key.
```python theme={null}
import os
from unmute_core.slng import OpenAIEndpoint, RouterConfig
config = RouterConfig.single(
"gpt-5.6-luna",
OpenAIEndpoint(
url="https://api.openai.com/v1",
api_key=os.environ["OPENAI_API_KEY"],
),
)
```
1. `RouterConfig.single` puts one model on your OpenAI key. `RouterModelCall(config=config)` sends it with every request.
2. Always pass a config. Without one, the router uses a stored config that may not select your model, and answers 400.
3. Only an SLNG key from a project on the Execution Layer may send a config. Any other key gets 403 `project_mode_forbidden`.
For weights, fallbacks and other providers, see [Your router config](/core/reference/slng#your-router-config).
## Without the router
`OpenAIModelCall` is a native call for any OpenAI-compatible endpoint. It sends nothing to SLNG, and the library fills the prompt. See [Use any OpenAI-compatible model](/core/models/model-call#use-any-openai-compatible-model).
The complete files with speech and the router together are `examples/parcel-desk/livekit/agent.py` and `examples/parcel-desk/pipecat/bot.py`.
## Where to go next
Every RouterModelCall argument, header, config field, error and Gemini detail.
The interface the router implements, and FallbackModelCall.
The `SLNG_*` variables and how to check them at startup.
The `agent.yaml` side of the router.
# Telemetry
Source: https://unmute.ai/core/observe/telemetry
Send every call's spans to Langfuse, Logfire, Coval or Datadog. Turn it on once, then pick where the spans go.
The library traces each call the same way on LiveKit and Pipecat. A call is one trace. Each caller turn is a span, with the speech, the model requests and the tool calls under it. You pick where the spans go.
In the salon tutorial, [See every call](/core/tutorial/see-every-call) builds this step by step.
## Turn it on
Build one `Telemetry` for every call, and give it to the agent.
```python LiveKit theme={null}
from unmute_core.livekit import UnmuteAgent
from unmute_core.telemetry import Langfuse, Telemetry
telemetry = Telemetry(Langfuse.from_env(), agent="salon", call_id=state.call.session_id)
agent = UnmuteAgent(spec, state=state, telemetry=telemetry)
```
```python Pipecat theme={null}
from pipecat.pipeline.worker import PipelineParams, PipelineWorker
from unmute_core.pipecat import TelemetryObserver, UnmuteFlows
from unmute_core.telemetry import Langfuse, Telemetry
telemetry = Telemetry(Langfuse.from_env(), agent="salon", call_id=state.call.session_id)
flows = UnmuteFlows(
spec, llm=llm, context=context, aggregators=aggregators, state=state, telemetry=telemetry
)
worker = PipelineWorker(
pipeline,
params=PipelineParams(enable_metrics=True, enable_usage_metrics=True),
observers=[TelemetryObserver(telemetry, model="gpt-5.6-terra", provider="openai", flows=flows)],
)
telemetry.start_call()
try:
await runner.run()
finally:
await telemetry.close(state=state, reason="ended")
```
On LiveKit, the trace ends and is sent when the session closes. On Pipecat, `close` does it. Leave Pipecat's own `enable_tracing` off, or the call is traced twice.
## Pick where the spans go
Change the sink. The rest of your code stays the same.
### Langfuse
```bash theme={null}
export LANGFUSE_PUBLIC_KEY=pk-... LANGFUSE_SECRET_KEY=sk-... LANGFUSE_BASE_URL=https://cloud.langfuse.com
```
```python theme={null}
telemetry = Telemetry(Langfuse.from_env(), agent="salon", call_id=state.call.session_id)
```
### Logfire
```bash theme={null}
export LOGFIRE_TOKEN=...
```
```python theme={null}
telemetry = Telemetry(Logfire.from_env(), agent="salon", call_id=state.call.session_id)
```
### Coval
```bash theme={null}
export COVAL_API_KEY=...
```
```python theme={null}
from unmute_core.livekit import correlate_coval # or unmute_core.pipecat
coval = Coval.from_env()
telemetry = Telemetry(coval, agent="salon", call_id=state.call.session_id)
correlate_coval(ctx, coval, telemetry) # LiveKit: the JobContext
correlate_coval(runner_args, coval, telemetry) # Pipecat: the runner's arguments
```
A call that Coval placed joins its simulation. Any other call is filed as a Coval conversation when it ends.
### Datadog
Send the spans to an OpenTelemetry Collector. The Collector sends them to Datadog.
```python theme={null}
telemetry = Telemetry(
Otlp(endpoint="http://collector:4318/v1/traces"), agent="salon", call_id=state.call.session_id
)
```
```yaml collector.yaml theme={null}
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
exporters:
datadog:
api:
key: ${env:DD_API_KEY}
site: datadoghq.com
service:
pipelines:
traces:
receivers: [otlp]
exporters: [datadog]
```
### Any OpenTelemetry endpoint
```python theme={null}
Otlp(endpoint="https://otlp.example.com/v1/traces", headers={"x-api-key": key})
```
## Send to several at once
Pass more than one sink. Each one gets every span.
```python theme={null}
telemetry = Telemetry(
Langfuse.from_env(), Coval.from_env(), agent="salon", call_id=state.call.session_id
)
```
## Keep transcripts out
Add `filter=MetadataOnly()` to a sink. It then gets timings and names, and no transcript or prompt. The other sinks still get everything.
```python theme={null}
Otlp(endpoint="http://collector:4318/v1/traces", filter=MetadataOnly())
```
## What you see
```mermaid theme={null}
flowchart TD
C[conversation: the call] --> T[turn: one caller message and the reply]
C --> S[task_step]
T --> A[stt]
T --> L[llm: the filled prompt and tokens]
T --> K[llm_tool_call]
T --> B[tts]
```
1. The call span holds the transcript and why the call ended.
2. Each turn holds what the caller said, what the agent said and how long the reply took.
3. Each model span holds the prompt the model really read, the tools and the tokens.
4. A missing time is left out, never sent as 0.
## Where to go next
Every helper, sink argument, span and attribute.
What one call did, for the local dev page.
Every Langfuse, Logfire and Coval variable.
The `tracing` key of `agent.yaml`, on the Unmute tab.
# AgentSpec reference
Source: https://unmute.ai/core/reference/agent-spec
Every field of AgentSpec, the one description of an agent that runs the same on LiveKit and Pipecat.
`AgentSpec` says what one agent of a call is: its prompt, its tools or tasks, its models, its language and its handoff tools. You write it once. `UnmuteAgent(spec)` runs it on LiveKit, and `UnmuteFlows(spec, ...)` runs it on Pipecat. A handoff takes the next agent's spec on both.
The adapter adds only two kinds of thing:
1. What every agent of the call shares: `state`, `call` and `telemetry`.
2. The framework's own objects: `native_tools`, `then_targets`, `tts`, LiveKit's `Agent` options, and Pipecat's `llm`, `context` and `aggregators`.
These have the same names on both frameworks. See [LiveKit](/core/reference/livekit#unmuteagent) and [Pipecat](/core/reference/pipecat#unmuteflows) for them.
```python LiveKit theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent
state = CallState(State)
spec = AgentSpec(PROMPT, tasks=plan, language="es-ES", timezone="Europe/Madrid")
agent = UnmuteAgent(spec, state=state, call=call, telemetry=telemetry)
```
```python Pipecat theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows
state = CallState(State)
spec = AgentSpec(PROMPT, tasks=plan, language="es-ES", timezone="Europe/Madrid")
flows = UnmuteFlows(
spec,
llm=llm,
context=context,
aggregators=aggregators,
state=state,
call=call,
telemetry=telemetry,
)
```
Build the spec per call, after the state. A model like `RouterModelCall(state.call, ...)` reads the call, so it cannot be built before it. The spec is frozen: it does not change once it is built.
## AgentSpec
```python theme={null}
from unmute_core.agent import AgentSpec
```
`instructions` is the only positional argument. Pass the others by keyword.
The main prompt. It may hold `{{name}}` placeholders. See [State](/core/build/state).
The agent's name, which a `handoff` event shows. One to 64 letters, digits, `_` or `-`. None uses the call's `agent_id`, from `state.call`. An agent the call is handed to sets its own name.
The checked tasks and groups. The plan holds every tool, task-only ones included. It needs a state on the adapter. See [Tasks](/core/build/tasks).
The agent's tools, for an agent without tasks. Pass `tools` or `tasks`, not both.
The agent's model. Its steps run on it too. On LiveKit, a plugin goes in as `LiveKitModel(plugin)`. On Pipecat, it needs the call's `llm` to be a `ModelCallLLMService`. None uses the framework's own LLM. See [Model call](/core/models/model-call).
Writes the summary a `summary` history asks for, for a task step or a handoff without its own. None asks the agent's model. On Pipecat, it also answers each finish check when the call's LLM cannot be asked.
The models a task's `model` names, by name. A step of that task runs on it. Pipecat runs every task on the agent's LLM service, so it refuses a task with a `model`.
The call's language, a BCP-47 tag like `es-MX`. Confirm and reply lines say dates and times in it.
Where the business is, an IANA name like `Europe/Madrid`. Confirm and reply lines then name a day from today, like "today, October 8". An unknown name raises `ValueError` when the adapter is built.
End each main agent request with the current text of the State values. The agent also gets the `save_values` tool, for the values no task saves and the call does not start with. It needs a state on the adapter. It belongs to this agent only. See [State](/core/build/state).
The names of the agent's handoff tools, among its framework tools. The first reply after a handoff leaves them out, so the agent cannot hand the call straight back. A greeting the model words leaves them out too. See [Handoffs](/core/build/handoffs).
`AgentSpec` raises `ValueError` in these cases:
* `tools` comes with `tasks`. The task plan holds the tools.
* A task names a model that `task_models` does not name.
* `name` is not 1 to 64 letters, digits, `_` or `-`.
The adapter checks the rest when it is built, the same way on both frameworks. It raises `ValueError` in these cases:
* The spec has `tasks` or `save_values`, and there is no state. Pass `state=CallState(...)` or `call=CallHooks(...)`.
* A group transfers to an agent `then_targets` lacks.
* With `call`, a task input reads a tool that no prefetch lookup of the call runs.
* A placeholder makes a key longer than the model call takes. The router takes 64 characters. A native model has no limit.
Each framework page lists the checks that only it makes.
## Attributes on the adapter
`agent.spec` on LiveKit: the spec the agent was built with. `flows.spec` on Pipecat: the spec of the agent that holds the call now. It changes on each handoff.
The task runs the adapter built from the spec. `agent.tasks` on LiveKit is None for an agent without `tasks`. `flows.tasks` on Pipecat always holds one, for the agent that holds the call. See [Tasks reference](/core/reference/tasks#calltasks).
# Call lifecycle reference
Source: https://unmute.ai/core/reference/call-lifecycle
Every argument of CallHooks, Greeting, EventTool and save_call_start, the order of a call, and each rule for the greeting, failures and the end.
This page is the full detail behind [The call's life](/core/build/call-lifecycle). Start there to open, greet and end a call. Come here for every argument, the exact order and each rule.
`unmute_core.call` and `unmute_core.greeting` run what happens around a call. `CallHooks` runs the call's [hooks](/core/build/hooks). The checks, the failure and the end below are hooks too.
## What it gives you
| On a call without it | What the library does |
| - | - |
| The caller talks during setup, and that audio mixes into the first turn. | Caller audio waits until the greeting starts, for at most 20 s. [Holding the caller's audio](#holding-caller-audio) |
| A service is down. The agent greets the caller, then dies. | Checks run before the greeting. A failure plays a short line and hangs up. [Checks before the greeting](#checks-before-the-greeting) |
| The model or speech service fails, and the caller hears silence. | A short apology plays once, then the call ends. A voice error alone keeps the call going. [When a part fails](#when-a-part-fails) |
| Late saves, end tools and webhooks are cut off when the process exits. | The end runs once and waits for them. [The end](#the-end) |
| "Why did the call end?" has a different answer on each framework. | Seven reasons, the same on both. [Why the call ended](/core/build/call-lifecycle#why-the-call-ended) |
## A whole call
Both tabs share this setup. It holds the State, one webhook tool for the call end and one background lookup.
```python setup.py theme={null}
from pydantic import BaseModel
from unmute_core.call import CallHooks, EventTool
from unmute_core.hooks import Hooks
from unmute_core.prefetch import Lookup, Prefetch
from unmute_core.state import CallState
from unmute_core.tools import Done, Transcript, local_tool, webhook_tool
PROMPT = "You answer the phone for {{brand}}. The shop closes at {{closes_at}}."
class CallLog(BaseModel):
customer_id: str
transcript: list[dict[str, str]]
class Hours(BaseModel):
close: str
class State(BaseModel):
customer_id: str | None = None
brand: str | None = None
closes_at: str | None = None
def store_hours() -> Hours:
"""Return when the shop closes."""
return Hours(close="18:00")
def new_call() -> tuple[CallState, CallHooks]:
"""Build the state and the hooks of one call."""
state = CallState(State, call_start={"customer_id": "required", "brand": "optional"})
log_call = webhook_tool(
"log_call",
"Send the call to the CRM.",
"https://crm.example.com/calls",
input=CallLog,
output=Done,
locked={"customer_id": "{{customer_id}}", "transcript": Transcript(max_messages=50)},
)
prefetch = Prefetch(
[Lookup("hours", local_tool(store_hours), {"closes_at": "close"}, background=True)]
)
hooks = Hooks(EventTool(log_call, on=["call_end"]))
return state, CallHooks(state, hooks=hooks, prefetch=prefetch)
```
```python LiveKit theme={null}
import json
from livekit.agents import AgentSession, JobContext
from unmute_core.agent import AgentSpec
from unmute_core.call import save_call_start
from unmute_core.greeting import Greeting
from unmute_core.livekit import UnmuteAgent, open_call
async def entrypoint(ctx: JobContext) -> None:
state, call = new_call()
metadata = json.loads(ctx.job.metadata or "{}")
save_call_start(state, metadata.get("call_start"))
session = AgentSession(...) # your STT, LLM, TTS and VAD
agent = UnmuteAgent(AgentSpec(PROMPT), state=state, call=call)
await session.start(agent=agent, room=ctx.room)
await open_call(session, Greeting(text="Hi, thanks for calling."), call)
```
```python Pipecat theme={null}
from pipecat.frames.frames import EndFrame
from unmute_core.call import save_call_start
from unmute_core.greeting import Greeting
from unmute_core.pipecat import GreetingHold, fill_prompt, open_call
# runner_args, transport, llm, context, worker and runner are the objects your own bot builds.
state, call = new_call()
save_call_start(state, runner_args.body.get("call_start"))
hold = GreetingHold() # also give it to the user aggregator: user_mute_strategies=[hold]
await fill_prompt(llm, worker, PROMPT, state) # the prompt reads the values, each time they change
@transport.event_handler("on_client_connected")
async def on_connected(transport, client):
await open_call(
worker,
Greeting(text="Hi, thanks for calling.", interruptible=False),
call,
context=context,
llm=llm,
hold=hold,
transport=transport,
)
@transport.event_handler("on_client_disconnected")
async def on_disconnected(transport, client):
await worker.queue_frame(EndFrame())
await runner.run()
end = await call.end("ended")
```
## The order
```mermaid theme={null}
flowchart TD
A[Dispatch values] --> B[save_call_start]
B --> C[Session or pipeline starts]
C --> D[open_call: caller audio off]
D --> E{Checks pass?}
E -->|no| F[Failure line, hang up]
E -->|yes| P[Prefetch runs]
P --> G[Background lookups start]
G --> H[Greeting]
H --> I[Model requests wait for the lookups]
I --> J[Caller talks, tools run on events]
J --> K[Call ends]
K --> L[call.end: held saves, call_end tools, observers, webhooks]
J -->|a part fails for good| F
```
1. The dispatch brings values. `save_call_start` saves them into the state.
2. The session or pipeline starts.
3. `open_call` holds the caller's audio, then runs the `before_call` hooks in order. A failed check says the failure line and hangs up. No lookup runs.
4. When the checks pass, it runs the prefetch with `prefetch.run`.
5. Then the background lookups start with `prefetch.run_background`. The call's end, or a failure, stops them.
6. The greeting plays. A fixed line plays at once. A worded greeting on a realtime model waits for the background lookups and for the instructions they change.
7. Every model request waits for the background lookups, up to `first_request_timeout_s` (10 seconds).
8. During the call, tools run on events: the first caller message, the call end, and the success or failure of a tool.
9. If STT or the model fails for good, the call says the failure line and hangs up. A TTS failure only logs a warning, and the call stays open. On LiveKit the session still closes at the fourth unrecoverable TTS error. Pipecat has no such limit: a voice that stays broken keeps the line open until the idle hang-up, the call's limit or the caller ends it.
10. When the call ends, `call.end` settles the held saves, runs the `call_end` tools, tells the `call.ended` observers and drains the webhooks.
## CallHooks
The call's own object. Build one per call. See [Open a call](/core/build/call-lifecycle#open-a-call).
The call's state. Tools read it and the end reports its values. Each save reaches the `state.changed` observers. None builds `CallState()`. `UnmuteAgent` takes `call.state`, so a call has one state and one `session_id`.
The call's hooks, with its tools on events. None runs none.
What the call reads as it starts. It needs a state.
The longest the `before_call` hooks may take together.
The longest a model request waits for tools on events and background lookups.
Said before hanging up on a failure. None says nothing.
The longest the held saves and the `call_end` tools may take. It is also the longest the `call.ended` observers and the webhook drain may take.
`FAILURE_LINE` is `I'm sorry, something went wrong on our side. Please call back later. Goodbye.`
## open\_call
`open_call` differs by framework.
```python LiveKit theme={null}
from unmute_core.livekit import open_call
handle = await open_call(session, greeting, call)
```
```python Pipecat theme={null}
from unmute_core.pipecat import open_call
greeted = await open_call(worker, greeting, call, context=context, hold=hold, transport=transport)
```
On LiveKit it takes `session`, `greeting` and `call`, then the keyword `max_hold_s` (default `GREETING_HOLD_SECONDS`). It returns the greeting's speech, or None when the caller speaks first or a check failed.
On Pipecat it takes `worker`, `greeting` and `call`, then the keywords `context` (required), `llm`, `hold` and `transport`. It returns True once the greeting is queued, and False after a failed check.
## save\_call\_start
Saves the values a dispatch sends. See [Start values](/core/build/call-lifecycle#start-values).
The call's state.
The dispatch's `call_start` object. None when there is none.
Also read `UNMUTE_CALL_START`. `False` reads only `dispatched`. Pass it by keyword.
Call it before the session starts, so a bad dispatch fails at once. [State](/core/build/state#values-the-call-starts-with) shows how these values read in prompts and tools.
### Start value rules
1. `dispatched` is the `call_start` object of the dispatch. On LiveKit it is `json.loads(ctx.job.metadata or "{}").get("call_start")`. On Pipecat it is `runner_args.body.get("call_start")`.
2. For a local run, set `UNMUTE_CALL_START` to a JSON object. The dispatch's values win over it. Pass `env=False` to read only the dispatch.
3. `CallState(call_start=...)` names the values and says if each is `required` or `optional`. Every one is a State value.
4. With a mapping, only those names are taken. A missing required name raises `CallStartError`: `Missing call_start fields: customer_id`.
5. Without a mapping, any State value may be set and none is required.
6. Names the State does not hold are dropped, and the log names them.
7. A value that does not fit its type raises `CallStartError` with `call_start: : `. Nothing is saved.
8. A value of `None` is left out. It keeps its default.
9. The saved values have the origin kind `call_start`.
10. The function returns the values it saved.
11. A `call` object in `dispatched` sets what the call carries. On a web call every field applies. On a phone call the line's own fields win, and the dispatch fills only the empty ones. `agent_id` and `session_id` always apply. See [State](/core/build/state#values-the-call-carries-state-call).
## Work at call start
```python theme={null}
from unmute_core.prefetch import Lookup, Prefetch
prefetch = Prefetch(
[
Lookup("customer", find_customer, {"customer_name": "name"}),
Lookup("hours", local_tool(store_hours), {"closes_at": "close"}, background=True),
],
state=State,
)
call = CallHooks(state, prefetch=prefetch)
```
Work at call start is a [prefetch](/core/build/prefetch). A tool on a `call_start` event is not possible.
1. `CallHooks(state, prefetch=...)` takes the prefetch. A prefetch needs a state.
2. `open()` runs the `before_call` hooks first, then `prefetch.run`. The prefetch holds the greeting until it ends or its budget (2 seconds) runs out.
3. Then `open()` starts `prefetch.run_background`. It runs each `background=True` lookup beside the greeting.
4. Every model request waits for the background lookups, up to `first_request_timeout_s` (10 seconds). So a fixed greeting plays at once.
5. `call.results` holds each lookup's result as JSON, by entry name. `UnmuteAgent(call=call)` and `UnmuteFlows(call=call)` give it to their tasks, so a step with a `tool` input reads it. In your own host, pass it to `CallTasks(call_start=call.results)`. See [Tasks](/core/build/tasks).
6. `EventTool(..., on=["call_start"])` raises `ValueError`. It points you to `Lookup(..., background=True)`.
## Checks before the greeting
```python theme={null}
hooks.before_call(check_crm)
hooks.before_call(check_calendar)
call = CallHooks(state, hooks=hooks, ready_timeout_s=10)
```
1. Each check is a `before_call` hook. The checks run in order, before `prefetch.run`.
2. All checks share `ready_timeout_s`, 10 seconds by default.
3. A check that raises, or runs out of time, is a terminal failure with the component `ready`.
4. `open_call` returns `None` (LiveKit) or `False` (Pipecat) in that case. The caller's audio stays off.
## Greeting
How the call opens. See [Greet the caller](/core/build/call-lifecycle#greet-the-caller).
```python theme={null}
from unmute_core.greeting import GREETING_INSTRUCTION, Greeting
Greeting(text="Hello {{customer.name}}, how can I help?")
Greeting()
Greeting(speaks_first="user")
```
| Greeting | What happens |
| - | - |
| `Greeting(text="...")` | The agent says that fixed line. |
| `Greeting()` | The model words a greeting from `instruction`. |
| `Greeting(speaks_first="user")` | The agent waits for the caller. |
`agent` opens the call. `user` waits for the caller.
The line the agent says. None has the model word the greeting. It needs `speaks_first="agent"`, and it may not be blank.
What the model is told when it words the greeting.
False keeps the caller from cutting the greeting off. It also holds the caller's audio until the greeting has played.
### Greeting rules
1. A fixed line may name State values as `{{name}}` or `{{name.field}}`.
2. Only values that prefetch or `call_start` fills before the greeting can be named. Any other value is still empty when the call opens.
3. `greeting.check(prefetch, call_start)` raises `ValueError` for a line that names a value neither fills. `call_start` is the `CallState(call_start=...)` mapping, or its names. Background lookups do not count.
4. If a named value is empty at the moment of greeting, or still waits for the caller to confirm it, the line is not said. The model words the greeting instead. The log says why.
5. `GREETING_INSTRUCTION` is what the model is told when it words the greeting: `Greet the caller and offer to help.`
6. `Greeting` is a frozen Pydantic dataclass. A value of the wrong type raises a `ValidationError` in Pydantic's wording, like `Input should be 'agent' or 'user'`. A blank `text` raises one too.
7. A `text` with `speaks_first="user"` raises `ValueError`: `greeting text requires speaks_first: agent`. So does a `{{` or `}}` that is not a `{{name}}` or `{{name.field}}` placeholder.
### Open a call with it
`open_call` is the usual way. It runs the checks and the prefetch, then greets. To greet by hand, after the session or pipeline runs and prefetch has filled the state:
```python LiveKit theme={null}
from unmute_core.livekit import greet
greet(session, greeting, state)
```
```python Pipecat theme={null}
from unmute_core.pipecat import greeting_frames
await worker.queue_frames(greeting_frames(greeting, state))
```
## Holding caller audio
The rule is the same on both frameworks. The caller's audio stays off until the agent starts to speak, so the greeting is not talked over.
1. `open_call` turns the caller's audio off, runs the checks, and greets.
2. By default, the audio comes back when the agent starts to speak. The caller can cut the greeting off.
3. With `Greeting(interruptible=False)`, the audio comes back when the greeting ends. The caller cannot cut it off.
4. If the caller speaks first, the audio comes back at once.
5. After a failed check, the audio stays off.
6. The hold has a limit on both frameworks: `GREETING_HOLD_SECONDS` (20 seconds). A greeting that never starts or never ends gives the audio back after that, so the caller is never held for ever. Import it from `unmute_core.greeting`.
LiveKit does this inside `open_call`, and `open_call(max_hold_s=...)` sets the limit. See [LiveKit](/core/frameworks/livekit). Pipecat needs a `GreetingHold` on the user aggregator, and `open_call(hold=hold)` sets `hold.interruptible` from the greeting. `GreetingHold(max_hold_s=...)` defaults to `GREETING_HOLD_SECONDS`. See [Pipecat](/core/frameworks/pipecat).
## EventTool
Runs a tool without the model. See [Tools on events](/core/build/call-lifecycle#tools-on-events).
```python theme={null}
from unmute_core.call import EventTool
EventTool(
load_booking,
on=["tool_succeeded:book_slot"],
assign={"booking_ref": "ref"},
note=True,
)
```
Add it to the call's hooks with `hooks.add(EventTool(...))`, or pass it to `Hooks(...)`. These are the events:
| Event | When |
| - | - |
| `first_user_message` | The first model request that has a caller message. |
| `call_end` | The call ends. |
| `tool_succeeded:` | The named tool succeeded. |
| `tool_failed:` | The named tool failed. |
The tool to run.
Its events. At least one.
State value name to the top-level result key it gets. Saved when the tool succeeds.
True also shows the result to the model as a note.
### Saving the result
1. `assign={"state_value": "result_key"}` saves a top-level key of the result into the State.
2. It saves only when the tool succeeds. The origin kind is `event`.
3. A value that does not fit its type is only logged. The call goes on.
4. The names are checked against the state when you build `CallHooks`. An unknown value raises `ValueError`.
5. `call_end` tools save before the `call.ended` observers run.
### Rules
1. Every required argument must be locked: a constant, `{{value}}`, `{{call.name}}` or `Transcript(...)`. The model never fills one.
2. The tool reads these call values besides the usual ones: `{{call.first_user_message}}` and `{{call.end_reason}}`. The library saves each one just before the tools of that event run. For the transcript, lock `Transcript()`. `trigger_event` exists only in the webhook envelope.
3. A tool on an event has no announce line. Nobody waits for it.
4. Tools of one event run in list order.
5. A tool that follows another tool starts after it. A chain is at most 8 tools deep. A loop is refused when you build `CallHooks`.
6. Each of `first_user_message` and `call_end` fires once a call.
7. An event tool that is refused starts no tool after it.
8. `tool_succeeded` and `tool_failed` follow the tools of the agent. On a plain agent, pass `hooks=call` to `function_tools` or `tools_schema`.
### Transcript
`Transcript` is a locked argument that reads the call's transcript so far.
```python theme={null}
from unmute_core.tools import Transcript
webhook_tool(
..., locked={"transcript": Transcript(max_messages=50), "reason": "{{call.end_reason}}"}
)
```
1. `max_messages` is the newest messages to send. The default is 200. It must be 1 or more. The result is also capped at `TRANSCRIPT_MAX_BYTES` (32 KiB). Over that, the oldest messages go first, and the newest message is always kept.
2. `text=False` (default) sends a list of `{"role", "content"}` messages. `text=True` sends one text with a `role: content` line per message.
3. The model never sees a locked argument.
### What the model reads
```text theme={null}
Results of tools that ran on their own in this call. Use them, but never read them aloud or share the raw data:
- load_booking ran on its own after book_slot succeeded. Use the result like this: Tell the caller the booking code. Result: {"ref": "B-17"}
```
1. A note is opt-in. Set `note=True` on the `EventTool`. By default the model reads nothing.
2. With `note=True`, every main-agent request ends with one system message that starts with `NOTES_HEADER`. It holds all notes so far.
3. It sits just before the values block, the system message that lists the State values. A step's request gets no notes.
4. A tool with `show_result=False` that succeeded leaves no note.
5. A `call_end` tool leaves no note. The call is over.
6. With `note=True`, a failure is noted too, even for a tool with `show_result=False`.
7. The tool's `result_instructions` come first in the note, after "Use the result like this:". A note cut to its length limit never loses them. A tool that failed gets no instructions.
8. A note has at most 15,000 characters. Its `{{` is broken, so the model call never fills it.
### The wait before the first reply
Each model request waits for the tools on events and for the background lookups, up to `first_request_timeout_s`. So a fixed greeting plays at once. The first model request, and a greeting the model words, wait for them.
A plain native LLM on LiveKit with no `traced_llm` gets no wait and no notes. Wrap the LLM with `traced_llm`, or use `ModelCallLLM(call=call)`. On a Pipecat pipeline with no `UnmuteFlows`, pass `llm=` to `open_call`. See [Add one piece to your agent](/core/frameworks/standalone).
## When a part fails
```python theme={null}
@hooks.wrap_failure
async def page_then_hang_up(component: str, error: BaseException, handler) -> None:
await pager.notify(component, error)
await handler()
call = CallHooks(
state, hooks=hooks, failure_line="Sorry, we have a problem. Please call back. Goodbye."
)
```
A part fails for good when LiveKit reports an unrecoverable `error` event, or Pipecat reports a fatal error or an unusable processor. A `ModelCall` that raises inside `UnmuteAgent` or `ModelCallLLMService` before its reply began fails the call too. A short error of a native Pipecat LLM does not.
A model error after the reply began does not fail the call. The caller already heard the start. The reply ends as it stands, the error is logged, and the call goes on. The next turn runs as usual.
`ModelCallLLMService.failure_is_final` decides this on Pipecat. `attach_call(llm=...)` and `UnmuteFlows(call=...)` set it. Without them, a model failure stays recoverable, as Pipecat reports it.
1. Only the first failure counts.
2. The `call.failed` observers hear it first. The component is `stt`, `llm`, `pipeline` or `ready`. A `tts` failure is logged and tells the `call.tts_failed` observers, with `{component, error}`: the framework's own retry or fallback may still speak, and a failure line would need the voice that failed. The call stays open and no line plays. An observer may switch voices.
3. The `wrap_failure` hooks run around the failure line. `handler()` says `failure_line` and hangs up. `handler(line=None)` only hangs up, for a hook that plays a recording first. A hook that returns without calling `handler` keeps the call going. The call is no longer failed, the `call.recovered` observers hear it with `{component}`, and a later failure counts again. Use this to switch to a backup service.
4. The line is `failure_line`. The default is `FAILURE_LINE`. None says nothing.
5. Then the call hangs up. The line has at most 15 seconds.
6. The call's end reason becomes `error`.
7. A failure before the adapter binds waits. The line plays once it binds.
8. A failure after the end started changes nothing.
9. A failure after the end was requested changes nothing too. No line plays and no `call.failed` fires. See [The end](#the-end).
On Pipecat, keep the worker's `processor_unusable_policy` at `CONTINUE`, so the line can play.
## The end
```python theme={null}
@hooks.on("call.ended")
async def save_summary(event: str, ended: CallEnd) -> None:
await crm.save(ended.reason, ended.values, ended.transcript)
call = CallHooks(state, hooks=hooks, end_timeout_s=5)
```
`call.end(reason)` runs once. Every caller waits for the same run. It does these steps:
1. It settles the held saves. See [Tasks](/core/build/tasks).
2. It runs the `call_end` tools. They save their `assign` values.
3. It tells the `call.ended` observers, with a `CallEnd`: `reason`, `values`, `confirmed`, `transcript` and `duration_s`. It waits for each.
4. It drains the webhooks of every watched registry.
Each step that fails is logged. Steps 1 and 2 share `end_timeout_s`, 5 seconds by default. Steps 3 and 4 get their own `end_timeout_s`. So a slow tool never skips the observers.
| Framework | Who calls `call.end` |
| - | - |
| LiveKit | The session's close. The job's shutdown waits for it. See [LiveKit](/core/frameworks/livekit#open-and-end-the-call). |
| Pipecat | `on_pipeline_finished`. After `runner.run()`, call `await call.end(...)` again. It returns the same result. |
Then close the telemetry. See [Telemetry](/core/observe/telemetry). On Pipecat, `call.end` replaces `flows.settle()`. `settle()` still works.
`CallEnd` is a frozen Pydantic dataclass. A wrong type in a field raises a `ValidationError`.
### Reading a transcript from a chat
```python theme={null}
from unmute_core.call import transcript_messages
transcript_messages(chat) # [{"role": "user", "content": "Hi"}, ...]
transcript_messages(chat, drop_empty=True) # also leaves out empty replies
```
`transcript_messages` is how both adapters build the call's transcript from a chat. It keeps only the `user` and `assistant` messages with text. It leaves out prompts, tool calls and tool results. It works on an OpenAI-format history from either framework. Pipecat passes `drop_empty=True`.
A chat history in OpenAI format. Anything that is not a dict is left out.
True also leaves out a message whose text is empty. Pass it by keyword.
### The goodbye line
```python theme={null}
from unmute_core.call import GOODBYE_LINE
```
`GOODBYE_LINE` is the English line `Thank you for your time. Have a great day. Goodbye.` Pipecat's `end_call_tool` says it when the model said nothing and you gave no line of your own. For another language, pass your own `goodbye` in that language. See [Tools](/core/build/tools#end-the-call).
## End reasons
The reasons and their causes are in [Why the call ended](/core/build/call-lifecycle#why-the-call-ended).
```python theme={null}
call.caller_left() # your own transport code
call.end_requested("agent_ended") # your own code, before it ends the call
```
1. The words are constants in `unmute_core.call`: `CALLER_HUNG_UP`, `AGENT_ENDED`, `TRANSFERRED`, `MAX_DURATION`, `IDLE`, `ERROR` and `ENDED`.
2. `call.end_requested(reason)` notes why the call is about to end. The first request wins. Every adapter calls it before it ends the call. Call it yourself before you end a call in your own code.
3. `call.caller_left()` is `end_requested("caller_hung_up")`. LiveKit reads the caller leaving from the session's close. On Pipecat, pass `transport=` to `attach_call` or `open_call`, and the transport's `on_client_disconnected` event notes it. For a Daily dial-out, pass `call=` to `dial_out`: the callee hanging up reads `caller_hung_up`. Call `call.caller_left()` yourself only for a transport the library does not see. Your own handler still ends the pipeline.
4. A failure that comes first wins: the reason is `error`. A failure after a requested end changes nothing. No failure line plays and no `call.failed` fires.
5. Pass `call=` to `max_duration`, `idle_nudges` (LiveKit) or `IdleNudgeObserver` (Pipecat), `end_call_tool` and `voicemail_tool` (Pipecat) and `SipLine` (LiveKit). Without it, the call's end reads `ended`.
6. Code that read LiveKit's own words, like `participant_disconnected` or `user_initiated`, must read these words instead.
## Troubleshooting
### CallStartError: Missing call\_start fields
The dispatch left out a value that `call_start` marks `required`.
**Fix:** send the value in the dispatch's `call_start` object, or mark it `optional`.
```python theme={null}
state = CallState(State, call_start={"customer_id": "optional"})
```
### ValueError from CallHooks
A tool on an event assigns a value the state lacks. It can also name a loop of tools, or a chain deeper than 8. A prefetch with no state raises it too.
**Fix:** read the message. It names the tool or the value to change.
### The call hangs up before the greeting
A `before_call` check raised, or ran past `ready_timeout_s`. The call failed with the component `ready`.
**Fix:** find the check in the log. Make it faster, or raise `ready_timeout_s`.
### The failure line never plays on Pipecat
The worker's `processor_unusable_policy` is not `CONTINUE`.
**Fix:** set it to `CONTINUE`.
## Where to go next
Open, greet and end a call, the short way.
Every entry and argument of the work at call start.
How `open_call` and the end work on a LiveKit session.
How `open_call`, `GreetingHold` and the end work in a pipeline.
# Dev records
Source: https://unmute.ai/core/reference/dev-records
Record what one call did, for the local dev page that unmute dev shows.
`unmute_core.dev` sends what one call did as records that `unmute dev` reads. Each record is one JSON object on a line that starts with `UNMUTE_METRIC`. Build one `DevRecorder` for every call. Its default sink prints the lines to stdout, so a bot built on this library shows on the dev page with no other change.
```mermaid theme={null}
flowchart LR
F[Frames or session events] --> O[DevObserver]
S[CallState.listen] --> R[DevRecorder]
K[Task events] --> R
O --> R
R --> K2[Sink function]
```
1. The `DevObserver` of your framework turns pipeline frames or session events into records.
2. `watch_state` sends a record for each change to the call's state.
3. `task_event` sends a handoff operation for each task or group run.
4. The recorder sends each record to the sink function.
```python Pipecat theme={null}
from unmute_core.dev import DevRecorder, call_id_from, metrics_enabled
from unmute_core.pipecat import DevObserver
recorder = DevRecorder(call_id_from(runner_args.body) or room_id) # or sink=my_function
recorder.watch_state(state)
flows.listen(recorder.task_event) # every agent's task events, after a handoff too
observer = DevObserver(
recorder,
handoffs={t["name"] for t in flows.tasks.delegate_tools()},
controls=["transfer_to_sales"], # agent handoff and human transfer tools
)
worker = PipelineWorker(pipeline, observers=[observer, TelemetryObserver(...)])
```
```python LiveKit theme={null}
from unmute_core.dev import DevRecorder, metrics_enabled
from unmute_core.livekit import DevObserver
if metrics_enabled():
recorder = DevRecorder(ctx.room.name, target="livekit")
recorder.watch_state(state)
DevObserver(recorder, controls=["transfer_to_sales"]).attach(session)
```
Send records only when the dev loop asked for them. `metrics_enabled()` reads `UNMUTE_DEV_METRICS` through `DevSettings`, with the on/off words of `env_flag`. So `1` turns it on, and `0` or `false` turns it off. A word that is neither logs a warning and counts as off, so a typo in this dev-only variable never breaks a call. See [Settings](/core/reference/settings).
## DevRecorder
The call's id, 1 to 128 letters, digits, `-` or `_`. Anything else raises `ValueError`.
Receives each record. A `DevSink` is any function that takes one record dict. The default prints `UNMUTE_METRIC` lines. A sink that raises is logged and the record is lost. A record never fails the call.
The framework the call runs on.
`partial` when some model calls are not seen.
## DevObserver
The same arguments on both frameworks. On LiveKit, call `.attach(session)` before or after `session.start`.
The call's recorder. On LiveKit, build it with `target="livekit"`.
The tools that start a task or a group, like `flows.tasks.delegate_tools()` on Pipecat.
Tools that hand the call over and return no result.
A control is a tool that hands the call over and returns no result. An agent handoff tool and a human transfer tool are controls. Each run gets a `handoff` operation and no `tool_duration`, because its call time is the time of whatever it started. On Pipecat, pass every control name. On LiveKit, `UnmuteAgent` adds its own handoff tools, so pass only the transfer tools.
`call_id_from(body)` reads the dev call id from a Pipecat runner's body. It returns `None` when there is none that is valid.
## The call id and the dev settings
```python theme={null}
from unmute_core.dev import CallId, DevSettings
DevSettings().metrics # True when UNMUTE_DEV_METRICS is on
```
One field, `metrics`, read from `UNMUTE_DEV_METRICS`. An unset or empty variable reads as off. A word that is not an on/off word raises `SettingsError`. `metrics_enabled()` catches that error and returns `False`.
The type of a dev call id: text of 1 to 128 letters, digits, `-` or `_`. Use it for a field of your own Pydantic model. `DevRecorder(call_id)` raises `ValueError` for an id that does not fit. `call_id_from(body)` returns `None` instead.
The variable name, `UNMUTE_DEV_METRICS`.
The word that starts each stdout line, `UNMUTE_METRIC`.
## Building records in your own adapter
`DevObserver` is the way to feed a recorder. An adapter of your own can call the recorder's methods. All of them are on `DevRecorder`.
`operation(kind, name, ...)`.
Opens an `llm`, `stt`, `tts`, `tool` or `handoff` operation. It returns the operation's id.
`pending_request(operation, exchange_id, source)`.
Sends the two timings of a model request, a transcript or a piece of speech as pending.
`settle_request(operation, state, timings=, source=, unavailable=, ...)`.
Ends the operation and sends its timings. A timing that was not measured is sent as unavailable.
`measure_operation(operation, metric, value, source, ...)`.
Sends one timing of an operation.
`append_text(row, exchange_id, text)`.
Adds words to the text row of a model request. The row stays provisional until `settle_request`.
`user_text(input_id, text, final=)`.
Records what the caller said. It is provisional until `final`.
`typed_text(input_id, text)`.
Records words the caller typed, as final text. Blank text is ignored.
`tool_started(name, exchange_id=, parent=, control=)`.
Opens the operation of a tool call. It returns the operation's id. A control tool gets a `handoff`.
`tool_ended(operation, state, duration=, source=, control=, reason=)`.
Ends that operation.
`settle_exchange(exchange_id, cut=, spoke=)`.
Ends a response: ended, or interrupted when the caller cut it off.
`breakdown(measured_from, total_secs, parts)`.
Sends where the wait for a reply went. Nothing is sent when a part cannot sit in a record.
`close_response()`.
Says no response is open now, so a task's handoff belongs to none. Use it instead of setting `recorder.response = None`.
`DevRecorder.measure` treats a `bool` as unavailable and never sends it as a number.
## How the LiveKit observer works
1. It reads public session events only. The session's close ends the call's records.
2. `UnmuteAgent` reports each model request, with its streamed text and tool calls, and the lines it says outside the chat, like a handoff's line. The observer follows each agent's tasks as the agent enters, also after a handoff.
3. A plain `Agent` and a realtime model get one `llm` operation per request from LiveKit's metrics, once the request is over.
4. A request seen only through LiveKit's metrics sets `model_calls` to `partial` on the call record. A reply whose text no streamed request carried sets `generated_text` to `limited`.
5. A tool that ends in an error while the session closes is `cancelled`, not `failed`. It is the hang-up.
6. LiveKit may log that `metrics_collected` is deprecated when the observer subscribes. It is still the only source for each piece of synthesis.
## Record kinds
Each record has `version`, `call_id`, `id`, `revision`, `order` and `kind`, and one object named after the kind. Sending an `id` again with a higher `revision` replaces the record, and it keeps its place.
| Kind | What it holds |
| - | - |
| `call` | Open, then ended or error, with the reason when there is one. |
| `exchange` | One input (the caller speaking or typing) or one response (what the agent did next). |
| `text` | What was said. Provisional while it grows, then final, or incomplete if it was cut off. |
| `operation` | One `llm`, `stt`, `tts` or `tool` run, or a `handoff` for a task, a group, an agent handoff tool or a transfer tool. |
| `measurement` | A time in seconds. Pending, measured, or unavailable. A time that was not measured is never zero. |
| `breakdown` | Pipecat only. Where the wait for one reply went, part by part, with the parts summing to the total. |
| `state` | A change to the call's state: each value, who set it, and whether the caller confirmed it. |
An `llm` operation is one model request that answers the caller, the agent's or a step's. It names the model the request went to, also after a handoff gives the next agent its own model. A side request, a handoff's summary or a step's finish check, gets no `llm` operation on either framework. Its `llm` span is still in the trace.
The save tool's and an event tool's state changes go out as `step` and `prefetch`, the nearest origins the Unmute CLI reads.
A `state` record carries the caller's own values. A value over 4 KiB is cut, with `truncated` set. Do not send these records anywhere but the local dev page.
| Measurement | Of | Pipecat | LiveKit |
| - | - | - | - |
| `first_response`, `request_duration` | each model request and piece of synthesis | the services' metrics | `llm_node`'s own clock, LiveKit's metrics |
| `first_response` | each reply | not sent | the reply's `llm_node_ttft` and `tts_node_ttfb` |
| `first_response`, `request_duration` | each transcript | the STT service's metrics | `request_duration` only, of an STT that does not stream, from LiveKit's metrics |
| `tool_duration` | each tool call | the function call frames | `tool_execution_updated` |
| `reply_latency` | each reply | caller silence to the agent's first audio | the reply's `e2e_latency` |
| `turn_detection` | each reply | the latency observer's user turn | the caller message's `end_of_turn_delay` |
| `transcription_delay` | each reply | not sent | the caller message's `transcription_delay` |
| `speech_duration` | each reply | the bot's speaking frames | the reply's speaking times |
| `text_aggregation` | each reply | the TTS service's metrics | the reply's `llm_node_ttfs` less `llm_node_ttft` |
| `playback_delay` | each reply | not sent | the reply's `playback_latency` |
| `first_speech` | the call | client connected to the first speech | session start to the earliest `playback_started` of the audio output, or to the agent first speaking when there is no audio output |
Not sent, and why:
* `breakdown` on LiveKit. LiveKit reports timings that overlap, like synthesis that starts while the model still streams. A split of the total would be made up.
* `playback_delay` on Pipecat. The transport marks the agent speaking as it writes the first audio, so there is no later playback start to measure to.
* A tool a step runs in code as it opens. No framework tool call shows it, on either side.
* A transcript's `first_response` on LiveKit. LiveKit's STT metrics carry no first response. A streaming STT's metrics carry no duration either, so its `request_duration` is not sent.
## Watch the state
`CallState.listen(callback)` is the hook behind `watch_state`. After each save that changed something, the callback gets one `StateEvent`. It holds an `origin` and its `changes`. Each change has the `field`, the new `value` as JSON, `confirmed` (or `None` for a value that never waits for the caller) and `by`.
```python theme={null}
stop = state.listen(lambda event: print(event.origin.kind, [c.field for c in event.changes]))
state.save({"count": 2}, step="book") # step book
stop()
```
* The origin is a `StateOrigin`. Its `kind` is one of nine words: `step`, `prefetch`, `call`, `call_start`, `tool`, `event`, `withdraw`, `start` or `reset`. `call` is the library saving `state.call`. Any other kind raises a validation error. `save` takes `origin=` to name it. Without it, the origin is the `step`, or a `prefetch` when `inputs` is given.
* A save that changed nothing sends nothing. A value that went back to its default because an input changed is listed with the origin `reset`. A confirmation that changed is listed too.
* `listen(callback, replay=True)` first sends the values already set, as one event of origin `start`.
* A listener that raises is logged and removed. It never fails the save.
See [State](/core/build/state) for how values are saved.
## Where to go next
Send a call's spans to Langfuse, Logfire, Coval or Datadog.
Every span and attribute.
# Handoffs reference
Source: https://unmute.ai/core/reference/handoffs
Every argument of HandoffContext and the two hand_off calls, the history rules, the helpers, and how each framework runs a handoff.
This page is the full detail behind [Handoffs](/core/build/handoffs). Start there to hand the call to another agent.
## What it gives you
| On a call without it | What the library does |
| - | - |
| The new agent hands the call straight back before it says a word. | Handoff tools are hidden on its first reply. [The first reply after a handoff](#the-first-reply-after-a-handoff) |
| The next agent rereads old prompts and tool calls, and gets confused. | You choose what it hears: messages, everything, the last few, a summary, or nothing. [What the next agent hears](/core/build/handoffs#what-the-next-agent-hears) |
| A cut history starts on a tool result, and the provider refuses the request. | Tool calls and results stay together. Calls to tools the new agent lacks are dropped. |
| A slow summary holds up the handoff. | The summary runs while the handoff line plays. After 8 s it falls back to messages. [The summary](#the-summary) |
| Every specialist must use the same model and voice. | Each agent can have its own. [Model and voice on each framework](#model-and-voice-on-each-framework) |
## How it works
```mermaid theme={null}
flowchart LR
T[Handoff tool runs] --> A[Line is said]
T --> S[Summary is asked for]
A --> H[History is shaped]
S --> H
H --> N[Next agent replies first]
```
1. The model calls the handoff tool. Its handler calls `hand_off`.
2. The `announce` line is said, and the handoff waits for it to play.
3. With `history="summary"`, the summary request runs while the line plays.
4. The next agent gets its history, its prompt and its tools, and its own model and voice when it has them.
5. The next agent replies first. That reply offers none of its handoff tools.
The two specs are the same on both frameworks. LiveKit makes the new agent the session's agent. Pipecat swaps the prompt, tools, tasks and model to the new spec's.
The announce line differs by framework:
* **LiveKit** says it with `allow_interruptions=False`, so the caller cannot cut it off.
* **Pipecat** has no such flag for one line. It says the line while the handoff call still runs, so `user_mute_strategies(protect=["tool_calls"])` keeps the caller from cutting it. Without that strategy, a cut line counts as played. Pipecat waits at most 30 seconds for the line.
## HandoffContext
What the agent that takes the call hears of it. Import it from `unmute_core.handoff`.
What the next agent hears. See [What the next agent hears](/core/build/handoffs#what-the-next-agent-hears) and [History rules](#history-rules).
How many items `last_n` keeps. Required with `last_n`, at 1 or more. Refused with any other history. A `max_messages` of 0 raises a Pydantic `ValidationError`.
`False` leaves tool calls and results out of `full` and `last_n`.
The model that writes a `summary`. `None` asks the agent's own model. Refused with any history but `summary`.
`HandoffContext` is a frozen Pydantic dataclass. A wrong `history`, a `max_messages` of 0, or a `max_messages` or `summarizer` that does not fit the history raises a `ValidationError` when you build it. The message names the argument and the fix. An unknown argument raises `TypeError`.
## UnmuteAgent.hand\_off
LiveKit. Call it from a `@function_tool` method of an `UnmuteAgent`, and return what it returns.
The agent that takes the call: `UnmuteAgent(spec, state=self.state)`. Build it on this agent's `CallState`, and without `telemetry`, since it records into this agent's spans. Another state raises `ValueError`. A plain `Agent` raises `TypeError`.
A line said first, which the caller cannot cut off. The handoff waits for it to play.
What the agent hears. `None` keeps what was said, without tool calls.
A tool of the new agent's own, run in code as it takes the call. See [Open the next agent on a tool](/core/build/handoffs#open-the-next-agent-on-a-tool). A tool the agent lacks, or a realtime model, raises `ValueError`.
It returns the new agent, which LiveKit switches to. It returns a refusal while a task runs.
## UnmuteFlows.hand\_off
Pipecat. Call it from the handoff tool's handler.
The handoff call's params. `hand_off` reports its result.
The agent that takes the call. Its tasks run on this call's `CallState`. Its `model` needs the call's LLM to be a `ModelCallLLMService`. With no model, it runs on the model call the service was built with. Its `name` is the name the `handoff` event shows, else the call's `agent_id`. See [AgentSpec](/core/reference/agent-spec).
The new agent's Pipecat tools, like its own handoffs. Pass it by keyword.
The new agent's voice, one of the services of `UnmuteFlows(tts=...)`. `None` goes back to that switcher's first service.
A line said first, while the handoff call still runs. The handoff waits for it to play.
What the new agent hears. `None` keeps what was said, without tool calls.
A tool of the new agent's own, run in code as it takes the call. See [Open the next agent on a tool](/core/build/handoffs#open-the-next-agent-on-a-tool). A tool the agent lacks, or a realtime model, raises `ValueError`.
The new spec's tools, tasks, `save_values` and `summarizer` replace the old agent's. They do not carry over. The line is said in the old voice, and a summary is written by the old agent's summarizer or model. The new model, voice and summarizer take over after both.
`hand_off` raises `ValueError` in these cases. The agent that holds the call keeps it.
* The spec lists a handoff that is not one of `native_tools`.
* A task names a model, or transfers to an agent `then_targets` lacks.
* The spec has a model without a `ModelCallLLMService`.
* `tts` is not one of the call's voices.
* `opens_with` names a tool the spec lacks, or the model is a realtime one.
## History rules
`HandoffContext.history` takes one of five values. A task's `history` takes the same values, for what a task step opens on.
| `history` | What the next agent hears |
| - | - |
| `messages` (default) | What the caller and the agent said. No tool calls, no prompts. |
| `full` | Everything, with tool calls and their results. No prompts. Tool calls to tools the next agent does not have, and their results, are dropped, on both frameworks. |
| `last_n` | The newest `max_messages` items. A reply's text and its tool call count apart. A call and its result stay together. Tool calls to tools the next agent does not have, and their results, are dropped, on both frameworks. The window is counted before the drop. |
| `summary` | One message: "Summary of the conversation so far: ..." |
| `reset` | Nothing. The next agent answers on its prompt alone. |
* The `announce` line is the last thing the next agent hears, in `messages`, `full` and `last_n`.
* A step's `finish` calls and the step-start cue never cross. The step-start cue is the short line `(The call continues.)` that opens a step when the caller has said nothing in it yet. The next agent would read them as its own work, or as the caller.
* On a realtime model, only `full` works. The model keeps the whole conversation on its server. Pass `HandoffContext(history="full")`. Any other value is refused. See [Realtime models](/core/models/realtime).
## History helpers
`shape_history(messages, context, tools=None)` applies one `HandoffContext` to an OpenAI-format chat. It uses smaller helpers, and `unmute_core.handoff` exports them for your own code. Each one takes a list of messages and returns a new list. The input does not change.
| Helper | What it returns |
| - | - |
| `shaped(messages, history, max_messages=, include_tool_calls=, tools=)` | The same as `shape_history`, from a `history` word and not a context. |
| `without_instructions(messages)` | The chat without system and developer messages. |
| `speech_only(messages)` | What was said out loud. No tool call and no tool reply. |
| `last_n(messages, limit)` | The newest `limit` messages. It drops a tool reply whose call fell outside the window. |
| `without_calls_to(messages, names)` | The chat without calls to `names` and their replies. |
| `without_unknown_calls(messages, tools)` | The chat without calls to any tool outside `tools`, and their replies. |
| `without_text_signatures(messages)` | Earlier spoken replies without provider data like a Gemini thought signature. A tool call keeps its own. |
Two more read a single message:
```python theme={null}
from unmute_core.handoff import call_name, newest_caller
newest_caller(chat, skip_cue=True) # the caller's newest message, or None
call_name(call) # the function name of one tool_calls entry, or None
```
1. `newest_caller(messages, skip_cue=)` returns the caller's newest message. It returns the message itself, not a copy.
2. With `skip_cue=True`, it passes over the step-start cue, which the caller never said. It returns the turn before the cue.
3. `call_name(call)` reads the name from one entry of a message's `tool_calls`.
## The summary
```python theme={null}
HandoffContext(history="summary", summarizer=my_model_call)
```
1. The library sends one model request at the `summary` site, with no tools. It holds a fixed prompt and the conversation as `role: text` lines. Prompts, tool calls and tool results are left out.
2. `summarizer` is any `ModelCall`, like a LiveKit plugin in `LiveKitModel`. Without one, the agent spec's `summarizer` answers. Without that, the model of the agent that hands off answers, by the path the finish check uses.
3. On Pipecat, the agent's own model can answer only through a `ModelCallLLMService`, an OpenAI-compatible service or a `GoogleLLMService`. Give any other service a `summarizer`.
4. A summary that fails, comes back empty, or takes longer than 8 seconds is dropped. The next agent then hears `messages`. The call goes on.
5. The request is traced as an `llm` span in the open turn, with site `summary`.
6. On the SLNG Context Router, the request goes out under the agent's own id, with prompt site `task:summary`. The router accepts only `task:` as a prompt site, so no task or group may be named `summary`. See [SLNG](/core/models/slng).
The spec's `summarizer` writes the summaries for every handoff from that agent that has no summarizer of its own. It is the same `AgentSpec(summarizer=...)` on both frameworks.
## Model and voice on each framework
Each agent may have its own model and voice, as Unmute's `think:` and `speak:` per agent. The guide shows the code in [Give the next agent its own model and voice](/core/build/handoffs#give-the-next-agent-its-own-model-and-voice).
1. The `announce` line plays in the old voice, and a `summary` is written by the old model.
2. Then the new model and voice take over. The new agent's first reply, its steps, finish checks and summaries all use them.
3. An agent whose spec has no `model` runs on the call's first model. That is the session's LLM on LiveKit, and the model call the `ModelCallLLMService` was built with on Pipecat. The same holds for the voice.
4. The `llm` spans name the model each request went to. The `tts` spans name the voice.
On LiveKit:
1. The spec's `model` takes a LiveKit plugin as `LiveKitModel(plugin)`, or any other `ModelCall`, like the SLNG Context Router. Without it, the agent runs on the session's LLM.
* A `ModelCall` is retried as the session retries its own LLM. It uses the session's `conn_options`. It retries only before the first event, and only when the call does not retry itself (`retries_itself`).
* When the session closes, the agent closes its `ModelCall`s, like the router's HTTP client. A LiveKit LLM plugin stays open. LiveKit owns it.
2. A plugin answers as the session's LLM does. The library fills the prompt, and the plugin's chunks pass through unchanged.
3. `UnmuteAgent(tts=...)` is the agent's voice. Without it, the agent speaks with the session's TTS.
4. The agent's steps run on its model and speak with its voice. A task's own `model` still wins for its steps.
5. The spec's `summarizer` and `task_models` take a plugin the same way, as `LiveKitModel(plugin)`.
6. `LiveKitModel(plugin)` is the plugin as a `ModelCall`. It also fits `HandoffContext(summarizer=LiveKitModel(openai.LLM(model="gpt-5.6-luna")))` and a `FallbackModelCall`. A tool call's provider data, like a Gemini thought signature, comes back as `ToolCall.extra`, and the plugin sends it back when the call is replayed.
On Pipecat:
1. The spec's `model` needs a `ModelCallLLMService`. The service swaps the model call it sends through. A native Pipecat service runs one model, and a spec with a `model` is refused there. For an agent on its own native model, give its spec `model=OpenAIModelCall("gpt-5.6-terra")`. See [OpenAIModelCall](/core/reference/model-call#openaimodelcall). The service closes each model call it was given when the pipeline ends.
2. A spec with no `model` goes back to the model call the service was built with. A handoff back to the first agent passes its spec, with no model.
3. `hand_off(tts=...)` is one of the services of the `VoiceSwitcher`, the voice that speaks next. `tts=None` goes back to the switcher's first service.
4. Two voices of one provider are two instances of its service. Each opens its own connection as the pipeline starts.
5. `VoiceSwitcher` is Pipecat's `ServiceSwitcher` with one fix. A plain one lets each frame out once, so Pipecat's flush probe is lost on its way back, and every handoff and task waits out the flush timeout. `UnmuteFlows(tts=...)` refuses a plain one.
## The first reply after a handoff
An agent that could hand the call on before it said anything would ping-pong. So three first replies leave out the agent's handoff tools:
* The first reply after a handoff.
* A greeting the model words, which answers no caller turn.
* The opening reply of a task step that offers handoffs.
```python LiveKit theme={null}
billing = AgentSpec(BILLING_PROMPT, name="billing", handoffs=("to_front_desk",))
await self.hand_off(Billing(billing, state=self.state, native_tools=[...]))
```
```python Pipecat theme={null}
billing = AgentSpec(BILLING_PROMPT, name="billing", handoffs=("to_front_desk",))
await flows.hand_off(params, billing, native_tools=[...])
```
1. The spec's `handoffs` names the agent's handoff tools. Neither framework can tell a handoff tool from any other. On LiveKit they are `native_tools` or `@function_tool` methods.
2. The first reply after the agent takes the call offers every other tool. A tool it calls is answered with the handoffs still left out.
3. The first request after the caller speaks offers them again.
4. A realtime model keeps every tool.
5. For a greeting, give the first agent's spec its `handoffs` too. It is the same `AgentSpec(handoffs=...)` on both frameworks. A greeting you write yourself makes no model request, so it needs none of this.
## Step handoff rules
The rules for a handoff a task step offers. The guide shows the task in [A handoff from a task step](/core/build/handoffs#a-handoff-from-a-task-step).
1. The step offers `to_notes` after its own tools, with the same name and description as the main agent's. Its opening reply leaves `to_notes` out. It comes back on the first request after the caller speaks in the step.
2. The handoff tool must be one of the agent's own tools: a `native_tools` entry, or a LiveKit `@function_tool` method. The agent refuses a task that names any other tool.
3. When the step's model calls it, the step ends with `task.handed_off`. Its task or group ends with it, and nothing is saved.
4. The next agent hears the step's own chat, shaped by the handoff's `context`.
5. A handoff in the same reply as another call of the step is refused, and asks for no reply. The other call runs. A handoff in a later reply of the same turn, after the step's own tool returned, is not refused.
6. The step ends only once the next agent is ready. A handoff tool that raises, or returns no agent, leaves the step running.
## Group transfer rules
A task group with `then="transfer"` gives the call to the agent its `then_target` names, once its last step completes:
```python theme={null}
TaskGroupSpec(
name="take_payment",
when="The caller is ready to pay.",
steps=("confirm_amount", "take_card"),
context_scope="shared",
then="transfer",
then_target="billing",
)
```
The agent runs the handoff you would write for a handoff tool. `then_targets` maps
each target name to it.
```python LiveKit theme={null}
billing = AgentSpec(BILLING_PROMPT, name="billing", tasks=billing_plan)
# The agent that ran the group comes in, its hand_off goes out
UnmuteAgent(
front_desk,
state=state,
then_targets={
"billing": lambda agent: agent.hand_off(
UnmuteAgent(billing, state=agent.state), announce="One moment."
)
},
)
```
```python Pipecat theme={null}
billing = AgentSpec(BILLING_PROMPT, name="billing", tasks=billing_plan)
# The same handler a handoff tool has
async def to_billing(params: FunctionCallParams) -> None:
await flows.hand_off(params, billing, announce="One moment.")
flows = UnmuteFlows(front_desk, ..., state=state, then_targets={"billing": to_billing})
```
1. A group whose target `then_targets` does not name is refused when the agent is built. On Pipecat, so is a `hand_off` to a spec with such a group, because one `then_targets` serves every agent of the call.
2. The last step's words play first. Then the handoff runs as from a tool: its `announce` line, its `context`, and the next agent replies first. The main agent is not asked for a reply.
3. The next agent hears the main agent's history as the group left it. That is what was said before the group, the caller turn a step carried back, and the step's spoken closing line. The steps' own talk stays in the group, as it does when the group returns. Saved values reach the next agent through its prompt.
4. The group's own tool call never crosses, as a handoff tool's call does not.
5. A group that hands the caller back, or fails, returns to the main agent instead. So does a transfer whose handoff raises, or hands nothing over. The caller is never left in silence.
6. The main agent's tool description says that the flow does not return: "This flow does not return to you: when it finishes the caller is handed to the billing."
## A handoff on a plain agent
On Pipecat, `UnmuteFlows` works without tasks. A spec with only a prompt is enough.
On LiveKit, `UnmuteAgent.hand_off` does the full handoff. A plain `Agent` hands off the LiveKit way, by returning a new agent from a tool. `shape_chat_ctx` gives the next agent the history the library's rules keep. Pass its result as `chat_ctx`. The guide shows both in [Hand off from a plain agent](/core/build/handoffs#hand-off-from-a-plain-agent).
`shape_chat_ctx(chat_ctx, context=None)` returns a LiveKit `ChatContext`. With no `context`, it keeps what was said, without tool calls. With `history="summary"`, it keeps what was said too. Ask your own model for a summary if you want one. `UnmuteAgent.hand_off(plain_agent)` raises `TypeError` and names this recipe.
For OpenAI-format messages, `shape_history(messages, context, *, tools=None)` does the same and returns a new list. With `tools`, it drops any call to a tool not in that collection, and its reply. A full handoff on LiveKit, with the announce line, the model and voice switch and the summary, needs `UnmuteAgent.hand_off`.
## Troubleshooting
### A handoff is refused while a task runs
A handoff beside a running task is refused, unless that task's step made it. A task called in the same reply as a handoff that went first is refused too.
**Fix:** let the task finish, or offer the handoff from the step with `TaskSpec.handoffs`.
### `hand_off needs an agent built on the same CallState.`
LiveKit raises `ValueError` when the new agent holds another state. It raises `TypeError` when the new agent is not an `UnmuteAgent`.
**Fix:** build the new agent on the first agent's state. For a plain `Agent`, return it from the tool and build it with `chat_ctx=shape_chat_ctx(...)`.
```python theme={null}
return await self.hand_off(UnmuteAgent(specialist, state=self.state))
```
### A spec with a `model` is refused on Pipecat
A native Pipecat service runs one model.
**Fix:** build the LLM as a `ModelCallLLMService`, and pass the voices through a `VoiceSwitcher`.
### The next agent hands the call straight back
Neither framework can tell a handoff tool from any other.
**Fix:** name the new agent's handoff tools in its spec's `handoffs`.
## How Unmute uses handoffs
Unmute's `handoffs:` block (`to`, `when`, `announce`, `context`) and a task's `handoffs:` map to this API. [How Unmute uses unmute-core](/core/start/unmute-and-core) shows which key becomes which class.
Where Unmute's LiveKit and Pipecat code differ, the library does one thing on both:
* `summary` works on Pipecat too. Unmute refuses it there.
* A failed summary falls back to `messages`. In Unmute, the handoff tool raises.
* `last_n` keeps a tool call whose result is in the window. LiveKit's `truncate` drops it. Unmute's Pipecat code keeps it.
* A step handoff beside another call is refused at once. Unmute waits for the other call, then refuses when it ended the step or failed.
* A group's `then: transfer` and `then_target` map to `TaskGroupSpec`, and the target to `then_targets`. Unmute's LiveKit code transfers a group that stopped unserved too. The library returns it to the main agent, as for `then: end`. Unmute's handoff has no line and keeps the whole history. Here the handoff in `then_targets` decides both.
* The first reply after a handoff leaves out the new agent's handoffs on Pipecat too. Unmute's Pipecat code offers them.
* On Pipecat, one pipeline runs every agent. The model switches inside a `ModelCallLLMService`, and the voice through a `VoiceSwitcher`. Unmute builds one worker per agent, each with its own LLM and TTS.
## Where to go next
Hand the call to another agent, with its own model and voice.
The `AgentSpec` each agent of a call is built from.
`TaskSpec.handoffs` and `TaskGroupSpec`.
How `agent.yaml` declares a handoff.
# Hooks reference
Source: https://unmute.ai/core/reference/hooks
Every hook point, event and argument, the rules each point follows, and where a hook does not reach.
This page is the full detail behind [Hooks](/core/build/hooks). Start there to add hooks to a call.
## What it gives you
| On a call without it | What the library does |
| - | - |
| A rule about prompts or tools is written twice, once per framework. | One set of hooks runs on both. |
| A buggy hook breaks the tool or the call. | A failed hook is logged. The model reads that the tool did not run. [Hooks around a tool call](#hooks-around-a-tool-call) |
| One model needs `/no_think` on every prompt, summary and check. | `PromptSuffix` adds it everywhere that model reads. [A suffix after every prompt](#a-suffix-after-every-prompt) |
| A tweak for one model changes all of them. | Rules can read the model name per request. [Rules for one model](#rules-for-one-model) |
| Hooks silently do nothing on an agent that cannot run them. | The call logs one warning that names the fix. [Where the model hooks run](/core/build/hooks#where-the-model-hooks-run) |
## How it works
```mermaid theme={null}
flowchart LR
H[Hooks] --> C[CallHooks, one per call]
C --> P[prompt]
C --> M[before_model, wrap_model, after_model]
C --> T[before_tool, wrap_tool, after_tool]
C --> L[before_call, wrap_failure]
C --> O[on: events]
```
1. `prompt` hooks change each system prompt the library builds: the agent's, each task step's, a finish check's and a summary's.
2. `before_model` hooks change the request about to go out. `wrap_model` hooks run around it. `after_model` hooks hear the answer.
3. `before_tool` hooks change or refuse a tool call. `wrap_tool` hooks run around it. `after_tool` hooks may replace its result.
4. `before_call` hooks run before the greeting. `wrap_failure` hooks run around the failure line.
5. `on` observers watch events. They never change anything.
Define `hooks` once, at import. Build one `CallHooks` per call. Every adapter already takes `call=`, so the hooks reach every request and tool of the call. See [Many calls at once](#many-calls-at-once) for what calls share.
## The points
| Point | Signature | What it may do |
| - | - | - |
| `prompt` | `(text, PromptInfo) -> str` | Return the new prompt. It is still unfilled. |
| `before_model` | `(ModelRequest) -> ModelRequest \| None` | Change messages and `params`. None keeps the request. |
| `wrap_model` | async generator `(request, handler)` | Call `handler(request)` and yield its events, or not. |
| `after_model` | `(ModelRequest, ModelResponse) -> None` | Watch the reply. The caller has heard it already. |
| `before_tool` | `(ToolRun) -> ToolRun \| Refuse \| None` | Change the arguments, or refuse the call. |
| `wrap_tool` | `async (ToolRun, handler) -> result` | Call `await handler(run)`, or not. |
| `after_tool` | `(ToolRun, result) -> result \| None` | Replace what the model reads. None keeps it. |
| `before_call` | `() -> None` | Raise to fail the call before the greeting. |
| `wrap_failure` | `async (component, error, handler)` | Call `handler()` for the failure line, `handler(line=None)` to only hang up, or neither. Returning without calling `handler` keeps the call going. |
| `on(*patterns)` | `(event, data) -> None` | Watch. |
1. `before_*` and `prompt` hooks run first to last.
2. `wrap_*` hooks nest. The first one added is the outermost.
3. `after_*` hooks run last to first.
4. Any hook may be sync or async, except `prompt`, which must be a plain function, and `wrap_*`, which must be async.
5. A hook that raises fails its own request or tool call. A model request that fails this way fails the call, as a failed model call does. A tool call becomes a `ToolError` the model reads.
6. An `after_tool` hook that raises is logged, and the model reads the tool's own result, because the tool already ran. An `after_model` hook or an observer that raises is only logged.
7. On Pipecat, an `after_model` hook reads each tool call's arguments as UTF-8 JSON, like `{"name": "José"}`. It never sees `é` escapes. The Pipecat span and LiveKit show the same text.
8. `ModelRequest` and `ToolRun` are frozen Pydantic dataclasses. `dataclasses.replace(request, ...)` builds a new object and checks it again. A wrong type, like `site=5`, raises a `ValidationError`. An unknown argument raises `TypeError`. `messages`, `tools` and `params` are not checked, so a hook may put any JSON in them.
## Hooks around a tool call
Every tool call of a call passes the tool hooks. The `before_tool`, `wrap_tool` and `after_tool` points are the home for this.
```python theme={null}
result = await registry.call("refund", {"order_id": "A-1"}, state, hooks=call)
```
1. `ToolRegistry.call(..., hooks=...)` runs the call's tool hooks in this order: `before_tool`, then the checks and the locked values, then `wrap_tool` around the tool, then `after_tool`.
2. A `before_tool` hook that returns `Refuse(message)` stops the call. The model reads `{"refused": message}`, as for a value not set yet.
3. A hook that changes the arguments gets them checked against the schema again.
4. Every adapter passes the call's `CallHooks`. So the hooks reach every tool of `UnmuteAgent` and `UnmuteFlows` with no more wiring.
5. A `ToolRun` holds `name`, `arguments` as the model wrote them, and `source`. The source is `model`, or `event` for a [tool on an event](/core/build/call-lifecycle#tools-on-events).
On a plain agent, pass the call's hooks to the tools yourself, as in [Run tool hooks on a plain agent](/core/build/hooks#run-tool-hooks-on-a-plain-agent). Pass `hooks=call` so the tool hooks run, and so `tool_succeeded` and `tool_failed` events fire for your tools. A `CallHooks` also drains the registry's webhooks when the call ends. You do not call `call.watch` yourself.
Framework tools skip the tool hooks: end call, handoffs and `native_tools`. So do prefetch lookups. See [Known limits](#known-limits).
## Writing hooks as a class
```python theme={null}
class Audit:
events = ("tool.*",)
def before_model(self, request: ModelRequest) -> ModelRequest:
return replace(request, params={"temperature": 0})
def on_event(self, event: str, data: dict) -> None:
log.info("%s %s", event, data["name"])
hooks = Hooks(Audit(), EventTool(log_call, on=["call_end"]))
```
1. `hooks.add(obj)`, or `Hooks(obj, ...)`, hooks the object in with each method named after a point.
2. An `on_event(event, data)` method watches the patterns in its `events` attribute. All events when it has none.
3. An `EventTool` is a hook too. See [The call's life](/core/build/call-lifecycle#tools-on-events).
4. An object with none of these raises `ValueError`.
## Events
| Event | Data |
| - | - |
| `call.first_user_message` | `{"text": ...}` |
| `call.failed` | `{"component": ..., "error": ...}` |
| `call.recovered` | `{"component": ...}`. A `wrap_failure` hook kept the call going. |
| `call.tts_failed` | `{"component": ..., "error": ...}`. The voice failed. The call stays open. |
| `call.ended` | `CallEnd`. The end waits for these observers, up to `end_timeout_s`. |
| `tool.started`, `tool.succeeded`, `tool.failed`, `tool.refused` | `{"name", "source", "ms", "error"}` |
| `state.changed` | `StateEvent` |
| `task.*`, `group.*` | The task event's data. See [Tasks](/core/build/tasks). |
1. A pattern may hold `*`, like `task.*`.
2. A pattern that matches no event raises `ValueError` when you register it.
3. A sync observer runs at once. An async one runs as a task of its own, except for `call.ended`, which the end waits for. Another async observer still running when the process stops is cut off.
## A suffix after every prompt
```python theme={null}
hooks.add(PromptSuffix("/no_think"))
hooks.add(PromptSuffix("/no_think", model="qwen/qwen3-32b"))
```
Some models take an instruction no parameter carries, like Qwen3's `/no_think`. `PromptSuffix` adds it after every prompt, after a blank line. It follows Unmute's `prompt_suffix`.
1. It reaches the agent's prompt, every task step's, the finish checks' and the summaries'.
2. With `model=`, only prompts that model reads get it. A summarizer of another model keeps its prompt as it is.
3. It refuses blank text, more than 512 characters, and a `{{...}}` placeholder. Each refusal says what to do instead.
4. The native path and a `ModelCall` give the model the same final prompt.
## Rules for one model
```python theme={null}
@hooks.before_model
def no_think(request: ModelRequest) -> ModelRequest | None:
if "nemotron" not in request.model:
return None
return replace(request, params=request.params | {"temperature": 0})
```
1. `request.model` names the model that answers, like `gpt-5.6-luna`.
2. `request.params` are extra body fields for this request only.
3. `RouterModelCall` sends them. A request's `params` win over the router call's `body`. See [SLNG](/core/models/slng).
4. A native LLM gets them as `extra_body`, when it is OpenAI compatible.
## Many calls at once
```mermaid theme={null}
flowchart LR
S[Hooks at import: functions only] --> A[call A: CallHooks, state, tasks, LLM service]
S --> B[call B: CallHooks, state, tasks, LLM service]
```
1. A `Hooks` object holds only your functions. Many calls may share it, in one process or across threads.
2. Everything a call changes lives in its own objects: `CallHooks`, `CallState`, the adapter with the `CallTasks` it builds and, on Pipecat, the LLM service. Each call builds its own. Build the `AgentSpec` per call too when it holds a model, because the adapter closes its models when the call ends.
3. The library refuses a second call on the same object. A `CallHooks` binds once. `CallTasks.use` takes one call's hooks. A Pipecat LLM service runs one call's hooks.
4. A hook that keeps state, or needs to know its call, belongs to that call. Build it per call, together with the shared hooks:
```python theme={null}
SHARED = Hooks(PromptSuffix("/no_think"))
async def entrypoint(ctx: JobContext) -> None:
hooks = Hooks(SHARED, RoomLog(ctx.room.name)) # your class, one per call
call = CallHooks(state, hooks=hooks)
```
`Hooks(SHARED, ...)` copies the shared hooks in as they are at that moment. A hook added to `SHARED` later reaches only the calls built after it.
## Hooks
Import it from `unmute_core.hooks`.
Objects to add at once, each as for `hooks.add`. A function, a class instance, an `EventTool` or another `Hooks`.
## PromptSuffix
The suffix, like `/no_think`. It is stripped. It may not be blank, longer than 512 characters, or hold a `{{...}}` placeholder.
Only prompts this model reads get the suffix. None adds it for every model. Pass it by keyword.
## Refuse
Why the tool did not run, in words the model can pass on.
## PromptInfo
Which prompt a `prompt` hook is filling.
An empty string for the main prompt, `task:` in a step, `summary` for a summary.
The model that will read the prompt, like `gpt-5.6-luna`, or `unknown`.
## ModelResponse
What an `after_model` hook gets. Import it from `unmute_core.hooks`.
The text the agent said.
The tools the model called.
The error's type name when the request failed. A Pipecat pipeline request reports its failure through `call.failed` instead.
True when the caller cut the reply off.
## Known limits
1. `wrap_model` reaches only requests a `ModelCall` answers. A framework's own LLM keeps its own retries and fallback.
2. On native Pipecat:
* a hook that changes the tools is ignored, with one warning.
* the system prompt must stay the first message, and a hook sees the service's own prompt, without the guidance Pipecat adds to it.
* `params` reach only OpenAI-compatible services.
3. On native LiveKit, `params` need an OpenAI-compatible plugin, and the plugin's own `extra_kwargs` win.
4. Framework tools (end call, handoffs, `native_tools`) and prefetch lookups skip the tool hooks.
5. Under `FallbackModelCall`, `before_model` runs once. Every fallback gets the same `params`, and `request.model` names the first.
6. With `slng/auto`, the client does not know which model the router picks. A rule for one model then belongs in the router.
## Troubleshooting
### ValueError: matches no event
An `on(...)` pattern matches nothing. The message lists every event.
**Fix:** use a name from [Events](#events), or a pattern like `task.*`.
```python theme={null}
@hooks.on("tool.*")
def watch(event: str, data: dict) -> None: ...
```
### ValueError: hooks in nowhere
`hooks.add(obj)` got an object with no method named after a point and no `on_event`.
**Fix:** give it a method such as `before_model`, or an `on_event` method.
### TypeError: a prompt hook is async
A `prompt` hook must be a plain function. Adapters build prompts where nothing can wait.
**Fix:** do async work in `before_model` instead.
### A second call refuses the same CallHooks
A `CallHooks` binds to one call.
**Fix:** build a `CallHooks` per call from the shared `Hooks`.
```python theme={null}
call = CallHooks(state, hooks=Hooks(SHARED, RoomLog(room_name)))
```
## Where to go next
Add hooks to a call, and change prompts, requests and tool calls.
`CallHooks`, tools on events, the failure line and the end.
# LiveKit adapter reference
Source: https://unmute.ai/core/reference/livekit
Every argument of UnmuteAgent, the model classes and the call helpers on LiveKit, and the rules they follow.
This page is the full detail behind [LiveKit](/core/frameworks/livekit). Start there to run the library in your own LiveKit agent.
## How it works
```mermaid theme={null}
flowchart TD
S[AgentSession] --> A[UnmuteAgent]
A -->|task tool| R[Task run, core]
R -->|next_step| T[StepTask, one AgentTask per step]
A --> N[llm_node]
T --> N
N -->|no model, or a plugin| P[agent or session LLM plugin]
N -->|a ModelCall| M[ModelCall]
S -->|session events| X[Telemetry spans]
```
1. The main agent gets its tools, plus one tool per task and group.
2. A task tool starts a run in the core. The run hands out one step at a time.
3. Each step is a LiveKit `AgentTask`, awaited inside the tool call. It opens on the history the core's rule gives it.
4. When the run ends, the main agent gets its own history back. A caller turn a step answered for it comes too.
5. Every model request goes through one `llm_node`. It puts the prompt of the agent or step into the request as it reads now.
6. With no `model`, or a `LiveKitModel` plugin, the library fills the prompt from the call state and the plugin answers. Its output passes through unchanged.
7. With a `ModelCall`, the request goes to it in OpenAI format, with the prompt site (the place where the prompt is used) and the variables. A native call fills the prompt. The SLNG router fills it on its side.
8. Session events become spans. The names are in the [Telemetry reference](/core/reference/telemetry#span-contract).
## UnmuteAgent
```python theme={null}
from unmute_core.livekit import UnmuteAgent
```
`UnmuteAgent` is a LiveKit `Agent`. `spec` is the only positional argument. The others are keyword only.
The agent: its prompt, tools or tasks, models, language and handoff tools. Its `name` is the LiveKit id a `handoff` event shows. With no name, the id is the call's `agent_id`. With no name and no state, LiveKit derives the id from the class name. Every field is on [AgentSpec](/core/reference/agent-spec).
The call state that prompts and tools read. None takes the state of `call`, so the call keeps one state and one `session_id`. The spec's `tasks` and `save_values` need one.
The call's hooks: tools on events, the failure line and the end of the call. Each model request waits for the tools on events. Give every agent of one call the same object. See [The call's life](/core/build/call-lifecycle).
The call's telemetry, new for this call. Spans start when the agent enters. It closes when the session closes.
LiveKit tools the main agent gets as they are, like `EndCallTool`. A `@function_tool` method of a subclass is one too. A step gets the ones its task lists in `handoffs` or `native_tools`.
The agents a group goes to when its `then` is `transfer`, by `then_target`. Each one returns `agent.hand_off(...)`. See [Handoffs](/core/build/handoffs).
The agent's voice. Its steps speak with it too. None uses the session's TTS.
LiveKit's own `Agent` options, passed on as they are. For example `chat_ctx`, `stt`, `vad`, `turn_handling` and `allow_interruptions`.
`AgentSpec` refuses `tools` beside `tasks`, and a task model that `task_models` does not name. `UnmuteAgent` raises `ValueError` in these cases:
* The spec has `tasks` or `save_values`, and there is no state.
* The spec's timezone is unknown.
* A task lists a handoff the agent has no tool for.
* A group transfers to an agent `then_targets` lacks.
* The spec's `handoffs` names a tool the agent does not have.
* A task's tool input names a prefetch lookup the call's `prefetch` lacks.
* A placeholder makes a key longer than the model call takes. The router takes 64 characters. A native model has no limit.
* A task or group has the same name as another tool of the agent, like `end_call`.
### UnmuteAgent attributes
The spec the agent was built with.
The call state the agent was built with. With none, it is the `state` of the agent's `call` hooks. `state.call` holds what the call carries.
The call's task runs, built from the spec. None for an agent without `tasks`.
The names of the agent's handoff tools, from the spec.
### UnmuteAgent.hand\_off
A handoff tool returns `await self.hand_off(UnmuteAgent(other_spec, state=self.state), announce=..., context=...)`. Build the next agent on this agent's `CallState`, and without `telemetry`: it records into this agent's spans. The model, voice, history and announce rules are on [Handoffs](/core/build/handoffs). An agent built on another state raises `ValueError`. For a plain `Agent`, `hand_off` raises `TypeError`. Return the plain agent from the tool instead, built with `shape_chat_ctx`.
## The model
With no `model` in the spec, the agent runs on the session's LLM. To give the agent its own plugin, pass `AgentSpec(model=LiveKitModel(plugin))`. A LiveKit plugin answers as it does on a plain agent. The library fills the prompt and passes the plugin's chunks through unchanged. A value reaches the model whole.
To use another provider, give the spec a `ModelCall`. `OpenAIModelCall` reaches any OpenAI-compatible endpoint. See [Model call](/core/models/model-call). The SLNG Context Router is one more `ModelCall`. Leave `llm` out of the session when you give one. Each router request carries your own router config, so the model runs on your own OpenAI key. See [SLNG](/core/models/slng) for the router.
1. A `ModelCall` is retried as the session retries its own LLM. It uses the session's `conn_options`. It retries only before the first event, and only when the call does not retry itself (`retries_itself`).
2. When the session closes, the agent closes its `ModelCall`s, like the router's HTTP client. A LiveKit LLM plugin stays open. LiveKit owns it.
3. A model that fails after its reply began does not fail the call. The reply ends as it stands, and the next turn runs.
### ModelCallLLM
`ModelCallLLM` runs a `ModelCall` as the session's LLM. Use it on a plain agent.
```python theme={null}
from unmute_core.livekit import ModelCallLLM
session = AgentSession(llm=ModelCallLLM(router, state=state), ...)
```
The model call that answers.
The call state the prompt's placeholders read.
The session's trace from `trace_session`. Each request is then an `llm` span in its turn.
The prompt site of each request. `""` is the main prompt, and `task:` is a step.
The call's hooks. Each request waits for the tools on events and ends with their notes. None uses the trace's hooks.
### filled\_llm
`filled_llm` is for a plain `Agent` that keeps its own LLM plugin. Call it from the agent's `llm_node`. It fills the prompt from the call state on each request. It needs no `Telemetry`.
```python theme={null}
from livekit.agents import Agent
from unmute_core.livekit import filled_llm
class Desk(Agent):
async def llm_node(self, chat_ctx, tools, model_settings):
async for chunk in filled_llm(self, chat_ctx, tools, model_settings, state=state, call=call):
yield chunk
```
The agent whose session LLM answers.
The chat LiveKit sends.
The tools LiveKit offers.
LiveKit's settings for this reply.
The state the prompt's `{{placeholders}}` read. Pass it by keyword.
The call's hooks. The request then waits for the background prefetch, ends with the tools' notes, and runs the `prompt`, `before_model` and `after_model` hooks.
End the request with the current values block, for `values_tool`.
`traced_llm` does the same and adds an `llm` span. See [On a plain agent](/core/reference/telemetry#on-a-plain-agent).
When the call has model hooks and the agent keeps LiveKit's default `llm_node` with a plain plugin, the hooks cannot run. `attach_call` logs one warning at the first reply. See [Hooks](/core/build/hooks#where-the-model-hooks-run).
### LiveKitModel
`LiveKitModel(plugin)` turns a LiveKit LLM plugin into a `ModelCall`. Its `llm` attribute is the plugin. Use it wherever a model goes: the spec's `model`, `summarizer` and `task_models`, `HandoffContext(summarizer=...)` or a `FallbackModelCall`. Inside an `UnmuteAgent`, LiveKit holds the plugin itself. The plugin keeps its own client, settings and retries. Outside an `UnmuteAgent`, it sends the request through the plugin's `chat`. A tool call's provider data, like a Gemini thought signature, comes back as `ToolCall.extra`. The plugin sends it back when the call is replayed. So a `FallbackModelCall` of Gemini plugins keeps its signatures.
## How the call opens and ends
Without a `CallHooks`, open the call step by step:
```python theme={null}
import json
from unmute_core.greeting import Greeting
from unmute_core.livekit import greet, max_duration, sip_call_info
participant = await ctx.wait_for_participant()
info = sip_call_info(participant, json.loads(ctx.job.metadata or "{}"))
state = CallState(State, call=info)
await prefetch.run(state)
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan), state=state)
await session.start(agent=agent, room=ctx.room)
greet(session, Greeting(text="Hi {{customer_name}}, thanks for calling."), state)
max_duration(session, 20 * 60)
```
With a `CallHooks`, `open_call` opens the whole call:
```mermaid theme={null}
flowchart TD
A[open_call] --> B[attach_call binds say, hang up and transcript]
B --> C[Caller audio off]
C --> D[before_call hooks and prefetch]
D -->|check fails| E[Failure line, hang up, audio stays off]
D -->|passes| F[greet]
F --> G[Caller audio back]
```
1. `open_call` attaches the hooks and turns the caller's audio off.
2. It runs the `before_call` hooks and the prefetch, and starts the background lookups.
3. It greets. A failed check says the failure line and hangs up instead.
4. The caller's audio comes back when the agent starts to speak. With `interruptible=False`, it comes back when the greeting ends. Either way it comes back after `GREETING_HOLD_SECONDS` (20 seconds) at the latest, or `max_hold_s`, so a greeting that never starts cannot hold the caller for ever.
5. A greeting the model words, on a realtime model, waits for the background lookups and for the instructions they change. That is at most the prefetch's background budget for the lookups (`BACKGROUND_BUDGET_S`, 10 seconds by default), then at most `SETTLE_WAIT_SECONDS` (5 seconds) for the instructions.
6. If the caller leaves while the checks or the prefetch run, `open_call` returns None and greets no one.
7. `idle_nudges(session, config, call=call)` and `SipLine(session, call=call)` take the hooks too. The idle hang-up is then noted as `idle`. A dial that ends on a voicemail is noted as `agent_ended`.
8. The caller leaving closes the session with LiveKit's reason `participant_disconnected`. The call's end reads `caller_hung_up`. A tool that ends the call, a group with `then: end` and a step's ending tool read `agent_ended`. See [Why the call ended](/core/build/call-lifecycle#why-the-call-ended).
The events, the failure line and the end are in [The call's life](/core/build/call-lifecycle). The greeting's own rules are there too.
### sip\_call\_info
The SIP participant, or None before it has joined.
The job's metadata, parsed. Its `direction`, when it says `inbound` or `outbound`, sets the direction.
The agent's own number, when the participant does not report it. Pass it by keyword.
The direction, when your dispatch knows it. It wins over everything else. Pass it by keyword.
The agent's id, the same on every framework. Pass it by keyword.
The call's id, when your dispatch gives one. A new one otherwise. Pass it by keyword.
It returns a `CallInfo`: the direction, the two numbers and the SIP call id as `carrier_call_id`. The room name is not stored. The direction is `direction`, else the metadata's `direction`. Else a SIP participant with the `sip.ruleID` attribute came in through a dispatch rule, so it is inbound. Else a job that names `phone_number` dials out. Any other call is inbound. A participant without `sip.ruleID` does not mean outbound by itself. A contradiction between these is no longer refused.
### greet
`greet(session, greeting, state)` says the line, has the model word a greeting, or waits for the caller. It returns the greeting's `SpeechHandle`, or None when the caller speaks first. Call it after the session has started and prefetch has run.
The call's session.
How the call opens.
The call state the line's values come from.
### open\_call
`await open_call(session, greeting, call)` returns the greeting's `SpeechHandle`, or None when the caller speaks first or a check failed.
The call's session, already started.
How the call opens.
The call's hooks, with the checks to pass.
The longest the caller's audio stays off once the greeting is queued, in case its speech never starts. Pass it by keyword.
### attach\_call
`attach_call(session, call)` does only the attaching, once per call. It binds say, shutdown and the transcript. The first unrecoverable `error` event fails the call. LiveKit counts these errors per part and closes the session on its own only at the fourth of one part, so this is sooner. A TTS error is only logged, and the call stays open. LiveKit still closes the session at the fourth unrecoverable TTS error. The session's close runs `call.end`, and the job's shutdown waits for it.
The call's session.
The call's hooks.
### max\_duration
`max_duration(session, seconds, call=call)` closes the session after that many seconds, with no closing line. It stops counting when the session closes first. Give it `call=call` and the call's end reads `max_duration`. It returns the running `CallLimit`.
The call's session.
The longest the call may run. It must be above zero.
The call's hooks. With them, the call's end reads `max_duration`.
### At the end of the call
When the session closes, the agent settles the steps' held saves and closes its models before the telemetry closes. Inside a LiveKit job, the job's shutdown waits for all of it. The library stops waiting after 15 seconds. LiveKit kills the job process after `shutdown_process_timeout`, which is 10 seconds by default. So raise it in `WorkerOptions` if the saves or the telemetry need longer. See [Tasks](/core/build/tasks).
### Phone legs
`SipLine` is a SIP call's phone leg. It transfers the caller and dials out. See [Phone calls](/core/telephony).
## Native tools and MCP
`native_tools` gives the main agent LiveKit tools as they are. A LiveKit MCP toolset is one. A step gets only the toolsets its task lists, by id. It borrows the tools inside a toolset and never the toolset itself. So a step that ends cannot close the main agent's toolset.
```python theme={null}
TaskSpec(name="look_up_customer", native_tools=("crm",), ...)
```
See [Tasks](/core/build/tasks) for a step that offers the agent's native tools.
## Rules to know
* A subclass that overrides `on_enter` must call `super().on_enter()`, or no span starts.
* A subclass that overrides `tts_node` must call `super().tts_node(...)`, or the `tts` spans stop.
* Build one `AgentSpec`, one `UnmuteAgent` and one `Telemetry` per call. Build the `ModelCall` per call too, after the state. The agent closes the models it was given when the call ends, after the call's end has finished, so a `RouterModelCall` or `OpenAIModelCall` shared across calls is closed under the others.
* Give the spec `tools` or `tasks`, not both. The task plan holds every tool.
* A `ModelCall` that raises inside `UnmuteAgent` fails the call. LiveKit alone only logs a failed `llm_node`. A model that fails after its reply began does not fail the call.
* Gemini's OpenAI-compatible endpoint keeps only the last system message. `OpenAIModelCall` folds the library's several into one for a Gemini model. A native OpenAI-compatible plugin pointed at that endpoint sends them as they are, so use the native Gemini plugin there. See [Gemini and several system messages](/core/reference/model-call#gemini-and-several-system-messages).
* With LiveKit preemptive generation, `{{call.first_user_message}}` can be a partial transcript.
* LiveKit's own spans stay off. The adapter does not call `set_tracer_provider`.
* A request a `ModelCall` answers through `UnmuteAgent` emits LiveKit's `LLMMetrics`, with the tokens and the time to the first token. `metrics_collected` and `session.usage` count it as they count an LLM plugin.
* LiveKit's AEC warm-up (`AgentSession(aec_warmup_duration=...)`, 3 seconds by default, off on an outbound SIP call) turns the caller's audio into silence while the agent speaks during that time. The caller cannot cut in on the greeting then, even though `open_call` turns their audio back on when the agent starts to speak.
* `EndCallTool` asks the model for a goodbye reply, then ends the call. With `delete_room=True`, its default, it deletes the room, which drops a phone caller. A `ToolSpec(effect="ends_conversation")` says only its `announce` line and closes the session. Set `room_io.RoomOptions(delete_room_on_close=True)` so the phone caller is dropped then too.
* LiveKit always lets a running tool finish. Tool fields and webhooks are in [Tools](/core/build/tools).
* A tool that ends the call, beside another tool in the same reply, makes no second reply. The library cancels the reply for all of them.
* A line a tool waits for (`announce_wait=True`) and the lines a `SipLine` says on a transfer cannot be cut off by the caller.
* In `record` mode, a reply that spoke and called nothing can be followed by a short finish check of up to 8 seconds. See [Tasks](/core/build/tasks).
## Where to go next
Run the library in your own LiveKit agent.
Every field of the agent, the same on both frameworks.
Every span and attribute the adapter writes.
The same detail for Pipecat.
# Model call reference
Source: https://unmute.ai/core/reference/model-call
ModelCall, ModelRequest, the events, placeholders, NativeModelCall, OpenAIModelCall and every FallbackModelCall argument.
This page is the full detail behind [The model call](/core/models/model-call). Start there to pick a model call and give it to your agent.
## What it gives you
`ModelCall` is the one plug point for model requests. An adapter builds a `ModelRequest`, streams it through a `ModelCall`, and turns the events back into framework output.
| On a call without it | What the library does |
| - | - |
| A provider fails and the caller hears silence. | `FallbackModelCall` moves to the next model. [FallbackModelCall](#fallbackmodelcall) |
| A bad key is tried on every model while the caller waits. | Errors every model would give, like 401 or 422, stop the chain at once. |
| A retry after the reply started gives a doubled sentence. | The chain moves on only before the first word. |
| A rate limit sends the call to a worse model when 1 s of waiting would work. | A short `Retry-After` waits on the same model. |
| Gemini refuses several system messages. | They are folded into one. [Gemini and several system messages](#gemini-and-several-system-messages) |
| A `` block is read aloud. | Reasoning tags are removed from the stream. |
| The model sees a different prompt depending on how you reach it. | Placeholders are filled once, the same way on every path. [The same final prompt](#the-same-final-prompt) |
## Stream one request
```python agent.py theme={null}
import asyncio
from unmute_core.model import ModelRequest, OpenAIModelCall, TextDelta
model = OpenAIModelCall("gpt-5.6-terra") # reads OPENAI_API_KEY
request = ModelRequest(
messages=[
{"role": "system", "content": "Help {{customer.name}}."},
{"role": "user", "content": "Hi."},
],
variables={"customer__name": "Ana"},
)
async def main() -> None:
async for event in model.stream(request):
if isinstance(event, TextDelta):
print(event.text, end="")
asyncio.run(main())
```
`OpenAIModelCall` fills the prompt, then sends it to any OpenAI-compatible endpoint. A framework's own LLM plugin works the same way through `NativeModelCall`. Another provider is another `ModelCall`. For example, the [SLNG page](/core/models/slng) shows `RouterModelCall`, which sends the unfilled prompt and lets the router fill it.
## How a request flows
```mermaid theme={null}
flowchart LR
A[Adapter] --> R[ModelRequest]
R --> N[NativeModelCall]
R --> S[RouterModelCall]
R --> Y[Your ModelCall]
N --> L[Framework LLM]
S --> C[Context Router]
```
1. The adapter builds a `ModelRequest`. On LiveKit it is `ModelCallLLM`. On Pipecat it is `ModelCallLLMService`.
2. The adapter calls `stream(request)` on the `ModelCall`.
3. The call sends the request to a model.
4. The call yields `TextDelta` and `ToolCall` events. It yields a `Usage` event last when it knows the token counts.
5. The adapter turns the events into LiveKit chunks or Pipecat frames.
## ModelCall
A protocol with one method, `stream`. Any class that has it is a `ModelCall`.
### stream
Streams the model's text and tool calls for one request.
The request to send. The prompt is still unfilled.
It returns an `AsyncIterator[ModelEvent]`.
## ModelRequest
A frozen Pydantic dataclass. It holds one request, with the prompt still unfilled. A value of the wrong type, like `site=1`, raises a `ValidationError`. An unknown argument raises `TypeError`. To change a request, build a new one with `dataclasses.replace`, which checks it again.
The chat in OpenAI format. Placeholders like `{{name}}` are not filled.
The tools the model may call, as OpenAI function schemas.
The prompt site: the place where the prompt is used. An empty string for the main prompt, or `task:` while a task runs.
Placeholder name to its text, from `template_variables`.
Extra HTTP headers for this request only, like `traceparent`.
`required` makes the model call a tool. `none` forbids one. `auto` and `None` leave it to the model.
The name of the model that answers, like `gpt-5.6-luna`. A `before_model` hook can read it. Under `FallbackModelCall` it is the first call's name. It is empty when unknown.
Extra body fields for this request only, like `{"temperature": 0}`. `RouterModelCall` sends them. An OpenAI compatible framework LLM gets them as `extra_body`.
The call's `before_model` hooks may change a request. `wrap_model` hooks run around a `ModelCall`. See [Hooks](/core/build/hooks).
## Events
A call streams three kinds of event.
| Event | Fields | What it is |
| - | - | - |
| `TextDelta` | `text` | The next piece of the answer. |
| `ToolCall` | `id`, `name`, `arguments`, `extra` | One whole tool call. `arguments` is the JSON text the model wrote. |
| `Usage` | `input_tokens`, `output_tokens` | The token counts, once, at the end. |
1. `extra` on a `ToolCall` holds provider data sent with the call, like a Gemini thought signature. It is empty when there is none. See [Thought signatures](/core/reference/slng#gemini-thought-signatures).
2. Both adapters put `Usage` on the `llm` span. Code that reads events skips a `Usage` it has no use for.
3. Every event is a frozen Pydantic dataclass. A value of the wrong type, like `ToolCall(id=1, ...)`, raises a `ValidationError`. Token counts in `Usage` pass through unchecked, as a provider sends them.
### ToolCall
A frozen Pydantic dataclass.
The call id the model gave.
The tool's name.
The JSON text the model wrote.
Provider data sent with the call, like a Gemini thought signature in `{"google": {"thought_signature": "..."}}`.
`to_openai()`.
Returns the call as an OpenAI `tool_calls` entry: `{"id", "type": "function", "function": {"name", "arguments"}}`. It leaves `extra` out. A span records the calls the model chose in this shape.
## Reading a whole answer
`collect(events)` reads a stream to the end and returns a `ModelAnswer`. It works on a `ModelCall`'s stream and on the stream a `wrap_model` hook sees. Use it for a side request, like a summary, where you want the whole answer and not each piece. The guide shows it in [Read a whole answer](/core/models/model-call#read-a-whole-answer).
### ModelAnswer
Every text piece, joined.
The tool calls, in the order the model made them.
The token counts, when the model gave them.
## Site and variables
A prompt holds placeholders like `{{customer.name}}`. The call state gives their values.
```python theme={null}
from unmute_core.model import template_variables
messages = [{"role": "system", "content": "Help {{customer.name}}."}]
variables = template_variables(messages, state, site="")
```
1. `site` says which prompt reads the values. A value that waits for the caller to confirm it reads as empty, except at its own task.
2. `template_variables` renders every placeholder the system and developer messages use. A dotted name `a.b` becomes the key `a__b`.
3. A placeholder the state does not have raises `MissingVariablesError`. Its message reads `Missing required template variables:` followed by the names.
User and assistant messages are never filled.
### template\_variables
The chat in OpenAI format.
The call state. Pass `None` for an agent without state.
The prompt reading the values, like `task:verify_customer`.
### fill\_messages
Fills the placeholders of the system and developer messages, as the router does. It returns a new list and raises `MissingVariablesError` when a value is missing.
The chat in OpenAI format.
The placeholder key to its text.
### render\_prompt
Fills one prompt text from the call state. Use it to give a plain framework LLM a filled prompt.
The prompt, like `"Help {{customer.name}} with their order."`.
The call state.
The prompt reading the values.
```python theme={null}
from unmute_core.model import render_prompt
prompt = render_prompt("Help {{customer.name}}.", state)
```
Render it again after a save, so the prompt shows the new values.
## NativeModelCall
A framework's own LLM. The library fills the prompt. The LLM keeps its own client, settings and retries.
```python theme={null}
from unmute_core.model import NativeModelCall
native = NativeModelCall(stream_framework_llm)
```
### NativeModelCall arguments
Takes a filled request and yields events. You rarely write one.
On LiveKit, `LiveKitModel` wraps any LLM plugin:
```python theme={null}
from livekit.plugins import openai
from unmute_core.livekit import LiveKitModel
model = LiveKitModel(openai.LLM(model="gpt-5.6-terra"))
```
Give it to an `AgentSpec` as its `model`, `summarizer` or one of its `task_models`, or to a `FallbackModelCall`. Inside `UnmuteAgent` the plugin's chunks pass through unchanged. See [LiveKit](/core/frameworks/livekit).
## OpenAIModelCall
A native call for any OpenAI-compatible chat endpoint. It works on LiveKit and Pipecat. It needs the `openai` package, which comes with the `slng` extra and with Pipecat.
```python theme={null}
import os
from unmute_core.model import OpenAIModelCall
model = OpenAIModelCall("gpt-5.6-terra")
gemini = OpenAIModelCall(
"gemini-2.5-flash",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key=os.environ["GEMINI_API_KEY"],
)
```
### OpenAIModelCall arguments
The model name sent with each request. It may not be blank.
The endpoint, ending in `/v1` or the like. It must start with `http://` or `https://`. `None` means OpenAI.
The key. `None` reads `OPENAI_API_KEY`.
A ready client. `base_url`, `api_key` and `timeout` are then unused.
Body fields for every request, like `{"temperature": 0}`. A request's own `params` win. It may not set `stream_options`.
The client timeout: seconds above zero, or an `openai.Timeout`. `0` raises `ValueError`. The default is 15 seconds to connect and 5 seconds for each read.
1. The library fills the prompt, as with any native call. The model sees the same final prompt as on the router.
2. The request carries no SLNG header and no SLNG body field.
3. The events are the same as the router's: `TextDelta`, `ToolCall` and `Usage`.
4. The client never retries. Put the call in a `FallbackModelCall` to fail over.
5. `provider` is `openai`, or the host name of `base_url`.
6. A missing `openai` package raises an `ImportError` that names the fix.
## FallbackModelCall
Tries several calls in order. It moves on when a call fails before it answers. It is itself a `ModelCall`, so it can nest.
```python theme={null}
from unmute_core.model import FallbackModelCall
model = FallbackModelCall([router, backup], first_event_timeout_s=10)
```
### FallbackModelCall arguments
The calls, first choice first. An empty list raises `ValueError`. So does a call with no `stream` method.
How long a call may take to start answering, its same-model retries included. `None` waits as long as the call does. `FIRST_EVENT_TIMEOUT_S` is 45 seconds and clears slow reasoning models.
The longest `Retry-After` worth waiting for. A longer one fails over. A value below zero raises `ValueError`.
The pause before each retry of the same call after a short failure. A short failure has no status, or is a 408, a 429 or a 5xx. A 429 with a usable `Retry-After` waits that long once instead. Empty moves to the next call at once. `SAME_MODEL_RETRIES_S` is `(0.25, 0.75)`. It is off by default because the Context Router retries by itself.
Statuses that end the chain at once. The default is 400, 401, 402, 413 and 422.
Error codes that end the chain at once, whatever their status. `None` reads the `stop_codes` of each wrapped call. A call may have none. `RouterModelCall` has `project_mode_forbidden`. `STOP_CODES` is empty.
`True` starts each request with the call that answered last, then the others in the given order. A dead first call is then tried once and not on every request. `False` always starts with the first call. LiveKit's `FallbackAdapter` works the same way.
Called at each move to the next call. A callback that raises is logged and the chain goes on.
### How it fails over
1. It never retries or fails over once the caller has part of the answer.
2. No other model fixes a stop status or a stop code, so the chain ends there.
3. `error_code(error)` reads the code of an error. `http_status(error)` reads its status.
4. `retries_itself` is `True`. On LiveKit, `ModelCallLLM` then marks the call's errors as final, so LiveKit does not walk the chain again. A plain `RouterModelCall` does not set it, so LiveKit still retries a router it cannot reach. Another call can set the attribute, and `retries_itself(model)` reads it.
5. It remembers which call answered last, so build one for each call of the agent.
6. `.model` and `.provider` name the call the next request starts with. That is the first call, or with `sticky=True` the one that answered last. `.answered` names the call that answered last, the first before any answer. `answered_model(model)` reads it, and falls back to the model's own name. Spans carry both: `gen_ai.request.model` is the call the request started with, and `gen_ai.response.model` is the call that answered.
7. `aclose()` closes every call that has an `aclose`. `close_model(model)` calls `aclose` on any model that has one and does nothing for the rest.
8. The agent closes the models it was given when the call ends. Build a `RouterModelCall` or an `OpenAIModelCall` for each call. Never share one across calls in a process, or the first call to end closes it under the others.
### FailOver
The object `on_fail_over` receives.
The position of the call that failed.
The model name of the call that failed, or `unknown`.
The model name of the call tried next, or `unknown`.
The HTTP status of the failure, or `None`.
The error the call raised. `None` when the call answered nothing.
A framework's own fallback works without this class. Native LLM plugins keep their own retries and fallback.
## Write your own
Any class with `stream` is a `ModelCall`. The guide shows a small one in [Write your own ModelCall](/core/models/model-call#write-your-own-modelcall). Give it to an adapter the way you give it the router: `ModelCallLLM(Echo())` on LiveKit or `ModelCallLLMService(Echo())` on Pipecat.
1. `model`, `provider` and `aclose` are optional. Spans show `unknown` without a name. See [Naming a call](#naming-a-call).
2. A call that does not send the prompt to a router must call `fill_messages`. `variables` holds the values.
3. Raise the error of a failed request. `FallbackModelCall` reads its status and code from it.
4. Yield `Usage` last when you know the token counts. It is optional.
## Naming a call
`NamedModelCall` is the protocol for the optional members of a call. A framework LLM carries the same names. Functions read them and fall back when one is missing.
The model name, like `gpt-5.6-luna`. `model_name(call)` returns `unknown` when it is missing.
Who serves the model, like `openai`. `provider_name(call)` returns `unknown` when it is missing.
`True` when the call retries and fails over on its own. `retries_itself(call)` returns `False` when it is missing.
The longest placeholder key the call takes, for a call that fills the prompt on its own side. `RouterModelCall` has 64. `FallbackModelCall` has the smallest limit of its calls. `variable_key_max(*calls)` returns the smallest limit, or `None` when no call has one. A native call has none, so a key is never refused on it.
Error codes after which `FallbackModelCall` tries no other call.
## The same final prompt
The model sees the same final prompt on every path.
* **Native.** The library fills the prompt with `fill_messages`. Then the framework LLM sends it.
* **Router.** The library sends the prompt unfilled with `variables`. The router fills it.
Both paths use the same placeholders, the same values and the same rule for a missing one. SLNG may add capabilities, like caching or failover. It never changes what the agent says.
One limit comes from the router, not the library. The router refuses a template variable over 4000 characters, so `RouterModelCall` cuts a longer one and logs a warning. A native call sends a value whole.
## Gemini and several system messages
Gemini's OpenAI-compatible endpoint keeps only the last system message. The library may send several, for example the prompt, the values block and notes. The values block is a system message that lists the State values. See [State](/core/build/state#saving-values-no-task-saves).
1. `OpenAIModelCall` folds every system and developer message into one system message at the front, for a Gemini model: one whose id, after any vendor prefix, starts with `gemini`. The host does not count, since a Google endpoint serves other models too. The texts join in order with a blank line. Other messages keep their order. A chat with one system message goes out unchanged.
2. SLNG's Context Router folds them too.
3. A native OpenAI-compatible plugin keeps its own client and sends the messages as they are. Pointed at that endpoint, the model may miss the earlier ones. Use the native Gemini plugin there.
## Where to go next
Pick a model call and give it to your agent.
RouterModelCall, router config, thought signatures and router errors.
Change or wrap a model request with your own code.
The `agent.yaml` side of the router.
# Pipecat adapter reference
Source: https://unmute.ai/core/reference/pipecat
Every argument of UnmuteFlows, the model service, the call helpers, observers, tools and voices on Pipecat, and the rules they follow.
This page is the full detail behind [Pipecat](/core/frameworks/pipecat). Start there to run the library in your own Pipecat pipeline.
## How it works
```mermaid theme={null}
flowchart TD
M[Main agent: its tools and one tool per task] -->|task tool| R[Task run, core]
R -->|next_step| N[Flows node per step]
N -->|run ends| M
M -->|hand_off| O[Other main agent]
```
1. `install()` puts the main agent's tools on the context, each with its handler.
2. A task tool starts a run in the core. The main agent's context is copied.
3. Each step becomes a node on the call's one `FlowManager`.
4. When the run ends, the copy comes back with the run's result.
5. `hand_off` gives the call to another main agent on the same context.
## UnmuteFlows
```python theme={null}
from unmute_core.pipecat import UnmuteFlows
```
`UnmuteFlows` runs the tasks of one call. Build one per call, then call `install()` before the pipeline runs. `spec` is the only positional argument. The others are keyword only. `UnmuteFlows` builds the call's `CallTasks` itself, from the spec.
The first agent: its prompt, tools or tasks, models, language and handoff tools. Its `model` needs `llm` to be a `ModelCallLLMService`. Its `name` is the name a `handoff` event shows. With no name, it is the call's `agent_id`. Every field is on [AgentSpec](/core/reference/agent-spec).
The LLM service, shared by every agent and every step.
The shared context.
The context's aggregator pair.
The call state. None takes the state of `call`, else a `CallState()` that keeps no values of its own. The spec's `tasks` and `save_values` need one.
The call's hooks. Each model request waits for the tools on events. A main agent request ends with their notes. Steps read the call start results. See [The call's life](/core/build/call-lifecycle).
Records a `task_step` span per step, and each task event.
Pipecat tools the first agent gets as they are, each with its handler, like a handoff or an end-call tool. A step gets the ones its task lists in `handoffs` or `native_tools`.
The agents a group goes to when its `then` is `transfer`, by `then_target`: the handler of a handoff to that agent, which calls `hand_off`. One mapping serves every agent of the call. See [Handoffs](/core/build/handoffs).
The call's voices. The first service speaks first. `hand_off(tts=...)` switches to another. A plain `ServiceSwitcher` is refused.
On Pipecat, the spec's `summarizer` also answers each finish check when the call's LLM cannot be asked: one that is not OpenAI compatible and not a `ModelCallLLMService`. With no summarizer, such an LLM gets what was said instead, and no finish check.
`AgentSpec` refuses `tools` beside `tasks`, and a task model that `task_models` does not name. `UnmuteFlows` raises `ValueError` in these cases:
* The spec has `tasks` or `save_values`, and there is no state.
* A task lists a handoff that is not one of `native_tools`.
* A task names a model. Pipecat runs every task on the agent's LLM service.
* A group transfers to an agent `then_targets` lacks.
* The spec's `handoffs` names a tool `native_tools` lacks.
* The spec has a `model`, and `llm` is not a `ModelCallLLMService`.
* `tts` is a plain `ServiceSwitcher`.
* A native tool has the same name as a registry tool, a task, a group or `save_values`.
* A task or group has the same name as another tool of the agent, like `end_call`.
* A placeholder makes a key longer than the model call takes. The router takes 64 characters. A native service has no limit.
### UnmuteFlows attributes
The spec of the agent that holds the call. Each handoff changes it.
The task runs of the agent that holds the call, built from its spec.
The call state of the agent that holds the call.
The service you passed as `llm=`, a `ModelCallLLMService` or a native one. Read it when a handler needs the service and holds only `flows`.
The model call a handoff gave the agent that holds the call. None for the first agent.
The prompt site of the next model request, the place where the prompt is used: `task:` in a step, else `""`.
For `TelemetryObserver`: the result the main agent reads for each task call, by call id. None while the task runs.
For `TelemetryObserver`: what a step's closing tool returned, by tool name.
For `TelemetryObserver`: the tools steps ran in code as they opened.
Set by `TelemetryObserver`. It traces a finish check, a model request no frame shows.
### UnmuteFlows.hand\_off
`await flows.hand_off(params, spec, native_tools=..., tts=..., announce=..., context=...)` gives the call to another main agent, described by its own `AgentSpec`. Its arguments, and the model and voice that go with them, are on [Handoffs](/core/build/handoffs).
### UnmuteFlows.listen
`flows.listen(sink)` sends every later task event of the call to `sink`, from each agent the call is handed to as well. Use it for a dev recorder: `flows.listen(recorder.task_event)`. See [Telemetry](/core/observe/telemetry).
## The model
A native Pipecat LLM service, like `OpenAILLMService`, gets its prompts filled by `UnmuteFlows`. A value reaches the model whole. A `ModelCallLLMService` gets them unfilled, with the prompt site of each request, and the `ModelCall` decides who fills them. See [Model call](/core/models/model-call) for the interface and [SLNG](/core/models/slng) for the router, one `ModelCall` you can use.
### ModelCallLLMService
Where the requests go.
The call state, read for each request's variables.
The call's hooks, run on each request. `attach_call(llm=...)` and `UnmuteFlows(call=...)` set it.
`OpenAILLMService` arguments, like `settings`. A key or a base URL is not used.
### ModelCallLLMService attributes
Where the requests go.
The prompt site of the next request. `""` is the main agent, and `task:` is a step. `UnmuteFlows` sets it.
True makes a failed model call leave the service unusable, so the call fails.
The newest request as it went out, after the hooks.
Returns the trace headers for the next request. `TelemetryObserver` sets it, so a router's spans join the turn's trace.
The service marks itself unusable when a model call raises, but only when `failure_is_final` is set. `attach_call(llm=...)` and `UnmuteFlows(call=...)` set it. Otherwise a model failure stays recoverable, as Pipecat reports it. A short error of a native Pipecat LLM is not a failure. A model error after the reply began does not fail the call either. The reply ends as it stands, the error goes on the `llm` span, and the call goes on.
The service closes each model call it was given when the pipeline ends.
## How the call opens and ends
A full opening reads the phone call's details, holds the caller until the greeting, and sets a longest length:
```python theme={null}
from unmute_core.agent import AgentSpec
from unmute_core.call import CallHooks
from unmute_core.greeting import Greeting
from unmute_core.pipecat import (
GreetingHold,
UnmuteFlows,
max_duration,
open_call,
telephony_call_info,
)
from unmute_core.state import CallState, call_phone_region, use_phone_region
info = telephony_call_info(runner_args.call_data)
state = CallState(State, call=info)
call = CallHooks(state, prefetch=prefetch)
flows = UnmuteFlows(
AgentSpec(PROMPT, tasks=plan), llm=llm, context=context, aggregators=aggregators, call=call
)
hold = GreetingHold()
# user aggregator: LLMUserAggregatorParams(user_mute_strategies=[hold])
greeting = Greeting(text="Hi {{customer_name}}.")
@transport.event_handler("on_client_connected")
async def on_connected(transport, client):
await open_call(worker, greeting, call, context=context, hold=hold, transport=transport)
max_duration(worker, 20 * 60, call=call)
@transport.event_handler("on_client_disconnected")
async def on_disconnected(transport, client):
await worker.queue_frame(EndFrame())
await runner.add_workers(worker)
with use_phone_region(lambda: call_phone_region(state.call)):
await runner.run()
end = await call.end("ended")
await telemetry.close(state=state, reason=end.reason)
```
```mermaid theme={null}
flowchart TD
A[open_call] --> B[attach_call binds say, hang up and transcript]
B --> C[ready checks and prefetch]
C -->|check fails| D[Failure line, EndFrame, returns False]
C -->|passes| E[Queue the greeting, returns True]
```
1. `open_call` attaches the hooks, runs the `ready` checks and the prefetch, and starts the background lookups.
2. It queues the greeting and returns True. After a failed check it says the failure line, ends the call and returns False.
3. `call.end` makes the saves steps held, runs the `call_end` tools and drains the webhooks. Call it after `runner.run()` and before the telemetry closes, so the held saves' model request is traced in the last turn.
4. The end of the pipeline already starts `call.end`, and a second call waits for the same run. `flows.settle()` still works alone. See [Tasks](/core/build/tasks).
5. The reason does not come from the `EndFrame`. Pass `transport=` to `open_call` (or `attach_call`) and the transport's `on_client_disconnected` event notes the caller's hang-up, so the end reads `caller_hung_up`. On a Daily dial-out, `dial_out(..., call=call)` notes the callee hanging up the same way. Your own handler still ends the pipeline. `end_call_tool(call=call)`, `max_duration(call=call)` and `IdleNudgeObserver(call=call)` note their own reasons. Without a note, the end reads `ended`. See [Why the call ended](/core/build/call-lifecycle#why-the-call-ended).
Pass `telemetry.close(state=state, reason=...)` the reason `await call.end(...)` returns. Without hooks, pass one in the library's words: `caller_hung_up` when the caller leaves, `agent_ended` when the agent ends the call, or `ended` when you do not know.
The events, the failure line and the greeting's own rules are in [The call's life](/core/build/call-lifecycle).
### telephony\_call\_info
`runner_args.call_data`, as the Pipecat runner parsed the carrier's handshake. It reads Twilio, Telnyx, Plivo and Exotel.
The agent's own number, when the handshake does not carry it. Pass it by keyword.
The agent's id, the same on every framework. Pass it by keyword.
The call's id, when your dispatch gives one. A new one otherwise. Pass it by keyword.
It returns a `CallInfo`. It reads the carrier call id from the handshake. It reads the direction and the numbers from the handshake's body, the parameters your TwiML sends, and else from the handshake's own `from` and `to`. A call with no direction is inbound.
### greeting\_frames
`greeting_frames(greeting, state, llm=None)` returns the frames that open the call: a `TTSSpeakFrame` with the line, a request for the model to word a greeting, or nothing when the caller speaks first. Queue them once the pipeline runs and prefetch has filled the state. A line whose value is still empty is worded by the model. The instruction for a worded greeting goes in as a developer message.
### open\_call
`await open_call(worker, greeting, call, context=..., llm=..., hold=..., transport=...)` returns True once the greeting is queued, and False after a failed check.
The call's pipeline worker.
How the call opens.
The call's hooks, with the checks to pass.
The shared context.
The LLM service of a pipeline without `UnmuteFlows`. Pass OpenAI's realtime or live service always, with `UnmuteFlows` too, because it says the greeting and the failure line itself.
The greeting hold on the user aggregator. It lets go when the caller speaks first.
### GreetingHold
`GreetingHold` is a user mute strategy. It holds the caller's audio until the greeting starts. With `Greeting(interruptible=False)`, it holds until the greeting ends.
True lets go as the greeting starts, so the caller can cut in. False lets go once it has played. `open_call(hold=hold)` sets it from the greeting. Pass it yourself only when you do not use `open_call`.
Lets go after this many seconds, so a greeting that never starts or never ends cannot hold the caller for ever. The clock starts when `open_call` queues the greeting, with `hold.arm()`. The checks and the prefetch do not count. An uninterruptible greeting longer than this can be cut when the hold lets go, so raise it for a long greeting.
`hold.release()` lets go at once. `open_call` calls it when the caller speaks first.
### attach\_call
`attach_call(worker, call, context, llm=None, transport=None)` does only the attaching, once per call. It binds say, hang up and the transcript. A fatal error, or a processor that becomes unusable, fails the call: `TTSSpeakFrame(line)`, then `EndFrame()`. A TTS service that fails is logged and emits `call.tts_failed`, and the call stays open. The end of the pipeline runs `call.end`. With no `llm=` and no `UnmuteFlows`, a call that has model hooks logs one warning, because nothing sends the model request through the library. See [Hooks](/core/build/hooks#where-the-model-hooks-run).
The call's pipeline worker.
The call's hooks.
The shared context, for the transcript and the notes.
The LLM service of a pipeline without `UnmuteFlows`. Each request then waits for the tools on events, ends with their notes and runs the call's `prompt` and model hooks. A failed `ModelCallLLMService` request fails the call.
The call's transport. Its `on_client_disconnected` event notes that the caller hung up (`caller_hung_up`), unless the call already has an end reason. It does not end the pipeline: your own handler does that. `open_call` takes the same argument.
Keep the worker's `processor_unusable_policy` at `CONTINUE`, so the failure line can play. Give a pipeline without `UnmuteFlows` its tools with `tools_schema(registry, state, hooks=call)`.
### fill\_prompt
`await fill_prompt(llm, worker, prompt, state, save_values=False)` keeps a plain pipeline's prompt filled, for a cascade LLM service. A plain pipeline has no `UnmuteFlows`. Await `fill_prompt` before the pipeline runs. It sends the filled prompt as the service's system instruction now, and again after each save. So a value saved by prefetch or a tool reaches the next request. The call's `prompt` hooks still run through `attach_call(llm=)`.
The call's LLM service. A realtime service raises `TypeError`: use `attach_realtime`.
The call's worker. Its end stops following the state.
The agent's prompt, with placeholders still in it.
The call state the placeholders read.
End the prompt with the current values block, for `values_tool`. Pass it by keyword.
### attach\_realtime
`await attach_realtime(service, worker, prompt, state=None, ...)` runs OpenAI's realtime or live service as the agent, for a pipeline without `UnmuteFlows`. Await it before the pipeline runs. See [Realtime](/core/models/realtime).
The call's realtime or live service. Anything else raises `TypeError`.
The call's worker.
The agent's prompt, with placeholders still in it.
The call state the placeholders read.
The call's hooks: its `prompt` hooks and the notes of its tools on events.
The agent has the `save_values` tool, so its values follow the prompt.
Value name to the task that saves it, for the values block.
### max\_duration
`max_duration(worker, seconds, call=call)` queues an `EndFrame` after that many seconds, with no closing line. It stops counting when the pipeline ends first. It returns the running `CallLimit`.
The call's pipeline worker.
The longest the call may run. It must be above zero.
The call's hooks. With them, the call's end reads `max_duration`.
## Observers
`TelemetryObserver` records STT, each model request with its prompt, tools and tool calls, TTS and every task event. A `handoff` event names each agent by its spec's `name`, else the call's `agent_id`. So give each `AgentSpec` its own `name`.
The call's telemetry, with its call span started.
The model name the `llm` spans carry. After a handoff that gave the next agent its own model call, its spans name that one.
Who serves the model, like `openai`.
The call's tasks, which tell each request's prompt site.
Without `enable_metrics` and `enable_usage_metrics`, Pipecat sends no time to first byte and no token counts. `TelemetryObserver` logs one warning when they are off.
`DevObserver` sends the same call as the records `unmute dev` shows. Span names are in the [Telemetry reference](/core/reference/telemetry), and dev records on [Dev records](/core/reference/dev-records). Keep Pipecat's own `enable_tracing` off, because `TelemetryObserver` writes the spans.
## Native tools and MCP
`native_tools` are Pipecat `FunctionSchema`s with their own handlers, like a handoff or an end-call tool. A Pipecat MCP client needs no new class.
1. `MCPClient.tools()` returns a `ToolsSchema`. Its `FunctionSchema`s carry their handlers.
2. The main agent gets every tool you pass in `native_tools`.
3. A step gets only the names its task lists. See [Tasks](/core/build/tasks).
### end\_call\_tool
`end_call_tool` ends the call after one model request. The goodbye rides in the reply that calls the tool.
What the model reads after the built-in end-call text: when this agent ends a call, and to say its goodbye in the same reply. The model reads LiveKit's `EndCallTool` text first, then yours, so both frameworks make the same choice.
The line spoken when the reply that ends the call has no words. Write it in the call's language. `None` says `GOODBYE_LINE`, in English.
Returns the text of the reply that called the tool. `lambda: flows.reply_text` reads it when the tool runs, so the tool can be built before `flows`. Without `UnmuteFlows`, use `reply_text(llm)`.
The call's hooks. With them, the end is noted as `agent_ended`. A failure after that plays no line.
1. The tool answers with `run_llm=False`, so the call ends after one model request.
2. When the reply has no words, the tool speaks the goodbye you give it.
3. Then `worker.end()` drains the pipeline, so the goodbye plays before the call ends.
4. The ending tool asks for no second reply, on a realtime service too, and also when another tool is called in the same reply.
5. `goodbye=None` says `GOODBYE_LINE` from `unmute_core.call`, in English. For another language, pass your own `goodbye`.
## VoiceSwitcher
`VoiceSwitcher` holds the TTS services of a call's agents, in the pipeline where the TTS goes. It is Pipecat's `ServiceSwitcher` with one fix. A plain one lets the flush probe get lost, so every handoff and task waits out the flush timeout.
```python theme={null}
from unmute_core.pipecat import VoiceSwitcher
voices = VoiceSwitcher([front, billing])
flows = UnmuteFlows(..., llm=llm, tts=voices)
```
Put `voices` in the pipeline where one TTS would go. Two voices of one provider are two instances of its service, and each opens its own connection as the pipeline starts. Which agent uses which model and voice is on [Handoffs](/core/build/handoffs).
## Turn pace
```python theme={null}
from pipecat.audio.turn.smart_turn.local_smart_turn_v3 import LocalSmartTurnAnalyzerV3
from pipecat.audio.vad.silero import SileroVADAnalyzer
from unmute_core.pipecat import smart_turn_params, vad_params
from unmute_core.turn import turn_window
window = turn_window("balanced", "pipecat")
vad = SileroVADAnalyzer(params=vad_params(window))
turn = LocalSmartTurnAnalyzerV3(params=smart_turn_params(window))
```
For `vad_params` and `smart_turn_params`: a window from `turn_window(pace, "pipecat")`.
`vad_params(window)` returns `VADParams(stop_secs=window.vad_silence)`. `smart_turn_params(window)` returns `SmartTurnParams(stop_secs=window.max_delay)`. The paces, interruption and idle nudges are on [Turn taking](/core/build/turn-taking).
## Rules to know
* Build one `UnmuteFlows` and one `Telemetry` per call, and one `AgentSpec` per agent of the call. Build the `ModelCall` per call too, after the state. The service closes the models it was given when the pipeline ends, so a `RouterModelCall` or `OpenAIModelCall` shared across calls is closed under the others.
* Keep Pipecat's own `enable_tracing` off.
* `UnmuteFlows(call=...)` runs the `prompt` hooks on every prompt it builds, and the model and tool [hooks](/core/build/hooks) on every request and tool call. On a native LLM, a request borrows a hook's changes and gives them back once it ends.
* `UnmuteFlows` gives a native Pipecat LLM the main prompt as it reads now, before each main request. A value saved since shows.
* A tool's `interruption="continue"` makes it a background tool to Pipecat. The library keeps Pipecat's own guidance about background tools out of the prompt, so the model reads the same prompt as on LiveKit. Your own tool with `cancel_on_interruption=False` brings the guidance back. Tool fields and webhooks are in [Tools](/core/build/tools).
* In `record` mode, a reply that spoke and called nothing can be followed by a short finish check. Through a `ModelCallLLMService` it is a `ModelRequest`. A native OpenAI compatible service gets it on its own client. Any other service asks the spec's `summarizer` model. With none, it skips the check, and `UnmuteFlows` logs one warning at build. A `summary` history on such a service needs a `summarizer` too, and warns once.
* A tool that ends the call, or a tool beside it in the same reply, makes no second model request. The same holds on a realtime service.
* `TelemetryObserver` warns once when `PipelineParams(enable_metrics=True, enable_usage_metrics=True)` is not set, because the spans then miss tokens and the time to first byte.
* The greeting instruction and the idle nudge go in as developer messages.
* A step's first request never ends on its own announce line. The library adds a short cue after it, the step cue `(The call continues.)`, so a provider like Gemini does not answer with nothing.
* The caller can still cut off a transfer's announce line on Pipecat. To protect it, build the user aggregator with `user_mute_strategies(protect=["tool_calls"])`. See [Turn taking](/core/build/turn-taking#turn-off-interruption-or-protect-a-line).
* On a phone call over a carrier line, set the pipeline's audio in and out sample rates to 8000. The library does not build the pipeline, so it cannot do this for you. See [Phone calls](/core/reference/telephony#pipecat-on-a-carrier-websocket).
* A realtime model's worded greeting waits for the background lookups, as on LiveKit.
* Gemini's OpenAI-compatible endpoint keeps only the last system message. `OpenAIModelCall` folds the library's several into one for a Gemini model. A native OpenAI-compatible service pointed at that endpoint sends them as they are, so use `GoogleLLMService` or a `ModelCallLLMService` there. See [Gemini and several system messages](/core/reference/model-call#gemini-and-several-system-messages).
* A provider's own context messages, like Gemini's thought signatures, stay in the context and never count as caller turns.
## Where to go next
Run the library in your own Pipecat pipeline.
Every field of the agent, the same on both frameworks.
Every span and attribute the observer writes.
The same detail for LiveKit.
# Prefetch reference
Source: https://unmute.ai/core/reference/prefetch
Every argument of Prefetch, Clock, CallValue, Lookup and call_info, the checks at build time, and how a run spends its budget.
This page is the full detail behind [Prefetch](/core/build/prefetch). Start there to fill the call state before the greeting. Come here for every entry, argument, check and rule.
## What it gives you
| On a call without it | What the library does |
| - | - |
| The model spends call time asking for the date, or for a caller it could know. | The clock, call facts and lookups fill the state before the first word. [Prefetch](/core/build/prefetch#fill-values-before-the-greeting) |
| A slow lookup delays the greeting, or a failed one ends the call. | All lookups share a 2 s budget. A late or failed one keeps its default. [How it works](#how-it-works) |
| The server's time zone gives the wrong day. | The clock reads the zone you name. |
| "anonymous" is saved as a phone number and read aloud. | Withheld numbers count as absent. [CallValue](#callvalue) |
| The caller fixes their number. The name looked up from the old one stays. | Values looked up from the old number go back to empty. |
## How it works
```mermaid theme={null}
flowchart LR
R[run state] --> E[Next entry]
E --> V[Read a value]
V --> S[state.save]
S --> E
E -->|budget used up| D[Rest keep their defaults]
```
1. `run` goes through the entries in order.
2. A `Clock` reads the time in one zone. A `CallValue` copies a value from `state.call`. A `Lookup` runs your function or tool.
3. Each entry saves its values with `state.save`. A listener sees them as origin `prefetch`.
4. The whole block has one budget, 2 seconds by default. Pass `budget=` to change it.
5. When the budget runs out, the rest of the entries are skipped. Their values keep their defaults.
6. `run` never raises. An entry that is skipped, times out or fails is logged and leaves its values at their defaults. The call greets on time.
In the [guide's example](/core/build/prefetch#fill-values-before-the-greeting), `find_customer` takes the call state and returns a mapping, like `{"name": "Ana Ruiz"}`. It may be a plain function or an `async` one. After `run`, `booking_date`, `weekday`, `caller_phone` and `customer_name` hold their values. The agent greets with them.
## Prefetch
The block of entries a call runs as it starts.
The entries, run in order. Names must be unique.
The State model. With it, every entry is checked at build time against the types of the values it saves.
Seconds the entries before the greeting may take together. Past it, the rest keep their defaults.
Seconds each background lookup may take.
`state`, `budget` and `background_budget` are keyword-only.
## Clock
`Clock(name, timezone, assign)` reads the clock once, at the start of the call. A call that crosses midnight keeps the day it started on.
The entry name, used in log lines.
An IANA zone, like `Europe/Madrid`. It is never the container's clock.
State value name to the clock field it gets, like `{"booking_date": "date"}`. It may not be empty.
The fields are `date`, `time`, `datetime`, `day_of_week`, `year` and `timezone`. A `date` reads `2026-10-13`, a `time` reads `09:30`, and a `day_of_week` reads `Tuesday`. A wrong zone raises `ValueError` when you build the entry: `'Mars/Base' is not an IANA time zone`. So does a wrong field, like `'dat' is not a clock field`.
## CallValue
`CallValue(name, source, assign)` copies a value from `state.call` into a value of your own. `state.call` is read-only. A copy lets the caller confirm the number or correct it. See [State](/core/build/state#values-the-call-carries-state-call).
The entry name, used in log lines.
The `state.call` field to read: `calling_number`, `called_number`, `remote_number`, `direction`, `channel`, `carrier_call_id`, `agent_id` or `session_id`.
The state value names that get the value. They all get it. A bare string raises `TypeError`, so write `["caller_phone"]`.
A call value that is empty counts as absent, and the entry is skipped. A withheld caller ID, like `anonymous`, is already `None` in `state.call`. So it is skipped too.
## Lookup
`Lookup(name, run, assign, inputs=(), needs_confirmed=(), background=False)` runs a function or a tool and saves fields of its result.
The entry name, used in log lines and as its label in the results.
A function that takes the call state, or a `ToolSpec`. It returns a mapping. A plain function runs in a thread, so a blocking call cannot delay the greeting.
State value name to a top-level key of the result. A tool lookup may leave it empty. Its result then only reaches a step's `tool` input.
Value paths the lookup reads. The entry is skipped while one is empty. When an input changes later, the saved values go back to their defaults. So do values looked up from them.
Values that must not be waiting for the caller. The entry is skipped while one is.
True runs the lookup beside the greeting.
A result that is not a mapping counts as a failure.
### A tool as a lookup
```python theme={null}
find = local_tool(find_customer, locked={"phone": "{{caller_phone}}"})
Lookup("customer", find, {"customer_name": "name"})
```
1. `run` may be a `ToolSpec`. It runs like any tool: locked arguments, `{{value}}`, `{{call.name}}` and refusal.
2. Every required argument must be locked. The model never fills one. An open one raises `ValueError` when you build the entry.
3. A tool lookup has no announce line. Nobody waits for it. A tool with one is refused.
4. A tool that is refused or fails counts as a failure. The values keep their defaults.
5. A tool that hides its result with `show_result=False` records `{"ok": true}`.
### Work beside the greeting
```python theme={null}
Lookup("hours", local_tool(store_hours), {"closes_at": "close"}, background=True)
```
A slow lookup should not delay the greeting. Mark it `background=True`.
1. `Prefetch.run` runs only the other entries. It never waits for a background lookup.
2. `Prefetch.run_background(state, results=...)` runs the background lookups, one after the other.
3. Each one has its own budget, 10 seconds by default. Pass `background_budget=` to `Prefetch` to change it.
4. A lookup that fails or runs out of time is logged. Its values keep their defaults.
5. `prefetch.fills` leaves background lookups out. So `Greeting.check(prefetch)` refuses a greeting line that names one of their values.
6. `CallHooks` starts `run_background` for you. Every model request then waits for it, up to `first_request_timeout_s`. A fixed greeting plays at once.
7. The prompt shows the value once it is saved. `UnmuteAgent` and `UnmuteFlows` fill the prompt again before each request.
### What each lookup returned
```python theme={null}
from unmute_core.tasks import CallStartResults
results = CallStartResults()
await prefetch.run(state, results=results)
```
1. `run` and `run_background` take `results`. Each lookup that ran records its result as JSON, under the entry name. A lookup that failed records `{"error": ...}`.
2. `CallHooks` keeps one as `call.results`. `UnmuteAgent(call=call)` and `UnmuteFlows(call=call)` give it to their tasks, so a step with a `tool` input reads it. In your own host, pass it to `CallTasks(call_start=call.results)`. See [Tasks](/core/build/tasks).
## Checks when you build it
Pass `state=State` to `Prefetch`. Each entry is then checked at once, not during a call. Each check raises `ValueError` and names the entry.
| Check | Example refusal |
| - | - |
| Every assigned value is declared in the State | `assigns an undeclared runtime variable` |
| A shape or list cannot be filled | `cannot fill the shape or list` |
| The type fits the reading | A `date` fits `str` and `Date`, never `int` |
| A `Literal` offers every value the reading can give | A `day_of_week` needs all seven days |
| Entry names are unique | `entry names must be unique` |
Every entry also refuses an empty `assign` with `ValueError`, because it would save nothing.
`Clock`, `CallValue`, `Lookup` and `Prefetch` are Pydantic dataclasses. A value of the wrong type raises a `ValidationError` in Pydantic's wording. `prefetch.state` is the State model you passed. `Prefetch` compares by identity, so two prefetches with the same entries are two objects. `Lookup` and `Clock` copy the `assign` mapping you give them, so changing your dict later changes nothing.
`prefetch.fills` is the set of values the entries fill before the greeting. `Greeting.check(prefetch)` uses it to refuse a greeting that names a value no entry fills. See [Greeting](/core/reference/call-lifecycle#greeting).
A value reaches the model whole. Only the SLNG Context Router cuts a long template variable. See [SLNG](/core/models/slng).
## call\_info
```python theme={null}
from unmute_core.state import call_info, call_phone_region
call = call_info(
"inbound", remote_number="+34612345678", local_number="+34911000000", carrier_call_id="CA1"
)
call.calling_number # "+34612345678"
call.called_number # "+34911000000"
call.remote_number # "+34612345678"
```
1. `call_info` builds the `CallInfo` of a phone call. It names the numbers by who called whom.
2. On an inbound call, the caller is `calling_number`. On an outbound call, the agent's own number is.
3. `remote_number` is the other party's number either way.
4. A direction other than `inbound` or `outbound` raises `ValidationError`.
LiveKit and Pipecat have their own builders: `sip_call_info` and `telephony_call_info`. See [Telephony](/core/telephony). Pass the result to `CallState(State, call=call)`.
`inbound` or `outbound`.
The other party's number: the caller, or the one dialled.
The agent's own number, its trunk.
`phone` for a phone line. `web` to simulate a phone call in a web session.
The carrier's id of the call.
The agent's id.
The call's id. A new one when None.
`call_phone_region(state.call)` gives the call's country, like `"ES"`, or `None` for a call without numbers. Use it with `use_phone_region`, so the state can read a national number. See [What a call carries](/core/build/prefetch#what-a-call-carries).
## In a call
What `open_call` does with the prefetch, when you give it to `CallHooks`. See [Use it in a call](/core/build/prefetch#use-it-in-a-call).
1. `open_call` runs `call.open()`. It runs the `before_call` checks first.
2. When the checks pass, it runs `prefetch.run`.
3. Then it starts `prefetch.run_background` and the greeting.
4. Every model request waits for the background lookups, up to `first_request_timeout_s` (10 seconds).
5. A failed check hangs up before any lookup runs. The call's end, or a failure, stops the background lookups.
6. Each lookup's result goes to `call.results`: `{"ok": true}` for a tool that hides it, and `{"error": ...}` when it failed.
On a plain agent, run `await prefetch.run(state)` yourself before the session starts. Then you have no background lookups. A native LLM reads the values with `render_prompt(PROMPT, state)`. See [State](/core/build/state#filling-a-prompt) and [The order](/core/reference/call-lifecycle#the-order).
## Troubleshooting
### ValueError names an entry when you build the Prefetch
The entry assigns a value the State does not declare, a value of a type the reading does not fit, or a shape or list. Two entries may share a name too.
**Fix:** read the message. It names the entry and the value. Declare the value, change its type, or give the entry a new name.
```python theme={null}
class State(BaseModel):
booking_date: Date | None = None
```
### Greeting.check refuses the line
The greeting names a value that no entry fills before the greeting. A background lookup does not count.
**Fix:** fill the value with an entry that is not `background=True`, or take it out of the greeting line.
### A value stays at its default
The entry was skipped, ran out of time, or failed. The log names the entry and says why. An input may have been empty, or a needed value may still wait for the caller.
**Fix:** fix the failing entry, or raise `budget`. Move a slow lookup to `background=True`.
## Where to go next
Fill the call state before the greeting, the short way.
The order of a whole call, the greeting and every CallHooks argument.
A step that reads a lookup's result.
How saved values read in a prompt, and when the caller confirms them.
# Settings
Source: https://unmute.ai/core/reference/settings
Every environment variable the library reads, and how to check them all at startup.
Each part of the library that needs a key or a URL reads it through one settings class. Load them once at startup, so a missing key fails the deploy and not the first call.
On this page:
* [Check them at startup](#check-them-at-startup) - `check_settings`
* [How a value is read](#how-a-value-is-read) - the order and the errors
* [Every variable](#every-variable) - SLNG, Langfuse, Logfire, Coval
* [Flag variables](#flag-variables) - `env_flag`
* [A variable whose name comes from config](#a-variable-whose-name-comes-from-config) - `env_value`
* [Your own settings](#your-own-settings) - subclass `EnvSettings`
* [Every argument these functions take](#every-argument-these-functions-take) - signatures
## Check them at startup
```python agent.py theme={null}
from pydantic import Field, SecretStr
from pydantic_settings import SettingsConfigDict
from unmute_core.model import OpenAIModelCall
from unmute_core.settings import EnvSettings, check_settings
from unmute_core.telemetry import Langfuse, LangfuseSettings
class ShopSettings(EnvSettings):
"""The settings of your own agent. Each variable starts with SHOP_."""
model_config = SettingsConfigDict(env_prefix="SHOP_")
openai_api_key: SecretStr = Field(description="Your OpenAI key.")
model: str = "gpt-5.6-terra"
shop, langfuse = check_settings(ShopSettings, LangfuseSettings)
model = OpenAIModelCall(shop.model, api_key=shop.openai_api_key.get_secret_value())
sink = Langfuse.from_settings(langfuse)
```
If `SHOP_OPENAI_API_KEY` and `LANGFUSE_SECRET_KEY` are unset, `check_settings` raises one `SettingsError` that names both. The error lists every missing variable, so one deploy fixes them all.
The library's own classes work the same way. `LangfuseSettings` above is one. `SlngSettings` holds the variables of the SLNG Context Router. This is a router call with your own OpenAI key:
```python router.py theme={null}
from pydantic import Field, SecretStr
from unmute_core.settings import check_settings
from unmute_core.slng import (
OpenAIEndpoint,
RouterConfig,
RouterModelCall,
SlngSettings,
)
class RouterSettings(SlngSettings):
"""The router settings, with your own OpenAI key."""
model: str = "gpt-5.6-luna"
openai_api_key: SecretStr = Field(min_length=1, validation_alias="OPENAI_API_KEY")
def config(self) -> RouterConfig:
"""Return one model, on your OpenAI key."""
endpoint = OpenAIEndpoint(
url="https://api.openai.com/v1",
api_key=self.openai_api_key.get_secret_value(),
)
return RouterConfig.single(self.model, endpoint)
(slng,) = check_settings(RouterSettings)
model = RouterModelCall(
state.call,
model=slng.model,
config=slng.config(),
)
```
`RouterSettings` adds your OpenAI key to the SLNG settings. Each request carries your own router config with that key. See [Your router config](/core/reference/slng#your-router-config).
## How a value is read
```mermaid theme={null}
flowchart LR
A[Constructor values] --> S[Settings class]
E[Environment] --> S
F[.env file, opt-in] --> S
S --> C[RouterModelCall or sink]
S -->|missing or bad value| X[SettingsError naming each variable]
```
1. A value passed to the constructor wins. `SlngSettings(model="m")` ignores `SLNG_MODEL`.
2. Otherwise the class reads the environment. An empty variable counts as unset.
3. A `.env` file is read only when you ask: `SlngSettings(_env_file=".env")`.
4. The settings feed a `RouterModelCall` or a sink. Secrets are `SecretStr`, so they never show in a log line or `repr`.
5. A missing or bad value raises an error that names every variable to fix. Each class raises its own subclass of `SettingsError`: `SlngConfigError` or `TelemetryConfigError`.
Nothing reads the environment when you import the library.
## Every variable
Copy this into your `.env.example`. A line that starts with `#` has a default.
```bash theme={null}
# The SLNG API key.
SLNG_API_KEY=
# The world part whose router to use, like eu-north. Or set SLNG_ROUTER_URL.
# SLNG_WORLD_PART=
# The Context Router URL, like https://eu.context-router.slng.ai/v1. It wins over SLNG_WORLD_PART.
# SLNG_ROUTER_URL=
# The model name. slng/auto lets the router config pick and fail over.
# SLNG_MODEL=slng/auto
# The stored router config to use, when the key does not fix one.
# SLNG_LLM_CONFIG_ID=
# The Langfuse public key, pk-lf-...
LANGFUSE_PUBLIC_KEY=
# The Langfuse secret key, sk-lf-...
LANGFUSE_SECRET_KEY=
# The Langfuse host, like https://cloud.langfuse.com.
LANGFUSE_BASE_URL=
# The Logfire write token, like pylf_v1_eu_...
LOGFIRE_TOKEN=
# The Coval API key. Unset sends no spans to Coval.
# COVAL_API_KEY=
# The Coval simulation this call belongs to. Unset reads it from the call.
# COVAL_SIMULATION_ID=
```
`env_example(SlngSettings, LangfuseSettings, ...)` prints the same text for the classes your app uses. A test keeps this block in step with the classes.
| Class | Module | Variables |
| - | - | - |
| `SlngSettings` | `unmute_core.slng` | `SLNG_API_KEY`, `SLNG_WORLD_PART` or `SLNG_ROUTER_URL` (one is needed), `SLNG_MODEL` (default `slng/auto`), `SLNG_LLM_CONFIG_ID` |
| `LangfuseSettings` | `unmute_core.telemetry` | `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL` (or `LANGFUSE_HOST`) |
| `LogfireSettings` | `unmute_core.telemetry` | `LOGFIRE_TOKEN` |
| `CovalSettings` | `unmute_core.telemetry` | `COVAL_API_KEY`, `COVAL_SIMULATION_ID` (both may be unset) |
| `AgentSettings` | `unmute_core.state` | `UNMUTE_AGENT_ID`, the agent id a call takes when your code passes none. Without either, building the call state raises `SettingsError`. |
| `CallStartSettings` | `unmute_core.call` | `UNMUTE_CALL_START` (a JSON object, may be unset) |
| `DevSettings` | `unmute_core.dev` | `UNMUTE_DEV_METRICS` (an on/off word, off when unset). `unmute dev` sets it. `metrics_enabled()` reads it. |
The SLNG variables feed the optional [Context Router model call](/core/models/slng). The Langfuse, Logfire and Coval variables feed the [telemetry sinks](/core/observe/telemetry).
Some names are yours to pick, and the library reads them when it needs them, not through a settings class:
* `WebhookAuth(token_env=...)` reads its token on each webhook call, so a rotated token works without a restart. It uses `env_value` below. Like `credential_env`, it reads the exact name, in the case you wrote it.
* `save_call_start` reads `UNMUTE_CALL_START`, a JSON object like `{"customer_id": "c_42"}`, for a local run. The dispatch's values win over it, and `env=False` skips it. See [start values](/core/build/call-lifecycle). A value that is not a JSON object raises `SettingsError`.
* `KnowledgeBase(credential_env=...)` reads its embedding key when it starts.
The OpenTelemetry SDK reads `OTEL_EXPORTER_OTLP_*` for the `Otlp` sink itself.
## Flag variables
`env_flag` reads a variable that turns something on or off:
```python theme={null}
from unmute_core.settings import env_flag
if env_flag("UNMUTE_LOCAL_RUN"):
...
```
1. `1`, `true`, `yes`, `y`, `on` and `t` mean on. `0`, `false`, `no`, `n`, `off` and `f` mean off. Case and spaces around the value do not matter.
2. An unset or empty variable gives `default`, which is `False` unless you pass one.
3. Any other word raises `SettingsError` and names the variable. The library does not guess.
`UNMUTE_DEV_METRICS`, which turns on dev records, reads the same words. A word it does not know logs a warning and counts as off, so a typo never breaks a call.
## A variable whose name comes from config
```python theme={null}
from unmute_core.settings import env_value
token = env_value("ORDERS_TOKEN", str) # the text, or None when unset or empty
retries = env_value("ORDERS_RETRIES", int) # read as an int
```
1. `env_value(name, kind)` reads one variable and returns it as a `kind`.
2. An unset or empty variable gives `None`.
3. A value that is not a `kind` raises `SettingsError`.
4. Use it when the name is your own config, like a webhook's `token_env`. Use a settings class when the name is fixed.
5. The name is read exactly, and case matters. `orders_token` does not answer `ORDERS_TOKEN`. The same holds for `token_env` and `credential_env`.
## Your own settings
Subclass `EnvSettings` to get the same behaviour for your app's own names:
```python theme={null}
from pydantic import Field, SecretStr
from pydantic_settings import SettingsConfigDict
from unmute_core.settings import EnvSettings
class SalonSettings(EnvSettings):
model_config = SettingsConfigDict(env_prefix="SALON_")
booking_api_key: SecretStr = Field(description="The booking system's API key.")
```
`check_settings(SlngSettings, SalonSettings)` then names `SALON_BOOKING_API_KEY` with the rest.
## Every argument these functions take
### check\_settings
The settings classes the app needs, like `SlngSettings`. Returns one loaded object per class, in order. Raises `SettingsError` if any class is missing a value or holds a bad one.
### env\_flag
The variable to read, like `UNMUTE_LOCAL_RUN`.
The value when the variable is unset or empty. Keyword only.
### env\_value
The variable to read, like `ORDERS_TOKEN`.
The type to read it as, like `str` or `int`. Returns a `kind`, or `None` when the variable is unset or empty. Raises `SettingsError` when the value is not a `kind`.
### env\_example
The settings classes to print. Each variable gets its field description as a comment. A required variable is left empty, and one with a default shows it commented out.
## Where to go next
What the SLNG variables do in the Context Router call.
The sinks that read the Langfuse, Logfire and Coval variables.
# SLNG reference
Source: https://unmute.ai/core/reference/slng
Every RouterModelCall argument, the headers and body fields each request carries, the router config, Gemini thought signatures, and the router's errors.
This page is the full detail behind [SLNG speech and the Context Router](/core/models/slng). Start there to add SLNG speech or the router to your agent.
## Speech and router in one session
```python agent.py theme={null}
import os
from livekit.agents import AgentSession
from livekit.plugins import silero, slng
from unmute_core.livekit import ModelCallLLM
from unmute_core.slng import (
OpenAIEndpoint,
RouterConfig,
RouterModelCall,
tracking_ids,
)
# Your SLNG project's region, like eu-north.
world_part = os.environ["SLNG_WORLD_PART"]
config = RouterConfig.single(
"gpt-5.6-luna",
OpenAIEndpoint(
url="https://api.openai.com/v1",
api_key=os.environ["OPENAI_API_KEY"],
),
)
router = RouterModelCall(
state.call,
model="gpt-5.6-luna",
config=config,
)
session = AgentSession(
stt=slng.STT(
api_key=os.environ["SLNG_API_KEY"],
slng_base_url=f"{world_part}.api.slng.ai",
model="soniox/speech-ai:rt-v5",
language="en",
**tracking_ids(state.call),
),
llm=ModelCallLLM(router, state=state),
tts=slng.TTS(
api_key=os.environ["SLNG_API_KEY"],
slng_base_url=f"{world_part}.api.slng.ai",
voice="8d8aec63a56c460cb7def795bdf754fa",
model="slng/fish/tts:s2.1-pro",
language="en",
**tracking_ids(state.call),
),
vad=silero.VAD.load(),
)
```
Each request carries your own router config. It sends the model to OpenAI on your own `OPENAI_API_KEY`. The `SLNG_API_KEY` must come from a project on the Execution Layer. See [Your router config](#your-router-config).
Speech and the router send the same two ids: the agent's id and the call's session id, from `state.call`. SLNG groups usage by them. See [Agent and session ids](#agent-and-session-ids).
`SLNG_WORLD_PART` must be your SLNG project's region. Speech and the router both use it. `RouterModelCall` reads it from the settings. A key used in another region gets 401 from the router.
The three parts are independent. Use the SLNG speech plugins with your own LLM, or the router with your own speech plugins. The complete files are `examples/parcel-desk/livekit/agent.py` and `examples/parcel-desk/pipecat/bot.py`.
## Speech plugins
The speech plugins are separate packages: `livekit-plugins-slng` for LiveKit and `pipecat-slng` for Pipecat. The `slng` extra holds only what the router client needs.
`tracking_ids(state.call)` gives both plugins `external_agent_id` and `external_session_id`. Build the call state before the session or the pipeline, so the ids exist.
On LiveKit, call `stt.attach_to_session(session)` after you build the session. Put both services in the session or the pipeline.
STT and TTS spans carry `unmute.upstream.provider` when the provider is a gateway and the model id reads `[slng/]/`. For `soniox/speech-ai:rt-v5` the value is `soniox`, and for `slng/fish/tts:s2.1-pro` it is `fish`. A gateway is a provider that passes a request on to another one. `Telemetry(gateways=)` names them, and `openrouter` and `slng` are the default. A model id with no upstream part gives no attribute. The LiveKit SLNG STT plugin reports `slng` as its model, so its STT span has no upstream.
## The router adapters
The router is a [`ModelCall`](/core/models/model-call). Each framework runs it through a small adapter: `ModelCallLLM` on LiveKit, `ModelCallLLMService` on Pipecat.
```mermaid theme={null}
flowchart LR
P["Prompt with {{placeholders}}"] --> A[Adapter]
S[Call state] --> A
A -->|prompt and template_variables| R[Context Router]
R --> M[Model]
```
1. The adapter sends the prompt with its `{{placeholders}}` still in it.
2. It sends the values of `state` beside the prompt, as `template_variables`.
3. The router fills the prompt. The model sees the same text it would see on a native LLM.
4. The router retries and fails over by its own rules.
Pass `state=None` when the prompt has no placeholders.
With `UnmuteAgent`, give the router to the agent's spec instead: `AgentSpec(PROMPT, model=router)`. On Pipecat, `UnmuteFlows` sends the requests through the `ModelCallLLMService`. Build the router and the spec per call, after the state, because the router reads `state.call`. See [AgentSpec](/core/reference/agent-spec).
`ModelCallLLM` is a real LiveKit `llm.LLM`, so `AgentSession` accepts it. Its `site` attribute is the prompt site of the next request. A prompt site is the place where the prompt is used: the main prompt, or a task step. It starts as an empty string, the main prompt. Its `model` and `provider` come from the router, so spans show `slng/auto` and `slng`. On Pipecat, give `ModelCallLLMService` the usual `settings`. It builds no OpenAI client of its own.
## RouterModelCall
Sends each request to the SLNG Context Router. It needs the `slng` extra and raises `ImportError` with the install command when the extra is missing.
```python theme={null}
from unmute_core.slng import RouterModelCall
router = RouterModelCall(
state.call,
model="gpt-5.6-luna",
config=config,
body={"reasoning_effort": "none"},
)
```
OpenAI refuses function tools with reasoning on `/v1/chat/completions`, and answers 400. The router sends the request there. So an agent with tools sends `reasoning_effort` `"none"`. An agent with no tools may leave it out.
* It sends `config` as `slng_config` with every request. See [Your router config](#your-router-config).
* It sends the prompt unfilled, with `{{a.b}}` written `{{a__b}}`.
* It sends the values as `template_variables`. The router fills the prompt.
* The `provider` attribute is `slng`. The `model` attribute defaults to `slng/auto`.
* `aclose()` closes the client only when the call built it. A client you pass in stays open.
* `last_response` holds the `x-slng-*` headers of the latest answer.
* A placeholder name whose router key is over 64 characters is refused when the agent is built. `RouterModelCall.variable_key_max` is 64. See [Placeholder names](/core/build/tasks/what-the-model-reads#placeholder-names).
* Each answer ends with its `Usage`.
Arguments left out are read from the `SLNG_*` settings. See [Settings](/core/reference/settings).
### RouterModelCall arguments
What the call carries: pass `state.call`. Every request sends its `agent_id` and `session_id`. Anything else raises `TypeError`.
The stored router config to use, when the key does not fix one. Falls back to `SLNG_LLM_CONFIG_ID`.
The model name. Falls back to the settings, then to `slng/auto`. A name that is not in the `config` raises `ValueError` when the config sets tiers.
The router's OpenAI-compatible URL, ending in `/v1`.
The world part whose router to use, like `eu-north`, when there is no `base_url`. It is checked by shape, as one DNS label, and read in lower case.
The SLNG key. Falls back to the settings.
A router config sent with every request as `slng_config`. Always pass one. See [Your router config](#your-router-config).
Sends `slng_pure_proxy`: no cache, no prompt edits, the default tier only.
Extra body fields for every request, like `reasoning_effort`. A request's `params` win over it. Its `template_variables` join each request's own, and the request's value wins on a shared name. Setting `slng_config`, `slng_pure_proxy` or `stream_options` here raises `ValueError`.
Headers for every request. They never replace the identity headers.
The client timeout. See [Token counts, timeouts and errors](#token-counts-timeouts-and-errors).
A ready client, for tests. The environment is then not read.
A missing key, or neither a URL nor a world part, raises `SlngConfigError`.
### Agent and session ids
Every call has both ids in `state.call`. The router, SLNG speech-to-text and SLNG text-to-speech all send them.
* `agent_id` is required. Pass it to `CallInfo`, `call_info`, `sip_call_info` or `telephony_call_info`. Else the call takes `UNMUTE_AGENT_ID`. With neither, building the call state raises `SettingsError`.
* `session_id` is a fresh id per call, unless your dispatch passes one. It is the same on every turn and on both frameworks.
* Each id is 1 to 128 characters after stripping. It may not hold a comma, whitespace, `{`, `}` or `|`, and it must be printable ASCII. A bad id fails when the call state is built, not on the first request.
`RouterHeaders` builds the headers from these ids. `RouterModelCall` makes it for you.
## What each request carries
| Part | What it is |
| - | - |
| `X-Slng-Agent-Id`, `X-Slng-Session-Id` | From `state.call`. |
| `X-Slng-Llm-Config-Id` | From `llm_config_id` or the settings. A config in the request wins over it. |
| `X-Slng-Prompt-Site` | `task:` while a task runs. None for the main prompt. |
| `X-Slng-Request-Id` | New for each request. The router logs it and sends it back. A failed request logs it too. |
| `extra_headers` | Your own headers. |
| `slng_config` | The `config`. |
| `slng_pure_proxy` | With `pure_proxy=True`. |
| `stream_options.include_usage` | Always on, so the answer ends with its token counts. |
| `template_variables` | The values the router fills the prompt with. At most 64 names. A name is 1 to 64 letters, digits or underscores. The router takes a value of at most 4000 characters, so `RouterModelCall` cuts a longer one to 4000 and logs a warning. A native model call cuts nothing. |
The site goes in a header so the router scopes its cache by prompt. The router judges which turns are repeatable, and some never cache. A site must be `task:` plus a lower snake case name of at most 64 characters, or `summary`, which goes out as `task:summary`.
Each answer logs one line at info level: `slng router: scope= source= layer= model= request_id=`. `layer` and `model` appear only when the router sends them.
## Your router config
A router config names the models the router may use, their weights, their fallbacks and the keys they run on. Send your own config with every request. Your provider keys go in it.
```python theme={null}
import os
from unmute_core.slng import (
OpenAIEndpoint,
RouterConfig,
RouterModelCall,
)
config = RouterConfig.single(
"gpt-5.6-luna",
OpenAIEndpoint(
url="https://api.openai.com/v1",
api_key=os.environ["OPENAI_API_KEY"],
),
)
router = RouterModelCall(
state.call,
config=config,
)
```
1. `RouterConfig.single` puts one model in tier 1 with weight 100. The endpoint holds your OpenAI key.
2. `RouterModelCall` sends the config as `slng_config` with every request.
3. A pinned `model` must be one of the config's models when the config sets tiers. `slng/auto` lets the router pick.
### Which key may send a config
The router accepts a `slng_config` only from an SLNG key in a project on the Execution Layer. Any other key gets 403 `project_mode_forbidden`.
### Why not the stored config
The router also keeps a config for your org or key. Do not rely on it. A request with no `slng_config` uses the stored config. When that config does not select the request's model, the router answers 400:
```text wrap theme={null}
model "gpt-5.6-luna" is not selected by this org's default router config
```
Your config also lays over the stored one, one top-level field at a time. A field you leave out keeps its stored value. So always set `tiers`, as `RouterConfig.single` does.
### RouterConfig
Tier to its models. `None` keeps the stored tiers.
The tier `slng/auto` uses when it does not pick one. `None` keeps the stored value.
Whether the router may answer from its cache. The router judges which turns are repeatable, and some never cache. `None` keeps the stored value.
The most characters of an earlier assistant reply the router keeps in the prompt, 1 to 10000. `None` keeps the stored value.
Whether the router fills its cache ahead of requests. `None` keeps the stored value.
Other fields are `None` by default, and `None` keeps the stored value:
```python theme={null}
RouterConfig(
disable_reasoning=True,
pii_detection_enabled=True,
pii_regex_packs=("global", "us"),
)
```
| Field | What it does |
| - | - |
| `cache_skip_numeric_enabled` | Skips the cache for requests that hold numbers. |
| `template_vars_strict` | Refuses a request that leaves a placeholder without a value. |
| `disable_reasoning` | Asks the model not to reason. |
| `pii_detection_enabled` | Looks for personal data. |
| `pii_regex_packs` | The pattern packs for personal data: `global`, `indian`, `european`, `us`. |
| `pii_ner_models` | The name-finding models: `gliner_multilingual`, `indic_ner`, `gliner_pii_en`, `gliner_multi_ar`. |
| `slng_flow` | A map of agent id to that agent's flow, the steps the router follows. Each key must be a valid agent id. |
`RouterConfig`, `TierEntry` and the endpoint classes are Pydantic models. `RouterConfig.model_validate(data)` reads a config from JSON or YAML data. A bad value raises a `ValidationError` that names the field. The config is checked when you build it:
1. A tier needs an entry with priority 0. A higher priority is a fallback.
2. The weights of one priority in one tier sum to 100.
3. A model appears once per tier.
4. An unknown field is refused. The JSON may be at most 256 KB.
5. Some request fields never reach the model: the Context Router drops them. They are fields like `api_base`, `api_key`, `metadata` or `extra_headers`, and any name that starts with `aws_`, `vertex_`, `azure_` or `watsonx_`. The library still sends them. It logs one warning per field name that says the router drops it. A tier entry's `kwargs`, `RouterModelCall(body=...)` and a request's `params` are all checked. `reasoning_effort`, `extra_body` and `extra_query` are not dropped.
### TierEntry
The name a request may pin, like `gpt-5.6-luna`.
Its share of the traffic of its priority, 1 to 100.
0 is tried first. A higher priority is a fallback. The range is 0 to 100.
Where the model runs. `None` uses SLNG's own deployment of the model.
Default request fields for this entry, like `{"temperature": 0}`. A request's own fields win.
```python theme={null}
from unmute_core.slng import RouterConfig, TierEntry
luna = TierEntry(model="gpt-5.6-luna", weight=70, endpoint=openai)
flash = TierEntry(model="gemini-flash", weight=30, endpoint=vertex)
haiku = TierEntry(
model="claude-haiku", weight=100, priority=1, endpoint=bedrock
)
tier_1 = [luna, flash, haiku]
config = RouterConfig(tiers={"1": tier_1}, default_tier=1)
```
### Providers
| Class | `provider` | Fields |
| - | - | - |
| `OpenAIEndpoint` | `openai-compat` (default) or `openai-responses` | `url`, `api_key`, optional `model_id` and `auth_header` |
| `AzureEndpoint` | `azure` | `url` (the resource root), `api_key`, `azure_deployment`, `api_version`, optional `model_id` |
| `VertexEndpoint` | `vertex` | `vertex_credentials`, `vertex_location`, optional `vertex_project` and `model_id` |
| `BedrockEndpoint` | `bedrock` | `aws_access_key_id`, `aws_secret_access_key`, `aws_region`, `model_id`, optional `aws_session_token` and `aws_bedrock_runtime_endpoint` |
1. Field names are the router's own. A missing `provider` means `openai-compat`.
2. Unmute's validation has exercised the `openai` and `openai-compat` upstreams against the live router. `azure`, `vertex` and `bedrock` follow the router's published contract, and have not been run live there.
3. `auth_header` names the header the key goes in when it is not `Authorization: Bearer`. It can never be `Authorization`.
4. Every key is a secret. Neither `repr` nor a validation error shows it. Only the request body has it in clear. Never turn on the OpenAI client's debug logging (`OPENAI_LOG=debug`) with an inline config, because it prints request bodies.
5. On `AzureEndpoint`, the router ignores `model_id`. It is accepted so a stored config validates.
6. `vertex_credentials` takes a dict, or text. The text is the key's JSON, that JSON base64 encoded, or a path to the key file. `read_vertex_key(text)` does the same on its own.
```python theme={null}
VertexEndpoint(
vertex_credentials=os.environ["VERTEX_KEY"],
vertex_location="europe-west4",
)
```
## Without the router
`OpenAIModelCall` is a native call for any OpenAI-compatible endpoint. It sends no SLNG header and no SLNG body field, and the library fills the prompt. See [OpenAIModelCall](/core/reference/model-call#openaimodelcall).
## Gemini thought signatures
Gemini 3 signs the first tool call of each reply. Through an OpenAI-compatible API, the signature comes as the call's `extra_content`:
```json theme={null}
{
"id": "c1",
"type": "function",
"function": {"name": "find", "arguments": "{}"},
"extra_content": {"google": {"thought_signature": "..."}}
}
```
When the chat is sent again, each call must carry its signature back. Without it, Gemini 3 can refuse the request with a 400. The router passes `extra_content` through as it is, both ways.
```mermaid theme={null}
flowchart LR
M[Model] -->|signed tool call| R[RouterModelCall]
R -->|ToolCall.extra| H[History]
H -->|extra_content on the next request| R
```
1. `RouterModelCall` reads each call's `extra_content` into `ToolCall.extra`. A `ModelCall` of your own does the same.
2. The adapter keeps it with the call in the history. Each later request sends it back as the call's `extra_content`. Finish checks do too, and the finish a check chose keeps the check's own signature. So does an agent that takes the call with the full history, on a model of its own.
3. On LiveKit, it becomes `FunctionCall.extra`, which LiveKit sends back itself.
4. On Pipecat, the context keeps only a call's id, name and arguments. So `ModelCallLLMService.tool_extras` keeps the extras by call id and puts them back on each request, before the `before_model` hooks.
5. Both adapters send back only the `google`, `livekit` and `xai` keys, the ones LiveKit sends (`REPLAYED_PROVIDERS`). `replayed_extra(extra)` returns what goes back. A call with none of them goes back with no `extra_content`.
6. An `after_model` hook reads all the provider data the model sent, in `ToolCall.extra`. On Pipecat this needs a `ModelCallLLMService`. A native service keeps none.
For a Gemini model, `RouterModelCall` adds Google's placeholder, `skip_thought_signature_validator`, to an assistant message whose first call has no signature. A call the runtime makes itself, or one from another model, then passes. The model counts as Gemini when:
* the pinned `model` names Gemini,
* a model of the `config` names Gemini, or
* the history already holds a signature.
Under `slng/auto` with no config, the library cannot know the router picked Gemini until a signature comes back. A call the runtime adds before then, like a step's opening call, goes without the placeholder. An answer from the router's cache carries no signature. When the library knows the model is Gemini, the placeholder covers its calls on the next request.
`signed_tool_calls(messages, gemini=True)` applies the placeholder rule to any OpenAI-format chat, for a `ModelCall` of your own.
Gemini's OpenAI-compatible endpoint keeps only the last system message. The router folds the library's several system messages into one, so it avoids this limit. See [Gemini and several system messages](/core/reference/model-call#gemini-and-several-system-messages).
A native framework LLM keeps or drops signatures as its framework does. LiveKit's OpenAI-compatible plugins keep them. Pipecat's OpenAI services drop them, so reach Gemini 3 through `GoogleLLMService` or a `ModelCallLLMService`.
## Token counts, timeouts and errors
The router sends the token counts at the end of each answer. `RouterModelCall` yields them as a `Usage` event. The `llm` span shows them as `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. On Pipecat, turn on usage metrics:
```python theme={null}
params = PipelineParams(
enable_metrics=True, enable_usage_metrics=True
)
PipelineWorker(pipeline, params=params)
```
The client never retries. The router fails over by itself. `RouterModelCall.aclose()` closes the client only when the call built it. The default timeout is 15 seconds to connect, then 5 seconds for each read, the first token included. Pass `timeout=openai.Timeout(...)` or a number of seconds above zero to change it. `timeout=0` is refused.
| Answer | What happens |
| - | - |
| 400, 401, 402, 413, 422 | The call stops. No other model fixes it. |
| 400 from OpenAI on a request with tools | The call stops. Reasoning is on. Send `body={"reasoning_effort": "none"}`. |
| 400 `model ... is not selected by this org's default router config` | The call stops. The request carried no config of its own. Pass `config=`. |
| 401 with a valid key | The call stops. `SLNG_WORLD_PART` is not your SLNG project's region. |
| 403 `project_mode_forbidden` | The call stops. The key's project is not on the Execution Layer, so it may not send a config. `RouterModelCall.stop_codes` holds this code, and `FallbackModelCall` reads it. |
| 429 | `FallbackModelCall` waits out a short `Retry-After`, then fails over. With `same_model_retries`, a 429 with no usable `Retry-After` retries the same call first. |
| 5xx, a timeout, a lost connection | `FallbackModelCall` tries the next call. |
## Where to go next
Add SLNG speech or the router to your agent.
ModelCall, ModelRequest, events and FallbackModelCall.
The `SLNG_*` variables and how to check them at startup.
Where the `llm` span and the router's headers show up.
# State reference
Source: https://unmute.ai/core/reference/state
Every CallState argument, save and confirmation rule, prompt reading, value type and error, and State from type text.
This page is the full detail behind [State](/core/build/state). Start there to define, save and read a call's values. Come here for every rule, argument and error.
## What it gives you
| On a call without it | What the library does |
| - | - |
| The model saves half of a batch, and the values no longer fit together. | The whole batch is checked first. One bad value refuses all of it. [How a save works](#how-a-save-works) |
| A bad value comes back as a bare validation error. The model cannot tell what to ask. | The refusal says what is wrong, like `caller_phone: expected a phone number with its country code`. The model asks the caller again. |
| "612 345 678" is saved, or a number that does not exist. | `Phone` cleans and checks the number and saves it in E.164. [Value types](#value-types) |
| A misheard value is treated as fact, and the model reads it back as true. | Only the confirming step can confirm a value. Until then, other prompts show `none recorded yet`. [Confirmation](#confirmation) |
| The caller fixes their number. The record looked up from the old one stays. | A value saved from inputs goes back to empty when an input changes. |
| `3.0` is read aloud as "three point zero". | Whole numbers read as `3`. [How a value reads in a prompt](#how-a-value-reads-in-a-prompt) |
| Your product lets users define agents, and needs its own type system. | `StateSchema` builds the State from type text like `Phone \| None`. [Building a State from type text](#building-a-state-from-type-text) |
## CallState
`unmute_core.state` holds what one call knows. It keeps typed values, whether the caller confirmed each one, and how each value reads in a prompt. It works on any Pydantic model.
```python state.py theme={null}
from pydantic import BaseModel
from unmute_core.state import CallState, Phone
class State(BaseModel):
caller_phone: Phone | None = None
note: str | None = None
state = CallState(State, confirm={"caller_phone": "verify_phone"})
state.save({"caller_phone": "+34 612 345 678"}, step="verify_phone")
state.plain("caller_phone") # "+34612345678"
state.is_confirmed("caller_phone") # True, the confirming step saved it
state.save({"caller_phone": "+34 612 345 679"})
state.is_confirmed("caller_phone") # False, another save must wait for the caller
state.render("caller_phone") # "none recorded yet."
```
Every field needs a default, because every value starts the call empty. A field with no default raises `TypeError` when you build the `CallState`.
`state.names` lists the value names in the model's order. `state.name_set` gives the same names as a `frozenset`, for a quick membership test:
```python theme={null}
"note" in state.name_set # True
```
### Every argument CallState takes
The Pydantic model class of the state. Every field needs a default. Anything else raises `TypeError`. The default, `NoValues`, is for an agent with no values.
Value name to the task step that must hear the caller agree to it.
A looked-up value name to the value names it was looked up from.
Value name to `required` or `optional`, for the values a dispatch sets.
What the call carries, as `state.call`. None gives a web call with a new `session_id`. Build one with `call_info`, `sip_call_info` or `telephony_call_info`.
Every call needs an agent id. Pass `agent_id` to `CallInfo`, `call_info`, `sip_call_info` or `telephony_call_info`, or set `UNMUTE_AGENT_ID`. With neither, building the call state raises `SettingsError`. See [Settings](/core/reference/settings).
## How a save works
```mermaid theme={null}
flowchart LR
S[save] --> C{Every value fits its type?}
C -->|no| R[StateRefused, nothing saved]
C -->|yes| W[All values saved]
W --> F[Confirmation updated]
W --> L[Listeners told]
```
1. `state.save(values)` checks the whole batch against the model first.
2. If one value is unknown, does not fit its type, or is longer than 64,000 characters, `save` raises `StateRefused`. Nothing from the batch is saved.
3. `StateRefused.message` is worded for the model, like `caller_phone: expected a phone number with its country code`. A task step shows it to the model, so the model can ask the caller again.
4. Otherwise every value is saved. Phone numbers, dates and the like are saved in their clean form.
5. Read `state.values` if you like, but never write to it. `save` is the one way in.
A value is saved by a task step, by [prefetch](/core/build/prefetch), by the model through the [`save_values` tool](#saving-values-no-task-saves), or by your own code calling `state.save`.
A task step may try to save before the caller said anything in it. The state keeps that save aside. It is a held save. When the call ends, the library decides whether to keep it. That decision is to settle it. [Held saves](/core/build/tasks/held-saves) explains how.
## Confirmation
`confirm` maps a value name to the task step that must hear the caller agree to it.
1. A value in `confirm` starts unconfirmed.
2. It becomes confirmed when its own step saves it with something in it.
3. Any other save of it makes it unconfirmed again. The caller must agree again.
4. `state.withdraw("verify_phone")` takes back every confirmation that step gave. The step runs again.
5. `state.is_confirmed(name)` is true when the value is filled and its confirmation stands.
`dependencies` covers a value that was looked up from other values: `CallState(State, dependencies={"customer": ["caller_phone"]})`. It is confirmed only while all of those values are filled and confirmed.
A dependent value that no step confirms reads empty in every prompt until its sources are confirmed. One that a step confirms reads in that step's prompt too.
A value saved by a prefetch `Lookup` also remembers what it was read from. When one of those inputs changes, the value goes back to its default. See [Prefetch](/core/build/prefetch).
## How a value reads in a prompt
`state.render(path, site="")` gives the text a prompt shows.
| Value | What `render` returns |
| - | - |
| Text | The text as it is |
| Anything else | Compact JSON, like `{"name":"Jo"}` |
| Empty, or waiting for the caller | `none recorded yet.` |
| An empty call-start value | Empty text |
| A long value | The whole value. Only a model call with its own limit, like the router, cuts it |
A value that waits for confirmation reads as empty. The one exception is the step that confirms it. Pass `site="task:verify_phone"` and that step sees the value, so it can read it back to the caller.
`state.plain(path)` gives JSON data instead of text. A date reads `"2026-10-02"`. A dotted path reads into a shape: `state.plain("customer.status")`. A path through an absent value gives `None`. A name the state does not hold raises `KeyError`.
`state.snapshot(site="")` gives every value as `render` does. The model call uses it to fill the prompt.
## Filling a prompt
```python theme={null}
from unmute_core.model import render_prompt
prompt = render_prompt("Help the caller on {{caller_phone}}.", state)
```
The prompt names a value as `{{caller_phone}}`. A path into a shape is `{{customer.status}}`. The same path also reads `{{customer__status}}`, the form the SLNG Context Router reads.
```mermaid theme={null}
flowchart LR
P[Prompt with placeholders] --> N[Find each name]
N --> R[state.render for each]
R --> F[Filled prompt]
N -->|name not in the state| E[MissingVariablesError]
```
1. Each `{{name}}` is found. Spaces inside the braces are fine: `{{ name }}`.
2. Each name is rendered with `state.render`. So a value that waits for confirmation reads `none recorded yet.`
3. A task step passes its own site, like `task:verify_phone`. A site is the place in the agent where a prompt is used: `task:` for a task step, none for the main prompt. At its own site, the step sees the unconfirmed value.
4. The fill runs in one pass. A value that holds `{{x}}` is not filled again.
5. A saved value reaches the model whole. A native model call never cuts it.
6. A name the state does not hold raises `MissingVariablesError`. Its `names` list every missing name.
### render\_prompt
The prompt, with `{{name}}` placeholders.
The call state. None works for a prompt with no placeholders.
The prompt reading the values, like `task:verify_phone`.
Call `render_prompt` again after a save, so the prompt shows the new values. Two lower-level helpers, `template_variables(messages, state, site)` and `fill_messages(messages, variables)`, work on chat messages. They fill only system and developer messages.
### Which one to use
```python LiveKit theme={null}
from unmute_core.livekit import ModelCallLLM, UnmuteAgent
agent = UnmuteAgent(AgentSpec(PROMPT, tasks=plan), state=state) # the session's LLM answers
llm = ModelCallLLM(model, state=state) # a ModelCall answers
```
```python Pipecat theme={null}
from unmute_core.pipecat import ModelCallLLMService, UnmuteFlows
llm = ModelCallLLMService(model_call, state=state) # a ModelCall answers
flows = UnmuteFlows(AgentSpec(PROMPT, tasks=plan), llm=llm, state=state, ...)
```
```python Plain agent theme={null}
instructions = render_prompt(PROMPT, state) # a native LLM of your own
```
With a `ModelCall`, the prompt stays unfilled in the request. The model call fills it, natively or through the router. The model reads the same final prompt either way. See [Model call](/core/models/model-call).
## Values the call starts with
```python theme={null}
from unmute_core.call import save_call_start
state = CallState(State, call_start={"customer_id": "required", "brand": "optional"})
save_call_start(state, dispatched)
render_prompt("Welcome to {{brand}}.", state) # "Welcome to Salon Sol." or "Welcome to ."
```
Every value a call starts with is a State value. `call_start=` names them, like `confirm=` does.
1. `required` means the call cannot start without it. `optional` means it may be missing.
2. `save_call_start(state, dispatched, *, env=True)` reads `state.call_start`.
3. `dispatched` is the `call_start` object a call is dispatched with. `UNMUTE_CALL_START` gives the same for a local run, and the dispatch wins. Pass `env=False` to read only the dispatch.
4. With a mapping, only those names are taken. A missing required name raises `CallStartError`.
5. Without a mapping, any State value may be set and none is required.
6. Other names are dropped, and the log names them. A value that does not fit raises `CallStartError`, and nothing is saved.
7. The origin kind of these saves is `call_start`.
8. A name in `call_start` that the model does not have raises `ValueError`. So does a rule other than `required` or `optional`, and a name that is also in `confirm`. The caller is never asked for a value the call starts with.
[The call's life](/core/build/call-lifecycle#start-values) shows where `save_call_start` runs.
### How they read
1. An empty call-start value reads `""` in a prompt. Other empty values read `none recorded yet.`.
2. An optional call-start value never refuses a tool. A `{{brand}}` in an argument, a locked argument or an announce line reads as empty text.
3. The save tool (`values_tool`) leaves call-start values out. A call that names one is refused with `brand is set when the call starts. It cannot change`.
4. `values_block` shows each one as "set when the call starts".
### In a schema
```python theme={null}
{"name": "brand", "type": "str", "call_start": "optional"}
```
A `StateSchema` row has a `call_start` field: `"required"`, `"optional"` or none. `schema.call_start` gives the mapping, like `schema.confirm` does. Pass it on to `CallState`.
## Values the call carries: `state.call`
```python theme={null}
state = CallState(State)
state.call.session_id # one id for the whole call
state.call.calling_number # "+34612345678", or None
render_prompt("The caller is {{call.calling_number}}.", state)
```
Every `CallState` holds one more value. Its name is `call`. It holds what the call itself carries: who is on it and how it came in. The library fills it. Your State class does not declare it. [State](/core/build/state#values-the-call-carries-state-call) lists its fields.
`CallState()` with no model works too. It uses `NoValues`, for an agent that has no values of its own.
More on the fields:
1. `session_id` is new for each call and never changes. It is the same on every turn, task and handoff, on LiveKit and on Pipecat.
2. `carrier_call_id` is not `session_id`.
3. The library saves `first_user_message` from what the caller said first, and `end_reason` as the call ends.
4. A withheld or malformed number reads as `None`. It is never an error.
### The three cases
1. **Inbound phone call.** The caller is `calling_number`. The agent's own number is `called_number`. `remote_number` is the caller.
2. **Outbound phone call.** The agent's own number is `calling_number`. The customer is `called_number`. `remote_number` is the customer.
3. **Web call.** `channel` is `web`. There are no numbers and no `direction`. The `session_id` is still set.
To try a phone call in a web session, give a `call` object in the call-start dispatch. `save_call_start(state, dispatched)` reads it, so your agent must call it:
```bash theme={null}
UNMUTE_CALL_START='{"call": {"direction": "inbound", "calling_number": "+34612345678"}}' uv run python agent.py
```
1. On a web call, every field you give applies.
2. On a phone call, the line wins. Its own `channel`, `direction`, `calling_number`, `called_number` and `carrier_call_id` stay. The dispatch fills only the empty ones.
3. `agent_id` and `session_id` always apply.
### Where it reads
1. Python reads `state.call.calling_number`.
2. A prompt, a task text, a greeting, an announce line and a locked tool argument read `{{call.calling_number}}` and `{{call.session_id}}`.
3. An empty call value reads `""` in a prompt.
4. A tool that locks an empty call value is refused: `this tool reads call.carrier_call_id, which this call does not carry`.
5. `state.names`, `values_block`, `snapshot`, `save_values` and `state.dump()` leave `call` out.
### Read-only
Only the library writes `call`. `state.save({"call": ...})` is refused unless the save comes from the library.
A State value named `call` raises `ReservedNameError`. It is a `ValueError`. The same holds for a `StateSchema` variable, an alias, a `confirm`, `dependencies` or `call_start` rule, a task `assign` and a prefetch `assign`. The message says:
```text theme={null}
... names 'call', which unmute-core reserves for what the call carries ...
```
**Fix:** rename your value, like `caller_phone`.
### Confirming the caller's number
`state.call` is read-only, so the caller cannot confirm it there. Copy it into your own value with a `CallValue` prefetch entry. Then confirm that value in `confirm=`.
```python theme={null}
from unmute_core.prefetch import CallValue, Prefetch
class State(BaseModel):
customer_phone: Phone | None = None
prefetch = Prefetch([CallValue("caller", "calling_number", ["customer_phone"])], state=State)
state = CallState(State, confirm={"customer_phone": "verify_phone"})
```
A step named `verify_phone` then asks the caller to agree. See [Prefetch](/core/reference/prefetch#callvalue).
## Saving values no task saves
Some values belong to no task. The model learns them in free talk. `values_tool` gives the model a `save_values` tool for those values. `values_block` writes the values block: a short system message that lists each value and what it holds now.
```python theme={null}
from unmute_core.tools import values_block, values_tool
tool = values_tool(state, owners=plan_spec.owners())
values_block(state, owners=plan_spec.owners())
```
`values_block` gives text like this:
```text theme={null}
Values of this call. Save new ones with save_values.
- name (The caller's name): Ana
- party: 2
- booking, saved by the task book_table: none recorded yet.
- brand, set when the call starts: Salon Sol
```
1. `values_tool` builds the `save_values` tool. Each free value is an optional argument that may be null.
2. `null` puts a value back to its default.
3. `owners` maps a value to the task that saves it. Use `TasksSpec.owners()`.
4. A value a task saves is refused with ` is saved by the task . Start that task to change it`.
5. A call-start value is left out and refused too, with ` is set when the call starts. It cannot change`.
6. The tool returns `{"ok": true, "saved": {...}}`.
7. The tool saves the batch as a whole, like `state.save`. A value that does not fit refuses all of them.
8. If every value belongs to a task or to the call's start, there is nothing to save. `values_tool` raises `ValueError`. `free_values(state, owners)` lists the values left to save, so you can check first.
9. `AgentSpec(save_values=True)`, on either adapter, shows the block whenever State has values. It offers the `save_values` tool only when a value is free. With none free, the block's first line names no tool.
### values\_tool
The call state.
Value name to the task that saves it.
The tool name.
### values\_block
The call state.
Value name to the task that saves it.
The save tool's name, as the block names it.
### Turn it on
[State](/core/build/state#saving-values-no-task-saves) shows `save_values=True` on `UnmuteAgent` and `UnmuteFlows`. On a plain LiveKit agent:
```python Plain LiveKit agent theme={null}
from livekit.agents import Agent
from unmute_core.livekit import filled_llm, function_tools
from unmute_core.tools import ToolRegistry, values_tool
registry = ToolRegistry([values_tool(state)])
class Desk(Agent):
def __init__(self) -> None:
super().__init__(instructions=PROMPT, tools=function_tools(registry, state))
async def llm_node(self, chat_ctx, tools, model_settings):
async for chunk in filled_llm(
self, chat_ctx, tools, model_settings, state=state, save_values=True
):
yield chunk
```
1. `save_values=True` on the spec gives that agent the tool. An agent the call is handed to has its own `save_values`. Each main-agent model request ends with the block as its last system message. A step's request gets none.
2. `save_values=True` needs a state. Without one, `UnmuteAgent` and `UnmuteFlows` raise `ValueError`.
3. On a plain LiveKit agent, `filled_llm` runs the agent's own LLM plugin. It fills the prompt from the state on each request. With `save_values=True` it ends the request with the block.
4. On a plain Pipecat pipeline, give `tools_schema(registry, state)` to the context. Then `await fill_prompt(llm, worker, PROMPT, state, save_values=True)` before the pipeline runs. It sends the filled prompt as the service's system instruction, and sends it again after each save. See [Pipecat](/core/frameworks/pipecat).
5. `is_values(role, text)` from `unmute_core.tools` tells whether a message is that block. It is a `system` message that starts with the block's header. Use it to drop the old block from a chat before you add a new one.
## Building a State from type text
```python theme={null}
from unmute_core.state import CallState, StateSchema
schema = StateSchema(
[
{"name": "caller_phone", "type": "Phone | None", "confirm": "verify_phone"},
{"name": "contacts", "type": "list[Contact]", "description": "People to call back."},
{"name": "note"},
],
[
{
"name": "Contact",
"fields": [
{"name": "name", "type": "str"},
{"name": "email", "type": "EmailStr"},
],
}
],
)
state = CallState(schema.model, confirm=schema.confirm, call_start=schema.call_start)
```
`StateSchema(variables, shapes)` checks the rows and builds the Pydantic class. `schema.model` is that class. `schema.confirm` and `schema.call_start` are the maps for `CallState`. The class and a hand-written one run through the same `CallState`.
1. Every value starts empty. A list starts as `[]`. Anything else starts as `None`.
2. Empty text counts as no value.
3. A `Variable` holds `name`, `description`, `type` (text by default), `confirm` and `call_start`.
4. A `Shape` is a named group of fields, like `Contact`. Name a shape in the type text.
5. A field of a shape is required unless its type ends in `| None`.
6. A bad row raises `StateSchemaError` or a Pydantic error. It names the row and the fix.
### The type grammar
A type is plain Python type text. `parse_type("Phone | None").canonical` gives the one canonical spelling.
| Type text | Meaning |
| - | - |
| `str`, `int`, `float`, `bool` | The usual scalars. `string`, `integer`, `number` and `boolean` also work. A `float` refuses NaN and infinity. A text value is trimmed of spaces at both ends. |
| `Phone`, `Date`, `Time`, `Id`, `EmailStr` | The value types below |
| `Literal["new", "known"]` | One of the listed texts |
| `list[T]` | A list of `T` |
| `Contact`, `NameEmail` | A shape. `NameEmail` is built in. |
| `T \| None` | `T`, or nothing yet |
A type the grammar does not take raises `TypeTextError`. Its message says what to write instead. For example, `datetime` is refused. Write `Date` and `Time` as two fields.
## Value types
A model may also use these classes from `unmute_core.state` directly, as `State` does in the [CallState](#callstate) example.
| Type | Saved as | JSON Schema `format` |
| - | - | - |
| `Phone` | E.164 text, like `+34612345678` | `phone` |
| `Date` | `YYYY-MM-DD` text | `date` |
| `BirthDate` | `YYYY-MM-DD` text | `birth-date` |
| `Time` | `HH:MM` text on the 24-hour clock | `time` |
| `Id` | Text of letters, digits, and `. _ : -` | `id` |
| `Spelled` | The code as given, trimmed | `spelled` |
| `NameEmail` | A shape with `name` and `email` | none |
1. `Phone` drops spaces, dashes, dots and brackets. A leading `00` becomes `+`.
2. A phone number with no plus is saved only when one valid reading exists. The call's country can help. Enter `use_phone_region(...)` with the country the call is in. [Prefetch](/core/build/prefetch#what-a-call-carries) shows how.
3. A bad number is refused with a reason the model can act on. It may be too short, too long, or missing its country code.
4. `NameEmail` reads `Jo Bloggs ` or a bare address. Paths read its parts: `{{contact.email}}`.
5. The `format` lets a tool schema or another reader name the type.
6. A bad `Id` is refused with the words: "expected an identifier: letters, digits, and then any of dot, dash, underscore or colon". An `Id` has at most 64 characters. The refusal shows no pattern.
7. A number sent to a text value is saved as its text. NaN and infinity are refused there too.
8. A whole float reads as an integer in a prompt, a tool result, a webhook URL placeholder and `CallState.snapshot()`: `3.0` renders as `3`. A locked argument that is a whole `"{{price}}"` still sends the float.
9. A choice (`Literal[...]`) is matched with the spaces around the answer and the choices ignored, so a padded answer still fits. The value saved is the choice as declared, `" small"` included.
10. Code says a `BirthDate` with its year and no weekday, like "June 5, 1979", and a `Spelled` code a character at a time, in groups, like "K P, 4 8 2, 9 1 3". A voice then reads each character on its own. Check a code's pattern with your own validator.
11. A variable name may start with an underscore or be a `model_*` name. It works as any other name, in the prompt, in a tool's arguments and in a task's saves.
## Listening to changes
```python theme={null}
def show(event) -> None:
for change in event.changes:
print(change.field, change.value, change.confirmed, change.by.kind)
stop = state.listen(show)
state.save({"note": "call back"}, step="take_note")
stop()
```
1. A listener gets one `StateEvent` per save that changed something. A save that changed nothing sends nothing.
2. `event.changes` lists each value that changed. A change holds `field`, `value` as JSON, `confirmed`, and `by`.
3. `confirmed` is `None` for a value that never waits for the caller.
4. `by` is a `StateOrigin`. Its `kind` is one of nine: `step`, `prefetch`, `call`, `call_start`, `tool`, `event`, `withdraw`, `start` or `reset`. Any other kind raises a `ValidationError` when you build the origin.
5. `listen(listener, replay=True)` first sends the values already set, as one event of kind `start`.
6. A listener that raises is logged and removed. It never fails the save.
## Who supplies a value
When a tool needs a value that is not set, the refusal tells the model which task saves it. See [Tools](/core/reference/tools#a-call-that-is-refused). The state keeps that map in `state.suppliers`.
```python theme={null}
state.set_suppliers({"caller_phone": "verify_phone"}) # value name to task or group
state.clear_suppliers() # an agent with no tasks has no suppliers
```
1. `set_suppliers` replaces the earlier map. It does not merge.
2. The adapters call it when a task plan runs. You call it only when you build your own task host.
3. Write to the map only through these two methods.
## Troubleshooting
### TypeError when you build the CallState
The first argument is not a Pydantic model class, like `CallState(int)`. Or a field has no default. Every value starts the call empty.
**Fix:** pass your State class, or `schema.model`. Give each field a default.
```python theme={null}
class State(BaseModel):
note: str | None = None
```
### StateRefused from a save
A value is unknown, does not fit its type, or is too long. Nothing from the batch was saved. `StateRefused.message` says which value and why.
**Fix:** correct the value and save the batch again. In a task step, the model reads the message and asks the caller again.
### MissingVariablesError when a prompt fills
The prompt names a `{{name}}` the state does not hold. Its `names` list every missing name.
**Fix:** add the value to the model, or correct the name in the prompt.
### ValueError from values\_tool
Every State value belongs to a task or to the call's start, so there is nothing to save. Only a direct `values_tool` call raises it. `AgentSpec(save_values=True)` shows the block and offers no tool instead.
**Fix:** build the tool only when a value is free, or use `save_values=True`.
## Where to go next
Define, save, confirm and read a call's values.
Fill values before the greeting.
# Tasks reference
Source: https://unmute.ai/core/reference/tasks
Every argument of the task spec classes, TaskPlan, CallTasks and StepRun.
Every class you import from `unmute_core.tasks` to define and run tasks. Each spec class is immutable and refuses keys it does not know. They are Pydantic models, so you can build them as literals or from JSON with `model_validate`.
## TaskSpec
One task: a prompt, its tools, and the values it saves when it finishes. Guide: [Your first task in code](/core/build/tasks/first-task).
Lower snake case, at most 64 characters. The prompt site is `task:`.
The step's prompt, at least one character. `{{name}}` reads a State value. `{{customer.status}}` or `{{customer__status}}` reads a field inside one.
When the main agent starts it, said to the model. Leave it out for a step that only a group or a `via` tool starts. At most 1000 characters, never blank.
Names of the tools the step may call.
The values it saves, from its finish call or a closing tool's result.
Tools whose result ends the step by itself.
Lines spoken as it starts. Several are alternatives, and one is picked each time. A line holds no placeholder.
`generate` opens with a model reply. `listen` speaks the announce line and waits for the caller.
What the step hears of the call so far. See [What a step hears of the call](/core/build/tasks/what-the-model-reads#what-a-step-hears-of-the-call).
How many items `last_n` keeps, from 1 to 200. Required with `last_n`, and refused with any other history.
`False` leaves tool calls and results out of `full` and `last_n`.
Handoff tools of the agent that the step offers too. Calling one ends the step and gives the call to another agent. See [Handoffs](/core/build/handoffs).
Framework tools of the agent that the step offers too, as they are. An MCP toolset is one example.
State values that must be set before it runs. Exactly one other task must save all of them. That task runs first when they are not set.
Tools of its own that the main agent may call too. A success moves the caller into this task. Each must also be in `tools`.
What it reads at the end of its prompt.
State values the main agent passes when it starts the task. Each call saves all of them, so a value it leaves out is cleared. Needs a `when`.
A tool it runs in code as it opens, before any model request.
Lines code speaks for a tool result, in place of a model reply. At most 16.
The model its step runs on, by a name `AgentSpec(task_models=...)` maps to a model, like `fast`. `None` runs it on the agent's model. Pipecat refuses it.
## Assign
One value a step saves. Guide: [Your first task in code](/core/build/tasks/first-task#assign).
The State value it saves.
Where the value sits in the step's result, like `("order", "id")`. At most 8 parts. `()` saves the whole result, into a State value typed as the tool's output model.
Add one entry onto a list instead of replacing it. This is Unmute's `+`.
The step may finish without it. This is Unmute's `?`. Otherwise a served finish must carry it, unless it appends.
The finish parameter is the field itself for a one-part path. For a longer or an
empty path it is the variable name. Two assignments may not share a finish
parameter. An agent without tasks uses the same rows on its `ToolRegistry`. See
[Save a result and speak it](/core/build/tools#save-a-result-and-speak-it).
## FinishRule
A step ends by itself when this tool returns a result the rule calls a success. Guide: [Reply and confirm in code](/core/build/tasks/confirm-in-code).
The tool. It must be one of the step's own `tools`.
Result field to the values that count as success. Every field must hold one of its values. From 1 to 16 fields.
Lines spoken from the result. They may use `{{result.}}` and `{{variable}}`, nested like `{{account.amount_words}}`.
Lines asked before the tool runs. They may use `{{input.}}` and `{{variable}}`, nested like `{{account.amount_words}}`. See [Ask before a closing tool runs](/core/build/tasks/confirm-in-code#ask-before-a-closing-tool-runs).
## ToolReply
A line code speaks when one of the step's tools returns a matching result. Guide: [Reply and confirm in code](/core/build/tasks/confirm-in-code#say-a-fixed-reply-to-a-tool-result).
One of the step's own tools.
Result field to the values that call for the line. Every field must hold one of its values. Empty matches every result.
State value to the values that call for the line, read the same way.
At least one line. They may use `{{result.}}` and `{{variable}}`, nested like `{{account.amount_words}}`.
The first reply that matches and fills is spoken. An agent without tasks uses the
same rows on its `ToolRegistry`. See
[Save a result and speak it](/core/build/tools#save-a-result-and-speak-it).
## OpeningTool
A tool a step runs in code as it opens, before any model request. Guide: [Reply and confirm in code](/core/build/tasks/confirm-in-code#open-a-step-with-a-tool).
One of the step's own tools. A tool the step ends on is allowed only with `confirm` lines.
Tool parameter to the State value it takes. The tool runs only when every value is set. A parameter the tool's schema declares and does not require is left out of the call when its value is not set.
Lines spoken from the result. The first one that fills is spoken. Give none for a tool with `confirm` lines.
## TaskInput
Something a step reads at the end of its prompt. Guide: [What the model reads](/core/build/tasks/confirm-in-code#a-step-that-reads-a-prefetch-lookup).
`memory` reads a State value. `input` is a fixed text, in `value`. `tool` is what a prefetch lookup returned, recorded by name.
The State value, the input's name, or the lookup's name.
The text of an `input`, up to 4000 characters. Only that kind carries one.
## TaskGroupSpec
Tasks the main agent runs as one flow, step after step. Guide: [Task groups in code](/core/build/tasks/groups).
Lower snake case. A task and a group may not share a name.
The task names, in order. There must be at least one. Each runs at most once in the group.
`shared`: each step hears the steps before it. `isolated`: each step starts fresh.
When the main agent starts it.
What follows a group that completes. See [What a group does when it finishes](/core/build/tasks/groups#what-a-group-does-when-it-finishes).
The agent a `transfer` hands the call to, by the name the adapter's `then_targets` gives it. Only `transfer` takes one, and `transfer` needs one.
Lines spoken as it starts.
Steps whose failure the group records and carries on past. Each must be one of its steps.
Step to the State value whose confirmation lets the group skip it. The step must be the one that confirms that value.
What every step reads at the end of its prompt, before its own inputs.
State values the main agent passes when it starts the group. Each call saves all of them.
## TasksSpec
Every task and group of one agent. Guide: [Your first task in code](/core/build/tasks/first-task#run-the-tasks).
The format version.
`status`: a run hands the main agent a status, and a hand-back saves nothing, as Unmute's emitted agents do. `record`: a run hands back a record of each step, a hand-back keeps what the caller confirmed, steps can go back, and a step's finish is checked against what the caller said.
The tasks.
The task groups.
Tools only tasks may call. The main agent does not get them. A task must list each one.
`TasksSpec.owners()` returns each State value that a task saves, with the first
task that saves it. The save tool for values no task saves uses it. See
[State](/core/build/state).
## TaskPlan
The tasks and groups of one agent, checked once and read by every call.
`TaskPlan` checks the spec against the State and the tools. It raises
`ValueError` and names the first task, group or value that does not fit. Guide: [Your first task in code](/core/build/tasks/first-task#taskplan).
The tasks and groups.
The State model the call's `CallState` runs on.
State value to the step that confirms it, as given to `CallState`.
Every tool of the agent, task-only ones included.
`TaskPlan.check_then_targets(known)` refuses a group that transfers to an agent
the adapter was not given. The adapters call it when they are built.
```python theme={null}
plan.check_native_tools(["crm"])
plan.check_handoff_tools(["to_notes"], fix="Add it to native_tools.")
```
1. `check_native_tools(names)` refuses a task that lists a native tool the agent does not have. It raises `ValueError` and names the first task and the missing tool.
2. `check_handoff_tools(names, fix=)` refuses a task whose `handoffs` names a tool the agent has no handoff for. `fix` is the end of the message. Say how to add the tool.
3. Both take `task=` to check one task. Without it, they check every task.
4. The adapters call them when the agent is built. Call them yourself when you write your own host.
## CallTasks
The tasks of one call: the main agent's task tools, and every run they start.
`UnmuteAgent` and `UnmuteFlows` build one per call from the [`AgentSpec`](/core/reference/agent-spec). Build one yourself only in your own host. Guide: [Your first task in code](/core/build/tasks/first-task#calltasks).
The agent's checked tasks.
The call state.
The call's hooks, like its `CallHooks`. They run around each tool a step calls, and hear each task event.
What the lookups that run at call start gave the main agent. Pass `call.results`.
The call's language, a BCP-47 tag like `es-MX`. Confirm lines say dates and times in it.
Where the business is, an IANA name like `Europe/Madrid`. Confirm lines then name a day from today, like "today, October 8". Without it they say the full date with its year. An unknown name raises `ValueError`.
What a step says when the model's reply stays empty after every retry. Write it in the call's language. LiveKit says it. The constant is in `unmute_core.tasks`. Each adapter builds its own `CallTasks`, as `agent.tasks` on LiveKit and `flows.tasks` on Pipecat. So set `agent.tasks.gave_up_line` after you build the agent.
The same, when the last retry followed a step tool's result.
`CallTasks.empty(state, tools=...)` gives the tasks of an agent
that has none. Use it in your own host when it needs a stack and you have no tasks.
## StepRun
`StepRun` is what an adapter holds for the step that is running. Its values are
read-only properties. Assigning to one raises `AttributeError`. Guide: [How a task step ends](/core/build/tasks/how-a-step-ends).
How the step ended: the outcome's status, `went_back`, or empty text while it runs.
The step opens by speaking `announce` and waiting, with no model request.
The line to say as it opens.
The tool that just ran succeeded, and its effect ends the call.
The spoken line the step ended on, from a closing tool's result.
The line code speaks for the tool call that just ran. It is a `replies` line, or a `confirm` line asked before the tool runs.
The whole result of the tool call that just ran, for code.
The step tool and result that the first refused finish answered with no words.
A tool's result the step finished on without telling the caller.
Whether the model replies to the last refusal of `finish`. It is `False` when the reply that made the finish already spoke to the caller.
What the closing tool that ended the step returned.
# Telemetry reference
Source: https://unmute.ai/core/reference/telemetry
Every Telemetry helper, sink argument, span and attribute, and how each vendor's names are added.
This page is the full detail behind [Telemetry](/core/observe/telemetry). Start there to send a call's spans somewhere. Come here to call the helpers by hand, write a sink, or read a span's attributes.
## How it works
```mermaid theme={null}
flowchart LR
A[Adapter] -->|start_* / end_*| T[Telemetry]
T --> P[TracerProvider, one per call]
P --> L[Langfuse sink]
P --> G[Logfire sink]
P --> C[Coval sink]
P --> O[Otlp sink]
O -.->|filter=MetadataOnly| X[Collector]
```
1. The LiveKit or Pipecat adapter calls the `start_*` and `end_*` helpers on session events.
2. `Telemetry` owns one TracerProvider for the call. It stamps the call's identity on every span.
3. Each sink adds a batch processor and an OTLP/HTTP exporter to that provider.
4. A sink with `filter=MetadataOnly()` sends no text. It keeps only an allow-list of attributes.
5. `close()` ends the call span and flushes every sink.
## Telemetry
### Telemetry arguments
Where the spans go. Pass at least one.
The agent's name. It is the trace name and the service name.
The call's ID, like the room or session ID. It is stamped on every span as `session.id`. An empty `agent` or `call_id` raises `ValueError`.
Extra resource attributes, like `deployment.environment.name`.
Extra span processors that run before the sinks, for example one that adds your own attributes.
Providers that pass a request on to another provider named in the model id, like OpenRouter. A speech span for one of them records the provider behind it as `unmute.upstream.provider`. For `slng/fish/tts:s2.1-pro` the value is `fish`. Add your own gateway here. The default is `GATEWAYS`.
### Call the helpers by hand
The adapters call these helpers for you. Call them yourself only on a framework the library has no adapter for.
```python agent.py theme={null}
telemetry = Telemetry(Langfuse.from_env(), agent="salon", call_id=state.call.session_id)
telemetry.start_call()
telemetry.describe_call(origin="phone", framework="livekit") # how the call arrived
turn = telemetry.start_turn(1)
telemetry.stt(text="Book me in", model="soniox/speech-ai:rt-v5", provider="slng", start_time=spoke_at)
llm = telemetry.start_model_request(
model="gpt-5.6-terra", provider="openai", messages=messages, tools=tools, parent=turn
)
request_headers = telemetry.headers(llm) # traceparent for the model request
telemetry.end_model_request(llm, tool_calls=calls, input_tokens=812, output_tokens=40, ttfb=0.31)
telemetry.event("task.started", {"task": "booking"}) # also: tasks.listen(telemetry.event)
tts = telemetry.start_tts(model="slng/fish/tts:s2.1-pro", provider="slng", voice=VOICE)
telemetry.end_tts(tts, text="Which day?", ttfb=0.12)
telemetry.end_turn(turn, user_text="...", agent_lines=["Which day?"], e2e=1.1)
await telemetry.close(state=call_state, reason="ended") # ends the call, flushes
```
### Helpers
| Helper | Span it makes |
| - | - |
| `start_call()`, `describe_call(origin=, framework=)`, `close(timeout=, state=, reason=)` | `conversation` |
| `start_turn(number, parent=)`, `end_turn(span, ...)` | `turn` |
| `stt(text=, model=, provider=, start_time=, language=, ttfb=, parent=)` | `stt` |
| `start_model_request(model=, provider=, site=, messages=, tools=, parent=, started_at=)`, `end_model_request(span, ...)` | `llm` |
| `start_tool_call(name=, call_id=, arguments=, parent=)`, `end_tool_call(span, result=, error=)` | `llm_tool_call` |
| `start_tts(model=, provider=, voice=, parent=)`, `end_tts(span, text=, ttfb=, interrupted=, error=)` | `tts` |
| `start_task_step(task=, step=, parent=)`, `end_task_step(span, outcome=, saved=, error=)` | `task_step` |
| `event(name, data, parent=)` | one event span |
| `headers(span)` | none. Returns a `traceparent` for a model request. |
`close` waits up to 10 seconds by default (`CLOSE_TIMEOUT_SECONDS`) so a call that no simulation placed has time to be filed with Coval. It returns whether the flush finished.
Rules for the end helpers:
1. Latencies are in seconds. A missing, negative or infinite latency is left out, never sent as 0.
2. `error=""` sets `error.type` and the span status to ERROR. On Pipecat, the `llm` span gets the error type of an `ErrorFrame` from the LLM service.
3. An attribute with no value is not set.
4. `gen_ai.provider.name` is lowercase, so one provider has one name on both frameworks.
5. A text attribute keeps up to 256 KiB, so a long prompt stays valid JSON.
`describe_call(origin=..., framework=...)` sets `unmute.call.origin` (`phone`, `browser` or `websocket`) and `unmute.call.framework` (`livekit` or `pipecat`) on the call span. Values given before `start_call` wait and are set when it starts. After the call span ended, it does nothing. The adapters stamp the framework themselves. `correlate_coval` sets the origin.
## On a plain agent
On LiveKit, `UnmuteAgent` traces the session for you. `trace_session` is for a plain `Agent`:
```python theme={null}
from unmute_core.livekit import trace_session
trace = trace_session(session, telemetry, state)
```
A native LLM plugin on a plain `Agent` gets an `llm` span through `traced_llm`, which also fills `{{placeholders}}` from the trace's state. `tts` spans need a `tts_node` on your agent:
```python theme={null}
class OrdersAgent(Agent):
async def llm_node(self, chat_ctx, tools, model_settings):
async for chunk in traced_llm(self, trace, chat_ctx, tools, model_settings):
yield chunk
async def tts_node(self, text, model_settings):
async for frame in traced_tts(self, trace, text, model_settings):
yield frame
```
`ModelCallLLM(model, trace=trace)` also gives an `llm` span when a `ModelCall` answers.
On Pipecat, leave Pipecat's own `enable_tracing` off, or the call is traced twice. Set `PipelineParams(enable_metrics=True, enable_usage_metrics=True)`, or the spans have no time to first byte and no tokens. `TelemetryObserver` logs one warning when these are not on.
### TelemetryObserver
The call's telemetry, with its call span started.
The model name the `llm` spans carry. After a handoff gives the next agent its own model call, its spans name that one.
Who serves the model, like `openai`.
The call's tasks, which tell each request's prompt site.
With a `ModelCallLLMService` in `flows`, the observer also sets the service's `trace_headers`. Each model request then carries a `traceparent`, so the router's spans join the call's trace. On Pipecat they are children of the turn span, not of the request's `llm` span. The observer gets frames through a queue, so the `llm` span may open after the request is sent.
## Sinks
| Sink | Sends to |
| - | - |
| `Langfuse` | `{base_url}/api/public/otel/v1/traces` |
| `Logfire` | `https://logfire-{us,eu}.pydantic.dev/v1/traces`. The token names the region. |
| `Coval` | `https://api.coval.dev/v1/traces`, after `activate()` or when the call is filed |
| `Otlp` | Any OTLP/HTTP endpoint, like an OpenTelemetry Collector |
Each of the first three has `from_env()` and `from_settings(settings)`. `from_env` raises `TelemetryConfigError` and names every missing variable. A missing Coval key only logs a warning. `LangfuseSettings`, `LogfireSettings` and `CovalSettings` read the same variables. Pass one to `from_settings` to load them at startup with `check_settings`, or to set values in code. Both methods take sink options too, like `Langfuse.from_env(filter=MetadataOnly())`. [Settings](/core/reference/settings) lists every variable.
### Sink arguments
`Langfuse`. The project's public key.
`Langfuse`. The project's secret key.
`Langfuse`. Like `https://cloud.langfuse.com`.
`Logfire`. A write token.
`Coval`. The Coval API key. `None` exports nothing.
`Coval`. The simulation ID for a local run. An adapter's `correlate_coval` reads it.
`Coval`. File a call no simulation placed as a Coval conversation at the end. `False` files nothing.
`Otlp`. The full traces URL, like `http://collector:4318/v1/traces`. With none, the OpenTelemetry SDK reads its own `OTEL_EXPORTER_OTLP_*` variables.
`Otlp`. Extra HTTP headers, like an API key.
Every sink. Lets only metadata through.
### Datadog
Send the spans with an `Otlp` sink to an OpenTelemetry Collector. The Collector exports them to Datadog. The library needs no Datadog package.
```python theme={null}
from unmute_core.telemetry import Otlp, Telemetry
telemetry = Telemetry(
Otlp(endpoint="http://collector:4318/v1/traces"), agent="salon", call_id=state.call.session_id
)
```
A Collector config that receives OTLP over HTTP and exports to Datadog:
```yaml collector.yaml theme={null}
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
batch:
exporters:
datadog:
api:
key: ${env:DD_API_KEY}
site: datadoghq.com
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [datadog]
```
Set `site` to your Datadog site, like `datadoghq.eu`. Keep the API key in the Collector's environment, not in the agent. Add `filter=MetadataOnly()` to the `Otlp` sink to send no text.
### Coval
Coval needs to know which Coval run the call belongs to. Spans wait in memory, up to 1024, until `coval.activate(simulation_id=...)` or `coval.activate(conversation_id=...)`. Pass `method="dispatch_metadata"` or similar to record how the ID was found. It becomes `coval.correlation.method` on the call span. `activate` raises `ValueError` unless you pass exactly one of the two IDs. It raises `RuntimeError` when no `Telemetry` was built with the sink, or the call already has a Coval ID. It sends the held spans on the calling thread, so call it with `asyncio.to_thread` from async code.
An adapter finds the ID for you. Call `correlate_coval` once, with the sink the call's `Telemetry` was built with:
```python theme={null}
from unmute_core.livekit import correlate_coval # or unmute_core.pipecat
correlate_coval(ctx, coval, telemetry) # LiveKit: the JobContext
correlate_coval(runner_args, coval, telemetry) # Pipecat: the runner's arguments
```
On Pipecat, `runner_args` is Pipecat's `RunnerArguments`. It also tells `telemetry` how the caller arrived, with `describe_call(origin=...)`.
| | LiveKit | Pipecat |
| - | - | - |
| Where it looks, in order | The job's dispatch metadata (JSON, bad JSON is ignored), the simulation ID setting, then each remote participant's attributes | The WebSocket headers, the SIP headers of a dial-in body, the body, `call_data.body`, then the simulation ID setting |
| When it looks | Now, on `participant_connected` and on `participant_attributes_changed`, because a SIP participant joins late | Once, at the start |
| `origin` | `phone` when a SIP participant is in the room, `browser` for any other, nothing for an empty room | `phone` for a dial-in body or a carrier's WebSocket, `websocket` for a plain one, `browser` for WebRTC or a Daily room |
The ID is the `coval.simulation_id` key, or any key that ends in `x-coval-simulation-id`, in any case. `coval_simulation_id(mapping)` does the lookup. On LiveKit the first ID wins, and the sink activates once on a worker thread. On Pipecat it activates at once, on the calling thread.
A call that no simulation placed is filed when it ends. A real call or a local run then shows up in Coval's trace search.
1. `Telemetry.close()` flushes, then the provider shuts the Coval exporter down.
2. The exporter reads the transcript, the session ID, the agent name and the origin from the held call span. It merges consecutive lines of one speaker.
3. It posts them to `https://api.coval.dev/v1/conversations:submit` and waits at most 5 seconds.
4. With the conversation ID it sends every held span with the `X-Conversation-Id` header. The call span gets `coval.conversation_id` and `coval.correlation.method=conversation_submit`.
An adapter logs the two events with helpers you can reuse in your own adapter. `log_no_simulation(log, call="call")` says no simulation placed the call, so its trace is filed at the end. `log_activated(log, simulation_id, method, call=None)` says the sink is now bound to a simulation.
A failed submit logs a warning and never raises. The held spans are then dropped. A call is not filed, and the log says why, when:
* it already has a simulation or conversation ID,
* there is no Coval API key,
* the sink is `Coval(file_calls=False)`,
* the sink has a `filter`, because metadata only never sends the transcript,
* the call span has no transcript.
## Metadata only
```python theme={null}
Otlp(endpoint="http://collector:4318/v1/traces", filter=MetadataOnly())
```
The filter does the following:
1. It keeps an attribute only if the key is on the list and the value is a number, a bool or a short safe string.
2. It renames any span not on the list to `operation`.
3. It drops events, link attributes and the status description.
4. It keeps only allowed resource keys.
### MetadataOnly arguments
Span attribute keys to keep. Pass `DEFAULT_ATTRIBUTES | {"my.key"}` to allow more.
Span names to keep.
Resource attribute keys to keep.
`MetadataOnly` is a frozen Pydantic dataclass. A value of the wrong type raises a `ValidationError`.
`filter.apply(span)` filters one span. `filter.apply_all(spans)` filters a batch. The sink uses `apply_all` on each export. It builds the filtered resource once for each resource the spans share, so a batch of a call's spans costs less than one `apply` per span.
## Write a sink
`Sink` is the plug point for a new provider. Subclass it and return an exporter:
```python theme={null}
from dataclasses import dataclass
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import SpanExporter
from unmute_core.telemetry import Sink
@dataclass(kw_only=True)
class MyVendor(Sink):
api_key: str
def exporter(self) -> SpanExporter:
return OTLPSpanExporter(
endpoint="https://otlp.example.com/v1/traces", headers={"x-api-key": self.api_key}
)
```
The base class wraps the exporter in a batch processor, and in `filter` when one is set. Build sinks once per call, with the call's `Telemetry`.
`Sink` is a Pydantic dataclass. A stdlib `@dataclass(kw_only=True)` subclass, as above, works. So does a `pydantic.dataclasses.dataclass(kw_only=True)` subclass. With the Pydantic one, a field of the wrong type, like `api_key=3`, raises a `ValidationError` when you build the sink. The built-in sinks check their fields the same way.
## Span contract
Both adapters emit these spans through the helpers. Do not create them by hand.
```mermaid theme={null}
flowchart TD
C[conversation] --> T[turn]
C --> S[task_step]
T --> A[stt]
T --> L[llm]
T --> K[llm_tool_call]
T --> E[event: task.started, handoff, ...]
T --> B[tts]
```
1. `conversation` is the call. It starts a new trace. When it closes, its input is the transcript, one entry per line. Its output is how the call ended: `{"end_reason", "state", "confirmed"}`.
2. `turn` is one caller message and everything the agent does until the next one. Its output is every line the agent said, joined by a space. Only a turn where the agent speaks first has no caller input.
3. `stt` is one transcript. `tts` is one piece of speech.
4. `llm` is one model request: the prompt as filled, the tools offered, and the text and tool calls the model chose. `llm_tool_call` is one tool run.
5. An event span is one decision, like a task starting, a step skipped or a handoff. It has no length. Langfuse does not show OpenTelemetry span events, so each one is a span.
6. `task_step` sits under the call, not around turns. One turn can finish a task and start the next.
Every span also gets `session.id`, `gen_ai.conversation.id` (both the call ID) and `agent.name`. The resource has `service.name` set to the agent name.
| Span | Helper | Start attributes | End attributes |
| - | - | - | - |
| `conversation` | `start_call`, `describe_call`, `close` | `gen_ai.operation.name=invoke_workflow`, `langfuse.trace.name`, `unmute.call.origin` and `unmute.call.framework` (when `describe_call` set them) | `input.value` (transcript as JSON, one entry per line), `output.value` (end reason, final values and the confirmed ones, JSON), `unmute.call.end_reason`. Both adapters write the shared end reasons: `caller_hung_up`, `agent_ended`, `transferred`, `max_duration`, `idle`, `error` or `ended`. See [Why the call ended](/core/build/call-lifecycle#why-the-call-ended) |
| `turn` | `start_turn`, `end_turn` | `turn.number`, `gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name` | `input.value` (caller), `output.value` (every agent line, joined), `turn.interrupted`, `turn.e2e_seconds` (the caller's end of speech to the agent's first audio, whether the model or code wrote the line), `turn.stt_final_seconds`, `turn.eou_seconds` (LiveKit only), `turn.llm_ttft_seconds`, `turn.tts_ttfb_seconds`, `turn.llm_requests` (the turn's model requests, 0 when code spoke the reply), `turn.llm_requests_cut` (the ones cut off, like a LiveKit preemptive request the caller spoke over) |
| `stt` | `stt` | `langfuse.observation.type=generation`, `gen_ai.operation.name=stt`, `gen_ai.provider.name`, `gen_ai.request.model`, `stt.language` | `output.value` (transcript), `metrics.ttfb` |
| `llm` | `start_model_request`, `end_model_request` | `gen_ai.operation.name=chat`, `gen_ai.provider.name`, `gen_ai.request.model`, `unmute.prompt.site`, `input.value` (messages as JSON, prompt filled), `gen_ai.tool.definitions` (tools offered, JSON) | `output.value` (text, or the assistant message with `tool_calls` as JSON), `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`, `metrics.ttfb`, `langfuse.observation.completion_start_time`, `gen_ai.response.model` (the model call that answered, read at the end of the request, so a `FallbackModelCall` shows the call it moved to), `error.type` (when the request failed, also on Pipecat). A reply cut off before it finished adds `llm.interrupted`, `langfuse.observation.level=WARNING` and `langfuse.observation.status_message` |
| `tts` | `start_tts`, `end_tts` | `langfuse.observation.type=generation`, `gen_ai.operation.name=tts`, `gen_ai.provider.name`, `gen_ai.request.model`, `tts.voice` | `input.value` (text), `metrics.character_count`, `langfuse.observation.usage_details` (`{"characters": n}`), `metrics.ttfb`, `langfuse.observation.completion_start_time`, `tts.interrupted` |
| event | `event` | `langfuse.observation.type=event`, `unmute.event.name`, `input.value` (its data, JSON) | none |
| `llm_tool_call` | `start_tool_call`, `end_tool_call` | `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.call.arguments`, `function.name`, `tool_call_id`, `function.arguments` | `gen_ai.tool.call.result`, `tool.error` (0 or 1) |
| `task_step` | `start_task_step`, `end_task_step` | `unmute.task.name`, `unmute.task.step`, `input.value` | `unmute.task.outcome`, `output.value` (outcome and saved values, JSON) |
| Span | LiveKit | Pipecat |
| - | - | - |
| `conversation` | The agent's first `on_enter`. It ends when the session closes, which also flushes every sink. | `Telemetry.start_call()` and `close()` |
| `stt` | The caller's message, with its speech timings and STT model | Each `TranscriptionFrame` from the STT service |
| `llm` | `llm_node`, after the prompt is filled | `LLMContextFrame`, the service's system instruction, `FunctionCallsStartedFrame`. `gen_ai.request.model` is the model the request went to, read from the service's model call, not `TelemetryObserver(model=)` |
| `tts` | `tts_node` of the agent and of each step | `TTSStartedFrame` to `TTSStoppedFrame`, per context |
| `turn` | Starts at a caller message the trace has not seen. A model request carries it before LiveKit adds it to the chat. | Starts at `UserStartedSpeakingFrame`, a `TranscriptionFrame`, or an `LLMMessagesAppendFrame` with a user message (RTVI typed text) |
| event | `CallTasks.listen(telemetry.event)` and `hand_off` | the same, through `UnmuteFlows`. `flows.listen(sink)` adds another sink |
| `llm_tool_call` | `tool_execution_updated`: started and ended | `FunctionCallInProgressFrame` to `FunctionCallResultFrame` |
| `task_step` | The step loop, under the call | The step loop, under the call |
On LiveKit, STT is read from the caller's message, not from `stt_node`. Overriding `stt_node` would stop LiveKit reusing the STT stream each time a step starts. A subclass that overrides `tts_node` loses the `tts` spans unless it calls `super().tts_node(...)`. LiveKit's own spans stay off, and the adapter does not call `set_tracer_provider`.
### What a tool span shows
A tool that takes no parameters shows `{}` as its input. A tool span's output is what the tool gave back, in three cases that need care:
1. A task call's span lasts the whole task. Its output is the task result the main agent reads, not Pipecat's first "running" result.
2. A step's closing tool shows what it really returned, like the customer record. The model reads only how the step ended, and the `task_step` span shows that.
3. A handoff shows `{"status": "handed off"}` on both frameworks. A step that hands off ends its `task_step` span with the outcome `handed_off`.
### Model requests that make no reply
Three kinds of model request make no reply. All are still `llm` spans in the turn they belong to.
1. A step's finish check. Its tools are only `finish` and `not_yet`, and a call is required. A `not_yet` is an answer, never run, so it has no tool span. A `finish` it chose runs as a tool, under the call id the check gave it.
2. The decision on a held save, made when the call ends. It sits in the last turn. LiveKit settles before it ends the turn, and a Pipecat host calls `flows.settle()` before the `EndFrame`. Its calls are answers too, never run.
3. A summary, for a handoff or a step with `history: summary`. Its site is `summary`, it offers no tools, and its output is the summary text.
See [Tasks](/core/build/tasks) and [Handoffs](/core/build/handoffs) for when each runs.
### When a turn starts and ends
A turn belongs to the caller until the agent says a line, starts speech or calls a tool. A model request alone does not count. A request cut off because the caller went on speaking leaves the rest of their words in the same turn. More caller input before that joins the open turn, like a caller who pauses mid-sentence. Caller input after that starts the next turn.
### Following the turns in your own adapter
```python theme={null}
from unmute_core.telemetry import TurnEnd, TurnTracker
turns = TurnTracker(telemetry)
turns.start() # the caller's words open a turn
turns.open() # the agent does something: the turn is now answered
turns.caller_open # True while a turn is open and the agent has not answered
end: TurnEnd = {"user_text": "Book me in", "agent_lines": ["Which day?"], "e2e": 1.1}
turns.end(**end)
```
Both adapters use `TurnTracker`. It numbers the turns and keeps the open `turn` span. You decide when a turn starts and what its text and latencies are.
`start()`.
Opens the next turn under the call and returns its span. End the earlier turn first.
`open(answering=True)`.
Returns the open turn, or opens one when none is. It marks the turn answered unless you pass `answering=False`.
True while a turn is open and nothing the agent did has answered in it.
`end(**fields)`.
Ends the open turn through `Telemetry.end_turn`. It does nothing when no turn is open.
Names the fields of `end`: `user_text`, `agent_lines`, `interrupted`, `e2e`, `stt_final`, `eou`, `llm_ttft`, `tts_ttfb` and `error`. They are the same as the arguments of `end_turn`.
### Events
The events are the task stages (`task.started`, `task.completed`, `task.refused_busy`, `group.step_skipped`, `task.handed_off` and the rest of `TaskStage`), `handoff` with `{"from", "to"}`, and the idle nudges (`idle_nudges.armed`, `idle_nudges.first.fired` and the rest). A nudge the model worded carries `{"generated": true}` in place of its text. The names are each agent's `AgentSpec.name`, else the call's `agent_id`, on both frameworks.
Coval shows `conversation`, `turn`, `llm` and `llm_tool_call` with their own colours and runs its built-in metrics on them. Langfuse and Logfire type spans from `gen_ai.operation.name`, not from the span name.
## Vendor names
The span contract above is neutral. A vendor's own names are added inside that vendor's sink, on a copy of each span just before export. No sink changes what another sink gets.
### Coval
Text keys move to the Coval name, so a large prompt is not sent twice. Other keys stay. A `metrics.ttfb` of zero or less is dropped, because Coval would average it as an instant answer.
| Span | Coval name | From |
| - | - | - |
| `conversation` | `coval.call.origin` | `unmute.call.origin` |
| | `agent.provider` | `unmute.call.framework` |
| | `coval.agent_type=sip_inbound_voice` | only when the framework is `livekit` |
| | `coval.simulation_id` or `coval.conversation_id`, and `coval.correlation.method` | the sink's binding |
| `turn` | `turn.index` | `turn.number` |
| | `turn.user_transcript`, `turn.agent_transcript` | `input.value`, `output.value` |
| | `turn.interrupted` (1 or 0) | `turn.interrupted` |
| | `metrics.e2e_latency` | `turn.e2e_seconds` |
| | `vad.end_of_turn_delay` | `turn.eou_seconds` |
| `stt` | `transcript` | `output.value` |
| | `stt.providerName` | `gen_ai.provider.name` |
| | `stt.transcription_delay` | `metrics.ttfb` |
| `llm` | `input`, `prompt.message_count`, `prompt.messages_traced` | `input.value` |
| | `gen_ai.system_instructions` | the system messages in `input.value`, joined |
| | `tools` (names), `tool_count` | `gen_ai.tool.definitions` |
| | `output`, `response.length` | `output.value`, only when it is plain text |
| | `llm.finish_reason` | `gen_ai.response.finish_reasons`, else `tool_calls` or `stop` |
| | `llm.cancelled` (1 or 0) | `llm.interrupted` |
| `llm_tool_call` | `tool.result`, `tool.result.length` | `gen_ai.tool.call.result` |
| | `tool.latency_ms` | the span's start and end |
| `tts` | `transcript` | `input.value` |
| | `tts.characters_count` | `metrics.character_count` |
Coval rejects an oversized batch with a 413, so text is cut. Most text keeps 1,024 characters. A prompt keeps 8,192. The system messages stay and the newest other messages fill the rest. `prompt.message_count` is how many there were, and `prompt.messages_traced` is how many were kept.
There is no `vad` span and no `transport` span. The turn carries `vad.end_of_turn_delay`, and the call span carries the origin and the correlation method, so they hold what those spans would say. The call span is still held until the ID is known.
### Logfire
`Logfire` adds `logfire.msg`, the row label: `turn: `, `chat `, `tool `, `stt `, `tts ` and `call `. On a model request it also writes the messages under the GenAI names Logfire's LLM panel reads: `gen_ai.system_instructions`, `gen_ai.input.messages` (tool calls and tool replies as parts) and `gen_ai.output.messages`. `input.value` and `output.value` stay. With `filter=MetadataOnly()` the filter runs first, so only the labels go out.
## Where to go next
Send a call's spans to Langfuse, Logfire, Coval or Datadog.
What one call did, for the local dev page.
# Phone calls reference
Source: https://unmute.ai/core/reference/telephony
Every argument of Transfer, the phone lines, dialling and voicemail, and how a transfer runs on each route.
This page is the full detail behind [Phone calls](/core/telephony). Start there to take a call, place one or transfer a caller.
## How a transfer works
```mermaid theme={null}
flowchart LR
T[Transfer] --> X[transfer_tool]
L[phone line, one per call] --> X
X --> R[a ToolSpec in the agent's tools]
R --> M[the model calls it]
M --> S[the line is said]
S --> P[the line transfers the caller]
P --> E[the call ends, or the agent keeps helping]
```
1. A `Transfer` says where the caller goes and what happens when nobody answers.
2. A phone line is the call's own leg. Build it per call, like `CallHooks`.
3. `transfer_tool` returns an ordinary tool. Hooks, spans, task tool lists and the end of the call treat it like any other tool. See [Tools](/core/build/tools).
4. The model calls it with no arguments. It never sees the destination.
5. The tool says its line first, like "Putting you through now, one moment." Once the transfer starts, the caller's speech cannot cancel it, on either framework. On LiveKit the line itself cannot be cut off either, and neither can the lines a `SipLine` says. On Pipecat the caller can still cut the line off. Build the user aggregator with `user_mute_strategies(protect=["tool_calls"])` to protect it.
6. The line transfers the caller. On success the call ends, with no model reply after it, and its end reason is `transferred`.
7. When nobody takes the transfer, `on_unavailable` decides:
* `return_to_caller` is the default. The model reads why, like "The transfer failed (busy). Tell the caller and keep helping them."
* `hangup` makes the line say `unavailable_line`, then the call ends. Write that line in the call's language.
8. A call with no phone leg, like a web call, tells the model so, and the agent keeps helping.
9. One transfer runs at a time per call. A second call of a transfer tool, the same one or another, tells the model one is already under way. After a transfer nobody took, the model may try again.
## Transfer
A frozen Pydantic dataclass.
The tool's name, like `send_to_billing`.
An E.164 number, or a `tel:`, `sip:` or `sips:` URI.
When the model should call it.
`cold` hands the caller's leg over. `warm` calls the person first and briefs them.
Extra words for the person a warm transfer calls, after the chat. Only a warm transfer may set it.
How long the destination may ring. `None` uses the carrier's default. It must be positive.
What happens when nobody takes it.
Said before the transfer starts. `None` uses the mode's line.
Said once a warm transfer has merged the calls.
Said before hanging up, with `on_unavailable="hangup"`.
A bad destination raises `ValueError`. A briefing on a cold transfer, or a warm transfer with a destination that names no one, raises `ValueError` that names the transfer. An unknown `mode` or `on_unavailable`, or a `ring_timeout_s` that is not positive, raises a `ValidationError` that names the field. An unknown argument raises `TypeError`.
### transfer\_tool
Returns a tool that transfers the caller on this call's line. Build it per call.
Where to go, and what happens when nobody takes it.
This call's phone line.
A warm transfer on a line that cannot make one raises `ValueError`. The message says to run it on LiveKit SIP or make it cold.
`PhoneLine` is a protocol. The adapters ship `SipLine`, `TwilioLine`, `TelnyxLine` and `DailySipLine`. A line of your own must be hashable and weak-referenceable, as a plain class is. The library uses this to tell which lines have a transfer under way without keeping them alive. `transfer_tool` raises `TypeError` for a line that is not, like a class with `__slots__` and no `__weakref__`.
## Phone numbers
```python theme={null}
from pydantic import BaseModel
from unmute_core.telephony import E164_PATTERN, E164Number, is_e164
is_e164("+34910000000") # True
is_e164("0034910000000") # False
class Callback(BaseModel):
number: E164Number
```
An E.164 number is a plus, then 2 to 15 digits. The first digit is not 0.
### Phone number checks
`is_e164(value)`.
Returns `True` or `False`. Any value that is not a string gives `False`.
A type for a field of your own Pydantic model. A bad number raises a `ValidationError` that says to use a number like `+34910000000`.
The pattern as text, `\+[1-9][0-9]{1,14}`. Use it where a regex string fits, like a JSON Schema `pattern`.
The same pattern, compiled.
`SipLine.dial` checks its number with `E164Number`.
## LiveKit SIP
### An inbound call
Your SIP trunk and dispatch rule put the caller in a room. Read what the call carries once the caller joins:
```python theme={null}
participant = await ctx.wait_for_participant()
info = sip_call_info(participant, metadata, trunk_number=os.environ["SIP_NUMBER"])
state = CallState(State, call=info)
```
`sip_call_info` gives a `CallInfo`. Pass it to `CallState(call=...)`. Then `state.call.calling_number` is the caller. The room name is not stored. `trunk_number` is the agent's own number, when the participant does not report it. `agent_id` and `session_id` are also keywords. See [State](/core/build/state#values-the-call-carries-state-call).
The direction is `direction=` when you pass it. Else it is the metadata's `direction`. Else a SIP participant with the `sip.ruleID` attribute came in through a dispatch rule, so it is inbound. Else a job that names `phone_number` dials out. Any other call is inbound. A participant without `sip.ruleID` does not mean outbound by itself. A contradiction between these is not refused. Pass `direction="inbound"` or `direction="outbound"` when your dispatch knows it.
### SipLine
The SIP leg of one LiveKit call. Build one per call, once the session has started.
The call's session.
A stored outbound trunk id, or the trunk's settings sent with each dial. `None` leaves a warm transfer to `LIVEKIT_SIP_OUTBOUND_TRUNK`.
The number the person called sees, like `+34910000000`.
```python theme={null}
trunk = api.SIPOutboundConfig(
hostname=os.environ["SIP_ADDRESS"],
auth_username=os.environ["SIP_USERNAME"],
auth_password=os.environ["SIP_PASSWORD"],
)
```
### An outbound call
Dispatch the job with `phone_number` in its metadata. Start the session, then dial:
```python theme={null}
line = SipLine(session, trunk=trunk, caller_id=os.environ["FROM_NUMBER"])
try:
dialled = await line.dial(metadata["phone_number"], on_voicemail="leave_message")
except DialError as error:
logger.info("nobody answered: %s", error.reason) # busy, no answer, sip 503
ctx.shutdown("dial failed")
return
if not dialled.ended:
greet(session, greeting, state)
```
1. `dial` checks the number is E.164, then calls it and waits for an answer.
2. LiveKit's answering machine detection holds the agent's speech until it knows who answered. It asks a model: `detector_llm`, else the session's LLM, else the agent's.
3. Voicemail hangs up, or leaves a message the model words. A full or missing mailbox hangs up. `ended` is then `True`. Pass `SipLine(session, call=call)` to note that end as `agent_ended` in the call's hooks.
4. A number nobody answers raises `DialError` with the `reason` and the `sip_status`.
#### SipLine.dial
The number to call, in E.164. Anything else raises `ValueError`.
The participant identity the callee gets.
How long it may ring. `None` is LiveKit's 30 seconds.
What to do on voicemail. The model words a left message.
Run LiveKit's answering machine detection.
The model that judges who answered.
The callee's display name in the room. Empty keeps LiveKit's.
The caller name the callee's phone shows. `None` keeps the trunk's.
Metadata for the callee's participant.
Attributes for the callee's participant.
Turn on Krisp noise cancellation for the callee.
Without detection, wait at most this long for the callee's audio track, then `AUDIO_SETTLE_S` (0.3 seconds) more, so the first word is not clipped. A timeout is logged and the dial goes on. `None` does not wait. With detection on it does nothing, because detection already listens.
It returns a `Dialled` result. Greet the callee unless its `ended` is `True`.
### Cold transfer
The line sends a SIP REFER for the SIP caller in the room. A bare number becomes `tel:+34...`. A carrier that wants its host in the `Refer-To`, like Plivo, takes `sip:+34...@your-trunk` as written. The carrier must allow transfers on the trunk. On Twilio, that is "Call Transfer (SIP REFER)" with PSTN transfer turned on.
LiveKit can answer a REFER with a failed status instead of an error. The line checks the status, so that counts as a failed transfer too. An ongoing status counts as done. The caller is the session's own participant when it is a SIP one, else the first SIP participant in the room.
### Warm transfer
```python theme={null}
ESCALATE = Transfer(
"escalate",
"+34910000000",
mode="warm",
briefing="Mention that the caller is a VIP.",
)
```
1. The caller hears hold music.
2. The agent calls the person and briefs them from the chat. The briefing persona is `BRIEFING_PERSONA`, and `briefing` is added after it.
3. The person says they are ready, and the calls merge. The agent says `connected_line` and leaves.
4. When the person declines, does not answer, or is a voicemail, the caller comes back to the agent.
Warm transfer uses LiveKit's `WarmTransferTask` from `livekit.agents.beta`. It merges the calls with `move_participant`, which only LiveKit Cloud and LiveKit Private Cloud have. A self-hosted LiveKit server cannot finish a warm transfer. Keep `RoomOptions(delete_room_on_close=False)`, the default, so the room outlives the agent.
## Pipecat on a carrier websocket
Pipecat's runner reads the carrier's first messages and builds the transport with the carrier's serializer. Read what the call carries from what it parsed:
```python theme={null}
info = telephony_call_info(runner_args.call_data, trunk_number=os.environ["FROM_NUMBER"])
state = CallState(State, call=info)
```
It reads Twilio's TwiML parameters, and the `from` and `to` that Telnyx and Exotel send.
A carrier line carries 8 kHz audio. Set the pipeline's audio in and out sample rates to 8000 (`PipelineParams(audio_in_sample_rate=8000, audio_out_sample_rate=8000)`). The library does not build the pipeline, so it cannot set them for you.
Build the line once the worker exists:
```python theme={null}
line = TwilioLine(
info.carrier_call_id,
account_sid=os.environ["TWILIO_ACCOUNT_SID"],
auth_token=os.environ["TWILIO_AUTH_TOKEN"],
worker=worker,
serializer=serializer,
)
```
### TwilioLine
The Twilio call, from `state.call.carrier_call_id`.
The Twilio account.
Its auth token.
The call's pipeline worker.
The call's serializer. Pass `None` only for a serializer built with `auto_hang_up=False`.
Twilio's REST API URL.
The transfer replaces the call's TwiML with ``, then ``. The stream closes and Twilio rings the person. The agent does not learn whether they answered.
### TelnyxLine
`TelnyxLine(call_control_id, api_key=..., worker=..., serializer=...)` takes the same `worker`, `serializer` and `api_url` as `TwilioLine`. Its `api_url` defaults to Telnyx's REST API. It sends Telnyx's transfer command with a ring timeout of at least 5 seconds, Telnyx's floor. Telnyx keeps the caller's leg when the person does not answer, and reports that later by webhook. So the tool counts an accepted request as done.
### The serializer
The Twilio, Telnyx and Plivo serializers hang up the call when the pipeline ends. After a transfer that would drop the caller you just handed over. So the line turns the hang-up off before it sends the transfer, and back on if the carrier refuses it.
### An outbound call
Your app asks the carrier to place a call that streams to the bot. For Twilio, send the stream's parameters in the TwiML, since Twilio does not fill `{{To}}` in inline TwiML:
```xml theme={null}
```
## Pipecat in a Daily room over SIP
```python theme={null}
line = DailySipLine(transport, worker, sip_host=os.environ["SIP_ADDRESS"])
forward_dial_in(transport, body["call_sid"], account_sid=sid, auth_token=token) # inbound
dial_out(transport, worker, "sip:+34910000000@trunk.example", call=call) # outbound
```
`transport` is Pipecat's `DailyTransport`. `DailySipLine`, `forward_dial_in` and `dial_out` ask a type checker for that type.
1. `forward_dial_in` sends a Twilio call into the room once Daily gives the room's SIP address. It runs once.
2. `dial_out` calls a SIP address once the bot joins. When that leg ends, the pipeline is cancelled. Other legs of the room end nothing. Pass `call=` and the callee hanging up ends the call with `caller_hung_up`. A leg that failed is no hang-up.
3. `DailySipLine` asks Daily to call the person through your trunk, then waits until they answer, up to the ring timeout. A transfer nobody answers leaves the caller with the agent. Once the person answers, the agent leaves and Daily keeps bridging the two legs, so both are billed until the call ends. An event about the caller's own leg settles no transfer.
The call's Daily transport.
The call's pipeline worker.
Your trunk's termination host. A number is dialled as `sip:@`.
## voicemail\_tool
`voicemail_tool` gives a Pipecat model the `detected_answering_machine` tool. On a pipeline without `UnmuteFlows`, give the tool to the context's tools.
What to do at a voicemail.
What the model is told to say with `leave_message`.
The call's idle nudges, held while the tool speaks.
The call's hooks, which note the end as the agent's own.
## Where to go next
Take a call, place one, and transfer a caller.
How a transfer tool fits the registry and its hooks.
# Tools reference
Source: https://unmute.ai/core/reference/tools
Every tool option, rule and edge case: inputs and outputs, announce lines, saved results, locked arguments, webhooks, built-ins and your own kind of tool.
This page is the full detail behind [Tools](/core/build/tools). Start there to add a tool to your agent. Come here for every option, rule and edge case.
## Use it in your agent
The code for each kind of agent is in [Use it in your agent](/core/build/tools#use-it-in-your-agent).
1. Build the tools once per call. They read that call's state, and what the call carries from `state.call`.
2. Every option on this page works in all four kinds of agent: `UnmuteAgent`, a plain LiveKit `Agent`, `UnmuteFlows` and a plain Pipecat pipeline. The sections below say where one kind of agent needs one more line.
3. `call` is the call's `CallHooks`. It runs your [tool hooks](/core/build/hooks) and lets background webhooks finish when the call ends. `state` and `call` are needed only when a tool reads them. On a plain agent, without `state`, the tools take the state of `call`.
4. A [reply line](#save-a-result-and-speak-it) says dates and times in the call's language. `function_tools` and `tools_schema` take `language=` and `timezone=` for it. On `UnmuteAgent` and `UnmuteFlows`, the spec's `AgentSpec(language=, timezone=)` sets them.
## What it handles for you
You write a typed Python function. The library turns it into a tool that
LiveKit and Pipecat call the same way. It checks every argument before your code
runs and every result after it, says a line while a slow tool works, and tells
the model plainly when a tool failed. It can save a result to State and speak a
line from it, in the call's language. You keep your framework, and you add only
the tools.
| On a call without it | What the library does |
| - | - |
| The model sends a bad date or a number out of range, and your code breaks. | Arguments are checked with Pydantic and arrive as real Python types. A bad one goes back to the model with what to fix. [Inputs and outputs](#inputs-and-outputs) |
| A slow tool leaves the caller in silence. | `announce=` says a line as the tool starts. [What a tool does around its call](#what-a-tool-does-around-its-call) |
| The caller speaks, the tool is cancelled, and its result lands in a later reply. | A running tool keeps running on both frameworks. [A tool the caller talks over](#a-tool-the-caller-talks-over) |
| The model claims a failed tool worked. | Every failure reaches the model as words it can act on, ending with "Do not claim success". [A call that is refused](#a-call-that-is-refused) |
| A tool returns the wrong shape, and the model reads half a result as a success. | Every tool names its output model. A result that does not fit fails the call, and the model reads which field is wrong. [Outputs](#outputs) |
| The model reads out "2026-10-16", or words the booking slightly differently each time. | A reply line is spoken by code, with the date said as "tomorrow, October 16". [Save a result and speak it](#save-a-result-and-speak-it) |
| The model sends or forges a `customer_id`. | Locked arguments are hidden from the model and filled from the call. [Locked arguments](#locked-arguments) |
| A webhook reaches `localhost` or a cloud metadata address. | Each address must be public, and the connection is pinned to it. [Private addresses](#private-addresses) |
| A slow or huge response stalls the call. | One deadline covers the whole request. Bodies are capped at 64 KiB. [Time and size limits](#time-and-size-limits) |
## Inputs and outputs
Tool inputs and outputs are Pydantic. Write a function with type hints, and
`local_tool` does the rest.
```python theme={null}
from datetime import date
from typing import Annotated, Literal
from pydantic import BaseModel, Field
from unmute_core.state import Phone
from unmute_core.tools import local_tool
class Booking(BaseModel):
reference: str
day: date
def book_table(
day: Annotated[date, Field(description="The day the caller wants.")],
party: Annotated[int, Field(ge=1, le=12)] = 2,
seating: Literal["inside", "terrace"] = "inside",
phone: Phone | None = None,
) -> Booking:
"""Book a table."""
return Booking(reference="B-12", day=day)
tool = local_tool(book_table)
```
1. `local_tool` builds a Pydantic model from the type hints. Its JSON Schema is what the model reads.
2. `Field(description=...)` tells the model what an argument is. Limits like `ge` and `le` go into the schema too.
3. Each call is checked before your function runs. Your function gets real Python types: a `date`, an `int`, a clean `Phone`.
4. A bad argument goes back to the model with what to fix, like "party: 40 is greater than the maximum of 12". The model asks the caller or calls again.
5. Every parameter needs a type. A parameter with none raises `TypeError` that names it. `*args` and `**kwargs` are refused too.
6. The tool name is the function name, and the description is the docstring up to its `Args:` section. `name=` and `description=` change them.
### Outputs
Every tool names the Pydantic model of its result. A tool without one is refused
when it is built.
```python theme={null}
def find_order(order_id: str) -> Order: # the return annotation is the output
...
def find_raw(order_id: str) -> dict: # a function that returns a dict names it
...
local_tool(find_raw, output=Order)
```
1. `local_tool` reads the output from the return annotation. A function that returns a dict passes `output=`. With neither, `local_tool` raises `TypeError`: "name its output".
2. A result that succeeded is checked against the output when the tool returns. The model then reads the checked result, `output.model_dump(mode="json")`. Defaults are filled, and a field the model does not declare is dropped, unless the model sets `extra="allow"`.
3. A result that does not fit fails the call. The model reads "find\_order returned a result that does not fit Order: status: ... Do not claim success." The log names the tool and the field, never a value.
4. A result that reports an error is never checked: an `error` or a `refused` with text in it, or `"ok": false`. For a failure in your own function, raise `ToolError`.
5. `Done` is the output of a tool that only runs: `{"ok": true}`. A webhook that answers with an empty body returns it. `Accepted` is the output of a webhook that does not wait for its answer. Both come from `unmute_core.tools`.
6. The `wrap_tool` and `after_tool` hooks see the checked result. What a hook puts in its place is not checked again.
7. The rule covers every library tool. A framework tool passed as `native_tools=` is the framework's own object, and the library does not check it.
### One input model
When the inputs are a model you already have, make it the function's only
parameter. The function gets one value of the model.
```python theme={null}
class OrderQuery(BaseModel):
order_id: Annotated[str, Field(description="The order id the caller reads out.")]
async def lookup_order(query: OrderQuery) -> Order:
return await orders.get(query.order_id)
tool = local_tool(lookup_order)
```
### Inputs and outputs of a webhook
`webhook_tool` takes both models.
```python theme={null}
webhook_tool("lookup_order", "Look up an order by its id.", URL, input=OrderQuery, output=Order)
```
**Why it works this way.** One Pydantic model tells the model what to send,
checks what it sent, and converts it for your code. A second one checks what the
tool sent back. The schema the model reads cannot drift from the code that runs,
and a result of the wrong shape never reaches the model as a success.
**Best practice.**
1. Use precise types: `date`, `Literal`, `Phone`, and `Field` limits. Each one is a check you do not write.
2. Give every argument a `description`. It is the only place the model learns what the argument means.
3. Type the result's dates and choices too: `date`, `time`, `Literal`. A reply line then says them as a person does.
4. Raise `ToolError` for a failure the model should read. Do not return an error dict from a function typed to return a model.
## What a tool does around its call
Every tool builder takes the same options: `local_tool` and `webhook_tool`.
| Option | Values | What happens |
| - | - | - |
| `announce` | one line, or a list of lines | The agent says one of them as the tool starts. A slow tool is then not silence. A refused call says nothing. |
| `announce_wait` | `False` (default), `True` | `True` runs the tool only after the line has played. |
| `show_result` | `True` (default), `False` | `False` gives the model `{"ok": true}` for a result that succeeded. |
| `result_instructions` | text | Tells the model how to use the result. |
| `effect` | `returns_data` (default), `ends_conversation` | `ends_conversation` ends the call once the tool succeeds. |
| `interruption` | `provider_default` (default), `cancel`, `continue` | What the caller's speech does to a running call. |
1. With several announce lines, the agent never says the same one twice in a row.
2. A failed tool never ends the call. The model reads the error and goes on.
3. `interruption` matters on Pipecat, where `cancel` is the default. `continue` lets the tool finish. The library keeps Pipecat's own guidance about background tools out of the prompt, so the model reads the same prompt as on LiveKit. That holds only while the library's tools are the only background tools. Register your own tool with `cancel_on_interruption=False` and Pipecat's guidance comes back for all of them. LiveKit never cancels a running tool. When the reply that called it is cut off, the model reads that the tool is still running, and its result comes in a later reply.
4. A value that is not one of the listed words raises a Pydantic `ValidationError`. It names the field and the allowed words. An unknown argument raises `TypeError`.
### A tool the caller talks over
**Why it works this way.** A cancelled tool may have half done its work, and
its result comes late or never. The model then cannot tell the caller what
happened. LiveKit never cancels a running tool, and Pipecat cancels one by
default. `continue` gives Pipecat the LiveKit behaviour, with the same prompt on
both.
**Best practice.**
1. Use `interruption="continue"` for a tool that changes something: a booking, a payment, a transfer.
2. Leave `provider_default` for a lookup the model can simply ask again.
**On each kind of agent.**
* `UnmuteFlows` keeps Pipecat's background-tool text out of the prompt by itself.
* A plain Pipecat pipeline needs `attach_call(..., llm=llm)` for that. Without it, Pipecat adds its own text about background tools to the prompt.
* On LiveKit, both kinds of agent need nothing more.
### Announce lines with values
```python theme={null}
local_tool(
check_day,
announce="Let me check {{day}} for {{brand}}. Call {{call.session_id}}.",
announce_wait=True,
)
```
1. `{{value}}` reads a State value or an argument of this call. `{{call.name}}` reads what the call carries, like `{{call.session_id}}`.
2. The line is filled as it is said.
3. If a line reads a value that is not set, the call is refused. Nothing is said and the tool does not run.
4. With `announce_wait=True`, LiveKit waits for the speech to end, and the caller cannot cut the line off. Pipecat waits for the bot to stop speaking, at most 30 seconds. On Pipecat, `user_mute_strategies(protect=["tool_calls"])` keeps the caller from cutting the line.
5. A realtime model that speaks itself skips the line and words its own. See [Realtime models](/core/models/realtime).
**Why it works this way.** On a phone call, silence sounds like a dropped line.
The line is said only once the call is checked, so a refused call makes no
promise. The tool's answer is spoken after the line, so a long line delays the
answer. Several lines rotate, so the agent does not sound like a recording.
**Best practice.**
1. Announce only a tool the caller would notice waiting for. A fast lookup needs no line.
2. Keep each line short, and give two or three for a tool the agent calls often.
3. Use `announce_wait=True` only when the line must come before the action, like "Putting you through now."
### A result the model does not read
```python theme={null}
local_tool(
save_order,
show_result=False,
result_instructions="Tell the caller the order is saved. Do not read out the number.",
)
```
1. With `show_result=False`, the model reads `{"ok": true}` for a result that succeeded.
2. A failure or a refusal is always shown. The model never claims a success. A result is a failure when it has an `error` with text in it, a `refused` with text in it, or `"ok": false`. `{"error": null}` and an empty `error` are a success.
3. Task code still reads the full result. Finish rules and `ToolReply` lines work as before.
4. `result_instructions` is added to the description as `"\n\nUse the result like this: "`.
5. `ToolRegistry.for_model(name, result)` gives what the model reads. The adapters call it.
6. `hidden=("read_back",)` leaves only those fields out of a result that succeeded. Use it for a line code speaks from the result, like a read-back: a model that can see the words may say them itself. `assign` rows and spoken lines still read the field. A field the output model does not have fails when the tool is built.
### End the call
A tool with `effect="ends_conversation"` ends the call once it succeeds, on both
frameworks. The model is not asked for another reply, even when another tool is
called in the same reply, and on a realtime model too. So the goodbye goes in the
reply that calls the tool.
```python theme={null}
hang_up = local_tool(hang_up_handler, effect="ends_conversation")
```
On Pipecat, `end_call_tool` ends the call with no second model request:
```python theme={null}
from unmute_core.pipecat import end_call_tool, reply_text
tool = end_call_tool("Call it when the caller is done.", "Goodbye!", reply_text(llm))
```
Give the tool to `UnmuteFlows(native_tools=[tool])`. The goodbye line is spoken
only when the reply that called the tool had no words. Write it in the call's
language. Pass `None` to say `GOODBYE_LINE` from `unmute_core.call`, in English.
On Pipecat, `voicemail_tool` gives the model a tool that ends an outbound call at a
voicemail. See [Phone calls](/core/telephony#voicemail).
## A call that is refused
```python theme={null}
{"refused": "day not set yet. Get it from the caller, then call this tool again."}
```
A call that reads a value not set yet gets this result. The value may sit in a
locked argument, a webhook URL or an announce line.
1. The tool does not run, and nothing is said. The model reads the message and acts on its hint.
2. If a step must still confirm the value, the hint is "Run first: it confirms with the caller".
3. Else, if a task saves the value, the hint is "Run first: it saves ". The first task that saves it wins.
4. Else the hint is "Get it from the caller", with the value's description from the State model in brackets when it has one.
5. Every announce line of the tool is filled before one is picked. So every line's values must be set, even when another line needs none.
6. A refused call counts as a failure. `ends_conversation` never fires on it.
7. In code, `ToolRefused` is a `ToolError`. LiveKit and Pipecat send the same JSON.
**Why it works this way.** A model that reads a bare error, or nothing, often
tells the caller the action worked. So every failure reaches the model as words
it can act on, and ends with "Do not claim success". A refusal is a result, not
a raised error. Each framework words a raised error its own way, and a result
reads the same on both.
**Best practice.**
1. In your own tool, raise `ToolError` with the words the model should read, like "No table is free that day. Offer another day."
2. Let any other error raise. The model reads that the tool failed, and the log keeps the details.
3. Use `show_result=False` for a result the caller must not hear. See [A result the model does not read](#a-result-the-model-does-not-read).
## The schema the model reads
The model reads a plainer copy of each tool's parameters. The tool still checks what the model sent against the full schema.
1. An optional value whose default is `null` loses its `null` branch and that default. Leaving it out means the same thing. A value without that default keeps `null`, because there `null` means something, like "clear this value".
2. `format` and `pattern` become words in the description. Some providers refuse them, and a format only this library knows, like `spelled`, tells a model nothing.
3. Local `$ref`s are inlined.
**Why it works this way.** Voice agents run small, fast models. Each extra branch or unknown keyword in a schema is one more thing such a model can get wrong:
1. A `null` branch on every optional value makes the model choose between leaving a value out, sending `null` and guessing. Small models often guess.
2. A keyword the provider does not support can make it refuse the call, or return no call at all. The caller then hears silence.
3. A format name the model has never seen, like `spelled`, tells it nothing. Plain words do.
The full schema still checks every call, so nothing the model could send before is refused now.
## A required argument left out or empty
```python theme={null}
{"refused": "birth_date is missing. Ask the caller for it, then call lookup_policy again.",
"missing": ["birth_date"]}
```
Small models often call a tool before they ask, with `""` for what they do not know.
1. A required argument that is absent, or text that is blank, is missing. The tool does not run. It raises `ArgumentsMissing`, a `ToolRefused`.
2. The model reads this refusal, not a format error like "expected a day written year-month-day".
3. When the reply that made the call already said something, no model reply follows. That reply asked the caller, so the caller answers next. `replies_to(result, spoke=...)` from `unmute_core.tools` holds this rule.
4. When the reply said nothing, the model replies to the refusal and asks.
5. A step's closing tool with `confirm` lines refuses the same way, before it asks anything.
6. On Pipecat, `tools_schema` cannot tell whether the reply spoke, so the model always replies there. So does OpenAI's live service, which cannot take a result without replying.
## Save a result and speak it
A task step lists the values a result saves (`Assign`) and the lines code speaks
for it (`ToolReply`) on its `TaskSpec`. See [Confirm in code](/core/build/tasks/confirm-in-code).
An agent without tasks lists the same rows on its `ToolRegistry`.
```python theme={null}
from unmute_core.tools import Assign, ToolRegistry, ToolReply
registry = ToolRegistry(
[local_tool(find_order)],
state=State,
assign={
"find_order": [
Assign(variable="order", path=()),
Assign(variable="order_number", path=("order_id",)),
]
},
replies=[
ToolReply(tool="find_order", when={"status": ["held"]}, say=["{{result.order_id}} is held."]),
ToolReply(tool="find_order", state={"vip": [True]}, say=["{{name}}, it arrives {{result.arrives}}."]),
ToolReply(tool="find_order", say=["Your order arrives {{result.arrives}}."]),
],
)
```
1. `assign` maps a tool to the State values its result saves. `path` walks the result by field names. `path=()` saves the whole result into a State value typed as the output model, like `order: Order | None = None`.
2. The values of one result are saved in one batch, or not at all. A save the State refuses is logged and told to the sinks as `tool.save_refused`. The model still reads the result, because the tool ran. A tool's save never confirms a value.
3. `replies` are tried in order. The first one that matches the result and fills is spoken. The model reads the result and is asked for no reply.
4. `when` maps a result field to the values that call for the line. `state` maps a State value to its values the same way. A reply with neither is the fixed reply. A line whose value is missing does not play, and the next reply is tried.
5. A line reads `{{result.}}`, nested like `{{result.order.id}}`, and `{{variable}}` from the State, nested like `{{account.amount_words}}`. Several lines are alternatives, said in turn.
6. A value is said by its output field's JSON Schema `format`, in the call's language. A `date` reads "tomorrow, October 16" with a timezone and "Friday, October 16, 2026" without one. A `date-time` adds the time, a `time` reads "9:00 AM", a `phone` is grouped, and a `Literal` or `Enum` value is said as words. Any other value is said as it is.
7. The registry checks every row when it is built. A tool, a result field or a State value that does not exist, or a result value whose type cannot fill the State value, fails with a message that names the fix.
8. A reply on a tool that ends the call is refused: the call is over before the line could play. Say a goodbye with the tool's `announce` and `announce_wait=True`.
9. A result that reports an error saves nothing and speaks nothing. Inside a task step, a tool that does not end the step still saves its registry `assign` rows at once, so a step that asks several questions keeps each answer as it comes. The step's own `replies` are spoken, then the tool's own, and the step's own `assign` saves when the step ends.
10. A `when` value on a `Literal`, `bool` or `Enum` field must be one the field can hold. A typo like `"shiped"` fails when the registry is built, with the values the field holds.
11. Each line code speaks is told to the sinks as `tool.replied`, so a trace shows which turns cost no model reply.
### Replies on the tool itself
A tool can carry its own replies. They play wherever the tool runs: on the main
agent, as a step's tool, and as a step's closing tool.
```python theme={null}
class Noted(BaseModel):
status: Literal["noted", "future_day"] = "noted"
complete: bool
next_question: str = ""
local_tool(
note_facts,
replies=[
ToolReply(when={"status": ["future_day"]}, say=["That day hasn't happened yet. On which day did it happen?"]),
ToolReply(when={"complete": [False]}, say=["{{result.next_question}}"]),
],
)
```
1. A tool's own reply leaves out `tool`. One that names another tool is refused.
2. The place's replies are tried first: the registry's on the main agent, the `TaskSpec`'s in a step. Then the tool's own, in order.
3. A reply on a `ToolRegistry` or a `TaskSpec` still names its tool.
### Check a rule before the tool runs
A closing tool with `confirm` reads its input back before it runs. A rule about
the request, like "a day within ten days", must answer before that read-back.
Give the tool a `precheck`:
```python theme={null}
def outside_window(day: date) -> Recorded | None:
if day < today():
return Recorded(status="past_day")
return None
local_tool(
ledger.record_promise,
precheck=outside_window,
replies=[ToolReply(when={"status": ["past_day"]}, say=["That day has already gone. Which other day would suit you?"])],
)
```
1. The precheck is a plain function, not async. It takes some of the tool's parameters by name, with the same types, or the whole input model when the tool takes one. Locked values are filled.
2. It returns an instance of the tool's output model, the outcome, or None to go ahead. An outcome is the tool's result: the tool does not run, and no announce plays.
3. The tool's replies say the outcome, like any result. A `when` value is checked against the output's `Literal` at build time.
4. On a closing tool with `confirm`, the precheck runs before the read-back. A wrong value is never read back, and the turn costs one model request: the call. It runs again on the caller's yes, since the state may have changed.
5. An outcome must not match the tool's `finish` rule. It is a refusal, not a success.
**Why it works this way.** A model that reads a booking back to the caller
words it a little differently each time, and sometimes gets the day wrong. A
line spoken by code says the same words every time, from the checked result. The
same `Assign` and `ToolReply` rows serve a task step and a plain agent, so a
value is saved and spoken one way across the whole library.
**Best practice.**
1. Use a reply for a line that must come out word for word, like a booking's day and time.
2. Save the whole output with `path=()` when later prompts read several of its fields, like `{{order.status}}`.
3. Set `language=` and `timezone=` on the spec, or on `function_tools` and `tools_schema`, so "tomorrow" means the business's tomorrow.
**On each kind of agent.** All four say the line. On Pipecat, a realtime model
words its own reply from the result instead. See [Realtime models](/core/models/realtime).
## Locked arguments
```python theme={null}
webhook_tool(..., locked={"customer_id": "{{customer.id}}", "call": "{{call.session_id}}"})
```
1. The model never sees a locked argument. A value it sends is replaced.
2. `{{name}}` and `{{name.field}}` read the call state. The tool is refused, with a hint, while the value is unset.
3. `{{call.name}}` reads what the call carries, like `{{call.remote_number}}` or `{{call.carrier_call_id}}`. It reads `state.call`, so every adapter has it.
4. A tool that locks an empty call value is refused: `this tool reads call.carrier_call_id, which this call does not carry`.
5. `{{@name}}` no longer exists. A tool that uses it fails when it is built, and the message names the new spelling. `{{@call_id}}` is now `{{call.carrier_call_id}}` or `{{call.session_id}}`. `{{@phone_number}}` is `{{call.remote_number}}`. `{{@transcript}}` is `Transcript()`.
6. A `ToolRegistry` built with `state=` checks each locked path when the registry is built. The path must exist, and its type must fit the parameter.
7. A path may name a whole shape or a list, like `"{{customer}}"`. Lock it as the only text, to a parameter that is an `object`, an `array` or has no type. The tool then gets the object or the list.
8. A shape or a list inside a longer text, like `"Customer: {{customer}}"`, fails at build.
**Why it works this way.** The model fills arguments from what it heard, so it
can mishear a value or invent one. An id the caller never says must come from
the call, not from the model. The filled call is checked against the whole
schema, so a value of the wrong type fails before any request leaves.
**Best practice.**
1. Lock every value the caller does not choose: customer ids, account numbers, the call id, the brand.
2. Build the `ToolRegistry` with `state=`. A typo in a path then stops the agent at startup, not in the middle of a call.
### Send the transcript
`Transcript` is a locked argument that reads the call's transcript so far.
A tool the model calls reads it from the call's `CallHooks`, the same as a tool on an event. On a plain agent with no `CallHooks`, it is an empty list.
```python theme={null}
from unmute_core.tools import Transcript
webhook_tool(
..., locked={"transcript": Transcript(max_messages=50), "reason": "{{call.end_reason}}"}
)
```
The newest messages to send. It must be 1 or more. A smaller number raises a Pydantic `ValidationError`. Whatever the number, the result stays within `TRANSCRIPT_MAX_BYTES` (32 KiB): the oldest messages go first, and the newest is always kept.
`False` sends a list of `{"role", "content"}` messages. `True` sends one text with a `role: content` line per message.
## Webhooks
```python theme={null}
webhook_tool(
"notify_crm",
"Tell the CRM about the booking.",
"https://crm.example.com/hooks/booking",
input=BookingNote,
output=Accepted,
auth=WebhookAuth.api_key("CRM_KEY", header="X-API-Key"),
body="envelope",
wait_for_response=False,
)
```
### webhook\_tool
The tool name. Letters, digits, `_` and `-`, at most 64.
What the tool does and when to call it. The model reads it. A blank description falls back to the tool name.
The endpoint. `{{name}}` placeholders may fill the path and query values from the call state, never the scheme or host.
The Pydantic model of the arguments. Its JSON Schema is what the model sees. See [Inputs and outputs](#inputs-and-outputs).
The Pydantic model of the answer. See [Outputs](#outputs). Use `Done` for a webhook that answers with an empty body.
Arguments filled from the call state and hidden from the model.
A line said as the tool starts.
`ends_conversation` ends the call once the tool succeeds.
What the caller's speech does to a running call.
Run the tool only after the announce line has played.
`False` hides a result that succeeded from the model.
How the model should use the result.
The credential, read at each call.
`raw` sends the arguments as the JSON object. `envelope` sends `tool_name`, `description`, `arguments`, a `timestamp` and `context`. The `context` holds what the call carries (`state.call`, without empty fields). An event tool adds `trigger_event` and `transcript`. So the receiver knows which tool called it.
`False` answers the model `{"ok": true, "accepted": true}` at once and sends the request in the background. A failed send is only logged. Call `await webhook.drain()` when the call ends. The tool's `output` must then be `Accepted`, or it fails at build.
Signs the body. `X-Signature-256` is its HMAC-SHA256 in hex. A GET webhook has no body to sign.
GET puts the arguments in the query. The others send them as JSON.
Fixed headers. Put a secret in `auth` instead.
Seconds for the whole call: DNS, connect, redirects and the answer. From 1 to 60.
Allow private, loopback and link-local addresses, and plain `http`.
`webhook_tool` takes these options as keywords after its fixed arguments. The
`WebhookOptions` type, from `unmute_core.tools`, names them all for a type checker:
`method`, `headers`, `hmac_secret`, `timeout`, `allow_private_network`, `auth`,
`body`, `tool_name` and `wait_for_response`. A value out of range raises a Pydantic
`ValidationError`, like a `timeout` of 0 or a `body` that is not `raw` or
`envelope`. An unknown option raises `TypeError`.
```python theme={null}
from unmute_core.tools import WebhookOptions
options: WebhookOptions = {"timeout": 5, "wait_for_response": False}
webhook_tool("notify_crm", "Tell the CRM.", URL, input=BookingNote, output=Accepted, **options)
```
Redirects stay on the same origin, at most three.
1. The URL is checked when the tool is built. The scheme must be `https`, or `http` with `allow_private_network`. The host must be there. User info, a fragment and a port outside 1 to 65535 are refused.
2. When the webhook answers with an error, the model reads the status and a short excerpt of the body. The excerpt is the `error`, `message` and `code` of a JSON body, or the first 300 characters of the text.
3. The tool events keep only the status. They never carry text that another service sent. In code, `ToolError(message, event_text=...)` sets the two apart.
A GET webhook sends the arguments as the query, beside the query values already
in its URL. Three rules keep them apart:
1. A GET tool whose input or `locked` names a query value of the URL fails at build. Rename the argument or drop the value from the URL.
2. A call whose argument clashes with a URL query value is refused with an error that names the argument.
3. With `auth`, a fixed `Authorization` header fails at build, in any letter case. `auth` sends the credential.
### WebhookAuth
`WebhookAuth.bearer(token_env)` sends `Authorization: Bearer `.
`WebhookAuth.api_key(token_env, header)` sends the token as it is, in `header`.
The library reads the token at each call, so a new token works without a restart.
The environment variable that holds the token, in UPPER\_SNAKE case. The name is read exactly, and case matters. An unset variable refuses the call, and the log names the variable.
The header `api_key` sends. `bearer` always sends `Authorization`. `WebhookAuth.api_key` defaults it to `X-API-Key`.
A function that returns the token. It may be `async`. It runs at each call. Use it in place of `token_env`.
Give exactly one of `token_env` and `token`.
```python theme={null}
async def fetch_token() -> str:
return await vault.read("crm-token")
auth = WebhookAuth.bearer(token=fetch_token)
auth = WebhookAuth.api_key(header="X-Key", token=fetch_token)
```
A provider that fails or returns an empty text refuses the call with "the
webhook could not authenticate". The log says why.
### Time and size limits
```python theme={null}
webhook_tool(..., timeout=5)
webhook_tool(..., wait_for_response=False)
```
1. `timeout` is one deadline for the whole request: DNS, the connection, every redirect and the answer. It is 10 seconds by default.
2. The request and the answer may each be 64 KiB at most. A larger one fails the tool call, and the model reads the error.
3. With `wait_for_response=False`, the model reads `{"ok": true, "accepted": true}` at once. The request goes on in the background. The tool's `output` is then `Accepted`.
**Why it works this way.** The caller waits through every second a webhook
takes. A separate limit for each step can add up to far more than any one of
them. One deadline puts a firm ceiling on the wait. The size cap keeps one
large answer from slowing the call.
**Best practice.**
1. Keep the 10 second default. Lower it for a lookup the caller waits on.
2. Use `wait_for_response=False` for a notification nobody waits for, like telling a CRM about a booking.
**On each kind of agent.** A background request finishes when the call ends
only when the tools have the call's hooks. `UnmuteAgent` and `UnmuteFlows` get
them from `call=`. A plain agent gets them from `hooks=call`. See
[Use it in your agent](#use-it-in-your-agent).
### Private addresses
```python theme={null}
webhook_tool(..., "http://localhost:8000/hooks/booking", allow_private_network=True)
```
1. `allow_private_network` is off by default.
2. Off, the webhook refuses private, loopback and link-local addresses. It refuses plain `http` too.
3. On, it accepts them.
**Why it works this way.** A webhook URL often comes from config, and sometimes
from someone else. Pointed at `localhost` or a cloud metadata address, a tool
could reach services inside your network. So every address must be public. The
host name is looked up once, and the connection goes to the address that was
checked. A second lookup cannot send it somewhere else.
**Best practice.**
1. Keep it off in production.
2. Turn it on only for your own internal service, or for `localhost` while you develop.
3. Never turn it on when someone else writes the URL.
## Built-in tools
```python theme={null}
from unmute_core.tools import current_datetime_tool, user_phone_number_tool
registry = ToolRegistry([current_datetime_tool("Europe/Madrid"), user_phone_number_tool()])
```
Neither tool takes arguments.
| Tool | The result |
| - | - |
| `current_datetime_tool(timezone="UTC")` | `timezone`, `local_datetime`, `local_date`, `local_time`, `day_of_week`, `utc_offset` and `is_dst` |
| `user_phone_number_tool()` | `{"available": true, "phone_number": "+34...", "call_type": "inbound", "reason": null}`, read from `state.call.remote_number` and `state.call.direction` |
1. Give `current_datetime_tool` an IANA zone, like `Europe/Madrid`. Another name raises `ValueError`.
2. `call_type` is `inbound` or `outbound`, and `null` when the call has no `direction`.
3. When the call has no phone number, `user_phone_number_tool` returns `{"available": false, "phone_number": null, "call_type": null, "reason": ...}`.
4. Both take `name=` and `description=` to change what the model reads. The defaults are `current_datetime` and `user_phone_number`.
5. The tool reads `state.call`, so the adapter needs nothing more.
To let the model save State values with a tool, see
[State](/core/build/state).
## Watch tool calls
```python theme={null}
def show(stage: str, data: dict) -> None:
print(stage, data)
registry.listen(show)
```
| Stage | Data |
| - | - |
| `tool.started` | `name`, `source` |
| `tool.succeeded` | `name`, `source`, `ms` |
| `tool.failed` | `name`, `source`, `ms`, `error` |
| `tool.refused` | `name`, `source`, `error` |
| `tool.save_refused` | `name`, `source`, `error` |
1. The sink gets names and timing only. It never gets argument values. `source` is `model`, or `event` for a tool on an event.
2. `ms` is the time the tool ran. A wait for the announce line is not in it. A cancelled call ends with `tool.failed` and the error `cancelled`.
3. A sink that raises is logged. It never breaks the call. A sink the registry already holds is not added again.
4. `only()` and `with_tools(*tools)` keep the sinks.
5. In a call, use the call's hooks instead. See [Hooks](/core/build/hooks).
A tool can also run on its own, with no model choice, when the call starts or
ends. That is a tool on an event. See [The call's life](/core/build/call-lifecycle).
Code that runs before, around or after each tool call is a hook. See
[Hooks](/core/build/hooks).
## Advanced
### Rules for a hand-written schema
A custom `ToolSpec` takes the JSON Schema of its arguments as `parameters`. See
[Your own kind of tool](#your-own-kind-of-tool). A schema built with
`model_json_schema()` already follows these rules, so `local_tool` and
`webhook_tool` always do.
The schema is JSON Schema 2020-12 with a fixed list of keywords. Anything else fails when the tool is built, and the message names the keyword.
| Group | Keywords |
| - | - |
| Structure | `$schema`, `$defs`, `$ref`, `type`, `properties`, `required`, `additionalProperties`, `items`, `prefixItems`, `contains`, `minContains`, `maxContains`, `patternProperties`, `propertyNames`, `minProperties`, `maxProperties` |
| Limits | `minItems`, `maxItems`, `uniqueItems`, `minLength`, `maxLength`, `pattern`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`, `enum`, `const` |
| Choices | `anyOf`, `oneOf`, `allOf`, `not`, `discriminator` |
| Notes | `description`, `title`, `default`, `examples`, `example`, `deprecated`, `readOnly`, `writeOnly`, `format`, `$comment`, and any key that starts with `x-` |
In that schema:
1. `definitions` and `$id` are refused. Use `$defs` and local `#/$defs/...` references.
2. `format` and the notes are hints. Nothing checks them.
3. `nullable` is not JSON Schema, so it is refused. Write `"type": ["", "null"]` instead.
4. The root of the parameters is a plain object schema. It may hold only `$schema`, `$defs`, `type` (`"object"`), `properties`, `required`, `additionalProperties`, `description`, `title`, `$comment` and `x-` keys. Frameworks send only the root `properties` and `required`, so another root keyword, like `oneOf`, `anyOf`, `allOf`, `not`, `patternProperties`, `propertyNames`, `minProperties`, `maxProperties` or `if`, would be lost on one of them. It fails when the tool is built. Move it into a property, or wrap the choice in one property. Nested schemas may use every keyword in the table.
**Why it works this way.** Each framework turns a schema into a model request
its own way. A keyword one of them drops would make the same tool behave
differently on LiveKit and Pipecat. So one list of keywords is checked when the
tool is built, and a schema either works on both or fails at startup.
**Best practice.**
1. Build the schema from a Pydantic model with `model_json_schema()`, so it cannot drift from your code.
2. Keep the root a plain object of named properties. Put a choice, like `oneOf`, inside one property.
### Arguments the schema does not name
1. The model may send an argument the schema does not list. The call is refused with a message that names it: "bogus is not an argument of lookup. Call lookup again without it." The model reads this and calls again.
2. A schema stays open when it sets `additionalProperties` to `true` or to a schema, or when it has no `properties`. It then keeps the extra arguments.
3. A custom `ToolExecutor` with `checks_extra_arguments = True` gets the extra arguments. It then refuses them in its own words.
### Ask the registry
```python theme={null}
"lookup_order" in registry # True when the registry has a tool of this name
registry.keeps_running("lookup_order") # True when its interruption is "continue"
```
1. `name in registry` tests for a tool by name.
2. `keeps_running(name)` says whether the caller's speech must leave a running call of the tool alone. An unknown name gives `False`, so the call is cancelled.
3. The adapters use both. You need them only when you write your own adapter.
### Your own kind of tool
`ToolExecutor` is the plug point for every way to run a tool. The library ships
`Webhook` and `LocalHandler`. You can add a third, for example one that runs your
tools through your own service.
```python theme={null}
from typing import Any
from unmute_core.state import CallState
from unmute_core.tools import ToolError, ToolSpec
class ServiceTool:
"""Runs a tool through your own tool service."""
def __init__(self, client: ServiceClient, tool_id: str) -> None:
self._client = client
self._tool_id = tool_id
async def run(
self,
arguments: dict[str, Any],
state: CallState | None,
*,
context: dict[str, object] | None = None,
) -> object:
result = await self._client.invoke(self._tool_id, arguments, context=context)
if not result.ok:
raise ToolError(result.message_for_the_model)
return result.data
spec = ToolSpec("book", "Book a table.", PARAMETERS, Booking, ServiceTool(client, "book"))
```
1. `run` gets the model's arguments, with the locked values filled and checked against the schema. It must be an `async` method. A `ToolSpec` refuses an executor with no async `run`.
2. Raise `ToolError` with the words the model should read. Any other error becomes "failed before completing. Do not claim success."
3. Add a `context` keyword to `run` to get the event context. Without it, `run` gets only the arguments and the state.
4. Add `validate(arguments) -> dict` to refuse bad input before a step asks the caller to confirm it.
5. Set `checks_extra_arguments = True` on the class to get arguments the schema does not name. Without it, the registry refuses them first.
6. The executor never changes what the model sees. The output model, the announce line, the effect and the interruption rule stay on the `ToolSpec`, the same for every kind of tool. `PARAMETERS` is the JSON Schema of the arguments, and `Booking` the output model.
## Troubleshooting
### A tool call fails with "does not fit"
The tool returned a result that its output model does not take. The message
names the first field that is wrong.
**Fix:** return what the output model declares, or change the model. A failure the
model should read is a raised `ToolError`, not a returned dict.
### A tool call returns `refused` and nothing is said
The call reads a value that is not set yet. The result is `{"refused": ...}`
and holds a hint.
**Fix:** set the value first, or start the task the hint names. Check every
announce line too, because all of them must fill.
### A webhook call fails with "could not authenticate"
The token variable is unset, or the token provider failed.
**Fix:** set the variable named in the log, or fix the provider.
```bash theme={null}
export ORDERS_TOKEN="..."
```
### A webhook to localhost is refused
Private and loopback addresses are off by default.
**Fix:** turn on `allow_private_network` for the tool, for development only.
```python theme={null}
webhook_tool(..., "http://localhost:8000/hooks/booking", allow_private_network=True)
```
## Where to go next
Add a tool to your agent, step by step.
Run your code around each tool call.
Offer tools to a step that saves values.
How `agent.yaml` declares the same tools.
# Turn taking reference
Source: https://unmute.ai/core/reference/turn-taking
Every turn pace window, interruption rule, idle nudge and call limit argument, and how each framework applies them.
This page is the full detail behind [Turn taking](/core/build/turn-taking). Start there to set the pace, the interruption rule and the idle nudges. Come here for every argument, window and error.
## What it gives you
| On a call without it | What the library does |
| - | - |
| Callers get cut off mid-sentence, or wait too long for a reply. | Three paces, `snappy`, `balanced` and `patient`, set each framework's own timing. [Turn pace](#turn-pace) |
| The caller pauses, then goes on. The reply plays over them. | The reply is dropped. The next one answers everything they said. [When the caller goes on speaking](#when-the-caller-goes-on-speaking) |
| A "yes" or a cough cuts the agent off. | Keep short answers until the line ends, or stop only for real speech. [When the caller speaks over a line](#when-the-caller-speaks-over-a-line) |
| A quiet caller keeps the line open, or the agent asks "are you there?" during its own slow tool. | Up to two nudges, then a hang-up. The timer runs only while the agent listens. [When the caller goes quiet](#when-the-caller-goes-quiet) |
| A call that never ends keeps costing money. | `CallLimit` ends it. [Call length](#call-length) |
## All of it together
```python LiveKit theme={null}
from unmute_core.idle import IdleNudges
from unmute_core.livekit import endpointing, idle_nudges, interruption, yield_to_caller
from unmute_core.turn import turn_window
window = turn_window("balanced", "livekit")
session = AgentSession(
...,
turn_handling=TurnHandlingOptions(
endpointing=endpointing(window), interruption=interruption("keep")
),
user_away_timeout=None,
)
yield_to_caller(session)
idle_nudges(session, IdleNudges(first_nudge_text="Are you still there?"))
```
```python Pipecat theme={null}
from unmute_core.idle import IdleNudges
from unmute_core.pipecat import IdleNudgeObserver, interruption, smart_turn_params, vad_params
from unmute_core.turn import turn_window
window = turn_window("balanced", "pipecat")
vad = SileroVADAnalyzer(params=vad_params(window))
turn = LocalSmartTurnAnalyzerV3(params=smart_turn_params(window))
params = LLMUserAggregatorParams(
user_turn_strategies=interruption("keep", stop=[TurnAnalyzerUserTurnStopStrategy(...)]),
)
worker.add_observer(IdleNudgeObserver(IdleNudges(first_nudge_text="Are you still there?"), worker))
```
On Unmute, `conversation` and `models.turn.*.pace` in `agent.yaml` turn into these objects. See [How Unmute uses unmute-core](/core/start/unmute-and-core).
## Turn pace
A caller pauses mid-sentence. The pace says how long the agent waits before it decides the turn is over.
```mermaid theme={null}
flowchart LR
P[Pace name] -->|turn_window| W[TurnWindow]
W -->|endpointing, vad_silence| L[LiveKit options]
W -->|vad_params, smart_turn_params| K[Pipecat options]
```
1. Pick a pace by name: `snappy`, `balanced` or `patient`. `TURN_PACES` lists them.
2. `turn_window(pace, framework)` returns the floor and ceiling that framework uses for the pace.
3. The framework's helper turns the window into its own options.
These windows are Unmute's measured ones. The pace is how long the caller may pause before the turn ends.
### turn\_window
```python theme={null}
from unmute_core.turn import turn_window
```
`snappy`, `balanced` or `patient`. None means `balanced`.
Whose window to return.
A constraint error names the function and the field, like `1 validation error for turn_window`. A pace that is not one of the three raises `ValueError` with the text `turn_pace 'x' is not one of snappy, balanced, patient`. A framework that is not one of the two raises Pydantic's `ValidationError`, which is a `ValueError`.
### TurnWindow
A frozen Pydantic dataclass. A wrong type, or a `mode` other than `fixed` or `dynamic`, raises `ValidationError`.
The floor. The silence the VAD waits before it says speech stopped and the end of turn model is asked.
The shortest wait LiveKit's endpointing considers.
The ceiling. The longest the agent waits for a caller the end of turn model thinks is not done.
LiveKit's endpointing mode. `dynamic` adapts inside the window to the pauses this caller leaves. Pipecat has no mode.
### The windows
| Pace | LiveKit floor, min, max, mode | Pipecat floor and max |
| - | - | - |
| `snappy` | 0.25, 0.25, 1.2, dynamic | 0.2 and 1.2 |
| `balanced` | 0.3, 0.3, 1.6, dynamic | 0.2 and 1.6 |
| `patient` | 0.4, 0.5, 2.5, fixed | 0.2 and 3.0 |
`balanced` is the default pace. On Pipecat the floor stays at 0.2 seconds for every pace, so the pace moves only the ceiling.
`TURN_WINDOWS` in `unmute_core.turn` holds these numbers, by framework and then by pace. It is a read-only mapping, and assigning to it raises `TypeError`. To use other numbers, build your own `TurnWindow` or your own framework options. Do not edit the table.
### On each framework
`endpointing(window)` returns the window's ceiling as `TurnHandlingOptions(endpointing=...)`. Use `window.vad_silence` as Silero's `min_silence_duration`. On Pipecat the VAD waits a short, fixed silence, and the turn analyzer decides the rest within the ceiling. [Turn taking](/core/build/turn-taking#set-the-turn-pace) shows the code.
## When the caller goes on speaking
A caller pauses ("Hi." then "I'd like to book a haircut"). LiveKit ends their turn at the pause. If they go on before the reply plays, LiveKit still plays the reply, over them. `yield_to_caller` drops that reply. On Pipecat there is nothing to call: a new caller turn interrupts whatever the bot is thinking, saying or running.
Call `yield_to_caller` once, after building the session.
1. The caller speaks while the agent thinks, or the agent starts to think while the caller speaks. The reply is dropped.
2. The caller's words are already in the history, so the next reply answers all of them.
3. Audio that already plays is left to LiveKit's interruption settings.
4. A reply with a tool running is kept, because dropping it would cancel the tool.
### yield\_to\_caller
The call's session.
## When the caller speaks over a line
A "mm-hm" or a "yes" over the agent can mean "go on" or "that is my answer". The `interruption` rule picks which. It uses the same three names on both frameworks: `keep`, `drop` and `stop`. [Turn taking](/core/build/turn-taking#choose-what-speech-over-a-line-does) shows what each one does, and the code.
The details differ by framework:
* **LiveKit** uses its adaptive detector. It judges the sound. With `keep` or `drop`, the detector decides, and LiveKit drops a backchannel's words unless they ended in the line's last second. The detector runs on LiveKit's inference service. It needs `LIVEKIT_API_KEY` or `LIVEKIT_INFERENCE_API_KEY`. Without one, LiveKit falls back to `stop`, and the library logs a warning. That is why `keep` and `drop` differ there. With `stop`, the agent stops after half a second of speech. `keep` and `drop` ask for the detector. LiveKit turns the detector on by itself only in dev mode and for an agent deployed on LiveKit Cloud. In production, with no `interruption` set, LiveKit uses plain voice detection. That is the same as `stop`. So `drop` is not LiveKit's default in production. `keep` and `drop` set the detector on purpose.
* **Pipecat** has no detector, so `keep` counts words. A turn of fewer than 3 words waits for the line to end. A turn of 3 or more words stops the agent. "Yes, that's right" has 3 words and stops it. Chinese, Japanese and Thai have no spaces between words, so `word_count` counts them: one word for each 2 characters of Chinese or Japanese, and one for each 4 characters of Thai.
### InterruptionRule
`interruption(...)` on both frameworks checks its arguments with `unmute_core.turn.InterruptionRule`. Use the rule yourself to check numbers before you build the options. A frozen Pydantic dataclass.
```python theme={null}
from unmute_core.turn import InterruptionRule
InterruptionRule("stop", min_speech_s=0.8)
```
The rule.
Words the caller must say over the agent before it counts.
Seconds of speech over the agent before it stops. It works with `stop` only.
The lowest `min_words` the framework takes. It is 0 on LiveKit and 1 on Pipecat.
It raises `ValueError` with a text that names the argument and the fix:
* `min_words must be 0 or more, got -1`, with the floor in place of 0.
* A `min_speech_s` below 0 raises a Pydantic `ValidationError`, which is a `ValueError`.
* `words already gate the turn, so min_speech_s applies to stop only`, when `min_speech_s` comes with `keep` or `drop`.
### word\_count
`word_count(text)` from `unmute_core.turn` counts the words a caller said, also in a language written without spaces. A run of Chinese or Japanese counts one word for each 2 characters. A run of Thai counts one for each 4. The rest counts what spaces separate. The count for Chinese, Japanese and Thai is an average, not a word splitter. Pipecat's `interruption("keep")` uses it.
```python theme={null}
from unmute_core.turn import word_count
word_count("Yes, that is right") # 4
```
### interruption on LiveKit
It returns the session's `InterruptionOptions`. The floor for `min_words` is 0. With `keep` or `drop`, it needs `LIVEKIT_API_KEY` or `LIVEKIT_INFERENCE_API_KEY`. Without one it logs a warning, and LiveKit stops the agent on any speech, as `stop` does.
The rule.
False lets the agent finish every line, whatever the caller says.
Words the caller must say before speech counts as an interruption. 0 keeps LiveKit's default.
Seconds of speech over the agent before it stops. It sets LiveKit's interruption `min_duration`, 0.5 seconds by default. A cough or a "mm" shorter than this does not cut the agent off. It works with `stop` only.
It raises the `InterruptionRule` `ValueError` when `min_words` or `min_speech_s` is negative, or when `min_speech_s` comes with `keep` or `drop`. With those two, the detector already judges the sound.
### interruption on Pipecat
It returns `UserTurnStrategies`. Give them to `LLMUserAggregatorParams(user_turn_strategies=...)`. The floor for `min_words` is 1.
The rule.
The stop strategies, like a `TurnAnalyzerUserTurnStopStrategy`.
Words over the agent that cut it off, for `keep` and `drop`. It must be 1 or more.
Seconds of speech over the agent that cut it off, for `stop`. Speech that ends sooner does not cut the agent off. A cough holds nothing. A "mm" or a "yes" with words is kept: when the agent stops, those words start the caller's turn and reach the model. The VAD's own `start_secs` counts toward it. When the agent is silent, speech starts the turn at once.
It raises the `InterruptionRule` `ValueError` when `min_words` is below 1, when `min_speech_s` is negative, or when `min_speech_s` comes with `keep` or `drop`. With those two, words already gate the turn.
On Pipecat, `keep` uses Pipecat's own start strategies and `drop` uses `MinWordsUserTurnStartStrategy`. `stop` keeps Pipecat's defaults.
### Turn off interruption or protect a line
Unmute's `conversation.interruption` has `enabled` and `minimum_words`. On LiveKit, `interruption("keep", enabled=False)` lets the agent finish every line. `interruption("keep", min_words=2)` needs two words before speech counts.
On Pipecat, `min_words` covers `minimum_words` and `user_mute_strategies` covers the rest:
```python theme={null}
from unmute_core.pipecat import interruption, user_mute_strategies
LLMUserAggregatorParams(
user_turn_strategies=interruption("drop", stop=[...], min_words=2),
user_mute_strategies=user_mute_strategies(protect=["greeting", "tool_calls"]),
)
```
False mutes the caller while the agent speaks, so no line is cut off.
What the caller cannot cut off while interruption is on. `greeting` is the agent's first line. `tool_calls` is a running tool.
`user_mute_strategies` raises `ValueError` when `protect` comes with `enabled=False`, or names something else. On LiveKit, a greeting nobody may cut off is `Greeting(interruptible=False)`. A tool call that runs always finishes.
### What the trace shows
Each verdict is a `caller.over_agent` event in the trace.
* **LiveKit** records the probability the detector gave.
* **Pipecat** records `interruption: true` when the caller's turn starts over the agent. It records `false` when their words wait for the line to end.
A step's confirm line, like "Can you confirm your number is +34 671 51 01 03?", counts as heard when the caller cuts in after it said every value. LiveKit keeps the words that played, so a "yes, that's right" over the last word books. A cut before that asks again.
## When the caller goes quiet
`IdleNudges` holds up to three lines, each said after its own quiet. Any word from the caller, or any reply from the agent, starts again from the first one. The lines are spoken by code, so no model request is made. A nudge with no text is worded by the model. [Turn taking](/core/build/turn-taking#nudge-a-quiet-caller) shows the code on each framework.
```mermaid theme={null}
flowchart TD
A[Agent stops speaking] --> B[Wait first_nudge_delay_seconds]
B --> C[First nudge]
C --> D[Wait second_nudge_delay_seconds]
D --> E[Second nudge]
E --> F[Wait hangup_delay_seconds]
F --> G[Final line, then end the call]
H[Caller speaks or agent replies] -->|start again| B
```
1. After the agent stops speaking, it waits `first_nudge_delay_seconds`, then says the first line.
2. It waits again, says the second line, waits again, says the final line and ends the call.
3. Any caller transcript, interim ones too, starts again from the first line.
4. A nudge the model words (one with no text) runs the whole sequence too: the second nudge and the idle hang-up still come after it.
On LiveKit, leave `user_away_timeout` at `None`. LiveKit's own timeout never starts while a tool runs, and a task runs inside the tool that starts it. `idle_nudges` reads only the agent's state and the caller's words, so it keeps working in the middle of a booking.
On LiveKit, closing the session hangs up a phone caller only with `delete_room_on_close=True`. Without it, the caller stays on an empty line.
On Pipecat, leave the user aggregator's `user_idle_timeout` unset. The observer reads the agent's state from frames. The bot speaks between `BotStartedSpeakingFrame` and `BotStoppedSpeakingFrame`. It thinks from a model response's start, and while a tool call runs. The final step runs `worker.end()`, which drains the pipeline so the final line plays.
### IdleNudges
A frozen Pydantic model. It refuses unknown fields. A delay below 1 or a wrong type raises `ValidationError`, which is a `ValueError`.
Off keeps every timer still.
Quiet before the first nudge, at least 1. None gives no nudges: the call ends after `hangup_delay_seconds` of quiet.
Quiet after the first nudge, at least 1. None gives no second nudge: the hang-up wait follows the first.
Quiet after the last nudge, at least 1. None never ends the call: the agent only nudges.
The first nudge, like "Are you still there?" Trimmed, 1 to 500 characters. None lets the model word it.
The second nudge. None lets the model word it.
Said just before the call ends. None ends it without a line.
What the model is told for a nudge with no text. Write it in the language the model should answer in, or leave the English default.
`IdleNudges` refuses these, with a `ValidationError`:
* Both `first_nudge_delay_seconds` and `hangup_delay_seconds` None is refused. Use `enabled=False`.
* With no first nudge, set `second_nudge_delay_seconds=None` and leave out the nudge texts.
* A second nudge text needs a second nudge delay.
* A final hang-up text needs a hang-up delay.
`GENERATED_NUDGE_INSTRUCTIONS` is the default `nudge_instruction`: "The caller went quiet. Briefly check whether they are still there." On Pipecat, the instruction goes into the context as a developer message.
### Nudge only, hang up only
```python theme={null}
IdleNudges(first_nudge_text="Are you still there?", hangup_delay_seconds=None) # nudge only
IdleNudges(first_nudge_delay_seconds=None, hangup_delay_seconds=40) # hang up only
```
1. `hangup_delay_seconds=None` never ends the call. The agent only nudges.
2. `first_nudge_delay_seconds=None` says no nudge. The call ends after `hangup_delay_seconds` of quiet.
Unmute's `conversation.inactivity` maps like this:
| Unmute | `IdleNudges` |
| - | - |
| nudge and end | `first_nudge_delay_seconds=nudge_after`, `second_nudge_delay_seconds=None`, `hangup_delay_seconds=end_after - nudge_after` |
| nudge only | `hangup_delay_seconds=None` |
| end only | `first_nudge_delay_seconds=None`, `second_nudge_delay_seconds=None`, `hangup_delay_seconds=end_after` |
### idle\_nudges and IdleNudgeObserver
Both return or hold an `IdleNudgeController`. Use its `suspend(reason)` and `resume(reason)` around something that must not draw a nudge. Calls nest.
For `idle_nudges` on LiveKit: the call's session, before it starts.
The lines and waits. None turns it off.
For `IdleNudgeObserver` on Pipecat: the call's worker, which speaks the lines and ends the call. Pass it as the second argument, after `config`.
How to end the call. LiveKit uses `session.shutdown()` and Pipecat uses `worker.end()` when None.
Called with each `idle_nudges.*` event, for the trace.
The call's hooks. With them, the hang-up is noted as `idle`, so the call's end reads `idle`. See [Why the call ended](/core/build/call-lifecycle#why-the-call-ended).
Pipecat only, on `IdleNudgeObserver`. OpenAI's realtime or live service that speaks itself says the lines and words the nudges in replies of its own.
### IdleNudgeController
`IdleNudgeController(config, speak=..., hangup=..., on_event=None, sleep=asyncio.sleep, generate=None)` runs the nudges for one call. The two adapters build it for you. Build one yourself only for a framework the library does not wrap. Report each agent state change with `on_agent_state_changed(old, new)` and each caller transcript with `on_user_transcript(text)`. Call `close()` when the call ends.
It raises `ValueError` when a nudge has no text and there is no `generate`.
## Call length
`CallLimit` ends a call after a longest allowed length, with no closing line. The adapters wrap it as `max_duration` on each framework, on [LiveKit](/core/frameworks/livekit) and on [Pipecat](/core/frameworks/pipecat).
```python theme={null}
from unmute_core.idle import CallLimit
limit = CallLimit(20 * 60, session.shutdown)
limit.start()
```
The longest the call may run. It must be above zero, or `ValidationError` is raised. It is a `ValueError`, and its first line names `CallLimit` and the field.
Ends the call, like `session.shutdown`.
`start()` begins the count and a second call does nothing. `cancel()` stops it. `running` is True from `start` until the call ends.
## Where to go next
Set the pace, the interruption rule and the idle nudges.
The greeting, the failure line and the end of the call.
# Install Unmute Core
Source: https://unmute.ai/core/start/installation
Add unmute-core and a framework extra to a project from PyPI.
unmute-core is on [PyPI](https://pypi.org/project/unmute-core/). It needs Python 3.12 or newer.
```bash theme={null}
uv add "unmute-core[livekit]" # or [pipecat]
```
On this page:
* [Add it to a project](#add-it-to-a-project) - the extras and the version range
* [Check the version at import](#check-the-version-at-import) - `require()`
* [With the knowledge extra](#with-the-knowledge-extra) - copy, do not hardlink
## Add it to a project
```toml pyproject.toml theme={null}
[project]
dependencies = ["unmute-core[livekit]~=X.Y.Z"] # or [pipecat]
```
Write the newest version from the [changelog](https://github.com/slng-ai/unmute-core/blob/main/CHANGELOG.md) in place of `X.Y.Z`.
`~=X.Y.Z` allows `X.Y.Z` and later patches, never the next minor version. Before 1.0, a new minor version can break your code.
| Extra | What it installs |
| - | - |
| `livekit` | the supported LiveKit Agents range, and `unmute_core.livekit` |
| `pipecat` | the supported Pipecat range, and `unmute_core.pipecat` |
| `slng` | the `openai` package, which `OpenAIModelCall` and the SLNG Context Router use |
| `knowledge` | llama-index, for [knowledge](/core/build/knowledge) search |
The library needs these versions:
| Package | Version |
| - | - |
| `pydantic` | 2.11 or newer |
| `pydantic-settings` | 2.8 or newer |
| OpenTelemetry (`opentelemetry-sdk` and the OTLP exporter) | 1.40 or newer |
| `phonenumbers` | 8.13 up to, not including, 10 |
| `openai`, with the `slng` extra | 1.109 up to, not including, 4 |
LiveKit 1.8.8 itself needs `openai` 3. A Pipecat app may keep `openai` 1 or 2.
Extras combine: `unmute-core[livekit,slng]`.
With pip:
```bash theme={null}
pip install "unmute-core[livekit]"
```
To move to a new release, change the range and run:
```bash theme={null}
uv lock --upgrade-package unmute-core
uv sync
```
Check the environment at startup too. `check_settings(LangfuseSettings)` names every missing variable in one error. [Settings](/core/reference/settings) lists them.
## Check the version at import
Generated code states the library version it was built for:
```python agent.py theme={null}
import unmute_core
unmute_core.require("X.Y.Z")
```
Write the real version in place of `X.Y.Z`. `require()` fails at import, so a wrong version fails the deploy and never a call.
1. It fails when the installed library is older than the required version.
2. It fails when the installed library has another major version.
3. While the version is 0.x, `0.MINOR` counts as the major.
The error names both versions, the range to require in `pyproject.toml`, and the command that fixes it. A version that is not three numbers raises `ValueError`.
## With the knowledge extra
`unmute-core[knowledge]` brings llama-index, which reads NLTK data files.
NLTK refuses a file with more than one hardlink.
On Linux, uv installs packages as hardlinks by default.
So install with copies wherever the `[knowledge]` extra is used:
```bash theme={null}
UV_LINK_MODE=copy uv sync # local, CI
uv pip install --link-mode=copy ... # Dockerfile
```
Without it, the first knowledge lookup fails with
`PermissionError: Security Violation [pathsec.open]: refusing multiply-linked file`.
`import unmute_core.knowledge` without the extra raises an `ImportError` that names the extra and the command to install it.
## Where to go next
Run the smallest agent on LiveKit or Pipecat.
Every environment variable, and how to check them at startup.
# Unmute Core quickstart
Source: https://unmute.ai/core/start/quickstart
Run the smallest unmute-core agent on LiveKit or Pipecat: a salon receptionist that keeps the caller's phone number.
This agent answers the phone for a salon. It asks for the caller's number and keeps it in typed call state. If the number is not valid, the library refuses it and the agent asks again.
You need the library with a framework extra. See [Installation](/core/start/installation). The agent hears and speaks through SLNG: Soniox for speech to text and Fish Audio for text to speech. It uses OpenAI for the model. Set `SLNG_API_KEY`, `SLNG_WORLD_PART` (your SLNG project's region, like `eu-north`) and `OPENAI_API_KEY`.
## The agent
```python livekit_agent.py theme={null}
import os
from livekit.agents import AgentServer, AgentSession, JobContext, cli
from livekit.plugins import openai, silero, slng
from pydantic import BaseModel
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent
from unmute_core.state import CallState, Phone
PROMPT = "You answer the phone for a hair salon. Ask for the caller's phone number. Keep replies short."
SLNG_HOST = f"{os.environ['SLNG_WORLD_PART']}.api.slng.ai"
VOICE = "8d8aec63a56c460cb7def795bdf754fa"
class State(BaseModel):
customer_phone: Phone | None = None
server = AgentServer()
@server.rtc_session()
async def entrypoint(ctx: JobContext) -> None:
stt = slng.STT(
api_key=os.environ["SLNG_API_KEY"],
slng_base_url=SLNG_HOST,
model="soniox/speech-ai:rt-v5",
language="en",
)
session = AgentSession(
stt=stt,
llm=openai.LLM(model="gpt-5.6-luna"),
tts=slng.TTS(
api_key=os.environ["SLNG_API_KEY"],
slng_base_url=SLNG_HOST,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language="en",
),
vad=silero.VAD.load(),
)
stt.attach_to_session(session)
state = CallState(State)
spec = AgentSpec(PROMPT, save_values=True)
agent = UnmuteAgent(spec, state=state)
await session.start(agent=agent, room=ctx.room)
if __name__ == "__main__":
cli.run_app(server)
```
```python pipecat_bot.py theme={null}
import os
from collections.abc import Callable
from typing import Any
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.frames.frames import LLMUpdateSettingsFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
LLMContextAggregatorPair,
LLMUserAggregatorParams,
)
from pipecat.runner.types import RunnerArguments
from pipecat.runner.utils import create_transport
from pipecat.services.openai.llm import OpenAILLMService
from pipecat.services.settings import LLMSettings
from pipecat.transcriptions.language import Language
from pipecat.transports.base_transport import BaseTransport, TransportParams
from pipecat.workers.runner import WorkerRunner
from pipecat_slng import SlngSTTService, SlngTTSService
from pydantic import BaseModel
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows
from unmute_core.state import CallState, Phone
PROMPT = "You answer the phone for a hair salon. Ask for the caller's phone number. Keep replies short."
VOICE = "8d8aec63a56c460cb7def795bdf754fa"
TRANSPORTS: dict[str, Callable[..., Any]] = {
"webrtc": lambda: TransportParams(audio_in_enabled=True, audio_out_enabled=True)
}
class State(BaseModel):
customer_phone: Phone | None = None
async def bot(runner_args: RunnerArguments) -> None:
transport = await create_transport(runner_args, TRANSPORTS)
state = CallState(State)
llm = OpenAILLMService(
settings=OpenAILLMService.Settings(model="gpt-5.6-luna", system_instruction="")
)
context = LLMContext()
aggregators = LLMContextAggregatorPair(
context, user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer())
)
spec = AgentSpec(PROMPT, save_values=True)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
flows.install()
pipeline = Pipeline(
[
transport.input(),
SlngSTTService(
api_key=os.environ["SLNG_API_KEY"],
world_part=os.environ["SLNG_WORLD_PART"],
model="soniox/speech-ai:rt-v5",
language=Language.EN,
),
aggregators.user(),
llm,
SlngTTSService(
api_key=os.environ["SLNG_API_KEY"],
world_part=os.environ["SLNG_WORLD_PART"],
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language=Language.EN,
),
transport.output(),
aggregators.assistant(),
]
)
worker = PipelineWorker(pipeline)
@transport.event_handler("on_client_connected")
async def prompt(transport: BaseTransport, client: Any) -> None:
delta = LLMSettings(system_instruction=flows.main_instruction())
await worker.queue_frame(LLMUpdateSettingsFrame(delta=delta))
runner = WorkerRunner(handle_sigint=runner_args.handle_sigint)
await runner.add_workers(worker)
await runner.run()
if __name__ == "__main__":
from pipecat.runner.run import main
main()
```
## Run it
Install the plugins your framework needs next to the library:
```bash LiveKit theme={null}
uv add livekit-plugins-openai livekit-plugins-silero livekit-plugins-slng
export SLNG_API_KEY=... SLNG_WORLD_PART=eu-north OPENAI_API_KEY=...
uv run python livekit_agent.py console
```
```bash Pipecat theme={null}
uv add "pipecat-ai[openai,runner,silero,webrtc]" pipecat-slng
export SLNG_API_KEY=... SLNG_WORLD_PART=eu-north OPENAI_API_KEY=...
uv run python pipecat_bot.py -t webrtc
```
LiveKit `console` talks to your microphone. Use `dev` in its place to connect to a LiveKit server. For Pipecat, open `http://localhost:7860` and talk.
## Try it
Say "My number is six one two, three four five." That is not a full number. The save is refused, and the agent asks for the number again. Then give a full number with its country code. The agent keeps it.
## What the code does
1. `State` is a Pydantic model. It holds what the call remembers. `Phone` is a value type from the library. It checks the number and stores it in E.164.
2. `CallState(State)` keeps one live copy of that model for the call.
3. `AgentSpec` describes the agent: its prompt, and here `save_values=True`. It reads the same on both frameworks. `save_values=True` gives the model a `save_values` tool. Each save is checked against `State`. A wrong value comes back to the model with a reason it can act on.
4. On LiveKit, `UnmuteAgent` runs the spec as a normal LiveKit `Agent`. On Pipecat, `UnmuteFlows` runs it in your pipeline. Each takes the call's state beside the spec.
5. Speech to text, the model, text to speech and turn detection stay framework plugins. SLNG's plugins carry Soniox and Fish Audio. `VOICE` is a Fish Audio voice id. On LiveKit, `stt.attach_to_session(session)` lets speech to text close each caller turn as soon as the caller stops. See [SLNG](/core/models/slng).
## Where to go next
Pick one path.
Grow this agent one piece per page: a greeting, a tool, task steps, a handoff and traces.
Keep your own LiveKit or Pipecat agent, and add only the parts you need.
# Why Unmute Core
Source: https://unmute.ai/core/start/why-unmute-core
What the library adds to a LiveKit or Pipecat agent, and when you need it.
LiveKit and Pipecat move audio, run the models and call your tools. They do not
decide how a good phone call behaves. Every team learns that from its first real
calls. unmute-core holds what we learned, so your agent starts from it.
You keep your framework, your plugins and your pipeline. The library adds one
piece or all of them.
## One call, two ways
A caller phones a salon to book a haircut. Here is what goes wrong on a plain
agent, and what the library does instead.
| The call | A plain agent | With unmute-core |
| - | - | - |
| The caller dials in and talks while the agent sets up. | That audio mixes into the first turn. | Caller audio waits until the greeting starts. |
| "My number is six one two, three four five..." | The model saves `612345` and books with it. | The save is refused because the number is not valid. The model asks again. |
| The caller pauses, then goes on. | The reply plays over them. | The reply is dropped. The next one answers everything they said. |
| "Yes" while the agent reads the times. | The agent stops mid-sentence. | The agent finishes, then answers the "yes". |
| The model says "Noted, thank you." | The step waits for a finish that never comes. | The library asks the model directly: finished, or not yet? |
| The booking tool takes 3 seconds. | Silence. | "One moment, let me check." |
| The model calls the booking tool. | It books what the model guessed. | Code asks "Shall I book Friday, October 16?" and books only what the caller heard. |
| The booking API answers with half a record. | The model tells the caller it is booked. | The answer is checked against the tool's model. The model reads which field is missing and does not claim success. |
| The caller is handed to billing. | Billing hands the call straight back. | Billing speaks first. Handoff tools wait for the caller. |
| The model provider fails. | Silence, then the line drops. | The next model answers. If none can, a short apology plays. |
| The call ends. | Each framework gives a different reason, and its own trace shape. | One reason and one trace on both frameworks. |
Each row is a few lines of code to fix, once you know it happens. Most teams
find out on a live call, one row at a time.
## Three reasons to use it
1. **One agent on both frameworks.** State, tasks, tools, prompts and traces
behave the same on LiveKit and Pipecat. 90 shared test scenarios check it on
every change. You can switch frameworks without rewriting the agent.
2. **The model cannot break your data.** Each value has a type. A save that does
not fit is refused with a reason the model can act on. Values the caller has
not confirmed stay out of the prompt.
3. **What real calls taught us, built in.** Pauses, interruptions, idle callers,
slow tools, failing providers, transfers and handoffs. Each feature page
starts with what it fixes.
## Where each part helps
| You want to | Read |
| - | - |
| Collect values the caller gives, and trust them | [State](/core/build/state) |
| Walk the caller through steps that cannot get stuck | [Tasks](/core/build/tasks) |
| Call your code and APIs safely during a call | [Tools](/core/build/tools) |
| Pass the call between agents | [Handoffs](/core/build/handoffs) |
| Open, fail and end a call well | [Call lifecycle](/core/build/call-lifecycle) |
| Know the caller before the first word | [Prefetch](/core/build/prefetch) |
| Get pauses, interruptions and quiet callers right | [Turn taking](/core/build/turn-taking) |
| Change prompts, requests and tool calls in one place | [Hooks](/core/build/hooks) |
| Answer from your documents | [Knowledge](/core/build/knowledge) |
| Keep answering when a model fails | [Model call](/core/models/model-call) |
| Transfer to a person, dial out, handle voicemail | [Telephony](/core/telephony) |
| See every call in Langfuse, Coval, Logfire or Datadog | [Telemetry](/core/observe/telemetry) |
| Spend fewer tokens, and say the same words on every call | [Type the path](/core/examples/typed-path) |
| See whole agents built this way | [Example agents](/core/examples/overview) |
## When you don't need it
* One agent on one framework, with a few tools and no values to collect.
* You already built and tested your own answers to the rows above.
Even then, you can take one piece, like [tools](/core/build/tools) or
[telemetry](/core/observe/telemetry), and add more when a call shows you need it.
# Phone calls in code
Source: https://unmute.ai/core/telephony
Take calls in, place calls out, and transfer a caller to a person, the same way on LiveKit and Pipecat.
The library reads who is calling, places outbound calls, and gives the model a tool that transfers the caller to a person. Your SIP trunk or carrier stays yours.
## Take a call in
Read the caller's number into the call's state once the call starts.
```python LiveKit theme={null}
from unmute_core.livekit import sip_call_info
participant = await ctx.wait_for_participant()
metadata = json.loads(ctx.job.metadata or "{}")
state = CallState(State, call=sip_call_info(participant, metadata))
```
```python Pipecat theme={null}
from unmute_core.pipecat import telephony_call_info
state = CallState(State, call=telephony_call_info(runner_args.call_data))
```
`state.call.calling_number` is the caller, and `state.call.called_number` is your number. On Pipecat, set the pipeline's sample rates to 8000, because a phone line carries 8 kHz audio.
## Call someone
```python LiveKit theme={null}
from unmute_core.livekit import DialError, SipLine, greet
line = SipLine(session, trunk=trunk, caller_id=os.environ["FROM_NUMBER"])
try:
answered = await line.dial(metadata["phone_number"])
except DialError:
ctx.shutdown("nobody answered")
return
if not answered.ended: # ended is True when a voicemail picked up and the call is over
greet(session, GREETING, state)
```
```xml Pipecat with Twilio theme={null}
```
On LiveKit, dispatch the job with `phone_number` in its metadata. `dial` waits until someone answers, and hangs up on a voicemail. On Pipecat, your app asks the carrier to place a call that streams to the bot. With a Daily room, call `dial_out(transport, worker, "sip:+34910000000@trunk.example")`.
## Transfer to a person
Describe where the caller goes, then give the model a tool for it. The model calls the tool with no arguments, so it never sees the number.
```python agent.py theme={null}
from unmute_core.telephony import Transfer, transfer_tool
BILLING = Transfer(
"send_to_billing",
"+34910000000",
description="Transfer the caller to billing when they ask about an invoice.",
)
tools = ToolRegistry([*my_tools, transfer_tool(BILLING, line)])
```
`line` is the call's phone line. Build one per call:
```python LiveKit theme={null}
line = SipLine(session, trunk=trunk, caller_id=os.environ["FROM_NUMBER"])
```
```python Pipecat with Twilio theme={null}
line = TwilioLine(
state.call.carrier_call_id,
account_sid=os.environ["TWILIO_ACCOUNT_SID"],
auth_token=os.environ["TWILIO_AUTH_TOKEN"],
worker=worker,
serializer=serializer, # the TwilioFrameSerializer of the transport
)
```
```python Pipecat with Telnyx theme={null}
line = TelnyxLine(
state.call.carrier_call_id,
api_key=os.environ["TELNYX_API_KEY"],
worker=worker,
serializer=serializer,
)
```
1. The tool says "Putting you through now, one moment." The caller cannot cut the transfer off.
2. On success, the call ends with the reason `transferred`.
3. When nobody answers, the model hears why and keeps helping the caller. Pass `on_unavailable="hangup"` to end the call instead.
On LiveKit Cloud, `Transfer(..., mode="warm")` calls the person first and briefs them while the caller hears hold music.
## Voicemail
```python LiveKit theme={null}
answered = await line.dial(number, on_voicemail="leave_message")
```
```python Pipecat theme={null}
from unmute_core.pipecat import voicemail_tool
tool = voicemail_tool(on_voicemail="leave_message", call=call)
flows = UnmuteFlows(..., native_tools=[tool])
```
`hangup`, the default, ends the call at once. `leave_message` has the model say a short message first.
## What each route supports
| Route | Line | Transfer | Warm transfer | Outbound call | Voicemail |
| - | - | - | - | - | - |
| LiveKit SIP, any trunk | `SipLine` | yes | yes, on LiveKit Cloud | `SipLine.dial` | `dial(on_voicemail=)` |
| Pipecat, Twilio | `TwilioLine` | yes | no | your app asks Twilio | `voicemail_tool` |
| Pipecat, Telnyx | `TelnyxLine` | yes | no | your app asks Telnyx | `voicemail_tool` |
| Pipecat, Plivo or Exotel | none | no | no | your app asks the carrier | `voicemail_tool` |
| Pipecat, Daily room over SIP | `DailySipLine` | yes | no | `dial_out` | `voicemail_tool` |
For DTMF and IVR, use the framework's own tools: `GetDtmfTask` on LiveKit, `IVRNavigator` on Pipecat.
## Where to go next
Every argument, each route in detail, and warm transfers.
Opening, greeting and ending the call.
Give the call to another agent instead of a person.
The `agent.yaml` side of transfers and escalations.
# Answer the phone
Source: https://unmute.ai/core/tutorial/answer-the-phone
Build the smallest salon agent: a prompt, a greeting and a call you can talk to.
The caller phones the salon, and Robin says hello.
## What you add
The prompt and the greeting go in the shared package. Both frameworks read them.
```python salon/agent.py theme={null}
from unmute_core.greeting import Greeting
GREETING = Greeting(
text="Hi, you've reached Sage and Stone. Robin speaking, what can I do for you?"
)
CONCIERGE_PROMPT = """\
You are Robin, on the front desk at Sage and Stone, a hair salon.
Speak only in English. Everything you write is read aloud, so write plain
sentences with no lists and no symbols. Keep every reply short.
Help the caller book a haircut, a hair colour or a blowout.
"""
```
`Greeting(text=...)` is a fixed line. Code says it at once, so the caller does not wait for a model request.
Now build the pipeline around it. This is the base you will grow.
```python livekit/agent.py theme={null}
import os
from livekit.agents import AgentServer, AgentSession, JobContext
from livekit.plugins import openai, silero, slng
from salon import agent as salon
from unmute_core.agent import AgentSpec
from unmute_core.livekit import UnmuteAgent, greet
SLNG_KEY = os.environ["SLNG_API_KEY"]
SLNG_HOST = f"{os.environ['SLNG_WORLD_PART']}.api.slng.ai"
VOICE = "8d8aec63a56c460cb7def795bdf754fa"
server = AgentServer()
@server.rtc_session()
async def entrypoint(ctx: JobContext) -> None:
"""Run one call: start Robin, then say the greeting."""
stt = slng.STT(
api_key=SLNG_KEY, slng_base_url=SLNG_HOST, model="soniox/speech-ai:rt-v5", language="en"
)
session = AgentSession(
stt=stt,
llm=openai.LLM(model="gpt-5.6-terra"),
tts=slng.TTS(
api_key=SLNG_KEY,
slng_base_url=SLNG_HOST,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language="en",
),
vad=silero.VAD.load(),
)
stt.attach_to_session(session)
spec = AgentSpec(salon.CONCIERGE_PROMPT)
agent = UnmuteAgent(spec)
await session.start(agent=agent, room=ctx.room)
greet(session, salon.GREETING, None)
```
```python pipecat/bot.py theme={null}
import os
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.frames.frames import LLMUpdateSettingsFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.worker import PipelineWorker
from pipecat.processors.aggregators.llm_context import LLMContext
from pipecat.processors.aggregators.llm_response_universal import (
LLMContextAggregatorPair,
LLMUserAggregatorParams,
)
from pipecat.runner.types import RunnerArguments
from pipecat.runner.utils import create_transport
from pipecat.services.openai.llm import OpenAILLMService
from pipecat.services.settings import LLMSettings
from pipecat.transcriptions.language import Language
from pipecat.transports.base_transport import TransportParams
from pipecat.workers.runner import WorkerRunner
from pipecat_slng import SlngSTTService, SlngTTSService
from salon import agent as salon
from unmute_core.agent import AgentSpec
from unmute_core.pipecat import UnmuteFlows, greeting_frames
SLNG_KEY = os.environ["SLNG_API_KEY"]
WORLD_PART = os.environ["SLNG_WORLD_PART"]
VOICE = "8d8aec63a56c460cb7def795bdf754fa"
transport_params = {
"webrtc": lambda: TransportParams(audio_in_enabled=True, audio_out_enabled=True),
}
async def bot(runner_args: RunnerArguments) -> None:
"""Run one call: start Robin, then say the greeting."""
transport = await create_transport(runner_args, transport_params)
llm = OpenAILLMService(settings=OpenAILLMService.Settings(model="gpt-5.6-terra"))
context = LLMContext()
aggregators = LLMContextAggregatorPair(
context, user_params=LLMUserAggregatorParams(vad_analyzer=SileroVADAnalyzer())
)
spec = AgentSpec(salon.CONCIERGE_PROMPT)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators)
flows.install()
pipeline = Pipeline(
[
transport.input(),
SlngSTTService(
api_key=SLNG_KEY,
world_part=WORLD_PART,
model="soniox/speech-ai:rt-v5",
language=Language.EN,
),
aggregators.user(),
llm,
SlngTTSService(
api_key=SLNG_KEY,
world_part=WORLD_PART,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language=Language.EN,
),
transport.output(),
aggregators.assistant(),
]
)
worker = PipelineWorker(pipeline)
@transport.event_handler("on_client_connected")
async def greet(transport, client) -> None:
"""Set the prompt, then say the greeting."""
await worker.queue_frames(
[
LLMUpdateSettingsFrame(
delta=LLMSettings(system_instruction=flows.main_instruction())
),
*greeting_frames(salon.GREETING, None),
]
)
runner = WorkerRunner(handle_sigint=runner_args.handle_sigint)
await runner.add_workers(worker)
await runner.run()
if __name__ == "__main__":
from pipecat.runner.run import main
main()
```
The agent hears the caller through SLNG's Soniox speech to text and speaks with SLNG's Fish Audio text to speech. `VOICE` is a Fish Audio voice id. On LiveKit, `stt.attach_to_session(session)` lets speech to text close each caller turn as soon as the caller stops.
`AgentSpec` describes the agent, the same way on both frameworks. For now it holds only the prompt, as plain text. `UnmuteAgent` runs it as a LiveKit `Agent`. `UnmuteFlows` runs it in a normal Pipecat pipeline. The `None` is the call state, which you add on the next page.
## Try it
Set your keys, then start the agent. `SLNG_WORLD_PART` is your SLNG project's region.
```bash LiveKit theme={null}
export SLNG_API_KEY=... SLNG_WORLD_PART=eu-north OPENAI_API_KEY=...
lk agent console agent.py # talk through your microphone
lk agent console --text agent.py # or type
```
```bash Pipecat theme={null}
export SLNG_API_KEY=... SLNG_WORLD_PART=eu-north OPENAI_API_KEY=...
uv run bot.py -t webrtc # then open http://localhost:7860
```
You should hear the greeting at once. Say "I'd like a haircut on Friday." Robin answers in one or two short sentences and asks what it needs. It cannot check a diary yet.
## Why it works this way
A plain agent usually asks the model to word the first line, and the caller waits for that request. The greeting here is code, so it plays at once.
You still own the session, the pipeline and every plugin. `UnmuteAgent` and `UnmuteFlows` add the call behaviour on top. The next pages use them for state, tools, tasks and handoffs.
## What you have now
| Piece | File |
| - | - |
| Prompt and greeting | `salon/agent.py` |
| LiveKit pipeline | `livekit/agent.py` |
| Pipecat pipeline | `pipecat/bot.py` |
Keep the caller's number, and refuse a number that cannot be right.
Go deeper: [Call lifecycle](/core/build/call-lifecycle), [LiveKit](/core/frameworks/livekit) and [Pipecat](/core/frameworks/pipecat).
# Book step by step
Source: https://unmute.ai/core/tutorial/book-step-by-step
Turn booking into a task and a group, so the agent verifies the caller and asks before it writes to the diary.
You have: a typed diary tool, from [Check the diary](/core/tutorial/check-the-diary).
The caller picks a time, the agent asks "Shall I book it?", and the diary changes only after a yes.
## What you add
A task is a step with its own prompt, its own tools and a finish check. The model does not have to remember the order. Code runs it.
First, the state needs the values the steps save. Add these fields to `State`.
```python salon/state.py theme={null}
from datetime import date, time
from unmute_core.state import Id
class Appointment(BaseModel):
"""The latest booking that was created, moved or cancelled."""
booking_id: Id
service: Literal["haircut", "hair-color", "blowout"]
date: date
time: time
class State(BaseModel):
# customer_phone and requested_service stay as they were. Add:
appointment: Appointment | None = None
customer_verified: str = ""
requested_day: date | None = None
requested_intent: Literal["book", "move", "cancel"] | None = None
```
Next, add the other two diary methods to the registry from the last page.
```python salon/agent.py theme={null}
local_tool(
salon.find_or_create_customer,
output=Customer,
description="Look up or create the customer.",
),
local_tool(
salon.book_appointment,
output=BookingAction,
locked=LOCKED_PHONE,
description="Book a free time.",
),
```
`Customer` and `BookingAction` are the answers' models, in `salon/store.py`. A
booking's answer holds its `appointment`, typed as the `Appointment` above.
### One task: verify the caller
`verify_customer` reads the number from the state, asks the caller to confirm it, and saves the result.
```python salon/agent.py theme={null}
CONFIRM = {"customer_phone": "verify_customer"}
VERIFY_CUSTOMER = {
"name": "verify_customer",
"when": "Run this when the caller gives or corrects their phone number.",
"instructions": "Ask for the number if none is saved. Read it back and wait for a yes.",
"opening": "listen",
"announce": ["Sure, what's the best number to reach you on?"],
"opens_with": {"tool": "find_or_create_customer", "arguments": {"phone": "customer_phone"}},
"tools": ["find_or_create_customer"],
"finish": [
{
"tool": "find_or_create_customer",
"success": {"status": ["existing", "created"]},
"confirm": ["Is the best number to reach you {{input.phone}}?"],
}
],
"assign": [
{"variable": "customer_phone", "path": ["customer_phone"]},
{"variable": "customer_verified", "path": ["status"]},
],
}
```
1. `when` tells the model when to start the task. The library turns the task into a tool, `verify_customer`.
2. With `opening` set to `listen`, a step with no saved number says its `announce` line and waits for the caller.
3. When a number is saved, `opens_with` and `confirm` work together. Code asks the `confirm` line. The tool runs only when the model calls it again after the caller heard the question and said yes.
4. `assign` copies fields from the tool result into the state. This is the step that confirms `customer_phone`, as `CONFIRM` says.
### A group: verify, then book
`manage_booking` finds a time and books it. The `book` group runs both steps in order.
```python salon/agent.py theme={null}
from unmute_core.tasks import TaskPlan, TasksSpec
MANAGE_BOOKING = {
"name": "manage_booking",
"instructions": "Offer free times with find_slots, then book the one the caller picks.",
"announce": ["Let me have a look."],
"tools": ["find_slots", "book_appointment"],
"finish": [
{
"tool": "book_appointment",
"success": {"status": ["booked"]},
"confirm": ["Shall I book your {{input.service}} for {{input.date}} at {{input.time}}?"],
"say": [
"Lovely, your {{result.appointment.service}} is booked for "
"{{result.appointment.date}} at {{result.appointment.time}}. Anything else?"
],
}
],
"assign": [{"variable": "appointment", "path": ["appointment"]}],
"history": "messages",
}
CONCIERGE_TASKS = TasksSpec.model_validate(
{
"mode": "record",
"tasks": [VERIFY_CUSTOMER, MANAGE_BOOKING],
"groups": [
{
"name": "book",
"when": "The caller wants to book a time.",
"steps": ["verify_customer", "manage_booking"],
"context_scope": "shared",
"skip_when_confirmed": {"verify_customer": "customer_phone"},
"arguments": ["requested_service", "requested_day", "requested_intent"],
}
],
"task_only_tools": ["find_or_create_customer", "find_slots", "book_appointment"],
}
)
def concierge_plan(registry: ToolRegistry) -> TaskPlan:
"""Return the concierge's checked plan, on the diary's tools."""
return TaskPlan(CONCIERGE_TASKS, state=State, confirm=CONFIRM, tools=registry)
```
1. `skip_when_confirmed` skips `verify_customer` when the number is already confirmed.
2. `arguments` are values the model passes when it starts the group. They are saved into the state.
3. `task_only_tools` hides the diary tools from the main agent. Only the steps call them.
4. `say` is a line code speaks after the save. The model makes no request to confirm it. Its values are said by their type in `Appointment`: the service as words, the day from today, the time on the clock. The caller hears "Lovely, your hair color is booked for tomorrow, October 16 at 9:00 AM."
5. `TasksSpec` and `TaskPlan` check everything at startup. A wrong tool name stops the agent before any call.
Add to the prompt: "Every booking request goes to `book`. Never ask for the number yourself."
Last, give the spec the plan instead of the tools, and the salon's timezone. Build the `CallState` with `confirm=CONFIRM`.
```python livekit/agent.py theme={null}
from salon.store import TIMEZONE
PLAN = salon.concierge_plan(salon.tools(Salon()))
# In entrypoint(), use the plan in place of tools.
state = CallState(State, confirm=salon.CONFIRM)
spec = AgentSpec(salon.CONCIERGE_PROMPT, tasks=PLAN, timezone=TIMEZONE)
agent = UnmuteAgent(spec, state=state)
```
```python pipecat/bot.py theme={null}
from salon.store import TIMEZONE
PLAN = salon.concierge_plan(salon.tools(Salon()))
# In bot(), use the plan in place of tools.
state = CallState(State, confirm=salon.CONFIRM)
spec = AgentSpec(salon.CONCIERGE_PROMPT, tasks=PLAN, timezone=TIMEZONE)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
```
## Try it
Start the agent as before.
1. "I'd like a haircut on Friday." Robin starts `book`.
2. Robin asks for your number, then reads it back. Say yes.
3. Robin offers free times. Pick one.
4. Robin asks "Shall I book your haircut for ...?" Say yes. Robin says the booking line and asks what else.
## Why it works this way
On a plain agent the model decides the order, so it can skip a check or write to the diary on a guess. Here the order is code. A write waits for the caller's yes, and the saved number is confirmed by the step that asked.
The step also cannot get stuck. When the model says "Noted" and no finish check passes, the library asks it directly: finished, or not yet?
## What you have now
| Piece | File |
| - | - |
| State with booking values | `salon/state.py` |
| Tools, `VERIFY_CUSTOMER`, `CONCIERGE_TASKS` | `salon/agent.py` |
| Pipelines, with the plan | `livekit/agent.py`, `pipecat/bot.py` |
Add a second agent for complaints, and a handoff to it.
Go deeper: [Tasks](/core/build/tasks).
# Check the diary
Source: https://unmute.ai/core/tutorial/check-the-diary
Give the salon agent a typed tool that reads the diary, and say a line while it runs.
You have: a call state that keeps the caller's number, from [Remember the caller](/core/tutorial/remember-the-caller).
The caller asks for Friday, and the agent reads the diary.
## What you add
The diary is a plain Python class, `Salon`, in `salon/store.py`. It keeps customers and bookings in memory. Copy the file from the example. You do not write it here.
Each method is typed, and each argument says what it means. Each answer has a
Pydantic model too. This is the shape of `find_slots` and its answer, `Diary`.
```python salon/store.py theme={null}
from datetime import date
from typing import Annotated, Literal
from pydantic import BaseModel, Field
DayArgument = Annotated[
date | None,
Field(description="The day the caller named. Leave it out when they named none."),
]
ServiceArgument = Annotated[
Literal["any", "haircut", "hair-color", "blowout"],
Field(description="Narrow the free times to one service, or `any` to see all three."),
]
class Diary(BaseModel):
"""What find_slots returns: the caller's bookings, the free times, and the offer."""
bookings: list[Held]
slots: list[Slot]
status: Literal["need_date", "ok", "invalid_service", "invalid_date", "full"]
offer: str = ""
offered: bool = False
class Salon:
def find_slots(
self,
customer_phone: str,
date: DayArgument = None,
service: ServiceArgument = "any",
) -> dict:
"""Return the caller's bookings and the free slots on a date."""
```
Now turn the method into a tool. `local_tool` reads the types and the descriptions and builds the tool schema. A `ToolRegistry` holds the tools of one agent.
```python salon/agent.py theme={null}
from salon.store import Diary, Salon
from unmute_core.tools import ToolRegistry, local_tool
LOCKED_PHONE = {"customer_phone": "{{customer_phone}}"}
def tools(salon: Salon) -> ToolRegistry:
"""Return the agent's tools, on one diary."""
return ToolRegistry(
[
local_tool(
salon.find_slots,
output=Diary,
locked=LOCKED_PHONE,
announce="Let me have a look.",
description=(
"Read the diary: what the caller already has booked, and what times "
"are free. Ask the caller which day they want before you call this, "
"and never guess one."
),
),
]
)
```
Three options matter here.
1. `output` names the answer's model. The method returns a dict, so it names the model here. A method that returns a `Diary` needs no `output=`. Every answer is checked against it, and an answer of the wrong shape fails the call.
2. `locked` fills `customer_phone` from the call state. The model never sees that argument, so it cannot invent a number. While no number is saved, the call is refused with a hint.
3. `announce` is a line the agent says as the tool starts. A refused call says nothing.
Last, give the registry to the agent. Build it once, not for each call.
```python livekit/agent.py theme={null}
from salon import agent as salon
from salon.store import Salon
TOOLS = salon.tools(Salon())
# In entrypoint(), add the tools to the spec.
spec = AgentSpec(salon.CONCIERGE_PROMPT, tools=TOOLS, save_values=True)
agent = UnmuteAgent(spec, state=state)
```
```python pipecat/bot.py theme={null}
from salon import agent as salon
from salon.store import Salon
TOOLS = salon.tools(Salon())
# In bot(), add the tools to the spec.
spec = AgentSpec(salon.CONCIERGE_PROMPT, tools=TOOLS, save_values=True)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
```
## Try it
Start the agent as before.
1. "I'd like a haircut on Friday." Robin has no number yet, so the tool is refused. Robin should ask for your number.
2. Give a number with its country code. Then say "Friday" again.
3. You should hear "Let me have a look." Then Robin should read out free times from the diary.
The demo diary offers 9:00 AM, 11:30 AM and 3:00 PM for each service.
## Why it works this way
The model fills tool arguments from what it heard. It can mishear or invent a value. So the library checks every call against the schema before your code runs, and a bad one goes back to the model with what to fix.
A value the caller never chooses, like the number of the person on the line, comes from the state instead. And a slow tool is not silence, because the announce line plays first.
## What you have now
| Piece | File |
| - | - |
| Prompt and greeting | `salon/agent.py` |
| Call state: `State` | `salon/state.py` |
| The diary: `Salon` | `salon/store.py` |
| Tools: `tools()` | `salon/agent.py` |
| LiveKit and Pipecat pipelines | `livekit/agent.py`, `pipecat/bot.py` |
Turn booking into a task, so Robin confirms before it writes.
Go deeper: [Tools](/core/build/tools).
# Hand off complaints
Source: https://unmute.ai/core/tutorial/hand-off-complaints
Add a complaint specialist agent, and a handoff tool that moves the caller to it and back.
You have: a booking task and group, from [Book step by step](/core/tutorial/book-step-by-step).
The caller says a colour went wrong, and a specialist takes the complaint down.
## What you add
Two agents share one call. The concierge books. The complaint specialist records complaints. Both read and write the same `CallState`.
In the shared package, add the specialist's tool, prompt and plan. Robin stays the name the caller hears.
```python salon/agent.py theme={null}
SPECIALIST_PROMPT = """\
You are still Robin, the same person the caller was talking to. Listen to the
complaint, say sorry for the trouble, and write down the useful facts.
Everything you write is read aloud, so write plain sentences.
Verification so far: {{customer_verified}}.
"""
TO_COMPLAINTS = "The caller has a complaint or service problem."
TO_COMPLAINTS_LINE = "I'm sorry to hear that. Let me take this down properly."
TO_CONCIERGE = "The caller changes to a request owned by another specialist."
```
Add `record_complaint` to the registry in `tools()`. It uses the same locked number and an announce line. `ComplaintRecord` is its answer's model, in `salon/store.py`.
```python salon/agent.py theme={null}
local_tool(
salon.record_complaint,
output=ComplaintRecord,
locked=LOCKED_PHONE,
announce="Let me get that written down.",
description="Record the verified customer's complaint after enough facts are known.",
),
```
Then replace `concierge_plan` with `agents`. It returns both agents as `AgentSpec`s, the same on LiveKit and Pipecat. Their plans share one set of tools, and `registry.only(...)` gives each agent the tools it may use. Each agent names itself, so a `handoff` event shows which one holds the call.
```python salon/agent.py theme={null}
from typing import NamedTuple
from unmute_core.agent import AgentSpec
from salon.store import TIMEZONE
SPECIALIST_TASKS = TasksSpec.model_validate(
{
"mode": "record",
"tasks": [VERIFY_CUSTOMER],
"task_only_tools": ["find_or_create_customer"],
}
)
CONCIERGE_TOOLS = ("find_or_create_customer", "find_slots", "book_appointment")
SPECIALIST_TOOLS = ("record_complaint", "find_or_create_customer")
class Agents(NamedTuple):
"""The call's two main agents, the same on LiveKit and Pipecat."""
concierge: AgentSpec
specialist: AgentSpec
def agents(salon: Salon) -> Agents:
"""Return both agents, on one diary. Build them once per process."""
registry = tools(salon)
concierge = TaskPlan(
CONCIERGE_TASKS, state=State, confirm=CONFIRM, tools=registry.only(CONCIERGE_TOOLS)
)
specialist = TaskPlan(
SPECIALIST_TASKS, state=State, confirm=CONFIRM, tools=registry.only(SPECIALIST_TOOLS)
)
return Agents(
concierge=AgentSpec(CONCIERGE_PROMPT, name="concierge", tasks=concierge, timezone=TIMEZONE),
specialist=AgentSpec(
SPECIALIST_PROMPT, name="complaint_specialist", tasks=specialist, timezone=TIMEZONE
),
)
```
The specialist reuses `VERIFY_CUSTOMER`, so a complaint is written down only for a verified customer.
Both agents answer on the framework's own LLM, so neither spec has a model. They hold nothing of one call, so you build them once. A spec whose model reads the call, like the SLNG router, is built per call, after the state.
Now run the two agents. A handoff is a tool the model calls. It returns the next agent.
```python livekit/agent.py theme={null}
from livekit.agents import function_tool
CONCIERGE, SPECIALIST = salon.agents(Salon())
class Concierge(UnmuteAgent):
"""Books appointments."""
def __init__(self, state: CallState[State]) -> None:
"""Build the concierge for one call."""
super().__init__(CONCIERGE, state=state)
@function_tool
async def to_complaints(self) -> UnmuteAgent | str:
"""The caller has a complaint or service problem."""
return await self.hand_off(
ComplaintSpecialist(self.state), announce=salon.TO_COMPLAINTS_LINE
)
class ComplaintSpecialist(UnmuteAgent):
"""Takes a complaint down."""
def __init__(self, state: CallState[State]) -> None:
"""Build the complaint specialist. It records into the concierge's spans."""
super().__init__(SPECIALIST, state=state)
@function_tool
async def to_concierge(self) -> UnmuteAgent | str:
"""The caller changes to a request owned by another specialist."""
return await self.hand_off(Concierge(self.state))
```
```python pipecat/bot.py theme={null}
from pipecat.adapters.schemas.function_schema import FunctionSchema
from pipecat.services.llm_service import FunctionCallParams
CONCIERGE, SPECIALIST = salon.agents(Salon())
def salon_flows(state, llm, context, aggregators) -> UnmuteFlows:
"""Return the call's agents: the concierge first, the specialist a handoff away."""
def handoff(name, description, to, tools, announce=None) -> FunctionSchema:
"""Return a tool that hands the call to ``to``, with the Pipecat tools ``tools()`` gives."""
async def handler(params: FunctionCallParams) -> None:
"""Give the call to the other agent."""
await flows.hand_off(params, to, native_tools=tools(), announce=announce)
return FunctionSchema(name, description, {}, [], handler=handler)
concierge_tools = [
handoff(
"to_complaints",
salon.TO_COMPLAINTS,
SPECIALIST,
lambda: specialist_tools,
salon.TO_COMPLAINTS_LINE,
)
]
specialist_tools = [
handoff("to_concierge", salon.TO_CONCIERGE, CONCIERGE, lambda: concierge_tools)
]
flows = UnmuteFlows(
CONCIERGE,
llm=llm,
context=context,
aggregators=aggregators,
state=state,
native_tools=concierge_tools,
)
flows.install()
return flows
```
In `entrypoint()` and `bot()`, start `Concierge(state)` or `salon_flows(...)` in place of the single agent. Add to the concierge prompt: "A complaint or a refund goes to `to_complaints`."
## Try it
Start the agent as before and book a haircut. Then say "My last colour went wrong, I want to complain."
1. Robin says "I'm sorry to hear that. Let me take this down properly." The caller cannot cut that line off.
2. The specialist speaks next. It is still Robin to the caller.
3. Describe the problem. The specialist verifies your number if needed, says "Let me get that written down", and records it.
## Why it works this way
Each agent is its own `AgentSpec`, with its own prompt and its own tools. The specialist cannot book, and the concierge cannot write a complaint. Both share one call state, so the number the caller confirmed is not asked for again.
A plain handoff often lets the next agent hand the call straight back, or lets it start before the caller heard the line. Here the line plays first, and the next agent speaks first.
## What you have now
| Piece | File |
| - | - |
| The specialist's prompt, tool and plan, and `agents()` | `salon/agent.py` |
| Agents and handoff tools | `livekit/agent.py`, `pipecat/bot.py` |
Read today's date and the caller's number before the greeting.
Go deeper: [Handoffs](/core/build/handoffs).
# Know the time before hello
Source: https://unmute.ai/core/tutorial/know-the-time
Read today's date on the salon's clock and the caller's number before the greeting, with Prefetch.
You have: Robin with a concierge and a complaint specialist, from [Hand off complaints](/core/tutorial/hand-off-complaints).
The caller says "Friday", and the agent knows which Friday.
## What you add
A model does not know today's date, and a server clock may be in another time zone. `Prefetch` reads what the call needs before the greeting and saves it into the state.
First, three more state fields for the clock.
```python salon/state.py theme={null}
class State(BaseModel):
# The fields from the earlier pages stay. Add:
booking_date: date | None = Field(
None, description="Today's date in the salon's timezone, read once before the greeting."
)
booking_weekday: str = Field("", description="The weekday of booking_date, in English.")
salon_local_time: time | None = Field(
None, description="The salon's wall clock when the call began."
)
```
Next, the prefetch and the function that builds each call's state. These are the names the example uses.
```python salon/agent.py theme={null}
from collections.abc import Mapping
from unmute_core.call import save_call_start
from unmute_core.prefetch import CallValue, Clock, Prefetch
from unmute_core.state import CallInfo, CallState
AGENT_ID = "salon-concierge"
PREFETCH = Prefetch(
[
Clock(
"today",
"Europe/Madrid",
{"booking_date": "date", "booking_weekday": "day_of_week", "salon_local_time": "time"},
),
CallValue("caller", "calling_number", ["customer_phone"]),
]
)
GREETING.check(PREFETCH)
async def new_call(
call: CallInfo | None = None, dispatched: Mapping[str, object] | None = None
) -> CallState[State]:
"""Return a fresh call state, with today's date and the caller's number read in.
Args:
call: What the line carries. A web call's when None.
dispatched: The dispatch's ``call_start`` object, when there is one.
"""
state = CallState(State, confirm=CONFIRM, call=call or CallInfo(agent_id=AGENT_ID))
save_call_start(state, dispatched)
await PREFETCH.run(state)
return state
```
1. `Clock` reads one time zone, once. Its `assign` maps each state value to a clock field: `date`, `day_of_week` or `time`.
2. `CallValue` copies a value the call carries, here the caller's number from `state.call.calling_number`, into `customer_phone`. A browser call has no number, so that value stays empty.
3. `save_call_start` saves what the call was started with. It also reads `UNMUTE_CALL_START`, so a browser call can pretend to be a phone call.
4. `GREETING.check(PREFETCH)` refuses, at import, a greeting that names a value prefetch does not fill.
The number from caller ID is saved but not confirmed. It stays out of the prompts until `verify_customer` has read it back and the caller said yes.
Then tell the concierge what day it is. Add this line to `CONCIERGE_PROMPT`.
```text theme={null}
Today is {{booking_weekday}}, {{booking_date}}, so "Friday" is the coming Friday.
```
Last, build the state with `new_call` where you built it by hand before.
```python livekit/agent.py theme={null}
# In entrypoint(), before the session starts.
state = await salon.new_call()
```
```python pipecat/bot.py theme={null}
# In bot(), in place of CallState(State, confirm=salon.CONFIRM).
state = await salon.new_call()
```
A console or browser call has no caller ID, so `state.call` has no number. On a phone call, `unmute_core.livekit.sip_call_info` and `unmute_core.pipecat.telephony_call_info` read it from the carrier. Pass the result as `call`. [Telephony](/core/telephony) shows how.
## Try it
To try the caller ID path, simulate a phone caller, then start the agent.
```bash theme={null}
export UNMUTE_CALL_START='{"call": {"direction": "inbound", "calling_number": "+34612345678"}}'
```
1. Say "Can I book a haircut for Friday?" Robin should offer times on the coming Friday, with no question about today's date.
2. When Robin asks for your number, it should read back the one from caller ID and wait for a yes.
## Why it works this way
The model reads today's date from the state, so a call that starts at 11 pm in Madrid still gets Madrid's date. The value is read once. A call that crosses midnight keeps the day it began on.
Prefetch runs before the greeting. The first model request then has the date, and no tool call is spent to fetch it.
## What you have now
| Piece | File |
| - | - |
| State with the clock values | `salon/state.py` |
| `PREFETCH` and `new_call` | `salon/agent.py` |
| A call built with `new_call` | `livekit/agent.py`, `pipecat/bot.py` |
Set the turn pace, nudge a quiet caller and end a long call.
Go deeper: [Prefetch](/core/build/prefetch).
# Build a salon agent
Source: https://unmute.ai/core/tutorial/overview
Build one phone agent for a hair salon, one piece at a time, on LiveKit or Pipecat.
You will build one agent, step by step. It answers the phone for a hair salon called Sage and Stone. Each page adds one piece of unmute-core and ends with a call you can try.
The last page maps your code to a real example in the repository. CI runs that example on every change.
## The call
A caller phones the salon. The agent, Robin, answers.
1. The caller asks for a haircut on Friday. Robin checks the diary and offers times.
2. The caller gives their phone number. Robin saves it, reads it back and waits for a yes.
3. The caller picks a time. Robin asks "Shall I book it?" and books only after the caller agrees.
4. The caller says a colour went wrong. Robin hands the call to a complaint specialist, who takes it down.
5. The caller says goodbye. Robin says goodbye and hangs up.
## The finished agent
```mermaid theme={null}
flowchart TD
C[Caller] --> F[Your LiveKit or Pipecat pipeline]
F --> R[Concierge: Robin]
R -->|complaint| S[Complaint specialist]
R --> T[Tools: the salon diary]
R --> K[Tasks: verify the caller, book]
P[Prefetch: today and caller number] --> ST[Call state]
ST --- R
ST --- S
R --> L[Langfuse trace]
```
The agent lives in one framework-neutral package, `salon/`. It imports only unmute-core. The LiveKit file and the Pipecat file build the pipeline around it.
## What you need
* Python 3.12 and [uv](https://docs.astral.sh/uv/).
* An SLNG API key and its region, for speech. The pages use SLNG's Soniox speech to text and Fish Audio text to speech.
* An OpenAI API key for the model. Any LLM plugin works.
* For LiveKit, the [`lk` CLI](https://docs.livekit.io/home/cli/). Console mode needs no LiveKit server.
* For Pipecat, nothing more. The Pipecat runner serves a test page on your machine.
* Optional, for the last step: Langfuse keys.
Install the library with the extra for your framework.
```bash LiveKit theme={null}
uv add "unmute-core[livekit]" livekit-plugins-openai livekit-plugins-silero livekit-plugins-slng
```
```bash Pipecat theme={null}
uv add "unmute-core[pipecat]" "pipecat-ai[openai,runner,silero,webrtc]" pipecat-slng
```
## The files you will grow
```text theme={null}
salon-agent/
salon/
pyproject.toml
src/salon/
state.py what one call remembers
store.py the demo diary, copied from the example
agent.py prompt, tools, tasks, prefetch, idle nudges
livekit/
pyproject.toml
agent.py the LiveKit pipeline
pipecat/
pyproject.toml
bot.py the Pipecat pipeline
```
Package the `salon/` folder like the example does, and add it to each framework project as a path dependency. Copy the three `pyproject.toml` files from `examples/salon-concierge-unmute/` and keep only what you use. `store.py` is plain Python with no framework in it, so copy it too.
Code in `salon/` has no framework in it, so it has no tabs. Where LiveKit and Pipecat differ, a page shows one tab for each.
## The nine steps
| Step | You add |
| - | - |
| [Answer the phone](/core/tutorial/answer-the-phone) | The smallest agent, with a prompt and a greeting |
| [Remember the caller](/core/tutorial/remember-the-caller) | Call state, with a phone number that is checked |
| [Check the diary](/core/tutorial/check-the-diary) | A typed tool the model can call |
| [Book step by step](/core/tutorial/book-step-by-step) | A task and a group that cannot get stuck |
| [Hand off complaints](/core/tutorial/hand-off-complaints) | A second agent and the handoff to it |
| [Know the time](/core/tutorial/know-the-time) | Today's date and the caller's number, read before hello |
| [Quiet callers](/core/tutorial/quiet-callers) | Turn pace, idle nudges and a call time limit |
| [See every call](/core/tutorial/see-every-call) | One Langfuse trace per call |
| [What you built](/core/tutorial/what-you-built) | Your code next to the full example |
The smallest agent that picks up and says hello.
# Quiet callers and long calls
Source: https://unmute.ai/core/tutorial/quiet-callers
Set the turn pace, nudge a caller who goes quiet, end a long call, and let the agent hang up when the caller says goodbye.
You have: Robin that knows the date and the caller's number, from [Know the time](/core/tutorial/know-the-time).
The caller goes quiet, and the agent checks they are still there, then lets them go.
## What you add
All the settings live in the shared package, so both frameworks use the same ones.
```python salon/agent.py theme={null}
from unmute_core.idle import IdleNudges
PACE = "balanced"
IDLE = IdleNudges(
first_nudge_delay_seconds=20,
first_nudge_text="Are you still there?",
second_nudge_delay_seconds=15,
second_nudge_text="I'm still here whenever you're ready.",
hangup_delay_seconds=10,
final_hangup_text="I'll let you go for now. Call us back any time. Goodbye.",
)
MAX_DURATION_S = 900
END_CALL = (
'End the call once the caller\'s own words say the call is over: "no, that\'s all", '
'"I\'m good, thanks", "goodbye". A question is never one of those. Answer what they '
"asked and wait for them to say they are done."
)
SAY_GOODBYE_WITH_THE_CALL = (
"In the same reply as this call, and before it, say one short goodbye in your own words."
)
GOODBYE_LINE = "Thanks for calling. Goodbye."
```
1. `PACE` is one of `snappy`, `balanced` or `patient`. It says how long the agent waits after the caller pauses.
2. `IdleNudges` is a quiet caller's script: a nudge after 20 seconds, a second after 15 more, and a hang-up after 10 more. Code says these lines. The model is not asked.
3. `MAX_DURATION_S` is the longest a call may run. Here it is 15 minutes.
4. `END_CALL` is what the model reads about when to hang up. The example's text names a real failure: a tired question must not end the call.
Now wire them into each framework. The turn window turns the pace into that framework's own timing.
```python livekit/agent.py theme={null}
from livekit.agents import TurnHandlingOptions
from livekit.agents.beta.tools import EndCallTool
from livekit.agents.voice import room_io
from unmute_core.livekit import endpointing, idle_nudges, interruption, max_duration
from unmute_core.turn import turn_window
WINDOW = turn_window(salon.PACE, "livekit")
VAD = silero.VAD.load(min_silence_duration=WINDOW.vad_silence)
def end_call() -> EndCallTool:
"""Return LiveKit's end-call tool, with the salon's wording."""
return EndCallTool(
extra_description=f"{salon.END_CALL}\n{salon.SAY_GOODBYE_WITH_THE_CALL}",
end_instructions=None,
delete_room=False,
)
# In entrypoint(): build the session with the window, nudge a quiet caller,
# hang up by closing the room, and start the call timer after the greeting.
stt = slng.STT(
api_key=SLNG_KEY, slng_base_url=SLNG_HOST, model="soniox/speech-ai:rt-v5", language="en"
)
session = AgentSession(
stt=stt,
llm=openai.LLM(model="gpt-5.6-terra"),
tts=slng.TTS(
api_key=SLNG_KEY,
slng_base_url=SLNG_HOST,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language="en",
),
vad=VAD,
turn_handling=TurnHandlingOptions(
endpointing=endpointing(WINDOW), interruption=interruption("keep")
),
user_away_timeout=None,
)
stt.attach_to_session(session)
idle_nudges(session, salon.IDLE)
await session.start(
agent=agent, room=ctx.room, room_options=room_io.RoomOptions(delete_room_on_close=True)
)
greet(session, salon.GREETING, state)
max_duration(session, salon.MAX_DURATION_S)
# In both agents, add the tool: super().__init__(..., native_tools=[end_call()]).
```
```python pipecat/bot.py theme={null}
from pipecat.audio.turn.smart_turn.local_smart_turn_v3 import LocalSmartTurnAnalyzerV3
from pipecat.turns.user_stop import TurnAnalyzerUserTurnStopStrategy
from unmute_core.pipecat import (
IdleNudgeObserver,
end_call_tool,
interruption,
max_duration,
smart_turn_params,
vad_params,
)
from unmute_core.turn import turn_window
WINDOW = turn_window(salon.PACE, "pipecat")
# In bot(): build the user aggregator with the window.
aggregators = LLMContextAggregatorPair(
context,
user_params=LLMUserAggregatorParams(
vad_analyzer=SileroVADAnalyzer(params=vad_params(WINDOW)),
user_turn_strategies=interruption(
"keep",
stop=[
TurnAnalyzerUserTurnStopStrategy(
turn_analyzer=LocalSmartTurnAnalyzerV3(params=smart_turn_params(WINDOW))
)
],
),
),
)
# In salon_flows(): the end-call tool goes in both agents' native_tools lists.
ending = end_call_tool(
f"{salon.END_CALL}\n{salon.SAY_GOODBYE_WITH_THE_CALL}",
salon.GOODBYE_LINE,
lambda: flows.reply_text,
)
# In bot(): nudge a quiet caller, and start the call timer in the greet handler.
worker.add_observer(IdleNudgeObserver(salon.IDLE, worker))
max_duration(worker, salon.MAX_DURATION_S)
```
The model says its goodbye in the same reply as the end-call tool. The call then ends after one model request.
## Try it
Start the agent as before.
1. Say "Hello" and then stay silent. After about 20 seconds you should hear "Are you still there?"
2. Stay silent again. You should hear the second line, then the goodbye line, and the call ends.
3. On a new call, ask "Can you tell me my appointment time?" Robin answers, and the call does not end.
4. Say "No, that's all, goodbye." Robin says goodbye and hangs up.
## Why it works this way
LiveKit and Pipecat time a caller's pause in different ways. One pace name gives each framework its own matching settings, so a caller is paused the same way on both.
The idle timer runs only while the agent listens, so it never asks "are you there?" during its own slow tool. A call limit stops a call that would run for hours.
## What you have now
| Piece | File |
| - | - |
| `PACE`, `IDLE`, `MAX_DURATION_S`, `END_CALL` | `salon/agent.py` |
| Turn window, nudges, end-call tool on LiveKit | `livekit/agent.py` |
| Turn window, nudges, end-call tool on Pipecat | `pipecat/bot.py` |
Send one Langfuse trace for each call.
Go deeper: [Turn taking](/core/build/turn-taking) and [Call lifecycle](/core/build/call-lifecycle).
# Remember the caller
Source: https://unmute.ai/core/tutorial/remember-the-caller
Give the salon agent a typed call state, so it keeps the caller's number and refuses one that cannot be right.
You have: Robin answering and greeting, from [Answer the phone](/core/tutorial/answer-the-phone).
The caller gives their number, and the agent keeps it.
## What you add
First, the state. It is a Pydantic model. Every field has a default, because every value starts the call empty.
```python salon/state.py theme={null}
from typing import Literal
from pydantic import BaseModel, Field
from unmute_core.state import Phone
class State(BaseModel):
"""What one call knows."""
customer_phone: Phone | None = Field(
None, description="The caller's phone number in E.164."
)
requested_service: Literal["haircut", "hair-color", "blowout"] | None = Field(
None, description="The service the caller asked for. Leave it out if they did not say."
)
```
`Phone` is a type the library ships. It cleans a number and saves it with a plus and a country code. A number that cannot be right is refused.
Next, let the prompt read the state. A `{{name}}` placeholder is filled from the state before each model request.
```python salon/agent.py theme={null}
CONCIERGE_PROMPT = """\
You are Robin, on the front desk at Sage and Stone, a hair salon.
Speak only in English. Everything you write is read aloud, so write plain
sentences with no lists and no symbols. Keep every reply short.
Help the caller book a haircut, a hair colour or a blowout.
The caller's phone number: {{customer_phone}}.
When the caller gives a number or a service, save it with save_values.
"""
```
Last, build a `CallState` for each call and give it to the agent. `save_values=True` on the spec adds a tool the model calls to save these values.
```python livekit/agent.py theme={null}
from salon.state import State
from unmute_core.state import CallState
@server.rtc_session()
async def entrypoint(ctx: JobContext) -> None:
"""Run one call: start Robin with a state, then say the greeting."""
stt = slng.STT(
api_key=SLNG_KEY, slng_base_url=SLNG_HOST, model="soniox/speech-ai:rt-v5", language="en"
)
session = AgentSession(
stt=stt,
llm=openai.LLM(model="gpt-5.6-terra"),
tts=slng.TTS(
api_key=SLNG_KEY,
slng_base_url=SLNG_HOST,
model="slng/fish/tts:s2.1-pro",
voice=VOICE,
language="en",
),
vad=silero.VAD.load(),
)
stt.attach_to_session(session)
state = CallState(State)
spec = AgentSpec(salon.CONCIERGE_PROMPT, save_values=True)
agent = UnmuteAgent(spec, state=state)
await session.start(agent=agent, room=ctx.room)
greet(session, salon.GREETING, state)
```
```python pipecat/bot.py theme={null}
from salon.state import State
from unmute_core.state import CallState
# In bot(), build the state and give it to the flows.
state = CallState(State)
spec = AgentSpec(salon.CONCIERGE_PROMPT, save_values=True)
flows = UnmuteFlows(spec, llm=llm, context=context, aggregators=aggregators, state=state)
# In the greet handler, give the greeting the state.
frames = greeting_frames(salon.GREETING, state)
```
## See a refusal
You can check the state without a call. This is the same check the model's save goes through.
```python theme={null}
from unmute_core.state import CallState, StateRefused
from salon.state import State
state = CallState(State, confirm={"customer_phone": "verify_customer"})
try:
state.save({"customer_phone": "612345"})
except StateRefused as refused:
print(refused.message) # customer_phone: expected a phone number with its country code ...
state.save({"customer_phone": "+34 612 345 678"}, step="verify_customer")
state.plain("customer_phone") # "+34612345678"
state.is_confirmed("customer_phone") # True
```
`612345` is not a phone number, so nothing is saved. The refusal says what to fix, and the model reads it.
The `confirm` map says which task step must hear the caller agree to the number. Only that step can confirm it. You add the step in [Book step by step](/core/tutorial/book-step-by-step), so the agent itself does not use `confirm` yet.
## Try it
Start the agent as before. Then say these two lines.
1. "My number is six one two three four five." Robin should ask again, and ask for the country code.
2. "Sorry. Plus three four, six one two, three four five, six seven eight." Robin saves it.
Robin has the number now. The prompt shows it in `{{customer_phone}}` on the next turn.
## Why it works this way
A plain agent lets the model write any text into its memory. Here every save passes the type first, and the whole batch is refused if one value is wrong. The model gets a refusal worded for it, so it asks the caller instead of guessing.
The state is a normal Pydantic model. The same `State` class works on LiveKit and Pipecat.
## What you have now
| Piece | File |
| - | - |
| Prompt and greeting | `salon/agent.py` |
| Call state: `State` | `salon/state.py` |
| LiveKit pipeline, with state | `livekit/agent.py` |
| Pipecat pipeline, with state | `pipecat/bot.py` |
Give Robin a tool that reads the salon's diary.
Go deeper: [State](/core/build/state).
# See every call
Source: https://unmute.ai/core/tutorial/see-every-call
Send one trace for each salon call to Langfuse, with the same shape on LiveKit and Pipecat.
You have: Robin with turn pace, idle nudges and an end-call tool, from [Quiet callers](/core/tutorial/quiet-callers).
After the call, you can open it in Langfuse and see what happened.
## What you add
A `Telemetry` object records one trace for one call. A sink, here `Langfuse`, says where the trace goes. The sink reads its keys from the environment, so no key is in your code.
```bash theme={null}
export LANGFUSE_PUBLIC_KEY=pk-...
export LANGFUSE_SECRET_KEY=sk-...
export LANGFUSE_BASE_URL=https://cloud.langfuse.com
```
Build it for each call. The example builds it only when the keys are set, so the same file runs with or without Langfuse.
```python livekit/agent.py theme={null}
import os
from unmute_core.telemetry import Langfuse, Telemetry
class Concierge(UnmuteAgent):
"""Books appointments."""
def __init__(self, state: CallState[State], telemetry: Telemetry | None = None) -> None:
"""Build the concierge for one call."""
super().__init__(
CONCIERGE, state=state, telemetry=telemetry, native_tools=[end_call()]
)
# In entrypoint(), after the state is built.
telemetry = None
if os.getenv("LANGFUSE_PUBLIC_KEY"):
telemetry = Telemetry(
Langfuse.from_env(),
agent="salon-concierge",
call_id=ctx.job.id,
resource={"deployment.environment.name": os.getenv("ENVIRONMENT", "development")},
)
agent = Concierge(state, telemetry)
```
```python pipecat/bot.py theme={null}
import uuid
from unmute_core.pipecat import TelemetryObserver
from unmute_core.telemetry import Langfuse, Telemetry
# In bot(), after the state is built.
telemetry = None
if os.getenv("LANGFUSE_PUBLIC_KEY"):
telemetry = Telemetry(
Langfuse.from_env(),
agent="salon-concierge",
call_id=runner_args.session_id or uuid.uuid4().hex,
resource={"deployment.environment.name": os.getenv("ENVIRONMENT", "development")},
)
# Give it to the flows with telemetry=telemetry, and watch the pipeline.
observers = []
if telemetry is not None:
observers.append(
TelemetryObserver(telemetry, model="gpt-5.6-terra", provider="openai", flows=flows)
)
worker = PipelineWorker(pipeline, observers=observers)
# Start the trace before the runner, and close it when the call is over.
if telemetry is not None:
telemetry.start_call()
try:
await runner.run()
finally:
await flows.settle()
if telemetry is not None:
await telemetry.close(state=state, reason="ended")
```
On LiveKit, the adapter starts and closes the trace with the session. On Pipecat, you start it and close it, because you own the runner.
The complaint specialist is built without `telemetry`. It records into the concierge's spans, so one call is one trace even after a handoff.
## Try it
Run a call as before, with the three keys set. Book a haircut, then hang up.
1. Open your project in Langfuse. A trace for your call should appear.
2. Open it. You should see the turns, the transcript, the model requests and the tool calls.
3. Run a call again with no keys. The agent works the same and sends nothing.
## Why it works this way
Each framework gives its own events in its own shape. The adapters turn them into one trace shape, so a LiveKit call and a Pipecat call look the same in Langfuse. The call ends with one reason on both.
`Langfuse` is one sink. `Telemetry` takes others too, and the page on telemetry lists them. Your agent code does not change when the sink does.
## What you have now
| Piece | File |
| - | - |
| `Telemetry` and `Langfuse`, built per call | `livekit/agent.py`, `pipecat/bot.py` |
| The agent, with `telemetry=` | `livekit/agent.py` |
| `TelemetryObserver` and the trace's start and close | `pipecat/bot.py` |
Compare your agent with the full example, and run it.
Go deeper: [Telemetry](/core/observe/telemetry).
# What you built
Source: https://unmute.ai/core/tutorial/what-you-built
Map your salon agent to the full example in the repository, run it on LiveKit and Pipecat, and find the guide for each piece.
You have: Robin with state, a diary tool, a booking task, a handoff, prefetch, quiet-caller settings and a trace, from [See every call](/core/tutorial/see-every-call).
You built a phone agent that keeps a typed state, books only what the caller agreed to, hands off a complaint, knows the date, and shows up in Langfuse. The same `salon/` package runs on LiveKit and Pipecat.
## Your code and the example
The full example is `examples/salon-concierge-unmute/`. Its names are the ones you used, so you can read it next to your files. Its `salon/` package keeps its code in `salon/src/salon/`.
| You wrote | In the example |
| - | - |
| `State` | `salon/src/salon/state.py` |
| `GREETING`, `CONCIERGE_PROMPT` | `salon/src/salon/agent.py`, and the prompts in `salon/src/salon/prompts/` |
| `tools()` and the diary | `salon/src/salon/agent.py` and `salon/src/salon/store.py` |
| `VERIFY_CUSTOMER`, `CONCIERGE_TASKS`, `agents()` | `salon/src/salon/agent.py` |
| `Concierge` and `ComplaintSpecialist` on LiveKit | `livekit/agent.py` |
| `salon_flows()` on Pipecat | `pipecat/bot.py` |
| `PREFETCH`, `new_call()` | `salon/src/salon/agent.py` |
| `PACE`, `IDLE`, `MAX_DURATION_S`, `END_CALL` | `salon/src/salon/agent.py` |
| `Telemetry` with `Langfuse` | `livekit/agent.py`, `pipecat/bot.py` |
## What the example adds
1. **Knowledge.** `look_up_salon_info` and `look_up_refund_policy` search the salon's own documents, so Robin quotes the guide instead of guessing a price.
2. **Receipts and confirmations for every write.** Booking, moving and cancelling each ask a question first and say a fixed line after. Most turns cost one model request.
3. **Held saves.** A save made before the caller answered is held, and the call's end settles it. Pipecat calls `UnmuteFlows.settle`. LiveKit does it on its own.
4. **A locked phone number.** `customer_phone` is locked to the state on every diary tool, so the model never types it.
5. **Phone calls.** `sip_call_info` and `telephony_call_info` read what a phone call carries into `state.call`. On a browser or console call, `UNMUTE_CALL_START` simulates a caller.
6. **A complaint mid-booking.** `manage_booking` offers `to_complaints` too, so a complaint in the middle of a booking goes straight to the specialist.
## Run the full example
Copy the `.env.example` in each project to `.env`, and fill the keys it lists. Langfuse keys are optional.
```bash LiveKit theme={null}
cd examples/salon-concierge-unmute/livekit
cp .env.example .env # fill in the keys
uv sync
lk agent console agent.py # talk through your microphone
lk agent console --text agent.py # or type
```
```bash Pipecat theme={null}
cd examples/salon-concierge-unmute/pipecat
cp .env.example .env # fill in the keys
uv sync
uv run bot.py -t webrtc # then open http://localhost:7860
```
A call to try:
1. "I'd like to book a haircut on Friday." The agent checks your number, offers times, confirms and books.
2. "How much is a full head colour?" It answers from the salon guide.
3. "My last colour went wrong, I want to complain." It hands you to the complaint specialist.
4. "Can I also move my haircut to Saturday?" It hands you back to the concierge, who moves it.
5. "That's all, bye." It says goodbye and hangs up.
## Where to go next
Types, confirmation and prompt placeholders.
Typed tools, locked arguments and announce lines.
Steps, groups and finish checks.
Pass the call between agents.
Read values before the greeting.
Pace, interruptions and quiet callers.
Answer from your own documents.
Langfuse, Logfire, Coval and more.
How the library plugs into LiveKit Agents.
How the library plugs into a Pipecat pipeline.
# Going live
Source: https://unmute.ai/deploy/going-live
Create a package, choose a host, and deploy it with the right configuration and credentials.
Deploy an Unmute package to SLNG, LiveKit Cloud, or Pipecat Cloud, then update
it from the same authored files. A Twilio target is an app you host yourself;
[the Twilio walkthrough](/telephony/twilio-conversation-relay) covers hosting it and pointing a number
at it. Validation checks your declarations;
compilation turns them into what the selected target runs.
On this page:
* [Quickstart](#quickstart) - create, compile, and choose a host
* [Keep the package as the source](#1-keep-the-package-as-the-source) - what belongs where
* [Choose models and regions](#2-choose-models-and-regions) - configuration and target limits
* [Separate accounts and credentials](#3-separate-accounts-and-credentials) - names and values
* [Deploy and verify](#4-deploy-and-verify) - follow the hosting route
* [Update the agent](#5-update-the-agent) - code, secrets, and names
* [Advanced](#advanced) - custom code and hosting limits
* [Troubleshooting](#troubleshooting) - symptom, cause, and fix
* [Where to go next](#where-to-go-next)
## Quickstart
Run these commands from the directory that will hold your new package:
```sh Terminal theme={null}
unmute init my-agent
cd my-agent
unmute validate
unmute compile
```
Named initialization creates a LiveKit package. Run `unmute init` without a
name for the interactive target choices. Add `--from-manifest` to create the
package under a saved organization manifest instead; see
[initialization](/reference/cli/init#from-a-saved-manifest).
Already have a package? Start inside it at `unmute validate`. To change its
target, follow [Switching a package](/targets/overview#switching-a-package-to-another-target),
including the model changes that target needs. `--target` selects a declared
instance; it does not convert the package to another framework.
Then follow **one** hosting guide:
| Destination | What you deploy | First deployment |
| - | - | - |
| [SLNG](/deploy/slng) | Compiled agent body | `unmute deploy --target slng` from the package |
| [LiveKit Cloud](/deploy/livekit-cloud) | Generated Python project | `lk agent create` from `build/livekit/` |
| [Pipecat Cloud](/deploy/pipecat-cloud) | Generated Python project | `pipecat cloud deploy` from `build/pipecat/` |
The target guides supply the authentication, destination, region, and secret
steps those commands need. For [Twilio](/telephony/twilio-conversation-relay),
host the generated app first, then run `unmute deploy --target twilio` to
connect the number. `unmute deploy` publishes SLNG agents or configures Twilio
number routing; LiveKit and Pipecat use their platform commands.
## 1. Keep the package as the source
| Authored file | What you change |
| - | - |
| `agent.yaml` | Agent declarations, model bindings, call behavior, and secret names |
| `instructions.md` and task prompt files | What the agent should do and say |
| `targets.yaml` | Target instances, supported framework version, and deployment settings |
| `tools/.yaml` | Tool inputs and execution choice |
| Python files named by `local.handler` | Your tool functions, on LiveKit and Pipecat |
| `connections/.yaml` | A supported phone route and its environment names |
`unmute validate` checks the package against each selected target.
`unmute compile` performs those checks too, then writes
`build//`. No provider credentials are needed to compile.
On LiveKit and Pipecat, that directory includes a `Dockerfile`,
`pyproject.toml`, the runtime code, `agent.json`, and `.env.example`. The
project imports the `unmute-core` library from PyPI. Unmute writes no deploy
manifest for either platform yet, so you pass the destination to the platform's
own command. SLNG gets an agent body and a runbook, with no Python project or
container to build.
`.env.example` lists the values the build needs. `compile-report.json` records
the `unmute-core` version and those environment names. Generated files hold
names, never credential values.
Recompilation replaces the selected build directory. Keep authored code outside
`build/`. The compiler preserves `.env`, `livekit*.toml`, and `samples/*.json`;
it does not preserve arbitrary edits or added modules.
## 2. Choose models and regions
Models live under `models` in `agent.yaml`. Agents bind a named reasoning and
voice entry; the package also supplies listening and turn detection where its
[pipeline](/build/architecture/overview) uses them.
For example, this is the reasoning entry from the current scaffold. Merge it
into the existing `models.think` block; it is one supported choice:
```yaml agent.yaml theme={null}
models:
think:
assistant_model:
provider: openai
model: gpt-5.6-terra
params:
reasoning_effort: none
```
Selects an integration for this model role and target. See the role pages below.
The provider's model identifier. Requiredness and defaults depend on the integration;
copy a supported binding from its role page.
Provider settings for this binding. Omit to use the integration's defaults.
These are not an unrestricted runtime configuration API.
| Role | Bindings, credentials, and target support |
| - | - |
| Reasoning | [Language models](/models/llm) |
| Speech recognition | [Speech to text](/models/stt) |
| Speech generation | [Text to speech](/models/tts) |
| Turn detection | [Turn detection](/models/turn-detection) |
| A live speech model | [Live models](/models/live) |
Unmute checks provider support and known invalid settings. It transforms some
settings and forwards others to the provider integration; the compile report
shows the resolved binding. Validation cannot prove a model exists in your
account or that every forwarded parameter will succeed.
The role pages link to the provider's parameter and credential documentation.
For a target-specific choice, use a [model override](/targets/overview#overrides-not-forks).
An override replaces the provider, model, and parameters. Omitted shared
behavior settings, such as turn timing, carry forward.
Keep three different region choices separate:
| Setting | What it controls |
| - | - |
| Target `deployment_region` | Where the host runs the agent; allowed values and defaults are target-specific |
| Provider inference region or endpoint | Where a model request runs, when that integration supports choosing it |
| Provider routing, such as SLNG `params.world_part` | Which provider gateway receives the request |
A hosting region does not move a provider's inference service. See
[target fields](/targets/overview#targets-yaml) and the
[SLNG router](/optimization/context-router) for their respective settings.
## 3. Separate accounts and credentials
| Concept | Where it belongs |
| - | - |
| Deployment authentication | Your host CLI login or deployment credential, on the developer machine or CI runner |
| Destination account or project | The host CLI's explicit project or organization selection |
| Provider credentials | Keys issued by the selected model or service provider |
| Runtime secrets | Values provisioned into the deployed agent's environment or SLNG Vault |
| Platform-injected values | Connection settings the host supplies, such as LiveKit Cloud's connection URL and key pair |
| Application configuration | Non-secret environment values, such as an API base URL, read through a supported field or handler |
For a code target, declare environment names separately from provisioning their
values. Merge the names your package reads into this list:
```yaml agent.yaml theme={null}
secrets:
- SERVICE_API_TOKEN
- SERVICE_API_URL
```
Inventory of environment names the generated project reads, including non-secret
configuration. Declaring a name does not create or populate a host secret.
SLNG derives its Vault requirements from the compiled body instead.
After compiling, make a deployment file from that target's `.env.example`.
Fill only the names read by the deployed agent. Some routes also list values
for a separately hosted helper; follow the comments rather than uploading the
whole development environment.
For a handler that reads these two names, a minimal file has this shape.
Replace the placeholders privately before using it:
```dotenv .env.deploy (outside the build directory) theme={null}
SERVICE_API_TOKEN=REPLACE_WITH_PROVIDER_ISSUED_VALUE
SERVICE_API_URL=https://api.example.com
```
Keep this file out of source control and the uploaded build context. Use a
secret manager or a private editor to fill values; do not put them in command
arguments, generated code, or image layers. See [Credentials](/build/credentials)
for the fields that read environment names.
Call [variables](/build/variables) hold conversation data. Prompt interpolation
is not a way to deliver credentials. Updating a deployed value also does not
create or revoke its provider key; manage that key with its issuing provider.
## 4. Deploy and verify
Each hosting guide separates first creation, later code updates, and
secrets-only changes. It also explains how the host finds the existing agent:
[LiveKit](/deploy/livekit-cloud), [Pipecat](/deploy/pipecat-cloud),
[SLNG](/deploy/slng).
Check each stage separately:
1. **Validation passes:** the package fits the target. Provider access remains untested.
2. **The build finishes:** the host has an image or agent body. Check readiness next.
3. **The worker is ready:** open a new session through the selected host and transport.
4. **A full interaction works:** speak a short question, confirm the input was received, and hear a relevant answer.
5. **The application works:** exercise a tool or task that matters to your agent, then end the session.
A greeting proves output works; it does not prove microphone input or tool
credentials work. Use host status and logs from the target guide to locate the
failed stage. Keep transcript and credential values out of diagnostic reports.
For phone calls, deploy first, then finish the
[carrier setup](/telephony/overview). `unmute dev` is the
[local browser workflow](/dev/overview), not a deployed phone test.
## 5. Update the agent
Change the authored prompt, tool, model, or configuration, then run from the
package directory:
```sh Terminal theme={null}
unmute validate
unmute compile
```
Follow the target's **update** command using the existing deployment identity.
Code targets build a new image for changed code or compiled settings. SLNG's
`unmute deploy` validates and recompiles automatically before pushing.
A changed value under an existing environment name needs the host's
secrets-only workflow. Adding a new required name also changes the package's
inventory, so compile and deploy that source change. Check a new session after
either update.
`--target livekit` replaces only `build/livekit/`. Deploying from another build
directory can ship stale code, names, or requirements. Compile the instance
you intend to deploy.
### Except changing its name
The package's `name` joined to its target instance becomes the deployment name.
A rename is an identity change, and phone routing may still point at the old one.
| Target | What a rename changes |
| - | - |
| SLNG | The push resolves the new name; existing callers still use the old agent ID |
| LiveKit | A package rename changes the dispatch name; the same build directory keeps its cloud agent ID in `livekit.toml` |
| Pipecat | The manifest names a new agent and secret set; the old agent remains |
Renaming a target also changes its build directory. On LiveKit, recover the
existing agent config in that new directory before updating; compilation does
not move it from the old folder.
Follow the rename steps for [LiveKit](/deploy/livekit-cloud#renaming-the-agent-breaks-that-rule),
[Pipecat](/deploy/pipecat-cloud#renaming-the-agent), or
[SLNG](/deploy/slng#renaming-the-agent) before changing a production name.
## Advanced
### Add only the code you need
Start with native declarations and [tools](/build/tools/overview). Use a
webhook for an HTTP service or MCP for a supported remote tool server. Use a
[local Python handler](/build/tools/python) for logic inside the generated
LiveKit or Pipecat process.
[Sharing Python helpers](/build/tools/python#share-a-helper-between-tools)
explains the supported single-source-file pattern and the limit on separate
imported modules. Arbitrary module trees and data files are not copied into the
build. Declared [knowledge documents](/build/tools/knowledge) have their own
supported inclusion path.
There is no authored lifecycle-hook API or custom Dockerfile hook. LiveKit's
[target pins](/targets/overview#targets-yaml) can change versions of recognized
dependencies within supported bounds; they cannot add arbitrary packages.
Pipecat does not support those overrides. Per-tool dependency declarations are
refused on both code targets.
Use the compiler-owned build files for the native workflow. An SDK that needs
an extra package or a custom startup service has no durable package extension
point today; consider a remote tool service instead.
### Hosting the generated container yourself
The managed-host pages cover the native deployment commands. Operating the
container yourself also means supplying networking, credentials, monitoring,
and session draining.
A LiveKit worker connects out to LiveKit Server. The server needs public media
connectivity and trusted TLS; SIP adds its own signaling and media service.
Follow [LiveKit's self-hosting documentation](https://docs.livekit.io/transport/self-hosting/).
For self-hosted Pipecat browser calls, the generated SmallWebRTC configuration
adds no ICE servers. Cross-network use needs a supported STUN/TURN setup that
Unmute does not currently expose as an authored deployment option.
## Troubleshooting
| Symptom | Cause | Fix |
| - | - | - |
| The host cannot find a project | Deployment ran from the authored package or a partial build | Compile, then use the complete `build//` directory named by the guide |
| An imported module or data file is missing | Compilation copies selected handlers, not their import tree or adjacent files | Use the supported shared-handler layout or move the operation to a remote tool |
| A worker reports a missing credential | Declaring a name did not provision its value, or it went to another destination | Compare the generated inventory with the selected host's secret names |
| A model request rejects a parameter or region | Provider acceptance is not fully checked offline | Read that integration's supported parameters and account availability, then change the binding |
| An update creates another agent | The name, destination, or saved identity changed | Check the target's identity and rename steps before deploying again |
| The first session fails | The image exists but the worker is still starting | Wait for readiness and read startup logs before testing again |
| The greeting plays but the agent hears nothing | The client may have no active microphone input | Check microphone permission, selected device, and mute state; then inspect input events |
## Where to go next
Create a cloud agent, update it, and manage its secrets.
Deploy the generated project to a chosen organization and region.
Push an agent body and resolve its hosted dependencies.
Keep reusable tool logic in the authored package.
# Go live on LiveKit Cloud
Source: https://unmute.ai/deploy/livekit-cloud
Create a LiveKit Cloud agent from your package, then update its code and runtime secrets.
Deploy your compiled package to a LiveKit Cloud project, then update the same agent.
Unmute writes the runnable project; LiveKit's `lk` CLI builds and hosts it.
Edit your authored package and compile again when its behavior changes.
`unmute deploy` publishes SLNG agents or connects Twilio numbers; this route uses `lk agent`.
On this page:
* [Quickstart](#quickstart) - compile and create the first deployment
* [Choose the project](#1-choose-the-project) - authentication and destination
* [Prepare the package](#2-prepare-the-package) - target, build files and credentials
* [The first deploy is create](#the-first-deploy-is-create) - create and save its identity
* [Check it, and recover it](#check-it-and-recover-it) - status and a real interaction
* [Every later deploy is deploy](#every-later-deploy-is-deploy) - update the existing agent
* [Secrets](#secrets) - change values without rebuilding
* [Advanced](#advanced) - regions, phone routes and customization
* [Troubleshooting](#troubleshooting) - symptoms and fixes
* [Where to go next](#where-to-go-next)
## Quickstart
Start with a package that declares a LiveKit target named `livekit`.
[Create a package](/deploy/going-live) first if you do not have one.
Install the [LiveKit CLI](https://docs.livekit.io/reference/developer-tools/livekit-cli/)
and prepare the runtime secret file described below.
From the package root; replace both placeholders with your destination:
```sh Package root theme={null}
lk cloud auth
lk project list
unmute validate . --target livekit
unmute compile . --target livekit
cd build/livekit
lk --project "" agent create --region "" --secrets-file ../../.env.livekit
lk --project "" agent status
```
`create` writes `livekit.toml` with the new agent ID and project.
Keep it for later updates. The following sections explain each step.
## 1. Choose the project
`lk cloud auth` links a project through your browser. This authenticates the
CLI on your machine; it does not provision your model providers' keys.
Use an account with access to manage agents in the destination project.
`lk project list` shows linked projects. Pass `--project ""`
on deployment commands so the destination is explicit. You can also set a
default with `lk project set-default ""`.
See [project selection](https://docs.livekit.io/reference/developer-tools/livekit-cli/projects/).
On later runs, `livekit.toml` identifies the project and agent. The explicit
project must match that file. Changing the CLI's default does not move an agent.
## 2. Prepare the package
### Set the target and models
Declare `provider: livekit` and an exact supported framework `version:` in
`targets.yaml`. See the [LiveKit target fields](/targets/livekit#target-fields)
and [supported versions](/reference/targets-yaml#framework-versions-are-exact).
The generated image supplies Python; you do not need a local Python environment
to validate or compile.
Choose [reasoning](/models/llm), [speech recognition](/models/stt),
[speech generation](/models/tts), and [turn detection](/models/turn-detection)
in the package, or use the target's model overrides. Provider parameters and credentials follow those bindings.
Changing a model uses the same compile and deploy steps.
`unmute validate` checks declarations and target support. Compilation also
validates, then writes `build/livekit/`. Neither operation proves a provider
will accept a request with your account and credentials.
### Use the generated build directory
Run LiveKit commands from `build/livekit/`, where these files are generated:
| File | Role |
| - | - |
| `agent.py`, `spec.py`, `speech.py` and `agent.json` | Worker entry point, and the agent data it builds from |
| `state.py` | Your `State` class, when the package has one |
| `pyproject.toml` | Python project manifest, including the `unmute-core` library |
| `Dockerfile` and `.dockerignore` | Image build and file exclusions |
| `tools/` | Copied local tool handlers, when declared |
| `.env.example` | Environment names for this package and route |
| `compile-report.json` | Resolved bindings and compiler decisions |
The compiler supplies the project manifest and Dockerfile. No custom adapter
or Dockerfile is needed for this route. LiveKit builds the image remotely from
this directory; files elsewhere in the authored package are not its build context.
See [LiveKit builds](https://docs.livekit.io/deploy/agents/builds/).
### Supply only the runtime values
Declare secret names in the package as described in
[credentials](/build/credentials). Supply their values separately.
Create `.env.livekit` in the package root, outside the generated build directory,
and exclude it from source control.
This is a format example. Replace the name with a required name from your
build's `.env.example`, then add only the other runtime values it needs:
```dotenv .env.livekit — package root, placeholders only theme={null}
SERVICE_API_KEY=replace-with-the-provider-key
```
Obtain keys from the provider linked by your [model binding](/models/llm).
Do not copy a whole development environment into this file. Remove unused names,
blank placeholders, and local-only connection settings.
| Value | Where it belongs |
| - | - |
| CLI authentication | The linked project on your machine |
| Provider, tracing and tool credentials | Runtime secrets supplied to the deployed agent |
| `LIVEKIT_URL`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` | Injected by LiveKit Cloud; omit from the upload |
| Local SIP `REDIS_URL` | Local infrastructure; omit for managed Cloud SIP |
| Non-secret settings a handler reads from its environment | May use the same runtime environment file |
| Conversation variables | Package/session state; see [variables](/build/variables) |
LiveKit excludes its three connection credentials from secret uploads.
It does not create or revoke your provider keys.
See [runtime secret storage](https://docs.livekit.io/deploy/agents/secrets/).
## The first deploy is `create`
From `build/livekit/`, choose a supported worker region and create the agent:
```sh build/livekit/ theme={null}
lk --project "" agent create --region "" --secrets-file ../../.env.livekit
```
Choose the region declared by your target, if any. See
[region selection](#region-is-chosen-once) below.
If the package needs no uploaded runtime values, omit `--secrets-file`.
`create` registers a resource, writes `livekit.toml`, uploads the build context,
and starts the image build and deployment. It expects no existing config with
that filename. Use `deploy` for an existing resource.
See LiveKit's [first deployment](https://docs.livekit.io/deploy/agents/quickstart/).
| Name | What it identifies |
| - | - |
| Package `name:` | The authored package |
| Target name, such as `livekit` | The selected target and build directory |
| Dispatch name | Package name joined to target name, such as `my-agent-livekit` |
| Cloud agent ID | The resource created by LiveKit and saved in `livekit.toml` |
Recompiling preserves `livekit*.toml`, `.env`, and `samples/*.json` within this
build directory. It replaces everything else there. Keep authored changes in
the package, and retain a backup of deployment config files.
## Check it, and recover it
From `build/livekit/`, inspect the selected deployment:
```sh build/livekit/ theme={null}
lk --project "" agent status
lk --project "" agent list
lk --project "" agent logs
```
A successful image build does not prove the worker is ready. Check its status
and startup logs, then start a session with its dispatch name in the
[Agent Console](https://docs.livekit.io/agents/start/console/)
or your existing frontend.
Ask one short question and confirm the agent receives it and answers it.
A greeting alone does not prove caller input reached the model. Exercise one tool
if the package uses tools. Read the new session's logs for provider and tool
errors, without sharing secret values or sensitive conversation content.
This is a deployment smoke check. Phone routes still need
[carrier setup and a deployed call](/telephony/overview#point-the-carrier-at-the-deployment),
and application testing still needs its own cases.
If you lose the config, recover it using the existing ID from `agent list`:
```sh build/livekit/ theme={null}
lk --project "" agent config --id ""
```
## Every later deploy is `deploy`
Change authored prompts, tool handlers, declarations or model bindings. Return
to the package root before validating and compiling:
```sh Package root theme={null}
unmute validate . --target livekit
unmute compile . --target livekit
cd build/livekit
lk --project "" agent deploy
```
`deploy` builds a new image for the ID in `livekit.toml`. It does not read the
authored files outside this directory. Target selection leaves other targets'
builds untouched, so compile each target you intend to update.
The secrets file is optional on update. Existing secrets remain unless you
change them. If the CLI offers to import a discovered environment file,
decline when you intend a code-only update. Use [secrets-only updates](#secrets)
for deliberate credential changes.
LiveKit rolls out new workers for new sessions and gives old workers up to an
hour to finish active sessions. Repeat the status and interaction checks after
the rollout. See [deployment management and rollback](https://docs.livekit.io/deploy/agents/managing-deployments/)
for recovery options and plan limits.
## Secrets
From `build/livekit/`, add or replace the values in your runtime file:
```sh build/livekit/ theme={null}
lk --project "" agent update-secrets --secrets-file ../../.env.livekit
lk --project "" agent secrets
```
The update merges supplied names into the existing set. Removing a line from
the file does not delete the deployed secret.
To remove names, prepare the complete set you want to retain, then replace
the deployed set:
```sh build/livekit/ theme={null}
lk --project "" agent update-secrets --secrets-file ../../.env.livekit --overwrite
```
`--overwrite` removes existing names absent from the supplied set. Check the
retained file before running it. The command uses the same project access and
agent identity as deployment.
Both updates trigger a rolling restart without rebuilding the image. New
sessions receive the new values. `agent secrets` displays names and timestamps,
never values. Test a fresh session after updating a credential.
See [LiveKit secret semantics](https://docs.livekit.io/deploy/agents/secrets/).
Rotating a key has two separate parts: update this deployed value, then revoke
the old key with its provider after confirming the replacement works.
## Advanced
### Region is chosen once
On the LiveKit target, Unmute accepts `us-east`, `eu-central`, or `ap-south`,
either singly or as a list without duplicates. Omission emits no region flag.
Use an explicit `--region` when destination placement matters.
This controls worker hosting. Provider inference locations, provider routing
parameters and LiveKit media placement are separate settings. See
[regional infrastructure](/optimization/regional-infrastructure).
LiveKit documents a deployment's region as fixed after creation. To move,
create in the new region and retire the old deployment after verification.
For several regions, run one create command per region. Each writes its own
`livekit..toml` when you pass a separate `--config`. Pass the matching `--config` on subsequent
updates, secret changes and inspection commands.
All those workers share the dispatch name. Routing may use another region
when the nearest is at capacity. See [multi-region routing](https://docs.livekit.io/deploy/admin/regions/agent-deployment/)
before relying on worker placement for strict locality.
### Telephony needs two more records
An inbound SIP route needs a LiveKit inbound trunk and a dispatch rule.
Unmute does not write the two JSON files for them yet, so you write them
yourself. Create both after deploying, with `lk sip inbound create` and
`lk sip dispatch create`. The dispatch rule names the worker. Name the project
on both. `lk` has a default project, and a command without `--project` writes
the records into it and reports success.
[Create the two LiveKit records](/telephony/livekit-twilio#4-create-the-two-livekit-records)
has the sequence, including which flags to avoid and why.
### Renaming the agent breaks that rule
Changing the package name changes the dispatch name. Within the same build
directory, `deploy` still updates the resource ID in the preserved config.
Renaming the target changes the build directory too: recover the existing
agent config there with `lk agent config --id` before updating.
An existing SIP dispatch rule keeps the old agent name, and no deploy updates
it.
Deploy the new worker and confirm its dispatch name with `lk agent list`.
Then list the rules with `lk --project "" sip dispatch list`, and
remove the stale one with `lk --project "" sip dispatch delete `. Create the rule again with the same trunk ID, using `lk sip dispatch create`. The number is unrouted between the delete and
the create. Check that the rule names the new worker, then make a test call.
For the `connector` route, redeploy the bridge from the new build: its
`AGENT_NAME` also carries the dispatch name.
### Customize the supported inputs
Use [model bindings](/models/llm), [tools](/build/tools/overview), and
[LiveKit target fields](/targets/livekit#target-fields) first. Local Python
handlers are supported; arbitrary neighboring modules and data files are not
automatically copied. See [local handlers](/build/tools/python).
Target `pins:` can override known catalog dependencies within validated bounds.
It is not an arbitrary Python requirements list. Unmute exposes no authored
Dockerfile override or general worker lifecycle hook. Generated edits disappear
on compilation.
For self-hosting, use the [generated LiveKit project](/targets/livekit) and
[LiveKit's self-hosted deployment guide](https://docs.livekit.io/deploy/custom/deployments/).
You supply your own LiveKit server URL and API credentials on that route.
## Troubleshooting
| Symptom | Cause → fix |
| - | - |
| Project or manifest not recognized | Wrong working directory or incomplete build → compile and run from `build/livekit/`, containing `pyproject.toml` and `Dockerfile`. |
| Config already exists during create | This directory already identifies an agent → use `deploy`, or recover the intended config before proceeding. |
| Project mismatch or wrong destination | CLI selection and config disagree → compare `lk project list` with `livekit.toml` and use the matching `--project`. |
| Build passes, worker is not ready | Startup, dependency or provider failure → read `agent logs`; check `agent status` before testing. An idle deployment may have scaled to zero. |
| Missing credentials | Required values were omitted or the key has the wrong provider scope → inspect names with `agent secrets`, then correct and update the required values. |
| Provider rejects a parameter or region | Local validation does not verify provider account access → check the binding's provider documentation, correct the authored setting, compile and deploy. |
| Missing shared module or data file | The file was not included by the compiler → use supported tool inputs; see [local handlers](/build/tools/python). |
| Greeting works, caller input does not | The client may not publish microphone audio → check browser permission, selected input and mute state; inspect the session before changing models. |
| New behavior is absent | Stale target build, wrong config or an older active session → compile the intended target, deploy its config and start a fresh session. |
| Phone rings without an answer | Carrier routing, dispatch or runtime failure → follow the route's [telephony checks](/telephony/overview). |
## Where to go next
The package-to-deployment workflow across targets.
Generated files and supported target settings.
# Go live on Pipecat Cloud
Source: https://unmute.ai/deploy/pipecat-cloud
Compile your package, choose an organization, deploy it, and update its code or secrets.
Deploy your Unmute package as a managed Pipecat Cloud agent.
Unmute writes the runnable project; Pipecat Cloud builds and hosts it.
Change the authored package, then compile again before deploying code changes.
On this page:
* [Quickstart](#quickstart) - the first deployment
* [Prepare the package](#1-prepare-the-package) - target, version, and build files
* [Choose the destination](#2-choose-the-destination) - login, organization, and region
* [Supply runtime values](#3-supply-runtime-values) - a dedicated secret set
* [Deploy and verify](#4-deploy-and-verify) - readiness and a complete interaction
* [Every later deploy](#every-later-deploy) - update the existing agent
* [Secrets-only updates](#secrets-only-updates) - change values without rebuilding
* [Advanced](#advanced) - warm instances, names, and customization
* [Troubleshooting](#troubleshooting) - symptom, cause, and fix
* [Where to go next](#where-to-go-next)
## Quickstart
Start with a package named `my-agent` and a target named `pipecat`.
[Create a package](/deploy/going-live) first if you do not have one.
Install the [Pipecat CLI](https://docs.pipecat.ai/api-reference/cli/overview)
with its cloud commands; this needs Python 3.11 or later and `uv`:
```sh Terminal theme={null}
uv tool install "pipecat-ai[cli]" --with pipecatcloud
pipecat cloud auth login
pipecat cloud organizations select
pipecat cloud organizations list
```
Run these from the directory containing `my-agent/`:
```sh Terminal theme={null}
unmute validate my-agent --target pipecat
unmute compile my-agent --target pipecat
cd my-agent/build/pipecat
cp .env.example .env
```
Fill `.env` with only the deployed agent's required values, as described below.
Unmute does not write a `pcc-deploy.toml` yet. You pass the agent
name, secret set and region to `pipecat cloud deploy` as flags. These examples
use `my-agent-pipecat` and `my-agent-pipecat-secrets`. Pick your own names.
```sh Terminal — from my-agent/build/pipecat theme={null}
pipecat cloud secrets set my-agent-pipecat-secrets --file .env
pipecat cloud secrets list my-agent-pipecat-secrets
```
Wait until the set reports `ready`, then deploy:
```sh Terminal — from my-agent/build/pipecat theme={null}
pipecat cloud deploy my-agent-pipecat --secrets my-agent-pipecat-secrets
pipecat cloud agent status my-agent-pipecat
```
If you deploy to a region, pass the same `--region` to `secrets set` and to `deploy`.
Finish with the [interaction check](#4-deploy-and-verify).
## 1. Prepare the package
Merge this target into an existing package's `targets.yaml`:
```yaml targets.yaml theme={null}
targets:
pipecat:
provider: pipecat
version: "1.12.0"
```
Targets the package can compile. The entry name selects `--target` and the build folder.
Use `pipecat` for this hosting route.
Exact framework version. This release supports `1.12.0`; omitted or unsupported
versions are refused. The cloud CLI is installed separately from this runtime pin.
Keep prompts, models, and tools in the authored package. Select models through
[model bindings](/reference/agent-yaml#models), with any target overrides in
[`targets.yaml`](/reference/targets-yaml#models-overrides).
See [Pipecat support](/targets/pipecat) for model and transport limits.
`compile` validates the selected target before writing
`my-agent/build/pipecat/`. It needs no hosting login. Validation checks the
package and known capabilities; it does not make a successful provider request.
`unmute deploy` publishes SLNG agents or connects Twilio numbers. Pipecat uses
its own deployment command.
| Generated file | Role |
| - | - |
| `Dockerfile` | Compiler-owned Cloud build using Python 3.12 |
| `pyproject.toml` | Exact framework version, `unmute-core`, and generated dependencies |
| `bot.py`, `agent.json`, `spec.py`, `speech.py` | The entry point and the agent the `unmute-core` library runs |
| `state.py`, `tools/`, `knowledge/` | Your state, local handlers, and declared knowledge files, copied |
| `.dockerignore` | Excludes `.env`, `.env.*`, and local Python environments from the build |
| `.env.example` | Environment names to review and fill |
| `compile-report.json` | The target, runtime, and required environment names |
Keep the generated directory together as the build context. No custom
Dockerfile, container registry, or local Docker build is required for this path.
## 2. Choose the destination
Login authenticates the deployment operator. The selected organization decides
where commands act; it is separate from model-provider accounts.
`organizations select` saves that choice in the CLI's local configuration.
Run `organizations list` before each deployment to confirm it.
For scripts, use `--organization` on deployment and secret commands with the
organization identifier from the listing. See the
[organization commands](https://docs.pipecat.ai/api-reference/cli/cloud/organizations)
and [account permissions](https://docs.pipecat.ai/pipecat-cloud/fundamentals/accounts-and-organizations).
Use an account permitted to manage agents and secrets in that organization.
### Choose a hosting region
```sh Terminal theme={null}
pipecat cloud regions list
pipecat cloud organizations default-region
```
Omitting a region uses the organization's default placement. To choose one,
pass `--region` to `deploy`. Unmute writes no manifest, so `deployment_region`
reaches nothing and the flag is the way to choose a region. `eu-central` is an example. Choose from `regions list`.
The secret set must use the same region:
```sh Terminal — from my-agent/build/pipecat theme={null}
pipecat cloud secrets set my-agent-pipecat-secrets --file .env --region eu-central
pipecat cloud deploy my-agent-pipecat --secrets my-agent-pipecat-secrets --region eu-central
```
Hosting region places the worker. Provider inference regions and SLNG
`params.world_part` are separate model settings. See
[regional infrastructure](/optimization/regional-infrastructure).
## 3. Supply runtime values
[Declare secret names](/build/credentials) in the package and provision their
values separately. Use the generated `.env.example` to prepare a dedicated
deployment `.env`.
This example shows placeholders only. Replace the names with those your package
requires, and fill their values privately:
```dotenv .env — example values only theme={null}
MODEL_API_KEY=replace-with-provider-key
SERVICE_API_TOKEN=replace-with-service-token
SERVICE_API_URL=https://api.example.com
```
| Kind of value | Where it belongs |
| - | - |
| CLI login or deployment token | The operator's CLI configuration or deployment environment |
| Required provider and tool credentials | The deployed agent's secret set |
| Runtime application URLs and other environment settings | The same set, under the names the package reads |
| Helper-only phone settings | The separately hosted helper |
| Platform session connection details | Supplied by the selected Cloud transport when the session starts |
Do not upload the operator's unrelated development credentials.
On a `daily-sip` route, remove helper-only entries from the file uploaded to the
agent. Keep entries marked as shared. See the [phone guide](/telephony/pipecat-twilio)
for each route's requirements.
`--file` sends every entry in the file. The generated Dockerfile reads no secret
values, and `.dockerignore` excludes `.env`. Keep the value file out of source
control. Unmute preserves this `.env` when it recompiles, but rewrites
`.env.example` with the current requirements.
Provider keys come from the chosen provider; the [model pages](/models/llm)
link to setup instructions. Prompt [variables](/build/variables) hold call state
and do not supply credentials.
## 4. Deploy and verify
Run `pipecat cloud deploy my-agent-pipecat --secrets my-agent-pipecat-secrets`
inside `my-agent/build/pipecat/`. The command builds the directory's Dockerfile
in Cloud. It creates the agent with that name, or asks to update a matching one.
See the [deploy reference](https://docs.pipecat.ai/api-reference/cli/cloud/deploy).
The agent name is yours to choose. Use the same name on every deploy. The
destination organization lives in your CLI configuration.
Check the deployment, then open a session through the transport your package
uses. For a browser session supported by the generated project, select a Cloud
public API key and start a Daily session:
```sh Terminal theme={null}
pipecat cloud organizations keys use
pipecat cloud agent start my-agent-pipecat --use-daily
```
Create a key through `organizations keys create` if none exists. This public
session key is separate from the deployment login and your model-provider keys.
Use the returned session connection details in your supported client. Phone
routes need their own [carrier setup and test](/telephony/overview).
| Check | What it establishes |
| - | - |
| Build succeeded | The generated project became an image |
| Agent status is ready | The platform can serve sessions |
| Latest deployment names the expected build | The intended compiled image is selected |
| Speak a short request and receive a relevant reply | Input, model request, and output all worked |
A greeting alone does not prove input works. Allow microphone access and unmute the
client before speaking. Then exercise one tool if the package uses tools.
This is deployment smoke acceptance; application-specific end-to-end tests come
next.
```sh Terminal theme={null}
pipecat cloud agent deployments my-agent-pipecat
pipecat cloud agent logs my-agent-pipecat
```
Use the [agent commands](https://docs.pipecat.ai/api-reference/cli/cloud/agent)
to select a session or deployment in logs. Leave the log level unset to see errors
as well as normal messages. Avoid sharing logs that contain caller data or secrets.
## Every later deploy
Edit the authored prompts, tools, supported local handlers, or model settings.
From the directory containing `my-agent/`:
```sh Terminal theme={null}
unmute validate my-agent --target pipecat
unmute compile my-agent --target pipecat
cd my-agent/build/pipecat
pipecat cloud organizations list
pipecat cloud deploy my-agent-pipecat --secrets my-agent-pipecat-secrets
pipecat cloud agent status my-agent-pipecat
```
Check the regenerated `.env.example` before deploying. A new provider, renamed
setting, or new tool may need another runtime value. Update the set only when
its values change; an unchanged code deployment uses its existing values and
needs no local secrets file. Keep the same organization, agent name, and secret
set to update the intended resource.
Cloud builds can reuse an identical build. Compare the selected build with your
intended version, then repeat the interaction check. Compilation replaces the
generated directory except `.env`. Any hand-edited generated Python is replaced.
Normal updates let active sessions finish on their existing image. New sessions
move to the new deployment as it rolls out. A failed deployment can leave the
previous ready version serving requests. See
[deployment behavior](https://docs.pipecat.ai/pipecat-cloud/fundamentals/deploy).
To return to a previous image, select its build ID from deployment history and
follow [redeploying a previous build](https://docs.pipecat.ai/pipecat-cloud/guides/cloud-builds#redeploying-a-previous-build).
This does not restore earlier secret values or authored files.
## Secrets-only updates
Changing the value of an existing runtime name requires no compile or new image.
Run these commands in the generated directory, using the existing set and region:
```sh Terminal — from my-agent/build/pipecat theme={null}
pipecat cloud secrets set my-agent-pipecat-secrets --file .env
pipecat cloud secrets list my-agent-pipecat-secrets
```
`set` adds new names and replaces supplied values; names omitted from the file
remain in the set. Removing a line from `.env` therefore does not remove a
deployed secret. Remove an obsolete name explicitly:
```sh Terminal theme={null}
pipecat cloud secrets unset my-agent-pipecat-secrets OLD_API_KEY
```
The listing shows names and readiness, without values. Wait for `ready` after
changes. Updating the set does not refresh running agents. Each deployment using
it needs a forced rollout, as described in
[Pipecat secret management](https://docs.pipecat.ai/pipecat-cloud/fundamentals/secrets).
Read the current image's build ID from deployment history. Replace the
placeholder below with that ID to roll out the same image without rebuilding:
```sh Terminal — from my-agent/build/pipecat theme={null}
pipecat cloud agent deployments my-agent-pipecat
pipecat cloud deploy --build-id --force
pipecat cloud agent status my-agent-pipecat
```
`--force` replaces running instances and can interrupt active sessions.
Verify a fresh interaction with the new value. Updating a stored value does not
create or revoke its provider key. Do that with the provider's key management.
If the code must start reading a new name, also change the package and recompile.
## Advanced
### Keep an instance ready
Pass `--min-agents` to `deploy`:
```sh Terminal — from my-agent/build/pipecat theme={null}
pipecat cloud deploy my-agent-pipecat --secrets my-agent-pipecat-secrets --min-agents 1
```
Unmute writes no manifest, so `warm_instances` in `targets.yaml` reaches
nothing yet. Use the flag. A positive value adds a standing cost. Zero lets the platform scale to zero.
A warm instance avoids cold starts. Some phone routes need it to answer within
the carrier's session window; see [Pipecat over Twilio](/telephony/pipecat-twilio#2-deploy-with-a-warm-instance).
### Renaming the agent
Changing the package or target name creates another deployment; it does not move
the existing one. A second hosting region also needs a distinct agent name and
a secret set in that region.
Compile the new target, provision its set, deploy, and verify an interaction.
Then point clients and carrier routes at the new name before retiring the old
agent. For `cloud-websocket`, update the service host in carrier markup; for
`daily-sip`, redeploy the helper with its new `AGENT_NAME`.
See the [phone guide](/telephony/pipecat-twilio) for route-specific steps.
### Customize supported code
Use native model settings and tools first. Local handlers compile into the
project; shared Python modules and dependency limits are covered in
[Going live](/deploy/going-live#advanced).
Unmute has no general Pipecat build hook or arbitrary dependency declaration.
Editing generated files does not create a supported extension.
Pipecat's deploy flags carry the host settings. Keep them in a deployment
script outside `build/`, so every deploy uses the same ones.
Use the [deployment reference](https://docs.pipecat.ai/api-reference/cli/cloud/deploy)
for host options and the [target reference](/reference/targets-yaml) for settings
Unmute owns.
## Troubleshooting
| Symptom | Cause | Fix |
| - | - | - |
| Deploy asks for an agent name or cannot find a Dockerfile | Wrong working directory or incomplete build | Compile, then deploy inside `my-agent/build/pipecat/` |
| Secret set is missing or not ready | Wrong organization/region, or provisioning is pending | Confirm the destination and matching region; wait for the set to report `ready` |
| Deploy reports ready but behavior stays old | Old compiled files, cached image, or client points elsewhere | Check the selected build and agent name; compile the changed package and redeploy |
| New secret value has no effect | Existing instances still hold their environment | Force a rollout of the current build after the set is ready |
| Session fails with a missing environment name | `.env` did not follow a package change | Compare with the current `.env.example`, then update the set and roll out |
| Import or data-file lookup fails | The module, dependency, or file was never packaged | Use the supported local-code layout and check the [customization limits](/deploy/going-live#advanced) |
| Provider rejects a parameter or region | Provider availability differs from package validation | Check that model's provider reference, credentials, and inference region; fix the binding and compile again |
| Another agent appears after a deploy | Organization, package name, or target name changed | Restore the intended destination and identity; inspect both resources before retiring either |
| Agent speaks but never hears you | Client microphone is muted or blocked | Enable the microphone and check the selected transport's input path |
| First session times out after an idle period | Worker is still starting | Wait for readiness and consider `--min-agents 1` for that route |
## Where to go next
The package lifecycle and supported customization.
Supported models, transport choices, and target settings.
Declare runtime names separately from their values.
Connect and verify the carrier route your package uses.
# Deploy to SLNG
Source: https://unmute.ai/deploy/slng
Deploy a package to SLNG, update the existing agent, and manage its credentials.
Deploy your package as a managed SLNG agent and test it in the browser.
Unmute turns your authored files into a deployment body. SLNG runs the agent,
so this route needs no Docker image or Python project.
On this page:
* [Quickstart](#quickstart) - the native deployment command
* [Choose the target](#1-choose-the-target) - region and supported package features
* [Select the organisation](#2-select-the-organisation) - authentication and destination
* [Supply credentials](#3-supply-credentials) - model keys and tool secrets
* [Preview and deploy](#4-preview-and-deploy) - files, checks and identity
* [Verify the agent](#5-verify-the-agent) - a complete browser interaction
* [Every later deploy](#every-later-deploy) - update the same agent
* [Secrets-only updates](#secrets-only-updates) - add, replace and remove values
* [Advanced](#advanced) - hosted tools and optional integrations
* [Troubleshooting](#troubleshooting) - symptoms and fixes
* [Where to go next](#where-to-go-next) - related guides
## Quickstart
For a new package, run this from the directory that will contain `my-agent`:
```sh Terminal theme={null}
unmute init
```
In the console:
1. Enter `my-agent` as the name.
2. Open **Identity → Target** and select **SLNG**.
3. Open **Behavior → Advanced → Advanced target settings → Deployment region** and enter one supported [SLNG region](/targets/slng#targets-yaml).
4. Return to **Create agent**, review the package and confirm.
The region field is labelled optional in the console, but SLNG requires it.
This path creates a package without code-target turn settings. Create it with
`--from-manifest` and a saved organisation manifest restricts the choices; see
[manifest-based initialization](/reference/cli/init#from-a-saved-manifest).
Already have a package declaring a `slng` target? Start here. Run these commands
from the directory containing `my-agent`:
```sh Terminal theme={null}
brew install slng-ai/tap/voiceai
voiceai login --profile production
unmute deploy my-agent --target slng --profile production --dry-run
unmute deploy my-agent --target slng --profile production
```
The profile name `production` is your local label for a credential. Use your
own name. Before deploying, supply any missing resources the preview names.
A successful deploy prints the agent ID. Open that agent in the SLNG dashboard
and choose **Test → Web session**. The sections below explain each step.
## 1. Choose the target
Merge this target into an existing `targets.yaml`. `eu-north` is one example;
choose a supported region that serves your models and language.
```yaml targets.yaml theme={null}
targets:
slng:
provider: slng
deployment_region: eu-north
```
Set to `slng`. The surrounding target name selects this build with `--target`
and names its directory under `build/`.
Exactly one [SLNG region](/targets/slng#targets-yaml). There is no default.
Omission, an unknown region and multiple regions are refused.
The package needs a name, one entry agent, a prompt, a fixed greeting, and
bindings for reasoning, speech recognition and speech generation. Keep those
in `agent.yaml` and the prompt files it references.
SLNG owns runtime versions, capacity and turn detection. Omit target `version`,
`pins`, `sdk_language`, `connection` and `warm_instances`. Tasks and typed
`local:` tools work, and `unmute deploy` publishes each local tool as a SLNG code
tool. Handoffs and prefetch are refused. See the
[complete target limits](/targets/slng#what-a-slng-package-may-not-ask-for).
### Choose models and their region
Set model bindings under `models.think`, `models.listen` and `models.speak` in
`agent.yaml`. A target can override an existing binding by name. See
[model configuration](/reference/agent-yaml#models) for the authored shape.
The SLNG driver joins a provider and model with `/`, unless the model already
contains `/`. It forwards each binding's `params` into that component's
provider options. It does not test model availability or provider option
support offline.
Use SLNG's [model discovery instructions](https://docs.slng.ai/examples/agents-config#finding-models)
to select models available to your organisation, language and region. The
[Unmute model pages](/models/stt) explain the bindings and target differences.
Provider defaults apply to omitted options; an accepted package can still fail
when a provider receives its first request.
`deployment_region` selects the hosted agent's region. An upstream model's
inference location is a separate provider setting. Choosing a hosting region
does not move that provider's inference service.
## 2. Select the organisation
Install the [voiceai CLI](https://docs.slng.ai/sdks/cli) and sign in with an API
key from the destination organisation. The login prompt keeps the key out of
your command history:
```sh Terminal theme={null}
voiceai login --profile production
```
Unmute needs a `voiceai` release that supports checked, resolved pushes.
It checks that capability before pushing and gives upgrade guidance if it is
missing. Use `voiceai 0.1.22` or later. A package with `local:` tools needs `voiceai 0.1.23` or later. Unmute refuses an older release before
it writes anything, with the command that upgrades it. No Python SDK version is
yours to install for this target.
Environment keys override the selected profile. Unmute reads `SLNG_API_KEY`,
then `VOICEAI_API_KEY`, then the profile. It also loads the package's `.env`
and `.env.local`. Remove unintended deployment keys from those files and
your shell when using a profile. The `credential from` line names the key a
deploy used.
There is no separate Unmute project selector for SLNG. The credential selects
the organisation, and `--profile` selects a saved credential when no environment
key overrides it. Use the same profile for every command below.
## 3. Supply credentials
These settings have different owners:
| Setting | Where it belongs |
| - | - |
| SLNG deployment key | Local `voiceai` profile or deployment environment |
| Model provider key | SLNG's [Bring Your Own Key page](https://docs.slng.ai/dashboard/byok), when using your own provider account |
| Hosted tool or MCP credential | Organisation Vault, under the exact required name |
| Shared non-secret text | A Vault variable, where the target supports it |
| Per-call input | An authored [variable](/build/variables) supplied at session start |
| Worker connection settings | SLNG manages them; this target emits no environment file |
Model credentials registered through BYOK are separate from tool secrets.
Choose a supported model in the organisation; putting its provider key in a
local `.env` file does not configure managed-agent BYOK.
The generated `build/slng/README.md` lists the Vault requirements visible to the
compiler. Deployment also checks credentials required by published tools and
MCP servers. A declaration names a requirement; it does not supply its value.
See [Credentials](/build/credentials) and [the SLNG Vault](/targets/slng#the-vault).
Create a missing tool secret by name and enter its value at the hidden prompt:
```sh Terminal theme={null}
voiceai --profile production secret create SERVICE_API_TOKEN
voiceai --profile production secret get SERVICE_API_TOKEN
```
Replace `SERVICE_API_TOKEN` with a name in your package's requirements.
The read command reports metadata, including `has_value`, without displaying
the value. Vault writes require an organisation admin.
For a batch, prepare a private file containing only required tool credentials:
```dotenv runtime.secrets.env — placeholders; replace before use theme={null}
SERVICE_API_TOKEN=replace-with-the-service-token
```
```sh Terminal theme={null}
voiceai --profile production secret create --secrets-file runtime.secrets.env
```
Keep the file outside `build/` and out of source control. Do not upload an
entire development environment or the deployment key as a tool secret.
A real `unmute deploy` can also offer to fill missing Vault entries with your
consent; a dry run cannot fill them.
## 4. Preview and deploy
You can inspect the generated files before any account checks:
```sh Terminal — from the directory containing my-agent theme={null}
unmute validate my-agent --target slng
unmute compile my-agent --target slng
```
Both commands work offline. Compilation writes `agent.json`, `README.md` and
`compile-report.json` into `my-agent/build/slng/`. The report lists checks
that need the live account. Edit the authored package and compile again;
generated files are replaced.
Deploy from the same parent directory, passing the authored package path:
```sh Terminal theme={null}
unmute deploy my-agent --target slng --profile production --dry-run
unmute deploy my-agent --target slng --profile production
```
`deploy` validates and compiles again automatically. It resolves hosted tool
names and MCP selections in the chosen organisation, checks the resolved
contracts, and pushes that checked body. It writes a `deploy-report.json`
beside the generated files when it reaches the push stage.
A dry run changes no remote state. A real run may refresh MCP discovery or
create Vault entries with your consent before a later check fails. Its report
records those changes. The agent is written only after its required checks pass.
The deployed name joins the package name and target name: package `my-agent`
with target `slng` deploys as `my-agent-slng`. SLNG assigns a separate agent ID.
The report records that ID, but Unmute stores no deployment lockfile: later
pushes resolve the name again. Find the resource with:
```sh Terminal theme={null}
voiceai --profile production agents list
```
Do not post `build/slng/agent.json` with `voiceai agents create`. The compiled
body still contains names that deployment must resolve to platform identifiers.
## 5. Verify the agent
Open the deployed agent in the dashboard and choose **Test → Web session**.
Fill required call inputs, allow microphone access, and start the session.
See [SLNG's test panel](https://docs.slng.ai/dashboard/agent-infra#test-your-agent).
Say a short question and wait for a relevant answer. If the package uses a
tool, exercise one safe tool interaction and check the result. A greeting
proves audio output; a response to your question also checks input and reasoning.
Use the returned agent ID and call ID to read the call. Replace the angle-bracket
placeholders before running:
```sh Terminal theme={null}
voiceai --profile production agents calls list --json
voiceai --profile production agents calls get --json
```
Check the transcript, tool results and any `call_end_reason`. A completed push
proves that the platform accepted the configuration. A completed interaction
is the deployment smoke check; application-specific tests still come next.
## Every later deploy
Change your authored prompt, model bindings, configuration or tool references,
then preview and update with the same target and profile:
```sh Terminal theme={null}
unmute deploy my-agent --target slng --profile production --dry-run
unmute deploy my-agent --target slng --profile production
```
Unmute regenerates the body on each run. There is no image to rebuild and no
secrets file required on update. Existing Vault values remain in the Vault.
A push replaces the agent configuration. Fields edited only in the dashboard
can be overwritten, and tool references removed from the package are detached.
Read the preview's removals. Hosted tools resolve to their latest published
versions on each deploy; a committed code-target mirror does not pin them here.
The same deployed name updates the existing agent. If the name is ambiguous,
pass `--agent-id `. The ID remains the same on update. An unchanged
push creates no version. Test a fresh session after each change; Unmute offers
no worker restart or rolling-update controls for this managed runtime.
For rollback, SLNG's [Versions tab](https://docs.slng.ai/dashboard/agent-infra#versions)
can restore a saved version after showing its checks. Bring the authored package
back into agreement before the next deploy, which would replace that restored
configuration again.
### Renaming the agent
Changing the package or target name creates a different deployment name.
It can create a second agent and leave the first running. Integrations holding
the old ID keep reaching the old agent. Inspect `agents list` and update those
integrations deliberately; a rename is not a migration.
## Secrets-only updates
For an existing Vault name, update its value without compiling or deploying:
```sh Terminal theme={null}
voiceai --profile production secret create SERVICE_API_TOKEN --overwrite
voiceai --profile production secret get SERVICE_API_TOKEN
```
The first command prompts for the replacement. Omit `--overwrite` when adding
a new name. If it already exists, the CLI asks before replacing it; a
non-interactive run refuses without overwrite consent.
For a file, `--secrets-file runtime.secrets.env --overwrite` adds new entries
and replaces listed existing entries. It does not remove entries omitted from
the file. List metadata with `voiceai --profile production secret list`.
SLNG resolves tool credentials at execution time, so changing an existing
Vault value needs no agent rebuild. Check a fresh tool interaction after
rotation; do not assume an active call has refreshed every credential.
To remove a secret, use the dashboard's Vault page. The CLI has no delete
command. SLNG blocks deletion while active configurations or calls still
reference it. Remove the use first, deploy that change if needed, then delete.
See [Vault management](https://docs.slng.ai/dashboard/vault).
Replacing a stored value does not create or revoke its provider key. Do those
operations in the provider's account. For model credentials, use
[BYOK rotation](https://docs.slng.ai/dashboard/byok#rotating-a-key).
## Advanced
### Reuse tools and shared code
Start with supported package declarations. For external services, reference
published [hosted tools](/build/tools/hosted) or select named
[MCP tools](/build/tools/mcp) from your organisation.
A typed `local:` tool works here. `unmute deploy` publishes it as an SLNG code
tool, after it runs the tool once on `tools/.sample.json`. See
[a local tool on this target](/targets/slng#a-local-tool-on-this-target). The
target refuses `webhook:` tool bodies. It has no shared-module packaging, custom
Dockerfile, dependency override or lifecycle hook. Create a request tool on
SLNG and reference it with `slng:`, or choose LiveKit or Pipecat when the
package must own more Python.
A hosted tool needs no local mirror for this target. `unmute pull` is for a
package that also compiles to a code target, where that mirrored tool runs.
### Receive phone calls
Configure a carrier connection through
[SLNG Telephony](https://docs.slng.ai/dashboard/telephony), then attach the
inbound trunk when `unmute deploy` offers it or in the agent's Telephony tab.
The attachment does not change the carrier's routing.
Inbound calls supply no web-session input payload. Give required `with:`
inputs valid defaults or leave those arguments for the model to collect.
Call the number and inspect the new SLNG call record. Outbound calling needs
its own outbound connection; an inbound attachment does not enable it.
### Create a session for your own client
With every input at its default, no request body is needed:
```sh Terminal theme={null}
voiceai --profile production agents web-sessions create
```
To fill call inputs, save a request body and pass it with `--file`:
```json session.json theme={null}
{"arguments": {}, "participant_name": "tester"}
```
```sh Terminal theme={null}
voiceai --profile production agents web-sessions create --file session.json
```
The result contains `livekit_url` and `livekit_token` for your client.
Treat the token as a credential. This command requests a session; it opens no
browser and does not prove a worker joined. Keep deployment keys on your server.
## Troubleshooting
| Symptom | Cause | Fix |
| - | - | - |
| The agent lands in the wrong organisation | An environment key overrides the profile | Read the `credential from` line, check the package's `.env` files and shell keys, then preview again with the intended profile |
| A second agent appears | The package name, target name or destination changed | Find both with `agents list`; restore the intended name and select the correct ID |
| `agent ambiguous` | More than one agent matches the name | Pass `--agent-id ` after checking the destination |
| `vault missing` | A required secret is absent or exists as a variable | Create the exact case-sensitive name with the required Vault kind |
| A hosted tool is missing | The organisation has no published tool with that name | Publish it in SLNG or change the authored reference |
| `--require-resolved` is refused | The installed CLI lacks checked pushes | Upgrade `voiceai` using the install instructions above |
| `AGENT_MODEL_UNAVAILABLE` | The organisation, region or language cannot use the selected model | Choose a compatible model using SLNG's model selector and update the package |
| The greeting plays but input is absent | The client is muted or its microphone is blocked | Allow microphone access, unmute and check for caller text in the transcript |
| A call ends with a component error | STT, LLM, TTS or a tool failed at runtime | Read the call details, fix that component's credentials or options, then test again |
| No phone call appears in SLNG | Carrier routing failed before the agent started | Check the number's routing and inbound connection |
A dry run may report an unusable MCP snapshot. A real deploy can refresh it
once and recheck it. SLNG runs a `local:` tool as a code tool, built from its typed handler.
## Where to go next
The package-to-deployment workflow across targets.
Every flag and deployment check.
Model bindings, Vault references and target limits.
Declare names and supply values separately.
# The dev loop
Source: https://unmute.ai/dev/overview
What unmute dev actually does, how to pick a target, and where the logs are.
`unmute dev` is the loop you live in while building an agent. One command
compiles the package, starts the target's local runtime, and serves a web page
you can talk through.
```sh theme={null}
unmute dev examples/salon-concierge --target pipecat
```
```text theme={null}
compiled examples/salon-concierge/build/pipecat
starting the local Pipecat agent...
▸ http://localhost:8765/?agent=pipecat
ctrl-c to stop · logs: examples/salon-concierge/build/pipecat/dev.log
```
That names a package sitting somewhere else, which is why it carries a path.
The argument is optional: inside a package, `unmute dev` on its own runs the
directory you are standing in, and every path it prints is relative to there.
On this page:
* [The one way to run](#the-one-way-to-run) - one command
* [What it does, in order](#what-it-does-in-order) - the five things it runs
* [Every flag](#every-flag) - targets, ports, seeding
* [Typing instead of talking](#typing-instead-of-talking) - a text box and a no-microphone call
* [The two views](#the-two-views) - the transcript and the timings
* [Advanced](#advanced) - environment, seeding, more than one session
## The one way to run
A phone call reaches an agent that is deployed, so telephony is verified after
you deploy. [Phone calls](/telephony/overview) covers what a route is.
Deploying to [LiveKit Cloud](/deploy/livekit-cloud) or [Pipecat
Cloud](/deploy/pipecat-cloud) puts an agent where a real call can reach it.
## What it does, in order
The package is generated into `build//`. You do not run `unmute
compile` first.
Pipecat starts the generated `bot.py` directly with `uv`. This keeps its
WebRTC ICE candidates reachable from the host browser. LiveKit uses Docker
Compose because its stack also includes a local LiveKit server.
A small local web server opens your browser straight away, before the
runtime is up. The page shows the startup output while it waits, so a build
that fails is something you read rather than guess at.
Pipecat waits for its `/status` response. LiveKit waits for the worker to
register, up to three minutes. The call button stays unavailable until then,
and the page moves to the conversation view once a call would be answered.
Ctrl-c stops the local Pipecat process or removes the LiveKit stack. LiveKit
data volumes are kept.
Pipecat browser development needs `uv`. LiveKit browser development needs
Docker with Compose.
## Picking a target
A package with one target needs no flag. With more than one:
* In a terminal, `unmute dev` asks which target to run.
* Without a terminal, for example in a script, it refuses and tells you the
choices:
```text theme={null}
unmute: dev examples/salon-concierge: multiple targets declared; pass --target : livekit (livekit), pipecat (pipecat)
```
`--target` takes exactly one name here, unlike `validate` and `compile`, which
take a repeatable list. A name that is not declared is an error:
```text theme={null}
unmute: dev examples/salon-concierge: target instance "nope" is not declared
```
## Every flag
Which target to run. Needed when `targets.yaml` declares more than one. See
[Picking a target](#picking-a-target).
The local web page you talk through.
The host port the local agent runtime uses.
Seed a declared variable before the call. See
[Seeding variables](#seeding-variables).
Stand in for a fact the phone network would supply, such as
`from_number`. See [Seeding call facts](#seeding-call-facts).
Do not open a browser. See [Not opening the browser](#not-opening-the-browser).
Print the runtime's own logs as well as the run's. See [Logs](#logs).
### Ports
When a default port is busy, most often because another session holds it, a
free one is chosen and the printed URL names it. Pass the flag to pin a port; a
pinned port that is busy is a refusal:
```sh theme={null}
unmute dev examples/salon-concierge --target pipecat --port 8790 --bot-port 7890
```
The web page URL always carries the target name, for example
`http://localhost:8765/?agent=pipecat`.
## Typing instead of talking
You can type to the agent as well as talk to it. While a call is connected, a
text box sits in the call bar. Type a line and press Enter, or press **Send**.
The agent takes it as the caller's turn and answers by voice, as it does for
speech. Your line shows in the conversation as the caller's words.
To start a call with no microphone, press **Text only** next to **Connect**.
The page never asks for microphone permission. You still hear the agent, and
you type your side. **Connect** is unchanged and still uses the microphone.
How the line reaches the agent depends on the target:
| Target | What the page sends |
| - | - |
| Pipecat | An RTVI `send-text` message on the `chat` data channel. It interrupts the agent if it is speaking, then runs the model on your line. |
| LiveKit | A text stream on the `lk.chat` topic. The generated agent reads it, because LiveKit's agent session listens on that topic by default. |
A text-only Pipecat call sends no audio, so a package with an idle prompt can
speak up after a quiet spell. That is the same prompt a silent caller would
hear.
## The two views
The page has two views and one set of call controls that stays put across both,
so switching never interrupts a call.
| View | What it is for |
| - | - |
| Conversation | streaming words, current activity, and expandable measurements |
| Logs | runtime output and activity or measurement updates labelled by call |
Recognized words appear as they arrive. Each finalized part becomes normal text
immediately, even while the model is still silent. The agent's text also grows
as it is generated. Generated words can lead audio playback; the page keeps
those states separate and marks interruptions or incomplete replies.
Model and tool activity appears before answer text. Each tool call has its own
row, even when two calls use the same name. Reported outcomes update that row;
`returned` means a result arrived, not that the business action succeeded.
A call into a task, or a handoff to another agent, gets its own row too,
labelled `HANDOFF`, and carries no duration: it hands control over rather than
returning a result. That row is what accounts for the model call that follows
it.
A reply summary shows its reported latency and model-call count. Each `LLM 1`,
`LLM 2`, and later row shows its own first-response and full-duration values
without expanding anything. TTS first-audio time and tool duration stay visible
too. **Debug details** holds secondary timings and source/model details. See
[Reading the latency numbers](/optimization/latency) for definitions. Counts appear only after
identified model calls arrive.
Only captured measurements appear. Missing and pending values have no
placeholder; a measured zero is `0ms`. Small positive values stay positive:
`1ms`, or `<1ms` below one millisecond. Timing values can overlap, so adding
stage values does not reconstruct reply latency.
The conversation follows new content until you scroll back. **Latest** returns
to the newest content with one action. Details keep their open state and work
with Enter or Space. Ending a call retains its words and marks unfinished text;
starting another call clears that history.
Live-data status is separate from audio status. Reconnecting the event feed
does not restart the microphone. If some history cannot be recovered, the page
keeps the incomplete-history label until the next call and shows observed model
calls labelled as observed. Late updates stay with their known exchange;
unassignable values remain labelled as unassigned. **Call diagnostics** is the
inspector beside the conversation, or under it on a phone. Its **Unassigned
activity and measurements** section holds those values and call-level
first-speech measurements. Its **Reply time** section holds Pipecat's reply-time
breakdowns. It starts collapsed and appears only when there is data to inspect;
it does not insert diagnostic sections between turns.
**The call's state shows as it changes.** Every save to `State` is a row in the
conversation, at the point where it happened. The row names what set the value:
a step finishing, a pre-fetch, a carrier fact or a dispatched value. A changed
value shows what it was before. The **State** section, above Call diagnostics,
holds every field in `state.py`'s order with its current value and what set it,
and marks the newest change in yellow. A value that waits for the caller's yes
reads `not confirmed` until the step that confirms it hears one. Hover a field's
name for its type and description. These are the call's real values, so they
can include a tool's result and the caller's details; they stay in
`build//dev.log` and this local page.
The `HANDOFF` row carries no duration on purpose. A task, a flow, or a
handoff to another agent reaches the framework as a function call, so it could
be timed like a tool. But a task or a flow does not return until
everything it started has finished, and a handoff never returns at all. Timed
that way, a three-turn task would appear as one very slow tool, which is the
opposite of what the numbers are for. The row marks the moment control moved,
and the model call that follows it is timed on its own.
[Reading the latency numbers](/optimization/latency) covers what each number means, where
the time goes in a voice turn, and how to tell which part is slow.
The **Metrics** view sums up the current call from the same records. Its tiles
show how long the caller waited, STT and turn decision, LLM first token and TTS
first audio at p90, and the error count. Below them is one row per caller turn:
what the caller said, how long they waited in silence, and the first number of
each stage. A turn can hold several replies, such as a filler and then the
answer, so its wait sits on the turn and not on each reply. Open a turn to see
every stage on its own row: STT and turn decision, each LLM request, each tool,
each TTS request, and the wait. Each bar runs from zero to two seconds and marks
that stage's limit. These limits are the UNMUTE studio's defaults.
Below the turns, **Latency by model** has one section per kind. STT shows the
final transcript and the turn decision. LLM shows time to first token, the whole
request and requests per turn. TTS shows time to first byte, the whole synthesis
and requests that never played. Tools and handoffs are listed by name.
The logs view is in front while the target is starting, and the conversation
view takes over once the agent is ready. If anything in the startup output looked
like a failure, the logs view stays in front instead, and the count of those
lines sits on the **Logs** cell in the top bar, so it is visible from every view. Pick a view yourself and
the page stops moving it for you.
Filter the output by typing, or narrow it to output, measurements, or problems.
There is no log-level parsing behind those buttons, just a match on the text,
which is why it does not break when a provider reformats a line.
**A failed start is now visible in the browser.** The page stays up so you can
read the output, the terminal still prints the error and the log path, and the
command still exits non-zero.
## Advanced
### Logs
**Every run writes its log into the build directory**, and prints the path when it
starts. That file is the first place to look when the page loads but nothing
speaks, and it is where a failure to start explains itself. It holds everything
the process printed, measurement lines included, so it always matches the run.
The log file is always `build//dev.log`. The path is printed with the
ready line, exactly as you will see it. From inside a scaffolded package, run
with no argument, that reads:
```text theme={null}
▸ http://localhost:8765/?agent=livekit
ctrl-c to stop · logs: build/livekit/dev.log
```
The file holds the local runtime's output and the reason a start failed. Raw
dev records include recognized and generated transcript text. The visible
measurement filter leaves out repeated transcript fragments. The file is
rewritten on every run, so the file you are looking at is
always this run.
To follow the same output in your terminal while it runs, add `--verbose`. The flag
means "follow container/agent logs on stderr", and without it the log goes to the
file only:
```sh theme={null}
unmute dev examples/salon-concierge --target pipecat --verbose
```
### Not opening the browser
```sh theme={null}
unmute dev examples/salon-concierge --target pipecat --no-open
```
The URL is still printed. Useful over SSH, and in scripts.
### Environment
`unmute dev` builds the run's environment in this order, with later files
winning:
1. your shell environment
2. `.env` in the directory you run the command from
3. `.env.local` in the directory you run the command from
4. `.env` in the package directory
5. `.env.local` in the package directory
So a repository wide `.env` can hold shared keys while `.env.local` overrides
it, and one package can override both. The generated
`build//.env.example` lists exactly what you supply.
### Seeding variables
`--var name=value` stands in for the values a production call would arrive
with. It is repeatable, and it only accepts variables declared with
`source: call_start`. The value is parsed against the field's type in
`state.py`, and a model or a list is passed as JSON.
```python state.py theme={null}
class State(BaseModel):
customer_id: str = Field("cus_1001", description="CRM id of the caller.")
```
```yaml agent.yaml theme={null}
variables:
- name: customer_id
source: call_start
```
```sh theme={null}
unmute dev my-agent --var customer_id=cus_2002
```
Leave the flag out and the field's default is used instead. See
[variables](/build/variables) for what happens when you try to seed something
else.
### Seeding call facts
`--source name=value` stands in for a fact the call itself carries, such as
the caller's number. It is repeatable, and it only accepts the eight facts a
call carries: `from_number`, `to_number`, `call_id`, `direction`, `carrier`,
`connection`, `session_id`, `stream_id`.
```sh theme={null}
unmute dev my-agent --source from_number=+34600111222
```
This seeds the fact, which a `prefetch:` entry then reads, so the run
exercises the pre-fetch, the confirmation marking, and the read back. On a
real call the carrier's own value wins: a seed only fills in what the route
gave nothing for.
Which facts a real call actually carries depends on the route: LiveKit's two
routes grant the most, and Pipecat's two Twilio routes grant a smaller set,
one direction only for a phone number. Seed whichever your target's route
grants; [Where it works](/build/prefetch#where-it-works) has the full grid.
Do not use `--var` to seed a caller's number. `--var` writes the variable
directly, so it skips the pre-fetch, marks nothing as awaiting confirmation,
and lets a local run act on a number it never read back. That is a path a
real call cannot take.
### More than one session at a time
Each `unmute dev` run of a LiveKit package is its own Compose project, named
from the package path and the target. Two runs from the same path share one
project, so the second replaces the first. Two runs from different paths, such
as two checkouts of the same agent, run side by side: each picks a free set of
LiveKit server ports and a free page port.
To pin the LiveKit ports yourself, move signaling, TCP fallback, and UDP media
as one set:
```sh theme={null}
LIVEKIT_HOST_PORT=7890 LIVEKIT_TCP_HOST_PORT=7891 LIVEKIT_UDP_HOST_PORT=7892 \
unmute dev my-other-agent --target livekit --port 8766
```
A run stops its own stack when it ends, including on ctrl-c and on a closed
terminal. A stack whose `unmute dev` process was killed outright is stopped by
the next run, which says so. When a stack cannot be stopped, the run prints the
`docker compose` command to run by hand.
A second Pipecat run picks a free agent port the same way when `--bot-port` is
not passed.
## Where to go next
See the whole call after it ends: transcript, tool calls, and per-span
timing.
What each route means, and how a call reaches a deployed agent.
Every flag, with defaults and requirements.
What each number under a turn means, and which part to fix.
# Unmute
Source: https://unmute.ai/index
A declarative standard for voice agents. Describe the agent once, compile it to SLNG, LiveKit, Pipecat, or Twilio.
Unmute is a declarative standard for voice agents. You describe the agent
once, in YAML and Markdown. The compiler turns that package into a native
project for the target you pick: SLNG, LiveKit, Pipecat, or Twilio.
## The problem
A voice agent is a small idea buried in a lot of plumbing. Speech in, a model
that thinks, speech out, a way to end the call, a way to hand the caller to a
person. Every framework asks you to write that plumbing again, in its own
shape.
So teams end up here:
* The prompt, the tools, and the phone number live in the same file as the
session setup, the audio pipeline, and the retry logic.
* Changing the voice means reading framework code.
* Trying a second framework means rewriting the agent.
* Nobody can answer "what does this agent actually do" without reading Python.
## What Unmute does
Unmute splits the agent from the code that runs it.
You describe the agent once: who it is, which models it uses, which tools it
can call, how it hands work to another agent, what happens on a phone call.
That description is the package. Nothing in it belongs to one framework.
Then you pick a target. A target is where the agent will run, and Unmute
compiles the package into what that target expects:
* **SLNG** is a hosted target. You get a deployment body, `unmute deploy`
pushes it, and SLNG runs the agent.
* **Pipecat** and **LiveKit** generate a Python project with a Dockerfile,
`.env.example`, and runbook. You own, host, and run that project.
* **Twilio** generates a FastAPI app for ConversationRelay. You host it,
then `unmute deploy --target twilio` connects your Twilio number to it.
`agent.yaml`, your prompts, your tool files. Read it and you know what the
agent does.
The same package compiles to SLNG, LiveKit, and Pipecat. Same
prompt, same tools, same behavior. A phone agent with one prompt can
also compile to a Twilio ConversationRelay app.
## What a package looks like
An Unmute package keeps the agent in `agent.yaml`, its prompt in a Markdown
file, and the target choices in `targets.yaml`. The guided path shows the
complete files, then explains each block where you first need it.
Read, validate, and compile the canonical agent package.
Jump to complete key lists for every package file.
## Who it is for
* Teams who ship voice agents and want the agent's behavior in files a
reviewer can read, not in framework code.
* Teams who want to compare SLNG, LiveKit, Pipecat, and Twilio without rewriting
the agent for each target.
* Anyone who wants what the agent does reviewable in a pull request.
Unmute itself is not a runtime. It compiles ahead of time and hands the result
to the target: a project you run, or a deployment SLNG runs for you.
## Where to go next
Get the `unmute` binary.
From nothing to an agent you can talk to in your browser.
The four stages between your package and what each target runs.
The guided path: one agent, then tools, then everything else.
## Join the community
Unmute is open source and MIT licensed. Anyone can use it, and anyone can
contribute to it. Bring a question, show what you built, or send the change
yourself. The [contributing guide](/community/contributing) says what a pull
request needs.
Ask a question, show what you built, and talk to the people who maintain
Unmute.
Read the source, file an issue, and open a pull request.
The issue, an example that uses your feature, a video, a README and the
docs page.
What shipped in each release, newest first.
# Live model
Source: https://unmute.ai/models/live
Configure the OpenAI live model, its voice, and the backend that runs tools.
Connect a live voice model to the reasoning backend that runs your agent's tools.
The agent binds a named `models.live` entry through `live:`; that entry can bind an OpenAI `models.think` entry through `backend:`.
On this page:
* [Quickstart](#quickstart) - start with a working package
* [Configure the entry](#1-configure-the-live-entry) - fields and defaults
* [Attach the backend](#2-attach-a-backend-for-tools) - tools and knowledge
* [Pipecat](#pipecat) - target support
* [LiveKit Agents](#livekit-agents) - target support
* [Advanced](#advanced) - session behavior and limits
* [Troubleshooting](#troubleshooting) - symptoms and fixes
* [Where to go next](#where-to-go-next) - guides and references
## Quickstart
From a clone of the [examples](https://github.com/slng-ai/unmute/tree/main/examples), set `OPENAI_API_KEY` in your shell or `examples/takeaway-orders/.env`.
The package is complete and includes a live model, backend, local tools, and knowledge lookup.
```sh Terminal, from the repository root theme={null}
unmute validate examples/takeaway-orders
unmute compile examples/takeaway-orders
unmute dev examples/takeaway-orders --target pipecat
```
Ask for salt and pepper chicken and egg fried rice for collection.
Check that the tool results determine the order and its total.
For a new package, follow the complete [Live quickstart](/build/architecture/live#quickstart).
## 1. Configure the live entry
To reuse the takeaway setup, replace its model palette and live binding with this **replacement fragment**.
It uses shorter names, `voice` and `fast`. Keep the existing instructions, tool attachments, and other package settings.
```yaml examples/takeaway-orders/agent.yaml theme={null}
architecture: live
models:
live:
- name: voice
provider: openai
model: gpt-live-1
voice: marin
backend: fast
think:
fast:
provider: openai
model: gpt-5.6-terra
agents:
- name: counter
prompt: instructions.md
live: voice
```
Set `architecture: live` explicitly. If omitted, the architecture is `cascade`.
The agent's `live:` binding replaces its `think:` and `speak:` bindings.
`name`, `provider`, and `model` are required. `voice`, `backend`, and `description` are optional unless the tool setup requires a backend.
Name used by the agent's `live:` binding. It must be unique across model sections.
OpenAI is the supported live provider on both code targets. There is no wildcard provider route.
Provider model ID, such as `gpt-live-1`. It is forwarded as written; access and availability are checked by the provider when the session starts.
Provider voice ID. Omitted means the provider's default voice.
OpenAI backend for tools and reasoning. Required when the agent has tools, including knowledge lookup. The referenced entry cannot set `endpoint_env`.
Optional note for package readers. It has no runtime effect.
A live entry does not accept `temperature`, `language`, `speed`, `params`, `pace`, `endpoint_env`, or per-target model overrides.
Validation refuses these settings rather than ignoring them.
## 2. Attach a backend for tools
With the replacement names above, `voice` hands tool work to `fast`.
The backend calls the attached local and knowledge tools, and the live model speaks the result.
The backend must be at OpenAI. Both models and the knowledge embeddings use `OPENAI_API_KEY`.
Only the backend's **model name** reaches the live service.
Its `params:` do not configure the live session, even when they appear in `compile-report.json`.
With no attached tools, `backend:` is optional; requests that need a backend may be declined.
Use the [Live tool walkthrough](/build/architecture/live#2-give-the-backend-a-tool) to attach a new tool.
Use [Knowledge bases](/build/tools/knowledge) for document lookup.
## Pipecat
| Provider | Configuration |
| - | - |
| `openai` | `gpt-live-1`, `OPENAI_API_KEY`, and an OpenAI backend when tools are attached. |
Pipecat keeps local voice activity detection for inactivity and reply measurements.
It does not use that detector to end the live model's turn.
## LiveKit Agents
| Provider | Configuration |
| - | - |
| `openai` | `gpt-live-1`, `OPENAI_API_KEY`, and an OpenAI backend when tools are attached. |
LiveKit uses the model's speech events and adds no local voice activity detector to the live session.
Both targets support browser audio. The slng target refuses `architecture: live`.
## Advanced
The session fixes its instructions, model, and voice when it starts.
A greeting is an opening instruction, so the model can paraphrase it.
The model also controls interruptions; `conversation.interruption` is refused.
Inactivity nudges ask the model to check whether the caller is still there.
The inactivity end timer ends the call.
The dev page shows speech transcripts, replies, and backend tool calls with their durations.
It does not show per-reply first-token or request timing for live speech.
Live serves one agent, with local and webhook tools, built-in tools, and knowledge lookup.
| Unsupported setting | Reason |
| - | - |
| Tasks and transfers | The session has no `tasks`, `flows`, `handoffs`, or `transfers`. |
| Listen, speak, and turn sections | The model listens, speaks and decides the turn itself. |
| Variables and pre-fetch | This shape carries no call state. |
| Tracing | This shape has no traced worker. |
| MCP tools | This shape cannot start and close a server connection. |
| Phone connections | Live compiles for the browser route in this version. |
Use [Cascade](/build/architecture/cascade) when your workflow needs these features.
See the [architecture comparison](/build/architecture/overview#2-check-what-your-package-needs) before switching an existing package.
## Troubleshooting
### Validation asks for a backend
The agent has a tool, but its live entry has no backend.
**Fix:** set `backend: fast` and provide the OpenAI think entry shown above.
### A backend setting has no effect
The live service receives only the backend model name.
**Fix:** remove unsupported tuning assumptions; choose a suitable backend model and verify the result in a call.
### The first call fails with a provider error
The API key may lack access to the selected model or voice.
**Fix:** read the provider error in the dev logs and check both the live and backend model IDs.
### Validation refuses a task or phone connection
Those features need the cascade architecture.
**Fix:** follow the [switching guide](/build/architecture/overview), or keep this package as a single browser agent.
## Where to go next
Start from a complete package and add a tool.Compare live, realtime, and cascade.
# Reasoning model
Source: https://unmute.ai/models/llm
The think binding: every key it takes, the vendors each target can construct, and what happens when yours is not listed.
`models.think` picks the model that decides what to say and when to call a tool.
**SLNG serves this role as a proxy with a cache in front.** The
[Context Router](/optimization/context-router) answers the turns it judges
repeatable and calls your model for the rest. The model stays yours to
choose, and so does the provider that serves it, so one `SLNG_API_KEY` can
sit in front of a supported upstream. Declare its key too: upstream
credentials are forwarded to SLNG. Keep `agent_id` stable for cache reuse;
change it when prompt changes invalidate old answers.
On this page:
* [Quickstart](#quickstart) - the smallest binding that works
* [Every key a think binding takes](#every-key-a-think-binding-takes) - the full shape
* [Why `reasoning_effort` is there](#why-reasoning_effort-is-there) - the line that stops a 400
* [LiveKit Responses API](#livekit-responses-api) - one target's own client
* [Native Gemini locations](#native-gemini-locations) - Google Vertex with your API key
* [Pipecat](#pipecat) and [LiveKit](#livekit) - the vendors each target can construct
* [When your provider is not listed](#when-your-provider-is-not-listed) - two different answers
* [Fallback](#fallback) - what to try when the first call fails
* [Troubleshooting](#troubleshooting) - the refusals that come up most
## Quickstart
Set the agent's `think: reasoning` to use this binding, or keep the existing
binding name when replacing its configuration.
```yaml agent.yaml theme={null}
secrets:
- SLNG_API_KEY
- OPENAI_API_KEY
models:
think:
reasoning:
provider: slng
agent_id: my-agent-v1
upstream:
provider: openai
model: gpt-5.6-terra
params:
world_part: eu-west
reasoning_effort: "none"
```
```sh theme={null}
unmute validate my-agent
```
Model ids are forwarded to the vendor exactly as you write them. Unmute keeps
no allowlist, so a typo surfaces as a provider error at run time. The LiveKit
Responses mode below is the narrow exception: `api` selects the generated
client and `reasoning_effort` becomes the API's nested reasoning setting.
## Every key a think binding takes
`provider:` and `model:` carry a plain binding. The rest shape the request, or
put the Context Router in front.
A provider supported for this role and target, listed on the model pages. Required for
an API binding; there is no inferred API provider. `local` selects local placement.
Provider model id, passed through as written. Required where the selected integration
requires a model; otherwise its default applies. No model id is checked against a provider catalog.
Provider parameter names and values. Omit to add no extra parameters. Provider limits
apply; Unmute does not define a universal accepted set. SLNG `params.world_part`
is checked against its supported regions.
Sampling temperature on a `think` entry. Provider-defined values and limits; omitted
leaves the provider default.
Nucleus sampling value on a `think` entry. Provider-defined values and limits; omitted
leaves the provider default.
Sampling count on a `think` entry. Provider-defined values and limits; omitted leaves
the provider default.
Points at a variable holding an OpenAI-compatible endpoint URL, for a binding
that talks to your gateway directly. On Pipecat this is what lets an unlisted
provider through.
Whether the model is called over the network or runs in the agent's own
process. Left out, it is `api` whenever the entry names a provider or a
model. `local` is refused on the slng target.
Names from the same `think` or `listen` section, in retry order. Omit for no fallback
chain. Cycles and other roles are refused; Pipecat refuses generated fallback.
Literal text appended to every system prompt this binding sends: each agent's,
each task's, and the summarizer's. No `{{variables}}`. It exists for models
that take instructions no parameter can carry. A per-target override cannot
name a different value.
Scopes the Context Router's cache. One stable value per package, written by
you, with a version suffix you bump after a prompt change you judge
meaningful. Router bindings only, and refused on any other.
Where the router actually calls the model and whose credentials pay for it.
Required on a router think binding, because the configuration travels inline
on every request. Router bindings only.
An author note. It reaches no generated artifact, so it is for the next
person reading `agent.yaml`.
## Why `reasoning_effort` is there
`gpt-5.6-terra` is a reasoning model, and OpenAI rejects a chat completions
request that carries function tools unless the request also sets
`reasoning_effort`. Leaving the line out is not the same as leaving the value
alone: the server applies its own default, and every turn comes back as HTTP
400\. This model takes `none`, `low`, `medium`, `high`, and `xhigh`. It rejects
`minimal`.
Every shared example profile writes `none`, and so does `unmute init`. Keep the
line whenever the agent has tools; a target-specific Responses override is the
exception below.
On LiveKit the line matters for a second reason. `livekit-plugins-openai`
1.8.8 injects `reasoning_effort="minimal"` by itself for several older ids in
the same GPT-5 family, which is the same 400 once the agent has tools. Setting
the param yourself is what avoids it.
One shared authoring line lowers correctly to both targets. LiveKit passes it as a
constructor argument, `openai.LLM(..., reasoning_effort="none")`. Pipecat's
settings class has no field for it, so it rides the service's `extra` field,
`OpenAILLMService.Settings(..., extra={"reasoning_effort": "none"})`, which
Pipecat merges into the request body as written.
## LiveKit Responses API
Ask for the Responses API on the shared think binding when a package needs it:
```yaml agent.yaml theme={null}
models:
think:
reasoning:
provider: openai
model: gpt-5.6-terra
params:
api: responses
reasoning_effort: none
use_websocket: true
```
Unmute emits `openai.responses.LLM` and turns `reasoning_effort` into the API's
nested reasoning setting when it is present. Use that field instead of a raw
`reasoning` map.
`api` and `use_websocket` are the two params only LiveKit can act on: one picks
the class, the other is a kwarg that class has and the chat completions one
does not. Write them here rather than in a target override. A per-target
`models:` entry replaces the base entry instead of merging into it. An override
would have to repeat `provider`, `model` and `reasoning_effort` to keep them,
and two copies of one binding is a binding somebody edits on one side only.
Pipecat drops both and builds `OpenAILLMService` either way, and `unmute
validate` prints a warning per param naming the target, so you are told what
did not apply. No shipped example uses this binding: both salon packages use
native Gemini through Google's EU Vertex endpoint.
`use_websocket: true` keeps a WebSocket connection for Responses requests.
HTTP clients can also reuse connections, so compare latency on the package's
own prompts and tools before choosing a transport.
## Native Gemini locations
`provider: google` uses the native Google plugin on both targets. `gemini` is
also accepted. On LiveKit this uses `livekit-plugins-google`, with no LiveKit
Inference request.
```yaml theme={null}
models:
think:
reasoning:
provider: google
model: gemini-3.5-flash-lite
params:
vertexai: true
location: us
thinking_config:
thinking_level: minimal
```
Set `GOOGLE_API_KEY` in the package's `.env`. `params.location` selects the
inference endpoint, independently of the worker's deployment region.
| Location | Inference endpoint |
| - | - |
| `us` | `https://aiplatform.us.rep.googleapis.com` |
| `eu` | `https://aiplatform.eu.rep.googleapis.com` |
| `global` | `https://aiplatform.googleapis.com` |
| Individual region, such as `us-central1` | `https://us-central1-aiplatform.googleapis.com` |
These are [Google's endpoint rules](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations).
Unmute checks the location's format without keeping a region allowlist.
Google determines whether the requested model and API key work at that location.
An unsupported location or unavailable model fails at the requested endpoint;
there is no fallback to global or another region.
The pinned plugins handle streaming and tools; a small adapter supplies their
Google GenAI client because their Vertex constructors expect OAuth credentials.
Other provider parameters, including `thinking_config`, still reach the native
plugin. Omit `vertexai` and `location` to keep using the Gemini Developer API
with `GOOGLE_API_KEY`.
Set to `true` for the Vertex API-key path. Omit it for the Gemini Developer API.
Required with `vertexai: true`. Use `us`, `eu`, an individual Google region,
or explicitly choose `global`. A location without Vertex is refused.
Google thinking options. Pipecat receives these as its native `ThinkingConfig`.
This example uses `minimal`. Allowed levels depend on the selected model.
## Pipecat
| Provider | Notes |
| - | - |
| `slng` | the [Context Router](/optimization/context-router): a cache in front of your own model, for the turns it judges repeatable |
| `anthropic` | Since Pipecat 1.10.0 `temperature`, `top_p` and `top_k` travel in the request body rather than as call parameters, because the Anthropic SDK's 1.x line dropped them. They reach the API unchanged and keep their names and meaning, so a package that sets them needs no edit. |
| `deepseek` | Since Pipecat 1.10.0 the reasoning pass is off unless you ask for it: V4 models otherwise reason before every answer, which delays the first spoken word. `params: {thinking: {type: enabled}}` turns it on. |
| `google` | native Gemini; also accepted as `gemini` |
| `groq` | |
| `mistral` | |
| `openai` | |
| `openrouter` | |
| `qwen` | |
## LiveKit
| Provider | Notes |
| - | - |
| `slng` | the [Context Router](/optimization/context-router): caching in front of your own model |
| `anthropic` | |
| `aws` | credentials come from the AWS SDK environment |
| `azure` | |
| `google` | native Gemini; also accepted as `gemini` |
| `groq` | |
| `mistralai` | also accepted as `mistral` |
| `openai` | |
| `openrouter` | |
| `sarvam` | |
## The differences that matter
This is the role where the two lists diverge most. LiveKit adds `aws`, `azure`,
and `sarvam`. Pipecat adds `deepseek` and `qwen`. LiveKit spells the
Mistral integration `mistralai`.
## When your provider is not listed
The two targets answer this differently, and the difference is worth knowing before
you pick one.
**On Pipecat**, an unlisted provider is legal for any role on one condition: a
genuinely OpenAI-compatible endpoint, named with `endpoint_env`.
### Behind the Context Router: `openai-compat`
`endpoint_env` above is for a think binding that talks to your gateway directly.
When the [Context Router](/optimization/context-router) is in front, the upstream
travels inline in the request body instead, and an OpenAI-compatible host is the
`openai-compat` kind. OpenRouter is the worked example:
```yaml agent.yaml theme={null}
secrets:
- SLNG_API_KEY
- OPENROUTER_API_KEY
models:
think:
reasoning:
provider: slng
model: qwen/qwen3-32b # the slug the host publishes
agent_id: salon-concierge-v1
upstream:
provider: openai-compat
url: https://openrouter.ai/api/v1
key_env: OPENROUTER_API_KEY
params:
world_part: eu-west # where the router serves you
provider: # forwarded to OpenRouter
only: ["groq"]
```
`url` and `key_env` are both required here: there is no default to fall back on,
and your key travels to the router on every think request, so a package has to say
whose it is.
Two things this shape buys, both worth knowing before you copy it:
* **A host pin.** OpenRouter serves one model from several providers, and they do
not behave the same. `params.provider` is forwarded verbatim, so you can accept
one. With `only` set, an unavailable host is a 404 with the message intact rather
than a quiet fall-back to a provider that breaks your tools.
* **The context ceiling is the host's, not the model's.** A model card advertises
the largest window any provider offers. On `qwen/qwen3-32b` that is 131,072 on
Groq and 40,960 on Nebius, for the same model. Check the one you pinned.
**Measure the host you pin, and measure two things separately.** On
`qwen/qwen3-32b` the four providers spanned a wide range at both the median and
the tail. Latency did not predict correctness: the second-fastest spoke a
fragment of its own tool-call template into every reply. A provider's published
figures are aggregated over everybody's traffic, mostly short prompts with no
tools, so they will not match a voice agent's request. Send your own prompt and
your own tool schemas, and count tool calls as well as milliseconds.
A model whose behaviour no parameter reaches may still need
[`prompt_suffix`](/optimization/context-router#prompt_suffix-for-what-no-parameter-reaches).
```yaml theme={null}
models:
think:
house_model:
provider: my-gateway
model: my-model
endpoint_env: MY_GATEWAY_URL
```
Without `endpoint_env` it is refused, and the error lists what the role does take:
```text wrap theme={null}
pipecat reason binding provider "my-gateway" has no slot; reason providers on pipecat: anthropic, deepseek, google, groq, mistral, openai, openrouter, qwen; an unlisted provider needs endpoint_env (an OpenAI-compatible endpoint)
```
**On LiveKit**, an unlisted reasoning provider routes through LiveKit Inference:
managed models billed through LiveKit Cloud, with no provider key of their own.
That path needs `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`, in local development
as well as in production.
Writing `provider: livekit` passes your model string through verbatim.
## Fallback
`fallback:` on a `think` entry names other think entries, tried in order when
the primary model's call fails:
```yaml agent.yaml theme={null}
models:
think:
assistant_model:
provider: openai
model: gpt-5.6-terra
params:
reasoning_effort: none
fallback:
- backup_model
backup_model:
provider: anthropic
model: claude-sonnet-5
```
`fallback` is legal on `think` and `listen` models only. Naming it on a `speak`
or `turn` entry is refused, by name. A name the section does not have, or a
chain that loops back on itself, is refused too, naming the loop.
What that one block compiles to depends on the target:
```json SLNG theme={null}
// on the push body, in the same shape the primary binding uses: the driver
// joins each entry's provider and model. See /targets/slng#model-names.
"fallbacks": {
"llm": ["/", "/"]
}
```
```python LiveKit theme={null}
# one constructor call, wrapped in llm.FallbackAdapter
llm=llm.FallbackAdapter(
llm=[
openai.LLM(
api_key=os.environ["OPENAI_API_KEY"],
model="gpt-5.6-terra",
reasoning_effort="none",
),
anthropic.LLM(
api_key=os.environ["ANTHROPIC_API_KEY"], model="claude-sonnet-5"
),
]
),
```
```text Pipecat theme={null}
# refused before a file is written
pipecat: the Pipecat driver does not emit generated fallback yet
```
Pipecat does not emit a generated fallback, so validating the same package
against a Pipecat target refuses it. The SLNG list uses the same
[vendor/model shape](/targets/slng#model-names) as the primary binding.
[Speech to text](/models/stt#fallback) documents the same field on the `listen`
role.
## Troubleshooting
### Every turn comes back as HTTP 400
A reasoning model was sent function tools without `reasoning_effort`. **Fix:**
set it in `params:`, as the Quickstart does. On LiveKit it also stops the
plugin injecting a value of its own.
### `agent_id` or `upstream` is refused
Both belong to a think binding routed through the Context Router, and the
message names the provider the binding actually has. **Fix:** set
`provider: slng` on that binding, or remove the key.
### `prompt_suffix` is refused on a listen or speak binding
It appends to a system prompt, and only a think model sends one. **Fix:** move
it to the think binding those prompts run on.
### The package compiles for LiveKit and is refused for Pipecat
Pipecat does not emit generated fallback. **Fix:** remove `fallback:` from
the `think` section, or keep that package on LiveKit or slng.
### A provider is refused and the message lists other names
The vendor is not on your target's list for this role. **Fix:** see [When your
provider is not listed](#when-your-provider-is-not-listed); the two targets
answer it differently.
## Where to go next
Knowing when the caller has finished.
One model that listens, thinks and speaks, on Pipecat.
# Speech to text
Source: https://unmute.ai/models/stt
The listen binding: every key it takes, the vendors each target can construct, and how one SLNG key reaches many models.
`models.listen` picks the service that turns the caller's voice into text.
**SLNG is a host and a proxy, and one key covers both.** It runs its own
copies of speech models, and it also forwards to the vendors' own endpoints.
So a single `SLNG_API_KEY` reaches many vendors' models, and you choose which
of thirteen regions the audio is processed in. [One key, many
models](#one-key-many-models) is the whole picture.
On this page:
* [Quickstart](#quickstart) - the smallest binding that works
* [Every key a listen binding takes](#every-key-a-listen-binding-takes) - the full shape
* [One key, many models](#one-key-many-models) - hosted, proxied, and where it runs
* [Pipecat](#pipecat) and [LiveKit](#livekit) - the vendors each target can construct
* [One transcriber per agent](#one-transcriber-per-agent) - an agent that hears another language
* [Fallback](#fallback) - what to try when the first call fails
* [Troubleshooting](#troubleshooting) - the refusals that come up most
## Quickstart
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
```
```sh theme={null}
unmute validate my-agent
```
That is a whole transcriber. `provider:` says who runs it, `model:` says which
one, and the name you give the entry, `transcriber` here, is how the rest of
the package refers to it.
## Every key a listen binding takes
Only `model:` is required. The rest narrow where the model runs and what
happens when it fails.
A provider supported for this role and target, listed on the model pages. Required for
an API binding; there is no inferred API provider. `local` selects local placement.
Provider model id, passed through as written. Required where the selected integration
requires a model; otherwise its default applies. No model id is checked against a provider catalog.
BCP-47 language tag, such as `en` or `en-US`, on `listen` or `speak`. Omit to leave
language selection to the integration.
Whether the model is called over the network or runs in the agent's own
process. Left out, it is `api` whenever the entry names a provider or a
model. `local` is refused on the slng target, which has no machine of yours
to run on.
Points at a variable holding an OpenAI-compatible endpoint URL. This is what
lets a vendor that is not on Pipecat's list through. Pipecat only: LiveKit
has no custom speech endpoint at all, and neither does the slng target.
Provider parameter names and values. Omit to add no extra parameters. Provider limits
apply; Unmute does not define a universal accepted set. SLNG `params.world_part`
is checked against its supported regions.
Names from the same `think` or `listen` section, in retry order. Omit for no fallback
chain. Cycles and other roles are refused; Pipecat refuses generated fallback.
## One key, many models
SLNG serves a speech model two ways, and the shape of the id says which:
| `model:` | What it means |
| - | - |
| `slng/deepgram/nova:3-en` | a copy SLNG hosts itself |
| `deepgram/nova:3` | the vendor's own endpoint, reached through SLNG as a proxy |
Both are one binding and one `SLNG_API_KEY`. The point is that you do not
collect a key per vendor to reach a vendor's model. The difference is who runs
the model and how it is billed, which
[docs.slng.ai](https://docs.slng.ai/execution-layer/byok) covers.
### Where it runs
`params.world_part` picks the SLNG speech gateway that serves the call:
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
params:
world_part: eu-north
```
Thirteen are accepted: `us-east`, `us-west`, `br`, `eu-west`, `eu-north`,
`gb`, `za`, `il`, `jp`, `sg`, `id`, `au` and `in`. Pipecat requires one. On
LiveKit, left out, the SDK default stands.
A hosted `slng/` id is a separate question: those run only where SLNG
has put them, so a region you need may rule one out.
[Regional infrastructure](/optimization/regional-infrastructure) explains the
separate model, worker and media regions.
### Which shape to pick for listening
The scaffold and every example take the proxied route. Routing through a
hosted id adds a hop the proxied route skips, on the one leg the caller waits
through on every turn, from the end of their speech to the final transcript.
Measure your own route rather than assuming this holds for you; see
[Optimizing your agent](/optimization/overview).
| Where | `model:` |
| - | - |
| LiveKit and Pipecat starters and examples, plus `hotel-concierge` on the `slng` target | `deepgram/nova:3` |
| the SLNG-hosted English copy, which runs in `us-central`, `au` and `in` only, so an `slng` package deploying to `eu-central-livekit` cannot name it | `slng/deepgram/nova:3-en` |
Those are the only exact ids the docs name, because they are the ones the
examples run. The full SLNG catalog, with languages, regions and hosting, is
at [docs.slng.ai/models](https://docs.slng.ai/models); any id from there goes
in `model:` as written.
## Pipecat
| Provider | Notes |
| - | - |
| `slng` | SLNG hosted speech to text. `SLNG_API_KEY`. |
| `assemblyai` | `universal-3-5-pro` is the default; `universal-3-6-pro` is the same model upgraded, with the same features. |
| `cartesia` | An `ink-` model such as `ink-2` can decide the turn itself and predict it early; see [Turn detection](/models/turn-detection). `ink-whisper` is the ordinary transcriber. Under a listening decider, `params: {turn_start_threshold: …, turn_eager_end_threshold: …, turn_end_threshold: …}` tune how sure it has to be; unset, Cartesia's own defaults apply. |
| `deepgram` | A Flux model (`flux-general-en`, `flux-general-multi`) can decide the turn itself and predict it early; see [Turn detection](/models/turn-detection). Since Pipecat 1.9.0 the profanity filter is off unless you ask for it: the filter rewrites the words it matches, so a false positive silently changes a transcript. `params: {profanity_filter: true}` turns it on, and a Flux model also takes `params: {redact: …}` to mask numbers. `params: {version: "2021-03-17.0"}` pins a model version instead of whatever `latest` resolves to. |
| `elevenlabs` | also accepted as `eleven_labs`. `params: {no_verbatim: true}` asks Scribe to drop filler words and false starts. |
| `gradium` | The service can decide the turn itself; see [Turn detection](/models/turn-detection). Under a listening decider, `params: {eot_horizon_s: …, eot_threshold: …}` tune how sure it has to be before it ends a turn; unset, Gradium's own defaults apply. |
| `openai` | OpenAI retires its previous transcription model on 2027-02-26; `gpt-transcribe` is the current one, and the framework's default since 1.9.0. This transcriber works on speech segments, and since 1.9.0 each segment is padded with half a second of silence so the last word is not cut; the padding counts toward usage. |
| `soniox` | |
| `speechmatics` | The service can decide the turn itself; see [Turn detection](/models/turn-detection). `linden-1` is the default model. `params: {enable_partials: true}` includes partial fragments as the caller speaks, and `params: {enable_diarization: true}` labels speakers. Eleven settings this service had before Pipecat 1.10.0 are gone; a package still writing one is refused with the line and what to write instead. |
An unlisted provider is legal on Pipecat on one condition: it has to be a
genuinely OpenAI-compatible endpoint, named with `endpoint_env`. Without that
it is refused, and the message lists what the role does take.
## LiveKit
| Provider | Notes |
| - | - |
| `slng` | SLNG hosted speech to text. `SLNG_API_KEY`. |
| `assemblyai` | |
| `cartesia` | |
| `deepgram` | |
| `elevenlabs` | also accepted as `eleven_labs` |
| `gradium` | |
| `sarvam` | |
| `soniox` | |
| `speechmatics` | `model:` picks the model; `operating_point` is its old name and is refused. Ten turn and speaker settings this service had before LiveKit 1.8.2, such as `max_delay` and `focus_speakers`, are gone; a package still writing one is refused with the line and what to write instead. |
This list is closed. LiveKit speech to text has no custom endpoint slot, so a
provider that is not here cannot be bound at all.
## The difference between the two
Pipecat has `openai`, LiveKit has `sarvam`. Everything else matches.
## One transcriber per agent
An agent can name its own `listen:` entry, so it hears the language it speaks. Without
it the agent uses the package's. Only a cascaded agent takes it, and that entry cannot
have a `fallback:` list. On livekit and pipecat each agent hears with its own model
after a handoff; slng and twilio refuse one that differs from the package's.
## Fallback
`fallback:` names other `listen` entries, tried in order when the primary
transcriber's call fails:
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
fallback:
- transcriber_backup
transcriber_backup:
provider: deepgram
model: nova-3
```
What that one block compiles to depends on the target:
```json SLNG theme={null}
// on the push body, in the same vendor/model shape the primary binding uses
"fallbacks": {
"stt": ["slng/deepgram/nova:3", "deepgram/nova-3"]
}
```
```python LiveKit theme={null}
# one constructor call, wrapped in stt.FallbackAdapter
stt=stt.FallbackAdapter(
stt=[
slng.STT(api_key=os.environ["SLNG_API_KEY"], model="deepgram/nova:3"),
deepgram.STT(api_key=os.environ["DEEPGRAM_API_KEY"], model="nova-3"),
]
),
```
```text Pipecat theme={null}
# refused before a file is written
pipecat: the Pipecat driver does not emit listen fallback yet
```
Pipecat does not emit a generated fallback, so validating the same package
against a Pipecat target refuses it. The SLNG list uses the same
[vendor/model shape](/targets/slng#model-names) as the primary binding.
## Troubleshooting
### The provider is refused, and the message lists other names
The vendor is not on your target's list for this role. **Fix:** pick one from
the list above, or on Pipecat point `endpoint_env` at a variable holding an
OpenAI-compatible endpoint. On LiveKit there is no such escape for listening.
### `language` is refused on a provider that clearly supports languages
The vendor carries the language inside the model id rather than in a separate
field, so the binding has no slot for it. **Fix:** drop `language:` and name
the language variant in `model:`.
### `voice`, `speed`, `temperature`, `top_p` or `top_k` is refused
Those are speak and think fields. A transcriber takes none of them. **Fix:**
move the key to the binding it belongs to, or delete it.
### `pace`, `endpointing_delay` or `semantic_endpointing` is refused
All three belong on a `turn` binding, which decides when the caller has
finished. **Fix:** move them; see [Turn detection](/models/turn-detection).
### The package compiles for LiveKit and is refused for Pipecat
Pipecat does not emit listen fallback. **Fix:** remove `fallback:` from
the `listen` section, or keep that package on LiveKit or slng.
## Where to go next
The voice the caller hears.
The SLNG Execution Layer behind these models.
Place speech compute and the agent worker separately.
# Text to speech
Source: https://unmute.ai/models/tts
The speak binding: every key it takes, the vendors each target can construct, and how one SLNG key reaches many voices.
`models.speak` picks the service that turns the agent's words into audio.
**SLNG is a host and a proxy, and one key covers both.** It runs its own
copies of voice models, and it also forwards to the vendors' own endpoints.
So a single `SLNG_API_KEY` reaches many vendors' voices, and you choose which
of thirteen regions the audio is generated in. [One key, many
voices](#one-key-many-voices) is the whole picture.
On this page:
* [Quickstart](#quickstart) - the smallest binding that works
* [Every key a speak binding takes](#every-key-a-speak-binding-takes) - the full shape
* [One key, many voices](#one-key-many-voices) - hosted, proxied, and where it runs
* [Pipecat](#pipecat) and [LiveKit](#livekit) - the vendors each target can construct
* [Troubleshooting](#troubleshooting) - the refusals that come up most
## Quickstart
```yaml agent.yaml theme={null}
models:
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
```
```sh theme={null}
unmute validate my-agent
```
This role usually takes a voice as well as a model. The entry's name, `voice`
here, is how the rest of the package refers to it; the `voice:` key inside it
is the vendor's voice id.
## Every key a speak binding takes
Which of `model:` and `voice:` are required depends on the vendor, and the
refusal names whichever one is missing.
A provider supported for this role and target, listed on the model pages. Required for
an API binding; there is no inferred API provider. `local` selects local placement.
Provider model id, passed through as written. Required where the selected integration
requires a model; otherwise its default applies. No model id is checked against a provider catalog.
A voice id accepted by the selected model and provider. Unmute forwards it
without checking a voice list. If omitted, the integration may choose its
default or require a value. An unknown id can fail only when speech runs.
Speaking speed on a `speak` entry. Provider-defined values and limits; omitted leaves
the provider default.
A fixed BCP-47 language tag such as `es` or `en-US`, on `listen` or `speak`
where the integration supports it. Accepted languages depend on the selected
provider and model. Omission keeps that integration's default; it does not
promise automatic detection. `{{language}}` is refused. Unmute exposes no
tool or variable binding that changes this setting during a call.
Whether the model is called over the network or runs in the agent's own
process. Left out, it is `api` whenever the entry names a provider, a model
or a voice. `local` is refused on the slng target, which has no machine of
yours to run on.
Points at a variable holding an OpenAI-compatible endpoint URL. This is what
lets a vendor that is not on Pipecat's list through. Pipecat only: LiveKit's
OpenAI plugin carries no language slot for speech, so there is no custom
endpoint for this role there, and the slng target has none either.
Provider parameter names and values. Omit to add no extra parameters. Provider limits
apply; Unmute does not define a universal accepted set. SLNG `params.world_part`
is checked against its supported regions.
A `speak` entry cannot carry `fallback:`. That key is legal only on `think`
and `listen`; see [Reasoning model](/models/llm#fallback).
## One key, many voices
SLNG serves a voice model two ways, and the shape of the id says which:
| `model:` | What it means |
| - | - |
| `slng/deepgram/aura:2-en` | a copy SLNG hosts itself |
| `deepgram/aura:2` | the vendor's own endpoint, reached through SLNG as a proxy |
Both are one binding and one `SLNG_API_KEY`. The point is that you do not
collect a key per vendor to reach a vendor's voice. The difference is who runs
the model and how it is billed, which
[docs.slng.ai](https://docs.slng.ai/execution-layer/byok) covers.
For **listening** the two differ in speed by enough to matter, and
[Speech to text](/models/stt#which-shape-to-pick-for-listening) explains the
gap. For speaking nobody has measured them against each other. The scaffold
takes the proxied route here to match the transcriber, not because it is known
to be faster.
### Where it runs
`params.world_part` picks the SLNG speech gateway that serves the call:
```yaml agent.yaml theme={null}
models:
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
params:
world_part: eu-north
```
Thirteen are accepted: `us-east`, `us-west`, `br`, `eu-west`, `eu-north`,
`gb`, `za`, `il`, `jp`, `sg`, `id`, `au` and `in`. Pipecat requires one. On
LiveKit, left out, the SDK default stands.
A hosted `slng/` id is a separate question: those run only where SLNG
has put them, so a region you need may rule one out.
[Regional infrastructure](/optimization/regional-infrastructure) explains the
separate model, worker and media regions.
| Where | `model:` | `voice:` |
| - | - | - |
| `unmute init`, and every example, `hotel-concierge` on the `slng` target included | `deepgram/aura:2` | `aura-2-thalia-en` |
| the SLNG-hosted English copy, which runs in `us-central` only, so an `slng` package deploying to `eu-central-livekit` cannot name it | `slng/deepgram/aura:2-en` | `aura-2-thalia-en` |
These are the ids used by the scaffold and examples. The full SLNG catalog is at
[docs.slng.ai/models](https://docs.slng.ai/models); any id from there goes in
`model:` as written, for example `slng/cartesia/sonic-3` with a voice id of
its own.
## Pipecat
| Provider | Notes |
| - | - |
| `slng` | SLNG hosted text to speech. `SLNG_API_KEY`. |
| `cartesia` | Since Pipecat 1.9.0 the default model is `sonic-3.6`. Write `model: "sonic-3.5"` to stay on the previous one. |
| `deepgram` | `params: {speed: 1.1}` sets Aura's speech rate, from 0.7 to 1.5. |
| `elevenlabs` | also accepted as `eleven_labs` |
| `gradium` | |
| `inworld` | |
| `openai` | |
| `rime` | |
| `sarvam` | Since Pipecat 1.9.0 the default model is `bulbul:v3`. Sarvam's API no longer serves `bulbul:v2`, so a package naming it cannot speak. |
| `soniox` | `params: {reduce_silence: true}` shortens the pauses between words, on models that support it. |
An unlisted provider is legal on Pipecat on one condition: it has to be a
genuinely OpenAI-compatible endpoint, named with `endpoint_env`.
## LiveKit
| Provider | Notes |
| - | - |
| `slng` | SLNG hosted text to speech. `SLNG_API_KEY`. |
| `cartesia` | |
| `deepgram` | |
| `elevenlabs` | also accepted as `eleven_labs` |
| `gemini` | |
| `gradium` | |
| `inworld` | |
| `rime` | |
| `sarvam` | |
| `soniox` | |
This list is closed, and closed harder than Pipecat's: LiveKit's OpenAI plugin
carries no language slot for speech, so there is no custom-endpoint fallback
for this role at all.
## The difference between the two
Pipecat has `openai`, LiveKit has `gemini`. Everything else matches.
## Troubleshooting
### The binding is missing a model, or missing a voice
The vendor needs both and the package gave one. **Fix:** add whichever the
message names. Which of the two a vendor needs is the vendor's own decision,
not a rule this page can shorten.
### `voice` is refused on a provider that clearly has voices
The vendor carries the voice inside the model id rather than in a separate
field, so the binding has no slot for it. **Fix:** drop `voice:` and name the
voice variant in `model:`.
### `fallback` is refused
A speak binding cannot have one, on any target. **Fix:** remove it. Fallback
is legal on `think` and `listen` only.
### `temperature`, `top_p` or `top_k` is refused
Those are think fields, which shape what the model writes rather than how it
is spoken. **Fix:** move them to the `think` binding, or delete them.
### `endpoint_env` is refused on LiveKit
LiveKit has no custom speech endpoint at all. **Fix:** bind a vendor from the
LiveKit list above, or compile to Pipecat, which emits the `endpoint_env`
lookup.
## Find a Soniox voice
Use the [SLNG Soniox voice catalog](https://docs.slng.ai/voices/soniox) to hear
voices and find their ids. Check the SLNG dashboard for voices available to
your selected model if the catalog differs. Copy the id exactly; do not infer an id from a
person's name or change its capitalization. For a direct Soniox binding, use
[Soniox's voice documentation](https://soniox.com/docs/tts/concepts/voices).
## Multilingual speech
The reply text and its spoken delivery are separate. A model can produce correct
Spanish text while TTS still uses an English language setting or voice accent.
Listen to each intended language before shipping a multilingual agent.
| TTS choice | Language behavior | What to configure |
| - | - | - |
| Soniox through SLNG | The stream has a language setting; the SLNG catalog documents `en` as the default | Set `language` deliberately and select a voice suited to it. Omission is not a multilingual switch |
| ElevenLabs multilingual TTS | Can infer language from the text; model and voice still affect delivery | Choose a multilingual model and suitable voice; a fixed language setting can constrain it |
See [SLNG's Soniox catalog](https://docs.slng.ai/voices/soniox) and
[ElevenLabs language guidance](https://elevenlabs.io/docs/eleven-creative/playground/text-to-speech).
Provider support for runtime changes does not mean Unmute exposes those changes.
STT has its own language behavior. Do not assume that leaving `listen.language`
out enables detection for every provider. For example, Deepgram multilingual
recognition uses `language: multi`; see its
[LiveKit integration](https://docs.livekit.io/agents/models/stt/deepgram/).
Check the selected STT model separately from TTS.
For a Spanish-only agent, use a Spanish prompt and a speech binding configured
for Spanish. For a multilingual brief, choose TTS that handles the required
languages with the settings Unmute can emit. If that is not possible, explain
the tradeoff before reducing the agent to one language.
## Where to go next
The model that decides what to say.
The SLNG Execution Layer behind these models.
Place speech compute and the agent worker separately.
# Turn detection
Source: https://unmute.ai/models/turn-detection
The turn binding: every key it takes, and how each target decides the caller has finished speaking.
`models.turn` decides when the caller has finished speaking, so the agent knows
when to reply.
The silence window is the floor charged on every turn. [Optimizing your agent](/optimization/overview) has the measured values, and why the minimum is the wrong choice.
Two different jobs hide behind the phrase "turn detection", and the two targets do
them differently. Worth keeping apart:
* **Voice activity detection** hears whether anyone is speaking at all. It is
cheap, local, and runs on the audio.
* **End of turn detection** decides whether the caller has finished their thought.
That can be the same signal as silence, or a model of its own.
On this page:
* [It is not a catalog role](#it-is-not-a-catalog-role) - why there is no vendor list
* [Every key a turn binding takes](#every-key-a-turn-binding-takes) - the full shape
* [What each target builds](#what-each-target-builds) - one binding, two pipelines
* [Semantic endpointing](#semantic-endpointing) - and what `off` removes
* [Troubleshooting](#troubleshooting) - the refusals that come up most
## It is not a catalog role
The `turn` role has **no vendor list**. Unlike listening, speaking, and thinking,
nothing here is constructed from the integration catalog: the binding is forwarded
to the runtime as written.
```yaml agent.yaml theme={null}
models:
turn:
detector:
provider: local
model: silero
```
That is the Pipecat binding used by the cascade examples. A package scaffolded by `unmute init`
targets LiveKit, so it writes the LiveKit binding below in this spot instead.
A package on a [live model](/models/live) has no `turn:` section at all: the
model hears the caller directly and decides the turn itself, so a `turn:` entry
beside a `live:` binding is refused.
## Every key a turn binding takes
A cascade needs a turn binding. Its optional timing settings default to the target’s behavior, described in [What each target builds](#what-each-target-builds).
Live and realtime do not accept `models.turn`; realtime selects turn handling on its own model entry.
See [Realtime turn detection](/build/architecture/realtime#2-choose-who-ends-the-turn).
Forwarded to the runtime as written. There is no vendor list to pick from,
which is what the section above is about.
Provider model id, passed through as written. Required where the selected integration
requires a model; otherwise its default applies. LiveKit turn bindings accept only
`turn-detector-mini` or `turn-detector`.
On `turn`, accepts `snappy`, `balanced`, or `patient`. Omitted means `balanced`. Sets
the ceiling and, unless `endpointing_delay` is present, the floor. Cannot be authored in
a per-target override.
On `turn`, a positive Go duration such as `300ms`. Sets only the silence floor; LiveKit
requires at least `250ms`. Omit to use the pace’s floor. See [turn
taking](/optimization/turn-taking).
On `turn`, accepts `required`, `preferred`, or `off`. Omit to keep the target’s semantic
detector. `off` removes it; see [turn
detection](/models/turn-detection#semantic-endpointing).
Where the check runs. On LiveKit it is only a preference: that runtime picks
the side itself and an authored value does not change it.
Forwarded to the runtime as written.
An author note. It reaches no generated artifact.
A `turn` entry cannot carry `fallback:`, `voice:`, `speed:`, `language:` or any
of the think sampling fields. Each is refused by name. Fallback is legal on
`think` and `listen` only; see [Reasoning model](/models/llm#fallback).
[Turn taking](/optimization/turn-taking) has every legal value of `pace` and
`endpointing_delay`, and what each becomes on each target.
## What each target builds
Both targets do two jobs, not one: decide you stopped making sound, then decide
you had finished a thought. Here is what one `turn` binding compiles to on each.
```python Pipecat theme={null}
vad_analyzer=SileroVADAnalyzer(params=VADParams(stop_secs=0.2)),
user_turn_strategies=UserTurnStrategies(
stop=[
TurnAnalyzerUserTurnStopStrategy(
turn_analyzer=LocalSmartTurnAnalyzerV3(
params=SmartTurnParams(stop_secs=1.6)
)
)
],
),
```
```python LiveKit theme={null}
turn_handling=TurnHandlingOptions(
turn_detection=inference.TurnDetector(version="v1-mini"),
endpointing={"mode": "dynamic", "min_delay": 0.3, "max_delay": 1.6},
interruption={"enabled": True},
preemptive_generation={"enabled": True},
),
vad=ctx.proc.userdata["vad"],
```
The two sections below say where each number comes from, and what is yours to
set.
## Pipecat
On Pipecat both stages run on device.
Silero is the transport's voice activity analyzer: it decides you stopped making
sound. Pipecat's own Smart Turn v3 classifier then decides whether you had
finished a thought. The classifier is a small ONNX model shipped inside the
framework, so it needs no extra install and no API call, and it runs in every
package Unmute compiles unless you set `semantic_endpointing: off`.
So `provider: local` and `model: silero` name the first stage. The second stage
has no binding to name because it is the framework's own, and `semantic_endpointing: off` disables it.
The two `stop_secs` are different fields with the same name: the first is the
silence window, from `endpointing_delay`, and the second is the classifier's
ceiling, from `pace`. See [Latency](/optimization/latency) for both.
### Transcribers that detect turns themselves
Some transcribers decide the caller has finished on their own. AssemblyAI,
Cartesia and Soniox all do. While `turn:` names the local pair above, those
services only *propose* an ending; the pair still decides. So picking one of
them does not change what `endpointing_delay` and `pace` mean, and does not give
you a second thing racing your settings.
Speechmatics is the exception, and it is worth a sentence because the answer
changed. Its service now closes turns itself unless it is told not to. A package
that names the local pair is told not to, so the local pair still decides and
nothing about your settings changes. A package that hands the turn to the
transcriber gets the service's own decision. Either way you write only the
`turn:` binding; nothing else has to be set.
### Let the transcriber decide
Four transcribers can take the whole decision, and two of them can also predict
it before it is final. Name the listener as the decider in the `turn:` binding:
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: deepgram
model: flux-general-en
language: en
turn:
detector:
provider: listen # the transcriber decides when the caller is done
eager: true # answer its prediction early; dropped if the caller goes on
pace: snappy # the ceiling: the transcriber's own end-of-turn timeout
```
The emitted bot then builds the vendor's turn-detecting service in place of its
ordinary transcriber and builds no local end-of-turn analyzer. The VAD still
runs, for the speaking frames the idle timer and the latency measurement use,
but it ends no turn.
| Transcriber | `listen:` binding | Where `pace` lands | Early answer |
| - | - | - | - |
| Deepgram Flux (`DeepgramFluxSTTService`) | `provider: deepgram` and a `flux-` model such as `flux-general-en` | `eot_timeout_ms` | yes |
| Cartesia Turns (`CartesiaTurnsSTTService`) | `provider: cartesia` and an `ink-` model such as `ink-2` | `turn_end_timeout_ms` | yes |
| Gradium (`GradiumSTTService`) | `provider: gradium` and any model it serves, such as `default` | no ceiling, so `pace` is refused | no |
| Speechmatics (`SpeechmaticsSTTService`) | `provider: speechmatics` and any model it serves, such as `linden-1` | no ceiling, so `pace` is refused | no |
Any other listening vendor is refused with this list. A Deepgram model that is
not a Flux model, or `ink-whisper` on Cartesia, is refused too: those two are
reached through a separate class that serves its own model family. Gradium and
Speechmatics keep their ordinary service and are switched on by an argument, so
any model they serve can decide.
**What `pace` means here.** On the first two, the ceiling becomes the
transcriber's own end-of-turn timeout, in milliseconds: `snappy` is 1200,
`balanced` 1600, `patient` 3000. The other two expose no such timeout, so `pace`
is refused there rather than landing on a nearby setting that means something
else; those services decide their own timing.
There is no floor either way, because no local silence window ends a turn, so
`endpointing_delay` is refused. `semantic_endpointing` is refused for the same
reason: it names a local analyzer that is not built. `interruption.minimum_words`
gates a local turn start the transcriber replaces, and is refused as well.
`interruption.protect` and `interruption.enabled: false` still work.
**What `eager` buys and costs.** With `eager: true` the transcriber predicts
the end of the turn, and the reply is generated while it is still confirming.
The framework holds that reply inside the LLM service and drops it if the caller
resumes speaking or the confirmed words differ, so an unconfirmed turn never
reaches the caller, the conversation context or a tool. Each prediction costs
one model request, including the ones the transcriber withdraws. That is why it
is off unless you ask for it. `eager: true` beside `provider: local` is refused:
the local detector predicts nothing. It is refused on Gradium and Speechmatics
too, for the same reason: both report a turn that has already ended, never one
they expect to end.
This is a Pipecat feature. LiveKit runs its turn model beside the transcriber
and has no path that hands it the decision, so `provider: listen` is refused
there and the two LiveKit identities below are the options. The emitted runbook
says who decides the turn, which field carries the ceiling, and whether an
early answer is on.
## LiveKit
LiveKit does both jobs, with two different pieces. It always loads Silero for
voice activity, and it takes a turn model on top.
The `endpointing` dict comes from `pace`. Unlike Pipecat, LiveKit can adapt the
wait to the pauses a caller actually leaves, which is what `mode: dynamic` asks
for.
The turn model comes from a per-target override, which is how every example that
runs on LiveKit writes it:
```yaml targets.yaml theme={null}
models:
detector:
provider: livekit
model: turn-detector-mini
```
A package with only a LiveKit target, which is what `unmute init` scaffolds,
needs no override: the same two lines go straight into `agent.yaml` under
`models:` / `turn:`. The override is for packages that keep both targets and
need a different answer on each.
### The two identities LiveKit accepts
This is the one model id Unmute checks. Everywhere else `model:` is forwarded to
the provider exactly as written, because the provider is the only thing that
knows its own catalogue. A LiveKit turn detector is different: the driver loads
it **by name**, so only two names exist.
| `model:` | Runs | Needs |
| - | - | - |
| `turn-detector-mini` | on your machine | nothing |
| `turn-detector` | LiveKit Cloud | your LiveKit credentials |
Anything else fails validation, before any file is written:
```text theme={null}
✗ livekit (livekit)
Errors:
livekit: turn model "silero" is not recognized; use turn-detector-mini (local) or turn-detector (LiveKit Cloud)
```
`silero` is the value most likely to end up here, because it is the right answer
on Pipecat, where it is a VAD rather than a turn detector. That is why every
example that runs on both targets overrides the entry per target. Pipecat
forwards the field unchecked, so the same `agent.yaml` is legal there and not
here, which is what the target prefix on the refusal is telling you.
Because LiveKit decides for itself where that work runs, `placement:` is only a
preference there. LiveKit picks whichever side actually does the check, and an
authored `placement:` does not change that.
## Semantic endpointing
`semantic_endpointing` takes one of three values: `required`, `preferred`, or
`off`.
`required` and `preferred` are forwarded and change nothing else Unmute emits.
Whether either one does anything depends on whether the model behind the turn
binding documents support for the setting.
`off` is different: it removes the turn model instead of forwarding a value
nothing reads. On LiveKit the session drops `inference.TurnDetector` and
decides end of turn from voice activity alone, `turn_detection="vad"`; the
`pace` ceiling still applies, because the endpointing dict does not depend on
the detector. On Pipecat it replaces the Smart Turn analyzer's stop strategy
with `SpeechTimeoutUserTurnStopStrategy()`, and loses the ceiling along with
it, because on this target the ceiling *is* the analyzer's own `stop_secs`.
## Troubleshooting
### LiveKit refuses the `model:` every example writes
`silero` is the right answer on Pipecat, where it is a voice activity detector
rather than a turn detector. LiveKit knows two identities of its own and
refuses the rest. **Fix:** override the entry per target, which is what every
example that runs on both targets does.
### `endpointing_delay` is refused on LiveKit
LiveKit will not accept a window under `250ms`. **Fix:** raise the value, or
reach for `pace: snappy`, which sets the ceiling rather than the floor.
### `pace` is refused
It belongs on a turn binding and nowhere else, and it takes no per-target
override. **Fix:** move it here. For a per-target duration, use
`endpointing_delay`.
### Turning `semantic_endpointing` off made replies slower on Pipecat
On that target the ceiling *is* the analyzer's own `stop_secs`, so removing the
analyzer loses the ceiling with it. **Fix:** keep `preferred`, or set
`endpointing_delay` to hold the floor yourself.
## Where to go next
The SLNG Execution Layer behind the speech models.
Every field a model entry takes.
# Context Router
Source: https://unmute.ai/optimization/context-router
The optimization layer for thinking: repeated turns come back from a cache instead of calling your model.
The SLNG Context Router is an **optimization layer for the `think` role**. It sits
between your agent and your reasoning model. On every turn it decides whether it
has answered this turn before: if it has, it replies from its cache; if not, it
calls your model and answers as normal. You keep your model, your provider,
and your bill for the turns that reach it, and gain speed on the turns that
repeat.
Use SLNG Context Router as the default LLM optimization path.
`unmute init my-agent --target twilio` and the shipped Twilio example already
select it. Other target starters use a direct reasoning binding; follow the
steps below to add the router. Twilio handles speech itself. On LiveKit and
Pipecat, SLNG speech bindings use the
[Execution Layer](/optimization/execution-layer).
On this page:
* [Start here](#start-here) - three edits to one binding
* [Every key a router binding takes](#every-key-a-router-binding-takes) - the full shape
* [Reading the router's log line](#reading-the-routers-log-line) - how to see a hit
* [How it decides](#how-it-decides) - what it treats as a repeat
* [One stable `agent_id`, one scope per prompt](#one-stable-agent_id-one-scope-per-prompt) - naming your cache
* [World parts](#world-parts) - the 13 places the router serves you from
* [Your model, and who serves it](#your-model-and-who-serves-it) - the `upstream` block
* [Params ride the request body](#params-ride-the-request-body) - what is forwarded
* [Advanced](#advanced) - prompt text, effort, and personal prompts
* [Troubleshooting](#troubleshooting) - when a repeat never caches
## Start here
Three edits, all to one binding:
Add `SLNG_API_KEY` to `secrets:`. Your own model's key stays where it is.
Change the `think` binding to `provider: slng`, keeping the model you already
use.
Add an `agent_id`, which names your project's cache, and an `upstream`, which
says where your model actually lives. One `agent_id` for the package; the
compiler gives each agent and task its own scope under it.
Then compile and run as usual. Nothing else in your package changes.
```yaml agent.yaml theme={null}
secrets:
- SLNG_API_KEY
- OPENAI_API_KEY
models:
think:
reasoning:
provider: slng
model: gpt-5.6-luna
agent_id: salon-concierge-v1
upstream:
provider: openai
params:
world_part: eu-west
reasoning_effort: "none"
```
Keep the existing think binding name when applying this example. If you name
it `reasoning`, set the agent's `think: reasoning` to select it.
Everything else in your package stays as it is: prompts,
tools, agents, tasks, flows, greetings, channels, capacity.
## Every key a router binding takes
What points the `think` binding at the router instead of straight at a vendor.
The model you already use. The router calls it through `upstream`.
Names your project's cache. One value for the package, and compiling fails if
two think profiles disagree about it. The compiler gives each agent and task
its own scope under it.
Where the router actually calls your model. There is no default, because your
provider's credentials travel with the request.
Literal text appended to every system prompt this binding sends. See
[`prompt_suffix`](#prompt_suffix-for-what-no-parameter-reaches).
Which of the 13 [world parts](#world-parts) serves this binding. The same key
and the same values a `listen` or `speak` model takes. The compiler turns it
into the base URL, so it never reaches your upstream.
`world_part` and `slng_pure_proxy` are consumed here and everything else rides
the request body. See
[Params ride the request body](#params-ride-the-request-body).
## Reading the router's log line
Every think request writes one line, at info level, in every run, deployed or
local:
```
slng router: scope=clinic-scheduler-v1:concierge source=cache layer=l2_exact request_id=req_...
slng router: scope=clinic-scheduler-v1:concierge source=llm model=gpt-5.6-luna request_id=req_...
```
`source=cache` means no model ran. Repeat an exchange and watch it change: that
is the check, and it needs no dashboard and no code of yours. `layer` appears
only on a hit, `model` only on a live answer, `request_id` is what to quote to
support.
The line is built from three response headers, which the generated project
reads through a hook on its own HTTP client because neither framework surfaces
them. The `twilio` target's app writes the same line, from the same hook.
| Header | Values | Meaning |
| - | - | - |
| `x-slng-response-source` | `llm`, `cache` | which path answered this turn |
| `x-slng-cache-layer` | seen so far: `l1_exact`, `l2_exact`, `l1_full_input`, `l2_full_input`; absent on the model path | which cache layer answered |
| `x-slng-model` | a model id, present only on the model path | which model answered |
| `x-slng-request-id` | always present, errors included | quote this to support |
Read `x-slng-response-source` rather than guessing a hit from how fast the
reply came back. Fast is not proof of a hit. A repeat served by the model is
expected, not a fault: the router decides which turns are worth serving from
cache. A miss just costs a little, an extra hop in front of your own model.
Streamed responses report no usage on either path, so token savings cannot be
read off the stream either.
## How it decides
The router remembers pairs: **what your agent said last, and what the caller said
next**. When that same pair comes round again, it can answer from the cache.
**A first turn never caches.** There is no preceding pair yet, so the first turn
of every call takes the full path to your model. A conversation with no repeat
in it never shows a hit.
**Not every repeat caches, and that is by design.** The router decides which
turns are worth treating as repeatable. Two pairs identical in everything a
client controls can still behave differently: one served from cache, one sent
to the model every time. A repeat served by the model is expected, not a fault.
## One stable `agent_id`, one scope per prompt
`agent_id` names your project's cache, and everything learned under one scope
is invisible to another. You write one value and own its version suffix:
change a prompt in a way that should make old answers wrong, and bump it,
`salon-concierge-v1` to `salon-concierge-v2`, so the router starts fresh. Fix
a typo and leave it alone, since throwing the cache away buys nothing. The
compiler never derives this value from your prompts or hashes them into it,
because it has no way to know whether a reworded sentence changes what a good
answer looks like. A package sends one `agent_id`, and compiling fails if two
think profiles disagree about it.
What the compiler does add is the name of whoever is speaking. Each agent and
task sends the `agent_id`, a colon, then its own name:
```
optimized-salon-concierge-v13:concierge
optimized-salon-concierge-v13:complaint_specialist
optimized-salon-concierge-v13:task.verify_customer
optimized-salon-concierge-v13:task.manage_booking
```
The cache key is the last exchange, not the system prompt. Separate scopes
prevent agents with different instructions from sharing cached answers.
The names come from your package and nothing else, so the same package always
compiles to the same scopes on either target, and a wording change never moves
one. Two agents with identical instructions still get two scopes and stop
sharing warmth, because they are two prompt sites. Hit rates build over calls
either way, so a fresh id is a cold cache: bump it deliberately rather than as
housekeeping. Pre-warmed answers, where they exist, are arranged against a
scope rather than the bare `agent_id`. Bump the id, or start sending one scope
per prompt, and that arrangement has to be redone. The generated runbook prints
the exact list of scopes your package sends.
## World parts
`params.world_part` picks which router serves you. It is the same key, and the
same 13 world parts, that a speech model takes. Learn a world part once and you
write the same word for listening, thinking and speaking.
| Value | Where | Endpoint |
| - | - | - |
| `us-east` | Eastern United States | `https://us-east.context-router.slng.ai/v1` |
| `us-west` | Western United States | `https://us-west.context-router.slng.ai/v1` |
| `br` | Brazil | `https://br.context-router.slng.ai/v1` |
| `eu-west` | Western Europe | `https://eu-west.context-router.slng.ai/v1` |
| `eu-north` | Northern Europe | `https://eu-north.context-router.slng.ai/v1` |
| `gb` | United Kingdom | `https://gb.context-router.slng.ai/v1` |
| `za` | South Africa | `https://za.context-router.slng.ai/v1` |
| `il` | Israel | `https://il.context-router.slng.ai/v1` |
| `jp` | Japan | `https://jp.context-router.slng.ai/v1` |
| `sg` | Singapore | `https://sg.context-router.slng.ai/v1` |
| `id` | Indonesia | `https://id.context-router.slng.ai/v1` |
| `in` | India | `https://in.context-router.slng.ai/v1` |
| `au` | Australia | `https://au.context-router.slng.ai/v1` |
One word, three roles. `eu-west` on a `think` binding and `eu-west` on a
`listen` binding are the same place, so a package can keep a whole call in one
world part. See [the speech gateways](/optimization/regional-infrastructure#choose-a-speech-gateway)
for the same table on the speech side.
SLNG deployment takes [agent regions](/targets/slng#targets-yaml), a separate
list. The location of each service is still chosen separately.
The key is consumed rather than forwarded: it becomes the base URL.
The router used to take four names of its own: `eu`, `us`, `india` and
`indonesia`. Those are refused now, with a line saying where they moved.
Rewrite them as world parts. `india` becomes `in`, `indonesia` becomes `id`,
and `eu` and `us` each become the specific world part you want, because the
world parts are finer: `eu-west` or `eu-north`, `us-east` or `us-west`.
## Your model, and who serves it
The `upstream` block says where the router actually calls your model. It is
required, and there is no default, because your provider's credentials travel with
the request and a package has to name whose they are.
| `provider` | You must write | You may write |
| - | - | - |
| `openai` | nothing else | `url`, `key_env` to override the defaults |
| `openai-compat` | `url`, `key_env` | `auth_header` |
| `azure` | `url`, `key_env`, `deployment`, `api_version` | nothing |
| `vertex` | `credentials_env`, `location` | `project` |
| `bedrock` | `access_key_id_env`, `secret_access_key_env`, `region`, `model_id` | `session_token_env` |
The `openai` and `openai-compat` upstreams have been exercised against the live
router. `azure`, `vertex`, and `bedrock` configuration follows the published
contract; these upstreams have not been run live in Unmute's validation.
Upstream support also depends on the target. The Twilio app supports `openai`,
`openai-compat`, `azure`, and `bedrock`; it does not support the router's `vertex`
credentials. Verify your selected upstream with a real model request before
connecting a production number.
On `openai` the compiler supplies the URL and the `OPENAI_API_KEY` name, so
the block is one line, `upstream: {provider: openai}`. Any other upstream
writes its own, naming its own secret:
```yaml agent.yaml theme={null}
upstream:
provider: azure
url: https://my-resource.cognitiveservices.azure.com/
key_env: AZURE_OPENAI_API_KEY
deployment: reasoning-deploy
api_version: 2024-12-01-preview
```
A key the router does not expect for that upstream is a compile error rather than
a silent pass-through, because an unknown field comes back as a 400 on every think
request. That check is on the `upstream` block only. Everything under `params:` is
forwarded without checking, which is [what makes it useful](#params-ride-the-request-body).
**The configuration travels inline, in the request body of every think
request, so your upstream credentials are sent to SLNG.** That is a trust
decision, and it is the price of not registering anything anywhere in
advance. What the tooling guarantees is narrower: a credential is always
*named*, never written. A `*_env` field holds an environment variable name,
the generated agent reads it with `os.environ[...]` at run time, and no
package, generated file, or compile report ever contains a value. Every name
you write has to appear in `secrets:` and joins the generated startup check,
so a missing value stops the agent at boot rather than on the first turn of a
live call.
`auth_header` is a header **name**, not a secret, for an `openai-compat` host
that wants the key somewhere other than `Authorization: Bearer`; the value
still comes from `key_env`. A Vertex `credentials_env` may hold the key JSON
itself, that JSON base64 encoded, or a path to the key file, and the agent
works out which at startup.
## Upstream fields
Accepts `openai`, `openai-compat`, `azure`, `vertex`, or `bedrock`. No provider is
inferred. Fields belonging to another provider are refused.
The upstream endpoint. Required for `openai-compat` and `azure`; defaults to
`https://api.openai.com/v1` for `openai`. On Azure, use the resource root, not a
deployment URL.
An UPPER\_SNAKE environment variable name. Required for `openai-compat` and `azure`;
defaults to `OPENAI_API_KEY` for `openai`.
Header name for `openai-compat` authentication. Omit to use the default bearer
Authorization header; the value still comes from `key_env`.
Required for `azure`: the deployment name. No name is inferred.
Required for `azure`: its API version string. No version is inferred.
Required for `vertex`: an UPPER\_SNAKE environment name holding service-account JSON,
base64 JSON, or a path to its file. No credentials are inferred.
Required for `vertex`: its location name. No location is inferred.
Vertex project id. Omit to use the project from the service-account key.
Required for `bedrock`: an UPPER\_SNAKE name holding the AWS access key id. No name is
inferred.
Required for `bedrock`: an UPPER\_SNAKE name holding the AWS secret access key. No name
is inferred.
Required for `bedrock`: an AWS region name. No region is inferred.
Required for `bedrock`: its model id, which may differ from the model profile’s label.
No id is inferred.
An UPPER\_SNAKE name holding the temporary AWS session token for `bedrock`. Omit when the
credentials need no session token.
## Params ride the request body
Everything under `params:` on a router think binding is passthrough. The compiler
reads two names and forwards the rest:
Consumed, and becomes the router's base URL for that world part. One of the 13
values in the table above, the same set a speech binding takes.
Consumed, and rides the body as the router's shadow-trial switch.
Forwarded in the request body on LiveKit, Pipecat, and Twilio.
The router passes a key it does not recognise straight to your upstream. That
is how you reach a provider-specific option Unmute has never heard of, and why
the compiler cannot check one. A wrong value comes back as the upstream's own
error, with its status code and message intact. A nested value is fine too,
since the body is JSON, so `provider: {only: ["groq"]}` forwards straight
through to OpenRouter.
## Trying it on a package you already have
[`examples/twilio`](https://github.com/slng-ai/unmute/tree/main/examples/twilio)
uses SLNG Context Router with an OpenAI upstream. Follow the
[Twilio walkthrough](/telephony/twilio-conversation-relay) to host it and connect
a phone number. For an existing LiveKit or Pipecat package, apply the binding
above; each agent and task receives its own cache scope.
To see the router's own contribution on your own agent, compile it once with
the think profile bound directly to the upstream vendor and once bound to the
router, then run the same conversation through both.
## Advanced
Three things a first router binding does not need.
### `prompt_suffix`, for what no parameter reaches
Some models take instructions that only work as prompt text. `prompt_suffix` is
literal text the compiler appends to **every system prompt that binding sends**:
each agent's, each task's on that binding's profile, and the summarizer's where one
is emitted.
```yaml agent.yaml theme={null}
models:
think:
reasoning:
provider: slng
model: qwen/qwen3-32b
agent_id: salon-concierge-v1
prompt_suffix: "/no_think"
upstream:
provider: openai-compat
url: https://openrouter.ai/api/v1
key_env: OPENROUTER_API_KEY
params:
world_part: eu-west
```
The worked reason it exists: Qwen3 is a hybrid thinking model, and thinking
costs your caller seconds of silence before the first word. The usual
parameters for turning that off are accepted and ignored on some of its
hosts, with no error, but Qwen3's own `/no_think` directive in the prompt
works across hosts, from the system prompt, mid-prompt, and on a tool turn.
It goes on the model, not on an agent, since it is a fact about the model; an
agent that needs different wording has its own prompt file. It is literal,
never a placeholder. The router substitutes placeholders from a snapshot of
the names your *prompts* reference, so one arriving from a suffix would be sent
with no value and come back 422 mid-call, which the compiler refuses. It
moves no cache, since scopes come from names and never from prompt content,
so bumping `agent_id` is still the only way to retire one deliberately. And
the compiler attaches no meaning to it: `/no_think` is just a string here,
and the next model's directive works the same way.
You can read what it did in the instructions inside the emitted `agent.json`,
and `unmute compile` names it on its own line.
### `reasoning_effort`, and when it is the problem
If your upstream serves an OpenAI reasoning model and your agent has tools, set
it. The GPT-5 family rejects function tools on chat completions without it, and
every tool turn comes back as:
```
400 Function tools with reasoning_effort are not supported ...
To use function tools, use /v1/responses or set reasoning_effort to 'none'.
```
`"none"` works. This is the same trap a direct OpenAI think binding has, and
[the reasoning model page](/models/llm) explains it there too. The compiler
warns when your package has tools and the param is missing, but only for the
`openai` and `azure` upstreams, the ones serving the models the advice is
about.
**On an `openai-compat` upstream, ignore all of that**, and do not set it
defensively. The advice is for OpenAI's own model families. Elsewhere the param
ranges from useless to fatal depending on the host: one host answers a request
carrying it with a 400, and another accepts it with a 200 and ignores it. Same
model, same param, two different failures, and neither is a reason to set it.
### Personal prompts stay cacheable
A prompt that names the caller is different on every call, which would mean
nothing ever repeats. So a router-bound prompt keeps its placeholders, for
example `{{state.caller_name}}` in an instructions file with a matching
`caller_name` field on `State`. The router receives the prompt with the placeholder
intact, plus a map of this call's values, and substitutes them itself. Every
call sends the same prompt, so turns can still repeat. This applies to the
system prompt only; greetings, tool arguments, injected values, and webhook
paths keep rendering locally.
Only variables referenced by the current prompt are sent. Declaring a model
or saving a task result does not add all call state to a router request.
Dotted references such as `{{state.appointment.date}}` select that field alone.
On LiveKit, values are read again for every request. On Pipecat, they refresh
when the call saves state. Direct-provider agent prompts refresh when their
tasks save values, and task prompts render on entry.
An unset referenced value is sent as `none recorded yet.`, never `None`.
Shapes and lists use compact JSON. A rendered value over 4000 characters is
shortened with a warning. Prefetch has its own smaller input limit; see
[Variables](/reference/variables#what-happens-when-it-cannot-resolve).
#### Which values belong in a placeholder
A placeholder is for a value your agent **says**: the caller's name, an
appointment detail read back aloud. Supplied that way, the stored copy holds
the placeholder instead of the value, so the turn caches like any other and the
next caller hears their own name in it. A value that changes **what the answer
is**, like the reply language, does not belong in one, however much it varies
per call. Two callers would share one cached answer written in a single
language. Write it into the prompt text instead. Variants that must never share
answers need their own `agent_id`, which is the only thing that partitions the
cache. The compiler does not judge a value by its name, so this is not checked
for you.
The value also has to match the answer **character for character** to be
recognised and stored. A phone number the model regroups, or a date it
rewrites, leaves the real thing in the stored copy. The personal-data scan then
refuses to share it, and the turn stops caching. There is no error, just a hit
rate of zero. Write the expected shape into the field's own `Field(description=...)`,
and make whatever produces the value follow it. This decides caching only for a
value the agent says out loud. A value passed only to tools can take whatever
shape the rest of your package uses. `examples/salon-concierge` returns E.164
everywhere and never reads a number back to the caller.
#### What the router will not cache, whatever you do
Three rules decide this, and none of them is about your placeholders:
| The answer | Why |
| - | - |
| holds personal data a scan flags | it would be replayed to the next caller |
| contains a tool call | the turn is an instruction to act, not an answer |
| follows a tool result | the result is this caller's data |
A fourth rule, and unlike these three a placeholder beats it: the router
refuses to store an answer **holding a number in any script**, since a number
in a reply is usually caller-specific. A number the agent says from a
placeholder is not in the stored copy at all, so that answer still caches; a
number the agent renders or reformats itself falls under the rule. So an
agent that quotes times and prices from its own working sees fewer hits than
one that asks questions, and a placeholder is what turns per-call numbers
back into hits.
## Troubleshooting
### A repeat never comes back from the cache
`x-slng-response-source` reads `llm` on a turn you expected to hit.
**Fix:** check four things. The same `agent_id` on both calls, a couple of
seconds since the turn it repeats, the second turn or later, and the exact pair
of previous reply and current message. If all four hold, stop looking: some
turns just never cache.
### Compiling refuses a scope
The value leaves as an HTTP header, and the bound is 128 characters, counted on
the finished scope rather than on the `agent_id` alone. It refuses rather than
truncating, because two truncated scopes could land on the same string.
**Fix:** shorten the name the message gives you. It names which agent or task
produced the long value.
### The compiler refuses a `world_part_override`
That key is gone. The router took four names of its own, and now it takes the
same world parts as speech.
**Fix:** rename the key to `params.world_part` and write a world part. `india`
becomes `in` and `indonesia` becomes `id`; `eu` and `us` each become a specific
world part, such as `eu-west` or `us-east`.
### The compiler refuses a `world_part`
The value is not one of the [13 world parts](#world-parts). The refusal lists
them all.
**Fix:** write one of the 13. A speech binding on the same package takes the
same words, so copying the value from there works.
## Next
How region works across all three SLNG roles, thinking included.
The `think` role and the vendors each target can construct directly.
# SLNG Execution Layer
Source: https://unmute.ai/optimization/execution-layer
A scaffolded package binds SLNG speech models by design, and those models run on SLNG's Execution Layer.
The SLNG Execution Layer is the layer SLNG's own speech models run on. It aims
at the two things a voice call is judged on: how fast it answers, and what it
costs per turn.
LiveKit and Pipecat starters bind SLNG for listening and speaking. Bind SLNG
for a speech role and you are on that layer. Twilio handles speech through ConversationRelay. Its generated app uses SLNG
Context Router for LLM optimization instead.
Unmute does not measure any of this. Everything on this page is SLNG's published
description of its own system, linked so you can read the source.
On this page:
* [What this means for your package](#what-this-means-for-your-package) - the binding you already wrote
* [What the Execution Layer is](#what-the-execution-layer-is) - routing instead of calling everything
* [The STT Performance Layer](#the-stt-performance-layer) - the stage on the way in
* [TTS Path Optimization](#tts-path-optimization) - the stage on the way out
* [The third role](#the-third-role) - LLM optimization with Context Router
## What this means for your package
Nothing you have to write. The layer sits behind the SLNG models you already bound:
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
```
One `SLNG_API_KEY` covers both. If you bind a different vendor for either role, you
are on that vendor's own path instead, and none of the above applies. The lists of
what else each target can construct are on
[speech to text](/models/stt) and [text to speech](/models/tts).
To select an SLNG speech gateway, set `params.world_part` on each
binding. [Regional infrastructure](/optimization/regional-infrastructure) shows
the YAML and explains the separate model, worker, and media regions.
## What the Execution Layer is
Rather than sending every turn through every model, the layer routes each turn to
the path that can serve it, and avoids the inference calls it does not need. SLNG's
own framing is that "a 16-turn voice call makes 48 model calls", and that at "1M
calls per month, that is 48M inference calls".
Two stages of it matter to a package you build here.
Figures below are SLNG's, published for the Execution Layer as a whole, and
are not measurements Unmute took. Source:
[docs.slng.ai/execution-layer](https://docs.slng.ai/execution-layer), read
2026-08-14.
| What SLNG reports | Their figure |
| - | - |
| end-to-end latency per turn | "39% reduction" |
| total pipeline cost | "53% reduction" |
| call completion rate | "Zero dropped, zero downtime" |
## The STT Performance Layer
The first stage, which routes incoming audio to the transcription model best suited
to it, per turn, based on the caller's context: language, location, environment.
SLNG lists noise cancellation across audio types, voice activity detection across
multiple speakers, language routing across models, and diarization for transcription
metadata.
SLNG marks this stage `PRIVATE BETA` and says "The behavior described here is being
rolled out gradually." That is their status for their feature, quoted as published
on 2026-08-14 at
[docs.slng.ai/execution-layer/stt-performance-layer](https://docs.slng.ai/execution-layer/stt-performance-layer).
Read it before you plan around this stage.
## TTS Path Optimization
The other stage, on the way out. Instead of generating audio for every request, it
"serves from cache when possible and synthesizes only when genuinely new". In SLNG's
words: "When audio has been produced before for the same request, it is served
instantly, with no upstream model call and no provider billing. When it has not, it
is generated, and the result is available for future requests."
SLNG makes no numeric claim for this stage on its own, and describes the saving as
structural rather than measured: "Cost decreases structurally. As coverage grows,
fewer turns hit the upstream model." Read as published on 2026-08-14 at
[docs.slng.ai/execution-layer/tts-path-optimization](https://docs.slng.ai/execution-layer/tts-path-optimization).
Which is worth knowing when you write a greeting: a line every caller hears is the
kind of output this stage is built for.
## The third role
Thinking uses [SLNG Context Router](/optimization/context-router). It serves
turns the router judges reusable without calling the upstream model; other turns use
your selected model and provider. This is the default LLM optimization path in
the Twilio starter and example.
For a LiveKit or Pipecat starter, change the `think` binding to SLNG, choose a
stable `agent_id`, and declare the upstream credentials. Those credentials
travel to SLNG with each request. The Context Router guide covers the setup.
## Where to go next
Cache repeated turns on the `think` role.
The full catalog, with languages and regions.
Every vendor each target can use for listening.
Choose the speech gateway, model region, and worker region.
# Reading the latency numbers
Source: https://unmute.ai/optimization/latency
Where the time goes in a voice turn, and what each number under a turn means.
When an agent feels slow, start with its reported reply latency, then inspect
the model requests, tools and speech measurements around that reply.
`unmute dev` displays activity and values as they arrive, so you can inspect
finished work while a later step is still running.
This page is about **reading** the numbers. For the settings that move them,
see [Optimizing your agent](/optimization/overview).
On this page:
* [Where the time goes](#where-the-time-goes) - the parts of one turn
* [What is making your agent slow](#what-is-making-your-agent-slow) - symptom by symptom
* [How Unmute measures it](#how-unmute-measures-it) - where the numbers come from
* [What each number means](#what-each-number-means) - reading the dev page
* [Reading a slow turn](#reading-a-slow-turn) - a worked example
* [What this does not measure](#what-this-does-not-measure) - the honest limits
## Where the time goes
Speech recognition, model generation and speech synthesis stream. Some work
starts before an earlier stage has finished, and source measurements can cover
more than one part of the wait. Their intervals can overlap. Do not add
first-response values to reconstruct reply latency or total model time.
```text theme={null}
while you speak recognition supplies words
when you stop turn detection and remaining recognition finish
while the model runs answer text or tool calls become available
while text arrives speech synthesis starts producing audio
after runtime audio the browser or phone receives and plays it
```
**Reply latency** is the runtime's measured interval from the end of caller
speech to the first agent audio. It excludes delivery to the browser. It appears
only when a value is reported. A stage value never substitutes for it.
On Pipecat, reply latency, turn detection and speech duration belong to the
reply whose audio started the bot speaking. The page reads that reply from the
synthesis the output transport is playing at that moment. Speech that no single
reply's synthesis started, such as a speech-to-speech model's, stays unassigned.
The page displays generated text before audio when the source supplies it.
A model's first response can be a tool call or other output before visible
answer text. Generation finishing also does not mean all displayed words have
been spoken, especially after an interruption.
**Turn detection is a real cost, and it is a setting.** The runtime must decide
whether silence ends a turn or is a pause for breath. This can be a large part
of the wait. See [Turn detection](/models/turn-detection).
### Tool calls can add model requests
A common tool flow needs the model once to choose a tool and again to use its
result:
```text theme={null}
model requests the tool
→ the tool runs (your API, your database, or an MCP server)
→ the model reads the result and continues
```
Several tools, retries or further decisions can add more requests. A caller
pausing and then resuming can also interrupt a request and start another. Keep
those requests separate; a short or interrupted request still consumed time. Use the
observed count and the labelled `LLM 1`, `LLM 2`, and later rows instead of
assuming every tool reply has exactly two model calls. The tool's duration
covers its own work; separate model measurements cover the requests around it.
Two overlapping calls to the same tool keep separate rows and outcomes.
`returned` means the tool supplied a result. It does not prove the business
operation succeeded. Handoff and task controls are excluded from business
tool timing: their duration can include a whole sub-conversation.
## What is making your agent slow
Compare the reported intervals and their source details to find a useful
place to investigate.
| What you see | What it usually is | Where to look |
| - | - | - |
| `turn_detection` is large or repeats a fixed value | the wait used to close an utterance | [Turn detection](/models/turn-detection) |
| LLM first response is large on every request | the model, or work before its first response | [Thinking models](/models/llm) |
| LLM request time grows as the call goes on | the prompt and history read on each request | [agent.yaml](/reference/agent-yaml) |
| a tool duration is large | the tool's own round trip | [Tools](/build/tools/overview) |
| several service requests are slower than expected | distance between the worker and model services | [Regional infrastructure](/optimization/regional-infrastructure) |
| only the first reply is slow | cold start or initial connections | on Pipecat, [`warm_instances`](/reference/targets-yaml#instances-held-ready) on the target |
| TTS first audio is small but speech duration is large | a long spoken reply, rather than a long initial wait | |
### Turn detection is a wait you chose
A repeated `turn_detection` value can point to a configured wait. Compare
several turns and the source's definition before changing a model.
Three settings matter: the detector you bind, `semantic_endpointing`, and
`pace`. On LiveKit the detector also decides where its work happens:
`turn-detector-mini` runs on your machine, and `turn-detector` runs in LiveKit
Cloud. `semantic_endpointing: off` removes the turn model on LiveKit and the
end-of-turn analyzer on Pipecat; any other value keeps it running.
#### The floor and the ceiling are different numbers
`endpointing_delay` sets the silence **floor**. `pace` selects the endpointing
**ceiling**, taking `snappy`, `balanced` or `patient` on a `turn` binding and
defaulting to `balanced`.
If a turn is hitting the ceiling, lowering the floor alone will not shorten
that wait. Compare repeated low and high values, then check both settings.
[Turn taking](/optimization/turn-taking) explains every legal value, what it
becomes on each target, and how to choose between them.
#### Or let the transcriber decide, and answer early
On Pipecat, a Deepgram Flux or Cartesia Turns listener can end the turn itself
(`turn: provider: listen`), and with `eager: true` the reply is generated while
the transcriber is still confirming the caller stopped. The wait you see under
`turn_detection` then belongs to the transcriber, the ceiling is its own
end-of-turn timeout, and the early answer is dropped if the caller goes on.
[Turn detection](/models/turn-detection) has the shape and what it refuses.
### The model can think before it speaks
On a reasoning model, `reasoning_effort` controls how much reasoning happens
before the answer. The shared example profiles and `unmute init` write `none`.
Raising it trades more reasoning for more work before the answer is available.
A first-response measurement can precede visible words, so read its source
label alongside the streamed conversation.
### The prompt is re-read every turn
Instructions go with each request, along with the conversation so far. A long
instructions file can affect later requests as well as the first one.
For tasks and handoffs you control how much is carried across with
`context.history`, `max_messages`, and `summarizer`. Carrying the full history
into a task is a choice, not a default you have to keep.
## How Unmute measures it
The generated agent observes native SDK activity, lifecycle events and timing
reports. Each quantity keeps its source and scope. Model-call counts come from
observed SDK invocations on both targets, not from the number of timing values.
Hidden network retries are not counted as separate SDK invocations.
`DevRecorder` in `unmute_core.dev` prints a marked JSON record when text,
activity or a measurement changes. Available values do not wait for a
completed-turn report.
The local server reads the run's output and forwards identified records to
the page, with a bounded replay buffer for reconnects.
Call, operation and measurement identities keep late values on the right
item. Repeated records add no duplicate rows. Unknown associations remain
unassigned.
This display path adds no external collector or exporter. Voice services still
make their normal provider requests. Trace export is a separate opt-in feature.
`unmute dev` enables `UNMUTE_DEV_METRICS`; the producer stays inert when it is
not enabled.
Raw updates, including recognized and generated transcript text, are kept in
`build//dev.log`. The browser's measurement filter shows activity and
values with their call IDs, and omits repeated text fragments. To inspect raw
measurement records:
```sh theme={null}
rg '"kind":"measurement"' build/livekit/dev.log
```
## At a glance and debug details
Each reply shows its reported reply latency and observed model-call count.
Under it, each `LLM N` row shows its own first-response time and request
duration as soon as they arrive. TTS first-audio time and tool duration also
stay visible. There is no need to expand a reply to compare model requests.
**Debug details** holds turn detection, transcription delay, text aggregation,
node timings, playback delay, and speech duration. The **Call diagnostics**
inspector beside the conversation starts collapsed. It holds call first-speech
timing and activity or measurements with no proven exchange. These do not
interrupt the conversation.
It also holds model, provider, request IDs, and source names. Use these when the
main timings do not explain the wait. Definitions live here, rather than
repeating under every value in the conversation.
The **Metrics** view adds up the same values for the whole call. Its tiles show
reply latency, LLM first token and TTS first audio at p90. Each number is
colored against a limit: over the first limit it is slow (yellow), over the
second it is over the limit (orange, marked ▲). Red means a request failed. A
caller turn is green up to 900ms, slow above 900ms and over the limit above
1200ms. A turn where the model ran more than once, as it does around a tool
call, is not rated, because it cannot fit a one-request budget. Each tile names
its target, each bar marks its stage's limit, and a legend under the turns
explains every color.
The view groups replies by caller turn. One caller turn can make several
replies, such as "Let me have a look." and then the answer. The runtime reports
reply latency once, on the reply the caller heard first, so the turn carries it.
## What each number means
Only captured measurements are shown. Missing and pending values have no
placeholder. A real zero is `0ms`; positive values below one millisecond
show as `<1ms`. Values use milliseconds until rounding reaches one second,
then seconds with two decimal places.
| Label | What it measures |
| - | - |
| Reply latency | End of caller speech to first runtime agent audio; excludes delivery to the browser. |
| LLM N · TTFT / TTFB | First response for that identified request: LiveKit reports time to first token (TTFT); Pipecat reports time to first byte (TTFB). This can be tool output before visible answer text. A source without either label uses `first response`. |
| Request duration | The full SDK service request, when reported; separate from first response. |
| TTS · TTFB | Time until the first audio output at the reported source. |
| Speech duration | Time spent speaking, separate from computation and caller wait. |
| `turn_detection` | The native end-of-turn interval, with the source's boundary. |
| `transcription_delay` | Delay from speech ending to transcription, when reported. |
| `text_aggregation` | Delay grouping text for speech. |
| `playback_delay` | First audio forwarded to native playback start; excludes delivery to the browser. |
| Tool duration | Time the identified tool ran, whether local or remote. A call into a task or a handoff has none. |
| Reply time (Pipecat) | The same wait as reply latency, split into the parts that make it up. See [Where a reply's time went](#where-a-replys-time-went-on-pipecat). |
| First speech | A call-level interval: LiveKit starts at reporter installation; Pipecat starts at the native observer session boundary. |
Expand **Debug details** for model, provider, request and source names, even
when timing is unavailable. A reply-level or node-level value stays separate from a
request-level value. For example, LiveKit's `llm_node_ttft` is labelled LLM node
TTFT, and `tts_node_ttfb` is labelled TTS node TTFB. Neither
creates a model request or replaces that request's own timing.
A known count says how many SDK model calls were observed for the reply, with
`so far` while it is open. A reply-level report alone shows no request count.
Partial source coverage or a lost slice of history labels the count as `observed`.
## Where a reply's time went, on Pipecat
Pipecat splits each measured reply into the parts that make it up, and the dev
page shows them in time order in the **Reply time** section of the call
diagnostics:
```text theme={null}
Reply time 1.02s · from the caller falling silent
200ms endpointing wait · config: VAD stop_secs
120ms transcription · DeepgramSTTService#0
40ms pipeline · pipeline
660ms LLM inference · OpenAILLMService#0
```
The parts account for the whole wait, so they add up to the total. That is what
makes a gap visible: time that belongs to no service is a part of its own rather
than quietly missing from the list. Each part names an owner, and the owner is
one of four kinds:
| Owner kind | What it means | Where to change it |
| - | - | - |
| service | a model you bound | the `models:` entry, or a different provider |
| setting | a value you wrote | the setting the owner names, such as the silence window |
| bot | the generated project's own code between the frameworks | usually nothing to change |
| pipeline | time inside the framework that belongs to none of the above | usually nothing to change |
The first line says what the interval was measured from: the caller falling
silent, or the client connecting. A greeting is anchored on the second, so it is
never compared with a reply to someone who spoke.
This breakdown carries no reply identity, so it has its own section rather than
being attached to a reply by timing. The **Metrics** view lists every breakdown
in arrival order, one column per part. LiveKit reports its own per
request timings instead and has no equivalent split.
## Reading a slow turn
A reply might show:
```text theme={null}
Reply latency 3.93s · 3 model calls
LLM 1 · ended TTFT 880ms request duration 1.14s
TOOL · lookup · returned tool duration 1ms
LLM 2 · ended TTFT 890ms
HANDOFF · do_reserve · returned
LLM 3 · ended TTFT 930ms
TTS · ended TTFB 240ms
▸ Debug details
```
A tool that produced no result says why in its own row: `failed` with the kind
of error its handler raised, or `timed_out` when it ran past its deadline. A tool
or task cut off by a hang-up is not an error. It reads `cancelled` on LiveKit and
`incomplete` on Pipecat. A call
that ends because something broke names the service that stopped it. The messages
themselves are in `build//dev.log`, because an error's text quotes what
was being worked on and these records carry no prompts or tool arguments.
Every model call after the first follows a tool call or a control, and the row
above it says which. A `HANDOFF` row is a call into a task, or a handoff to
another agent. It carries no duration, because it hands control over rather
than returning a result, and on LiveKit that call stays open until the task
finishes.
The three LLM rows describe three requests. Their first-response values do not
add up to reply latency. The later request-duration value also does not replace
the first-response value for LLM 1. Inspect each request and tool before
choosing which part to change.
A long speech duration can exceed reply latency without a problem: the caller
is listening during that speech. Keep it separate from the wait for the first
audio.
Start with reply latency when it is available, then compare source-labelled
requests and tools across several replies. Use
[What is making your agent slow](#what-is-making-your-agent-slow) to choose
the next setting or service to inspect.
## What this does not measure
* **Delivery to the listener.** Runtime timings exclude the trip to your
browser or through a phone carrier. Provider request timings can still
include the worker's network trip to its model service. Verify the phone
route on a deployed agent.
* **Unavailable source detail.** Targets and services expose different
quantities and associations. A value without a proven reply stays
unassigned, even when it arrives while another reply is visible.
* **Complete history after a gap.** Feed loss does not restart audio. If the
replay cannot recover all records, the incomplete-history label and observed
count remain until a new call, even after individual values become fresh.
## Where to go next
The settings behind turn detection, which can be a large part of the wait.
Remove a round trip instead of waiting it out.
What the speech models a scaffolded package binds run on.
Every kind of tool a turn can call, and what each costs you.
# Optimizing your agent
Source: https://unmute.ai/optimization/overview
Settings that speed up a call, why each one matters, and how to write them in agent.yaml.
Optimizing an agent means cutting what the caller waits through: the model round
trips a turn makes, how long the agent listens before it answers, and how far
each request travels.
A caller judges a voice agent on how long it waits. This page is the short list of
settings that make a call faster, why each one matters, and where it goes in
`agent.yaml`.
Two different jobs, two different pages. This one is **what to change**. If you
are looking at a slow call and want to know *which part* was slow, start with
[Reading the latency numbers](/optimization/latency) instead, then come back here.
On this page:
* [All of it in one package](#all-of-it-in-one-package) - every setting at once
* [Where the wait actually is](#where-the-wait-actually-is) - the spans in one turn
* [The short list](#the-short-list) - eight changes, in order
* [Troubleshooting](#troubleshooting) - settings that quietly do nothing
## All of it in one package
```yaml agent.yaml theme={null}
secrets:
- SLNG_API_KEY
- OPENAI_API_KEY
models:
think:
reasoning:
provider: slng
agent_id: my-agent-v1
upstream:
provider: openai
model: gpt-5.6-luna
params:
world_part: eu-west
# No thinking before the first token.
reasoning_effort: "none"
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
language: en
params:
# Hold a socket open so the provider's setup is done before the text
# arrives. Off by default, and it holds a second connection open while
# an utterance runs.
warm_standby_enabled: true
# Connect through eu-north.api.slng.ai.
world_part: eu-north
listen:
transcriber:
provider: slng
# Chosen on time-to-final, not accuracy score.
model: "deepgram/nova:3"
language: en
turn:
detector:
provider: local
model: silero
# The floor on every turn. Come down from the default in steps and listen
# for interruptions. Defaults differ per target, so set it if you ship to
# both.
endpointing_delay: 400ms
```
```yaml targets.yaml theme={null}
targets:
livekit:
models:
# local/silero above is what Pipecat runs. LiveKit needs its own turn
# model, so a package shipping to both overrides it here.
detector:
provider: livekit
model: turn-detector-mini
```
Set the agent's `think: reasoning` and `speak: voice` to use these bindings,
or keep its existing binding names when replacing their configuration.
These speech and turn settings apply to LiveKit and Pipecat; Twilio manages
speech through ConversationRelay.
The rest of the page explains each setting.
## Where the wait actually is
One turn is four spans, and they are nothing like equal:
| span | what it is |
| - | - |
| silence window | how long you have to stay quiet before the agent believes you finished |
| turn ceiling | the longest the agent will keep waiting before answering regardless |
| transcript | your last word to the final text |
| LLM | one round trip, and a tool turn costs two |
| TTS | synthesis to the first audio |
| network | every hop between your agent and each model, on every turn |
The LLM is typically the largest span, and the silence window is the most
predictable, with the rest smaller than people expect. That is why the order
below is not the order of size. It is the order of how reliably each one pays
off.
The turn ceiling is the exception, and it is worth checking early rather than
last. Nothing in a package could reach it before `pace` existed, so it sat at
the framework default no matter how short the authored silence window was.
[Reading the latency numbers](/optimization/latency) shows what `unmute dev`
reports for every turn, so you can see which span is slow on your own agent
before you change anything.
## The short list
Start with [SLNG Context Router](/optimization/context-router) for LLM
optimization, as the binding above does. Keep its `agent_id` stable for cache
reuse; change it when prompts invalidate old answers. Both the SLNG key and
your upstream model key are required, and upstream credentials travel to SLNG.
Twilio starters already use this binding. The remaining settings below apply
to LiveKit and Pipecat speech pipelines. The keys they use:
Binds SLNG for listening and speaking. The caching and the per-connection
settings below rest on it.
The transcriber. Choose it on time from the end of speech to the final
transcript, not on its accuracy score.
The SLNG speech gateway each `listen` or `speak` model connects through.
Required on Pipecat.
Holds the TTS connection open, so the provider's session setup is done before
the text arrives.
On a `turn` binding. The ceiling: the longest the agent keeps waiting before
answering regardless.
On a `turn` binding. The floor: how long you have to stay quiet before the
agent believes you finished.
Lookups that run once, before the greeting, into variables the prompt can
name.
On a `think` binding. `"none"` asks for no thinking before the first token.
On a tool entry. Short lines, one said while the tool runs.
### Bind SLNG for listening and speaking
LiveKit and Pipecat starters already bind SLNG speech. Twilio instead uses
ConversationRelay for speech, so speech bindings and turn settings on this
page do not apply to it. The caching described in
[Execution Layer](/optimization/execution-layer) and
[Context Router](/optimization/context-router) exists on SLNG's own layer, and the
per-connection settings below are only exposed by the SLNG plugins.
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
language: en
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
language: en
```
### Put the models near your callers
Network time is charged on **every** span above, not once per call: the turn
detector, the transcriber, the reasoning model and the speech model each pay a
round trip. Coval's
[guide to measuring voice AI latency](https://www.coval.ai/blog/how-to-measure-voice-ai-latency-the-complete-guide/)
explains why that adds up faster than people expect.
Choose a nearby endpoint or location for each STT, TTS and LLM provider when
its integration supports one. With SLNG, set a world part on each speech model
to choose its API gateway. See
[Regional infrastructure](/optimization/regional-infrastructure) for the full
picture, including where the agent itself runs.
```yaml agent.yaml theme={null}
models:
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
params:
# Connect through eu-north.api.slng.ai.
world_part: eu-north
```
Not every model is offered in every region, and the regions available for
listening and speaking are not the same set. Set a region on a route you have
tested: a model that rejects one fails at connection time, on a live call.
### Choose the transcriber on how fast it finalises
Not on its accuracy score. The turn detector reads the transcript to decide
whether you have finished talking, so a transcriber that has not finalised yet
holds the whole turn open: the agent is waiting on text, not on thinking.
The number to compare is **time from the end of speech to the final transcript**,
and it varies a lot between models that score similarly on accuracy. Two models
can return the same words with very different waits.
For independent, like-for-like comparisons across providers, see
[Coval's voice AI benchmarks](https://benchmarks.coval.ai/overview). Then confirm
on your own audio, because accents, phone codecs and the length of a typical
utterance all move the result.
The same model reached two ways is also two different waits. `deepgram/nova:3`
and `slng/deepgram/nova:3-en` are the same vendor model, one proxied through SLNG
and one hosted by it, and the proxied route finishes noticeably sooner to the
final transcript. That is why the scaffold and the examples take it.
[Speech to text](/models/stt) has the numbers and the caveats.
Test the route before you ship it. Not every model on a provider is available on
every transport or in every region, and some combinations only fail once a call
is live. See [Speech to text](/models/stt).
### Hold the TTS connection open
Off by default, and it works on both targets: on LiveKit since the SLNG plugin
shipped it, and on Pipecat since `pipecat-slng` 0.5.2. It takes the provider's
session setup off the front of every segment, which shows up most on the first
segment of a call and on the fastest turns.
It holds a second connection open while an utterance runs. A route that
already reuses a healthy connection has no setup cost to remove, so it pays
for the spare and gains nothing. Measure your own route with it on and off.
```yaml agent.yaml theme={null}
models:
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
language: en
params:
# Hold a socket open so the provider's setup is done before the text
# arrives. Off by default, and it holds a second connection open while
# an utterance runs.
warm_standby_enabled: true
# Pick the speech gateway nearest your callers.
world_part: eu-north
```
### Set the pace, then the silence window
Two settings, and the order matters. **Reach for `pace` first.**
`pace` is the ceiling: the longest the agent keeps waiting before answering
regardless. `snappy`, `balanced` or `patient`, defaulting to `balanced`. A turn
that feels flat and long is sitting at the ceiling, and only this moves it.
`endpointing_delay` is the floor: how long you have to stay quiet before the
agent believes you finished. Lowering it also makes short replies finalise
sooner. The transcriber is only asked to finalise once the silence window
elapses, so the change pays twice on a "yes, that's right". **But lowering the
floor alone does not shorten a long turn.**
```yaml agent.yaml theme={null}
models:
turn:
detector:
provider: local
model: silero
pace: balanced # the ceiling
endpointing_delay: 400ms # the floor
```
`local`/`silero` is what Pipecat runs. LiveKit needs its own turn model, so a
package that ships to both overrides it in `targets.yaml`:
```yaml targets.yaml theme={null}
targets:
livekit:
models:
detector:
provider: livekit
model: turn-detector-mini
```
Do not take the floor to the minimum. Too short and a caller who pauses
mid-sentence gets cut in two: a pause between words reads as the end of the
turn, and the agent answers before the sentence is finished. Come down from
the default in steps and listen for interruptions rather than chasing the
number.
The same trade applies to `pace`. `snappy` will occasionally answer someone who
was pausing to think, and that failure never appears in a latency figure, so
check for it deliberately. `patient` reproduces the framework defaults exactly
and is the escape hatch for callers reading out digits.
See [Turn taking](/optimization/turn-taking) for every legal value and what each
becomes on each target, and [Turn detection](/models/turn-detection) for what
actually runs.
### Resolve what you already know before the call
The cheapest turn is the one that never happens. A date, the number a call came
from, and whatever your own records say about that number are all knowable before
anybody speaks. `prefetch:` resolves them once, before the greeting, and lands
them in variables the prompt can name.
Two shapes cover most of what is worth moving: a step that collects a phone
number the call already carried, and a date that costs two chained tool hops
with nothing spoken over them.
```yaml agent.yaml theme={null}
prefetch:
- name: today
clock: now
timezone: Europe/Madrid
save:
- booking_date: result.date
- booking_weekday: result.day_of_week
- name: caller
source: from_number
save:
- customer_phone: result.value
```
One reading of the clock fills both variables above, at no extra cost: an
entry saves as many variables as the result has fields, from one call.
A `clock:` entry works on any route, and so does a `call:` entry whose
arguments you already hold, once you say `writes: false` on it. A `source:`
entry depends on the route: LiveKit's two routes supply every fact, and
Pipecat's two Twilio routes supply a smaller set, each in one direction only
for a phone number. `unmute validate` warns when an entry can never resolve on
a target. See [Where it works](/build/prefetch#where-it-works) for the full
grid.
A fact from the carrier is a proposal, not a settled value, so mark anything a
caller could dispute with `confirm:`. The step that used to collect it then reads
it back and asks for a yes, which is one round trip where collecting was several.
Deciding what qualifies is most of the work, and it has its own traps: a slow
lookup moves the wait to before the greeting, where the caller has nothing at all
to listen to. See [Pre-fetch](/optimization/prefetch) for how to think about it,
and [writing one](/build/prefetch) for the syntax.
### Cut LLM round trips before tuning connections
The largest span, and every control hop costs a whole round trip. Collapsing a
multi-step flow into one task, and asking for one piece of information instead of
three, removes whole round trips, which usually outweighs every
connection-level setting on this page combined.
Look for: a task that could be one task instead of three, a confirmation step the
tool already enforces, and a prompt long enough to slow the first token.
```yaml agent.yaml theme={null}
secrets:
- SLNG_API_KEY
- OPENAI_API_KEY
models:
think:
reasoning:
provider: slng
agent_id: my-agent-v1
upstream:
provider: openai
model: gpt-5.6-luna
params:
# No thinking before the first token.
reasoning_effort: "none"
```
### Speak before a tool runs
The tool is usually not the wait. A local handler returns in milliseconds; the
caller is waiting through the second LLM round trip and the speech after it.
`start: say:` on the tool fills that gap with something to listen to.
This is for a fact that genuinely has to be fetched now. If it was knowable
before the call, pre-fetch it instead: a cover line shortens a round trip to sit
through, while a pre-fetch removes it.
```yaml tools/check_slots.yaml theme={null}
local:
handler: tools/salon.py:find_slots
```
```yaml agent.yaml theme={null}
tools:
- name: check_slots
start:
say:
- Let me check.
```
Keep the line **shorter than the gap it covers**. A long line runs into the
answer and breaks its own promise of a wait: "Okay, one sec." works where "One
sec, let me pull up your details and see what we have" does not. Put it only on
tools that fetch or push data. Never put it on two things that speak for one
request: two tools in the same turn, or a tool at the end of one step and a
task at the start of the next.
## Troubleshooting
### A param you authored never reaches a target
If your package has a `targets.yaml` that overrides a model, a target's
`params:` block **replaces** the base block rather than merging into it. A param
authored on the base model never reaches that target, and nothing warns you.
**Fix:** author it on the override.
### The wait stays flat and long, turn after turn
That is usually the ceiling rather than the floor, and lowering
`endpointing_delay` will not move it.
**Fix:** set `pace` on the `turn` binding. See
[Turn taking](/optimization/turn-taking).
## Next
Where the time goes in a turn, and what to change when one number is too big.
Deciding which lookups to remove before the greeting.
`pace` and `endpointing_delay`, the two settings above, in full.
Caching and routing for speech, on SLNG's own layer.
Caching at the reasoning step.
Putting the models near the caller.
# What to fetch before the call
Source: https://unmute.ai/optimization/prefetch
How to decide which lookups belong before the greeting, and the traps in moving them there.
[`prefetch:`](/build/prefetch) runs a lookup once, before the greeting, and puts
the answer in a variable. Deciding which lookups belong there is the work, and
this page is how to decide.
The model is the slowest part of a voice turn, and a turn with a tool call in it
goes to the model twice instead of once. So the cheapest turn is the one that
never happens.
On this page:
* [What it looks like](#what-it-looks-like) - three entries, three kinds
* [Count round trips, not seconds](#count-round-trips-not-seconds) - the habit worth building
* [The one question](#the-one-question) - what passes the test
* [Collecting becomes confirming](#collecting-becomes-confirming) - shorter, not skipped
* [Do not move the wait to before the greeting](#do-not-move-the-wait-to-before-the-greeting) - the trap
* [Design for empty](#design-for-empty-because-empty-is-the-common-case) - the common case
* [Advanced](#advanced) - how far a fetched value travels
* [Troubleshooting](#troubleshooting) - what goes wrong, and the fix
## What it looks like
Three entries, and they are the three kinds of value worth moving: a clock
reading, a fact the call arrives with, and a read-only lookup you already have
the inputs for.
```yaml agent.yaml theme={null}
prefetch:
- name: today
clock: now
timezone: Europe/Madrid
save:
- booking_date: result.date
- name: caller
source: from_number
save:
- customer_phone: result.value
- name: profile
call: look_up_account
writes: false
with:
- phone: state.customer_phone
save:
- account_name: result.name
```
```sh theme={null}
unmute validate my-agent
```
[Writing a pre-fetch](/build/prefetch) is the syntax. The rest of this page is
which lookups belong in that list.
## Count round trips, not seconds
This is the habit worth building. When you look at a slow stretch of a call, do
not ask how many seconds it took. Ask how many times the model had to speak,
listen and speak again.
On a given setup a round trip takes about the same time every time. So a step
costs roughly its number of round trips, plus however long the caller talks. That
is why removing a round trip makes a slow step faster, and tuning a connection
mostly does not.
Counting them tells you what a pre-fetch is worth before you write it:
* a value the model would have fetched with a tool: **two round trips**, because a tool turn is a call and a reply;
* a value the model would have asked a person for: **at least two**, usually more, because people give you half of it and you have to read it back;
* a value already in the prompt: **zero**.
## The one question
**Could this have been known before anybody spoke?** Not "is it slow", and not
"is it annoying to collect".
Three kinds of value pass that test, and they are the three entries above.
**A clock reading.** The easiest win, and the easiest to miss, because a date tool
looks like a real tool. It is not. It takes nothing from the conversation, so it
can only return something you could have written into the prompt. Any tool that
takes no arguments at all is the same case.
**A fact the call arrives with.** The caller's number, the number they dialled,
whether the call is incoming or outgoing. The agent is handed these before it
speaks, and then agents routinely ask for one of them out loud anyway.
**Any read-only lookup you already have the inputs for.** This is the big one,
because the answer is your own data. A number becomes a customer. An id becomes an
account, an order, a ticket, a plan. A date becomes today's opening hours. If your
prompt tells the model to call something first before it can be useful, that is
your candidate.
What fails the test: anything the caller has to decide. The time they want, the
product they want, why they are calling, whether an option suits them. No amount
of pre-fetching helps there, and a step that collects a decision is doing its
job.
### Update the prompt to use what was fetched
A saved value can remove a lookup from the conversation only if the agent or
tool uses it. Add a placeholder where the model needs to read it, or use
`with:` for a tool argument it need not type.
Then update any instruction that still says to collect the value from scratch.
Tell the agent to use the existing value when present and ask only when it is
missing. If a value needs the caller's agreement, keep the verification task
and make it confirm the candidate instead of collecting it again.
Prefetch does not decide task order or automatically skip tasks. Prompts and
`when:` descriptions still guide that flow. Check them together with the
prefetch entries.
## Collecting becomes confirming
A pre-fetched value the caller might disagree with does not let you skip the
conversation. It lets you make it shorter.
Take a caller's number. It tells you which phone called, not who is holding it.
People call from a partner's phone, or hold two accounts. An agent that trusts the
number on its own will eventually read one stranger's details out to another. The
same goes for anything you worked out rather than heard: an account you looked up,
a saved address, a card on file.
So the step does not disappear. It changes job:
* **before:** ask for the value, hear part of it, read it back, get corrected, confirm. Several round trips.
* **after:** read back what you already have, hear a yes. One.
[`confirm:`](/build/prefetch#always-check-a-value-with-the-caller) makes that
happen. Only the confirming task may reference the candidate in a prompt. During the
conversation, tools that take it through `with:` refuse to run until that task saves the
confirmed value. The prompt must ask for agreement; saving through the named
task is what clears the runtime mark.
Confirmation carries over. Anything looked up from an unconfirmed value is
unconfirmed too. That is what keeps it out of the greeting, and it means you
mark one value at the start rather than hunting down everything that came from
it.
## Do not move the wait to before the greeting
The trap. A pre-fetch runs before the agent says anything, so any time it spends
is silence with nothing to listen to at all. Silence before hello is worse than
silence in the middle of a call.
Three rules keep it safe, and the first two are enforced for you:
1. The whole block has a **time limit**. A lookup that runs over is logged and given up on.
2. It **cannot fail a call**. An error is logged and given up on too.
3. Keep the list short, and do not chain a lookup off a lookup off a lookup. Entries run one after another, so a chain eats the time limit.
For a noticeable wait, consider one short `start: say:` line on the tool. Omit it for quick
tools, and avoid a second model-generated line saying the same thing.
### A pre-fetch is not a cover line
Both make a gap easier to sit through. They are not interchangeable.
| | `prefetch:` | `start: say:` |
| - | - | - |
| what it does | removes a round trip | gives the caller something to hear during one |
| when it runs | once, before the greeting | every time that tool fires |
| use it for | a value that was already knowable | a value you really do have to fetch now |
A task transition may also take time. A task can have a `start: say:` line,
but it is optional; test whether the caller benefits from hearing it.
Reach for a pre-fetch first, because a round trip you remove is gone for good.
Use an announcement only for waits that need one.
## Design for empty, because empty is the common case
Every input a pre-fetch needs can be missing, and on some routes it always is.
Your machine has no phone network. Some facts are absent on some routes by
design, for example `source.carrier` on either Pipecat route, or a phone
number on the direction a route does not grant. Callers hide their number too,
so even a route that grants a fact can still supply nothing on a given call.
Your lookup will not know a first-time customer.
So the empty call is not an edge case to handle later. It is the one to write
first:
* Write each prompt so it reads as a whole sentence with the value empty. An unset variable renders as `none recorded yet.` Use a label such as `Candidate phone: {{state.customer_phone}}` and explain what to ask when it is absent.
* Then check it still reads well once the value is there.
* Then run the agent both ways: `unmute dev` with `--source` and without it. Both are real paths in production.
## What you see in the log
Every entry writes one line, whether it resolved or was skipped:
```text theme={null}
prefetch today: resolved booking_date=2026-09-01
prefetch caller: skipped, the call carries no from_number
```
A removed round trip is one fewer `llm_request` span on LiveKit's own trace for
that turn.
## Advanced
### Where a fetched value is allowed to go
A value does not sit in front of every prompt just because a pre-fetch found
it. Variables are declared once, with a type and a default. From there, four
controls decide how far each value travels.
* **`confirm:`**, covered above, is the strictest. An unconfirmed value
renders in no prompt but its confirming step's. The phone number tells you
which phone called, not who is holding it, so it appears in the verification
step and nowhere else: not the greeting, not the booking step.
* **`with:`** hands a value straight to a tool. The model never types it, so
it cannot type it in a shape your records do not match. See
[Hand a value to a tool](/build/variables#hand-a-value-to-a-tool).
* **`{{ }}` placeholders** give a prompt only the values it names. Two
placeholders, two values. The greeting names none, so it gets none, however
many variables the call has collected by then.
* **Task `save:`** derives each finish field from its destination field on `State`
and saves it. Values that are not saved never enter call state. See
[Tasks](/build/orchestration/tasks).
#### Why this beats a prompt instruction
None of this is a rule written in a prompt and hoped for. Reference a value that still requires confirmation in the greeting and
you get a build error.
A `prefetch:` `call:` entry without an explicit `writes: true` or
`writes: false` is refused the same way. A value goes only where the file
says it goes.
A `prefetch:` entry itself is not held to that bar. An entry whose input is
empty for this call is skipped with a warning, and the call carries on with the
field's default in `state.py`. What an entry does enforce is on
[Troubleshooting](/build/prefetch#troubleshooting):
a `call:` entry needs `writes: true` or `writes: false`, and `save:` and
`with:` are lists, one pair per line, never a mapping.
Behind all of it is one plain fact. The model remembers nothing between turns,
so every token in the prompt is paid again on every turn. Routing a value to
the one place that needs it keeps it off that bill everywhere else. A turn the
[Context Router](/optimization/context-router) judges repeatable can answer
from cache instead of calling the upstream model. Twilio starters already
select the router; add its binding to other packages as described in the guide.
## Troubleshooting
### A value arrives empty on every call
The entry cannot resolve on that route, or the input it needs is missing.
**Fix:** `unmute validate` tells you which entries can never get a value on a
given target, and names the later entries that then get skipped too. Read its
warnings instead of finding out on a call.
### The greeting is late now
A lookup you moved is spending its time where the caller has nothing at all to
listen to.
**Fix:** if a lookup is usually slow, leave it as a tool called during the
conversation. A cover line can sit over it there.
### The caller hears two cover lines for one request
Two things are speaking for one thing the caller asked for.
**Fix:** never let two things speak for one request: two tools in the same
turn, or a tool at the end of one step and a task at the start of the next.
## Next
The three sources, the ordering rule, and confirmation.
The two settings that decide how long a caller waits before the agent answers.
# Regional infrastructure
Source: https://unmute.ai/optimization/regional-infrastructure
Keep STT, LLM, and TTS services close to your users, with separate settings for model gateways, workers, and media.
Regional infrastructure is where each part of a call runs: the edge that
receives the caller's audio, the worker, and every model service the worker
waits on. Each one is its own setting.
Where your models run matters as much as where you deploy your agent. A nearby
worker still waits on distant speech and reasoning services. Review the whole
path from the caller to STT, the LLM, and TTS, for every provider you use.
On this page:
* [Quickstart](#quickstart) - the one setting for speech
* [Why model proximity matters](#why-model-proximity-matters) - where the time goes
* [Choose a location for every model](#choose-a-location-for-every-model) - one review per role
* [Separate the regional settings](#separate-the-regional-settings) - four locations, four controls
* [Choose a speech gateway](#choose-a-speech-gateway) - the 13 SLNG world parts
* [Place the worker near your users and models](#place-the-worker-near-your-users-and-models) - `deployment_region`
* [Troubleshooting](#troubleshooting) - what the compiler refuses
## Quickstart
On LiveKit and Pipecat, set `params.world_part` on each SLNG `listen` or
`speak` model to choose its gateway:
```yaml agent.yaml theme={null}
models:
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
params:
world_part: eu-north
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
params:
world_part: eu-north
```
```sh theme={null}
unmute validate my-agent
```
That is the speech half. The worker has its own region, set in `targets.yaml`,
and the two do not have to match. The rest of this page is which location each
part of the call has, and how to choose it.
## Why model proximity matters
A voice turn crosses several network boundaries: the caller sends audio through
a media or telephony edge, the worker sends it to STT, the worker calls the LLM
and tools, and TTS produces the audio that returns to the caller. Long trips
between these services add delay throughout the conversation, even when the
models themselves are fast.
Start with where your users are. Keep the media edge, worker, and model services
close to them and to one another where your providers offer that choice. Apply
the same review to tools and other services the agent waits on. Moving only the
worker leaves any long trips to remote models in place.
Use geography as a starting point, then measure the time from the caller
finishing a sentence to hearing the first reply from your users' locations.
Network routes, model availability, and load can change which choice is fastest.
Compare both typical calls and slow calls; a regional endpoint does not change
the model's own processing time.
## Choose a location for every model
The same review applies whether you use SLNG or bind a provider directly.
Choose each model separately, including fallback models where configured:
| Model role | Where distance adds delay | What to check |
| - | - | - |
| [Speech to text](/models/stt), `listen` | Audio must reach the transcriber and its transcript must return to the worker. | The provider's streaming endpoint, the model's availability there, and final transcript latency. |
| [Reasoning model](/models/llm), `think` | Every reply and tool decision waits on a model request. | The endpoint or deployment serving the LLM and its time to first token with your prompts and tools. |
| [Text to speech](/models/tts), `speak` | Text must reach the voice model and the first audio must return. | The regional endpoint, availability of your model and voice, and time to first audio. |
Unmute supports direct speech providers such as Deepgram, Cartesia, ElevenLabs,
and Soniox, and reasoning providers such as OpenAI, Anthropic, and Mistral. The
linked model pages list the providers supported by each target. Regional
settings depend on the provider, model, account, and framework integration;
there is no shared region parameter for all of them.
For a direct provider, check its current documentation for regional endpoints
or deployments, then use the settings supported by the selected integration.
Do not copy another provider's parameter names. Some services select their
location automatically or offer no regional choice. Measure the route you
actually use before deciding whether to change providers or model deployments.
## Three region settings
| Setting | Written on | Accepted values | What it moves |
| - | - | - | - |
| `params.world_part` | SLNG `listen` and `speak` models on code targets | `us-east`, `us-west`, `br`, `eu-west`, `eu-north`, `gb`, `za`, `il`, `jp`, `sg`, `id`, `in`, `au` | The speech gateway endpoint |
| `params.world_part` | SLNG Context Router `think` models | `us-east`, `us-west`, `br`, `eu-west`, `eu-north`, `gb`, `za`, `il`, `jp`, `sg`, `id`, `in`, `au` | The router endpoint |
| `deployment_region` | Each target in `targets.yaml` | LiveKit: `us-east`, `eu-central`, `ap-south`. SLNG: its [agent regions](/targets/slng#targets-yaml), not the world parts above. Pipecat: one platform region name, forwarded without a value check | The agent worker on code targets; call placement on SLNG |
SLNG speech and routing share the world part names. SLNG deployment takes the
agents API's region names instead. SLNG's own are spelled like the world
parts, and LiveKit Cloud's end in `-livekit`.
LiveKit keeps its own worker names. Each setting is still independent of the others. None alone guarantees
data residency: model providers, media, tools, traces, and storage have their
own locations. A nearby speech gateway does not prove where its model runs.
LiveKit's compute names come from its
[agent region list](https://docs.livekit.io/deploy/admin/regions/endpoints/#agent-deployment-regions).
Accepts the speech gateway values in the table. Required on Pipecat, where
omission is refused. On LiveKit, omit it to use the plugin's default
endpoint. An empty or unknown value is refused. Do not combine it with
`params.base_url` or `params.slng_base_url`.
Accepts the same 13 world parts as speech. Required on a Context Router
think binding; omission is refused. It selects the router endpoint independently.
The old `world_part_override` key is refused; use `world_part`.
## Separate the regional settings
Each part of the call has its own location:
| Location | What runs there | How you choose it |
| - | - | - |
| Media or telephony ingress | The first platform edge that receives the caller's audio. | Platform region controls and carrier settings. |
| Worker region | The generated LiveKit or Pipecat process. | `deployment_region` in `targets.yaml`. |
| Model service | The provider serving STT, the LLM, or TTS. | That provider's supported endpoint or deployment settings, per model. |
| Model gateway | An API that routes requests to a model service. | The gateway's own location setting; SLNG speech uses `params.world_part`. |
Setting one row does not set the others. A gateway location also does not by
itself guarantee where the underlying model processes data. Tools, tracing,
and storage keep their own locations too.
LiveKit configures [realtime region pinning](https://docs.livekit.io/deploy/admin/regions/region-pinning/)
separately from [agent deployment regions](https://docs.livekit.io/deploy/admin/regions/agent-deployment/).
For Pipecat Cloud WebSocket telephony, Unmute derives the regional endpoint
from `deployment_region`; that endpoint must match the worker's region. See
[Pipecat's regions guide](https://docs.pipecat.ai/pipecat-cloud/guides/regions).
Carrier routing remains a separate choice.
## Choose a speech gateway
**SLNG provides 13 regional speech gateways through one model setting.** It is
set per model, and it gives both speech roles the same configuration shape
across the two frameworks.
The SLNG speech gateway an SLNG `listen` or `speak` model connects through.
One of the 13 values below. Set it on each model separately. Pipecat requires
it. On LiveKit, omitting it keeps the existing default URL.
Each world part is served at the host `{world_part}.api.slng.ai`. For the
`eu-north` in the quickstart above, Unmute emits `world_part="eu-north"` on
Pipecat and `slng_base_url="eu-north.api.slng.ai"` on LiveKit for both speech
models. The Pipecat plugin takes the world part itself and builds the host. The
LiveKit plugin takes the host without a scheme or path, so Unmute turns
`world_part` into that host and does not pass `world_part` on.
This setting changes generated SLNG speech services on LiveKit and Pipecat.
Choose the worker's `deployment_region` separately. The SLNG hosted target
keeps its own deployment settings.
### Available SLNG world parts
All 13 world parts below work for SLNG `listen` and `speak` models on LiveKit
and Pipecat. Set the world part on each model separately.
| World part | Geography | Gateway host |
| - | - | - |
| `us-east` | Eastern United States | `us-east.api.slng.ai` |
| `us-west` | Western United States | `us-west.api.slng.ai` |
| `br` | Brazil | `br.api.slng.ai` |
| `eu-west` | Western Europe | `eu-west.api.slng.ai` |
| `eu-north` | Northern Europe | `eu-north.api.slng.ai` |
| `gb` | United Kingdom | `gb.api.slng.ai` |
| `za` | South Africa | `za.api.slng.ai` |
| `il` | Israel | `il.api.slng.ai` |
| `jp` | Japan | `jp.api.slng.ai` |
| `sg` | Singapore | `sg.api.slng.ai` |
| `id` | Indonesia | `id.api.slng.ai` |
| `in` | India | `in.api.slng.ai` |
| `au` | Australia | `au.api.slng.ai` |
On LiveKit, omitting `world_part` keeps the existing default URL. On Pipecat
the compiler refuses the model, because the SLNG Pipecat plugin has no default
gateway.
### SLNG reasoning uses the same world parts
For a `think` model with `provider: slng`, the
[Context Router](/optimization/context-router) serves the same 13 world parts as
the table above, under the same key: `params.world_part`. So `eu-north` on a
speech binding and `eu-north` on a think binding are the same place, and a
package can keep listening, thinking and speaking in one world part. The LLM
behind the router keeps its own provider settings.
SLNG deployment takes [agent regions](/targets/slng#targets-yaml), a separate
list. The location of each service is still chosen separately.
## Place the worker near your users and models
Set the worker location in `targets.yaml`, using each platform's own region
names:
Where the generated LiveKit or Pipecat worker runs. Written per target in
`targets.yaml`, in that platform's own region names. Pipecat accepts one.
LiveKit accepts one region as a scalar or several as a list.
```yaml targets.yaml theme={null}
targets:
livekit:
provider: livekit
version: "1.8.8"
sdk_language: python
deployment_region: eu-central
pipecat:
provider: pipecat
version: "1.12.0"
deployment_region: eu-central
```
The worker region and model gateway codes do not need to match. For example,
a worker in `eu-central` can call SLNG speech through `eu-north.api.slng.ai`.
Choose nearby locations from the platform's current
[LiveKit](https://docs.livekit.io/deploy/admin/regions/agent-deployment/) or
[Pipecat](https://docs.pipecat.ai/pipecat-cloud/guides/regions) region list, then
measure the full call path.
### One worker region or several
Pipecat accepts one `deployment_region` per target. A second Pipecat region is a
second target and agent name.
LiveKit accepts either one region as a scalar or several regions as a list:
```yaml targets.yaml theme={null}
targets:
livekit:
provider: livekit
version: "1.8.8"
sdk_language: python
deployment_region:
- eu-central
- us-east
```
Unmute emits one LiveKit create command per listed region. The deployments keep
one dispatch name, so LiveKit may send a caller to another declared region when
the nearest deployment is at capacity. For strict worker locality, use separate
agent names and explicit dispatch. See LiveKit's
[multi-region deployment guidance](https://docs.livekit.io/deploy/admin/regions/agent-deployment/#multi-region-deployments).
Adding worker regions leaves the model settings as authored. Review the model
endpoints each deployment will call so that a nearby worker also has a short
path to its STT, LLM, and TTS services.
## Troubleshooting
### The compiler refuses a `world_part` value
An empty, non-string, or unknown value is refused. The old speech values `na`,
`eu`, and `ap` are refused too. There is no automatic mapping from the old
broad areas.
**Fix:** choose one of the 13 values in
[the table above](#available-slng-world-parts) explicitly.
### Pipecat asks for a `world_part`
The compiler says `params.world_part is required for SLNG speech on pipecat`.
The SLNG Pipecat plugin has no default gateway, so a bot built without one
would stop at startup.
**Fix:** add `world_part` to the model's `params:`, for example
`world_part: eu-north`. Pick the gateway closest to your callers.
### The compiler refuses `world_part` next to a URL
`params.base_url` and `params.slng_base_url` cannot be combined with
`params.world_part`.
**Fix:** remove the explicit URL or the world part.
### The router refuses a `world_part_override`
The router used to take four names of its own, `eu`, `us`, `india` and
`indonesia`, under a key of its own. It takes the 13 world parts now, under
`params.world_part`, like speech.
**Fix:** rename the key and write a world part. See
[SLNG reasoning uses the same world parts](#slng-reasoning-uses-the-same-world-parts).
### A nearby worker is still slow
Setting one row of the table above does not set the others, and moving only the
worker leaves any long trips to remote models in place.
**Fix:** review the model endpoints each deployment calls, then measure the full
call path rather than the worker's own region.
## Where to go next
Measure what the caller waits for.
Choose the model that decides what to say.
Choose the model that listens to the caller.
Choose the model that speaks to the caller.
Deploy one worker region or several.
Deploy one worker region per target.
# Setting how long the agent waits
Source: https://unmute.ai/optimization/turn-taking
pace and endpointing_delay: the two settings that decide how long a caller waits before the agent answers.
Turn taking is the wait between a caller finishing a sentence and the agent
starting to answer. Two settings decide it. They are not the same setting, and
confusing them is the most common way to spend a day tuning the wrong number.
On this page:
* [`pace`](#pace) - the ceiling on a turn
* [`endpointing_delay`](#endpointing_delay) - the floor on a turn
* [Reading what you set](#reading-what-you-set) - the resolved numbers
* [How to tune it](#how-to-tune-it) - five steps, in order
* [Where the rest of turn taking lives](#where-the-rest-of-turn-taking-lives) - interruption, and the turn model
* [Troubleshooting](#troubleshooting) - reading `user_turn`
```yaml agent.yaml theme={null}
models:
turn:
detector:
provider: local
model: silero
pace: balanced # the ceiling
endpointing_delay: 400ms # the floor
```
`local`/`silero` is what Pipecat runs. LiveKit needs its own turn model, so a
package that ships to both overrides it in `targets.yaml`:
```yaml targets.yaml theme={null}
targets:
livekit:
models:
detector:
provider: livekit
model: turn-detector-mini
```
**`pace` is the ceiling**: the longest the agent will keep waiting before it
answers regardless. Reach for this first.
**`endpointing_delay` is the floor**: how long silence has to last before the
agent believes you finished. Nothing downstream can start earlier.
**Lowering the floor alone does not shorten a long turn.** A turn that runs long
is sitting at the ceiling, and only `pace` moves that.
Before `pace` existed nothing in a package could reach the ceiling, so it stayed
at the framework default, **2.5s** on LiveKit and **3.0s** on Pipecat, no
matter how small you made the window. If replies feel slow and your
`endpointing_delay` is already short, this is why.
## `pace`
Legal on a `turn` binding. The ceiling: the longest the agent will keep
waiting before it answers regardless. It sets the floor too when
`endpointing_delay` is absent. No per-target override.
Three values. Defaulting to `balanced` when you leave it out means a package
that says nothing still gets the faster behaviour.
| Value | The agent | Choose it when |
| - | - | - |
| `snappy` | answers quickly, and will occasionally answer someone who was pausing to think | short exchanges, confirmations, menu navigation |
| `balanced` | the default | most agents |
| `patient` | waits, and someone who has finished waits with it. Reproduces the framework defaults exactly | callers reading out numbers, addresses, spellings |
`patient` is the escape hatch. Selecting it changes nothing for a package that
already has today's behaviour, so it is always safe to fall back to.
### The two targets are not equally capable
`unmute compile` writes the resolved floor and ceiling for each target to
`build//compile-report.json` and the emitted `README.md`, so you never
have to look either up. Two differences are worth knowing before you read them:
* **The Pipecat floor never moves.** It is the same 0.2s at every pace,
deliberately. See [the cliff](#the-pipecat-floor-is-a-cliff-not-a-dial) below.
* **Only LiveKit adapts.** It shortens its wait based on the pauses a caller
actually leaves, between a lower bound and the ceiling. Pipecat has no
equivalent, so its wait is the same fixed window every turn.
`pace` takes **no per-target override**. One word is meant to work on both
targets, and a value that differed per target would be a duration in disguise,
which is what `endpointing_delay` is for. Writing a `pace` inside a
`targets.yaml` override is refused, naming what to do instead.
## `endpointing_delay`
Legal on a `turn` binding. The floor: the window of silence before the caller
counts as finished. Optional, and leaving it out lets the pace set the floor
too. LiveKit refuses anything under `250ms`. Takes a per-target override.
Set it when you have measured a value for your transcriber. Lowering it makes
short replies finalise sooner as well, because the transcriber is only asked to
finalise once the silence window elapses, so it pays twice on a "yes, that's
right".
**Do not take it to the minimum.** LiveKit refuses anything under 250ms and
`unmute compile` rejects it rather than letting the worker raise on its first
call. But even a legal short value splits utterances: a pause between words
gets read as the end of the turn, and the agent answers before the sentence is
finished.
Unlike `pace`, this one **does** take a per-target override, because a silence
window is tied to one target's mechanism. `examples/salon-concierge` authors no
floor on its base binding, so the pace owns it there, and 200ms on its Pipecat
target. The next section is why that one figure is authored rather than left to
the pace.
### The Pipecat floor is a cliff, not a dial
Widening the Pipecat window can make turns **slower**. This is the one
counter-intuitive thing on this page.
`pipecat-slng` asks the bridge to finalise when voice activity detection reports
the caller stopped. A final transcript that has already arrived by then finds no
request outstanding, so the frame goes out unfinalized and Pipecat waits out a
flat safety-net timeout instead, on top of the window you set.
So the relationship between the window and the wait is not monotonic. Below the
transcript's arrival time the turn ends promptly. Above it, the turn pays that
flat extra wait, and a transcript can arrive sooner than you would guess, so
"above it" starts sooner too.
That is why the Pipecat column in the pace table stays at 0.2s for every pace, and
why a patient Pipecat agent gets its patience from the ceiling instead. If you
raise this window on Pipecat, check the wait afterwards rather than assuming it
went up by what you added.
Setting `interruption.minimum_words` on a Pipecat target used to replace the
floor and ceiling with a plain timeout, which stopped the end-of-turn
classifier running and made turn taking worse instead of better. It no longer
does: the classifier survives, and it still carries the `pace` ceiling.
## Let the transcriber decide
On Pipecat there is a third setting, and it changes what the other two mean.
A Deepgram Flux or Cartesia Turns listener can end the turn itself: write
`provider: listen` on the `turn:` binding. The pace ceiling then becomes the
transcriber's own end-of-turn timeout (`eot_timeout_ms` or
`turn_end_timeout_ms`, in milliseconds), there is no floor because no local
silence window ends a turn, and `endpointing_delay` is refused.
Add `eager: true` and the reply is generated while the transcriber is still
confirming the caller stopped. The framework holds it and drops it if the
caller goes on or the confirmed words differ. It costs one model request per
prediction, including the withdrawn ones, so it is off unless you ask.
[Turn detection](/models/turn-detection) has the shape, the two vendors, and
every refusal.
## Reading what you set
On LiveKit and Pipecat, the emitted `build//agent.json` shows what you
set under `models.turn`: the pace, and your `endpointing_delay` when you wrote
one. The unmute-core library turns them into the framework's floor and ceiling
when the agent starts. See [turn taking in unmute-core](/core/reference/turn-taking).
## How to tune it
The order below matters. Each step tells you whether the next one is worth doing,
and the first two need no audio at all.
### 1. Read what you already have
```bash theme={null}
unmute compile
```
The report names the resolved floor and ceiling per target. Most of the time this
is the whole answer: a package that never set a pace was sitting at the framework
ceiling, and simply compiling on a current build moves it.
### 2. Decide from the caller, not from the clock
Pick the pace from what your callers actually say, before measuring anything:
* Do they answer in a few words: confirmations, a menu choice, a yes? Start at
`snappy`.
* Do they read things out: phone numbers, dates, postcodes, an email address,
a name being spelled? Start at `balanced`, and be ready to go to `patient`.
* Do they think aloud, with pauses inside a sentence? `patient`.
A single agent often has both kinds of turn. Choose for the ones where being
wrong is expensive: answering over someone reading their phone number costs more
than half a second of extra silence on a "yes".
### 3. Listen before you measure
```bash theme={null}
unmute dev --target
```
Have the conversation your callers will have. Two specific things to do, and the
second is the one people skip:
1. **Finish sentences cleanly and stop.** This is the case a shorter ceiling
improves, so it is where you will feel the change.
2. **Read a phone number aloud in groups, with a pause between each group.** Then
pause mid-sentence and carry on. If the agent answers your first group, or
answers half your sentence, the pace is too fast for these callers. Go up one.
### 4. Then read the numbers
`unmute dev` reports the wait as its own number, `user_turn`, separately from
everything else in the turn. That separation is the point: it tells you whether
turn taking is your problem before you change anything.
Compare each turn's `user_turn` against the floor and ceiling from step 1.
[Troubleshooting](#troubleshooting) has what each comparison means and what to
do about it.
### 5. When turn taking is not the answer
This is the common outcome once the ceiling is set sensibly.
Look at how many model round trips the slow turns took. A turn that calls a tool
pays time-to-first-token **twice**: once to decide the tool, once to answer with
its result. Tool turns cost roughly double, and two tools in one turn cost
more again. That is usually a bigger number than anything on this page, and no
pace will touch it.
The fixes are structural: collapse two tools into one, ask for one piece of
information instead of three, or answer from context rather than looking something
up. See [Optimizing your agent](/optimization/overview) for that side.
**A latency figure only shows you half of turn taking.** It fails two ways:
dead air after the caller finishes, and answering the caller mid-sentence. And
shrinking the window trades one for the other, while only the first appears
in a number. Do step 3 every time you change the pace, not just the first
time.
## Where the rest of turn taking lives
Everything on this page is on the `turn` binding under `models`. Two related
things are not, and it is worth knowing why:
* **`conversation.interruption`** decides who holds the floor while the *agent* is
speaking: whether a caller can barge in, how many words it takes, and which
stretches of the call are protected. It is a conversation policy rather than a
property of the turn detector, so it sits under `conversation`. Its fields are
in the [agent.yaml reference](/reference/agent-yaml).
* **The turn model itself** is per-target vendor selection, so a LiveKit package
names `turn-detector-mini` in its `targets.yaml` override. See
[Turn detection](/models/turn-detection) for what actually runs on each target.
Individual framework parameters, LiveKit's `alpha` and `unlikely_threshold`,
Pipecat's `pre_speech_ms` and VAD confidence, are **not** reachable from a
package today. `pace` and `endpointing_delay` are the whole surface.
## Troubleshooting
### `user_turn` sits at your floor, turn after turn
The floor is the only thing being waited on. Turn taking is working.
**Fix:** nothing. Look at the model instead.
### `user_turn` sits at your ceiling
The turn ran out of patience rather than deciding. These are the turns a shorter
ceiling saves.
**Fix:** go down one pace, then repeat
[step 3](#3-listen-before-you-measure).
### `user_turn` is above your ceiling
Something else is holding the turn open. Check the transcription number on the
same turn: the ceiling cannot fire before the transcript arrives.
**Fix:** look at the transcriber, not the pace.
### `user_turn` looks right and replies are still slow
Turn taking is not your problem.
**Fix:** see
[When turn taking is not the answer](#5-when-turn-taking-is-not-the-answer).
### Widening the Pipecat window made turns slower
The Pipecat floor is a cliff. Above the transcript's arrival time the turn pays
a flat extra wait on top of the window you set.
**Fix:** come back down, and check the wait afterwards rather than assuming it
moved by what you added. See
[The Pipecat floor is a cliff, not a dial](#the-pipecat-floor-is-a-cliff-not-a-dial).
### `unmute compile` warns that a turn `params:` block reaches nothing
A `params:` block on a turn binding is not the escape hatch. It is accepted
for shape but reaches neither framework, so `unmute compile` warns rather than
letting you believe it worked:
```
warning: model "detector" is a turn model and sets params (alpha), which no
target reads: turn params are not forwarded to either framework.
```
The same goes for `agent_id` and `fallback` on a turn binding.
**Fix:** remove the block. `pace` and `endpointing_delay` are the whole surface.
## Next
Caching and routing for speech, on SLNG's own layer.
Read `user_turn` against the floor and ceiling you just set.
# Agent configuration
Source: https://unmute.ai/reference/agent-yaml
Every block of the agent file, and the tool files beside it.
`agent.yaml` is the declarative description of the agent: what it says, what it
can do, and who it can reach. Nothing in it belongs to one target; the runtime
half lives in [targets.yaml](/reference/targets-yaml).
An optional `manifest: manifest.yaml` links the company contract copied into the
package root. If that file exists, the link is required. See
[Manifest](/reference/manifest) for the rules and saved defaults.
A package compiles onto [unmute-core](/core/start/why-unmute-core) for LiveKit and
Pipecat. Twilio and SLNG read the same file and run it with their own runtimes.
Each target refuses the keys it cannot run. See [What each target compiles](#what-each-target-compiles).
An `agent.yaml` written for unmute 0.8 or older has a `version:` line, and unmute
refuses it. See [Migrate an older package](/reference/migrate).
YAML decoding is strict. An unknown field is an error with the file and the
line, not a shrug.
Durations use Go duration syntax, for example `90s`, `15m`, or `1h30m`.
```yaml agent.yaml theme={null}
name: acme-greeter
entry_agent: greeter
models:
think:
reasoning:
provider: openai
model: gpt-5.6-terra
speak:
voice:
provider: slng
model: "deepgram/aura:2"
voice: "aura-2-thalia-en"
listen:
transcriber:
provider: slng
model: "deepgram/nova:3"
turn:
detector:
provider: local
model: silero
agents:
- name: greeter
prompt: instructions.md
think: reasoning
speak: voice
```
`channels:` and `capacity:` live in [targets.yaml](/reference/targets-yaml#channels), above `targets:`.
That `turn.detector` binding runs as written on Pipecat, which forwards a
model identity unchecked. `silero` is a voice activity detector, not a turn
detector, and LiveKit checks the identity and refuses it. A LiveKit target
names its own detector in [targets.yaml](/reference/targets-yaml):
```yaml targets.yaml theme={null}
targets:
livekit:
provider: livekit
version: "1.8.8"
sdk_language: python
models:
detector:
provider: livekit
model: turn-detector-mini
```
One `agent.yaml`, two targets, and only the override changes. That is the
split this page and [targets.yaml](/reference/targets-yaml) hold between them.
## All keys
What the deployed agent is called. Accepts lowercase letters, digits, single hyphens; 3
to 64 characters. Required; omission is refused.
Agent that answers. Accepts declared agent name. Required; omission is refused.
Starts the call on the agent a State value names, read after the prefetch. Keys
`value`, the State field to read, and `agents`, a list of `- : ` pairs.
Omit to start on `entry_agent`. Twilio and SLNG refuse it.
```yaml theme={null}
entry_by:
value: explanation
agents:
- EN: faro_en
- ES: faro_es
```
Which pipeline to build. Left out, it is `cascade`. It decides which `models`
sections are legal, so it is read before the rest of the file. See
[Architecture](/build/architecture/overview).
Model palette grouped by kind. Accepts sections `think`, `speak`, `listen`, `turn`,
and the speech to speech sections `realtime` and `live`.
Required; omission is refused.
Listen entry to use. Accepts declared `models.listen` name. Selects the sole listen
chain head; required when there are two or more, unless every cascaded agent names its
own `listen:`.
Turn entry to use. Accepts declared `models.turn` name. Selects the sole turn entry;
required when there are two or more.
Where a value comes from and which step confirms it. One entry per value, each with a
`name:` that is a field on `State` in `state.py`, plus a `source:` or a `confirm:`. Types,
defaults and descriptions live in `state.py`. If omitted, no value has a source or a
confirmation.
Facts resolved once per call, before the greeting, in the order written. Accepts one
entry per fact, each with a `name:`. If omitted, no pre-fetch runs.
Environment values the generated project reads. Accepts UPPER\_SNAKE names. If omitted,
there is no explicit secret inventory; inferred requirements still apply and missing
declarations warn.
Folders of documents a tool can search. Accepts 3 to 64 characters of `[a-z0-9_]`. If
omitted, there are no document bases.
Agents, each with a `name:`, a prompt, models, and the tasks, flows, handoffs and
transfers it owns. Accepts one or more lower snake case names. Required; omission is
refused.
Behaviour for tools that need some: `save:`, `outcomes:`, `hidden:` or `start:`. Every
file in `tools/` is already a tool. A bare name here is refused. If omitted, no tool
has package-wide behaviour.
Greeting, interruption, inactivity, and limits. Accepts keys below. If omitted, code
targets open with a model-written greeting and default interruption behavior. SLNG
requires an explicit greeting.
Tracing provider. Accepts `provider: langfuse`, `provider: logfire` or `provider: coval`. If omitted, no
tracing is configured.
## `name`
What this agent is called. Required on every target.
```yaml agent.yaml theme={null}
name: acme-support
```
The deployed name is this joined to the target it was compiled for, so
`acme-support` on a target called `slng` deploys as `acme-support-slng`, and on
a target called `livekit_eu` as `acme-support-livekit-eu`. The target half is
there for one collision the package half cannot solve: a package with two
targets of the same provider would otherwise deploy one name twice and overwrite
itself.
Where the deployed name lands:
| Target | What carries it |
| - | - |
| `slng` | the pushed agent's `name`, which is how a push finds the agent to update |
| `pipecat` | the agent name you give `pipecat cloud deploy`, its secret set, and every `pipecat cloud agent ...` command |
| `livekit` | the worker's `agent_name`, which is what a SIP dispatch rule matches |
`name:` on its own, without the target, labels the generated project: the
pyproject distribution name, the logger and the trace name.
### Why unmute does not infer it
Both candidates look like names and neither is an identity.
* The **target** is called `slng`, `livekit` or `pipecat`, because that is what
the docs, the examples and the console all call it. Unmute used to deploy
under it, so two packages in one organisation claimed one live agent and the
second deploy replaced the first, prompt, models and attached tools included.
* The **folder** is named by whoever cloned the repository. It changes on a
rename, a copy, or a CI checkout into another path, and it changes silently.
### Shape
Lowercase letters, digits and single hyphens, starting with a letter, 3 to 64
characters. The name is written into a PEP 508 `name =` in `pyproject.toml`, a
Pipecat Cloud agent, a LiveKit `agent_name` and an SLNG agent. SLNG is the
loosest of the four and pyproject the strictest, so unmute holds one shape all
four accept rather than rewriting yours per target.
### Renaming an agent that is already deployed
A rename does not move a deployment. It leaves the old one running and creates a
second, so after changing `name:`:
* **slng**: the old agent stays in your organisation. Delete it, or leave it and
point your sessions at the new id.
* **pipecat**: `pipecat cloud deploy` creates a new agent, and the old one keeps
billing. Delete it with `pipecat cloud agent delete `, and re-create
the secret set under the new name.
* **livekit**: the agent itself is fine, because `lk agent deploy` targets the
id in the preserved `livekit.toml` and re-registers the worker under the new
name. The **SIP dispatch rule** is what breaks: it still names the old worker,
so inbound calls ring and nothing answers. Delete it
(`lk sip dispatch delete `) and create it again with the new name.
There is no way to keep the old bare name. An agent deployed as `livekit` was
named after the target, and the new name always carries the package half, so the
first compile after this change renames every existing deployment once. Do that
rename deliberately, with the steps above, rather than discovering it on a call.
## `models`
Six sections. The section an entry sits in decides its kind: `think` (LLM),
`speak` (TTS), `listen` (STT), `turn` (turn detection), and `realtime` and
`live`, a
[live model](/models/live) that does the first three as one and compiles on
both code targets. The first four are maps keyed by entry name; `live` is a list
whose items carry `name:`. Entry names share one namespace across sections and
are yours to choose.
```yaml theme={null}
models:
think:
reasoning:
provider: openai
model: gpt-5.6-terra
params:
reasoning_effort: "none"
```
Which fields are legal depends on the section:
| Field | Legal section |
| - | - |
| `provider`, `model`, `endpoint_env`, `placement`, `params`, `description` | `think`, `speak`, `listen`, `turn` |
| `voice`, `speed` | `speak` |
| `language` | `speak`, `listen` |
| `temperature`, `top_p`, `top_k` | `think` |
| `semantic_endpointing` | `turn`: `required`, `preferred`, or `off` |
| `pace` | `turn`: `snappy`, `balanced`, or `patient`. How quickly the agent decides the caller has finished. Sets the ceiling on a turn, and the floor when `endpointing_delay` is absent. Defaults to `balanced`. No per-target override |
| `endpointing_delay` | `turn`: a positive duration, the window of silence before the caller counts as finished. The floor on every turn, and only the floor. LiveKit refuses under `250ms` |
| `eager` | `turn`, Pipecat only, with `provider: listen`: `true` answers the transcriber's predicted end of turn before it is confirmed, dropping the early reply if the caller goes on. Off unless set; costs one model request per prediction |
A `turn` entry's `provider` is `local` (the on-device pair) or, on Pipecat,
`listen`, which hands the decision to the listening model's own turn detection.
`listen` takes no `model` of its own and needs a Deepgram Flux or Cartesia Turns
listening model. Under `listen` the `pace` ceiling becomes the transcriber's own
end-of-turn timeout, and `semantic_endpointing`, `endpointing_delay` and
`interruption.minimum_words` are refused because nothing reads them; see
[Turn detection](/models/turn-detection).
\| `fallback` | `think`, `listen` |
\| `name`, `provider`, `model`, `voice`, `backend`, `description` | `live`, and nothing else: every other field is refused on a live entry by name, with its line. `backend` names a `models.think` entry with `provider: openai` that runs the model's tools and reasoning. See [Live model](/models/live) |
\| `name`, `provider`, `model`, `voice`, `turn_detection`, `description` | `realtime`, and nothing else. `turn_detection` is `server_vad`, `semantic` or `local`. `voice` and an agent `speak:` binding are mutually exclusive, and neither is refused. See [Realtime](/build/architecture/realtime) |
\| `prompt_suffix` | `think`: literal text appended to every prompt this binding sends, up to 512 characters, no `{{variables}}`. A per-target override cannot name a different value. See [Context Router](/optimization/context-router) |
\| `agent_id`, `upstream` | `think`, and only on a binding routed through the SLNG Context Router; refused on any other binding. See [Context Router](/optimization/context-router) |
`pace` and `endpointing_delay` are the two turn-timing settings and they do
different jobs: the pace sets the ceiling on a turn, the duration sets only the
floor. [Turn taking](/optimization/turn-taking) has every legal value and what
each becomes on each target.
A provider supported for this role and target, listed on the model pages. Required for
an API binding; there is no inferred API provider. `local` selects local placement.
Provider model id, passed through as written. Required where the selected integration
requires a model; otherwise its default applies. LiveKit turn bindings accept only
`turn-detector-mini` or `turn-detector`.
Voice id on a `speak` entry. No voice is chosen by Unmute when omitted; the selected
integration may require one or use its own default.
Speaking speed on a `speak` entry. Provider-defined values and limits; omitted leaves
the provider default.
BCP-47 language tag, such as `en` or `en-US`, on `listen` or `speak`. Omit to leave
language selection to the integration.
Sampling temperature on a `think` entry. Provider-defined values and limits; omitted
leaves the provider default.
Nucleus sampling value on a `think` entry. Provider-defined values and limits; omitted
leaves the provider default.
Sampling count on a `think` entry. Provider-defined values and limits; omitted leaves
the provider default.
An UPPER\_SNAKE environment variable name holding a custom endpoint URL. Omit to use the
integration’s endpoint. Required for Pipecat’s unlisted-provider path.
Accepts `api` or `local`. If omitted, `provider: local` selects local placement; another
named model selects API placement. Target-specific turn detection may decide placement
itself.
Provider parameter names and values. Omit to add no extra parameters. Provider limits
apply; Unmute does not define a universal accepted set. The Responses directive below is
checked separately.
Names from the same `think` or `listen` section, in retry order. Omit for no fallback
chain. Cycles and other roles are refused; Pipecat refuses generated fallback.
An author note. Omit for no note.
On `turn`, accepts `required`, `preferred`, or `off`. Omit to keep the target’s semantic
detector. `off` removes it; see [turn
detection](/models/turn-detection#semantic-endpointing).
On `turn`, accepts `snappy`, `balanced`, or `patient`. Omitted means `balanced`. Sets
the ceiling and, unless `endpointing_delay` is present, the floor. Cannot be authored in
a per-target override.
On `turn`, a positive Go duration such as `300ms`. Sets only the silence floor; LiveKit
requires at least `250ms`. Omit to use the pace’s floor. See [turn
taking](/optimization/turn-taking).
Required on a Context Router think binding: a stable id of at most 128 printable ASCII
characters, with no whitespace or colon. No id is generated. See [Context
Router](/optimization/context-router) for scope rules.
Required on a Context Router think binding; no upstream is inferred. Names the provider
and its credentials. See [upstream
fields](/optimization/context-router#upstream-fields). Refused on other bindings.
Literal text on a `think` entry, up to 512 characters, with no `{{variables}}`. Appended
to every prompt using the profile. Omit to append nothing. A target override cannot
declare a different value.
Entries you do not reference are legal alternates.
The provider catalogue has two wildcard routes. Pipecat accepts an unlisted
listen, speak, or think provider only with `endpoint_env`, through an
OpenAI-compatible integration. LiveKit accepts an unlisted think provider
through LiveKit Inference; its listen and speak provider lists are closed.
Never invent a provider name for either route.
`model` and `voice` are passthrough. Most `params` are too: a name the target's
settings object has no field for rides that target's overflow field and reaches
the provider. The narrow exception is `api: responses` on a LiveKit OpenAI
reasoning binding. Unmute checks that directive, selects the Responses client,
and turns `reasoning_effort` into the API's nested reasoning setting.
[Reasoning model](/models/llm) shows the target-local form and explains why.
Do not guess model ids, voice ids, or params. Use values the user supplied or
values verified in the provider's own documentation.
## `variables`
```yaml theme={null}
variables:
- name: caller_name
source: call_start
- name: customer_phone
confirm: verify_customer
```
A list. Types, defaults and descriptions are not written here. They live on
the `State` class in `state.py`, next to `agent.yaml`. List a value here only
when it needs a `source:` or a `confirm:`. An entry with neither is refused,
and so is the old map form. A `shapes:` block is refused too: declare each
shape as a Pydantic model in `state.py`.
The field on `State` this entry configures. An entry naming no field is refused.
Accepts `call_start`, `conversation` (SLNG only), or a [system call
fact](/reference/variables#sources). If omitted, the variable has no automatic call-fact
source; a task, pre-fetch, or session payload can still fill it. Route support is
checked for system sources. `conversation` requires a `Field(description=...)` and an
`= None` default in `state.py`. Inbound code-target calls require a default for
`call_start`.
The name of the task that must hear the caller agree to a pre-fetched value. Until
confirmed, only that task can read it in a prompt and tools cannot silently use it. If
omitted, the value is usable as soon as it arrives.
Prompts and tool templates name a value as `{{state.name}}`, or
`{{state.name.field}}` for one field of a model. Full detail on
[variables](/reference/variables), and on what `state.py` can hold:
[state.py](/reference/variables#the-state-class-holds-the-types).
## `prefetch`
```yaml theme={null}
prefetch:
- name: today
clock: now
timezone: Europe/Madrid
save:
- booking_date: result.date
- booking_weekday: result.day_of_week
```
One reading of the clock fills both variables above, at no extra cost: an
entry saves as many variables as the result has fields, from one call.
An ordered list of facts resolved once per call, before the greeting: the
clock, a fact the call itself carries, or the result of one already-declared
tool with `writes:` declared on the entry. Entries resolve top to bottom, and
one that cannot resolve is skipped rather than failing the call.
A prompt and a greeting read State as `{{state.x}}` and `{{state.x.y}}`, and read
what the call carries as `{{call.x}}`. A line code says next to a tool reads more: a
`confirm:` line reads the tool's `{{input.x}}`, and an outcome's `say:` reads
`{{result.x}}`. No helper `save:` is needed to say a value.
A `clock:` entry also carries its own `timezone:`, an IANA zone name. It is
required there, never defaulted, because a container's own clock is UTC, so a
business elsewhere needs it to date a call correctly. It sits on the entry
rather than on the package, because two entries may honestly want two zones.
An entry can also carry `refuse_call:`, a line said when the lookup finds nothing.
The call is then refused with that line. Twilio and SLNG refuse the key.
A `call:` entry runs one tool, passes its inputs with `with:`, and needs `writes: true` or `writes: false`. There is no default,
because a pre-fetch runs unasked on every call. `writes: true` compiles: it is
named in `compile-report.json` and the runbook, rather than printing a
warning.
Full field reference, the ordering rule, every result field a clock gives you,
and what an empty value does to a prompt:
[variables](/reference/variables#prefetch-resolves-a-value-before-the-call-starts).
## `secrets`
```yaml theme={null}
secrets:
- OPENAI_API_KEY
- SLNG_API_KEY
- SIP_TRUNK_HOSTNAME
- SIP_AUTH_USERNAME
- SIP_AUTH_PASSWORD
- SIP_FROM_NUMBER
- BILLING_PHONE_NUMBER
- SUPERVISOR_PHONE_NUMBER
```
A list of UPPER\_SNAKE environment variable names. Never values, and never usable
in a `{{template}}`. That list is a worked example: two model keys, the four
names a SIP connection maps, and the two desks the agent can transfer to.
Declare every environment name the generated project reads. That means names
written in tool and connection fields, transfer `to:` values, literal `os.environ`
reads in local handlers, provider API keys inferred from the model catalogue,
and the names your tracing provider needs. Names the driver or platform
supplies, such as `REDIS_URL` or `DAILY_API_KEY`, stay out. See
[secrets](/reference/secrets).
## `knowledge`
Each base has a name of 3 to 64 characters using `[a-z0-9_]`. The name is
the map key and becomes the search collection and build folder name.
```yaml theme={null}
knowledge:
refunds:
documents: knowledge/refunds
services:
documents: knowledge/services
embed: openai
```
Folders of your own documents an agent can search, so it quotes them instead of
guessing. Each folder is read, split and embedded once when the agent starts, and
held in memory, so content is fixed until the next compile.
Path to a folder inside the package containing `.txt`, `.md`, or `.pdf` documents. No
folder is inferred.
An [embedding service](/build/tools/knowledge#embedding-models). Omitted means `openai`.
Keyword mode makes no embedding call.
Accepts `meaning`, `keyword`, or `hybrid`. Omitted means `hybrid`.
Passage size in tokens, from 1 to 2048. Omitted means `90`.
Tokens shared by neighboring passages, from 0 through `chunk_size`. Omitted means `20`.
Maximum passages returned by a lookup, from 1 to 20. Omitted means `3`.
Minimum accepted result score, from 0 to 1. Omit for no score filtering. Scores are
similarities, not probabilities.
The five retrieval fields are per base, because a price list and a prose policy
want different treatment. `mode: keyword` is the one with a structural
consequence: it uses BM25, needs no embedding service, no credential and no
network call, and the emitted image installs no embeddings package. `min_score`
needs care, and needs `mode: meaning` to do anything useful. These are
similarity scores, not probabilities, and in practice they land well below 1,
so a value near 1 returns nothing. On `hybrid` the unscored keyword results
pass through any cutoff. See [Knowledge bases](/build/tools/knowledge) for how
to set it. `top_k` times `chunk_size` is roughly what reaches the model on
every lookup, and the compiler warns above about 1500 tokens.
A tool reaches a base by name, with a
[`knowledge:` block](/build/tools/knowledge), and an agent reaches it by being
given that tool. The base selects a search mode and may set a minimum score.
Full behaviour, every message, and what a lookup gives the model:
[Knowledge bases](/build/tools/knowledge).
## `agents`
```yaml theme={null}
agents:
- name: appointment_desk
prompt: instructions.md
think: reasoning
speak: voice
tools:
- check_slots
```
A lower snake case name, unique across the package.
Path to a Markdown prompt inside the package. No prompt is inferred.
Name of an entry in `models.think`. No profile is inferred. Required under
`architecture: cascade`, and refused under the other two, where one model does
this job.
Name of an entry in `models.realtime`, in place of `think` and `speak`. Legal
only under `architecture: realtime`.
Name of an entry in `models.live`, in place of `think` and `speak`. Legal only
under `architecture: live`.
Name of an entry in `models.speak`. No profile is inferred. On livekit and pipecat
each agent speaks with its own voice after a handoff.
Name of an entry in `models.listen`, for an agent that hears another language. Omit to
use the package's listen model. Cascaded agents only: a realtime or live agent hears the
caller itself, so `listen:` there is refused. This entry cannot have a `fallback:` list.
The slng and twilio targets refuse one that differs from the package's; livekit and
pipecat hear each agent with its own.
Names of loaded tool files this agent may call. Omit for no ordinary tools.
Nested task definitions or bare names of tasks defined by another agent. Omit for no
tasks. See [task fields](/build/orchestration/tasks#every-key-a-task-takes).
Ordered task sequences. Each item is a block this agent defines or the bare name of a
flow another agent defines. Omit for no flows. See [`flows`](#flows).
Agent to agent, and never returns. Each item is a block this agent defines or the bare
name of a handoff another agent defines. Omit for no agent handoffs. See
[`handoffs`](#handoffs).
Agent to a person. Each item is a block this agent defines or the bare name of a
transfer another agent defines. Omit for no human transfers. See
[`transfers`](#transfers).
A handoff, transfer or flow is defined once, by the agent that writes its block.
Any other agent names it with a bare name. A bare name nobody defines is refused,
and so are two blocks with one name.
## `tasks`
A task is nested inside the agent that defines it, not written in a top-level
catalog. Each item of an agent's `tasks:` list is either a full definition or
a bare string naming a task another agent already defines:
```yaml theme={null}
agents:
- name: appointment_desk
tasks:
- name: customer_record
when: Identify the caller before handling an appointment request.
prompt: tasks/customer-record.md
start:
say:
- One moment.
- Let me have a look.
tools:
- lookup_customer
save:
- customer_id: result.customer_id
- name: billing_desk
# appointment_desk already defines customer_record. A bare name runs the
# same task from here, so there is one definition and both agents offer it.
tasks:
- customer_record
```
A lower snake case name, unique across all agents in the package. To reuse an existing
task, write its bare name instead of defining it again.
Path to the task’s Markdown prompt inside the package. No prompt is inferred.
The situation the model reads to decide whether to start the task. If omitted, the task
is a definition only and must be used in a flow; it cannot be attached elsewhere
by bare name.
Tools loaded by the package. Each item is a bare tool name, or a block that starts
`- name: ` and adds `confirm:` and `outcomes:` for this step only. Omit for no
ordinary tools in this task; it does not inherit its owner’s tools.
Lines said to read the call back before the tool runs. The tool runs on the caller’s
yes. Lines read `{{input.x}}`. Needs a `then: done` outcome on the same tool.
What the step does with each result of this tool, top to bottom, first match wins. The
rules are in [Say what success looks like](/build/orchestration/tasks#say-what-success-looks-like).
A typed match on the result, such as `- status: booked` or `- status: [booked, moved]`.
Matches every result no `if:` above matched. Last, and at most one.
Pairs of `variable: result.field`, saved only when this outcome matches.
Lines said for this result; several are alternatives. Lines read `{{result.x}}`.
Accepts `done` or `failed`. Omitted means the step goes on.
Bare names of handoffs an agent defines. Omit for no handoffs from this task.
`State` fields the model fills from the conversation when it starts the task. Omit to
fill none.
Pairs of `variable: result.field`, including dotted result paths. Use `variable+` to
append one list item, and `result.field?` for a value the step may leave out. Omit to
save no values; the task can still finish. Types and descriptions come from the
destination fields on `State`.
What the step does as it opens. Omitted means the model writes the opening turn. Keys
below.
Fixed lines with no `{{placeholders}}`, said as the step opens. Several are
alternatives: the caller hears one each time, never the one used last.
`true` waits for the caller after `say:`, with no model request.
A tool of this step, run in code before the model speaks.
The tool’s inputs, as `- day: state.requested_day`. A `?` after the value lets the call
run without it; a value without one is required. See
[Start a step](/build/orchestration/tasks#start-a-step).
A `models.think` entry name. LiveKit only. If omitted, use the entry agent’s think
profile, even when another agent defines the task.
The [history fields](/reference/agent-yaml#context). Omit for `history: messages`. A
returning task restores its owner’s earlier context and adds only completion or unserved
status.
`result`, `expect`, and `requires` are retired task fields. A package that
writes one gets a located migration error. Declare variables, save them with
`save:`, and reference only the values a receiving prompt needs.
Two agents defining a task under the same name is refused:
```text theme={null}
agent.yaml:17: task "verify_customer" is defined by agent "concierge" and again by
agent "complaint_specialist". A task name is one name across the package: keep
one definition and let the other agent name it, "- verify_customer"
```
`when` makes a task callable; `save` says which values it saves.
A task may omit `save:` and still finish. Every generated finish also takes
optional `unserved_request`; it returns only an `unserved` status to the owner.
A webhook tool keeps its `input:` and `output:` JSON Schemas. A local tool has
neither: its handler's types are the contract.
### `context`
Used by tasks, flows and handoffs.
Accepts `full`, `messages`, `last_n`, `summary`, or `reset`. Omitted means `messages`:
keep speech and remove tool calls with their replies. `summary` is LiveKit only; SLNG
refuses authored context settings.
Required and positive with `history: last_n`. There is no default count. Refused with
other history modes.
Required with `history: summary`: a `models.think` entry name. No model is inferred.
Refused with other history modes.
Accepts `true` or `false`. Omitted behaves as `true` in modes that keep tool records. It
cannot add tool records to `messages` or `reset`. Explicit `false` is LiveKit only.
| `history` | What the receiver gets |
| - | - |
| `messages` | Caller and agent speech; tool calls and replies are removed together |
| `full` | Earlier speech and paired tool records, without earlier instructions |
| `last_n` | The newest `max_messages` entries, keeping tool calls paired with replies |
| `reset` | No earlier conversation, including the sentence that triggered the task or handoff |
| `summary` | A generated summary of earlier conversation, using `summarizer` |
`include_tool_calls: true` does not add tool records to `messages` or `reset`.
To keep old tool results, use `full` or `last_n`. Pipecat supports those two
modes plus `messages` and `reset`; it refuses `summary` and explicit
`include_tool_calls: false`. SLNG takes `messages`, `full`, `last_n` and
`reset` on a task, refuses `summary` and `include_tool_calls: false`, and has
no handoffs.
For example, these are two separate context blocks:
```yaml theme={null}
context:
history: last_n
max_messages: 8
```
```yaml theme={null}
context:
history: summary
summarizer: reasoning
```
History controls entry into the receiver. A returning task always restores
the owner's earlier conversation and adds only a status. Saved values reach
either prompt only through explicit placeholders. See
[Reduce context sharing step by step](/best-practices/context-scope).
## `flows`
An agent runs a flow by defining it in its own `flows:` list. The flow carries
its own `when:`, the situation the model reads to decide whether to run it. Another
agent runs the same flow by writing its bare name:
```yaml theme={null}
agents:
- name: appointment_desk
flows:
- name: appointment_flow
when: The caller wants to book, reschedule, or cancel an appointment.
fills:
- requested_service
steps:
- identify_customer
- select_appointment
```
A lower snake case name, unique across the package.
One or more task names, in execution order. An object requires `task` and may set
`skip_when_confirmed` to a variable that task confirms. Omit that condition to run the
step every time. An empty or absent steps list is refused.
The situation the model reads to decide whether to run the flow. Omission is accepted
but supplies no trigger guidance, so write one.
One fixed spoken line, with no `{{placeholders}}`, when the flow starts. Omit for no
announcement.
Write several as a list and the caller hears one of them each time the line fires.
Never the one that site used last. A caller who comes back through the same flow
does not hear the identical sentence twice.
It fires on entry, before any step runs, so it is spoken whether or not a
`skip_when_confirmed:` step is skipped. A line that is only true when some step
runs belongs on that step's own `start:` `say:`, not here.
`State` fields the model fills from the conversation when it picks the flow. The steps
read them. Omit to fill none.
Accepts `shared` or `isolated`. Omit it for `shared`. Each member still applies its own
`context.history`; an isolated flow cannot be widened by a member's `full`.
Accepts `return`, `transfer`, or `end`. Omit it for `return`.
Required with `then: transfer`: an existing agent name. Refused for `return` or `end`;
there is no inferred destination.
Steps that run without holding the caller. Each name must be one of `steps`. Omit to
run every step in turn.
Only `results` is accepted. Omission also means `results`.
The flow decides whether members share its running conversation. Each member
still applies its own `context.history`. An isolated flow cannot be widened by
a member's `full`.
## `handoffs` and `transfers`
Everything the model can hand the caller to and not get back. Each one is a list
in the agent that defines it, so there is no `kind:` field.
### `handoffs`
The conversation becomes another agent, and never comes back.
A lower snake case name, unique across the package.
An existing agent name. The conversation moves to that agent and does not return. No
destination is inferred.
The situation the model reads to decide whether to hand over. Omission supplies no
trigger guidance, so write one.
Any number of fixed lines. One is picked each time the handoff runs, never the one
said last, and the next agent's voice says it. A line takes no `{{ }}` placeholder and
a blank line is refused. Omit for a silent handoff.
Pairs of `variable: result.field` saved as the handoff happens. Omit to save nothing.
A tool of the receiving agent, run in code as it takes the call. Keys `call` and `with`.
Name of the receiving agent’s tool. Required inside `start`.
The tool’s inputs, as `- day: state.requested_day`. A `?` after the value lets the call
run without it; a value without one is required.
The [history fields](/reference/agent-yaml#context). Omitted means `messages`. Saved
values are visible only where the receiving prompt names them.
Saved state stays with the call, but the receiving model sees only values its
prompt references. A reset handoff gets no automatic briefing or triggering
sentence.
`say` is exact spoken text, not a model instruction: write the short
sentence the caller should hear. Omit it for a silent handoff.
### `transfers`
Puts the caller through to a person. A transfer is cold by default. Writing
`brief:` makes it warm: the agent briefs the person before connecting the caller.
```yaml theme={null}
agents:
- name: front_desk
transfers:
- name: to_manager
to: MANAGER_PHONE_NUMBER
when: The caller asks for a manager.
ring_timeout: 30s
on_unavailable: hangup
```
A lower snake case name, unique across the package.
The UPPER\_SNAKE name of an environment variable holding an E.164 number or a `sip:` URI,
read at call time. Declare it in `secrets:`. A number written here is refused, because
`agent.yaml` is the portable half of a package. The model never sees a number.
The situation the model reads to decide whether to transfer. Omission supplies no
trigger guidance, so write one.
A positive Go duration, such as `25s`. Omitted means 25 seconds on Pipecat; LiveKit
leaves it unset for the platform default.
Accepts `return_to_caller` or `hangup`. Omitted means `return_to_caller`. Pipecat
cloud-websocket requires explicit `hangup`, because the original media stream cannot be
reconnected.
Instructions for briefing the person before connecting the caller. Makes the transfer
warm. Supported only on LiveKit SIP.
Whether a route can carry the shape you asked for is decided by the connection.
A warm transfer is supported only on LiveKit `sip`; Unmute does not support warm
transfer on any Pipecat target.
A warm transfer on a route with no leg to move is refused by name:
```text wrap theme={null}
pipecat: telephony warm_transfer: telephony route (pipecat, cloud-websocket, twilio) does
not emit warm transfer: a warm handoff has to act on how the destination's leg ended,
which on this route needs a callback endpoint you host, and hosting nothing is what
this route is for; warm transfer compiles on (livekit, sip) trunks today. Connection
"twilio_voice" declares transport: cloud-websocket
```
## `tools`
```yaml theme={null}
tools:
- name: record_complaint
start:
say:
- Let me get that written down.
- name: continue_lesson
save:
- waiting: result.waiting
outcomes:
- else:
say:
- "{{result.said}}"
```
Every file in `tools/` is a tool, read in name order. The top-level `tools:`
list holds only the tools that need behaviour around them on every agent. A
bare name there is refused. Availability is decided by the `tools` list on each
agent and task, which hold names only, except that a task's list may also carry
a block for that step. **Define each tool once.** Put its
full contract in `tools/.yaml`; never inline `description`, `input`,
`output`, `with`, or an execution block under a `tools:` list in `agent.yaml`.
A block starting `- name: ` with at least one of the keys below.
Pairs of `variable: result.field`, saved on every result of the tool, whatever the
outcome. Package scope only.
What is said for each result, top to bottom, first match wins. Each item takes `if:` or
`else:` and `say:`, with no `then:` here, because only a step ends. Lines read
`{{result.x}}`. See [Say what success looks like](/build/orchestration/tasks#say-what-success-looks-like).
Result fields the model never reads. Use it for a field code speaks, such as a
read-back, so the model does not say it in its own words. Each name must be a field the
tool returns.
What is said as the tool starts, so a slow call is not silence. Keys `say` and `wait`.
Fixed sentences with no `{{variables}}`, said when the tool is called, not when it
succeeds. Several are alternatives: the caller hears one each time, never the one used
last. The `slng` target takes one line only, because an attachment carries a single
pre-action message; a list is refused there. Legal on local, webhook, knowledge, and
hosted `slng` tools.
`true` runs the tool only after the `say:` line has played, for a goodbye heard in full
before a tool that ends the call runs. Needs a `say:` line.
### Tool files
One file per tool, in `tools/`. The top level is the contract with the model;
exactly one execution block says how it runs. A local tool names a typed Python
function with `local: handler: tools/.py:`. The function's
arguments are the model's input and its Pydantic return model is the output, so a
local tool file has no `input:` or `output:`. A webhook tool writes both as JSON Schema.
Required for local, webhook, and knowledge tools: explains when the model should call
the tool. Builtins use their registry description if omitted; hosted `slng` tools
inherit their published description. Refused on MCP sources.
Required for authored webhook contracts: a JSON Schema with `type: object`
describing model arguments. A local tool leaves it out, because its handler signature is the
input. Refused on builtin, MCP, knowledge, and hosted `slng` tools, which own
their schemas.
An author-side JSON Schema with `type: object`. Omit for no declared result schema. Used
by `save:` rows and outcome matches; it is not a general runtime result validator or a
model prompt. A local tool leaves it out, because its return model is the
output. Refused on builtin, MCP, knowledge, and hosted `slng` tools.
Hidden argument/value pairs. A value is `state.variable`, a scalar, or a string with
`{{state.variable}}` placeholders. Omit to pass nothing. Legal on local, webhook, and
hosted `slng` tools; builtin `send_sms` requires its literal `from_number` setting.
Accepts `provider_default`, `continue`, or `cancel`. Omitted means `provider_default`.
Refused on MCP sources. Target support is listed above.
Accepts `returns_data` or `ends_conversation`. Omitted means `returns_data`, except
builtins whose effect comes from the registry. Refused on MCP and knowledge tools.
`file.py:function`, run before the tool. It returns an outcome to refuse the call, or
`None` to go on. Legal on a `local` tool only. Twilio and SLNG refuse it.
| Execution block | Fields |
| - | - |
| `slng` | a published tool name, or the [legacy hash block](/build/tools/hosted#the-legacy-form-still-loads) |
| `local` | `handler`, written `file.py:function`. It is required, and the function carries the types. Optional `dependencies`, exact `name==version` pins for a SLNG per-tool environment; refused on LiveKit and Pipecat, which build one dependency list for the whole project |
| `webhook` | `url_env` is required on LiveKit and Pipecat; `base_url` is a legacy literal HTTPS base that neither code target reads. SLNG refuses authored webhooks; optional `path` and `auth`; a non-empty path starts with `/` |
| `mcp` | required `url_env`; optional `server` (the platform's name for it, when it differs from this tool's name), `transport`, `auth`, and non-empty unique `tools` entries |
| `builtin` | required `id`; optional `instructions` |
| `knowledge` | required `base`, naming an entry in [`knowledge:`](#knowledge) |
| `client` | no fields; write `client: {}`; gated on every target today |
| `provider_hosted` | no fields; write `provider_hosted: {}`; gated on every target today |
A `webhook` tool takes no `precheck:`. A `knowledge` file takes no `input`, `output`, `with` or `effect`: the tool owns
both sides of its contract, taking one string and returning passages.
An `mcp` file is the block and nothing else. The six contract fields above are
all illegal on one, because the server describes its own tools.
Accepts `sse` or `streamable_http`. Inside `mcp`, omission uses the runtime’s
URL-based transport choice; a URL ending in `/mcp` selects streamable HTTP.
Builtin ids: `current_datetime`, `end_call`, `send_sms`, `user_phone_number`.
`end_call` compiles on every target. The other three are capabilities SLNG
curates, so they compile on the `slng` target only.
The file has to be named after the id it selects, because `slng` attaches a
builtin by the tool file's own name.
On a builtin, `with:` pins the capability's own settings rather than an
argument, because a curated capability publishes no argument schema. The model
never sees one either way.
`send_sms` takes a single `from_number`: the sender, as a literal number in
international format starting with a plus sign. The model supplies the
recipient and the body itself, and SLNG reads the Twilio credentials from your
vault under `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN`, which `unmute deploy`
checks.
`current_datetime` takes a single `timezone`, an IANA zone name such as
`America/Los_Angeles`. Write it whenever the agent is not in UTC. The curated
tool defaults to UTC and belongs to no organisation, so it cannot be changed on
the platform. An agent without it is told the wrong date for part of every day.
A zone survives daylight saving; an offset written into the prompt does not.
`user_phone_number` takes no settings.
`webhook.auth`:
Accepts `bearer` or `api_key`. Required when `auth` is present; no scheme is inferred.
An UPPER\_SNAKE environment variable name holding the token, never the token itself.
There is no default.
An HTTP header name, legal only with `type: api_key`. Omitted means `X-API-Key`. Bearer
authentication uses `Authorization: Bearer`.
## `conversation`
```yaml theme={null}
conversation:
greeting:
speaks_first: agent
say: "Hi, how can I help?"
interruption:
enabled: true
```
Opening behavior using `speaks_first` and optional `say`. If omitted, LiveKit and
Pipecat generate an opening line. SLNG requires an explicit greeting with `say`.
Required when `greeting` is present. Accepts `agent` or `user`; there is no default
inside an authored block. SLNG requires `agent`.
The exact opening line, with eligible variable placeholders. Requires `speaks_first:
agent`. If omitted on a code target, the model writes the greeting; SLNG requires `say`.
Barge-in settings. If omitted, interruptions remain enabled. Pipecat phone routes also
protect the greeting by default.
Required when `interruption` is present. Accepts `true` or `false`. There is no default
inside an authored block.
Accepts `greeting`, `tool_calls`, or both on Pipecat. Omit to protect the greeting on a
Pipecat phone route and nothing on a browser route. Set `[]` to protect nothing.
Non-empty protection is refused with `enabled: false`.
A positive count sets how many words count as an interruption on code targets. Omitted
or zero leaves the runtime’s default word threshold.
Phrases that do not interrupt on code targets. Omit for no authored ignored phrases.
Optional `nudge_after` and `end_after` timers. Omit for no authored inactivity timers.
SLNG refuses this block.
A positive Go duration, such as `15s`, before an idle nudge. Omit for no authored nudge
timer.
A positive Go duration, such as `45s`, before ending an idle call. Omit for no authored
idle end timer.
A positive Go duration, such as `15m`, limiting a call on code targets. Omit for no
package-defined limit. SLNG refuses this field.
Accepts `none` or `subtle`. Omitted means no thinking audio. `subtle` is LiveKit only.
## `tracing`
```yaml theme={null}
tracing:
provider: langfuse
```
### Tracing fields
Accepts `langfuse`, `logfire` or `coval`. Required inside `tracing`; no provider is inferred. Omit
the whole `tracing` block to disable tracing. Supported on LiveKit and Pipecat; refused
on SLNG.
`provider` takes one of three values: `langfuse`, `logfire` or `coval`. Tracing
works on both code targets.
| Provider | Required environment names |
| - | - |
| `langfuse` | `LANGFUSE_BASE_URL`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` |
| `logfire` | `LOGFIRE_TOKEN` |
| `coval` | `COVAL_API_KEY` |
LiveKit uses the room name as the session ID. Pipecat uses the runner session ID
as both its conversation ID and the session ID. Langfuse reads it as
`langfuse.session.id`, and Logfire as `session.id`.
Pipecat tracing owns the process OpenTelemetry provider and startup fails if another SDK provider is installed first.
With `coval`, each trace is attached to the Coval simulation that placed the
call, and the agent finds that simulation ID on the call itself. See
[tracing](/tracing/overview) for how the ID reaches the agent on each target.
Traces can contain caller speech, model input and output, and tool arguments and results.
Use only fake identities and fake customer data for release tests. Use a separate
project on your tracing provider for those tests, and do not send real customer
data until its access and retention rules are approved.
## Reachability
Models are a palette, so an unused model entry is legal. Other declarations must
be reachable from `entry_agent`. An unused handoff, transfer, flow,
or non-entry agent is a build error, and so is a tool no agent's
`tools:` list names. Attach it to the reachable graph or remove it.
A task is reachable a different way, because it is defined inside the agent
that lists it rather than in a top-level catalogue. A task with no `when:` and no
flow naming it in `steps:` is a build error too. Give it a `when:` so an
agent can decide to run it, or list it as a step of a flow that is
reached.
## What each target compiles
LiveKit and Pipecat compile a package onto unmute-core. `unmute compile` writes
`agent.json`, the package's data in the library's names. `spec.py` builds the library's
objects from it when the agent starts, so a broken package fails then, never during a
call. `agent.py` (LiveKit) or `bot.py` (Pipecat) builds the pipeline around them, and
`speech.py` holds any speech model that is not SLNG's.
The `twilio` and `slng` targets run the same file with their own runtimes and without
unmute-core. They refuse these keys at compile time. The error says to remove them or
compile to livekit or pipecat:
* a tool entry's `save`, `outcomes`, `hidden` and `start: wait`, and a tool file's `precheck`;
* a step's outcomes without `then:`, a step `start:` with `call:`, and a step outcome with `confirm:`;
* `entry_by`;
* prefetch `refuse_call`;
* a handoff's `save` or `start`.
A step outcome with `then: done` and `say:` is refused on Twilio only. SLNG speaks the line itself.
Each target refuses more of its own: see [Twilio](/targets/twilio#what-the-package-may-carry)
and [SLNG](/targets/slng).
LiveKit and Pipecat do not compile these yet:
| Key | Why |
| - | - |
| `mcp` and `slng` tools, builtins other than `end_call` | No unmute-core equivalent is wired yet. They still work on SLNG |
| A second idle nudge | One nudge, then the end |
What the models sections compile on LiveKit and Pipecat:
| Role | Compiles |
| - | - |
| `think` | Google, OpenAI, and the SLNG Context Router |
| `speak`, `listen` | SLNG speech, and every provider the catalogue lists for the target |
| `realtime` | OpenAI's realtime model |
| `live` | OpenAI's live model, with the `think` model its `backend:` names |
`tracing:` compiles `langfuse` there so far. `transfers:` transfer the caller on a phone
line, and a browser session needs no phone route variable to start. An agent's language is
its voice's `language:`, and its timezone is the clock prefetch's `timezone:`. Code says
dates in them.
A package with a `scenarios/` folder runs whole calls on the real model with
`make e2e PKG=salon-concierge FW=livekit`. See
[`examples/salon-concierge`](https://github.com/slng-ai/unmute/tree/main/examples/salon-concierge)
for every key on this page in one agent.
## Where to go next
The runtime half.
Which `provider:` values each target accepts.
# unmute compile
Source: https://unmute.ai/reference/cli/compile
Write the compiled project for each target, and read the report written next to it.
```text theme={null}
$ unmute compile --help
Compile an agent package to its resolved target artifacts.
With no package-dir, the package is the current directory, so you can cd into an agent and run this with no arguments.
Usage:
unmute compile [package-dir] [flags]
Flags:
-h, --help help for compile
--target strings target instance name (repeatable; default: all)
```
## Usage
```sh theme={null}
unmute compile my-agent
```
Every file written is printed. This is a package scaffolded by
[`unmute init`](/reference/cli/init), which declares one LiveKit target:
```text theme={null}
generated my-agent/build/livekit/.dockerignore
generated my-agent/build/livekit/.env.example
generated my-agent/build/livekit/.python-version
generated my-agent/build/livekit/Dockerfile
generated my-agent/build/livekit/agent.json
generated my-agent/build/livekit/agent.py
generated my-agent/build/livekit/compile-report.json
generated my-agent/build/livekit/compose.dev.yaml
generated my-agent/build/livekit/pyproject.toml
generated my-agent/build/livekit/spec.py
generated my-agent/build/livekit/speech.py
generated my-agent/build/livekit/state.py
```
A package with tools or knowledge files writes more: `tools/.py` per
local tool and a `knowledge/` folder. `state.py` appears when the package has a
`State` class. On Pipecat the entry point is `bot.py` in place of `agent.py`.
Output goes to `/build//`. With no `--target`,
every declared target is compiled. `--target` is repeatable.
## Files you keep next to the build
`compile` deletes `build//` and writes it again. It keeps `.env`, a
LiveKit Cloud `livekit*.toml` and tool `samples/*.json`, and nothing else. For
any other file you want next to the generated ones, such as a host's
service definition, use the package's `hosting//` folder:
```text theme={null}
my-agent/
hosting/
livekit/
fly.toml
```
Every compile copies that folder into `build//`, with its subfolders,
and prints each file:
```text theme={null}
copied my-agent/build/livekit/fly.toml
```
A hosting file may not share a name with a generated or kept file. Compile
refuses one, names it, and leaves the old build as it was. Hosting files are
copied byte for byte, and they do not change the build's `artifact_id`.
## The report
The compiler does not print what it decided. It writes that to
`build//compile-report.json`, next to the files it describes, one JSON
object per target:
A LiveKit or Pipecat build writes a short report: the `target`, the
`runtime` (the `unmute-core` version it pins) and `required_env`. The fields
below describe the other targets.
* `bindings`: what each model role resolved to, forwarded to the provider
without being checked. A LiveKit OpenAI Responses binding is the one
exception: its entry names the compiler directive it consumed and the
reasoning setting it lowered, instead of claiming every param passed through
unchanged.
* `sizing`: your `capacity:` block from targets.yaml turned into numbers, tagged with the
assumption they came from.
* `telephony`: present only for a target with a phone route. The resolved
route, its endpoints, and an evidence line per capability.
* `route_prerequisites`: setup work you must do outside Unmute before a real
call, when the route needs any.
* `required_env`, `variables`, `secrets`: what the generated project reads
from its environment, and where each name comes from.
* `generated_files`: the same paths `compile` printed above.
* `supported`: the framework version window this build was verified against.
* `notes`: driver detail, such as how a role was routed or how a turn pace
resolved to a silence window.
Open the file to see what a package resolved to. None of it appears on the
terminal.
## Warnings
Warnings print on standard error, and do not change the exit code:
```text theme={null}
warning: livekit: environment variables referenced but not declared in secrets: SIP_TRUNK_HOSTNAME (connections/twilio_sip.yaml environment sip_address)
```
## Compiling is safe to repeat
`build/` is output. Compile as often as you like; never edit inside it.
## Where to go next
Push the package you just compiled.
# unmute deploy
Source: https://unmute.ai/reference/cli/deploy
Validate, compile and push a package to SLNG in one command, or point a Twilio number at a twilio target you host.
```text theme={null}
$ unmute deploy --help
Compile a package and push it to SLNG.
Validates the package, compiles each slng target, then pushes it with `voiceai agents push`. Nothing on SLNG is created until every check passes, so a run that reports problems has changed nothing.
The credential is read from SLNG_API_KEY, falling back to VOICEAI_API_KEY and then to whatever profile `voiceai login` stored. The organisation a push resolved is always printed, because an environment key and a stored profile can belong to different ones.
With --target naming one twilio target, deploy instead points an existing Twilio number at the app you already host for it. It checks the number, checks that the host's /healthz names this build, sends /voice one signed request and compares the TwiML, then sets only the number's VoiceUrl and VoiceMethod. It uploads nothing and places no call. The account SID, Auth Token, number SID and public URL are read from the environment names the connection declares. The old route is saved to a private file under your user config directory before anything is written.
With no package-dir, the package is the current directory, so you can cd into an agent and run this with no arguments.
Usage:
unmute deploy [package-dir] [flags]
Flags:
--agent-id string update this agent, when more than one has the package's name
--call string after a successful push, place one outbound call to this E.164 number
--dry-run check everything and report, changing nothing
-h, --help help for deploy
--label string version label (default: the package name and a timestamp)
--profile string voiceai credential profile to check and push with
--run-samples run each tool's sample against your real dependencies
--target strings target instance name (repeatable for slng; default: every slng target; one twilio target per run)
```
## What it needs
Two things.
**The `voiceai` CLI, on your PATH.** SLNG hosts the agent, and `voiceai` is the
tool that owns your account and the push. Unmute opens no connection to the SLNG
agents API itself, at compile time or any other time.
```sh theme={null}
brew install slng-ai/tap/voiceai
```
**A key.** `SLNG_API_KEY` is read first, then `VOICEAI_API_KEY`, then whatever
profile `voiceai login` stored. One SLNG key serves every SLNG role, so this is
the same key a generated livekit or pipecat project reads at run time.
```sh theme={null}
export SLNG_API_KEY=...
```
Get one at [app.slng.ai/api-keys](https://app.slng.ai/api-keys).
## Usage
```sh theme={null}
unmute deploy examples/hotel-concierge
```
A `slng:` reference needs no `unmute pull` first, no mirror, and no hash:
`unmute deploy` resolves it directly against your organisation, checks it,
and attaches the version it checked. This needs `voiceai` 0.1.22 or later. An
older one is refused with upgrade guidance before anything is written. See [Hosted tools](/build/tools/hosted).
A clean run reads:
```text theme={null}
✓ slng (slng)
slng: requirements satisfied
slng: credential from SLNG_API_KEY
slng: compiled examples/hotel-concierge/build/slng (3 files)
slng: attached hotel_info v
slng: attached search_places_text v
slng: attached end_call v
slng: attached firecrawl-mcp-2 firecrawl_scrape
slng: attached firecrawl-mcp-2 firecrawl_search
slng: agent created
slng: deployed. Talk to it: voiceai agents web-sessions create
```
The first line is `validate`'s own row. Every line after it is a check
`validate` cannot make, made against your organisation.
Each `attached` line names a reference this run resolved and checked against
your organisation, never one it created. Every tool it names already existed,
published, before this run started. `v` is the version this run checked and
attached, which is always the latest published one. An MCP selection carries no
version, because a server tool has none; what was checked for it is the schema
hash SLNG's own snapshot recorded. The `requirements satisfied` count is the
same account read, folded in with every Vault entry, MCP server and builtin the
package needs.
With no `--target`, only `slng` targets are deployed. A livekit or pipecat
target compiles to a project that somebody else's platform runs, so it is
`unmute compile` plus that platform's own deploy step. Deploying a package with
no slng target names the block that would add one. A twilio target is deployed
only when `--target` names it; see [A twilio target](#a-twilio-target).
No line names the organisation. The key decides it, and the `credential from`
line names the key.
## Stages
**Validate.** The same checks as [`unmute validate`](/reference/cli/validate),
against the slng target only. The slng target refuses what SLNG will not run,
and hearing it here costs no network call.
**Preflight.** Your organisation is asked what it already has, and the answer is
compared with what the package needs. A real run can refresh an unusable MCP
snapshot or fill a missing Vault entry with consent before later checks finish.
A dry run does neither.
**Compile.** The same output as [`unmute compile --target slng`](/reference/cli/compile),
written to `build/slng/`. Compiling as part of deploying is deliberate: it means
you cannot push an artifact that is older than the package.
**Publish code tools.** This runs before the account is read. Each `local:` tool
becomes an SLNG code tool. Unmute creates it (`voiceai tool create`) or updates
it (`voiceai tool update`) when its code or description changed. It runs the tool
once on its sample (`voiceai tool run --confirm-side-effects`) and publishes it
(`voiceai tool publish`). A tool that is already current is left alone and
printed as `code tool X is current (vN)`. A name already held by a tool that is
not a code tool is refused. This needs voiceai 0.1.23 or newer.
**Push.** Checked references are staged with their resolved IDs and versions,
then passed to `voiceai agents push` with `--require-resolved`.
A direct push of `build/slng` skips Unmute's binding checks and resolved staging;
use `unmute deploy` for this workflow.
## What the preflight checks
Four kinds of read, plus one per MCP server your package names and one per
`slng:` reference, to check the published version it would attach. The cost
does not grow with how many secrets you declare.
| It checks | Against | If it is wrong |
| - | - | - |
| every `builtin:` tool | your organisation's tool list | create it in the SLNG dashboard, or rename the file |
| every `slng:` reference | your organisation's tools, and its latest published version | missing entirely stops the run; a version behind a committed mirror only warns, because the agent calls the platform's latest either way |
| every `with:` argument on a `slng:` reference | that version's published parameters | the run stops, naming the tool, the argument, the version it checked, and the file that supplied it |
| every MCP server | the servers attached to your organisation | attach it in the SLNG dashboard |
| every MCP tool you expose | that server's last stored probe | correct the name, or expose a different tool |
| every vault secret and variable, including one a hosted tool or MCP server needs that the package never declares | the vault, including whether it holds a value | `unmute deploy` offers to create it |
Unmute creates no MCP servers and no tool for a `slng:` reference. The package's
own `local:` tools are published first, so they are already current when this
step reads the account. An authored `webhook:` block is refused before this step
is reached. Every other name this preflight checks already exists, published, or
the run stops.
With `--dry-run`, the code tool step prints `would create code tool X, run its
sample and publish it` (or `would update`) and stops the preview there. The rest
is checked against the published tool, which does not exist yet.
A control is never checked either. It reaches SLNG as a curated capability you
attach to the agent in the dashboard, and the compiled body carries no reference
to it, so there is nothing for a check to resolve.
A `builtin:` reference carries **the tool file's own name**, not the builtin id
it selects. A `slng:` reference carries the hosted name you wrote, so its local
file name may differ. `tools/hang_up.yaml` declaring
`builtin: end_call` emits a reference to `hang_up`, which your organisation has
never heard of. The fix is to rename the file; the preflight says so.
## When a check cannot be made
Two different things can go wrong here, and they are not treated the same.
**An old `voiceai` stops the run before any account read**, because it cannot
make the checked, resolved push this command promises. It is refused with
upgrade guidance rather than falling back to a push that resolves and attaches
whatever is newest, unchecked. See [Deploy to SLNG](/deploy/slng).
**A read that fails once the run is under way splits by what the rest of the
run still covers**, and it splits per requirement rather than per listing. Each
one says what covers it:
```text theme={null}
warning: slng: `voiceai secret list` could not be run: insufficient scope
warning: slng: secret SLNG_TOOL_RENDER: the vault could not be listed. The push checks this name and its kind against a fresh read, so a missing one is still refused there; what neither run can tell you is whether the entry holds a value
```
An unreadable vault does not block a credential **your package declares**,
because the push reads the vault again before it writes and refuses a missing
name. Two limits on that, both worth knowing:
* The push checks a name and its kind. It never reads whether the entry holds
a value, so neither run can tell you that.
* The push reads the names in your package: the credentials named on your own
tool bodies. A credential
**discovered** from a hosted tool's published contract, or from a hosted MCP
server's connection, is in neither, so it reaches no later check and an
unreadable vault blocks it here.
A read this command's own promise depends on is the same case. `unmute deploy`
attaches the published version and the MCP schema hash it resolved, under a
mode that tells the push to check neither itself, so a read that failed here
has no later step to catch it:
```text theme={null}
Cannot deploy slng. 2 things to fix:
hosted tool (2)
check_order
tools/check_order.yaml references a tool SLNG hosts, so SLNG must already have one of that name
the account's tools could not be listed, so this reference was not resolved and no version was checked
search_places_text
tools/search_places_text.yaml references a tool SLNG hosts, so SLNG must already have one of that name
the account's tools could not be listed, so this reference was not resolved and no version was checked
nothing was compiled, created or changed.
```
A read that could not be made is never reported as satisfied, either way.
Whether it also stops the run depends on whether anything downstream still
checks what it would have covered.
## Creating missing secrets
Secrets are the only thing unmute can write, so they are the only gap it offers
to close:
```text theme={null}
2 entries missing from the vault, and unmute can create them.
REFUND_API_TOKEN (secret)
tools/refund.yaml authenticates with it
a value for REFUND_API_TOKEN is set in this package's environment. Use it? [y/N]
```
Say no and the run stops with the entry still missing. Say yes and one of two
things happens. A value already in your package's `.env` is piped to `voiceai
secret create` on standard input. If there is none, the terminal is handed to
`voiceai secret create`, which prompts with the input masked.
Either way the value never reaches a command line, a file unmute writes, or your
screen. There is no `--value` flag anywhere in this path, deliberately: an
argument lands in shell history and is visible in `ps`.
A run with no terminal, such as CI, prompts for nothing. It prints the command
that would fix each entry and exits non-zero.
An entry that exists under the *other* kind, a variable where you need a secret,
is reported as a mismatch and is **not** offered a fill: the name is taken, so
creating it again would be refused.
## After a successful push
The run reports attached numbers from your organisation's SIP trunks. It does
not verify the carrier's routing or place an inbound test call:
```text theme={null}
slng: inbound trunk 2_inbound reaches this agent on +447700900222
```
Or, far more often on a first deploy, that none does yet:
```text theme={null}
slng: no number reaches this agent yet
```
When a trunk is free and you are at a terminal, the run offers to point one at
the agent it just deployed:
```text theme={null}
slng: no number reaches this agent yet
2 inbound trunks are free, and this agent has none. Which should answer for it?
[1] 1_inbound on +447700900111
[2] 2_inbound on +447700900222
[0] none, leave it unattached
choose [0]: 2
slng: 2_inbound attached. Call +447700900222 to reach this agent.
```
That is a single-field `PATCH` on the agent, so it disturbs nothing else, and it
runs *after* the push, so re-running a deploy offers it again rather than
leaving you with a silent number.
Anything other than a listed number leaves it unattached, and a run with no
terminal never asks and never attaches: a deploy that quietly claimed a phone
number would be somebody's phone bill.
Unmute buys no numbers and configures no carrier routing. Set up the connection
in SLNG and route the carrier number to its SIP destination. Attachment alone
does not redirect a number from Twilio Dev Phone or another webhook. Follow
[Receive phone calls](/deploy/slng#receive-phone-calls), then confirm a real
call appears in SLNG. Required `with:` inputs need valid defaults for inbound
calls, since the carrier supplies no web-session arguments.
`--call` places one outbound call from the agent you just deployed, which is how
you hear a phone agent without waiting for someone to ring it:
```sh theme={null}
unmute deploy --call +447700900123
```
It rings a real phone and costs a real call, so it happens only when you ask. A
call that fails does not fail the deploy: the agent is live either way.
## A push replaces
Updating an agent replaces it with what the package declares. A tool reference
the package no longer names is **detached**, and a field that differs from the
live agent is **overwritten**.
`--dry-run` names both, and changes nothing:
```text theme={null}
slng: requirements satisfied
slng: credential from SLNG_API_KEY
slng: compiled examples/hotel-concierge/build/slng (3 files)
slng: hotel_info v, from v
slng: would change argument_overrides.trace_id, which the agent has now and this package does not supply, so a replacement removes it and the model supplies the argument
slng: would change description, which the agent has now and this package does not declare, so a replacement removes it and the published description is used instead
slng: would change execution_policy.pre_action_message, from "Hold on." to this package's `start: say:`
slng: would change invocation, which is "system" on the agent now and "model" in this package
slng: would change system arguments `caller`, which the agent supplies to this tool now and this package cannot declare, so a replacement removes them
slng: would change trigger on `call_start`, which the agent has now and this package cannot declare, so a replacement removes it and the tool is called by the model instead
slng: would change version, from to
slng: the published description differs between those two versions
slng: search_places_text v, new
slng: would detach tool (description), which this package does not name
slng: agent acme-orders-slng — update
slng: dry run, nothing was created or changed
```
A preview names a version without the word `attached`, because nothing was:
`v, from v` is a reference the agent already has at an older version,
and `v, new` is one it does not have at all. A first deployment shows no
previous version rather than inventing one.
The indented lines are what a replacement would alter on that attachment. They
exist for the settings only the dashboard could have added: a description typed
there, an invocation switched to `system`, a `call_start` trigger, a system
argument, or an argument override the package no longer supplies. Each is named
against the attachment it belongs to rather than left for the push to discard
silently.
A setting the package **can** declare is compared, not listed. The sentence
spoken before a tool runs is `start: say:` on the tool's entry in `agent.yaml`, so a package whose
announcement already matches the agent's shows no line for it, and one that
differs shows the sentence being replaced. Only the parts of that setting a
package has no key for, such as making the agent wait for the sentence, are
reported as things a replacement clears.
A detached reference is named by the identifier the live agent carries for it,
because a tool the package no longer mentions may be knowable by nothing else.
The published-description and published-parameter lines say the two versions'
contracts differ. They say nothing about whether the tool behaves the same: a
schema comparison cannot see a change that kept the same signature, and this
output does not pretend otherwise.
An agent's name comes from `name:` in `agent.yaml` joined to the target, so a
run that resolves to `update` when you expected `create` means an agent of that
name already exists. `unmute deploy` warns and names it; change `name:`, or let
`--agent-id` pick a different one.
## When it refuses
A refusal blocks the agent push. A real deploy may already have completed MCP
refresh or consented Vault writes; inspect `deploy-report.json` for those
changes. A dry run changes no remote state.
The problems you will meet most:
| It says | What to do |
| - | - |
| `vault missing` | create each name in [the vault](https://app.slng.ai/vault/secrets). A name that exists as a *variable* does not count. |
| `tool unresolved`, `this organisation has no tool of this name` | the package references a tool name your organisation cannot see. Rename the reference, or create the tool in the dashboard. Unmute creates none. |
| `could not be listed`, `published contract was not checked` | this run could not read your organisation's tools, or the one published version it needed. Nothing is attached unverified: fix what blocked the read and run again. |
| `--require-resolved`, naming `brew install` | the installed `voiceai` does not support a checked, resolved push. Upgrade it; see [Deploy to SLNG](/deploy/slng). |
| `agent ambiguous` | two agents share the package's name. Pass `--agent-id`. |
These problems stop the agent push. `no mirror of it is committed` and `does
not match the hash` are not on this list. `unmute deploy` compiles only the
slng target, which reads no mirror. Those two refusals belong to a `livekit` or
`pipecat` compile of the same package. See [Hosted tools](/build/tools/hosted).
## Trying a hosted tool
No sample is needed to deploy references to published tools. To exercise one
separately, use the same account and supply arguments matching its contract:
```sh theme={null}
export VOICEAI_API_KEY="$SLNG_API_KEY"
voiceai tool run check_order --input - --confirm-side-effects <<'JSON'
{"order_number":"A-1001"}
JSON
```
This executes the hosted tool against its real dependencies. The example
assumes your organisation publishes `check_order` with an `order_number`
parameter; change the name and input for your own tool.
## A twilio target
```sh theme={null}
unmute deploy --target twilio --dry-run
unmute deploy --target twilio
```
With `--target` naming one twilio target, `unmute deploy` points one existing
Twilio number at the app you already host for it. It needs no `voiceai` and no
SLNG key. It uploads nothing, buys no number and places no call.
It reads the account SID, the Auth Token, the number SID and the public URL
from the environment names the connection declares. It needs no model key.
Before it writes, it checks three things: the number takes voice calls and has
no TwiML App, SIP trunk or fallback URL; the host's `/healthz` names this
build's `artifact_id`; and a signed `POST /voice` answers this build's TwiML.
It reads and writes the number's settings in the connection's `region`, and
refuses a number whose calls another region handles.
Then it saves the old voice URL to a private file under your user config
directory, sets `VoiceUrl` and `VoiceMethod` only, and reads the number back.
A successful run reads:
```text theme={null}
✓ twilio (twilio)
twilio: routed +15005550006 (PN) to POST https://relay.example.com/voice
twilio: old route saved to /unmute/twilio-rollback/PN-