-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmjp.py
More file actions
1008 lines (834 loc) · 35.1 KB
/
Copy pathmjp.py
File metadata and controls
1008 lines (834 loc) · 35.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import logging
import re
import sys
import traceback
from logging.handlers import RotatingFileHandler
from pathlib import Path
from config import load_config
logger = logging.getLogger("luna")
_cfg = load_config()
def terminal_debug(message):
print(message, flush=True)
from stt.stt import listen
from llm.jp_only import ask_llm_jp
from tts.voicevox import tts
from audio.play_audio import play
from iot.iot_controller import try_handle_iot_command
from agent_tools import (
add_reminder,
add_todo,
classify_file_operation,
complete_todo,
delete_note,
delete_reminder,
delete_todo,
detect_file_query,
detect_news_query,
detect_article_followup_query,
detect_reminder_query,
detect_time_query,
detect_vision_query,
detect_web_search_query,
extract_search_query,
get_article_context_from_news,
get_current_time_context,
get_pending_alerts,
handle_vision_tool,
list_notes,
list_reminders,
list_todos,
open_search_in_browser,
parse_reminder,
queue_pending_alerts,
read_daily_log,
save_note,
search_news,
search_web,
should_open_browser,
write_daily_log,
)
from memory.memory_manager import (
add_stm,
clear_active_topic,
get_active_topic,
get_stm,
get_ltm,
add_ltm,
set_active_topic,
)
from memory.memory_command import (
detect_memory_command,
extract_memory_content,
classify_memory,
)
FOLLOW_UP_MARKERS = [
"yang tadi",
"tadi",
"barusan",
"sebelumnya",
"kok tahu",
"kok bisa",
"maksudnya",
"yang itu",
"itu siapa",
"itu apa",
"terus",
"lanjut",
"lanjutkan",
"ulang",
"jelasin lagi",
"kenapa begitu",
"topik itu",
"berita itu",
"artikel itu",
"lebih detail",
"ringkasannya",
"intinya",
"maksud berita itu",
]
STOPWORDS = {
"yang", "dan", "atau", "dari", "untuk", "dengan", "karena", "kalau",
"juga", "sudah", "udah", "saja", "aja", "nih", "dong", "deh",
"aku", "saya", "kamu", "dia", "itu", "ini", "ada", "jadi",
"banget", "bisa", "gitu", "begitu", "tapi", "biar", "buat",
"apakah", "gimana", "bagaimana", "kenapa", "mengapa", "siapa", "apa",
"berita", "headline", "news", "terbaru", "hari", "today", "info",
"tentang", "cari", "search", "carikan", "cek", "tolong", "dong",
"berapa", "turun", "naik", "sekarang", "lagi", "baru",
}
PREPARED_AUDIO_TASKS = {}
# Async callable set by api.py to broadcast raw search payloads to the web client.
# Signature: async (payload: dict) -> None
_search_result_callback = None
# Normalize text so routing and memory heuristics stay consistent.
def normalize_text(text):
return " ".join(str(text).lower().split()).strip()
# Extract meaningful keywords for context selection.
def extract_keywords(text):
tokens = re.findall(r"\w+", normalize_text(text), flags=re.UNICODE)
return {
token for token in tokens
if len(token) >= 3 and token not in STOPWORDS and not token.isdigit()
}
# Detect whether the latest query depends on prior conversation.
def is_follow_up_query(user_text):
normalized = normalize_text(user_text)
return any(marker in normalized for marker in FOLLOW_UP_MARKERS)
# Select only the most relevant recent STM messages for prompting.
def select_context_messages(stm, user_text, max_messages=4):
if not stm:
return []
history = list(stm)
normalized_user = normalize_text(user_text)
if history and history[-1]["role"] == "user" and normalize_text(history[-1]["content"]) == normalized_user:
history = history[:-1]
if not history:
return []
if is_follow_up_query(user_text):
return history[-max_messages:]
current_keywords = extract_keywords(user_text)
if not current_keywords:
return []
selected_reversed = []
allow_one_adjacent = False
for message in reversed(history):
message_keywords = extract_keywords(message["content"])
has_overlap = bool(message_keywords & current_keywords)
if has_overlap:
selected_reversed.append(message)
allow_one_adjacent = True
elif allow_one_adjacent:
selected_reversed.append(message)
allow_one_adjacent = False
if len(selected_reversed) >= max_messages:
break
return list(reversed(selected_reversed))
# Keep tool prompts isolated unless the user is clearly continuing the same topic.
def select_tool_context_messages(user_text, context_messages, active_topic):
if not context_messages:
return []
if is_follow_up_query(user_text) or should_use_active_topic(user_text, active_topic):
return context_messages
return []
# Persist explicit memory commands without changing the existing memory model.
def remember_user_memory(user_text):
if not detect_memory_command(user_text):
return None
memory_text = extract_memory_content(user_text)
if not memory_text:
return "うん、覚えたいことをもう少しだけ詳しく教えてね。"
category = classify_memory(memory_text)
existing_memories = get_ltm()
existing_values = {item.casefold() for item in existing_memories[category]}
if memory_text.casefold() in existing_values:
return "うん、そのことはもうちゃんと覚えているよ。"
add_ltm(category, memory_text)
return "うん、ちゃんと覚えておくね。"
# Build the active-topic prompt block from stored article context.
def build_active_topic_block(active_topic):
prompt = "【現在の話題】\n"
prompt += f"- タイトル: {active_topic.get('title', '')}\n"
if active_topic.get("source"):
prompt += f"- ソース: {active_topic['source']}\n"
if active_topic.get("published_at"):
prompt += f"- 日時: {active_topic['published_at']}\n"
if active_topic.get("summary"):
prompt += f"- 要点: {active_topic['summary']}\n"
if active_topic.get("content_excerpt"):
prompt += f"- 記事内容: {active_topic['content_excerpt']}\n"
if active_topic.get("headlines"):
for index, item in enumerate(active_topic["headlines"], start=1):
prompt += f"- 関連見出し{index}: {item.get('title', '')} ({item.get('source', '')})\n"
prompt += "\n"
return prompt
# Decide whether the stored active topic should influence the next response.
def should_use_active_topic(user_text, active_topic):
if not active_topic:
return False
if detect_article_followup_query(user_text) or is_follow_up_query(user_text):
return True
active_text = " ".join([
active_topic.get("title", ""),
active_topic.get("summary", ""),
active_topic.get("content_excerpt", ""),
])
return bool(extract_keywords(user_text) & extract_keywords(active_text))
# Build the base conversation prompt for normal LLM replies.
def build_prompt(context_messages, ltm, user_text, active_topic=None):
prompt = ""
if ltm["facts"] or ltm["preferences"]:
prompt += "【長期記憶】\n"
for fact in ltm["facts"]:
prompt += f"- {fact}\n"
for preference in ltm["preferences"]:
prompt += f"- {preference}\n"
prompt += "\n"
if context_messages:
prompt += "【直前の話題】\n"
for message in context_messages:
speaker = "ユーザー" if message["role"] == "user" else "ルナ"
prompt += f"- {speaker}: {message['content']}\n"
prompt += "\n"
if active_topic and should_use_active_topic(user_text, active_topic):
prompt += build_active_topic_block(active_topic)
prompt += (
"【応答方針】\n"
"- 長期記憶はユーザー情報としてのみ使ってください。\n"
"- 直前の話題が今の質問と無関係なら引きずらないでください。\n"
"- 現在の話題が与えられている場合は、その記事内容の範囲で答えてください。\n"
"- 過去の返答に誤りや不自然さがあっても、そのまま繰り返さず自然に言い直してください。\n"
"- 分からない事実は作らず、今の質問にいちばん自然な返答をしてください。\n\n"
"【現在のユーザー入力】\n"
f"{user_text}\n\n"
"ルナの返答:"
)
return prompt
# Build a prompt that explains tool output to the LLM.
def build_tool_prompt(user_text, tool_name, tool_payload, context_messages, ltm):
prompt = ""
if ltm["facts"] or ltm["preferences"]:
prompt += "【長期記憶】\n"
for fact in ltm["facts"]:
prompt += f"- {fact}\n"
for preference in ltm["preferences"]:
prompt += f"- {preference}\n"
prompt += "\n"
if context_messages:
prompt += "【直前の話題】\n"
for message in context_messages:
speaker = "ユーザー" if message["role"] == "user" else "ルナ"
prompt += f"- {speaker}: {message['content']}\n"
prompt += "\n"
prompt += f"【外部ツール】\n- 使用したツール: {tool_name}\n"
if tool_name == "time":
prompt += (
f"- 日付: {tool_payload['date']}\n"
f"- 時刻: {tool_payload['time']}\n"
f"- 曜日: {tool_payload['day_name']}\n"
f"- タイムゾーン: {tool_payload['timezone']}\n\n"
)
elif tool_name == "news_search":
prompt += f"- 検索クエリ: {tool_payload['query']}\n"
if tool_payload.get("results"):
for index, result in enumerate(tool_payload["results"], start=1):
prompt += f"- ニュース{index}: {result['title']}\n"
prompt += f" ソース: {result.get('source', '不明')}\n"
if result.get("published_at"):
prompt += f" 日時: {result['published_at']}\n"
if result.get("url"):
prompt += f" URL: {result['url']}\n"
elif tool_payload.get("message"):
prompt += f"- エラー: {tool_payload['message']}\n"
prompt += "\n"
elif tool_name == "web_search":
prompt += f"- 検索クエリ: {tool_payload['query']}\n"
if tool_payload.get("results"):
for index, result in enumerate(tool_payload["results"], start=1):
prompt += f"- 結果{index}: {result['title']}\n"
if result.get("snippet"):
prompt += f" 要約: {result['snippet']}\n"
if result.get("url"):
prompt += f" URL: {result['url']}\n"
elif tool_payload.get("message"):
prompt += f"- エラー: {tool_payload['message']}\n"
prompt += "\n"
prompt += (
"【応答方針】\n"
"- 外部ツールで得た最新情報を優先してください。\n"
"- 事実は外部ツールの内容だけを使い、推測で補わないでください。\n"
"- ニュース・Web検索の場合は、見つかった見出しや要点を自然な日本語でまとめてください。\n"
"- 「何が起きているか」を軸に、背景や理由にも一言触れると良いです。\n"
"- 少なくとも一件は具体的な話題名や見出しを含めてください。\n"
"- 『調べるね』『探してみるね』のような予告だけで終わってはいけません。\n"
"- 検索結果が少ない場合でも、分かる範囲だけを丁寧に伝えてください。\n\n"
"【現在のユーザー入力】\n"
f"{user_text}\n\n"
"ルナの返答:"
)
return prompt
# Trim long search snippets while preserving readability.
def clean_search_text(text, limit=140):
cleaned = " ".join(str(text).split()).strip()
if len(cleaned) <= limit:
return cleaned
return cleaned[: limit - 1].rstrip() + "…"
# Build the article-summary prompt for detailed news follow-ups.
def build_article_summary_prompt(user_text, article_payload, context_messages, ltm):
prompt = ""
if ltm["facts"] or ltm["preferences"]:
prompt += "【長期記憶】\n"
for fact in ltm["facts"]:
prompt += f"- {fact}\n"
for preference in ltm["preferences"]:
prompt += f"- {preference}\n"
prompt += "\n"
if context_messages:
prompt += "【直前の話題】\n"
for message in context_messages:
speaker = "ユーザー" if message["role"] == "user" else "ルナ"
prompt += f"- {speaker}: {message['content']}\n"
prompt += "\n"
prompt += "【記事情報】\n"
prompt += f"- タイトル: {article_payload.get('title', '')}\n"
prompt += f"- ソース: {article_payload.get('source', '')}\n"
if article_payload.get("description"):
prompt += f"- 概要: {article_payload['description']}\n"
if article_payload.get("content"):
prompt += f"- 本文抜粋:\n{article_payload['content'][:4000]}\n"
prompt += "\n"
prompt += (
"【応答方針】\n"
"- 記事の内容を読んだ前提で、日本語で自然に説明してください。\n"
"- まず「何が起きているのか」を1〜2文で明確に伝えてください。\n"
"- 次に「なぜそうなったのか」や「背景・原因」を加えてください。\n"
"- 最後に「どんな影響や意味があるか」を簡潔に触れてください。\n"
"- 全体で3〜5文を目安に、読者が本当に理解できるように話してください。\n"
"- 専門用語や難しい言葉はやさしく言い換えてください。\n"
"- 単なる見出しの繰り返しや「調べてみます」のような返答は不可です。\n\n"
"【現在のユーザー入力】\n"
f"{user_text}\n\n"
"ルナの返答:"
)
return prompt
# Provide a deterministic article summary fallback when the LLM is unhelpful.
def build_article_summary_fallback(article_payload):
title = clean_search_text(article_payload.get("title") or article_payload.get("headline") or "見つかった記事", limit=120)
source = clean_search_text(article_payload.get("source") or "ニュースソース", limit=50)
text = article_payload.get("description") or article_payload.get("content") or title
sentences = [segment.strip() for segment in re.split(r"(?<=[.!?。])\s+", text) if segment.strip()]
snippet = clean_search_text(" ".join(sentences[:2]), limit=180)
return f"うん、{source}の記事を読むと、{title}という内容だったよ。要点は、{snippet}"
# Reject article pages that don't match the requested topic or selected headline.
def is_relevant_article(article_payload, query, headline=""):
if not article_payload.get("ok"):
return False
article_text = " ".join([
article_payload.get("title", ""),
article_payload.get("description", ""),
article_payload.get("content", "")[:600],
])
article_keywords = extract_keywords(article_text)
query_keywords = extract_keywords(query)
headline_keywords = extract_keywords(headline)
if not article_keywords:
return False
if query_keywords and (article_keywords & query_keywords):
return True
headline_overlap = article_keywords & headline_keywords
return len(headline_overlap) >= 2
# Detect placeholder-style LLM replies that should be replaced with fallbacks.
def is_generic_search_reply(reply):
normalized = normalize_text(reply)
generic_markers = [
"調べてみる",
"調べるね",
"探してみる",
"探してみるね",
"見てみるね",
"どんなニュースかな",
"知らないかもしれない",
"聞いたところでしょうか",
]
return any(marker in normalized for marker in generic_markers)
# Run blocking LLM inference off the event loop.
async def ask_llm_async(prompt):
logger.info("Waiting for LLM response...")
return await asyncio.to_thread(ask_llm_jp, prompt)
# Start TTS synthesis in the background for the final text.
def prepare_tts_task(jp_text):
if not jp_text or jp_text in PREPARED_AUDIO_TASKS:
return
if len(PREPARED_AUDIO_TASKS) >= _cfg.tts.cache_max_size:
oldest = next(iter(PREPARED_AUDIO_TASKS))
PREPARED_AUDIO_TASKS.pop(oldest)
logger.info("Generating TTS...")
PREPARED_AUDIO_TASKS[jp_text] = asyncio.create_task(asyncio.to_thread(tts, jp_text))
# Retrieve a prepared TTS task or synthesize on demand.
async def get_audio_path(jp_text):
task = PREPARED_AUDIO_TASKS.pop(jp_text, None)
if task is None:
logger.info("Generating TTS...")
task = asyncio.create_task(asyncio.to_thread(tts, jp_text))
return await task
# Summarize article content asynchronously while preserving fallback behavior.
async def summarize_article_payload(user_text, article_payload, context_messages, ltm):
prompt = build_article_summary_prompt(user_text, article_payload, context_messages, ltm)
logger.debug("[DEBUG ARTICLE PROMPT]\n%s", prompt)
terminal_debug(f"\n[DEBUG ARTICLE PROMPT]\n{prompt}")
reply = await ask_llm_async(prompt)
if reply and not is_generic_search_reply(reply):
return reply
return build_article_summary_fallback(article_payload)
# Build a direct fallback summary for plain web search results.
def build_web_search_fallback(tool_payload):
results = tool_payload.get("results", [])
if not results:
return "ごめんね、いま見つけられた最新情報が少なくて、うまくまとめられなかったよ。"
lines = ["うん、見つかった内容をまとめるね。"]
for index, result in enumerate(results[:2], start=1):
title = clean_search_text(result.get("title") or "新しい話題")
snippet = clean_search_text(result.get("snippet") or "くわしい要約は少なめだったよ。", limit=160)
if index == 1:
lines.append(f"まず一つ目は、{title}。{snippet}")
else:
lines.append(f"次に、{title}。{snippet}")
return " ".join(lines)
# Build a direct fallback summary for news headlines.
def build_news_search_fallback(tool_payload):
results = tool_payload.get("results", [])
if not results:
return "ごめんね、いま確認できる新しいニュースが見つからなかったよ。"
lines = ["うん、今日の話題を短くまとめるね。"]
for index, result in enumerate(results[:3], start=1):
source = clean_search_text(result.get("source") or "ニュースソース", limit=50)
headline = clean_search_text(result.get("title") or "新しいニュース", limit=120)
if index == 1:
lines.append(f"まず一つ目は、{source}で、{headline}。")
elif index == 2:
lines.append(f"次は、{source}で、{headline}。")
else:
lines.append(f"もう一つは、{source}で、{headline}。")
return " ".join(lines)
# Convert tool payloads into a final Japanese answer.
async def answer_with_tool_context(user_text, tool_name, tool_payload, context_messages, ltm):
prompt = build_tool_prompt(user_text, tool_name, tool_payload, context_messages, ltm)
logger.debug("[DEBUG TOOL PROMPT]\n%s", prompt)
terminal_debug(f"\n[DEBUG TOOL PROMPT]\n{prompt}")
reply = await ask_llm_async(prompt)
if reply and not is_generic_search_reply(reply):
return reply
if tool_name == "time":
return f"いまは{tool_payload['date']}の{tool_payload['time']}だよ。"
if tool_name == "news_search":
return build_news_search_fallback(tool_payload)
if tool_name == "web_search":
if tool_payload.get("results"):
return build_web_search_fallback(tool_payload)
return "ごめんね、うまく検索できなかったみたい。"
return "ごめんね、うまく答えをまとめられなかったよ。"
# Build the runtime context needed by routing and prompting.
def build_runtime_context(user_text):
stm = get_stm(limit=_cfg.memory.stm_limit)
ltm = get_ltm()
active_topic = get_active_topic()
context_messages = select_context_messages(stm, user_text, max_messages=_cfg.memory.context_max_messages)
return {
"stm": stm,
"ltm": ltm,
"active_topic": active_topic,
"context_messages": context_messages,
}
# Handle the datetime tool with the shared tool-response pipeline.
async def handle_time_tool(user_text, context):
return await answer_with_tool_context(
user_text,
"time",
get_current_time_context(),
context["context_messages"],
context["ltm"],
)
# Handle the news tool, active topic updates, and browser opening.
async def handle_news_tool(user_text, context):
query = extract_search_query(user_text)
search_payload = search_news(query, max_results=_cfg.tools.news_max_results)
if _search_result_callback and search_payload.get("ok"):
try:
await _search_result_callback({
"kind": "news",
"query": query,
"results": search_payload.get("results", []),
})
except Exception:
pass
article_payload = get_article_context_from_news(search_payload)
tool_context_messages = select_tool_context_messages(
user_text,
context["context_messages"],
context["active_topic"],
)
article_summary_task = None
top_headline = ""
if search_payload.get("results"):
top_headline = search_payload["results"][0].get("title", "")
if article_payload.get("ok") and not is_relevant_article(article_payload, query, top_headline):
article_payload = {
"ok": False,
"error": "irrelevant_article",
"message": "Resolved article is not relevant to the selected headline.",
}
if article_payload.get("ok"):
article_summary_task = asyncio.create_task(
summarize_article_payload(
user_text,
article_payload,
tool_context_messages,
context["ltm"],
)
)
else:
clear_active_topic()
if should_open_browser(user_text):
first_result_url = None
if article_payload.get("ok"):
first_result_url = article_payload.get("url")
elif search_payload.get("results"):
first_result_url = search_payload["results"][0].get("url")
search_payload["browser_opened"] = open_search_in_browser(query, first_result_url=first_result_url)
jp_text = await answer_with_tool_context(
user_text,
"news_search",
search_payload,
tool_context_messages,
context["ltm"],
)
if article_summary_task:
article_summary = await article_summary_task
topic_payload = {
"title": article_payload.get("title") or article_payload.get("headline", ""),
"source": article_payload.get("source", ""),
"url": article_payload.get("url", ""),
"summary": article_summary,
"content_excerpt": clean_search_text(
article_payload.get("content") or article_payload.get("description") or "",
limit=900,
),
"query": query,
"published_at": article_payload.get("published_at", ""),
"headlines": [
{
"title": item.get("title", ""),
"source": item.get("source", ""),
}
for item in search_payload.get("results", [])[:_cfg.tools.news_max_results]
],
}
set_active_topic(topic_payload)
jp_text += " " + article_summary
if search_payload.get("browser_opened"):
jp_text += " ブラウザーも開いておいたよ。"
return jp_text
# Handle the generic web-search tool and optional browser opening.
async def handle_web_search_tool(user_text, context):
query = extract_search_query(user_text)
search_payload = search_web(query, max_results=_cfg.tools.web_max_results)
if _search_result_callback and search_payload.get("ok"):
try:
await _search_result_callback({
"kind": "web",
"query": query,
"results": search_payload.get("results", []),
})
except Exception:
pass
tool_context_messages = select_tool_context_messages(
user_text,
context["context_messages"],
context["active_topic"],
)
if should_open_browser(user_text):
first_result_url = None
if search_payload.get("results"):
first_result_url = search_payload["results"][0].get("url")
search_payload["browser_opened"] = open_search_in_browser(query, first_result_url=first_result_url)
jp_text = await answer_with_tool_context(
user_text,
"web_search",
search_payload,
tool_context_messages,
context["ltm"],
)
if search_payload.get("browser_opened"):
jp_text += " ブラウザーも開いておいたよ。"
elif search_payload.get("error") == "missing_dependency":
jp_text = "ごめんね、まだ検索用のライブラリが入っていないみたい。ddgs を入れると使えるようになるよ。"
return jp_text
# Handle the file read/write tool (notes, to-dos, daily log).
async def handle_file_tool(user_text, context):
category, operation, content = classify_file_operation(user_text)
if category == "todo":
if operation == "list":
items = list_todos()
if not items:
jp_text = "今、ToDoリストは空だよ。"
else:
jp_text = "今のToDoはこれだよ。"
for item in items:
status = "✓" if item.get("done") else "○"
jp_text += f" {status}{item['id']}番、「{item['text']}」。"
elif operation == "complete":
if not content:
jp_text = "どのToDoを完了にしたい?内容か番号を教えてね。"
else:
try:
result = complete_todo(todo_id=int(content))
except ValueError:
result = complete_todo(keyword=content)
jp_text = f"「{result['text']}」を完了にしたよ。" if result else "そのToDoは見つからなかったよ。"
elif operation == "delete":
if not content:
jp_text = "どのToDoを消したい?内容か番号を教えてね。"
else:
try:
result = delete_todo(todo_id=int(content))
except ValueError:
result = delete_todo(keyword=content)
jp_text = f"「{result['text']}」をToDoから消したよ。" if result else "そのToDoは見つからなかったよ。"
else:
if not content:
jp_text = "何をToDoに追加したい?内容を教えてね。"
else:
add_todo(content)
jp_text = f"うん、「{content}」をToDoに追加したよ。"
elif category == "log":
if operation == "list":
entries = read_daily_log()
if not entries:
jp_text = "今日のログはまだ何もないよ。"
else:
jp_text = "今日のログはこれだよ。"
for entry in entries:
jp_text += f" {entry['time']}に、「{entry['text']}」。"
else:
if not content:
jp_text = "ログに何を書きたい?内容を教えてね。"
else:
write_daily_log(content)
jp_text = f"うん、今日のログに「{content}」を書いたよ。"
else: # note
if operation == "list":
items = list_notes()
if not items:
jp_text = "今、メモは何もないよ。"
else:
jp_text = "今のメモはこれだよ。"
for item in items:
jp_text += f" {item['id']}番、「{item['text']}」。"
elif operation == "delete":
if not content:
jp_text = "どのメモを消したい?内容か番号を教えてね。"
else:
try:
result = delete_note(note_id=int(content))
except ValueError:
result = delete_note(keyword=content)
jp_text = f"「{result['text']}」のメモを消したよ。" if result else "そのメモは見つからなかったよ。"
else:
if not content:
jp_text = "メモに何を書きたい?内容を教えてね。"
else:
save_note(content)
jp_text = f"うん、メモに「{content}」を書いたよ。"
return jp_text
# Handle the reminder/scheduler tool.
async def handle_reminder_tool(user_text, context):
normalized = normalize_text(user_text)
# List active reminders.
if any(kw in normalized for kw in ["lihat", "daftar", "list", "apa saja"]):
items = list_reminders()
if not items:
jp_text = "今、リマインダーは何もないよ。"
else:
jp_text = "今のリマインダーはこれだよ。"
for item in items:
jp_text += f" {item['id']}番、{item['remind_at']}に「{item['text']}」。"
return jp_text
# Delete a reminder by ID.
if any(kw in normalized for kw in ["hapus", "delete", "batalkan", "cancel"]):
match = re.search(r"(\d+)", normalized)
if match:
rid = int(match.group(1))
removed = delete_reminder(rid)
jp_text = f"リマインダー{rid}番を消したよ。" if removed else "そのリマインダーは見つからなかったよ。"
else:
jp_text = "どのリマインダーを消したいか、番号で教えてね。"
return jp_text
# Add a new reminder.
remind_at, message = parse_reminder(user_text)
if remind_at is None:
jp_text = "ごめんね、時間がうまく読み取れなかったよ。「10分後」や「3時に」のように言ってみてね。"
return jp_text
if not message:
message = "リマインダー"
add_reminder(message, remind_at)
time_str = remind_at.strftime("%H:%M")
jp_text = f"うん、{time_str}に「{message}」のリマインダーをセットしたよ。"
return jp_text
TOOL_REGISTRY = [
{
"name": "file",
"detect": detect_file_query,
"handler": handle_file_tool,
},
{
"name": "reminder",
"detect": detect_reminder_query,
"handler": handle_reminder_tool,
},
{
"name": "time",
"detect": detect_time_query,
"handler": handle_time_tool,
},
{
"name": "news_search",
"detect": detect_news_query,
"handler": handle_news_tool,
},
{
"name": "web_search",
"detect": detect_web_search_query,
"handler": handle_web_search_tool,
},
{
"name": "vision",
"detect": detect_vision_query,
"handler": handle_vision_tool,
},
]
# Route one user utterance through IoT, memory, tools, or the base LLM flow.
async def route_and_execute(user_text, context):
if try_handle_iot_command(user_text, on_send=lambda topic, payload: logger.info("[IOT] publish %s <- %s", topic, payload)):
jp_text = "了解しました。デバイスに命令を送りました。"
prepare_tts_task(jp_text)
return jp_text
memory_reply = remember_user_memory(user_text)
if memory_reply:
prepare_tts_task(memory_reply)
return memory_reply
for tool in TOOL_REGISTRY:
if tool["detect"](user_text):
jp_text = await tool["handler"](user_text, context)
if jp_text:
prepare_tts_task(jp_text)
return jp_text
prompt = build_prompt(
context["context_messages"],
context["ltm"],
user_text,
active_topic=context["active_topic"],
)
logger.debug("[DEBUG PROMPT]\n%s", prompt)
terminal_debug(f"\n[DEBUG PROMPT]\n{prompt}")
jp_text = await ask_llm_async(prompt)
if not jp_text:
logger.warning("empty JP response")
return ""
prepare_tts_task(jp_text)
return jp_text
# Save the assistant reply to STM and play the synthesized audio.
async def handle_tts_and_stm(jp_text):
if not jp_text:
return
logger.info("JP: %s", jp_text)
terminal_debug(f"JP: {jp_text}")
add_stm("assistant", jp_text)
audio_path = await get_audio_path(jp_text)
if audio_path:
await asyncio.to_thread(play, audio_path)
else:
logger.error("TTS failed to generate audio")
# Orchestrate a single listen-route-speak interaction cycle.
async def main_cycle():
# Play any pending reminder alerts before listening.
for alert in get_pending_alerts():
jp_alert = f"リマインダーだよ!{alert['text']}"
logger.info("[REMINDER] %s", jp_alert)
audio_path = await get_audio_path(jp_alert)
if audio_path:
await asyncio.to_thread(play, audio_path)
try:
user_text = await asyncio.to_thread(listen)
if not user_text:
return
logger.info("User: %s", user_text)
terminal_debug(f"User: {user_text}")
add_stm("user", user_text)
context = build_runtime_context(user_text)
jp_text = await route_and_execute(user_text, context)
await handle_tts_and_stm(jp_text)
except Exception as exc:
logger.critical("[CRITICAL ERROR in MAIN LOOP] %s", exc, exc_info=True)
# Background task that checks reminders every 30 seconds.
async def reminder_checker_loop():
while True:
try:
queue_pending_alerts()
except Exception as exc:
logger.warning("Reminder check error: %s", exc)
await asyncio.sleep(_cfg.reminder.check_interval_seconds)
# Main interaction loop.
async def main_loop():
while True:
try:
await main_cycle()
except Exception:
logger.critical("[CRITICAL CRASH] Restarting loop...", exc_info=True)
# Persistent event loop that hosts both the interaction cycle and the reminder checker.
async def run():
await asyncio.gather(
reminder_checker_loop(),
main_loop(),
)
if __name__ == "__main__":
_log_path = Path(_cfg.paths.log_file)
_log_path.parent.mkdir(exist_ok=True)
_fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
_console_handler = logging.StreamHandler(sys.stdout)
_console_handler.setFormatter(_fmt)
_console_handler.setLevel(logging.DEBUG)
_file_handler = RotatingFileHandler(
_log_path,
maxBytes=_cfg.logging.max_bytes,
backupCount=_cfg.logging.backup_count,
encoding="utf-8",
)
_file_handler.setFormatter(_fmt)
logger.setLevel(logging.DEBUG)