backend_llm_worker

Backend LLM worker for two-tier voice agents.

A frontend holds the conversation and hands off requests that need tools or careful reasoning. What the frontend is does not matter to this contract: a speech-to-speech model delegating on its own, or a pipeline calling a tool. A BackendLLMWorker runs any Pipecat LLM service, with its own context and multi-step tool calling, to do that work.

The frontend and the backend exchange messages. A frontend attaches to the worker once, for as long as it lives, and from then on hears everything the backend produces as a stream: each of its model’s turns and reasoning summaries as a BackendOutput, each phase of the function calls it makes as a BackendToolCall, and when it has run out of things to do, that it is idle. Requests go the other way as messages appended to the backend’s conversation, each answered at once; a message that arrives while the backend is working joins that work, and the backend’s model sorts out what it means. _BackendSession is the caller side of that contract.

A request is text, so how a frontend words one is its own business. _render_transcript_request() renders the conversation as a labelled transcript, which is what a frontend hands over when its model signals a handoff without wording a request; a frontend whose model does word one sends that instead. OpenAILiveLLMService’s client delegation and LLMWithBackend both drive the worker this way.

pipecat.workers.llm.backend_llm_worker.ATTACH_JOB_NAME = 'attach'

Name of the job that attaches a frontend to a BackendLLMWorker.

pipecat.workers.llm.backend_llm_worker.MESSAGE_JOB_NAME = 'message'

Name of the job that puts a message to an attached BackendLLMWorker.

pipecat.workers.llm.backend_llm_worker.OUTPUT_UPDATE_TYPE = 'output'

The type of a job update that carries a BackendOutput.

pipecat.workers.llm.backend_llm_worker.TOOL_CALL_UPDATE_TYPE = 'tool_call'

The type of a job update that carries a BackendToolCall.

pipecat.workers.llm.backend_llm_worker.ATTACHED_UPDATE_TYPE = 'attached'

The type of the update that opens an attach job’s stream.

pipecat.workers.llm.backend_llm_worker.IDLE_UPDATE_TYPE = 'idle'

The type of the update that says the backend has nothing left to do.

pipecat.workers.llm.backend_llm_worker.ERROR_UPDATE_TYPE = 'error'

The type of the update that says the backend could not go on.

pipecat.workers.llm.backend_llm_worker.SPOKEN_MARK = '>>'

The mark the backend’s model puts at the start of a message it wants the user told. The message is sent with prefers_spoken=True, mark stripped; a message without it is a note (prefers_spoken=False). Strict prompt, flexible parsing: the model is told to put the mark first, but sometimes writes a note paragraph and then a marked one, so a mark at the start of a later line splits the message, a note before it and a spoken message from it on, rather than losing the result. The turn-completion markers are read the same way (user_turn_completion_mixin).

pipecat.workers.llm.backend_llm_worker.BACKEND_PAIRING_INSTRUCTION = "You are the backend of a voice assistant. The assistant talks with the user and sends you requests: the conversation it is having, or a request it worded for you. Do the parts that need your tools or careful reasoning; the assistant handles the rest of the conversation itself, such as small talk, jokes and stories, so leave those to it.\n\nWHAT THE USER HEARS: Begin a message with >> and the whole of it is told to the user, in the assistant's own words, tool calls or not. Anything you write without the mark is not told to the user: the assistant keeps it as notes on your work, and draws on them only if the user asks how the work is going. Mark a message to give a result, to ask a question you cannot proceed without, or for news the user should have now. A result you do not mark is lost: the message that gives it begins with >>. Never say again what you have already marked, and never mark that you have stopped or that there is nothing to do: the assistant has already told the user. Write a marked message as plain spoken sentences the assistant can say as they are: no headings, lists, Markdown or raw JSON.\n\nREQUESTS: A request may arrive while you are working on an earlier one. It may add work, change it, or stop some or all of it: follow the latest, cancel the tools whose results are no longer wanted, and do not repeat work already done. With several requests in hand, do the newest first unless it depends on an earlier one, and give each one's result as soon as you have it, not when everything is done."

