can i use a custom api endpoint for my llm?
# ask-ai
s
can i use a custom api endpoint for my llm?
t
Thanks for reaching out, Nakshatra. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Absolutely, you can use a custom API endpoint for your LLM in LiveKit! There are two main ways to go about it: 1. Using OpenAI-Compatible Endpoints: If your custom LLM service supports an OpenAI-compatible API (like the
/chat/completions
endpoint), you just need to set the
base_url
parameter when you initialize your LLM instance. For example, if you're working with a local Ollama server:
Copy code
from livekit.plugins import openai

llm_instance = openai.LLM.with_ollama(
    model="llama3.1",
    base_url="<BASE_API_URL>",
)
And if you're using JavaScript:
Copy code
const llm = new LLM({
  model: 'llama3.1',
  baseURL: '<BASE_API_URL>',
  apiKey: 'ollama',
});
This approach works great with providers like Cerebras, Groq, and others that mimic OpenAI's API. 1. Customizing the LLM Node for Non-OpenAI APIs: If your LLM doesn't follow the OpenAI API format, no worries! You can customize the
llm_node
directly by extending the base
LLM
class or creating a new node to interact with your provider’s API. This gives you full control over how requests and responses are handled. For more examples and details, feel free to check out the LiveKit GitHub repo here: LiveKit GitHub. If you have any questions or want a hand with anything else, just let me know—I’m here to help! Sources: Using Custom LLM Providers with the Agent | LLM Integrations | livekit/livekit_composite | DeepWiki | LiveKit integration guides | LiveKit Docs | plugins/openai/src/realtime/realtime_model.ts | Large language model (LLM) integrations | LiveKit Docs
s
using a custom endpoint is giving a timeour error
t
Timeout errors when using a custom API endpoint for your LLM can be frustrating, but don’t worry—we can work through this together. Here are some friendly steps to help you troubleshoot and fix the issue: 1. Adjust Client Timeout Settings: Make sure the
timeout
parameter is set just right when you initialize your LLM instance. If the default (like 5 seconds) feels too short for your endpoint, try increasing the read timeout a bit. 2. Verify Network Connectivity: Double-check that your custom API endpoint is reachable from where you’re running things. Tools like
curl
or
telnet
can be super helpful to test this. 3. Check Server-Side Performance: Keep an eye on the server hosting your LLM—high CPU, memory, or GPU usage can slow things down. Optimizing how your model loads and runs can make a big difference. 4. Use Retry Logic: Setting up retry logic with exponential backoff can handle those occasional hiccups. Just make sure the total retry time fits with what your app needs latency-wise. 5. Implement Error Handling: It’s a good idea to log and handle timeout errors in your code so you can spot patterns and keep improving. For example:
Copy code
except asyncio.TimeoutError:
    raise APITimeoutError() from None
Also, take a look at your deployment environment—sometimes burstable instance types (like t3/t4) can throttle the CPU and cause delays, so avoiding those might help. If you want, I’m here to help you walk through any of these steps or answer any questions you have! Sources: agents/src/llm/llm.ts | livekit-plugins/livekit-plugins-turn-detector/livekit/plugins/turn_detector... | Troubleshooting Latency and Timeout Errors with Turn Detection on AWS
s
this is my entrypoint: async def entrypoint(ctx: agents.JobContext): _# worker_options= WorkerOptions(initialize_process_timeout=30)_ session = AgentSession( stt=deepgram.STT(), llm=openai.LLM(model="gpt-4o-mini"), tts=cartesia.TTS( model="sonic-2", voice="28ca2041-5dda-42df-8123-f58ea9c3da00", language="hi" ), vad=silero.VAD.load(), turn_detection=MultilingualModel(), use_tts_aligned_transcript=True, #to sync dpoken and transcribed text ) suppose my custom llm endpoint api _base_url is "<https://x>_yz.com/abc/", what changes will i make in the script?
t
To use your custom LLM API endpoint (`https://xyz.com/abc/`) in your script, you’ll want to set the
base_url
parameter for the LLM instance. Here’s a friendly walkthrough on how to update your script:
Copy code
from livekit.agents import AgentSession
from livekit.plugins import openai

