class Interviewer(Agent): def *__init__*(self,...
# ask-ai
b
class Interviewer(Agent): def *__init__*(self, *_args_, **_kwargs_) -> None: tts = agents.tts.StreamAdapter( tts=openai.TTS(model="gpt-4o-mini-tts", voice=VOICE, speed=1) ) stt = deepgram.STT(model="nova-2", language="en") llm = openai.realtime.RealtimeModel( model="gpt-4o-mini-realtime-preview", voice=VOICE, speed=1, _tool_choice_="none", modalities=["audio"], _input_audio_transcription_=None, _turn_detection_=None, ) vad = silero.VAD.load( _min_silence_duration_=1.2, # Wait a bit longer before ending the turn _activation_threshold_=0.45, # Slightly lower threshold to catch softer speech _min_speech_duration_=0.05, _prefix_padding_duration_=0.5, ) turn_detection = EnglishModel() super().__init__( *_args_, **_kwargs_, llm=llm, tts=tts, stt=stt, vad=vad, _turn_detection_=turn_detection, ) @pytest.mark.asyncio async def *test_interviewer_first_message*( _initial_context_: ChatContext, _llm_instructions_: str ) -> None: agent_session = AgentSession[UserSessionInfo]( userdata=UserSessionInfo(_question_prompt_="What's you biggest weakness?") ) async with openai.LLM(model="gpt-4o-mini") as llm, agent_session as session: await session.start( Interviewer(instructions=_llm_instructions_, _chat_ctx_=_initial_context_) ) result = await session.run() await ( result.expect.next_event() .is_message(role="assistant") .judge(llm, intent="Asks the question and listens to the candidate's response.") ) result.expect.no_more_events() @pytest.mark.asyncio async def test_interviewer_first_message( initial_context: ChatContext, llm_instructions: str ) -> None: agent_session = AgentSession[UserSessionInfo]( userdata=UserSessionInfo(question_prompt="What's you biggest weakness?") ) async with openai.LLM(model="gpt-4o-mini") as llm, agent_session as session: await session.start(
Interviewer(instructions=llm_instructions, chat_ctx=initial_context)
) tests/voice/test_interviewer.py43 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ voice_agent/interviewer.py120 in init turn_detection = EnglishModel() ^^^^^^^^^^^^^^ .venv/lib/python3.12/site-packages/livekit/plugins/turn_detector/english.py26 in init super().__init__(model_type="en", unlikely_threshold=unlikely_threshold) .venv/lib/python3.12/site-packages/livekit/plugins/turn_detector/base.py161 in init self._executor = inference_executor or get_job_context().inference_executor ^^^^^^^^^^^^^^^^^ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ def get_job_context() -> JobContext: ctx = _JobContextVar.get(None) if ctx is None:
raise RuntimeError(
"no job context found, are you running this code inside a job entrypoint?" ) E RuntimeError: no job context found, are you running this code inside a job entrypoint? .venv/lib/python3.12/site-packages/livekit/agents/job.py44 RuntimeError ========================================================================================================================== warnings summary ========================================================================================================================== -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ====================================================================================================================== short test summary info ======================================================================================================================= FAILED tests/voice/test_interviewer.py::test_interviewer_first_message - RuntimeError: no job context found, are you running this code inside a job entrypoint? ==================================================================================================================== 1 failed, 1 warning in 7.39s =============== I'm getting this error trying to run a test - why?
t
Thanks for reaching out, mateuszkasprowicz. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
It looks like the error is happening because the LiveKit
JobContext
is being accessed outside of a valid job execution environment. The
JobContext
is available only during the execution of a job entrypoint function, which the LiveKit worker calls when a job is dispatched. To help you resolve this, here are a few friendly tips: • Make sure your code follows the entrypoint pattern. Your main agent logic should be inside a function that takes
JobContext
as a parameter and is registered with
WorkerOptions(entrypoint_fnc=your_function)
. • Keep job-specific code inside the entrypoint function. Avoid calling
get_job_context()
at the module level or outside asynchronous functions that run within the job context. • Double-check your worker setup to ensure your entrypoint function is properly registered with the LiveKit worker. • Confirm that your agent code runs only after the worker has initialized the context correctly—this means not during module imports or when global variables are being initialized. If any of this feels unclear or if you'd like a hand restructuring your code, please don’t hesitate to reach out. I’m here to help! Sources: agents/src/job.ts | Node.js Agents Architecture | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit Docs | examples/voice_agents/realtime_turn_detector.py
b
but it's for testing and evaluation
t
To help you with testing and evaluation, you can simulate the
JobContext
by creating a mock or stub context. This way, you can test your logic smoothly without needing the full LiveKit worker environment. Here’s a friendly example of how you might mock the `JobContext`:
Copy code
from unittest.mock import MagicMock
from livekit.agents import JobContext

# Create a mock JobContext
mock_job_context = MagicMock(spec=JobContext)
mock_job_context.room = MagicMock()
mock_job_context.agent = MagicMock()

# Pass the mock context to your function for testing
await your_entrypoint_function(mock_job_context)
This method helps your tests run independently from the LiveKit worker lifecycle. If you’d like, I’m here to help you set up the mock or answer any other questions you might have!
b
I think you missed a point I want to test an agent The agent uses EnglishModel for turn detection that apparently depends on job context. and I can't run a simple test
t
I'd love to help you test an agent using the
EnglishModel
for turn detection without relying on a job context. You can do this by directly initializing the
EnglishModel
and using its methods to evaluate the turn detection logic. This way, you can avoid any dependency on the job context. Here’s a simple approach you might find useful: 1. Manually create an instance of the
EnglishModel
. 2. Set up a simulated
ChatContext
with message history to represent user and assistant interactions. 3. Use the
predictEndOfTurn
method to check if the turn is ending based on the conversation context. For example:
Copy code
from livekit.plugins.turn_detector.english import EnglishModel
from livekit.llm import ChatContext

# Initialize the EnglishModel
eou_model = EnglishModel()

# Create a simulated ChatContext
chat_ctx = ChatContext.empty()
chat_ctx.add_message(role="assistant", content="Hi, how can I help you today?")

# Simulate a user message
chat_ctx.add_message(role="user", content="What is the weather in San Francisco?")

# Predict end of turn
result = eou_model.predict_end_of_turn(chat_ctx)
print("Turn ending prediction:", result)
This approach lets you test the turn detection logic on its own, without needing the full agent lifecycle. If you have any questions or need a hand setting this up, please don’t hesitate to ask—I’m here to support you! Sources: plugins/livekit/src/turn_detector/english.ts | examples/voice_agents/realtime_turn_detector.py