How the backend’s model works with the assistant, appended to its system instruction: who it is, which of what it writes the user hears, and how it takes requests. The backend’s own system instruction says what it does; this says how what it writes reaches the user. BackendLLMWorker(pairing_instruction=...) replaces it. Before changing it, see scripts/llm-with-backend/tuning/README.md.

class pipecat.workers.llm.backend_llm_worker.BackendOutput(text: str, is_thought: bool = False, prefers_spoken: bool = True)[source]

Bases: object

One piece of output from a backend, on its way to the frontend.

Parameters:
  • text – The text the backend produced.

  • is_thought – Whether this is a reasoning summary rather than a response.

  • prefers_spoken – Whether the backend would like the user to hear this. This is just a hint to the frontend: it may choose to follow it or not. OpenAILiveLLMService’s live model takes it into consideration, but ultimately decides what to speak (or not) based on the conversation.

is_thought: bool = False
prefers_spoken: bool = True
to_payload() → dict[str, Any][source]

Render the output as a job update payload.

Returns:

The payload.

classmethod from_payload(payload: dict[str, Any]) → BackendOutput[source]

Rebuild an output from a job update payload.

Parameters:

payload – The update payload.

Returns:

The output.

class pipecat.workers.llm.backend_llm_worker.BackendToolCall(phase: Literal['started', 'in_progress', 'result', 'cancelled'], function_name: str, tool_call_id: str, arguments: Mapping[str, Any] | None = None, result: Any = None, is_final: bool = True)[source]

Bases: object

One phase of a function call the backend made while working, on its way to the frontend.

The call ran in the backend’s own pipeline; the frontend reports it to clients, as the ExternalFunctionCall*Frame to_frame() builds, and does nothing else with it. The phases mirror the pipeline’s own function-call frames.

Parameters:
  • phase – started, in_progress, result or cancelled.

  • function_name – Name of the function called.

  • tool_call_id – Unique identifier of the call.

  • arguments – Arguments passed to the function, once known.

  • result – The result, for the result phase.

  • is_final – For the result phase, whether the result completes the call rather than being one of a stream of intermediate results.

arguments: Mapping[str, Any] | None = None
result: Any = None
is_final: bool = True
to_payload() → dict[str, Any][source]

Render the call phase as a job update payload.

Returns:

The payload.

classmethod from_payload(payload: dict[str, Any]) → BackendToolCall[source]

Rebuild a call phase from a job update payload.

Parameters:

payload – The update payload.

Returns:

The call phase.

to_frame() → Frame[source]

Build the frame that reports this phase in the frontend’s pipeline.

Returns:

The frame for the phase.

class pipecat.workers.llm.backend_llm_worker.BackendIdle[source]

Bases: object

The backend has nothing left to do: no run outstanding, no call in flight.

class pipecat.workers.llm.backend_llm_worker.BackendError(error: str)[source]

Bases: object

The backend could not go on with what it was doing.

Parameters:

error – What went wrong.

pipecat.workers.llm.backend_llm_worker.BackendEvent = pipecat.workers.llm.backend_llm_worker.BackendOutput | pipecat.workers.llm.backend_llm_worker.BackendToolCall | pipecat.workers.llm.backend_llm_worker.BackendIdle | pipecat.workers.llm.backend_llm_worker.BackendError

What a _BackendSession yields.

class pipecat.workers.llm.backend_llm_worker.BackendOutputTransform(*args, **kwargs)[source]

Bases: Protocol

Shapes one of the backend model’s outputs before it is sent.

pipecat.workers.llm.backend_llm_worker.TRANSCRIPT_REQUEST_INSTRUCTION = "Act on the user's most recent request in the conversation above. If it asks for something, tell the user the result as soon as you have it, before going on with other work, in a message that begins with >>. If it only stops or changes work already under way, tell them nothing: the assistant already has."

