most-vr-18651
11/21/2025, 1:32 PMtall-airline-16756
11/21/2025, 1:33 PMtall-airline-16756
11/21/2025, 1:33 PMOPENAI_API_KEY=<your-api-key>
1. Create the LLM instance with your custom base URL:
◦ Python:
from livekit.plugins import openai
llm = openai.LLM(
model="your-model-name",
base_url="https://your-custom-endpoint.com/v1",
api_key=os.getenv("OPENAI_API_KEY")
)
• Node.js:
import * as openai from '@livekit/agents-plugin-openai';
const llm = openai.LLM({
model: "your-model-name",
baseURL: "https://your-custom-endpoint.com/v1",
apiKey: process.env.OPENAI_API_KEY
});
1. Use that llm when creating the AgentSession:
◦ Example: session = AgentSession(llm=llm, stt=..., tts=..., vad=...)
Option B — Override llm_node for custom call logic (use when you need preprocessing, custom streaming, or non‑standard API)
1. Subclass Agent and implement llm_node, call your LLM client there, and yield streamed chat chunks:
◦ Python example:
from livekit.agents import Agent, llm, ModelSettings
from typing import AsyncIterable
class CustomLLMAgent(Agent):
async def llm_node(
self,
chat_ctx: llm.ChatContext,
tools: list[llm.FunctionTool],
model_settings: ModelSettings
) -> AsyncIterable[llm.ChatChunk]:
# modify chat_ctx or call your endpoint directly
async for chunk in self.llm.chat(chat_ctx=chat_ctx, tools=tools):
yield chunk
1. Start the session using your custom agent class.
Quick checks I recommend:
• Does your endpoint implement OpenAI-compatible /v1/chat/completions semantics? If yes, use Option A.
• Do you need custom preprocessing, function-call handling, or special streaming? If yes, use Option B.
Would you like the exact Python or Node example wired into your current agent code (share a short snippet of how you start your AgentSession)?
Sources: Models | LiveKit Docs | OpenAI LLM plugin guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Using Custom LLM Providers with the Agentmost-vr-18651
11/21/2025, 1:41 PMtall-airline-16756
11/21/2025, 1:42 PMmodel plus base_url and api_key to openai.LLM.
• Ensure OPENAI_API_KEY or the literal key is available at runtime.
• Keep only one Agent instance session assignment (you create temp agent then a real agent — that’s fine if intentional).
Minimal corrected example (Python)
from livekit.plugins import openai
from livekit.agents import AgentSession
# Example values
BASE_URL = "https://llama3b.publicaai.com/v1"
API_KEY = "publicaai-23e4"
MODEL = "your-model-name" # set to the model name your endpoint expects
# create LLM client pointing at your endpoint
llm_client = openai.LLM(
model=MODEL,
base_url=BASE_URL,
api_key=API_KEY
)
# later, create the AgentSession
session = AgentSession(
vad=ctx.proc.userdata["vad"],
llm=llm_client,
stt=openai.STT(model="whisper-1"),
tts=openai.TTS(),
allow_interruptions=True
)
agent.session = session
Checks to run if you see errors
• Verify your endpoint supports /v1/chat/completions semantics and the model name you pass.
• Confirm the API key is valid for that endpoint and not rate-limited.
• If streaming failures occur, try a non-streaming call first to validate connectivity.
If you want, share which host (the two you posted) is the correct one and the model name your endpoint expects — I’ll give a fully prefilled snippet and quick troubleshooting steps for any specific error you see.most-vr-18651
11/21/2025, 1:46 PMtall-airline-16756
11/21/2025, 1:47 PMopenai.LLM will work for TTS/STT.
• If your TTS/STT endpoints implement OpenAI’s specific TTS/STT APIs exactly, you might be able to use a provider plugin that expects OpenAI-format requests, but that is not guaranteed.
• Recommended approach: implement custom tts_node and stt_node in your Agent when your models do not match a supported provider’s API. In those nodes you call your endpoint, handle audio I/O, and yield/return the required speech events or audio chunks.
• Quick next steps:
a. Confirm whether your TTS/STT endpoints follow OpenAI’s request/response format.
b. If yes, try the corresponding plugin with a custom base URL; if you hit issues, fall back to custom nodes.
c. If no, implement stt_node and tts_node in your Agent and wire your HTTP/audio calls there.
If you want, share the TTS/STT API shape (example request/response) and I’ll draft the minimal stt_node and tts_node code snippets for your agent.
Sources: Models | LiveKit Docs | Using Custom LLM Providers with the Agent | OpenAI TTS plugin guide | LiveKit Docs | OpenAI STT plugin guide | LiveKit Docs | Pipeline nodes and hooks | LiveKit docsmost-vr-18651
11/21/2025, 1:50 PMtall-airline-16756
11/21/2025, 1:50 PMstt_node and tts_node. Adjust model names, endpoints, headers, and audio formats to match your services.
import os
import asyncio
import logging
import aiohttp
from dotenv import load_dotenv
from typing import AsyncIterable, Optional
from livekit import rtc
from livekit.agents import Agent, AgentSession, JobContext, llm, stt, tts
from livekit.plugins import openai
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Replace with your endpoints / keys
LLM_BASE_URL = "https://llama3b.publicaai.com/v1"
LLM_API_KEY = "publicaai-23e4"
LLM_MODEL = "your-model-name"
STT_BASE_URL = "http://whiper_stt_deployed.com"
TTS_BASE_URL = "http://my_tts_deployed.com"
# Example assumptions:
# - LiveKit audio frames are 48kHz, mono, 16-bit PCM in frame.data
# - STT endpoint accepts raw PCM bytes at POST /transcribe and returns plain text
# - TTS endpoint accepts JSON POST /synthesize {"text": "..."} and returns raw PCM bytes
class WAECExamAgent(Agent):
def __init__(self, user_id: str, student_name: str, chat_ctx: llm.ChatContext | None = None):
super().__init__(instructions="You are a helpful exam assistant.")
self.user_id = user_id
self.student_name = student_name
# Create LLM client pointing to your OpenAI-compatible endpoint
self.llm = openai.LLM(
model=LLM_MODEL,
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
)
# Optionally seed chat context
if chat_ctx:
self.chat_ctx = chat_ctx
async def stt_node(self, audio: AsyncIterable[rtc.AudioFrame], model_settings: stt.ModelSettings) -> Optional[AsyncIterable[stt.SpeechEvent]]:
"""
Collects audio frames from LiveKit, sends the combined PCM to STT endpoint,
and yields a single FINAL_TRANSCRIPT SpeechEvent with the returned text.
"""
async def stream_transcript():
buffer = bytearray()
async for frame in audio:
# frame.data is raw PCM bytes per LiveKit AudioFrame
buffer.extend(frame.data)
if not buffer:
return
try:
async with aiohttp.ClientSession() as session:
url = f"{STT_BASE_URL}/transcribe"
headers = {"Content-Type": "audio/raw; codec=pcm; rate=48000"}
async with session.post(url, data=bytes(buffer), headers=headers, timeout=30) as resp:
if resp.status == 200:
# Accept plain text or JSON { "text": "..." }
text = await resp.text()
# If JSON, try to parse a "text" field
try:
import json
j = json.loads(text)
text_value = j.get("text", "") if isinstance(j, dict) else text
except Exception:
text_value = text
yield stt.SpeechEvent(
type=stt.SpeechEventType.FINAL_TRANSCRIPT,
alternatives=[stt.SpeechEvent.Alternative(text=text_value, confidence=1.0)]
)
else:
logger.error(f"STT returned status {resp.status}: {await resp.text()}")
except Exception as e:
logger.exception(f"STT request failed: {e}")
raise
return stream_transcript()
async def tts_node(self, text: AsyncIterable[str], model_settings: tts.ModelSettings) -> AsyncIterable[rtc.AudioFrame]:
"""
Collects text chunks, sends to TTS service, receives PCM audio bytes, and yields a single AudioFrame.
"""
# Aggregate text chunks
full_text = ""
async for chunk in text:
full_text += chunk
if not full_text.strip():
return
try:
async with aiohttp.ClientSession() as session:
url = f"{TTS_BASE_URL}/synthesize"
payload = {"text": full_text}
headers = {"Content-Type": "application/json"}
async with session.post(url, json=payload, headers=headers, timeout=30) as resp:
if resp.status != 200:
logger.error(f"TTS returned {resp.status}: {await resp.text()}")
return
audio_bytes = await resp.read()
# Build an AudioFrame. Adjust sample_rate/num_channels/samples_per_channel to match your TTS output.
frame = rtc.AudioFrame(
data=audio_bytes,
sample_rate=48000,
num_channels=1,
samples_per_channel=len(audio_bytes) // 2 # 16-bit PCM => 2 bytes per sample
)
yield frame
except Exception as e:
logger.exception(f"TTS request failed: {e}")
return
# Your job prewarm and entrypoint similar to your original code
def prewarm(proc):
proc.userdata["vad"] = None # load VAD if you use it
async def entrypoint(ctx: JobContext):
await ctx.connect()
logger.info("Connected to room")
participant = await ctx.wait_for_participant()
user_id = participant.identity
student_name = participant.name
ctx.log_context_fields = {"room": ctx.room.name, "user_id": user_id}
logger.info(f"Participant joined with identity: {user_id}, name: {student_name}")
temp_agent = WAECExamAgent(user_id=user_id, student_name=student_name)
chat_ctx = await temp_agent.load_chat_history()
agent = WAECExamAgent(user_id=user_id, student_name=student_name, chat_ctx=chat_ctx)
# Build LLM client explicitly (agent.llm already set), and create session using overridden nodes
session = AgentSession(
vad=ctx.proc.userdata.get("vad"),
llm=agent.llm,
stt=None, # we override stt_node
tts=None, # we override tts_node
allow_interruptions=True
)
logger.info("Agent session components initialized")
agent.session = session
@session.on("metrics_collected")
def _on_metrics_collected(ev):
# implement metrics logging if desired
pass
# Start the session for this room context
await session.start(ctx.room)
# Optionally generate a reply to start interaction
await session.generate_reply(instructions="Greet the participant and ask how you can help.")
# If running as a standalone script, provide a minimal runner
if __name__ == "__main__":
from livekit.agents import cli
cli.run_app(entrypoint_fnc=entrypoint)
Notes and adjustments you may need:
• Set LL M_MODEL to the model name your LLM endpoint expects.
• If your STT/TTS require API keys or different routes, update the URLs and headers accordingly.
• If your STT returns JSON with { "text": "..." }, the code handles that. Modify parsing as needed.
• If your TTS returns WAV/MP3 instead of raw PCM, transcode or adjust AudioFrame construction (use proper decoder).
• For streaming STT/TTS behavior, implement chunked requests or WebSocket streaming in those node implementations.
Would you like me to:
• Pre-fill model names and headers if you share them, or
• Provide a variant that decodes WAV/MP3 outputs into PCM frames? Sources: Pipeline nodes and hooks | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | Voice AI quickstart | LiveKit docs