llm
LLM worker package – LLMWorker, LLMContextWorker, BackendLLMWorker, and the @tool decorator.
- class pipecat.workers.llm.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:
LLMContextWorkerA worker that runs an LLM service as the backend a frontend delegates to.
The worker owns the backend’s conversation: an
LLMContextplus 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._BackendSessionis 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, aBackendOutputpayload for each of the model’s turns and reasoning summaries and each output the app sends withsend_output(), aBackendToolCallpayload 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_MARKasks 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 thepairing_instructiongiven) is the only place the mark is named.transform_outputcan 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
BackendOutputthe model produces before it is sent, to adjust its text or whether the user may hear it, or to returnNoneand 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_INSTRUCTIONunless 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 withSPOKEN_MARKand 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_outputis 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_outputas the model’s outputs are.
- async on_job_cancelled(message: BusJobCancelMessage) None[source]
Stop the model: the frontend that was attached is gone.
The
attachjob’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.
- class pipecat.workers.llm.LLMWorker(name: str | None = None, *, llm: LLMService[Any], pipeline: Pipeline | None = None, active: bool = False, bridged: tuple[str, ...] | None = None, defer_tool_frames: bool = True)[source]
Bases:
PipelineWorkerWorker with an LLM pipeline and automatic tool registration.
Methods decorated with
@toolare registered as direct functions on the LLM and tracked so that frames queued during tool execution can be deferred until all tools complete.Example:
class MyTask(LLMWorker): @tool async def my_function(self, params, arg: str): ... worker = MyTask("worker", bus=bus, llm=OpenAILLMService(api_key="..."))
- __init__(name: str | None = None, *, llm: LLMService[Any], pipeline: Pipeline | None = None, active: bool = False, bridged: tuple[str, ...] | None = None, defer_tool_frames: bool = True)[source]
Initialize the LLMWorker.
- Parameters:
name – Unique name for this worker on the bus. Auto-generated when omitted; give one when other workers address this one by name, as they must when it runs in another process.
llm – The LLM service.
@tooldecorated methods are automatically registered on it.pipeline – Optional pipeline override. When
None, defaults toPipeline([llm]). Subclasses can pass a custom pipeline that wraps the LLM with additional processors.active – Whether the worker starts active. Defaults to False.
bridged – Bridge configuration forwarded to
PipelineWorker. Pass()to wrap the LLM pipeline with bus edge processors so it can exchange frames with another bridged worker.defer_tool_frames – Whether to defer frames queued during tool execution until all tools complete. Defaults to True.
- property llm: LLMService
The LLM service this worker wraps.
- async on_activated(args: dict | None) None[source]
Configure the LLM with tools and activation messages.
- Parameters:
args – Optional activation arguments with messages to append.
- async queue_frame(frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM) None[source]
Queue a frame, holding it if a tool handler queued it.
A frame queued from inside one of this worker’s
@toolhandlers, or from anything that handler awaits, is held and delivered once the last tool finishes. Frames from anywhere else are queued immediately: the worker’s own traffic and frames arriving over the bus, which run outside any handler’s context, and frames a handler on a different worker queues here, which this worker would never release.- Parameters:
frame – Any
Frameto deliver.direction – Direction the frame should travel. Defaults to
FrameDirection.DOWNSTREAM.
- build_tools() list[source]
Return the tools for this worker’s LLM.
By default, returns all methods decorated with
@tool. Override to provide additional or different tools.- Returns:
List of tool functions.
- async end(*, reason: str | None = None, messages: list | None = None, result_callback: Callable[[...], Any] | None = None) None[source]
Request a graceful end of the session.
When called from a
@toolhandler, deliver the function call result first withawait params.result_callback(result): the LLM output it triggers is delivered before the session ends.- Parameters:
reason – Optional human-readable reason for ending.
messages –
Optional LLM messages to inject and speak before ending. The LLM runs immediately so the output is delivered before the session terminates.
Deprecated since version 1.8.0: Call
params.result_callback(result)beforeend()instead. Will be removed in 2.0.0.result_callback –
The
result_callbackfrom FunctionCallParams.Deprecated since version 1.8.0: Call
params.result_callback(result)beforeend()instead. Will be removed in 2.0.0.
- async activate_worker(worker_name: str, *, args: WorkerActivationArgs | None = None, deactivate_self: bool = False, messages: list | None = None, result_callback: Callable[[...], Any] | None = None) None[source]
Activate another worker, draining this worker’s pipeline to hand over.
When called from a
@toolhandler, deliver the function call result first withawait params.result_callback(result): the output it triggers is delivered before the target is activated. The handover itself waits until the tool call asking for it has finished.- Parameters:
worker_name – The name of the worker to activate.
args – Optional
WorkerActivationArgsforwarded to the target worker’son_activatedhandler.deactivate_self – Whether to deactivate this worker before activating the target. Deactivating this worker drains its pipeline first; staying active does not. A worker that stays active and wants to drain anyway can call
flush_pipeline()before this.messages –
Optional LLM messages to inject and deliver before activating the target. The LLM runs immediately so the output is delivered before the transfer completes.
Deprecated since version 1.8.0: Call
params.result_callback(result)beforeactivate_worker()instead. Will be removed in 2.0.0.result_callback –
The
result_callbackfrom FunctionCallParams.Deprecated since version 1.8.0: Call
params.result_callback(result)beforeactivate_worker()instead. Will be removed in 2.0.0.
- async process_deferred_tool_frames(frames: list[tuple[Frame, FrameDirection]]) list[tuple[Frame, FrameDirection]][source]
Process deferred frames before they are flushed.
Called after all in-flight tools complete, before the deferred frames are queued into the pipeline. Override to inspect, modify, reorder, or filter the frames.
- Parameters:
frames – The deferred frames collected during tool execution.
- Returns:
The frames to queue. Return the list as-is for default behavior.
- class pipecat.workers.llm.LLMWorkerActivationArgs(metadata: dict | None = None, messages: list | None = None, run_llm: bool | None = None)[source]
Bases:
WorkerActivationArgsActivation arguments for LLM workers.
- Parameters:
messages – LLM context messages to inject on activation.
run_llm – Whether to run the LLM after appending messages. Defaults to True when
messagesis set.
- class pipecat.workers.llm.LLMContextWorker(name: str | None = None, *, llm: LLMService[Any], active: bool = False, bridged: tuple[str, ...] | None = None, defer_tool_frames: bool = True, context: LLMContext | None = None, user_params: LLMUserAggregatorParams | None = None, assistant_params: LLMAssistantAggregatorParams | None = None)[source]
Bases:
LLMWorkerLLM worker that owns an LLMContext and a context aggregator pair.
Useful for workers that need to track their own conversation history, typically workers that run their own LLM pipeline outside of a shared transport pipeline. Subclasses do not need to instantiate the context or aggregators themselves; the pipeline is built as
[user_aggregator, llm, assistant_aggregator]automatically.Example:
worker = LLMContextWorker( "worker", llm=OpenAILLMService(...), ) @worker.assistant_aggregator.event_handler("on_assistant_turn_stopped") async def _on_stopped(aggregator, message): ...
- __init__(name: str | None = None, *, llm: LLMService[Any], active: bool = False, bridged: tuple[str, ...] | None = None, defer_tool_frames: bool = True, context: LLMContext | None = None, user_params: LLMUserAggregatorParams | None = None, assistant_params: LLMAssistantAggregatorParams | None = None)[source]
Initialize the LLMContextWorker.
- Parameters:
name – Unique name for this worker on the bus. Auto-generated when omitted; give one when other workers address this one by name, as they must when it runs in another process.
llm – The LLM service.
active – Whether the worker starts active. Defaults to False.
bridged – Bridge configuration forwarded to
PipelineWorker. Pass()to wrap the pipeline with bus edges so it can exchange frames with another bridged worker.defer_tool_frames – Whether to defer frames queued during tool execution until all tools complete. Defaults to True.
context – Optional pre-built LLMContext. When omitted, a fresh empty context is created.
user_params – Optional parameters for the user aggregator.
assistant_params – Optional parameters for the assistant aggregator.
- property context: LLMContext
The LLMContext owned by this worker.
- property user_aggregator: LLMUserAggregator
The user-side context aggregator.
- property assistant_aggregator: LLMAssistantAggregator
The assistant-side context aggregator.
- class pipecat.workers.llm.BackendOutput(text: str, is_thought: bool = False, prefers_spoken: bool = True)[source]
Bases:
objectOne 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.
- pipecat.workers.llm.tool(fn=None, *, cancel_on_interruption=True, timeout_secs=None, timeout=None)[source]
Mark a method as a tool.
On
LLMWorkersubclasses, decorated methods are automatically registered with the LLM viaregister_direct_functionand included inbuild_tools().This is the worker-flavored variant of
@tool_options: it attaches the samecancel_on_interruption/timeout_secscall options and additionally marks the method (with_pipecat_is_llm_tool) so the worker collects it from the MRO.Can be used with or without arguments:
@tool async def my_tool(self, params, arg: str): ... @tool(cancel_on_interruption=False, timeout_secs=60) async def my_tool(self, params, arg: str): ...
- Parameters:
fn – The function to decorate (when used without arguments).
cancel_on_interruption – Whether to cancel this tool call when an interruption occurs. Defaults to True. Only applies to
LLMWorkertools.timeout_secs – Optional timeout in seconds for this tool call. A call that runs past it is cancelled. Defaults to None (uses the LLM service default). Only applies to
LLMWorkertools.timeout –
Deprecated alias for
timeout_secs.Deprecated since version 1.4.0: Use
timeout_secsinstead. Will be removed in 2.0.0.
Submodules
- backend_llm_worker
ATTACH_JOB_NAMEMESSAGE_JOB_NAMEOUTPUT_UPDATE_TYPETOOL_CALL_UPDATE_TYPEATTACHED_UPDATE_TYPEIDLE_UPDATE_TYPEERROR_UPDATE_TYPESPOKEN_MARKBACKEND_PAIRING_INSTRUCTIONBackendOutputBackendToolCallBackendIdleBackendErrorBackendEventBackendOutputTransformTRANSCRIPT_REQUEST_INSTRUCTIONEXPLICIT_REQUEST_INSTRUCTIONBackendLLMWorker
- llm_context_worker
- llm_worker
- tool_decorator