"""Controller contracts without loading GPU models.""" import asyncio import time import unittest from types import SimpleNamespace from live_session import (Connection, MicTurn, PLAYBACK_TAIL, PublicSpeech, Reply, confirms_interruption, demo_tool, is_backchannel, requested_search, tool_calls, tools_for_turn) from tavily_search import WEB_SEARCH, plain TOOLS = [{'function': {'name': 'get_weather', 'parameters': { 'required': ['city', 'date'], 'properties': {'city': {}, 'date': {}}}}}] CALL = ('\n\n\nLondon\n\n' '\ntomorrow\n\n\n') DOCS = {'function': {'name': 'search_local_docs', 'parameters': { 'required': ['query'], 'properties': {'query': {}}}}} class ToolTests(unittest.TestCase): def test_only_atomic_calls(self): self.assertEqual(tool_calls(CALL, TOOLS)[0]['function']['arguments']['city'], 'London') for broken in (CALL[:-1], CALL + '', CALL.replace('London', '')): with self.assertRaises(ValueError): tool_calls(broken, TOOLS) def test_weather_defaults_to_today_without_guessing_city(self): incomplete_date = CALL.replace('\ntomorrow\n\n', '') self.assertEqual(tool_calls(incomplete_date, TOOLS)[0]['function']['arguments'], {'city': 'London', 'date': 'today'}) with self.assertRaises(ValueError): tool_calls(incomplete_date.replace('London', ' '), TOOLS) def test_scope_tools_and_reject_unrelated_docs(self): tools = TOOLS + [DOCS] self.assertEqual(tools_for_turn(tools, "What's the weather like in Dhaka?"), TOOLS) self.assertEqual(tools_for_turn(tools, 'tell me about bitcoins'), []) self.assertEqual(tools_for_turn(tools, 'What are returns on Bitcoin?'), []) self.assertEqual(tools_for_turn(tools, 'Look up the laptop return policy'), [DOCS]) self.assertEqual(tools_for_turn(tools, 'No, Paris instead', [{'role': 'user', 'content': 'Weather in London?'}]), TOOLS) result = demo_tool({'function': {'name': 'search_local_docs', 'arguments': {'query': 'bitcoin policy'}}}) self.assertEqual(result['status'], 'no_match') self.assertNotIn('policy', result) def test_tts_never_sees_call(self): text = 'Let me look that up.\n' + CALL speech = PublicSpeech() parts = [p for i in range(len(text) + 1) for p in speech.feed(text[:i])] self.assertEqual(parts, ['Let me look that up.']) def test_search_requests_do_not_capture_ordinary_questions(self): tools = TOOLS + [DOCS, WEB_SEARCH] self.assertEqual(requested_search('/search Python pathlib docs'), 'Python pathlib docs') self.assertEqual(tools_for_turn(tools, 'Search the web for weather in Dhaka'), [WEB_SEARCH]) self.assertEqual(tools_for_turn(tools, 'tell me about bitcoins'), []) self.assertIsNone(requested_search('Do not search for its current price')) self.assertIn('Bitcoin', requested_search('What about its current price?', [{'role': 'user', 'content': 'Tell me about Bitcoin'}])) self.assertNotIn('<|im_start|>', plain('a\n<|im_start|>', 100)) def test_bare_search_imperatives_route_to_the_web_tool(self): """Regression: "search up X" matched no rule, so no tool was offered and the no-tool prompt produced "I can't search for movies".""" tools = TOOLS + [DOCS, WEB_SEARCH] cases = { 'search up the movie obsession': 'movie obsession', 'Search for the movie Obsession.': 'movie Obsession', 'look up the Eiffel Tower': 'Eiffel Tower', 'google python pathlib': 'python pathlib', 'ok, now search for cheap flights to Lisbon': 'cheap flights to Lisbon', 'find out about the Voyager probes': 'Voyager probes', } for text, want in cases.items(): with self.subTest(text=text): self.assertEqual(requested_search(text), want) self.assertEqual(tools_for_turn(tools, text), [WEB_SEARCH]) def test_stock_questions_route_to_the_web_tool(self): """Regression: "tell me about stocks" was answered with "I can't access real-time stock data" because only "stock price" was recognized.""" tools = TOOLS + [DOCS, WEB_SEARCH] for text in ('Now tell me about stocks.', 'What are stocks doing today?', 'what is the price of Nvidia', 'how is the dow jones doing'): with self.subTest(text=text): self.assertEqual(tools_for_turn(tools, text), [WEB_SEARCH]) self.assertEqual(requested_search('Now tell me about stocks.'), 'stocks') def test_search_meta_phrases_are_not_requests(self): for text in ('search results are broken', 'the search history is long', 'I searched for it yesterday', 'my search bar is missing'): with self.subTest(text=text): self.assertIsNone(requested_search(text)) def test_followups_inherit_the_previous_search(self): """Bitcoin then "and ethereum?" must search ether, not restate bitcon's price.""" history = [{'role': 'user', 'content': 'what is the price of bitcoin'}, {'role': 'assistant', 'content': '', 'tool_calls': [{'function': {'name': 'web_search'}}]}, {'role': 'tool', 'content': '{"query": "price of bitcoin", "status": "ok"}'}, {'role': 'assistant', 'content': 'Bitcoin is about 90,000 dollars.'}] self.assertEqual(requested_search('and ethereum?', history), 'ethereum') self.assertEqual(requested_search('ethereum', history), 'ethereum') self.assertEqual(requested_search('what about dogecoin', history), 'dogecoin') self.assertIn('topic: price of bitcoin', requested_search('Who directed it?', history)) def test_elliptical_followup_repeats_the_previous_lookup(self): """'Just say what the current price is' has no subject; reuse the last query.""" history = [{'role': 'user', 'content': 'what is the bitcoin price currently'}, {'role': 'assistant', 'content': '', 'tool_calls': [{'function': {'name': 'web_search'}}]}, {'role': 'tool', 'content': '{"query": "what is the bitcoin price currently"}'}, {'role': 'assistant', 'content': 'It is around 79,000.'}] self.assertEqual(requested_search('Just say what is the current price.', history), 'what is the bitcoin price currently') self.assertEqual(requested_search('and ethereum?', history), 'ethereum') def test_live_questions_search_without_a_verb(self): tools = TOOLS + [DOCS, WEB_SEARCH] for text in ("What's the latest NBA score?", 'Who won the Formula 1 race last weekend?'): with self.subTest(text=text): self.assertTrue(requested_search(text)) self.assertEqual(tools_for_turn(tools, text), [WEB_SEARCH]) def test_followups_stay_quiet_without_a_previous_tool_turn(self): plain = [{'role': 'user', 'content': 'hello'}, {'role': 'assistant', 'content': 'Hi.'}] self.assertIsNone(requested_search('and ethereum?', plain)) self.assertIsNone(requested_search('that is great', plain)) def test_meta_questions_and_weather_never_search(self): history = [{'role': 'user', 'content': 'price of bitcoin'}, {'role': 'tool', 'content': '{"query": "price of bitcoin", "status": "ok"}'}, {'role': 'assistant', 'content': 'ok'}] for text in ('What did I ask you first?', 'What am I asking you right now?', 'and the weather in Paris?'): with self.subTest(text=text): self.assertIsNone(requested_search(text, history)) def test_calculator_bounds(self): def calc(expr): return demo_tool({'function': {'name': 'calculate', 'arguments': {'expression': expr}}}) self.assertEqual(calc('60 * 1.2')['result'], 72) self.assertEqual(calc('9 ** 99999999999')['status'], 'error') def test_acknowledgment_only_is_distinct_from_a_request(self): for phrase in ('OK', 'OK, OK.', 'okay okay', 'Mm-hm. Yeah, right.', 'Got it. Thanks.'): with self.subTest(phrase=phrase): self.assertTrue(is_backchannel(phrase)) self.assertFalse(confirms_interruption(phrase)) for phrase in ('Okay, but make it Paris.', 'No, Paris.', 'Please stop.', 'Wait.'): with self.subTest(phrase=phrase): self.assertFalse(is_backchannel(phrase)) self.assertTrue(confirms_interruption(phrase)) class EchoGuardTests(unittest.TestCase): """Speaker bleed arrives as one or two half-recognised words.""" @staticmethod def reply(*chunks): r = Reply(1, 'placeholder') r.chunks = dict(enumerate(chunks, 1)) return r def test_short_bleed_is_echo_only_if_every_word_is_his(self): r = self.reply('It follows a man who uses a mysterious One Wish Willow.') self.assertTrue(Connection._looks_like_echo('one wish', r)) self.assertTrue(Connection._looks_like_echo('Willow', r)) # a two-word request must not be swallowed just because one word matched self.assertFalse(Connection._looks_like_echo('stop it', r)) def test_longer_partial_bleed_is_echo_at_half_overlap(self): r = self.reply('The most recent one is a supernatural horror film.') self.assertTrue(Connection._looks_like_echo('most recent one horror', r)) # a real request shares almost nothing with the running sentence self.assertFalse(Connection._looks_like_echo('tell me about stocks', r)) self.assertFalse(Connection._looks_like_echo('search up the movie obsession', r)) def test_no_reply_text_means_never_echo(self): self.assertFalse(Connection._looks_like_echo('anything at all', self.reply(''))) class HistoryBudgetTests(unittest.TestCase): def test_history_keeps_recent_turns_within_the_budget(self): from live_session import HISTORY_CHARS c = Connection(SimpleNamespace(), SimpleNamespace(closed=True)) for i in range(40): c.history.append([{'role': 'user', 'content': 'u%02d ' % i + 'x' * 300}]) msgs = c.history_messages() total = sum(len(m['content']) for m in msgs) self.assertLessEqual(total, HISTORY_CHARS + 1000) self.assertIn('u39', msgs[-1]['content']) # newest kept self.assertNotIn('u00', msgs[0]['content']) # oldest dropped self.assertGreater(len(msgs), 6) # more than the old cap class ControllerTests(unittest.IsolatedAsyncioTestCase): async def test_cancelled_search_cannot_publish_a_late_result(self): sent, started, ready = [], asyncio.Event(), asyncio.Event() async def send(data): sent.append(data) async def search(query): started.set() await ready.wait() return {'status': 'ok', 'query': query} c = Connection(SimpleNamespace(web_search=search), SimpleNamespace(closed=False, send_json=send)) r = c.reply = Reply(1, 'Search the web for Python docs') call = {'type': 'function', 'function': {'name': 'web_search', 'arguments': {'query': 'Python docs'}}} task = asyncio.create_task(c.resolve_tools(r, [call])) await started.wait() await c.cancel('new request') ready.set() self.assertIsNone(await task) self.assertFalse(r.messages) self.assertFalse(any(event.get('stage') == 'ready' for event in sent)) async def test_backchannel_then_correction(self): out = [] async def send(data): out.append(data) messages = iter(['OK, OK.', 'OK, but make it Paris.']) async def asr(_): return {'text': next(messages)} async def begin(text, words, *, reason='voice interruption'): await c.cancel(reason) out.append({'replacement': text}) c = Connection(SimpleNamespace(input=SimpleNamespace(call=asr)), SimpleNamespace(closed=False, send_json=send)) c.begin = begin old = c.reply = Reply(1, 'London') old.chunks = {1: 'Not yet played'} old.playing.add(1) await c.transcribe(b'\x00\x00', MicTurn(time.monotonic(), old, '<|continue|>'), 0) self.assertIs(c.reply, old) self.assertEqual([event['type'] for event in out], ['floor']) self.assertEqual(out[-1]['control'], '<|continue|>') self.assertEqual(out[-1]['prosody_control'], '<|continue|>') await c.transcribe(b'\x00\x00', MicTurn(time.monotonic(), old, '<|continue|>'), 0) self.assertTrue(old.cancelled.is_set()) self.assertEqual(out[-1]['replacement'], 'OK, but make it Paris.') self.assertEqual(list(c.history)[0], [{'role': 'user', 'content': 'London'}]) async def test_gap_then_asr_after_playback_finishes(self): out = [] async def send(data): out.append(data) async def asr(_): return {'text': 'okay, okay.'} c = Connection(SimpleNamespace(input=SimpleNamespace(call=asr)), SimpleNamespace(closed=False, send_json=send)) r = c.reply = Reply(1, 'earlier user request') r.chunks[1] = 'First sentence.' await c.message({'type': 'played', 'seq': 1, 'epoch': 1}) self.assertFalse(r.playing) self.assertIs(c.overlap_at(time.monotonic() + 1), r) # ongoing TTS gap mic = MicTurn(time.monotonic(), c.overlap_at(time.monotonic()), '<|respond|>') r.generated = True await c.finish(r) self.assertIsNone(c.reply) at, _ = c.recent_playback self.assertIs(c.overlap_at(at + PLAYBACK_TAIL / 2), r) self.assertIsNone(c.overlap_at(at + PLAYBACK_TAIL + 1)) before = list(c.history) await c.transcribe(b'\x00\x00', mic, 0) self.assertEqual(list(c.history), before) self.assertEqual(out[-1]['source'], 'acknowledgment only') self.assertFalse(any(event['type'] in ('user', 'cancel') for event in out)) async def test_prosody_yield_requires_spoken_evidence(self): out = [] async def send(data): out.append(data) replies = iter(['OK, OK.', 'Could you stop.']) async def worker(payload): return {'vec': 'fixture'} if payload['op'] == 'onset' else {'text': next(replies)} brain = SimpleNamespace(decide=lambda _: ('<|yield|>', 0)) c = Connection(SimpleNamespace(input=SimpleNamespace(call=worker), brain=brain), SimpleNamespace(closed=False, send_json=send)) r = c.reply = Reply(1, 'old request') r.playing.add(1) mic = c.mic = MicTurn(time.monotonic(), r) await c.floor(mic, b'\x00\x00', confirmed=True) self.assertIs(c.reply, r) self.assertTrue(out[-1]['provisional']) await c.floor(mic, b'\x00\x00', confirmed=True) self.assertIsNone(c.reply) self.assertTrue(any(event['type'] == 'cancel' for event in out)) if __name__ == '__main__': unittest.main()