What _render_transcript_request() tells the backend to do with a transcript. Before changing it, see scripts/llm-with-backend/tuning/README.md.

pipecat.workers.llm.backend_llm_worker.EXPLICIT_REQUEST_INSTRUCTION = 'If this request asks for something, tell the user the result as soon as you have it, before going on with other work, in a message that begins with >>. If it only stops or changes work already under way, tell them nothing: the assistant already has.'

Appended to a request the frontend worded itself, so the backend tells the user its result on its own rather than with whatever else it is doing. Before changing it, see scripts/llm-with-backend/tuning/README.md.

class pipecat.workers.llm.backend_llm_worker.BackendLLMWorker(*, llm: LLMService[Any], context: LLMContext | None = None, name: str | None = None, transform_output: BackendOutputTransform | None = None, pairing_instruction: str = "You are the backend of a voice assistant. The assistant talks with the user and sends you requests: the conversation it is having, or a request it worded for you. Do the parts that need your tools or careful reasoning; the assistant handles the rest of the conversation itself, such as small talk, jokes and stories, so leave those to it.\n\nWHAT THE USER HEARS: Begin a message with >> and the whole of it is told to the user, in the assistant's own words, tool calls or not. Anything you write without the mark is not told to the user: the assistant keeps it as notes on your work, and draws on them only if the user asks how the work is going. Mark a message to give a result, to ask a question you cannot proceed without, or for news the user should have now. A result you do not mark is lost: the message that gives it begins with >>. Never say again what you have already marked, and never mark that you have stopped or that there is nothing to do: the assistant has already told the user. Write a marked message as plain spoken sentences the assistant can say as they are: no headings, lists, Markdown or raw JSON.\n\nREQUESTS: A request may arrive while you are working on an earlier one. It may add work, change it, or stop some or all of it: follow the latest, cancel the tools whose results are no longer wanted, and do not repeat work already done. With several requests in hand, do the newest first unless it depends on an earlier one, and give each one's result as soon as you have it, not when everything is done.", user_params: LLMUserAggregatorParams | None = None, assistant_params: LLMAssistantAggregatorParams | None = None)[source]

Bases: LLMContextWorker

A worker that runs an LLM service as the backend a frontend delegates to.

The worker owns the backend’s conversation: an LLMContext plus the aggregator pair, so multi-step tool calling works as it does in any pipeline. A frontend attaches once, for as long as it lives, and from then on hears everything the backend produces; requests it sends are appended to that conversation as user messages and run the model. _BackendSession is the caller side.

The worker’s LLM does the reasoning its frontend hands off, so it runs at its provider’s default thinking unless its settings configure thinking (see LLMSettings.use_provider_thinking_default).

Job contract:

  • attach: no payload. Its first update is {"type": "attached", "capabilities": {...}}; after that, a BackendOutput payload for each of the model’s turns and reasoning summaries and each output the app sends with send_output(), a BackendToolCall payload for each phase of each function call the backend makes, {"type": "idle"} when the backend has nothing left to do, and {"type": "error", "error": ...} when it could not go on. The job lives until the requester cancels it, which stops the backend’s work. Refused while another frontend is attached.

  • message: {"request": str}, appended as a user message; responds at once with {"backend": "idle" | "working"}, what the backend was doing when the message arrived. A message that arrives mid-run is taken up after the current step, with everything that came before it in view.

The model decides what the user hears: a message it begins with SPOKEN_MARK asks to be spoken, whether or not the turn also calls tools, and the mark is stripped; anything else it writes, reasoning summaries included, is a note that the frontend keeps but does not speak. A mark at the start of a later line splits the message into a note and a spoken part, since the model sometimes writes it that way. The backend’s own system instruction says what it does and, in plain words, what the user should be told; the pairing instruction the worker appends (BACKEND_PAIRING_INSTRUCTION, or the pairing_instruction given) is the only place the mark is named. transform_output can change the flag, or the text, or drop the output.

Example:

