I HAVE A model deployed with an OpenAI endpoint. I...
# ask-ai
m
I HAVE A model deployed with an OpenAI endpoint. I want to use it for the for my agnt . howdo i create the llm node:
t
Thanks for reaching out, Anigilaje. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to create an LLM node that uses your model hosted behind an OpenAI-compatible endpoint. Below are two clear options depending on whether you just want to point the agent at your endpoint or need custom behavior. Option A — Use the OpenAI LLM plugin (recommended if your endpoint supports OpenAI-style APIs) 1. Install the OpenAI plugin: ◦ Python: add the plugin dependency you already have (example shown in docs). 1. Set your API key in `.env`: ◦
OPENAI_API_KEY=<your-api-key>
1. Create the LLM instance with your custom base URL: ◦ Python:
Copy code
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:
Copy code
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:
Copy code
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 Agent
m
This is my base LLM base_url="https://llama3b.pub.com/v1" api_key="pue4", this is my code : def prewarm(proc: JobProcess): proc.userdata["vad"] = silero.VAD.load() 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 # Set log context fields AFTER getting participant info ctx.log_context_fields = { "room": ctx.room.name, "user_id": user_id, } logger.info(f"Participant joined with identity: {user_id}, name: {student_name}") # Rest of your code... 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) session = AgentSession( vad=ctx.proc.userdata["vad"], llm=openai.LLM( base_url="https://llama3b.publicaai.com/v1", api_key="publicaai-23e4", ), stt= openai.STT(model="whisper-1"), # tts=elevenlabs.TTS(model="eleven_multilingual_v2", voice_id="JMwQvjJt08OhYlPBWeyc"), tts=openai.TTS(), allow_interruptions=True ) logger.info("Agent session components initialized") agent.session = session @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) usage_collector = metrics.UsageCollector() async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Usage summary: {summary}")
t
Thanks — I reviewed your code and your endpoint details. Below are concise fixes and a cleaned example to make the LLM use your OpenAI-compatible endpoint correctly and integrate into your AgentSession. Key fixes • Use the same base URL you shared (your code used two similar hosts; pick the correct one). • Pass
model
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)
Copy code
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.
m
it wptkeed, what about tts and sst, is it the same emthod , alos will i ha to create an opena ai compatible endpoint that also?
t
Great — glad the LLM hookup worked. Responding to your questions about TTS and STT and whether they need OpenAI-compatible endpoints. • TTS and STT are not automatically handled the same way as the LLM. You cannot assume the same base_url override used for
openai.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 docs
m
Share an example of STT and tts of node fg that . using whiper_stt_deployed.com as the base url wit it to work wth the coe i shared and write trhe fulll code with my stts an tts ans llm implemented
t
Below is a complete Python example that integrates your LLM (OpenAI-compatible), custom STT at http://whiper_stt_deployed.com, and custom TTS at http://my_tts_deployed.com into a LiveKit AgentSession. It follows the structure of your code and overrides
stt_node
and
tts_node
. Adjust model names, endpoints, headers, and audio formats to match your services.
Copy code
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