@pytest.mark.asyncio async def *test_interviewer_f...
# ask-ai
b
@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: result = await session.start( Interviewer( instructions=_llm_instructions_, _chat_ctx_=_initial_context_, _turn_detection_=None, # Avoid requiring LiveKit job context in tests ) ) result = await session.run(_user_input_="Hello") 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() if my interview uses on_enter method to say the message first - how to design this test? session.run requires user_input keyword arg and that's not reflecting what's going on in actual conversation
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.
When designing a test for an interview session where the
on_enter
method sends the first message, you can adjust the test setup to mimic the agent starting the conversation. Since
session.run
expects a
user_input
argument, a handy way to work around this is by directly calling the
on_enter
method in your test. Here’s a simple way to approach it: • Override the
on_enter
method in your agent so it sends the initial message using
session.say()
or
generate_reply()
. • In your test, create both a session and an agent instance, then explicitly invoke
agent.on_enter()
to simulate that first message. • Keep track of the conversation events to confirm that the first message is sent properly without needing any
user_input
. If you’d like, I’m here to help you step through the implementation or clarify anything further! Sources: Testing and evaluation | LiveKit Docs | pipeline-tts/short_replies_only.py | livekit-agents/livekit/agents/voice/agent.py
b
can you show me the code?
t
Here’s a friendly example to help you design a test for an interview session where the
on_enter
method sends the very first message:
Copy code
from your_agent_module import InterviewAgent
from your_session_module import create_session
import asyncio

async def test_interviewer_first_message():
    # Create a session instance
    session = create_session()

    # Create an agent instance with on_enter behavior
    agent = InterviewAgent()

    # Track conversation events
    conversation_events = []
    session.on("conversation_item_added", conversation_events.append)

    # Simulate the agent entering the session
    await agent.on_enter()

    # Verify the first message was sent
    assert len(conversation_events) > 0
    assert conversation_events[0].item.role == "assistant"
    assert "Welcome" in conversation_events[0].item.text_content

# Run the test
asyncio.run(test_interviewer_first_message())
This test gently calls the
on_enter
method to mimic the agent sending that first warm message. Then, it checks to make sure the message was successfully added to the conversation events. If you’d like me to walk you through any part of this or provide more examples, just let me know—I’m here to help!
b
do I have to create a session with this agent already?
t
Absolutely! You’ll want to create a session with the agent already initialized because the session is like the environment where your agent works. It’s essential for the
on_enter
method to run smoothly. Here’s an updated example to help you along:
Copy code
from your_agent_module import InterviewAgent
from your_session_module import create_session
import asyncio

async def test_interviewer_first_message():
    # Create a session instance
    session = create_session()

    # Create an agent instance and associate it with the session
    agent = InterviewAgent()
    session.attach_agent(agent)

    # Track conversation events
    conversation_events = []
    session.on("conversation_item_added", conversation_events.append)

    # Simulate the agent entering the session
    await agent.on_enter()

    # Verify the first message was sent
    assert len(conversation_events) > 0
    assert conversation_events[0].item.role == "assistant"
    assert "Welcome" in conversation_events[0].item.text_content

# Run the test
asyncio.run(test_interviewer_first_message())
In this example, the
session.attach_agent(agent)
step is key because it makes sure your agent is properly connected to the session before calling
on_enter
. This setup really reflects how the agent behaves during actual runtime within a session. If anything feels unclear or you want to dive deeper, just let me know—I’m here to help!
b
await session.start( Interviewer( instructions=_llm_instructions_, _chat_ctx_=_initial_context_, _turn_detection_=None, # Avoid requiring LiveKit job context in tests ) ) await session.current_agent.on_enter() I'm doing this getting no messages in session.history and conversation list you suggested mind that I'm using this setup for my interviewer class Interviewer(Agent): def *__init__*(self, *_args_, _turn_detection_=None, **_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, ) _# Use provided turn_detection or create EnglishModel by default_ _# In tests, pass turn_detection=None to avoid requiring job context_ if _turn_detection_ is None: _try_: _turn_detection_ = EnglishModel() except RuntimeError: # If no job context (e.g., in tests), leave as None pass super().__init__( *_args_, **_kwargs_, llm=llm, tts=tts, stt=stt, vad=vad, _turn_detection_=_turn_detection_, ) async def *on_enter*(self): """Initialize the agent and start the timer (in seconds).""" self.session.userdata.start_time = time.time() self.session.input.set_audio_enabled(False) speech = self.session.say(text=self.session.userdata.question_prompt) speech.add_done_callback(lambda ___: self.session.input.set_audio_enabled(True))
t
I completely understand how it can be a bit confusing when
session.history
and the conversation list stay empty after calling
on_enter
. The key thing to know is that no conversation items are being added during the session lifecycle by default. To see your history populate, you’ll want to explicitly generate or add messages during the
on_enter
phase. Here are some friendly, actionable steps to help you get this working: 1. Use `session.generate_reply()`: Try calling this method inside
on_enter
to generate an assistant message and add it to the conversation history. For example:
Copy code
async def on_enter(self):
    await self.session.generate_reply(instructions="Greet the user and start the interview.")
1. Preload Conversation Context: You can also pass a
ChatContext
object with some preloaded messages to the agent when you initialize it. This way, your session will start with a history already in place.
Copy code
chat_ctx = ChatContext()
chat_ctx.add_message(role="user", text="Hello, how are you?")
agent = Interviewer(chat_ctx=chat_ctx)
1. Manually Add Messages: Another approach is to use
session.say()
or
session.add_message()
to add messages directly during
on_enter
. If you’d like, I’d be more than happy to provide a detailed code example for any of these methods—just let me know! Sources: Workflows | LiveKit Docs | examples/warm-transfer/warm_transfer.py | main.py | Testing and evaluation | LiveKit Docs | tools/server/public_simplechat/simplechat.js