"""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 wording from assistant import web 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 = 4 # previous question/answer pairs kept for follow-up questions 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?" / "무엇을 도와드릴까요?". 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. - 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 briefly and honestly that you don't know it, in varied words ("I'm not sure about that one.", "That I don't know, sorry.", "그건 저도 잘 몰라요.", "아쉽지만 그 정보는 없어요."), not the same sentence every time. - 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, 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, charging time, battery level now): 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. "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. - 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. "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). 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. - 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): say no. Say you are not sure only when the notes do not have it. - When the visitor says goodbye or is done ("thank you for your time", "thanks, that's all", "됐어요 고마워요", "수고하세요", "잘 있어요", 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. - A correction ("no, I meant the arm", "아니, 팔 말고 키요", "아니, 루미 키요") asks the same question again about what they name now: answer that. - Asked how to say something in Korean, write the Korean words in Hangul ("안녕히 가세요"), never in Latin letters. - Never invent numbers, prices or dates. - 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 short follow-up ("How much?", "When?") asks about the thing in your previous answer (after the investors: the amount, 500 million won), not a price. - 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): - 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. 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: 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. - Battery: 24-volt lithium-ion, 45 Ah; lasts about 10 hours on a charge ("how long on a charge?": 10 hours; how far you go is given in hours, no distance is known; how long charging takes is not known, also asked as "and charging?"). - You are made for shops, hotels, schools, labs and exhibitions. You cannot dance, walk, jump or fly: say so. - Detector: YOLOv8 on your graphics processor, 4 to 13 ms per picture. Speech: Whisper, model large-v3-turbo; answers: Gemma 4 26b (Google), served by Ollama; voice: Supertonic TTS; first words about 2 s after a question. - 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 (not even roughly), 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 songs (Arirang, Happy Birthday, Twinkle Twinkle Little Star, Fantastic Baby and more); 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?)\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): """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.""" from assistant import 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) 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")] 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]}\" -> \"{ex[3]}\"" for ex in picked) return ("Examples of how you answered similar words before (for tone only: answer what is asked now, in your " f"own words, never copy them):\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). - 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). - 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" -> me, "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. - turn : turn the whole body ("turn around" -> turn around 180, "turn left" -> turn left 90, "spin around" / "한 바퀴 돌아" -> turn left 360). - arm : stretch your arm forward ("reach out your hand"), fold it back, or open / close your hand (the gripper: "open your hand", "grab it", "let go"). - 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") 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", "저 사람한테 줘"); if your hand is empty you will say so. - 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", "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. A real song with music then plays: only write a short "Okay!" / "네!". 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. - 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. - 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. "Shake hands with me" is a handshake you can't do: none, offer a wave. - 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", "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", "물병": "bottle", "페트병": "bottle", "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"} # 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"} # -> 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".""" if re.search(r"\blook up\b\s+(?!(?:a |please|lumi|slightly|again|at|to|\d|now|and|then|too|more)\b)[a-z]", t): return None if re.search(r"\b(?:straight|ahead|forward|center|centre)\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|위|들어|올려"), ("down", r"\bdown\b|\blower\b|\bdrop\b|아래|밑|숙여|내려")): 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) else d) if re.search(r"\b(?:at me|face me)\b|(?:^|\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. 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, 0), "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) 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 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.""" 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)) return got, bool(n and n != "small" and got != want) 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"(?:don'?t|do not|please don'?t) (?:look|stare) at me|quit (?:staring|looking))\b|(?:쳐다|바라)보지 ?마|" r"그만 ?(?:좀 ?)?(?:쳐다|바라)(?:봐|보세요)|" r"(?:날|나를?|저를?|절)\s*(?:좀\s*)?(?:보지|쳐다보지) ?마|다른 ?(?:데|곳|쪽)(?:을|를)? ?(?:좀 )?봐"), ("stop", r"\b(stop|halt|freeze|don'?t move)\b|멈춰|정지|그만 ?가|거기 ?서(?=[\s!.~,]*$)|스톱|움직이지 ?마|^\s*(서[\s,!.]*){2,}$"), ("follow", r"\b(?:follow|following|come with|come along with|walk with|tag along with)\s+(?:me|us)\b(?!\s+(?:on|at)\b)|" # not "follow r"\bcome along\b|(?[가-힣]{2})(?P아|야)[\s,!~]") 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): return True m = ASIDE_KO.search(text) 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 def intent(text, markers=()): """(action, target) for clear requests, or None. Backs up the LLM's ACTION line.""" if to_someone_else(text): return None # "민수야 이리 와 봐": to a friend t = _norm(text, markers) # "point five" -> "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|" # "can you pick up a bottle?" r"^\s*(what|when|which|at what|do you|does|is it|are you)\b|몇|언제|얼마|" # "at what level do you go back?" rf"({_OBJ})(은|는)\s.*수 ?있|(루미가|로봇이)\s.*수 ?있|는 ?거 ?(돼|되나|가능)|" # "물컵은 가져다줄 수 있어요?" r"어떻게|왜|혼자|스스로|\bby yourself\b|\bsomeone\b|줄 ?알아|할 ?줄|\bcome here often\b|" r"^\W*(?:even|only|also|and|but|so)?\s*(?:with|without|if|unless|while)\b.*\?\s*$", # "even with the lift down?" CALLING.sub("", t)) or LATER.search(CALLING.sub("", t)) # "Lumi, is it hard to ...?" visitor = re.search(r"^\W*(?:can|may|could|should|shall) (?:i|we)\b", CALLING.sub("", t)) # "can I come closer?" for action, pat in INTENTS: m = re.search(pat, t, re.I) if not m: continue if action == "stop" and (STOP_TALK.search(t) or "?" in t and not STOP_ASK.match(CALLING.sub("", t)) or asks): return None # "where's your emergency stop?", "how do I stop you?" if action == "look_away": return None if asks or "?" in t else ("look", "away") # "don't look at me", "쳐다보지 마" if action != "quiet" and re.search(r"(? 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 place = re.search(r"\bin ([A-Za-z][A-Za-z ]+?)(\?|$|\.| today| tomorrow| right now| now| this)", text) if 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) # "부산 날씨 어때?" return ("weather", web.en_place(ko) if ko else "") if action == "search": return ("search", text) if action == "sing" and SING_ECHO.match(text): return None # "오 노래?": asks back, the talk answers if action == "fetch": return ("fetch", text) # parse_fetch() reads the details 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": if re.search(r"around|뒤로", t) or not re.search(r"left|right|왼쪽|오른쪽", t): # "왼쪽으로 돌아": left return ("turn", "around 180") deg = re.search(r"(\d+)\s*(degrees?|도)", t) # "turn left 45 degrees" return ("turn", ("left" if re.search(r"left|왼쪽", t) else "right") + f" {deg.group(1) if deg else 90}") if action == "look": target = head_target(t) if target is None: continue # "look up the weather": a lookup, not the head return ("look", target) if action == "lift": return ("lift", lift_target(t)) if action == "come_back": if COME_BACK.fullmatch(CALLING.sub("", t).strip(" .!?,~")): return ("come_back", "") # "come back", "돌아와", "go back where you were" if driving.amount(t)[0] is None: return None # "I'll come back later", "come back tomorrow": talk continue # "come back 20 cm": a short drive if action == "make_way": return ("move", "back 1") # owner: a checked 1 m back-off (lumi.move_by) if action == "move": g = [x for x in m.groups() if x] dirs = {"ahead": "forward", "backward": "back", "backwards": "back", "back up": "back", "backup": "back", "reverse": "back", "bake": "back", "big": "back", "후진": "back", "앞으로": "forward", "뒤로": "back", "왼쪽으로": "left", "오른쪽으로": "right"} amounts = {"half": 0.5, "one": 1.0, "two": 2.0, "three": 3.0} d = next((dirs.get(x, x) for x in g if not re.match(r"[\d.]+$", x) and x not in amounts), "forward") n = driving.amount(t)[0] # "0.2 m" (wording), "a tiny bit", "two steps", "?" n = driving.DEFAULT_M if n is None else n if n == "?" or not driving.MOVE_MIN_M <= n <= MOVE_MAX_M: return None # asked about / refused with the limit (driving.read) return ("move", f"{d} {n:g}") if action == "arm": return ("arm", "fold" if re.search(r"fold|tuck|down|away|back|접|내려|거둬", t) else "reach") if action in ("grip_open", "grip_close"): return ("arm", action[5:]) if action == "put": return ("put", "back" if re.search(r"\bback\b|제자리|다시", t) else "down") if action in ("pick", "move_object"): g = [x for x in m.groups() if x] # [colour,] object return (action, f"{COLOURS[g[0]]} {OBJECTS[g[1]]}" if len(g) == 2 else OBJECTS[g[0]]) return (action, "") got = None if asks or re.search(r"\b(don'?t|do not|never)\b|지 ?마", t) else driving.move(t) if got and got[1] != "?" and driving.MOVE_MIN_M <= got[1] <= MOVE_MAX_M: return ("move", f"{got[0]} {got[1]:g}") # "back up a tiny bit", "a hair to the left", "20센티 뒤로" return None # ---------- a correction inside one sentence ("go to start, no, end", "컵 집어, 아니 병") ---------- _FIX_WORD = (r"no+|nope|sorry|i mean|i meant|actually|or rather|rather|make that|scratch that|correction|my bad|oops|" r"아니(?:야|다|요|에요|지)?|아니 아니|정정|그게 아니라|그거 말고|미안(?:해요?)?|죄송해요|죄송합니다") _FIX_PAD = r"oh|uh|um|ah|er|wait|hold on|hang on|아|어|음|잠깐만?" FIX = re.compile(rf"(?:^|(?<=[\s,.;!?]))(?:(?:{_FIX_PAD}|{_FIX_WORD})(?![\w'가-힣])\s*[,.;!?]*\s*)*" rf"(?:{_FIX_WORD})(?![\w'가-힣])(?!\s+(?:thanks|thank|problem|one|more|way|matter|need|longer|rush|hurry|" rf"worries|pressure)\b)\s*[,.;!?]*\s*(?:(?:{_FIX_PAD}|{_FIX_WORD})(?![\w'가-힣])\s*[,.;!?]*\s*)*") _STRONG_NO = re.compile(r"\b(?:no+|nope)\b|아니") FIX_CANCEL = re.compile(r"^\W*(?:never ?mind|forget (?:it|that|about it)|cancel(?: that| it)?|nothing|don'?t(?: do it| bother)?|" r"no need|됐어요?|됐다|됐습니다|괜찮아요?|취소(?:해 ?줘|해요?)?|하지 ?마(?:세요)?|아무것도 하지 마(?:세요)?|관둬요?|" r"말아 ?줘|가지 마(?:세요)?)\W*$") _FIX_DIR = r"\b(?:left|right|forward|ahead|back(?:wards?)?|up|down)\b|왼쪽|오른쪽|앞|뒤|위|아래" def _fix_kinds(t, markers): """The values in t a correction may replace: {kind: [match, ...]}: place, distance, angle, direction, object, colour.""" names = sorted((re.escape(m.lower()) for m in markers if len(m) > 1), key=len, reverse=True) pats = {"place": rf"(? "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 if re.search(r"\b(?:say|tell|announce)\b|말해|전해|[\"“”]", text, re.I) or \ re.search(r"\b(?:stop|halt|freeze|don'?t move)\b|멈춰|정지|그만|스톱|움직이지 ?마|거기 ?서", text, re.I): return text # a message to say may hold any words; a stop always wins t = wording.norm(text, markers) end = re.search(r"[\s,.;!?]+(?:(?:oh|uh|um|아|음)\W+)?(?:never ?mind|forget (?:it|that|about it)|cancel (?:that|it)|" r"(?:아니\s*)?(?:됐어요?|됐다|취소))\W*$", t) if end and t[:end.start()].strip(" ,.;!?") and not FIX.search(t[:end.start()]) and _reads(t[:end.start()], markers): return "" # "go to the stage, never mind": taken back for _ in range(3): m = next((m for m in FIX.finditer(t) if m.start() > 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) if not _reads(left, markers) and not {"distance", "angle", "direction"} & set(_fix_kinds(left, markers)): 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) 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 keep = left[:left.rfind(clauses[-1])].strip(" ,.;!?") if len(clauses) > 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 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"} and "object" in lk): 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():] 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: 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(" ", t)).strip() return re.sub(r"\b(the|a|to) \1\b", r"\1", 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 = unfill(wording.norm(text, markers)) for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them" t = re.sub(rf"\b{word}\b", digit, t) return t def _place_re(markers): """Place words; other marker names on the map ("final", "lobby") are matched as they are.""" extra = [re.escape(m.lower()) for m in markers if not re.fullmatch(r"p\d+|home", m.lower()) and len(m) > 2] 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 next((mk for mk in markers if mk.lower() == name), None) def _as_place(name): return name if name in ("here", None) else {"marker": name} 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 if "dest" not in out and re.search(r"\b(bring|get|fetch|give) (it |that |this )?(to )?me\b|\bto me\b|가져와|가지고 ?와|갖다 ?줘", t): out["dest"] = "here" if re.search(rf"\b(put|place|leave|set) (it|that|this|the \w+)\b.*\b(on|onto) (the )?({_TABLE})\b|\bplace\b" rf"|놔|놓아|놓고|둬", t): 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|(? 1: 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 re.fullmatch(r"p\d+", word) and not close: return no_place_say(word, markers) return None def fetch_problems(task): """'object' / 'place' (source) / 'dest': what is still missing or unknown in a task.""" return [p for p, f in (("object", "object"), ("place", "source"), ("dest", "dest")) if task.get(f) is None] def parse_fetch(text, markers=()): """'bring me the apple from p1' -> (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.)") 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", "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")) # "작은 컵", "왼쪽에 있는 컵", "가까이 있는 컵" _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 and got != ["pick", "give"]: # not "give me the cup" (picked first when the hand is empty) 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 = _mentions(text, markers), dict(task) if field in ("source", "dest") and not {"source", "dest"} & set(m): p = re.search(_place_re(markers), _norm(text, markers)) if p: m[field] = _as_place(_resolve(p, markers)) changed = [k for k, v in m.items() if task.get(k) != v and not (k == "colour" and "object" not in m)] for k in changed: task[k] = m[k] return task, changed _YES = (r"yes|yeah|yep|yup|ok|okay|alright|all right|sure|of course|exactly|absolutely|perfect|sounds good|right|correct|" r"that'?s (?:right|correct|it)|(?:you'?re|you are) (?:right|correct)|go ahead|go on|let'?s go|let'?s do (?:it|that)|" r"go|do (?:it|that)|please|네|예|응|어|맞아요?|맞습니다|맞네요?|좋아요?|그래요?|가자|가요|해 ?줘요?|해 ?주세요|" r"부탁해요?") # longer phrases before their first word ("go ahead" before "go") _NO = r"no|nope|wrong|not right|아니요?|아뇨|아니에요|틀렸어요?" def confirm_answer(text): """The answer to "Is that right?": 'yes', 'no' (alone), 'cancel', 'correction' (more words), or None.""" t = _norm(text).strip(" .,!?") if re.search(r"\b(cancel|never ?mind|forget it|stop|don'?t)\b|취소|됐어|그만|하지 ?마", t): return "cancel" rest, said = t, set() while True: m = re.match(rf"({_NO})(?![a-z가-힣])[\s,.!]*|({_YES})(?![a-z가-힣])[\s,.!]*", rest) if not m or not m.group(0): break said.add("no" if m.group(1) else "yes") rest = rest[m.end():] if rest.strip(" ,.!?"): return "correction" return "no" if "no" in said else ("yes" if said else None) UNSURE = re.compile(r"\b(not sure|don't know|do not know|don't have (any )?(information|details|data)|" r"do not have (any )?(information|details|data)|no information|can't (tell|say|find)|cannot (tell|say|find)|" r"ask a staff|i'm afraid i|my knowledge|would you like me to (search|look))\b|" r"모르|알 수 없|알지 못|정보(가|는|를)? ?(없|가지고 있지 않)|가지고 있지 않|확실하지|알려 드릴 수 없", re.I) QUESTION_START = re.compile(r"^\s*(where|what|how|why|when|which|who|do you|does|is|are|can i|could i)\b|어디 ?(있|에 있)|" r"(어디|뭐|왜|언제|몇)[^ ]*\s*\?*\s*$", re.I) # a question about a place, not a command ABILITY_Q = re.compile(r"(?[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?.!~]*$") # "그럼 부산은?": 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 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 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 "") class Brain: def __init__(self): self.history = [] # [(question, answer)] self.last_lookup = None # the last question answered from the internet self.last_facts = "" # ... and what was found for it (a follow-up is answered from it too) self.lookup_topic = "" # what the last lookup that was not a follow-up searched for self.weather_at = "" # the place of the last weather question in this talk ("" = here) def weather_place(self, target, text=""): """Where a weather lookup is for: a place not named ("내일 비 와?" after Jeju's weather) is the place of the last weather question in this talk; "here" / "여기" is here.""" if target or HERE_WORD.search(text): self.weather_at = target return self.weather_at def lookup_about(self, target, about, text=""): """What lumi.not_online reads for a lookup: right after a lookup (or _after's follow-up of it, "What time does Lotte World open? How much is a ticket?") the question looked up, so the ticket is Lotte World's, not this event's; words that name this place ("here", "the toilets") are read alone.""" if not (self.last_lookup and self.history and self.history[-1][0] == self.last_lookup or self.last_lookup and target.startswith(self.last_lookup)): return about return text if THIS_PLACE.search(text or about) else self.last_lookup def answer(self, question): 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 = "\n\n".join(f"[{src}]\n{t}" for _, src, t in hits) or "(no matching notes)" 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.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(about, on_task=bool(now) and 'not doing any task' not in now)}" f"Now it is {now_line()}." + f"\n\nVisitor: {text}\n\n" + self._fragment_hint(text) + f"(Reply in {lang}.)"}) buf, full, header, said = "", "", None, [] stream, retried = _stream(messages), False 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) buf = rest if NONE_LINE.match(first) and LOOKUP_ACTION.match(rest.lstrip()): first = re.search(r"search|weather", rest).group(0) # read as the action, never said header = self._after(self._action(first, text, markers), text) if header is None: # the model skipped the ACTION line header, buf = self._after({"action": "none", "target": ""}, text), first + " " + buf if header["action"] == "unclear" and not retried and has_meaning(text) and \ not other_latin_language(text): # 26b called short or broken but clear words unclear stream.close() retried, header, buf, full = True, None, "", "" messages[-1]["content"] += UNCLEAR_RETRY stream = _stream(messages) continue 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 parts = SENTENCE_END.split(buf) for sentence in parts[:-1]: if sentence.strip() and not (said and HELP_OFFER.search(sentence)): said.append(spoken(sentence.strip(), lang)) yield said[-1] buf = parts[-1] except Exception: if header is None: yield {"action": "none", "target": ""} header = {} buf += " Sorry, could you say that again?" if header is None: # very short reply on a single line (or two) first, _, rest = buf.partition("\n") header = self._after(self._action(first, text, markers), text) yield header or {"action": "none", "target": ""} buf = rest if header else buf if buf.strip() and not (said and HELP_OFFER.search(buf)): said.append(spoken(buf.strip(), lang)) yield said[-1] 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 "손 흔들 줄 알아?") self.history.append((text, full.strip())) 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.""" last = self._last_said() if self.history else "" part = SAME_ABOUT.match(text) or KO_SAME_ABOUT.match(text) if last and part: # "What about your cameras?" / "카메라는요?" after "can I wipe you?" return (f"(The visitor's question \"{self.history[-1][0]}\" asked again, now about {part.group(1)}: answer " f"that question for it, not other facts about it.)\n") if not last or len(text.split()) > FRAGMENT_WORDS or not SHORT_Q.search(text) or is_backchannel(text) \ or ABOUT_YOU.search(text) or OWN_TOPIC.search(text): return "" 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 not header or not self.history: return header last_q, last_a = self.history[-1] m = re.match(r"\s*\**ACTION\**\s*:\s*(\w+)", last_a) before, action = (m.group(1).lower() if m else ""), header["action"] if action == "sing" and before != "sing" and (not SING_ASK.search(text) or SING_ECHO.match(text)): return {"action": "none", "target": ""} # "Prove it." after "do you have a sense of humour?" if DO_IT.match(text) and action in ("none", "unclear"): asked = "wave" if WAVE_ASK.search(last_q) else "sing" if SING_ASK.search(last_q) else None 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)\b|말해|말씀", text, re.I): 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."} 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): # "Where?", "몇 살이야?", "who's the CEO?" after a lookup return {"action": "search", "target": f"{last_q} {text}"} return header 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(): return None 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 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 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.history[-HISTORY_TURNS:]: 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): # no "ACTION: none" copied from the history said = True yield spoken(sentence.strip(), lang) buf = parts[-1] if spoken(buf.strip(), lang) and not (not said and LOOKUP_ACTION.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 "") + "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"): # a fetch is read by parse_fetch() later target = target.split()[0] if target.split() else "" if action not in ACTION_NAMES: action = "none" say = None if action == "go_to": said, target = target, next((mk for mk in markers if mk.lower() == target.lower()), 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): target = None # "take me to the meeting room" -> p1: a guess, not driven say = no_place_say("that", markers, text) action = "go_to" if target else "none" bare = CALLING.sub("", text) 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)): action, target = "none", "" # "where is your charger?", "손 펼 수 있어요?": a question 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"(? ").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()