diff --git a/assistant/brain.py b/assistant/brain.py index 37c17b0..4c4a3fa 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -49,8 +49,8 @@ Rules: 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, can't do it or don't know which one - they mean: then answer it (say you don't know, that you can't and why, or ask which one) with the action none. + 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. @@ -81,13 +81,16 @@ Rules: 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. "It", "that", "그거" is the + 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). "And you?", "how about you?", "you?", "너는?", + 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 tired. You?" -> "I don't get tired, my battery lasts about 10 - hours."; "저는 서울에서 왔어요. 루미는요?" -> "저는 쿳션 컴퍼니에서 만들어졌어요."). A correction ("no, I meant + 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 @@ -602,7 +605,8 @@ def intent(text, markers=()): 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"어떻게|왜|혼자|스스로|\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: @@ -1321,7 +1325,9 @@ REFERS_BACK = re.compile(r"\b(it|they|them|those|these|another|one more|one abou re.I) # about the last answer HELP_OFFER = re.compile(r"\b(how|what) (can|may) i (help|assist|do for) you\b|\bis there anything (else )?i can\b|" r"\banything else i can (help|do)\b|\blet me know if (there'?s|there is|you need) anything\b|" - r"무엇을 도와|어떻게 도와|뭘 도와|도와드릴 (?:수 있는 )?일|도와 ?드릴까요", re.I) # owner: never tacked on after an answer + r"무엇을 도와|어떻게 도와|뭘 도와|도와드릴 (?:수 있는 )?일|도와 ?드릴까요|" + r"\bfeel free to ask\b|\bif you have (?:any )?(?:more |other )?questions\b|" + r"궁금한 (?:게|것이|점이?) (?:더 |또 )?(?:있으시면|생기면|있으면)|언제든(?:지)? (?:물어|말씀)", re.I) # owner: never tacked on after an answer SAY_AGAIN = re.compile(r"\b(say (it|that) again|repeat (it|that|please)|again,? please|one more time|come again|" r"pardon|say again)\b|^\s*again\s*\??\s*$|다시 ?(한 ?번|말해|말씀|해 ?줘)|한 ?번 ?더|" r"^\s*뭐라고(요)?\s*\??\s*$", re.I) @@ -1415,6 +1421,8 @@ def language(text): 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 +FRAGMENT_CHARS = 160 # chars of the last answer's first sentence shown with a fragment LOOKUP_BEFORE_CHARS = 1500 # chars of the last lookup's results given again with a follow-up ("how old is she?") 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 @@ -1534,7 +1542,7 @@ class Brain: 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" + f"\n\nVisitor: {text}\n\n" + self._fragment_hint(text) + f"(Reply in {lang}.)"}) buf, full, header, said = "", "", None, [] stream, retried = _stream(messages), False @@ -1593,6 +1601,15 @@ class Brain: 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 "" + if not last or len(text.split()) > FRAGMENT_WORDS or not SHORT_Q.search(text) or is_backchannel(text) \ + or ABOUT_YOU.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 diff --git a/assistant/lumi.py b/assistant/lumi.py index 80dd1cb..04e274b 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -196,7 +196,11 @@ EMPTY_HAND = re.compile(r"\b(give|hand|pass) (it|that|this)( (over|back|here))?( EMPTY_HAND_SAY = {"en": "I'm not holding anything right now.", "ko": "지금은 손에 아무것도 들고 있지 않아요."} ASK_PREFIX = re.compile(r"\b(do|did) you (know|happen to know)\b|\b(can|could) you (tell|find out|look up|check)( me)?\b|" r"아세요|알아요|알아\?", re.I) # "do you know who won?" is not about Lumi -ASKS_MORE = re.compile(r"\?|\b(but|can|could|what|how|where|why|when|who)\b|근데|그런데|뭐|어떻게|어디|언제|누구", re.I) +ASKS_MORE = re.compile(r"\?|\b(but|can|could|what|how|where|why|when|who|one more)\b|근데|그런데|뭐|어떻게|어디|언제|누구|하나만 더|" + r"물어볼게|물어봐도", re.I) +THANKS_REST = re.compile(r"\b(?:a bunch|a lot|so much|very much|lovely|great|nice|cool|good to know|again|that was \w+|" + r"for (?:the|that|this|telling) \w+)\b|감사요|잘 들었어요|잘 알겠어요|[~!.,\s요]", re.I) + # left of "Lovely, thanks!", "고마워요~" after the thanks: nothing, so only thanks (talk_fate waits) FOREIGN_SCRIPT = re.compile(r"[\u0400-\u04ff\u4e00-\u9fff\u3040-\u30ff]") # Cyrillic, Chinese, Japanese UNSURE_LOOKUP = False # look up what the model says it is not sure of: on for gemma4:e4b, which said "not sure" # instead of choosing search; gemma4:26b chooses search itself, and its "not sure" answers @@ -2588,8 +2592,8 @@ def says_goodbye(text): """"thank you for your time", "okay, bye", "수고하세요": the talk is over (not "thanks, but where is...?"). "thank you", "got it, thanks", "네 감사합니다" alone are not: often only "heard you" (talk_fate waits).""" if brain_mod.is_closing(text) and not DONE_WORDS.search(text) and not FAREWELL_WORDS.search(THANKS.sub(" ", text)) or \ - brain_mod.to_someone_else(text): # "Okay kids, say thank you to the robot." - return False + brain_mod.to_someone_else(text) or THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)): + return False # "Okay kids, say thank you to the robot.", "Thanks a bunch." return bool(FAREWELL_ONLY.match(text) or FAREWELL_WORDS.search(text) and not ASKS_MORE.search(text) and len(text.split()) <= 8 and not brain_mod.intent(text) and not brain_mod.hand_request(text, False) and not COMMAND_START.search(brain_mod.CALLING.sub("", text))) # "grab the cup, thanks": an order @@ -2601,8 +2605,9 @@ def talk_fate(text): (anything else; "I see", "got it", "그렇구나", "알겠어요" are understanding, "I see?", "그래요?" a check: answered).""" if says_goodbye(text): return "end" - if brain_mod.is_closing(text) and (THANKS.search(text) or not brain_mod.UNDERSTOOD.search(text)): - return "wait" + if brain_mod.is_closing(text) and (THANKS.search(text) or not brain_mod.UNDERSTOOD.search(text)) or \ + THANKS.search(text) and not THANKS_REST.sub("", THANKS.sub("", text)): + return "wait" # "Thanks a bunch.", "Good to know. Thanks.", "고마워요~" return "talk" diff --git a/assistant/web.py b/assistant/web.py index df316bf..2ae2517 100644 --- a/assistant/web.py +++ b/assistant/web.py @@ -152,18 +152,17 @@ def _distance(query): """The straight-line distance between the two places a "how far" question names (one: from Seoul), or ''.""" if not HOW_FAR.search(query): return "" - for form in BETWEEN: + for form in BETWEEN: # the first form whose two places are both found m = form.search(query) - if m: - names = m.groups() if len(m.groups()) == 2 else (DEFAULT_PLACE, m.group(1)) - break + if not m: + continue + names = m.groups() if len(m.groups()) == 2 else (DEFAULT_PLACE, m.group(1)) + a, b = (_place(DEFAULT_PLACE if re.fullmatch(r"here|this place|you|여기", n.strip(), re.I) else n.strip()) + for n in names) + if a and b and not any(p.get("population", 0) < TOWN and p not in FIXED for p in (a, b)): # "the moon": + break # a French village else: return "" - a, b = (_place(DEFAULT_PLACE if re.fullmatch(r"here|this place|you|여기", n.strip(), re.I) else n.strip()) - for n in names) - if not a or not b or any(p.get("population", 0) < TOWN and p not in FIXED for p in (a, b)): # "the moon": a - # village in France - return "" la1, lo1, la2, lo2 = map(math.radians, (a["latitude"], a["longitude"], b["latitude"], b["longitude"])) km = 2 * 6371 * math.asin(math.sqrt(math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2)) @@ -191,13 +190,11 @@ BROWSER = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KH "Safari/537.36", "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7"} WIKI_UA = {"User-Agent": "LumiRobot/1.0 (https://cutshion.com; cutshion@cutshion.com)"} # Wikimedia answers 429 # (too many requests) to a browser or bare robot name; a name with a contact it serves -SEARCH_WAIT_S = 2.0 # s the search page and Wikipedia get together; a slower one is left out (both ~0.7 s) -NEWS_WAIT_S = 1.2 # s from the start the headlines get (Google News 0.4-1.6 s): the answer waits on them; - # SEARCH_WAIT_S when the news is what is asked (NEWS_ASKED) -NEWS_ASKED = re.compile(r"\bnews\b|headlines?|happening|going on|뉴스|소식", re.I) -PAGE_CHARS = 1200 # chars of the search page given to the LLM (it reads ~1300 tokens a second; Korean - # is ~1 token a char): the answer box and the first sites hold the answer -BLOCK_CHARS = 500 # ... at most this much from one part of the page (an answer box, the news, one site) +SEARCH_WAIT_S = 2.0 # s all sources get together; a slower one is left out (Naver and Wikipedia ~0.7 s, + # Google News 0.4-1.6 s; the fetch runs while "Let me check." is said) +PAGE_CHARS = 1500 # chars of the search page given to the LLM (it reads ~1300 tokens a second; Korean + # is ~1 token a char); 1200 lost answers further down (Apple's founding year) +BLOCK_CHARS = 600 # ... at most this much from one part of the page (an answer box, the news, one site) WIKI_CHARS = 500 # chars of the Wikipedia summary NEWS_ITEMS = 3 # headlines given, only for questions about what changes (NEWSY) SEARCH_TTL = 600 # s a search result is reused (visitors ask the same things; follow-ups search again) @@ -225,8 +222,8 @@ KO_ASK = ((r"\bhow old\b|\bage\b|\bbirthday\b|\bwhen was \w+( \w+)? born\b", " (r"\bhow tall\b|\bheight\b", "키"), (r"\bstocks?( price)?\b|\bshares?( price)?\b", "주가"), (r"\bindex\b|(?=\b(nasdaq|dow jones|kospi|kosdaq|s&p 500)\b)", "지수"), (r"\bstandings?\b|\bfirst place\b|\bin first\b|\branking\b", "순위"), - (r"\bscore\b|\bresult\b|\blast (game|match)\b|\bhow did\b", "경기 결과"), - (r"\bopening hours\b|\bwhat time does\b|\bwhen does\b", "영업시간")) + (r"\bscore\b|\bresult\b|\blast (game|match)\b|\bhow did\b", "경기 결과")) + # not opening hours: "Louvre 영업시간" brings Korean shops named Louvre # English question -> the Korean word for Naver's answer box (ko_box_query) ASK_WORDS = re.compile(r"\b(what'?s|what|who'?s|who|whom|which|where|when|why|how|is|are|was|were|the|a|an|do|does|did|" r"can|could|you|tell me|please|lumi|right now|i|me|my|and|he|she|his|her|it|its|they|their)\b|" @@ -278,7 +275,7 @@ def _naver(query, boxes_only=False): def ko_box_query(query): - """An English question about a person, a share, an index, a team or a place as its names and the Korean word + """An English question about a person, a share, an index or a team as its names and the Korean word that brings Naver's answer box ("How old is Taylor Swift?" -> "Taylor Swift 나이": birth date and age; the English words give only web pages), or None.""" if re.search(r"[가-힣]", query): @@ -286,7 +283,7 @@ def ko_box_query(query): for asked, word in KO_ASK: if re.search(asked, query, re.I): names = re.sub(asked, " ", query, flags=re.I) - names = re.sub(r"'s\b|\b(today|now|currently|doing|in|at|of|for|right|this|last|latest|current|much|" + names = re.sub(r"'s\b|'|\b(today|now|currently|doing|in|at|of|for|right|this|last|latest|current|much|" r"open|close|first|price|their|team)\b", " ", names, flags=re.I) names = re.sub(r"\s+", " ", ASK_WORDS.sub(" ", names)).strip() return f"{names} {word}" if names else None @@ -418,11 +415,7 @@ def search(query, n=NEWS_ITEMS): jobs |= {"Search results": _pool.submit(_naver, keywords(query)), "Wikipedia": _pool.submit(_wikipedia, q, lang)} if NEWSY.search(query): # "how old is Musk?" got "80-year-old Musk's father" jobs["News headlines"] = _pool.submit(_news, q, lang, n) - t0 = time.time() - wait([j for name, j in jobs.items() if name != "News headlines"], timeout=SEARCH_WAIT_S) - if "News headlines" in jobs: - wait([jobs["News headlines"]], timeout=max(0.0, (SEARCH_WAIT_S if NEWS_ASKED.search(query) else NEWS_WAIT_S) - - (time.time() - t0))) + wait(jobs.values(), timeout=SEARCH_WAIT_S) found = {} for name, job in jobs.items(): try: @@ -434,7 +427,9 @@ def search(query, n=NEWS_ITEMS): found["Search results"] = _duckduckgo(keywords(query)) except Exception: pass - text = with_ages("\n\n".join(f"{name}:\n{t}" for name, t in found.items() if t)) + order = sorted(found, key=lambda name: name not in ("Rates and prices", "Distance", "Answer box", "News headlines")) + text = with_ages("\n\n".join(f"{name}:\n{found[name]}" for name in order if found[name])) # the news before + # old pages: "지금 대통령" got the president of 2024 if not text: return None if not online() else "No results." _searched[key] = (time.time(), text) diff --git a/tests/dialogue_check.py b/tests/dialogue_check.py index 0d3bedf..16b1b07 100644 --- a/tests/dialogue_check.py +++ b/tests/dialogue_check.py @@ -115,6 +115,8 @@ def action_ok(expect, got): return True # the reason the fingers can't take it if alt == "none" and got in ("none", "chat", "status"): return True + if alt == "end" and got == "chat": + return True # "Thanks." alone: lumi ends after the silence if alt == "mission" and got.startswith("action:fetch"): return True # the plain fetch does it (steps.is_mission is False) if got == "empty_hand" and alt in ("none", "give", "place", "fetch"): diff --git a/tests/test_web.py b/tests/test_web.py index f462a0e..326c204 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -13,10 +13,10 @@ for q, words in {"How tall is Son Heung-min?": "height Son Heung-min", "How long "오늘 달러 환율 얼마야?": "오늘 달러 환율 얼마야?"}.items(): assert web.keywords(q) == words, (q, web.keywords(q)) -# English questions about a person, a share, an index, a team, a place also ask Naver with the Korean word of its box +# English questions about a person, a share, an index or a team also ask Naver with the Korean word of its box for q, box in {"How old is Taylor Swift?": "Taylor Swift 나이", "What is Nvidia's stock price today?": "Nvidia 주가", "What's the Nasdaq doing today?": "Nasdaq 지수", "How did LAFC do in their last match?": "LAFC 경기 결과", - "What time does Lotte World open?": "Lotte World 영업시간", "Who is the pope?": None, + "What time does the Louvre open?": None, "Who is the pope?": None, "손흥민 나이": None}.items(): assert web.ko_box_query(q) == box, (q, web.ko_box_query(q)) @@ -94,6 +94,7 @@ web._get = lambda url, timeout=6, headers=web.UA: '{"results": [{"name": "Moon-s assert web._distance("How far away is the moon?") == "" and web._distance("How tall is the Eiffel Tower?") == "" assert "Busan to Seoul" in web._distance("Busan distance from Seoul") +assert "Incheon Airport to Seoul" in web._distance("Incheon Airport distance from Seoul") # not "Incheon" "Airport" # respond_from: an action line the model writes instead of the answer is never said; all of it: asked once more outs = iter([["search New York", " weather"], ["It is 15 degrees", " in New York."]])