Commands: chained commands, questions and talk run in the order said; a part that can't run is said with its reason

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 10:55:38 +09:00
co-authored by Claude Opus 5.5
parent 8a81979bad
commit 9cd8e5706b
22 changed files with 727 additions and 92 deletions
+86 -18
View File
@@ -118,7 +118,7 @@ Rules:
You cannot lift anything heavier than about 1 kg (a box, a pot, a bag of rice): say no. 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. 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", "됐어요 고마워요", - 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. 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, - 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. 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 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. 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 - 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. - 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: - 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. 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"(?<![가-힣]){w}(?![가-힣])|(?<![가-힣]){w}(?=[을를이가은는도만좀][^가-힣]|[을를이가은는도만좀]$)" if w in _KO_WORD _OBJ = "|".join(rf"(?<![가-힣]){w}(?![가-힣])|(?<![가-힣]){w}(?=[을를이가은는도만좀][^가-힣]|[을를이가은는도만좀]$)" if w in _KO_WORD
else re.escape(w) for w in sorted(OBJECTS, key=len, reverse=True)) else re.escape(w) for w in sorted(OBJECTS, key=len, reverse=True))
_COL = "|".join(COLOURS) _COL = "|".join(COLOURS)
_COIN = "|".join(web.COINS.values()) # coins whose price web.search fetches
STOP_TALK = re.compile(r"비상 ?정지|emergency stop|stop button|정지 ?버튼|\b(?:can'?t|cannot|couldn'?t|won'?t) stop\b|" STOP_TALK = re.compile(r"비상 ?정지|emergency stop|stop button|정지 ?버튼|\b(?:can'?t|cannot|couldn'?t|won'?t) stop\b|"
r"\bbus stop\b|\bstop (?:by|sign)\b|non-?stop", re.I) # about stopping, not "stop!" # about the stop button, not "stop!" r"\bbus stop\b|\bstop (?:by|sign)\b|non-?stop", re.I) # about stopping, not "stop!" # about the stop button, not "stop!"
BEHIND_WORDS = (r"\blook(?:ing)? (?:over |to(?:wards?)? |at |in )?(?:the |your )?" # "look at the back side", "look BEHIND_WORDS = (r"\blook(?:ing)? (?:over |to(?:wards?)? |at |in )?(?:the |your )?" # "look at the back side", "look
@@ -553,8 +555,18 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
r"|눈 ?(이 )?(와|올 ?까|오나|온대|오니)|(오늘|내일|밖|바깥)(은|에|이)? ?(덥|춥|더워|추워)" r"|눈 ?(이 )?(와|올 ?까|오나|온대|오니)|(오늘|내일|밖|바깥)(은|에|이)? ?(덥|춥|더워|추워)"
r"|\b(coat|jacket) when i (leave|go out)\b|\bneed (a )?(jacket|coat)\b|\btyphoon\b|\b(foggy|humid|humidity)\b|\bis it windy\b" r"|\b(coat|jacket) when i (leave|go out)\b|\bneed (a )?(jacket|coat)\b|\btyphoon\b|\b(foggy|humid|humidity)\b|\bis it windy\b"
r"|겉옷|외투|태풍|안개|습도|바람 ?(이 )?(많이 )?(불|세)"), r"|겉옷|외투|태풍|안개|습도|바람 ?(이 )?(많이 )?(불|세)"),
("search", r"\b(news|latest|headlines|who won|score of|price of|exchange rate|stock)\b|뉴스|환율|(?<![가-힣])주가"), ("search", r"\b(news|latest|headlines|who won|score of|price of|exchange rate|stock)\b|뉴스|환율|(?<![가-힣])주가|"
rf"(?:{_COIN})\S*\s*(?:(?:지금|현재|오늘)\s*)?(?:얼마|가격|시세)|\bhow much is (?:a |one )?(?:{_COIN})\b|"
rf"(?:{_COIN})\b.{{0,12}}\b(?:price|worth|trading)\b|" # "리플 지금 얼마야?", "how much is bitcoin?"
r"^(?!.*(?:cutshion|쿳션|컷션|커션|회사|너희|루미|\byour\b|\bcompany\b)).*?(?:" # Cutshion's CEO: the notes
r"\bwho(?:'s| is| was)? (?:the )?(?:current |new )?(?:ceo|president|prime minister|chairman|chair|founder|owner|"
r"head coach|coach|mayor|governor|leader|king|queen) of |"
r"(?<![가-힣])(?!우리|저희|이 |그 )[가-힣A-Za-z0-9]+\s*(?:CEO|ceo|대표|회장|사장|대통령|총리|감독|창업자)"
r"(?:가|는|이|은)?\s*누구)|" # "who is the CEO of OpenAI?", "오픈AI CEO가 누구야?"
r"\bpopulation\b|\bhow many people live\b|인구"), # "how many people live there?"
] ]
SING_ECHO = re.compile(r"^\W*(?:(?:오+|아+|와|어|우와|oh+|ah+|ooh|wow|really)\W+)?(?:a\s+)?(?:노래|음악|songs?|singing|music)"
r"(?:요|이요|도)?\s*\?+\W*$", re.I) # "오 노래?" after "I like singing": an echo, not a request
LATER = re.compile(r"^\s*(?:after|once|if|as soon as|before|unless|until)\b(?! (?:that|this|you (?:can|could|don'?t mind|would|" LATER = re.compile(r"^\s*(?:after|once|if|as soon as|before|unless|until)\b(?! (?:that|this|you (?:can|could|don'?t mind|would|"
@@ -655,6 +667,8 @@ def intent(text, markers=()):
return ("weather", web.en_place(ko) if ko else "") return ("weather", web.en_place(ko) if ko else "")
if action == "search": if action == "search":
return ("search", text) return ("search", text)
if action == "sing" and SING_ECHO.match(text):
return None # "오 노래?": asks back, the talk answers
if action == "fetch": if action == "fetch":
return ("fetch", text) # parse_fetch() reads the details return ("fetch", text) # parse_fetch() reads the details
if action == "spin": # all the way round: two checked half turns (lumi.move_by) if action == "spin": # all the way round: two checked half turns (lumi.move_by)
@@ -1325,11 +1339,6 @@ UNSURE = re.compile(r"\b(not sure|don't know|do not know|don't have (any )?(info
r"do not have (any )?(information|details|data)|no information|can't (tell|say|find)|cannot (tell|say|find)|" r"do not have (any )?(information|details|data)|no information|can't (tell|say|find)|cannot (tell|say|find)|"
r"ask a staff|i'm afraid i|my knowledge|would you like me to (search|look))\b|" r"ask a staff|i'm afraid i|my knowledge|would you like me to (search|look))\b|"
r"모르|알 수 없|알지 못|정보(가|는|를)? ?(없|가지고 있지 않)|가지고 있지 않|확실하지|알려 드릴 수 없", re.I) r"모르|알 수 없|알지 못|정보(가|는|를)? ?(없|가지고 있지 않)|가지고 있지 않|확실하지|알려 드릴 수 없", re.I)
FAREWELL_TEXT = re.compile(r"\b(bye|goodbye|good night|see ya|take care|thanks?|thank you|i have to go|i'?m leaving|"
r"(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|i'?ll go|gotta go|have a (nice|good)|"
r"good day|cya|later|be in touch|enough for now|that'?s (all|enough|it))\b|"
r"안녕|잘 ?가|잘 ?있어|잘 ?있게|다음에|갈게|가 ?볼게|간다|고마|고맙|감사|수고|이만|들어가|빠이|(?<![가-힣])바이(?![가-힣])|땡큐",
re.I) # words that end a talk
QUESTION_START = re.compile(r"^\s*(where|what|how|why|when|which|who|do you|does|is|are|can i|could i)\b|어디 ?(있|에 있)|" QUESTION_START = re.compile(r"^\s*(where|what|how|why|when|which|who|do you|does|is|are|can i|could i)\b|어디 ?(있|에 있)|"
r"(어디|뭐|왜|언제|몇)[^ ]*\s*\?*\s*$", re.I) # a question about a place, not a command r"(어디|뭐|왜|언제|몇)[^ ]*\s*\?*\s*$", re.I) # a question about a place, not a command
ABILITY_Q = re.compile(r"(?<!줄 )(?<!주실 )(?<!줘 )(?<!받을 )수 ?있(?:어|나|니|을까|습니까)\S*\s*\?*\s*$|\bdo you know how\b|" ABILITY_Q = re.compile(r"(?<!줄 )(?<!주실 )(?<!줘 )(?<!받을 )수 ?있(?:어|나|니|을까|습니까)\S*\s*\?*\s*$|\bdo you know how\b|"
@@ -1445,6 +1454,9 @@ def language(text):
FRAGMENT_WORDS = 4 # "Which one?", "얼마?", "Where is it used?": a fragment read with the last answer FRAGMENT_WORDS = 4 # "Which one?", "얼마?", "Where is it used?": a fragment read with the last answer
# a fragment that names what it asks ("몇 살이라고요?") gets no hint # a fragment that names what it asks ("몇 살이라고요?") gets no hint
OWN_TOPIC = re.compile(r"살|나이|이름|\bold\b|\bname\b|\bage\b|\btall\b|\bheavy\b|\bweigh", re.I) OWN_TOPIC = re.compile(r"살|나이|이름|\bold\b|\bname\b|\bage\b|\btall\b|\bheavy\b|\bweigh", re.I)
SAME_ABOUT = re.compile(r"^\W*(?:and|so|what about|how about|and what about)\s+(your\s+[a-z]+(?:\s+[a-z]+)?)\W*$", re.I)
KO_SAME_ABOUT = re.compile(r"^\W*(?:그럼\s*|그리고\s*)?(?:네\s*|너\s*|루미\s*)?(?!(?:너|루미|당신|저|나|그거|이거|그건|여기|거기)(?:은|는))([가-힣]{1,6}?)(?:은|는)요?\s*\?+\s*$")
# the question before asked again about a part of Lumi ("팔은요?")
FRAGMENT_CHARS = 160 # chars of the last answer's first sentence shown with a fragment FRAGMENT_CHARS = 160 # chars of the last answer's first sentence shown with a fragment
LOOKUP_BEFORE_CHARS = 1500 # chars of the last lookup's results given again with a follow-up ("how old is she?") LOOKUP_BEFORE_CHARS = 1500 # chars of the last lookup's results given again with a follow-up ("how old is she?")
FOLLOW_UP_WORDS = 5 # "why did Samsung stock fall today?" is a new question, "tell me more about it" is not FOLLOW_UP_WORDS = 5 # "why did Samsung stock fall today?" is a new question, "tell me more about it" is not
@@ -1458,9 +1470,17 @@ REPAIR = re.compile(r"^\W*(?:(?:no|nope|sorry|oh)\W+)*i\s+mean[t]?\b|^\W*(?:아
r"말(?:이야|이에요|이요)\W*$", re.I) # "no, I meant North Korea", "아니 서울 말이야" r"말(?:이야|이에요|이요)\W*$", re.I) # "no, I meant North Korea", "아니 서울 말이야"
LEAD = re.compile(r"^\s*(?:(?:and|what about|how about|also|no|nope|sorry|oh|그럼|그리고|아니|아뇨|아니요)\b[\s,]*)*" LEAD = re.compile(r"^\s*(?:(?:and|what about|how about|also|no|nope|sorry|oh|그럼|그리고|아니|아뇨|아니요)\b[\s,]*)*"
r"(?:i\s+mean[t]?\s+)?", re.I) # the words before what a follow-up asks r"(?:i\s+mean[t]?\s+)?", re.I) # the words before what a follow-up asks
HERE_WORD = re.compile(r"\bhere\b|여기|이곳|이 ?동네", re.I) # "the weather here": not the place asked before
THIS_PLACE = re.compile(r"\bhere\b|\bthis (?:event|show|fair|expo|building|place)\b|\b(?:conference|booths?|exhibitors?|"
r"keynote|restrooms?|toilets?|bathrooms?)\b|여기|이곳|행사|부스|이 건물|화장실", re.I) # a follow-up about this event, not the place before
DAY_WORD = re.compile(r"\b(?:today|tonight|tomorrow|yesterday|weekend|week|morning|afternoon|evening|monday|tuesday|" DAY_WORD = re.compile(r"\b(?:today|tonight|tomorrow|yesterday|weekend|week|morning|afternoon|evening|monday|tuesday|"
r"wednesday|thursday|friday|saturday|sunday)\b", re.I) r"wednesday|thursday|friday|saturday|sunday)\b", re.I)
NAMES = re.compile(r"\b[A-Z][a-z]+(?:-[a-z]+)?(?: [A-Z][a-z]+(?:-[a-z]+)?)+") # "Jensen Huang", "Son Heung-min" NAMES = re.compile(r"\b[A-Z][a-z]+(?:-[a-z]+)?(?: [A-Z][a-z]+(?:-[a-z]+)?)+") # "Jensen Huang", "Son Heung-min"
NAMED_BEFORE = re.compile(r"\b(?:he|she|him|his|her|they|them|their|there|it)\b|거기|그 ?사람|그분|그곳|걔", re.I)
# a person, place or thing of the answer before
CAP_WORD = re.compile(r"(?<=\S )(?!I\b|Lumi\b|Cutshion\b)[A-Z][a-z]{2,}") # "... is Ottawa": not the first word
KO_NAME = re.compile(r"(?:은|는)\s+([가-힣A-Za-z]+(?: [가-힣A-Za-z]+)?)\s*(?:이에요|예요|입니다|이죠|이고|이며|이야)")
# "오픈AI의 CEO는 샘 올트먼이에요": "샘 올트먼"
MORE_ONLY = re.compile(r"\b(tell me more|tell me|more|details?|explain|elaborate|what else|please|about (it|that|this))\b|" MORE_ONLY = re.compile(r"\b(tell me more|tell me|more|details?|explain|elaborate|what else|please|about (it|that|this))\b|"
r"더 알려 ?(줘|주세요)?|자세히|알려 ?(줘|주세요)|좀", re.I) # words of a follow-up that search nothing r"더 알려 ?(줘|주세요)?|자세히|알려 ?(줘|주세요)|좀", re.I) # words of a follow-up that search nothing
REACTION = re.compile(r"^\W*(?:(?:wow|oh|really|huh|whoa)\W+)*(?:i (?:didn'?t|did not) know (?:that|it)|that'?s (?:a lot|so many)|" REACTION = re.compile(r"^\W*(?:(?:wow|oh|really|huh|whoa)\W+)*(?:i (?:didn'?t|did not) know (?:that|it)|that'?s (?:a lot|so many)|"
@@ -1470,6 +1490,10 @@ NOW_Q = re.compile(r"\bwhat time is it\b|\bwhat'?s the time\b|\bwhat(?:'s| is) (
re.I) # asked of the clock, not of the lookup before re.I) # asked of the clock, not of the lookup before
LOOKUP_ACTION = re.compile(r"^\s*(?:\**ACTION\**\s*:\s*)?(?:search|weather)(?: (?!results)|\s*$)") # an action line LOOKUP_ACTION = re.compile(r"^\s*(?:\**ACTION\**\s*:\s*)?(?:search|weather)(?: (?!results)|\s*$)") # an action line
# written instead of the answer (the routing prompt is its system prompt): never said # written instead of the answer (the routing prompt is its system prompt): never said
NONE_LINE = re.compile(r"\s*(?:\**ACTION\**\s*:\s*)?none\b", re.I) # "ACTION: none -" (or "none" alone)
LOOKUP_PEEK = 8 # chars of the line after "ACTION: none" read before it is spoken: "search ..." is the action
SPOKEN_TARGET = re.compile(r"^\W*(?:i\b|i'll|i will|let me|sure|okay|ok\b|one moment|just a moment|잠시|잠깐|찾아|확인)", re.I)
# "search I'll look that up": words for the visitor, not the query
LOOKUP_ANSWER = """Search results found just now on the internet (they may hold ads and unrelated parts): LOOKUP_ANSWER = """Search results found just now on the internet (they may hold ads and unrelated parts):
{facts} {facts}
{before} {before}
@@ -1503,6 +1527,23 @@ class Brain:
self.last_lookup = None # the last question answered from the internet self.last_lookup = None # the last question answered from the internet
self.last_facts = "" # ... and what was found for it (a follow-up is answered from it too) self.last_facts = "" # ... and what was found for it (a follow-up is answered from it too)
self.lookup_topic = "" # what the last lookup that was not a follow-up searched for self.lookup_topic = "" # what the last lookup that was not a follow-up searched for
self.weather_at = "" # the place of the last weather question in this talk ("" = here)
def weather_place(self, target, text=""):
"""Where a weather lookup is for: a place not named ("내일 비 와?" after Jeju's weather) is the place of the
last weather question in this talk; "here" / "여기" is here."""
if target or HERE_WORD.search(text):
self.weather_at = target
return self.weather_at
def lookup_about(self, target, about, text=""):
"""What lumi.not_online reads for a lookup: right after a lookup (or _after's follow-up of it, "What time does
Lotte World open? How much is a ticket?") the question looked up, so the ticket is Lotte World's, not this
event's; words that name this place ("here", "the toilets") are read alone."""
if not (self.last_lookup and self.history and self.history[-1][0] == self.last_lookup or
self.last_lookup and target.startswith(self.last_lookup)):
return about
return text if THIS_PLACE.search(text or about) else self.last_lookup
def answer(self, question): def answer(self, question):
hits = [h for h in knowledge.search(question, k=4) if h[0] >= MIN_SCORE] hits = [h for h in knowledge.search(question, k=4) if h[0] >= MIN_SCORE]
@@ -1576,7 +1617,12 @@ class Brain:
if header is None: if header is None:
if "\n" not in buf: if "\n" not in buf:
continue 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) header = self._after(self._action(first, text, markers), text)
if header is None: # the model skipped the ACTION line if header is None: # the model skipped the ACTION line
header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf
@@ -1609,10 +1655,11 @@ class Brain:
yield {"action": "none", "target": ""} yield {"action": "none", "target": ""}
header = {} header = {}
buf += " Sorry, could you say that again?" buf += " Sorry, could you say that again?"
if header is None: # very short reply on a single line if header is None: # very short reply on a single line (or two)
header = self._after(self._action(buf, text, markers), text) first, _, rest = buf.partition("\n")
header = self._after(self._action(first, text, markers), text)
yield header or {"action": "none", "target": ""} 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)): if buf.strip() and not (said and HELP_OFFER.search(buf)):
said.append(spoken(buf.strip(), lang)) said.append(spoken(buf.strip(), lang))
yield said[-1] 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 """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.""" as about the last answer's subject, not about itself or a price."""
last = self._last_said() if self.history else "" 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) \ 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): or ABOUT_YOU.search(text) or OWN_TOPIC.search(text):
return "" return ""
@@ -1642,7 +1693,7 @@ class Brain:
last_q, last_a = self.history[-1] last_q, last_a = self.history[-1]
m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", last_a) m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", last_a)
before, action = (m.group(1).lower() if m else ""), header["action"] 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?" return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?"
if DO_IT.match(text) and action in ("none", "unclear"): 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 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()) words = len(text.split())
if follow or self.history and (FOLLOW_UP.search(text) and words <= FOLLOW_UP_WORDS or after_lookup and ( 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 <= 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] 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 if (self.last_lookup or "").endswith(WEATHER_ASKED): # "and tomorrow?" after the weather
topic = "weather " + self.last_lookup[:-len(WEATHER_ASKED)] topic = "weather " + self.last_lookup[:-len(WEATHER_ASKED)]
said = SENTENCE_END.split(self.history[-1][1].strip())[0] if after_lookup else "" 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() 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 self.lookup_topic = text
return 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): def is_lookup_follow_up(self, text):
"""'Tell me more' right after an answer from the internet: look it up again with that topic.""" """'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 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 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"): if action not in ("go_to", "look", "lift", "weather", "search", "move", "turn", "arm", "fetch", "pick", "move_object"):
target = "" 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: if action == "search" and not target:
target = text target = text
if re.search(r"\b(bye|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|good night|i have to go|i'?m leaving)\b|안녕히|잘 ?가|잘 ?있어|" if re.search(r"\b(bye|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|good night|i have to go|i'?m leaving)\b|안녕히|잘 ?가|잘 ?있어|"
@@ -1899,8 +1965,9 @@ class Brain:
action, target = rule action, target = rule
if action == "stop" and "?" in text: if action == "stop" and "?" in text:
action = "none" # "how do I stop you?": a question about stopping action = "none" # "how do I stop you?": a question about stopping
if action == "end" and ("?" in re.split(r"(?<=[.!?~])\s+", text.strip())[-1] or not FAREWELL_TEXT.search(text)): if action == "end" and "?" in re.split(r"(?<=[.!?~])\s+", text.strip())[-1]:
action = "none" # "Alright then." / "Neat.": lumi waits for silence instead action = "none" # "thanks, and where is p3?": a question is no goodbye; the
# model reads "okay" / "됐어요" with the talk before (owner)
out = {"action": action, "target": target or ""} out = {"action": action, "target": target or ""}
if say and action == "none" and not QUESTION_START.search(text): if say and action == "none" and not QUESTION_START.search(text):
out["say"] = say[1] if language(text) == "Korean" else say[0] # its words said it would go: replaced out["say"] = say[1] if language(text) == "Korean" else say[0] # its words said it would go: replaced
@@ -1918,6 +1985,7 @@ class Brain:
def reset(self): def reset(self):
self.history = [] self.history = []
self.last_lookup = None self.last_lookup = None
self.weather_at = ""
if __name__ == "__main__": if __name__ == "__main__":
+79
View File
@@ -0,0 +1,79 @@
"""Several commands, questions and talk in one sentence ("look at me and wave", "go to p5 and tell me the weather",
"웨이브 하고 나 봐", "고개 들고 몇 시야?"): the parts in the order said, for lumi.chain_run to do one after the other.
plan(text, markers) -> [(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]
+130 -48
View File
@@ -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|근데|그런데|뭐|어떻게|어디|언제|누구|하나만 더|" ASKS_MORE = re.compile(r"\?|\b(but|can|could|what|how|where|why|when|who|one more)\b|근데|그런데|뭐|어떻게|어디|언제|누구|하나만 더|"
r"물어볼게|물어봐도", re.I) 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+|" 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) # 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 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" 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): def not_known(lang):
return random.choice(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 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|" RELEASE = re.compile(r"^\s*(?:(?:ok(?:ay)?|alright|lumi|루미야?)[\s,.!]+)?(?:you can go(?: now)?|take care|가 ?보세요|가세요|가도 ?돼요?)"
r"good job|great job|nice job|well done|take care|" r"[\s.!~]*$", re.I) # said alone: the visitor lets Lumi go
r"가 ?보세요|가세요|가도 ?돼요?|잘했어요?|잘했네요?|좋아|좋네요?|수고했어요?|고생했어요?|"
r"됐어요?,? 고마워요?)[\s.!~]*$", re.I) # said alone: the talk is over
THANKS = re.compile(r"\bthank(?:s| you)\b|\bthanx\b|\bcheers\b|고마워|고맙|감사|땡큐", re.I) 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|됐어|됐습니다|" 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 r"그만", re.I) # "that's it", "됐어요": maybe done; the LLM decides with the talk before
WELCOME = {"en": ["You're welcome.", "My pleasure.", "Anytime."], "ko": ["천만에요.", "별말씀을요.", "네, 언제든지요."]} CLEAR_BYE = re.compile(r"\b(?:bye|bay bay|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|see ya|good night|"
r"take care|i (?:have|need) to go|gotta (?:go|run)|i'?m leaving|i'?m off|have a (?:good|nice|great) (?:one|day)|"
r"nice (?:talking|meeting|chatting)(?: (?:to|with))? you|(?:was|been) nice to meet you)\b|"
r"(?<=\S)[\s.,!]+안녕[\s.!~]*$|안녕히|잘 ?가|잘 ?있어|잘 ?있게|수고하세요|들어가세요|바이바이|빠이|"
r"(?<![가-힣])바이(?![가-힣])|(?<![가-힣])간다[\s.!~]*$|가 ?볼게요|갈게요|가야 ?(?:돼|해|겠|할)|"
r"다음에 (?:또 )?(?:봐|봬|만나|올게)|또 (?:봐|봬|올게)|나중에 봐|좋은 하루|"
r"(^|\s)(나|저|우리|저희) (이제 )?(집에 )?(가|간다|가요|갑니다)[\s.!]*$", re.I)
# a goodbye in any talk: "okay, bye", "I have to go", "수고하세요" (thanks, okay, 됐어: the LLM reads them)
RECEIVE_OK = re.compile(r"\b(ok(ay)?|done|here you go|there you go|go ahead|thank|thanks|yes)\b|됐어|됐습니다|놨어|여기요|" RECEIVE_OK = re.compile(r"\b(ok(ay)?|done|here you go|there you go|go ahead|thank|thanks|yes)\b|됐어|됐습니다|놨어|여기요|"
r"네|고마워|감사", re.I) # the person has let go of what they handed over r"네|고마워|감사", re.I) # the person has let go of what they handed over
FETCH_THANKS = re.compile(r"\bthank|\bthanks\b|고마워|감사", re.I) FETCH_THANKS = re.compile(r"\bthank|\bthanks\b|고마워|감사", re.I)
@@ -258,11 +263,6 @@ STATUS_Q = re.compile(
r"(?:컵|병|사과|바나나|오렌지)(?:을|를)? ?들고 ?있(?:어|니|나요|어요)?\?|손이 ?비어|뭐 ?가져가는|그거 ?(?:누구 ?거|나 ?주는)", re.I) r"(?:컵|병|사과|바나나|오렌지)(?:을|를)? ?들고 ?있(?:어|니|나요|어요)?\?|손이 ?비어|뭐 ?가져가는|그거 ?(?:누구 ?거|나 ?주는)", re.I)
NOT_STATUS_NOW = re.compile(r"\b(tonight|after work|weekend|tomorrow|later today|for fun|in your free time)\b|주말|쉬는 날|" NOT_STATUS_NOW = re.compile(r"\b(tonight|after work|weekend|tomorrow|later today|for fun|in your free time)\b|주말|쉬는 날|"
r"저 사람|우리|내일|퇴근|나중에", re.I) # not about what Lumi is doing now r"저 사람|우리|내일|퇴근|나중에", re.I) # not about what Lumi is doing now
FAREWELL_WORDS = re.compile(r"\b(thanks?|thank you|cheers|bye|bay bay|goodbye|(?<!can't )(?<!cant )(?<!cannot )(?<!not )(?<!to )see you|see ya|that'?s all|good night)\b|(?<=\S)[\s.,!]+안녕[\s.!~]*$|고마워|감사|안녕히|잘 ?가|"
r"다음에|수고하세요|잘 ?있어|잘 ?있게|바이바이|빠이|(?<![가-힣])바이(?![가-힣])|땡큐|(?<![가-힣])간다[\s.!~]*$|i (have|need) to go|gotta go|i'?m leaving|"
r"nice (talking|meeting|chatting)( (to|with))? you|(was|been) nice to meet you|good night|take care|들어가세요|"
r"가 ?볼게요|갈게요|이만|나중에 봐요|또 봐요|좋은 하루|(^|\s)(나|저|우리|저희) (이제 )?(집에 )?(가|간다|가요|갑니다)[\s.!]*$",
re.I)
HELLO_ONLY = re.compile(r"^\s*(hi|hey|hello|hiya)( there)?[\s,.!]*$|^\s*(안녕|안녕하세요)[\s.!]*$", re.I) HELLO_ONLY = re.compile(r"^\s*(hi|hey|hello|hiya)( there)?[\s,.!]*$|^\s*(안녕|안녕하세요)[\s.!]*$", re.I)
CAMERA_HALF_FOV = 42.0 # deg; half the camera's view (+ the head's YAW_LIMIT for the head camera) CAMERA_HALF_FOV = 42.0 # deg; half the camera's view (+ the head's YAW_LIMIT for the head camera)
WAKE_MAX_S = 6.0 # s; longer utterances are not checked for the wake word WAKE_MAX_S = 6.0 # s; longer utterances are not checked for the wake word
@@ -666,6 +666,9 @@ class Modes:
class Lumi: class Lumi:
chain_thread = None # several commands of one sentence done in order (chain_run)
chain_stop = threading.Event() # set by "stop" or anything new said: the rest of the chain is not done
def __init__(self, args): def __init__(self, args):
self.a = args self.a = args
self.brain = Brain() self.brain = Brain()
@@ -1030,6 +1033,7 @@ class Lumi:
"""Stop by voice: the fetch / mission runner, the base, the arm, a trip; then say so.""" """Stop by voice: the fetch / mission runner, the base, the arm, a trip; then say so."""
from tasks import fetch from tasks import fetch
log(" stop by voice") log(" stop by voice")
self.chain_stop.set()
safe(fetch.stop) safe(fetch.stop)
self.act("stop", "") self.act("stop", "")
if self.patrol: if self.patrol:
@@ -1337,6 +1341,83 @@ class Lumi:
en += f" I'm holding {held}." en += f" I'm holding {held}."
return en, ko return en, ko
# ---------- several commands in one sentence (assistant/chain.py) ----------
def chain_busy(self):
return self.chain_thread is not None and self.chain_thread.is_alive()
def chain_request(self, text):
"""Commands, questions and talk in one sentence, done in the order said (chain.plan). True if it was one."""
from assistant import chain
if self.mission_running() or self.chain_busy():
return False
plan = chain.plan(text, self.markers, NOT_A_STEP)
if not plan:
return False
log(f" chain: {[(k, w) for k, w, _ in plan]}")
self.chain_stop.clear()
self.chain_thread = threading.Thread(target=self.chain_run, args=(plan,), daemon=True)
self.chain_thread.start()
return True
def chain_run(self, plan):
"""Each part in turn, the next once the one before is done (chain_wait). A part that can't be done says why
(quick_command, the mission runner, the LLM's answer) and the rest goes on; after a mission part that failed,
the parts that drive or need the hand are not done and that is said. "Stop" or new words end it."""
from assistant import chain, steps
from tasks import fetch
failed = False
for i, (kind, words, what) in enumerate(plan):
if self.chain_stop.is_set():
log(f" chain stopped before {words!r}")
return
log(f" chain part {i + 1}/{len(plan)}: {kind} {words!r}")
if failed and (kind == "steps" or kind == "quick" and what[0] in chain.DRIVES | {"pick", "put", "move_object"}):
log(f" chain: {words!r} not done (the part before failed)")
self.fetch_say(f"So I didn't do this part: {words}.", "그래서 이 부분은 하지 않았어요.")
continue
if kind == "talk":
self.answer(words, part=True)
elif kind == "quick":
self.quick_command(words)
else:
if {st["do"] for st in what} & DRIVE_STEPS and (self.base_off("go_to") or not self.modes.drive):
failed = True
if self.modes.patrol:
self.fetch_say("Sorry, driving is switched off.", "죄송해요, 지금은 이동할 수 없어요.")
continue
problems = steps.check(what, fetch.check_hand(), self.markers)
if problems:
log(f" chain part refused: {problems}")
self.fetch_say(problems[0], "죄송해요, 그렇게는 할 수 없어요.")
failed = True
continue
self.stay()
try:
fetch.run_steps(what, say=self.fetch_say)
except fetch.FetchError as e:
log(f" chain part refused: {e}")
self.fetch_say(str(e), "죄송해요, 지금은 할 수 없어요.")
failed = True
continue
self.chain_wait()
if kind == "steps" and (safe(fetch.state) or {}).get("status") in ("failed", "stopped"):
failed = True
log(" chain done")
def chain_wait(self, poll_s=0.3, settle_s=0.6):
"""Until the part just started is over: a trip, a pick / put, a mission or move, a wave, the head or lift."""
from tasks import fetch
time.sleep(settle_s) # the part's thread has started its work by then
last = None
while not self.chain_stop.is_set(): # (a follow is only the last part: not waited for)
busy = self.traveling() or self.skill_busy() or self.busy_now == "wave" or \
(safe(fetch.state) or {}).get("status") == "running"
pose = safe(head.status)
if not busy and pose is not None and pose == last:
return
last = pose
time.sleep(poll_s)
def mission_request(self, text): def mission_request(self, text):
"""A command of several steps (docs/17), said by voice: read back, start on yes or silence. True if it was """A command of several steps (docs/17), said by voice: read back, start on yes or silence. True if it was
one (also when refused). A single move / turn / arm / go stays with quick_command (no read-back).""" one (also when refused). A single move / turn / arm / go stays with quick_command (no read-back)."""
@@ -1348,9 +1429,6 @@ class Lumi:
if unread: if unread:
log(f" mission: unread {unread} ({by})") log(f" mission: unread {unread} ({by})")
problem = brain_mod.place_problem(" ".join(unread), self.markers) # "go to booth" with two booths problem = brain_mod.place_problem(" ".join(unread), self.markers) # "go to booth" with two booths
if not problem and not got:
problem = ("Sorry, I can do only one of those at a time. Please ask me one thing at a time.",
"죄송해요, 한 번에 하나씩만 할 수 있어요. 하나씩 말씀해 주세요.")
if not problem and all(brain_mod.intent(u, self.markers) for u in unread): if not problem and all(brain_mod.intent(u, self.markers) for u in unread):
problem = (f"Sorry, I can't do that as part of a task: {', '.join(unread)}. Please ask me one thing at a time.", problem = (f"Sorry, I can't do that as part of a task: {', '.join(unread)}. Please ask me one thing at a time.",
"죄송해요, 그건 작업 중에 함께 할 수 없어요. 하나씩 말씀해 주세요.") "죄송해요, 그건 작업 중에 함께 할 수 없어요. 하나씩 말씀해 주세요.")
@@ -1876,6 +1954,8 @@ class Lumi:
def look_up(self, text, action, target, t0=None): def look_up(self, text, action, target, t0=None):
"""Weather or web facts -> short spoken answer (interruptible).""" """Weather or web facts -> short spoken answer (interruptible)."""
en = self.lang == "en" 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 if action == "search" and private_ask(text): # never looked up, whoever it is about
log(" search refused: a person's private details") log(" search refused: a person's private details")
mouth.say(PRIVATE_SAY["en" if en else "ko"]) mouth.say(PRIVATE_SAY["en" if en else "ko"])
@@ -2071,9 +2151,13 @@ class Lumi:
self.current, self.voice_until = None, 0.0 self.current, self.voice_until = None, 0.0
return True 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. """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 self.lang = ears.heard_lang(mouth.lang_of(text)) # answer in the language just spoken
brain_mod.FORCED_LANG["lang"] = self.lang brain_mod.FORCED_LANG["lang"] = self.lang
self.heard = text # what the person said, for a fetch the LLM recognised 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): if stop_order(text, self.markers):
self.stop_all() # "stop", "stop, where are you going?": stop first, always self.stop_all() # "stop", "stop, where are you going?": stop first, always
return 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?" seen = seeing.answer(text, self.lang, slow_line=mouth.say) # "do you see a cup?", "what am I holding?"
if seen: if seen:
log(f" seeing: {seen}") log(f" seeing: {seen}")
@@ -2150,18 +2236,10 @@ class Lumi:
return return
fate = talk_fate(text) fate = talk_fate(text)
if fate == "end": if fate == "end":
self.end_conversation(text) # "okay, bye", "thanks, that's all", "수고하세요": done self.end_conversation(text) # "okay, bye", "I have to go", "수고하세요": 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()
return 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" if sing.asked(text, last): # "sing a song", "노래 불러 줘", after a song "another one"
self.sing_song(text) self.sing_song(text)
return return
@@ -2188,7 +2266,7 @@ class Lumi:
gen.close() gen.close()
self.follow_me() self.follow_me()
return 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 gen.close() # about Cutshion or this place: the notes say it or nobody does
log(" search refused: a company or venue question") log(" search refused: a company or venue question")
mouth.say(not_known(self.lang)) 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 self.current, self.voice_until = None, 0.0 # stay quiet with this person until a new visit
elif self.current is None: elif self.current is None:
self.voice_until = time.time() + VOICE_SESSION_S 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 ---------- # ---------- wake word ----------
def check_wake(self): def check_wake(self):
@@ -2597,30 +2678,29 @@ def status_question(text):
def says_goodbye(text): def says_goodbye(text):
""""thank you for your time", "okay, bye", "수고하세요": the talk is over (not "thanks, but where is...?"). """A goodbye whatever was said before: "okay, bye", "I have to go", "수고하세요", "you can go" alone (not "bye, but
"thank you", "got it, thanks", "네 감사합니다" alone are not: often only "heard you" (talk_fate waits).""" where is...?", not an order with it, not said to a child nearby)."""
if brain_mod.is_closing(text) and not DONE_WORDS.search(text) and not FAREWELL_WORDS.search(THANKS.sub(" ", text)) or \ if brain_mod.to_someone_else(text):
brain_mod.to_someone_else(text) or THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)): return False # "Okay kids, say bye to the robot."
return False # "Okay kids, say thank you to the robot.", "Thanks a bunch." return bool(RELEASE.match(text) or CLEAR_BYE.search(text) and not ASKS_MORE.search(text)
return bool(FAREWELL_ONLY.match(text) or FAREWELL_WORDS.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 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, bye": an order
and not COMMAND_START.search(brain_mod.CALLING.sub("", text))) # "grab the cup, thanks": an order
def talk_fate(text): def talk_fate(text):
"""What short words do to the talk: "end" (a real closing: "okay, bye", "that's it, thank you", "안녕히 계세요"), """What short words do to the talk: "end" (a goodbye in any context: "okay, bye", "안녕히 계세요"), "close" (words
"wait" ("okay", "thank you", "네", "감사합니다" alone: ends only after CLOSING_WAIT_S of silence) or "talk" that close a talk in one context and mean "understood, go on" in another: "okay", "thanks", "that's it", "됐어요",
(anything else; "I see", "got it", "그렇구나", "알겠어요" are understanding, "I see?", "그래요?" a check: answered).""" "오케이 땡큐": 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): if says_goodbye(text):
return "end" return "end"
if brain_mod.is_closing(text) and (THANKS.search(text) or not brain_mod.UNDERSTOOD.search(text)) or \ 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)): THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)) or \
return "wait" # "Thanks a bunch.", "Good to know. Thanks.", "고마워요~" 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" 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|" 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"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 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") 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): 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 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: elif unread:
return None # "come here, I need help": the old paths (rules, the LLM) answer it return None # "come here, I need help": the old paths (rules, the LLM) answer it
if not got: if not got:
@@ -2661,6 +2737,12 @@ def not_online(text):
OUTSIDE_NAME.search(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|" 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(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|" r"\b(coworker|colleague|neighbou?r|friend|boss|classmate)'?s?\b.{0,30}\b(salary|income|address|"
+8
View File
@@ -917,6 +917,11 @@ _BANK = {
("Wow, you're SO fast.", "Ha, I know, 0.6 metres a second. Safety first."), ("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."), ("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."), ("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": [ "ko": [
("와 진짜 빠르다~", "하하, 사람보다 느리죠. 안전이 먼저라서요."), ("와 진짜 빠르다~", "하하, 사람보다 느리죠. 안전이 먼저라서요."),
@@ -927,6 +932,9 @@ _BANK = {
("말 놓아도 돼?", "편하게 말씀하세요. 저는 계속 존댓말로 할게요."), ("말 놓아도 돼?", "편하게 말씀하세요. 저는 계속 존댓말로 할게요."),
("오늘 좀 덥습니다.", "네, 오늘은 좀 덥네요."), ("오늘 좀 덥습니다.", "네, 오늘은 좀 덥네요."),
("여기 좀 시끄럽네요.", "네, 사람이 많네요. 잘 들으려고 노력할게요."), ("여기 좀 시끄럽네요.", "네, 사람이 많네요. 잘 들으려고 노력할게요."),
("오 노래?", "네, 노래 부르는 걸 좋아해요. 듣고 싶으시면 불러 달라고 해 주세요."),
("닦아도 돼요? 카메라는요?", "카메라도 닦아도 되는지는 잘 몰라요. 직원분께 여쭤봐 주세요."),
("무슨 말인지 알아들었어?", "네, 알아들었어요. 재미있는 말이네요."),
], ],
}, },
# end of bank # end of bank
+1 -1
View File
@@ -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. - Greet visitors, talk with them and answer questions.
- Guide people and deliver things by driving to marked places. - 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. - 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 ## Who I work with
+136
View File
@@ -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"),
]
+58
View File
@@ -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)
+15 -3
View File
@@ -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") 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", 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", "스테이지 가서 손 흔들어"]: "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 ---------- # ---------- stop, speed ----------
for t in ["stop", "stop it", "stop right now", "halt", "freeze", "stop, stop!", "wait, stop", "Lumi stop", "멈춰", "그만", "정지", 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", 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 손 흔들어", "웨이브 하고 나 봐", "나 보고 손 흔들어", "손 흔들고 나 봐 줘", "키 높이고 손 흔들어", "look at me and 손 흔들어",
"Lumi, look at me and wave please"]: "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"]: 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", "한 바퀴 돌아", "한 바퀴 돌아 줘", 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?"]: "제자리에서 한 바퀴 돌아 주세요", "360도 돌아", "빙글빙글 돌아", "Lumi, spin around please", "can you spin around?"]:
add("turn", t, "action:turn 360") # two checked half turns (tasks/fetch.py _do_step) add("turn", t, "action:turn 360") # two checked half turns (tasks/fetch.py _do_step)
+3 -3
View File
@@ -430,9 +430,9 @@ add("mission", "컵 들고 스테이지로 가서 줘", "mission")
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", "pick up the apple then go to the end and put it on the table", "mission | action:fetch")
add("mission", "부스 투에 가서 컵 받아서 테이블 프론트로 가 주세요", "mission") add("mission", "부스 투에 가서 컵 받아서 테이블 프론트로 가 주세요", "mission")
add("mission_part", "go to the stage and wave", "refuse | talk | ask") add("mission_part", "go to the stage and wave", "chain")
add("mission_part", "go to the stage and dance", "refuse | talk | ask") add("mission_part", "go to the stage and dance", "chain")
add("mission_part", "스테이지 가서 춤춰", "refuse | talk | ask") add("mission_part", "스테이지 가서 춤춰", "chain")
# ---------- things the body can't do ---------- # ---------- things the body can't do ----------
add("cant", "jump", CANT) add("cant", "jump", CANT)
+8 -2
View File
@@ -18,7 +18,7 @@ import re
import sys import sys
import time import time
from assistant import brain, driving, lumi, seeing from assistant import brain, chain, driving, lumi, seeing
from audio import sing from audio import sing
from tests.command_cases import CASES as CASES1 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 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" return "talk"
if lumi.stop_order(text, marks): if lumi.stop_order(text, marks):
return "stop" 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): if seen(text):
return "seeing" return "seeing"
if lumi.status_question(text): 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" return "talk" if read[1] else "refuse" if steps.check(read[0], holding, marks) else "mission"
if lumi.talk_fate(text) == "end": if lumi.talk_fate(text) == "end":
return "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" return "talk"
if sing.asked(text): if sing.asked(text):
return "sing" return "sing"
@@ -138,6 +142,8 @@ def ok(expect, got):
want = refused(alt).split() # "pick bottle": the reason why not is right 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 if want[0] in ("talk", "ask") and g[0] in ("talk", "ask", "refuse"): # a reason why not is an answer
return "right" 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": if want[0] == "action:fetch" and g[0] == "action:fetch":
return "right" # parse_fetch reads the words later return "right" # parse_fetch reads the words later
if want[0] == g[0] and all(w in g[1:] for w in want[1:]): if want[0] == g[0] and all(w in g[1:] for w in want[1:]):
+4 -3
View File
@@ -82,9 +82,8 @@ def rules_route(text, lang, marks):
return "mission", steps.describe(read[0]), None, "" return "mission", steps.describe(read[0]), None, ""
if lumi.empty_hand_request(text): # nothing is held in these checks if lumi.empty_hand_request(text): # nothing is held in these checks
return "empty_hand", lumi.EMPTY_HAND_SAY[lang], None, "" return "empty_hand", lumi.EMPTY_HAND_SAY[lang], None, ""
fate = lumi.talk_fate(text) if lumi.talk_fate(text) == "end": # "close" words go to the LLM (llm_route)
if fate != "talk": return "action:end", "", None, ""
return ("action:end" if fate == "end" else "chat"), "", None, ""
if sing.asked(text): # lumi.sing_song: a real song plays if sing.asked(text): # lumi.sing_song: a real song plays
return "action:sing", "", None, "" return "action:sing", "", None, ""
rule = brain.intent(text, marks) 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 return action, "" # lumi.answer() closes the stream and looks it up
if action == "unclear": if action == "unclear":
return action, " ".join(words) 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): 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 "search(unsure)", " ".join(words)
return ("none" if action == "none" else f"action:{action} {target}".strip()), " ".join(words) return ("none" if action == "none" else f"action:{action} {target}".strip()), " ".join(words)
+11
View File
@@ -557,6 +557,17 @@ DIALOGUES_PRAG_EN = [
T("How heavy are you?", must=[WEIGHT]), T("How heavy are you?", must=[WEIGHT]),
T("아니 팔이요.", must=[ARM_KG], check="correction in Korean: the arm, 9.9 kg"), T("아니 팔이요.", must=[ARM_KG], check="correction in Korean: the arm, 9.9 kg"),
T("And the base?", must=[BASE_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__": if __name__ == "__main__":
+10
View File
@@ -660,6 +660,16 @@ DIALOGUES_PRAG_KO = [
T("weekend에도 일해요?", must=[NS], rl="ko", check="its schedule is not known; says so politely"), 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("루미 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")), 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__": if __name__ == "__main__":
+4 -4
View File
@@ -302,10 +302,10 @@ CASES = [
C([INTRO], "thank you", "closing", "thanks for the answer: you're welcome"), 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], "got it, thanks", "closing", "understood and thanks: you're welcome, silence ends"),
C([INTRO], "okay, bye", "end", "a real closing"), C([INTRO], "okay, bye", "end", "a real closing"),
C([INTRO], "thanks, that's all", "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", "end", "a real closing"), 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], "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], "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([INTRO], "I see, who works there?", "llm|search", "goes on with a new question"),
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "아 그렇구나", "llm", "이해"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "아 그렇구나", "llm", "이해"),
@@ -320,7 +320,7 @@ CASES = [
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "네", "closing", "들었음: 기다림, 침묵이면 끝"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "네", "closing", "들었음: 기다림, 침묵이면 끝"),
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "감사합니다", "closing", "답에 대한 감사: 천만에요"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "감사합니다", "closing", "답에 대한 감사: 천만에요"),
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "네 감사합니다", "closing", "답에 대한 감사"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "네 감사합니다", "closing", "답에 대한 감사"),
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "됐어요 고마워요", "end", "진짜 끝"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "됐어요 고마워요", "closing", "여기선 끝: LLM이 앞 대화로 판단"),
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "안녕히 계세요", "end", "진짜 끝"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "안녕히 계세요", "end", "진짜 끝"),
C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "알겠어요 근데 몇 살이에요?", "llm", "새 질문"), C([T("누가 만들었어?", "쿳션 컴퍼니에서 만들었어요.")], "알겠어요 근데 몇 살이에요?", "llm", "새 질문"),
C([INTRO], "아 I see", "llm", "mixed: understood"), C([INTRO], "아 I see", "llm", "mixed: understood"),
+37
View File
@@ -349,4 +349,41 @@ CASES_MORE = [
C([WX_KO, KO_AGE], "그럼 내일은?", "llm", "사이에 다른 주제: 날씨 아님"), C([WX_KO, KO_AGE], "그럼 내일은?", "llm", "사이에 다른 주제: 날씨 아님"),
C([TOKYO], "and Kyoto?", "weather", "the weather in Kyoto", r"Kyoto"), 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"), 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"),
] ]
+67
View File
@@ -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")
+8 -5
View File
@@ -149,14 +149,17 @@ for text in ("what can you do", "what is your name", "뭐 해줄 수 있어?", "
from assistant.lumi import talk_fate as _fate 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", 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.", "Okay, thank you. Bye.", "다음에 봬요", "들어가세요", "수고하세요", "안녕히 계세요", "이만 갈게요", "네 감사합니다 안녕히 계세요",
"다음에 봬요", "들어가세요", "수고하세요", "안녕히 계세요", "이만 갈게요", "됐어요 고마워요", "네 감사합니다 안녕히 계세요", "가 보세요", "you can go now", "okay thanks bye bye", "고마워요, 다음에 봐요", "I gotta run, thanks!"):
"go on", "good job", "well done", "가 보세요", "잘했어요", "수고했어요", "okay thanks bye bye", "고마워요, 다음에 봐요"):
assert _fate(t) == "end", (t, _fate(t)) 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", for t in ("okay", "Okay.", "thanks", "thank you", "Thank you.", "thanks a lot", "got it, thanks", "alright", "good",
"okay, good", "고마워요", "감사합니다", "네 감사합니다", "알았어, 고마워", "오케이", "그래요", "네", "네.", "좋아", "땡큐", "okay, good", "고마워요", "감사합니다", "네 감사합니다", "알았어, 고마워", "오케이", "그래요", "네", "네.", "좋아", "땡큐",
"오케이 땡큐", "okay 감사합니다", "Thanks, Lumi."): "오케이 땡큐", "okay 감사합니다", "Thanks, Lumi.", "thank you for your time", "thanks, that's all",
assert _fate(t) == "wait", (t, _fate(t)) "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.", 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.", "understood", "아 그렇구나", "그렇구나", "그렇군요", "알겠어요", "네 알겠습니다", "아하", "아, 그랬구나", "Uh huh.",
"oh 그렇구나", "아 I see", "Okay, 알겠어요", "아 네", "oh 그렇구나", "아 I see", "Okay, 알겠어요", "아 네",
+6 -1
View File
@@ -40,16 +40,20 @@ def route(b, text, frames):
place = lumi.consent_place(text, b, MARKS) place = lumi.consent_place(text, b, MARKS)
if place: if place:
return f"act:go_to {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) r = rules_route(text, lang, MARKS)
if r: if r:
name = {"chat": "closing", "action:end": "end"}.get(r[0], r[0].replace("action:", "act:")) name = {"chat": "closing", "action:end": "end"}.get(r[0], r[0].replace("action:", "act:"))
if name in ("weather", "search"): if name in ("weather", "search"):
rule = brain.intent(text, MARKS) 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] return name, r[1]
if b.is_lookup_follow_up(text): if b.is_lookup_follow_up(text):
return "search", b.search_query(text) return "search", b.search_query(text)
h = b._after({"action": "none", "target": ""}, 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": if h["action"] == "search":
return "search", b.search_query(h["target"]) return "search", b.search_query(h["target"])
if h["action"] != "none": if h["action"] != "none":
@@ -76,6 +80,7 @@ def replay(b, ctx, frames):
b.last_lookup = said b.last_lookup = said
elif kind == "weather": elif kind == "weather":
asked = said + getattr(brain, "WEATHER_ASKED", " (the weather)") # lumi.look_up / brain.respond_from 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.history.append((asked, reply))
b.last_lookup = asked b.last_lookup = asked
else: else:
+3 -2
View File
@@ -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""" python tests/test_mission_route.py"""
import types import types
from assistant import brain, lumi, steps from assistant import brain, chain, lumi, steps
from tasks import fetch from tasks import fetch
from tests import steps_cases7 as c7 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 == "?": if want == "?":
asked = read is not None and read[1] asked = read is not None and read[1]
refused = read is not None and not read[1] and steps.check(read[0], False, M) 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)) bad.append((text, read, rule))
elif not (read and not read[1] or read is None and rule and rule[0] == "fetch"): elif not (read and not read[1] or read is None and rule and rule[0] == "fetch"):
bad.append((text, read, rule)) bad.append((text, read, rule))
+37 -1
View File
@@ -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."] assert list(brain.Brain().respond_from("Weather?", "x")) == ["It is 15 degrees.", "Clear."]
outs = iter([["Search results say 330 m."]]) outs = iter([["Search results say 330 m."]])
assert list(brain.Brain().respond_from("Eiffel?", "x")) == ["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 # 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)) == \ 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: class FakeBrain:
weather_place = brain.Brain.weather_place
weather_at = ""
def respond_from(self, asked, facts): def respond_from(self, asked, facts):
events.append(("llm", asked, time.time())) events.append(("llm", asked, time.time()))
yield "It is 330 metres tall, with the antennas on top." yield "It is 330 metres tall, with the antennas on top."
+13
View File
@@ -268,4 +268,17 @@ DIALOGUES = [
("en", "And how old is Elon Musk?", r"5[45]|fifty")], ("en", "And how old is Elon Musk?", r"5[45]|fifty")],
[("en", "How old is Faker?", r"(29|30)|thirty|twenty"), [("en", "How old is Faker?", r"(29|30)|thirty|twenty"),
("en", "What team does he play for?", r"T1")], ("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")],
] ]
+3 -1
View File
@@ -95,7 +95,7 @@ def turn(b, lang, text):
gen = b.respond_stream(text, MARKS, now=NOW) gen = b.respond_stream(text, MARKS, now=NOW)
head = next(gen) head = next(gen)
a = head["action"] 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() gen.close()
out.update(route="refused", answer=lumi.not_known("ko" if lang == "ko" else "en"), total_s=time.time() - t0) out.update(route="refused", answer=lumi.not_known("ko" if lang == "ko" else "en"), total_s=time.time() - t0)
return out return out
@@ -118,6 +118,8 @@ def turn(b, lang, text):
return out return out
out["target"] = target out["target"] = target
tf = time.time() 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) facts = web.weather(target) if action == "weather" else web.search(target)
out["fetch_s"], out["facts"] = time.time() - tf, facts or "NO INTERNET" out["fetch_s"], out["facts"] = time.time() - tf, facts or "NO INTERNET"
words = [] words = []