- how Use a custom STT, LLM, or TTS provider witho...
# ask-ai
p
• how Use a custom STT, LLM, or TTS provider without a plugin.
t
Thanks for reaching out, arpan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
p
please
t
I'm happy to guide you through integrating custom STT, LLM, or TTS providers directly into LiveKit without needing a plugin. You can do this by implementing the corresponding node interfaces (
STT
,
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:
Copy code
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.ts
I'm happy to guide you through integrating custom Speech-to-Text (STT), Large Language Model (LLM), or Text-to-Speech (TTS) providers directly into LiveKit without needing a plugin. You can do this by implementing the appropriate node interfaces (
STT
,
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:
Copy code
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!
p
Custom STT Implementation:
t
Custom STT Implementation: I'd love to help you get started with implementing a custom Speech-to-Text (STT) provider. Here's a simple guide to walk you through the process: • Subclass `stt.STT`: Begin by creating a new class that inherits from
stt.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:
Copy 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!
p
yes
t
That's wonderful to hear! If you run into any questions or need a hand while setting up your custom STT provider, please don't hesitate to reach out. I'm always happy to help you along the way!
p
full example
t
I'd love to walk you through a full example of implementing a custom STT provider—it’s a great way to get hands-on with the process!
Copy code
from 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!
p
prompt cache
t
The prompt cache in LiveKit is a wonderful feature designed to make things more efficient by saving the model's state after it processes an initial prompt. This way, when you send in new requests that share some content with the previous ones, it can speed things up by reusing the common tokens instead of starting from scratch each time. How It Works: • The model's state is saved to a file right after processing your prompt. • When a new request comes in with overlapping content, the cached state helps skip reprocessing those common tokens. Command-Line Usage:
Copy code
./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:
Copy code
{
  "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.cpp
p
how to use with llm
t
I'd love to help you get started with using the prompt cache with an LLM in LiveKit! You can either enable caching during completion requests or manage it through the server API. Here’s a friendly guide to walk you through it: 1. Enable Prompt Caching in Completion Requests: When you send a completion request to the LLM server, just set
cache_prompt
to
true
in your request payload. For example:
Copy code
{
  "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:
Copy code
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:
Copy code
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:
Copy code
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!
p
i want some sustomization like if i have data in memory stop generation
t
To help you customize the behavior of the LLM, like stopping generation if specific data is already in memory, you can add this logic in the
llm_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:
Copy code
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:
Copy code
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!
p
provide more examples
t
I'd love to share some additional examples to help you customize LLM behavior so it can stop generation based on in-memory data or other conditions. Let's walk through them together: Example 1: Stop Generation Based on Specific Keywords
Copy code
from 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
Copy code
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
Copy code
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!