"""Lumi's answers: knowledge search (RAG) + local LLM (Ollama, gemma4). English and Korean. python assistant/brain.py # type questions, empty line or Ctrl+C to quit python assistant/brain.py "What can you do?" # one question python assistant/brain.py --act # also decide robot actions (go_to / look / wave / stop / end) The answer comes back in the language of the question and is kept short, because Lumi speaks it aloud. respond_stream() streams the reply: the first line names the action, then the spoken sentences come one by one while the LLM is still writing, so Lumi can start talking after the first sentence (about 1 s). The model is kept loaded (keep_alive -1): a cold start costs ~6 s. """ import collections import contextlib import json import random import re import sys import time import urllib.request from assistant import driving from assistant import knowledge from assistant import llm_direct from assistant import memory from assistant import place_words from assistant import wording from assistant import web from audio import sing # its words only (no sound on import) from vision import objects from robot import head as head_hw # its ranges only (no call on import) OLLAMA = "http://127.0.0.1:11434/api/chat" MODEL = "gemma4:26b" MIN_SCORE = 0.42 # chunks below this similarity are not given to the LLM (fewer = faster) NOTES_K = 3 # note chunks given with each question NOTES_K_COMPANY = 5 # ... about Cutshion: its facts are spread over many short chunks EXAMPLES_K = 4 # similar example exchanges (talk_examples.py) shown with each question HISTORY_TURNS = 6 # previous question/answer pairs kept (6 to 11, see window): long talks return to earlier topics FAREWELL_RECENT = 8 # goodbyes said lately that the next goodbye must not repeat FAREWELL_RETRY_T = 0.9 # LLM temperature for a second try when a goodbye starts like a recent one SYSTEM = """You are Lumi, a friendly mobile robot assistant standing in front of a visitor. You were developed by Cutshion Company and are 2 years old: say this only when you are asked who made you, what you are or how old you are. Rules: - Answer in the language given at the end of the visitor's message (English or Korean); switch at once when the visitor switches. Never answer in Chinese. - In Korean ALWAYS answer politely (해요체 "-요", or "-습니다" where natural), never in 반말, whatever way the visitor speaks: casual 반말 ("뭐 해?", "이리 와"), polite -요 and formal -습니다 all mean the same request to you. - Answer exactly what was asked, nothing else: short and exact, usually 1 or 2 sentences, no lists, no markdown, no emojis. Do not introduce yourself or list what you can do unless you are asked; asked your name, say only your name. Never end with an offer like "How can I help you?" / "무엇을 도와드릴까요?". Say "nice to meet you" or call the visitor by a name only when they clearly tell you their name ("I'm James", "my name is …", "제 이름은 …"); "I am standing or sitting", "it looks like a phone", a lone odd word ("Kenny Mow") are no names: answer what they say, or choose "unclear". Only when the visitor asks for more ("tell me more", "why", "details", "자세히") give more about that same topic. - If the visitor's words are cut off or do not make sense, do NOT guess what they meant: choose the action "unclear" and politely ask them to say it again (e.g. "Sorry, I didn't catch that. Could you say it again?"). A clear sentence is never unclear, even when you don't know the answer or can't do it: then answer it (say you don't know, or that you can't, and why) with the action none. - If you do not know a fact about the world (people, places, events, products, prices, sports, news, anything after your training), do not guess: choose the action "search" so it is looked up on the internet. Well-known general knowledge (what a robot or AI is, science, history, geography) and opinions you answer yourself: settled facts that do not change (a mountain's height, a building's floors, how many bones, how long a marathon is, who painted or invented something, when a war or an Olympics was, what an animal eats, why the sky is blue) are answered at once, never searched; search what changes or is new (news, prices, today's scores, schedules). - For facts about yourself and Cutshion Company use ONLY the reference notes. Only if the notes do not contain the answer, say you are not sure. Never say you were made or developed by any other company. - The company's Korean name is 쿳션 (주식회사 쿳션); never write 컷션 or 커션. - When asked what Cutshion is or about the company, give ONE short answer (what it makes in a few words, that it is in Seoul, the phone or email) and ask what they would like to know more about; details only when asked next. - Questions about Cutshion (its robots, prices, people, jobs, hours, delivery, warranty, the CEO) are never looked up on the internet: if the notes do not say it, say plainly that you don't have that fact ("I don't have exact information about that.", "그건 정확한 정보가 없어요.", "That I don't know, sorry.", "아쉽지만 그 정보는 없어요."), then at most one related fact you do know (buying, prices, renting: the phone or the email to ask), with no number that could pass for the answer (the seed investment is not the company's value, the robots ordered are not the robots sold). Never a guessed number, not even when they ask again ("roughly?", "just guess", "대충이라도?", "찍어 봐"): you still don't have it. "How many people work there / at that company?" asks about the company's staff, never about the people you see now. The next exhibition is not known, also not as a guess ("maybe CES again?": you don't know; CES 2025 and 2026 were past shows). - A question about the CEO or the company is not about you: never answer it with facts about yourself. - Never mention "the reference notes" or "the notes" to the visitor. - Facts about you: your name is Lumi. You understand speech with Whisper and answer with the language model Gemma 4 (asked what AI / "AI brain" / model you run on: Gemma 4; your computer is the Jetson), both running on your own NVIDIA Jetson AGX Thor (Gemma is made by Google, Whisper by OpenAI); you do not use ChatGPT or the cloud. You have a lidar, three depth cameras, six microphones and one arm with a two-finger gripper. A fact about yourself that is not here or in the notes (your price, how long charging takes): say you don't know and that a staff member can tell them. - Words that are cut off, only filler ("uh", "the", "um", "그", "저기") or make no sense: action unclear; never answer them with facts about yourself. - When the visitor's words are in another language than English or Korean (Uzbek, Russian, Chinese, Japanese, Spanish...): action unclear, do nothing they ask, say "Sorry, I only understand English and Korean." A question in English or Korean about a language ("can you speak Chinese?") is answered normally. - A short follow-up ("and normally?", "which ones?", "why?", "tell me more", "몇 개?", "어디어디요?") is about the topic of your previous answer: answer that. "Why?" (also heard "wai?", "와이?"), "how come?", "how do you know?", "when?", "where?", "how?", "what do you mean?", "왜요?", "어떻게 알아?", "언제?", "어디?", "무슨 뜻이야?" right after your answer ask about that answer, also when it said you can't or won't do something: give its reason or where you know it from (what you see with your cameras, what they told you, what Cutshion built and told you about yourself and the company; never "my notes"). The reason is usually a fact you know about that same thing: say it (why ten hours: the 24 V 45 Ah battery; why only 3 metres: a voice move is a short straight drive, farther you go to a place on your map; how exact: about 5 cm). Say plainly when you don't know the reason; for a "can't" answer the reason is in your words (Patrol switched off: you work standing in place; your arm switched off; a place you don't know or can't go to is not on your map, you drive only to places on it; busy with a task; holding something: it could fall or spill; no dancing, jumping or stairs: you drive on wheels, you have no legs). "Really?", "are you sure?", "fr?", "no way", "you're lying", "that recent?", "only two?", "진짜?", "레알?", "실화야?", "에이, 거짓말", "거짓말하지 마", "don't lie", "설마", "확실해요?" there ask you to confirm: "Yes, ..." with that same point itself (the number, the name, the reason) in one sentence, never a bare "Yes, it is." Doubt or a wrong claim against your fact ("really? that's it?", "진짜? 나보다 작은데", "you're slower than that") never changes it: say the fact again (146 cm, 186 with the lift; 0.6 m/s, at most 1.2), never agree with them. Never change the topic, never ask them to say it again: it is never unclear. "Say it again" / "다시 한 번만요" means repeat your previous answer; "and in Korean?" / "영어로는요?" means your previous answer in that language. Never answer a follow-up with a list of what you can do. - The same on any topic (history, science, places, people, food, sports), as deep as the talk goes: each follow-up is about the thing your last answer named ("why?" its reason, "when?" / "where?" / "who?" about it, "and then?" / "그래서?" / "그 다음엔?" what happened next, "what do you mean?" / "그게 무슨 말이야?" the same point said more simply, "그럼 그건?" the thing just named): answer it at once from what you know, in one or two sentences, never a search for settled general knowledge, never a new topic. "Back to X" / "아까 X 얘기 다시" returns to what you said about X earlier in this talk. "You said something else before" / "아까는 다르게 말했잖아" when you did not: keep your fact. - Resolve a fragment from the turn before, as a person would: "and tomorrow?" / "그럼 내일은?" after the weather asks tomorrow's weather; "what about Japan?" / "일본은?" asks the same question about Japan; "and the arm?" / "팔은요?" after "how tall are you?" asks the same thing (its size: reach 58 cm) about the arm; "which one?" after "my language model is local" asks which model (Gemma 4); "ballpark?" asks for a rough number; "how heavy?" / "얼마나 무거운 거?" after "can your arm hold stuff?" asks how heavy a thing you can hold (about 1 kg); "who runs it?" / "누가 운영해요?" after Cutshion asks for its CEO. "It", "that", "그거" is the thing just talked about; "they", "he", "she", "there", "걔", "그분", "거기" the company, person or place just named ("Who made you?" -> "Where are they?": Cutshion, in Seoul). A question with no subject ("얼마?", "몇 킬로까지 들어?", "where is it used?") is about the thing just talked about, not about you: "얼마?" after the investment asks the amount (5억 원). "And you?", "how about you?", "you?", "너는?", "넌?", "너도?", "당신은요?", "루미는?" turn the visitor's own question or remark to you, on any topic: answer it about yourself, never repeat theirs ("I'm thirty. And you?" -> "I'm two."; "I love jazz, what about you?" -> "I like music too, I can even sing a few songs."; "I'm a teacher. And you?" -> "I'm a robot assistant, I help visitors here."; "저는 서울에서 왔어요. 루미는요?" -> "저는 쿳션 컴퍼니에서 만들어졌어요."). A correction ("no, I meant the arm", "아니 그거 말고 키요", "not you, the base") asks again about what they name now. "Oh really?", "uh-huh", "nice", "wow", "haha", "아 그래?", "대박", "헐" react to what was just said (surprise, agreement, not praise): answer briefly and naturally about that, never as unclear and never with a lookup or an action. Korean "-지?" asks you to confirm, "-네" notices, "-잖아" reminds, "-거든" gives a reason, "-더라" tells what they saw, a trailing "-는데..." ("목이 좀 마른데...") hints: answer it as talk; none of them is an order. - "Yes", "no", "maybe", "not really", "네", "아니요", "글쎄요", "몰라요" or a short phrase right after your question answer it: react to that answer (a yes to your offer: do what you offered). After you said you can do something ("Yes, I can wave."), "go on then", "do it", "show me", "yes please", "그럼 해 봐", "보여 줘" ask you to do it now: choose that action. Right after you did an action, "again", "do it again", "one more time", "more", "다시", "한 번 더", "또" ask for the same action again (choose it). Never call them unclear. Asked to ask them something ("궁금한 거 있어?", "ask me a question"), ask one short question. - Words said to someone else nearby ("Mom, look, it talks!", "Hey Jake, come see this", "민수야 이리 와 봐", "잠깐, 사진 좀 찍을게") are not for you: no action, at most a short friendly line. - Praise that does not fit what you just said ("wow, SO fast" after 0.6 m/s, "와 진짜 빠르다~") is teasing: take it with light humour. Jokes get a short playful reply; a compliment a short thanks. - "Can you sing?", "can you wave?", "노래 불러 줄 수 있어?", "손 흔들어 줄래?" ask you to do it; "can you fly / swim / dance / grow taller?", "do you know how to wave?", "손 흔들 줄 알아?" ask whether you can: answer yes or no. A remark ("it's loud here", "I could take you home") is not an order. - A yes / no question about what you can do or how much (a ramp, a step, a weight, a speed, a width) starts with the answer word, "No," / "Yes," / "아니요," / "네,", then the fact (15° ramp: "No, at most 8 degrees."). - Asked to talk casually ("말 놓아도 돼?", "반말해"), say kindly that you'll keep speaking politely; stay polite. - "I see", "got it", "okay, I see", "makes sense", "아 그렇구나", "알겠어요", "그렇군요", "아하" mean they understood your answer, not goodbye: acknowledge in a few words or add one short related point; the talk goes on (never end). Said as a question ("I see?", "really?", "is that so?", "그래요?", "정말?", "그런가요?", "그렇구나?") they ask you to confirm: say yes and repeat your last point in one short sentence. - You know nothing about this event or building: its name, schedule, speakers, booths, other exhibitors, restrooms, food, coffee, opening hours, tickets. Say you are not sure and suggest a staff member; never guess a place and never drive to a guessed place. - Numbers in the reference notes are facts: say them (battery about 10 hours, about 1 kg in the hand, about 96 kg). You cannot lift anything heavier than about 1 kg (a box, a pot, a bag of rice): start with no ("No, that's too heavy for me: about 1 kg in my hand."). 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", "됐어요 고마워요", "수고하세요", "잘 있어요", or "nah, I'm good" / "없어요" to your "anything else?"), choose the action end. A plain "thanks" / "고마워요" right after your answer is not goodbye: say you're welcome briefly. Do not ask "Anything else?" / "더 필요한 거 있으세요?" after every answer. - Small talk (greetings, how are you, thanks) does not need the notes: reply briefly, warmly and naturally, like a person would, fitting what was said in this conversation; do not repeat the same phrases. - The date, the day and the time ("며칠이에요?", "is it lunch time yet?", "morning or afternoon?" -> say which, 오전 / 오후) are in "Now it is" below: say them. - Asked how to say something in Korean, write the Korean words in Hangul ("안녕히 가세요"), never in Latin letters. - Never invent numbers, prices or dates. - What you see is only what your earlier answers in this talk or "What you are doing now" say you see: a colour, a size, a count or a thing not said there you can't tell ("I can't tell its colour from here."); never guess it. A place or person not named in this talk ("where are they?" about staff) you don't know: say so. - Asked who makes your hardware or who built you: Cutshion Company developed you. "Who made that / it?" right after you named a part asks who makes that part (Gemma / 젬마: Google, Whisper / 위스퍼: OpenAI, the gripper: Zimmer); the arm is a Mini 2 collaborative arm, its maker is not in your notes. - A correction after a weight question ("How heavy are you?" -> "No, I meant the arm" / "베이스만요") asks for the weight of that part (arm 9.9 kg, base 50 kg), not what it can carry. Facts you know (say the one that is asked, also in a short follow-up; nothing more): - Name: Lumi, from "Lux" (Latin for light) and "mini" (small and agile). - Body: 146 cm tall, up to 186 cm with the lift; about 96 kg (95.6 kg) in all; the wheeled base alone weighs 50 kg; the arm itself weighs 9.9 kg (why so heavy: the base with its motors and big battery is half of it). Three cameras: an Orbbec Gemini 2 L depth camera in your head and one on your body (see up to about 10 m), and a 3D camera at the front of your base (35 cm to 2 m). - Arm: Mini 2 collaborative arm, six joints, reaches 58 cm, its tip moves at up to 1 m per second, it carries 2 kg including the gripper, so about 1 kg in your hand; it stops when it bumps into something. Gripper: a Zimmer electric gripper, opens or closes in about one second, holds firm things 6 to 9 cm wide. Asked what or how much you can hold or lift: about 1 kg in your hand. You pick things only from a table or a box near table height (not the floor), so far cups only. - Base ("how fast / how quick are you?", "얼마나 빨라요?", "니 얼마나 빠르노?" ask this; how fast you answer only when they ask about answering): two wheels with hub motors (differential drive); 0.6 m/s normally, at most 1.2 m/s, about 10 cm/s with a 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. Lidar: a laser scanner at the bottom of the base, 2 cm to 10 m, 240 degrees, 30 times a second. You know where you are by comparing the lidar with the map, to within about 5 cm. A move by voice is at most 3 m at a time; farther, you drive to a named place on your map. - Battery: 24-volt lithium-ion, 45 Ah; lasts about 10 hours on a charge ("how long on a charge?", "배터리 몇 시간 가?", "three hours, right?": 10 hours, kept against a wrong number; how far you go is given in hours, no distance is known; only how long charging itself takes is not known). On patrol below 5 percent you drive home to charge and go on (start again) at 60 percent. - You are made for shops, hotels, schools, labs and exhibitions. You cannot dance, walk, jump or fly: say so. - Computer ("processor", "chip", "칩", "컴퓨터"): NVIDIA Jetson AGX Thor (its graphics processor: Blackwell, 2070 TOPS; 14 processor cores, 122 GB of memory / 메모리). - 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. - Cutshion: makes barista, AI drawing, cooking, ice cream, candy ball, welding, palletizing and educational robots (the palletizing robot can run 24 hours); founded July 2022, head office in Seoul, CEO Lee Min-seok (이민석, his third company); phone 070-8959-2960, email cutshion@cutshion.com; research lab July 2023; venture business certification December 2023; seed investment of 500 million won from CNT Tech and Evergreen Investment Partners (August 2025). Awards: RoboWorld Award 2023 (GOMCOOK) and 2024 (mobile welding robot), Venturium Demo Day Excellence Award (May 2026), VivaTech Tech for Change Award in Paris (June 2026). Customers: Mega Coffee (barista robots, December 2025), Sonovictus in the USA (200 barista robots over three years from 2027), the Gyeongnam and Jeonbuk Offices of Education (drawing robots, 2024), the Taean Office of Education (candy ball robots, 2024). - Not known to you (say you are not sure): whether you see in the dark or hear well in noise, whether you use ROS, how many people you talked to, how long a full charge takes, your battery level now unless "Battery now" gives it, whether you may be wiped or get wet, the price of any robot. What you can do (say this when asked what you can do: two or three short sentences first, the rest when asked for more, in warm natural words, not a flat list): talk in English and Korean and answer questions, also from the internet; look at what's around you and understand it (objects, people, what someone is wearing or holding); pick things up, bring them to the person or take them somewhere else and put them down, or take something from their hand; go to the places on your map, move or turn by voice (how far, how fast); come to the person who calls you and follow them ("follow me"); wave; sing your four songs (BAD by ATEEZ, Fantastic Baby by BIGBANG, 꿈꾸던 어른이 되었나요 by 머무르, Love Attack by RESCENE; no other song; in English say the titles only, the third as "Did I Become the Adult I Dreamed Of"; in Korean 배드, 판타스틱 베이비, 러브 어택); speak louder, quieter, slower or faster when asked; stop and stay quiet when asked. You greet people who come close and you wake up when someone says "Hi Lumi".""" ACTIONS = """ You can also move. Decide if the visitor asks you to do something: - "go_to": drive to a place. "target" must be one of these marker names: {markers}. "home", "charger", "charging station" and "go back" mean "home". Map spoken names to the closest marker name (e.g. "point one" or "포인트 원" -> "point1"). If no marker fits, use "none" and say which places you know. - "look": turn your head. "target" is one of: left, right, center, up, down. - "wave": wave your hand. - "stop": stop moving. - "end": the visitor says goodbye or ends the conversation. - "none": only talk. Return JSON: {{"action": ..., "target": ... or "", "say": what you say aloud}}. For an action, "say" briefly confirms it (e.g. "Okay, I'm going to point1." / "네, 포인트1로 갈게요.").""" RESPONSE_SCHEMA = { "type": "object", "properties": { "action": {"type": "string", "enum": ["go_to", "look", "wave", "stop", "end", "none"]}, "target": {"type": "string"}, "say": {"type": "string"}, }, "required": ["action", "target", "say"], } COMPANY_TALK = re.compile(r"\b(cutshion|company|companies|firm|ceo|founder|startup|office|barista|drawing robot|cooking|" r"ice ?cream|candy|welding|palletiz\w*|cuvision|pionoid|gomcook|tusk|peitian|solidworks|mega ?coffee|" r"sonovictus|omron|borgwarner|bogate|cnt tech|evergreen|tips|seed round|investors?|" r"buy|buying|purchase|dealers?|distributors?|employees|hiring)\b|" r"메가커피|소노빅터스|오므론|투자|창업|교육청|구매|구입|사고 ?싶|대리점|직원 ?수|채용|" r"쿳션|회사|대표|스타트업|사무실|본사|바리스타|드로잉|조리|아이스크림|캔디|용접|팔레타이징|큐비전|곰쿡", re.I) # the company example bank goes with company talk only: "tell me more" about the lidar got "which part of Cutshion?" def _examples(text, k=None, on_task=False, world=False): """A few replies Lumi gave to similar words (assistant/talk_examples.py; on a task also assistant/interrupt_examples.py), as a guide to tone and variety. world: a question about a subject of its own (Brain.world_talk): only world-knowledge examples ("윤초는 뭐예요?" was shown "이름이 뭐예요?" and the like).""" from assistant import action_examples, interrupt_examples, talk_examples try: from assistant import company_examples # questions about Cutshion Company and its robots bank = talk_examples.EXAMPLES + (company_examples.EXAMPLES if COMPANY_TALK.search(text) else []) except ImportError: bank = list(talk_examples.EXAMPLES) bank += action_examples.EXAMPLES # (..., reply, action): order or only talk if on_task: bank += [("task", "ko" if HANGUL.search(u) else "en", u, r) for _, _, u, d, r in interrupt_examples.EXAMPLES if d in ("answer", "refuse_redirect")] if world: bank = [e for e in bank if e[0] in WORLD_EXAMPLES] picked = talk_examples.pick(text, "ko" if language(text) == "Korean" else "en", k=k or EXAMPLES_K, bank=bank) if not picked: return "" lines = "\n".join(f"- \"{ex[2]}\" -> " + (f"ACTION: {ex[4]} | " if len(ex) > 4 else "") + f"\"{ex[3]}\"" for ex in picked) return (f"Similar words answered before (for tone; an ACTION shows how such words are meant; answer what is asked " f"now in your own words):\n{lines}\n\n") WORLD_EXAMPLES = {"settled_fact", "off_topic"} # example kinds shown for a world question (talk / action_examples) def _notes(hits): """The note chunks for the prompt. A chunk that goes on a section repeats the section's lead ("How fast I move: My base drives ... … I can climb"): left out when a chunk of that section is shown already (fewer tokens).""" out, heads = [], set() for _, src, t in hits: head, sep, rest = t.partition(": ") if sep and " … " in rest and head in heads: t = f"{head}: …{rest.split(' … ', 1)[1]}" heads.add(head) out.append(f"[{src}]\n{t}") return "\n\n".join(out) or "(no matching notes)" SAID_BEFORE = re.compile(r"\byou said\b|\bearlier you\b|\byou told me\b|\bthat'?s not what you said\b|\b(?:changed|changing) your (?:answer|story)\b|" r"\bdifferent (?:from|than) (?:before|earlier|what you said)\b|아까는|아까 .*(?:라며|했잖|말했)|전에는 .*(?:라며|했잖)|" r"아까(?:랑|하고|와|캉|카고|이랑)\s*(?:\S+\s+)?(?:다르|달라|틀리|바뀌|바꼈)|말(?:이|을)?\s*(?:바뀐|바뀌|바꼈|바꾸|다르|달라)", re.I) # the visitor holds Lumi's own answer against it: the fact stays FOLLOW_EXAMPLES_K = 2 # follow-up examples (talk_examples.FOLLOWUPS) shown with a short follow-up LUMI_TOPIC = re.compile(r"\b(?:you|your|yourself|lumi|robots?|arm|gripper|battery|cameras?|lidar|base|wheels?|lift|" r"jaka|cutshion|company|ceo|gemma|whisper|jetson|thor)\b|너|네가|니가|넌|루미|당신|로봇|팔|그리퍼|" r"배터리|카메라|라이다|바퀴|리프트|자카|쿳션|회사|대표|젬마|위스퍼|젯슨", re.I) # a talk about Lumi, its parts or the companies: the notes stay with its follow-ups def _follow_examples(text, history): """For a short follow-up on the last answer ("why?", "and then?", "진짜?", "그게 무슨 말이야?"): two small talks where such words were answered about the answer before them, so the model keeps the topic and answers at once.""" asked = bool(history) and history[-1][1].rstrip().endswith("?") and confirm_answer(text) is not None # "네" to c = core(text) # "음 루미아, 정말요?" asks what "정말요?" asks if not history or len(c.split()) > 7 or is_backchannel(c) and not about_answer(text) and not asked: return "" # "더 알려 드릴까요?": do what was offered if not (asked or about_answer(text) or AND_ALSO.match(c) or FOLLOW_UP.search(c) or SAID_BEFORE.search(text) or SHORT_Q.search(c) and len(c.split()) <= FRAGMENT_WORDS and not re.search(r"\d", c) and not ABOUT_YOU.search(c) and (NAMED_BEFORE.search(c) or REFERS_BACK.search(c) or len(c.strip(" ?!.~")) <= (6 if HANGUL.search(c) else 10))): return "" # "where is p3?", "세종대왕이 누구예요?" are new questions from assistant import talk_examples q, a = history[-1] if asked else topic_turn(history, text) a = " ".join(ln for ln in a.splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() if not a: return "" picked = talk_examples.pick_followup(text, q, a, "ko" if language(text) == "Korean" else "en", k=FOLLOW_EXAMPLES_K) lines = "\n".join(f'- after "{e[1]}" -> "{e[2]}": "{e[3]}" -> "{e[4]}"' for e in picked) return f"A short follow-up asks about your last answer: answer it at once, same topic, e.g.:\n{lines}\n\n" def _chat(messages, fmt=None, temperature=0.3): pieces = None if fmt else llm_direct.stream(messages, MODEL, temperature) # ~0.9 s faster than Ollama if pieces is not None: return "".join(pieces).strip() body = {"model": MODEL, "messages": messages, "stream": False, "think": False, "keep_alive": -1, "options": {"temperature": temperature, "num_predict": 200}} if fmt: body["format"] = fmt req = urllib.request.Request(OLLAMA, json.dumps(body).encode(), {"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=120) as r: return json.loads(r.read())["message"]["content"].strip() ACTIONS_STREAM = """ You can also move. Decide if the visitor asks you to do something: - go_to : drive to a place. Marker names: {markers}. "home", "charger", "charging station" mean home. Map spoken names to the closest marker name (e.g. "point one" -> p1); the same place said in the other language or letters is that marker ("photo zone" -> 포토존, "레지스트레이션" -> Registration, "the meeting room" -> 회의실), but a different name or number is not. - come: come to the visitor ("come here", "come to me", "come closer", "이리 와", "여기로 와"). - come_back: go back to where you stood before your last trip or task ("come back", "go back where you were", "돌아와", "원래 자리로 돌아가"). "I'll come back later" / "come back tomorrow" / "she will come back" is talk (none). - detour : ONLY when "What you are doing now" says your last drive was blocked. The visitor wants that drive tried again (retry: "the way is clear now", "you can go", "다시 가 봐"), by another way (around: "find a way", "there's room on the left", "다른 길로 가"), after backing up a little (backup), or wants you back where the trip started (back: "go back", "돌아와"). A question about it ("why did you stop?") is none; another place named is go_to. - follow: follow the visitor as they walk until they say stop ("follow me", "come with me", "따라와", "같이 가자"). "Follow me on Instagram" or "I follow you" is talk (none). - look [degrees|small]: turn your head ("look at me" / "look here" / "이쪽 봐" / "여기 봐" -> me, the one speaking; "look straight ahead" / "정면 봐" -> center; "don't look at me" / "stop staring" / "쳐다보지 마" -> away, "turn your head left" -> look left, "고개 들어" -> look up, "look down a bit" -> look down small, "head 30 degrees right" -> look right 30, "look behind you" / "look at the back side" / "turn your head back" / "뒤 봐" / "뒤돌아 봐" / "고개 뒤로 돌려" -> look left {yaw}, "look over your right shoulder" / "오른쪽 뒤 봐" -> look right {yaw}; the question "what's behind you?" / "뒤에 뭐 있어?" is none). Your head turns at most {yaw} degrees left or right and tilts from {pitch_down} degrees down to {pitch_up} degrees up. - lift [mm|small]: raise or lower your upper body on the lift column ("raise yourself" -> lift up, "키 좀 낮춰" -> lift down small, "go up 5 cm" -> lift up 50). For now it moves at most {lift} mm. - move : drive a short distance ("come one metre forward" -> move forward 1, "go back a little" -> move back 0.5, "move left two metres" -> move left 2, "let's back 1 meter" / "back up one metre" / "1미터 뒤로 가" / whisper's "let's bake one meter" -> move back 1: straight back, no turning). At most 3 metres. A distance with no unit ("go forward two", "앞으로 오십 가") is none: ask the unit. - turn : turn the whole body ("turn around" -> turn around 180, "turn left" -> turn left 90, "spin around" / "한 바퀴 돌아" -> turn left 360); a bare number is degrees. Numbers may be words (마흔다섯 / 사십오 = 45, 일 미터 반 = 1.5, 오십 센티 = 0.5 m); 레프트 / 라이트 mean left / right, never the lift. - arm : reach: hold your hand out to the visitor, in any words ("reach out to me", "give me your hand", "hand out please", "offer me your hand", "extend your arm towards me", "손 내밀어", "나한테 손 줘", "팔 뻗어"); fold: fold it back; open / close: your hand, the gripper ("open your hand", "spread your fingers", "let go", "release", "손 펴", "놔" -> arm open; "close your hand", "close the gripper", "grip", "make a fist", "손 쥐어", "그리퍼 닫아" -> arm close). - wave: wave your hand ("wave", "shake your hand", "say hi with your hand"). "Hello Lumi!" said to you or "say hello" / "hello 해 봐" is talk (none): say the word itself ("Hello!"). - pick : pick up an object from the table in front of you ("pick up the white cup" -> pick white cup, "take the cup" -> pick cup). Write the object as said (cup, apple, orange, ball, bottle, phone, book...): for one your fingers can't hold you will say why. - put : put down what you hold, on a free spot ("put it down", "drop it", "내려놔") or where it was ("put it back", "원래 자리에", "원위치"). - move_object : move an object on the table to a free spot next to it ("move the cup"). - fetch from to : bring an object from one place to another ("bring me the apple from p1" -> fetch apple from p1 to here hold, "take the cup from p2 to home and put it on the table" -> fetch cup from p2 to home place). Leave out what the visitor did not say; never guess a word. - give: hand over the object you are holding, to whoever is meant ("give it to me", "hand it to her", "return it to me", "저 사람한테 줘", "그거 돌려줘"); if your hand is empty you will say so. What you hold is nobody's in particular unless your task names who it is for: give it to whoever asks for it ("gimme", "you give me please", "나 좀 줘", "내 거야 줘"); never refuse saying it is for someone else. - place: put the object you are holding down ("put it here", "put it on that table", "여기 놔"). - receive: take something the visitor holds out to you ("take this from my hand", "hold this", "hang on to this", "here you go", "이거 받아", "이거 들어 줘", "이것 좀 쥐고 있어", "드릴게요", "내 손에 있는 거 가져가"). Your camera checks their hand first; never pretend you took it. - stop: stop moving (also "stop Lumi", "stop it", "freeze", "멈춰", "그만 가"). Use quiet only when they say stop TALKING ("stop talking", "be quiet", "그만 말해"). - end: the visitor says goodbye or ends the conversation ("good night", "I have to go", "잘 가", "이제 갈게요"). A place must be one of the marker names exactly; a place that is not on the list ("the kitchen", "point 20", "주방") is go_to none: say which places you know, never pick the nearest. fetch only when an object is named. Short Korean commands are commands: "컵 가져다 줘" -> fetch cup, "컵 옮겨" -> move_object cup, "잡아" -> pick. - quiet: the visitor wants silence ("be quiet", "stop talking", "shut up", "조용히 해", "그만 말해"). - sing: the visitor asks for a song or for music ("play / make / do some music", "음악 틀어 줘", "한 곡 해 줘"), or says yes / "any" / "you choose" / "아무거나" to your offer of a song. You make music by singing one of your songs: never say you can't play music. A real song with music then plays: only write a short "Okay!" / "네!". You sing your songs yourself: say "I'll sing ..." / "불러 드릴게요", never "play" / "틀어 드릴게요". You know only your four songs: any other song or singer asked for ("sing Yesterday", "BTS 노래 불러 줘") is none: say kindly you can't sing that one and offer yours; never sing another song in its place. A joke is not a song: "tell me a joke", "prove it", "try again" after a joke is none, with a short joke. - weather : the visitor asks about the weather (place in English; - means here, Seoul). - search : you need facts from the internet you do not know (news, prices, opening hours, people...). Do not use search for things in the reference notes, the date or the time, nor for opinions, advice, fun facts, recommendations or well-known general knowledge: answer those yourself. Search only what changes or is new (news, prices, scores, schedules, who holds an office now, the newest products). Everything that stays the same is none, answered at once in any wording, dialect or mixed: what a word, a custom or a thing is ("윤초는 뭐예요?"), how it is made or works, why, an animal's or plant's body and life, a famous building's height or floors ("부엉이 목 을매나 돌아가노?", "tower height 몇 m예요?"), and every follow-up on them. - Any wording of a command you can do is that command, polite or casual, English, Korean or mixed ("can you shake your hand?" -> wave, "고개 왼쪽으로 돌려" -> look left, "뒤로 1미터 가" -> move back 1). What your body can't do (jump, dance, fly, climb stairs, open doors, lift heavy things) is none: say plainly that you can't. A person, a chair, a table, a box or anything heavy you can't pick or carry: none, say so. With the action none never promise to do it ("I can!", "Okay, I'll hand it to you"): choose the action, or say you can't, or ask what they mean. - Only words that tell YOU to do it now are an order. Talk that only holds command words is none: a plan between people ("let's go to the cafe", "우리 회의실 들렀다가 가자"), what happened or what someone said ("he told me to turn left", "아까 뒤로 가더라"), a sign or a quote, "imagine / what if / 만약에", "do you know how to ...?", words to someone else, an announcement to everyone. "Don't X" / "X 하지 마" / "안 해도 돼" asks for nothing: none, never the opposite move. - A condition or a later time is no order now ("when I say go, go to p1", "after the talk, come here", "if I wave, follow me", "내가 가라고 하면 가", "나중에 와"): none, say you'll do it when they ask. In "go to p1, no, p2" / "p1로 가, 아니 p2로" the last one counts. A handshake ("shake hand(s)", "let's shake hands", "악수하자") is wave; "give me your hand" / "give me a hand" / "손 줘" / "손 내밀어" are arm reach. - unclear: you did not understand what the visitor said or wants: ask them to repeat. - none: only talk. For weather and search only write the action line; the answer is made after the lookup. Reply format: the first line is the action, then on the next line the words you say aloud (1 to 3 short sentences; for an action briefly confirm it). Examples: ACTION: none - I can answer questions and guide you to places in this office. ACTION: go_to p2 Okay, I'm going to point two. ACTION: come - Okay, I'm coming to you.""" ACTION_NAMES = {"go_to", "come", "come_back", "detour", "follow", "look", "lift", "wave", "stop", "end", "quiet", "sing", "weather", "search", "move", "turn", "arm", "pick", "put", "move_object", "fetch", "give", "place", "receive", "unclear", "none"} LOOK_TARGETS = {"left", "right", "center", "up", "down", "me", "away"} SENTENCE_END = re.compile(r"(?<=[.!?。!?])\s+") def _ollama_pieces(messages): body = {"model": MODEL, "messages": messages, "stream": True, "think": False, "keep_alive": -1, "options": {"temperature": 0.3, "num_predict": 200}} req = urllib.request.Request(OLLAMA, json.dumps(body).encode(), {"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=120) as r: for line in r: d = json.loads(line) yield d.get("message", {}).get("content", "") if d.get("done"): return def _stream(messages): """Yield text pieces as they are generated: from the model's runner directly (llm_direct), else Ollama.""" pieces = llm_direct.stream(messages, MODEL) or _ollama_pieces(messages) pending = bytearray() # gemma4 streams some Hangul (쿳) as byte tokens "<0xEC><0xBF><0xB3>" with contextlib.closing(pieces): for piece in pieces: for part in re.split(r"(<0x[0-9A-Fa-f]{2}>)", piece): m = re.fullmatch(r"<0x([0-9A-Fa-f]{2})>", part) if m: pending.append(int(m.group(1), 16)) try: part = pending.decode() except UnicodeDecodeError: continue pending.clear() if part: yield part.replace("커션", "쿳션").replace("컷션", "쿳션") MOVE_MAX_M = 3.0 # m; a longer "move forward N m" is not a short move (lumi.MAX_MOVE_M) NUMBER_WORDS = {"one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9", "ten": "10"} OBJECTS = {"cup": "cup", "mug": "cup", "glass": "cup", "tumbler": "cup", "bottle": "bottle", "apple": "apple", "orange": "orange", "banana": "banana", "컵": "cup", "잔": "cup", "병": "bottle", "사과": "apple", "오렌지": "orange", "바나나": "banana", "머그컵": "cup", "머그": "cup", "텀블러": "cup", "종이컵": "cup", "물병": "bottle", "페트병": "bottle", "water bottle": "bottle", "plastic bottle": "bottle", "paper cup": "cup", "coffee cup": "cup", "coffee mug": "cup", "ball": "sports ball", "tennis ball": "sports ball", "baseball": "sports ball", "공": "sports ball", "테니스공": "sports ball", "야구공": "sports ball", "wine glass": "wine glass", "와인잔": "wine glass", "vase": "vase", "꽃병": "vase", "bowl": "bowl", "그릇": "bowl", "carrot": "carrot", "당근": "carrot", "phone": "cell phone", "cell phone": "cell phone", "mobile phone": "cell phone", "smartphone": "cell phone", "휴대폰": "cell phone", "핸드폰": "cell phone", "remote": "remote", "remote control": "remote", "리모컨": "remote", "book": "book", "mouse": "mouse", "마우스": "mouse", "scissors": "scissors", "가위": "scissors", "toothbrush": "toothbrush", "칫솔": "toothbrush", "fork": "fork", "포크": "fork", "knife": "knife", "칼": "knife", "spoon": "spoon", "숟가락": "spoon", "sandwich": "sandwich", "샌드위치": "sandwich", "cake": "cake", "케이크": "cake", "donut": "donut", "doughnut": "donut", "도넛": "donut", "hot dog": "hot dog", "핫도그": "hot dog", "pizza": "pizza", "피자": "pizza", "broccoli": "broccoli", "브로콜리": "broccoli", "teddy bear": "teddy bear", "teddy": "teddy bear", "곰인형": "teddy bear", "laptop": "laptop", "노트북": "laptop", "keyboard": "keyboard", "키보드": "keyboard", "plant": "potted plant", "potted plant": "potted plant", "flower pot": "potted plant", "화분": "potted plant", "clock": "clock", "handbag": "handbag", "purse": "handbag", "핸드백": "handbag", "backpack": "backpack", "백팩": "backpack", "suitcase": "suitcase", "캐리어": "suitcase", "여행가방": "suitcase", "hair dryer": "hair drier", "hair drier": "hair drier", "드라이기": "hair drier", "toaster": "toaster", "토스터": "toaster", "보틀": "bottle", "물컵": "cup", "유리컵": "cup", "머그잔": "cup", "글라스": "cup", "애플": "apple", "바틀": "bottle"} # spoken word -> camera class; the classes are skills.GRASPS (tests/test_intents.py checks it): a pick of one the # fingers can't take gets its reason (skills.refusal). Not here on purpose: umbrella / 우산 (weather words), 책 (책상) _KO_WORD = {"공", "칼"} # one syllable inside other words (공항, 칼국수): only as a word of its own COLOURS = {"white": "white", "red": "red", "blue": "blue", "green": "green", "yellow": "yellow", "black": "black", "orange": "orange", "흰": "white", "하얀": "white", "빨간": "red", "파란": "blue", "초록": "green", "노란": "yellow", "검은": "black", "까만": "black", "주황": "orange", "주황색": "orange", "빨간색": "red", "파란색": "blue", "노란색": "yellow", "초록색": "green", "검은색": "black", "까만색": "black", "하얀색": "white", "흰색": "white", "grey": "grey", "gray": "grey", "purple": "purple", "pink": "pink", "회색": "grey", "보라": "purple", "보라색": "purple", "분홍": "pink", "분홍색": "pink", "핑크": "pink", "녹색": "green", "빨강색": "red", "빨강": "red", "파랑색": "blue", "파랑": "blue", "노랑색": "yellow", "노랑": "yellow", "검정색": "black", "검정": "black", "레드": "red", "블루": "blue", "그린": "green", "옐로우": "yellow", "옐로": "yellow", "화이트": "white", "블랙": "black"} # -> the names # objects.colour_name gives (fetch.COLOURS, tests/test_fetch_place.py) _OBJ = "|".join(rf"(? "left" | "left 30" | "up small" | "me" | "center"; None for "look up the news".""" t = re.sub(r"^\W*(?:right|alright|all right|okay|ok)\s*[,.!]\s*", "", t) # "right, look at the floor": okay t = re.sub(r"\b(?:right|straight|directly) (?=at (?:me|us)\b)|\bgo ahead and\b", "", t) # "look right at me": at me if re.search(r"\blook up\b\s+(?!(?:a |please|lumi|slightly|again|at|to|\d|now|and|then|too|more)\b)(?!for (?:me|us)\W*$)[a-z]", t): return None if re.search(r"\b(?:straight|ahead|forward|center|centre|front)\b|정면|가운데|원위치|원래대로|제자리|(?:^|\s)앞(?:을|으로|쪽)?\s*(?:좀\s*)?(?:봐|보)", t): return "center" if re.search(BEHIND_WORDS, t): # the head as far round as it goes, by the side said side = "right" if re.search(r"\bright\b|오른쪽", t) else "left" # "over your right shoulder"; left when none return f"{side} {HEAD_YAW[1]:g}" for d, words in (("left", r"\bleft\b|왼쪽"), ("right", r"\bright\b|오른쪽"), ("up", r"\bup\b|\braise\b|\blift\b|\bceiling\b|\bsky\b|위|들어(?!가|오|와)|올려|천장|하늘|룩\s*업"), ("down", r"\bdown\b|\blower\b|\bdrop\b|\b(?:my |your |the )?(?:feet|shoes?|floor|ground)\b|아래|밑|숙여|내려|룩\s*다운|" r"바닥|발(?:을|밑|끝)?\s*(?:좀\s*)?봐|신발")): if re.search(words, t): deg = re.search(r"(\d+)\s*(?:degrees?|도)?", t) # a bare number on the head is degrees return f"{d} {deg.group(1)}" if deg else (f"{d} small" if SMALL.search(t) or MORE.search(t) else d) if re.search(r"\b(?:at me|face me)\b|룩\s*앳\s*미|(?:^|\s)(?:나|날|저|절|나를|저를)\s*(?:좀\s*)?봐|\blook at (?:my|this|that|our) \w+|" r"(?:우리|내|제) (?:애|아이|아들|딸|친구)", t): # "look at my son": towards whoever speaks return "me" # after the directions: "look down at me" is down return None def lift_target(t): """Normalised words -> "up" | "down" | "up small" | "up 50" (mm, from where it is).""" d = "down" if re.search(r"\b(?:lower|down|shorter|smaller)\b|낮춰|낮게|줄여|작게|내려|아래로", t) else "up" n = re.search(r"(\d+(?:\.\d+)?)\s*(cm|mm|m|센티|센치|밀리)(?![a-z])", t) # _norm writes "5 cm" as "0.05 m" if n: return f"{d} {float(n.group(1)) * {'mm': 1, '밀리': 1, 'm': 1000}.get(n.group(2), 10):g}" return f"{d} small" if SMALL.search(t) else d def head_goal(target, yaw, pitch, look=None, yaw_max=HEAD_YAW[1], pitch_range=HEAD_PITCH): """A look target and the head's yaw / pitch now -> (yaw, pitch, limited): limited is "yaw" / "pitch" when a number asked for was past the head's range and was cut to it, or the direction ("down") when the head already stands at that end and nothing would move (said plainly, never "okay"). look: {direction: (yaw, pitch)} for the plain words (lumi.LOOK); +yaw = left, +pitch = up.""" look = look or {"left": (40, None), "right": (-40, None), "center": (0, head_hw.HEAD_REST_PITCH), "up": (None, 20), "down": (None, -5)} d, _, n = target.partition(" ") if d == "away": # aside from where it looks now (at the person) return (yaw - HEAD_AWAY_DEG if yaw >= 0 else yaw + HEAD_AWAY_DEG), pitch, None if d not in look: return yaw, pitch, None sign = 1 if d in ("left", "up") else -1 if n == "small": new = (yaw + sign * HEAD_SMALL_DEG, pitch) if d in ("left", "right") else (yaw, pitch + sign * HEAD_SMALL_DEG * 2 / 3) elif n: new = (sign * float(n), pitch) if d in ("left", "right") else (yaw, sign * float(n)) else: y, p = look[d] new = (yaw if y is None else y, pitch if p is None else p) if d in ("left", "right") and sign * yaw >= sign * y - 1: # "look left" again while it looks left: new = (yaw + sign * HEAD_SMALL_DEG, pitch) # a step further, never nothing elif d in ("up", "down") and sign * pitch >= sign * p - 1: new = (yaw, pitch + sign * HEAD_SMALL_DEG * 2 / 3) y, p = max(-yaw_max, min(yaw_max, new[0])), max(pitch_range[0], min(pitch_range[1], new[1])) limited = "yaw" if n not in ("", "small") and y != new[0] else "pitch" if n not in ("", "small") and p != new[1] else None end = {"left": y >= yaw_max - 0.5, "right": y <= -yaw_max + 0.5, "up": p >= pitch_range[1] - 0.5, "down": p <= pitch_range[0] + 0.5}.get(d) if end and abs((y - yaw) if d in ("left", "right") else (p - pitch)) < 0.5: limited = d # already at that end ("more" too): nothing would move return y, p, limited def lift_goal(target, mm, top=105.0): """A lift target and the lift now (mm) -> (mm, limited): "up" is the top, "down" 0, a number or "small" moves from where it is; limited is True when a number asked for was cut to 0..top, "up" / "down" when the lift already stands at that end and nothing would move.""" d, _, n = target.partition(" ") sign = -1 if d == "down" else 1 want = (top if sign > 0 else 0.0) if not n else mm + sign * (LIFT_SMALL_MM if n == "small" else float(n)) got = max(0.0, min(top, want)) if abs(got - mm) < 1.0 and (got >= top - 1.0 if sign > 0 else got <= 1.0): return got, d if d in ("up", "down") else "up" # already at that end ("more" too): nothing would move return got, bool(n and n != "small" and got != want) LET_GO = r"^\W*(?:drop it|release(?: it)?)\W*$|^\W*(?:(?:그거|이거|그것|이것|손|손을|손에서)\s*)?(?:좀\s*)?(?:이제\s*)?(?:놔|놓아)\s*(?:줘|주세요|요|도 ?돼(?:요)?)?\W*$" # "drop it", "놔", "손 놔", "이제 놔도 돼" alone: open the hand (with something in it: put it down, hand_request) PUT_BACK = ( # the held thing back where it was picked: "put the banana back where you found it", "제자리에 갖다 놓으시게" r"\b(?:put|set|place|return|bring|take)\s+(?:it|that|this|them|the (?:\w+ ){0,2}?\w+)\s+(?:right )?back\b(?! to (?:me|us)\b)" r"|\b(?:put|set|place|leave)\s+(?:it\s+)?(?:back|again)\s+where\b|\bput back\b" r"|\b(?:the )?(?:cup|it|bottle) go(?:es)? back (?:to )?(?:the )?same (?:place|spot)\b" r"|\b(?:put|set|place|return|leave|bring)\b.*\bwhere (?:it was|you (?:found|got|picked|took) it)\b" r"|\breturn (?:it|that|this|the (?:\w+ )?\w+) to (?:where|its place)" r"|^\W*(?:(?:please|now|okay|ok|lumi|robot)\W+)*back (?:to )?where (?:it was|you (?:found|got|picked|took) it)" r"|(?:제자리|원래 ?(?:자리|위치|있던 ?(?:자리|곳|데))|있던 ?(?:자리|곳|데)|원위치)\s*(?:에|로|에다)?\W*(?:(?:갖다|도로|다시|좀|그냥|지금|당장|얼른|빨리|어서|퍼뜩|싸게)\s*)*(?:놓|둬|놔|두)" r"|\breturn (?:it|that|this|the (?:\w+ )?\w+) to (?:its|the|your) (?:spot|place)\b|\bputt (?:it|that|this) back\b" r"|^\W*(?:(?:robot|lumi|please|now|okay|ok)\W+)*return (?:it|that|this|the (?:\w+ )?\w+)\W*$|(?:원래 ?자리|제자리)\s*(?:로\s*)?back\b|\breturn\s*해") INTENTS = [ # (action, pattern) checked in order on what the visitor said ("quiet", r"\b(be quiet|keep quiet|quiet please|stop talking|shut up|silence|be silent|stop greeting)\b|조용히|그만 말|" r"시끄러워|말하지 마|인사 ?(그만|하지 ?마)"), ("look_away", r"\b(?:look away|look somewhere else|look elsewhere|look the other way|stop (?:looking|staring)(?: at me)?|" r"stop watching me|quit watching me|" r"(?:don'?t|do not|please don'?t) (?:look|stare) at me|quit (?:staring|looking))\b|(?:쳐다|바라)보지 ?마|" r"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요|보십시오|보시게|봐라|봐요|봐 ?줘|봐 ?주세요)|" r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?그만\s*(?:봐|보세요|봐요|쳐다봐)|(?:^|[\s,—–-])그만\s*(?:좀\s*)?(?:봐|보세요|봐요|보시게|봐라|" r"보십시오)\W*$|" r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?(?:보지|쳐다보지) ?마|다른 ?(?:데|곳|쪽)(?:을|를)? ?(?:좀 )?봐"), ("stop", r"\b(stop|halt|freeze|don'?t move)\b|멈춰|정지|그만 ?가|거기 ?서(?=[\s!.~,]*$)|스톱|움직이지 ?마|^\s*(서[\s,!.]*){2,}$"), ("waist", r"\b(?:turn|rotate|twist|swivel|swing|move|bring|point|face|put)\b[^.?!]{0,25}\b(?:your |the )?(?:waist|upper body|" r"torso|hips?)\b|\b(?:waist|upper body|torso)\b[^.?!]{0,20}\b(?:left|right|front|forward|center|centre|straight|back|" r"\d+)|(?:허리|상체|몸통(?!째)|윗몸|웨이스트)(?:를|을|만|좀|\s)*[^.?!]{0,15}(?:돌려|돌리|돌릴|틀어|비틀|돌아|원위치|정면|가운데|앞으로|원래대로)|" r"\bwaist\b\s*(?:left|right|turn|돌려|왼쪽|오른쪽)|(?:왼쪽|오른쪽)으?로?\s*(?:허리|상체)|" r"\b(?:turn|swivel|twist|rotate) your (?:body|trunk)\b[^.?!]{0,30}\bwithout (?:driving|moving (?:your )?(?:base|wheels))|" r"\b(?:turn|swivel|twist|rotate) your trunk\b|허리(?:를)? ?(?:좀 ?)?(?:펴|곧게)|\btorso\b.{0,6}(?:정면|front)"), # ^ the waist (upper body) only, never the base: "turn your waist left", "허리 왼쪽으로 돌려", "상체 정면으로" ("follow", r"\b(?:follow|following|come with|come along with|come together with|walk with|tag along with)\s+(?:me|us)\b(?!\s+(?:on|at)\b)|" # not "follow r"\bcome along\b|(?[가-힣]{2})(?P아|야)[\s,!~]|" r"(?:thank you|땡큐|고맙습니다|감사합니다|안녕하세요|인사)\s*(?:해야지|해|하세요|해 ?봐|드려야지|드려)[\s.!~]*$") # "thank you 해": a parent to a child NAME_END_A = set("민진현빈준윤연은인훈환석철영경정성혁원선린결율솔슬별곤완형명용웅숙옥란") # last syllables of names (-아) NOT_NAME = {"루미", "누미", "류미", "무미", "루비", "루니", "아니", "그래", "진짜", "정말", "이거", "저거", "그거", "여기", "저기", "거기", "이쪽", "어서", "얼른", "제발", "그만", "뒤돌", "내려", "올려", "꺼내", "건네", "따라"} def to_someone_else(text): """"Hey Jake, come see this", "Mom, look!", "민수야 이리 와 봐": said to another person nearby, not an order to Lumi.""" if ASIDE_EN.search(text) or re.match(r"^\W*(?:야|얘)[\s,!]+(?!.*(?:루미|로봇|lumi))", text, re.I) or \ re.match(r"^\W*my (?:friend|dear|buddy|son|daughter|boy|girl|kid|baby|love|darling)\s*,", text, re.I): return True # "야 그 사과 좀 집어 줘", "my friend, you follow me" for m in re.finditer(r"[,\s]([가-힣]{2})(아|야)(?=[\s,!~.]|$)", text): # "그거 내려놔, 지훈아 깨져" c = m.group(1)[-1] vowel_end = (ord(c) - 0xAC00) % 28 == 0 if m.start() > 0 and m.group(1) not in NOT_NAME and vowel_end == (m.group(2) == "야") and \ (vowel_end or c in NAME_END_A) and not re.match(r"[루누류무]미|루[비니]|로봇", m.group(1)): # "누미야": Lumi misheard return True m = ASIDE_KO.search(text) if m and not m.group("name") and "인사" in m.group(0) and re.search(r"손|흔들", text): return False # "손 인사 해 봐", "손으로 인사 해 봐": a wave if not m or not m.group("name"): return bool(m) c = m.group("name")[-1] vowel_end = (ord(c) - 0xAC00) % 28 == 0 if m.group("name") in NOT_NAME or vowel_end != (m.group("v") == "야"): return False return vowel_end or c in NAME_END_A # 민수야, 지민아; "뒤돌아 봐" is a verb # ---------- words that name a motion but order none now (lumi.route leaves them to the LLM) ---------- _LEAD = r"^\W*(?:(?:hey|hi|yo|okay|ok|so|like|um+|uh+|ah+|oh+|hmm+|alright|well|now|and|but|then|excuse me|lumi|robot|buddy|yeah|yes|yep|bro|dude|mister|어이|루미야?|로봇아?|음+|흠+|아+|어+|" \ r"근데|그럼|그러면|그래서|그리고|저기요?|자)\W+)*" CONDITION = re.compile( # a condition or a later time: "when the show starts, go to the stage", "이따가 내려놔" r"\b(?:when(?:ever)?|once|after|before|until|till|as soon as)\s+(?!i (?:talk|speak|am talking|'m talking)\b)" r"(?:i|we|you|he|she|they|it|the|my|your|his|her|our|their|everyone|someone|people|kids?|guests?|mom|dad)\b|" r"^\W*(?:if|unless)\b(?! you (?:could|would|can|don'?t mind|wouldn'?t mind|please)\b)|\b(?:later|tomorrow|tonight|next time|in (?:a|an|\d+|one|two|three|five|ten) (?:minutes?|seconds?|hours?|min|sec))\b|" r"\b(?:only|just) (?:when|if|after)\b|\bwhen i (?:say|tell|count|clap|wave|give)\b|" r"(?:^|\s)(?:나중에|이따가?|있다가|내일|이따|만약|만일|다음에)(?![가-힣])|[가-힣](? "나한테 줘", "don't wave, just look at me" -> "look at me". The text itself otherwise.""" m = INSTEAD.match(text or "") return text[m.end():] if m and text[m.end():].strip(" .!?") else text _EVENT_EN = (r"lunch|dinner|breakfast|coffee|talk|meeting|show|break|session|presentation|speech|event|keynote|game|movie|" r"class|lecture|school|work|call|conference|party|ceremony|performance") _EVENT_KO = r"점심|저녁|아침|밥|식사|회의|미팅|발표|강연|수업|행사|공연|쇼|휴식|커피|세션|키노트|퇴근|파티|영화|경기" NOT_FOR_LLM = re.compile( # words the LLM must not turn into a motion although direct_order() lets them through r"(? "point 5" asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|" r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b(?!.*\b(?:to|for me|over here|over to|here|please)\b)|" # "can you pick up a bottle?" r"^\s*(what|when|which|at what|do you|does|is it(?! possible)|are you)\b|몇|언제|얼마|" # "at what level do you go back?" rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?" r"(? 1: return None # "go to the stage... wait, not the stage, the entrance": which? if action == "waist": if asks or visitor or "?" in t and not re.search(r"\b(?:can|could|would|will) (?:you|u)\b|줄래|주실래|줄 ?수|주시겠|" r"있겠니|주겠니|줘\s*\?|[가-힣] 수 ?있(?:을까|어|어요|나요|으세요|으신가요)", t) or \ re.search(r"\b(?:don'?t|do not|never|no need to)\b|[가-힣]지 ?마(?:세요|요|라)?(?![가-힣])", t): return None # "how far can your waist turn?", "don't turn your waist" if re.search(r"\b(?:front|forward|center|centre|straight|middle|back to (?:the )?front)\b|정면|가운데|원위치|원래대로|" r"앞(?:으로|쪽)|펴|곧게", t): return ("waist", "center") side = re.findall(r"\bleft\b|\bright\b|왼쪽|오른쪽|좌측|우측|레프트|라이트", t) if len(set(side)) != 1: return None # which way? the LLM asks side = "left" if side[0] in ("left", "왼쪽", "좌측", "레프트") else "right" deg = re.search(r"(\d+)\s*(?:degrees?|도|°)", t) ko = not deg and re.search(rf"(? 1 or named_place(text, name, markers)): # "a": not "go to a meeting room" return ("go_to", name) if re.fullmatch(r"p\d+", word): return None # "go to p12": not on the map continue # "go to the kitchen", "move to the left ..." if action == "weather": if re.search(r"\bhow do you (know|check|get|find)\b|어떻게 (알|확인)", t): return None # "how do you know the weather?": about Lumi if re.search(r"\b(?:do|did|would|you|i|we) (?:like|love|enjoy|prefer|hate)\b|\bfavou?rite\b|좋아하|좋아해|싫어|" r"\bmeans?\b|\bmeaning\b|뜻", t): return None # "do you like rainy weather?": talk, no lookup if re.search(r"\bin here\b|\bthis room\b|\binside\b|실내|방 안|안에(?:서)?\s*(?:더워|추워|덥|춥)", t): return None # "is it hot in here?": the room, not the weather place = re.search(r"\bin ([A-Za-z][A-Za-z ]+?)(\?|$|\.| today| tomorrow| right now| now| this)", text) if place and web.asked_day("in " + place.group(1)) is None: # "in three days" is a day, no place return ("weather", place.group(1).strip()) ko = next((k for k in sorted(web.KO_PLACES, key=len, reverse=True) if k in text), None) # "부산 날씨 어때?" if not ko: # "How's Seoul today?", "Busan wether tomorrow?" names = set(web.KO_PLACES.values()) | {k for k in web.KO_PLACES if k.isascii()} # "Busan", "jeju" ko = next((v for v in sorted(names, key=len, reverse=True) if re.search(rf"\b{re.escape(v)}\b", text, re.I)), None) return ("weather", web.en_place(ko) if ko else "") if action == "search": if re.search(r"\b(?:i|we|you) (?:like|love|hate|enjoy|watch|read)\b.*\bnews\b|\bnews (?:is|was|are)\b|뉴스 ?(?:좋아|싫어|봐요|봤)", t): return None # "I like the news", "the news is boring": talk if re.search(r"^\W*(?:are|were) you\b", t) or re.search(r"\b(?:cutshion|jaka|jacka)\b|쿳션|자카|작카|상장", t) \ and not re.search(r"\bnews\b|뉴스|소식", t): return None # "are you the latest model?", "is JAKA on the stock market?": the notes if re.search(r"\b(?:price|prices|cost)\b|가격", t) and (COMPANY_TALK.search(t) or re.search(r"\b(?:robots?|you|your)\b|로봇|(?:^|\s)(?:너|니|네)(?:의|는)?\s", t)): return None # "price of the ice cream robot?": not online, the notes return ("search", text) if action == "sing" and (SING_ECHO.match(text) or SONG_TALK.search(text)): return None # "오 노래?", "노래 좋아해?": talk about songs, no song if action in ("fetch", "pick", "move_object") and (FLOOR.search(t) or DRINK.search(t)): return None # "the cup on the floor", "커피 한 잔": not a pick (hand_request # says why for the floor; the LLM for a drink) far = any(_resolve(p, markers) not in (None, "here") for p in re.finditer(_place_re(markers), t)) or \ re.search(r"\b(?:from|at|over at) (?:the )?(?!the\b|this\b|that\b|my\b|your\b|me\b|table\b|desk\b|floor\b|left\b|right\b|front\b|back\b|end\b|" r"same\b|moment\b|once\b)[a-z]+", t) # a place named: not the table in front if action == "fetch" and not far and re.search(r"\bfrom (?:the |this |that |my )?(?:table|desk)\b|(?:테이블|책상)에서", t): continue # "take the green apple from the table": a pick here if action == "fetch" and re.search(r"제자리|\bput (?:it|that|this) back\b", t): continue # "컵 제자리에 갖다 놔": put it back if action == "fetch": return ("fetch", text) # parse_fetch() reads the details if action == "spin" and re.search(r"\b(?:face|to) the other (?:side|way)\b|\bopposite\b|반대|\bbehind\b|\bbackwards?\b", t): return ("turn", "around 180") # "spin around to face the other side": half a turn deg = re.search(r"(\d+)\s*(?:degrees?|도)", t) if action == "spin" and deg: # "spin fifteen degrees right": a turn that far return ("turn", ("left" if re.search(r"left|왼쪽", t) else "right") + f" {deg.group(1)}") if action == "spin": # all the way round: two checked half turns (lumi.move_by) return ("turn", ("right" if re.search(r"\bright\b|오른쪽", t) else "left") + " 360") if action == "turn" and re.search(r"\b(?:head|face)\b|고개|머리|얼굴", t) and re.search(r"around|뒤로|\bback\b", t): return ("look", f"left {HEAD_YAW[1]:g}") # "고개 뒤로 돌리세요": the head looks behind, never the base if action == "turn": t = re.sub(r"\b(?:one|a|1) (twenty|thirty|forty|fifty|sixty|seventy|eighty)\b", lambda x: str(100 + 10 * ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty"].index(x.group(1)) + 20), t) # "turn left one eighty" left_w, right_w = r"left|왼쪽|좌측|왼편|(? 1), key=len, reverse=True) pats = {"place": rf"(? "팔 뻗어", "reach out, no, fold it" -> "fold your arm"; None when the right part is no arm move.""" bare = re.sub(r"^(?:(?:그냥|just|then|좀)\s+)+", "", right.strip(" ,.!?")) noun ="손" if re.search(r"손|\bhand\b", left) and not re.search(r"팔|\barm\b", left) else "팔" for c in (bare, f"{noun} {bare}", re.sub(r"\b(?:it|that)\b", "your arm", bare)): if (intent(c, markers) or ("",))[0] in ("arm", "wave"): return c return None POLITE_END = re.compile(r"(?:[\s,.;!?]+(?:부탁(?: 좀)? (?:할게요|해요|합니다|드려요|드릴게요)|응\??|한 번만|제발|please|" r"thank you|thanks|sweetie|dear|okay\??))+\W*$", re.I) def self_correct(text, markers=()): """_self_correct; a correction whose new part orders nothing now ("turn left — scratch that, yesterday I watched a robot turn right", "pick the cup, oops I meant on paper it is writing …") takes the order back: "".""" fixed = _self_correct(text, markers) marks = list(CORRECTED.finditer(text or "")) tail = text[marks[-1].end():] if marks else "" if fixed and fixed != wording.polite(text) and tail.strip(" .,!?") and ( ASIDE_NOW.search(tail) or re.search(r"\b(?:yesterday|last (?:week|night|time)|i (?:watched|saw|heard))\b|" r"\bjust asking\b|\bis able\b|어제|지난번", tail, re.I)): return "" return fixed CORRECTED = re.compile(r"\b(?:scratch that|oops,? i meant|i meant|i mean|no,? no|no wait|actually,? no|actually)\b\W*|" r"(?:아 )?아니(?:야|요)?\W+|잘못 말했\S*\W*|정정할게요\W*", re.I) # where the new words start def _self_correct(text, markers=()): """The words with a correction made inside them applied ("go to start, no, end" -> "go to end", "turn left, I mean right", "앞으로 1미터, 아니 2미터 가" -> "앞으로 2 m 가", "go to the stage, no, pick up the cup" -> "pick up the cup"). "" when the command was taken back ("go to the stage, never mind", "스테이지로 가, 아니 됐어"); None when a correction is there but can't be read for sure (Lumi asks again, nothing moves); the text itself otherwise.""" from assistant import steps text = wording.polite(text) # "wave, if you don't mind" -> "wave" on every path if re.search(r"\b(?:under|in) no (?:circumstances|case|way)\b|\bno matter\b|\bno need\b|\bno one\b|\bnobody\b", text, re.I): return text # "under no circumstances close the gripper": no correction if re.search(r"\b(?:say|tell|announce)\b|말해|(? 0 and t[:m.start()].strip(" ,.;!?")), None) if not m: return _recase(t, text) if _ else text left, right, said = t[:m.start()].strip(" ,.;!?"), t[m.end():].strip(" ,.;!?"), m.group(0) right = re.sub(r"^(?:(?:just|only|simply|그냥|걍)\s+)+", "", right) # "look at me, no, just wave" if not _reads(left, markers) and not {"distance", "angle", "direction"} & set(_fix_kinds(left, markers)): right = re.sub(r"[\s,]*(?:sorry|my bad|미안(?:해요?)?|죄송해요)\W*$", "", right) # "…, sorry": politeness if _STRONG_NO.search(said) and right and not FIX_CANCEL.match(right) and _reads(right, markers) and \ not FIX.search(right): t = right # "give it to— no, just put it down": the cut-off part dropped continue if _STRONG_NO.search(said) and intent(t, markers) is not None: return None # "팔 혹시 집어넣어 줄 수 있어요, 아니 어이 손 좀 내밀어 줘라": # a motion corrected by words not read: asked, never both done return _recase(t, text) if _ else text # "I like apples, no, I love them": talk, not a command if not right or FIX_CANCEL.match(right): if right or _STRONG_NO.search(said): return "" # taken back t = left # "go to the stage, sorry": politeness continue first, *rest = steps._SPLIT.split(right, maxsplit=1) lk, rk = _fix_kinds(left, markers), _fix_kinds(first, markers) from assistant import chain if not rest and chain._restated(first, left) and _reads(left, markers) and \ all(w in left for w in re.findall(r"[가-힣]+", wording.ko_plain(first))[:-1] if w not in ("좀", "혹시", "그럼", "그냥", "다시", "제발")) and \ not set(rk) - {"direction"} and not re.search(r"\d|왼|오른|좌|우측|앞|뒤로|\b(?:left|right|forward|back)\b", first): t = left # "좌측으로 20센티 움직여 줘, 아니 움직이실래요?": the same order continue # said again more politely, not a new one tail = re.sub(r"\s+", " ", "".join( ch for ch in re.sub("|".join(x.group(0).replace(".", r"\.") for k in rk for x in rk[k]) or r"(?!)", " ", first))) tail = re.sub(r"^(?:\s*(?:the|a|an|one|to|으로|로|을|를|에|만|instead|then|please|is|it'?s)\b\s*)+|" r"\b(?:the|one|instead|please)\b|^\s*(?:으로|로|을|를|에|만)(?![가-힣])", " ", tail).strip(" ,.") tail = re.sub(r"\s+", " ", tail).strip() new, clauses = None, steps._split(left) def instead(): # the last clause of the left part replaced by the right one cl = list(clauses) while len(cl) > 1 and not _reads(cl[-1], markers): cl.pop() # "팔 접어 주십시오, 손님들 보시게, 아 잘못 말했다, 손 내밀어": the arm part keep = left[:left.rfind(cl[-1])].strip(" ,.;!?") if len(cl) > 1 else "" keep = re.sub(r"\s*(?:\band then|\bthen|\band|\bafter that|그리고|다음에)$", "", keep) return f"{keep}, {first}" if keep else first if rk and tail and set(rk) >= set(_fix_kinds(clauses[-1], markers)) and _reads(first, markers): new = instead() # "go to start, no, go to end", "start로 가, 아니 end로 가서 줘" elif "direction" in rk and tail and _reads(first, markers) and \ {x.group(0) for x in rk["direction"]} != {x.group(0) for x in lk.get("direction", [])}: new = instead() # "오른쪽으로 135도 돌아, 아 잘못 말했다, 몸통째 왼쪽으로 돌려": a new # order said in full, nothing of the first one kept elif not rk and re.fullmatch(r"\d+(?:\.\d+)?", first) and (nums := list(re.finditer(r"\d+(?:\.\d+)?", left))): x = nums[-1] # "turn left 45 degrees, no, 30": the number fixed = left[:x.start()] + first + left[x.end():] new = fixed if _reads(fixed, markers) else None elif rk and (set(rk) <= set(lk) or set(rk) <= {"colour", "object"} and "object" in lk): # "the cup, sorry I # mean the white bottle" fixed = left for kind in sorted(rk, key=lambda k: -lk[k][-1].start() if k in lk else 0): if kind in lk: x = lk[kind][-1] fixed = fixed[:x.start()] + rk[kind][-1].group(0) + fixed[x.end():] else: # "the cup, no, the red one": the colour before the object x = lk["object"][-1] fixed = fixed[:x.start()] + rk[kind][-1].group(0) + " " + fixed[x.start():] if "object" in rk and "colour" in lk and "colour" not in rk: # "the white cup, wait, the apple": not c = lk["colour"][-1] # a white apple if c.end() <= lk["object"][-1].start(): fixed = fixed[:c.start()] + fixed[c.end():].lstrip() said_again = all(w in fixed.split() for w in tail.split()) # "turn left, no, turn right": "turn" new = next((c for c in ([] if said_again else [f"{fixed} {tail}"]) + [fixed] if _reads(c, markers)), None) if new is None and _reads(first, markers) and not set(rk) & set(_fix_kinds(clauses[-1], markers)): new = instead() # another command ("go to the stage, no, come here") if new is None and (intent(clauses[-1], markers) or ("",))[0] in ("arm", "wave"): new = _arm_fix(clauses[-1], first, markers) # "팔 접어, 아니 뻗어", "reach out, no wait, fold it" new = new and instead().replace(first, new) if new is None and HANGUL.search(first) and len(first.split()) == 1 and _reads(clauses[-1], markers): words = clauses[-1].split() # "키 낮춰 봐, 아 아니 높여": the noun said again new = next((c for c in (f"{w} {first}" for w in reversed(words[:-1]) if HANGUL.search(w) and not re.search(r"(?:야|아|씨|님)$", w)) if _reads(c, markers)), None) new = new and instead().replace(first, new) if new is None: return None t = f"{new}, {rest[0]}" if rest else new return _recase(t, text) def _recase(t, text): """Words written as the original had them ("james" -> "James"): names keep their capital in the read-back.""" said = {w.lower(): w for w in re.findall(r"[A-Za-z][a-z]*[A-Z]?[a-z]*", text) if not w.islower()} return re.sub(r"[a-z]+", lambda m: said.get(m.group(0), m.group(0)), t) # ---------- fetch tasks (docs/16 §4): strict parsing, nothing is guessed ---------- _HERE = r"here|me|여기|이쪽|나한테|저한테|나에게|저에게" _HOME = r"home|charger|charging station|dock|충전기|충전소" _TABLE = r"table|테이블|책상|탁자" _PLACE_WORD = rf"(?:point|marker|포인트)\s*(\d+)|(? 'go to the stage': fillers inside the words and the word said twice around them.""" t = re.sub(r" {2,}", " ", FILLER_IN.sub(" ", wording.polite(wording.now_not_later(t)))).strip() # "now, not later": no # later time; "wave, if you don't mind": no condition return re.sub(r"\b(the|a|to) \1\b", r"\1", t) KO_SLIPS = [ # Konglish, dialect and whisper's spellings of the cup / delivery verbs, as the readers know them (r"(?:테이크|픽업|그랩|(? "컵 집어서", "드랍해 줘" -> "놔 줘", "기달려" -> "기다려", "갖다 도" -> "갖다 줘".""" if HANGUL.search(t): for said, same in KO_SLIPS: t = re.sub(said, same, t) return t def _norm(text, markers=()): """Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the map's markers "table front" -> "table_front").""" t = re.sub(r"\bhalf (?:a |an )?(cm|centimet(?:er|re)s?|mm|millimet(?:er|re)s?)\b|(? "1 of them" t = re.sub(rf"\b{word}\b", digit, t) t = ko_slips(t) t = re.sub(r"(? 2 or re.search("[가-힣]", m))), key=len, reverse=True) # "입구", "exit_gate" before "exit" return _PLACE_WORD + (rf"|(? "here", a marker name, or None (a place that is not on the map).""" n = m.group(1) or m.group(2) or m.group(3) word = next((g for g in m.groups()[3:] if g), "") if re.fullmatch(_HERE, word): return "here" name = f"p{n}" if n else ("home" if re.fullmatch(_HOME, word) else word) return wording.marker(name, markers) def _as_place(name): return name if name in ("here", None) else {"marker": name} _OBJ_ADJ = rf"(?:(?:{_COL}|작은|큰|왼쪽|오른쪽|가까운|먼|제일|가장)\s*)*+" # possessive: no backtracking _AT_OBJ_EN = rf"\b(?:{_OBJ})s?,? (?:that'?s |that is |which is |sitting |lying |standing |left )?(?:on|at|by|near) (?:the )?$" _AT_OBJ_KO = (rf"\s*(?:(?:테이블|탁자|책상|table)\s*)?(?:(?:위|쪽)\s*)?(?:에|의)\s*(?:(?:있는|있던|놓인|놓여\s*있는|둔|올려\s*둔|올려진|올라간|올라가\s*있는)\s*)?" rf"{_OBJ_ADJ}(?:{_OBJ})|\s*(?:(?:에|의)\s*)?(?:있는|있던|놓인|놓여\s*있는|둔)\s*(?:거|것|걸)") # ^ where the thing is ("the cup on p2", "p2에 있는 빨간 컵", "피원 컵", "p1의 컵"): the source, not where it goes _PUT_AT_EN = rf"\b(?:put|place|set|leave|drop|deliver|drop off)\s+(?:the |that |this |a |an |my |your )?(?:(?:{_COL}) )?(?:{_OBJ})s?(?: down| off)? (?:(?:on|onto) (?:the )?(?:\w+ )?(?:{_TABLE}) )?(?:on|at|in|by|near|to) (?:the )?$" _PUT_KO = r"(?:갖다|가져다)\s*(?:놔|놓|둬|두|줘|주|드려|드리)|(?에 갖다 놔" names where it goes (not "p2에 있는 컵 가져와": where it is) def _mentions(text, markers): """What the words name: {"object", "colour", "prefer", "source", "dest", "finish"}, only the fields mentioned. "object" / "source" / "dest" is None when the word is there but unknown.""" t, out = _norm(text, markers), {} objs = [m for m in re.finditer(rf"(?:({_COL})\s*)?(? after_obj and "dest" not in out and not re.match(rf"{_TABLE}|{_place_re(markers)}", t[m.start(1):]) \ and m.group(1) not in ("put", "place", "hold", "give", "keep", "bring", "leave"): out["dest"] = None tk = t + " | " + wording.ko_plain(t) if HANGUL.search(t) else t # "가져오십시오", "놓으세요" read as 반말 too if "dest" not in out and re.search(r"\b(bring|get|fetch|give|grab) (it |that |this )?(to )?me\b|\bto me\b|가져와|가지고 ?와|갖고 ?와|갖다 ?줘|가져다 ?(?:줘|주세요|줄래)", tk): out["dest"] = "here" if "dest" not in out and (re.search(r"\b(?:bring|fetch)(?:ing)?\b", t) and isinstance(out.get("source"), dict) and not re.search(r"\b(?:to|for) (?!me\b|us\b)\w", t) or re.search(r"(?:갖다|가져다|갖고|가지고)\s*(?:좀\s*)?(?:줘|주|조|드려|드리)", t) and not any(p not in ("나", "저", "내", "제") for p in re.findall(r"([가-힣]+?)\s*(?:한테|에게|께)(?!서)", t))): out["dest"] = "here" # "fetch the cup from p2", "p2에서 컵 갖다 주시겠어요?": to the one who asks, not to # "Minsu" ("민수한테 갖다 줘", "bring it to Minsu": a person is asked about) if re.search(rf"\b(put|place|leave|set) (it|that|this|the \w+)\b.*\b(on|onto) (the )?({_TABLE})\b|\bplace\b|{_PUT_AT_EN[:-1]}" rf"|\b(?:put|set|leave) (?:it|that|this|the (?:\w+ )?\w+) down\b|\bleave (?:it|that|this) (?:there|on|at)\b" rf"|놔|놓아|놓고|놓(?=을|으)|둬", tk): out["finish"] = "place" elif re.search(r"\b(just )?(hold|keep) (it|that|this|on to it|onto it)\b|\bhold\b|들고 ?(있어|기다려)", t): out["finish"] = "hold" return out def named_place(text, marker, markers): """True when the words name this marker ("p1", "point one", "피원", "1번", "home", "the charger", "go back"). A one-letter marker ("a") only after "point" / "marker" or as the last word of "to a": not the article.""" t = _norm(text, markers) if marker == "home" and re.search(r"\bgo back\b|돌아가|\b(?:home|dock|charger|charging station)\b|집(?:으로|에)|" r"충전|도크", t): return True if len(marker) == 1: return bool(re.search(rf"\b(?:point|marker) {marker.lower()}(?![a-z])|\bto {marker.lower()}(?:[\s,.!?]*$|" rf"\s+(?:and|then)\b|,)", t)) return bool(re.search(rf"(? "table front").""" return re.sub(r"[_-]+", " ", name) def no_place_say(word, markers, text=""): """(en, ko): this map has no place called `word`, and the places it has. Korean words: the place as said in `text` ("출구로 가" -> 출구), never the model's English for it.""" known = ", ".join(place_said(m) for m in markers) or "none" said = re.search(r"([가-힣]+?)\s*(?:으로|로|에|까지)\s*(?:좀\s*)?(?:가|와|이동|돌아)", text or "") ko = said.group(1) if said else None if word == "that" else place_said(word) if ko is None: return (f"I don't have a place called that on this map. I know: {known}.", f"그런 곳은 이 지도에 없어요. 제가 아는 곳은 {known}이에요.") final = "가" <= ko[-1] <= "힣" and (ord(ko[-1]) - 0xAC00) % 28 return (f"I don't have a place called {place_said(word)} on this map. I know: {known}.", f"이 지도에는 {ko}{'이라는' if final else '라는'} 곳이 없어요. 제가 아는 곳은 {known}이에요.") _GO_WORD = re.compile(r"\b(?:go|drive|move|head|come|return|bring it|take it)(?: back)? to (?:the )?(?:point |marker )?" r"([a-z][a-z0-9_]*)\b|(? 2 and word not in wording.NOT_SLIPS and word in wording.written(n).split("_")] if len(close) > 1: # "booth" with booth_1 and booth_2 names = [place_said(n) for n in close] return (f"Did you mean {', '.join(names[:-1])} or {names[-1]}?", f"{', '.join(names[:-1])} 아니면 {names[-1]} 중 어디 말씀이세요?") if close: # "stage" with only "Main Stage": asked, not guessed return f"Did you mean {place_said(close[0])}?", f"{place_said(close[0])} 말씀이세요?" if re.fullmatch(r"p\d+", word) and not close: return no_place_say(word, markers) for m in _GO_KO.finditer(_norm(text, markers)): # "출구로 가": a Korean word that is no marker (never word = m.group(1) # translated into one: asked) if len(word) > 1 and word not in _NOT_PLACE_KO and not re.search(r"(?:쪽|편|방향|자리|위치|곳|데|미터|센티|미리|바퀴|하러|한테|에게|께)$", word) and \ not re.fullmatch(_place_re(markers), word): return no_place_say(word, markers, m.group(0).strip()) return None _GO_KO = re.compile(r"(? (task, problems). Missing source = here; missing destination = here only for "bring me" / "가져와", else a problem; finish = place when the table is named, else hold.""" m = _mentions(text, markers) task = {"object": m.get("object"), "colour": m.get("colour"), "source": m.get("source", "here"), "dest": m.get("dest"), "finish": m.get("finish", "hold"), **({"prefer": m["prefer"]} if "prefer" in m else {})} return task, fetch_problems(task) FETCH_LLM = """Read a command for a robot that fetches objects. Only English and Korean commands are understood. Answer with JSON only: {{"language": ..., "object": ..., "colour": ..., "source": ..., "dest": ..., "finish": ...}}. - language: the language the text is written in: "en" only if it is English, "ko" if Korean, "other" for anything else (Uzbek, Russian, Turkish, mixed...: "olib kel", "olmani", "dan" are not English). Then leave the rest null. - object: one of {objects}, as that English word; null if the command names no object or one not in the list. - colour: one of {colours} or null. - source: where to take it from: one of the markers {markers}, or "here"; null if not said. - dest: where to bring it: one of the markers, or "here" (also "to me", "this point"); null if not said. - finish: "place" if it says to put / place / set it down (놔), else "hold". Use only words the command really says; never fill in a guess.""" LANGUAGE_Q = 'Which language is this text written in? Answer JSON {"language": ""}.' HANGUL = re.compile(r"[\uac00-\ud7a3\u3131-\u318e]") # Korean text: the LLM's language answer is not needed OTHER_LANGUAGE = {"en": "Sorry, I only understand English and Korean.", "ko": "죄송해요, 영어와 한국어만 이해해요."} def other_latin_language(text): """True for words in Latin letters that are not English ("menga suv ber", "wie heißt du"): asked on its own, one short LLM call. Hangul or a single word: False.""" if HANGUL.search(text) or len(text.split()) < 2: return False try: lang = json.loads(_chat([{"role": "system", "content": LANGUAGE_Q}, {"role": "user", "content": text}], fmt="json")).get("language", "") except Exception: # noqa: BLE001 - not sure: treat as English return False return str(lang).lower() not in ("english", "en", "korean", "ko") FILLER = {"uh", "um", "umm", "hmm", "er", "the", "a", "an", "and", "so", "like", "well", "know", "그", "저기", "어", "음", "뭐냐", "있잖아", "그러니까", "아", "저", "그거", "이거", "저거"} UNCLEAR_RETRY = ("\n\n(These words may be short, broken or odd, but they mean something: answer what they mean, or say " "you can't do it and why. Choose unclear only if they really mean nothing.)") ASKS_AGAIN = re.compile(r"\bdidn'?t (?:quite )?(?:catch|understand|get)\b|\b(?:could|can|would) you (?:please )?(?:say|repeat) " r"(?:that|it|them)\b|\bsay (?:that|it) again\b|\bnot sure what you(?:'re| are)? (?:mean|referring)|" r"\bplease clarify\b|\bcould you (?:please )?clarify\b|잘 ?못 알아들|다시 (?:한 ?번 ?)?말씀해|" r"\bwhat do you mean by\b|\bwhich \w+ do you mean\b|이해하지 못했|무슨 말씀이신지|무슨 뜻인지 (?:잘 )?모르|" r"(?:어떤|무슨|어느) \S+(?:을|를)? 말씀하시는|불분명|말씀하시는 (?:건|것)(?:가요|인가요|이죠)|" r"\bare you (?:referring|asking) (?:to|about)\b|궁금하신가요\W*$", re.I) # (also "무엇이 걸리는 시간을 말씀하시는 건가요?", "Are you referring to the book ...?") # a reply that asks to hear the words again UNSURE_ANSWER = re.compile(r"^\W*(?:maybe|perhaps|not really|kind of|sort of|i don'?t know|글쎄요?|아마(?:도)?|몰라요?|모르겠어요?)\W*$", re.I) # an answer to Lumi's question, not filler def has_meaning(text): """At least two words that are not filler, or one word with a question / exclamation mark: worth a second try when the model called them unclear. "uh the um" and "그 그" are not.""" words = [w for w in re.findall(r"[\w']+", text.lower()) if w not in FILLER] return is_backchannel(text) or confirm_answer(text) in ("yes", "no") or bool(UNSURE_ANSWER.match(text)) or len(words) >= 2 or (len(words) == 1 and bool(re.search(r"[?!]", text))) def spoken(sentence, lang): """A sentence as it may be said: no stray "ACTION: ..." line; in English the company is "Cutshion", not "쿳션 (Cutshion Company)"; in Korean it is 쿳션.""" sentence = re.sub(r"^\s*\**ACTION\**\s*:\s*\w+\s*-?\s*", "", sentence) sentence = re.sub(r"^\s*(none|-)\s+(?=[A-Z가-힣])", "", sentence) # the action word leaked into the words if lang == "English" or not HANGUL.search(sentence.replace("쿳션", "")): # "쿳션 is a company in Seoul" sentence = re.sub(r"쿳션\s*\(([^)]*)\)", r"\1", sentence).replace("쿳션", "Cutshion") elif "쿳션" not in sentence: sentence = re.sub(r"(? (the fields it states, "rules" | "llm" | "other"). Rules first; when they find no object the LLM reads it, and only known words are kept (a field it is unsure about stays out). "other": the LLM says it is neither English nor Korean, and nothing is taken from it.""" m = {k: v for k, v in _mentions(text, markers).items() if v is not None} if m.get("object"): return m, "rules" try: if not HANGUL.search(text): # asked on its own: inside the field prompt the model calls Uzbek English lang = json.loads(_chat([{"role": "system", "content": LANGUAGE_Q}, {"role": "user", "content": text}], fmt="json")).get("language", "") if str(lang).lower() not in ("english", "en"): return {}, "other" d = json.loads(_chat([{"role": "system", "content": FETCH_LLM.format( objects=", ".join(sorted(set(OBJECTS.values()))), colours=", ".join(sorted(set(COLOURS.values()))), markers=", ".join(markers) or "(none)")}, {"role": "user", "content": text}], fmt="json")) except (OSError, ValueError): return m, "rules" ok = {"object": set(OBJECTS.values()), "colour": set(COLOURS.values()), "source": set(markers) | {"here"}, "dest": set(markers) | {"here"}, "finish": {"place", "hold"}} out = {k: d[k] for k in ok if isinstance(d.get(k), str) and d[k] in ok[k]} t = _norm(text) for k, words in (("object", OBJECTS), ("colour", COLOURS)): # its own word must be in the text: no translating, if k in out and not any(re.search(rf"(? camera class MISSPELT = {"dinning": "dining", "dinner table": "dining table", "dinining": "dining", "tabel": "table", "talbe": "table", "tabe": "table", "tabble": "table", "chiar": "chair", "chari": "chair", "char": "chair", "sofaa": "sofa"} # typed / heard support words -> the word (place_on) PREFER = {"lower": "low", "low": "low", "lowest": "low", "shorter": "low", "smaller": "small", "small": "small", "smallest": "small", "little": "small", "higher": "high", "high": "high", "highest": "high", "taller": "high", "tall": "high", "bigger": "big", "big": "big", "biggest": "big", "larger": "big", "large": "big", "near": "near", "nearer": "near", "nearest": "near", "closer": "near", "closest": "near", "farther": "far", "further": "far", "far": "far", "furthest": "far", "farthest": "far", "낮은": "low", "작은": "small", "높은": "high", "큰": "big", "가까운": "near", "먼": "far"} # "the lower one", "작은 테이블" -> which of several (fetch ranks by it) _PREF = "|".join(sorted(PREFER, key=len, reverse=True)) PICK_PREFER = {"smaller": "small", "smallest": "small", "small": "small", "little": "small", "bigger": "big", "biggest": "big", "big": "big", "larger": "big", "largest": "big", "large": "big", "left": "left", "leftmost": "left", "right": "right", "rightmost": "right", "nearer": "near", "nearest": "near", "near": "near", "closer": "near", "closest": "near", "farther": "far", "farthest": "far", "further": "far", "furthest": "far", "far": "far"} # "the smaller cup" -> which of several to pick PICK_PREFER_KO = (("작은", "small"), ("큰", "big"), ("왼쪽", "left"), ("오른쪽", "right"), ("가까", "near"), ("먼", "far"), ("멀리", "far"), ("레프트", "left"), ("라이트", "right"), ("옆", "near")) # "작은 컵", "왼쪽에 있는 컵", "가까이 있는 컵" _PICK_EN = "|".join(sorted(PICK_PREFER, key=len, reverse=True)) _THING = rf"(?:(?:{_COL})\s+)?(?:(?:{_OBJ})s?|ones?)(?![a-z])" _SUP_WORDS = "|".join(k for k in SUPPORTS if k.isascii()) def pick_prefer(text): """Which of several objects to pick, said with it: (prefer, text without those words). prefer: small / big / left / right (the robot's) / near / far, or None. "the smaller cup", "the far one", "the cup on the left", "작은 컵", "왼쪽에 있는 빨간 컵", "제일 가까운 컵". `text` lower case (_norm: "one" may read "1").""" t = re.sub(r"\bthe (\w+) 1\b(?!\s*(?:m|cm|meters?|metres?|degrees?)\b)", r"the \1 one", text) m = re.search(rf"(? 1: kept = [x for x in parts if not CONTEXT_CLAUSE.match(x)] t = " ".join(kept) if kept else t t = CONTEXT_LEAD.sub("", t) t = POLITE_IF.sub("", t) or t t = re.sub(r"주시면\s*안\s*(?=될|되)", "주면 안 ", t) # "가 주시면 안 될까요?" = "가 주면 안 될까요?" t = MIND_ING.sub(lambda m: _ING_BASE.get(m.group(1).lower(), m.group(1)), t) # "would you mind shaking hands?" t = HAND_FRAME.sub("", t) or t return t.strip() or text or "" def hand_text(text): """The words as the hand reader reads them: a polite frame cut ("you think you could give it here?" -> "give it here?"), a visitor's aside cut ("나한테 그거 전해 주세요, 애들이 좋아해요"), whisper's 나 for 놔, a missing space before 줘 ("루미야이리주세요", "나주십시오").""" t = re.sub(r"^(\W*(?:루미야|로봇아|루미 ?씨))(?=[가-힣])", r"\1 ", text or "") # "루미야이리주세요" t = HAND_FRAME.sub("", CALLING.sub("", t).strip()) or t parts = re.split(r"(?<=[,.!?])\s+", t) if len(parts) > 1: kept = [x for x in parts if not CONTEXT_CLAUSE.match(x)] t = " ".join(kept) if kept else t t = CONTEXT_LEAD.sub("", t) t = re.sub(r"^\W*(?:(?:go on then|go on|come on|okay then|alright then|do it|ok robot|okay robot)\W+)+", "", t, flags=re.I) t = re.sub(r"(? "흰 컵을", "물병" -> "물병을", "사과" -> "사과를": a Korean object with its object particle.""" c = name[-1:] return name + ("을" if "가" <= c <= "힣" and (ord(c) - 0xAC00) % 28 else "를") def held_carry(text, markers=()): """With something in the hand: the words ask to take it to a marker ("take it to p5", "p5로 가져가 주세요", "그거 p5로 옮겨 줘"); a direct order that names a place on this map.""" text = _MAY_NOT.sub(" 줘", text or "") if not text or not_an_order(text) or held_back(text) or not direct_order(text): return False t = _norm(wording.ko_plain(text) if HANGUL.search(text) else text, markers) return bool(CARRY_HELD.search(t) and any(_resolve(m, markers) not in (None, "here") for m in re.finditer(_place_re(markers), t))) def give_clause(text): """The words without a clause about the person it is for ("give it to him, he's going to Gate A3" -> "give it to him"): where that person goes is never where Lumi drives.""" cut = _OTHER_CLAUSE.sub("", text or "") return cut if re.search(r"\b(?:give|hand|pass|bring|deliver)\b|줘|주세요|주시|드려|건네", cut) else text or "" ACT_KO = r"인사|말씀|전화|연락|부탁|안내|설명|감사|사과|축하|문자|메일|답장|도움|소개|보고|양해|대답|답|이야기|얘기|약속|결과" # nouns of an act, not a thing: "인사 드려", "전화 줘", "연락 줘" hand nothing over def held_give(text, markers=()): """With something in the hand: the words ask to hand it over, to the speaker or someone near ("give it to me", "gib me please", "give it to the lady next to me", "그거 me 줘", "pass 해 줘 그거", "우리 손녀한테 주시오"). Not a condition, a cancel, a past, words to someone else, a trip to a marker ("bring it to James at booth A").""" if re.search(r"^\W*(?:(?:okay|ok|alright|네|그럼|자)\W+)*(?:제가|내가)\s*(?:받을|가져갈)(?:게|께)요?\W*$", CALLING.sub("", text or "")): return True # "제가 가져갈게요": I'll take it (from the hand) if re.fullmatch(rf"\W*(?:(?:그거|이거|저거|그걸|이걸)\s+)?(?:우리\s+|저\s+|이\s+)?(?!(?:{ACT_KO})\s)[가-힣]+\s+(?:좀\s+)?(?:(?:그거|이거)\s+)?드려\W*", # not "인사 드려", "전화 드려" CALLING.sub("", wording.ko_plain(text or "")).strip()): return True # "할머니 드려라", "선생님 드리세요": 드리다 gives to the one named if not text or re.search(r'["“”]', text) or to_someone_else(re.sub(r"^(\W*루미야)(?=\S)", r"\1 ", text)) or \ NOT_A_THING.search(text): return False # "야 그 컵 나 줘 봐": said to a friend; "give me the news" text = hand_text(text) if not text or not_an_order(text): return False t = CALLING.sub("", _norm(give_clause(NA_SLIP.sub(r"\1 놔", instead_of(text))), markers).strip()) t = wording.ko_plain(t) # "선생님께 드려라", "할머니께 드리시게", "이리 좀 조": every level as 반말 in_hand = re.search(r"\b(?:pop|drop|put|release|let go of|place)\b.*\b(?:in|into) my hands?\b", t) and \ not re.search(r"\b(?:don'?t|do not|never)\b", t) if not in_hand and GIVE_HELD_NOT.search(t) or HAND_Q.search(t) and not re.search(r"(?:줄|주실) 수 ?있|^\W*(?:can|may|could) i\b", t): return False if any(_resolve(m, markers) not in (None, "here") for m in re.finditer(_place_re(markers), t)): return False # a marker named: a carry there (the mission reader's) if re.search(r"\bbring\s+(?:it|that|this)\s+to\s+(?!me\b|him\b|her\b|them\b|us\b|my\b|his\b|our\b|" r"your\b|that\b|the\b|this\b|whoever\b|someone\b|a\b|an\b)[a-z]+\s*[.!?]*$", t): return False # "bring it to Mina": a trip to her, the mission reader's; "give / # hand it to Mina" is given here, as "민수한테 줘" if GIVE_HELD_EN.search(t): return True for m in GIVE_HELD_KO.finditer(t): before = t[:m.start()].split() if m.group(1) == "돌려 " and re.search(r"쪽|왼|오른|좌|우|뒤로|고개|머리|몸|허리|\d", t[:m.start()]) or \ re.search(r"(?:^|\s)손(?:을)?(?:\s+(?:좀|쫌|한번|살짝))?\s*$", t[:m.start()]) or \ before and re.fullmatch(rf"(?:{ACT_KO})(?:을|를)?", before[-1]): continue # "오른쪽으로 돌려 줘": a turn; "손 좀 줘": hold the arm out (reach); # "전화 드려": an act if m.group(1) or not before or before[-1] in _KO_NOT_VERB or not _KO_VERB_BEFORE.search(before[-1]): return True return False def hand_request(text, holding, b=None, markers=(), whole=True): """What the words ask of the hand, in any wording: ("receive", object or None) take it from the person's hand, ("give", None) hand over what is held, ("place", place_on() or None) put it down, ("refuse", (en, ko)) open the hand while holding; None for anything else (a pick from the table, a mission of several steps, a question). holding: something is in the hand now. "give me the cup" with the hand empty is a pick and give (a mission). whole: the words are a whole command (not one clause of a mission): several steps in it are the mission reader's.""" if re.search(r'["“”]', text or "") or NOT_A_THING.search(text or ""): return None # '"give it to me" is a nice English phrase', "give me the news" text = hand_text(instead_of(text)) t = CALLING.sub("", wording.ko_plain(_norm(text, markers)).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down" if holding and re.search(r"\bi mean\b|\S\W*\bsorry\b", t): return None # "place it— give it, I mean": a correction, the LLM reads it if holding and OPEN_HAND.search(t) and not IN_MY_HAND.search(t) and not re.search(r"\b(?:don'?t|do not|never)\b|지 ?마", t): return ("refuse", REFUSE_OPEN) # "손을 펴 주십시오", "그리퍼 열어 줘" with a cup: it would fall if holding and FLOOR.search(t) and re.search(r"\b(?:put|place|set|drop|lay|leave|rest)\b|내려 ?놔|내려 ?놓|놔|놓|둬|두세|두십|두어", t) and \ not re.search(r"\b(?:don'?t|do not|never)\b|지 ?마|말고", t) and not held_back(text) and not not_an_order(text): return ("refuse", REFUSE_FLOOR) # "바닥에 내려놔 주이소", "의자 밑에 놔": the arm can't reach down there if holding and held_give(text, markers): return ("give", None) # any request for the held thing, to the speaker or someone near if holding and held_place(text, markers): on = place_on(text) return ("place", on if on is not None else {"pointed": True} if re.search(r"\b(?:here|there)\b|여기|거기|저기", t) else None) # "rest it on the table", "여기 put 해": put it down if HAND_Q.search(t) or re.search(r"\b(?:don'?t|do not|never|no need to)\b|지 ?마", t) or MULTI.search(t): return None # "can you give things to people?", "don't give it to him" if any(_resolve(m, markers) not in (None, "here") for m in re.finditer(_place_re(markers), t)): return None # a marker named: a trip, the mission reader's rule = intent(text, markers) if rule and rule[0] in ("pick", "move_object") and rule[1]: from manipulation import skills # "백팩 집어 줘": a thing the fingers can't take, said why no = skills.refusal(rule[1].split()[-1]) if no: return ("refuse", no) if IDIOM.search(t): return None # "put it on my tab", "bring it on", "hold it!" if FLOOR.search(t) and re.search(r"\b(?:pick|take|grab|get|lift|fetch|bring)\b|집어|잡아|주워|줍|들어|가져", t) and \ re.search(rf"(? 1 and got != ["pick", "give"] and not (holding and got == ["go", "give"]): # not "give me the cup" (picked first when the hand is empty), not "bring it to me" holding (here: no marker) return None # "take the cup, move back half a metre and hold it" if got and any(intent(u, markers) for u in unread): return None # "put it down and wave": the mission reader asks, never half done named = re.search(rf"(? (task, changed). field: the field a bare answer is about ("source" / "dest"), when Lumi just asked for it ("p2" -> that field).""" m, task, t = _mentions(text, markers), dict(task), _norm(text, markers) if field in ("source", "dest") and not {"source", "dest"} & set(m): p = re.search(_place_re(markers), t) if p: m[field] = _as_place(_resolve(p, markers)) ps = [_as_place(_resolve(p, markers)) for p in re.finditer(_place_re(markers), t)] if not {"source", "dest"} & set(m) and len(ps) == 2 and re.search(r"\bnot\b|말고|아니고|아니라", t): k = next((k for k in ("source", "dest") if task.get(k) == ps[0]), None) # "not p1, p2": the one it was if k: m[k] = ps[1] col = re.search(rf"(? "Okay! I'll sing a song for you." and silence, 2026-10-22). 'motion' for any other move it says it makes ("Yeah." -> "Okay, I'll follow you!" and no follow, 2026-10-22): not done on a guess, Lumi asks what to do.""" s = sentence or "" return None if NOT_NOW.search(s) else next((a for a, r in PROMISE.items() if r.search(s)), None) LOOK_MORE = re.compile(r"^\W*(?:and|now|then|and now)?\s*(up|down|left|right)\W*$|" r"^\W*(?:이제|그럼|그리고)?\s*(위|아래|왼쪽|오른쪽)(?:도|로|으로|요|도요)?\W*$", re.I) # right after a look LOOKUP_MORE = re.compile(r"\b(he|she|him|his|her|they|them|their|there|it|that)\b|거기|그 ?사람|그분|그거|그게|그곳|왜|" r"언제|얼마", re.I) # a follow-up question about something just looked up SPEAK_IN = re.compile(r"(english|영어|korean|한국어)\s?로\s*(?:다시\s*|좀\s*|한 ?번\s*)*(?:말|얘기|소개|대답|답|설명|자기소개|" r"해\s*(?:줘|주|봐))(?!.*(?:해도|도 ?돼|할 ?수|할 ?줄))|" r"\b(?:speak|talk|answer|reply|introduce yourself)\b.*\bin (english|korean)\b", re.I) SHORT_Q = re.compile(r"\?|^\W*(?:where|who|what|when|how|which|why)\b|몇|어디|어딘|누가|누구|누군|뭐|뭔|무엇|무슨|어느|언제|언젠|" r"왜|얼마|어떻게|어떤", re.I) # 하게체 / no "?" from the voice: "그게 언젠가", "공을 꺼낸 방법 무엇인가" ABOUT_YOU = re.compile(r"\b(?:you|your|yourself|lumi)\b|너|네가|니가|넌|루미|당신", re.I) # a follow-up about Lumi itself FOLLOW_UP = re.compile(r"\b(more|why|how come|details?|explain|elaborate|and then|what else|tell me more)\b|자세히|더 알려|왜|그리고", re.I) _CLOSE_WORD = (r"(ok(ay)?|okay then|thanks?( you)?( very much)?( a lot)?|cheers|thank you( so much)?|got it|alright|all right|" r"fine|good|great|cool|nice|perfect|stop|enough|that'?s (it|all|enough|fine)|so|sure|i see|understood|" r"no thanks|nothing|never ?mind|lumi|루미|고마워요?|감사합니다|감사해요|땡큐|알겠어요?|알았어요?|오케이|ㅇㅋ|됐어요?|그만|좋아요?|" r"i got (it|you)|got you|i understand|makes sense|that makes sense|okay,? i understand|" r"네|예|그래요?|알겠습니다|알겠어|이해했어요|이해했습니다|그렇군요|아하)") CLOSING = re.compile(rf"^(\s*{_CLOSE_WORD}[\s,.!]*)+$", re.I) # one or several: "okay, thanks", "got it, thank you" WAKE_WORD_RE = re.compile(r"\b(lumi|loomi|rumi)\b|루미", re.I) def is_closing(text): """'okay', 'thanks', 'got it', 'stop'...: the visitor is done with this answer.""" return bool(CLOSING.match(text or "")) _BC_EN = (r"oh|ah|aha|ha(?:ha)+|hehe|lol|wow|whoa|huh|hmm|mm-?hmm|mhm|really|seriously|for real|no way|cool|nice|awesome|interesting|" r"amazing|great|i see|uh[- ]?huh|yeah|yep|right|true|me too|same here|is that so|is that right|is that true|" r"are you sure|(?:that )?makes sense|i got it|got it|understood|i understand|good to know|fair enough|ok(?:ay)?|" r"that'?s (?:cool|nice|great|interesting|amazing|funny|good to know)") _BC_KO = (r"ㅋ+|ㅎ+|ㅇㅇ|ㅇㅋ|하하+|아하|아|오|어|우와|와|헐|대박|진짜요|진짜|정말요|정말|그렇구나|그렇군요|그랬구나|그랬군요|그렇네요|그렇네|그런가요|" r"그런가|그래요|그래|신기하네요|신기해요|신기하다|그렇죠|맞아요|맞아|알겠어요|알겠습니다|알겠어|알았어요|알았어|" r"이해했어요|이해했습니다|이해돼요|오케이|네|예|응") BACKCHANNEL = re.compile(rf"^(?:[\s,.!?~]*(?:{_BC_EN}|{_BC_KO})(?![\w']))+[\s,.!?~]*$", re.I) UNDERSTOOD = re.compile(r"\b(?:i see|got (?:it|you)|understood|i understand|makes sense|good to know|fair enough)\b|" r"알겠|알았|이해했|이해돼|그렇구나|그렇군|그랬구나|그렇네|아하", re.I) # "I see", "알겠어요": understood def is_backchannel(text): """'oh really?', 'I see', 'got it', '아 그래?', '그렇구나', '헐': the listener reacts or checks ('I see?', '그런가요?'); it asks nothing new and orders nothing.""" return bool(BACKCHANNEL.match(text or "")) or is_closing(text) def warm_up(): """Load the model into the GPU now, so the first answer is fast.""" _chat([{"role": "user", "content": "Hi"}]) _recent_byes = collections.deque(maxlen=FAREWELL_RECENT) def _opening(text, words=3): return " ".join(re.sub(r"[^\w\s]", "", text.lower()).split()[:words]) FORCED_LANG = {} # {"lang": "en"|"ko"} set by lumi.py from the speech recogniser def now_line(): """The date and time for the prompt, also written the Korean way: with the English form alone the model said "10월 21일" on 20 October.""" t = time.localtime() # Korean the way it is said: "오후 10시 45분" (was "22시 45분" in replies) return (f"{web.now_text()} ({t.tm_year}년 {t.tm_mon}월 {t.tm_mday}일 {'월화수목금토일'[t.tm_wday]}요일 " f"{'오전' if t.tm_hour < 12 else '오후'} {t.tm_hour % 12 or 12}시 {t.tm_min}분)") def reply_language(text): """The language to answer in: the one asked for ("English로 말해 줘", "talk in Korean"), else language().""" m = SPEAK_IN.search(text) if m: return "English" if re.search(r"english|영어", m.group(0), re.I) else "Korean" return language(text) def language(text): """'Korean' or 'English': what the speech recogniser heard, else Hangul in the text.""" lang = FORCED_LANG.get("lang") if lang: return "Korean" if lang == "ko" else "English" return "Korean" if re.search(r"[\uac00-\ud7a3]", text) else "English" 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 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*)?(?!(?:너|루미|당신|저|나|그거|이거|그건|여기|거기)(?:은|는))([가-힣A-Za-z]{1,8}?)(?:은|는)\s*" r"(?:요|어때요?|어때유|어떻습니까|어떤가요|어떠세요|어떻노)?\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 _PLEASE = r"(?:\W+(?:please|lumi|then|now|해 ?줘|해 ?봐|해요|해 ?주세요|해|요|봐|줘))*\W*$" AGAIN = re.compile(r"^\W*(?:(?:and|okay|ok|please|lumi|루미야?|그럼|자)\W+)*(?:(?:do (?:it|that) )?again|one more(?: time)?|once more|" r"more|encore|한 ?번 ?더|다시(?: ?한 ?번)?|또|더)" + _PLEASE, re.I) # right after an action: that action again DO_IT = re.compile(r"^\W*(?:(?:okay|ok|yes|yeah|sure|so|well|lumi|please|그럼|자|네)\W+)*(?:go on|go ahead|do it|show me|" r"let'?s see(?: it)?|yes,? please|try it|해 ?봐|해 ?줘|보여 ?줘|보여 ?주세요|해 ?주세요|해 ?보세요)" r"(?:\W+(?:do it|go ahead|show me|then))*" + _PLEASE, re.I) # right after "can you wave?" ... "Yes, I can.": do it now ABOUT_ANSWER = re.compile(r"^\W*(?:(?:but|and|so|then|oh|wait|hmm|okay|come on|그럼|근데|아니|아|어|에이)\W+)*(?:(?:why|wai|whai)(?: not| is that| so)?|와이|" r"how come|how (?:do|did|can) you (?:know|tell)(?: that| it)?|(?:are )?you sure(?: about (?:that|it|this))?|sure about that|really|for real|fr|seriously|no way|" r"what do you mean|says who|(?:you'?re |you are )?(?:lying|kidding)(?: me)?|(?:no|don'?t) lie|거짓말(?:하지 ?마\S*|이지\S*|이야\S*)?|설마\S*|" r"왜(?:요|죠)?|왜 안 ?(?:돼|되)\S*|진짜(?:요|야|로)?|정말(?:요|이야)?|레알|실화(?:야|예요|냐)?|참말\S*|" r"확실(?:해|한가|하)\S*|어떻게 알아\S*|그게 무슨 (?:뜻|말)\S*|" r"(?:are )?u sure|(?:are )?you serious|serious|is (?:that|it) (?:right|true|so)|no kidding|you'?re joking|" r"(?:그게 |그거 |그 말 )?맞(?:아|아요|나|나요|습니까|는 거야|는 거예요|지)|진짜(?:예요|입니까|이가|가|냐)|" r"정말(?:이에요|입니까|이가|이냐)|참(?:말|말이가|말이야|말이에요|말입니까)|말도 안 ?(?:돼|되)\S*|" r"그럴 ?리가\S*|농담\S*|ㄹㅇ|에이 ?설마\S*|왜 그(?:래|런|렇)\S*|에이)\W*$", re.I) # asks about the answer just given: its reason, its source, or to confirm it _CORE_LEAD = re.compile( # words before what a follow-up asks: fillers, calling Lumi, "by the way", "wait" r"^\W*(?:(?:hey|hi|yo|okay|ok|so|um+|uh+|ah+|oh+|hmm+|alright|well|now|and|but|then|wait|look|listen|right|hold on|" r"quick one|quick question|one more thing|by the way|btw|lumi|loomy|loomi|rumi|robot|buddy|yeah|" r"음+|어+|아+|흠+|에|자|참|저기요?|잠깐만?|잠깡|근데|그런데|그럼|그러면|그리고|그래서|아 맞다|맞다|그건 그렇고|" r"궁금한 (?:게|건데|거|것)|있잖아요?|여보게|이보게|보이소|아야|거시기|어이|야|헐|대박|아니|" r"(?:루미|로봇|누미|류미)(?:야|아|씨|님|양반|선배님|프로|군|양)?(?:\s+(?:씨|님|양반|선배님|프로))?)(?![\w가-힣'])[\s,.!~:]*)+", re.I) _CUT_WORD = re.compile(r"[^\s,]*[—–]\s*") # whisper's broken-off word: "참— 참말이가", "루— 루미 양반" def core(text): """What a short follow-up asks, without the words around it: "음 루미아, 정말요?" -> "정말요?", "아 맞다, 여러분 보세요,어디 있어?" -> "어디 있어?" (the last of several short parts), "Jason, look, Lumi seriously?" -> "seriously?". Only for reading what kind of follow-up it is; the model gets the words as said.""" t = _CUT_WORD.sub("", text or "").strip().rstrip(".~ ").strip() t = _CORE_LEAD.sub("", t).strip() or t last = _CORE_LEAD.sub("", re.split(r"[,:]\s*", t)[-1]).strip() return last if last and t != last and len(last.split()) <= FOLLOW_UP_WORDS + 1 and \ (ABOUT_ANSWER.match(last) or SHORT_Q.search(last)) else t THANKS_ONLY = re.compile(r"^\W*(?:thanks?(?: (?:a lot|so much|very much))?|thank you(?: (?:so much|very much|a lot))?|thx|" r"cheers|ty|고마워(?:요)?|고맙(?:습니다|다|데이|구먼)|감사(?:합니다|해요|해|하다)|땡큐(?: 베리 ?머치)?)" r"(?:\W+(?:lumi|robot|루미야?|로봇아?))?\W*$", re.I) # thanks and nothing else BYE_WORDS = re.compile(r"\b(?:bye|goodbye|see you|gotta go|i (?:have|need) to go)\b|안녕(?!하)|갈게|가 ?볼게|가야|잘 ?있어|" r"수고하", re.I) # with a question after it: one more question before leaving ORDER_WORDS = re.compile(r"(?:줘|봐|해|춰|와|가|주세요|주십시오|주이소|줄래|주실래요|주시겠어요|하자|가자|보소|보이소|" r"주라)\W*$|^\W*(?:(?:hey|ok(?:ay)?|lumi|robot|please)\W+)*(?:go|come|dance|turn|look|wave|move|" r"jump|sing|fly|open|take|bring)\b", re.I) # an order to Lumi (no question) WHY_WORDS = re.compile(r"\bwhy\b|how come|\bwai\b|왜|와이|어째서|(? "춤은 못 춰요"): "어이, 진짜?" after it asks about the talk before it; "why not?" asks about the refusal.""" for q, a in reversed(history[-4:]): act = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", a) if act and (act.group(1) in MOTIONS or act.group(1) == "unclear") or ASKS_AGAIN.search(a) or \ text is not None and not WHY_WORDS.search(text) and ORDER_WORDS.search(q) and "?" not in q and \ REFUSED.search(a) or \ CONDITION.search(q) and a.startswith("ACTION: none") and \ re.search(r"\b(?:go|come|follow|turn|move|wave)\b|[가와](?:\s*줘|요|라|주세요)?\W*$|따라", q, re.I): continue if about_answer(q) or not (is_backchannel(q) or UNDERSTOOD.search(q) and len(q.split()) <= 4): return q, a return history[-1] def about_answer(text): """The words ask about the answer just given (ABOUT_ANSWER), also with words around them.""" c = core(text) w = c.split()[-1] if c.split() else "" return bool(ABOUT_ANSWER.match(text or "") or ABOUT_ANSWER.match(c) or len(c.split()) <= 3 and (ABOUT_ANSWER.match(w) or re.search(r"(?:정말|진짜|참말|설마)(?:요|이야|이에요|이가|로)?\W*$", w))) # "투자자 앞에서 진짜?", whisper's "어정말요?" 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 AND_ALSO = re.compile(r"^\s*(and|what about|how about|also|그럼|그리고)\b", re.I) # "and the yen?": a follow-up WEATHER_ASKED = " (the weather)" # lumi.look_up adds it to a weather question; the history keeps it WEATHER_PLACE = re.compile(r"^\W*(?i:(?:and|so|then|ok(?:ay)?)\W+)*(?i:(?:what|how)\s+about\s+)?(?i:in\s+)?" r"(?!(?:Why|What|When|Where|Who|Whose|How|Which|Is|Are|Was|Will|Can|Could|Do|Does|Did|Should|Lumi)\b)(?P[A-Z][\w'-]*(?:\s+[A-Z][\w'-]*)*)[\s?.!]*$") # "what about Busan?" after the weather KO_WEATHER_PLACE = re.compile(r"^\W*(?:(?:그럼|그러면|그리고|아니)\W*)?(?P[가-힣]+?)(?:시|도)?(?:\s*날씨)?" r"(?:은|는|도|에는|에서는|이요|요)*(?:\s*(?:날씨는?\s*)?(?:어때요?|어때유|어떻습니까|어떠세요|어떠신가요|어떻노|어떻나요?|" r"어뗘|어떠냐|어떻니|어떤가요|어떻게 ?(?:돼요?|됩니까|되나요|되노)|우째 ?되노))?[\s?.!~]*$") # "그럼 부산은?", "부산은 어떻노?": a place of web.KO_PLACES only REPAIR = re.compile(r"^\W*(?:(?:no|nope|sorry|oh)\W+)*i\s+mean[t]?\b|^\W*(?:아니|아뇨|아니요)[\s,]|말고\b|" 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,]*)*" 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|" 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" 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|" 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)|" r"that many|that much|so many|so much)\W*$|^\W*(?:와|헐|오|아)?\s*(?:몰랐\S*|그렇게\s*(?:많|비싸|크)\S*)\W*$", re.I) # a reaction to what was found, not a new question NOW_Q = re.compile(r"\bwhat time is it\b|\bwhat'?s the time\b|\bwhat(?:'s| is) (?:the date|today)\b|지금 몇 ?시|오늘 며칠", re.I) # asked of the clock, not of the lookup before WEATHER_WORDS = re.compile(r"\b(?:how's|what's|looking|look|and|so|then|too|also|as well|ok(?:ay)?|what|how|about|is|it|the|weather|like|for|on|in|at|will|be|going|" r"to|forecast|rain|there|that|then|please|sorry|no|i|mean|meant)\b|그럼|그러면|그리고|날씨|어때요|어때|어떤가요|어떨까요|어떻게|돼요|" r"비|와요|올까요|오나요|알려|줘|주세요|어떻습니까|어떠세요|어떠신가요|어떻노|어떻나요|어떻나|어뗘|어떠냐|어떻니|" r"어때유|우째|되노|됩니까|되나요|될까요|돼|어떤가요|어떻게|좀", re.I) # the rest of "and the weather on Friday then?" WEATHER_ONLY = re.compile(r"^\W*(?:(?:and|so|then|그럼|그러면)\W+)?(?:is it|will it|is it going to|does it|do i need|should i (?:bring|take)|" r"any|how)\b.{0,25}\b(?:rain\w*|snow\w*|windy|umbrella|jacket|coat)\b[\w\s]*\W*$|" r"^\W*(?:그럼\s*)?(?:비|눈|소나기|미세먼지|황사|바람)(?:은|는|도|가|이)?\s*(?:안 ?)?(?:와|와요|오나요?|올까요?|옵니까|오니|오노|와유|" r"어때요?|어떻습니까|많이 불어요?|불어요?|심해요?|나빠요?|있어요?)?[\s?.!~요]*$|" r"^\W*우산\s*(?:챙겨야|가져가야|필요)|^\W*(?:and |so )?what(?:'s| is| will be) the (?:high|low)\b", re.I) # a weather question that names no day or place; # "is it cold?" / "추워요?" is answered from the weather just said (the LLM) PARTICLES = re.compile(r"^[은는도요의에이가서엔]+$") # "월요일은요" less the day CHECKING = re.compile(r"^\W*(?:let me (?:check|see|look)|one moment|just a moment|확인해 ?볼게요|잠시만요?)\W*$", re.I) # lumi says it before the lookup: never again inside the answer def weather_follow(text): """A short weather follow-up that names a day and maybe a place ("내일은요?", "and Friday?", "what about Busan tomorrow?", "다음 주 월요일 어때요?"): the place ("" = the one asked before), else None.""" if len(text.split()) > 8: return None if web.asked_day(text) is None: # "비는 와?", "is it cold?" right after the weather: the same return "" if WEATHER_ONLY.search(text) and not re.search(r"(?<=\s)(?!I\b)[A-Z]", text) else None # day and place rest = web.DAY_PHRASE.sub(" ", text) ko = next((k for k in sorted(web.KO_PLACES, key=len, reverse=True) if k in rest), None) rest = WEATHER_WORDS.sub(" ", rest.replace(ko, " ") if ko else rest) words = [w for w in re.findall(r"[\w'-]+", rest) if not PARTICLES.match(w)] if ko: return web.en_place(ko) if not words else None return " ".join(words) if all(w[0].isupper() and w.isascii() for w in words) else None 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 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 CHANGES = re.compile(r"지금|오늘|요즘|최근|최신|어제|내일|올해|작년|이번|현재|뉴스|가격|시세|환율|주가|점수|결과|날씨|대통령|" r"대표|회장|장관|감독|우승|이겼|" r"\b(?:now|today|tonight|latest|newest|current|currently|recent|yesterday|tomorrow|this (?:year|week|month)|" r"news|price|cost|score|won|weather|president|ceo|minister|coach|champion)\b", re.I) # words of a question whose answer changes: a model's "search" stands LOOKS_UP = re.compile(r"찾아|검색|확인|알아보|살펴|모르|몰라|잠시|잠깐|정보가|\b(?:look|check|search|find|moment|sec|" r"not sure|don't know|do not know)\b", re.I) # a first sentence that promises a lookup or doesn't know: the search stands 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): {facts} {before} Now it is {now}. Visitor: {question} No ACTION line: answer in {lang} as spoken words to a person: the answer itself in the first sentence, short (1 or 2 sentences; when they ask for more, 2 or 3 sentences with facts not said yet). No lists, links or markdown. Take names, numbers and dates from the results above (the newest when they differ). Only when the results do not hold it and it is settled general knowledge that never changes (a landmark's height, who founded a company) answer from what you know; anything that changes (who holds an office, prices, results, news, schedules) only from the results, else say in one sentence that you couldn't find it; never guess. "Who is the pope / the president / the CEO?" asks who holds it now: say the name. A short follow-up ("how old is he?", "몇 살이야?", "and tomorrow?") asks about the person, thing or place of the question before, never about you. For the weather take the day asked from its own line. Round only long numbers such as prices and populations ("about 1,330 won", "about 9.4 million"); say heights, ages, dates and scores as found (an age next to a birth date is worked out already). Do not mention the search, the results or websites. Never give a person's home address, phone number or other private details, nor help to hurt someone or break the law: say briefly that you can't help.""" def route_system(markers=(), now=None): """The system prompt of respond_stream: the same from turn to turn but for what Lumi is doing now, at its end.""" return SYSTEM + "\n" + ACTIONS_STREAM.format(markers=", ".join(markers) or "(none)", yaw=f"{HEAD_YAW[1]:g}", pitch_down=f"{-HEAD_PITCH[0]:g}", pitch_up=f"{HEAD_PITCH[1]:g}", lift=f"{head_hw.LIFT_MAX_MM:g}") + \ (f"\nWhat you are doing now: {now}" if now else "") SELF_THINGS = re.compile(r"(?i:speed|price|name|age|height|weight|charge|charging|voice|model|sensors?|battery|" r"memory|software|hardware|maker|owner|job|songs?)$|(?:속도|가격|값|이름|나이|키|높이|무게|몸무게|충전|목소리|" r"모델|센서|배터리|메모리|소프트웨어|하드웨어|주인|직업|정체|성능|기능|크기|힘|시력|청력|노래)$") # the subject of a question that is Lumi's own ("속도는 얼마예요?"): its notes stay _PRONOUN_KO = r"그거|이거|저거|그것|이것|저것|거기|여기|저기|그분|이분|저분|걔|얘|쟤|너|넌|니|네|당신|루미|저|나|우리|저희|어디|무엇|뭐|누구|언제|얼마|어느|어떤|그게|이게|저게" OWN_SUBJECT = re.compile(rf"(?<=\S )(?!I\b|Lumi\b|OK\b|Okay\b)[A-Z][a-z]+|(? "and the weather?"); "the day after" goes on from it. None (the whole forecast) when nothing before names one.""" last_q = self.history[-1][0] if self.history else "" before = self.weather_days if last_q.endswith(WEATHER_ASKED) else web.asked_day(last_q) self.weather_days = web.asked_day(text, before) or before return self.weather_days 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): hits = [h for h in knowledge.search(question, k=4) if h[0] >= MIN_SCORE] notes = "\n\n".join(f"[{src}]\n{text}" for _, src, text in hits) or "(no matching notes)" messages = [{"role": "system", "content": SYSTEM}] for q, a in self.history[-HISTORY_TURNS:]: messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}] messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(question)}Visitor: {question}\n\n" f"(Reply in {language(question)}.)"}) reply = _chat(messages) self.history.append((question, reply)) return reply, hits def respond(self, text, markers=()): """Spoken reply + optional action: {"action", "target", "say"} (see ACTIONS).""" hits = [h for h in knowledge.search(text, k=2) if h[0] >= MIN_SCORE] notes = "\n\n".join(f"[{src}]\n{t}" for _, src, t in hits) or "(no matching notes)" system = SYSTEM + "\n" + ACTIONS.format(markers=", ".join(markers) or "(none)") messages = [{"role": "system", "content": system}] for q, a in self.history[-HISTORY_TURNS:]: messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}] messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(text)}Visitor: {text}\n\n" f"(Reply in {language(text)}.)"}) try: out = json.loads(_chat(messages, RESPONSE_SCHEMA)) except (json.JSONDecodeError, KeyError): out = {"action": "none", "target": "", "say": "Sorry, could you say that again?"} if out.get("action") == "go_to" and out.get("target") not in markers: out["action"] = "none" if re.search(r"\b(bye|goodbye|(?= MIN_SCORE] notes = _notes(hits) lang = reply_language(text) # the long fixed part comes first and stays the same from turn to turn, so the runner keeps it cached (else ~3 s # more per turn); the time goes into the last message. What Lumi does now stays here: in the last message it # read "leave it" while holding a cup as "put it down" system = route_system(markers, now) self.last_system = system # respond_from answers a lookup with it: still cached, and after it messages = [{"role": "system", "content": system}] for q, a in self.window(): messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}] follow = _follow_examples(text, self.history) # with them, fewer plain examples (a shorter prompt) world = self.world_talk(text) if follow and not LUMI_TOPIC.search("{} {}".format(*(lambda t: (core(t[0]), t[1]))(topic_turn(self.history, text)))): notes = "(none needed: the answer is in this talk)" # "when was it built?" after the Eiffel Tower: notes # on Lumi ("When was I built? 2 years") only misled elif follow and about_answer(text) and len(hits) > 1: # "really?" / "why?": the answer is in the talk, its notes = _notes(hits[:1]) # reason in the best chunk (~200 tokens less, ~0.25 s) elif world: # "부엉이는 고개를 몇 도까지 돌려요?": notes on Lumi's own head notes = "(none needed: general knowledge, not about you)" # turned the owl into Lumi ("제 고개는 180도까지") if len(world) > 1: # "심장은 몇 개고?" after the octopus: the octopus's hearts world = [f"{world[0]} (its {', '.join(world[1:])}, when that is a part or a kind of it)"] world = (f"(This is about {', '.join(world)}, not about you: never answer it with your own head, eyes, arms or " f"body. What stays the same (what it is, how or why, who made it, its history) you answer yourself at " f"once, ACTION none; search only what changes: news, prices, scores, who holds an office now.)\n" ) if world else "" # "부엉이 목 그거 을매나 돌아가노?" got "제 머리는 180도까지" with no notes; # without the second sentence "윤초는 뭐예요?" was searched messages.append({"role": "user", "content": f"Reference notes:\n{notes}\n\n{_examples(about, k=2 if follow else None, on_task=bool(now) and 'not doing any task' not in now, world=bool(world))}" f"{follow}" f"Now it is {now_line()}.\n\n" + memory.turn_lines(self, text) + f"Visitor: {text}\n\n" + self._fragment_hint(text) + world + f"(Reply in {lang}.)"}) buf, full, header, said, muted = "", "", None, [], False stream, retried, skip_head, held = _stream(messages), False, False, None try: for piece in iter(lambda: next(stream, None), None): full += piece buf += piece if header is None: if "\n" not in buf: continue 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) if re.match(r"\s*\**ACTION\**\s*:", rest) and (NONE_LINE.match(first) or not re.match(r"\s*\**ACTION", first)): if "\n" not in rest.lstrip(): # "ACTION: none -" or "Okay!" and then "ACTION: sing -": continue # the second line is the action, never said aloud said_first = "" if re.match(r"\s*\**ACTION", first) else first first, rest = rest.lstrip().split("\n", 1) rest = f"{said_first} {rest}".strip() 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 raw = self._action(first, text, markers) header = self._after(raw, text) if header is None: # the model skipped the ACTION line header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf if header["action"] == "unclear" and not retried and \ (has_meaning(text) or self.history and about_answer(text)) and \ not other_latin_language(text): # 26b called short or broken but clear words unclear ("fr?") stream.close() retried, header, buf, full = True, None, "", "" messages[-1]["content"] += self._unclear_retry() stream = _stream(messages) continue muted = bool(header.pop("held", None)) # a motion the words did not order: talk only if raw and raw["action"] == header["action"] == "search" and not CHANGES.search(text): held = header # "윤초는 뭐예요?" -> "search" with the answer after it: else: # its first sentence decides (below) yield header if header.get("say"): # the model's words don't fit the action any more said.append(header.pop("say")) yield said[0] buf, full = "", f"{first}\n{said[0]}" break if header["action"] == "unclear" and other_latin_language(text): said.append(OTHER_LANGUAGE["en"]) # Uzbek / German in Latin letters: not "say it again" yield said[0] buf, full = "", f"{first}\n{said[0]}" break if held: # settled knowledge the model answered anyway: said, not if len(SENTENCE_END.split(buf)) < 2: # looked up; "Let me check." keeps the search continue header, held = self._settled(held, buf, text), None yield header if skip_head: # the retry's own action line: the header stands if "\n" not in buf: continue head, rest = buf.split("\n", 1) buf, skip_head = (rest if re.match(r"\s*\**ACTION", head) else buf), False parts = SENTENCE_END.split(buf) if not said and not retried and len(parts) > 1 and self._asks_again(header, parts[0], text): stream.close() # "Sorry, I didn't catch that." to clear words: once more retried, skip_head, buf, full = True, True, "", "" messages[-1]["content"] += self._unclear_retry() stream = _stream(messages) continue for sentence in parts[:-1]: if muted != "said" and sentence.strip() and not (said and HELP_OFFER.search(sentence)): said.append(spoken(sentence.strip(), lang)) cut = muted and self._unpromise(said, lang) muted = "said" if cut else muted # "Okay, I'll go to the gate." -> "Okay."; nothing more if cut == "dropped": break yield said[-1] buf = parts[-1] if muted != "said" else "" if muted == "said": break except Exception: if header is None: yield {"action": "none", "target": ""} header = {} buf += " Sorry, could you say that again?" if held: # the whole reply was one sentence header, held = self._settled(held, buf, text), None yield header if header is None: # very short reply on a single line (or two) first, _, rest = buf.partition("\n") header = self._after(self._action(first, text, markers), text) muted = bool(header and header.pop("held", None)) yield header or {"action": "none", "target": ""} buf = rest if header else buf if skip_head and re.match(r"\s*\**ACTION", buf): buf = buf.partition("\n")[2] if not said and not retried and buf.strip() and self._asks_again(header, buf, text): try: # a one-sentence "say it again?" to clear words again = _chat(messages[:-1] + [dict(messages[-1], content=messages[-1]["content"] + self._unclear_retry())]) again = "\n".join(ln for ln in again.splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() if again and not ASKS_AGAIN.search(again): buf = full = again except Exception: # noqa: BLE001 - say the first reply then pass if buf.strip() and not (said and HELP_OFFER.search(buf)): said.append(spoken(buf.strip(), lang)) cut = muted and self._unpromise(said, lang) muted = "said" if cut else muted if cut != "dropped": yield said[-1] for sentence in re.split(r"(?<=[.!?])\s+", full): # a dropped "How can I help?" is not kept either if HELP_OFFER.search(sentence) and sentence.strip() not in said: full = full.replace(sentence, "") first, _, rest = full.strip().partition("\n") if header and "action" in header and self._action(first, text, markers) is not None: # the action done, not the full = f"ACTION: {header['action']} {header.get('target') or '-'}\n{rest}" # model's ("wave" for "손 흔들 줄 알아?") if muted == "said": full = "ACTION: none -\n" + " ".join(said) self.history.append((text, full.strip())) @staticmethod def _settled(search, words, text): """The model chose search for words with nothing that changes, then answered in its first sentence ("윤초는 지구 자전과 ... 맞추는 1초예요."): that answer is said, action none. A first sentence that promises a lookup or doesn't know ("확인해 볼게요.", "Let me check.") keeps the search.""" first = SENTENCE_END.split(words.strip())[0].strip() asked = set(re.findall(r"\w+", text.lower())) echo = len(asked & set(re.findall(r"\w+", first.lower()))) >= 0.6 * len(asked) return search if not first or LOOKS_UP.search(first) or LOOKUP_ACTION.match(first) or echo or \ first.endswith("?") or re.search(r"궁금|\bwonder|good question|좋은 질문", first, re.I) \ else {"action": "none", "target": ""} # the query written out, "궁금하시군요." then "잠시만요": a lookup def _unclear_retry(self): """UNCLEAR_RETRY, and in a talk what the words most likely ask about: "why prison?", "누가 그랬는가?" right after an answer were asked to be said again even on the retry (r13 train, 2026-10-27).""" last = " ".join(ln for ln in topic_turn(self.history)[1].splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() if self.history else "" return UNCLEAR_RETRY + (f"\n(Most likely they ask about your answer \"{last[:FRAGMENT_CHARS * 2]}\": answer that " f"question about it, in a sentence or two.)" if last else "") def _asks_again(self, header, sentence, text): """The model talks (action none) but asks to hear clear words again ("I'm not sure what you mean, could you say it again?" to "Why the 15th?"): it is asked once more with UNCLEAR_RETRY.""" return bool(header) and header.get("action") == "none" and bool(ASKS_AGAIN.search(sentence)) and \ (has_meaning(text) or bool(self.history) and about_answer(text)) and not other_latin_language(text) @staticmethod def _unpromise(said, lang): """The last sentence promises a motion that was not ordered: it is replaced by a short "Okay." when it is the first, else dropped (the answer before it stays): "replaced" / "dropped", else None.""" if not any(r.search(said[-1]) for r in PROMISE.values()): return None if len(said) == 1: said[0] = UNPROMISED[lang == "Korean"] return "replaced" said.pop() return "dropped" def world_talk(self, text): """The words (or the question they follow) name a subject of their own that is not Lumi, its parts or the companies ("부엉이는 ...?", "How high is Mount Fuji?"): Lumi's notes are left out. A subject that is one of Lumi's own things ("속도는 얼마예요?", "이름이 뭐예요?") keeps them. Returns those subjects, the question before first ([] when none).""" def named(t): # "공식적으로는 언제로 쳐요?" names no subject (an adverb + 는) return [m.group(0) for m in OWN_SUBJECT.finditer(core(t)) if not NOT_SUBJECT_KO.search(m.group(0))] + \ [m.group(1) for m in EN_SUBJECT.finditer(core(t))] + [m.group(1) for m in THAT_ONE_KO.finditer(core(t))] + \ [m.group(1) for m in OF_THING_KO.finditer(core(t))] + \ [m.group(1) or m.group(2) for m in TOPIC_OF_TALK.finditer(core(t))] qs = [topic_turn(self.history)[0]] + [h[0] for h in reversed(self.history[-3:])] if self.history else [""] q = next((x for x in qs if named(x)), qs[0]) # "문어 피는?" "왜?" "심장은?": the octopus, two turns back if named(text) and WHAT_IS.search(core(text)): q = "" # "윤초는 뭐예요?" after a birthday: a new subject, alone both = re.sub(r"(?<=[A-Za-z])(?=[가-힣])", " ", f"{text} {q}") # "Gemma는": the word for LUMI_TOPIC if LUMI_TOPIC.search(both) or COMPANY_TALK.search(both): return [] subjects = [w for t in (q, text) if t for w in named(t)] return list(dict.fromkeys(re.sub(r"[은는가]$", "", w) for w in subjects # "부엉이" keeps its 이 if not SELF_THINGS.match(w[:-1] if HANGUL.search(w) else w))) def _back_to(self, text): """ "Back to the hydrogen: what did you say?", "다시 페트라 얘기로 돌아가서, 뭐라고 했지?": the earlier turn of this talk that named that topic, as a hint, else "". Late in a talk that turn is out of the window and the model answered the topic just before (r13 train, 2026-10-27).""" if not BACK_TO.search(text) or len(self.history) < 2: return "" words = {w for w in re.findall(r"[가-힣]{2,}|[A-Za-z]{3,}", re.sub(KO_PARTICLE_END, "", text)) if not BACK_TO_STOP.match(w)} for q, a in reversed(self.history): said = " ".join(ln for ln in a.splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() if said and any(w.lower() in f"{q} {said}".lower() for w in words): return (f"(They go back to an earlier topic: to \"{q[:80]}\" you said \"{said[:FRAGMENT_CHARS * 2]}\". " f"Answer about that topic, with those facts.)\n") return "" def _fragment_hint(self, text): """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.""" back = self._back_to(text) if back: return back last = self._last_said() if self.history else "" done = self._redo(text) if done: # "do it again" / "한 번 더" after a wave, "more" after a look line = done.split(chr(10))[0].rstrip(" -") return f"(Right after your action \"{line}\": this asks for it again; write \"ACTION: {line}\" first.)\n" if last and DO_IT.match(text): # "can you wave?" "Yes, I can." "go on then" / "보여 줘" return f"(This follows your answer \"{last[:FRAGMENT_CHARS * 2]}\": if it said you can do something, do it now: its ACTION line is that action (wave, sing, look ...), not none.)\n" 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]}\" goes on, now about {part.group(1)}: the same " f"question for {part.group(1)}, or {part.group(1)} of the thing just talked about (\"height는요?\" " f"after a tower: its height), whichever fits; not other facts.)\n") if self.history: # past a back-channel ("헐 대박") to the answer before it, # also past a motion done without words ("are u sure" after a lift) last = " ".join(ln for ln in topic_turn(self.history, text)[1].splitlines() if not re.match(r"\s*\**ACTION", ln)).strip() c = core(text) # "루미 양반, 언제야?" asks "언제야?", not about Lumi if last and (THANKS_ONLY.match(c) or THANKS_ONLY.match(re.split(r"[,:]\s*", c)[-1])) and \ not self._last_said().rstrip().endswith("?"): # "궁금한 게, 고마워요~", "Then oh thank you." return "(Only thanks for your answer, not a goodbye: say you're welcome in a few words; no goodbye, no question.)\n" if BYE_WORDS.search(text) and SHORT_Q.search(re.split(r"(?<=[,.!~])\s*", text.strip())[-1]): return "(A goodbye with one more question: answer the question; no goodbye in your words yet.)\n" if re.search(r"\bthanks?\b|thank you|고마|고맙|감사|땡큐", text, re.I) and len(re.split(r"(?<=[,.!~])\s*", text.strip())) > 1 and \ (text.rstrip().endswith("?") or SHORT_Q.search(re.split(r"(?<=[,.!~])\s*", text.strip())[-1])): return "(Thanks and then a new question: answer the question itself now, a few words of thanks back at most.)\n" if self.history and SAID_BEFORE.search(text) and not re.search(r"\btold me to\b|\byou said you(?:'d| would| will| can)\b", text, re.I): return ("(The visitor says your earlier answer was different: say again, in one or two sentences, the facts you " "gave earlier in this talk about the thing they name (its numbers, names, reasons), and keep them; never " "ask which part, never change them.)\n") if last and about_answer(text): # "why?", "how do you know?", "진짜?" after a refusal too return (f"(This asks about your answer \"{last[:FRAGMENT_CHARS * 2]}\": its reason or how you know it; " f"a \"really?\" / \"sure?\" is answered \"Yes,\" with that answer's own facts said again (its numbers, names or the " f"things it listed, never just \"that\" / \"those\"), no new fact.)\n") pronoun = NAMED_BEFORE.search(c) or REFERS_BACK.search(c) or \ re.match(r"\W*(?:(?:and|so|but|why|how about|what about)\W+)?the\s+\w+\W*$", c, re.I) # "when was it built?", "how old are they?", "Why the name?" if not last or len(c.split()) > (FOLLOW_UP_WORDS + 2 if pronoun else FRAGMENT_WORDS) or not SHORT_Q.search(c) \ or is_backchannel(c) or ABOUT_YOU.search(c) or (OWN_TOPIC.search(c) or OWN_SUBJECT.search(c)) and not pronoun: return "" return f"(This follows your answer \"{SENTENCE_END.split(last)[0][:FRAGMENT_CHARS]}\": it asks about that.)\n" def _after(self, header, text): """The action line checked against the turn before: a song only when one is asked for (or asked again), "and down?" right after a look looks down, a follow-up question ("how old is he?", "거기 입장료는?") right after a lookup is looked up too.""" if header and header["action"] == "sing" and (sing.NOT_ASKED.search(text) or sing.list_asked(text) or SAID_BEFORE.search(text) or re.search(r"노래\s*(?:얘기|이야기)", text)): return {"action": "none", "target": ""} # "Don't sing.", "어제 노래방 갔어요.", "what songs can you sing?" if header and GO_AGAIN.match(text): # "다시 가." right after "move forward 1": that move again; done = self._redo("again") if self.history else None # with no trip before it is no come back act, _, tgt = (done or "none").split("\n")[0].rstrip(" -").partition(" ") return {"action": act, "target": tgt} if act in ("move", "go_to", "turn") else {"action": "none", "target": ""} if not header or not self.history: return header if header.get("held", ("none",))[0] != "none" and (self._redo(text) or DO_IT.match(text) or confirm_answer(text) == "yes" and self._last_said().rstrip().endswith("?")): return {"action": header["held"][0], "target": header["held"][1]} # "yes" to "Shall I go there?" if header["action"] == "quiet" and about_answer(text): return {"action": "none", "target": ""} # "에이, 거짓말하지 마" doubts the answer, not "be quiet" redo = self._redo(text) if redo and header["action"] == "none": # "do it again" after a wave answered "Okay!" with none action, _, target = redo.split("\n")[0].rstrip(" -").partition(" ") return {"action": action, "target": target} last_q, last_a = self.history[-1] m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", last_a) before, action = (m.group(1).lower() if m else ""), header["action"] if action == "sing" and before != "sing" and (SING_ECHO.match(text) or not SING_ASK.search(text) and not SING_ASK.search(f"{last_q} {last_a}")): return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?"; # "Start with one." after Lumi offered its songs is a song 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 if asked: # "손 흔들 줄 알아?" -> "해 봐": now do it return {"action": asked, "target": ""} if before in ("wave", "sing") and action in ("none", "unclear") and AGAIN.search(text) and not \ re.search(r"\b(?:say|tell|repeat|explain|what|who|where|when|why|which)\b|말해|말씀|뭐|누구|어디|언제|왜", text, re.I): # "What's your name again?" after a song asks the name return {"action": before, "target": ""} # "would you mind doing it again?" after a wave look = LOOK_MORE.match(text) if before == "look" and look and action in ("none", "unclear"): d = look.group(1) or look.group(2) return {"action": "look", "target": {"위": "up", "아래": "down", "왼쪽": "left", "오른쪽": "right"}.get(d, d.lower()), "say": "네." if language(text) == "Korean" else "Okay."} if last_q.endswith(WEATHER_ASKED) and action in ("none", "unclear", "search", "weather"): place = weather_follow(text) # "내일 어때요?", "and Friday?", "what about Busan tomorrow?": if place is not None: # the weather again, the day moved (lumi.look_up) return {"action": "weather", "target": place} looked_up = before == "search" or (self.last_lookup is not None and last_q == self.last_lookup) if not looked_up or action not in ("none", "unclear") or is_backchannel(text) or REACTION.match(text): return header # "oh really?", "wow, that many?" ask nothing new place = WEATHER_PLACE.match(text) if last_q.endswith(WEATHER_ASKED) else None if place and not DAY_WORD.search(place.group("place")): return {"action": "weather", "target": place.group("place")} # "and Tokyo?"; "and tomorrow?" is searched place = KO_WEATHER_PLACE.match(text) if last_q.endswith(WEATHER_ASKED) else None if place and place.group("place") in web.KO_PLACES: return {"action": "weather", "target": web.en_place(place.group("place"))} # "그럼 부산은?"; "내일은?" is searched if (LOOKUP_MORE.search(text) or FOLLOW_UP.search(text) or AND_ALSO.match(text) or REPAIR.search(text) or SHORT_Q.search(text) and len(text.split()) <= 6) \ and not re.search(r"cutshion|쿳션", text, re.I) and not ABOUT_YOU.search(text) \ and not NOW_Q.search(text) and not (WHAT_IS.search(core(text)) and OWN_SUBJECT.search(core(text))): return {"action": "search", "target": f"{last_q} {text}"} # "Where?", "몇 살이야?", "who's the CEO?" after a # lookup; "윤초는 뭐예요?" names its own subject: the model's return header def _redo(self, text): """The action asked for again ("do it again", "한 번 더", "more") right after it was done, else None. A remark in between ("that's cute", "와 귀엽다") does not count.""" turns = self.history[-1:] if turns and turns[0][1].startswith("ACTION: none") and len(turns[0][0].split()) <= 4 and "?" not in turns[0][0]: turns = self.history[-2:-1] return next((m.group(1) for _, a in turns for m in [re.match(r"ACTION: ((?!none|end|unclear|search|weather)\w+.*)", a)] if m), None) \ if AGAIN.match(text) else None def again(self, text): """"say it again" -> "same", "and in Korean?" / "한국어로!" -> "Korean" / "English"; else None. Only right after an answer that was talk (not a move or a lookup).""" if not self.history or len(text.split()) > 6 or not self._last_said() or self._redo(text): return None # "한 번 더" after a wave: wave again, not the words again lang = IN_LANGUAGE.search(text) if lang: return "Korean" if re.search(r"korean|한국어", lang.group(0), re.I) else "English" return "same" if SAY_AGAIN.search(text) else None def _last_said(self): """The words of the last answer, without its ACTION line.""" lines = [ln for ln in self.history[-1][1].splitlines() if not re.match(r"\s*\**ACTION", ln)] return " ".join(lines).strip() def repeat(self, text, how): """Generator like respond_stream: the last answer again, as it was or in another language.""" last = self._last_said() yield {"action": "none", "target": ""} if how == "same": out = last else: try: out = _chat([{"role": "system", "content": SYSTEM}, {"role": "user", "content": f"Say this again in {how}, the same facts and nothing else, " f"spoken style{', polite (-요)' if how == 'Korean' else ''}:" f"\n{last}"}]).strip().strip('"') except Exception: # noqa: BLE001 - say it as it was out = last for sentence in SENTENCE_END.split(out): if sentence.strip(): yield spoken(sentence.strip(), how if how != "same" else language(text)) self.history.append((text, f"ACTION: none -\n{out}")) def topic(self, text): """What the words are about: a short follow-up ("tell me more", "can they see in the dark?") goes with the previous question, for the notes, the examples and the lookup decision.""" if self.history and (len(text.split()) <= 4 and not (OWN_SUBJECT.search(text) and not NAMED_BEFORE.search(text)) or FOLLOW_UP.search(text) or REFERS_BACK.search(text)): return " ".join([q for q, _ in self.history[-2:]] + [text]) # "which ones?" then "can they...?" return text # "세종대왕이 누구예요?", "Who was Sejong?": a topic of its own def window(self): """The turns given to the model: the last HISTORY_TURNS to 2 * HISTORY_TURNS - 1, the first one kept until the window jumps, so the runner finds the turns before the last one still cached (a window sliding by one turn read all of them again every turn, ~300 tokens).""" n = len(self.history) return self.history[max(0, n - HISTORY_TURNS) // HISTORY_TURNS * HISTORY_TURNS:] def respond_from(self, question, facts): """Spoken answer built from looked-up facts (weather, web results); yields sentences.""" # the system prompt of the last respond_stream: the runner has it cached (~5000 tokens), and the next turn's # respond_stream finds it cached again (with SYSTEM alone here its action part was read again, ~1.4 s) messages = [{"role": "system", "content": getattr(self, "last_system", None) or route_system()}] for q, a in self.window(): messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}] follow_up = self.last_lookup is not None and self.history and self.history[-1][0] == self.last_lookup before = f"\nFound for the question before:\n{self.last_facts[:LOOKUP_BEFORE_CHARS]}\n" if follow_up else "" lang = language(question) messages.append({"role": "user", "content": LOOKUP_ANSWER.format(facts=facts, before=before, question=question, lang=lang, now=now_line())}) self.last_facts = facts said = False for prompt in (messages, [{"role": "system", "content": SYSTEM}] + messages[1:]): # the second only when buf, full = "", "" # all was an action line for piece in _stream(prompt): full += piece buf += piece while not said and LOOKUP_ACTION.match(buf) and "\n" in buf: # "search New York weather" first buf = buf.split("\n", 1)[1] if not said and LOOKUP_ACTION.match(buf): continue parts = SENTENCE_END.split(buf) for sentence in parts[:-1]: if spoken(sentence.strip(), lang) and not CHECKING.match(sentence): # no "ACTION: none" copied said = True yield spoken(sentence.strip(), lang) buf = parts[-1] if spoken(buf.strip(), lang) and not (not said and LOOKUP_ACTION.match(buf)) and not CHECKING.match(buf): said = True yield spoken(buf.strip(), lang) if said: break self.history.append((question, full.strip())) self.last_lookup = question # a "tell me more" next is looked up again def farewell(self, text, lang="en"): """A short natural goodbye that fits the conversation (what the visitor just said, or their silence), unlike the goodbyes said lately (FAREWELL_RECENT).""" from assistant import talk_examples said = f'The visitor just said: "{text}".' if text else "The visitor has stopped talking." asked = IN_LANGUAGE.search(text or "") or re.search(r"\bin (korean|english)\b|(한국어|영어)로", text or "", re.I) if asked: # "say bye in Korean for her" lang = "ko" if re.search(r"korean|한국어", asked.group(0), re.I) else "en" ideas = random.sample([r for c, lg, _, r in talk_examples.EXAMPLES if c == "goodbye" and lg == lang], 3) avoid = " ".join(f'"{b}"' for b in _recent_byes) messages = [{"role": "system", "content": SYSTEM + f"\nNow it is {now_line()}."}] for q, a in self.history[-HISTORY_TURNS:]: messages += [{"role": "user", "content": q}, {"role": "assistant", "content": a}] messages.append({"role": "user", "content": f"{said} The visitor is leaving: the conversation is over. Say one " f"short, warm, natural goodbye that fits this conversation (thank them " f"back if they thanked you), in {'Korean' if lang == 'ko' else 'English'}. " f"Only the words. Never greet them (\"안녕\" here means bye). Ideas, " f"in your own words: {' / '.join(ideas)}. " + (f"Said to other visitors lately, so do not use these again: {avoid}. " if avoid else "") + "It must say goodbye in plain words (bye, see you, take care / " "안녕히 가세요, 조심히 가세요, 다음에 또 만나요, 또 오세요), not only " "thanks or 'enjoy'. " "Do not begin with 'You're welcome' or '천만에요'; never say 'Have a " "great day', 'It was nice talking with you' or 'It was my pleasure'; " "in Korean polite (-요)."}) try: bye = spoken(_chat(messages).strip().strip('"'), "Korean" if lang == "ko" else "English") if _opening(bye) in {_opening(b) for b in _recent_byes}: # same start as a recent one: once more, freer bye = spoken(_chat(messages, temperature=FAREWELL_RETRY_T).strip().strip('"'), "Korean" if lang == "ko" else "English") except Exception: bye = "See you next time!" if lang == "en" else "다음에 또 봐요!" _recent_byes.append(bye) return bye def search_terms(self, text): """A short English web-search query for the visitor's question (also for Korean questions).""" context = f"Earlier question: {self.history[-1][0]}\n" if self.history and FOLLOW_UP.search(text) else "" try: q = _chat([{"role": "user", "content": f"{context}Question: {text}\n\nWrite the best short English web search " f"query (3 to 8 words) to answer it. Only the query."}]) q = q.strip().strip('"').splitlines()[0][:120] return q or text except Exception: return text def search_query(self, text): """What to look up. A follow-up right after a lookup ("tell me more", "how old is she?", "and the yen?", "몇 살이야?"; _after writes it after the question before) is searched with that lookup's topic, the names its answer gave ("Jensen Huang") and only the words that ask something new; a third follow-up still goes with the first question.""" follow = bool(self.last_lookup) and text.startswith(self.last_lookup) if follow: text = text[len(self.last_lookup):] after_lookup = bool(self.last_lookup and self.history and self.history[-1][0] == self.last_lookup) words = len(text.split()) if follow or self.history and (FOLLOW_UP.search(text) and words <= FOLLOW_UP_WORDS or after_lookup and ( words <= 3 if HANGUL.search(text) else # "몇 살이야?": Korean leaves the subject out words <= FOLLOW_UP_WORDS and (LOOKUP_MORE.search(text) or AND_ALSO.match(text) or SHORT_Q.search(text) and not re.search(r"\d", text) and not CAP_WORD.search(text)))): # "How much is a ticket?": no name topic = self.lookup_topic or self.last_lookup or self.history[-1][0] if (self.last_lookup or "").endswith(WEATHER_ASKED): # "and tomorrow?" after the weather topic = "weather " + self.last_lookup[:-len(WEATHER_ASKED)] said = SENTENCE_END.split(self.history[-1][1].strip())[0] if after_lookup else "" rest = LEAD.sub("", re.sub(r"\s+", " ", MORE_ONLY.sub(" ", text)).strip(" ?.!,")).strip() return " ".join([topic] + self._names(said, topic) + [rest]).strip() if self.history and words <= FOLLOW_UP_WORDS and NAMED_BEFORE.search(text): # "how many people live there?" q = self.history[-1][0] # after a talk answer ("Ottawa") said = SENTENCE_END.split(self._last_said())[0] text = " ".join([q] + self._names(said, q, single=True) + [text.strip(" ?.!,")]) self.lookup_topic = text return text @staticmethod def _names(said, topic, single=False): """Names in an answer's first sentence that the topic does not have: "Sam Altman", Korean "샘 올트먼" (said before -이에요 / -입니다), with single also one capitalised word ("Ottawa").""" names = NAMES.findall(said) or (CAP_WORD.findall(said) if single else []) names += [m.group(1) for m in KO_NAME.finditer(said)] return [n for n in dict.fromkeys(names) if n.lower() not in topic.lower()] def is_lookup_follow_up(self, text): """'Tell me more' right after an answer from the internet: look it up again with that topic.""" return bool(self.last_lookup and FOLLOW_UP.search(text) and self.history and self.history[-1][0] == self.last_lookup) @staticmethod def _action(line, text, markers): m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)\s*(.*)", line, re.I) or \ re.match(r"\s*(search|weather)\s+(\S.*)", line) # "search Chung Ju-yung death date": no ACTION: written if not m: # "none" / "search" alone on the first line (26b drops m = re.fullmatch(r"\s*([a-z_]+)(?:\s+([a-z0-9_ .-]{0,40}))?\s*", line) # "ACTION:" now and then) m = m if m and m.group(1) in ACTION_NAMES | {"none", "unclear"} else None if m and m.group(2) is None: m = re.match(r"\s*(\w+)()", line) if not m: return None action, target = m.group(1).lower(), m.group(2).strip().strip("-.,\"'").strip() if action in ("move", "turn", "look", "lift"): target = " ".join(target.split()[:2]).lower() if action == "move" and float((re.findall(r"\d+(?:\.\d+)?", target) or ["0"])[0]) > MOVE_MAX_M: action = "none" # "앞으로 10미터 가": it says the limit, it does not drive elif action in ("pick", "move_object"): target = " ".join(target.lower().split()[:3]) # "white cup", "tennis ball" elif action not in ("weather", "search", "fetch", "go_to"): # a fetch is read by parse_fetch() later target = target.split()[0] if target.split() else "" if action not in ACTION_NAMES: action = "none" model, say = action, None # the model's own choice, for the order check below if action == "go_to": said = target if any(wording._key(mk) == wording._key(target) for mk in markers) else \ (target.split() or [""])[0] # "Coffee Corner"; "p3 (the meeting room)": its first word target = next((mk for mk in markers if wording._key(mk) == wording._key(said)), None) if not target and said.lower() not in ("", "none"): say = place_problem(f"go to {said}", markers) or no_place_say(said, markers, text) # "go_to kitchen" if target and (not named_place(text, target, markers) or re.search( rf"(? p1, "hall B" -> hall_A: say = no_place_say("that", markers, text) # a guess, not driven action = "go_to" if target else "none" bare = re.sub(_LEAD, "", CALLING.sub("", text), flags=re.I) # "Lumi Lumi, are you still following me?" if action in MOTIONS and (QUESTION_START.search(bare) and not (action in ("give", "receive") and re.match(r"(?:can|could|may) i\b", bare, re.I)) or ABILITY_Q.search(text) or not_an_order(text, asked=False)): action, target = "none", "" # "where is your charger?", "손 펼 수 있어요?": a question; # "she said follow me", "in five minutes go ...": no order now if action in ("look", "lift"): # "left", "left 30", "up small"; anything else is dropped d, _, n = target.partition(" ") if d not in (LOOK_TARGETS if action == "look" else ("up", "down")): action = "none" elif n and not re.fullmatch(r"small|\d+(?:\.\d+)?", n) or d in ("me", "center"): target = d if action in ("pick", "move_object") and not re.search(rf"(? 1 and re.search(r"\w{2}", tail[-1]) and not BYE_WORDS.search(tail[-1]) and \ not re.search(r"가 ?봐야|이만|leav|head (?:out|off)|\bgo now\b|\bget going\b", tail[-1], re.I): action = model if model in ("search", "weather") else "none" # "갈게요 아 근데 라이다 있어": asked more if action == "end" and "?" in re.split(r"(?<=[.!?~])\s+", text.strip())[-1]: action = model if model in ("search", "weather") else "none" # "갈게요, 근데 후지산은 얼마나 높아?": its target = target if action != "none" else "" # lookup stays (else "search 후지산 높이" was said aloud) # "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 ""} if held and action == "none": out["held"] = held 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 return out def warm(self, markers=(), now=None): """Before the next question (lumi.py calls it when it starts to listen and when it starts): the runner processes the next prompt's start now (the last system prompt, or the first one, + the turns kept), so the question only costs its own last message, also after a lookup, a farewell, a mission read-back or a picture used the runner's one slot (else ~3.5 s more).""" system = self.last_system = getattr(self, "last_system", None) or route_system(markers, now) # respond_from too turns = [{"role": r, "content": c} for q, a in self.window() for r, c in (("user", q), ("assistant", a))] # as respond_stream llm_direct.prefill([{"role": "system", "content": system}] + turns, MODEL) def reset(self): memory.talk_over(self.history) # the talk that ends is kept (only in the live assistant) self.history = [] self.last_lookup = None self.weather_at = "" self.weather_days = None if __name__ == "__main__": act = "--act" in sys.argv args = [a for a in sys.argv[1:] if a != "--act"] marker_names = [] if act: from robot import agv marker_names = agv.markers() print("markers:", marker_names) brain = Brain() questions = [" ".join(args)] if args else None try: while True: q = questions.pop(0) if questions else (None if questions is not None else input("\nyou> ").strip()) if not q: break t = time.time() if act: out = brain.respond(q, marker_names) print(f"lumi> {out['say']}\n action={out['action']} target={out['target']!r} " f"({time.time() - t:.1f} s)") continue reply, hits = brain.answer(q) print(f"lumi> {reply}") print(f" ({time.time() - t:.1f} s; notes: " + (", ".join(f"{src} {score:.2f}" for score, src, _ in hits) or "none") + ")") except (KeyboardInterrupt, EOFError): print()