polite-dog-12152
10/31/2025, 11:15 AMtall-airline-16756
10/31/2025, 11:15 AMpolite-dog-12152
10/31/2025, 11:16 AMtall-airline-16756
10/31/2025, 11:16 AMSTT, LLM, or TTS) right in your agent code. This way, you have complete control over how you bring in third-party or proprietary models.
Here’s a simple breakdown of the steps:
• Custom STT: Create a subclass of stt.STT and implement methods like stream() and _recognize_impl(). Don’t forget to set capabilities like streaming and interim results in the constructor.
• Custom LLM: Subclass llm.LLM and override the llm_node() method. This lets you handle chat context, call external APIs, and yield responses bit by bit.
• Custom TTS: Subclass tts.TTS and add methods to generate audio from text. You can specify features like streaming or stereo output here.
Once you have your custom classes ready, just pass them into AgentSession like this:
session = voice.AgentSession(
stt=CustomSTT(api_key="your-key"),
llm=CustomLLM(),
tts=CustomTTS(voice="my-voice"),
vad=silero.VAD.load(),
)
This approach gives you full flexibility without relying on plugins. If you'd like, I’m here to help with more details or examples—just let me know!
Sources: Pipeline nodes and hooks | LiveKit docs | livekit-plugins/livekit-plugins-fal/livekit/plugins/fal/stt.py | Tool definition and use | LiveKit docs | Text-to-speech (TTS) models | LiveKit Docs | examples/src/cartersia_tts.tstall-airline-16756
10/31/2025, 11:16 AMSTT, LLM, or TTS) right in your agent code. This way, you have complete control over how you bring in third-party or proprietary models.
1. Custom STT Implementation:
• Start by subclassing stt.STT and implementing methods like stream() and _recognize_impl().
• Make sure to set STTCapabilities in the constructor to specify features such as streaming and interim results.
• Handle authentication securely, for example, by using environment variables or configuration files for API keys.
2. Custom LLM Implementation:
• Subclass llm.LLM and override the llm_node() method in your agent class.
• Process the chat context, call your external LLM API, and yield responses step-by-step.
3. Custom TTS Implementation:
• Subclass tts.TTS and implement the methods needed to generate audio from text.
• Define capabilities like streaming, stereo, or aligned_transcript using the TTSCapabilities object.
When you're ready, just pass your custom implementations directly to AgentSession like this:
session = voice.AgentSession(
stt=CustomSTT(api_key="your-key"),
llm=CustomLLM(),
tts=CustomTTS(voice="my-voice"),
vad=silero.VAD.load(),
)
This approach gives you full flexibility and ensures smooth integration with LiveKit’s built-in features. Please feel free to reach out if you have any questions or need a hand with anything else!polite-dog-12152
10/31/2025, 11:17 AMtall-airline-16756
10/31/2025, 11:17 AMstt.STT. This sets the foundation for your custom implementation.
• Implement Required Methods: You'll want to override these key methods:
◦ `stream()`: This method will handle streaming transcription, allowing real-time processing.
◦ `_recognize_impl()`: Here, you'll process audio buffers and return a SpeechEvent, which is essential for recognition.
• Set Capabilities: In your constructor, define what features your STT supports, like streaming and interim results, using the STTCapabilities object.
• Authentication: Make sure to securely manage your API keys or credentials, ideally through environment variables to keep things safe.
Example Code:
class CustomSTT(stt.STT):
def __init__(self, api_key: str):
super().__init__(capabilities=stt.STTCapabilities(streaming=True))
self.api_key = api_key
def stream(self, *, language: str = "en", conn_options: APIConnectOptions):
# Implement streaming logic
pass
def _recognize_impl(self, audio_buffer):
# Process audio buffer and return SpeechEvent
pass
If you have any questions or would like me to walk you through more examples, just let me know—I’m here to help!polite-dog-12152
10/31/2025, 11:18 AMtall-airline-16756
10/31/2025, 11:18 AMpolite-dog-12152
10/31/2025, 11:20 AMtall-airline-16756
10/31/2025, 11:20 AMfrom livekit import stt
class CustomSTT(stt.STT):
def __init__(self, api_key: str):
# Define capabilities such as streaming support
super().__init__(capabilities=stt.STTCapabilities(streaming=True))
self.api_key = api_key
def stream(self, *, language: str = "en", conn_options: stt.APIConnectOptions):
# Implement streaming logic here
# Example: Connect to your custom STT API and stream audio data
pass
def _recognize_impl(self, audio_buffer):
# Process the audio buffer and return a SpeechEvent
# Example: Send the audio buffer to your custom STT API and parse the response
response = self._call_custom_stt_api(audio_buffer)
return stt.SpeechEvent(text=response["transcription"], is_final=True)
def _call_custom_stt_api(self, audio_buffer):
# Example function to call your custom STT API
# Replace this with actual API call logic
return {"transcription": "This is a sample transcription"}
# Example usage
custom_stt = CustomSTT(api_key="your-api-key")
# Pass the custom STT instance to your AgentSession
from livekit import voice
session = voice.AgentSession(
stt=custom_stt,
vad=voice.silero.VAD.load(),
)
This example shows you how to subclass stt.STT, implement the necessary methods, and smoothly integrate it into an AgentSession. If anything feels unclear or if you'd like me to provide more examples, just let me know—I’m here to help!polite-dog-12152
11/03/2025, 5:35 AMtall-airline-16756
11/03/2025, 5:37 AM./llama-cli -m models/gemma-1.1-7b-it.Q4_K_M.gguf --prompt-cache ./cache.bin --prompt "Your longer initial prompt here"
• `--prompt-cache`: This lets you specify where to save the cache file.
• `--prompt-cache-all`: Saves both what you input and the generated output into the cache.
• `--prompt-cache-ro`: Uses the cache in a read-only way, so it won't make changes.
Server API Usage:
You can turn on prompt caching in your completion requests by setting cache_prompt to true like this:
{
"prompt": "Your prompt here",
"cache_prompt": true,
"id_slot": 1
}
Slot Management:
• Save Slot Cache: POST /slots/{id_slot}?action=save
• Restore Slot Cache: POST /slots/{id_slot}?action=restore
• Erase Slot Cache: POST /slots/{id_slot}?action=erase
If you have any questions or would like me to walk you through some examples, just let me know—I'm here to help!
Sources: examples/parallel/parallel.cpppolite-dog-12152
11/03/2025, 5:38 AMtall-airline-16756
11/03/2025, 5:38 AMcache_prompt to true in your request payload. For example:
{
"prompt": "Your prompt here",
"cache_prompt": true,
"id_slot": 1
}
This way, the model’s state after processing your prompt gets saved, helping speed up any future requests that share similar content.
2. Manage Prompt Cache Using Slots:
• Save Slot Cache: You can save the cached state of a specific slot to a file with this API call:
POST /slots/{id_slot}?action=save
{
"filename": "slot_save_file.bin"
}
• Restore Slot Cache: If you want to bring back a saved cached state from a file, use this:
POST /slots/{id_slot}?action=restore
{
"filename": "slot_save_file.bin"
}
• Erase Slot Cache: And if you need to clear the cached state for a slot, here’s how:
POST /slots/{id_slot}?action=erase
3. Benefits:
Using the prompt cache is especially handy for things like chatbots or any situation where your prompts share common beginnings. It helps avoid doing the same work over and over and makes responses quicker.
If anything feels unclear or you’d like some extra help, just let me know—I’m here for you!polite-dog-12152
11/03/2025, 7:45 AMtall-airline-16756
11/03/2025, 7:46 AMllm_node() method of your custom LLM class. Let me walk you through how you can do this:
1. Subclass the LLM Interface:
Start by creating a custom LLM class that subclasses llm.LLM, and then override the llm_node() method.
2. Implement Custom Logic:
Inside the llm_node() method, you can check your in-memory data before moving forward with generation. If the data is already there, you can skip generating new content or return a predefined response.
Example:
from livekit import llm
class CustomLLM(llm.LLM):
def __init__(self, memory_data):
self.memory_data = memory_data
async def llm_node(self, chat_ctx: llm.ChatContext, tools: list[llm.FunctionTool], model_settings: llm.ModelSettings):
# Check if data exists in memory
if chat_ctx.messages[-1].content in self.memory_data:
yield llm.ChatChunk(text="Data already exists in memory. Stopping generation.")
return
# Otherwise, proceed with generation (e.g., call external LLM API)
response = call_external_llm_api(chat_ctx.messages)
yield llm.ChatChunk(text=response)
# Example usage
custom_llm = CustomLLM(memory_data={"example_key": "example_value"})
3. Integrate with AgentSession:
Then, you can pass your custom LLM implementation to the AgentSession like this:
session = voice.AgentSession(
llm=custom_llm,
stt=CustomSTT(api_key="your-key"),
tts=CustomTTS(voice="my-voice"),
vad=silero.VAD.load(),
)
This way, you have full control over the generation process based on your in-memory data. If you'd like, I’m here to help with any questions or if you want me to provide more examples—just let me know!polite-dog-12152
11/03/2025, 7:48 AMtall-airline-16756
11/03/2025, 7:49 AMfrom livekit import llm
class KeywordStopLLM(llm.LLM):
def __init__(self, stop_keywords):
self.stop_keywords = stop_keywords
async def llm_node(self, chat_ctx: llm.ChatContext, tools: list[llm.FunctionTool], model_settings: llm.ModelSettings):
# Check if the latest message contains any stop keywords
for keyword in self.stop_keywords:
if keyword in chat_ctx.messages[-1].content:
yield llm.ChatChunk(text=f"Keyword '{keyword}' detected. Stopping generation.")
return
# Proceed with generation if no keywords are found
response = call_external_llm_api(chat_ctx.messages)
yield llm.ChatChunk(text=response)
# Example usage
custom_llm = KeywordStopLLM(stop_keywords=["stop", "cancel"])
Example 2: Stop Generation Based on Message Length
from livekit import llm
class LengthBasedStopLLM(llm.LLM):
def __init__(self, max_length):
self.max_length = max_length
async def llm_node(self, chat_ctx: llm.ChatContext, tools: list[llm.FunctionTool], model_settings: llm.ModelSettings):
# Check if the latest message exceeds the maximum length
if len(chat_ctx.messages[-1].content) > self.max_length:
yield llm.ChatChunk(text="Message too long. Stopping generation.")
return
# Proceed with generation if length is within the limit
response = call_external_llm_api(chat_ctx.messages)
yield llm.ChatChunk(text=response)
# Example usage
custom_llm = LengthBasedStopLLM(max_length=100)
Example 3: Stop Generation Based on Custom Validation
from livekit import llm
class ValidationStopLLM(llm.LLM):
def __init__(self, validation_function):
self.validation_function = validation_function
async def llm_node(self, chat_ctx: llm.ChatContext, tools: list[llm.FunctionTool], model_settings: llm.ModelSettings):
# Use a custom validation function to decide whether to stop
if not self.validation_function(chat_ctx.messages[-1].content):
yield llm.ChatChunk(text="Validation failed. Stopping generation.")
return
# Proceed with generation if validation passes
response = call_external_llm_api(chat_ctx.messages)
yield llm.ChatChunk(text=response)
# Example usage
def custom_validation(message):
return "valid" in message
custom_llm = ValidationStopLLM(validation_function=custom_validation)
These examples are here to guide you through different ways to tailor the LLM's behavior to your needs. If you have any questions or want me to walk you through any part in more detail, just let me know—I'm here to help!