async def entrypoint(ctx: agents.JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        llm=openai.LLM(
            model="gpt-4o-mini",
            base_url="https://xyz.com/abc/",
            temperature=0.7
        ),
        tts=cartesia.TTS(
            model="sonic-2",
            voice="28ca2041-5dda-42df-8123-f58ea9c3da00",
            language="hi"
        ),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
        use_tts_aligned_transcript=True
    )
    # Add your agent logic here
Here are a few important points to keep in mind: • Make sure to set the
base_url
parameter to your custom endpoint (`https://xyz.com/abc/`). • Double-check that your endpoint is reachable and correctly set up to handle the requests. • Feel free to tweak other parameters like
temperature
to best fit your needs. If you run into any bumps or have questions along the way, please don’t hesitate to reach out—I’m here to help! Sources: Ollama integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-groq/livekit/plugins/groq/services.py | Baseten LLM integration guide | LiveKit Docs | Groq LLM integration guide | LiveKit Docs | Groq LLM integration guide | LiveKit Docs
s
and the custom api in the env file too, right?
t
Absolutely! Including the custom API endpoint in your environment file is a great step for keeping things secure and easy to manage. For instance, in your
.env
file, you can add this:
Copy code
CUSTOM_LLM_API_BASE_URL=https://xyz.com/abc/
After that, you can update your script to load this value dynamically like this:
Copy code
import os
from livekit.agents import AgentSession
from livekit.plugins import openai

