diff --git a/docs/llm_contexts.md b/docs/llm_contexts.md index 72b7dc6..4ee7851 100644 --- a/docs/llm_contexts.md +++ b/docs/llm_contexts.md @@ -46,7 +46,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i - **File**: [src/jarvis/reply/enrichment.py](src/jarvis/reply/enrichment.py) — `extract_search_params_for_memory()` (~line 71). - **Trigger**: once per reply, **only when the pre-flight planner (#12) emitted a `searchMemory` directive or returned an empty plan (fail-open)**. Pure reply-only plans skip this entirely — saves one LLM call per greeting / small-talk turn. - **Model / gating**: resolved via `resolve_tool_router_model(cfg)` — `tool_router_model → intent_judge_model → ollama_chat_model`. Small classification task; rides the same small/warm model as the router. Silent empty-dict on failure. -- **Inputs**: user query (with the planner's `topic` hint appended when present), optional context hint (live-context compact summary), UTC now. +- **Inputs**: user query (with the planner's `topic` hint appended when present), optional context hint (live-context compact summary, placed after the examples so the model checks its questions against it last), UTC now. - **System prompt**: inline at [enrichment.py:35-63](src/jarvis/reply/enrichment.py:35). - **Output**: `{keywords, from?, to?, questions?}`. Consumed by memory search in the reply engine. - **Limits**: up to 2 retries; timeout from `llm_tools_timeout_sec`. @@ -158,7 +158,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i - **File**: [src/jarvis/reply/planner.py](src/jarvis/reply/planner.py) — `plan_query()`. - **Trigger**: once per reply, **after the tool router and before memory search**. Skipped when `cfg.planner_enabled = False`, when the query is shorter than `MIN_QUERY_CHARS` (4), or when no model / base URL is available. - **Model / gating**: resolution chain `planner_model (override) → ollama_chat_model`. The planner tracks the chat model so upgrading the chat model (via setup wizard or config) automatically upgrades plan quality. -- **Inputs**: user query, dialogue context, **router-narrowed** tool catalogue (names + one-line descriptions + argument names, built by `planner_tool_catalog()`) — not the full 30+ list. When the carry-over guard from #7 fires, the previous turn's failed tool name is unioned into this catalogue before the planner sees it, so the planner can plan a re-call without `toolSearchTool` round-tripping. **No** memory context — the planner decides *whether* memory is needed. +- **Inputs**: user query, dialogue context, the live time/location line (`LIVE CONTEXT:`, so a location-dependent ask plans `searchMemory topic='where the user lives'` only when the location is unknown or disabled), **router-narrowed** tool catalogue (names + one-line descriptions + argument names, built by `planner_tool_catalog()`) — not the full 30+ list. When the carry-over guard from #7 fires, the previous turn's failed tool name is unioned into this catalogue before the planner sees it, so the planner can plan a re-call without `toolSearchTool` round-tripping. **No** memory context — the planner decides *whether* memory is needed. - **System prompt**: `_PROMPT_TEMPLATE` in `planner.py`. Teaches the `searchMemory topic='...'` directive for prior-conversation lookups, short imperative tool steps, angle-bracket entity placeholders, final synthesis step, same-language output, no numbering. - **Output**: list of plan steps (max `MAX_STEPS` = 5). Gates memory enrichment (#3 / #4) and augments the tool router (#7 — planner's picks are unioned in, not replacing). Single-step `["Reply to the user."]` plans are the planner's positive "no memory, no tools" signal. An empty list is fail-open — the engine reverts to running #3 unconditionally. Consumed further by the engine to build the `ACTION PLAN:` system-message block and drive the direct-exec loop (#13) for small models. - **Limits**: `planner_timeout_sec` (6s). Fail-open → `[]`. diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index f1c9e92..fd1b0f5 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -7,7 +7,7 @@ | M0 | 게임PC 사전 검증 | 측정 스크립트를 게임PC에서 직접 실행하고 결과 파일을 보내 주시는 방식입니다. 결과로 기본값을 확정합니다. 확인 항목은 아래 목록에 있습니다. 가상 모니터 확인을 뺀 모든 항목 측정 완료(2026-11-10). 가상 모니터 확인은 M6에서 합니다. 2026-11-10에 추가한 `desktop` 단계(agent-desktop)는 측정을 마쳤고, 자동 성능 조절용 `gamemode` 단계는 세 번 쟀고, `gamemode_stt`(LLM과 STT를 함께 켬, STT GPU·CPU)와 `gamemode_live`(실제 게임을 켬) 단계도 측정을 마쳤습니다(2026-11-10). 결과로 게임 중 최소 배치는 전문가 2GB로 정했고, 평소 배치에 STT 자리를 남기는 것과 게임 중 LLM이 답하는 동안 부분 전사 간격을 늘리는 것(게임이 없을 때는 그대로)도 정했습니다(사용자 결정, 2026-11-10). `gamemode_tune` 단계도 측정을 마쳤고(2026-11-11), 게임 중 LLM이 답하는 동안에는 부분 전사를 멈추기로 정했습니다. GPU 95% 제한은 측정에서 사용률을 낮추지 못해 기본값을 끔으로 바꿨고(사용자 결정, 2026-11-11), `video_drops` 단계(Jarvis를 돌리는 동안 유튜브 영상의 끊긴 프레임, 직접 실행)도 측정을 마쳤습니다(2026-11-11). Jarvis가 바쁠 때도 영상이 끊기지 않았고 제한이 끊김을 줄이지 못해 설정을 뺐습니다. 대신 게임 화면의 프레임을 직접 재는 `game_frames` 단계(게임을 켠 채로 Jarvis를 끈 때·쉴 때·바쁠 때와 우선순위를 낮춘 양보 상태, 직접 실행, 관리자 권한)를 넣었고 측정을 마쳤습니다(2026-11-11). Jarvis가 바쁠 때도 게임의 평균 fps와 1% low가 5% 넘게 떨어지지 않아 양보는 넣지 않기로 했습니다. 남은 M0 측정은 가상 모니터 확인(M6)입니다. 측정 키트: [scripts/m0/](../../scripts/m0/README.md) | | M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과. 구현과 테스트 완료(2026-11-11): `src/voice_worker/`, 스펙은 [voice_worker.spec.md](../../src/voice_worker/voice_worker.spec.md). 이 서버의 RTX 5050에서 10명이 겹쳐 말하는 실시간 입력(48kHz 스테레오, M0 한국어 샘플 8개를 10명에게 나눠 줌, 절반은 디스코드 speaking 종료, 절반은 무음으로 끝남)을 넣어 10명 모두 최종 전사를 받았고 문자 오류율은 평균 4%, 최대 19%("일곱 시"를 "7시"로 적은 것), 말 끝 판정부터 최종 전사 전송까지 중앙값 0.64초, 최대 1.56초였습니다. TTS는 첫 문장 소리가 0.2초에 나왔고, 그 소리를 다시 넣으면 같은 문장으로 받아 적혔습니다. 샘플이 MeloTTS 합성 음성이라 실제 사람 녹음과 게임PC 수치는 아직 없습니다 | | M2 | 디스코드 음성 코어 이전 | v1 봇 기능을 새 앱 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기). 구현과 테스트 완료(2026-11-11): `app/`(Rust, serenity + songbird), 스펙은 [discord_core.spec.md](../../app/src/discord_core.spec.md). 처음 Electron + TypeScript로 만든 것을 사용자 요청으로 Rust로 다시 씀. 앱이 음성 워커를 띄우고(실행마다 새 토큰, 죽으면 다시 시작) 연결이 끊기면 다시 붙습니다. 음성 채널에 들어갈 때마다 전사 고지를 채널 채팅에 올립니다. songbird 0.6.1의 DAVE 수신 해독이 조각 3분의 1가량을 깨뜨려서(20ms마다 음이 바뀌는 시험 신호로 확인, 보내기는 정상) 받은 패킷의 순서 맞추기와 Opus 해독은 앱이 직접 합니다. 실제 디스코드에서 봇 두 개로 확인(이 서버의 RTX 5050): 다른 봇이 채널에 튼 녹음 문장 5개를 모두 받아 적었고(문자 오류율 3개 0%, "기록해"를 "비록해"로 적은 1개 5%, "일곱 시"를 "7시"로 적은 1개 12.5%), 말이 끝난 뒤 최종 전사까지 0.71~0.90초였습니다. 자비스가 말한 문장을 상대 봇이 받아 다시 전사하니 오류율 3.4%였고, 정지 명령 뒤 0.08초 만에 소리가 끊겼습니다. 채팅 채널은 새 글 받기, 최근 글 읽기, 보내기(2,000자 넘으면 나눔, 아무도 호출하지 않음)가 됩니다. 사람이 직접 말한 소리와 게임PC(Windows) 빌드는 아직 확인하지 않았고, 음성으로 "자비스, 멈춰"는 호출 판정이 필요해 M4에서 합니다 | -| M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 | +| M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 날씨 평가 12개는 3번에 36번 중 34번 통과(실패 2번은 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 남은 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트 | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | diff --git a/evals/test_agent_behavior.py b/evals/test_agent_behavior.py index c1f2f03..18125d4 100644 --- a/evals/test_agent_behavior.py +++ b/evals/test_agent_behavior.py @@ -500,6 +500,39 @@ class TestMemoryEnrichment: assert not any("locat" in q or "where" in q for q in questions), \ f"Should not ask about location when it's in context. Got: {questions}" + @pytest.mark.eval + @requires_judge_llm + def test_enrichment_asks_location_when_context_lacks_it(self, mock_config): + """ + Counterpart of the test above: when the live context has no location, + a query that depends on where the user is still asks for it, so the + memory lookup can find where the user said they live. + """ + from jarvis.reply.enrichment import extract_search_params_for_memory + from helpers import JUDGE_MODEL + + mock_config.ollama_base_url = JUDGE_BASE_URL + mock_config.ollama_chat_model = JUDGE_MODEL + + result = extract_search_params_for_memory( + query="recommend a restaurant I'd enjoy", + ollama_base_url=mock_config.ollama_base_url, + ollama_chat_model=mock_config.ollama_chat_model, + timeout_sec=15.0, + context_hint=( + "Current local time: Sunday, 2026-04-19 14:30 local. " + "Location: Unknown" + ), + ) + + questions = [q.lower() for q in result.get("questions", [])] + print(f"\n📊 Questions without a location in context: {questions}") + + assert result.get("keywords"), \ + f"Extractor returned no keywords. Result: {result}" + assert any("locat" in q or "where" in q for q in questions), \ + f"Should ask where the user is when the context has no location. Got: {questions}" + @pytest.mark.eval def test_enrichment_provides_context_to_llm(self, mock_config, eval_db, eval_dialogue_memory): """ @@ -1030,24 +1063,27 @@ class TestHelpfulness: is_small = detect_model_size(JUDGE_MODEL) == ModelSize.SMALL - call_count = {"n": 0} + # Every call in turn 1 fails and every call in turn 2 succeeds. A + # model that retries by itself inside turn 1 must not get the data + # there, or turn 2 is answered from that result and the user's + # "try again" is never tested. + phase = {"turn": 1} def mock_tool_run(db, cfg, tool_name, tool_args, **kwargs): - """First call returns error, second call succeeds.""" + """Fails throughout turn 1, succeeds in turn 2.""" from jarvis.tools.types import ToolExecutionResult capture.record(tool_name, tool_args or {}) - call_count["n"] += 1 if tool_name == "getWeather": - if call_count["n"] <= 1: - # First call: tool can't find the location + if phase["turn"] == 1: + # Turn 1: tool can't find the location return ToolExecutionResult( success=False, reply_text="", error_message="Could not find location 'Kazbegi'. Try a different spelling or a nearby city." ) else: - # Subsequent calls: tool succeeds + # Turn 2: tool succeeds return ToolExecutionResult( success=True, reply_text="Current weather near Kazbegi (Stepantsminda), Georgia:\nConditions: Partly cloudy\nTemperature: 2.5°C\nWind: 25 km/h\n7-day: 2026-04-10: -1–5°C, Snow showers" @@ -1070,6 +1106,7 @@ class TestHelpfulness: # Turn 2: User insists on retry — tool should succeed this time capture.clear() + phase["turn"] = 2 response = run_reply_engine( db=eval_db, cfg=mock_config, tts=None, text=follow_up, diff --git a/evals/test_tool_skip_confabulation.py b/evals/test_tool_skip_confabulation.py index 749e8b2..4e0304f 100644 --- a/evals/test_tool_skip_confabulation.py +++ b/evals/test_tool_skip_confabulation.py @@ -16,8 +16,8 @@ answers without it. This eval drives the real engine (planner, router and chat model are live; only the tools are mocked) and checks both shapes: - live facts: an umbrella / rain question must reach getWeather. The - queries avoid the words the deterministic weather shortcut matches, so - the chat model has to choose the tool itself. + queries avoid the word "weather", so the chat model has to see that + the question needs the tool. - actions: "log my meal" must reach logMeal, and a timer request (no timer tool exists) must not be answered as if a timer had been set. diff --git a/src/jarvis/reply/engine.py b/src/jarvis/reply/engine.py index f7b6aa7..3f313c8 100644 --- a/src/jarvis/reply/engine.py +++ b/src/jarvis/reply/engine.py @@ -940,49 +940,6 @@ def _maybe_deterministic_site_search(text: str, db, cfg, language) -> Optional[s return None -_WEATHER_INTENT_WORDS = ( - "날씨", "기온", "더워", "더운", "추워", "추운", "비 와", "비와", "비 올", - "눈 와", "눈와", "weather", "temperature", "forecast", -) - - -def _maybe_deterministic_weather(text: str, db, cfg, language) -> Optional[str]: - """Run getWeather directly and return its concise Korean sentence, bypassing - the chat model. The 7B otherwise re-synthesises the weather into multiple - sentences and leaks units ("25도 Celsius"); the tool already formats one - clean Korean sentence, so for a plain weather ask we just return it. - Fail-open: any problem returns None and the normal flow continues. - """ - try: - low = (text or "").lower() - if not any(w in low for w in _WEATHER_INTENT_WORDS): - return None - # Extract a city candidate from the utterance (GeoIP auto-detect is - # unavailable in the container, so a named city must be passed through). - import re - _loc = text - for w in _WEATHER_INTENT_WORDS + ( - "알려줘", "어때", "어떄", "말해줘", "확인해줘", "확인", "해줘", - "오늘", "지금", "현재", "좀", "그래서", "그럼", - ): - _loc = re.sub(re.escape(w), " ", _loc, flags=re.IGNORECASE) - _loc = re.sub(r"(은|는|이|가|의|에|에서|로|을|를)\b", " ", _loc) - _loc = re.sub(r"\s+", " ", _loc).strip(" .,!?。") - args = {"location": _loc} if 1 <= len(_loc) <= 12 else {} - from ..tools.registry import run_tool_with_retries - res = run_tool_with_retries( - db=db, cfg=cfg, tool_name="getWeather", tool_args=args, - system_prompt="", original_prompt="", redacted_text=redact(text), - max_retries=1, language=language, - ) - if res and getattr(res, "success", False) and res.reply_text: - debug_log("deterministic weather executed", "tools") - return res.reply_text - except Exception as e: # noqa: BLE001 - debug_log(f"deterministic weather failed (fail-open): {e}", "tools") - return None - - _HISTORY_FENCE = "conversation_records" @@ -1061,13 +1018,6 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any], if _site_search_reply is not None: return _site_search_reply - # Step 0.6: Deterministic weather — return getWeather's concise Korean - # sentence directly so the chat model can't rephrase it into multiple - # sentences or leak units. - _weather_reply = _maybe_deterministic_weather(text, db, cfg, language) - if _weather_reply is not None: - return _weather_reply - # Step 2: Check for recent dialogue context recent_messages = [] is_new_conversation = True @@ -1312,6 +1262,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any], query=redacted, dialogue_context=_dialogue_ctx, tools=_planner_tool_catalog, + live_context=_live_time_location_string(cfg), ) except Exception as _plan_exc: # pragma: no cover — defensive debug_log(f"planner step failed (non-fatal): {_plan_exc}", "planning") @@ -2566,8 +2517,10 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any], # In native-tools mode results carry role="tool"; in text-tools mode they carry # role="user" with a "tool_name" key — check both to make the guard effective # in small-model paths where direct-exec is most likely to loop. + # Only this reply's messages count: results carried over from the + # previous reply must not block a retry the user just asked for. duplicate_tool_count = sum( - 1 for msg in messages[-10:] + 1 for msg in messages[max(user_msg_index + 1, len(messages) - 10):] if msg.get("tool_name") == tool_name and msg.get("role") in ("tool", "user") ) diff --git a/src/jarvis/reply/enrichment.py b/src/jarvis/reply/enrichment.py index 993fb68..ad5bd7f 100644 --- a/src/jarvis/reply/enrichment.py +++ b/src/jarvis/reply/enrichment.py @@ -37,9 +37,7 @@ def extract_search_params_for_memory(query: str, ollama_base_url: str, ollama_ch Extract: 1. CONTENT KEYWORDS: 3-5 relevant topics/subjects (ignore time words). Include general, high-level category tags that would be suitable for blog-style tagging when applicable (e.g., "cooking", "fitness", "travel", "finance"). 2. TIME RANGE: If mentioned, convert to exact timestamps -3. QUESTIONS: What implicit personal questions does this query need answered from stored knowledge about the user? These are things the assistant would need to know about the user to give a personalised answer. Omit if the query needs no personal context, OR if the answer is already visible in the ALREADY IN CONTEXT block below. - -{hint_block} +3. QUESTIONS: What implicit personal questions does this query need answered from stored knowledge about the user? These are things the assistant would need to know about the user to give a personalised answer. Omit if the query needs no personal context, OR if the answer is already visible in the ALREADY IN CONTEXT block at the end. Respond ONLY with JSON in this format: {{"keywords": ["keyword1", "keyword2"], "questions": ["what are the user's food preferences?"], "from": "2025-08-21T00:00:00Z", "to": "2025-08-21T23:59:59Z"}} @@ -57,10 +55,14 @@ Examples: "remember that password I mentioned today?" → {{"keywords": ["password", "accounts", "security", "credentials"], "from": "2025-08-22T00:00:00Z", "to": "2025-08-22T23:59:59Z"}} "what news might interest me?" → {{"keywords": ["interests", "hobbies", "preferences", "likes", "passionate"], "questions": ["what topics interest the user?", "what are the user's hobbies?"]}} "news of interest to me" / "news that would interest me" / "news interesting for me" / "recall my interests and search for news on them" → {{"keywords": ["interests", "hobbies", "preferences", "likes", "passionate"], "questions": ["what topics interest the user?", "what are the user's hobbies?"]}} -"recommend a restaurant I'd enjoy" (no location in context) → {{"keywords": ["food preferences", "restaurants", "cuisine", "dining", "favorites"], "questions": ["what cuisine does the user like?", "where is the user located?"]}} -"recommend a restaurant I'd enjoy" (location already in context) → {{"keywords": ["food preferences", "restaurants", "cuisine", "dining", "favorites"], "questions": ["what cuisine does the user like?"]}} +"recommend a restaurant I'd enjoy" (ALREADY IN CONTEXT shows a location) → {{"keywords": ["food preferences", "restaurants", "cuisine", "dining", "favorites"], "questions": ["what cuisine does the user like?"]}} +"find me a gym I'd like" (ALREADY IN CONTEXT shows no location, or Location: Unknown) → {{"keywords": ["fitness", "gym", "exercise", "preferences"], "questions": ["what kind of exercise does the user enjoy?", "where is the user located?"]}} "suggest a movie for me" → {{"keywords": ["movies", "films", "entertainment", "preferences", "genres"], "questions": ["what film genres does the user enjoy?", "what movies has the user watched recently?"]}} "what time is it?" → {{"keywords": []}} + +{hint_block} + +Before answering, drop every question whose answer is shown in the block above. """ formatted_prompt = system_prompt.format(hint_block=hint_block) diff --git a/src/jarvis/reply/planner.py b/src/jarvis/reply/planner.py index d670294..012d455 100644 --- a/src/jarvis/reply/planner.py +++ b/src/jarvis/reply/planner.py @@ -180,10 +180,17 @@ _PROMPT_TEMPLATE = ( "preferences and dietary restrictions'; 'suggest something I'd " "enjoy watching' → searchMemory topic='user viewing tastes'. " "NO-examples (DO NOT emit searchMemory): 'who is Britney Spears', " - "'what is the capital of France', 'what's the weather today', " + "'what is the capital of France', 'what's the weather today' " + "(when LIVE CONTEXT gives the location), " "'search the web for Possessor 2020'. If no prior-conversation " "memory is needed, OMIT this step entirely — every extra " "searchMemory directive costs a real LLM call.\n" + "2b. A tool step that depends on a fact about the user themself " + "(where they are, for weather or local results) also needs memory " + "FIRST when neither LIVE CONTEXT nor DIALOGUE CONTEXT gives that " + "fact, e.g. LIVE CONTEXT says 'Location: Unknown' or 'Location: " + "Disabled': emit `searchMemory topic='where the user lives'` before " + "the tool step. When LIVE CONTEXT gives a location, do not.\n" "3. Use external tools ONLY from the AVAILABLE TOOLS list below, " "by exact name. If no tool is needed (greeting, small-talk, " "opinion, a question about yourself, a fact already in the " @@ -257,6 +264,7 @@ def _build_user_message( query: str, dialogue_context: str, tools: Sequence[Tuple[str, str]], + live_context: str = "", ) -> str: parts = [] if tools: @@ -264,6 +272,8 @@ def _build_user_message( parts.append(f"AVAILABLE TOOLS:\n{tool_lines}") else: parts.append("AVAILABLE TOOLS: (none — plan a direct reply)") + if live_context.strip(): + parts.append(f"LIVE CONTEXT: {live_context.strip()}") if dialogue_context.strip(): parts.append(f"DIALOGUE CONTEXT (most recent last):\n{dialogue_context.strip()}") else: @@ -445,6 +455,7 @@ def plan_query( *, timeout_sec: Optional[float] = None, memory_context: str = "", # deprecated; planner now runs before memory + live_context: str = "", ) -> List[str]: """Run a short planning LLM pass over the query + dialogue context. @@ -454,6 +465,10 @@ def plan_query( A single ``["Reply to the user."]`` is a valid plan and means "answer directly; skip both memory and tools". + ``live_context`` is the engine's live time/location line. It lets the + planner tell a known location from an unknown one, and plan a memory + lookup for where the user is only in the second case. + ``memory_context`` is accepted for backward compatibility with old callers but no longer used: the planner runs before memory search so it decides *whether* memory is needed, via the searchMemory @@ -478,7 +493,7 @@ def plan_query( ) system_prompt = _PROMPT_TEMPLATE.format(max_steps=MAX_STEPS) - user_content = _build_user_message(query, dialogue_context, tools) + user_content = _build_user_message(query, dialogue_context, tools, live_context) try: raw = call_llm_direct( diff --git a/src/jarvis/reply/planner.spec.md b/src/jarvis/reply/planner.spec.md index 34cda79..656c44e 100644 --- a/src/jarvis/reply/planner.spec.md +++ b/src/jarvis/reply/planner.spec.md @@ -69,6 +69,11 @@ one turn's allow-list. ### Prompt contract (plan_query) +The planner's user message also carries a `LIVE CONTEXT:` line: the +engine's live time/location string (`_live_time_location_string`), passed +as `plan_query(..., live_context=...)`. It lets the planner tell a known +location from an unknown one without seeing any memory content. + The planner's AVAILABLE TOOLS lines come from `planner_tool_catalog(schema)`: the tool's first description line plus its argument names, e.g. `getWeather: Weather only ... (args: location)`. Without the argument names @@ -83,6 +88,11 @@ The planner prompt instructs the model to emit: when** answering requires information the user shared in prior conversations. Omit otherwise — every extra directive is an avoidable LLM call downstream. +- The same directive (`searchMemory topic='where the user lives'`) before a + tool step that needs a fact about the user themself, such as where they + are, when neither the LIVE CONTEXT nor the dialogue gives it (the live + context says `Location: Unknown` or `Location: Disabled`). When the live + context gives a location, a plain weather ask stays memory-free. - Tool names from the provided catalog only (exact match), for any concrete tool step. - Concrete arguments composed against dialogue context, not the raw diff --git a/src/jarvis/reply/prompts/model_variants.py b/src/jarvis/reply/prompts/model_variants.py index 081138e..2b7a485 100644 --- a/src/jarvis/reply/prompts/model_variants.py +++ b/src/jarvis/reply/prompts/model_variants.py @@ -119,10 +119,13 @@ TOOL_CONSTRAINTS_LARGE = ( "Tools may state in their description that an argument has a sensible default " "(for example getWeather uses the user's current location when none is given). " "Call the tool in the SAME turn with whatever arguments you have — even zero — " - "and let it fill the rest. Do NOT reply with a clarifying question like \"which " - "location?\" for an argument the tool auto-derives. Concretely: \"how's the " - "weather today\" must trigger getWeather immediately with no arguments, not a " - "question back to the user.\n\n" + "and let it fill the rest. What the user has told you counts as having it: if the " + "conversation or what you remember about the user gives the value, pass it " + "(\"how's the weather\" from a user who told you they live in Leeds calls " + "getWeather with location Leeds). Do NOT reply with a clarifying question like " + "\"which location?\" for an argument the tool auto-derives. Concretely: \"how's " + "the weather today\" with no place known must trigger getWeather immediately " + "with no arguments, not a question back to the user.\n\n" "SELF-CONTAINED TOOL ARGUMENTS:\n" "When you call any tool with a free-form text argument (search queries, lookup " "strings, question fields — whatever the tool calls them), the string you pass " @@ -205,7 +208,7 @@ Any phrasing that requests information about a named entity is a search trigger Only skip the lookup if you can state concrete facts about the exact entity (title, year, creator, plot) without guessing. A diary or memory mention of the entity's name only confirms the topic came up — it does NOT give you facts you can state. Never invent plot, cast, release year, themes, or other specifics from prior knowledge. If you do not have facts from a tool result in this turn, you must call webSearch. ARGUMENTS THE TOOL CAN AUTO-DERIVE: -If a tool's description says it has a default for some argument (for example getWeather uses the user's current location when none is given), call the tool in the SAME turn with whatever arguments you do have — even zero — and let the tool fill the rest. Do NOT ask the user to supply that argument. Do NOT reply with a clarifying question like "which location?" or "where are you?" when the tool's description already states it auto-derives that argument. Concretely: a message like "how's the weather today" must trigger getWeather immediately with no arguments, NOT a question back to the user. Asking for an argument the tool auto-derives wastes a turn and frustrates the user. +If a tool's description says it has a default for some argument (for example getWeather uses the user's current location when none is given), call the tool in the SAME turn with whatever arguments you do have — even zero — and let the tool fill the rest. What the user has told you counts as having it: if the conversation or what you remember about the user gives the value, pass it (a user who told you they live in Leeds asking "how's the weather" calls getWeather with location Leeds). Do NOT ask the user to supply that argument. Do NOT reply with a clarifying question like "which location?" or "where are you?" when the tool's description already states it auto-derives that argument. Concretely: a message like "how's the weather today" with no place known must trigger getWeather immediately with no arguments, NOT a question back to the user. Asking for an argument the tool auto-derives wastes a turn and frustrates the user. SELF-CONTAINED TOOL ARGUMENTS: Whenever you call any tool with a free-form text argument (a search query, lookup string, question field — whatever the tool names it), the string you pass MUST be a self-contained restatement of the user's intent. Resolve pronouns, ellipsis, and implicit references from earlier turns yourself — the tool does NOT see the conversation history, it only sees the argument you pass. If the previous turn was about "Harry Styles" and the user now asks "what are his most famous songs?", the argument must be something like "Harry Styles most famous songs", NOT "what are his most famous songs". Prefer a compact keyword phrase over a conversational sentence. Never pass the user's literal utterance through when it contains unresolved pronouns, "that", "those", "it", "his", "her", "their", or similar references. This applies to every tool — webSearch, Wikipedia, MCP tools, all of them.""" diff --git a/src/jarvis/reply/reply.spec.md b/src/jarvis/reply/reply.spec.md index 068a831..8ee9fef 100644 --- a/src/jarvis/reply/reply.spec.md +++ b/src/jarvis/reply/reply.spec.md @@ -96,6 +96,7 @@ Design principles enforced by the engine: - `thinking` field: Internal reasoning (not shown to user), continue loop - `content` field: Natural language response to user - Note: System messages are NOT added after the conversation starts, as this breaks native tool calling in models like Llama 3.2 + - Repeat guard: an exact repeat of a tool call (same name and arguments) in one reply, or a third call of the same tool within the reply's last 10 messages, gets guidance to use the earlier results instead of running. Only this reply's messages count: tool results carried over from the previous reply never block a retry the user asks for. Malformed-response guard (all models): - After each turn, before the content is accepted as a final reply, `_is_malformed_json_response` checks for structured-data hallucinations that should never reach the user: diff --git a/src/jarvis/tools/builtin/weather.py b/src/jarvis/tools/builtin/weather.py index 36b495f..37df804 100644 --- a/src/jarvis/tools/builtin/weather.py +++ b/src/jarvis/tools/builtin/weather.py @@ -203,8 +203,11 @@ class WeatherTool(Tool): "Weather only (current + forecast). NOT for time-of-day, date, or " "location questions — those are already in the assistant's context. " "Use for ANY weather question: now, later today, tomorrow, this week. " - "Call with {} — user location is auto-detected. Do NOT ask the user " - "where they are or request a city; just call this tool with empty args." + "Set location to the place the user asked about. If they named none, " + "set it to where the user has said they are, from the conversation or " + "what you remember about them. Otherwise leave it empty: the tool " + "auto-detects the user's location (do not copy the detected location " + "into it). Do NOT ask the user where they are; just call this tool." ) @property @@ -214,7 +217,7 @@ class WeatherTool(Tool): "properties": { "location": { "type": "string", - "description": "OPTIONAL. City name or location (e.g., 'London', 'New York', 'Tokyo'). Only set this if the user explicitly named a place different from their own location. If omitted, the tool auto-uses the user's current detected location — never ask the user for this argument." + "description": "City name or location (e.g., 'London', 'New York', 'Tokyo'): the place the user asked about, or else where the user has said they are (the conversation or your memory of them). Omit otherwise; the tool then auto-detects the user's location. Never ask the user for this argument." } }, "required": [] @@ -364,6 +367,20 @@ class WeatherTool(Tool): if geo_data.get("results"): location_str = romanised + # A "district, city, country" name (often the detected location + # copied from the context) may not match as a whole. Retry + # without the leading parts, narrowest area first. + parts = [p.strip() for p in location_str.split(",") if p.strip()] + for i in range(1, len(parts)): + if geo_data.get("results"): + break + wider = ", ".join(parts[i:]) + debug_log(f" 🌤️ geocode empty; retrying wider area '{wider}'", "tools") + geocode_params["name"] = wider + geo_response = requests.get(geocode_url, params=geocode_params, timeout=10) + geo_response.raise_for_status() + geo_data = geo_response.json() + if not geo_data.get("results"): return ToolExecutionResult( success=False, @@ -442,8 +459,7 @@ class WeatherTool(Tool): # The reply is the clean Korean sentence ONLY — no English/°C source # for the model to echo ("25도 Celsius"), no forecast firehose to - # ramble over. The deterministic weather path in the engine returns - # this verbatim; on the LLM path the model just echoes one sentence. + # ramble over. The model just echoes this one sentence. lines = [ko_sentence] reply_text = "\n".join(lines) diff --git a/tests/test_engine_planner_integration.py b/tests/test_engine_planner_integration.py index 731ec43..e3f8100 100644 --- a/tests/test_engine_planner_integration.py +++ b/tests/test_engine_planner_integration.py @@ -524,3 +524,32 @@ def test_direct_exec_fires_despite_prior_query_tool_carryover( "direct-exec must fire for the current plan's getWeather step even when " "prior-query tool results are present in dialogue carryover" ) + + +def test_planner_receives_live_location_context(mock_config, db, dialogue_memory): + """The planner gets the same live time/location line as the rest of + the turn, so it can tell an unknown location from a known one.""" + from jarvis.reply import engine as engine_mod + + mock_config.ollama_chat_model = "gpt-oss:20b" + mock_config.evaluator_enabled = False + mock_config.location_enabled = False + + seen: dict = {} + + def fake_plan(*args, **kwargs): + seen.update(kwargs) + return ["Reply to the user."] + + with patch.object(engine_mod, "chat_with_messages", + return_value=_assistant_content("Hello.")), \ + patch.object(engine_mod, "select_tools", return_value=["stop"]), \ + patch.object(engine_mod, "plan_query", side_effect=fake_plan): + engine_mod.run_reply_engine( + db=db, cfg=mock_config, tts=None, + text="how is the weather today", + dialogue_memory=dialogue_memory, + ) + + assert seen.get("live_context") == engine_mod._live_time_location_string(mock_config) + assert "Location: Disabled" in seen["live_context"] diff --git a/tests/test_engine_tool_carryover.py b/tests/test_engine_tool_carryover.py index 0a7343e..cc8a716 100644 --- a/tests/test_engine_tool_carryover.py +++ b/tests/test_engine_tool_carryover.py @@ -225,3 +225,53 @@ def test_tool_carryover_text_tool_mode( assert any( "Paris" in (m.get("content") or "") for m in tool_like ) + + +@pytest.mark.unit +@patch("src.jarvis.reply.engine.plan_query", return_value=[]) +@patch("src.jarvis.reply.engine.extract_search_params_for_memory", return_value={}) +@patch("src.jarvis.reply.engine.run_tool_with_retries") +@patch("src.jarvis.reply.engine.extract_text_from_response") +@patch("src.jarvis.reply.engine.chat_with_messages") +def test_retry_asked_in_next_reply_runs_despite_prior_reply_calls( + mock_chat, mock_extract, mock_tool, _mock_extract, _mock_plan +): + """Calls carried over from the previous reply do not count against the + per-reply repeat guard: when reply 1 tried a tool twice and the user + then asks to try again, reply 2 runs it.""" + def _call(cid, place): + return {"message": {"content": "", "tool_calls": [{ + "id": cid, "type": "function", + "function": {"name": "getWeather", "arguments": {"location": place}}, + }]}} + + mock_tool.side_effect = [ + Mock(success=False, reply_text="", error_message="Could not find location."), + Mock(success=False, reply_text="", error_message="Could not find location."), + Mock(success=True, reply_text="Kazbegi: 2.5C, partly cloudy.", error_message=None), + ] + mock_chat.side_effect = [ + _call("c1", "Kazbegi"), + _call("c2", "Stepantsminda"), + {"message": {"content": "I could not find that place."}}, + _call("c3", "Kazbegi, Georgia"), + {"message": {"content": "It is 2.5C and partly cloudy in Kazbegi."}}, + ] + mock_extract.side_effect = [ + "", "", "I could not find that place.", + "", "It is 2.5C and partly cloudy in Kazbegi.", + ] + + db = Mock() + cfg = _mock_cfg() + dm = DialogueMemory() + + run_reply_engine(db=db, cfg=cfg, tts=None, + text="how's the weather in Kazbegi today?", + dialogue_memory=dm) + reply = run_reply_engine(db=db, cfg=cfg, tts=None, + text="just try checking the weather one more time", + dialogue_memory=dm) + + assert mock_tool.call_count == 3 + assert "2.5" in (reply or "") diff --git a/tests/test_planner.py b/tests/test_planner.py index 9f325d9..b4d141a 100644 --- a/tests/test_planner.py +++ b/tests/test_planner.py @@ -194,6 +194,32 @@ class TestPlanQuery: ) assert steps == ["Reply to user."] + def test_planner_sees_live_context(self): + """The planner is told what the live context knows (time, location), + so it can plan a memory lookup for a fact about the user, such as + where they are, only when the live context lacks it.""" + cfg = _cfg() + with patch.object( + planner_mod, "call_llm_direct", return_value="Reply to user." + ) as llm: + plan_query( + cfg, + "how is the weather today", + "", + [("getWeather", "Weather. (args: location)")], + live_context="Current local time: Monday 09:00. Location: Unknown", + ) + assert "Location: Unknown" in llm.call_args.kwargs["user_content"] + + def test_prompt_plans_memory_for_user_facts_missing_from_live_context(self): + """The prompt must tie the searchMemory directive to a user fact + (where they are) that the live context does not give, so a + location-dependent tool still gets the user's place from memory + when auto-detection is off.""" + prompt = planner_mod._PROMPT_TEMPLATE + assert "LIVE CONTEXT" in prompt + assert "Location: Unknown" in prompt + def test_prompt_warns_against_fabricating_optional_arguments(self): """The planner prompt must explicitly tell the model to omit optional arguments when the user didn't supply a value, and warn diff --git a/tests/tools/builtin/test_weather.py b/tests/tools/builtin/test_weather.py index 32f3daf..a68ccc3 100644 --- a/tests/tools/builtin/test_weather.py +++ b/tests/tools/builtin/test_weather.py @@ -163,6 +163,40 @@ class TestWeatherTool: # The romanised name must be what the second geocode actually queried. assert mock_get.call_args_list[1].kwargs["params"]["name"] == "Seoul" + @patch('requests.get') + def test_run_comma_place_falls_back_to_wider_area(self, mock_get): + """A "district, city, country" name the geocoder can't match is retried + without its leading parts, so a location taken from the context (e.g. + a detected "Gangnam-gu, Seoul, South Korea") still gets weather.""" + known = { + "Seoul, South Korea": { + "latitude": 37.566, "longitude": 126.9784, + "name": "Seoul", "country": "South Korea", "admin1": "Seoul", + }, + } + + def fake_get(url, params=None, timeout=None): + resp = Mock() + resp.raise_for_status = Mock() + if "geocoding" in url: + place = known.get(params["name"]) + resp.json.return_value = {"results": [place]} if place else {} + else: + resp.json.return_value = { + "current": { + "temperature_2m": 12.0, "apparent_temperature": 11.0, + "weather_code": 0, + }, + } + return resp + + mock_get.side_effect = fake_get + + result = self.tool.run({"location": "Gangnam-gu, Seoul, South Korea"}, self.context) + + assert result.success is True + assert "Seoul" in result.reply_text + def test_romanise_place_skips_ascii_names(self): """ASCII names already geocode, so no LLM round-trip is spent on them.""" cfg = Mock()