I am starting the agent server using the following...
# ask-ai
t
I am starting the agent server using the following code. It doesn't use livekit configurations set from the environment variables to connect to livekit server, the job context sets the livekit server configurations, what are they setup?
Copy code
import logging
import os
from dotenv import load_dotenv
from livekit import rtc
from livekit.agents import (
    Agent,
    AgentServer,
    AgentSession,
    JobContext,
    JobProcess,
    cli,
    inference,
    room_io,
)
from livekit.plugins import noise_cancellation, silero, deepgram, openai, elevenlabs
from livekit.plugins.turn_detector.multilingual import MultilingualModel

logger = logging.getLogger("agent")

load_dotenv(".env-self-livekit.local", override=True)


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="""You are a helpful voice AI assistant. The user is interacting with you via voice, even if you perceive the conversation as text.
            You eagerly assist users with their questions by providing information from your extensive knowledge.
            Your responses are concise, to the point, and without any complex formatting or punctuation including emojis, asterisks, or other symbols.
            You are curious, friendly, and have a sense of humor.""",
        )
Copy code
server = AgentServer()


def prewarm(proc: JobProcess):
    proc.userdata["vad"] = silero.VAD.load()


server.setup_fnc = prewarm


@FlashCall Server.rtc_session()
async def my_agent(ctx: JobContext):
    ctx.log_context_fields = {
        "room": ctx.room.name,
    }

    # Set up a voice AI pipeline using OpenAI, Cartesia, AssemblyAI, and the LiveKit turn detector
    session = AgentSession(
        # Speech-to-text (STT) is your agent's ears, turning the user's speech into text that the LLM can understand
        # See all available models at https://docs.livekit.io/agents/models/stt/
        # stt=inference.STT(model="assemblyai/universal-streaming", language="en"),

        stt=deepgram.STTv2(
            model="flux-general-en",
            eager_eot_threshold=0.4,
        ),
        # A Large Language Model (LLM) is your agent's brain, processing user input and generating a response
        # See all available models at https://docs.livekit.io/agents/models/llm/
        # llm=inference.LLM(model="openai/gpt-4.1-mini"),
        llm=openai.LLM(model="gpt-4o-mini"),
        # Text-to-speech (TTS) is your agent's voice, turning the LLM's text into speech that the user can hear
        # See all available models as well as voice selections at https://docs.livekit.io/agents/models/tts/
        # tts=inference.TTS(
        #     model="cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"
        # ),
        tts=elevenlabs.TTS(voice_id="ODq5zmih8GrVes37Dizd",model="eleven_multilingual_v2"),
        # VAD and turn detection are used to determine when the user is speaking and when the agent should respond
        # See more at https://docs.livekit.io/agents/build/turns
        turn_detection=MultilingualModel(),
        vad=ctx.proc.userdata["vad"],
        # allow the LLM to generate a response while waiting for the end of turn
        preemptive_generation=True,
    )

    # To use a realtime model instead of a voice pipeline, use the following session setup instead.
    # (Note: This is for the OpenAI Realtime API. For other providers, see https://docs.livekit.io/agents/models/realtime/))
    # 1. Install livekit-agents[openai]
    # 2. Set OPENAI_API_KEY in .env.local
    # 3. Add `from livekit.plugins import openai` to the top of this file
    # 4. Use the following session setup instead of the version above
    # session = AgentSession(
    #     llm=openai.realtime.RealtimeModel(voice="marin")
    # )

    # # Add a virtual avatar to the session, if desired
    # # For other providers, see https://docs.livekit.io/agents/models/avatar/
    # avatar = hedra.AvatarSession(
    #   avatar_id="...",  # See https://docs.livekit.io/agents/models/avatar/plugins/hedra
    # )
    # # Start the avatar and wait for it to join
    # await avatar.start(session, room=ctx.room)

    # Start the session, which initializes the voice pipeline and warms up the models
    await session.start(
        agent=Assistant(),
        room=ctx.room,
        room_options=room_io.RoomOptions(
            audio_input=room_io.AudioInputOptions(
                noise_cancellation=lambda params: noise_cancellation.BVCTelephony()
                if params.participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_SIP
                else noise_cancellation.BVC(),
            ),
        ),
    )

    # Join the room and connect to the user
    print(os.getenv("LIVEKIT_URL"))
    print(os.getenv("LIVEKIT_API_KEY"))
    print(os.getenv("LIVEKIT_API_SECRET"))
    print(os.getenv("DEEPGRAM_API_KEY"))
    print(os.getenv("OPENAI_API_KEY"))
    print(os.getenv("ELEVEN_API_KEY"))

    await ctx.connect()


if __name__ == "__main__":
    cli.run_app(server)