async def entrypoint(ctx: agents.JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        llm=openai.LLM(
            model=\"gpt-4o-mini\",
            base_url=os.getenv(\"CUSTOM_LLM_API_BASE_URL\"),
            temperature=0.7
        ),
        tts=cartesia.TTS(
            model=\"sonic-2\",
            voice=\"28ca2041-5dda-42df-8123-f58ea9c3da00\",
            language=\"hi\"
        ),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
        use_tts_aligned_transcript=True
    )
    # Add your agent logic here
This way, your API endpoint stays protected, and you can easily update it anytime without touching the code. If you have any questions or need a hand with this, feel free to ask—I’m here to help!
s
no i meant, I have one custom url endpoint and the corresponding API key to use that, what goes where
t
Thank you so much for clarifying! If you have a custom URL endpoint and an API key, I’d be happy to guide you through setting it up: 1. In your
.env
file, please add the following:
Copy code
CUSTOM_LLM_API_BASE_URL=https://xyz.com/abc/
CUSTOM_LLM_API_KEY=your_api_key_here
2. Then, update your script to load these values dynamically like this:
Copy code
import os
from livekit.agents import AgentSession
from livekit.plugins import openai

async def entrypoint(ctx: agents.JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        llm=openai.LLM(
            model="gpt-4o-mini",
            base_url=os.getenv("CUSTOM_LLM_API_BASE_URL"),
            api_key=os.getenv("CUSTOM_LLM_API_KEY"),
            temperature=0.7
        ),
        tts=cartesia.TTS(
            model="sonic-2",
            voice="28ca2041-5dda-42df-8123-f58ea9c3da00",
            language="hi"
        ),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
        use_tts_aligned_transcript=True
    )
    # Add your agent logic here
Just a few key things to keep in mind: •
CUSTOM_LLM_API_BASE_URL
should be the URL of your custom endpoint. •
CUSTOM_LLM_API_KEY
is the API key you’ll use to authenticate with your custom endpoint. • Make sure your custom endpoint is set up to accept the API key in the right way, like through a header or a query parameter. If you run into any questions or need a hand with anything else, please don’t hesitate to reach out—I’m here to help!
s
also the api is limited to openai's gpt-5 model
t
Thank you so much for clarifying! If your custom API endpoint is limited to a specific model, here’s a friendly guide to help you set it up: 1. In your
.env
file, please include:
Copy code
CUSTOM_LLM_API_BASE_URL=https://xyz.com/abc/
CUSTOM_LLM_API_KEY=your_api_key_here
2. Then, update your script to load these values dynamically like this:
Copy code
import os
from livekit.agents import AgentSession
from livekit.plugins import openai

async def entrypoint(ctx: agents.JobContext):
    session = AgentSession(
        stt=deepgram.STT(),
        llm=openai.LLM(
            model="gpt-4o-mini",  # Just replace this with the exact model name your API supports
            base_url=os.getenv("CUSTOM_LLM_API_BASE_URL"),
            api_key=os.getenv("CUSTOM_LLM_API_KEY"),
            temperature=0.7
        ),
        tts=cartesia.TTS(
            model="sonic-2",
            voice="28ca2041-5dda-42df-8123-f58ea9c3da00",
            language="hi"
        ),
        vad=silero.VAD.load(),
        turn_detection=MultilingualModel(),
        use_tts_aligned_transcript=True
    )
    # Feel free to add your agent logic here
Here are a few key points to keep in mind: • Make sure the
model
parameter exactly matches the model name your API supports (like "gpt-4o-mini" or a similar one). • Double-check that your custom endpoint is set up to handle requests for this specific model. • Verify your API key is valid and has the right permissions to access the model you want to use. If you have any questions or need a hand with anything else, just let me know—I’m here to help!
s
how to change tts speed in this case?
t
If you'd like to change the TTS speed while using Cartesia TTS, you can easily do this by adjusting the
speed
parameter when you initialize it. You have the flexibility to set the speed either as a float value between -1.0 and 1.0, or by choosing from convenient predefined levels like
"fastest"
,
"fast"
,
"normal"
,
"slow"
, or
"slowest"
. Here’s a simple example to get you started:
Copy code
from livekit.plugins import cartesia

tts = cartesia.TTS(
    model="sonic-2-2025-03-07",  # Required for speed control
    voice="28ca2041-5dda-42df-8123-f58ea9c3da00",
    language="hi",
    speed="fast"  # You can also use float values like 0.8
)
And if you want to change the speed while the program is running, you can do that too with the
update_options()
method:
Copy code
tts.update_options(speed="slow")
Just a quick note: speed control works only with the
sonic-2-2025-03-07
model. If you’re using a different model, speed adjustments won’t take effect. If you have any questions or need a hand with this, please don’t hesitate to ask. I’m here to help! Sources: plugins/cartesia/src/models.ts | Cartesia integration guide | LiveKit Docs | examples/voice_agents/tts_text_pacing.py
s
the application has more latency now and i am getting this error: DEBUGopenai. base clientSending HTTP Request: POST https://labs.shl.com/llm-internal/chat/completions 2025-09-09 183418,264 - ERROR livekit.agents - Error predicting end of turn Traceback (most recent call last): File "/usr/lib/python3.12/asyncio/tasks.py", line 520, in wait_for return await fut ^^^^^^^^^ File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 101, in do_inference inf_resp = await fut ^^^^^^^^^ asyncio.exceptions.CancelledError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/agents/voice/audio_recognition.py", line 364, in _bounce_eou_task end_of_turn_probability = await turn_detector.predict_end_of_turn( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/plugins/turn_detector/multilingual.py", line 68, in predict_end_of_turn return await super().predict_end_of_turn(chat_ctx, timeout=timeout) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/naksh/wslvenv/lib/python3.12/site-packages/livekit/plugins/turn_detector/base.py", line 229, in predict_end_of_turn result = await asyncio.wait_for( ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/asyncio/tasks.py", line 519, in wait_for async with timeouts.timeout(timeout): File "/usr/lib/python3.12/asyncio/timeouts.py", line 115, in aexit raise TimeoutError from exc_val TimeoutError {"pid": 700, "job_id": "AJ_HadDwCekwMWu"} DEBUGhttpcore.http11send_request_headers.started request=<Request [b'POST']> DEBUGhttpcore.http11send_request_headers.complete DEBUGhttpcore.http11send_request_body.started request=<Request [b'POST']> DEBUGhttpcore.http11send_request_body.complete DEBUGhttpcore.http11receive_response_headers.started request=<Request [b'POST']>
t
The
TimeoutError
during end-of-turn (EOT) prediction and increased latency can be addressed with the following steps: 1. Check Instance Type: If you're using AWS, try to avoid burstable instance types like
t3
or
t4g
, as they can throttle performance when CPU credits run out. Instead, using non-burstable instances like
m5
,
c5
, or
c6i
can help ensure more consistent performance. 2. Monitor CPU Credits: If burstable instances are your only option, keep an eye on the
CPUCreditBalance
metric in CloudWatch to make sure credits aren’t getting depleted. You might also consider enabling
t3.unlimited
mode if that fits your use case. 3. Verify Inference Runtime: It’s important to confirm that your EOT prediction inference finishes within the expected latency of 50–160ms. If you notice it consistently takes over 500ms, it might be worth investigating possible environmental issues like CPU throttling or network delays. 4. Pre-Download Model Files: To avoid any delays during initialization, make sure all required model files are pre-downloaded by running
python3 your_agent.py download-files
before deployment. 5. Review Timeout Settings: The default timeout for
predict_end_of_turn
is 3 seconds. While you can adjust this, it’s generally better to optimize your environment so inference completes within this timeframe. 6. Optimize Network Latency: If you’re using a remote EOT inference endpoint, ensuring low network latency between your agent and the endpoint can really help improve performance. 7. Monitor Metrics: Keep an eye on metrics like
end_of_utterance_delay
and
transcription_delay
to spot any bottlenecks in your audio processing pipeline. Please feel free to reach out if you'd like any help walking through these steps—I’m here to support you! Sources: Troubleshooting Latency and Timeout Errors with Turn Detection on AWS | livekit-plugins/livekit-plugins-aws/livekit/plugins/aws/experimental/realti...
s
can i prewarm the llm now that i am using a custom endpoint?
t
Absolutely, you can prewarm the LLM when using a custom API endpoint to help reduce latency during runtime. Let me walk you through how you can set this up: 1. Start by defining a
prewarm
function to initialize the LLM client with your custom API endpoint:
Copy code
from livekit.agents import JobProcess, WorkerOptions, cli
from livekit.plugins import openai

def prewarm(proc: JobProcess):
    # Initialize the LLM with your custom API endpoint
    llm_instance = openai.LLM(
        model="your-custom-model",
        api_key="your-api-key",  # if required
        base_url="https://your-custom-api-endpoint.com/v1"
    )
    # Store the instance in userdata for reuse in the entrypoint
    proc.userdata["llm"] = llm_instance
    # Optionally, call prewarm on the instance if it has specific prewarming logic
    llm_instance.prewarm()
2. Then, use the pre-initialized LLM in your
entrypoint
function like this:
Copy code
async def entrypoint(ctx: JobContext):
    session = AgentSession(
        llm=ctx.proc.userdata["llm"],
        stt=deepgram.STT(),
        tts=openai.TTS(voice="your-voice"),
        vad=silero.VAD.load()
    )
    await session.start(agent=MyAgent(), room=ctx.room)
3. Finally, run your application with prewarming enabled:
Copy code
if __name__ == "__main__":
    cli.run_app(
        WorkerOptions(
            entrypoint_fnc=entrypoint,
            prewarm_fnc=prewarm,
            num_idle_processes=1
        )
    )
Here are a few key points to keep in mind: • The
prewarm
function sets up the LLM client and stores it in
proc.userdata
so it can be reused efficiently. • Calling
llm_instance.prewarm()
makes sure any specific prewarming steps for the LLM are taken care of. • This method helps you avoid the delay of creating the LLM client on the very first request, which means faster response times. If you have any questions or need a hand with anything else, please don’t hesitate to ask—I’m here to help! Sources: plugins/openai/src/realtime/realtime_model.ts | examples/other/kokoro_tts.py
s
async def entrypoint(ctx: agents.JobContext): _# worker_options= WorkerOptions(initialize_process_timeout=30)_ session = AgentSession( stt=deepgram.STT(), llm=ctx.proc.userdata["llm"], tts=cartesia.TTS( model="sonic-2", voice="28ca2041-5dda-42df-8123-f58ea9c3da00", language="hi", speed="slow" ), vad=silero.VAD.load(), turn_detection=MultilingualModel(), use_tts_aligned_transcript=True, #to sync dpoken and transcribed text ) def prewarm(proc: agents.JobProcess): proc.userdata["vad"] = silero.VAD.load() llm_instance = openai.LLM( model="gpt-5", base_url=os.getenv("CUSTOM_LLM_API_BASE_URL"), api_key=os.getenv("CUSTOM_LLM_API_KEY"), ) # Store the instance in userdata for reuse in the entrypoint proc.userdata["llm"] = llm_instance
this good?
?
a
AttributeError: 'LLM' object has no attribute 'prewarm' Using this as : LLM.with_azure