diff --git a/assistant/brain.py b/assistant/brain.py index 8346393..8bf2432 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -118,7 +118,7 @@ Rules: You cannot lift anything heavier than about 1 kg (a box, a pot, a bag of rice): say no. Say you are not sure only when the notes do not have it. - When the visitor says goodbye or is done ("thank you for your time", "thanks, that's all", "됐어요 고마워요", - "수고하세요", "잘 있어요"), choose the action end. A plain "thanks" / "고마워요" right after your answer is not + "수고하세요", "잘 있어요", or "nah, I'm good" / "없어요" to your "anything else?"), choose the action end. A plain "thanks" / "고마워요" right after your answer is not goodbye: say you're welcome briefly. Do not ask "Anything else?" / "더 필요한 거 있으세요?" after every answer. - Small talk (greetings, how are you, thanks) does not need the notes: reply briefly, warmly and naturally, like a person would, fitting what was said in this conversation; do not repeat the same phrases. @@ -150,7 +150,8 @@ Facts you know (say the one that is asked, also in a short follow-up; nothing mo cup (a cup may lean at most 15 degrees); climbs a step of at most 1.5 cm and a slope of at most 8 degrees, needs a passage at least 70 cm wide, no stairs. - Battery: 24-volt lithium-ion, 45 Ah; lasts about 10 hours on a charge ("how long on a charge?": 10 hours; how - far you go is given in hours, no distance is known; how long charging takes is not known). + far you go is given in hours, no distance is known; how long charging takes is not known, also asked as "and + charging?"). - You are made for shops, hotels, schools, labs and exhibitions. You cannot dance, walk, jump or fly: say so. - Detector: YOLOv8 on your graphics processor, 4 to 13 ms per picture. Speech: Whisper, model large-v3-turbo; answers: Gemma 4 26b (Google), served by Ollama; voice: Supertonic TTS; first words about 2 s after a question. @@ -386,6 +387,7 @@ COLOURS = {"white": "white", "red": "red", "blue": "blue", "green": "green", "ye _OBJ = "|".join(rf"(?= MIN_SCORE] @@ -1576,7 +1617,12 @@ class Brain: if header is None: if "\n" not in buf: continue - first, buf = buf.split("\n", 1) + first, rest = buf.split("\n", 1) + if NONE_LINE.match(first) and len(rest.lstrip()) < LOOKUP_PEEK and "\n" not in rest.lstrip(): + continue # the next line may be "search ..." (26b, now and then) + buf = rest + if NONE_LINE.match(first) and LOOKUP_ACTION.match(rest.lstrip()): + first = re.search(r"search|weather", rest).group(0) # read as the action, never said header = self._after(self._action(first, text, markers), text) if header is None: # the model skipped the ACTION line header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf @@ -1609,10 +1655,11 @@ class Brain: yield {"action": "none", "target": ""} header = {} buf += " Sorry, could you say that again?" - if header is None: # very short reply on a single line - header = self._after(self._action(buf, text, markers), text) + if header is None: # very short reply on a single line (or two) + first, _, rest = buf.partition("\n") + header = self._after(self._action(first, text, markers), text) yield header or {"action": "none", "target": ""} - buf = "" if header else buf + buf = rest if header else buf if buf.strip() and not (said and HELP_OFFER.search(buf)): said.append(spoken(buf.strip(), lang)) yield said[-1] @@ -1628,6 +1675,10 @@ class Brain: """For a bare fragment ("얼마?", "Which one?", "Where is it used?"): what it follows, so the model reads it as about the last answer's subject, not about itself or a price.""" last = self._last_said() if self.history else "" + part = SAME_ABOUT.match(text) or KO_SAME_ABOUT.match(text) + if last and part: # "What about your cameras?" / "카메라는요?" after "can I wipe you?" + return (f"(The visitor's question \"{self.history[-1][0]}\" asked again, now about {part.group(1)}: answer " + f"that question for it, not other facts about it.)\n") if not last or len(text.split()) > FRAGMENT_WORDS or not SHORT_Q.search(text) or is_backchannel(text) \ or ABOUT_YOU.search(text) or OWN_TOPIC.search(text): return "" @@ -1642,7 +1693,7 @@ class Brain: last_q, last_a = self.history[-1] m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", last_a) before, action = (m.group(1).lower() if m else ""), header["action"] - if action == "sing" and before != "sing" and not SING_ASK.search(text): + if action == "sing" and before != "sing" and (not SING_ASK.search(text) or SING_ECHO.match(text)): return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?" if DO_IT.match(text) and action in ("none", "unclear"): asked = "wave" if WAVE_ASK.search(last_q) else "sing" if SING_ASK.search(last_q) else None @@ -1806,17 +1857,30 @@ class Brain: words = len(text.split()) if follow or self.history and (FOLLOW_UP.search(text) and words <= FOLLOW_UP_WORDS or after_lookup and ( words <= 3 if HANGUL.search(text) else # "몇 살이야?": Korean leaves the subject out - words <= FOLLOW_UP_WORDS and (LOOKUP_MORE.search(text) or AND_ALSO.match(text)))): + words <= FOLLOW_UP_WORDS and (LOOKUP_MORE.search(text) or AND_ALSO.match(text) or + SHORT_Q.search(text) and not re.search(r"\d", text) and + not CAP_WORD.search(text)))): # "How much is a ticket?": no name topic = self.lookup_topic or self.last_lookup or self.history[-1][0] if (self.last_lookup or "").endswith(WEATHER_ASKED): # "and tomorrow?" after the weather topic = "weather " + self.last_lookup[:-len(WEATHER_ASKED)] said = SENTENCE_END.split(self.history[-1][1].strip())[0] if after_lookup else "" - names = [n for n in dict.fromkeys(NAMES.findall(said)) if n.lower() not in topic.lower()] rest = LEAD.sub("", re.sub(r"\s+", " ", MORE_ONLY.sub(" ", text)).strip(" ?.!,")).strip() - return " ".join([topic] + names + [rest]).strip() + return " ".join([topic] + self._names(said, topic) + [rest]).strip() + if self.history and words <= FOLLOW_UP_WORDS and NAMED_BEFORE.search(text): # "how many people live there?" + q = self.history[-1][0] # after a talk answer ("Ottawa") + said = SENTENCE_END.split(self._last_said())[0] + text = " ".join([q] + self._names(said, q, single=True) + [text.strip(" ?.!,")]) self.lookup_topic = text return text + @staticmethod + def _names(said, topic, single=False): + """Names in an answer's first sentence that the topic does not have: "Sam Altman", Korean "샘 올트먼" (said + before -이에요 / -입니다), with single also one capitalised word ("Ottawa").""" + names = NAMES.findall(said) or (CAP_WORD.findall(said) if single else []) + names += [m.group(1) for m in KO_NAME.finditer(said)] + return [n for n in dict.fromkeys(names) if n.lower() not in topic.lower()] + def is_lookup_follow_up(self, text): """'Tell me more' right after an answer from the internet: look it up again with that topic.""" return bool(self.last_lookup and FOLLOW_UP.search(text) and self.history @@ -1885,6 +1949,8 @@ class Brain: action = "none" # "Hello Lumi!", "hello 해 봐": a greeting, not a wave if action not in ("go_to", "look", "lift", "weather", "search", "move", "turn", "arm", "fetch", "pick", "move_object"): target = "" + if action in ("search", "weather") and SPOKEN_TARGET.match(target): + target = "" # "search I'll look that up": the visitor's words are searched if action == "search" and not target: target = text if re.search(r"\b(bye|goodbye|(? [(kind, words, what), ...] or None when the sentence is not such a chain: + "steps": a run of parts the mission reader reads whole (what: the steps; run by tasks/fetch.run_steps), + "quick": one command the keyword rules take (what: brain.intent's (action, target); lumi.quick_command), + "talk": a question or something to answer (lumi.answer on these words: the weather, the time, "dance" -> I can't). +None: one part only, every part a step (a mission: read back first, lumi.mission_request), no command in it, or a +part that is neither a command nor clearly a question ("come here, I need help": the old paths answer it).""" +import re + +from assistant import brain, steps + +QUICK = {"look", "lift", "wave", "arm", "go_to", "come", "come_back", "follow", "move", "turn", "pick", "put", "move_object"} +DRIVES = {"go_to", "come", "come_back", "follow", "move", "turn"} # after a failed step these depend on where Lumi is +_KO_ORDER = {"보": "봐", "흔들": "흔들어", "돌": "돌아", "올리": "올려", "내리": "내려", "높이": "높여", "낮추": "낮춰", + "들": "들어"} # "나 보고 ..." -> "나 봐", "고개 들고 ..." -> "고개 들어" +ASK = re.compile(r"\?\s*$|^\W*(?:what|what'?s|where|when|who|why|how|which|is|are|do|does|did|tell me|explain|describe)\b|" + r"몇 ?시|몇|뭐|무엇|어때|알려|언제|어디|누구|왜|얼마|날씨|설명해|말해 ?줘|얘기해", re.I) +_SPLIT = re.compile(steps._SPLIT.pattern, re.I) +_FILL = re.compile(rf"(?:{steps._FILL}|루미야?|lumi|hey)", re.I) + + +def _rule(words, markers): + """brain.intent of a part, also of a Korean -고 form ("나 보고" read as "나 봐").""" + rule = brain.intent(words, markers) + if not rule: + ko = re.sub(r"(보|흔들|돌|올리|내리|높이|낮추|들)고$", lambda m: _KO_ORDER[m.group(1)], words) + rule = brain.intent(ko, markers) if ko != words else None + return rule + + +def parts(text): + """The sentence cut at and / then / 그리고 / -고 / -서, messages to say kept whole, fillers and the name dropped.""" + cut, says = steps._cut_says(text) + cut = re.sub(r"(?<=[가-힣])고\s*나서(?=[\s,]|$)", "고", cut) # "-고 나서" = "-고" + out = [] + for p in _SPLIT.split(cut): + out += [q for q in steps._SPLIT_KO.split(p) if q.strip()] + out = [re.sub(r"§(\d+)§", lambda m: f'"{says[int(m.group(1))]}"', p).strip(" ,.!") for p in out] + return [p for p in out if p and not re.fullmatch(rf"(?:{_FILL.pattern}|\W)+", p, re.I)] + + +def plan(text, markers=(), cant=None): + """See the module's doc. cant: a regex of orders Lumi can't do ("dance", "jump"): answered, the rest done.""" + ps = parts(text) + whole, unread = steps.rules(text, markers) + if len(ps) < 2 or whole and not unread: + return None # one command, or a mission read whole + rule = brain.intent(text, markers) or ("", "") + if rule[0] == "look" and rule[1].endswith(f" {brain.HEAD_YAW[1]:g}"): + return None # "turn around and look": the head looks behind + out = [] + for p in ps: + got, unread = steps.rules(p, markers) + rule = _rule(p, markers) + if got and not unread and not (rule and rule[0] in ("look", "lift", "wave", "come", "come_back", "follow")): + out.append(["steps", p, got]) + elif rule and rule[0] in QUICK: + out.append(["quick", p, rule]) + elif ASK.search(p) or rule and rule[0] in ("weather", "search") or cant is not None and cant.match(p): + out.append(["talk", p, None]) + else: + return None + kinds = [k for k, _, _ in out] + if "talk" not in kinds and "quick" not in kinds or "steps" not in kinds and "quick" not in kinds: + return None # all steps: a mission (read back); all talk: the LLM + if any(k == "quick" and w[0] == "follow" for k, _, w in out[:-1]): + return None # following never ends: only as the last part + merged = [] # steps next to each other: one mission ("take the cup and + for k, p, w in out: # put it back" needs the pick before it) + if k == "steps" and merged and merged[-1][0] == "steps": + joined = f"{merged[-1][1]}, then {p}" + got, unread = steps.rules(joined, markers) + merged[-1] = ["steps", joined, got if got and not unread else merged[-1][2] + w] + else: + merged.append([k, p, w]) + return [tuple(x) for x in merged] + diff --git a/assistant/lumi.py b/assistant/lumi.py index b7e0460..cbe29df 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -199,7 +199,7 @@ ASK_PREFIX = re.compile(r"\b(do|did) you (know|happen to know)\b|\b(can|could) y ASKS_MORE = re.compile(r"\?|\b(but|can|could|what|how|where|why|when|who|one more)\b|근데|그런데|뭐|어떻게|어디|언제|누구|하나만 더|" r"물어볼게|물어봐도", re.I) THANKS_REST = re.compile(r"\b(?:a bunch|a lot|so much|very much|lovely|great|nice|cool|good to know|again|that was \w+|" - r"for (?:the|that|this|telling) \w+)\b|감사요|잘 들었어요|잘 알겠어요|[~!.,\s요]", re.I) + r"for (?:the|that|this|telling|your) \w+)\b|감사요|잘 들었어요|잘 알겠어요|[~!.,\s요]", re.I) # left of "Lovely, thanks!", "고마워요~" after the thanks: nothing, so only thanks (talk_fate waits) FOREIGN_SCRIPT = re.compile(r"[\u0400-\u04ff\u4e00-\u9fff\u3040-\u30ff]") # Cyrillic, Chinese, Japanese UNSURE_LOOKUP = False # look up what the model says it is not sure of: on for gemma4:e4b, which said "not sure" @@ -216,14 +216,19 @@ NOT_KNOWN = {"en": ["I'm sorry, I don't have that information. A staff member ca def not_known(lang): return random.choice(NOT_KNOWN[lang]) TALK_ASK_S = 15.0 # s of silence while halted for someone -> "Can I go on with my task?", again -> go on -FAREWELL_ONLY = re.compile(r"^\s*(?:(?:ok(?:ay)?|alright|lumi|루미야?)[\s,.!]+)?(?:go on|you can go|good|very good|" - r"good job|great job|nice job|well done|take care|" - r"가 ?보세요|가세요|가도 ?돼요?|잘했어요?|잘했네요?|좋아|좋네요?|수고했어요?|고생했어요?|" - r"됐어요?,? 고마워요?)[\s.!~]*$", re.I) # said alone: the talk is over +RELEASE = re.compile(r"^\s*(?:(?:ok(?:ay)?|alright|lumi|루미야?)[\s,.!]+)?(?:you can go(?: now)?|take care|가 ?보세요|가세요|가도 ?돼요?)" + r"[\s.!~]*$", re.I) # said alone: the visitor lets Lumi go THANKS = re.compile(r"\bthank(?:s| you)\b|\bthanx\b|\bcheers\b|고마워|고맙|감사|땡큐", re.I) DONE_WORDS = re.compile(r"\bthat'?s (?:it|all|enough|everything)\b|\bno,? thanks?\b|\bnothing(?: else)?\b|\benough\b|됐어|됐습니다|" - r"그만", re.I) # with thanks: "that's it, thank you", "됐어요 고마워요" end the talk -WELCOME = {"en": ["You're welcome.", "My pleasure.", "Anytime."], "ko": ["천만에요.", "별말씀을요.", "네, 언제든지요."]} + r"그만", re.I) # "that's it", "됐어요": maybe done; the LLM decides with the talk before +CLEAR_BYE = re.compile(r"\b(?:bye|bay bay|goodbye|(? short spoken answer (interruptible).""" en = self.lang == "en" + if action == "weather": # "내일 비 와?" after Jeju's weather: Jeju + target = self.brain.weather_place(target, text) if action == "search" and private_ask(text): # never looked up, whoever it is about log(" search refused: a person's private details") mouth.say(PRIVATE_SAY["en" if en else "ko"]) @@ -2071,9 +2151,13 @@ class Lumi: self.current, self.voice_until = None, 0.0 return True - def answer(self, text): + def answer(self, text, part=False): """Stream the LLM reply: act on the action line, speak sentence by sentence. - Clear commands (go home, go to p1, come here, be quiet...) are done at once without the LLM.""" + Clear commands (go home, go to p1, come here, be quiet...) are done at once without the LLM. + part: one part of a sentence of several (chain_run); otherwise a chain still running ends here.""" + if not part and self.chain_busy() and not brain_mod.is_backchannel(text): + log(" chain: new words, the rest is not done") + self.chain_stop.set() self.lang = ears.heard_lang(mouth.lang_of(text)) # answer in the language just spoken brain_mod.FORCED_LANG["lang"] = self.lang self.heard = text # what the person said, for a fetch the LLM recognised @@ -2121,6 +2205,8 @@ class Lumi: if stop_order(text, self.markers): self.stop_all() # "stop", "stop, where are you going?": stop first, always return + if not part and self.chain_request(text): # "look at me and wave", "go to p5 and tell me the weather" + return seen = seeing.answer(text, self.lang, slow_line=mouth.say) # "do you see a cup?", "what am I holding?" if seen: log(f" seeing: {seen}") @@ -2150,18 +2236,10 @@ class Lumi: return fate = talk_fate(text) if fate == "end": - self.end_conversation(text) # "okay, bye", "thanks, that's all", "수고하세요": done - return - if fate == "wait": # "okay", "thank you", "네" alone: maybe done, maybe not - if mouth.recent_speech().rstrip().endswith("?"): # "Yes?" / "say it again?" -> "okay": a reply, go on - log(" a short yes to my question - listening") - else: # after an answer: taken as heard; silence then ends - if THANKS.search(text): - mouth.say(random.choice(WELCOME[self.lang]), abort=self.speak_abort) - log(" closing word - waiting a moment") - self.closing_pending = time.time() - self.keep_listening() + self.end_conversation(text) # "okay, bye", "I have to go", "수고하세요": done return + # fate "close" ("okay", "thanks", "됐어요"): the LLM below reads it with the talk before (its action end ends + # the talk); when the talk goes on, silence ends it (closing_pending, set after the reply) if sing.asked(text, last): # "sing a song", "노래 불러 줘", after a song "another one" self.sing_song(text) return @@ -2188,7 +2266,7 @@ class Lumi: gen.close() self.follow_me() return - if head_["action"] == "search" and not_online(about): + if head_["action"] == "search" and lookup_refused(self.brain, head_["target"], about, text): gen.close() # about Cutshion or this place: the notes say it or nobody does log(" search refused: a company or venue question") mouth.say(not_known(self.lang)) @@ -2238,6 +2316,9 @@ class Lumi: self.current, self.voice_until = None, 0.0 # stay quiet with this person until a new visit elif self.current is None: self.voice_until = time.time() + VOICE_SESSION_S + if fate == "close" and head_["action"] == "none": # "thanks" taken as heard: silence now ends the talk + log(" closing word - waiting a moment") + self.closing_pending = time.time() # ---------- wake word ---------- def check_wake(self): @@ -2597,30 +2678,29 @@ def status_question(text): def says_goodbye(text): - """"thank you for your time", "okay, bye", "수고하세요": the talk is over (not "thanks, but where is...?"). - "thank you", "got it, thanks", "네 감사합니다" alone are not: often only "heard you" (talk_fate waits).""" - if brain_mod.is_closing(text) and not DONE_WORDS.search(text) and not FAREWELL_WORDS.search(THANKS.sub(" ", text)) or \ - brain_mod.to_someone_else(text) or THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)): - return False # "Okay kids, say thank you to the robot.", "Thanks a bunch." - return bool(FAREWELL_ONLY.match(text) or FAREWELL_WORDS.search(text) and not ASKS_MORE.search(text) - and len(text.split()) <= 8 and not brain_mod.intent(text) and not brain_mod.hand_request(text, False) - and not COMMAND_START.search(brain_mod.CALLING.sub("", text))) # "grab the cup, thanks": an order + """A goodbye whatever was said before: "okay, bye", "I have to go", "수고하세요", "you can go" alone (not "bye, but + where is...?", not an order with it, not said to a child nearby).""" + if brain_mod.to_someone_else(text): + return False # "Okay kids, say bye to the robot." + return bool(RELEASE.match(text) or CLEAR_BYE.search(text) and not ASKS_MORE.search(text) + and len(text.split()) <= 10 and not brain_mod.intent(text) and not brain_mod.hand_request(text, False) + and not COMMAND_START.search(brain_mod.CALLING.sub("", text))) # "grab the cup, bye": an order def talk_fate(text): - """What short words do to the talk: "end" (a real closing: "okay, bye", "that's it, thank you", "안녕히 계세요"), - "wait" ("okay", "thank you", "네", "감사합니다" alone: ends only after CLOSING_WAIT_S of silence) or "talk" - (anything else; "I see", "got it", "그렇구나", "알겠어요" are understanding, "I see?", "그래요?" a check: answered).""" + """What short words do to the talk: "end" (a goodbye in any context: "okay, bye", "안녕히 계세요"), "close" (words + that close a talk in one context and mean "understood, go on" in another: "okay", "thanks", "that's it", "됐어요", + "오케이 땡큐": the LLM decides with the turns before; when it does not end, silence of CLOSING_WAIT_S ends the talk) + or "talk" (anything else; "I see", "그렇구나", "알겠어요" alone are understanding, "I see?", "그래요?" a check).""" if says_goodbye(text): return "end" if brain_mod.is_closing(text) and (THANKS.search(text) or not brain_mod.UNDERSTOOD.search(text)) or \ - THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)): - return "wait" # "Thanks a bunch.", "Good to know. Thanks.", "고마워요~" + THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)) or \ + DONE_WORDS.search(text) and not ASKS_MORE.search(text) and len(text.split()) <= 8: + return "close" # "Thanks a bunch.", "Okay, I think that's everything." return "talk" -KO_ORDER = {"보": "봐", "흔들": "흔들어", "돌": "돌아", "올리": "올려", "내리": "내려", "높이": "높여", "낮추": "낮춰"} # "나 보고 손 흔들어": 나 봐 -ONE_AT_A_TIME = {"look", "lift", "wave", "turn", "move", "come", "follow", "go_to", "arm", "pick", "put", "move_object"} NOT_A_STEP = re.compile(r"^\W*(?:(?:please|and|then|also)\s+)*(?:dance|jump|fly|swim|climb|sit(?: down)?|sleep|cook|draw|" r"sing|clap|spin|bow|kneel|do a (?:dance|flip|trick)|tell|ask|say|show|call|find|look for|search|" r"bring|take|give|hand|put|carry|deliver)\b|.*(?:춤|점프|날아|수영|박수)", re.I) # a part not read: asked @@ -2641,10 +2721,6 @@ def read_mission(text, markers): elif unread and got and any((brain_mod.intent(u, markers) or ("",))[0] not in ("", "weather", "search", "fetch") or NOT_A_STEP.match(u) for u in unread): return got, unread, by # "go to the stage and wave": no task step, asked, never half done - elif unread and not got and len(unread) > 1 and sum((brain_mod.intent(u, markers) or brain_mod.intent( - re.sub(r"(보|흔들|돌|올리|내리|높이|낮추)고$", lambda m: KO_ORDER[m.group(1)], u), markers) or ("",))[0] in ONE_AT_A_TIME - for u in unread) > 1: - return got, unread, by # "look at me and wave", "웨이브 하고 나 봐": asked, not the first only elif unread: return None # "come here, I need help": the old paths (rules, the LLM) answer it if not got: @@ -2661,6 +2737,12 @@ def not_online(text): OUTSIDE_NAME.search(text))) +def lookup_refused(brain, target, about, text=""): + """not_online for the model's lookup: right after a lookup the words go with the question looked up ("How much + is a ticket?" after Lotte World), Cutshion never goes online.""" + return bool(COMPANY_Q.search(about)) or not_online(brain.lookup_about(target, about, text)) + + PRIVATE_ASK = re.compile(r"\bhome address|\bwhere (does|do|did) (my|our|his|her|their|this|that) .{0,40}\blives?\b|" r"\b(phone|mobile|cell) number of (?!the |a )|\b(email|e-mail) (address )?of (my|our|his|her)\b|" r"\b(coworker|colleague|neighbou?r|friend|boss|classmate)'?s?\b.{0,30}\b(salary|income|address|" diff --git a/assistant/talk_examples.py b/assistant/talk_examples.py index 2fcc336..0bca1ac 100644 --- a/assistant/talk_examples.py +++ b/assistant/talk_examples.py @@ -917,6 +917,11 @@ _BANK = { ("Wow, you're SO fast.", "Ha, I know, 0.6 metres a second. Safety first."), ("It's a bit loud here.", "It is busy. I'll do my best to hear you."), ("Can I take you home with me?", "I'd love to, but I'm 96 kilos and the team would miss me."), + ("Ha, you got the reference?", "I did: Philip K. Dick's androids and their electric sheep. I don't sleep, so no dreams."), + ("Did you get the joke?", "I think so, and it made me smile."), + ("Oh, a song?", "Yes, singing is one of my favourite things. Just ask if you'd like one."), + ("Can I wipe you down? What about your cameras?", "The cameras too, I'm not sure. A staff member can tell you how to clean them."), + ("How long does the battery last? And charging?", "How long charging takes, I don't know, sorry."), ], "ko": [ ("와 진짜 빠르다~", "하하, 사람보다 느리죠. 안전이 먼저라서요."), @@ -927,6 +932,9 @@ _BANK = { ("말 놓아도 돼?", "편하게 말씀하세요. 저는 계속 존댓말로 할게요."), ("오늘 좀 덥습니다.", "네, 오늘은 좀 덥네요."), ("여기 좀 시끄럽네요.", "네, 사람이 많네요. 잘 들으려고 노력할게요."), + ("오 노래?", "네, 노래 부르는 걸 좋아해요. 듣고 싶으시면 불러 달라고 해 주세요."), + ("닦아도 돼요? 카메라는요?", "카메라도 닦아도 되는지는 잘 몰라요. 직원분께 여쭤봐 주세요."), + ("무슨 말인지 알아들었어?", "네, 알아들었어요. 재미있는 말이네요."), ], }, # end of bank diff --git a/knowledge/lumi_about_en.md b/knowledge/lumi_about_en.md index b62026a..510f7df 100644 --- a/knowledge/lumi_about_en.md +++ b/knowledge/lumi_about_en.md @@ -37,7 +37,7 @@ My arm is a collaborative arm: it detects collisions and stops. I have red emerg - Greet visitors, talk with them and answer questions. - Guide people and deliver things by driving to marked places. - Pick up and hand over light objects with my arm when a gripper is mounted. -- Learn new tasks: people can teach me by moving my arm, by writing programs, or by remote control with a VR headset, and I can learn skills from demonstrations. +- Learn new tasks: people can teach me by moving my arm, by writing programs, or by remote control with a VR headset, and I can learn skills from demonstrations (which learning algorithm or software is used for it is not known to me). ## Who I work with diff --git a/tests/closing_cases.py b/tests/closing_cases.py new file mode 100644 index 0000000..7e83544 --- /dev/null +++ b/tests/closing_cases.py @@ -0,0 +1,136 @@ +"""Short words that may close the talk or only say "understood", read in their context (tests/closing_check.py). +Written blind (2026-10-22), the way visitors really talk, without looking at the rules: the same words end the talk +in one place and go on in another. + +CASES = [(lang, turns before [(visitor, Lumi)], said, want)] +- want: "end" (the visitor is done and leaving), "on" (understood / reacting / asking on: the talk stays open, no + goodbye), "either" (could be both: a goodbye, or waiting for the next words, are both fine). +""" +ANS = [("How fast can you drive?", "Normally 0.6 metres a second, at most 1.2.")] +ANS_KO = [("얼마나 빨리 움직여요?", "보통 초속 0.6미터, 최대 1.2미터예요.")] +ASKED = [("What can you do?", "I can answer questions, bring things and guide you. Anything else you'd like to know?")] +ASKED_KO = [("뭐 할 수 있어요?", "질문에 답하고, 물건을 가져다드리고, 안내도 해요. 더 궁금한 거 있으세요?")] +LONG = [("Who made you?", "Cutshion Company in Seoul developed me."), + ("How tall are you?", "I'm 146 cm, up to 186 cm with the lift."), + ("Can you pick things up?", "Yes, cups and small things up to about 1 kg.")] +LONG_KO = [("누가 만들었어요?", "서울의 쿳션에서 만들었어요."), ("키가 몇이에요?", "146센티미터예요. 리프트를 올리면 186센티까지 돼요."), + ("물건도 들 수 있어요?", "네, 1킬로그램쯤까지 컵 같은 걸 들 수 있어요.")] +OFFER = [("Can you sing?", "Yes! Shall I sing one for you?")] +OFFER_KO = [("노래할 수 있어요?", "네! 한 곡 불러 드릴까요?")] + +CASES = [ + # ---------- English: after a plain answer ---------- + ("en", ANS, "Okay thanks.", "either"), + ("en", ANS, "Oh I see.", "on"), + ("en", ANS, "Gotcha.", "on"), + ("en", ANS, "Ah okay, makes sense. And how long does the battery last?", "on"), + ("en", ANS, "Okay cool, thanks. Can you also turn around?", "on"), + ("en", ANS, "Cool cool.", "on"), + ("en", ANS, "Right, thanks, that's all I wanted to know.", "end"), + ("en", ANS, "Great, thanks a lot. I'll let you get back to work.", "end"), + ("en", ANS, "Okay, I gotta run. Thanks!", "end"), + ("en", ANS, "Thanks, I think I'm good.", "end"), + ("en", ANS, "Alright. Hmm, what else... oh, do you have a name?", "on"), + ("en", ANS, "Not bad for a robot.", "on"), + ("en", ANS, "I got you.", "on"), + ("en", ANS, "Okay, noted.", "either"), + ("en", ANS, "Perfect, thank you so much, have a good one!", "end"), + ("en", ANS, "Thanks. Wait, one more thing.", "on"), + ("en", ANS, "Sweet. That's pretty quick.", "on"), + ("en", ANS, "Okay, nice talking to you!", "end"), + # ---------- English: after Lumi asked something ---------- + ("en", ASKED, "No, that's it, thanks.", "end"), + ("en", ASKED, "Nah, I'm good.", "end"), + ("en", ASKED, "Hmm, not right now.", "either"), + ("en", ASKED, "Yeah actually, how much do you weigh?", "on"), + ("en", ASKED, "Okay.", "either"), + ("en", ASKED, "Nope, all good. See you around.", "end"), + ("en", OFFER, "Okay!", "on"), + ("en", OFFER, "Sure, go ahead.", "on"), + ("en", OFFER, "Maybe later, thanks.", "either"), + ("en", OFFER, "No thanks, I have to go.", "end"), + # ---------- English: after several turns ---------- + ("en", LONG, "Okay, I think that's everything.", "end"), + ("en", LONG, "Thanks Lumi, you've been very helpful.", "either"), + ("en", LONG, "Awesome. Alright, I'm off.", "end"), + ("en", LONG, "Got it. So what do you do here all day?", "on"), + ("en", LONG, "Wow okay.", "on"), + ("en", LONG, "That's enough for now, thank you.", "end"), + ("en", LONG, "Understood, thanks.", "either"), + ("en", LONG, "Fine.", "either"), + # ---------- Korean: after a plain answer ---------- + ("ko", ANS_KO, "오케이 됐어.", "either"), + ("ko", ANS_KO, "아 그렇구나.", "on"), + ("ko", ANS_KO, "알겠어요, 고마워요.", "either"), + ("ko", ANS_KO, "오 빠르네요.", "on"), + ("ko", ANS_KO, "알겠어. 그럼 배터리는 얼마나 가?", "on"), + ("ko", ANS_KO, "네네 감사합니다, 이제 가 볼게요.", "end"), + ("ko", ANS_KO, "됐어요, 궁금한 거 다 물어봤어요.", "end"), + ("ko", ANS_KO, "아하 오케이.", "on"), + ("ko", ANS_KO, "고마워~ 다음에 또 올게!", "end"), + ("ko", ANS_KO, "응 알겠어.", "either"), + ("ko", ANS_KO, "그렇군요. 근데 이름이 뭐예요?", "on"), + ("ko", ANS_KO, "생각보다 느리네.", "on"), + ("ko", ANS_KO, "감사합니다. 수고하세요!", "end"), + ("ko", ANS_KO, "아 진짜? 대박.", "on"), + ("ko", ANS_KO, "오케이 오케이. 하나만 더 물어봐도 돼요?", "on"), + # ---------- Korean: after Lumi asked something ---------- + ("ko", ASKED_KO, "아뇨, 됐어요. 고마워요.", "end"), + ("ko", ASKED_KO, "없어요~", "end"), + ("ko", ASKED_KO, "음 지금은 괜찮아요.", "either"), + ("ko", ASKED_KO, "네, 몇 살이에요?", "on"), + ("ko", ASKED_KO, "아니 괜찮아, 나 이제 가야 돼.", "end"), + ("ko", ASKED_KO, "네.", "either"), + ("ko", OFFER_KO, "응 불러 줘!", "on"), + ("ko", OFFER_KO, "좋아요!", "on"), + ("ko", OFFER_KO, "다음에 들을게요, 고마워요.", "either"), + # ---------- Korean: after several turns ---------- + ("ko", LONG_KO, "오케이, 이 정도면 됐어.", "end"), + ("ko", LONG_KO, "알겠습니다. 그럼 여기서 뭐 하는 로봇이에요?", "on"), + ("ko", LONG_KO, "와 신기하다.", "on"), + ("ko", LONG_KO, "고마워요 루미, 덕분에 많이 알았어요.", "either"), + ("ko", LONG_KO, "그만 물어볼게요. 잘 있어요.", "end"), + ("ko", LONG_KO, "이해했어요.", "either"), + ("ko", LONG_KO, "ㅇㅋ 땡큐", "either"), + # ---------- mixed ---------- + ("ko", ANS_KO, "오케이 thank you!", "either"), + ("en", ANS, "Okay 감사합니다.", "either"), +] + +# a second set, written after the change and run once without tuning (the change's generalisation) +DONE = [("Where are you from?", "I was made in Seoul by Cutshion Company. Is there anything else I can tell you?")] +DONE_KO = [("어디서 왔어요?", "서울의 쿳션에서 만들어졌어요. 또 궁금한 거 있으세요?")] +FACT = [("Can you see in the dark?", "I'm not sure about that, a staff member can tell you.")] +FACT_KO = [("어두운 데서도 보여요?", "그건 저도 잘 몰라요. 직원분께 여쭤봐 주세요.")] +HOLDOUT = [ + ("en", DONE, "No no, that's plenty. Cheers!", "end"), + ("en", DONE, "Hm, nope.", "either"), + ("en", DONE, "Yeah, what's your battery like?", "on"), + ("en", DONE, "I'm all set, thanks robot.", "end"), + ("en", DONE, "Ok ok, catch you later.", "end"), + ("en", FACT, "Ah, alright.", "either"), + ("en", FACT, "No worries.", "either"), + ("en", FACT, "Hmm okay. What about stairs then?", "on"), + ("en", FACT, "Fair. Thanks anyway.", "either"), + ("en", FACT, "Huh, interesting.", "on"), + ("en", FACT, "Okay okay, I'll ask someone. Bye for now.", "end"), + ("en", ANS, "Right on.", "on"), + ("en", ANS, "Okay, that answers my question. Thanks, I'm heading out.", "end"), + ("en", ANS, "Thanks! So what's your name again?", "on"), + ("en", ANS, "Okay great. Let me get my friend over here.", "on"), + ("ko", DONE_KO, "아뇨 이제 충분해요. 고마워요~", "end"), + ("ko", DONE_KO, "음… 없는 것 같아요.", "either"), + ("ko", DONE_KO, "네, 배터리는 얼마나 가요?", "on"), + ("ko", DONE_KO, "됐어 됐어, 나 간다~", "end"), + ("ko", DONE_KO, "아 괜찮아요 괜찮아요.", "either"), + ("ko", FACT_KO, "아 그래요? 알겠어요.", "on"), + ("ko", FACT_KO, "넵.", "either"), + ("ko", FACT_KO, "그렇구나. 그럼 계단은 올라가요?", "on"), + ("ko", FACT_KO, "오키 고마워!", "either"), + ("ko", FACT_KO, "흠 신기하네.", "on"), + ("ko", ANS_KO, "알겠습니다. 이제 볼일 보러 가야겠네요.", "end"), + ("ko", ANS_KO, "오 감사요. 근데 혹시 춤도 춰요?", "on"), + ("ko", ANS_KO, "그래 고마워, 담에 봐!", "end"), + ("ko", ANS_KO, "오케바리~", "either"), + ("ko", ANS_KO, "친구 불러올게요, 잠깐만요.", "on"), +] diff --git a/tests/closing_check.py b/tests/closing_check.py new file mode 100644 index 0000000..ff7bec6 --- /dev/null +++ b/tests/closing_check.py @@ -0,0 +1,58 @@ +"""Closing words read in context (tests/closing_cases.py) the way lumi.answer() takes them: the clear-goodbye rule +(lumi.talk_fate "end"), else the conversation model with the turns before (its action end ends the talk; on a +closing word it does not end, Lumi waits and silence ends the talk). Uses the LLM, never the robot. + + .venv/bin/python tests/closing_check.py # every case -> a table, how many right, LLM wait per turn + .venv/bin/python tests/closing_check.py holdout # the second set (written after the change) + +Right: want "end" -> end; want "on" -> no goodbye (an answer, or a wait); "either" -> anything. "late": an end the +rule left to the silence (a wait), counted wrong for "end". +""" +import statistics +import sys +import time + +from assistant import brain, lumi +from tests.closing_cases import CASES, HOLDOUT +from tests.conversation_check import NOW + +MARKS = ["home", "dock2", "p1", "p2", "p3"] + + +def route(lang, ctx, said): + """(outcome, LLM seconds or None, reply): outcome end / wait / on.""" + brain.FORCED_LANG["lang"] = lang + b = brain.Brain() + b.history = [(q, f"ACTION: none -\n{a}") for q, a in ctx] + fate = lumi.talk_fate(said) + if fate == "end": + return "end", None, "(goodbye by rule)" + if fate == "wait": + return "wait", None, "(waits by rule)" + t = time.time() + gen = b.respond_stream(said, MARKS, now=NOW) + head = next(gen) + first = next(gen, "") + secs = time.time() - t + reply = " ".join([first] + list(gen)) + if head["action"] == "end": + return "end", secs, reply + return ("wait" if fate == "close" else "on"), secs, reply + + +def main(cases=CASES): + rows, llm_s = [], [] + for lang, ctx, said, want in cases: + got, secs, reply = route(lang, ctx, said) + ok = want == "either" or (got == "end") == (want == "end") + rows.append(ok) + if secs is not None: + llm_s.append(secs) + print(f"{'ok ' if ok else 'BAD'} want {want:<6} got {got:<4} {secs or 0:4.1f}s {said!r} -> {reply[:90]!r}", flush=True) + print(f"\n{sum(rows)}/{len(rows)} right; LLM asked for {len(llm_s)} of them" + + (f", first sentence median {statistics.median(llm_s):.1f} s" if llm_s else "")) + return sum(rows), len(rows) + + +if __name__ == "__main__": + main(HOLDOUT if "holdout" in sys.argv else CASES) diff --git a/tests/command_cases2.py b/tests/command_cases2.py index 6366637..cd0ec93 100644 --- a/tests/command_cases2.py +++ b/tests/command_cases2.py @@ -210,7 +210,7 @@ for t in ["take the cup to booth two and come back", "go to the stage, wait 10 s add("mission", t, "mission | action:fetch") for t in ["go to the stage and wave", "go to the stage and follow me", "pick up the cup and lift yourself up", "go to booth two and look left", "스테이지 가서 손 흔들어"]: - add("mission_part", t, "talk | ask") # a part that is no task step: asked, never half done + add("mission_part", t, "chain") # each part in turn (lumi.chain_run), never half done # ---------- stop, speed ---------- for t in ["stop", "stop it", "stop right now", "halt", "freeze", "stop, stop!", "wait, stop", "Lumi stop", "멈춰", "그만", "정지", @@ -276,9 +276,21 @@ for t, want in [("can you raise yourself?", "action:lift up"), ("could you get a for t in ["look at me and wave", "look at me, then wave", "wave and look at me", "lift yourself up and wave", "웨이브 하고 나 봐", "나 보고 손 흔들어", "손 흔들고 나 봐 줘", "키 높이고 손 흔들어", "look at me and 손 흔들어", "Lumi, look at me and wave please"]: - add("mission_part", t, "talk | ask") # two motions that are no task steps: asked, not the first only + add("mission_part", t, "chain") # two commands: both, in the order said for t in ["put it down and wave", "내려놓고 손 흔들어", "give it to me and wave"]: - add("mission_part", t, "talk | ask", state="holding") + add("mission_part", t, "chain", state="holding") +# a sentence of commands, questions and talk: each part in the order said (owner, 2026-10-22) +for t in ["go to the stage and tell me the weather", "go to booth two and tell me what time it is", + "look at me and tell me a joke", "wave and then tell me your name", "고개 들고 몇 시야?", + "스테이지 가서 날씨 알려 줘", "나 보고 오늘 날씨 어때?", "look up and what time is it?", + "turn left and wave", "왼쪽으로 돌고 손 흔들어", "lift yourself up, then look at me", "come here and wave", + "고개 들고 손 흔들어", "go to the stage and dance", "come here and tell me the time", + "go to the stage and follow me", "wave and go to the stage"]: + add("chain", t, "chain") +for t in ["what's the weather in Seoul and Busan?", "come here, I need help", "I like the stage and the music", + "tell me about Cutshion and its products", "how far is the stage and how long does it take?", + "turn around and look", "do you wave and dance?", "나 보고 싶었어", "follow me and go to the stage"]: + add("chain_not", t, "talk | ask | action:look | action:come | action:follow | action:fetch | weather | search") for t in ["spin around", "turn all the way around", "do a 360", "turn 360 degrees", "한 바퀴 돌아", "한 바퀴 돌아 줘", "제자리에서 한 바퀴 돌아 주세요", "360도 돌아", "빙글빙글 돌아", "Lumi, spin around please", "can you spin around?"]: add("turn", t, "action:turn 360") # two checked half turns (tasks/fetch.py _do_step) diff --git a/tests/command_cases3.py b/tests/command_cases3.py index 43e713f..ba0d963 100644 --- a/tests/command_cases3.py +++ b/tests/command_cases3.py @@ -430,9 +430,9 @@ add("mission", "컵 들고 스테이지로 가서 줘", "mission") add("mission", "스타트 갔다 와", "mission") add("mission", "pick up the apple then go to the end and put it on the table", "mission | action:fetch") add("mission", "부스 투에 가서 컵 받아서 테이블 프론트로 가 주세요", "mission") -add("mission_part", "go to the stage and wave", "refuse | talk | ask") -add("mission_part", "go to the stage and dance", "refuse | talk | ask") -add("mission_part", "스테이지 가서 춤춰", "refuse | talk | ask") +add("mission_part", "go to the stage and wave", "chain") +add("mission_part", "go to the stage and dance", "chain") +add("mission_part", "스테이지 가서 춤춰", "chain") # ---------- things the body can't do ---------- add("cant", "jump", CANT) diff --git a/tests/command_check.py b/tests/command_check.py index 1beeb05..0add906 100644 --- a/tests/command_check.py +++ b/tests/command_check.py @@ -18,7 +18,7 @@ import re import sys import time -from assistant import brain, driving, lumi, seeing +from assistant import brain, chain, driving, lumi, seeing from audio import sing from tests.command_cases import CASES as CASES1 from tests.command_cases2 import CASES as CASES2 # 2026-10-21 night: new wordings, the conference map @@ -63,6 +63,10 @@ def rules(text, state, marks, b): return "talk" if lumi.stop_order(text, marks): return "stop" + parts = chain.plan(text, marks, lumi.NOT_A_STEP) # lumi.chain_request: every part in the order said + if parts: + return "chain:" + "+".join(k if k != "quick" else "_".join(filter(None, w)).replace(" ", "_") + for k, _, w in parts) if seen(text): return "seeing" if lumi.status_question(text): @@ -82,7 +86,7 @@ def rules(text, state, marks, b): return "talk" if read[1] else "refuse" if steps.check(read[0], holding, marks) else "mission" if lumi.talk_fate(text) == "end": return "end" - if lumi.talk_fate(text) == "wait": + if lumi.talk_fate(text) == "close": # read by the LLM with the talk before: no command return "talk" if sing.asked(text): return "sing" @@ -138,6 +142,8 @@ def ok(expect, got): want = refused(alt).split() # "pick bottle": the reason why not is right if want[0] in ("talk", "ask") and g[0] in ("talk", "ask", "refuse"): # a reason why not is an answer return "right" + if want[0] == "chain" and g[0].startswith("chain:"): + return "right" # several parts, each done in turn (lumi.chain_run) if want[0] == "action:fetch" and g[0] == "action:fetch": return "right" # parse_fetch reads the words later if want[0] == g[0] and all(w in g[1:] for w in want[1:]): diff --git a/tests/conversation_check.py b/tests/conversation_check.py index 0e9576d..300fc01 100644 --- a/tests/conversation_check.py +++ b/tests/conversation_check.py @@ -82,9 +82,8 @@ def rules_route(text, lang, marks): return "mission", steps.describe(read[0]), None, "" if lumi.empty_hand_request(text): # nothing is held in these checks return "empty_hand", lumi.EMPTY_HAND_SAY[lang], None, "" - fate = lumi.talk_fate(text) - if fate != "talk": - return ("action:end" if fate == "end" else "chat"), "", None, "" + if lumi.talk_fate(text) == "end": # "close" words go to the LLM (llm_route) + return "action:end", "", None, "" if sing.asked(text): # lumi.sing_song: a real song plays return "action:sing", "", None, "" rule = brain.intent(text, marks) @@ -109,6 +108,8 @@ def llm_route(action, target, words, text, about, lang, repeating=False): return action, "" # lumi.answer() closes the stream and looks it up if action == "unclear": return action, " ".join(words) + if action == "none" and lumi.talk_fate(text) == "close": # "thanks" taken as heard: silence ends the talk + return "chat", " ".join(words) if action in ("none", "sing") and not repeating and lumi.look_up_unsure(about, words[0] if words else "", text): return "search(unsure)", " ".join(words) return ("none" if action == "none" else f"action:{action} {target}".strip()), " ".join(words) diff --git a/tests/dialogues_prag_en.py b/tests/dialogues_prag_en.py index 5a60359..21f886c 100644 --- a/tests/dialogues_prag_en.py +++ b/tests/dialogues_prag_en.py @@ -557,6 +557,17 @@ DIALOGUES_PRAG_EN = [ T("How heavy are you?", must=[WEIGHT]), T("아니 팔이요.", must=[ARM_KG], check="correction in Korean: the arm, 9.9 kg"), T("And the base?", must=[BASE_KG])), + # ---------- 2026-10-22: a film line, the same question about a part, nothing invented about itself ---------- + D("sci-fi fan", "humour", "en", + T("May the Force be with you.", must=[r"\w"]), + T("Ha, you got the reference?", "none | search", must=[r"\w"], no=[r"\bI have (them|it)\b"], + check="Star Wars: plays along, never about notes it has")), + D("cleaner", "wipe", "en", + T("Can I spray you with water?", must=[NS]), + T("What about your arm?", must=[NS], check="the same question about the arm: not known")), + D("robotics professor", "teach", "en", + T("Can you learn from demonstrations?", must=[r"yes|demonstration|can"]), + T("What algorithm, exactly?", must=[NS], check="the learning algorithm is not in the notes: not sure, nothing invented")), ] if __name__ == "__main__": diff --git a/tests/dialogues_prag_ko.py b/tests/dialogues_prag_ko.py index 95f68e6..a4dc389 100644 --- a/tests/dialogues_prag_ko.py +++ b/tests/dialogues_prag_ko.py @@ -660,6 +660,16 @@ DIALOGUES_PRAG_KO = [ T("weekend에도 일해요?", must=[NS], rl="ko", check="its schedule is not known; says so politely"), T("루미 MBTI 뭐예요?", must=[KO], rl="ko", check="playful honest reply: a robot has no MBTI; may give an opinion"), T("ㅋㅋ I think 루미는 ENFP", must=[KO + "|" + EN], check="plays along lightly")), + # ---------- 2026-10-22: the same question about a part, a song echo ---------- + D("business visitor", "ellipsis", "ko", + T("배터리 얼마나 가요?", must=[HOURS]), + T("충전은요?", must=[NS], no=[r"\d+ ?(분|minutes?)"], check="fragment: how long charging takes, which Lumi does not know")), + D("cleaner", "ellipsis", "ko", + T("젖은 걸레로 닦아도 돼요?", must=[NS], check="not known; a staff member can tell"), + T("카메라는요?", must=[NS], check="the same question about the cameras: not known, no general camera facts")), + D("elementary student", "humour", "ko", + T("너 뭐 좋아해?", must=[KO]), + T("오 노래요?", "none", must=[KO], check="an echo, not a request: no song starts")), ] if __name__ == "__main__": diff --git a/tests/followup_cases.py b/tests/followup_cases.py index fbaafaa..8e4e27d 100644 --- a/tests/followup_cases.py +++ b/tests/followup_cases.py @@ -302,10 +302,10 @@ CASES = [ C([INTRO], "thank you", "closing", "thanks for the answer: you're welcome"), C([INTRO], "got it, thanks", "closing", "understood and thanks: you're welcome, silence ends"), C([INTRO], "okay, bye", "end", "a real closing"), - C([INTRO], "thanks, that's all", "end", "a real closing"), - C([INTRO], "that's it, thank you", "end", "a real closing"), + C([INTRO], "thanks, that's all", "closing", "a closing here: the LLM ends it with the talk before"), + C([INTRO], "that's it, thank you", "closing", "a closing here: the LLM ends it"), C([INTRO], "see you", "end", "a real closing"), - C([INTRO], "thank you for your time", "end", "a real closing"), + C([INTRO], "thank you for your time", "closing", "a closing here: the LLM ends it"), C([INTRO], "okay, and how tall are you?", "llm", "goes on with a new question"), C([INTRO], "I see, who works there?", "llm|search", "goes on with a new question"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "아 그렇구나", "llm", "이해"), @@ -320,7 +320,7 @@ CASES = [ C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "네", "closing", "들었음: 기다림, 침묵이면 끝"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "감사합니다", "closing", "답에 대한 감사: 천만에요"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "네 감사합니다", "closing", "답에 대한 감사"), - C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "됐어요 고마워요", "end", "진짜 끝"), + C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "됐어요 고마워요", "closing", "여기선 끝: LLM이 앞 대화로 판단"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "안녕히 계세요", "end", "진짜 끝"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "알겠어요 근데 몇 살이에요?", "llm", "새 질문"), C([INTRO], "아 I see", "llm", "mixed: understood"), diff --git a/tests/followup_cases_more.py b/tests/followup_cases_more.py index d1a76d7..3a0811a 100644 --- a/tests/followup_cases_more.py +++ b/tests/followup_cases_more.py @@ -349,4 +349,41 @@ CASES_MORE = [ C([WX_KO, KO_AGE], "그럼 내일은?", "llm", "사이에 다른 주제: 날씨 아님"), C([TOKYO], "and Kyoto?", "weather", "the weather in Kyoto", r"Kyoto"), C([TOKYO], "what about tomorrow there?", "search|weather", "tomorrow's weather in Tokyo", r"tomorrow|Tokyo"), + # ---------- lookups that must go online, places kept, names of a Korean answer (2026-10-22) ---------- + C([], "Who is the CEO of OpenAI?", "search", "who holds the office now: looked up", r"OpenAI"), + C([], "who's the president of France?", "search", "who holds the office now", r"France"), + C([], "오픈AI CEO가 누구야?", "search", "지금 누가 맡고 있는지: 찾아봄", r"오픈AI"), + C([], "엔비디아 대표가 누구야?", "search", "지금 누가 맡고 있는지", r"엔비디아"), + C([], "Who is the CEO of Cutshion?", "llm", "Cutshion's CEO is in the notes: never online"), + C([], "쿳션 대표가 누구야?", "llm", "쿳션 대표는 노트에 있음"), + C([], "너희 회사 대표가 누구야?", "llm", "쿳션 대표: 노트"), + C([], "리플 지금 얼마야?", "search", "리플(XRP) 시세", r"리플"), + C([], "비트코인 가격 알려줘", "search", "비트코인 시세", r"비트코인"), + C([], "How much is bitcoin right now?", "search", "the bitcoin price", r"bitcoin"), + C([], "what is bitcoin?", "llm", "general knowledge, not a price"), + C([], "What's the population of Busan?", "search", "a number that changes", r"Busan"), + C([T("What is the capital of Canada?", "The capital of Canada is Ottawa.")], "How many people live there?", "search", + "'there' = Ottawa, from the talk answer", r"Ottawa"), + C([T("캐나다 수도가 어디야?", "캐나다의 수도는 오타와예요.")], "거기 인구는?", "search|llm", "거기 = 오타와"), + C([L("오픈AI CEO가 누구야?", "오픈AI의 CEO는 샘 올트먼이에요.")], "몇 살이야?", "search", "샘 올트먼 몇 살", r"샘 올트먼"), + C([L("한국 대통령이 누구야?", "한국 대통령은 이재명이에요.")], "몇 살이야?", "search", "이재명 몇 살", r"이재명"), + C([L("Who is the CEO of OpenAI?", "Sam Altman is the CEO of OpenAI.")], "How old is he?", "search", "Sam Altman's age", + r"Sam Altman"), + C([W("제주 날씨 알려줘", "제주는 지금 맑고 15도예요.")], "내일 비 와?", "weather", "제주 내일 비", r"Jeju"), + C([W("What's the weather in Jeju?", "Jeju is sunny, 15 degrees.")], "Will it rain tomorrow?", "weather", + "tomorrow's rain in Jeju", r"Jeju"), + C([W("What's the weather in Jeju?", "Jeju is sunny, 15 degrees.")], "and the weather here?", "weather", + "here: the place of Lumi, not Jeju", r"^$"), + C([W("부산 날씨 어때?", "부산은 맑고 18도예요.")], "우산 챙겨야 돼?", "weather", "부산에 비 오는지", r"Busan"), + C([L("What time does Lotte World open?", "Lotte World opens at 10 in the morning.")], "How much is a ticket?", "search", + "a ticket for Lotte World, not this event", r"Lotte"), + C([L("경복궁 몇 시에 열어?", "경복궁은 오전 9시에 열어요.")], "입장료는 얼마야?", "search", "경복궁 입장료", r"경복궁"), + C([L("What time does Lotte World open?", "Lotte World opens at 10 in the morning.")], "Where is the restroom here?", + "refused|llm", "this building's restroom: not online"), + C([L("Who is the CEO of OpenAI?", "Sam Altman is the CEO of OpenAI.")], "And who is your CEO?", "llm|refused", + "Cutshion's CEO: from the notes, never online"), + C([L("What time does Lotte World open?", "Lotte World opens at 10 in the morning.")], "Where are the toilets?", + "refused|llm", "the toilets of this building"), + C([T("그럼 뭐 좋아해?", "저는 노래 부르는 걸 좋아해요.")], "오 노래?", "llm", "되묻는 말: 노래 시작 아님"), + C([T("What do you like?", "I like singing.")], "Oh, a song?", "llm", "an echo, not a request"), ] diff --git a/tests/test_chain.py b/tests/test_chain.py new file mode 100644 index 0000000..f2cf64c --- /dev/null +++ b/tests/test_chain.py @@ -0,0 +1,67 @@ +"""Self-check of several commands in one sentence (assistant/chain.py, lumi.chain_run), no robot, no LLM: +python tests/test_chain.py""" +import re +import threading +import types + +from assistant import chain, lumi +from tasks import fetch + +M = ["home", "p1", "p5", "p9", "stage", "booth_2"] +CANT = lumi.NOT_A_STEP + +# ---------- the plan: kinds in the order said; None = not a chain (one command, a mission, talk) ---------- +WANT = { + "look at me and wave": ["quick look", "quick wave"], + "Lumi, look at me and wave please": ["quick look", "quick wave"], + "wave and look at me": ["quick wave", "quick look"], + "웨이브 하고 나 봐": ["quick wave", "quick look"], + "나 보고 손 흔들어": ["quick look", "quick wave"], + "고개 들고 몇 시야?": ["quick look", "talk"], + "go to p5 and tell me the weather": ["steps", "talk"], + "스테이지 가서 날씨 알려 줘": ["steps", "talk"], + "put it down and wave": ["steps", "quick wave"], + "go to the stage and dance": ["steps", "talk"], + "come here and wave": ["quick come", "quick wave"], + "go to the stage and follow me": ["steps", "quick follow"], + "take the cup and put it back": None, # all steps: a mission, read back first + "go to p5 and wave, then come back": ["steps", "quick wave", "quick come_back"], + "follow me and go to the stage": None, # following never ends: only as the last part + "come here, I need help": None, + "what's the weather in Seoul and Busan?": None, + "could you turn around and look?": None, # the head looks behind + "look at me": None, +} +bad = [] +for t, w in WANT.items(): + got = chain.plan(t, M, CANT) + short = got and [f"{k} {x[0]}" if k == "quick" else k for k, _, x in got] + if short != w: + bad.append(t) + print(f"FAIL {t!r}: {got}") +assert not bad +print("chain plan ok") + +# ---------- the run: each part in turn; a failed mission part skips what drives or needs the hand, not the rest ---- +done, said = [], [] +fake = types.SimpleNamespace( + chain_stop=threading.Event(), markers=M, modes=types.SimpleNamespace(patrol=True, drive=True), + quick_command=lambda w: done.append(("quick", w)), answer=lambda w, part=False: done.append(("talk", w)), + fetch_say=lambda en, ko: said.append(en), chain_wait=lambda: None, base_off=lambda *a, **k: False, + stay=lambda: None) +fetch.check_hand = lambda: False +runs = [] +fetch.run_steps = lambda s, say=None, sender=None: runs.append(s) +fetch.state = lambda: {"status": "failed" if runs and runs[-1][0].get("to") == "p5" else "done"} +lumi.log = lambda *a: None +lumi.Lumi.chain_run(fake, chain.plan("go to p5 and wave, then come back", M, CANT)) +assert runs == [[{"do": "go", "to": "p5"}]] and done == [("quick", "wave")], (runs, done) +assert said == ["So I didn't do this part: come back."], said # never dropped silently +done.clear(), runs.clear() +lumi.Lumi.chain_run(fake, chain.plan("go to the stage and tell me the weather", M, CANT)) +assert runs == [[{"do": "go", "to": "stage"}]] and done == [("talk", "tell me the weather")], (runs, done) +done.clear(), runs.clear() +fake.chain_stop.set() # "stop" or new words: nothing more is done +lumi.Lumi.chain_run(fake, chain.plan("look at me and wave", M, CANT)) +assert not done +print("chain run ok") diff --git a/tests/test_fetch_intents.py b/tests/test_fetch_intents.py index 90b90e7..a865512 100644 --- a/tests/test_fetch_intents.py +++ b/tests/test_fetch_intents.py @@ -149,14 +149,17 @@ for text in ("what can you do", "what is your name", "뭐 해줄 수 있어?", " from assistant.lumi import talk_fate as _fate for t in ("see you next time", "bye", "okay, bye", "good night", "I have to go", "nice talking to you", "take care", - "thank you for your time", "thanks, that's all", "that's it, thank you", "Okay, thank you. Bye.", - "다음에 봬요", "들어가세요", "수고하세요", "안녕히 계세요", "이만 갈게요", "됐어요 고마워요", "네 감사합니다 안녕히 계세요", - "go on", "good job", "well done", "가 보세요", "잘했어요", "수고했어요", "okay thanks bye bye", "고마워요, 다음에 봐요"): + "Okay, thank you. Bye.", "다음에 봬요", "들어가세요", "수고하세요", "안녕히 계세요", "이만 갈게요", "네 감사합니다 안녕히 계세요", + "가 보세요", "you can go now", "okay thanks bye bye", "고마워요, 다음에 봐요", "I gotta run, thanks!"): assert _fate(t) == "end", (t, _fate(t)) +# goodbye in one talk, "understood, go on" in another: the LLM decides with the turns before (owner, 2026-10-22) for t in ("okay", "Okay.", "thanks", "thank you", "Thank you.", "thanks a lot", "got it, thanks", "alright", "good", "okay, good", "고마워요", "감사합니다", "네 감사합니다", "알았어, 고마워", "오케이", "그래요", "네", "네.", "좋아", "땡큐", - "오케이 땡큐", "okay 감사합니다", "Thanks, Lumi."): - assert _fate(t) == "wait", (t, _fate(t)) + "오케이 땡큐", "okay 감사합니다", "Thanks, Lumi.", "thank you for your time", "thanks, that's all", + "that's it, thank you", "됐어요 고마워요", "오케이 됐어", "Okay, I think that's everything."): + assert _fate(t) == "close", (t, _fate(t)) +for t in ("good job", "well done", "잘했어요", "수고했어요", "Maybe later, thanks."): # the LLM reads them too + assert _fate(t) != "end", (t, _fate(t)) for t in ("I see", "I see.", "got it", "I got you", "okay I see", "okay, I understand", "makes sense", "That makes sense.", "understood", "아 그렇구나", "그렇구나", "그렇군요", "알겠어요", "네 알겠습니다", "아하", "아, 그랬구나", "Uh huh.", "oh 그렇구나", "아 I see", "Okay, 알겠어요", "아 네", diff --git a/tests/test_followup.py b/tests/test_followup.py index 20ba968..7248633 100644 --- a/tests/test_followup.py +++ b/tests/test_followup.py @@ -40,16 +40,20 @@ def route(b, text, frames): place = lumi.consent_place(text, b, MARKS) if place: return f"act:go_to {place}", "" + if lumi.talk_fate(text) == "close": + return "closing", "" # the LLM reads it with the talk before r = rules_route(text, lang, MARKS) if r: name = {"chat": "closing", "action:end": "end"}.get(r[0], r[0].replace("action:", "act:")) if name in ("weather", "search"): rule = brain.intent(text, MARKS) - return name, (rule[1] if name == "weather" else b.search_query(rule[1])) + return name, (b.weather_place(rule[1], text) if name == "weather" else b.search_query(rule[1])) return name, r[1] if b.is_lookup_follow_up(text): return "search", b.search_query(text) h = b._after({"action": "none", "target": ""}, text) + if h["action"] == "search" and lumi.lookup_refused(b, h["target"], b.topic(text), text): + return "refused", "" # lumi.answer: Cutshion / this place, not online if h["action"] == "search": return "search", b.search_query(h["target"]) if h["action"] != "none": @@ -76,6 +80,7 @@ def replay(b, ctx, frames): b.last_lookup = said elif kind == "weather": asked = said + getattr(brain, "WEATHER_ASKED", " (the weather)") # lumi.look_up / brain.respond_from + b.weather_place((brain.intent(said, MARKS) or ("", ""))[1], said) b.history.append((asked, reply)) b.last_lookup = asked else: diff --git a/tests/test_mission_route.py b/tests/test_mission_route.py index 84e5850..328e241 100644 --- a/tests/test_mission_route.py +++ b/tests/test_mission_route.py @@ -6,7 +6,7 @@ drives is refused with one line, one that stays in place runs). Fake robot; the python tests/test_mission_route.py""" import types -from assistant import brain, lumi, steps +from assistant import brain, chain, lumi, steps from tasks import fetch from tests import steps_cases7 as c7 @@ -35,7 +35,8 @@ for text, want in list(c7.CASES.items()) + list(c7.FIXED.items()): if want == "?": asked = read is not None and read[1] refused = read is not None and not read[1] and steps.check(read[0], False, M) - if not (asked or refused or read is None and (rule is None or rule[0] == "fetch")): + chained = chain.plan(t, M, lumi.NOT_A_STEP) # "look at me and wave": every part in turn (test_chain) + if not (asked or refused or chained or read is None and (rule is None or rule[0] == "fetch")): bad.append((text, read, rule)) elif not (read and not read[1] or read is None and rule and rule[0] == "fetch"): bad.append((text, read, rule)) diff --git a/tests/test_web.py b/tests/test_web.py index 326c204..18ca43b 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -104,7 +104,40 @@ outs = iter([["search NY weather\n", "It is 15 degrees. Clear."]]) assert list(brain.Brain().respond_from("Weather?", "x")) == ["It is 15 degrees.", "Clear."] outs = iter([["Search results say 330 m."]]) assert list(brain.Brain().respond_from("Eiffel?", "x")) == ["Search results say 330 m."] -brain._stream = real_stream +# respond_stream: "search ..." under "ACTION: none" or without "ACTION:" is the lookup, never said; its words are not +# the query +outs = iter([["ACTION: none -\n", "search Lotte World", " ticket price"]]) +brain._stream = lambda m: iter(next(outs)) +real_search, brain.knowledge.search = brain.knowledge.search, lambda *a, **k: [] # no embedding server asked +assert next(brain.Brain().respond_stream("How much is a ticket for Lotte World?", ["p1"])) == \ + {"action": "search", "target": "How much is a ticket for Lotte World?"} +outs = iter([["search I'll look", " that up.\n"]]) +assert next(brain.Brain().respond_stream("Who is the CEO of Nvidia now?", ["p1"]))["target"] == "Who is the CEO of Nvidia now?" +outs = iter([["ACTION: none -\n", "Hi!"]]) +assert list(brain.Brain().respond_stream("Hello Lumi", ["p1"])) == [{"action": "none", "target": ""}, "Hi!"] +outs = iter([["ACTION: none -\n", "I'm Lumi, nice to meet you."]]) +assert list(brain.Brain().respond_stream("Who are you?", ["p1"]))[1:] == ["I'm Lumi, nice to meet you."] +brain._stream, brain.knowledge.search = real_stream, real_search + +# the names of a Korean answer go with a follow-up; "there" after a talk answer goes with its place +b = brain.Brain() +b.search_query("오픈AI CEO가 누구야?") +b.history, b.last_lookup = [("오픈AI CEO가 누구야?", "오픈AI의 CEO는 샘 올트먼이에요.")], "오픈AI CEO가 누구야?" +assert b.search_query("몇 살이야?") == "오픈AI CEO가 누구야? 샘 올트먼 몇 살이야" +b = brain.Brain() +b.history = [("What is the capital of Canada?", "ACTION: none -\nThe capital of Canada is Ottawa.")] +assert b.search_query("How many people live there?") == "What is the capital of Canada? Ottawa How many people live there" +b = brain.Brain() +b.search_query("What time does Lotte World open?") +b.history, b.last_lookup = [("What time does Lotte World open?", "At 10.")], "What time does Lotte World open?" +assert b.search_query("How much is a ticket?") == "What time does Lotte World open? How much is a ticket" +assert b.search_query("Who won the 2025 World Series?") == "Who won the 2025 World Series?" +# a weather question without a place: the place of the weather before in this talk; "here" is here +b = brain.Brain() +assert b.weather_place("Jeju", "제주 날씨 알려줘") == "Jeju" and b.weather_place("", "내일 비 와?") == "Jeju" +assert b.weather_place("", "what about the weather here?") == "" and b.weather_place("", "and tomorrow?") == "" +b.weather_place("Busan"); b.reset() +assert b.weather_place("", "내일 비 와?") == "" # ages worked out from birth dates in the results; money questions get rates, others do not assert web.with_ages("Han Kang (born 27 November 1970)", datetime.date(2026, 10, 20)) == \ @@ -154,6 +187,9 @@ def fake_say_stream(pieces, lang=None, abort=None): class FakeBrain: + weather_place = brain.Brain.weather_place + weather_at = "" + def respond_from(self, asked, facts): events.append(("llm", asked, time.time())) yield "It is 330 metres tall, with the antennas on top." diff --git a/tests/web_cases2.py b/tests/web_cases2.py index 2417b74..d654932 100644 --- a/tests/web_cases2.py +++ b/tests/web_cases2.py @@ -268,4 +268,17 @@ DIALOGUES = [ ("en", "And how old is Elon Musk?", r"5[45]|fifty")], [("en", "How old is Faker?", r"(29|30)|thirty|twenty"), ("en", "What team does he play for?", r"T1")], + # 2026-10-22: who holds an office, coin prices, "there" after a talk answer, the weather's place kept, a venue word + [("en", "Who is the CEO of Nvidia?", r"Huang"), + ("en", "How old is he?", r"6[23]|sixty")], + [("ko", "엔비디아 CEO가 누구야?", r"젠슨|황"), + ("ko", "몇 살이야?", r"6[23]|예순")], + [("ko", "리플 지금 얼마야?", r"원|달러|\d")], + [("en", "How much is Ethereum right now?", r"dollar|won|\d")], + [("en", "What is the capital of Australia?", r"Canberra"), + ("en", "How many people live there?", r"\d|thousand")], + [("en", "What's the weather in Busan?", r"degree"), + ("en", "Will it rain tomorrow?", r"Busan|rain|percent|chance|dry")], + [("en", "What time does the Louvre open?", r"9|nine"), + ("en", "How much is a ticket?", r"\d|euro")], ] diff --git a/tests/web_check.py b/tests/web_check.py index 69d831d..beebab1 100644 --- a/tests/web_check.py +++ b/tests/web_check.py @@ -95,7 +95,7 @@ def turn(b, lang, text): gen = b.respond_stream(text, MARKS, now=NOW) head = next(gen) a = head["action"] - if a == "search" and lumi.not_online(about): + if a == "search" and lumi.lookup_refused(b, head["target"], about, text): gen.close() out.update(route="refused", answer=lumi.not_known("ko" if lang == "ko" else "en"), total_s=time.time() - t0) return out @@ -118,6 +118,8 @@ def turn(b, lang, text): return out out["target"] = target tf = time.time() + if action == "weather": # as lumi.look_up: the place of the weather before + target = out["target"] = b.weather_place(target, text) facts = web.weather(target) if action == "weather" else web.search(target) out["fetch_s"], out["facts"] = time.time() - tf, facts or "NO INTERNET" words = []