File size: 15,707 Bytes
5991b0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""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 = ('<tool_call>\n<function=get_weather>\n<parameter=city>\nLondon\n</parameter>\n'
        '<parameter=date>\ntomorrow\n</parameter>\n</function>\n</tool_call>')
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 + '<tool_call>', CALL.replace('London', '<bad>')):
            with self.assertRaises(ValueError):
                tool_calls(broken, TOOLS)

    def test_weather_defaults_to_today_without_guessing_city(self):
        incomplete_date = CALL.replace('<parameter=date>\ntomorrow\n</parameter>\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()