backend = BackendLLMWorker(
    llm=AnthropicLLMService(api_key=...),
    context=LLMContext(
        [{"role": "system", "content": BACKEND_INSTRUCTIONS}],
        tools=[get_weather],
    ),
)
__init__(*, llm: LLMService[Any], context: LLMContext | None = None, name: str | None = None, transform_output: BackendOutputTransform | None = None, pairing_instruction: str = "You are the backend of a voice assistant. The assistant talks with the user and sends you requests: the conversation it is having, or a request it worded for you. Do the parts that need your tools or careful reasoning; the assistant handles the rest of the conversation itself, such as small talk, jokes and stories, so leave those to it.\n\nWHAT THE USER HEARS: Begin a message with >> and the whole of it is told to the user, in the assistant's own words, tool calls or not. Anything you write without the mark is not told to the user: the assistant keeps it as notes on your work, and draws on them only if the user asks how the work is going. Mark a message to give a result, to ask a question you cannot proceed without, or for news the user should have now. A result you do not mark is lost: the message that gives it begins with >>. Never say again what you have already marked, and never mark that you have stopped or that there is nothing to do: the assistant has already told the user. Write a marked message as plain spoken sentences the assistant can say as they are: no headings, lists, Markdown or raw JSON.\n\nREQUESTS: A request may arrive while you are working on an earlier one. It may add work, change it, or stop some or all of it: follow the latest, cancel the tools whose results are no longer wanted, and do not repeat work already done. With several requests in hand, do the newest first unless it depends on an earlier one, and give each one's result as soon as you have it, not when everything is done.", user_params: LLMUserAggregatorParams | None = None, assistant_params: LLMAssistantAggregatorParams | None = None)[source]

Initialize the backend worker.

Parameters:
  • llm – The backend LLM service.

  • context – The backend’s context, typically carrying its tools. A fresh empty context when omitted.

  • name – Unique name for this worker on the bus. Auto-generated when omitted; give one when the backend runs in another process, where the frontend addresses it by name.

  • transform_output – Called with each BackendOutput the model produces before it is sent, to adjust its text or whether the user may hear it, or to return None and send nothing. Outputs the app sends itself are not passed through it unless the call asks.

  • pairing_instruction – How the model works with the assistant, appended to the LLM’s system instruction: BACKEND_PAIRING_INSTRUCTION unless given. One of its own has to say what that one says: that the assistant sends it requests, that the user hears what it marks with SPOKEN_MARK and nothing else, and how to take requests that arrive while it works.

  • user_params – Optional parameters for the user aggregator. Defaults to external turn strategies: the backend has no audio, so the default VAD and turn-analysis strategies (and the model the latter loads) have nothing to do here.

  • assistant_params – Optional parameters for the assistant aggregator.

Raises:

ValueError – If the LLM service declines the role.

property working: bool

a request or run outstanding, or a call in flight.

Type:

Whether the backend has work in hand

property capabilities: dict[str, bool]

What an attached frontend can count on; all of it, for a backend that is an LLM.

async attach_frontend(message: BusJobRequestMessage)[source]

Attach a frontend: stream everything the backend produces until the job is cancelled.

Parameters:

message – The job request.

async handle_message(message: BusJobRequestMessage)[source]

Put a message to the backend, and say what it was doing when it arrived.

Parameters:

message – The job request; see the class docstring for the payload.

async send_output(output: BackendOutput, *, apply_transform_output: bool = False) → None[source]

Send one output of the app’s own to the frontend.

It reaches the frontend as the model’s outputs do, but as given unless asked: transform_output is not applied to it by default. With no frontend attached there is nowhere for it to go, and it is dropped with a warning.

Parameters:
  • output – The output.

  • apply_transform_output – Whether to run the output through transform_output as the model’s outputs are.

async on_job_cancelled(message: BusJobCancelMessage) → None[source]

Stop the model: the frontend that was attached is gone.

The attach job’s handler is already cancelled by the time this runs, and has let go of the attachment; the work in flight stops too, so none of it is reported after the frontend has let go of it.