diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2dafdfa26..4749329ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,102 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- ElevenLabs TTS services now support a sample rate of 8000.
+
+### Fixed
+
+- Fixed an issue in `UltravoxSTTService` that caused improper audio processing
+ and incorrect LLM frame output.
+
+### Other
+
+- Added `examples/foundational/07x-interruptible-local.py` to show how a local
+ transport can be used.
+
+## [0.0.60] - 2025-03-20
+
+### Added
+
+- Added `default_headers` parameter to `BaseOpenAILLMService` constructor.
+
+### Changed
+
+- Rollback to `deepgram-sdk` 3.8.0 since 3.10.1 was causing connections issues.
+
+- Changed the default `InputAudioTranscription` model to `gpt-4o-transcribe`
+ for `OpenAIRealtimeBetaLLMService`.
+
+### Other
+
+- Update the `19-openai-realtime-beta.py` and `19a-azure-realtime-beta.py`
+ examples to use the FunctionSchema format.
+
+## [0.0.59] - 2025-03-20
+
+### Added
+
+- When registering a function call it is now possible to indicate if you want
+ the function call to be cancelled if there's a user interruption via
+ `cancel_on_interruption` (defaults to False). This is now possible because
+ function calls are executed concurrently.
+
+- Added support for detecting idle pipelines. By default, if no activity has
+ been detected during 5 minutes, the `PipelineTask` will be automatically
+ cancelled. It is possible to override this behavior by passing
+ `cancel_on_idle_timeout=False`. It is also possible to change the default
+ timeout with `idle_timeout_secs` or the frames that prevent the pipeline from
+ being idle with `idle_timeout_frames`. Finally, an `on_idle_timeout` event
+ handler will be triggered if the idle timeout is reached (whether the pipeline
+ task is cancelled or not).
+
+- Added `FalSTTService`, which provides STT for Fal's Wizper API.
+
+- Added a `reconnect_on_error` parameter to websocket-based TTS services as well
+ as a `on_connection_error` event handler. The `reconnect_on_error` indicates
+ whether the TTS service should reconnect on error. The `on_connection_error`
+ will always get called if there's any error no matter the value of
+ `reconnect_on_error`. This allows, for example, to fallback to a different TTS
+ provider if something goes wrong with the current one.
+
+- Added new `SkipTagsAggregator` that extends `BaseTextAggregator` to aggregate
+ text and skips end of sentence matching if aggregated text is between
+ start/end tags.
+
+- Added new `PatternPairAggregator` that extends `BaseTextAggregator` to
+ identify content between matching pattern pairs in streamed text. This allows
+ for detection and processing of structured content like XML-style tags that
+ may span across multiple text chunks or sentence boundaries.
+
+- Added new `BaseTextAggregator`. Text aggregators are used by the TTS service
+ to aggregate LLM tokens and decide when the aggregated text should be pushed
+ to the TTS service. They also allow for the text to be manipulated while it's
+ being aggregated. A text aggregator can be passed via `text_aggregator` to the
+ TTS service.
+
+- Added new `sample_rate` constructor parameter to `TavusVideoService` to allow
+ changing the output sample rate.
+
+- Added new `NeuphonicTTSService`.
+ (see https://neuphonic.com)
+
+- Added new `UltravoxSTTService`.
+ (see https://github.com/fixie-ai/ultravox)
+
+- Added `on_frame_reached_upstream` and `on_frame_reached_downstream` event
+ handlers to `PipelineTask`. Those events will be called when a frame reaches
+ the beginning or end of the pipeline respectively. Note that by default, the
+ event handlers will not be called unless a filter is set with
+ `PipelineTask.set_reached_upstream_filter()` or
+ `PipelineTask.set_reached_downstream_filter()`.
+
+- Added support for Chirp voices in `GoogleTTSService`.
+
+- Added a `flush_audio()` method to `FishTTSService` and `LmntTTSService`.
+
+- Added a `set_language` convenience method for `GoogleSTTService`, allowing
+ you to set a single language. This is in addition to the `set_languages`
+ method which allows you to set a list of languages.
+
- Added `on_user_turn_audio_data` and `on_bot_turn_audio_data` to
`AudioBufferProcessor`. This gives the ability to grab the audio of only that
turn for both the user and the bot.
@@ -65,11 +161,176 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `AzureRealtimeBetaLLMService` to support Azure's OpeanAI Realtime API. Added
foundational example `19a-azure-realtime-beta.py`.
+- Introduced `GoogleVertexLLMService`, a new class for integrating with Vertex AI
+ Gemini models. Added foundational example
+ `14p-function-calling-gemini-vertex-ai.py`.
+
+- Added support in `OpenAIRealtimeBetaLLMService` for a slate of new features:
+
+ - The `'gpt-4o-transcribe'` input audio transcription model, along
+ with new `language` and `prompt` options specific to that model.
+ - The `input_audio_noise_reduction` session property.
+
+ ```python
+ session_properties = SessionProperties(
+ # ...
+ input_audio_noise_reduction=InputAudioNoiseReduction(
+ type="near_field" # also supported: "far_field"
+ )
+ # ...
+ )
+ ```
+
+ - The `'semantic_vad'` `turn_detection` session property value, a more
+ sophisticated model for detecting when the user has stopped speaking.
+ - `on_conversation_item_created` and `on_conversation_item_updated`
+ events to `OpenAIRealtimeBetaLLMService`.
+
+ ```python
+ @llm.event_handler("on_conversation_item_created")
+ async def on_conversation_item_created(llm, item_id, item):
+ # ...
+
+ @llm.event_handler("on_conversation_item_updated")
+ async def on_conversation_item_updated(llm, item_id, item):
+ # `item` may not always be available here
+ # ...
+ ```
+
+ - The `retrieve_conversation_item(item_id)` method for introspecting a
+ conversation item on the server.
+
+ ```python
+ item = await llm.retrieve_conversation_item(item_id)
+ ```
+
### Changed
+- Updated `OpenAISTTService` to use `gpt-4o-transcribe` as the default
+ transcription model.
+
+- Updated `OpenAITTSService` to use `gpt-4o-mini-tts` as the default TTS model.
+
+- Function calls are now executed in tasks. This means that the pipeline will
+ not be blocked while the function call is being executed.
+
+- ⚠️ `PipelineTask` will now be automatically cancelled if no bot activity is
+ happening in the pipeline. There are a few settings to configure this
+ behavior, see `PipelineTask` documentation for more details.
+
+- All event handlers are now executed in separate tasks in order to prevent
+ blocking the pipeline. It is possible that event handlers take some time to
+ execute in which case the pipeline would be blocked waiting for the event
+ handler to complete.
+
+- Updated `TranscriptProcessor` to support text output from
+ `OpenAIRealtimeBetaLLMService`.
+
+- `OpenAIRealtimeBetaLLMService` and `GeminiMultimodalLiveLLMService` now push
+ a `TTSTextFrame`.
+
- Updated the default mode for `CartesiaTTSService` and
`CartesiaHttpTTSService` to `sonic-2`.
+### Deprecated
+
+- Passing a `start_callback` to `LLMService.register_function()` is now
+ deprecated, simply move the code from the start callback to the function call.
+
+- `TTSService` parameter `text_filter` is now deprecated, use `text_filters`
+ instead which is now a list. This allows passing multiple filters that will be
+ executed in order.
+
+### Removed
+
+- Removed deprecated `audio.resample_audio()`, use `create_default_resampler()`
+ instead.
+
+- Removed deprecated`stt_service` parameter from `STTMuteFilter`.
+
+- Removed deprecated RTVI processors, use an `RTVIObserver` instead.
+
+- Removed deprecated `AWSTTSService`, use `PollyTTSService` instead.
+
+- Removed deprecated field `tier` from `DailyTranscriptionSettings`, use `model`
+ instead.
+
+- Removed deprecated `pipecat.vad` package, use `pipecat.audio.vad` instead.
+
+### Fixed
+
+- Fixed an assistant aggregator issue that could cause assistant text to be
+ split into multiple chunks during function calls.
+
+- Fixed an assistant aggregator issue that was causing assistant text to not be
+ added to the context during function calls. This could lead to duplications.
+
+- Fixed a `SegmentedSTTService` issue that was causing audio to be sent
+ prematurely to the STT service. Instead of analyzing the volume in this
+ service we rely on VAD events which use both VAD and volume.
+
+- Fixed a `GeminiMultimodalLiveLLMService` issue that was causing messages to be
+ duplicated in the context when pushing `LLMMessagesAppendFrame` frames.
+
+- Fixed an issue with `SegmentedSTTService` based services
+ (e.g. `GroqSTTService`) that was not allow audio to pass-through downstream.
+
+- Fixed a `CartesiaTTSService` and `RimeTTSService` issue that would consider
+ text between spelling out tags end of sentence.
+
+- Fixed a `match_endofsentence` issue that would result in floating point
+ numbers to be considered an end of sentence.
+
+- Fixed a `match_endofsentence` issue that would result in emails to be
+ considered an end of sentence.
+
+- Fixed an issue where the RTVI message `disconnect-bot` was pushing an
+ `EndFrame`, resulting in the pipeline not shutting down. It now pushes an
+ `EndTaskFrame` upstream to shutdown the pipeline.
+
+- Fixed an issue with the `GoogleSTTService` where stream timeouts during
+ periods of inactivity were causing connection failures. The service now
+ properly detects timeout errors and handles reconnection gracefully,
+ ensuring continuous operation even after periods of silence or when using an
+ `STTMuteFilter`.
+
+- Fixed an issue in `RimeTTSService` where the last line of text sent didn't
+ result in an audio output being generated.
+
+- Fixed `OpenAIRealtimeBetaLLMService` by adding proper handling for:
+ - The `conversation.item.input_audio_transcription.delta` server message,
+ which was added server-side at some point and not handled client-side.
+ - Errors reported by the `response.done` server message.
+
+### Other
+
+- Add foundational example `07w-interruptible-fal.py`, showing `FalSTTService`.
+
+- Added a new Ultravox example
+ `examples/foundational/07u-interruptible-ultravox.py`.
+
+- Added new Neuphonic examples
+ `examples/foundational/07v-interruptible-neuphonic.py` and
+ `examples/foundational/07v-interruptible-neuphonic-http.py`.
+
+- Added a new example `examples/foundational/36-user-email-gathering.py` to show
+ how to gather user emails. The example uses's Cartesia's ``
+ tags and Rime `spell()` function to spell out the emails for confirmation.
+
+- Update the `34-audio-recording.py` example to include an STT processor.
+
+- Added foundational example `35-voice-switching.py` showing how to use the new
+ `PatternPairAggregator`. This example shows how to encode information for the
+ LLM to instruct TTS voice changes, but this can be used to encode any
+ information into the LLM response, which you want to parse and use in other
+ parts of your application.
+
+- Added a Pipecat Cloud deployment example to the `examples` directory.
+
+- Removed foundational examples 28b and 28c as the TranscriptProcessor no
+ longer has an LLM depedency. Renamed foundational example 28a to
+ `28-transcript-processor.py`.
+
## [0.0.58] - 2025-02-26
### Added
@@ -150,6 +411,9 @@ stt = DeepgramSTTService(..., live_options=LiveOptions(model="nova-2-general"))
### Fixed
+- Fixed an issue that would cause undesired interruptions via
+ `EmulateUserStartedSpeakingFrame`.
+
- Fixed a `GoogleLLMService` that was causing an exception when sending inline
audio in some cases.
@@ -166,10 +430,6 @@ stt = DeepgramSTTService(..., live_options=LiveOptions(model="nova-2-general"))
- Fixed `match_endofsentence` support for ellipses.
-- Fixed an issue that would cause undesired interruptions via
- `EmulateUserStartedSpeakingFrame` when only interim transcriptions (i.e. no
- final transcriptions) where received.
-
- Fixed an issue where `EndTaskFrame` was not triggering
`on_client_disconnected` or closing the WebSocket in FastAPI.
@@ -1834,7 +2094,7 @@ async def on_connected(processor):
completed. If a task is never ran `has_finished()` will return False.
- `PipelineRunner` now supports SIGTERM. If received, the runner will be
- canceled.
+ cancelled.
### Fixed
diff --git a/README.md b/README.md
index ec09c8f72..f28005618 100644
--- a/README.md
+++ b/README.md
@@ -57,13 +57,13 @@ pip install "pipecat-ai[option,...]"
| Category | Services | Install Command Example |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
-| Speech-to-Text | [AssemblyAI](https://docs.pipecat.ai/server/services/stt/assemblyai), [Azure](https://docs.pipecat.ai/server/services/stt/azure), [Deepgram](https://docs.pipecat.ai/server/services/stt/deepgram), [Gladia](https://docs.pipecat.ai/server/services/stt/gladia), [Google](https://docs.pipecat.ai/server/services/stt/google), [Groq (Whisper)](https://docs.pipecat.ai/server/services/stt/groq), [OpenAI (Whisper)](https://docs.pipecat.ai/server/services/stt/openai), [Whisper](https://docs.pipecat.ai/server/services/stt/whisper) | `pip install "pipecat-ai[deepgram]"` |
+| Speech-to-Text | [AssemblyAI](https://docs.pipecat.ai/server/services/stt/assemblyai), [Azure](https://docs.pipecat.ai/server/services/stt/azure), [Deepgram](https://docs.pipecat.ai/server/services/stt/deepgram), [Fal Wizper](https://docs.pipecat.ai/server/services/stt/fal), [Gladia](https://docs.pipecat.ai/server/services/stt/gladia), [Google](https://docs.pipecat.ai/server/services/stt/google), [Groq (Whisper)](https://docs.pipecat.ai/server/services/stt/groq), [OpenAI (Whisper)](https://docs.pipecat.ai/server/services/stt/openai), [Parakeet (NVIDIA)](https://docs.pipecat.ai/server/services/stt/parakeet), [Ultravox](https://docs.pipecat.ai/server/services/stt/ultravox), [Whisper](https://docs.pipecat.ai/server/services/stt/whisper) | `pip install "pipecat-ai[deepgram]"` |
| LLMs | [Anthropic](https://docs.pipecat.ai/server/services/llm/anthropic), [Azure](https://docs.pipecat.ai/server/services/llm/azure), [Cerebras](https://docs.pipecat.ai/server/services/llm/cerebras), [DeepSeek](https://docs.pipecat.ai/server/services/llm/deepseek), [Fireworks AI](https://docs.pipecat.ai/server/services/llm/fireworks), [Gemini](https://docs.pipecat.ai/server/services/llm/gemini), [Grok](https://docs.pipecat.ai/server/services/llm/grok), [Groq](https://docs.pipecat.ai/server/services/llm/groq), [NVIDIA NIM](https://docs.pipecat.ai/server/services/llm/nim), [Ollama](https://docs.pipecat.ai/server/services/llm/ollama), [OpenAI](https://docs.pipecat.ai/server/services/llm/openai), [OpenRouter](https://docs.pipecat.ai/server/services/llm/openrouter), [Perplexity](https://docs.pipecat.ai/server/services/llm/perplexity), [Together AI](https://docs.pipecat.ai/server/services/llm/together) | `pip install "pipecat-ai[openai]"` |
-| Text-to-Speech | [AWS](https://docs.pipecat.ai/server/services/tts/aws), [Azure](https://docs.pipecat.ai/server/services/tts/azure), [Cartesia](https://docs.pipecat.ai/server/services/tts/cartesia), [Deepgram](https://docs.pipecat.ai/server/services/tts/deepgram), [ElevenLabs](https://docs.pipecat.ai/server/services/tts/elevenlabs), [Fish](https://docs.pipecat.ai/server/services/tts/fish), [Google](https://docs.pipecat.ai/server/services/tts/google), [LMNT](https://docs.pipecat.ai/server/services/tts/lmnt), [OpenAI](https://docs.pipecat.ai/server/services/tts/openai), [PlayHT](https://docs.pipecat.ai/server/services/tts/playht), [Rime](https://docs.pipecat.ai/server/services/tts/rime), [XTTS](https://docs.pipecat.ai/server/services/tts/xtts) | `pip install "pipecat-ai[cartesia]"` |
+| Text-to-Speech | [AWS](https://docs.pipecat.ai/server/services/tts/aws), [Azure](https://docs.pipecat.ai/server/services/tts/azure), [Cartesia](https://docs.pipecat.ai/server/services/tts/cartesia), [Deepgram](https://docs.pipecat.ai/server/services/tts/deepgram), [ElevenLabs](https://docs.pipecat.ai/server/services/tts/elevenlabs), [FastPitch (NVIDIA)](https://docs.pipecat.ai/server/services/tts/fastpitch), [Fish](https://docs.pipecat.ai/server/services/tts/fish), [Google](https://docs.pipecat.ai/server/services/tts/google), [LMNT](https://docs.pipecat.ai/server/services/tts/lmnt), [Neuphonic](https://docs.pipecat.ai/server/services/tts/neuphonic), [OpenAI](https://docs.pipecat.ai/server/services/tts/openai), [PlayHT](https://docs.pipecat.ai/server/services/tts/playht), [Rime](https://docs.pipecat.ai/server/services/tts/rime), [XTTS](https://docs.pipecat.ai/server/services/tts/xtts) | `pip install "pipecat-ai[cartesia]"` |
| Speech-to-Speech | [Gemini Multimodal Live](https://docs.pipecat.ai/server/services/s2s/gemini), [OpenAI Realtime](https://docs.pipecat.ai/server/services/s2s/openai) | `pip install "pipecat-ai[google]"` |
| Transport | [Daily (WebRTC)](https://docs.pipecat.ai/server/services/transport/daily), [FastAPI Websocket](https://docs.pipecat.ai/server/services/transport/fastapi-websocket), [WebSocket Server](https://docs.pipecat.ai/server/services/transport/websocket-server), Local | `pip install "pipecat-ai[daily]"` |
| Video | [Tavus](https://docs.pipecat.ai/server/services/video/tavus), [Simli](https://docs.pipecat.ai/server/services/video/simli) | `pip install "pipecat-ai[tavus,simli]"` |
-| Vision & Image | [Moondream](https://docs.pipecat.ai/server/services/vision/moondream), [fal](https://docs.pipecat.ai/server/services/image-generation/fal) | `pip install "pipecat-ai[moondream]"` |
+| Vision & Image | [fal](https://docs.pipecat.ai/server/services/image-generation/fal), [Google Imagen](https://docs.pipecat.ai/server/services/image-generation/fal), [Moondream](https://docs.pipecat.ai/server/services/vision/moondream) | `pip install "pipecat-ai[moondream]"` |
| Audio Processing | [Silero VAD](https://docs.pipecat.ai/server/utilities/audio/silero-vad-analyzer), [Krisp](https://docs.pipecat.ai/server/utilities/audio/krisp-filter), [Koala](https://docs.pipecat.ai/server/utilities/audio/koala-filter), [Noisereduce](https://docs.pipecat.ai/server/utilities/audio/noisereduce-filter) | `pip install "pipecat-ai[silero]"` |
| Analytics & Metrics | [Canonical AI](https://docs.pipecat.ai/server/services/analytics/canonical), [Sentry](https://docs.pipecat.ai/server/services/analytics/sentry) | `pip install "pipecat-ai[canonical]"` |
diff --git a/dev-requirements.txt b/dev-requirements.txt
index 2b55adcbe..e65c2755c 100644
--- a/dev-requirements.txt
+++ b/dev-requirements.txt
@@ -3,10 +3,10 @@ coverage~=7.6.12
grpcio-tools~=1.67.1
pip-tools~=7.4.1
pre-commit~=4.0.1
-pyright~=1.1.394
+pyright~=1.1.397
pytest~=8.3.4
pytest-asyncio~=0.25.3
-ruff~=0.9.7
+ruff~=0.11.1
setuptools~=70.0.0
setuptools_scm~=8.1.0
python-dotenv~=1.0.1
diff --git a/dot-env.template b/dot-env.template
index e31681235..2da20fc0b 100644
--- a/dot-env.template
+++ b/dot-env.template
@@ -29,6 +29,9 @@ DAILY_SAMPLE_ROOM_URL=https://...
ELEVENLABS_API_KEY=...
ELEVENLABS_VOICE_ID=...
+# Neuphonic
+NEUPHONIC_API_KEY=...
+
# Fal
FAL_KEY=...
diff --git a/examples/bot-ready-signalling/server/signalling_bot.py b/examples/bot-ready-signalling/server/signalling_bot.py
index c6e47b812..3b98700aa 100644
--- a/examples/bot-ready-signalling/server/signalling_bot.py
+++ b/examples/bot-ready-signalling/server/signalling_bot.py
@@ -64,7 +64,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
runner = PipelineRunner()
diff --git a/examples/deployment/modal-example/bot.py b/examples/deployment/modal-example/bot.py
index 02bcff379..97ec11905 100644
--- a/examples/deployment/modal-example/bot.py
+++ b/examples/deployment/modal-example/bot.py
@@ -34,7 +34,7 @@ async def main(room_url: str, token: str):
)
tts = CartesiaTTSService(
- api_key=os.getenv("CARTESIA_API_KEY", ""), voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22"
+ api_key=os.getenv("CARTESIA_API_KEY", ""), voice_id="71a7ad14-091c-4e8e-a314-022ece01c121"
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/deployment/pipecat-cloud-example/.gitignore b/examples/deployment/pipecat-cloud-example/.gitignore
new file mode 100644
index 000000000..8a5b4de3d
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/.gitignore
@@ -0,0 +1,94 @@
+# Python
+__pycache__/
+*.py[cod]
+*$py.class
+*.so
+.Python
+build/
+dist/
+*.egg-info/
+*.egg
+.installed.cfg
+.eggs/
+downloads/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+MANIFEST
+
+# Virtual Environments
+venv/
+env/
+.env
+.venv/
+ENV/
+env.bak/
+venv.bak/
+
+# IDE
+.idea/
+.vscode/
+.spyderproject
+.spyproject
+.ropeproject
+
+# Testing and Coverage
+.coverage
+.coverage.*
+htmlcov/
+.pytest_cache/
+.tox/
+.nox/
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+cover/
+
+# Logs and Databases
+*.log
+*.db
+db.sqlite3
+db.sqlite3-journal
+pip-log.txt
+
+# System Files
+.DS_Store
+Thumbs.db
+desktop.ini
+*.swp
+*.swo
+*.bak
+*.tmp
+*~
+
+# Build and Documentation
+docs/_build/
+.pybuilder/
+target/
+instance/
+.webassets-cache
+.pdm.toml
+.pdm-python
+.pdm-build/
+__pypackages__/
+
+# Other
+*.mo
+*.pot
+*.sage.py
+.mypy_cache/
+.dmypy.json
+dmypy.json
+.pyre/
+.pytype/
+cython_debug/
+.ipynb_checkpoints
+
+# Pipecat cloud
+.pcc-deploy.toml
\ No newline at end of file
diff --git a/examples/deployment/pipecat-cloud-example/Dockerfile b/examples/deployment/pipecat-cloud-example/Dockerfile
new file mode 100644
index 000000000..290899e5c
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/Dockerfile
@@ -0,0 +1,7 @@
+FROM dailyco/pipecat-base:latest
+
+COPY ./requirements.txt requirements.txt
+
+RUN pip install --no-cache-dir --upgrade -r requirements.txt
+
+COPY ./bot.py bot.py
\ No newline at end of file
diff --git a/examples/deployment/pipecat-cloud-example/README.md b/examples/deployment/pipecat-cloud-example/README.md
new file mode 100644
index 000000000..7d5e4bd6f
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/README.md
@@ -0,0 +1,196 @@
+# Pipecat Cloud Starter Project
+
+[](https://docs.pipecat.daily.co) [](https://discord.gg/dailyco)
+
+A template voice agent for [Pipecat Cloud](https://www.daily.co/products/pipecat-cloud/) that demonstrates building and deploying a conversational AI agent.
+
+> **For a detailed step-by-step guide, see our [Quickstart Documentation](https://docs.pipecat.daily.co/quickstart).**
+
+## Prerequisites
+
+- Python 3.10+
+- Linux, MacOS, or Windows Subsystem for Linux (WSL)
+- [Docker](https://www.docker.com) and a Docker repository (e.g., [Docker Hub](https://hub.docker.com))
+- A Docker Hub account (or other container registry account)
+- [Pipecat Cloud](https://pipecat.daily.co) account
+
+> **Note**: If you haven't installed Docker yet, follow the official installation guides for your platform ([Linux](https://docs.docker.com/engine/install/), [Mac](https://docs.docker.com/desktop/setup/install/mac-install/), [Windows](https://docs.docker.com/desktop/setup/install/windows-install/)). For Docker Hub, [create a free account](https://hub.docker.com/signup) and log in via terminal with `docker login`.
+
+## Get Started
+
+### 1. Get the starter project
+
+Clone the starter project from GitHub:
+
+```bash
+git clone https://github.com/daily-co/pipecat-cloud-starter
+cd pipecat-cloud-starter
+```
+
+### 2. Set up your Python environment
+
+We recommend using a virtual environment to manage your Python dependencies.
+
+```bash
+# Create a virtual environment
+python -m venv .venv
+
+# Activate it
+source .venv/bin/activate # On Windows: .venv\Scripts\activate
+
+# Install the Pipecat Cloud CLI
+pip install pipecatcloud
+```
+
+### 3. Authenticate with Pipecat Cloud
+
+```bash
+pcc auth login
+```
+
+### 4. Acquire required API keys
+
+This starter requires the following API keys:
+
+- **OpenAI API Key**: Get from [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
+- **Cartesia API Key**: Get from [play.cartesia.ai/keys](https://play.cartesia.ai/keys)
+- **Daily API Key**: Automatically provided through your Pipecat Cloud account
+
+### 5. Configure to run locally (optional)
+
+You can test your agent locally before deploying to Pipecat Cloud:
+
+```bash
+# Set environment variables with your API keys
+export CARTESIA_API_KEY="your_cartesia_key"
+export DAILY_API_KEY="your_daily_key"
+export OPENAI_API_KEY="your_openai_key"
+```
+
+> Your `DAILY_API_KEY` can be found at [https://pipecat.daily.co](https://pipecat.daily.co) under the `Settings` in the `Daily (WebRTC)` tab.
+
+First install requirements:
+
+```bash
+pip install -r requirements.txt
+```
+
+Then, launch the bot.py script locally:
+
+```bash
+LOCAL_RUN=1 python bot.py
+```
+
+## Deploy & Run
+
+### 1. Build and push your Docker image
+
+```bash
+# Build the image (targeting ARM architecture for cloud deployment)
+docker build --platform=linux/arm64 -t my-first-agent:latest .
+
+# Tag with your Docker username and version
+docker tag my-first-agent:latest your-username/my-first-agent:0.1
+
+# Push to Docker Hub
+docker push your-username/my-first-agent:0.1
+```
+
+### 2. Create a secret set for your API keys
+
+The starter project requires API keys for OpenAI and Cartesia:
+
+```bash
+# Copy the example env file
+cp env.example .env
+
+# Edit .env to add your API keys:
+# CARTESIA_API_KEY=your_cartesia_key
+# OPENAI_API_KEY=your_openai_key
+
+# Create a secret set from your .env file
+pcc secrets set my-first-agent-secrets --file .env
+```
+
+Alternatively, you can create secrets directly via CLI:
+
+```bash
+pcc secrets set my-first-agent-secrets \
+ CARTESIA_API_KEY=your_cartesia_key \
+ OPENAI_API_KEY=your_openai_key
+```
+
+### 3. Deploy to Pipecat Cloud
+
+```bash
+pcc deploy my-first-agent your-username/my-first-agent:0.1 --secrets my-first-agent-secrets
+```
+
+> **Note (Optional)**: For a more maintainable approach, you can use the included `pcc-deploy.toml` file:
+>
+> ```toml
+> agent_name = "my-first-agent"
+> image = "your-username/my-first-agent:0.1"
+> secret_set = "my-first-agent-secrets"
+>
+> [scaling]
+> min_instances = 0
+> ```
+>
+> Then simply run `pcc deploy` without additional arguments.
+
+> **Note**: If your repository is private, you'll need to add credentials:
+>
+> ```bash
+> # Create pull secret (you’ll be prompted for credentials)
+> pcc secrets image-pull-secret pull-secret https://index.docker.io/v1/
+>
+> # Deploy with credentials
+> pcc deploy my-first-agent your-username/my-first-agent:0.1 --credentials pull-secret
+> ```
+
+### 4. Check deployment and scaling (optional)
+
+By default, your agent will use "scale-to-zero" configuration, which means it may have a cold start of around 10 seconds when first used. By default, idle instances are maintained for 5 minutes before being terminated when using scale-to-zero.
+
+For more responsive testing, you can scale your deployment to keep a minimum of one instance warm:
+
+```bash
+# Ensure at least one warm instance is always available
+pcc deploy my-first-agent your-username/my-first-agent:0.1 --min-instances 1
+
+# Check the status of your deployment
+pcc agent status my-first-agent
+```
+
+By default, idle instances are maintained for 5 minutes before being terminated when using scale-to-zero.
+
+### 5. Create an API key
+
+```bash
+# Create a public API key for accessing your agent
+pcc organizations keys create
+
+# Set it as the default key to use with your agent
+pcc organizations keys use
+```
+
+### 6. Start your agent
+
+```bash
+# Start a session with your agent in a Daily room
+pcc agent start my-first-agent --use-daily
+```
+
+This will return a URL, which you can use to connect to your running agent.
+
+## Documentation
+
+For more details on Pipecat Cloud and its capabilities:
+
+- [Pipecat Cloud Documentation](https://docs.pipecat.daily.co)
+- [Pipecat Project Documentation](https://docs.pipecat.ai)
+
+## Support
+
+Join our [Discord community](https://discord.gg/dailyco) for help and discussions.
diff --git a/examples/deployment/pipecat-cloud-example/bot.py b/examples/deployment/pipecat-cloud-example/bot.py
new file mode 100644
index 000000000..89d4973b7
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/bot.py
@@ -0,0 +1,161 @@
+#
+# Copyright (c) 2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import os
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from pipecatcloud.agent import DailySessionArguments
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.frames.frames import LLMMessagesFrame
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
+from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.openai import OpenAILLMService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+# Check if we're in local development mode
+LOCAL_RUN = os.getenv("LOCAL_RUN")
+if LOCAL_RUN:
+ import asyncio
+ import webbrowser
+
+ try:
+ from local_runner import configure
+ except ImportError:
+ logger.error("Could not import local_runner module. Local development mode may not work.")
+
+# Load environment variables
+load_dotenv(override=True)
+
+
+async def main(room_url: str, token: str):
+ """Main pipeline setup and execution function.
+
+ Args:
+ room_url: The Daily room URL
+ token: The Daily room token
+ """
+ logger.debug("Starting bot in room: {}", room_url)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "bot",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ ),
+ )
+
+ tts = CartesiaTTSService(
+ api_key=os.getenv("CARTESIA_API_KEY"), voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22"
+ )
+
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+
+ messages = [
+ {
+ "role": "system",
+ "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
+ },
+ ]
+
+ context = OpenAILLMContext(messages)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(),
+ context_aggregator.user(),
+ llm,
+ tts,
+ transport.output(),
+ context_aggregator.assistant(),
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ logger.info("First participant joined: {}", participant["id"])
+ await transport.capture_participant_transcription(participant["id"])
+ # Kick off the conversation.
+ messages.append(
+ {
+ "role": "system",
+ "content": "Please start with 'Hello World' and introduce yourself to the user.",
+ }
+ )
+ await task.queue_frames([LLMMessagesFrame(messages)])
+
+ @transport.event_handler("on_participant_left")
+ async def on_participant_left(transport, participant, reason):
+ logger.info("Participant left: {}", participant)
+ await task.cancel()
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+async def bot(args: DailySessionArguments):
+ """Main bot entry point compatible with the FastAPI route handler.
+
+ Args:
+ room_url: The Daily room URL
+ token: The Daily room token
+ body: The configuration object from the request body
+ session_id: The session ID for logging
+ """
+ logger.info(f"Bot process initialized {args.room_url} {args.token}")
+
+ try:
+ await main(args.room_url, args.token)
+ logger.info("Bot process completed")
+ except Exception as e:
+ logger.exception(f"Error in bot process: {str(e)}")
+ raise
+
+
+# Local development functions
+async def local_main():
+ """Function for local development testing."""
+ try:
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+ logger.warning("_")
+ logger.warning("_")
+ logger.warning(f"Talk to your voice agent here: {room_url}")
+ logger.warning("_")
+ logger.warning("_")
+ webbrowser.open(room_url)
+ await main(room_url, token)
+ except Exception as e:
+ logger.exception(f"Error in local development mode: {e}")
+
+
+# Local development entry point
+if LOCAL_RUN and __name__ == "__main__":
+ try:
+ asyncio.run(local_main())
+ except Exception as e:
+ logger.exception(f"Failed to run in local mode: {e}")
diff --git a/examples/deployment/pipecat-cloud-example/env.example b/examples/deployment/pipecat-cloud-example/env.example
new file mode 100644
index 000000000..1cbb5c4f6
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/env.example
@@ -0,0 +1,2 @@
+CARTESIA_API_KEY=
+OPENAI_API_KEY=
\ No newline at end of file
diff --git a/examples/deployment/pipecat-cloud-example/local_runner.py b/examples/deployment/pipecat-cloud-example/local_runner.py
new file mode 100644
index 000000000..432592534
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/local_runner.py
@@ -0,0 +1,46 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import os
+
+import aiohttp
+
+from pipecat.transports.services.helpers.daily_rest import DailyRESTHelper, DailyRoomParams
+
+
+async def configure(aiohttp_session: aiohttp.ClientSession):
+ (url, token) = await configure_with_args(aiohttp_session)
+ return (url, token)
+
+
+async def configure_with_args(aiohttp_session: aiohttp.ClientSession = None):
+ key = os.getenv("DAILY_API_KEY")
+ if not key:
+ raise Exception(
+ "No Daily API key specified. set DAILY_API_KEY in your environment to specify a Daily API key, available from https://dashboard.daily.co/developers."
+ )
+
+ daily_rest_helper = DailyRESTHelper(
+ daily_api_key=key,
+ daily_api_url=os.getenv("DAILY_API_URL", "https://api.daily.co/v1"),
+ aiohttp_session=aiohttp_session,
+ )
+
+ room = await daily_rest_helper.create_room(
+ DailyRoomParams(properties={"enable_prejoin_ui": False})
+ )
+ if not room.url:
+ raise HTTPException(status_code=500, detail="Failed to create room")
+
+ url = room.url
+
+ # Create a meeting token for the given room with an expiration 1 hour in
+ # the future.
+ expiry_time: float = 60 * 60
+
+ token = await daily_rest_helper.get_token(url, expiry_time)
+
+ return (url, token)
diff --git a/examples/deployment/pipecat-cloud-example/pcc-deploy.toml b/examples/deployment/pipecat-cloud-example/pcc-deploy.toml
new file mode 100644
index 000000000..063ed5929
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/pcc-deploy.toml
@@ -0,0 +1,6 @@
+agent_name = "my-first-agent"
+image = "your-username/my-first-agent:0.1"
+secret_set = "my-first-agent-secrets"
+
+[scaling]
+ min_instances = 0
diff --git a/examples/deployment/pipecat-cloud-example/requirements.txt b/examples/deployment/pipecat-cloud-example/requirements.txt
new file mode 100644
index 000000000..2e9fd4e9d
--- /dev/null
+++ b/examples/deployment/pipecat-cloud-example/requirements.txt
@@ -0,0 +1,3 @@
+pipecatcloud
+pipecat-ai[cartesia,daily,openai,silero]>=0.0.58
+python-dotenv~=1.0.1
diff --git a/examples/foundational/01-say-one-thing.py b/examples/foundational/01-say-one-thing.py
index dbbb94cb4..945afefda 100644
--- a/examples/foundational/01-say-one-thing.py
+++ b/examples/foundational/01-say-one-thing.py
@@ -36,7 +36,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
runner = PipelineRunner()
diff --git a/examples/foundational/01a-local-audio.py b/examples/foundational/01a-local-audio.py
index 20aaedfae..c5ed3610e 100644
--- a/examples/foundational/01a-local-audio.py
+++ b/examples/foundational/01a-local-audio.py
@@ -29,7 +29,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
pipeline = Pipeline([tts, transport.output()])
diff --git a/examples/foundational/01b-livekit-audio.py b/examples/foundational/01b-livekit-audio.py
index ed610e027..5529d4184 100644
--- a/examples/foundational/01b-livekit-audio.py
+++ b/examples/foundational/01b-livekit-audio.py
@@ -83,7 +83,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
runner = PipelineRunner()
diff --git a/examples/foundational/02-llm-say-one-thing.py b/examples/foundational/02-llm-say-one-thing.py
index d19496fae..f6f8030f1 100644
--- a/examples/foundational/02-llm-say-one-thing.py
+++ b/examples/foundational/02-llm-say-one-thing.py
@@ -37,7 +37,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/05-sync-speech-and-image.py b/examples/foundational/05-sync-speech-and-image.py
index 4b343d2af..f6d415e64 100644
--- a/examples/foundational/05-sync-speech-and-image.py
+++ b/examples/foundational/05-sync-speech-and-image.py
@@ -87,7 +87,7 @@ async def main():
tts = CartesiaHttpTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
imagegen = FalImageGenService(
diff --git a/examples/foundational/05a-local-sync-speech-and-image.py b/examples/foundational/05a-local-sync-speech-and-image.py
index 7bd689fe6..c09631061 100644
--- a/examples/foundational/05a-local-sync-speech-and-image.py
+++ b/examples/foundational/05a-local-sync-speech-and-image.py
@@ -97,7 +97,7 @@ async def main():
tts = CartesiaHttpTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
imagegen = FalImageGenService(
diff --git a/examples/foundational/06-listen-and-respond.py b/examples/foundational/06-listen-and-respond.py
index ee9ae056a..d59d143f8 100644
--- a/examples/foundational/06-listen-and-respond.py
+++ b/examples/foundational/06-listen-and-respond.py
@@ -74,7 +74,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/06a-image-sync.py b/examples/foundational/06a-image-sync.py
index 077f9b7dd..ab1c9399d 100644
--- a/examples/foundational/06a-image-sync.py
+++ b/examples/foundational/06a-image-sync.py
@@ -93,7 +93,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/07-interruptible-vad.py b/examples/foundational/07-interruptible-vad.py
index d6d3aca7c..2afc36702 100644
--- a/examples/foundational/07-interruptible-vad.py
+++ b/examples/foundational/07-interruptible-vad.py
@@ -47,7 +47,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/07-interruptible.py b/examples/foundational/07-interruptible.py
index 13e728bfc..5eab40454 100644
--- a/examples/foundational/07-interruptible.py
+++ b/examples/foundational/07-interruptible.py
@@ -46,7 +46,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/07a-interruptible-anthropic.py b/examples/foundational/07a-interruptible-anthropic.py
index f855f81e6..85f5ac68e 100644
--- a/examples/foundational/07a-interruptible-anthropic.py
+++ b/examples/foundational/07a-interruptible-anthropic.py
@@ -46,7 +46,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = AnthropicLLMService(
diff --git a/examples/foundational/07b-interruptible-langchain.py b/examples/foundational/07b-interruptible-langchain.py
index efa631b34..dd7b0b69c 100644
--- a/examples/foundational/07b-interruptible-langchain.py
+++ b/examples/foundational/07b-interruptible-langchain.py
@@ -64,7 +64,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
prompt = ChatPromptTemplate.from_messages(
diff --git a/examples/foundational/07g-interruptible-openai.py b/examples/foundational/07g-interruptible-openai.py
index f9cac5910..b66d0346a 100644
--- a/examples/foundational/07g-interruptible-openai.py
+++ b/examples/foundational/07g-interruptible-openai.py
@@ -51,16 +51,20 @@ async def main():
# api_key="gsk_***",
# model="whisper-large-v3",
# )
- stt = OpenAISTTService(api_key=os.getenv("OPENAI_API_KEY"), model="whisper-1")
+ stt = OpenAISTTService(
+ api_key=os.getenv("OPENAI_API_KEY"),
+ model="gpt-4o-transcribe-latest",
+ prompt="Expect words related to dogs, such as breed names.",
+ )
- tts = OpenAITTSService(api_key=os.getenv("OPENAI_API_KEY"), voice="alloy")
+ tts = OpenAITTSService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o-mini-tts-latest")
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
messages = [
{
"role": "system",
- "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
+ "content": "You are very knowledgable about dogs. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
},
]
diff --git a/examples/foundational/07h-interruptible-openpipe.py b/examples/foundational/07h-interruptible-openpipe.py
index 95d786297..bded77139 100644
--- a/examples/foundational/07h-interruptible-openpipe.py
+++ b/examples/foundational/07h-interruptible-openpipe.py
@@ -47,7 +47,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
timestamp = int(time.time())
diff --git a/examples/foundational/07j-interruptible-gladia.py b/examples/foundational/07j-interruptible-gladia.py
index b1e92e787..7dcd44a7a 100644
--- a/examples/foundational/07j-interruptible-gladia.py
+++ b/examples/foundational/07j-interruptible-gladia.py
@@ -51,7 +51,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/07l-interruptible-together.py b/examples/foundational/07l-interruptible-together.py
index 54ebd4c2c..d17a4fe7f 100644
--- a/examples/foundational/07l-interruptible-together.py
+++ b/examples/foundational/07l-interruptible-together.py
@@ -46,7 +46,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = TogetherLLMService(
diff --git a/examples/foundational/07o-interruptible-assemblyai.py b/examples/foundational/07o-interruptible-assemblyai.py
index bffa35322..3c30cabc9 100644
--- a/examples/foundational/07o-interruptible-assemblyai.py
+++ b/examples/foundational/07o-interruptible-assemblyai.py
@@ -51,7 +51,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/07s-interruptible-google-audio-in.py b/examples/foundational/07s-interruptible-google-audio-in.py
index e1232a155..76711d730 100644
--- a/examples/foundational/07s-interruptible-google-audio-in.py
+++ b/examples/foundational/07s-interruptible-google-audio-in.py
@@ -213,7 +213,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = GoogleLLMService(api_key=os.getenv("GOOGLE_API_KEY"), model="gemini-2.0-flash-001")
diff --git a/examples/foundational/07u-interruptible-ultravox.py b/examples/foundational/07u-interruptible-ultravox.py
new file mode 100644
index 000000000..429e5a9fb
--- /dev/null
+++ b/examples/foundational/07u-interruptible-ultravox.py
@@ -0,0 +1,91 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from runner import configure
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.audio.vad.vad_analyzer import VADParams
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.ultravox import UltravoxSTTService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+load_dotenv(override=True)
+
+# NOTE: This example requires GPU resources to run efficiently.
+# The Ultravox model is compute-intensive and performs best with GPU acceleration.
+# This can be deployed on cloud GPU providers like Cerebrium.ai for optimal performance.
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+# Want to initialize the ultravox processor since it takes time to load the model and dont
+# want to load it every time the pipeline is run
+ultravox_processor = UltravoxSTTService(
+ model_size="fixie-ai/ultravox-v0_4_1-llama-3_1-8b",
+ hf_token=os.getenv("HF_TOKEN"),
+)
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Respond bot",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=False,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(params=VADParams(stop_secs=0.2)),
+ vad_audio_passthrough=True,
+ ),
+ )
+
+ tts = CartesiaTTSService(
+ api_key=os.environ.get("CARTESIA_API_KEY"),
+ voice_id="97f4b8fb-f2fe-444b-bb9a-c109783a857a",
+ )
+
+ pipeline = Pipeline(
+ [
+ transport.input(), # Transport user input
+ ultravox_processor,
+ tts, # TTS
+ transport.output(), # Transport bot output
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ ),
+ )
+
+ @transport.event_handler("on_participant_left")
+ async def on_participant_left(transport, participant, reason):
+ await task.cancel()
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/07v-interruptible-neuphonic-http.py b/examples/foundational/07v-interruptible-neuphonic-http.py
new file mode 100644
index 000000000..8377c3baf
--- /dev/null
+++ b/examples/foundational/07v-interruptible-neuphonic-http.py
@@ -0,0 +1,102 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from runner import configure
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
+from pipecat.services.neuphonic import NeuphonicHttpTTSService
+from pipecat.services.openai import OpenAILLMService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Respond bot",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ ),
+ )
+
+ tts = NeuphonicHttpTTSService(
+ api_key=os.getenv("NEUPHONIC_API_KEY"),
+ voice_id="fc854436-2dac-4d21-aa69-ae17b54e98eb", # Emily
+ )
+
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+
+ messages = [
+ {
+ "role": "system",
+ "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
+ },
+ ]
+
+ context = OpenAILLMContext(messages)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(), # Transport user input
+ context_aggregator.user(), # User responses
+ llm, # LLM
+ tts, # TTS
+ transport.output(), # Transport bot output
+ context_aggregator.assistant(), # Assistant spoken responses
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ await transport.capture_participant_transcription(participant["id"])
+ # Kick off the conversation.
+ messages.append({"role": "system", "content": "Please introduce yourself to the user."})
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ @transport.event_handler("on_participant_left")
+ async def on_participant_left(transport, participant, reason):
+ await task.cancel()
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/07v-interruptible-neuphonic.py b/examples/foundational/07v-interruptible-neuphonic.py
new file mode 100644
index 000000000..b5d666511
--- /dev/null
+++ b/examples/foundational/07v-interruptible-neuphonic.py
@@ -0,0 +1,102 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from runner import configure
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
+from pipecat.services.neuphonic import NeuphonicTTSService
+from pipecat.services.openai import OpenAILLMService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Respond bot",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ ),
+ )
+
+ tts = NeuphonicTTSService(
+ api_key=os.getenv("NEUPHONIC_API_KEY"),
+ voice_id="fc854436-2dac-4d21-aa69-ae17b54e98eb", # Emily
+ )
+
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+
+ messages = [
+ {
+ "role": "system",
+ "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
+ },
+ ]
+
+ context = OpenAILLMContext(messages)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(), # Transport user input
+ context_aggregator.user(), # User responses
+ llm, # LLM
+ tts, # TTS
+ transport.output(), # Transport bot output
+ context_aggregator.assistant(), # Assistant spoken responses
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ await transport.capture_participant_transcription(participant["id"])
+ # Kick off the conversation.
+ messages.append({"role": "system", "content": "Please introduce yourself to the user."})
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ @transport.event_handler("on_participant_left")
+ async def on_participant_left(transport, participant, reason):
+ await task.cancel()
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/07w-interruptible-fal.py b/examples/foundational/07w-interruptible-fal.py
new file mode 100644
index 000000000..526602166
--- /dev/null
+++ b/examples/foundational/07w-interruptible-fal.py
@@ -0,0 +1,110 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from runner import configure
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
+from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.fal import FalSTTService
+from pipecat.services.gladia import GladiaSTTService
+from pipecat.services.openai import OpenAILLMService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Respond bot",
+ DailyParams(
+ audio_out_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ vad_audio_passthrough=True,
+ ),
+ )
+
+ stt = FalSTTService(
+ api_key=os.getenv("FAL_KEY"),
+ )
+
+ tts = CartesiaTTSService(
+ api_key=os.getenv("CARTESIA_API_KEY"),
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
+ )
+
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+
+ messages = [
+ {
+ "role": "system",
+ "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
+ },
+ ]
+
+ context = OpenAILLMContext(messages)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(), # Transport user input
+ stt, # STT
+ context_aggregator.user(), # User responses
+ llm, # LLM
+ tts, # TTS
+ transport.output(), # Transport bot output
+ context_aggregator.assistant(), # Assistant spoken responses
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ await transport.capture_participant_transcription(participant["id"])
+ # Kick off the conversation.
+ messages.append({"role": "system", "content": "Please introduce yourself to the user."})
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ # Register an event handler to exit the application when the user leaves.
+ @transport.event_handler("on_participant_left")
+ async def on_participant_left(transport, participant, reason):
+ await task.cancel()
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/07x-interruptible-local.py b/examples/foundational/07x-interruptible-local.py
new file mode 100644
index 000000000..54942ad97
--- /dev/null
+++ b/examples/foundational/07x-interruptible-local.py
@@ -0,0 +1,91 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+from dotenv import load_dotenv
+from loguru import logger
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
+from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.deepgram import DeepgramSTTService
+from pipecat.services.openai import OpenAILLMService
+from pipecat.transports.local.audio import LocalAudioTransport, LocalAudioTransportParams
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+
+async def main():
+ transport = LocalAudioTransport(
+ LocalAudioTransportParams(
+ audio_in_enabled=True,
+ audio_out_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ vad_audio_passthrough=True,
+ )
+ )
+
+ stt = DeepgramSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"))
+
+ tts = CartesiaTTSService(
+ api_key=os.getenv("CARTESIA_API_KEY"),
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
+ )
+
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+
+ messages = [
+ {
+ "role": "system",
+ "content": "You are a helpful LLM. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative and helpful way.",
+ },
+ ]
+
+ context = OpenAILLMContext(messages)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(), # Transport user input
+ stt,
+ context_aggregator.user(), # User responses
+ llm, # LLM
+ tts, # TTS
+ transport.output(), # Transport bot output
+ context_aggregator.assistant(), # Assistant spoken responses
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ messages.append({"role": "system", "content": "Please introduce yourself to the user."})
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/10-wake-phrase.py b/examples/foundational/10-wake-phrase.py
index 1bdeba15f..0fbd47f4a 100644
--- a/examples/foundational/10-wake-phrase.py
+++ b/examples/foundational/10-wake-phrase.py
@@ -47,7 +47,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/11-sound-effects.py b/examples/foundational/11-sound-effects.py
index 2f62d5d71..ed189551a 100644
--- a/examples/foundational/11-sound-effects.py
+++ b/examples/foundational/11-sound-effects.py
@@ -100,7 +100,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
messages = [
diff --git a/examples/foundational/12-describe-video.py b/examples/foundational/12-describe-video.py
index 2ae3ed1ad..5eeb69718 100644
--- a/examples/foundational/12-describe-video.py
+++ b/examples/foundational/12-describe-video.py
@@ -77,7 +77,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
@transport.event_handler("on_first_participant_joined")
diff --git a/examples/foundational/12a-describe-video-gemini-flash.py b/examples/foundational/12a-describe-video-gemini-flash.py
index 876aa7f07..59a9f40db 100644
--- a/examples/foundational/12a-describe-video-gemini-flash.py
+++ b/examples/foundational/12a-describe-video-gemini-flash.py
@@ -77,7 +77,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
@transport.event_handler("on_first_participant_joined")
diff --git a/examples/foundational/12b-describe-video-gpt-4o.py b/examples/foundational/12b-describe-video-gpt-4o.py
index f2944b140..fb3aa039e 100644
--- a/examples/foundational/12b-describe-video-gpt-4o.py
+++ b/examples/foundational/12b-describe-video-gpt-4o.py
@@ -76,7 +76,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
@transport.event_handler("on_first_participant_joined")
diff --git a/examples/foundational/12c-describe-video-anthropic.py b/examples/foundational/12c-describe-video-anthropic.py
index a8f3f0455..bd364a636 100644
--- a/examples/foundational/12c-describe-video-anthropic.py
+++ b/examples/foundational/12c-describe-video-anthropic.py
@@ -76,7 +76,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
@transport.event_handler("on_first_participant_joined")
diff --git a/examples/foundational/14-function-calling.py b/examples/foundational/14-function-calling.py
index 043f278e2..dddfed1d2 100644
--- a/examples/foundational/14-function-calling.py
+++ b/examples/foundational/14-function-calling.py
@@ -30,13 +30,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -58,13 +53,14 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
- # Register a function_name of None to get all functions
+
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14a-function-calling-anthropic.py b/examples/foundational/14a-function-calling-anthropic.py
index 14e788f99..923b1488d 100644
--- a/examples/foundational/14a-function-calling-anthropic.py
+++ b/examples/foundational/14a-function-calling-anthropic.py
@@ -53,11 +53,11 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = AnthropicLLMService(
- api_key=os.getenv("ANTHROPIC_API_KEY"), model="claude-3-5-sonnet-20240620"
+ api_key=os.getenv("ANTHROPIC_API_KEY"), model="claude-3-7-sonnet-latest"
)
llm.register_function("get_weather", get_weather)
diff --git a/examples/foundational/14b-function-calling-anthropic-video.py b/examples/foundational/14b-function-calling-anthropic-video.py
index b31e59442..cd9777b72 100644
--- a/examples/foundational/14b-function-calling-anthropic-video.py
+++ b/examples/foundational/14b-function-calling-anthropic-video.py
@@ -39,7 +39,12 @@ async def get_weather(function_name, tool_call_id, arguments, llm, context, resu
async def get_image(function_name, tool_call_id, arguments, llm, context, result_callback):
question = arguments["question"]
- await llm.request_image_frame(user_id=video_participant_id, text_content=question)
+ await llm.request_image_frame(
+ user_id=video_participant_id,
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ text_content=question,
+ )
async def main():
@@ -62,13 +67,12 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = AnthropicLLMService(
api_key=os.getenv("ANTHROPIC_API_KEY"),
- # model="claude-3-5-sonnet-20240620",
- model="claude-3-5-sonnet-latest",
+ model="claude-3-7-sonnet-latest",
enable_prompt_caching_beta=True,
)
llm.register_function("get_weather", get_weather)
diff --git a/examples/foundational/14c-function-calling-together.py b/examples/foundational/14c-function-calling-together.py
index 7f47eb28e..94d587799 100644
--- a/examples/foundational/14c-function-calling-together.py
+++ b/examples/foundational/14c-function-calling-together.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,16 +54,16 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = TogetherLLMService(
api_key=os.getenv("TOGETHER_API_KEY"),
model="meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
)
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14d-function-calling-video.py b/examples/foundational/14d-function-calling-video.py
index 15344b7ac..a7e997f9b 100644
--- a/examples/foundational/14d-function-calling-video.py
+++ b/examples/foundational/14d-function-calling-video.py
@@ -39,7 +39,12 @@ async def get_weather(function_name, tool_call_id, arguments, llm, context, resu
async def get_image(function_name, tool_call_id, arguments, llm, context, result_callback):
logger.debug(f"!!! IN get_image {video_participant_id}, {arguments}")
question = arguments["question"]
- await llm.request_image_frame(user_id=video_participant_id, text_content=question)
+ await llm.request_image_frame(
+ user_id=video_participant_id,
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ text_content=question,
+ )
async def main():
@@ -60,7 +65,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
@@ -141,7 +146,7 @@ indicate you should use the get_image tool are:
await transport.capture_participant_transcription(participant["id"])
await transport.capture_participant_video(video_participant_id, framerate=0)
# Kick off the conversation.
- await tts.say("Hi! Ask me about the weather in San Francisco.")
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
runner = PipelineRunner()
diff --git a/examples/foundational/14e-function-calling-gemini.py b/examples/foundational/14e-function-calling-gemini.py
index 146ed77d7..8448643b4 100644
--- a/examples/foundational/14e-function-calling-gemini.py
+++ b/examples/foundational/14e-function-calling-gemini.py
@@ -33,13 +33,8 @@ logger.add(sys.stderr, level="DEBUG")
video_participant_id = None
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def get_weather(function_name, tool_call_id, arguments, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
location = arguments["location"]
await result_callback(f"The weather in {location} is currently 72 degrees and sunny.")
@@ -47,7 +42,12 @@ async def get_weather(function_name, tool_call_id, arguments, llm, context, resu
async def get_image(function_name, tool_call_id, arguments, llm, context, result_callback):
logger.debug(f"!!! IN get_image {video_participant_id}, {arguments}")
question = arguments["question"]
- await llm.request_image_frame(user_id=video_participant_id, text_content=question)
+ await llm.request_image_frame(
+ user_id=video_participant_id,
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ text_content=question,
+ )
async def main():
@@ -68,11 +68,11 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = GoogleLLMService(api_key=os.getenv("GOOGLE_API_KEY"), model="gemini-2.0-flash-001")
- llm.register_function("get_weather", get_weather, start_fetch_weather)
+ llm.register_function("get_weather", get_weather)
llm.register_function("get_image", get_image)
weather_function = FunctionSchema(
diff --git a/examples/foundational/14f-function-calling-groq.py b/examples/foundational/14f-function-calling-groq.py
index 5bbddcc4d..9818d185f 100644
--- a/examples/foundational/14f-function-calling-groq.py
+++ b/examples/foundational/14f-function-calling-groq.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -61,13 +56,13 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = GroqLLMService(api_key=os.getenv("GROQ_API_KEY"), model="llama-3.3-70b-versatile")
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14g-function-calling-grok.py b/examples/foundational/14g-function-calling-grok.py
index 423919772..e5bb2f9b3 100644
--- a/examples/foundational/14g-function-calling-grok.py
+++ b/examples/foundational/14g-function-calling-grok.py
@@ -16,7 +16,6 @@ from runner import configure
from pipecat.adapters.schemas.function_schema import FunctionSchema
from pipecat.adapters.schemas.tools_schema import ToolsSchema
from pipecat.audio.vad.silero import SileroVADAnalyzer
-from pipecat.frames.frames import TTSSpeakFrame
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.runner import PipelineRunner
from pipecat.pipeline.task import PipelineParams, PipelineTask
@@ -31,12 +30,6 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,13 +52,13 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = GrokLLMService(api_key=os.getenv("GROK_API_KEY"))
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14h-function-calling-azure.py b/examples/foundational/14h-function-calling-azure.py
index 669055a55..6c8465832 100644
--- a/examples/foundational/14h-function-calling-azure.py
+++ b/examples/foundational/14h-function-calling-azure.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,7 +54,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = AzureLLMService(
@@ -67,9 +62,9 @@ async def main():
endpoint=os.getenv("AZURE_CHATGPT_ENDPOINT"),
model=os.getenv("AZURE_CHATGPT_MODEL"),
)
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14i-function-calling-fireworks.py b/examples/foundational/14i-function-calling-fireworks.py
index 88168383f..887e734dd 100644
--- a/examples/foundational/14i-function-calling-fireworks.py
+++ b/examples/foundational/14i-function-calling-fireworks.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,16 +54,16 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = FireworksLLMService(
api_key=os.getenv("FIREWORKS_API_KEY"),
- model="accounts/fireworks/models/firefunction-v2",
+ model="accounts/fireworks/models/llama-v3p1-405b-instruct",
)
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14j-function-calling-nim.py b/examples/foundational/14j-function-calling-nim.py
index 5d4b123d0..c628bedf0 100644
--- a/examples/foundational/14j-function-calling-nim.py
+++ b/examples/foundational/14j-function-calling-nim.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,16 +54,16 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
- # text_filter=MarkdownTextFilter(),
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
+ # text_filters=[MarkdownTextFilter()],
)
llm = NimLLMService(
api_key=os.getenv("NVIDIA_API_KEY"), model="meta/llama-3.3-70b-instruct"
)
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14k-function-calling-cerebras.py b/examples/foundational/14k-function-calling-cerebras.py
index b9f1c6b18..541e6f250 100644
--- a/examples/foundational/14k-function-calling-cerebras.py
+++ b/examples/foundational/14k-function-calling-cerebras.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,13 +54,13 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = CerebrasLLMService(api_key=os.getenv("CEREBRAS_API_KEY"), model="llama-3.3-70b")
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14l-function-calling-deepseek.py b/examples/foundational/14l-function-calling-deepseek.py
index 6add663d5..812a6716e 100644
--- a/examples/foundational/14l-function-calling-deepseek.py
+++ b/examples/foundational/14l-function-calling-deepseek.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -59,13 +54,13 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = DeepSeekLLMService(api_key=os.getenv("DEEPSEEK_API_KEY"), model="deepseek-chat")
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14m-function-calling-openrouter.py b/examples/foundational/14m-function-calling-openrouter.py
index e816f6322..a675c8ac4 100644
--- a/examples/foundational/14m-function-calling-openrouter.py
+++ b/examples/foundational/14m-function-calling-openrouter.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -67,9 +62,9 @@ async def main():
llm = OpenRouterLLMService(
api_key=os.getenv("OPENROUTER_API_KEY"), model="openai/gpt-4o-2024-11-20"
)
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14n-function-calling-perplexity.py b/examples/foundational/14n-function-calling-perplexity.py
index aee185f75..9d2439fb0 100644
--- a/examples/foundational/14n-function-calling-perplexity.py
+++ b/examples/foundational/14n-function-calling-perplexity.py
@@ -55,7 +55,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = PerplexityLLMService(api_key=os.getenv("PERPLEXITY_API_KEY"), model="sonar")
diff --git a/examples/foundational/14o-function-calling-gemini-openai-format.py b/examples/foundational/14o-function-calling-gemini-openai-format.py
index a1bb53b6b..78100f0d3 100644
--- a/examples/foundational/14o-function-calling-gemini-openai-format.py
+++ b/examples/foundational/14o-function-calling-gemini-openai-format.py
@@ -31,13 +31,8 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -63,11 +58,9 @@ async def main():
)
llm = GoogleLLMOpenAIBetaService(api_key=os.getenv("GEMINI_API_KEY"))
- # Register a function_name of None to get all functions
+ # You can aslo register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(
- "get_current_weather", fetch_weather_from_api, start_callback=start_fetch_weather
- )
+ llm.register_function("get_current_weather", fetch_weather_from_api)
weather_function = FunctionSchema(
name="get_current_weather",
diff --git a/examples/foundational/14p-function-calling-gemini-vertex-ai.py b/examples/foundational/14p-function-calling-gemini-vertex-ai.py
new file mode 100644
index 000000000..8888a2922
--- /dev/null
+++ b/examples/foundational/14p-function-calling-gemini-vertex-ai.py
@@ -0,0 +1,130 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from runner import configure
+
+from pipecat.adapters.schemas.function_schema import FunctionSchema
+from pipecat.adapters.schemas.tools_schema import ToolsSchema
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.frames.frames import TTSSpeakFrame
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.services.elevenlabs import ElevenLabsTTSService
+from pipecat.services.google import GoogleVertexLLMService
+from pipecat.services.openai import OpenAILLMContext
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+
+async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
+ await result_callback({"conditions": "nice", "temperature": "75"})
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Respond bot",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ ),
+ )
+
+ tts = ElevenLabsTTSService(
+ api_key=os.getenv("ELEVENLABS_API_KEY", ""),
+ voice_id=os.getenv("ELEVENLABS_VOICE_ID", ""),
+ )
+
+ llm = GoogleVertexLLMService(
+ # credentials="",
+ params=GoogleVertexLLMService.InputParams(
+ project_id="",
+ )
+ )
+ # You can aslo register a function_name of None to get all functions
+ # sent to the same callback with an additional function_name parameter.
+ llm.register_function("get_current_weather", fetch_weather_from_api)
+
+ weather_function = FunctionSchema(
+ name="get_current_weather",
+ description="Get the current weather",
+ properties={
+ "location": {
+ "type": "string",
+ "description": "The city and state, e.g. San Francisco, CA",
+ },
+ "format": {
+ "type": "string",
+ "enum": ["celsius", "fahrenheit"],
+ "description": "The temperature unit to use. Infer this from the user's location.",
+ },
+ },
+ required=["location", "format"],
+ )
+ tools = ToolsSchema(standard_tools=[weather_function])
+
+ messages = [
+ {
+ "role": "user",
+ "content": "Start a conversation with 'Hey there' to get the current weather.",
+ },
+ ]
+
+ context = OpenAILLMContext(messages, tools)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(),
+ context_aggregator.user(),
+ llm,
+ tts,
+ transport.output(),
+ context_aggregator.assistant(),
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ await transport.capture_participant_transcription(participant["id"])
+ # Kick off the conversation.
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/15-switch-voices.py b/examples/foundational/15-switch-voices.py
index 49280449f..15bd2f954 100644
--- a/examples/foundational/15-switch-voices.py
+++ b/examples/foundational/15-switch-voices.py
@@ -78,7 +78,7 @@ async def main():
british_lady = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
barbershop_man = CartesiaTTSService(
@@ -125,7 +125,10 @@ async def main():
llm, # LLM
ParallelPipeline( # TTS (one of the following vocies)
[FunctionFilter(news_lady_filter), news_lady], # News Lady voice
- [FunctionFilter(british_lady_filter), british_lady], # British Lady voice
+ [
+ FunctionFilter(british_lady_filter),
+ british_lady,
+ ], # British Reading Lady voice
[FunctionFilter(barbershop_man_filter), barbershop_man], # Barbershop Man voice
),
transport.output(), # Transport bot output
diff --git a/examples/foundational/15a-switch-languages.py b/examples/foundational/15a-switch-languages.py
index 217502ea2..4e05efcb0 100644
--- a/examples/foundational/15a-switch-languages.py
+++ b/examples/foundational/15a-switch-languages.py
@@ -71,7 +71,7 @@ async def main():
english_tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
spanish_tts = CartesiaTTSService(
diff --git a/examples/foundational/17-detect-user-idle.py b/examples/foundational/17-detect-user-idle.py
index 00c969df4..0a41f9d84 100644
--- a/examples/foundational/17-detect-user-idle.py
+++ b/examples/foundational/17-detect-user-idle.py
@@ -48,7 +48,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/19-openai-realtime-beta.py b/examples/foundational/19-openai-realtime-beta.py
index 504f8fbf1..3aff14e65 100644
--- a/examples/foundational/19-openai-realtime-beta.py
+++ b/examples/foundational/19-openai-realtime-beta.py
@@ -14,6 +14,8 @@ from dotenv import load_dotenv
from loguru import logger
from runner import configure
+from pipecat.adapters.schemas.function_schema import FunctionSchema
+from pipecat.adapters.schemas.tools_schema import ToolsSchema
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.audio.vad.vad_analyzer import VADParams
from pipecat.pipeline.pipeline import Pipeline
@@ -21,10 +23,11 @@ from pipecat.pipeline.runner import PipelineRunner
from pipecat.pipeline.task import PipelineParams, PipelineTask
from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
from pipecat.services.openai_realtime_beta import (
+ InputAudioNoiseReduction,
InputAudioTranscription,
OpenAIRealtimeBetaLLMService,
+ SemanticTurnDetection,
SessionProperties,
- TurnDetection,
)
from pipecat.transports.services.daily import DailyParams, DailyTransport
@@ -46,28 +49,25 @@ async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context
)
-tools = [
- {
- "type": "function",
- "name": "get_current_weather",
- "description": "Get the current weather",
- "parameters": {
- "type": "object",
- "properties": {
- "location": {
- "type": "string",
- "description": "The city and state, e.g. San Francisco, CA",
- },
- "format": {
- "type": "string",
- "enum": ["celsius", "fahrenheit"],
- "description": "The temperature unit to use. Infer this from the users location.",
- },
- },
- "required": ["location", "format"],
+weather_function = FunctionSchema(
+ name="get_current_weather",
+ description="Get the current weather",
+ properties={
+ "location": {
+ "type": "string",
+ "description": "The city and state, e.g. San Francisco, CA",
},
- }
-]
+ "format": {
+ "type": "string",
+ "enum": ["celsius", "fahrenheit"],
+ "description": "The temperature unit to use. Infer this from the users location.",
+ },
+ },
+ required=["location", "format"],
+)
+
+# Create tools schema
+tools = ToolsSchema(standard_tools=[weather_function])
async def main():
@@ -92,9 +92,10 @@ async def main():
input_audio_transcription=InputAudioTranscription(),
# Set openai TurnDetection parameters. Not setting this at all will turn it
# on by default
- turn_detection=TurnDetection(silence_duration_ms=1000),
+ turn_detection=SemanticTurnDetection(),
# Or set to False to disable openai turn detection and use transport VAD
# turn_detection=False,
+ input_audio_noise_reduction=InputAudioNoiseReduction(type="near_field"),
# tools=tools,
instructions="""Your knowledge cutoff is 2023-10. You are a helpful and friendly AI.
@@ -147,8 +148,8 @@ Remember, your responses should be short. Just one or two sentences, usually."""
transport.input(), # Transport user input
context_aggregator.user(),
llm, # LLM
- context_aggregator.assistant(),
transport.output(), # Transport bot output
+ context_aggregator.assistant(),
]
)
diff --git a/examples/foundational/19a-azure-realtime-beta.py b/examples/foundational/19a-azure-realtime-beta.py
index 14d034836..2eefd4ec9 100644
--- a/examples/foundational/19a-azure-realtime-beta.py
+++ b/examples/foundational/19a-azure-realtime-beta.py
@@ -10,11 +10,12 @@ import sys
from datetime import datetime
import aiohttp
-import websockets
from dotenv import load_dotenv
from loguru import logger
from runner import configure
+from pipecat.adapters.schemas.function_schema import FunctionSchema
+from pipecat.adapters.schemas.tools_schema import ToolsSchema
from pipecat.audio.vad.silero import SileroVADAnalyzer
from pipecat.audio.vad.vad_analyzer import VADParams
from pipecat.pipeline.pipeline import Pipeline
@@ -25,7 +26,6 @@ from pipecat.services.openai_realtime_beta import (
AzureRealtimeBetaLLMService,
InputAudioTranscription,
SessionProperties,
- TurnDetection,
)
from pipecat.transports.services.daily import DailyParams, DailyTransport
@@ -47,28 +47,26 @@ async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context
)
-tools = [
- {
- "type": "function",
- "name": "get_current_weather",
- "description": "Get the current weather",
- "parameters": {
- "type": "object",
- "properties": {
- "location": {
- "type": "string",
- "description": "The city and state, e.g. San Francisco, CA",
- },
- "format": {
- "type": "string",
- "enum": ["celsius", "fahrenheit"],
- "description": "The temperature unit to use. Infer this from the users location.",
- },
- },
- "required": ["location", "format"],
+# Define weather function using standardized schema
+weather_function = FunctionSchema(
+ name="get_current_weather",
+ description="Get the current weather",
+ properties={
+ "location": {
+ "type": "string",
+ "description": "The city and state, e.g. San Francisco, CA",
},
- }
-]
+ "format": {
+ "type": "string",
+ "enum": ["celsius", "fahrenheit"],
+ "description": "The temperature unit to use. Infer this from the users location.",
+ },
+ },
+ required=["location", "format"],
+)
+
+# Create tools schema
+tools = ToolsSchema(standard_tools=[weather_function])
async def main():
diff --git a/examples/foundational/20a-persistent-context-openai.py b/examples/foundational/20a-persistent-context-openai.py
index 8da683a47..0be0536cd 100644
--- a/examples/foundational/20a-persistent-context-openai.py
+++ b/examples/foundational/20a-persistent-context-openai.py
@@ -184,7 +184,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/20c-persistent-context-anthropic.py b/examples/foundational/20c-persistent-context-anthropic.py
index 64829450d..65d45c3d6 100644
--- a/examples/foundational/20c-persistent-context-anthropic.py
+++ b/examples/foundational/20c-persistent-context-anthropic.py
@@ -179,7 +179,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = AnthropicLLMService(
diff --git a/examples/foundational/20d-persistent-context-gemini.py b/examples/foundational/20d-persistent-context-gemini.py
index 74c4e69be..2381ea131 100644
--- a/examples/foundational/20d-persistent-context-gemini.py
+++ b/examples/foundational/20d-persistent-context-gemini.py
@@ -54,7 +54,12 @@ async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context
async def get_image(function_name, tool_call_id, arguments, llm, context, result_callback):
question = arguments["question"]
- await llm.request_image_frame(user_id=video_participant_id, text_content=question)
+ await llm.request_image_frame(
+ user_id=video_participant_id,
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ text_content=question,
+ )
async def get_saved_conversation_filenames(
@@ -234,7 +239,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = GoogleLLMService(model="gemini-2.0-flash-001", api_key=os.getenv("GOOGLE_API_KEY"))
diff --git a/examples/foundational/22-natural-conversation.py b/examples/foundational/22-natural-conversation.py
index 9282f4e4b..d1f84bb90 100644
--- a/examples/foundational/22-natural-conversation.py
+++ b/examples/foundational/22-natural-conversation.py
@@ -56,7 +56,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
# This is the LLM that will be used to detect if the user has finished a
diff --git a/examples/foundational/22b-natural-conversation-proposal.py b/examples/foundational/22b-natural-conversation-proposal.py
index 1eb2dd956..d7f7eb597 100644
--- a/examples/foundational/22b-natural-conversation-proposal.py
+++ b/examples/foundational/22b-natural-conversation-proposal.py
@@ -199,13 +199,8 @@ class OutputGate(FrameProcessor):
break
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -229,7 +224,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
# This is the LLM that will be used to detect if the user has finished a
@@ -239,9 +234,9 @@ async def main():
# This is the regular LLM.
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
- # Register a function_name of None to get all functions
+ # You can also register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
tools = [
ChatCompletionToolParam(
diff --git a/examples/foundational/22c-natural-conversation-mixed-llms.py b/examples/foundational/22c-natural-conversation-mixed-llms.py
index 362c7554d..7fa1bb5fa 100644
--- a/examples/foundational/22c-natural-conversation-mixed-llms.py
+++ b/examples/foundational/22c-natural-conversation-mixed-llms.py
@@ -403,13 +403,8 @@ class OutputGate(FrameProcessor):
break
-async def start_fetch_weather(function_name, llm, context):
- """Push a frame to the LLM; this is handy when the LLM response might take a while."""
- await llm.push_frame(TTSSpeakFrame("Let me check on that."))
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
+ await llm.push_frame(TTSSpeakFrame("Let me check on that."))
await result_callback({"conditions": "nice", "temperature": "75"})
@@ -433,7 +428,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
# This is the LLM that will be used to detect if the user has finished a
@@ -451,7 +446,7 @@ async def main():
)
# Register a function_name of None to get all functions
# sent to the same callback with an additional function_name parameter.
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
tools = [
ChatCompletionToolParam(
diff --git a/examples/foundational/22d-natural-conversation-gemini-audio.py b/examples/foundational/22d-natural-conversation-gemini-audio.py
index 0041ff530..9e3b8c9a3 100644
--- a/examples/foundational/22d-natural-conversation-gemini-audio.py
+++ b/examples/foundational/22d-natural-conversation-gemini-audio.py
@@ -644,7 +644,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
# This is the LLM that will transcribe user speech.
diff --git a/examples/foundational/23-bot-background-sound.py b/examples/foundational/23-bot-background-sound.py
index 1b443190d..92d6cdc42 100644
--- a/examples/foundational/23-bot-background-sound.py
+++ b/examples/foundational/23-bot-background-sound.py
@@ -59,7 +59,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/24-stt-mute-filter.py b/examples/foundational/24-stt-mute-filter.py
index 7ae6c73fa..d2b7174d1 100644
--- a/examples/foundational/24-stt-mute-filter.py
+++ b/examples/foundational/24-stt-mute-filter.py
@@ -30,10 +30,6 @@ logger.remove(0)
logger.add(sys.stderr, level="DEBUG")
-async def start_fetch_weather(function_name, llm, context):
- logger.debug(f"Starting fetch_weather_from_api with function_name: {function_name}")
-
-
async def fetch_weather_from_api(function_name, tool_call_id, args, llm, context, result_callback):
# Add a delay to test interruption during function calls
logger.info("Weather API call starting...")
@@ -72,7 +68,7 @@ async def main():
tts = DeepgramTTSService(api_key=os.getenv("DEEPGRAM_API_KEY"), voice="aura-helios-en")
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
- llm.register_function(None, fetch_weather_from_api, start_callback=start_fetch_weather)
+ llm.register_function("get_current_weather", fetch_weather_from_api)
tools = [
ChatCompletionToolParam(
diff --git a/examples/foundational/25-google-audio-in.py b/examples/foundational/25-google-audio-in.py
index e3ff21d95..830cfb769 100644
--- a/examples/foundational/25-google-audio-in.py
+++ b/examples/foundational/25-google-audio-in.py
@@ -294,7 +294,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
conversation_llm = GoogleLLMService(
diff --git a/examples/foundational/26-gemini-multimodal-live.py b/examples/foundational/26-gemini-multimodal-live.py
index 71d41304b..c26d6ad2f 100644
--- a/examples/foundational/26-gemini-multimodal-live.py
+++ b/examples/foundational/26-gemini-multimodal-live.py
@@ -77,7 +77,7 @@ async def main():
LLMMessagesAppendFrame(
messages=[
{
- "role": "assistant",
+ "role": "user",
"content": "Greet the user.",
}
]
diff --git a/examples/foundational/26d-gemini-multimodal-live-text.py b/examples/foundational/26d-gemini-multimodal-live-text.py
index 2e0e27a13..147b882eb 100644
--- a/examples/foundational/26d-gemini-multimodal-live-text.py
+++ b/examples/foundational/26d-gemini-multimodal-live-text.py
@@ -78,7 +78,7 @@ async def main():
# )
tts = CartesiaTTSService(
- api_key=os.getenv("CARTESIA_API_KEY"), voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22"
+ api_key=os.getenv("CARTESIA_API_KEY"), voice_id="71a7ad14-091c-4e8e-a314-022ece01c121"
)
messages = [
diff --git a/examples/foundational/28a-transcription-processor-openai.py b/examples/foundational/28-transcription-processor.py
similarity index 98%
rename from examples/foundational/28a-transcription-processor-openai.py
rename to examples/foundational/28-transcription-processor.py
index f341cc0dd..a3707e347 100644
--- a/examples/foundational/28a-transcription-processor-openai.py
+++ b/examples/foundational/28-transcription-processor.py
@@ -113,7 +113,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(
diff --git a/examples/foundational/28b-transcript-processor-anthropic.py b/examples/foundational/28b-transcript-processor-anthropic.py
deleted file mode 100644
index 05956fdf7..000000000
--- a/examples/foundational/28b-transcript-processor-anthropic.py
+++ /dev/null
@@ -1,177 +0,0 @@
-#
-# Copyright (c) 2024–2025, Daily
-#
-# SPDX-License-Identifier: BSD 2-Clause License
-#
-
-import asyncio
-import os
-import sys
-from typing import List, Optional
-
-import aiohttp
-from dotenv import load_dotenv
-from loguru import logger
-from runner import configure
-
-from pipecat.audio.vad.silero import SileroVADAnalyzer
-from pipecat.frames.frames import TranscriptionMessage, TranscriptionUpdateFrame
-from pipecat.pipeline.pipeline import Pipeline
-from pipecat.pipeline.runner import PipelineRunner
-from pipecat.pipeline.task import PipelineParams, PipelineTask
-from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
-from pipecat.processors.transcript_processor import TranscriptProcessor
-from pipecat.services.anthropic import AnthropicLLMService
-from pipecat.services.cartesia import CartesiaTTSService
-from pipecat.services.deepgram import DeepgramSTTService
-from pipecat.transports.services.daily import DailyParams, DailyTransport
-
-load_dotenv(override=True)
-
-logger.remove(0)
-logger.add(sys.stderr, level="DEBUG")
-
-
-class TranscriptHandler:
- """Handles real-time transcript processing and output.
-
- Maintains a list of conversation messages and outputs them either to a log
- or to a file as they are received. Each message includes its timestamp and role.
-
- Attributes:
- messages: List of all processed transcript messages
- output_file: Optional path to file where transcript is saved. If None, outputs to log only.
- """
-
- def __init__(self, output_file: Optional[str] = None):
- """Initialize handler with optional file output.
-
- Args:
- output_file: Path to output file. If None, outputs to log only.
- """
- self.messages: List[TranscriptionMessage] = []
- self.output_file: Optional[str] = output_file
- logger.debug(
- f"TranscriptHandler initialized {'with output_file=' + output_file if output_file else 'with log output only'}"
- )
-
- async def save_message(self, message: TranscriptionMessage):
- """Save a single transcript message.
-
- Outputs the message to the log and optionally to a file.
-
- Args:
- message: The message to save
- """
- timestamp = f"[{message.timestamp}] " if message.timestamp else ""
- line = f"{timestamp}{message.role}: {message.content}"
-
- # Always log the message
- logger.info(f"Transcript: {line}")
-
- # Optionally write to file
- if self.output_file:
- try:
- with open(self.output_file, "a", encoding="utf-8") as f:
- f.write(line + "\n")
- except Exception as e:
- logger.error(f"Error saving transcript message to file: {e}")
-
- async def on_transcript_update(
- self, processor: TranscriptProcessor, frame: TranscriptionUpdateFrame
- ):
- """Handle new transcript messages.
-
- Args:
- processor: The TranscriptProcessor that emitted the update
- frame: TranscriptionUpdateFrame containing new messages
- """
- logger.debug(f"Received transcript update with {len(frame.messages)} new messages")
-
- for msg in frame.messages:
- self.messages.append(msg)
- await self.save_message(msg)
-
-
-async def main():
- async with aiohttp.ClientSession() as session:
- (room_url, token) = await configure(session)
-
- transport = DailyTransport(
- room_url,
- None,
- "Respond bot",
- DailyParams(
- audio_out_enabled=True,
- vad_enabled=True,
- vad_analyzer=SileroVADAnalyzer(),
- vad_audio_passthrough=True,
- ),
- )
-
- stt = DeepgramSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"))
-
- tts = CartesiaTTSService(
- api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
- )
-
- llm = AnthropicLLMService(
- api_key=os.getenv("ANTHROPIC_API_KEY"), model="claude-3-5-sonnet-20241022"
- )
-
- messages = [
- {
- "role": "system",
- "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative, helpful, and brief way.",
- },
- {"role": "user", "content": "Say hello."},
- ]
-
- context = OpenAILLMContext(messages)
- context_aggregator = llm.create_context_aggregator(context)
-
- # Create transcript processor and handler
- transcript = TranscriptProcessor()
- transcript_handler = TranscriptHandler() # Output to log only
- # transcript_handler = TranscriptHandler(output_file="transcript.txt") # Output to file and log
-
- pipeline = Pipeline(
- [
- transport.input(), # Transport user input
- stt, # STT
- transcript.user(), # User transcripts
- context_aggregator.user(), # User responses
- llm, # LLM
- tts, # TTS
- transport.output(), # Transport bot output
- transcript.assistant(), # Assistant transcripts
- context_aggregator.assistant(), # Assistant spoken responses
- ]
- )
-
- task = PipelineTask(pipeline, params=PipelineParams(allow_interruptions=True))
-
- @transport.event_handler("on_first_participant_joined")
- async def on_first_participant_joined(transport, participant):
- await transport.capture_participant_transcription(participant["id"])
- # Kick off the conversation.
- await task.queue_frames([context_aggregator.user().get_context_frame()])
-
- # Register event handler for transcript updates
- @transcript.event_handler("on_transcript_update")
- async def on_transcript_update(processor, frame):
- await transcript_handler.on_transcript_update(processor, frame)
-
- @transport.event_handler("on_participant_left")
- async def on_participant_left(transport, participant, reason):
- # Stop the pipeline immediately when the participant leaves
- await task.cancel()
-
- runner = PipelineRunner()
-
- await runner.run(task)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/foundational/28c-transcription-processor-gemini.py b/examples/foundational/28c-transcription-processor-gemini.py
deleted file mode 100644
index 3760a227f..000000000
--- a/examples/foundational/28c-transcription-processor-gemini.py
+++ /dev/null
@@ -1,210 +0,0 @@
-#
-# Copyright (c) 2024–2025, Daily
-#
-# SPDX-License-Identifier: BSD 2-Clause License
-#
-
-import asyncio
-import os
-import sqlite3
-import sys
-from typing import List, Optional
-
-import aiohttp
-from dotenv import load_dotenv
-from loguru import logger
-from runner import configure
-
-from pipecat.audio.vad.silero import SileroVADAnalyzer
-from pipecat.frames.frames import TranscriptionMessage, TranscriptionUpdateFrame
-from pipecat.pipeline.pipeline import Pipeline
-from pipecat.pipeline.runner import PipelineRunner
-from pipecat.pipeline.task import PipelineParams, PipelineTask
-from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
-from pipecat.processors.transcript_processor import TranscriptProcessor
-from pipecat.services.cartesia import CartesiaTTSService
-from pipecat.services.deepgram import DeepgramSTTService
-from pipecat.services.google import GoogleLLMService
-from pipecat.services.openai import OpenAILLMContext
-from pipecat.transports.services.daily import DailyParams, DailyTransport
-
-load_dotenv(override=True)
-
-logger.remove(0)
-logger.add(sys.stderr, level="DEBUG")
-
-
-class TranscriptHandler:
- """Handles real-time transcript processing and output.
-
- Maintains a list of conversation messages and outputs them either to a log
- or to a file as they are received. Each message includes its timestamp and role.
-
- Attributes:
- messages: List of all processed transcript messages
- output_file: Optional path to file where transcript is saved. If None, outputs to log only.
- """
-
- def __init__(self, output_file: Optional[str] = None, output_db: Optional[str] = None):
- """Initialize handler with optional file or database output.
-
- Args:
- output_file: Path to output file. If None, outputs to log only.
- """
- self.messages: List[TranscriptionMessage] = []
- self.output_file: Optional[str] = output_file
- self.output_db: Optional[str] = output_db
-
- if self.output_db:
- self.con = sqlite3.connect("example.db")
- self.db = self.con.cursor()
-
- table = self.db.execute("SELECT name FROM sqlite_master WHERE name='messages'")
- if not (table.fetchone()):
- self.db.execute(
- "CREATE TABLE messages(role TEXT, content TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP )"
- )
- logger.debug(
- f"TranscriptHandler initialized; output file: {output_file}, output DB: {output_db}"
- )
-
- async def save_message(self, message: TranscriptionMessage):
- """Save a single transcript message.
-
- Outputs the message to the log and optionally to a SQLite database or file.
-
- Args:
- message: The message to save
- """
- timestamp = f"[{message.timestamp}] " if message.timestamp else ""
- line = f"{timestamp}{message.role}: {message.content}"
-
- # Always log the message
- logger.info(f"Transcript: {line}")
-
- # Optionally write to file
- if self.output_file:
- try:
- with open(self.output_file, "a", encoding="utf-8") as f:
- f.write(line + "\n")
- except Exception as e:
- logger.error(f"Error saving transcript message to file: {e}")
-
- # and/or to a SQLite database
- if self.output_db:
- self.db.execute(
- "INSERT INTO messages VALUES (?, ?, ?)",
- (message.role, message.content, message.timestamp),
- )
- self.con.commit()
-
- async def on_transcript_update(
- self, processor: TranscriptProcessor, frame: TranscriptionUpdateFrame
- ):
- """Handle new transcript messages.
-
- Args:
- processor: The TranscriptProcessor that emitted the update
- frame: TranscriptionUpdateFrame containing new messages
- """
- logger.debug(f"Received transcript update with {len(frame.messages)} new messages")
-
- for msg in frame.messages:
- self.messages.append(msg)
- await self.save_message(msg)
-
-
-async def main():
- async with aiohttp.ClientSession() as session:
- (room_url, token) = await configure(session)
-
- transport = DailyTransport(
- room_url,
- None,
- "Respond bot",
- DailyParams(
- audio_out_enabled=True,
- vad_enabled=True,
- vad_analyzer=SileroVADAnalyzer(),
- vad_audio_passthrough=True,
- ),
- )
-
- stt = DeepgramSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"))
-
- tts = CartesiaTTSService(
- api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
- )
-
- llm = GoogleLLMService(
- model="models/gemini-2.0-flash-exp",
- # model="gemini-exp-1114",
- api_key=os.getenv("GOOGLE_API_KEY"),
- )
-
- messages = [
- {
- "role": "system",
- "content": "You are a helpful LLM in a WebRTC call. Your goal is to demonstrate your capabilities in a succinct way. Your output will be converted to audio so don't include special characters in your answers. Respond to what the user said in a creative, helpful, and brief way.",
- },
- {"role": "user", "content": "Say hello."},
- ]
-
- context = OpenAILLMContext(messages)
- context_aggregator = llm.create_context_aggregator(context)
-
- # Create transcript processor and handler
- transcript = TranscriptProcessor()
- # Select a TranscriptHandler output method
- # Uncomment out only one of the following lines:
- transcript_handler = TranscriptHandler() # Output to log only
- # transcript_handler = TranscriptHandler(output_file="transcript.txt") # Output to file and log
- # transcript_handler = TranscriptHandler(output_db="example.db") # Output to SQLite DB and log
-
- pipeline = Pipeline(
- [
- transport.input(), # Transport user input
- stt, # STT
- transcript.user(), # User transcripts
- context_aggregator.user(), # User responses
- llm, # LLM
- tts, # TTS
- transport.output(), # Transport bot output
- transcript.assistant(), # Assistant transcripts
- context_aggregator.assistant(), # Assistant spoken responses
- ]
- )
-
- task = PipelineTask(
- pipeline,
- params=PipelineParams(
- allow_interruptions=True,
- enable_metrics=True,
- enable_usage_metrics=True,
- ),
- )
-
- @transport.event_handler("on_first_participant_joined")
- async def on_first_participant_joined(transport, participant):
- await transport.capture_participant_transcription(participant["id"])
- # Kick off the conversation.
- await task.queue_frames([context_aggregator.user().get_context_frame()])
-
- # Register event handler for transcript updates
- @transcript.event_handler("on_transcript_update")
- async def on_transcript_update(processor, frame):
- await transcript_handler.on_transcript_update(processor, frame)
-
- @transport.event_handler("on_participant_left")
- async def on_participant_left(transport, participant, reason):
- # Stop the pipeline immediately when the participant leaves
- await task.cancel()
-
- runner = PipelineRunner()
-
- await runner.run(task)
-
-
-if __name__ == "__main__":
- asyncio.run(main())
diff --git a/examples/foundational/29-livekit-audio-chat.py b/examples/foundational/29-livekit-audio-chat.py
index 2ad02c296..e5afb5ffb 100644
--- a/examples/foundational/29-livekit-audio-chat.py
+++ b/examples/foundational/29-livekit-audio-chat.py
@@ -131,7 +131,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
messages = [
diff --git a/examples/foundational/30-observer.py b/examples/foundational/30-observer.py
index 49885d82c..129407628 100644
--- a/examples/foundational/30-observer.py
+++ b/examples/foundational/30-observer.py
@@ -89,7 +89,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/foundational/32-gemini-grounding-metadata.py b/examples/foundational/32-gemini-grounding-metadata.py
index 516549694..5f0a497a5 100644
--- a/examples/foundational/32-gemini-grounding-metadata.py
+++ b/examples/foundational/32-gemini-grounding-metadata.py
@@ -81,7 +81,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
# Initialize the Gemini Multimodal Live model
diff --git a/examples/foundational/34-audio-recording.py b/examples/foundational/34-audio-recording.py
index 1d0431b83..24f009570 100644
--- a/examples/foundational/34-audio-recording.py
+++ b/examples/foundational/34-audio-recording.py
@@ -32,6 +32,7 @@ Requirements:
OPENAI_API_KEY=your_openai_key
CARTESIA_API_KEY=your_cartesia_key
DAILY_API_KEY=your_daily_key
+ DEEPGRAM_API_KEY=your_deepgram_key
The recordings will be saved in a 'recordings' directory with timestamps:
recordings/
@@ -65,6 +66,7 @@ from pipecat.pipeline.task import PipelineParams, PipelineTask
from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
from pipecat.processors.audio.audio_buffer_processor import AudioBufferProcessor
from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.deepgram import DeepgramSTTService
from pipecat.services.openai import OpenAILLMService
from pipecat.transports.services.daily import DailyParams, DailyTransport
@@ -98,16 +100,17 @@ async def main():
DailyParams(
# audio_in_enabled=True,
audio_out_enabled=True,
- transcription_enabled=True,
vad_enabled=True,
vad_analyzer=SileroVADAnalyzer(),
- vad_audio_passthrough=True, # Enable audio passthrough for recording
+ vad_audio_passthrough=True,
),
)
+ stt = DeepgramSTTService(api_key=os.getenv("DEEPGRAM_API_KEY"), audio_passthrough=True)
+
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22",
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121",
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4")
@@ -128,6 +131,7 @@ async def main():
pipeline = Pipeline(
[
transport.input(),
+ stt,
context_aggregator.user(),
llm,
tts,
diff --git a/examples/foundational/35-pattern-pair-voice-switching.py b/examples/foundational/35-pattern-pair-voice-switching.py
new file mode 100644
index 000000000..bb9587706
--- /dev/null
+++ b/examples/foundational/35-pattern-pair-voice-switching.py
@@ -0,0 +1,230 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+"""Pattern Pair Voice Switching Example with Pipecat.
+
+This example demonstrates how to use the PatternPairAggregator to dynamically switch
+between different voices in a storytelling application. It showcases how pattern matching
+can be used to control TTS behavior in streaming text from an LLM.
+
+The example:
+ 1. Sets up a storytelling bot with three distinct voices (narrator, male, female)
+ 2. Uses pattern pairs (name) to trigger voice switching
+ 3. Processes the patterns in real-time as text streams from the LLM
+ 4. Removes the pattern tags before sending text to TTS
+
+The PatternPairAggregator:
+ - Buffers text until complete patterns are detected
+ - Identifies content between start/end pattern pairs
+ - Triggers callbacks when patterns are matched
+ - Processes patterns that may span across multiple text chunks
+ - Returns processed text at sentence boundaries
+
+Example usage (run from pipecat root directory):
+ $ pip install "pipecat-ai[daily,openai,cartesia,silero]"
+ $ pip install -r dev-requirements.txt
+ $ python examples/foundational/35-pattern-pair-voice-switching.py
+
+Requirements:
+ - OpenAI API key (for GPT-4o)
+ - Cartesia API key (for text-to-speech)
+ - Daily API key (for video/audio transport)
+
+ Environment variables (.env file):
+ OPENAI_API_KEY=your_openai_key
+ CARTESIA_API_KEY=your_cartesia_key
+ DAILY_API_KEY=your_daily_key
+
+Note:
+ This example shows one application of PatternPairAggregator (voice switching),
+ but the same approach can be used for various pattern-based text processing needs,
+ such as formatting instructions, command recognition, or structured data extraction.
+"""
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from runner import configure
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
+from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.openai import OpenAILLMService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+from pipecat.utils.text.pattern_pair_aggregator import PatternMatch, PatternPairAggregator
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+# Define voice IDs
+VOICE_IDS = {
+ "narrator": "c45bc5ec-dc68-4feb-8829-6e6b2748095d", # Narrator voice
+ "female": "71a7ad14-091c-4e8e-a314-022ece01c121", # Female character voice
+ "male": "7cf0e2b1-8daf-4fe4-89ad-f6039398f359", # Male character voice
+}
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Multi-voice storyteller",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ ),
+ )
+
+ # Create pattern pair aggregator for voice switching
+ pattern_aggregator = PatternPairAggregator()
+
+ # Add pattern for voice switching
+ pattern_aggregator.add_pattern_pair(
+ pattern_id="voice_tag",
+ start_pattern="",
+ end_pattern="",
+ remove_match=True,
+ )
+
+ # Register handler for voice switching
+ def on_voice_tag(match: PatternMatch):
+ voice_name = match.content.strip().lower()
+ if voice_name in VOICE_IDS:
+ voice_id = VOICE_IDS[voice_name]
+ tts.set_voice(voice_id)
+ logger.info(f"Switched to {voice_name} voice")
+ else:
+ logger.warning(f"Unknown voice: {voice_name}")
+
+ pattern_aggregator.on_pattern_match("voice_tag", on_voice_tag)
+
+ # Initialize TTS with narrator voice as default
+ tts = CartesiaTTSService(
+ api_key=os.getenv("CARTESIA_API_KEY"),
+ voice_id=VOICE_IDS["narrator"],
+ text_aggregator=pattern_aggregator,
+ )
+
+ # Initialize LLM
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+
+ # System prompt for storytelling with voice switching
+ system_prompt = """You are an engaging storyteller that uses different voices to bring stories to life.
+
+You have three voices to use, but each has a specific purpose:
+
+narrator
+This is the default narrator voice. Use this for all narration, descriptions, and non-dialogue text.
+
+female
+Use this ONLY for direct speech by female characters (just the quoted text).
+
+male
+Use this ONLY for direct speech by male characters (just the quoted text).
+
+IMPORTANT: Switch back to narrator voice immediately after character dialogue.
+
+Here's an EXAMPLE of correct voice usage:
+
+narrator
+Sarah spotted her old friend across the café. She couldn't believe her eyes.
+
+female
+"Jacob! It's been so long!"
+
+narrator
+Sarah exclaimed, jumping up from her seat with a radiant smile.
+
+male
+"Sarah, is it really you? I can't believe it!"
+
+narrator
+Jacob replied, grinning widely as he walked over to her. The two friends embraced warmly, as if trying to make up for all the years spent apart.
+
+female
+"What are you doing in town? Last I heard you were in Seattle."
+
+narrator
+She asked, gesturing for him to join her at the table.
+
+FOLLOW THESE RULES:
+1. Always begin with the narrator voice
+2. Only use character voices for the EXACT words they speak (in quotes)
+3. SWITCH BACK to narrator voice for speech tags and all other text
+4. Begin by asking what kind of story the user would like to hear
+5. Create engaging dialogue with distinct characters
+
+Remember: Use narrator voice for EVERYTHING except the actual quoted dialogue."""
+
+ # Set up LLM context
+ messages = [
+ {
+ "role": "system",
+ "content": system_prompt,
+ },
+ ]
+
+ context = OpenAILLMContext(messages)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ # Create pipeline
+ pipeline = Pipeline(
+ [
+ transport.input(),
+ context_aggregator.user(),
+ llm,
+ tts, # TTS with pattern aggregator
+ transport.output(),
+ context_aggregator.assistant(),
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ logger.info(f"First participant joined: {participant['id']}")
+ await transport.capture_participant_transcription(participant["id"])
+
+ # Start conversation - empty prompt to let LLM follow system instructions
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ @transport.event_handler("on_participant_left")
+ async def on_participant_left(transport, participant, reason):
+ logger.info(f"Participant left: {participant['id']}")
+ await task.cancel()
+
+ logger.info(f"Starting storytelling bot at: {room_url}")
+ logger.info("Join the room to interact with the bot!")
+
+ runner = PipelineRunner()
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/foundational/36-user-email-gathering.py b/examples/foundational/36-user-email-gathering.py
new file mode 100644
index 000000000..0e76826e3
--- /dev/null
+++ b/examples/foundational/36-user-email-gathering.py
@@ -0,0 +1,141 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import os
+import sys
+
+import aiohttp
+from dotenv import load_dotenv
+from loguru import logger
+from openai.types.chat import ChatCompletionToolParam
+from runner import configure
+
+from pipecat.audio.vad.silero import SileroVADAnalyzer
+from pipecat.pipeline.pipeline import Pipeline
+from pipecat.pipeline.runner import PipelineRunner
+from pipecat.pipeline.task import PipelineParams, PipelineTask
+from pipecat.services.cartesia import CartesiaTTSService
+from pipecat.services.openai import OpenAILLMContext, OpenAILLMService
+from pipecat.services.rime import RimeHttpTTSService
+from pipecat.transports.services.daily import DailyParams, DailyTransport
+
+load_dotenv(override=True)
+
+logger.remove(0)
+logger.add(sys.stderr, level="DEBUG")
+
+
+async def store_user_emails(function_name, tool_call_id, args, llm, context, result_callback):
+ print(f"User emails: {args}")
+
+
+async def main():
+ async with aiohttp.ClientSession() as session:
+ (room_url, token) = await configure(session)
+
+ transport = DailyTransport(
+ room_url,
+ token,
+ "Respond bot",
+ DailyParams(
+ audio_out_enabled=True,
+ transcription_enabled=True,
+ vad_enabled=True,
+ vad_analyzer=SileroVADAnalyzer(),
+ ),
+ )
+
+ # Cartesia offers a `` tags that we can use to ask the user
+ # to confirm the emails.
+ # (see https://docs.cartesia.ai/build-with-sonic/formatting-text-for-sonic/spelling-out-input-text)
+ tts = CartesiaTTSService(
+ api_key=os.getenv("CARTESIA_API_KEY"),
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
+ aiohttp_session=session,
+ )
+
+ # Rime offers a function `spell()` that we can use to ask the user
+ # to confirm the emails.
+ # (see https://docs.rime.ai/api-reference/spell)
+ # tts = RimeHttpTTSService(
+ # api_key=os.getenv("RIME_API_KEY", ""),
+ # voice_id="eva",
+ # aiohttp_session=session,
+ # )
+
+ llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
+ # You can aslo register a function_name of None to get all functions
+ # sent to the same callback with an additional function_name parameter.
+ llm.register_function("store_user_emails", store_user_emails)
+
+ tools = [
+ ChatCompletionToolParam(
+ type="function",
+ function={
+ "name": "store_user_emails",
+ "description": "Store user emails when confirmed",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "emails": {
+ "type": "array",
+ "description": "The list of user emails",
+ "items": {"type": "string"},
+ },
+ },
+ "required": ["emails"],
+ },
+ },
+ )
+ ]
+ messages = [
+ {
+ "role": "system",
+ # Cartesia
+ "content": "You need to gather a valid email or emails from the user. Your output will be converted to audio so don't include special characters in your answers. If the user provides one or more email addresses confirm them with the user. Enclose all emails with tags, for example a@a.com.",
+ # Rime spell()
+ # "content": "You need to gather a valid email or emails from the user. Your output will be converted to audio so don't include special characters in your answers. If the user provides one or more email addresses confirm them with the user. Enclose all emails with spell(), for example spell(a@a.com).",
+ },
+ ]
+
+ context = OpenAILLMContext(messages, tools)
+ context_aggregator = llm.create_context_aggregator(context)
+
+ pipeline = Pipeline(
+ [
+ transport.input(),
+ context_aggregator.user(),
+ llm,
+ tts,
+ transport.output(),
+ context_aggregator.assistant(),
+ ]
+ )
+
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ allow_interruptions=True,
+ enable_metrics=True,
+ enable_usage_metrics=True,
+ report_only_initial_ttfb=True,
+ ),
+ )
+
+ @transport.event_handler("on_first_participant_joined")
+ async def on_first_participant_joined(transport, participant):
+ await transport.capture_participant_transcription(participant["id"])
+ # Kick off the conversation.
+ await task.queue_frames([context_aggregator.user().get_context_frame()])
+
+ runner = PipelineRunner()
+
+ await runner.run(task)
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/examples/moondream-chatbot/bot.py b/examples/moondream-chatbot/bot.py
index 5fb86ac79..6639c08c1 100644
--- a/examples/moondream-chatbot/bot.py
+++ b/examples/moondream-chatbot/bot.py
@@ -23,7 +23,6 @@ from pipecat.frames.frames import (
OutputImageRawFrame,
SpriteFrame,
TextFrame,
- UserImageRawFrame,
UserImageRequestFrame,
)
from pipecat.pipeline.parallel_pipeline import ParallelPipeline
@@ -154,7 +153,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
llm = OpenAILLMService(api_key=os.getenv("OPENAI_API_KEY"), model="gpt-4o")
diff --git a/examples/news-chatbot/server/news_bot.py b/examples/news-chatbot/server/news_bot.py
index d1cde2f22..b9f60200f 100644
--- a/examples/news-chatbot/server/news_bot.py
+++ b/examples/news-chatbot/server/news_bot.py
@@ -96,8 +96,8 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
- text_filter=MarkdownTextFilter(),
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
+ text_filters=[MarkdownTextFilter()],
)
llm = GoogleLLMService(
diff --git a/examples/patient-intake/bot.py b/examples/patient-intake/bot.py
index 75279fce3..de6ad2051 100644
--- a/examples/patient-intake/bot.py
+++ b/examples/patient-intake/bot.py
@@ -142,7 +142,9 @@ class IntakeProcessor:
]
)
- async def start_prescriptions(self, function_name, llm, context):
+ async def list_prescriptions(
+ self, function_name, tool_call_id, args, llm, context, result_callback
+ ):
print(f"!!! doing start prescriptions")
# Move on to allergies
context.set_tools(
@@ -182,9 +184,12 @@ class IntakeProcessor:
print(f"!!! about to await llm process frame in start prescrpitions")
await llm.queue_frame(OpenAILLMContextFrame(context), FrameDirection.DOWNSTREAM)
print(f"!!! past await process frame in start prescriptions")
+ await self.save_data(args, result_callback)
- async def start_allergies(self, function_name, llm, context):
- print("!!! doing start allergies")
+ async def list_allergies(
+ self, function_name, tool_call_id, args, llm, context, result_callback
+ ):
+ print("!!! doing list allergies")
# Move on to conditions
context.set_tools(
[
@@ -221,8 +226,11 @@ class IntakeProcessor:
}
)
await llm.queue_frame(OpenAILLMContextFrame(context), FrameDirection.DOWNSTREAM)
+ await self.save_data(args, result_callback)
- async def start_conditions(self, function_name, llm, context):
+ async def list_conditions(
+ self, function_name, tool_call_id, args, llm, context, result_callback
+ ):
print("!!! doing start conditions")
# Move on to visit reasons
context.set_tools(
@@ -260,8 +268,11 @@ class IntakeProcessor:
}
)
await llm.queue_frame(OpenAILLMContextFrame(context), FrameDirection.DOWNSTREAM)
+ await self.save_data(args, result_callback)
- async def start_visit_reasons(self, function_name, llm, context):
+ async def list_visit_reasons(
+ self, function_name, tool_call_id, args, llm, context, result_callback
+ ):
print("!!! doing start visit reasons")
# move to finish call
context.set_tools([])
@@ -269,8 +280,9 @@ class IntakeProcessor:
{"role": "system", "content": "Now, thank the user and end the conversation."}
)
await llm.queue_frame(OpenAILLMContextFrame(context), FrameDirection.DOWNSTREAM)
+ await self.save_data(args, result_callback)
- async def save_data(self, function_name, tool_call_id, args, llm, context, result_callback):
+ async def save_data(self, args, result_callback):
logger.info(f"!!! Saving data: {args}")
# Since this is supposed to be "async", returning None from the callback
# will prevent adding anything to context or re-prompting
@@ -303,7 +315,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
# tts = CartesiaTTSService(
@@ -319,18 +331,10 @@ async def main():
intake = IntakeProcessor(context)
llm.register_function("verify_birthday", intake.verify_birthday)
- llm.register_function(
- "list_prescriptions", intake.save_data, start_callback=intake.start_prescriptions
- )
- llm.register_function(
- "list_allergies", intake.save_data, start_callback=intake.start_allergies
- )
- llm.register_function(
- "list_conditions", intake.save_data, start_callback=intake.start_conditions
- )
- llm.register_function(
- "list_visit_reasons", intake.save_data, start_callback=intake.start_visit_reasons
- )
+ llm.register_function("list_prescriptions", intake.list_prescriptions)
+ llm.register_function("list_allergies", intake.list_allergies)
+ llm.register_function("list_conditions", intake.list_conditions)
+ llm.register_function("list_visit_reasons", intake.list_visit_reasons)
fl = FrameLogger("LLM Output")
diff --git a/examples/telnyx-chatbot/bot.py b/examples/telnyx-chatbot/bot.py
index 8243e05a4..94f44e2b1 100644
--- a/examples/telnyx-chatbot/bot.py
+++ b/examples/telnyx-chatbot/bot.py
@@ -54,7 +54,7 @@ async def run_bot(
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
messages = [
diff --git a/examples/telnyx-chatbot/env.example b/examples/telnyx-chatbot/env.example
index 5de3bace2..1da398649 100644
--- a/examples/telnyx-chatbot/env.example
+++ b/examples/telnyx-chatbot/env.example
@@ -1,3 +1,3 @@
OPENAI_API_KEY=
DEEPGRAM_API_KEY=
-ELEVENLABS_API_KEY=
+CARTESIA_API_KEY=
diff --git a/examples/telnyx-chatbot/requirements.txt b/examples/telnyx-chatbot/requirements.txt
index 630a98dd6..e103e438d 100644
--- a/examples/telnyx-chatbot/requirements.txt
+++ b/examples/telnyx-chatbot/requirements.txt
@@ -1,4 +1,4 @@
-pipecat-ai[openai,silero,deepgram,elevenlabs]
+pipecat-ai[openai,silero,deepgram,cartesia]
fastapi
uvicorn
python-dotenv
diff --git a/examples/twilio-chatbot/bot.py b/examples/twilio-chatbot/bot.py
index afddc3fe9..7b05e6dfe 100644
--- a/examples/twilio-chatbot/bot.py
+++ b/examples/twilio-chatbot/bot.py
@@ -74,7 +74,7 @@ async def run_bot(websocket_client: WebSocket, stream_sid: str, testing: bool):
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
push_silence_after_stop=testing,
)
diff --git a/examples/websocket-server/bot.py b/examples/websocket-server/bot.py
index d44c77df8..489605aef 100644
--- a/examples/websocket-server/bot.py
+++ b/examples/websocket-server/bot.py
@@ -97,7 +97,7 @@ async def main():
tts = CartesiaTTSService(
api_key=os.getenv("CARTESIA_API_KEY"),
- voice_id="79a125e8-cd45-4c13-8a67-188112f4dd22", # British Lady
+ voice_id="71a7ad14-091c-4e8e-a314-022ece01c121", # British Reading Lady
)
messages = [
diff --git a/pyproject.toml b/pyproject.toml
index dd58b1bfe..0d1e46ed9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -31,7 +31,7 @@ dependencies = [
"pyloudnorm~=0.1.1",
"resampy~=0.4.3",
"soxr~=0.5.0",
- "openai~=1.59.6"
+ "openai~=1.67.0"
]
[project.urls]
@@ -39,48 +39,51 @@ Source = "https://github.com/pipecat-ai/pipecat"
Website = "https://pipecat.ai"
[project.optional-dependencies]
-anthropic = [ "anthropic~=0.47.2" ]
-assemblyai = [ "assemblyai~=0.36.0" ]
-aws = [ "boto3~=1.35.99" ]
+anthropic = [ "anthropic~=0.49.0" ]
+assemblyai = [ "assemblyai~=0.37.0" ]
+aws = [ "boto3~=1.37.16" ]
azure = [ "azure-cognitiveservices-speech~=1.42.0"]
canonical = [ "aiofiles~=24.1.0" ]
-cartesia = [ "cartesia~=1.3.1", "websockets~=13.1" ]
+cartesia = [ "cartesia~=1.4.0", "websockets~=13.1" ]
+neuphonic = [ "pyneuphonic~=1.5.13", "websockets~=13.1" ]
cerebras = []
deepseek = []
daily = [ "daily-python~=0.15.0" ]
deepgram = [ "deepgram-sdk~=3.8.0" ]
elevenlabs = [ "websockets~=13.1" ]
-fal = [ "fal-client~=0.5.6" ]
+fal = [ "fal-client~=0.5.9" ]
fish = [ "ormsgpack~=1.7.0", "websockets~=13.1" ]
gladia = [ "websockets~=13.1" ]
-google = [ "google-cloud-speech~=2.31.0", "google-cloud-texttospeech~=2.25.0", "google-genai~=1.3.0", "google-generativeai~=0.8.4" ]
+google = [ "google-cloud-speech~=2.31.1", "google-cloud-texttospeech~=2.25.1", "google-genai~=1.7.0", "google-generativeai~=0.8.4" ]
grok = []
groq = []
gstreamer = [ "pygobject~=3.50.0" ]
fireworks = []
krisp = [ "pipecat-ai-krisp~=0.3.0" ]
koala = [ "pvkoala~=2.0.3" ]
-langchain = [ "langchain~=0.3.14", "langchain-community~=0.3.14", "langchain-openai~=0.3.0" ]
-livekit = [ "livekit~=0.19.1", "livekit-api~=0.8.1", "tenacity~=9.0.0" ]
+langchain = [ "langchain~=0.3.20", "langchain-community~=0.3.20", "langchain-openai~=0.3.9" ]
+livekit = [ "livekit~=0.22.0", "livekit-api~=0.8.2", "tenacity~=9.0.0" ]
lmnt = [ "websockets~=13.1" ]
local = [ "pyaudio~=0.2.14" ]
moondream = [ "einops~=0.8.0", "timm~=1.0.13", "transformers~=4.48.0" ]
nim = []
noisereduce = [ "noisereduce~=3.0.3" ]
openai = [ "websockets~=13.1" ]
-openpipe = [ "openpipe~=4.45.0" ]
+openpipe = [ "openpipe~=4.48.0" ]
+openrouter = []
perplexity = []
playht = [ "pyht~=0.1.12", "websockets~=13.1" ]
rime = [ "websockets~=13.1" ]
-riva = [ "nvidia-riva-client~=2.18.0" ]
-sentry = [ "sentry-sdk~=2.20.0" ]
+riva = [ "nvidia-riva-client~=2.19.0" ]
+sentry = [ "sentry-sdk~=2.23.1" ]
silero = [ "onnxruntime~=1.20.1" ]
simli = [ "simli-ai~=0.1.10"]
soundfile = [ "soundfile~=0.13.0" ]
+tavus=[]
together = []
+ultravox = [ "transformers~=4.48.0", "vllm~=0.7.3" ]
websocket = [ "websockets~=13.1", "fastapi~=0.115.6" ]
whisper = [ "faster-whisper~=1.1.1" ]
-openrouter = []
[tool.setuptools.packages.find]
# All the following settings are optional:
diff --git a/src/pipecat/audio/utils.py b/src/pipecat/audio/utils.py
index 7c4c25fcc..1f7db648f 100644
--- a/src/pipecat/audio/utils.py
+++ b/src/pipecat/audio/utils.py
@@ -18,23 +18,6 @@ def create_default_resampler(**kwargs) -> BaseAudioResampler:
return SOXRAudioResampler(**kwargs)
-def resample_audio(audio: bytes, original_rate: int, target_rate: int) -> bytes:
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'resample_audio()' is deprecated, use 'create_default_resampler()' instead.",
- DeprecationWarning,
- )
-
- if original_rate == target_rate:
- return audio
- audio_data = np.frombuffer(audio, dtype=np.int16)
- resampled_audio = soxr.resample(audio_data, original_rate, target_rate)
- return resampled_audio.astype(np.int16).tobytes()
-
-
def mix_audio(audio1: bytes, audio2: bytes) -> bytes:
data1 = np.frombuffer(audio1, dtype=np.int16)
data2 = np.frombuffer(audio2, dtype=np.int16)
diff --git a/src/pipecat/frames/frames.py b/src/pipecat/frames/frames.py
index 74dd2accb..c2a79461f 100644
--- a/src/pipecat/frames/frames.py
+++ b/src/pipecat/frames/frames.py
@@ -634,6 +634,15 @@ class FunctionCallInProgressFrame(SystemFrame):
function_name: str
tool_call_id: str
arguments: str
+ cancel_on_interruption: bool
+
+
+@dataclass
+class FunctionCallCancelFrame(SystemFrame):
+ """A frame to signal a function call has been cancelled."""
+
+ function_name: str
+ tool_call_id: str
@dataclass
@@ -653,13 +662,19 @@ class TransportMessageUrgentFrame(SystemFrame):
@dataclass
class UserImageRequestFrame(SystemFrame):
- """A frame user to request an image from the given user."""
+ """A frame to request an image from the given user. The frame might be
+ generated by a function call in which case the corresponding fields will be
+ properly set.
+
+ """
user_id: str
context: Optional[Any] = None
+ function_name: Optional[str] = None
+ tool_call_id: Optional[str] = None
def __str__(self):
- return f"{self.name}, user: {self.user_id}"
+ return f"{self.name}(user: {self.user_id}, function: {self.function_name}, request: {self.tool_call_id})"
@dataclass
@@ -689,10 +704,11 @@ class UserImageRawFrame(InputImageRawFrame):
"""An image associated to a user."""
user_id: str
+ request: Optional[UserImageRequestFrame] = None
def __str__(self):
pts = format_pts(self.pts)
- return f"{self.name}(pts: {pts}, user: {self.user_id}, size: {self.size}, format: {self.format})"
+ return f"{self.name}(pts: {pts}, user: {self.user_id}, size: {self.size}, format: {self.format}, request: {self.request})"
@dataclass
diff --git a/src/pipecat/pipeline/runner.py b/src/pipecat/pipeline/runner.py
index 3209fa92a..7ac07064f 100644
--- a/src/pipecat/pipeline/runner.py
+++ b/src/pipecat/pipeline/runner.py
@@ -40,12 +40,18 @@ class PipelineRunner(BaseObject):
task.set_event_loop(self._loop)
await task.run()
del self._tasks[task.name]
+
+ # Cleanup base object.
+ await self.cleanup()
+
# If we are cancelling through a signal, make sure we wait for it so
# everything gets cleaned up nicely.
if self._sig_task:
await self._sig_task
+
if self._force_gc:
self._gc_collect()
+
logger.debug(f"Runner {self} finished running {task}")
async def stop_when_done(self):
diff --git a/src/pipecat/pipeline/task.py b/src/pipecat/pipeline/task.py
index 1c9d2dff9..8279373cb 100644
--- a/src/pipecat/pipeline/task.py
+++ b/src/pipecat/pipeline/task.py
@@ -5,7 +5,8 @@
#
import asyncio
-from typing import Any, AsyncIterable, Dict, Iterable, List, Optional
+import time
+from typing import Any, AsyncIterable, Dict, Iterable, List, Optional, Tuple, Type
from loguru import logger
from pydantic import BaseModel, ConfigDict
@@ -13,6 +14,7 @@ from pydantic import BaseModel, ConfigDict
from pipecat.clocks.base_clock import BaseClock
from pipecat.clocks.system_clock import SystemClock
from pipecat.frames.frames import (
+ BotSpeakingFrame,
CancelFrame,
CancelTaskFrame,
EndFrame,
@@ -20,6 +22,7 @@ from pipecat.frames.frames import (
ErrorFrame,
Frame,
HeartbeatFrame,
+ LLMFullResponseEndFrame,
MetricsFrame,
StartFrame,
StopFrame,
@@ -119,12 +122,42 @@ class PipelineTaskSink(FrameProcessor):
class PipelineTask(BaseTask):
"""Manages the execution of a pipeline, handling frame processing and task lifecycle.
+ It has a couple of event handlers `on_frame_reached_upstream` and
+ `on_frame_reached_downstream` that are called when upstream frames or
+ downstream frames reach both ends of pipeline. By default, the events
+ handlers will not be called unless some filters are set using
+ `set_reached_upstream_filter` and `set_reached_downstream_filter`.
+
+ @task.event_handler("on_frame_reached_upstream")
+ async def on_frame_reached_upstream(task, frame):
+ ...
+
+ @task.event_handler("on_frame_reached_downstream")
+ async def on_frame_reached_downstream(task, frame):
+ ...
+
+ It also has an event handler that detects when the pipeline is idle. By
+ default, a pipeline is idle if no `BotSpeakingFrame` or
+ `LLMFullResponseEndFrame` are received within `idle_timeout_secs`.
+
+ @task.event_handler("on_idle_timeout")
+ async def on_idle_timeout(task):
+ ...
+
Args:
pipeline: The pipeline to execute.
params: Configuration parameters for the pipeline.
observers: List of observers for monitoring pipeline execution.
clock: Clock implementation for timing operations.
check_dangling_tasks: Whether to check for processors' tasks finishing properly.
+ idle_timeout_secs: Timeout (in seconds) to consider pipeline idle or
+ None. If a pipeline is idle the pipeline task will be cancelled
+ automatically.
+ idle_timeout_frames: A tuple with the frames that should trigger an idle
+ timeout if not received withing `idle_timeout_seconds`.
+ cancel_on_idle_timeout: Whether the pipeline task should be cancelled if
+ the idle timeout is reached.
+
"""
def __init__(
@@ -136,12 +169,21 @@ class PipelineTask(BaseTask):
clock: BaseClock = SystemClock(),
task_manager: Optional[BaseTaskManager] = None,
check_dangling_tasks: bool = True,
+ idle_timeout_secs: Optional[float] = 300,
+ idle_timeout_frames: Tuple[Type[Frame], ...] = (
+ BotSpeakingFrame,
+ LLMFullResponseEndFrame,
+ ),
+ cancel_on_idle_timeout: bool = True,
):
super().__init__()
self._pipeline = pipeline
self._clock = clock
self._params = params
self._check_dangling_tasks = check_dangling_tasks
+ self._idle_timeout_secs = idle_timeout_secs
+ self._idle_timeout_frames = idle_timeout_frames
+ self._cancel_on_idle_timeout = cancel_on_idle_timeout
if self._params.observers:
import warnings
@@ -163,20 +205,47 @@ class PipelineTask(BaseTask):
# This is the heartbeat queue. When a heartbeat frame is received in the
# down queue we add it to the heartbeat queue for processing.
self._heartbeat_queue = asyncio.Queue()
+ # This is the idle queue. When frames are received downstream they are
+ # put in the queue. If no frame is received the pipeline is considered
+ # idle.
+ self._idle_queue = asyncio.Queue()
# This event is used to indicate a finalize frame (e.g. EndFrame,
# StopFrame) has been received in the down queue.
self._pipeline_end_event = asyncio.Event()
+ # This is a source processor that we connect to the provided
+ # pipeline. This source processor allows up to receive and react to
+ # upstream frames.
self._source = PipelineTaskSource(self._up_queue)
self._source.link(pipeline)
+ # This is a sink processor that we connect to the provided
+ # pipeline. This sink processor allows up to receive and react to
+ # downstream frames.
self._sink = PipelineTaskSink(self._down_queue)
pipeline.link(self._sink)
+ # This task maneger will handle all the asyncio tasks created by this
+ # PipelineTask and its frame processors.
self._task_manager = task_manager or TaskManager()
+ # The task observer acts as a proxy to the provided observers. This way,
+ # we only need to pass a single observer (using the StartFrame) which
+ # then just acts as a proxy.
self._observer = TaskObserver(observers=observers, task_manager=self._task_manager)
+ # These events can be used to check which frames make it to the source
+ # or sink processors. Instead of calling the event handlers for every
+ # frame the user needs to specify which events they are interested
+ # in. This is mainly for efficiency reason because each event handler
+ # creates a task and most likely you only care about one or two frame
+ # types.
+ self._reached_upstream_types: Tuple[Type[Frame], ...] = ()
+ self._reached_downstream_types: Tuple[Type[Frame], ...] = ()
+ self._register_event_handler("on_frame_reached_upstream")
+ self._register_event_handler("on_frame_reached_downstream")
+ self._register_event_handler("on_idle_timeout")
+
@property
def params(self) -> PipelineParams:
"""Returns the pipeline parameters of this task."""
@@ -185,6 +254,20 @@ class PipelineTask(BaseTask):
def set_event_loop(self, loop: asyncio.AbstractEventLoop):
self._task_manager.set_event_loop(loop)
+ def set_reached_upstream_filter(self, types: Tuple[Type[Frame], ...]):
+ """Sets which frames will be checked before calling the
+ on_frame_reached_upstream event handler.
+
+ """
+ self._reached_upstream_types = types
+
+ def set_reached_downstream_filter(self, types: Tuple[Type[Frame], ...]):
+ """Sets which frames will be checked before calling the
+ on_frame_reached_downstream event handler.
+
+ """
+ self._reached_downstream_types = types
+
def has_finished(self) -> bool:
"""Indicates whether the tasks has finished. That is, all processors
have stopped.
@@ -277,19 +360,30 @@ class PipelineTask(BaseTask):
self._heartbeat_monitor_handler(), f"{self}::_heartbeat_monitor_handler"
)
+ def _maybe_start_idle_task(self):
+ if self._idle_timeout_secs:
+ self._idle_monitor_task = self._task_manager.create_task(
+ self._idle_monitor_handler(), f"{self}::_idle_monitor_handler"
+ )
+
async def _cancel_tasks(self):
- await self._maybe_cancel_heartbeat_tasks()
+ await self._observer.stop()
await self._task_manager.cancel_task(self._process_up_task)
await self._task_manager.cancel_task(self._process_down_task)
- await self._observer.stop()
+ await self._maybe_cancel_heartbeat_tasks()
+ await self._maybe_cancel_idle_task()
async def _maybe_cancel_heartbeat_tasks(self):
if self._params.enable_heartbeats:
await self._task_manager.cancel_task(self._heartbeat_push_task)
await self._task_manager.cancel_task(self._heartbeat_monitor_task)
+ async def _maybe_cancel_idle_task(self):
+ if self._idle_timeout_secs:
+ await self._task_manager.cancel_task(self._idle_monitor_task)
+
def _initial_metrics_frame(self) -> MetricsFrame:
processors = self._pipeline.processors_with_metrics()
data = []
@@ -303,6 +397,10 @@ class PipelineTask(BaseTask):
self._pipeline_end_event.clear()
async def _cleanup(self, cleanup_pipeline: bool):
+ # Cleanup base object.
+ await self.cleanup()
+
+ # Cleanup pipeline processors.
await self._source.cleanup()
if cleanup_pipeline:
await self._pipeline.cleanup()
@@ -311,12 +409,13 @@ class PipelineTask(BaseTask):
async def _process_push_queue(self):
"""This is the task that runs the pipeline for the first time by sending
a StartFrame and by pushing any other frames queued by the user. It runs
- until the tasks is canceled or stopped (e.g. with an EndFrame).
+ until the tasks is cancelled or stopped (e.g. with an EndFrame).
"""
self._clock.start()
self._maybe_start_heartbeat_tasks()
+ self._maybe_start_idle_task()
start_frame = StartFrame(
clock=self._clock,
@@ -356,6 +455,10 @@ class PipelineTask(BaseTask):
"""
while True:
frame = await self._up_queue.get()
+
+ if isinstance(frame, self._reached_upstream_types):
+ await self._call_event_handler("on_frame_reached_upstream", frame)
+
if isinstance(frame, EndTaskFrame):
# Tell the task we should end nicely.
await self.queue_frame(EndFrame())
@@ -366,12 +469,14 @@ class PipelineTask(BaseTask):
# Tell the task we should stop nicely.
await self.queue_frame(StopFrame())
elif isinstance(frame, ErrorFrame):
- logger.error(f"Error running app: {frame}")
if frame.fatal:
+ logger.error(f"A fatal error occurred: {frame}")
# Cancel all tasks downstream.
await self.queue_frame(CancelFrame())
# Tell the task we should stop.
await self.queue_frame(StopTaskFrame())
+ else:
+ logger.warning(f"Something went wrong: {frame}")
self._up_queue.task_done()
async def _process_down_queue(self):
@@ -383,6 +488,14 @@ class PipelineTask(BaseTask):
"""
while True:
frame = await self._down_queue.get()
+
+ # Queue received frame to the idle queue so we can monitor idle
+ # pipelines.
+ await self._idle_queue.put(frame)
+
+ if isinstance(frame, self._reached_downstream_types):
+ await self._call_event_handler("on_frame_reached_downstream", frame)
+
if isinstance(frame, (EndFrame, StopFrame)):
self._pipeline_end_event.set()
elif isinstance(frame, HeartbeatFrame):
@@ -417,6 +530,48 @@ class PipelineTask(BaseTask):
f"{self}: heartbeat frame not received for more than {wait_time} seconds"
)
+ async def _idle_monitor_handler(self):
+ """This tasks monitors activity in the pipeline. If no frames are
+ received (heartbeats don't count) the pipeline is considered idle.
+
+ """
+ running = True
+ last_frame_time = 0
+ while running:
+ try:
+ frame = await asyncio.wait_for(
+ self._idle_queue.get(), timeout=self._idle_timeout_secs
+ )
+
+ if isinstance(frame, StartFrame) or isinstance(frame, self._idle_timeout_frames):
+ # If we find a StartFrame or one of the frames that prevents a
+ # time out we update the time.
+ last_frame_time = time.time()
+ else:
+ # If we find any other frame we check if the pipeline is
+ # idle by checking the last time we received one of the
+ # valid frames.
+ diff_time = time.time() - last_frame_time
+ if diff_time >= self._idle_timeout_secs:
+ running = await self._idle_timeout_detected()
+
+ self._idle_queue.task_done()
+ except asyncio.TimeoutError:
+ running = await self._idle_timeout_detected()
+
+ async def _idle_timeout_detected(self) -> bool:
+ """Logic for when the pipeline is idle.
+
+ Returns:
+ bool: Whther the pipeline task is being cancelled or not.
+ """
+ await self._call_event_handler("on_idle_timeout")
+ if self._cancel_on_idle_timeout:
+ logger.warning(f"Idle pipeline detected, cancelling pipeline task...")
+ await self.cancel()
+ return False
+ return True
+
def _print_dangling_tasks(self):
tasks = [t.get_name() for t in self._task_manager.current_tasks()]
if tasks:
diff --git a/src/pipecat/processors/aggregators/llm_response.py b/src/pipecat/processors/aggregators/llm_response.py
index d8582e32f..75435a214 100644
--- a/src/pipecat/processors/aggregators/llm_response.py
+++ b/src/pipecat/processors/aggregators/llm_response.py
@@ -5,16 +5,21 @@
#
import asyncio
-import time
from abc import abstractmethod
-from typing import List
+from typing import Dict, List
+
+from loguru import logger
from pipecat.frames.frames import (
+ BotStoppedSpeakingFrame,
CancelFrame,
EmulateUserStartedSpeakingFrame,
EmulateUserStoppedSpeakingFrame,
EndFrame,
Frame,
+ FunctionCallCancelFrame,
+ FunctionCallInProgressFrame,
+ FunctionCallResultFrame,
InterimTranscriptionFrame,
LLMFullResponseEndFrame,
LLMFullResponseStartFrame,
@@ -23,10 +28,12 @@ from pipecat.frames.frames import (
LLMMessagesUpdateFrame,
LLMSetToolsFrame,
LLMTextFrame,
+ OpenAILLMContextAssistantTimestampFrame,
StartFrame,
StartInterruptionFrame,
TextFrame,
TranscriptionFrame,
+ UserImageRawFrame,
UserStartedSpeakingFrame,
UserStoppedSpeakingFrame,
)
@@ -35,6 +42,7 @@ from pipecat.processors.aggregators.openai_llm_context import (
OpenAILLMContextFrame,
)
from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
+from pipecat.utils.time import time_now_iso8601
class LLMFullResponseAggregator(FrameProcessor):
@@ -139,68 +147,20 @@ class BaseLLMResponseAggregator(FrameProcessor):
pass
@abstractmethod
- async def push_aggregation(self):
+ async def handle_aggregation(self, aggregation: str):
+ """Adds the given aggregation to the aggregator. The aggregator can use
+ a simple list of message or a context. It doesn't not push any frames.
+
+ """
pass
-
-class LLMResponseAggregator(BaseLLMResponseAggregator):
- """This is a base LLM aggregator that uses a simple list of messages to
- store the conversation. It pushes `LLMMessagesFrame` as an aggregation
- frame.
-
- """
-
- def __init__(
- self,
- *,
- messages: List[dict],
- role: str = "user",
- **kwargs,
- ):
- super().__init__(**kwargs)
-
- self._messages = messages
- self._role = role
-
- self._aggregation = ""
-
- self.reset()
-
- @property
- def messages(self) -> List[dict]:
- return self._messages
-
- @property
- def role(self) -> str:
- return self._role
-
- def add_messages(self, messages):
- self._messages.extend(messages)
-
- def set_messages(self, messages):
- self.reset()
- self._messages.clear()
- self._messages.extend(messages)
-
- def set_tools(self, tools):
- pass
-
- def reset(self):
- self._aggregation = ""
-
+ @abstractmethod
async def push_aggregation(self):
- if len(self._aggregation) > 0:
- self._messages.append({"role": self._role, "content": self._aggregation})
+ """Pushes the current aggregation. For example, iN the case of context
+ aggregation this might push a new context frame.
- # Reset the aggregation. Reset it before pushing it down, otherwise
- # if the tasks gets cancelled we won't be able to clear things up.
- self._aggregation = ""
-
- frame = LLMMessagesFrame(self._messages)
- await self.push_frame(frame)
-
- # Reset our accumulator state.
- self.reset()
+ """
+ pass
class LLMContextResponseAggregator(BaseLLMResponseAggregator):
@@ -247,20 +207,6 @@ class LLMContextResponseAggregator(BaseLLMResponseAggregator):
def reset(self):
self._aggregation = ""
- async def push_aggregation(self):
- if len(self._aggregation) > 0:
- self._context.add_message({"role": self.role, "content": self._aggregation})
-
- # Reset the aggregation. Reset it before pushing it down, otherwise
- # if the tasks gets cancelled we won't be able to clear things up.
- self._aggregation = ""
-
- frame = OpenAILLMContextFrame(self._context)
- await self.push_frame(frame)
-
- # Reset our accumulator state.
- self.reset()
-
class LLMUserContextAggregator(LLMContextResponseAggregator):
"""This is a user LLM aggregator that uses an LLM context to store the
@@ -275,26 +221,26 @@ class LLMUserContextAggregator(LLMContextResponseAggregator):
self,
context: OpenAILLMContext,
aggregation_timeout: float = 1.0,
- bot_interruption_timeout: float = 2.0,
**kwargs,
):
super().__init__(context=context, role="user", **kwargs)
self._aggregation_timeout = aggregation_timeout
- self._bot_interruption_timeout = bot_interruption_timeout
self._seen_interim_results = False
self._user_speaking = False
- self._last_user_speaking_time = 0
self._emulating_vad = False
+ self._waiting_for_aggregation = False
self._aggregation_event = asyncio.Event()
self._aggregation_task = None
- self.reset()
-
def reset(self):
super().reset()
self._seen_interim_results = False
+ self._waiting_for_aggregation = False
+
+ async def handle_aggregation(self, aggregation: str):
+ self._context.add_message({"role": self.role, "content": self._aggregation})
async def process_frame(self, frame: Frame, direction: FrameDirection):
await super().process_frame(frame, direction)
@@ -331,6 +277,17 @@ class LLMUserContextAggregator(LLMContextResponseAggregator):
else:
await self.push_frame(frame, direction)
+ async def push_aggregation(self):
+ if len(self._aggregation) > 0:
+ await self.handle_aggregation(self._aggregation)
+
+ # Reset the aggregation. Reset it before pushing it down, otherwise
+ # if the tasks gets cancelled we won't be able to clear things up.
+ self.reset()
+
+ frame = OpenAILLMContextFrame(self._context)
+ await self.push_frame(frame)
+
async def _start(self, frame: StartFrame):
self._create_aggregation_task()
@@ -341,12 +298,14 @@ class LLMUserContextAggregator(LLMContextResponseAggregator):
await self._cancel_aggregation_task()
async def _handle_user_started_speaking(self, _: UserStartedSpeakingFrame):
- self._last_user_speaking_time = time.time()
self._user_speaking = True
+ self._waiting_for_aggregation = True
async def _handle_user_stopped_speaking(self, _: UserStoppedSpeakingFrame):
- self._last_user_speaking_time = time.time()
self._user_speaking = False
+ # We just stopped speaking. Let's see if there's some aggregation to
+ # push. If the last thing we saw is an interim transcription, let's wait
+ # pushing the aggregation as we will probably get a final transcription.
if not self._seen_interim_results:
await self.push_aggregation()
@@ -399,18 +358,13 @@ class LLMUserContextAggregator(LLMContextResponseAggregator):
frame we might want to interrupt the bot.
"""
- if not self._user_speaking:
- diff_time = time.time() - self._last_user_speaking_time
- if diff_time > self._bot_interruption_timeout:
- # If we reach this case we received a transcription but VAD was
- # not able to detect voice (e.g. when you whisper a short
- # utterance). So, we need to emulate VAD (i.e. user
- # start/stopped speaking).
- await self.push_frame(EmulateUserStartedSpeakingFrame(), FrameDirection.UPSTREAM)
- self._emulating_vad = True
-
- # Reset time so we don't interrupt again right away.
- self._last_user_speaking_time = time.time()
+ if not self._user_speaking and not self._waiting_for_aggregation:
+ # If we reach this case we received a transcription but VAD was not
+ # able to detect voice (e.g. when you whisper a short
+ # utterance). So, we need to emulate VAD (i.e. user start/stopped
+ # speaking).
+ await self.push_frame(EmulateUserStartedSpeakingFrame(), FrameDirection.UPSTREAM)
+ self._emulating_vad = True
class LLMAssistantContextAggregator(LLMContextResponseAggregator):
@@ -424,17 +378,29 @@ class LLMAssistantContextAggregator(LLMContextResponseAggregator):
super().__init__(context=context, role="assistant", **kwargs)
self._expect_stripped_words = expect_stripped_words
- self._started = False
+ self._started = 0
+ self._function_calls_in_progress: Dict[str, FunctionCallInProgressFrame] = {}
- self.reset()
+ async def handle_aggregation(self, aggregation: str):
+ self._context.add_message({"role": "assistant", "content": aggregation})
+
+ async def handle_function_call_in_progress(self, frame: FunctionCallInProgressFrame):
+ pass
+
+ async def handle_function_call_result(self, frame: FunctionCallResultFrame):
+ pass
+
+ async def handle_function_call_cancel(self, frame: FunctionCallCancelFrame):
+ pass
+
+ async def handle_user_image_frame(self, frame: UserImageRawFrame):
+ pass
async def process_frame(self, frame: Frame, direction: FrameDirection):
await super().process_frame(frame, direction)
if isinstance(frame, StartInterruptionFrame):
- await self.push_aggregation()
- # Reset anyways
- self.reset()
+ await self._handle_interruptions(frame)
await self.push_frame(frame, direction)
elif isinstance(frame, LLMFullResponseStartFrame):
await self._handle_llm_start(frame)
@@ -448,14 +414,116 @@ class LLMAssistantContextAggregator(LLMContextResponseAggregator):
self.set_messages(frame.messages)
elif isinstance(frame, LLMSetToolsFrame):
self.set_tools(frame.tools)
+ elif isinstance(frame, FunctionCallInProgressFrame):
+ await self._handle_function_call_in_progress(frame)
+ elif isinstance(frame, FunctionCallResultFrame):
+ await self._handle_function_call_result(frame)
+ elif isinstance(frame, FunctionCallCancelFrame):
+ await self._handle_function_call_cancel(frame)
+ elif isinstance(frame, UserImageRawFrame) and frame.request and frame.request.tool_call_id:
+ await self._handle_user_image_frame(frame)
+ elif isinstance(frame, BotStoppedSpeakingFrame):
+ await self.push_aggregation()
else:
await self.push_frame(frame, direction)
+ async def push_aggregation(self):
+ if not self._aggregation:
+ return
+
+ aggregation = self._aggregation.strip()
+ self.reset()
+
+ if aggregation:
+ await self.handle_aggregation(aggregation)
+
+ # Push context frame
+ await self.push_context_frame()
+
+ # Push timestamp frame with current time
+ timestamp_frame = OpenAILLMContextAssistantTimestampFrame(timestamp=time_now_iso8601())
+ await self.push_frame(timestamp_frame)
+
+ async def _handle_interruptions(self, frame: StartInterruptionFrame):
+ await self.push_aggregation()
+ self._started = 0
+ self.reset()
+
+ async def _handle_function_call_in_progress(self, frame: FunctionCallInProgressFrame):
+ logger.debug(
+ f"{self} FunctionCallInProgressFrame: [{frame.function_name}:{frame.tool_call_id}]"
+ )
+ await self.handle_function_call_in_progress(frame)
+ self._function_calls_in_progress[frame.tool_call_id] = frame
+
+ async def _handle_function_call_result(self, frame: FunctionCallResultFrame):
+ logger.debug(
+ f"{self} FunctionCallResultFrame: [{frame.function_name}:{frame.tool_call_id}]"
+ )
+ if frame.tool_call_id not in self._function_calls_in_progress:
+ logger.warning(
+ f"FunctionCallResultFrame tool_call_id [{frame.tool_call_id}] is not running"
+ )
+ return
+
+ del self._function_calls_in_progress[frame.tool_call_id]
+
+ properties = frame.properties
+
+ await self.handle_function_call_result(frame)
+
+ # Run inference if the function call result requires it.
+ if frame.result:
+ run_llm = False
+
+ if properties and properties.run_llm is not None:
+ # If the tool call result has a run_llm property, use it
+ run_llm = properties.run_llm
+ else:
+ # Default behavior is to run the LLM if there are no function calls in progress
+ run_llm = not bool(self._function_calls_in_progress)
+
+ if run_llm:
+ await self.push_context_frame(FrameDirection.UPSTREAM)
+
+ # Emit the on_context_updated callback once the function call
+ # result is added to the context
+ if properties and properties.on_context_updated:
+ await properties.on_context_updated()
+
+ async def _handle_function_call_cancel(self, frame: FunctionCallCancelFrame):
+ logger.debug(
+ f"{self} FunctionCallCancelFrame: [{frame.function_name}:{frame.tool_call_id}]"
+ )
+ if frame.tool_call_id not in self._function_calls_in_progress:
+ return
+
+ if self._function_calls_in_progress[frame.tool_call_id].cancel_on_interruption:
+ await self.handle_function_call_cancel(frame)
+ del self._function_calls_in_progress[frame.tool_call_id]
+
+ async def _handle_user_image_frame(self, frame: UserImageRawFrame):
+ logger.debug(
+ f"{self} UserImageRawFrame: [{frame.request.function_name}:{frame.request.tool_call_id}]"
+ )
+
+ if frame.request.tool_call_id not in self._function_calls_in_progress:
+ logger.warning(
+ f"UserImageRawFrame tool_call_id [{frame.request.tool_call_id}] is not running"
+ )
+ return
+
+ del self._function_calls_in_progress[frame.request.tool_call_id]
+
+ await self.handle_user_image_frame(frame)
+ await self.push_aggregation()
+ await self.push_context_frame(FrameDirection.UPSTREAM)
+
async def _handle_llm_start(self, _: LLMFullResponseStartFrame):
- self._started = True
+ self._started += 1
async def _handle_llm_end(self, _: LLMFullResponseEndFrame):
- self._started = False
+ self._started -= 1
await self.push_aggregation()
async def _handle_text(self, frame: TextFrame):
@@ -474,18 +542,15 @@ class LLMUserResponseAggregator(LLMUserContextAggregator):
async def push_aggregation(self):
if len(self._aggregation) > 0:
- self._context.add_message({"role": self.role, "content": self._aggregation})
+ await self.handle_aggregation(self._aggregation)
# Reset the aggregation. Reset it before pushing it down, otherwise
# if the tasks gets cancelled we won't be able to clear things up.
- self._aggregation = ""
+ self.reset()
frame = LLMMessagesFrame(self._context.messages)
await self.push_frame(frame)
- # Reset our accumulator state.
- self.reset()
-
class LLMAssistantResponseAggregator(LLMAssistantContextAggregator):
def __init__(self, messages: List[dict] = [], **kwargs):
@@ -493,14 +558,11 @@ class LLMAssistantResponseAggregator(LLMAssistantContextAggregator):
async def push_aggregation(self):
if len(self._aggregation) > 0:
- self._context.add_message({"role": self.role, "content": self._aggregation})
+ await self.handle_aggregation(self._aggregation)
# Reset the aggregation. Reset it before pushing it down, otherwise
# if the tasks gets cancelled we won't be able to clear things up.
- self._aggregation = ""
+ self.reset()
frame = LLMMessagesFrame(self._context.messages)
await self.push_frame(frame)
-
- # Reset our accumulator state.
- self.reset()
diff --git a/src/pipecat/processors/aggregators/openai_llm_context.py b/src/pipecat/processors/aggregators/openai_llm_context.py
index e8391d62b..948e3e101 100644
--- a/src/pipecat/processors/aggregators/openai_llm_context.py
+++ b/src/pipecat/processors/aggregators/openai_llm_context.py
@@ -9,9 +9,8 @@ import copy
import io
import json
from dataclasses import dataclass
-from typing import Any, Awaitable, Callable, List, Optional
+from typing import Any, List, Optional
-from loguru import logger
from openai._types import NOT_GIVEN, NotGiven
from openai.types.chat import (
ChatCompletionMessageParam,
@@ -22,12 +21,7 @@ from PIL import Image
from pipecat.adapters.base_llm_adapter import BaseLLMAdapter
from pipecat.adapters.schemas.tools_schema import ToolsSchema
-from pipecat.frames.frames import (
- AudioRawFrame,
- Frame,
- FunctionCallInProgressFrame,
- FunctionCallResultFrame,
-)
+from pipecat.frames.frames import AudioRawFrame, Frame
from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
# JSON custom encoder to handle bytes arrays so that we can log contexts
@@ -52,7 +46,6 @@ class OpenAILLMContext:
self._messages: List[ChatCompletionMessageParam] = messages if messages else []
self._tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = tool_choice
self._tools: List[ChatCompletionToolParam] | NotGiven | ToolsSchema = tools
- self._user_image_request_context = {}
self._llm_adapter: Optional[BaseLLMAdapter] = None
def get_llm_adapter(self) -> Optional[BaseLLMAdapter]:
@@ -164,7 +157,7 @@ class OpenAILLMContext:
self._tool_choice = tool_choice
def set_tools(self, tools: List[ChatCompletionToolParam] | NotGiven | ToolsSchema = NOT_GIVEN):
- if tools != NOT_GIVEN and len(tools) == 0:
+ if tools != NOT_GIVEN and isinstance(tools, list) and len(tools) == 0:
tools = NOT_GIVEN
self._tools = tools
@@ -187,61 +180,6 @@ class OpenAILLMContext:
# todo: implement for OpenAI models and others
pass
- async def call_function(
- self,
- f: Callable[
- [str, str, Any, FrameProcessor, "OpenAILLMContext", Callable[[Any], Awaitable[None]]],
- Awaitable[None],
- ],
- *,
- function_name: str,
- tool_call_id: str,
- arguments: str,
- llm: FrameProcessor,
- run_llm: bool = True,
- ) -> None:
- logger.info(f"Calling function {function_name} with arguments {arguments}")
- # Push a SystemFrame downstream. This frame will let our assistant context aggregator
- # know that we are in the middle of a function call. Some contexts/aggregators may
- # not need this. But some definitely do (Anthropic, for example).
- # Also push a SystemFrame upstream for use by other processors, like STTMuteFilter.
- progress_frame_downstream = FunctionCallInProgressFrame(
- function_name=function_name,
- tool_call_id=tool_call_id,
- arguments=arguments,
- )
- progress_frame_upstream = FunctionCallInProgressFrame(
- function_name=function_name,
- tool_call_id=tool_call_id,
- arguments=arguments,
- )
-
- # Push frame both downstream and upstream
- await llm.push_frame(progress_frame_downstream, FrameDirection.DOWNSTREAM)
- await llm.push_frame(progress_frame_upstream, FrameDirection.UPSTREAM)
-
- # Define a callback function that pushes a FunctionCallResultFrame upstream & downstream.
- async def function_call_result_callback(result, *, properties=None):
- result_frame_downstream = FunctionCallResultFrame(
- function_name=function_name,
- tool_call_id=tool_call_id,
- arguments=arguments,
- result=result,
- properties=properties,
- )
- result_frame_upstream = FunctionCallResultFrame(
- function_name=function_name,
- tool_call_id=tool_call_id,
- arguments=arguments,
- result=result,
- properties=properties,
- )
-
- await llm.push_frame(result_frame_downstream, FrameDirection.DOWNSTREAM)
- await llm.push_frame(result_frame_upstream, FrameDirection.UPSTREAM)
-
- await f(function_name, tool_call_id, arguments, llm, self, function_call_result_callback)
-
def create_wav_header(self, sample_rate, num_channels, bits_per_sample, data_size):
# RIFF chunk descriptor
header = bytearray()
diff --git a/src/pipecat/processors/filters/stt_mute_filter.py b/src/pipecat/processors/filters/stt_mute_filter.py
index c74e495ab..cce087f22 100644
--- a/src/pipecat/processors/filters/stt_mute_filter.py
+++ b/src/pipecat/processors/filters/stt_mute_filter.py
@@ -92,20 +92,9 @@ class STTMuteFilter(FrameProcessor):
**kwargs: Additional arguments passed to parent class
"""
- def __init__(
- self, *, config: STTMuteConfig, stt_service: Optional[FrameProcessor] = None, **kwargs
- ):
+ def __init__(self, *, config: STTMuteConfig, **kwargs):
super().__init__(**kwargs)
self._config = config
- if stt_service is not None:
- import warnings
-
- warnings.warn(
- "The stt_service parameter is deprecated and will be removed in a future version. "
- "STTMuteFilter now manages mute state internally.",
- DeprecationWarning,
- stacklevel=2,
- )
self._first_speech_handled = False
self._bot_is_speaking = False
self._function_call_in_progress = False
diff --git a/src/pipecat/processors/frame_processor.py b/src/pipecat/processors/frame_processor.py
index 6a1669ff1..847cdf175 100644
--- a/src/pipecat/processors/frame_processor.py
+++ b/src/pipecat/processors/frame_processor.py
@@ -164,6 +164,7 @@ class FrameProcessor(BaseObject):
await self._task_manager.wait_for_task(task, timeout)
async def cleanup(self):
+ await super().cleanup()
await self.__cancel_input_task()
await self.__cancel_push_task()
diff --git a/src/pipecat/processors/frameworks/rtvi.py b/src/pipecat/processors/frameworks/rtvi.py
index dac903862..bb97c2098 100644
--- a/src/pipecat/processors/frameworks/rtvi.py
+++ b/src/pipecat/processors/frameworks/rtvi.py
@@ -29,6 +29,7 @@ from pipecat.frames.frames import (
CancelFrame,
DataFrame,
EndFrame,
+ EndTaskFrame,
ErrorFrame,
Frame,
FunctionCallResultFrame,
@@ -391,267 +392,6 @@ class RTVIServerMessageFrame(SystemFrame):
return f"{self.name}(data: {self.data})"
-class RTVIFrameProcessor(FrameProcessor):
- def __init__(self, direction: FrameDirection = FrameDirection.DOWNSTREAM, **kwargs):
- super().__init__(**kwargs)
- self._direction = direction
-
- async def _push_transport_message_urgent(self, model: BaseModel, exclude_none: bool = True):
- frame = TransportMessageUrgentFrame(message=model.model_dump(exclude_none=exclude_none))
- await self.push_frame(frame, self._direction)
-
-
-class RTVISpeakingProcessor(RTVIFrameProcessor):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVISpeakingProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, (UserStartedSpeakingFrame, UserStoppedSpeakingFrame)):
- await self._handle_interruptions(frame)
- elif isinstance(frame, (BotStartedSpeakingFrame, BotStoppedSpeakingFrame)):
- await self._handle_bot_speaking(frame)
-
- async def _handle_interruptions(self, frame: Frame):
- message = None
- if isinstance(frame, UserStartedSpeakingFrame):
- message = RTVIUserStartedSpeakingMessage()
- elif isinstance(frame, UserStoppedSpeakingFrame):
- message = RTVIUserStoppedSpeakingMessage()
-
- if message:
- await self._push_transport_message_urgent(message)
-
- async def _handle_bot_speaking(self, frame: Frame):
- message = None
- if isinstance(frame, BotStartedSpeakingFrame):
- message = RTVIBotStartedSpeakingMessage()
- elif isinstance(frame, BotStoppedSpeakingFrame):
- message = RTVIBotStoppedSpeakingMessage()
-
- if message:
- await self._push_transport_message_urgent(message)
-
-
-class RTVIUserTranscriptionProcessor(RTVIFrameProcessor):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVIUserTranscriptionProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, (TranscriptionFrame, InterimTranscriptionFrame)):
- await self._handle_user_transcriptions(frame)
-
- async def _handle_user_transcriptions(self, frame: Frame):
- message = None
- if isinstance(frame, TranscriptionFrame):
- message = RTVIUserTranscriptionMessage(
- data=RTVIUserTranscriptionMessageData(
- text=frame.text, user_id=frame.user_id, timestamp=frame.timestamp, final=True
- )
- )
- elif isinstance(frame, InterimTranscriptionFrame):
- message = RTVIUserTranscriptionMessage(
- data=RTVIUserTranscriptionMessageData(
- text=frame.text, user_id=frame.user_id, timestamp=frame.timestamp, final=False
- )
- )
-
- if message:
- await self._push_transport_message_urgent(message)
-
-
-class RTVIUserLLMTextProcessor(RTVIFrameProcessor):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVIUserLLMTextProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, OpenAILLMContextFrame):
- await self._handle_context(frame)
-
- async def _handle_context(self, frame: OpenAILLMContextFrame):
- messages = frame.context.messages
- if len(messages) > 0:
- message = messages[-1]
- if message["role"] == "user":
- content = message["content"]
- if isinstance(content, list):
- text = " ".join(item["text"] for item in content if "text" in item)
- else:
- text = content
- rtvi_message = RTVIUserLLMTextMessage(data=RTVITextMessageData(text=text))
- await self._push_transport_message_urgent(rtvi_message)
-
-
-class RTVIBotTranscriptionProcessor(RTVIFrameProcessor):
- def __init__(self):
- super().__init__()
- self._aggregation = ""
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVIBotTranscriptionProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, UserStartedSpeakingFrame):
- await self._push_aggregation()
- elif isinstance(frame, LLMTextFrame):
- self._aggregation += frame.text
- if match_endofsentence(self._aggregation):
- await self._push_aggregation()
-
- async def _push_aggregation(self):
- if len(self._aggregation) > 0:
- message = RTVIBotTranscriptionMessage(data=RTVITextMessageData(text=self._aggregation))
- await self._push_transport_message_urgent(message)
- self._aggregation = ""
-
-
-class RTVIBotLLMProcessor(RTVIFrameProcessor):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVIBotLLMProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, LLMFullResponseStartFrame):
- await self._push_transport_message_urgent(RTVIBotLLMStartedMessage())
- elif isinstance(frame, LLMFullResponseEndFrame):
- await self._push_transport_message_urgent(RTVIBotLLMStoppedMessage())
- elif isinstance(frame, LLMTextFrame):
- message = RTVIBotLLMTextMessage(data=RTVITextMessageData(text=frame.text))
- await self._push_transport_message_urgent(message)
-
-
-class RTVIBotTTSProcessor(RTVIFrameProcessor):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVIBotTTSProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, TTSStartedFrame):
- await self._push_transport_message_urgent(RTVIBotTTSStartedMessage())
- elif isinstance(frame, TTSStoppedFrame):
- await self._push_transport_message_urgent(RTVIBotTTSStoppedMessage())
- elif isinstance(frame, TTSTextFrame):
- message = RTVIBotTTSTextMessage(data=RTVITextMessageData(text=frame.text))
- await self._push_transport_message_urgent(message)
-
-
-class RTVIMetricsProcessor(RTVIFrameProcessor):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVIMetricsProcessor' is deprecated, use an 'RTVIObserver' instead.",
- DeprecationWarning,
- )
-
- async def process_frame(self, frame: Frame, direction: FrameDirection):
- await super().process_frame(frame, direction)
-
- await self.push_frame(frame, direction)
-
- if isinstance(frame, MetricsFrame):
- await self._handle_metrics(frame)
-
- async def _handle_metrics(self, frame: MetricsFrame):
- metrics = {}
- for d in frame.data:
- if isinstance(d, TTFBMetricsData):
- if "ttfb" not in metrics:
- metrics["ttfb"] = []
- metrics["ttfb"].append(d.model_dump(exclude_none=True))
- elif isinstance(d, ProcessingMetricsData):
- if "processing" not in metrics:
- metrics["processing"] = []
- metrics["processing"].append(d.model_dump(exclude_none=True))
- elif isinstance(d, LLMUsageMetricsData):
- if "tokens" not in metrics:
- metrics["tokens"] = []
- metrics["tokens"].append(d.value.model_dump(exclude_none=True))
- elif isinstance(d, TTSUsageMetricsData):
- if "characters" not in metrics:
- metrics["characters"] = []
- metrics["characters"].append(d.model_dump(exclude_none=True))
-
- message = RTVIMetricsMessage(data=metrics)
- await self._push_transport_message_urgent(message)
-
-
class RTVIObserver(BaseObserver):
"""Pipeline frame observer for RTVI server message handling.
@@ -876,18 +616,6 @@ class RTVIProcessor(FrameProcessor):
self._input_transport = input_transport
self._input_transport.enable_audio_in_stream_on_start(False)
- def observer(self) -> RTVIObserver:
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'RTVI.observer()' is deprecated, instantiate an 'RTVIObserver' directly instead.",
- DeprecationWarning,
- )
-
- return RTVIObserver(self)
-
def register_action(self, action: RTVIAction):
id = self._action_id(action.service, action.action)
self._registered_actions[id] = action
@@ -1039,7 +767,7 @@ class RTVIProcessor(FrameProcessor):
update_config = RTVIUpdateConfig.model_validate(message.data)
await self._handle_update_config(message.id, update_config)
case "disconnect-bot":
- await self.push_frame(EndFrame())
+ await self.push_frame(EndTaskFrame(), FrameDirection.UPSTREAM)
case "action":
action = RTVIActionRun.model_validate(message.data)
action_frame = RTVIActionFrame(message_id=message.id, rtvi_action_run=action)
diff --git a/src/pipecat/processors/transcript_processor.py b/src/pipecat/processors/transcript_processor.py
index 614fe176c..3eaff66ca 100644
--- a/src/pipecat/processors/transcript_processor.py
+++ b/src/pipecat/processors/transcript_processor.py
@@ -90,11 +90,62 @@ class AssistantTranscriptProcessor(BaseTranscriptProcessor):
self._aggregation_start_time: Optional[str] = None
async def _emit_aggregated_text(self):
- """Emit aggregated text as a transcript message."""
+ """Aggregates and emits text fragments as a transcript message.
+
+ This method uses a heuristic to automatically detect whether text fragments
+ use pre-spacing (spaces at the beginning of fragments) or not, and applies
+ the appropriate joining strategy. It handles fragments from different TTS
+ services with different formatting patterns.
+
+ Examples:
+ Pre-spaced fragments (concatenated):
+ ```
+ TTSTextFrame: ["Hello"]
+ TTSTextFrame: [" there"]
+ TTSTextFrame: ["!"]
+ TTSTextFrame: [" How"]
+ TTSTextFrame: ["'s"]
+ TTSTextFrame: [" it"]
+ TTSTextFrame: [" going"]
+ TTSTextFrame: ["?"]
+ ```
+ Result: "Hello there! How's it going?"
+
+ Word-by-word fragments (joined with spaces):
+ ```
+ TTSTextFrame: ["Hello"]
+ TTSTextFrame: ["there!"]
+ TTSTextFrame: ["How"]
+ TTSTextFrame: ["is"]
+ TTSTextFrame: ["it"]
+ TTSTextFrame: ["going?"]
+ ```
+ Result: "Hello there! How is it going?"
+ """
if self._current_text_parts and self._aggregation_start_time:
- content = " ".join(self._current_text_parts).strip()
+ # Heuristic to detect pre-spaced fragments
+ uses_prespacing = False
+ if len(self._current_text_parts) > 1:
+ # Check if any fragment after the first one starts with whitespace
+ has_spaced_parts = any(
+ part and part[0].isspace() for part in self._current_text_parts[1:]
+ )
+ if has_spaced_parts:
+ uses_prespacing = True
+
+ # Apply appropriate joining method
+ if uses_prespacing:
+ # Pre-spaced fragments - just concatenate
+ content = "".join(self._current_text_parts)
+ else:
+ # Word-by-word fragments - join with spaces
+ content = " ".join(self._current_text_parts)
+
+ # Clean up any excessive whitespace
+ content = content.strip()
+
if content:
- logger.debug(f"Emitting aggregated assistant message: {content}")
+ logger.trace(f"Emitting aggregated assistant message: {content}")
message = TranscriptionMessage(
role="assistant",
content=content,
@@ -102,7 +153,7 @@ class AssistantTranscriptProcessor(BaseTranscriptProcessor):
)
await self._emit_update([message])
else:
- logger.debug("No content to emit after stripping whitespace")
+ logger.trace("No content to emit after stripping whitespace")
# Reset aggregation state
self._current_text_parts = []
diff --git a/src/pipecat/services/ai_services.py b/src/pipecat/services/ai_services.py
index 65c9b5d92..9f9804e65 100644
--- a/src/pipecat/services/ai_services.py
+++ b/src/pipecat/services/ai_services.py
@@ -8,13 +8,13 @@ import asyncio
import io
import wave
from abc import abstractmethod
-from typing import Any, AsyncGenerator, Dict, List, Mapping, Optional, Tuple, Type
+from dataclasses import dataclass
+from typing import Any, AsyncGenerator, Dict, List, Mapping, Optional, Sequence, Set, Tuple, Type
from loguru import logger
from pipecat.adapters.base_llm_adapter import BaseLLMAdapter
from pipecat.adapters.services.open_ai_adapter import OpenAILLMAdapter
-from pipecat.audio.utils import calculate_audio_volume, exp_smoothing
from pipecat.frames.frames import (
AudioRawFrame,
BotStartedSpeakingFrame,
@@ -23,6 +23,9 @@ from pipecat.frames.frames import (
EndFrame,
ErrorFrame,
Frame,
+ FunctionCallCancelFrame,
+ FunctionCallInProgressFrame,
+ FunctionCallResultFrame,
InterimTranscriptionFrame,
LLMFullResponseEndFrame,
StartFrame,
@@ -38,6 +41,8 @@ from pipecat.frames.frames import (
TTSTextFrame,
TTSUpdateSettingsFrame,
UserImageRequestFrame,
+ UserStartedSpeakingFrame,
+ UserStoppedSpeakingFrame,
VisionImageRawFrame,
)
from pipecat.metrics.metrics import MetricsData
@@ -45,8 +50,9 @@ from pipecat.processors.aggregators.openai_llm_context import OpenAILLMContext
from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
from pipecat.services.websocket_service import WebsocketService
from pipecat.transcriptions.language import Language
-from pipecat.utils.string import match_endofsentence
+from pipecat.utils.text.base_text_aggregator import BaseTextAggregator
from pipecat.utils.text.base_text_filter import BaseTextFilter
+from pipecat.utils.text.simple_text_aggregator import SimpleTextAggregator
from pipecat.utils.time import seconds_to_nanoseconds
@@ -136,6 +142,13 @@ class AIService(FrameProcessor):
await self.push_frame(f)
+@dataclass
+class FunctionEntry:
+ function_name: Optional[str]
+ callback: Any # TODO(aleix): add proper typing.
+ cancel_on_interruption: bool
+
+
class LLMService(AIService):
"""This class is a no-op but serves as a base class for LLM services."""
@@ -145,38 +158,74 @@ class LLMService(AIService):
def __init__(self, **kwargs):
super().__init__(**kwargs)
- self._callbacks = {}
+ self._functions = {}
self._start_callbacks = {}
self._adapter = self.adapter_class()
+ self._function_call_tasks: Set[Tuple[asyncio.Task, str, str]] = set()
+
+ self._register_event_handler("on_completion_timeout")
def get_llm_adapter(self) -> BaseLLMAdapter:
return self._adapter
def create_context_aggregator(
- self, context: OpenAILLMContext, *, assistant_expect_stripped_words: bool = True
+ self,
+ context: OpenAILLMContext,
+ *,
+ user_kwargs: Mapping[str, Any] = {},
+ assistant_kwargs: Mapping[str, Any] = {},
) -> Any:
pass
- self._register_event_handler("on_completion_timeout")
+ async def process_frame(self, frame: Frame, direction: FrameDirection):
+ await super().process_frame(frame, direction)
- # TODO-CB: callback function type
- def register_function(self, function_name: Optional[str], callback, start_callback=None):
+ if isinstance(frame, StartInterruptionFrame):
+ await self._handle_interruptions(frame)
+
+ async def _handle_interruptions(self, frame: StartInterruptionFrame):
+ for function_name, entry in self._functions.items():
+ if entry.cancel_on_interruption:
+ await self._cancel_function_call(function_name)
+
+ def register_function(
+ self,
+ function_name: Optional[str],
+ callback: Any,
+ start_callback=None,
+ *,
+ cancel_on_interruption: bool = False,
+ ):
# Registering a function with the function_name set to None will run that callback
# for all functions
- self._callbacks[function_name] = callback
- # QUESTION FOR CB: maybe this isn't needed anymore?
+ self._functions[function_name] = FunctionEntry(
+ function_name=function_name,
+ callback=callback,
+ cancel_on_interruption=cancel_on_interruption,
+ )
+
+ # Start callbacks are now deprecated.
if start_callback:
+ import warnings
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("always")
+ warnings.warn(
+ "Parameter 'start_callback' is deprecated, just put your code on top of the actual function call instead.",
+ DeprecationWarning,
+ )
+
self._start_callbacks[function_name] = start_callback
def unregister_function(self, function_name: Optional[str]):
- del self._callbacks[function_name]
+ del self._functions[function_name]
if self._start_callbacks[function_name]:
del self._start_callbacks[function_name]
def has_function(self, function_name: str):
- if None in self._callbacks.keys():
+ if None in self._functions.keys():
return True
- return function_name in self._callbacks.keys()
+ return function_name in self._functions.keys()
async def call_function(
self,
@@ -186,36 +235,144 @@ class LLMService(AIService):
function_name: str,
arguments: str,
run_llm: bool = True,
- ) -> None:
- f = None
- if function_name in self._callbacks.keys():
- f = self._callbacks[function_name]
- elif None in self._callbacks.keys():
- f = self._callbacks[None]
- else:
- return None
- await self.call_start_function(context, function_name)
- await context.call_function(
- f,
- function_name=function_name,
- tool_call_id=tool_call_id,
- arguments=arguments,
- llm=self,
- run_llm=run_llm,
+ ):
+ if not function_name in self._functions.keys() and not None in self._functions.keys():
+ return
+
+ task = self.create_task(
+ self._run_function_call(context, tool_call_id, function_name, arguments, run_llm)
)
- # QUESTION FOR CB: maybe this isn't needed anymore?
+ self._function_call_tasks.add((task, tool_call_id, function_name))
+
+ task.add_done_callback(self._function_call_task_finished)
+
async def call_start_function(self, context: OpenAILLMContext, function_name: str):
if function_name in self._start_callbacks.keys():
await self._start_callbacks[function_name](function_name, self, context)
elif None in self._start_callbacks.keys():
return await self._start_callbacks[None](function_name, self, context)
- async def request_image_frame(self, user_id: str, *, text_content: Optional[str] = None):
+ async def request_image_frame(
+ self,
+ user_id: str,
+ *,
+ function_name: Optional[str] = None,
+ tool_call_id: Optional[str] = None,
+ text_content: Optional[str] = None,
+ ):
await self.push_frame(
- UserImageRequestFrame(user_id=user_id, context=text_content), FrameDirection.UPSTREAM
+ UserImageRequestFrame(
+ user_id=user_id,
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ context=text_content,
+ ),
+ FrameDirection.UPSTREAM,
)
+ async def _run_function_call(
+ self,
+ context: OpenAILLMContext,
+ tool_call_id: str,
+ function_name: str,
+ arguments: str,
+ run_llm: bool = True,
+ ):
+ if function_name in self._functions.keys():
+ entry = self._functions[function_name]
+ elif None in self._functions.keys():
+ entry = self._functions[None]
+ else:
+ return
+
+ logger.debug(
+ f"{self} Calling function [{function_name}:{tool_call_id}] with arguments {arguments}"
+ )
+
+ # NOTE(aleix): This needs to be removed after we remove the deprecation.
+ await self.call_start_function(context, function_name)
+
+ # Push a SystemFrame downstream. This frame will let our assistant context aggregator
+ # know that we are in the middle of a function call. Some contexts/aggregators may
+ # not need this. But some definitely do (Anthropic, for example).
+ # Also push a SystemFrame upstream for use by other processors, like STTMuteFilter.
+ progress_frame_downstream = FunctionCallInProgressFrame(
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ arguments=arguments,
+ cancel_on_interruption=entry.cancel_on_interruption,
+ )
+ progress_frame_upstream = FunctionCallInProgressFrame(
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ arguments=arguments,
+ cancel_on_interruption=entry.cancel_on_interruption,
+ )
+
+ # Push frame both downstream and upstream
+ await self.push_frame(progress_frame_downstream, FrameDirection.DOWNSTREAM)
+ await self.push_frame(progress_frame_upstream, FrameDirection.UPSTREAM)
+
+ # Define a callback function that pushes a FunctionCallResultFrame upstream & downstream.
+ async def function_call_result_callback(result, *, properties=None):
+ result_frame_downstream = FunctionCallResultFrame(
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ arguments=arguments,
+ result=result,
+ properties=properties,
+ )
+ result_frame_upstream = FunctionCallResultFrame(
+ function_name=function_name,
+ tool_call_id=tool_call_id,
+ arguments=arguments,
+ result=result,
+ properties=properties,
+ )
+
+ await self.push_frame(result_frame_downstream, FrameDirection.DOWNSTREAM)
+ await self.push_frame(result_frame_upstream, FrameDirection.UPSTREAM)
+
+ await entry.callback(
+ function_name, tool_call_id, arguments, self, context, function_call_result_callback
+ )
+
+ async def _cancel_function_call(self, function_name: str):
+ cancelled_tasks = set()
+ for task, tool_call_id, name in self._function_call_tasks:
+ if name == function_name:
+ # We remove the callback because we are going to cancel the task
+ # now, otherwise we will be removing it from the set while we
+ # are iterating.
+ task.remove_done_callback(self._function_call_task_finished)
+
+ logger.debug(f"{self} Cancelling function call [{name}:{tool_call_id}]...")
+
+ await self.cancel_task(task)
+
+ frame = FunctionCallCancelFrame(
+ function_name=function_name, tool_call_id=tool_call_id
+ )
+ await self.push_frame(frame)
+
+ logger.debug(f"{self} Function call [{name}:{tool_call_id}] has been cancelled")
+
+ cancelled_tasks.add(task)
+
+ # Remove all cancelled tasks from our set.
+ for task in cancelled_tasks:
+ self._function_call_task_finished(task)
+
+ def _function_call_task_finished(self, task: asyncio.Task):
+ tuple_to_remove = next((t for t in self._function_call_tasks if t[0] == task), None)
+ if tuple_to_remove:
+ self._function_call_tasks.discard(tuple_to_remove)
+ # The task is finished so this should exit immediately. We need to
+ # do this because otherwise the task manager would have a dangling
+ # task if we don't remove it.
+ asyncio.run_coroutine_threadsafe(self.wait_for_task(task), self.get_event_loop())
+
class TTSService(AIService):
def __init__(
@@ -237,6 +394,10 @@ class TTSService(AIService):
pause_frame_processing: bool = False,
# TTS output sample rate
sample_rate: Optional[int] = None,
+ # Text aggregator to aggregate incoming tokens and decide when to push to the TTS.
+ text_aggregator: Optional[BaseTextAggregator] = None,
+ # Text filter executed after text has been aggregated.
+ text_filters: Sequence[BaseTextFilter] = [],
text_filter: Optional[BaseTextFilter] = None,
**kwargs,
):
@@ -252,12 +413,22 @@ class TTSService(AIService):
self._sample_rate = 0
self._voice_id: str = ""
self._settings: Dict[str, Any] = {}
- self._text_filter: Optional[BaseTextFilter] = text_filter
+ self._text_aggregator: BaseTextAggregator = text_aggregator or SimpleTextAggregator()
+ self._text_filters: Sequence[BaseTextFilter] = text_filters
+ if text_filter:
+ import warnings
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("always")
+ warnings.warn(
+ "Parameter 'text_filter' is deprecated, use 'text_filters' instead.",
+ DeprecationWarning,
+ )
+ self._text_filters = [text_filter]
self._stop_frame_task: Optional[asyncio.Task] = None
self._stop_frame_queue: asyncio.Queue = asyncio.Queue()
- self._current_sentence: str = ""
self._processing_text: bool = False
@property
@@ -270,10 +441,6 @@ class TTSService(AIService):
def set_voice(self, voice: str):
self._voice_id = voice
- @abstractmethod
- async def flush_audio(self):
- pass
-
# Converts the text to audio.
@abstractmethod
async def run_tts(self, text: str) -> AsyncGenerator[Frame, None]:
@@ -285,6 +452,9 @@ class TTSService(AIService):
async def update_setting(self, key: str, value: Any):
pass
+ async def flush_audio(self):
+ pass
+
async def start(self, frame: StartFrame):
await super().start(frame)
self._sample_rate = self._init_sample_rate or frame.audio_out_sample_rate
@@ -314,8 +484,9 @@ class TTSService(AIService):
self.set_model_name(value)
elif key == "voice":
self.set_voice(value)
- elif key == "text_filter" and self._text_filter:
- self._text_filter.update_settings(value)
+ elif key == "text_filter":
+ for filter in self._text_filters:
+ filter.update_settings(value)
else:
logger.warning(f"Unknown setting for TTS service: {key}")
@@ -340,8 +511,8 @@ class TTSService(AIService):
# pause to avoid audio overlapping.
await self._maybe_pause_frame_processing()
- sentence = self._current_sentence
- self._current_sentence = ""
+ sentence = self._text_aggregator.text
+ self._text_aggregator.reset()
self._processing_text = False
await self._push_tts_frames(sentence)
if isinstance(frame, LLMFullResponseEndFrame):
@@ -350,12 +521,14 @@ class TTSService(AIService):
else:
await self.push_frame(frame, direction)
elif isinstance(frame, TTSSpeakFrame):
+ # Store if we were processing text or not so we can set it back.
+ processing_text = self._processing_text
await self._push_tts_frames(frame.text)
# We pause processing incoming frames because we are sending data to
# the TTS. We pause to avoid audio overlapping.
await self._maybe_pause_frame_processing()
await self.flush_audio()
- self._processing_text = False
+ self._processing_text = processing_text
elif isinstance(frame, TTSUpdateSettingsFrame):
await self._update_settings(frame.settings)
elif isinstance(frame, BotStoppedSpeakingFrame):
@@ -386,10 +559,10 @@ class TTSService(AIService):
await self._stop_frame_queue.put(frame)
async def _handle_interruption(self, frame: StartInterruptionFrame, direction: FrameDirection):
- self._current_sentence = ""
self._processing_text = False
- if self._text_filter:
- self._text_filter.handle_interruption()
+ self._text_aggregator.handle_interruption()
+ for filter in self._text_filters:
+ filter.handle_interruption()
async def _maybe_pause_frame_processing(self):
if self._processing_text and self._pause_frame_processing:
@@ -404,11 +577,7 @@ class TTSService(AIService):
if not self._aggregate_sentences:
text = frame.text
else:
- self._current_sentence += frame.text
- eos_end_marker = match_endofsentence(self._current_sentence)
- if eos_end_marker:
- text = self._current_sentence[:eos_end_marker]
- self._current_sentence = self._current_sentence[eos_end_marker:]
+ text = self._text_aggregator.aggregate(frame.text)
if text:
await self._push_tts_frames(text)
@@ -428,11 +597,16 @@ class TTSService(AIService):
self._processing_text = True
await self.start_processing_metrics()
- if self._text_filter:
- self._text_filter.reset_interruption()
- text = self._text_filter.filter(text)
+
+ # Process all filter.
+ for filter in self._text_filters:
+ filter.reset_interruption()
+ text = filter.filter(text)
+
await self.process_generator(self.run_tts(text))
+
await self.stop_processing_metrics()
+
if self._push_text_frames:
# We send the original text after the audio. This way, if we are
# interrupted, the text is not added to the assistant context.
@@ -533,11 +707,25 @@ class WordTTSService(TTSService):
class WebsocketTTSService(TTSService, WebsocketService):
- """This is a base class for websocket-based TTS services."""
+ """This is a base class for websocket-based TTS services.
- def __init__(self, **kwargs):
+ If an error occurs with the websocket, an "on_connection_error" event will
+ be triggered:
+
+ @tts.event_handler("on_connection_error")
+ async def on_connection_error(tts: TTSService, error: str):
+ ...
+
+ """
+
+ def __init__(self, *, reconnect_on_error: bool = True, **kwargs):
TTSService.__init__(self, **kwargs)
- WebsocketService.__init__(self)
+ WebsocketService.__init__(self, reconnect_on_error=reconnect_on_error, **kwargs)
+ self._register_event_handler("on_connection_error")
+
+ async def _report_error(self, error: ErrorFrame):
+ await self._call_event_handler("on_connection_error", error.error)
+ await self.push_error(error)
class InterruptibleTTSService(WebsocketTTSService):
@@ -574,11 +762,23 @@ class WebsocketWordTTSService(WordTTSService, WebsocketService):
"""This is a base class for websocket-based TTS services that support word
timestamps.
+ If an error occurs with the websocket a "on_connection_error" event will be
+ triggered:
+
+ @tts.event_handler("on_connection_error")
+ async def on_connection_error(tts: TTSService, error: str):
+ ...
+
"""
- def __init__(self, **kwargs):
+ def __init__(self, *, reconnect_on_error: bool = True, **kwargs):
WordTTSService.__init__(self, **kwargs)
- WebsocketService.__init__(self)
+ WebsocketService.__init__(self, reconnect_on_error=reconnect_on_error, **kwargs)
+ self._register_event_handler("on_connection_error")
+
+ async def _report_error(self, error: ErrorFrame):
+ await self._call_event_handler("on_connection_error", error.error)
+ await self.push_error(error)
class InterruptibleWordTTSService(WebsocketWordTTSService):
@@ -762,11 +962,9 @@ class STTService(AIService):
def sample_rate(self) -> int:
return self._sample_rate
- @abstractmethod
async def set_model(self, model: str):
self.set_model_name(model)
- @abstractmethod
async def set_language(self, language: Language):
pass
@@ -797,8 +995,6 @@ class STTService(AIService):
return
await self.process_generator(self.run_stt(frame.audio))
- if self._audio_passthrough:
- await self.push_frame(frame, direction)
async def process_frame(self, frame: Frame, direction: FrameDirection):
"""Processes a frame of audio data, either buffering or transcribing it."""
@@ -809,6 +1005,8 @@ class STTService(AIService):
# push a TextFrame. We also push audio downstream in case someone
# else needs it.
await self.process_audio_frame(frame, direction)
+ if self._audio_passthrough:
+ await self.push_frame(frame, direction)
elif isinstance(frame, STTUpdateSettingsFrame):
await self._update_settings(frame.settings)
elif isinstance(frame, STTMuteFrame):
@@ -819,79 +1017,64 @@ class STTService(AIService):
class SegmentedSTTService(STTService):
- """SegmentedSTTService is an STTService that will detect speech and will run
- speech-to-text on speech segments only, instead of a continous stream.
+ """SegmentedSTTService is an STTService that uses VAD events to detect
+ speech and will run speech-to-text on speech segments only, instead of a
+ continous stream. Since it uses VAD it means that VAD needs to be enabled in
+ the pipeline.
+
+ This service always keeps a small audio buffer to take into account that VAD
+ events are delayed from when the user speech really starts.
"""
- def __init__(
- self,
- *,
- min_volume: float = 0.6,
- max_silence_secs: float = 0.3,
- max_buffer_secs: float = 1.5,
- sample_rate: Optional[int] = None,
- **kwargs,
- ):
+ def __init__(self, *, sample_rate: Optional[int] = None, **kwargs):
super().__init__(sample_rate=sample_rate, **kwargs)
- self._min_volume = min_volume
- self._max_silence_secs = max_silence_secs
- self._max_buffer_secs = max_buffer_secs
self._content = None
self._wave = None
- self._silence_num_frames = 0
- # Volume exponential smoothing
- self._smoothing_factor = 0.2
- self._prev_volume = 0
-
- async def process_audio_frame(self, frame: AudioRawFrame, direction: FrameDirection):
- # Try to filter out empty background noise
- volume = self._get_smoothed_volume(frame)
- if volume >= self._min_volume:
- # If volume is high enough, write new data to wave file
- self._wave.writeframes(frame.audio)
- self._silence_num_frames = 0
- else:
- self._silence_num_frames += frame.num_frames
- self._prev_volume = volume
-
- # If buffer is not empty and we have enough data or there's been a long
- # silence, transcribe the audio gathered so far.
- silence_secs = self._silence_num_frames / self.sample_rate
- buffer_secs = self._wave.getnframes() / self.sample_rate
- if self._content.tell() > 0 and (
- buffer_secs > self._max_buffer_secs or silence_secs > self._max_silence_secs
- ):
- self._silence_num_frames = 0
- self._wave.close()
- self._content.seek(0)
- await self.process_generator(self.run_stt(self._content.read()))
- (self._content, self._wave) = self._new_wave()
+ self._audio_buffer = bytearray()
+ self._audio_buffer_size_1s = 0
+ self._user_speaking = False
async def start(self, frame: StartFrame):
await super().start(frame)
- if not self._wave:
- (self._content, self._wave) = self._new_wave()
+ self._audio_buffer_size_1s = self.sample_rate * 2
- async def stop(self, frame: EndFrame):
- await super().stop(frame)
- self._wave.close()
+ async def process_frame(self, frame: Frame, direction: FrameDirection):
+ await super().process_frame(frame, direction)
- async def cancel(self, frame: CancelFrame):
- await super().cancel(frame)
- self._wave.close()
+ if isinstance(frame, UserStartedSpeakingFrame):
+ await self._handle_user_started_speaking(frame)
+ elif isinstance(frame, UserStoppedSpeakingFrame):
+ await self._handle_user_stopped_speaking(frame)
+
+ async def _handle_user_started_speaking(self, frame: UserStartedSpeakingFrame):
+ self._user_speaking = True
+
+ async def _handle_user_stopped_speaking(self, frame: UserStoppedSpeakingFrame):
+ self._user_speaking = False
- def _new_wave(self):
content = io.BytesIO()
- ww = wave.open(content, "wb")
- ww.setsampwidth(2)
- ww.setnchannels(1)
- ww.setframerate(self.sample_rate)
- return (content, ww)
+ wav = wave.open(content, "wb")
+ wav.setsampwidth(2)
+ wav.setnchannels(1)
+ wav.setframerate(self.sample_rate)
+ wav.writeframes(self._audio_buffer)
+ wav.close()
+ content.seek(0)
- def _get_smoothed_volume(self, frame: AudioRawFrame) -> float:
- volume = calculate_audio_volume(frame.audio, frame.sample_rate)
- return exp_smoothing(volume, self._prev_volume, self._smoothing_factor)
+ await self.process_generator(self.run_stt(content.read()))
+
+ # Start clean.
+ self._audio_buffer.clear()
+
+ async def process_audio_frame(self, frame: AudioRawFrame, direction: FrameDirection):
+ # If the user is speaking the audio buffer will keep growin.
+ self._audio_buffer += frame.audio
+
+ # If the user is not speaking we keep just a little bit of audio.
+ if not self._user_speaking and len(self._audio_buffer) > self._audio_buffer_size_1s:
+ discarded = len(self._audio_buffer) - self._audio_buffer_size_1s
+ self._audio_buffer = self._audio_buffer[discarded:]
class ImageGenService(AIService):
diff --git a/src/pipecat/services/anthropic.py b/src/pipecat/services/anthropic.py
index 10a2ab7b7..6a95d04e2 100644
--- a/src/pipecat/services/anthropic.py
+++ b/src/pipecat/services/anthropic.py
@@ -21,19 +21,16 @@ from pydantic import BaseModel, Field
from pipecat.adapters.services.anthropic_adapter import AnthropicLLMAdapter
from pipecat.frames.frames import (
Frame,
+ FunctionCallCancelFrame,
FunctionCallInProgressFrame,
FunctionCallResultFrame,
- FunctionCallResultProperties,
LLMEnablePromptCachingFrame,
LLMFullResponseEndFrame,
LLMFullResponseStartFrame,
LLMMessagesFrame,
LLMTextFrame,
LLMUpdateSettingsFrame,
- OpenAILLMContextAssistantTimestampFrame,
- StartInterruptionFrame,
UserImageRawFrame,
- UserImageRequestFrame,
VisionImageRawFrame,
)
from pipecat.metrics.metrics import LLMTokenUsage
@@ -47,7 +44,6 @@ from pipecat.processors.aggregators.openai_llm_context import (
)
from pipecat.processors.frame_processor import FrameDirection
from pipecat.services.ai_services import LLMService
-from pipecat.utils.time import time_now_iso8601
try:
from anthropic import NOT_GIVEN, AsyncAnthropic, NotGiven
@@ -60,13 +56,6 @@ except ModuleNotFoundError as e:
raise Exception(f"Missing module: {e}")
-# internal use only -- todo: refactor
-@dataclass
-class AnthropicImageMessageFrame(Frame):
- user_image_raw_frame: UserImageRawFrame
- text: Optional[str] = None
-
-
@dataclass
class AnthropicContextAggregatorPair:
_user: "AnthropicUserContextAggregator"
@@ -683,42 +672,7 @@ class AnthropicLLMContext(OpenAILLMContext):
class AnthropicUserContextAggregator(LLMUserContextAggregator):
- def __init__(self, context: OpenAILLMContext | AnthropicLLMContext, **kwargs):
- super().__init__(context=context, **kwargs)
-
- async def process_frame(self, frame, direction):
- await super().process_frame(frame, direction)
- # Our parent method has already called push_frame(). So we can't interrupt the
- # flow here and we don't need to call push_frame() ourselves. Possibly something
- # to talk through (tagging @aleix). At some point we might need to refactor these
- # context aggregators.
- try:
- if isinstance(frame, UserImageRequestFrame):
- # The LLM sends a UserImageRequestFrame upstream. Cache any context provided with
- # that frame so we can use it when we assemble the image message in the assistant
- # context aggregator.
- if frame.context:
- if isinstance(frame.context, str):
- self._context._user_image_request_context[frame.user_id] = frame.context
- else:
- logger.error(
- f"Unexpected UserImageRequestFrame context type: {type(frame.context)}"
- )
- del self._context._user_image_request_context[frame.user_id]
- else:
- if frame.user_id in self._context._user_image_request_context:
- del self._context._user_image_request_context[frame.user_id]
- elif isinstance(frame, UserImageRawFrame):
- # Push a new AnthropicImageMessageFrame with the text context we cached
- # downstream to be handled by our assistant context aggregator. This is
- # necessary so that we add the message to the context in the right order.
- text = self._context._user_image_request_context.get(frame.user_id) or ""
- if text:
- del self._context._user_image_request_context[frame.user_id]
- frame = AnthropicImageMessageFrame(user_image_raw_frame=frame, text=text)
- await self.push_frame(frame)
- except Exception as e:
- logger.error(f"Error processing frame: {e}")
+ pass
#
@@ -732,112 +686,64 @@ class AnthropicUserContextAggregator(LLMUserContextAggregator):
class AnthropicAssistantContextAggregator(LLMAssistantContextAggregator):
- def __init__(self, context: OpenAILLMContext | AnthropicLLMContext, **kwargs):
- super().__init__(context=context, **kwargs)
- self._function_call_in_progress = None
- self._function_call_result = None
- self._pending_image_frame_message = None
+ async def handle_function_call_in_progress(self, frame: FunctionCallInProgressFrame):
+ assistant_message = {"role": "assistant", "content": []}
+ assistant_message["content"].append(
+ {
+ "type": "tool_use",
+ "id": frame.tool_call_id,
+ "name": frame.function_name,
+ "input": frame.arguments,
+ }
+ )
+ self._context.add_message(assistant_message)
+ self._context.add_message(
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": frame.tool_call_id,
+ "content": "IN_PROGRESS",
+ }
+ ],
+ }
+ )
- async def process_frame(self, frame, direction):
- await super().process_frame(frame, direction)
- # See note above about not calling push_frame() here.
- if isinstance(frame, StartInterruptionFrame):
- self._function_call_in_progress = None
- self._function_call_finished = None
- elif isinstance(frame, FunctionCallInProgressFrame):
- self._function_call_in_progress = frame
- elif isinstance(frame, FunctionCallResultFrame):
- if (
- self._function_call_in_progress
- and self._function_call_in_progress.tool_call_id == frame.tool_call_id
- ):
- self._function_call_in_progress = None
- self._function_call_result = frame
- await self.push_aggregation()
- else:
- logger.warning(
- "FunctionCallResultFrame tool_call_id != InProgressFrame tool_call_id"
- )
- self._function_call_in_progress = None
- self._function_call_result = None
- elif isinstance(frame, AnthropicImageMessageFrame):
- self._pending_image_frame_message = frame
- await self.push_aggregation()
+ async def handle_function_call_result(self, frame: FunctionCallResultFrame):
+ if frame.result:
+ result = json.dumps(frame.result)
+ await self._update_function_call_result(frame.function_name, frame.tool_call_id, result)
+ else:
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, "COMPLETED"
+ )
- async def push_aggregation(self):
- if not (
- self._aggregation or self._function_call_result or self._pending_image_frame_message
- ):
- return
+ async def handle_function_call_cancel(self, frame: FunctionCallCancelFrame):
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, "CANCELLED"
+ )
- run_llm = False
- properties: Optional[FunctionCallResultProperties] = None
+ async def _update_function_call_result(
+ self, function_name: str, tool_call_id: str, result: str
+ ):
+ for message in self._context.messages:
+ if message["role"] == "user":
+ for content in message["content"]:
+ if (
+ isinstance(content, dict)
+ and content["type"] == "tool_result"
+ and content["tool_use_id"] == tool_call_id
+ ):
+ content["content"] = result
- aggregation = self._aggregation.strip()
- self.reset()
-
- try:
- if aggregation:
- self._context.add_message({"role": "assistant", "content": aggregation})
-
- if self._function_call_result:
- frame = self._function_call_result
- properties = frame.properties
- self._function_call_result = None
- if frame.result:
- assistant_message = {"role": "assistant", "content": []}
- assistant_message["content"].append(
- {
- "type": "tool_use",
- "id": frame.tool_call_id,
- "name": frame.function_name,
- "input": frame.arguments,
- }
- )
- self._context.add_message(assistant_message)
- self._context.add_message(
- {
- "role": "user",
- "content": [
- {
- "type": "tool_result",
- "tool_use_id": frame.tool_call_id,
- "content": json.dumps(frame.result),
- }
- ],
- }
- )
- if properties and properties.run_llm is not None:
- # If the tool call result has a run_llm property, use it
- run_llm = properties.run_llm
- else:
- # Default behavior
- run_llm = True
-
- if self._pending_image_frame_message:
- frame = self._pending_image_frame_message
- self._pending_image_frame_message = None
- self._context.add_image_frame_message(
- format=frame.user_image_raw_frame.format,
- size=frame.user_image_raw_frame.size,
- image=frame.user_image_raw_frame.image,
- text=frame.text,
- )
- run_llm = True
-
- if run_llm:
- await self.push_context_frame(FrameDirection.UPSTREAM)
-
- # Emit the on_context_updated callback once the function call result is added to the context
- if properties and properties.on_context_updated is not None:
- await properties.on_context_updated()
-
- # Push context frame
- await self.push_context_frame()
-
- # Push timestamp frame with current time
- timestamp_frame = OpenAILLMContextAssistantTimestampFrame(timestamp=time_now_iso8601())
- await self.push_frame(timestamp_frame)
-
- except Exception as e:
- logger.error(f"Error processing frame: {e}")
+ async def handle_user_image_frame(self, frame: UserImageRawFrame):
+ await self._update_function_call_result(
+ frame.request.function_name, frame.request.tool_call_id, "COMPLETED"
+ )
+ self._context.add_image_frame_message(
+ format=frame.format,
+ size=frame.size,
+ image=frame.image,
+ text=frame.request.context,
+ )
diff --git a/src/pipecat/services/aws.py b/src/pipecat/services/aws.py
index b83df2f77..4c0417d72 100644
--- a/src/pipecat/services/aws.py
+++ b/src/pipecat/services/aws.py
@@ -248,16 +248,3 @@ class PollyTTSService(TTSService):
finally:
yield TTSStoppedFrame()
-
-
-class AWSTTSService(PollyTTSService):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
-
- import warnings
-
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "'AWSTTSService' is deprecated, use 'PollyTTSService' instead.", DeprecationWarning
- )
diff --git a/src/pipecat/services/azure.py b/src/pipecat/services/azure.py
index c59cd29c2..9df1a8ef1 100644
--- a/src/pipecat/services/azure.py
+++ b/src/pipecat/services/azure.py
@@ -686,8 +686,11 @@ class AzureSTTService(STTService):
):
super().__init__(sample_rate=sample_rate, **kwargs)
- self._speech_config = SpeechConfig(subscription=api_key, region=region)
- self._speech_config.speech_recognition_language = language
+ self._speech_config = SpeechConfig(
+ subscription=api_key,
+ region=region,
+ speech_recognition_language=language_to_azure_language(language),
+ )
self._audio_stream = None
self._speech_recognizer = None
diff --git a/src/pipecat/services/cartesia.py b/src/pipecat/services/cartesia.py
index 8b7f57c63..11796464d 100644
--- a/src/pipecat/services/cartesia.py
+++ b/src/pipecat/services/cartesia.py
@@ -26,6 +26,8 @@ from pipecat.frames.frames import (
from pipecat.processors.frame_processor import FrameDirection
from pipecat.services.ai_services import AudioContextWordTTSService, TTSService
from pipecat.transcriptions.language import Language
+from pipecat.utils.text.base_text_aggregator import BaseTextAggregator
+from pipecat.utils.text.skip_tags_aggregator import SkipTagsAggregator
# See .env.example for Cartesia configuration needed
try:
@@ -89,6 +91,7 @@ class CartesiaTTSService(AudioContextWordTTSService):
encoding: str = "pcm_s16le",
container: str = "raw",
params: InputParams = InputParams(),
+ text_aggregator: Optional[BaseTextAggregator] = None,
**kwargs,
):
# Aggregating sentences still gives cleaner-sounding results and fewer
@@ -106,6 +109,7 @@ class CartesiaTTSService(AudioContextWordTTSService):
push_text_frames=False,
pause_frame_processing=True,
sample_rate=sample_rate,
+ text_aggregator=text_aggregator or SkipTagsAggregator([("", "")]),
**kwargs,
)
@@ -183,7 +187,7 @@ class CartesiaTTSService(AudioContextWordTTSService):
async def _connect(self):
await self._connect_websocket()
if not self._receive_task:
- self._receive_task = self.create_task(self._receive_task_handler(self.push_error))
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
async def _disconnect(self):
if self._receive_task:
@@ -203,6 +207,7 @@ class CartesiaTTSService(AudioContextWordTTSService):
except Exception as e:
logger.error(f"{self} initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
async def _disconnect_websocket(self):
try:
diff --git a/src/pipecat/services/elevenlabs.py b/src/pipecat/services/elevenlabs.py
index c41e5de02..68c71a144 100644
--- a/src/pipecat/services/elevenlabs.py
+++ b/src/pipecat/services/elevenlabs.py
@@ -102,6 +102,8 @@ def language_to_elevenlabs_language(language: Language) -> Optional[str]:
def output_format_from_sample_rate(sample_rate: int) -> str:
match sample_rate:
+ case 8000:
+ return "pcm_8000"
case 16000:
return "pcm_16000"
case 22050:
@@ -113,7 +115,7 @@ def output_format_from_sample_rate(sample_rate: int) -> str:
logger.warning(
f"ElevenLabsTTSService: No output format available for {sample_rate} sample rate"
)
- return "pcm_16000"
+ return "pcm_24000"
def build_elevenlabs_voice_settings(
@@ -309,7 +311,7 @@ class ElevenLabsTTSService(InterruptibleWordTTSService):
await self._connect_websocket()
if not self._receive_task:
- self._receive_task = self.create_task(self._receive_task_handler(self.push_error))
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
if not self._keepalive_task:
self._keepalive_task = self.create_task(self._keepalive_task_handler())
@@ -364,6 +366,7 @@ class ElevenLabsTTSService(InterruptibleWordTTSService):
except Exception as e:
logger.error(f"{self} initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
async def _disconnect_websocket(self):
try:
diff --git a/src/pipecat/services/fal.py b/src/pipecat/services/fal.py
index 7173861ab..cb39da75f 100644
--- a/src/pipecat/services/fal.py
+++ b/src/pipecat/services/fal.py
@@ -7,6 +7,7 @@
import asyncio
import io
import os
+import wave
from typing import AsyncGenerator, Dict, Optional, Union
import aiohttp
@@ -14,8 +15,10 @@ from loguru import logger
from PIL import Image
from pydantic import BaseModel
-from pipecat.frames.frames import ErrorFrame, Frame, URLImageRawFrame
-from pipecat.services.ai_services import ImageGenService
+from pipecat.frames.frames import ErrorFrame, Frame, TranscriptionFrame, URLImageRawFrame
+from pipecat.services.ai_services import ImageGenService, SegmentedSTTService
+from pipecat.transcriptions.language import Language
+from pipecat.utils.time import time_now_iso8601
try:
import fal_client
@@ -27,6 +30,120 @@ except ModuleNotFoundError as e:
raise Exception(f"Missing module: {e}")
+def language_to_fal_language(language: Language) -> Optional[str]:
+ """Language support for Fal's Wizper API."""
+ BASE_LANGUAGES = {
+ Language.AF: "af",
+ Language.AM: "am",
+ Language.AR: "ar",
+ Language.AS: "as",
+ Language.AZ: "az",
+ Language.BA: "ba",
+ Language.BE: "be",
+ Language.BG: "bg",
+ Language.BN: "bn",
+ Language.BO: "bo",
+ Language.BR: "br",
+ Language.BS: "bs",
+ Language.CA: "ca",
+ Language.CS: "cs",
+ Language.CY: "cy",
+ Language.DA: "da",
+ Language.DE: "de",
+ Language.EL: "el",
+ Language.EN: "en",
+ Language.ES: "es",
+ Language.ET: "et",
+ Language.EU: "eu",
+ Language.FA: "fa",
+ Language.FI: "fi",
+ Language.FO: "fo",
+ Language.FR: "fr",
+ Language.GL: "gl",
+ Language.GU: "gu",
+ Language.HA: "ha",
+ Language.HE: "he",
+ Language.HI: "hi",
+ Language.HR: "hr",
+ Language.HT: "ht",
+ Language.HU: "hu",
+ Language.HY: "hy",
+ Language.ID: "id",
+ Language.IS: "is",
+ Language.IT: "it",
+ Language.JA: "ja",
+ Language.JW: "jw",
+ Language.KA: "ka",
+ Language.KK: "kk",
+ Language.KM: "km",
+ Language.KN: "kn",
+ Language.KO: "ko",
+ Language.LA: "la",
+ Language.LB: "lb",
+ Language.LN: "ln",
+ Language.LO: "lo",
+ Language.LT: "lt",
+ Language.LV: "lv",
+ Language.MG: "mg",
+ Language.MI: "mi",
+ Language.MK: "mk",
+ Language.ML: "ml",
+ Language.MN: "mn",
+ Language.MR: "mr",
+ Language.MS: "ms",
+ Language.MT: "mt",
+ Language.MY: "my",
+ Language.NE: "ne",
+ Language.NL: "nl",
+ Language.NN: "nn",
+ Language.NO: "no",
+ Language.OC: "oc",
+ Language.PA: "pa",
+ Language.PL: "pl",
+ Language.PS: "ps",
+ Language.PT: "pt",
+ Language.RO: "ro",
+ Language.RU: "ru",
+ Language.SA: "sa",
+ Language.SD: "sd",
+ Language.SI: "si",
+ Language.SK: "sk",
+ Language.SL: "sl",
+ Language.SN: "sn",
+ Language.SO: "so",
+ Language.SQ: "sq",
+ Language.SR: "sr",
+ Language.SU: "su",
+ Language.SV: "sv",
+ Language.SW: "sw",
+ Language.TA: "ta",
+ Language.TE: "te",
+ Language.TG: "tg",
+ Language.TH: "th",
+ Language.TK: "tk",
+ Language.TL: "tl",
+ Language.TR: "tr",
+ Language.TT: "tt",
+ Language.UK: "uk",
+ Language.UR: "ur",
+ Language.UZ: "uz",
+ Language.VI: "vi",
+ Language.YI: "yi",
+ Language.YO: "yo",
+ Language.ZH: "zh",
+ }
+
+ result = BASE_LANGUAGES.get(language)
+
+ # If not found in base languages, try to find the base language from a variant
+ if not result:
+ lang_str = str(language.value)
+ base_code = lang_str.split("-")[0].lower()
+ result = base_code if base_code in BASE_LANGUAGES.values() else None
+
+ return result
+
+
class FalImageGenService(ImageGenService):
class InputParams(BaseModel):
seed: Optional[int] = None
@@ -84,3 +201,109 @@ class FalImageGenService(ImageGenService):
frame = URLImageRawFrame(url=image_url, image=image_bytes, size=size, format=format)
yield frame
+
+
+class FalSTTService(SegmentedSTTService):
+ """Speech-to-text service using Fal's Wizper API.
+
+ This service uses Fal's Wizper API to perform speech-to-text transcription on audio
+ segments. It inherits from SegmentedSTTService to handle audio buffering and speech detection.
+
+ Args:
+ api_key: Fal API key. If not provided, will check FAL_KEY environment variable.
+ sample_rate: Audio sample rate in Hz. If not provided, uses the pipeline's rate.
+ params: Configuration parameters for the Wizper API.
+ **kwargs: Additional arguments passed to SegmentedSTTService.
+ """
+
+ class InputParams(BaseModel):
+ """Configuration parameters for Fal's Wizper API.
+
+ Attributes:
+ language: Language of the audio input. Defaults to English.
+ task: Task to perform ('transcribe' or 'translate'). Defaults to 'transcribe'.
+ chunk_level: Level of chunking ('segment'). Defaults to 'segment'.
+ version: Version of Wizper model to use. Defaults to '3'.
+ """
+
+ language: Optional[Language] = Language.EN
+ task: str = "transcribe"
+ chunk_level: str = "segment"
+ version: str = "3"
+
+ def __init__(
+ self,
+ *,
+ api_key: Optional[str] = None,
+ sample_rate: Optional[int] = None,
+ params: InputParams = InputParams(),
+ **kwargs,
+ ):
+ super().__init__(
+ sample_rate=sample_rate,
+ **kwargs,
+ )
+
+ if api_key:
+ os.environ["FAL_KEY"] = api_key
+ elif "FAL_KEY" not in os.environ:
+ raise ValueError(
+ "FAL_KEY must be provided either through api_key parameter or environment variable"
+ )
+
+ self._fal_client = fal_client.AsyncClient(key=api_key or os.getenv("FAL_KEY"))
+ self._settings = {
+ "task": params.task,
+ "language": self.language_to_service_language(params.language)
+ if params.language
+ else "en",
+ "chunk_level": params.chunk_level,
+ "version": params.version,
+ }
+
+ def can_generate_metrics(self) -> bool:
+ return True
+
+ def language_to_service_language(self, language: Language) -> Optional[str]:
+ return language_to_fal_language(language)
+
+ async def set_language(self, language: Language):
+ logger.info(f"Switching STT language to: [{language}]")
+ self._settings["language"] = self.language_to_service_language(language)
+
+ async def set_model(self, model: str):
+ await super().set_model(model)
+ logger.info(f"Switching STT model to: [{model}]")
+
+ async def run_stt(self, audio: bytes) -> AsyncGenerator[Frame, None]:
+ """Transcribes an audio segment using Fal's Wizper API.
+
+ Args:
+ audio: Raw audio bytes in WAV format (already converted by base class).
+
+ Yields:
+ Frame: TranscriptionFrame containing the transcribed text.
+
+ Note:
+ The audio is already in WAV format from the SegmentedSTTService.
+ Only non-empty transcriptions are yielded.
+ """
+ try:
+ # Send to Fal directly (audio is already in WAV format from base class)
+ data_uri = fal_client.encode(audio, "audio/x-wav")
+ response = await self._fal_client.run(
+ "fal-ai/wizper",
+ arguments={"audio_url": data_uri, **self._settings},
+ )
+
+ if response and "text" in response:
+ text = response["text"].strip()
+ if text: # Only yield non-empty text
+ logger.debug(f"Transcription: [{text}]")
+ yield TranscriptionFrame(
+ text, "", time_now_iso8601(), Language(self._settings["language"])
+ )
+
+ except Exception as e:
+ logger.error(f"Fal Wizper error: {e}")
+ yield ErrorFrame(f"Fal Wizper error: {str(e)}")
diff --git a/src/pipecat/services/fish.py b/src/pipecat/services/fish.py
index 0b2729958..9e6a8b91e 100644
--- a/src/pipecat/services/fish.py
+++ b/src/pipecat/services/fish.py
@@ -107,7 +107,7 @@ class FishAudioTTSService(InterruptibleTTSService):
async def _connect(self):
await self._connect_websocket()
if not self._receive_task:
- self._receive_task = self.create_task(self._receive_task_handler(self.push_error))
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
async def _disconnect(self):
if self._receive_task:
@@ -132,6 +132,7 @@ class FishAudioTTSService(InterruptibleTTSService):
except Exception as e:
logger.error(f"Fish Audio initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
async def _disconnect_websocket(self):
try:
@@ -148,6 +149,14 @@ class FishAudioTTSService(InterruptibleTTSService):
except Exception as e:
logger.error(f"Error closing websocket: {e}")
+ async def flush_audio(self):
+ """Flush any buffered audio by sending a flush event to Fish Audio."""
+ logger.trace(f"{self}: Flushing audio buffers")
+ if not self._websocket:
+ return
+ flush_message = {"event": "flush"}
+ await self._get_websocket().send(ormsgpack.packb(flush_message))
+
def _get_websocket(self):
if self._websocket:
return self._websocket
diff --git a/src/pipecat/services/gemini_multimodal_live/gemini.py b/src/pipecat/services/gemini_multimodal_live/gemini.py
index c2791ab97..965648ada 100644
--- a/src/pipecat/services/gemini_multimodal_live/gemini.py
+++ b/src/pipecat/services/gemini_multimodal_live/gemini.py
@@ -39,6 +39,8 @@ from pipecat.frames.frames import (
TTSAudioRawFrame,
TTSStartedFrame,
TTSStoppedFrame,
+ TTSTextFrame,
+ UserImageRawFrame,
UserStartedSpeakingFrame,
UserStoppedSpeakingFrame,
)
@@ -118,10 +120,10 @@ class GeminiMultimodalLiveUserContextAggregator(OpenAIUserContextAggregator):
class GeminiMultimodalLiveAssistantContextAggregator(OpenAIAssistantContextAggregator):
- async def push_aggregation(self):
- # We don't want to store any images in the context. Revisit this later when the API evolves.
- self._pending_image_frame_message = None
- await super().push_aggregation()
+ async def handle_user_image_frame(self, frame: UserImageRawFrame):
+ # We don't want to store any images in the context. Revisit this later
+ # when the API evolves.
+ pass
@dataclass
@@ -314,6 +316,7 @@ class GeminiMultimodalLiveLLMService(LLMService):
# context.add_message({"role": "assistant", "content": [{"type": "text", "text": text}]})
await self.push_frame(LLMFullResponseStartFrame())
await self.push_frame(LLMTextFrame(text=text))
+ await self.push_frame(TTSTextFrame(text=text))
await self.push_frame(LLMFullResponseEndFrame())
async def _transcribe_audio(self, audio, context):
@@ -341,10 +344,8 @@ class GeminiMultimodalLiveLLMService(LLMService):
async def process_frame(self, frame: Frame, direction: FrameDirection):
await super().process_frame(frame, direction)
- # logger.debug(f"Processing frame: {frame}")
-
if isinstance(frame, TranscriptionFrame):
- pass
+ await self.push_frame(frame, direction)
elif isinstance(frame, OpenAILLMContextFrame):
context: GeminiMultimodalLiveContext = GeminiMultimodalLiveContext.upgrade(
frame.context
@@ -361,31 +362,35 @@ class GeminiMultimodalLiveLLMService(LLMService):
# Support just one tool call per context frame for now
tool_result_message = context.messages[-1]
await self._tool_result(tool_result_message)
-
elif isinstance(frame, InputAudioRawFrame):
await self._send_user_audio(frame)
+ await self.push_frame(frame, direction)
elif isinstance(frame, InputImageRawFrame):
await self._send_user_video(frame)
+ await self.push_frame(frame, direction)
elif isinstance(frame, StartInterruptionFrame):
await self._handle_interruption()
+ await self.push_frame(frame, direction)
elif isinstance(frame, UserStartedSpeakingFrame):
await self._handle_user_started_speaking(frame)
+ await self.push_frame(frame, direction)
elif isinstance(frame, UserStoppedSpeakingFrame):
await self._handle_user_stopped_speaking(frame)
+ await self.push_frame(frame, direction)
elif isinstance(frame, BotStartedSpeakingFrame):
# Ignore this frame. Use the serverContent API message instead
- pass
+ await self.push_frame(frame, direction)
elif isinstance(frame, BotStoppedSpeakingFrame):
# ignore this frame. Use the serverContent.turnComplete API message
- pass
+ await self.push_frame(frame, direction)
elif isinstance(frame, LLMMessagesAppendFrame):
await self._create_single_response(frame.messages)
elif isinstance(frame, LLMUpdateSettingsFrame):
await self._update_settings(frame.settings)
elif isinstance(frame, LLMSetToolsFrame):
await self._update_settings()
-
- await self.push_frame(frame, direction)
+ else:
+ await self.push_frame(frame, direction)
#
# websocket communication
diff --git a/src/pipecat/services/google/google.py b/src/pipecat/services/google/google.py
index 1d914a9bb..bfddce46d 100644
--- a/src/pipecat/services/google/google.py
+++ b/src/pipecat/services/google/google.py
@@ -10,6 +10,7 @@ import io
import json
import os
import time
+import uuid
from google.api_core.exceptions import DeadlineExceeded
from openai import AsyncStream
@@ -33,20 +34,22 @@ from pipecat.frames.frames import (
EndFrame,
ErrorFrame,
Frame,
- FunctionCallResultProperties,
+ FunctionCallCancelFrame,
+ FunctionCallInProgressFrame,
+ FunctionCallResultFrame,
InterimTranscriptionFrame,
LLMFullResponseEndFrame,
LLMFullResponseStartFrame,
LLMMessagesFrame,
LLMTextFrame,
LLMUpdateSettingsFrame,
- OpenAILLMContextAssistantTimestampFrame,
StartFrame,
TranscriptionFrame,
TTSAudioRawFrame,
TTSStartedFrame,
TTSStoppedFrame,
URLImageRawFrame,
+ UserImageRawFrame,
VisionImageRawFrame,
)
from pipecat.metrics.metrics import LLMTokenUsage
@@ -58,7 +61,6 @@ from pipecat.processors.frame_processor import FrameDirection
from pipecat.services.ai_services import ImageGenService, LLMService, STTService, TTSService
from pipecat.services.google.frames import LLMSearchResponseFrame
from pipecat.services.openai import (
- BaseOpenAILLMService,
OpenAIAssistantContextAggregator,
OpenAILLMService,
OpenAIUnhandledFunctionException,
@@ -72,6 +74,7 @@ try:
import google.generativeai as gai
from google import genai
from google.api_core.client_options import ClientOptions
+ from google.auth.transport.requests import Request
from google.cloud import speech_v2, texttospeech_v1
from google.cloud.speech_v2.types import cloud_speech
from google.genai import types
@@ -565,91 +568,76 @@ class GoogleUserContextAggregator(OpenAIUserContextAggregator):
class GoogleAssistantContextAggregator(OpenAIAssistantContextAggregator):
- async def push_aggregation(self):
- if not (
- self._aggregation or self._function_call_result or self._pending_image_frame_message
- ):
- return
+ async def handle_aggregation(self, aggregation: str):
+ self._context.add_message(glm.Content(role="model", parts=[glm.Part(text=aggregation)]))
- run_llm = False
- properties: Optional[FunctionCallResultProperties] = None
-
- aggregation = self._aggregation.strip()
- self.reset()
-
- try:
- if aggregation:
- self._context.add_message(
- glm.Content(role="model", parts=[glm.Part(text=aggregation)])
- )
-
- if self._function_call_result:
- frame = self._function_call_result
- properties = frame.properties
- self._function_call_result = None
- if frame.result:
- logger.debug(f"FunctionCallResultFrame result: {frame.arguments}")
- self._context.add_message(
- glm.Content(
- role="model",
- parts=[
- glm.Part(
- function_call=glm.FunctionCall(
- name=frame.function_name, args=frame.arguments
- )
- )
- ],
+ async def handle_function_call_in_progress(self, frame: FunctionCallInProgressFrame):
+ self._context.add_message(
+ glm.Content(
+ role="model",
+ parts=[
+ glm.Part(
+ function_call=glm.FunctionCall(
+ id=frame.tool_call_id, name=frame.function_name, args=frame.arguments
)
)
- response = frame.result
- if isinstance(response, str):
- response = {"response": response}
- self._context.add_message(
- glm.Content(
- role="user",
- parts=[
- glm.Part(
- function_response=glm.FunctionResponse(
- name=frame.function_name, response=response
- )
- )
- ],
+ ],
+ )
+ )
+ self._context.add_message(
+ glm.Content(
+ role="user",
+ parts=[
+ glm.Part(
+ function_response=glm.FunctionResponse(
+ id=frame.tool_call_id,
+ name=frame.function_name,
+ response={"response": "IN_PROGRESS"},
)
)
- if properties and properties.run_llm is not None:
- # If the tool call result has a run_llm property, use it
- run_llm = properties.run_llm
- else:
- # Default behavior is to run the LLM if there are no function calls in progress
- run_llm = not bool(self._function_calls_in_progress)
+ ],
+ )
+ )
- if self._pending_image_frame_message:
- frame = self._pending_image_frame_message
- self._pending_image_frame_message = None
- self._context.add_image_frame_message(
- format=frame.user_image_raw_frame.format,
- size=frame.user_image_raw_frame.size,
- image=frame.user_image_raw_frame.image,
- text=frame.text,
- )
- run_llm = True
+ async def handle_function_call_result(self, frame: FunctionCallResultFrame):
+ if frame.result:
+ if not isinstance(frame.result, str):
+ return
- if run_llm:
- await self.push_context_frame(FrameDirection.UPSTREAM)
+ response = {"response": frame.result}
- # Emit the on_context_updated callback once the function call result is added to the context
- if properties and properties.on_context_updated is not None:
- await properties.on_context_updated()
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, response
+ )
+ else:
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, "COMPLETED"
+ )
- # Push context frame
- await self.push_context_frame()
+ async def handle_function_call_cancel(self, frame: FunctionCallCancelFrame):
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, "CANCELLED"
+ )
- # Push timestamp frame with current time
- timestamp_frame = OpenAILLMContextAssistantTimestampFrame(timestamp=time_now_iso8601())
- await self.push_frame(timestamp_frame)
+ async def _update_function_call_result(
+ self, function_name: str, tool_call_id: str, result: Any
+ ):
+ for message in self._context.messages:
+ if message.role == "user":
+ for part in message.parts:
+ if part.function_response and part.function_response.id == tool_call_id:
+ part.function_response.response = {"response": result}
- except Exception as e:
- logger.exception(f"Error processing frame: {e}")
+ async def handle_user_image_frame(self, frame: UserImageRawFrame):
+ await self._update_function_call_result(
+ frame.request.function_name, frame.request.tool_call_id, "COMPLETED"
+ )
+ self._context.add_image_frame_message(
+ format=frame.format,
+ size=frame.size,
+ image=frame.image,
+ text=frame.request.context,
+ )
@dataclass
@@ -1071,7 +1059,7 @@ class GoogleLLMService(LLMService):
args = type(c.function_call).to_dict(c.function_call).get("args", {})
await self.call_function(
context=context,
- tool_call_id="what_should_this_be",
+ tool_call_id=str(uuid.uuid4()),
function_name=c.function_call.name,
arguments=args,
)
@@ -1334,6 +1322,82 @@ class GoogleLLMOpenAIBetaService(OpenAILLMService):
)
+class GoogleVertexLLMService(OpenAILLMService):
+ """Implements inference with Google's AI models via Vertex AI while
+ maintaining OpenAI API compatibility.
+
+ Reference:
+ https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/call-vertex-using-openai-library
+
+ """
+
+ class InputParams(OpenAILLMService.InputParams):
+ """Input parameters specific to Vertex AI."""
+
+ # https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations
+ location: str = "us-east4"
+ project_id: str
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[str] = None,
+ credentials_path: Optional[str] = None,
+ model: str = "google/gemini-2.0-flash-001",
+ params: InputParams = OpenAILLMService.InputParams(),
+ **kwargs,
+ ):
+ """Initializes the VertexLLMService.
+ Args:
+ credentials (Optional[str]): JSON string of service account credentials.
+ credentials_path (Optional[str]): Path to the service account JSON file.
+ model (str): Model identifier. Defaults to "google/gemini-2.0-flash-001".
+ params (InputParams): Vertex AI input parameters.
+ **kwargs: Additional arguments for OpenAILLMService.
+ """
+ base_url = self._get_base_url(params)
+ self._api_key = self._get_api_token(credentials, credentials_path)
+
+ super().__init__(api_key=self._api_key, base_url=base_url, model=model, **kwargs)
+
+ @staticmethod
+ def _get_base_url(params: InputParams) -> str:
+ """Constructs the base URL for Vertex AI API."""
+ return (
+ f"https://{params.location}-aiplatform.googleapis.com/v1/"
+ f"projects/{params.project_id}/locations/{params.location}/endpoints/openapi"
+ )
+
+ @staticmethod
+ def _get_api_token(credentials: Optional[str], credentials_path: Optional[str]) -> str:
+ """Retrieves an authentication token using Google service account credentials.
+ Args:
+ credentials (Optional[str]): JSON string of service account credentials.
+ credentials_path (Optional[str]): Path to the service account JSON file.
+ Returns:
+ str: OAuth token for API authentication.
+ """
+ creds: Optional[service_account.Credentials] = None
+
+ if credentials:
+ # Parse and load credentials from JSON string
+ creds = service_account.Credentials.from_service_account_info(
+ json.loads(credentials), scopes=["https://www.googleapis.com/auth/cloud-platform"]
+ )
+ elif credentials_path:
+ # Load credentials from JSON file
+ creds = service_account.Credentials.from_service_account_file(
+ credentials_path, scopes=["https://www.googleapis.com/auth/cloud-platform"]
+ )
+
+ if not creds:
+ raise ValueError("No valid credentials provided.")
+
+ creds.refresh(Request()) # Ensure token is up-to-date, lifetime is 1 hour.
+
+ return creds.token
+
+
class GoogleTTSService(TTSService):
class InputParams(BaseModel):
pitch: Optional[str] = None
@@ -1448,10 +1512,13 @@ class GoogleTTSService(TTSService):
try:
await self.start_ttfb_metrics()
+ # Check if the voice is a Chirp voice (including Chirp 3) or Journey voice
+ is_chirp_voice = "chirp" in self._voice_id.lower()
is_journey_voice = "journey" in self._voice_id.lower()
# Create synthesis input based on voice_id
- if is_journey_voice:
+ if is_chirp_voice or is_journey_voice:
+ # Chirp and Journey voices don't support SSML, use plain text
synthesis_input = texttospeech_v1.SynthesisInput(text=text)
else:
ssml = self._construct_ssml(text)
@@ -1727,6 +1794,17 @@ class GoogleSTTService(STTService):
await self._disconnect()
await self._connect()
+ async def set_language(self, language: Language):
+ """Update the service's recognition language.
+
+ A convenience method for setting a single language.
+
+ Args:
+ language: New language for recognition.
+ """
+ logger.debug(f"Switching STT language to: {language}")
+ await self.set_languages([language])
+
async def set_languages(self, languages: List[Language]):
"""Update the service's recognition languages.
@@ -1959,7 +2037,8 @@ class GoogleSTTService(STTService):
break
except Exception as e:
- logger.error(f"Stream error, attempting to reconnect: {e}")
+ logger.warning(f"{self} Reconnecting: {e}")
+
await asyncio.sleep(1) # Brief delay before reconnecting
self._stream_start_time = int(time.time() * 1000)
continue
@@ -2012,3 +2091,6 @@ class GoogleSTTService(STTService):
except Exception as e:
logger.error(f"Error processing Google STT responses: {e}")
+
+ # Re-raise the exception to let it propagate (e.g. in the case of a timeout, propagate to _stream_audio to reconnect)
+ raise
diff --git a/src/pipecat/services/grok.py b/src/pipecat/services/grok.py
index cf7d74f59..faed13050 100644
--- a/src/pipecat/services/grok.py
+++ b/src/pipecat/services/grok.py
@@ -25,94 +25,15 @@ from pipecat.services.openai import (
)
-class GrokAssistantContextAggregator(OpenAIAssistantContextAggregator):
- """Custom assistant context aggregator for Grok that handles empty content requirement."""
-
- async def push_aggregation(self):
- if not (
- self._aggregation or self._function_call_result or self._pending_image_frame_message
- ):
- return
-
- run_llm = False
- properties: Optional[FunctionCallResultProperties] = None
-
- aggregation = self._aggregation.strip()
- self.reset()
-
- try:
- if aggregation:
- self._context.add_message({"role": "assistant", "content": aggregation})
-
- if self._function_call_result:
- frame = self._function_call_result
- properties = frame.properties
- self._function_call_result = None
- if frame.result:
- # Grok requires an empty content field for function calls
- self._context.add_message(
- {
- "role": "assistant",
- "content": "", # Required by Grok
- "tool_calls": [
- {
- "id": frame.tool_call_id,
- "function": {
- "name": frame.function_name,
- "arguments": json.dumps(frame.arguments),
- },
- "type": "function",
- }
- ],
- }
- )
- self._context.add_message(
- {
- "role": "tool",
- "content": json.dumps(frame.result),
- "tool_call_id": frame.tool_call_id,
- }
- )
- if properties and properties.run_llm is not None:
- # If the tool call result has a run_llm property, use it
- run_llm = properties.run_llm
- else:
- # Default behavior is to run the LLM if there are no function calls in progress
- run_llm = not bool(self._function_calls_in_progress)
-
- if self._pending_image_frame_message:
- frame = self._pending_image_frame_message
- self._pending_image_frame_message = None
- self._context.add_image_frame_message(
- format=frame.user_image_raw_frame.format,
- size=frame.user_image_raw_frame.size,
- image=frame.user_image_raw_frame.image,
- text=frame.text,
- )
- run_llm = True
-
- if run_llm:
- await self.push_context_frame(FrameDirection.UPSTREAM)
-
- # Emit the on_context_updated callback once the function call result is added to the context
- if properties and properties.on_context_updated is not None:
- await properties.on_context_updated()
-
- await self.push_context_frame()
-
- except Exception as e:
- logger.error(f"Error processing frame: {e}")
-
-
@dataclass
class GrokContextAggregatorPair:
_user: "OpenAIUserContextAggregator"
- _assistant: "GrokAssistantContextAggregator"
+ _assistant: "OpenAIAssistantContextAggregator"
def user(self) -> "OpenAIUserContextAggregator":
return self._user
- def assistant(self) -> "GrokAssistantContextAggregator":
+ def assistant(self) -> "OpenAIAssistantContextAggregator":
return self._assistant
@@ -235,5 +156,5 @@ class GrokLLMService(OpenAILLMService):
context.set_llm_adapter(self.get_llm_adapter())
user = OpenAIUserContextAggregator(context, **user_kwargs)
- assistant = GrokAssistantContextAggregator(context, **assistant_kwargs)
+ assistant = OpenAIAssistantContextAggregator(context, **assistant_kwargs)
return GrokContextAggregatorPair(_user=user, _assistant=assistant)
diff --git a/src/pipecat/services/lmnt.py b/src/pipecat/services/lmnt.py
index 31ddaf123..d3cc92603 100644
--- a/src/pipecat/services/lmnt.py
+++ b/src/pipecat/services/lmnt.py
@@ -112,7 +112,7 @@ class LmntTTSService(InterruptibleTTSService):
await self._connect_websocket()
if not self._receive_task:
- self._receive_task = self.create_task(self._receive_task_handler(self.push_error))
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
async def _disconnect(self):
if self._receive_task:
@@ -147,6 +147,7 @@ class LmntTTSService(InterruptibleTTSService):
except Exception as e:
logger.error(f"{self} initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
async def _disconnect_websocket(self):
"""Disconnect from LMNT websocket."""
@@ -170,6 +171,11 @@ class LmntTTSService(InterruptibleTTSService):
return self._websocket
raise Exception("Websocket not connected")
+ async def flush_audio(self):
+ if not self._websocket:
+ return
+ await self._get_websocket().send(json.dumps({"flush": True}))
+
async def _receive_messages(self):
"""Receive messages from LMNT websocket."""
async for message in self._get_websocket():
diff --git a/src/pipecat/services/neuphonic.py b/src/pipecat/services/neuphonic.py
new file mode 100644
index 000000000..407e54a83
--- /dev/null
+++ b/src/pipecat/services/neuphonic.py
@@ -0,0 +1,345 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import asyncio
+import base64
+import json
+from typing import Any, AsyncGenerator, Mapping, Optional
+
+from loguru import logger
+from pydantic import BaseModel
+
+from pipecat.frames.frames import (
+ BotStoppedSpeakingFrame,
+ CancelFrame,
+ EndFrame,
+ ErrorFrame,
+ Frame,
+ LLMFullResponseEndFrame,
+ StartFrame,
+ StartInterruptionFrame,
+ TTSAudioRawFrame,
+ TTSSpeakFrame,
+ TTSStartedFrame,
+ TTSStoppedFrame,
+)
+from pipecat.processors.frame_processor import FrameDirection
+from pipecat.services.ai_services import InterruptibleTTSService, TTSService
+from pipecat.transcriptions.language import Language
+
+# See .env.example for Neuphonic configuration needed
+try:
+ import websockets
+ from pyneuphonic import Neuphonic, TTSConfig
+except ModuleNotFoundError as e:
+ logger.error(f"Exception: {e}")
+ logger.error(
+ "In order to use Neuphonic, you need to `pip install pipecat-ai[neuphonic]`. Also, set `NEUPHONIC_API_KEY` environment variable."
+ )
+ raise Exception(f"Missing module: {e}")
+
+
+def language_to_neuphonic_lang_code(language: Language) -> Optional[str]:
+ BASE_LANGUAGES = {
+ Language.DE: "de",
+ Language.EN: "en",
+ Language.ES: "es",
+ Language.NL: "nl",
+ Language.AR: "ar",
+ Language.FR: "fr",
+ Language.PT: "pt",
+ Language.RU: "ru",
+ Language.HI: "HI",
+ Language.ZH: "zh",
+ }
+
+ result = BASE_LANGUAGES.get(language)
+
+ # If not found in base languages, try to find the base language from a variant
+ if not result:
+ # Convert enum value to string and get the base language part (e.g. es-ES -> es)
+ lang_str = str(language.value)
+ base_code = lang_str.split("-")[0].lower()
+ # Look up the base code in our supported languages
+ result = base_code if base_code in BASE_LANGUAGES.values() else None
+
+ return result
+
+
+class NeuphonicTTSService(InterruptibleTTSService):
+ class InputParams(BaseModel):
+ language: Optional[Language] = Language.EN
+ speed: Optional[float] = 1.0
+
+ def __init__(
+ self,
+ *,
+ api_key: str,
+ voice_id: Optional[str] = None,
+ url: str = "wss://api.neuphonic.com",
+ sample_rate: Optional[int] = 22050,
+ encoding: str = "pcm_linear",
+ params: InputParams = InputParams(),
+ **kwargs,
+ ):
+ super().__init__(
+ aggregate_sentences=True,
+ push_text_frames=False,
+ push_stop_frames=True,
+ stop_frame_timeout_s=2.0,
+ sample_rate=sample_rate,
+ **kwargs,
+ )
+
+ self._api_key = api_key
+ self._url = url
+ self._settings = {
+ "lang_code": self.language_to_service_language(params.language),
+ "speed": params.speed,
+ "encoding": encoding,
+ "sampling_rate": sample_rate,
+ }
+ self.set_voice(voice_id)
+
+ # Indicates if we have sent TTSStartedFrame. It will reset to False when
+ # there's an interruption or TTSStoppedFrame.
+ self._started = False
+ self._cumulative_time = 0
+
+ def can_generate_metrics(self) -> bool:
+ return True
+
+ def language_to_service_language(self, language: Language) -> Optional[str]:
+ return language_to_neuphonic_lang_code(language)
+
+ async def _update_settings(self, settings: Mapping[str, Any]):
+ if "voice_id" in settings:
+ self.set_voice(settings["voice_id"])
+
+ await super()._update_settings(settings)
+ await self._disconnect()
+ await self._connect()
+ logger.info(f"Switching TTS to settings: [{self._settings}]")
+
+ async def start(self, frame: StartFrame):
+ await super().start(frame)
+ await self._connect()
+
+ async def stop(self, frame: EndFrame):
+ await super().stop(frame)
+ await self._disconnect()
+
+ async def cancel(self, frame: CancelFrame):
+ await super().cancel(frame)
+ await self._disconnect()
+
+ async def flush_audio(self):
+ if self._websocket:
+ msg = {"text": ""}
+ await self._websocket.send(json.dumps(msg))
+
+ async def push_frame(self, frame: Frame, direction: FrameDirection = FrameDirection.DOWNSTREAM):
+ await super().push_frame(frame, direction)
+ if isinstance(frame, (TTSStoppedFrame, StartInterruptionFrame)):
+ self._started = False
+
+ async def process_frame(self, frame: Frame, direction: FrameDirection):
+ await super().process_frame(frame, direction)
+
+ # If we received a TTSSpeakFrame and the LLM response included text (it
+ # might be that it's only a function calling response) we pause
+ # processing more frames until we receive a BotStoppedSpeakingFrame.
+ if isinstance(frame, TTSSpeakFrame):
+ await self.pause_processing_frames()
+ elif isinstance(frame, LLMFullResponseEndFrame) and self._started:
+ await self.pause_processing_frames()
+ elif isinstance(frame, BotStoppedSpeakingFrame):
+ await self.resume_processing_frames()
+
+ async def _connect(self):
+ await self._connect_websocket()
+
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
+ self._keepalive_task = self.create_task(self._keepalive_task_handler())
+
+ async def _disconnect(self):
+ if self._receive_task:
+ await self.cancel_task(self._receive_task)
+ self._receive_task = None
+
+ if self._keepalive_task:
+ await self.cancel_task(self._keepalive_task)
+ self._keepalive_task = None
+
+ await self._disconnect_websocket()
+
+ async def _connect_websocket(self):
+ try:
+ logger.debug("Connecting to Neuphonic")
+
+ tts_config = {
+ **self._settings,
+ "voice_id": self._voice_id,
+ }
+
+ query_params = [f"api_key={self._api_key}"]
+ for key, value in tts_config.items():
+ if value is not None:
+ query_params.append(f"{key}={value}")
+
+ url = f"{self._url}/speak/{self._settings['lang_code']}?{'&'.join(query_params)}"
+
+ self._websocket = await websockets.connect(url)
+
+ except Exception as e:
+ logger.error(f"{self} initialization error: {e}")
+ self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
+
+ async def _disconnect_websocket(self):
+ try:
+ await self.stop_all_metrics()
+
+ if self._websocket:
+ logger.debug("Disconnecting from Neuphonic")
+ await self._websocket.close()
+ self._websocket = None
+
+ self._started = False
+ except Exception as e:
+ logger.error(f"{self} error closing websocket: {e}")
+
+ async def _receive_messages(self):
+ async for message in self._websocket:
+ if isinstance(message, str):
+ msg = json.loads(message)
+ if msg.get("data", {}).get("audio") is not None:
+ await self.stop_ttfb_metrics()
+
+ audio = base64.b64decode(msg["data"]["audio"])
+ frame = TTSAudioRawFrame(audio, self.sample_rate, 1)
+ await self.push_frame(frame)
+
+ async def _keepalive_task_handler(self):
+ while True:
+ await asyncio.sleep(10)
+ await self._send_text("")
+
+ async def _send_text(self, text: str):
+ if self._websocket:
+ msg = {"text": text}
+ logger.debug(f"Sending text to websocket: {msg}")
+ await self._websocket.send(json.dumps(msg))
+
+ async def run_tts(self, text: str) -> AsyncGenerator[Frame, None]:
+ logger.debug(f"Generating TTS: [{text}]")
+
+ try:
+ if not self._websocket:
+ await self._connect()
+
+ try:
+ if not self._started:
+ await self.start_ttfb_metrics()
+ yield TTSStartedFrame()
+ self._started = True
+ self._cumulative_time = 0
+
+ await self._send_text(text)
+ await self.start_tts_usage_metrics(text)
+ except Exception as e:
+ logger.error(f"{self} error sending message: {e}")
+ yield TTSStoppedFrame()
+ await self._disconnect()
+ await self._connect()
+ return
+ yield None
+ except Exception as e:
+ logger.error(f"{self} exception: {e}")
+
+
+class NeuphonicHttpTTSService(TTSService):
+ """Neuphonic Text-to-Speech service using HTTP streaming.
+
+ Args:
+ api_key: Neuphonic API key
+ voice_id: ID of the voice to use
+ url: Base URL for the Neuphonic API (default: "https://api.neuphonic.com")
+ sample_rate: Sample rate for audio output (default: 22050Hz)
+ encoding: Audio encoding format (default: "pcm_linear")
+ params: Additional parameters for TTS generation including language and speed
+ **kwargs: Additional keyword arguments passed to the parent class
+ """
+
+ class InputParams(BaseModel):
+ language: Optional[Language] = Language.EN
+ speed: Optional[float] = 1.0
+
+ def __init__(
+ self,
+ *,
+ api_key: str,
+ voice_id: Optional[str] = None,
+ url: str = "https://api.neuphonic.com",
+ sample_rate: Optional[int] = 22050,
+ encoding: str = "pcm_linear",
+ params: InputParams = InputParams(),
+ **kwargs,
+ ):
+ super().__init__(sample_rate=sample_rate, **kwargs)
+
+ self._api_key = api_key
+ self._url = url
+ self._settings = {
+ "lang_code": self.language_to_service_language(params.language),
+ "speed": params.speed,
+ "encoding": encoding,
+ "sampling_rate": sample_rate,
+ }
+ self.set_voice(voice_id)
+
+ def can_generate_metrics(self) -> bool:
+ return True
+
+ async def start(self, frame: StartFrame):
+ await super().start(frame)
+
+ async def flush_audio(self):
+ pass
+
+ async def run_tts(self, text: str) -> AsyncGenerator[Frame, None]:
+ """Generate speech from text using Neuphonic streaming API.
+
+ Args:
+ text: The text to convert to speech
+ Yields:
+ Frames containing audio data and status information
+ """
+ logger.debug(f"Generating TTS: [{text}]")
+
+ client = Neuphonic(api_key=self._api_key, base_url=self._url.replace("https://", ""))
+
+ sse = client.tts.AsyncSSEClient()
+
+ try:
+ await self.start_ttfb_metrics()
+ response = sse.send(text, TTSConfig(**self._settings, voice_id=self._voice_id))
+
+ await self.start_tts_usage_metrics(text)
+ yield TTSStartedFrame()
+
+ async for message in response:
+ if message.status_code != 200:
+ logger.error(f"{self} error: {message.errors}")
+ yield ErrorFrame(error=f"Neuphonic API error: {message.errors}")
+
+ await self.stop_ttfb_metrics()
+ yield TTSAudioRawFrame(message.data.audio, self.sample_rate, 1)
+ except Exception as e:
+ logger.error(f"Error in run_tts: {e}")
+ yield ErrorFrame(error=str(e))
+ finally:
+ yield TTSStoppedFrame()
diff --git a/src/pipecat/services/openai.py b/src/pipecat/services/openai.py
index 5a3a993aa..ff7bc0442 100644
--- a/src/pipecat/services/openai.py
+++ b/src/pipecat/services/openai.py
@@ -27,23 +27,20 @@ from pydantic import BaseModel, Field
from pipecat.frames.frames import (
ErrorFrame,
Frame,
+ FunctionCallCancelFrame,
FunctionCallInProgressFrame,
FunctionCallResultFrame,
- FunctionCallResultProperties,
LLMFullResponseEndFrame,
LLMFullResponseStartFrame,
LLMMessagesFrame,
LLMTextFrame,
LLMUpdateSettingsFrame,
- OpenAILLMContextAssistantTimestampFrame,
StartFrame,
- StartInterruptionFrame,
TTSAudioRawFrame,
TTSStartedFrame,
TTSStoppedFrame,
URLImageRawFrame,
UserImageRawFrame,
- UserImageRequestFrame,
VisionImageRawFrame,
)
from pipecat.metrics.metrics import LLMTokenUsage
@@ -63,7 +60,6 @@ from pipecat.services.ai_services import (
)
from pipecat.services.base_whisper import BaseWhisperSTTService, Transcription
from pipecat.transcriptions.language import Language
-from pipecat.utils.time import time_now_iso8601
ValidVoice = Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
@@ -116,6 +112,7 @@ class BaseOpenAILLMService(LLMService):
base_url=None,
organization=None,
project=None,
+ default_headers: Mapping[str, str] | None = None,
params: InputParams = InputParams(),
**kwargs,
):
@@ -132,10 +129,23 @@ class BaseOpenAILLMService(LLMService):
}
self.set_model_name(model)
self._client = self.create_client(
- api_key=api_key, base_url=base_url, organization=organization, project=project, **kwargs
+ api_key=api_key,
+ base_url=base_url,
+ organization=organization,
+ project=project,
+ default_headers=default_headers,
+ **kwargs,
)
- def create_client(self, api_key=None, base_url=None, organization=None, project=None, **kwargs):
+ def create_client(
+ self,
+ api_key=None,
+ base_url=None,
+ organization=None,
+ project=None,
+ default_headers=None,
+ **kwargs,
+ ):
return AsyncOpenAI(
api_key=api_key,
base_url=base_url,
@@ -146,6 +156,7 @@ class BaseOpenAILLMService(LLMService):
max_keepalive_connections=100, max_connections=1000, keepalive_expiry=None
)
),
+ default_headers=default_headers,
)
def can_generate_metrics(self) -> bool:
@@ -413,13 +424,13 @@ class OpenAIImageGenService(ImageGenService):
class OpenAISTTService(BaseWhisperSTTService):
- """OpenAI Whisper speech-to-text service.
+ """OpenAI Speech-to-Text service that generates text from audio.
- Uses OpenAI's Whisper API to convert audio to text. Requires an OpenAI API key
+ Uses OpenAI's transcription API to convert audio to text. Requires an OpenAI API key
set via the api_key parameter or OPENAI_API_KEY environment variable.
Args:
- model: Whisper model to use. Defaults to "whisper-1".
+ model: Model to use — either gpt-4o or Whisper. Defaults to "gpt-4o-transcribe".
api_key: OpenAI API key. Defaults to None.
base_url: API base URL. Defaults to None.
language: Language of the audio input. Defaults to English.
@@ -431,7 +442,7 @@ class OpenAISTTService(BaseWhisperSTTService):
def __init__(
self,
*,
- model: str = "whisper-1",
+ model: str = "gpt-4o-transcribe",
api_key: Optional[str] = None,
base_url: Optional[str] = None,
language: Optional[Language] = Language.EN,
@@ -472,22 +483,16 @@ class OpenAITTSService(TTSService):
"""OpenAI Text-to-Speech service that generates audio from text.
This service uses the OpenAI TTS API to generate PCM-encoded audio at 24kHz.
- When using with DailyTransport, configure the sample rate in DailyParams
- as shown below:
-
- DailyParams(
- audio_out_enabled=True,
- audio_out_sample_rate=24_000,
- )
Args:
api_key: OpenAI API key. Defaults to None.
voice: Voice ID to use. Defaults to "alloy".
- model: TTS model to use ("tts-1" or "tts-1-hd"). Defaults to "tts-1".
- sample_rate: Output audio sample rate in Hz. Defaults to 24000.
+ model: TTS model to use. Defaults to "gpt-4o-mini-tts".
+ sample_rate: Output audio sample rate in Hz. Defaults to None.
**kwargs: Additional keyword arguments passed to TTSService.
The service returns PCM-encoded audio at the specified sample rate.
+
"""
OPENAI_SAMPLE_RATE = 24000 # OpenAI TTS always outputs at 24kHz
@@ -497,7 +502,7 @@ class OpenAITTSService(TTSService):
*,
api_key: Optional[str] = None,
voice: str = "alloy",
- model: Literal["tts-1", "tts-1-hd"] = "tts-1",
+ model: str = "gpt-4o-mini-tts",
sample_rate: Optional[int] = None,
**kwargs,
):
@@ -564,156 +569,67 @@ class OpenAITTSService(TTSService):
logger.exception(f"{self} error generating TTS: {e}")
-# internal use only -- todo: refactor
-@dataclass
-class OpenAIImageMessageFrame(Frame):
- user_image_raw_frame: UserImageRawFrame
- text: Optional[str] = None
-
-
class OpenAIUserContextAggregator(LLMUserContextAggregator):
- def __init__(self, context: OpenAILLMContext, **kwargs):
- super().__init__(context=context, **kwargs)
-
- async def process_frame(self, frame, direction):
- await super().process_frame(frame, direction)
- # Our parent method has already called push_frame(). So we can't interrupt the
- # flow here and we don't need to call push_frame() ourselves.
- try:
- if isinstance(frame, UserImageRequestFrame):
- # The LLM sends a UserImageRequestFrame upstream. Cache any context provided with
- # that frame so we can use it when we assemble the image message in the assistant
- # context aggregator.
- if frame.context:
- if isinstance(frame.context, str):
- self._context._user_image_request_context[frame.user_id] = frame.context
- else:
- logger.error(
- f"Unexpected UserImageRequestFrame context type: {type(frame.context)}"
- )
- del self._context._user_image_request_context[frame.user_id]
- else:
- if frame.user_id in self._context._user_image_request_context:
- del self._context._user_image_request_context[frame.user_id]
- elif isinstance(frame, UserImageRawFrame):
- # Push a new OpenAIImageMessageFrame with the text context we cached
- # downstream to be handled by our assistant context aggregator. This is
- # necessary so that we add the message to the context in the right order.
- text = self._context._user_image_request_context.get(frame.user_id) or ""
- if text:
- del self._context._user_image_request_context[frame.user_id]
- frame = OpenAIImageMessageFrame(user_image_raw_frame=frame, text=text)
- await self.push_frame(frame)
- except Exception as e:
- logger.error(f"Error processing frame: {e}")
+ pass
class OpenAIAssistantContextAggregator(LLMAssistantContextAggregator):
- def __init__(self, context: OpenAILLMContext, **kwargs):
- super().__init__(context=context, **kwargs)
- self._function_calls_in_progress = {}
- self._function_call_result = None
- self._pending_image_frame_message = None
+ async def handle_function_call_in_progress(self, frame: FunctionCallInProgressFrame):
+ self._context.add_message(
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {
+ "id": frame.tool_call_id,
+ "function": {
+ "name": frame.function_name,
+ "arguments": json.dumps(frame.arguments),
+ },
+ "type": "function",
+ }
+ ],
+ }
+ )
+ self._context.add_message(
+ {
+ "role": "tool",
+ "content": "IN_PROGRESS",
+ "tool_call_id": frame.tool_call_id,
+ }
+ )
- async def process_frame(self, frame, direction):
- await super().process_frame(frame, direction)
- # See note above about not calling push_frame() here.
- if isinstance(frame, StartInterruptionFrame):
- self._function_calls_in_progress.clear()
- self._function_call_finished = None
- elif isinstance(frame, FunctionCallInProgressFrame):
- logger.debug(f"FunctionCallInProgressFrame: {frame}")
- self._function_calls_in_progress[frame.tool_call_id] = frame
- elif isinstance(frame, FunctionCallResultFrame):
- logger.debug(f"FunctionCallResultFrame: {frame}")
- if frame.tool_call_id in self._function_calls_in_progress:
- del self._function_calls_in_progress[frame.tool_call_id]
- self._function_call_result = frame
- # TODO-CB: Kwin wants us to refactor this out of here but I REFUSE
- await self.push_aggregation()
- else:
- logger.warning(
- "FunctionCallResultFrame tool_call_id does not match any function call in progress"
- )
- self._function_call_result = None
- elif isinstance(frame, OpenAIImageMessageFrame):
- self._pending_image_frame_message = frame
- await self.push_aggregation()
+ async def handle_function_call_result(self, frame: FunctionCallResultFrame):
+ if frame.result:
+ result = json.dumps(frame.result)
+ await self._update_function_call_result(frame.function_name, frame.tool_call_id, result)
+ else:
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, "COMPLETED"
+ )
- async def push_aggregation(self):
- if not (
- self._aggregation or self._function_call_result or self._pending_image_frame_message
- ):
- return
+ async def handle_function_call_cancel(self, frame: FunctionCallCancelFrame):
+ await self._update_function_call_result(
+ frame.function_name, frame.tool_call_id, "CANCELLED"
+ )
- run_llm = False
- properties: Optional[FunctionCallResultProperties] = None
+ async def _update_function_call_result(
+ self, function_name: str, tool_call_id: str, result: str
+ ):
+ for message in self._context.messages:
+ if (
+ message["role"] == "tool"
+ and message["tool_call_id"]
+ and message["tool_call_id"] == tool_call_id
+ ):
+ message["content"] = result
- aggregation = self._aggregation.strip()
- self.reset()
-
- try:
- if aggregation:
- self._context.add_message({"role": "assistant", "content": aggregation})
-
- if self._function_call_result:
- frame = self._function_call_result
- properties = frame.properties
- self._function_call_result = None
- if frame.result:
- self._context.add_message(
- {
- "role": "assistant",
- "tool_calls": [
- {
- "id": frame.tool_call_id,
- "function": {
- "name": frame.function_name,
- "arguments": json.dumps(frame.arguments),
- },
- "type": "function",
- }
- ],
- }
- )
- self._context.add_message(
- {
- "role": "tool",
- "content": json.dumps(frame.result),
- "tool_call_id": frame.tool_call_id,
- }
- )
- if properties and properties.run_llm is not None:
- # If the tool call result has a run_llm property, use it
- run_llm = properties.run_llm
- else:
- # Default behavior is to run the LLM if there are no function calls in progress
- run_llm = not bool(self._function_calls_in_progress)
-
- if self._pending_image_frame_message:
- frame = self._pending_image_frame_message
- self._pending_image_frame_message = None
- self._context.add_image_frame_message(
- format=frame.user_image_raw_frame.format,
- size=frame.user_image_raw_frame.size,
- image=frame.user_image_raw_frame.image,
- text=frame.text,
- )
- run_llm = True
-
- if run_llm:
- await self.push_context_frame(FrameDirection.UPSTREAM)
-
- # Emit the on_context_updated callback once the function call result is added to the context
- if properties and properties.on_context_updated is not None:
- await properties.on_context_updated()
-
- # Push context frame
- await self.push_context_frame()
-
- # Push timestamp frame with current time
- timestamp_frame = OpenAILLMContextAssistantTimestampFrame(timestamp=time_now_iso8601())
- await self.push_frame(timestamp_frame)
-
- except Exception as e:
- logger.error(f"Error processing frame: {e}")
+ async def handle_user_image_frame(self, frame: UserImageRawFrame):
+ await self._update_function_call_result(
+ frame.request.function_name, frame.request.tool_call_id, "COMPLETED"
+ )
+ self._context.add_image_frame_message(
+ format=frame.format,
+ size=frame.size,
+ image=frame.image,
+ text=frame.request.context,
+ )
diff --git a/src/pipecat/services/openai_realtime_beta/__init__.py b/src/pipecat/services/openai_realtime_beta/__init__.py
index 52b00f6c8..595105d7f 100644
--- a/src/pipecat/services/openai_realtime_beta/__init__.py
+++ b/src/pipecat/services/openai_realtime_beta/__init__.py
@@ -1,3 +1,9 @@
from .azure import AzureRealtimeBetaLLMService
-from .events import InputAudioTranscription, SessionProperties, TurnDetection
+from .events import (
+ InputAudioNoiseReduction,
+ InputAudioTranscription,
+ SemanticTurnDetection,
+ SessionProperties,
+ TurnDetection,
+)
from .openai import OpenAIRealtimeBetaLLMService
diff --git a/src/pipecat/services/openai_realtime_beta/context.py b/src/pipecat/services/openai_realtime_beta/context.py
index 31639dc6b..c8381976f 100644
--- a/src/pipecat/services/openai_realtime_beta/context.py
+++ b/src/pipecat/services/openai_realtime_beta/context.py
@@ -12,6 +12,7 @@ from loguru import logger
from pipecat.frames.frames import (
Frame,
+ FunctionCallResultFrame,
FunctionCallResultProperties,
LLMMessagesUpdateFrame,
LLMSetToolsFrame,
@@ -174,67 +175,12 @@ class OpenAIRealtimeUserContextAggregator(OpenAIUserContextAggregator):
class OpenAIRealtimeAssistantContextAggregator(OpenAIAssistantContextAggregator):
- async def push_aggregation(self):
- # the only thing we implement here is function calling. in all other cases, messages
- # are added to the context when we receive openai realtime api events
- if not self._function_call_result:
- return
+ async def handle_function_call_result(self, frame: FunctionCallResultFrame):
+ await super().handle_function_call_result(frame)
- properties: Optional[FunctionCallResultProperties] = None
-
- self.reset()
- try:
- run_llm = True
- frame = self._function_call_result
- properties = frame.properties
- self._function_call_result = None
- if frame.result:
- # The "tool_call" message from the LLM that triggered the function call
- self._context.add_message(
- {
- "role": "assistant",
- "tool_calls": [
- {
- "id": frame.tool_call_id,
- "function": {
- "name": frame.function_name,
- "arguments": json.dumps(frame.arguments),
- },
- "type": "function",
- }
- ],
- }
- )
- # The result of the function call. Need to add this both to our context here and to
- # the openai realtime api context.
- result_message = {
- "role": "tool",
- "content": json.dumps(frame.result),
- "tool_call_id": frame.tool_call_id,
- }
-
- self._context.add_message(result_message)
- # The standard function callback code path pushes the FunctionCallResultFrame from the llm itself,
- # so we didn't have a chance to add the result to the openai realtime api context. Let's push a
- # special frame to do that.
- await self.push_frame(
- RealtimeFunctionCallResultFrame(result_frame=frame), FrameDirection.UPSTREAM
- )
- if properties and properties.run_llm is not None:
- # If the tool call result has a run_llm property, use it
- run_llm = properties.run_llm
- else:
- # Default behavior is to run the LLM if there are no function calls in progress
- run_llm = not bool(self._function_calls_in_progress)
-
- if run_llm:
- await self.push_context_frame(FrameDirection.UPSTREAM)
-
- # Emit the on_context_updated callback once the function call result is added to the context
- if properties and properties.on_context_updated is not None:
- await properties.on_context_updated()
-
- await self.push_context_frame()
-
- except Exception as e:
- logger.error(f"Error processing frame: {e}")
+ # The standard function callback code path pushes the FunctionCallResultFrame from the llm itself,
+ # so we didn't have a chance to add the result to the openai realtime api context. Let's push a
+ # special frame to do that.
+ await self.push_frame(
+ RealtimeFunctionCallResultFrame(result_frame=frame), FrameDirection.UPSTREAM
+ )
diff --git a/src/pipecat/services/openai_realtime_beta/events.py b/src/pipecat/services/openai_realtime_beta/events.py
index 17ce0a6d4..c2dcb7f09 100644
--- a/src/pipecat/services/openai_realtime_beta/events.py
+++ b/src/pipecat/services/openai_realtime_beta/events.py
@@ -17,7 +17,29 @@ from pydantic import BaseModel, Field
class InputAudioTranscription(BaseModel):
- model: Optional[str] = "whisper-1"
+ """Configuration for audio transcription settings.
+
+ Attributes:
+ model: Transcription model to use (e.g., "gpt-4o-transcribe", "whisper-1").
+ language: Optional language code for transcription.
+ prompt: Optional transcription hint text.
+ """
+
+ model: str = "gpt-4o-transcribe"
+ language: Optional[str]
+ prompt: Optional[str]
+
+ def __init__(
+ self,
+ model: Optional[str] = "gpt-4o-transcribe",
+ language: Optional[str] = None,
+ prompt: Optional[str] = None,
+ ):
+ super().__init__(model=model, language=language, prompt=prompt)
+ if self.model != "gpt-4o-transcribe" and (self.language or self.prompt):
+ raise ValueError(
+ "Fields 'language' and 'prompt' are only supported when model is 'gpt-4o-transcribe'"
+ )
class TurnDetection(BaseModel):
@@ -27,6 +49,17 @@ class TurnDetection(BaseModel):
silence_duration_ms: Optional[int] = 800
+class SemanticTurnDetection(BaseModel):
+ type: Optional[Literal["semantic_vad"]] = "semantic_vad"
+ eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None
+ create_response: Optional[bool] = None
+ interrupt_response: Optional[bool] = None
+
+
+class InputAudioNoiseReduction(BaseModel):
+ type: Optional[Literal["near_field", "far_field"]]
+
+
class SessionProperties(BaseModel):
modalities: Optional[List[Literal["text", "audio"]]] = None
instructions: Optional[str] = None
@@ -34,8 +67,11 @@ class SessionProperties(BaseModel):
input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None
output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None
input_audio_transcription: Optional[InputAudioTranscription] = None
+ input_audio_noise_reduction: Optional[InputAudioNoiseReduction] = None
# set turn_detection to False to disable turn detection
- turn_detection: Optional[Union[TurnDetection, bool]] = Field(default=None)
+ turn_detection: Optional[Union[TurnDetection, SemanticTurnDetection, bool]] = Field(
+ default=None
+ )
tools: Optional[List[Dict]] = None
tool_choice: Optional[Literal["auto", "none", "required"]] = None
temperature: Optional[float] = None
@@ -93,6 +129,7 @@ class RealtimeError(BaseModel):
code: Optional[str] = ""
message: str
param: Optional[str] = None
+ event_id: Optional[str] = None
#
@@ -150,6 +187,11 @@ class ConversationItemDeleteEvent(ClientEvent):
item_id: str
+class ConversationItemRetrieveEvent(ClientEvent):
+ type: Literal["conversation.item.retrieve"] = "conversation.item.retrieve"
+ item_id: str
+
+
class ResponseCreateEvent(ClientEvent):
type: Literal["response.create"] = "response.create"
response: Optional[ResponseProperties] = None
@@ -193,6 +235,13 @@ class ConversationItemCreated(ServerEvent):
item: ConversationItem
+class ConversationItemInputAudioTranscriptionDelta(ServerEvent):
+ type: Literal["conversation.item.input_audio_transcription.delta"]
+ item_id: str
+ content_index: int
+ delta: str
+
+
class ConversationItemInputAudioTranscriptionCompleted(ServerEvent):
type: Literal["conversation.item.input_audio_transcription.completed"]
item_id: str
@@ -219,6 +268,11 @@ class ConversationItemDeleted(ServerEvent):
item_id: str
+class ConversationItemRetrieved(ServerEvent):
+ type: Literal["conversation.item.retrieved"]
+ item: ConversationItem
+
+
class ResponseCreated(ServerEvent):
type: Literal["response.created"]
response: "Response"
@@ -400,10 +454,12 @@ _server_event_types = {
"input_audio_buffer.speech_started": InputAudioBufferSpeechStarted,
"input_audio_buffer.speech_stopped": InputAudioBufferSpeechStopped,
"conversation.item.created": ConversationItemCreated,
+ "conversation.item.input_audio_transcription.delta": ConversationItemInputAudioTranscriptionDelta,
"conversation.item.input_audio_transcription.completed": ConversationItemInputAudioTranscriptionCompleted,
"conversation.item.input_audio_transcription.failed": ConversationItemInputAudioTranscriptionFailed,
"conversation.item.truncated": ConversationItemTruncated,
"conversation.item.deleted": ConversationItemDeleted,
+ "conversation.item.retrieved": ConversationItemRetrieved,
"response.created": ResponseCreated,
"response.done": ResponseDone,
"response.output_item.added": ResponseOutputItemAdded,
diff --git a/src/pipecat/services/openai_realtime_beta/openai.py b/src/pipecat/services/openai_realtime_beta/openai.py
index 00f8cd840..a1f4bc731 100644
--- a/src/pipecat/services/openai_realtime_beta/openai.py
+++ b/src/pipecat/services/openai_realtime_beta/openai.py
@@ -30,6 +30,7 @@ from pipecat.frames.frames import (
ErrorFrame,
Frame,
InputAudioRawFrame,
+ InterimTranscriptionFrame,
LLMFullResponseEndFrame,
LLMFullResponseStartFrame,
LLMMessagesAppendFrame,
@@ -43,6 +44,7 @@ from pipecat.frames.frames import (
TTSAudioRawFrame,
TTSStartedFrame,
TTSStoppedFrame,
+ TTSTextFrame,
UserStartedSpeakingFrame,
UserStoppedSpeakingFrame,
)
@@ -114,12 +116,35 @@ class OpenAIRealtimeBetaLLMService(LLMService):
self._messages_added_manually = {}
self._user_and_response_message_tuple = None
+ self._register_event_handler("on_conversation_item_created")
+ self._register_event_handler("on_conversation_item_updated")
+ self._retrieve_conversation_item_futures = {}
+
def can_generate_metrics(self) -> bool:
return True
def set_audio_input_paused(self, paused: bool):
self._audio_input_paused = paused
+ async def retrieve_conversation_item(self, item_id: str):
+ future = self.get_event_loop().create_future()
+ retrieval_in_flight = False
+ if not self._retrieve_conversation_item_futures.get(item_id):
+ self._retrieve_conversation_item_futures[item_id] = []
+ else:
+ retrieval_in_flight = True
+ self._retrieve_conversation_item_futures[item_id].append(future)
+ if not retrieval_in_flight:
+ await self.send_client_event(
+ # Set event_id to "rci_{item_id}" so that we can identify an
+ # error later if the retrieval fails. We don't need a UUID
+ # suffix to the event_id because we're ensuring only one
+ # in-flight retrieval per item_id. (Note: "rci" = "retrieve
+ # conversation item")
+ events.ConversationItemRetrieveEvent(item_id=item_id, event_id=f"rci_{item_id}")
+ )
+ return await future
+
#
# standard AIService frame handling
#
@@ -353,8 +378,12 @@ class OpenAIRealtimeBetaLLMService(LLMService):
await self._handle_evt_audio_done(evt)
elif evt.type == "conversation.item.created":
await self._handle_evt_conversation_item_created(evt)
+ elif evt.type == "conversation.item.input_audio_transcription.delta":
+ await self._handle_evt_input_audio_transcription_delta(evt)
elif evt.type == "conversation.item.input_audio_transcription.completed":
await self.handle_evt_input_audio_transcription_completed(evt)
+ elif evt.type == "conversation.item.retrieved":
+ await self._handle_conversation_item_retrieved(evt)
elif evt.type == "response.done":
await self._handle_evt_response_done(evt)
elif evt.type == "input_audio_buffer.speech_started":
@@ -364,9 +393,10 @@ class OpenAIRealtimeBetaLLMService(LLMService):
elif evt.type == "response.audio_transcript.delta":
await self._handle_evt_audio_transcript_delta(evt)
elif evt.type == "error":
- await self._handle_evt_error(evt)
- # errors are fatal, so exit the receive loop
- return
+ if not await self._maybe_handle_evt_retrieve_conversation_item_error(evt):
+ await self._handle_evt_error(evt)
+ # errors are fatal, so exit the receive loop
+ return
async def _handle_evt_session_created(self, evt):
# session.created is received right after connecting. Send a message
@@ -408,6 +438,8 @@ class OpenAIRealtimeBetaLLMService(LLMService):
# receive a BotStoppedSpeakingFrame from the output transport.
async def _handle_evt_conversation_item_created(self, evt):
+ await self._call_event_handler("on_conversation_item_created", evt.item.id, evt.item)
+
# This will get sent from the server every time a new "message" is added
# to the server's conversation state, whether we create it via the API
# or the server creates it from LLM output.
@@ -424,7 +456,16 @@ class OpenAIRealtimeBetaLLMService(LLMService):
self._current_assistant_response = evt.item
await self.push_frame(LLMFullResponseStartFrame())
+ async def _handle_evt_input_audio_transcription_delta(self, evt):
+ if self._send_transcription_frames:
+ await self.push_frame(
+ # no way to get a language code?
+ InterimTranscriptionFrame(evt.delta, "", time_now_iso8601())
+ )
+
async def handle_evt_input_audio_transcription_completed(self, evt):
+ await self._call_event_handler("on_conversation_item_updated", evt.item_id, None)
+
if self._send_transcription_frames:
await self.push_frame(
# no way to get a language code?
@@ -442,6 +483,12 @@ class OpenAIRealtimeBetaLLMService(LLMService):
# User message without preceding conversation.item.created. Bug?
logger.warning(f"Transcript for unknown user message: {evt}")
+ async def _handle_conversation_item_retrieved(self, evt: events.ConversationItemRetrieved):
+ futures = self._retrieve_conversation_item_futures.pop(evt.item.id, None)
+ if futures:
+ for future in futures:
+ future.set_result(evt.item)
+
async def _handle_evt_response_done(self, evt):
# todo: figure out whether there's anything we need to do for "cancelled" events
# usage metrics
@@ -454,7 +501,15 @@ class OpenAIRealtimeBetaLLMService(LLMService):
await self.stop_processing_metrics()
await self.push_frame(LLMFullResponseEndFrame())
self._current_assistant_response = None
+ # error handling
+ if evt.response.status == "failed":
+ await self.push_error(
+ ErrorFrame(error=evt.response.status_details["error"]["message"], fatal=True)
+ )
+ return
# response content
+ for item in evt.response.output:
+ await self._call_event_handler("on_conversation_item_updated", item.id, item)
pair = self._user_and_response_message_tuple
if pair:
user, assistant = pair
@@ -471,6 +526,7 @@ class OpenAIRealtimeBetaLLMService(LLMService):
async def _handle_evt_audio_transcript_delta(self, evt):
if evt.delta:
await self.push_frame(LLMTextFrame(evt.delta))
+ await self.push_frame(TTSTextFrame(evt.delta))
async def _handle_evt_speech_started(self, evt):
await self._truncate_current_audio_response()
@@ -485,6 +541,22 @@ class OpenAIRealtimeBetaLLMService(LLMService):
await self.push_frame(StopInterruptionFrame())
await self.push_frame(UserStoppedSpeakingFrame())
+ async def _maybe_handle_evt_retrieve_conversation_item_error(self, evt: events.ErrorEvent):
+ """If the given error event is an error retrieving a conversation item:
+ - set an exception on the future that retrieve_conversation_item() is waiting on
+ - return true
+ Otherwise:
+ - return false
+ """
+ if evt.error.code == "item_retrieve_invalid_item_id":
+ item_id = evt.error.event_id.split("_", 1)[1] # event_id is of the form "rci_{item_id}"
+ futures = self._retrieve_conversation_item_futures.pop(item_id, None)
+ if futures:
+ for future in futures:
+ future.set_exception(Exception(evt.error.message))
+ return True
+ return False
+
async def _handle_evt_error(self, evt):
# Errors are fatal to this connection. Send an ErrorFrame.
await self.push_error(ErrorFrame(error=f"Error: {evt}", fatal=True))
@@ -507,7 +579,7 @@ class OpenAIRealtimeBetaLLMService(LLMService):
arguments = json.loads(item.arguments)
if self.has_function(function_name):
run_llm = index == total_items - 1
- if function_name in self._callbacks.keys():
+ if function_name in self._functions.keys():
await self.call_function(
context=self._context,
tool_call_id=tool_id,
@@ -515,7 +587,7 @@ class OpenAIRealtimeBetaLLMService(LLMService):
arguments=arguments,
run_llm=run_llm,
)
- elif None in self._callbacks.keys():
+ elif None in self._functions.keys():
await self.call_function(
context=self._context,
tool_call_id=tool_id,
diff --git a/src/pipecat/services/playht.py b/src/pipecat/services/playht.py
index 80d313765..75677876f 100644
--- a/src/pipecat/services/playht.py
+++ b/src/pipecat/services/playht.py
@@ -160,7 +160,7 @@ class PlayHTTTSService(InterruptibleTTSService):
await self._connect_websocket()
if not self._receive_task:
- self._receive_task = self.create_task(self._receive_task_handler(self.push_error))
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
async def _disconnect(self):
if self._receive_task:
@@ -183,12 +183,14 @@ class PlayHTTTSService(InterruptibleTTSService):
raise ValueError("WebSocket URL is not a string")
self._websocket = await websockets.connect(self._websocket_url)
- except ValueError as ve:
- logger.error(f"{self} initialization error: {ve}")
+ except ValueError as e:
+ logger.error(f"{self} initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
except Exception as e:
logger.error(f"{self} initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
async def _disconnect_websocket(self):
try:
diff --git a/src/pipecat/services/rime.py b/src/pipecat/services/rime.py
index 60083f55d..a1a455eb5 100644
--- a/src/pipecat/services/rime.py
+++ b/src/pipecat/services/rime.py
@@ -27,6 +27,8 @@ from pipecat.frames.frames import (
from pipecat.processors.frame_processor import FrameDirection
from pipecat.services.ai_services import AudioContextWordTTSService, TTSService
from pipecat.transcriptions.language import Language
+from pipecat.utils.text.base_text_aggregator import BaseTextAggregator
+from pipecat.utils.text.skip_tags_aggregator import SkipTagsAggregator
try:
import websockets
@@ -78,6 +80,7 @@ class RimeTTSService(AudioContextWordTTSService):
model: str = "mistv2",
sample_rate: Optional[int] = None,
params: InputParams = InputParams(),
+ text_aggregator: Optional[BaseTextAggregator] = None,
**kwargs,
):
"""Initialize Rime TTS service.
@@ -97,6 +100,7 @@ class RimeTTSService(AudioContextWordTTSService):
push_stop_frames=True,
pause_frame_processing=True,
sample_rate=sample_rate,
+ text_aggregator=text_aggregator or SkipTagsAggregator([("spell(", ")")]),
**kwargs,
)
@@ -167,7 +171,7 @@ class RimeTTSService(AudioContextWordTTSService):
await self._connect_websocket()
if not self._receive_task:
- self._receive_task = self.create_task(self._receive_task_handler(self.push_error))
+ self._receive_task = self.create_task(self._receive_task_handler(self._report_error))
async def _disconnect(self):
"""Close websocket connection and clean up tasks."""
@@ -190,6 +194,7 @@ class RimeTTSService(AudioContextWordTTSService):
except Exception as e:
logger.error(f"{self} initialization error: {e}")
self._websocket = None
+ await self._call_event_handler("on_connection_error", f"{e}")
async def _disconnect_websocket(self):
"""Close websocket connection and reset state."""
@@ -249,7 +254,9 @@ class RimeTTSService(AudioContextWordTTSService):
async def flush_audio(self):
if not self._context_id or not self._websocket:
return
+
logger.trace(f"{self}: flushing audio")
+ await self._get_websocket().send(json.dumps({"text": " "}))
self._context_id = None
async def _receive_messages(self):
diff --git a/src/pipecat/services/tavus.py b/src/pipecat/services/tavus.py
index b0ca699cb..9083dd53d 100644
--- a/src/pipecat/services/tavus.py
+++ b/src/pipecat/services/tavus.py
@@ -37,6 +37,7 @@ class TavusVideoService(AIService):
replica_id: str,
persona_id: str = "pipecat0", # Use `pipecat0` so that your TTS voice is used in place of the Tavus persona
session: aiohttp.ClientSession,
+ sample_rate: int = 16000,
**kwargs,
) -> None:
super().__init__(**kwargs)
@@ -44,6 +45,7 @@ class TavusVideoService(AIService):
self._replica_id = replica_id
self._persona_id = persona_id
self._session = session
+ self._sample_rate = sample_rate
self._conversation_id: str
@@ -94,7 +96,7 @@ class TavusVideoService(AIService):
async def _encode_audio_and_send(self, audio: bytes, in_rate: int, done: bool) -> None:
"""Encodes audio to base64 and sends it to Tavus"""
if not done:
- audio = await self._resampler.resample(audio, in_rate, 16000)
+ audio = await self._resampler.resample(audio, in_rate, self._sample_rate)
audio_base64 = base64.b64encode(audio).decode("utf-8")
logger.trace(f"{self}: sending {len(audio)} bytes")
await self._send_audio_message(audio_base64, done=done)
@@ -108,7 +110,7 @@ class TavusVideoService(AIService):
elif isinstance(frame, TTSAudioRawFrame):
await self._encode_audio_and_send(frame.audio, frame.sample_rate, done=False)
elif isinstance(frame, TTSStoppedFrame):
- await self._encode_audio_and_send(b"\x00", 16000, done=True)
+ await self._encode_audio_and_send(b"\x00", self._sample_rate, done=True)
await self.stop_ttfb_metrics()
await self.stop_processing_metrics()
elif isinstance(frame, StartInterruptionFrame):
@@ -137,6 +139,7 @@ class TavusVideoService(AIService):
"inference_id": self._current_idx_str,
"audio": audio_base64,
"done": done,
+ "sample_rate": self._sample_rate,
},
}
)
diff --git a/src/pipecat/services/ultravox.py b/src/pipecat/services/ultravox.py
new file mode 100644
index 000000000..52a5d05eb
--- /dev/null
+++ b/src/pipecat/services/ultravox.py
@@ -0,0 +1,403 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+"""This module implements Ultravox speech-to-text with a locally-loaded model."""
+
+import json
+import os
+import time
+from typing import AsyncGenerator, List, Optional
+
+import numpy as np
+from huggingface_hub import login
+from loguru import logger
+
+from pipecat.frames.frames import (
+ AudioRawFrame,
+ CancelFrame,
+ EndFrame,
+ ErrorFrame,
+ Frame,
+ LLMFullResponseEndFrame,
+ LLMFullResponseStartFrame,
+ LLMTextFrame,
+ StartFrame,
+ UserStartedSpeakingFrame,
+ UserStoppedSpeakingFrame,
+)
+from pipecat.processors.frame_processor import FrameDirection
+from pipecat.services.ai_services import AIService
+
+try:
+ from transformers import AutoTokenizer
+ from vllm import AsyncLLMEngine, SamplingParams
+ from vllm.engine.arg_utils import AsyncEngineArgs
+except ModuleNotFoundError as e:
+ logger.error(f"Exception: {e}")
+ logger.error("In order to use Ultravox, you need to `pip install pipecat-ai[ultravox]`.")
+ raise Exception(f"Missing module: {e}")
+
+
+class AudioBuffer:
+ """Buffer to collect audio frames before processing.
+
+ Attributes:
+ frames: List of AudioRawFrames to process
+ started_at: Timestamp when speech started
+ is_processing: Flag to prevent concurrent processing
+ """
+
+ def __init__(self):
+ self.frames: List[AudioRawFrame] = []
+ self.started_at: Optional[float] = None
+ self.is_processing: bool = False
+
+
+class UltravoxModel:
+ """Model wrapper for the Ultravox multimodal model.
+
+ This class handles loading and running the Ultravox model for speech-to-text.
+
+ Args:
+ model_name: The name or path of the Ultravox model to load
+
+ Attributes:
+ model_name: The name of the loaded model
+ engine: The vLLM engine for model inference
+ tokenizer: The tokenizer for the model
+ stop_token_ids: Optional token IDs to stop generation
+ """
+
+ def __init__(self, model_name: str = "fixie-ai/ultravox-v0_4_1-llama-3_1-8b"):
+ self.model_name = model_name
+ self._initialize_engine()
+ self._initialize_tokenizer()
+ self.stop_token_ids = None
+
+ def _initialize_engine(self):
+ """Initialize the vLLM engine for inference."""
+ engine_args = AsyncEngineArgs(
+ model=self.model_name,
+ gpu_memory_utilization=0.9,
+ max_model_len=8192,
+ trust_remote_code=True,
+ )
+ self.engine = AsyncLLMEngine.from_engine_args(engine_args)
+
+ def _initialize_tokenizer(self):
+ """Initialize the tokenizer for the model."""
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
+
+ def format_prompt(self, messages: list):
+ """Format chat messages into a prompt for the model.
+
+ Args:
+ messages: List of message dictionaries with 'role' and 'content'
+
+ Returns:
+ str: Formatted prompt string
+ """
+ return self.tokenizer.apply_chat_template(
+ messages, tokenize=False, add_generation_prompt=True
+ )
+
+ async def generate(
+ self,
+ messages: list,
+ temperature: float = 0.7,
+ max_tokens: int = 100,
+ audio: np.ndarray = None,
+ ):
+ """Generate text from audio input using the model.
+
+ Args:
+ messages: List of message dictionaries
+ temperature: Sampling temperature
+ max_tokens: Maximum tokens to generate
+ audio: Audio data as numpy array
+
+ Yields:
+ str: JSON chunks of the generated response
+ """
+ sampling_params = SamplingParams(
+ temperature=temperature, max_tokens=max_tokens, stop_token_ids=self.stop_token_ids
+ )
+
+ mm_data = {"audio": audio}
+ inputs = {"prompt": self.format_prompt(messages), "multi_modal_data": mm_data}
+ results_generator = self.engine.generate(inputs, sampling_params, str(time.time()))
+
+ previous_text = ""
+ first_chunk = True
+
+ async for output in results_generator:
+ prompt_output = output.outputs
+ new_text = prompt_output[0].text[len(previous_text) :]
+ previous_text = prompt_output[0].text
+
+ # Construct OpenAI-compatible chunk
+ chunk = {
+ "id": str(int(time.time() * 1000)),
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": self.model_name,
+ "choices": [
+ {
+ "index": 0,
+ "delta": {},
+ "finish_reason": None,
+ }
+ ],
+ }
+
+ # Include the role in the first chunk
+ if first_chunk:
+ chunk["choices"][0]["delta"]["role"] = "assistant"
+ first_chunk = False
+
+ # Add new text to the delta if any
+ if new_text:
+ chunk["choices"][0]["delta"]["content"] = new_text
+
+ # Capture a finish reason if it's provided
+ finish_reason = prompt_output[0].finish_reason or None
+ if finish_reason and finish_reason != "none":
+ chunk["choices"][0]["finish_reason"] = finish_reason
+
+ yield json.dumps(chunk)
+
+
+class UltravoxSTTService(AIService):
+ """Service to transcribe audio using the Ultravox multimodal model.
+
+ This service collects audio frames and processes them with Ultravox
+ to generate text transcriptions.
+
+ Args:
+ model_size: The Ultravox model to use (ModelSize enum or string)
+ hf_token: Hugging Face token for model access
+ temperature: Sampling temperature for generation
+ max_tokens: Maximum tokens to generate
+ **kwargs: Additional arguments passed to AIService
+
+ Attributes:
+ model: The UltravoxModel instance
+ buffer: Buffer to collect audio frames
+ temperature: Temperature for text generation
+ max_tokens: Maximum tokens to generate
+ _connection_active: Flag indicating if service is active
+ """
+
+ def __init__(
+ self,
+ *,
+ model_size: str = "fixie-ai/ultravox-v0_4_1-llama-3_1-8b",
+ hf_token: Optional[str] = None,
+ temperature: float = 0.7,
+ max_tokens: int = 100,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ # Authenticate with Hugging Face if token provided
+ if hf_token:
+ login(token=hf_token)
+ elif os.environ.get("HF_TOKEN"):
+ login(token=os.environ.get("HF_TOKEN"))
+ else:
+ logger.warning("No Hugging Face token provided. Model may not load correctly.")
+
+ # Initialize model
+ model_name = model_size if isinstance(model_size, str) else model_size.value
+ self._model = UltravoxModel(model_name=model_name)
+
+ # Initialize service state
+ self._buffer = AudioBuffer()
+ self._temperature = temperature
+ self._max_tokens = max_tokens
+ self._connection_active = False
+
+ logger.info(f"Initialized UltravoxSTTService with model: {model_name}")
+
+ def can_generate_metrics(self) -> bool:
+ """Indicates whether this service can generate metrics.
+
+ Returns:
+ bool: True, as this service supports metric generation.
+ """
+ return True
+
+ async def start(self, frame: StartFrame):
+ """Handle service start.
+
+ Args:
+ frame: StartFrame that triggered this method
+ """
+ await super().start(frame)
+ self._connection_active = True
+ logger.info("UltravoxSTTService started")
+
+ async def stop(self, frame: EndFrame):
+ """Handle service stop.
+
+ Args:
+ frame: EndFrame that triggered this method
+ """
+ await super().stop(frame)
+ self._connection_active = False
+ logger.info("UltravoxSTTService stopped")
+
+ async def cancel(self, frame: CancelFrame):
+ """Handle service cancellation.
+
+ Args:
+ frame: CancelFrame that triggered this method
+ """
+ await super().cancel(frame)
+ self._connection_active = False
+ self._buffer = AudioBuffer()
+ logger.info("UltravoxSTTService cancelled")
+
+ async def process_frame(self, frame: Frame, direction: FrameDirection):
+ """Process incoming frames.
+
+ This method collects audio frames and processes them when speech ends.
+
+ Args:
+ frame: The frame to process
+ direction: Direction of the frame (input/output)
+ """
+ await super().process_frame(frame, direction)
+
+ if isinstance(frame, UserStartedSpeakingFrame):
+ logger.info("Speech started")
+ self._buffer = AudioBuffer()
+ self._buffer.started_at = time.time()
+
+ elif isinstance(frame, AudioRawFrame) and self._buffer.started_at is not None:
+ self._buffer.frames.append(frame)
+
+ elif isinstance(frame, UserStoppedSpeakingFrame):
+ if self._buffer.frames and not self._buffer.is_processing:
+ logger.info("Speech ended, processing buffer...")
+ await self.process_generator(self._process_audio_buffer())
+ return # Return early to avoid pushing None frame
+
+ # Only push the original frame if we haven't processed audio
+ if frame is not None:
+ await self.push_frame(frame, direction)
+
+ async def _process_audio_buffer(self) -> AsyncGenerator[Frame, None]:
+ """Process collected audio frames with Ultravox.
+
+ This method concatenates audio frames, processes them with the model,
+ and yields the resulting text frames.
+
+ Yields:
+ Frame: TextFrame containing the transcribed text
+ """
+ try:
+ self._buffer.is_processing = True
+
+ # Check if we have valid frames before processing
+ if not self._buffer.frames:
+ logger.warning("No audio frames to process")
+ yield ErrorFrame("No audio frames to process")
+ return
+
+ # Process audio frames
+ audio_arrays = []
+ for f in self._buffer.frames:
+ if hasattr(f, "audio") and f.audio:
+ # Handle bytes data - these are int16 PCM samples
+ if isinstance(f.audio, bytes):
+ try:
+ # Convert bytes to int16 array
+ arr = np.frombuffer(f.audio, dtype=np.int16)
+ if arr.size > 0: # Check if array is not empty
+ audio_arrays.append(arr)
+ except Exception as e:
+ logger.error(f"Error processing bytes audio frame: {e}")
+ # Handle numpy array data
+ elif isinstance(f.audio, np.ndarray):
+ if f.audio.size > 0: # Check if array is not empty
+ # Ensure it's int16 data
+ if f.audio.dtype != np.int16:
+ logger.info(f"Converting array from {f.audio.dtype} to int16")
+ audio_arrays.append(f.audio.astype(np.int16))
+ else:
+ audio_arrays.append(f.audio)
+
+ # Only proceed if we have valid audio arrays
+ if not audio_arrays:
+ logger.warning("No valid audio data found in frames")
+ yield ErrorFrame("No valid audio data found in frames")
+ return
+
+ # Concatenate audio frames - all should be int16 now
+ audio_data = np.concatenate(audio_arrays)
+
+ audio_int16 = audio_data # Already in int16 format
+ # Save int16 audio
+
+ # Convert int16 to float32 and normalize for model input
+ audio_float32 = audio_int16.astype(np.float32) / 32768.0
+
+ # Generate text using the model
+ if self._model:
+ try:
+ logger.info("Generating text from audio using model...")
+ full_response = ""
+
+ # Start metrics tracking
+ await self.start_ttfb_metrics()
+ await self.start_processing_metrics()
+
+ async for response in self.model.generate(
+ messages=[{"role": "user", "content": "<|audio|>\n"}],
+ temperature=self.temperature,
+ max_tokens=self.max_tokens,
+ audio=audio_float32,
+ ):
+ # Stop TTFB metrics after first response
+ await self.stop_ttfb_metrics()
+
+ chunk = json.loads(response)
+ if "choices" in chunk and len(chunk["choices"]) > 0:
+ delta = chunk["choices"][0]["delta"]
+ if "content" in delta:
+ new_text = delta["content"]
+ full_response += new_text
+
+ # Stop processing metrics after completion
+ await self.stop_processing_metrics()
+
+ logger.info(f"Generated text: {full_response}")
+ # Create a transcription frame with the generated text
+ yield LLMFullResponseStartFrame()
+
+ text_frame = LLMTextFrame(text=full_response.strip())
+ yield text_frame
+
+ yield LLMFullResponseEndFrame()
+
+ except Exception as e:
+ logger.error(f"Error generating text from model: {e}")
+ yield ErrorFrame(f"Error generating text: {str(e)}")
+ else:
+ logger.warning("No model available for text generation")
+ yield ErrorFrame("No model available for text generation")
+
+ except Exception as e:
+ logger.error(f"Error processing audio buffer: {e}")
+ import traceback
+
+ logger.error(traceback.format_exc())
+ yield ErrorFrame(f"Error processing audio: {str(e)}")
+ finally:
+ self._buffer.is_processing = False
+ self._buffer.frames = []
+ self._buffer.started_at = None
diff --git a/src/pipecat/services/websocket_service.py b/src/pipecat/services/websocket_service.py
index 19fb4ae01..2e82ddaba 100644
--- a/src/pipecat/services/websocket_service.py
+++ b/src/pipecat/services/websocket_service.py
@@ -19,9 +19,10 @@ from pipecat.utils.network import exponential_backoff_time
class WebsocketService(ABC):
"""Base class for websocket-based services with reconnection logic."""
- def __init__(self):
+ def __init__(self, *, reconnect_on_error: bool = True, **kwargs):
"""Initialize websocket attributes."""
self._websocket: Optional[websockets.WebSocketClientProtocol] = None
+ self._reconnect_on_error = reconnect_on_error
async def _verify_connection(self) -> bool:
"""Verify websocket connection is working.
@@ -72,24 +73,29 @@ class WebsocketService(ABC):
self._websocket.close_rcvd_then_sent,
)
except Exception as e:
- retry_count += 1
- if retry_count >= MAX_RETRIES:
- message = f"{self} error receiving messages: {e}"
- logger.error(message)
- await report_error(ErrorFrame(message, fatal=True))
+ message = f"{self} error receiving messages: {e}"
+ logger.error(message)
+
+ if self._reconnect_on_error:
+ retry_count += 1
+ if retry_count >= MAX_RETRIES:
+ await report_error(ErrorFrame(message, fatal=True))
+ break
+
+ logger.warning(f"{self} connection error, will retry: {e}")
+ await report_error(ErrorFrame(message))
+
+ try:
+ if await self._reconnect_websocket(retry_count):
+ retry_count = 0 # Reset counter on successful reconnection
+ wait_time = exponential_backoff_time(retry_count)
+ await asyncio.sleep(wait_time)
+ except Exception as reconnect_error:
+ logger.error(f"{self} reconnection failed: {reconnect_error}")
+ else:
+ await report_error(ErrorFrame(message))
break
- logger.warning(f"{self} connection error, will retry: {e}")
-
- try:
- if await self._reconnect_websocket(retry_count):
- retry_count = 0 # Reset counter on successful reconnection
- wait_time = exponential_backoff_time(retry_count)
- await asyncio.sleep(wait_time)
- except Exception as reconnect_error:
- logger.error(f"{self} reconnection failed: {reconnect_error}")
- continue
-
@abstractmethod
async def _connect(self):
"""Implement service-specific connection logic. This function will
diff --git a/src/pipecat/tests/utils.py b/src/pipecat/tests/utils.py
index 7fcecc3ff..e2368ba09 100644
--- a/src/pipecat/tests/utils.py
+++ b/src/pipecat/tests/utils.py
@@ -6,7 +6,7 @@
import asyncio
from dataclasses import dataclass
-from typing import Any, Awaitable, Callable, Dict, Sequence, Tuple
+from typing import Any, Awaitable, Callable, Dict, Optional, Sequence, Tuple
from pipecat.frames.frames import (
EndFrame,
@@ -80,8 +80,8 @@ async def run_test(
processor: FrameProcessor,
*,
frames_to_send: Sequence[Frame],
- expected_down_frames: Sequence[type],
- expected_up_frames: Sequence[type] = [],
+ expected_down_frames: Optional[Sequence[type]] = None,
+ expected_up_frames: Optional[Sequence[type]] = None,
ignore_start: bool = True,
start_metadata: Dict[str, Any] = {},
send_end_frame: bool = True,
@@ -101,7 +101,11 @@ async def run_test(
pipeline = Pipeline([source, processor, sink])
- task = PipelineTask(pipeline, params=PipelineParams(start_metadata=start_metadata))
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(start_metadata=start_metadata),
+ cancel_on_idle_timeout=False,
+ )
async def push_frames():
# Just give a little head start to the runner.
@@ -122,33 +126,35 @@ async def run_test(
# Down frames
#
received_down_frames: Sequence[Frame] = []
- while not received_down.empty():
- frame = await received_down.get()
- if not isinstance(frame, EndFrame) or not send_end_frame:
- received_down_frames.append(frame)
+ if expected_down_frames is not None:
+ while not received_down.empty():
+ frame = await received_down.get()
+ if not isinstance(frame, EndFrame) or not send_end_frame:
+ received_down_frames.append(frame)
- print("received DOWN frames =", received_down_frames)
- print("expected DOWN frames =", expected_down_frames)
+ print("received DOWN frames =", received_down_frames)
+ print("expected DOWN frames =", expected_down_frames)
- assert len(received_down_frames) == len(expected_down_frames)
+ assert len(received_down_frames) == len(expected_down_frames)
- for real, expected in zip(received_down_frames, expected_down_frames):
- assert isinstance(real, expected)
+ for real, expected in zip(received_down_frames, expected_down_frames):
+ assert isinstance(real, expected)
#
# Up frames
#
received_up_frames: Sequence[Frame] = []
- while not received_up.empty():
- frame = await received_up.get()
- received_up_frames.append(frame)
+ if expected_up_frames is not None:
+ while not received_up.empty():
+ frame = await received_up.get()
+ received_up_frames.append(frame)
- print("received UP frames =", received_up_frames)
- print("expected UP frames =", expected_up_frames)
+ print("received UP frames =", received_up_frames)
+ print("expected UP frames =", expected_up_frames)
- assert len(received_up_frames) == len(expected_up_frames)
+ assert len(received_up_frames) == len(expected_up_frames)
- for real, expected in zip(received_up_frames, expected_up_frames):
- assert isinstance(real, expected)
+ for real, expected in zip(received_up_frames, expected_up_frames):
+ assert isinstance(real, expected)
return (received_down_frames, received_up_frames)
diff --git a/src/pipecat/transcriptions/language.py b/src/pipecat/transcriptions/language.py
index b8b9fafe9..75f714a72 100644
--- a/src/pipecat/transcriptions/language.py
+++ b/src/pipecat/transcriptions/language.py
@@ -54,6 +54,9 @@ class Language(StrEnum):
AZ = "az"
AZ_AZ = "az-AZ"
+ # Bashkir
+ BA = "ba"
+
# Belarusian
BE = "be"
@@ -66,6 +69,12 @@ class Language(StrEnum):
BN_BD = "bn-BD"
BN_IN = "bn-IN"
+ # Tibetan
+ BO = "bo"
+
+ # Breton
+ BR = "br"
+
# Bosnian
BS = "bs"
BS_BA = "bs-BA"
@@ -159,6 +168,9 @@ class Language(StrEnum):
FIL = "fil"
FIL_PH = "fil-PH"
+ # Faroese
+ FO = "fo"
+
# French
FR = "fr"
FR_BE = "fr-BE"
@@ -178,6 +190,9 @@ class Language(StrEnum):
GU = "gu"
GU_IN = "gu-IN"
+ # Hausa
+ HA = "ha"
+
# Hebrew
HE = "he"
HE_IL = "he-IL"
@@ -190,6 +205,9 @@ class Language(StrEnum):
HR = "hr"
HR_HR = "hr-HR"
+ # Haitian Creole
+ HT = "ht"
+
# Hungarian
HU = "hu"
HU_HU = "hu-HU"
@@ -224,6 +242,7 @@ class Language(StrEnum):
# Javanese
JV = "jv"
JV_ID = "jv-ID"
+ JW = "jw" # Fal requires for Javanese
# Georgian
KA = "ka"
@@ -245,6 +264,15 @@ class Language(StrEnum):
KO = "ko"
KO_KR = "ko-KR"
+ # Latin
+ LA = "la"
+
+ # Luxembourgish
+ LB = "lb"
+
+ # Lingala
+ LN = "ln"
+
# Lao
LO = "lo"
LO_LA = "lo-LA"
@@ -257,6 +285,9 @@ class Language(StrEnum):
LV = "lv"
LV_LV = "lv-LV"
+ # Malagasy
+ MG = "mg"
+
# Macedonian
MK = "mk"
MK_MK = "mk-MK"
@@ -289,9 +320,10 @@ class Language(StrEnum):
MY_MM = "my-MM"
# Norwegian
- NB = "nb"
+ NB = "nb" # Norwegian Bokmål
NB_NO = "nb-NO"
NO = "no"
+ NN = "nn" # Norwegian Nynorsk
# Nepali
NE = "ne"
@@ -302,6 +334,9 @@ class Language(StrEnum):
NL_BE = "nl-BE"
NL_NL = "nl-NL"
+ # Occitan
+ OC = "oc"
+
# Odia
OR = "or"
OR_IN = "or-IN"
@@ -331,6 +366,12 @@ class Language(StrEnum):
RU = "ru"
RU_RU = "ru-RU"
+ # Sanskrit
+ SA = "sa"
+
+ # Sindhi
+ SD = "sd"
+
# Sinhala
SI = "si"
SI_LK = "si-LK"
@@ -343,6 +384,9 @@ class Language(StrEnum):
SL = "sl"
SL_SI = "sl-SI"
+ # Shona
+ SN = "sn"
+
# Somali
SO = "so"
SO_SO = "so-SO"
@@ -384,14 +428,23 @@ class Language(StrEnum):
TE = "te"
TE_IN = "te-IN"
+ # Tajik
+ TG = "tg"
+
# Thai
TH = "th"
TH_TH = "th-TH"
+ # Turkmen
+ TK = "tk"
+
# Turkish
TR = "tr"
TR_TR = "tr-TR"
+ # Tatar
+ TT = "tt"
+
# Ukrainian
UK = "uk"
UK_UA = "uk-UA"
@@ -413,6 +466,12 @@ class Language(StrEnum):
WUU = "wuu"
WUU_CN = "wuu-CN"
+ # Yiddish
+ YI = "yi"
+
+ # Yoruba
+ YO = "yo"
+
# Yue Chinese
YUE = "yue"
YUE_CN = "yue-CN"
diff --git a/src/pipecat/transports/base_input.py b/src/pipecat/transports/base_input.py
index 782ad1333..971dfe066 100644
--- a/src/pipecat/transports/base_input.py
+++ b/src/pipecat/transports/base_input.py
@@ -152,6 +152,7 @@ class BaseInputTransport(FrameProcessor):
async def _handle_user_interruption(self, frame: Frame):
if isinstance(frame, UserStartedSpeakingFrame):
logger.debug("User started speaking")
+ await self.push_frame(frame)
# Make sure we notify about interruptions quickly out-of-band.
if self.interruptions_allowed:
await self._start_interruption()
@@ -161,12 +162,11 @@ class BaseInputTransport(FrameProcessor):
await self.push_frame(StartInterruptionFrame())
elif isinstance(frame, UserStoppedSpeakingFrame):
logger.debug("User stopped speaking")
+ await self.push_frame(frame)
if self.interruptions_allowed:
await self._stop_interruption()
await self.push_frame(StopInterruptionFrame())
- await self.push_frame(frame)
-
#
# Audio input
#
diff --git a/src/pipecat/transports/network/fastapi_websocket.py b/src/pipecat/transports/network/fastapi_websocket.py
index bfb1e8146..937dda80c 100644
--- a/src/pipecat/transports/network/fastapi_websocket.py
+++ b/src/pipecat/transports/network/fastapi_websocket.py
@@ -102,11 +102,13 @@ class FastAPIWebsocketClient:
class FastAPIWebsocketInputTransport(BaseInputTransport):
def __init__(
self,
+ transport: BaseTransport,
client: FastAPIWebsocketClient,
params: FastAPIWebsocketParams,
**kwargs,
):
super().__init__(params, **kwargs)
+ self._transport = transport
self._client = client
self._params = params
self._receive_task = None
@@ -139,6 +141,10 @@ class FastAPIWebsocketInputTransport(BaseInputTransport):
await self._stop_tasks()
await self._client.disconnect()
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def _receive_messages(self):
try:
async for message in self._client.receive():
@@ -165,11 +171,14 @@ class FastAPIWebsocketInputTransport(BaseInputTransport):
class FastAPIWebsocketOutputTransport(BaseOutputTransport):
def __init__(
self,
+ transport: BaseTransport,
client: FastAPIWebsocketClient,
params: FastAPIWebsocketParams,
**kwargs,
):
super().__init__(params, **kwargs)
+
+ self._transport = transport
self._client = client
self._params = params
@@ -194,6 +203,10 @@ class FastAPIWebsocketOutputTransport(BaseOutputTransport):
await super().cancel(frame)
await self._client.disconnect()
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def process_frame(self, frame: Frame, direction: FrameDirection):
await super().process_frame(frame, direction)
@@ -266,6 +279,7 @@ class FastAPIWebsocketTransport(BaseTransport):
output_name: Optional[str] = None,
):
super().__init__(input_name=input_name, output_name=output_name)
+
self._params = params
self._callbacks = FastAPIWebsocketCallbacks(
@@ -278,10 +292,10 @@ class FastAPIWebsocketTransport(BaseTransport):
self._client = FastAPIWebsocketClient(websocket, is_binary, self._callbacks)
self._input = FastAPIWebsocketInputTransport(
- self._client, self._params, name=self._input_name
+ self, self._client, self._params, name=self._input_name
)
self._output = FastAPIWebsocketOutputTransport(
- self._client, self._params, name=self._output_name
+ self, self._client, self._params, name=self._output_name
)
# Register supported handlers. The user will only be able to register
diff --git a/src/pipecat/transports/network/websocket_client.py b/src/pipecat/transports/network/websocket_client.py
index eb2b5cfb8..11a000e69 100644
--- a/src/pipecat/transports/network/websocket_client.py
+++ b/src/pipecat/transports/network/websocket_client.py
@@ -118,9 +118,15 @@ class WebsocketClientSession:
class WebsocketClientInputTransport(BaseInputTransport):
- def __init__(self, session: WebsocketClientSession, params: WebsocketClientParams):
+ def __init__(
+ self,
+ transport: BaseTransport,
+ session: WebsocketClientSession,
+ params: WebsocketClientParams,
+ ):
super().__init__(params)
+ self._transport = transport
self._session = session
self._params = params
@@ -138,6 +144,10 @@ class WebsocketClientInputTransport(BaseInputTransport):
await super().cancel(frame)
await self._session.disconnect()
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def on_message(self, websocket, message):
frame = await self._params.serializer.deserialize(message)
if not frame:
@@ -149,9 +159,15 @@ class WebsocketClientInputTransport(BaseInputTransport):
class WebsocketClientOutputTransport(BaseOutputTransport):
- def __init__(self, session: WebsocketClientSession, params: WebsocketClientParams):
+ def __init__(
+ self,
+ transport: BaseTransport,
+ session: WebsocketClientSession,
+ params: WebsocketClientParams,
+ ):
super().__init__(params)
+ self._transport = transport
self._session = session
self._params = params
@@ -178,6 +194,10 @@ class WebsocketClientOutputTransport(BaseOutputTransport):
await super().cancel(frame)
await self._session.disconnect()
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
await self._write_frame(frame)
@@ -250,12 +270,12 @@ class WebsocketClientTransport(BaseTransport):
def input(self) -> WebsocketClientInputTransport:
if not self._input:
- self._input = WebsocketClientInputTransport(self._session, self._params)
+ self._input = WebsocketClientInputTransport(self, self._session, self._params)
return self._input
def output(self) -> WebsocketClientOutputTransport:
if not self._output:
- self._output = WebsocketClientOutputTransport(self._session, self._params)
+ self._output = WebsocketClientOutputTransport(self, self._session, self._params)
return self._output
async def _on_connected(self, websocket):
diff --git a/src/pipecat/transports/network/websocket_server.py b/src/pipecat/transports/network/websocket_server.py
index 19ebe4a45..e542342a2 100644
--- a/src/pipecat/transports/network/websocket_server.py
+++ b/src/pipecat/transports/network/websocket_server.py
@@ -55,6 +55,7 @@ class WebsocketServerCallbacks(BaseModel):
class WebsocketServerInputTransport(BaseInputTransport):
def __init__(
self,
+ transport: BaseTransport,
host: str,
port: int,
params: WebsocketServerParams,
@@ -63,6 +64,7 @@ class WebsocketServerInputTransport(BaseInputTransport):
):
super().__init__(params, **kwargs)
+ self._transport = transport
self._host = host
self._port = port
self._params = params
@@ -102,6 +104,10 @@ class WebsocketServerInputTransport(BaseInputTransport):
await self.cancel_task(self._server_task)
self._server_task = None
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def _server_task_handler(self):
logger.info(f"Starting websocket server on {self._host}:{self._port}")
async with websockets.serve(self._client_handler, self._host, self._port) as server:
@@ -163,9 +169,10 @@ class WebsocketServerInputTransport(BaseInputTransport):
class WebsocketServerOutputTransport(BaseOutputTransport):
- def __init__(self, params: WebsocketServerParams, **kwargs):
+ def __init__(self, transport: BaseTransport, params: WebsocketServerParams, **kwargs):
super().__init__(params, **kwargs)
+ self._transport = transport
self._params = params
self._websocket: Optional[websockets.WebSocketServerProtocol] = None
@@ -189,6 +196,10 @@ class WebsocketServerOutputTransport(BaseOutputTransport):
await self._params.serializer.setup(frame)
self._send_interval = (self._audio_chunk_size / self.sample_rate) / 2
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def process_frame(self, frame: Frame, direction: FrameDirection):
await super().process_frame(frame, direction)
@@ -283,13 +294,15 @@ class WebsocketServerTransport(BaseTransport):
def input(self) -> WebsocketServerInputTransport:
if not self._input:
self._input = WebsocketServerInputTransport(
- self._host, self._port, self._params, self._callbacks, name=self._input_name
+ self, self._host, self._port, self._params, self._callbacks, name=self._input_name
)
return self._input
def output(self) -> WebsocketServerOutputTransport:
if not self._output:
- self._output = WebsocketServerOutputTransport(self._params, name=self._output_name)
+ self._output = WebsocketServerOutputTransport(
+ self, self._params, name=self._output_name
+ )
return self._output
async def _on_client_connected(self, websocket):
diff --git a/src/pipecat/transports/services/daily.py b/src/pipecat/transports/services/daily.py
index 7735ae91f..af7d2308c 100644
--- a/src/pipecat/transports/services/daily.py
+++ b/src/pipecat/transports/services/daily.py
@@ -6,7 +6,6 @@
import asyncio
import time
-import warnings
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Mapping, Optional
@@ -18,7 +17,7 @@ from daily import (
VirtualSpeakerDevice,
)
from loguru import logger
-from pydantic import BaseModel, model_validator
+from pydantic import BaseModel
from pipecat.audio.vad.vad_analyzer import VADAnalyzer, VADParams
from pipecat.frames.frames import (
@@ -124,7 +123,6 @@ class DailyTranscriptionSettings(BaseModel):
Attributes:
language: ISO language code for transcription (e.g. "en").
- tier: Deprecated. Use model instead.
model: Transcription model to use (e.g. "nova-2-general").
profanity_filter: Whether to filter profanity from transcripts.
redact: Whether to redact sensitive information.
@@ -135,7 +133,6 @@ class DailyTranscriptionSettings(BaseModel):
"""
language: str = "en"
- tier: Optional[str] = None
model: str = "nova-2-general"
profanity_filter: bool = True
redact: bool = False
@@ -144,16 +141,6 @@ class DailyTranscriptionSettings(BaseModel):
includeRawResponse: bool = True
extra: Mapping[str, Any] = {"interim_results": True}
- @model_validator(mode="before")
- def check_deprecated_fields(cls, values):
- with warnings.catch_warnings():
- warnings.simplefilter("always")
- if "tier" in values:
- warnings.warn(
- "Field 'tier' is deprecated, use 'model' instead.", DeprecationWarning
- )
- return values
-
class DailyParams(TransportParams):
"""Configuration parameters for Daily transport.
@@ -824,9 +811,16 @@ class DailyInputTransport(BaseInputTransport):
params: Configuration parameters.
"""
- def __init__(self, client: DailyTransportClient, params: DailyParams, **kwargs):
+ def __init__(
+ self,
+ transport: BaseTransport,
+ client: DailyTransportClient,
+ params: DailyParams,
+ **kwargs,
+ ):
super().__init__(params, **kwargs)
+ self._transport = transport
self._client = client
self._params = params
@@ -894,6 +888,7 @@ class DailyInputTransport(BaseInputTransport):
async def cleanup(self):
await super().cleanup()
await self._client.cleanup()
+ await self._transport.cleanup()
#
# FrameProcessor
@@ -903,7 +898,7 @@ class DailyInputTransport(BaseInputTransport):
await super().process_frame(frame, direction)
if isinstance(frame, UserImageRequestFrame):
- await self.request_participant_image(frame.user_id)
+ await self.request_participant_image(frame)
#
# Frames
@@ -940,16 +935,16 @@ class DailyInputTransport(BaseInputTransport):
self._video_renderers[participant_id] = {
"framerate": framerate,
"timestamp": 0,
- "render_next_frame": False,
+ "render_next_frame": [],
}
await self._client.capture_participant_video(
participant_id, self._on_participant_video_frame, framerate, video_source, color_format
)
- async def request_participant_image(self, participant_id: str):
- if participant_id in self._video_renderers:
- self._video_renderers[participant_id]["render_next_frame"] = True
+ async def request_participant_image(self, frame: UserImageRequestFrame):
+ if frame.user_id in self._video_renderers:
+ self._video_renderers[frame.user_id]["render_next_frame"].append(frame)
async def _on_participant_video_frame(self, participant_id: str, buffer, size, format):
render_frame = False
@@ -958,17 +953,24 @@ class DailyInputTransport(BaseInputTransport):
prev_time = self._video_renderers[participant_id]["timestamp"]
framerate = self._video_renderers[participant_id]["framerate"]
+ # Some times we render frames because of a request.
+ request_frame = None
+
if framerate > 0:
next_time = prev_time + 1 / framerate
render_frame = (next_time - curr_time) < 0.1
elif self._video_renderers[participant_id]["render_next_frame"]:
- self._video_renderers[participant_id]["render_next_frame"] = False
+ request_frame = self._video_renderers[participant_id]["render_next_frame"].pop(0)
render_frame = True
if render_frame:
frame = UserImageRawFrame(
- user_id=participant_id, image=buffer, size=size, format=format
+ user_id=participant_id,
+ request=request_frame,
+ image=buffer,
+ size=size,
+ format=format,
)
await self.push_frame(frame)
self._video_renderers[participant_id]["timestamp"] = curr_time
@@ -984,9 +986,12 @@ class DailyOutputTransport(BaseOutputTransport):
params: Configuration parameters.
"""
- def __init__(self, client: DailyTransportClient, params: DailyParams, **kwargs):
+ def __init__(
+ self, transport: BaseTransport, client: DailyTransportClient, params: DailyParams, **kwargs
+ ):
super().__init__(params, **kwargs)
+ self._transport = transport
self._client = client
# Whether we have seen a StartFrame already.
@@ -1021,6 +1026,7 @@ class DailyOutputTransport(BaseOutputTransport):
async def cleanup(self):
await super().cleanup()
await self._client.cleanup()
+ await self._transport.cleanup()
async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
await self._client.send_message(frame)
@@ -1122,12 +1128,16 @@ class DailyTransport(BaseTransport):
def input(self) -> DailyInputTransport:
if not self._input:
- self._input = DailyInputTransport(self._client, self._params, name=self._input_name)
+ self._input = DailyInputTransport(
+ self, self._client, self._params, name=self._input_name
+ )
return self._input
def output(self) -> DailyOutputTransport:
if not self._output:
- self._output = DailyOutputTransport(self._client, self._params, name=self._output_name)
+ self._output = DailyOutputTransport(
+ self, self._client, self._params, name=self._output_name
+ )
return self._output
#
diff --git a/src/pipecat/transports/services/livekit.py b/src/pipecat/transports/services/livekit.py
index 7018ea520..8ce5c885c 100644
--- a/src/pipecat/transports/services/livekit.py
+++ b/src/pipecat/transports/services/livekit.py
@@ -345,9 +345,17 @@ class LiveKitTransportClient:
class LiveKitInputTransport(BaseInputTransport):
- def __init__(self, client: LiveKitTransportClient, params: LiveKitParams, **kwargs):
+ def __init__(
+ self,
+ transport: BaseTransport,
+ client: LiveKitTransportClient,
+ params: LiveKitParams,
+ **kwargs,
+ ):
super().__init__(params, **kwargs)
+ self._transport = transport
self._client = client
+
self._audio_in_task = None
self._vad_analyzer: Optional[VADAnalyzer] = params.vad_analyzer
self._resampler = create_default_resampler()
@@ -377,6 +385,10 @@ class LiveKitInputTransport(BaseInputTransport):
if self._audio_in_task and (self._params.audio_in_enabled or self._params.vad_enabled):
await self.cancel_task(self._audio_in_task)
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def push_app_message(self, message: Any, sender: str):
frame = LiveKitTransportMessageUrgentFrame(message=message, participant_id=sender)
await self.push_frame(frame)
@@ -414,8 +426,15 @@ class LiveKitInputTransport(BaseInputTransport):
class LiveKitOutputTransport(BaseOutputTransport):
- def __init__(self, client: LiveKitTransportClient, params: LiveKitParams, **kwargs):
+ def __init__(
+ self,
+ transport: BaseTransport,
+ client: LiveKitTransportClient,
+ params: LiveKitParams,
+ **kwargs,
+ ):
super().__init__(params, **kwargs)
+ self._transport = transport
self._client = client
async def start(self, frame: StartFrame):
@@ -433,6 +452,10 @@ class LiveKitOutputTransport(BaseOutputTransport):
await super().cancel(frame)
await self._client.disconnect()
+ async def cleanup(self):
+ await super().cleanup()
+ await self._transport.cleanup()
+
async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
if isinstance(frame, (LiveKitTransportMessageFrame, LiveKitTransportMessageUrgentFrame)):
await self._client.send_data(frame.message.encode(), frame.participant_id)
@@ -499,13 +522,15 @@ class LiveKitTransport(BaseTransport):
def input(self) -> LiveKitInputTransport:
if not self._input:
- self._input = LiveKitInputTransport(self._client, self._params, name=self._input_name)
+ self._input = LiveKitInputTransport(
+ self, self._client, self._params, name=self._input_name
+ )
return self._input
def output(self) -> LiveKitOutputTransport:
if not self._output:
self._output = LiveKitOutputTransport(
- self._client, self._params, name=self._output_name
+ self, self._client, self._params, name=self._output_name
)
return self._output
@@ -574,13 +599,6 @@ class LiveKitTransport(BaseTransport):
)
await self._output.send_message(frame)
- async def cleanup(self):
- if self._input:
- await self._input.cleanup()
- if self._output:
- await self._output.cleanup()
- await self._client.disconnect()
-
async def on_room_event(self, event):
# Handle room events
pass
diff --git a/src/pipecat/utils/base_object.py b/src/pipecat/utils/base_object.py
index e51eac35d..1dee24ce7 100644
--- a/src/pipecat/utils/base_object.py
+++ b/src/pipecat/utils/base_object.py
@@ -4,6 +4,7 @@
# SPDX-License-Identifier: BSD 2-Clause License
#
+import asyncio
import inspect
from abc import ABC
from typing import Optional
@@ -17,8 +18,15 @@ class BaseObject(ABC):
def __init__(self, *, name: Optional[str] = None):
self._id: int = obj_id()
self._name = name or f"{self.__class__.__name__}#{obj_count(self)}"
+
+ # Registered event handlers.
self._event_handlers: dict = {}
+ # Set of tasks being executed. When a task finishes running it gets
+ # automatically removed from the set. When we cleanup we wait for all
+ # event tasks still being executed.
+ self._event_tasks = set()
+
@property
def id(self) -> int:
return self._id
@@ -27,6 +35,12 @@ class BaseObject(ABC):
def name(self) -> str:
return self._name
+ async def cleanup(self):
+ if self._event_tasks:
+ event_names, tasks = zip(*self._event_tasks)
+ logger.debug(f"{self} wating on event handlers to finish {list(event_names)}...")
+ await asyncio.wait(tasks)
+
def event_handler(self, event_name: str):
def decorator(handler):
self.add_event_handler(event_name, handler)
@@ -45,6 +59,16 @@ class BaseObject(ABC):
self._event_handlers[event_name] = []
async def _call_event_handler(self, event_name: str, *args, **kwargs):
+ # Create the task.
+ task = asyncio.create_task(self._run_task(event_name, *args, **kwargs))
+
+ # Add it to our list of event tasks.
+ self._event_tasks.add((event_name, task))
+
+ # Remove the task from the event tasks list when the task completes.
+ task.add_done_callback(self._event_task_finished)
+
+ async def _run_task(self, event_name: str, *args, **kwargs):
try:
for handler in self._event_handlers[event_name]:
if inspect.iscoroutinefunction(handler):
@@ -54,5 +78,10 @@ class BaseObject(ABC):
except Exception as e:
logger.exception(f"Exception in event handler {event_name}: {e}")
+ def _event_task_finished(self, task: asyncio.Task):
+ tuple_to_remove = next((t for t in self._event_tasks if t[1] == task), None)
+ if tuple_to_remove:
+ self._event_tasks.discard(tuple_to_remove)
+
def __str__(self):
return self.name
diff --git a/src/pipecat/utils/string.py b/src/pipecat/utils/string.py
index 154d03174..69036a665 100644
--- a/src/pipecat/utils/string.py
+++ b/src/pipecat/utils/string.py
@@ -5,10 +5,12 @@
#
import re
+from typing import Optional, Sequence, Tuple
ENDOFSENTENCE_PATTERN_STR = r"""
(? str:
+ """Replace occurrences of a substring within a matched section of a given
+ text.
+
+ Args:
+ text (str): The input text in which replacements will be made.
+ match (re.Match): A regex match object representing the section of text to modify.
+ old (str): The substring to be replaced.
+ new (str): The substring to replace `old` with.
+
+ Returns:
+ str: The modified text with the specified replacements made within the matched section.
+
+ """
+ start = match.start()
+ end = match.end()
+ replacement = text[start:end].replace(old, new)
+ text = text[:start] + replacement + text[end:]
+ return text
+
def match_endofsentence(text: str) -> int:
- match = ENDOFSENTENCE_PATTERN.search(text.rstrip())
+ """Finds the position of the end of a sentence in the provided text string.
+
+ This function processes the input text by replacing periods in email
+ addresses and numbers with ampersands to prevent them from being
+ misidentified as sentence terminals. It then searches for the end of a
+ sentence using a specified regex pattern.
+
+ Args:
+ text (str): The input text in which to find the end of the sentence.
+
+ Returns:
+ int: The position of the end of the sentence if found, otherwise 0.
+
+ """
+ text = text.rstrip()
+
+ # Replace email dots by ampersands so we can find the end of sentence. For
+ # example, first.last@email.com becomes first&last@email&com.
+ emails = list(EMAIL_PATTERN.finditer(text))
+ for email_match in emails:
+ text = replace_match(text, email_match, ".", "&")
+
+ # Replace number dots by ampersands so we can find the end of sentence.
+ numbers = list(NUMBER_PATTERN.finditer(text))
+ for number_match in numbers:
+ text = replace_match(text, number_match, ".", "&")
+
+ # Match against the new text.
+ match = ENDOFSENTENCE_PATTERN.search(text)
+
return match.end() if match else 0
+
+
+def parse_start_end_tags(
+ text: str,
+ tags: Sequence[StartEndTags],
+ current_tag: Optional[StartEndTags],
+ current_tag_index: int,
+) -> Tuple[Optional[StartEndTags], int]:
+ """Parses the given text to identify a pair of start/end tags.
+
+ If a start tag was previously found (i.e. current_tags is valid), wait for
+ the corresponding end tag. Otherwise, wait for a start tag.
+
+ This function will return the index in the text that we should start parsing
+ in the next call and the current or new tags.
+
+ Parameters:
+ - text (str): The text to be parsed.
+ - tags (Sequence[StartEndTags]): List of tuples containing start and end tags.
+ - current_tags (Optional[StartEndTags]): The currently active tags, if any.
+ - current_tags_index (int): The current index in the text.
+
+ Returns:
+ Tuple[Optional[StartEndTags], int]: A tuple containing None or the current
+ tag and the index of the text.
+
+ """
+ # If we are already inside a tag, check if the end tag is in the text.
+ if current_tag:
+ _, end_tag = current_tag
+ if end_tag in text[current_tag_index:]:
+ return (None, len(text))
+ return (current_tag, current_tag_index)
+
+ # Check if any start tag appears in the text
+ for start_tag, end_tag in tags:
+ start_tag_count = text[current_tag_index:].count(start_tag)
+ end_tag_count = text[current_tag_index:].count(end_tag)
+ if start_tag_count == 0 and end_tag_count == 0:
+ return (None, current_tag_index)
+ elif start_tag_count > end_tag_count:
+ return ((start_tag, end_tag), len(text))
+ elif start_tag_count == end_tag_count:
+ return (None, len(text))
+
+ return (None, current_tag_index)
diff --git a/src/pipecat/utils/test_frame_processor.py b/src/pipecat/utils/test_frame_processor.py
deleted file mode 100644
index b35864497..000000000
--- a/src/pipecat/utils/test_frame_processor.py
+++ /dev/null
@@ -1,48 +0,0 @@
-from typing import List
-
-from pipecat.processors.frame_processor import FrameProcessor
-
-
-class TestException(Exception):
- pass
-
-
-class TestFrameProcessor(FrameProcessor):
- __test__ = False # Prevents pytest from collecting this class as a test
-
- def __init__(self, test_frames):
- self.test_frames = test_frames
- self._list_counter = 0
- super().__init__()
-
- async def process_frame(self, frame, direction):
- await super().process_frame(frame, direction)
-
- if not self.test_frames[
- 0
- ]: # then we've run out of required frames but the generator is still going?
- raise TestException(f"Oops, got an extra frame, {frame}")
- if isinstance(self.test_frames[0], List):
- # We need to consume frames until we see the next frame type after this
- next_frame = self.test_frames[1]
- if isinstance(frame, next_frame):
- # we're done iterating the list I guess
- print(f"TestFrameProcessor got expected list exit frame: {frame}")
- # pop twice to get rid of the list, as well as the next frame
- self.test_frames.pop(0)
- self.test_frames.pop(0)
- self.list_counter = 0
- else:
- fl = self.test_frames[0]
- fl_el = fl[self._list_counter % len(fl)]
- if isinstance(frame, fl_el):
- print(f"TestFrameProcessor got expected list frame: {frame}")
- self._list_counter += 1
- else:
- raise TestException(f"Inside a list, expected {fl_el} but got {frame}")
-
- else:
- if not isinstance(frame, self.test_frames[0]):
- raise TestException(f"Expected {self.test_frames[0]}, but got {frame}")
- print(f"TestFrameProcessor got expected frame: {frame}")
- self.test_frames.pop(0)
diff --git a/src/pipecat/utils/text/base_text_aggregator.py b/src/pipecat/utils/text/base_text_aggregator.py
new file mode 100644
index 000000000..452e5598e
--- /dev/null
+++ b/src/pipecat/utils/text/base_text_aggregator.py
@@ -0,0 +1,57 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+from abc import ABC, abstractmethod
+from typing import Optional
+
+
+class BaseTextAggregator(ABC):
+ """This is the base class for text aggregators. Text aggregators are usually
+ used by the TTS service to aggregate LLM tokens and decide when the
+ aggregated text should be pushed to the TTS service.
+
+ Text aggregators can also be used to manipulate text while it's being
+ aggregated (e.g. reasoning blocks can be removed).
+
+ """
+
+ @property
+ @abstractmethod
+ def text(self) -> str:
+ """Returns the currently aggregated text."""
+ pass
+
+ @abstractmethod
+ def aggregate(self, text: str) -> Optional[str]:
+ """Aggregates the specified text with the currently accumulated text.
+
+ This method should be implemented to define how the new text contributes
+ to the aggregation process. It returns the updated aggregated text if
+ it's ready to be processed, or None otherwise.
+
+ Args:
+ text (str): The text to be aggregated.
+
+ Returns:
+ Optional[str]: The updated aggregated text or None if aggregated
+ text is not ready.
+
+ """
+ pass
+
+ @abstractmethod
+ def handle_interruption(self):
+ """Handles interruptions. When an interruption occurs it is possible
+ that we might want to discard the aggregated text or do some internal
+ modifications to the aggregated text.
+
+ """
+ pass
+
+ @abstractmethod
+ def reset(self):
+ """Clears the internally aggregated text."""
+ pass
diff --git a/src/pipecat/utils/text/pattern_pair_aggregator.py b/src/pipecat/utils/text/pattern_pair_aggregator.py
new file mode 100644
index 000000000..86f87103b
--- /dev/null
+++ b/src/pipecat/utils/text/pattern_pair_aggregator.py
@@ -0,0 +1,262 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import re
+from typing import Callable, Optional, Tuple
+
+from loguru import logger
+
+from pipecat.utils.string import match_endofsentence
+from pipecat.utils.text.base_text_aggregator import BaseTextAggregator
+
+
+class PatternMatch:
+ """Represents a matched pattern pair with its content.
+
+ A PatternMatch object is created when a complete pattern pair is found
+ in the text. It contains information about which pattern was matched,
+ the full matched text (including start and end patterns), and the
+ content between the patterns.
+
+ Attributes:
+ pattern_id: The identifier of the matched pattern pair.
+ full_match: The complete text including start and end patterns.
+ content: The text content between the start and end patterns.
+ """
+
+ def __init__(self, pattern_id: str, full_match: str, content: str):
+ """Initialize a pattern match.
+
+ Args:
+ pattern_id: ID of the pattern pair.
+ full_match: Complete matched text including start and end patterns.
+ content: Content between the start and end patterns.
+ """
+ self.pattern_id = pattern_id
+ self.full_match = full_match
+ self.content = content
+
+ def __str__(self) -> str:
+ """Return a string representation of the pattern match.
+
+ Returns:
+ A string describing the pattern match.
+ """
+ return f"PatternMatch(id={self.pattern_id}, content={self.content})"
+
+
+class PatternPairAggregator(BaseTextAggregator):
+ """Aggregator that identifies and processes content between pattern pairs.
+
+ This aggregator buffers text until it can identify complete pattern pairs
+ (defined by start and end patterns), processes the content between these
+ patterns using registered handlers, and returns text at sentence boundaries.
+ It's particularly useful for processing structured content in streaming text,
+ such as XML tags, markdown formatting, or custom delimiters.
+
+ The aggregator ensures that patterns spanning multiple text chunks are
+ correctly identified and handles cases where patterns contain sentence
+ boundaries.
+ """
+
+ def __init__(self):
+ """Initialize the pattern pair aggregator.
+
+ Creates an empty aggregator with no patterns or handlers registered.
+ """
+ self._text = ""
+ self._patterns = {}
+ self._handlers = {}
+
+ @property
+ def text(self) -> str:
+ """Get the currently buffered text.
+
+ Returns:
+ The current text buffer content.
+ """
+ return self._text
+
+ def add_pattern_pair(
+ self, pattern_id: str, start_pattern: str, end_pattern: str, remove_match: bool = True
+ ) -> "PatternPairAggregator":
+ """Add a pattern pair to detect in the text.
+
+ Registers a new pattern pair with a unique identifier. The aggregator
+ will look for text that starts with the start pattern and ends with
+ the end pattern, and treat the content between them as a match.
+
+ Args:
+ pattern_id: Unique identifier for this pattern pair.
+ start_pattern: Pattern that marks the beginning of content.
+ end_pattern: Pattern that marks the end of content.
+ remove_match: Whether to remove the matched content from the text.
+
+ Returns:
+ Self for method chaining.
+ """
+ self._patterns[pattern_id] = {
+ "start": start_pattern,
+ "end": end_pattern,
+ "remove_match": remove_match,
+ }
+ return self
+
+ def on_pattern_match(
+ self, pattern_id: str, handler: Callable[[PatternMatch], None]
+ ) -> "PatternPairAggregator":
+ """Register a handler for when a pattern pair is matched.
+
+ The handler will be called whenever a complete match for the
+ specified pattern ID is found in the text.
+
+ Args:
+ pattern_id: ID of the pattern pair to match.
+ handler: Function to call when pattern is matched.
+ The function should accept a PatternMatch object.
+
+ Returns:
+ Self for method chaining.
+ """
+ self._handlers[pattern_id] = handler
+ return self
+
+ def _process_complete_patterns(self, text: str) -> Tuple[str, bool]:
+ """Process all complete pattern pairs in the text.
+
+ Searches for all complete pattern pairs in the text, calls the
+ appropriate handlers, and optionally removes the matches.
+
+ Args:
+ text: The text to process.
+
+ Returns:
+ Tuple of (processed_text, was_modified) where:
+ - processed_text is the text after processing patterns
+ - was_modified indicates whether any changes were made
+ """
+ processed_text = text
+ modified = False
+
+ for pattern_id, pattern_info in self._patterns.items():
+ # Escape special regex characters in the patterns
+ start = re.escape(pattern_info["start"])
+ end = re.escape(pattern_info["end"])
+ remove_match = pattern_info["remove_match"]
+
+ # Create regex to match from start pattern to end pattern
+ # The .*? is non-greedy to handle nested patterns
+ regex = f"{start}(.*?){end}"
+
+ # Find all matches
+ match_iter = re.finditer(regex, processed_text, re.DOTALL)
+ matches = list(match_iter) # Convert to list for safe iteration
+
+ for match in matches:
+ content = match.group(1) # Content between patterns
+ full_match = match.group(0) # Full match including patterns
+
+ # Create pattern match object
+ pattern_match = PatternMatch(
+ pattern_id=pattern_id, full_match=full_match, content=content
+ )
+
+ # Call the appropriate handler if registered
+ if pattern_id in self._handlers:
+ try:
+ self._handlers[pattern_id](pattern_match)
+ except Exception as e:
+ logger.error(f"Error in pattern handler for {pattern_id}: {e}")
+
+ # Remove the pattern from the text if configured
+ if remove_match:
+ processed_text = processed_text.replace(full_match, "", 1)
+ modified = True
+
+ return processed_text, modified
+
+ def _has_incomplete_patterns(self, text: str) -> bool:
+ """Check if text contains incomplete pattern pairs.
+
+ Determines whether the text contains any start patterns without
+ matching end patterns, which would indicate incomplete content.
+
+ Args:
+ text: The text to check.
+
+ Returns:
+ True if there are incomplete patterns, False otherwise.
+ """
+ for pattern_id, pattern_info in self._patterns.items():
+ start = pattern_info["start"]
+ end = pattern_info["end"]
+
+ # Count occurrences
+ start_count = text.count(start)
+ end_count = text.count(end)
+
+ # If there are more starts than ends, we have incomplete patterns
+ if start_count > end_count:
+ return True
+
+ return False
+
+ def aggregate(self, text: str) -> Optional[str]:
+ """Aggregate text and process pattern pairs.
+
+ This method adds the new text to the buffer, processes any complete pattern
+ pairs, and returns processed text up to sentence boundaries if possible.
+ If there are incomplete patterns (start without matching end), it will
+ continue buffering text.
+
+ Args:
+ text: New text to add to the buffer.
+
+ Returns:
+ Processed text up to a sentence boundary, or None if more
+ text is needed to form a complete sentence or pattern.
+ """
+ # Add new text to buffer
+ self._text += text
+
+ # Process any complete patterns in the buffer
+ processed_text, modified = self._process_complete_patterns(self._text)
+
+ # Only update the buffer if modifications were made
+ if modified:
+ self._text = processed_text
+
+ # Check if we have incomplete patterns
+ if self._has_incomplete_patterns(self._text):
+ # Still waiting for complete patterns
+ return None
+
+ # Find sentence boundary if no incomplete patterns
+ eos_marker = match_endofsentence(self._text)
+ if eos_marker:
+ # Extract text up to the sentence boundary
+ result = self._text[:eos_marker]
+ self._text = self._text[eos_marker:]
+ return result
+
+ # No complete sentence found yet
+ return None
+
+ def handle_interruption(self):
+ """Handle interruptions by clearing the buffer.
+
+ Called when an interruption occurs in the processing pipeline,
+ to reset the state and discard any partially aggregated text.
+ """
+ self._text = ""
+
+ def reset(self):
+ """Clear the internally aggregated text.
+
+ Resets the aggregator to its initial state, discarding any
+ buffered text.
+ """
+ self._text = ""
diff --git a/src/pipecat/utils/text/simple_text_aggregator.py b/src/pipecat/utils/text/simple_text_aggregator.py
new file mode 100644
index 000000000..9022fc25a
--- /dev/null
+++ b/src/pipecat/utils/text/simple_text_aggregator.py
@@ -0,0 +1,42 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+from typing import Optional
+
+from pipecat.utils.string import match_endofsentence
+from pipecat.utils.text.base_text_aggregator import BaseTextAggregator
+
+
+class SimpleTextAggregator(BaseTextAggregator):
+ """This is a simple text aggregator. It aggregates text until an end of
+ sentence is found.
+
+ """
+
+ def __init__(self):
+ self._text = ""
+
+ @property
+ def text(self) -> str:
+ return self._text
+
+ def aggregate(self, text: str) -> Optional[str]:
+ result: Optional[str] = None
+
+ self._text += text
+
+ eos_end_marker = match_endofsentence(self._text)
+ if eos_end_marker:
+ result = self._text[:eos_end_marker]
+ self._text = self._text[eos_end_marker:]
+
+ return result
+
+ def handle_interruption(self):
+ self._text = ""
+
+ def reset(self):
+ self._text = ""
diff --git a/src/pipecat/utils/text/skip_tags_aggregator.py b/src/pipecat/utils/text/skip_tags_aggregator.py
new file mode 100644
index 000000000..00129028e
--- /dev/null
+++ b/src/pipecat/utils/text/skip_tags_aggregator.py
@@ -0,0 +1,94 @@
+#
+# Copyright (c) 2024–2025, Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+from typing import Optional, Sequence
+
+from pipecat.utils.string import StartEndTags, match_endofsentence, parse_start_end_tags
+from pipecat.utils.text.base_text_aggregator import BaseTextAggregator
+
+
+class SkipTagsAggregator(BaseTextAggregator):
+ """Aggregator that prevents end of sentence matching between start/end tags.
+
+ This aggregator buffers text until it finds an end of sentence or a start
+ tag. If a start tag is found the aggregator will keep aggregating text
+ unconditionally until the corresponding end tag is found. It's particularly
+ useful for processing content with custom delimiters that should prevent
+ text from being considered for end of sentence matching..
+
+ The aggregator ensures that tags spanning multiple text chunks are correctly
+ identified.
+
+ """
+
+ def __init__(self, tags: Sequence[StartEndTags]):
+ """Initialize the pattern pair aggregator.
+
+ Creates an empty aggregator with no patterns or handlers registered.
+ """
+ self._text = ""
+ self._tags = tags
+ self._current_tag: Optional[StartEndTags] = None
+ self._current_tag_index: int = 0
+
+ @property
+ def text(self) -> str:
+ """Get the currently buffered text.
+
+ Returns:
+ The current text buffer content.
+ """
+ return self._text
+
+ def aggregate(self, text: str) -> Optional[str]:
+ """Aggregate text and process pattern pairs.
+
+ This method adds the new text to the buffer, processes any complete pattern
+ pairs, and returns processed text up to sentence boundaries if possible.
+ If there are incomplete patterns (start without matching end), it will
+ continue buffering text.
+
+ Args:
+ text: New text to add to the buffer.
+
+ Returns:
+ Processed text up to a sentence boundary, or None if more
+ text is needed to form a complete sentence or pattern.
+ """
+ # Add new text to buffer
+ self._text += text
+
+ (self._current_tag, self._current_tag_index) = parse_start_end_tags(
+ self._text, self._tags, self._current_tag, self._current_tag_index
+ )
+
+ # Find sentence boundary if no incomplete patterns
+ if not self._current_tag:
+ eos_marker = match_endofsentence(self._text)
+ if eos_marker:
+ # Extract text up to the sentence boundary
+ result = self._text[:eos_marker]
+ self._text = self._text[eos_marker:]
+ return result
+
+ # No complete sentence found yet
+ return None
+
+ def handle_interruption(self):
+ """Handle interruptions by clearing the buffer.
+
+ Called when an interruption occurs in the processing pipeline,
+ to reset the state and discard any partially aggregated text.
+ """
+ self._text = ""
+
+ def reset(self):
+ """Clear the internally aggregated text.
+
+ Resets the aggregator to its initial state, discarding any
+ buffered text.
+ """
+ self._text = ""
diff --git a/src/pipecat/vad/__init__.py b/src/pipecat/vad/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/src/pipecat/vad/silero.py b/src/pipecat/vad/silero.py
deleted file mode 100644
index 285e2e0e8..000000000
--- a/src/pipecat/vad/silero.py
+++ /dev/null
@@ -1,16 +0,0 @@
-#
-# Copyright (c) 2024–2025, Daily
-#
-# SPDX-License-Identifier: BSD 2-Clause License
-#
-
-import warnings
-
-with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "Package `pipecat.vad` is deprecated, use `pipecat.audio.vad` instead", DeprecationWarning
- )
-
-from ..audio.vad.silero import SileroVADAnalyzer
-from ..processors.audio.vad.silero import SileroVAD
diff --git a/src/pipecat/vad/vad_analyzer.py b/src/pipecat/vad/vad_analyzer.py
deleted file mode 100644
index 7c8fc4c31..000000000
--- a/src/pipecat/vad/vad_analyzer.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright (c) 2024–2025, Daily
-#
-# SPDX-License-Identifier: BSD 2-Clause License
-#
-
-import warnings
-
-with warnings.catch_warnings():
- warnings.simplefilter("always")
- warnings.warn(
- "Package `pipecat.vad` is deprecated, use `pipecat.audio.vad` instead", DeprecationWarning
- )
-
-from ..audio.vad.vad_analyzer import VADAnalyzer, VADParams, VADState
diff --git a/tests/integration/integration_azure_llm.py b/tests/integration/integration_azure_llm.py
deleted file mode 100644
index 8e49e9d04..000000000
--- a/tests/integration/integration_azure_llm.py
+++ /dev/null
@@ -1,33 +0,0 @@
-import asyncio
-import os
-import unittest
-
-from openai.types.chat import (
- ChatCompletionSystemMessageParam,
-)
-
-from pipecat.processors.aggregators.openai_llm_context import (
- OpenAILLMContext,
- OpenAILLMContextFrame,
-)
-from pipecat.services.azure import AzureLLMService
-
-if __name__ == "__main__":
-
- @unittest.skip("Skip azure integration test")
- async def test_chat():
- llm = AzureLLMService(
- api_key=os.getenv("AZURE_CHATGPT_API_KEY"),
- endpoint=os.getenv("AZURE_CHATGPT_ENDPOINT"),
- model=os.getenv("AZURE_CHATGPT_MODEL"),
- )
- context = OpenAILLMContext()
- message: ChatCompletionSystemMessageParam = ChatCompletionSystemMessageParam(
- content="Please tell the world hello.", name="system", role="system"
- )
- context.add_message(message)
- frame = OpenAILLMContextFrame(context)
- async for s in llm.process_frame(frame):
- print(s)
-
- asyncio.run(test_chat())
diff --git a/tests/integration/integration_ollama_llm.py b/tests/integration/integration_ollama_llm.py
deleted file mode 100644
index 085500cb8..000000000
--- a/tests/integration/integration_ollama_llm.py
+++ /dev/null
@@ -1,28 +0,0 @@
-import asyncio
-import unittest
-
-from openai.types.chat import (
- ChatCompletionSystemMessageParam,
-)
-
-from pipecat.processors.aggregators.openai_llm_context import (
- OpenAILLMContext,
- OpenAILLMContextFrame,
-)
-from pipecat.services.ollama import OLLamaLLMService
-
-if __name__ == "__main__":
-
- @unittest.skip("Skip azure integration test")
- async def test_chat():
- llm = OLLamaLLMService()
- context = OpenAILLMContext()
- message: ChatCompletionSystemMessageParam = ChatCompletionSystemMessageParam(
- content="Please tell the world hello.", name="system", role="system"
- )
- context.add_message(message)
- frame = OpenAILLMContextFrame(context)
- async for s in llm.process_frame(frame):
- print(s)
-
- asyncio.run(test_chat())
diff --git a/tests/integration/integration_openai_llm.py b/tests/integration/integration_openai_llm.py
deleted file mode 100644
index 2c84c8882..000000000
--- a/tests/integration/integration_openai_llm.py
+++ /dev/null
@@ -1,128 +0,0 @@
-import asyncio
-import json
-import os
-from typing import List
-
-from openai.types.chat import (
- ChatCompletionSystemMessageParam,
- ChatCompletionToolParam,
- ChatCompletionUserMessageParam,
-)
-
-from pipecat.frames.frames import LLMFullResponseEndFrame, LLMFullResponseStartFrame, TextFrame
-from pipecat.processors.frame_processor import FrameDirection
-from pipecat.services.openai import OpenAILLMContext, OpenAILLMContextFrame, OpenAILLMService
-from pipecat.utils.test_frame_processor import TestFrameProcessor
-
-tools = [
- ChatCompletionToolParam(
- type="function",
- function={
- "name": "get_current_weather",
- "description": "Get the current weather",
- "parameters": {
- "type": "object",
- "properties": {
- "location": {
- "type": "string",
- "description": "The city and state, e.g. San Francisco, CA",
- },
- "format": {
- "type": "string",
- "enum": ["celsius", "fahrenheit"],
- "description": "The temperature unit to use. Infer this from the users location.",
- },
- },
- "required": ["location", "format"],
- },
- },
- )
-]
-
-if __name__ == "__main__":
-
- async def test_simple_functions():
- async def get_weather_from_api(llm, args):
- return json.dumps({"conditions": "nice", "temperature": "75"})
-
- api_key = os.getenv("OPENAI_API_KEY")
-
- llm = OpenAILLMService(
- api_key=api_key or "",
- model="gpt-4-1106-preview",
- )
-
- llm.register_function("get_current_weather", get_weather_from_api)
- t = TestFrameProcessor([LLMFullResponseStartFrame, TextFrame, LLMFullResponseEndFrame])
- llm.link(t)
-
- context = OpenAILLMContext(tools=tools)
- system_message: ChatCompletionSystemMessageParam = ChatCompletionSystemMessageParam(
- content="Ask the user to ask for a weather report", name="system", role="system"
- )
- user_message: ChatCompletionUserMessageParam = ChatCompletionUserMessageParam(
- content="Could you tell me the weather for Boulder, Colorado",
- name="user",
- role="user",
- )
- context.add_message(system_message)
- context.add_message(user_message)
- frame = OpenAILLMContextFrame(context)
- await llm.process_frame(frame, FrameDirection.DOWNSTREAM)
-
- async def test_advanced_functions():
- async def get_weather_from_api(llm, args):
- return [
- {
- "role": "system",
- "content": "The user has asked for live weather. Respond by telling them we don't currently support live weather for that area, but it's coming soon.",
- }
- ]
-
- api_key = os.getenv("OPENAI_API_KEY")
-
- llm = OpenAILLMService(
- api_key=api_key or "",
- model="gpt-4-1106-preview",
- )
-
- llm.register_function("get_current_weather", get_weather_from_api)
- t = TestFrameProcessor([LLMFullResponseStartFrame, TextFrame, LLMFullResponseEndFrame])
- llm.link(t)
-
- context = OpenAILLMContext(tools=tools)
- system_message: ChatCompletionSystemMessageParam = ChatCompletionSystemMessageParam(
- content="Ask the user to ask for a weather report", name="system", role="system"
- )
- user_message: ChatCompletionUserMessageParam = ChatCompletionUserMessageParam(
- content="Could you tell me the weather for Boulder, Colorado",
- name="user",
- role="user",
- )
- context.add_message(system_message)
- context.add_message(user_message)
- frame = OpenAILLMContextFrame(context)
- await llm.process_frame(frame, FrameDirection.DOWNSTREAM)
-
- async def test_chat():
- api_key = os.getenv("OPENAI_API_KEY")
- t = TestFrameProcessor([LLMFullResponseStartFrame, TextFrame, LLMFullResponseEndFrame])
- llm = OpenAILLMService(
- api_key=api_key or "",
- model="gpt-4o",
- )
- llm.link(t)
- context = OpenAILLMContext()
- message: ChatCompletionSystemMessageParam = ChatCompletionSystemMessageParam(
- content="Please tell the world hello.", name="system", role="system"
- )
- context.add_message(message)
- frame = OpenAILLMContextFrame(context)
- await llm.process_frame(frame, FrameDirection.DOWNSTREAM)
-
- async def run_tests():
- await test_simple_functions()
- await test_advanced_functions()
- await test_chat()
-
- asyncio.run(run_tests())
diff --git a/tests/integration/test_integration_unified_function_calling.py b/tests/integration/test_integration_unified_function_calling.py
index 88407d703..0696c531a 100644
--- a/tests/integration/test_integration_unified_function_calling.py
+++ b/tests/integration/test_integration_unified_function_calling.py
@@ -1,3 +1,9 @@
+#
+# Copyright (c) 2024-2025 Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
import os
from unittest.mock import AsyncMock
@@ -6,17 +12,12 @@ from dotenv import load_dotenv
from pipecat.adapters.schemas.function_schema import FunctionSchema
from pipecat.adapters.schemas.tools_schema import ToolsSchema
-from pipecat.frames.frames import (
- LLMFullResponseEndFrame,
- LLMFullResponseStartFrame,
- LLMTextFrame,
-)
-from pipecat.processors.frame_processor import FrameDirection
+from pipecat.pipeline.pipeline import Pipeline
from pipecat.services.ai_services import LLMService
from pipecat.services.anthropic import AnthropicLLMService
from pipecat.services.google import GoogleLLMService
from pipecat.services.openai import OpenAILLMContext, OpenAILLMContextFrame, OpenAILLMService
-from pipecat.utils.test_frame_processor import TestFrameProcessor
+from pipecat.tests.utils import run_test
load_dotenv(override=True)
@@ -47,8 +48,6 @@ async def _test_llm_function_calling(llm: LLMService):
mock_fetch_weather = AsyncMock()
llm.register_function(None, mock_fetch_weather)
- t = TestFrameProcessor([LLMFullResponseStartFrame, LLMTextFrame, LLMFullResponseEndFrame])
- llm.link(t)
messages = [
{
@@ -61,10 +60,14 @@ async def _test_llm_function_calling(llm: LLMService):
# This is done by default inside the create_context_aggregator
context.set_llm_adapter(llm.get_llm_adapter())
- frame = OpenAILLMContextFrame(context)
+ pipeline = Pipeline([llm])
- # This will fail if an exception is raised
- await llm.process_frame(frame, FrameDirection.DOWNSTREAM)
+ frames_to_send = [OpenAILLMContextFrame(context)]
+ await run_test(
+ pipeline,
+ frames_to_send=frames_to_send,
+ expected_down_frames=None,
+ )
# Assert that the mock function was called
mock_fetch_weather.assert_called_once()
diff --git a/tests/test_context_aggregators.py b/tests/test_context_aggregators.py
index d4b8c35ce..185725632 100644
--- a/tests/test_context_aggregators.py
+++ b/tests/test_context_aggregators.py
@@ -44,8 +44,6 @@ from pipecat.tests.utils import SleepFrame, run_test
AGGREGATION_TIMEOUT = 0.1
AGGREGATION_SLEEP = 0.15
-BOT_INTERRUPTION_TIMEOUT = 0.2
-BOT_INTERRUPTION_SLEEP = 0.25
class BaseTestUserContextAggregator:
@@ -388,14 +386,13 @@ class BaseTestUserContextAggregator:
aggregator = self.AGGREGATOR_CLASS(
context,
aggregation_timeout=AGGREGATION_TIMEOUT,
- bot_interruption_timeout=BOT_INTERRUPTION_TIMEOUT,
)
frames_to_send = [
UserStartedSpeakingFrame(),
InterimTranscriptionFrame(text="How ", user_id="cat", timestamp=""),
SleepFrame(),
UserStoppedSpeakingFrame(),
- SleepFrame(BOT_INTERRUPTION_SLEEP),
+ SleepFrame(AGGREGATION_SLEEP),
InterimTranscriptionFrame(text="are you?", user_id="cat", timestamp=""),
TranscriptionFrame(text="How are you?", user_id="cat", timestamp=""),
SleepFrame(sleep=AGGREGATION_SLEEP),
@@ -405,12 +402,10 @@ class BaseTestUserContextAggregator:
UserStoppedSpeakingFrame,
*self.EXPECTED_CONTEXT_FRAMES,
]
- expected_up_frames = [EmulateUserStartedSpeakingFrame, EmulateUserStoppedSpeakingFrame]
await run_test(
aggregator,
frames_to_send=frames_to_send,
expected_down_frames=expected_down_frames,
- expected_up_frames=expected_up_frames,
)
self.check_message_content(context, 0, "How are you?")
@@ -418,7 +413,7 @@ class BaseTestUserContextAggregator:
class BaseTestAssistantContextAggreagator:
CONTEXT_CLASS = None # To be set in subclasses
AGGREGATOR_CLASS = None # To be set in subclasses
- EXPECTED_CONTEXT_FRAMES = [OpenAILLMContextFrame]
+ EXPECTED_CONTEXT_FRAMES = None # To be set in subclasses
def check_message_content(self, context: OpenAILLMContext, index: int, content: str):
assert context.messages[index]["content"] == content
@@ -577,6 +572,7 @@ class TestLLMAssistantContextAggregator(
):
CONTEXT_CLASS = OpenAILLMContext
AGGREGATOR_CLASS = LLMAssistantContextAggregator
+ EXPECTED_CONTEXT_FRAMES = [OpenAILLMContextFrame, OpenAILLMContextAssistantTimestampFrame]
#
diff --git a/tests/test_pattern_pair_aggregator.py b/tests/test_pattern_pair_aggregator.py
new file mode 100644
index 000000000..e1086e577
--- /dev/null
+++ b/tests/test_pattern_pair_aggregator.py
@@ -0,0 +1,147 @@
+#
+# Copyright (c) 2024-2025 Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import unittest
+from unittest.mock import Mock
+
+from pipecat.utils.text.pattern_pair_aggregator import PatternMatch, PatternPairAggregator
+
+
+class TestPatternPairAggregator(unittest.IsolatedAsyncioTestCase):
+ def setUp(self):
+ self.aggregator = PatternPairAggregator()
+ self.test_handler = Mock()
+
+ # Add a test pattern
+ self.aggregator.add_pattern_pair(
+ pattern_id="test_pattern",
+ start_pattern="",
+ end_pattern="",
+ remove_match=True,
+ )
+
+ # Register the mock handler
+ self.aggregator.on_pattern_match("test_pattern", self.test_handler)
+
+ async def test_pattern_match_and_removal(self):
+ # First part doesn't complete the pattern
+ result = self.aggregator.aggregate("Hello pattern")
+ self.assertIsNone(result)
+ self.assertEqual(self.aggregator.text, "Hello pattern")
+
+ # Second part completes the pattern and includes an exclamation point
+ result = self.aggregator.aggregate(" content!")
+
+ # Verify the handler was called with correct PatternMatch object
+ self.test_handler.assert_called_once()
+ call_args = self.test_handler.call_args[0][0]
+ self.assertIsInstance(call_args, PatternMatch)
+ self.assertEqual(call_args.pattern_id, "test_pattern")
+ self.assertEqual(call_args.full_match, "pattern content")
+ self.assertEqual(call_args.content, "pattern content")
+
+ # The exclamation point should be treated as a sentence boundary,
+ # so the result should include just text up to and including "!"
+ self.assertEqual(result, "Hello !")
+
+ # Next sentence should be processed separately
+ result = self.aggregator.aggregate(" This is another sentence.")
+ self.assertEqual(result, " This is another sentence.")
+
+ # Buffer should be empty after returning a complete sentence
+ self.assertEqual(self.aggregator.text, "")
+
+ async def test_incomplete_pattern(self):
+ # Add text with incomplete pattern
+ result = self.aggregator.aggregate("Hello pattern content")
+
+ # No complete pattern yet, so nothing should be returned
+ self.assertIsNone(result)
+
+ # The handler should not be called yet
+ self.test_handler.assert_not_called()
+
+ # Buffer should contain the incomplete text
+ self.assertEqual(self.aggregator.text, "Hello pattern content")
+
+ # Reset and confirm buffer is cleared
+ self.aggregator.reset()
+ self.assertEqual(self.aggregator.text, "")
+
+ async def test_multiple_patterns(self):
+ # Set up multiple patterns and handlers
+ voice_handler = Mock()
+ emphasis_handler = Mock()
+
+ self.aggregator.add_pattern_pair(
+ pattern_id="voice", start_pattern="", end_pattern="", remove_match=True
+ )
+
+ self.aggregator.add_pattern_pair(
+ pattern_id="emphasis",
+ start_pattern="",
+ end_pattern="",
+ remove_match=False, # Keep emphasis tags
+ )
+
+ self.aggregator.on_pattern_match("voice", voice_handler)
+ self.aggregator.on_pattern_match("emphasis", emphasis_handler)
+
+ # Test with multiple patterns in one text block
+ text = "Hello female I am very excited to meet you!"
+ result = self.aggregator.aggregate(text)
+
+ # Both handlers should be called with correct data
+ voice_handler.assert_called_once()
+ voice_match = voice_handler.call_args[0][0]
+ self.assertEqual(voice_match.pattern_id, "voice")
+ self.assertEqual(voice_match.content, "female")
+
+ emphasis_handler.assert_called_once()
+ emphasis_match = emphasis_handler.call_args[0][0]
+ self.assertEqual(emphasis_match.pattern_id, "emphasis")
+ self.assertEqual(emphasis_match.content, "very")
+
+ # Voice pattern should be removed, emphasis pattern should remain
+ self.assertEqual(result, "Hello I am very excited to meet you!")
+
+ # Buffer should be empty
+ self.assertEqual(self.aggregator.text, "")
+
+ async def test_handle_interruption(self):
+ # Start with incomplete pattern
+ result = self.aggregator.aggregate("Hello pattern")
+ self.assertIsNone(result)
+
+ # Simulate interruption
+ self.aggregator.handle_interruption()
+
+ # Buffer should be cleared
+ self.assertEqual(self.aggregator.text, "")
+
+ # Handler should not have been called
+ self.test_handler.assert_not_called()
+
+ async def test_pattern_across_sentences(self):
+ # Test pattern that spans multiple sentences
+ result = self.aggregator.aggregate("Hello This is sentence one.")
+
+ # First sentence contains start of pattern but no end, so no complete pattern yet
+ self.assertIsNone(result)
+
+ # Add second part with pattern end
+ result = self.aggregator.aggregate(" This is sentence two. Final sentence.")
+
+ # Handler should be called with entire content
+ self.test_handler.assert_called_once()
+ call_args = self.test_handler.call_args[0][0]
+ self.assertEqual(call_args.content, "This is sentence one. This is sentence two.")
+
+ # Pattern should be removed, resulting in text with sentences merged
+ self.assertEqual(result, "Hello Final sentence.")
+
+ # Buffer should be empty
+ self.assertEqual(self.aggregator.text, "")
diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py
index 07abef48e..46114b5b2 100644
--- a/tests/test_pipeline.py
+++ b/tests/test_pipeline.py
@@ -5,6 +5,7 @@
#
import asyncio
+import time
import unittest
from pipecat.frames.frames import EndFrame, HeartbeatFrame, StartFrame, TextFrame
@@ -12,7 +13,7 @@ from pipecat.pipeline.parallel_pipeline import ParallelPipeline
from pipecat.pipeline.pipeline import Pipeline
from pipecat.pipeline.task import PipelineParams, PipelineTask
from pipecat.processors.filters.identity_filter import IdentityFilter
-from pipecat.processors.frame_processor import FrameProcessor
+from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
from pipecat.tests.utils import HeartbeatsObserver, run_test
@@ -94,6 +95,42 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
await task.run()
assert task.has_finished()
+ async def test_task_event_handlers(self):
+ upstream_received = False
+ downstream_received = False
+
+ identity = IdentityFilter()
+ pipeline = Pipeline([identity])
+ task = PipelineTask(pipeline, cancel_on_idle_timeout=False)
+ task.set_event_loop(asyncio.get_event_loop())
+ task.set_reached_upstream_filter((TextFrame,))
+ task.set_reached_downstream_filter((TextFrame,))
+
+ @task.event_handler("on_frame_reached_upstream")
+ async def on_frame_reached_upstream(task, frame):
+ nonlocal upstream_received
+ if isinstance(frame, TextFrame) and frame.text == "Hello Upstream!":
+ upstream_received = True
+
+ @task.event_handler("on_frame_reached_downstream")
+ async def on_frame_reached_downstream(task, frame):
+ nonlocal downstream_received
+ if isinstance(frame, TextFrame) and frame.text == "Hello Downstream!":
+ downstream_received = True
+ await identity.push_frame(
+ TextFrame(text="Hello Upstream!"), FrameDirection.UPSTREAM
+ )
+
+ await task.queue_frame(TextFrame(text="Hello Downstream!"))
+
+ try:
+ await asyncio.wait_for(asyncio.shield(task.run()), timeout=1.0)
+ except asyncio.TimeoutError:
+ pass
+
+ assert upstream_received
+ assert downstream_received
+
async def test_task_heartbeats(self):
heartbeats_counter = 0
@@ -113,6 +150,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
heartbeats_period_secs=0.2,
),
observers=[heartbeats_observer],
+ cancel_on_idle_timeout=False,
)
task.set_event_loop(asyncio.get_event_loop())
@@ -120,7 +158,90 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
await task.queue_frame(TextFrame(text="Hello!"))
try:
- await asyncio.wait_for(task.run(), timeout=1.0)
+ await asyncio.wait_for(asyncio.shield(task.run()), timeout=1.0)
except asyncio.TimeoutError:
pass
assert heartbeats_counter == expected_heartbeats
+
+ async def test_idle_task(self):
+ identity = IdentityFilter()
+ pipeline = Pipeline([identity])
+ task = PipelineTask(pipeline, idle_timeout_secs=0.2)
+ task.set_event_loop(asyncio.get_event_loop())
+ await task.run()
+ assert True
+
+ async def test_no_idle_task(self):
+ identity = IdentityFilter()
+ pipeline = Pipeline([identity])
+ task = PipelineTask(pipeline, idle_timeout_secs=0.2, cancel_on_idle_timeout=False)
+ task.set_event_loop(asyncio.get_event_loop())
+ try:
+ await asyncio.wait_for(asyncio.shield(task.run()), timeout=0.3)
+ except asyncio.TimeoutError:
+ assert True
+ else:
+ assert False
+
+ async def test_idle_task_heartbeats(self):
+ identity = IdentityFilter()
+ pipeline = Pipeline([identity])
+ task = PipelineTask(
+ pipeline,
+ params=PipelineParams(
+ enable_heartbeats=True,
+ heartbeats_period_secs=0.1,
+ ),
+ idle_timeout_secs=0.3,
+ )
+ task.set_event_loop(asyncio.get_event_loop())
+ await task.run()
+ assert True
+
+ async def test_idle_task_event_handler(self):
+ identity = IdentityFilter()
+ pipeline = Pipeline([identity])
+ task = PipelineTask(pipeline, idle_timeout_secs=0.2, cancel_on_idle_timeout=False)
+ task.set_event_loop(asyncio.get_event_loop())
+
+ idle_timeout = False
+
+ @task.event_handler("on_idle_timeout")
+ async def on_idle_timeout(task: PipelineTask):
+ nonlocal idle_timeout
+ idle_timeout = True
+ await task.cancel()
+
+ await task.run()
+ assert True
+
+ async def test_idle_task_frames(self):
+ idle_timeout_secs = 0.2
+ sleep_time_secs = idle_timeout_secs / 2
+
+ identity = IdentityFilter()
+ pipeline = Pipeline([identity])
+ task = PipelineTask(
+ pipeline,
+ idle_timeout_secs=idle_timeout_secs,
+ idle_timeout_frames=(TextFrame,),
+ )
+ task.set_event_loop(asyncio.get_event_loop())
+
+ async def delayed_frames():
+ await asyncio.sleep(sleep_time_secs)
+ await task.queue_frame(TextFrame("Hello Pipecat!"))
+ await asyncio.sleep(sleep_time_secs)
+ await task.queue_frame(TextFrame("Hello Pipecat!"))
+ await asyncio.sleep(sleep_time_secs)
+ await task.queue_frame(TextFrame("Hello Pipecat!"))
+
+ start_time = time.time()
+
+ tasks = {asyncio.create_task(task.run()), asyncio.create_task(delayed_frames())}
+
+ await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+
+ diff_time = time.time() - start_time
+
+ self.assertGreater(diff_time, sleep_time_secs * 3)
diff --git a/tests/test_simple_text_aggregator.py b/tests/test_simple_text_aggregator.py
new file mode 100644
index 000000000..10c4c6a88
--- /dev/null
+++ b/tests/test_simple_text_aggregator.py
@@ -0,0 +1,29 @@
+#
+# Copyright (c) 2024-2025 Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import unittest
+
+from pipecat.utils.text.simple_text_aggregator import SimpleTextAggregator
+
+
+class TestSimpleTextAggregator(unittest.IsolatedAsyncioTestCase):
+ def setUp(self):
+ self.aggregator = SimpleTextAggregator()
+
+ async def test_reset_aggregations(self):
+ assert self.aggregator.aggregate("Hello ") == None
+ assert self.aggregator.text == "Hello "
+ self.aggregator.reset()
+ assert self.aggregator.text == ""
+
+ async def test_simple_sentence(self):
+ assert self.aggregator.aggregate("Hello ") == None
+ assert self.aggregator.aggregate("Pipecat!") == "Hello Pipecat!"
+ assert self.aggregator.text == ""
+
+ async def test_multiple_sentences(self):
+ assert self.aggregator.aggregate("Hello Pipecat! How are ") == "Hello Pipecat!"
+ assert self.aggregator.aggregate("you?") == " How are you?"
diff --git a/tests/test_skip_tags_aggregator.py b/tests/test_skip_tags_aggregator.py
new file mode 100644
index 000000000..8f36c4c05
--- /dev/null
+++ b/tests/test_skip_tags_aggregator.py
@@ -0,0 +1,54 @@
+#
+# Copyright (c) 2024-2025 Daily
+#
+# SPDX-License-Identifier: BSD 2-Clause License
+#
+
+import unittest
+
+from pipecat.utils.text.skip_tags_aggregator import SkipTagsAggregator
+
+
+class TestSkipTagsAggregator(unittest.IsolatedAsyncioTestCase):
+ def setUp(self):
+ self.aggregator = SkipTagsAggregator([("", "")])
+
+ async def test_no_tags(self):
+ self.aggregator.reset()
+
+ # No tags involved, aggregate at end of sentence.
+ result = self.aggregator.aggregate("Hello Pipecat!")
+ self.assertEqual(result, "Hello Pipecat!")
+ self.assertEqual(self.aggregator.text, "")
+
+ async def test_basic_tags(self):
+ self.aggregator.reset()
+
+ # Tags involved, avoid aggregation during tags.
+ result = self.aggregator.aggregate("My email is foo@pipecat.ai.")
+ self.assertEqual(result, "My email is foo@pipecat.ai.")
+ self.assertEqual(self.aggregator.text, "")
+
+ async def test_streaming_tags(self):
+ self.aggregator.reset()
+
+ # Tags involved, stream small chunk of texts.
+ result = self.aggregator.aggregate("My email is foo.")
+ self.assertIsNone(result)
+ self.assertEqual(self.aggregator.text, "My email is foo.")
+
+ result = self.aggregator.aggregate("bar@pipecat.")
+ self.assertIsNone(result)
+ self.assertEqual(self.aggregator.text, "My email is foo.bar@pipecat.")
+
+ result = self.aggregator.aggregate("aifoo.bar@pipecat.ai.")
+ self.assertEqual(result, "My email is foo.bar@pipecat.ai.")
+ self.assertEqual(self.aggregator.text, "")
diff --git a/tests/test_transcript_processor.py b/tests/test_transcript_processor.py
index 1c6db277f..d13246b2c 100644
--- a/tests/test_transcript_processor.py
+++ b/tests/test_transcript_processor.py
@@ -235,8 +235,7 @@ class TestUserTranscriptProcessor(unittest.IsolatedAsyncioTestCase):
BotStartedSpeakingFrame(),
SleepFrame(sleep=0.1),
TTSTextFrame(text="Hello"),
- TTSTextFrame(text="world"),
- TTSTextFrame(text="!"),
+ TTSTextFrame(text="world!"),
SleepFrame(sleep=0.1),
StartInterruptionFrame(), # User interrupts here
BotStartedSpeakingFrame(),
@@ -251,8 +250,7 @@ class TestUserTranscriptProcessor(unittest.IsolatedAsyncioTestCase):
expected_down_frames = [
BotStartedSpeakingFrame,
TTSTextFrame, # "Hello"
- TTSTextFrame, # "world"
- TTSTextFrame, # "!"
+ TTSTextFrame, # "world!"
TranscriptionUpdateFrame, # First message (emitted due to interruption)
StartInterruptionFrame, # Interruption frame comes after the update
BotStartedSpeakingFrame,
@@ -275,7 +273,7 @@ class TestUserTranscriptProcessor(unittest.IsolatedAsyncioTestCase):
# First update should be interrupted message
first_message = received_updates[0].messages[0]
self.assertEqual(first_message.role, "assistant")
- self.assertEqual(first_message.content, "Hello world !")
+ self.assertEqual(first_message.content, "Hello world!")
self.assertIsNotNone(first_message.timestamp)
# Second update should be new response
@@ -426,3 +424,57 @@ class TestUserTranscriptProcessor(unittest.IsolatedAsyncioTestCase):
self.assertEqual(received_updates[0].content, "User message")
self.assertEqual(received_updates[1].role, "assistant")
self.assertEqual(received_updates[1].content, "Assistant message")
+
+ async def test_text_fragments_with_spaces(self):
+ """Test aggregating text fragments with various spacing patterns"""
+ processor = AssistantTranscriptProcessor()
+
+ # Track received updates
+ received_updates = []
+
+ @processor.event_handler("on_transcript_update")
+ async def handle_update(proc, frame: TranscriptionUpdateFrame):
+ received_updates.append(frame)
+
+ # Test the specific pattern shared
+ frames_to_send = [
+ BotStartedSpeakingFrame(),
+ SleepFrame(sleep=0.1),
+ TTSTextFrame(text="Hello"),
+ TTSTextFrame(text=" there"),
+ TTSTextFrame(text="!"),
+ TTSTextFrame(text=" How"),
+ TTSTextFrame(text="'s"),
+ TTSTextFrame(text=" it"),
+ TTSTextFrame(text=" going"),
+ TTSTextFrame(text="?"),
+ BotStoppedSpeakingFrame(),
+ ]
+
+ expected_down_frames = [
+ BotStartedSpeakingFrame,
+ BotStoppedSpeakingFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TTSTextFrame,
+ TranscriptionUpdateFrame,
+ ]
+
+ # Run test
+ received_frames, _ = await run_test(
+ processor,
+ frames_to_send=frames_to_send,
+ expected_down_frames=expected_down_frames,
+ )
+
+ # Verify result
+ self.assertEqual(len(received_updates), 1)
+ message = received_updates[0].messages[0]
+ self.assertEqual(message.role, "assistant")
+ # Should be properly joined without extra spaces
+ self.assertEqual(message.content, "Hello there! How's it going?")
diff --git a/tests/test_utils_string.py b/tests/test_utils_string.py
index e4cdb4cb4..cabd88a36 100644
--- a/tests/test_utils_string.py
+++ b/tests/test_utils_string.py
@@ -6,7 +6,7 @@
import unittest
-from pipecat.utils.string import match_endofsentence
+from pipecat.utils.string import match_endofsentence, parse_start_end_tags
class TestUtilsString(unittest.IsolatedAsyncioTestCase):
@@ -18,6 +18,15 @@ class TestUtilsString(unittest.IsolatedAsyncioTestCase):
assert match_endofsentence("This is a sentence...") == 21
assert match_endofsentence("This is a sentence . . .") == 24
assert match_endofsentence("This is a sentence. ..") == 22
+ assert match_endofsentence("This is for Mr. and Mrs. Jones.") == 31
+ assert match_endofsentence("U.S.A and U.S.A..") == 17
+ assert match_endofsentence("My emails are foo@pipecat.ai and bar@pipecat.ai.") == 48
+ assert match_endofsentence("My email is foo.bar@pipecat.ai.") == 31
+ assert match_endofsentence("My email is spell(foo.bar@pipecat.ai).") == 38
+ assert match_endofsentence("My email is foo.bar@pipecat.ai.") == 46
+ assert match_endofsentence("The number pi is 3.14159.") == 25
+ assert match_endofsentence("Valid scientific notation 1.23e4.") == 33
+ assert match_endofsentence("Valid scientific notation 0.e4.") == 31
assert not match_endofsentence("This is not a sentence")
assert not match_endofsentence("This is not a sentence,")
assert not match_endofsentence("This is not a sentence, ")
@@ -28,6 +37,8 @@ class TestUtilsString(unittest.IsolatedAsyncioTestCase):
assert not match_endofsentence("Heute ist Dienstag, der 3.") # 3. Juli 2024
assert not match_endofsentence("America, or the U.") # U.S.A.
assert not match_endofsentence("It still early, it's 3:00 a.") # 3:00 a.m.
+ assert not match_endofsentence("My emails are foo@pipecat.ai and bar@pipecat.ai")
+ assert not match_endofsentence("The number pi is 3.14159")
async def test_endofsentence_zh(self):
chinese_sentences = [
@@ -50,3 +61,50 @@ class TestUtilsString(unittest.IsolatedAsyncioTestCase):
for i in hindi_sentences:
assert match_endofsentence(i)
assert not match_endofsentence("हैलो,")
+
+
+class TestStartEndTags(unittest.IsolatedAsyncioTestCase):
+ async def test_empty(self):
+ assert parse_start_end_tags("", [], None, 0) == (None, 0)
+ assert parse_start_end_tags("Hello from Pipecat!", [], None, 0) == (None, 0)
+
+ async def test_simple(self):
+ # (, )
+ assert parse_start_end_tags("Hello from Pipecat!", [("", "")], None, 0) == (
+ None,
+ 26,
+ )
+ assert parse_start_end_tags("Hello from Pipecat", [("", "")], None, 0) == (
+ ("", ""),
+ 21,
+ )
+ assert parse_start_end_tags("Hello from Pipecat", [("", "")], None, 6) == (
+ ("", ""),
+ 21,
+ )
+
+ # (spell(, ))
+ assert parse_start_end_tags("Hello from spell(Pipecat)!", [("spell(", ")")], None, 0) == (
+ None,
+ 26,
+ )
+ assert parse_start_end_tags("Hello from spell(Pipecat", [("spell(", ")")], None, 0) == (
+ ("spell(", ")"),
+ 24,
+ )
+
+ async def test_multiple(self):
+ # (, )
+ assert parse_start_end_tags(
+ "Hello from Pipecat! Hello World!", [("", "")], None, 0
+ ) == (
+ None,
+ 46,
+ )
+
+ assert parse_start_end_tags(
+ "Hello from Pipecat! Hello World", [("", "")], None, 0
+ ) == (
+ ("", ""),
+ 41,
+ )