t
Thanks for reaching out, Atul. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — you're asking why your agent process doesn't appear to use the
LIVEKIT_*
env vars directly and what the job context is setting. Short answer: the LiveKit Agents framework reads those environment variables at the agent server level and handles the LiveKit connection for each job;
JobContext
is given a pre-connected
room
so your entrypoint doesn't need to re-read the credentials. What happens in your code •
load_dotenv(...)
loads the env vars for the AgentServer process (registration/auth). • When you run
cli.run_app(server)
, the agent server uses the
LIVEKIT_URL
,
LIVEKIT_API_KEY
, and
LIVEKIT_API_SECRET
to register and authenticate with the LiveKit server. • When a job is dispatched the framework spawns a job process and provides
JobContext
to your
my_agent
function.
ctx.room
is already connected using the server credentials, so calling
await ctx.connect()
does not require re-providing the env vars. Why your prints may look empty • Printing
os.getenv("LIVEKIT_URL")
, etc., inside the job may show nothing if those env vars are only used/available to the parent server process or if the job process environment isn't inheriting them. The framework guarantees a connected
ctx.room
regardless of whether those env vars are present in the child process environment. If you want to verify or change behavior • Verify the env file is loaded by the process that starts the AgentServer (where you call
cli.run_app(server)
). • If you need the raw credentials inside your job process (not usually required), explicitly pass them into the job context or set them in the environment for child processes before
cli.run_app(server)
is called. If you'd like, tell me: • Are your prints inside the job showing empty values? • Do you need the raw LIVEKIT credentials inside the job process (why)? I can suggest exact ways to pass them if needed. Sources: Agent server | LiveKit docs | Job lifecycle | LiveKit docs | Voice AI quickstart | LiveKit docs | Agents v0.x migration guide - Node.js | LiveKit Docs
t
I need to pass livekit server credentials - livekit url, api and secret
t
Thanks — I can help. Quick follow-ups so I give the exact steps you need: 1. Are you running locally/self-hosted or on LiveKit Cloud? 2. How do you start the agent server process (manual python run, Docker, systemd, Kubernetes)? 3. Do you need the credentials inside the job function (
my_agent
/
ctx
) or only for AgentServer registration/auth? If you want the simplest immediate solution: set the three vars in the environment that starts the AgentServer (or in your .env loaded before calling
cli.run_app(server)
) so child job processes inherit them: • LIVEKIT_URL • LIVEKIT_API_KEY • LIVEKIT_API_SECRET If you tell me your answers to 1–3 I’ll provide the exact commands or a short code/Docker example to ensure the job process sees those vars (or show how to instantiate
LiveKitAPI
with them inside the job). Sources: Job lifecycle | LiveKit docs | Voice AI quickstart | LiveKit docs | Secrets management | LiveKit Docs | Deploying to custom environments | LiveKit Docs
t
1. I am running livekit server locally; however I also want to know how could I pass livekit cloud credentials if needed 2. I am starting the agent server using
uv run python src/agent.py console
3. both
t
You're running locally and want the same ability for LiveKit Cloud — got it. To ensure the LiveKit credentials are available both to the AgentServer and inside each job (your
my_agent
/
ctx
), do the following. 1) Set credentials as environment variables (local or cloud) • Local
.env.local
(project root):
Copy code
LIVEKIT_URL=ws://localhost:7880
  LIVEKIT_API_KEY=your-local-key
  LIVEKIT_API_SECRET=your-local-secret
• For LiveKit Cloud, use the cloud-provided values (you do not include them in the image when deploying to Cloud; Cloud injects them at runtime). 2) Load them before starting the AgentServer • In your Python file, at top-level (before
cli.run_app(server)
), load the file:
Copy code
from dotenv import load_dotenv
  load_dotenv(".env.local")
• Then start as you do: uv run python src/agent.py console This ensures the AgentServer process has the vars and that child job processes inherit them. 3) Access inside the job (if you need raw creds) • Inside your entrypoint use `os.getenv(...)`:
Copy code
livekit_url = os.getenv("LIVEKIT_URL")
  api_key = os.getenv("LIVEKIT_API_KEY")
  api_secret = os.getenv("LIVEKIT_API_SECRET")
• Use these to instantiate
LiveKitAPI
or other server-side clients if needed. 4) Why your prints might be empty • If
load_dotenv()
runs only in the parent but the child process doesn't inherit env vars (or you print before loading), prints will be empty. Ensure
load_dotenv()
runs in the process that launches
cli.run_app(server)
and that you start the process from the same shell/session that has the exported vars (or export them in the shell). 5) Alternatives / notes • If you absolutely must pass creds programmatically into the JobContext, explicitly set env vars before spawning (export in shell) or pass them into the process environment. Typically this is unnecessary because the framework provides a connected
ctx.room
. • For LiveKit Cloud deployments, do not bake secrets into images—Cloud injects them at runtime and you should rely on the provided mechanism. Would you like a short example showing: • A shell command that exports the vars before running your
uv run ...
command, or • A small Dockerfile / docker-compose snippet that injects the env vars into the container? Sources: Company directory phone assistant | LiveKit Docs | Next.js 12 quickstart | LiveKit docs | Next.js quickstart | LiveKit docs | Voice AI quickstart | LiveKit docs | Call forwarding | LiveKit docs