Done
Browse files- .env +3 -2
- .env.example +8 -3
- .history/.env_20260703222048 +16 -0
- .history/.env_20260703222052 +16 -0
- .history/.env_20260703222054 +17 -0
- .history/.env_20260703222055 +17 -0
- .history/.env_20260703222056 +17 -0
- .history/.env_20260703222101 +17 -0
- .history/.env_20260703222106 +17 -0
- .pytest_cache/v/cache/lastfailed +12 -6
- .pytest_cache/v/cache/nodeids +29 -0
- AGENTS.md +31 -0
- __pycache__/main.cpython-310.pyc +0 -0
- development_logs/2026-07-03_21-45-21_establish-development-policy.md +37 -0
- development_logs/2026-07-03_21-51-49_plan-conversation-memory.md +53 -0
- development_logs/2026-07-03_22-06-50_implement-conversation-memory-phase1.md +94 -0
- development_logs/2026-07-03_22-18-37_implement-conversation-memory-phase2.md +93 -0
- development_logs/2026-07-03_22-40-00_plan-context-aware-goal-check.md +57 -0
- development_logs/2026-07-03_22-46-06_implement-context-aware-goal-check.md +79 -0
- development_logs/2026-07-03_23-01-35_implement-preplanning-goal-resolution.md +70 -0
- development_logs/2026-07-03_23-10-10_fix-on-top-goal-check.md +69 -0
- docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md +358 -0
- docs/CONVERSATION_MEMORY_PLAN.md +437 -0
- frontend/__pycache__/interactive_server.cpython-310.pyc +0 -0
- frontend/app.js +14 -4
- frontend/controllers/__pycache__/ui_controller.cpython-310.pyc +0 -0
- frontend/controllers/ui_controller.py +38 -17
- frontend/interactive_server.py +79 -35
- frontend/overlay_app.py +28 -11
- frontend/threads/__pycache__/llm_thread.cpython-310.pyc +0 -0
- frontend/threads/__pycache__/simulation_thread.cpython-310.pyc +0 -0
- frontend/threads/llm_thread.py +18 -7
- llm_panda/__pycache__/geofik.cpython-310.pyc +0 -0
- llm_panda/__pycache__/llm_agent.cpython-310.pyc +0 -0
- llm_panda/__pycache__/scene_manager.cpython-310.pyc +0 -0
- llm_panda/conversation/__init__.py +19 -0
- llm_panda/conversation/manager.py +347 -0
- llm_panda/conversation/models.py +60 -0
- llm_panda/execution/monitor.py +102 -1
- llm_panda/execution/pipeline.py +42 -4
- llm_panda/llm_agent.py +714 -81
- llm_panda/scene_manager.py +54 -20
- main.py +3 -0
- tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc +0 -0
- tests/test_conversation_memory.py +683 -0
- tests/test_occupancy.py +26 -3
.env
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
# Choose one or both providers
|
| 2 |
-
OPENAI_API_KEY=sk-or-v1-
|
| 3 |
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
-
|
|
|
|
| 6 |
# Default model
|
| 7 |
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 8 |
# DEFAULT_MODEL=gpt-4o
|
|
|
|
| 1 |
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=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
|
| 3 |
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
# 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 của tôi
|
| 7 |
# Default model
|
| 8 |
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 9 |
# DEFAULT_MODEL=gpt-4o
|
.env.example
CHANGED
|
@@ -1,9 +1,14 @@
|
|
| 1 |
# Choose one or both providers
|
| 2 |
OPENAI_API_KEY= ...
|
| 3 |
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
-
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 8 |
# DEFAULT_MODEL=gpt-4o
|
| 9 |
|
|
|
|
| 1 |
# Choose one or both providers
|
| 2 |
OPENAI_API_KEY= ...
|
| 3 |
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
CONVERSATION_MEMORY_ENABLED=true
|
| 6 |
+
LLM_GOAL_RESOLUTION_ENABLED=true
|
| 7 |
+
STRUCTURED_GOAL_CHECK_ENABLED=true
|
| 8 |
+
MAX_REPLANS=3
|
| 9 |
+
LLM_STRUCTURED_OUTPUTS_ENABLED=auto
|
| 10 |
+
|
| 11 |
+
# Default model
|
| 12 |
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 13 |
# DEFAULT_MODEL=gpt-4o
|
| 14 |
|
.history/.env_20260703222048
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=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
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
# Default model
|
| 7 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 8 |
+
# DEFAULT_MODEL=gpt-4o
|
| 9 |
+
|
| 10 |
+
# Logging
|
| 11 |
+
LOG_LEVEL=INFO
|
| 12 |
+
|
| 13 |
+
# AI Hook Logging (set by instructor)
|
| 14 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 15 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 16 |
+
AI_LOG_DIR=.ai-log
|
.history/.env_20260703222052
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
# Default model
|
| 7 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 8 |
+
# DEFAULT_MODEL=gpt-4o
|
| 9 |
+
|
| 10 |
+
# Logging
|
| 11 |
+
LOG_LEVEL=INFO
|
| 12 |
+
|
| 13 |
+
# AI Hook Logging (set by instructor)
|
| 14 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 15 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 16 |
+
AI_LOG_DIR=.ai-log
|
.history/.env_20260703222054
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
|
| 7 |
+
# Default model
|
| 8 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 9 |
+
# DEFAULT_MODEL=gpt-4o
|
| 10 |
+
|
| 11 |
+
# Logging
|
| 12 |
+
LOG_LEVEL=INFO
|
| 13 |
+
|
| 14 |
+
# AI Hook Logging (set by instructor)
|
| 15 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 16 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 17 |
+
AI_LOG_DIR=.ai-log
|
.history/.env_20260703222055
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
#
|
| 7 |
+
# Default model
|
| 8 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 9 |
+
# DEFAULT_MODEL=gpt-4o
|
| 10 |
+
|
| 11 |
+
# Logging
|
| 12 |
+
LOG_LEVEL=INFO
|
| 13 |
+
|
| 14 |
+
# AI Hook Logging (set by instructor)
|
| 15 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 16 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 17 |
+
AI_LOG_DIR=.ai-log
|
.history/.env_20260703222056
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
# 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
|
| 7 |
+
# Default model
|
| 8 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 9 |
+
# DEFAULT_MODEL=gpt-4o
|
| 10 |
+
|
| 11 |
+
# Logging
|
| 12 |
+
LOG_LEVEL=INFO
|
| 13 |
+
|
| 14 |
+
# AI Hook Logging (set by instructor)
|
| 15 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 16 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 17 |
+
AI_LOG_DIR=.ai-log
|
.history/.env_20260703222101
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
# 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 của tôi
|
| 7 |
+
# Default model
|
| 8 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 9 |
+
# DEFAULT_MODEL=gpt-4o
|
| 10 |
+
|
| 11 |
+
# Logging
|
| 12 |
+
LOG_LEVEL=INFO
|
| 13 |
+
|
| 14 |
+
# AI Hook Logging (set by instructor)
|
| 15 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 16 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 17 |
+
AI_LOG_DIR=.ai-log
|
.history/.env_20260703222106
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Choose one or both providers
|
| 2 |
+
OPENAI_API_KEY=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
|
| 3 |
+
OPENAI_BASE_URL=https://openrouter.ai/api/v1
|
| 4 |
+
OPENAI_MODEL=deepseek/deepseek-v4-flash
|
| 5 |
+
# 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
|
| 6 |
+
# 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 của tôi
|
| 7 |
+
# Default model
|
| 8 |
+
DEFAULT_MODEL=claude-sonnet-4-20250514
|
| 9 |
+
# DEFAULT_MODEL=gpt-4o
|
| 10 |
+
|
| 11 |
+
# Logging
|
| 12 |
+
LOG_LEVEL=INFO
|
| 13 |
+
|
| 14 |
+
# AI Hook Logging (set by instructor)
|
| 15 |
+
AI_LOG_SERVER=https://ai-logs.note.transformerlabs.ai/api/ingest
|
| 16 |
+
AI_LOG_API_KEY=ai20k__9Mr6_Jl3j3E0JKOiFh499mhxzSl0A47
|
| 17 |
+
AI_LOG_DIR=.ai-log
|
.pytest_cache/v/cache/lastfailed
CHANGED
|
@@ -1,9 +1,15 @@
|
|
| 1 |
{
|
| 2 |
"tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true,
|
| 3 |
-
"tests/
|
| 4 |
-
"tests/
|
| 5 |
-
"tests/
|
| 6 |
-
"tests/
|
| 7 |
-
"tests/
|
| 8 |
-
"tests/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"tests/test_new_pipeline.py::test_pipeline_executor_completes_pick_and_place": true,
|
| 3 |
+
"tests/test_pipeline.py::test_grasp_survives_fast_translation": true,
|
| 4 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_1_g\\u1eafp qu\\u1ea3 chu\\u1ed1i l\\xean]": true,
|
| 5 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_2_g\\u1eafp lon s\\xfap \\u0111\\u1eb7t l\\xean b\\xe0n]": true,
|
| 6 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_3_g\\u1eafp bim bim b\\u1ecf v\\xe0o khay]": true,
|
| 7 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_4_\\u0111\\u1eb7t v\\xe0o khay]": true,
|
| 8 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_5_g\\u1eafp con m\\xe8o l\\xean]": true,
|
| 9 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_6_g\\u1eafp lon chips \\u0111\\u1eb7t c\\u1ea1nh qu\\u1ea3 chu\\u1ed1i]": true,
|
| 10 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_7_d\\u1ecdn b\\xe0n \\u0111i]": true,
|
| 11 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_8_g\\u1eafp v\\u1eadt n\\u1eb1m b\\xean tr\\xe1i qu\\u1ea3 chu\\u1ed1i \\u0111\\u1eb7t v\\xe0o khay]": true,
|
| 12 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_9_\\u0111\\u1eb7t qu\\u1ea3 chu\\u1ed1i l\\xean tr\\xean lon s\\xfap]": true,
|
| 13 |
+
"tests/test_llm_plan.py::test_remote_llm_planner_expected[Case_10_g\\u1eafp lon s\\xfap]": true,
|
| 14 |
+
"tests/test_multi_angle.py::test_side_grasp_pose_is_tilted": true
|
| 15 |
}
|
.pytest_cache/v/cache/nodeids
CHANGED
|
@@ -1,4 +1,30 @@
|
|
| 1 |
[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
"tests/test_cost_map.py::test_astar_finds_straight_path_on_empty_workspace",
|
| 3 |
"tests/test_cost_map.py::test_astar_routes_around_tall_obstacle",
|
| 4 |
"tests/test_cost_map.py::test_clearance_scales_with_carried_height",
|
|
@@ -71,6 +97,9 @@
|
|
| 71 |
"tests/test_occupancy.py::test_find_free_tray_placements_returns_spots",
|
| 72 |
"tests/test_occupancy.py::test_object_larger_than_table_has_no_placement",
|
| 73 |
"tests/test_occupancy.py::test_occupied_area_tracks_object_footprint",
|
|
|
|
|
|
|
|
|
|
| 74 |
"tests/test_occupancy.py::test_reachable_filter_is_applied",
|
| 75 |
"tests/test_occupancy.py::test_relation_left_of_places_on_correct_side",
|
| 76 |
"tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table",
|
|
|
|
| 1 |
[
|
| 2 |
+
"tests/test_conversation_memory.py::test_agent_keeps_one_shot_planner_input_unchanged",
|
| 3 |
+
"tests/test_conversation_memory.py::test_ambiguous_goal_is_clarified_before_planner_runs",
|
| 4 |
+
"tests/test_conversation_memory.py::test_cancel_clears_pending_without_another_planner_call",
|
| 5 |
+
"tests/test_conversation_memory.py::test_clear_removes_pending_and_recent_turns",
|
| 6 |
+
"tests/test_conversation_memory.py::test_complete_new_command_replaces_pending_request",
|
| 7 |
+
"tests/test_conversation_memory.py::test_default_replan_limit_is_finite",
|
| 8 |
+
"tests/test_conversation_memory.py::test_feature_flag_can_restore_stateless_behavior",
|
| 9 |
+
"tests/test_conversation_memory.py::test_follow_up_completes_rule_based_plan_without_extra_api_call",
|
| 10 |
+
"tests/test_conversation_memory.py::test_follow_up_marks_changed_scene_and_uses_fresh_state",
|
| 11 |
+
"tests/test_conversation_memory.py::test_follow_up_uses_exactly_one_planner_call_per_user_turn",
|
| 12 |
+
"tests/test_conversation_memory.py::test_goal_check_falls_back_to_live_geometry_for_on_top_relation",
|
| 13 |
+
"tests/test_conversation_memory.py::test_goal_resolution_parser_accepts_structured_clarification",
|
| 14 |
+
"tests/test_conversation_memory.py::test_goal_resolution_parser_rejects_ready_without_canonical_goal",
|
| 15 |
+
"tests/test_conversation_memory.py::test_invalid_clarification_choice_keeps_original_request_pending",
|
| 16 |
+
"tests/test_conversation_memory.py::test_invalid_physical_action_is_converted_to_clarification",
|
| 17 |
+
"tests/test_conversation_memory.py::test_one_shot_command_is_not_rewritten",
|
| 18 |
+
"tests/test_conversation_memory.py::test_pending_clarification_expires",
|
| 19 |
+
"tests/test_conversation_memory.py::test_pipeline_agent_setter_keeps_monitor_agent_in_sync",
|
| 20 |
+
"tests/test_conversation_memory.py::test_ready_goal_is_canonicalized_before_planning",
|
| 21 |
+
"tests/test_conversation_memory.py::test_remote_parser_accepts_structured_plan_wrapper",
|
| 22 |
+
"tests/test_conversation_memory.py::test_replan_can_skip_goal_resolution_gate",
|
| 23 |
+
"tests/test_conversation_memory.py::test_rule_based_move_request_tracks_missing_destination",
|
| 24 |
+
"tests/test_conversation_memory.py::test_sessions_do_not_share_pending_clarification",
|
| 25 |
+
"tests/test_conversation_memory.py::test_structured_clarification_metadata_is_preserved",
|
| 26 |
+
"tests/test_conversation_memory.py::test_structured_goal_check_uses_resolved_goal_not_raw_follow_up",
|
| 27 |
+
"tests/test_conversation_memory.py::test_structured_output_falls_back_once_when_provider_rejects",
|
| 28 |
"tests/test_cost_map.py::test_astar_finds_straight_path_on_empty_workspace",
|
| 29 |
"tests/test_cost_map.py::test_astar_routes_around_tall_obstacle",
|
| 30 |
"tests/test_cost_map.py::test_clearance_scales_with_carried_height",
|
|
|
|
| 97 |
"tests/test_occupancy.py::test_find_free_tray_placements_returns_spots",
|
| 98 |
"tests/test_occupancy.py::test_object_larger_than_table_has_no_placement",
|
| 99 |
"tests/test_occupancy.py::test_occupied_area_tracks_object_footprint",
|
| 100 |
+
"tests/test_occupancy.py::test_on_top_detection_accepts_small_physics_interpenetration",
|
| 101 |
+
"tests/test_occupancy.py::test_on_top_detection_rejects_object_floating_too_high",
|
| 102 |
+
"tests/test_occupancy.py::test_on_top_detection_rejects_side_contact_with_tiny_overlap",
|
| 103 |
"tests/test_occupancy.py::test_reachable_filter_is_applied",
|
| 104 |
"tests/test_occupancy.py::test_relation_left_of_places_on_correct_side",
|
| 105 |
"tests/test_occupancy.py::test_tray_object_does_not_count_against_the_table",
|
AGENTS.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Quy ước phát triển dự án
|
| 2 |
+
|
| 3 |
+
## Bảo toàn hành vi hiện có
|
| 4 |
+
|
| 5 |
+
- Phát triển tính năng mới theo hướng tương thích ngược.
|
| 6 |
+
- Không xóa, vô hiệu hóa, đổi tên hoặc thay đổi hành vi của tính năng hiện có nếu người dùng chưa yêu cầu tường minh.
|
| 7 |
+
- Nếu một thay đổi có thể ảnh hưởng hành vi hiện có, phải mô tả phạm vi và xin xác nhận của người dùng trước khi chỉnh sửa.
|
| 8 |
+
- Không tự ý dọn dẹp, hoàn tác hoặc ghi đè các thay đổi local đã tồn tại.
|
| 9 |
+
- Chỉ thay đổi những file cần thiết cho yêu cầu đang thực hiện.
|
| 10 |
+
|
| 11 |
+
## Kiểm tra trước và sau thay đổi
|
| 12 |
+
|
| 13 |
+
- Trước khi sửa, kiểm tra trạng thái Git và xác định các thay đổi local cần bảo toàn.
|
| 14 |
+
- Sau khi sửa, chạy kiểm tra phù hợp với mức rủi ro: tối thiểu là kiểm tra cú pháp và `git diff --check`; tính năng có test thì chạy test liên quan.
|
| 15 |
+
- Nếu test có lỗi không liên quan hoặc không thể chạy, ghi rõ trong báo cáo và development log.
|
| 16 |
+
|
| 17 |
+
## Development log bắt buộc
|
| 18 |
+
|
| 19 |
+
- Mỗi lần thực hiện thay đổi phải tạo đúng một file Markdown mới trong `development_logs/`.
|
| 20 |
+
- Tên file: `YYYY-MM-DD_HH-mm-ss_<mo-ta-ngan>.md`.
|
| 21 |
+
- Không ghi đè log cũ.
|
| 22 |
+
- Mỗi log cần nêu:
|
| 23 |
+
- yêu cầu của người dùng;
|
| 24 |
+
- phạm vi và giả định;
|
| 25 |
+
- file đã thêm/sửa/xóa;
|
| 26 |
+
- hành vi trước và sau;
|
| 27 |
+
- lệnh kiểm tra và kết quả;
|
| 28 |
+
- tính năng hiện có đã được bảo toàn;
|
| 29 |
+
- vấn đề còn lại hoặc việc cần người dùng quyết định.
|
| 30 |
+
- Không ghi API key, token, mật khẩu hoặc dữ liệu nhạy cảm vào log.
|
| 31 |
+
|
__pycache__/main.cpython-310.pyc
CHANGED
|
Binary files a/__pycache__/main.cpython-310.pyc and b/__pycache__/main.cpython-310.pyc differ
|
|
|
development_logs/2026-07-03_21-45-21_establish-development-policy.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Thiết lập quy ước phát triển
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Thiết lập nguyên tắc phát triển cẩn trọng: không xóa hoặc thay đổi tính năng cũ khi chưa có yêu cầu tường minh; thay đổi có ảnh hưởng phải xin xác nhận; mỗi lần thay đổi phải có một file log riêng.
|
| 6 |
+
|
| 7 |
+
## Phạm vi
|
| 8 |
+
|
| 9 |
+
- Chỉ bổ sung tài liệu quy ước và hệ thống development log.
|
| 10 |
+
- Không sửa mã nguồn hoặc hành vi của ứng dụng.
|
| 11 |
+
- Giữ nguyên các thay đổi local đã có trước lần thực hiện này.
|
| 12 |
+
|
| 13 |
+
## File thay đổi
|
| 14 |
+
|
| 15 |
+
- Thêm `AGENTS.md`.
|
| 16 |
+
- Thêm `development_logs/2026-07-03_21-45-21_establish-development-policy.md`.
|
| 17 |
+
|
| 18 |
+
## Hành vi trước và sau
|
| 19 |
+
|
| 20 |
+
- Trước: repo chưa có quy ước dành cho agent và chưa có folder log riêng cho từng lần phát triển.
|
| 21 |
+
- Sau: quy tắc bảo toàn tính năng, yêu cầu xin xác nhận và định dạng development log đã được ghi rõ trong repo.
|
| 22 |
+
|
| 23 |
+
## Kiểm tra
|
| 24 |
+
|
| 25 |
+
- Xác nhận `AGENTS.md` và `development_logs/` chưa tồn tại trước khi tạo.
|
| 26 |
+
- `git diff --check`: đạt; chỉ có cảnh báo chuyển đổi LF/CRLF trên file local có sẵn `llm_panda/robot_controller.py`.
|
| 27 |
+
- `git status --short`: xác nhận chỉ thêm tài liệu/log mới; các thay đổi local có sẵn vẫn được giữ nguyên.
|
| 28 |
+
|
| 29 |
+
## Bảo toàn
|
| 30 |
+
|
| 31 |
+
- Không thay đổi tính năng hiện có.
|
| 32 |
+
- Không thay đổi `llm_panda/robot_controller.py` đang có sửa đổi local từ trước.
|
| 33 |
+
- Không xóa các file lịch sử local trong `.history/`.
|
| 34 |
+
|
| 35 |
+
## Vấn đề còn lại
|
| 36 |
+
|
| 37 |
+
- Skill `dream` được khảo sát ở chế độ dry-run theo yêu cầu lần đầu; repo hiện chưa có hệ thống memory riêng. Không cài hook hoặc tạo memory ngoài repo.
|
development_logs/2026-07-03_21-51-49_plan-conversation-memory.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Lập kế hoạch conversation memory
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Phân tích và xây dựng kế hoạch bổ sung khả năng nhớ hội thoại để robot có thể nối
|
| 6 |
+
câu trả lời clarification với yêu cầu trước, sử dụng API LLM, đồng thời bảo đảm
|
| 7 |
+
hiệu năng và trải nghiệm người dùng.
|
| 8 |
+
|
| 9 |
+
## Phạm vi và giả định
|
| 10 |
+
|
| 11 |
+
- Chỉ khảo sát và lập tài liệu kế hoạch.
|
| 12 |
+
- Không sửa hành vi planner, executor, frontend hoặc API trong lần này.
|
| 13 |
+
- Ưu tiên short-term session memory; persistence dài hạn cần được phê duyệt riêng.
|
| 14 |
+
|
| 15 |
+
## File thay đổi
|
| 16 |
+
|
| 17 |
+
- Thêm `docs/CONVERSATION_MEMORY_PLAN.md`.
|
| 18 |
+
- Thêm `development_logs/2026-07-03_21-51-49_plan-conversation-memory.md`.
|
| 19 |
+
|
| 20 |
+
## Phát hiện chính
|
| 21 |
+
|
| 22 |
+
- Remote planner chỉ nhận system prompt, scene hiện tại và câu lệnh hiện tại.
|
| 23 |
+
- Clarification được trả về UI rồi pipeline kết thúc mà không lưu pending intent.
|
| 24 |
+
- Web và PySide tạo planner/agent mới theo từng lệnh.
|
| 25 |
+
- Web có simulation state global; memory mới phải cô lập theo session ID.
|
| 26 |
+
|
| 27 |
+
## Hành vi trước và sau
|
| 28 |
+
|
| 29 |
+
- Trước: chưa có thiết kế conversation memory thống nhất.
|
| 30 |
+
- Sau: có kế hoạch kiến trúc, mô hình dữ liệu, lifecycle, rollout, rollback,
|
| 31 |
+
performance budget và test matrix.
|
| 32 |
+
- Hành vi runtime chưa thay đổi.
|
| 33 |
+
|
| 34 |
+
## Kiểm tra
|
| 35 |
+
|
| 36 |
+
- Đối chiếu các luồng CLI, Tkinter, PySide và Web.
|
| 37 |
+
- Đối chiếu xử lý `clarify/reject` trong planner và pipeline.
|
| 38 |
+
- Tham khảo tài liệu chính thức về thread memory, summarization, OpenRouter
|
| 39 |
+
structured outputs và prompt caching.
|
| 40 |
+
- `git diff --check`: đạt; chỉ có cảnh báo LF/CRLF trên
|
| 41 |
+
`llm_panda/robot_controller.py`, là file local đã thay đổi từ trước.
|
| 42 |
+
- Xác nhận tài liệu có đầy đủ 16 phần và không sửa runtime code.
|
| 43 |
+
|
| 44 |
+
## Bảo toàn
|
| 45 |
+
|
| 46 |
+
- Không sửa hoặc xóa tính năng hiện có.
|
| 47 |
+
- Không thay đổi các local modification có sẵn trong `robot_controller.py` và
|
| 48 |
+
`.history/`.
|
| 49 |
+
|
| 50 |
+
## Vấn đề còn lại
|
| 51 |
+
|
| 52 |
+
- Cần người dùng phê duyệt Phase 1 trước khi triển khai code.
|
| 53 |
+
- Persistence qua restart và multi-user simulation isolation nằm ngoài Phase 1.
|
development_logs/2026-07-03_22-06-50_implement-conversation-memory-phase1.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Triển khai conversation memory Phase 1
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Bắt đầu thực hiện kế hoạch bổ sung khả năng nhớ hội thoại để robot nối câu trả
|
| 6 |
+
lời clarification với yêu cầu trước.
|
| 7 |
+
|
| 8 |
+
## Phạm vi và giả định
|
| 9 |
+
|
| 10 |
+
- Triển khai Phase 1: memory chỉ tồn tại trong vòng đời session/process.
|
| 11 |
+
- Không thêm database, vector store hoặc framework agent mới.
|
| 12 |
+
- Không thêm API call; mỗi user turn vẫn gọi planner đúng một lần.
|
| 13 |
+
- Không thay đổi executor, chuyển động robot, verifier hoặc safety guardrails.
|
| 14 |
+
|
| 15 |
+
## File thêm mới
|
| 16 |
+
|
| 17 |
+
- `llm_panda/conversation/__init__.py`
|
| 18 |
+
- `llm_panda/conversation/models.py`
|
| 19 |
+
- `llm_panda/conversation/manager.py`
|
| 20 |
+
- `tests/test_conversation_memory.py`
|
| 21 |
+
- `development_logs/2026-07-03_22-06-50_implement-conversation-memory-phase1.md`
|
| 22 |
+
|
| 23 |
+
## File chỉnh sửa
|
| 24 |
+
|
| 25 |
+
- `.env.example`
|
| 26 |
+
- `llm_panda/llm_agent.py`
|
| 27 |
+
- `main.py`
|
| 28 |
+
- `frontend/interactive_server.py`
|
| 29 |
+
- `frontend/app.js`
|
| 30 |
+
- `frontend/controllers/ui_controller.py`
|
| 31 |
+
- `frontend/threads/llm_thread.py`
|
| 32 |
+
- `frontend/overlay_app.py`
|
| 33 |
+
- `docs/CONVERSATION_MEMORY_PLAN.md`
|
| 34 |
+
|
| 35 |
+
## Hành vi trước và sau
|
| 36 |
+
|
| 37 |
+
### Trước
|
| 38 |
+
|
| 39 |
+
- Planner chỉ nhận câu lệnh hiện tại và scene hiện tại.
|
| 40 |
+
- Khi trả `clarify`, câu lệnh gốc và câu hỏi robot bị mất.
|
| 41 |
+
- Web/PySide tạo planner mới theo từng lệnh nên không có context nối tiếp.
|
| 42 |
+
|
| 43 |
+
### Sau
|
| 44 |
+
|
| 45 |
+
- Mỗi session có `ConversationManager` riêng.
|
| 46 |
+
- `clarify` lưu câu lệnh gốc và câu hỏi trong tối đa 10 phút.
|
| 47 |
+
- Câu trả lời tiếp theo được ghép thành context cho planner trong cùng API call.
|
| 48 |
+
- Plan hoàn chỉnh hoặc `reject` đóng pending clarification.
|
| 49 |
+
- Reset scene, đổi environment hoặc đóng WebSocket xóa memory.
|
| 50 |
+
- Web/PySide hiển thị clarification như hội thoại, không cố execute và không ghi
|
| 51 |
+
nhầm thành một lần robot chạy thất bại.
|
| 52 |
+
- Có thể rollback về stateless bằng
|
| 53 |
+
`CONVERSATION_MEMORY_ENABLED=false`.
|
| 54 |
+
|
| 55 |
+
## Kiểm tra và kết quả
|
| 56 |
+
|
| 57 |
+
- Baseline `tests/test_pipeline.py`: 25 pass, 1 lỗi có sẵn
|
| 58 |
+
`PandaApp.grasp_planner` trước khi triển khai.
|
| 59 |
+
- `tests/test_conversation_memory.py`: 8 pass.
|
| 60 |
+
- Regression offline:
|
| 61 |
+
- `tests/test_monitor.py`
|
| 62 |
+
- `tests/test_pipeline.py` (loại test baseline lỗi)
|
| 63 |
+
- kết quả: 31 pass, 1 deselected.
|
| 64 |
+
- Tập regression rộng hơn, loại remote API và baseline lỗi:
|
| 65 |
+
43 pass, 3 skip, 11 deselected.
|
| 66 |
+
- Python `py_compile`: đạt cho core và các frontend Python đã sửa.
|
| 67 |
+
- `node --check frontend/app.js`: đạt.
|
| 68 |
+
- Frontend import smoke test: đạt.
|
| 69 |
+
- `git diff --check`: đạt; chỉ có cảnh báo LF/CRLF.
|
| 70 |
+
- Benchmark `ConversationManager.contextualize()`:
|
| 71 |
+
khoảng 0,0011 ms trung bình trên 100.000 lần gọi.
|
| 72 |
+
|
| 73 |
+
## Kiểm tra API
|
| 74 |
+
|
| 75 |
+
- Các test gọi OpenRouter không chạy được trong sandbox vì network bị chặn.
|
| 76 |
+
- Không sửa API key và không ghi secret vào log.
|
| 77 |
+
- Planner API vẫn dùng cùng một request cho mỗi user turn.
|
| 78 |
+
|
| 79 |
+
## Bảo toàn
|
| 80 |
+
|
| 81 |
+
- Giữ nguyên thay đổi tốc độ robot `time_scale = 0.1` có trước lần triển khai.
|
| 82 |
+
- Không xóa hoặc hoàn tác file local trong `.history/`.
|
| 83 |
+
- Lệnh một lượt được truyền nguyên văn tới planner và có test regression riêng.
|
| 84 |
+
- Executor và toàn bộ kiểm tra an toàn hiện có không thay đổi.
|
| 85 |
+
|
| 86 |
+
## Giới hạn còn lại
|
| 87 |
+
|
| 88 |
+
- Memory mất khi process/Hugging Face Space restart.
|
| 89 |
+
- Recent-turn buffer đã được giới hạn nhưng Phase 1 mới dùng pending
|
| 90 |
+
clarification; rolling summary chưa bật.
|
| 91 |
+
- Web vẫn dùng simulation global; memory đã tách theo WebSocket nhưng simulation
|
| 92 |
+
multi-user isolation là hạng mục riêng.
|
| 93 |
+
- Structured output, OpenRouter `session_id` và persistent store thuộc Phase 2–4.
|
| 94 |
+
|
development_logs/2026-07-03_22-18-37_implement-conversation-memory-phase2.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Triển khai conversation memory Phase 2
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Tiếp tục Phase 2 của kế hoạch conversation memory.
|
| 6 |
+
|
| 7 |
+
## Phạm vi
|
| 8 |
+
|
| 9 |
+
- Mở rộng pending clarification thành dialogue state có cấu trúc.
|
| 10 |
+
- Thêm cancel, replace-intent, expiry và scene revision.
|
| 11 |
+
- Bổ sung structured output cho OpenRouter/model hỗ trợ.
|
| 12 |
+
- Giữ nguyên plan-array API, executor và safety pipeline.
|
| 13 |
+
- Không triển khai rolling summary hoặc persistence qua restart.
|
| 14 |
+
|
| 15 |
+
## File chỉnh sửa trong Phase 2
|
| 16 |
+
|
| 17 |
+
- `llm_panda/conversation/models.py`
|
| 18 |
+
- `llm_panda/conversation/manager.py`
|
| 19 |
+
- `llm_panda/llm_agent.py`
|
| 20 |
+
- `tests/test_conversation_memory.py`
|
| 21 |
+
- `.env.example`
|
| 22 |
+
- `docs/CONVERSATION_MEMORY_PLAN.md`
|
| 23 |
+
|
| 24 |
+
## Hành vi trước và sau
|
| 25 |
+
|
| 26 |
+
### Trước
|
| 27 |
+
|
| 28 |
+
- Pending state chỉ có câu lệnh gốc và câu hỏi robot.
|
| 29 |
+
- Không biết field còn thiếu hoặc partial intent.
|
| 30 |
+
- Không xử lý trực tiếp cancel/lệnh mới thay thế.
|
| 31 |
+
- Không biết scene có thay đổi giữa hai lượt.
|
| 32 |
+
- Remote planner chỉ parse plan array tự do.
|
| 33 |
+
|
| 34 |
+
### Sau
|
| 35 |
+
|
| 36 |
+
- Pending state lưu:
|
| 37 |
+
- `missing_fields`;
|
| 38 |
+
- `partial_intent`;
|
| 39 |
+
- `scene_revision`;
|
| 40 |
+
- TTL hiện có.
|
| 41 |
+
- RuleBased và system prompt RemoteLLM cung cấp metadata clarification.
|
| 42 |
+
- `thôi`, `hủy`, `cancel` và các biến thể đóng pending state mà không gọi LLM.
|
| 43 |
+
- Một lệnh mới có action + object thay thế yêu cầu đang chờ.
|
| 44 |
+
- Follow-up được thông báo nếu scene đã thay đổi và luôn dùng scene mới nhất.
|
| 45 |
+
- Remote planner thử JSON Schema structured output ở chế độ `auto` trên
|
| 46 |
+
OpenRouter; nếu provider/model trả 400/404/422, tự fallback về plan-array parser
|
| 47 |
+
và ghi nhớ capability cho các lượt sau.
|
| 48 |
+
- Parser chấp nhận cả:
|
| 49 |
+
- plan array cũ;
|
| 50 |
+
- object wrapper `{"plan": [...]}` mới.
|
| 51 |
+
|
| 52 |
+
## Cấu hình
|
| 53 |
+
|
| 54 |
+
- `CONVERSATION_MEMORY_ENABLED=true`: bật/tắt toàn bộ memory.
|
| 55 |
+
- `LLM_STRUCTURED_OUTPUTS_ENABLED=auto`:
|
| 56 |
+
- `auto`: thử structured output trên OpenRouter;
|
| 57 |
+
- `true`: bắt đầu bằng structured output với mọi endpoint;
|
| 58 |
+
- `false`: luôn dùng plan-array parser cũ.
|
| 59 |
+
|
| 60 |
+
## Kiểm tra
|
| 61 |
+
|
| 62 |
+
- `tests/test_conversation_memory.py`: 15 pass.
|
| 63 |
+
- Regression `conversation + monitor + pipeline`:
|
| 64 |
+
46 pass, 1 baseline test deselected.
|
| 65 |
+
- Python `py_compile`: đạt.
|
| 66 |
+
- `node --check frontend/app.js`: đạt.
|
| 67 |
+
- `git diff --check`: đạt; chỉ có cảnh báo LF/CRLF.
|
| 68 |
+
- Structured-output fallback được test bằng fake provider:
|
| 69 |
+
- request đầu trả 400;
|
| 70 |
+
- request fallback bỏ `response_format`;
|
| 71 |
+
- plan vẫn parse thành công;
|
| 72 |
+
- capability được cache là không hỗ trợ.
|
| 73 |
+
- Benchmark context Phase 2:
|
| 74 |
+
khoảng 0,0287 ms trung bình trên 100.000 lần gọi.
|
| 75 |
+
|
| 76 |
+
## Bảo toàn
|
| 77 |
+
|
| 78 |
+
- Không sửa executor, robot motion, verifier hoặc guardrails.
|
| 79 |
+
- Plan array hiện tại tiếp tục được chấp nhận.
|
| 80 |
+
- Lệnh một lượt không có pending state vẫn được chuyển nguyên văn.
|
| 81 |
+
- Giữ nguyên thay đổi tốc độ robot `time_scale = 0.1`.
|
| 82 |
+
- Không thay đổi/xóa các file local trong `.history/`.
|
| 83 |
+
- Không ghi API key hoặc dữ liệu nhạy cảm.
|
| 84 |
+
|
| 85 |
+
## Giới hạn
|
| 86 |
+
|
| 87 |
+
- Chưa xác minh live structured output với OpenRouter trong sandbox do network bị
|
| 88 |
+
chặn; fallback đã được test offline.
|
| 89 |
+
- Heuristic lệnh mới ưu tiên action + object rõ ràng; trường hợp ngôn ngữ cực kỳ
|
| 90 |
+
mơ hồ vẫn được giao cho LLM phân loại.
|
| 91 |
+
- Memory vẫn mất khi process/Hugging Face Space restart.
|
| 92 |
+
- Rolling summary, prompt `session_id` và persistent store thuộc Phase 3–4.
|
| 93 |
+
|
development_logs/2026-07-03_22-40-00_plan-context-aware-goal-check.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Lập kế hoạch sửa Goal Check theo ngữ cảnh
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Đọc log thực tế, xác định vì sao Goal Check chỉ dựa trên prompt gần nhất thay vì toàn
|
| 6 |
+
bộ ngữ cảnh hội thoại, và lập kế hoạch sửa chính xác.
|
| 7 |
+
|
| 8 |
+
## Phạm vi và giả định
|
| 9 |
+
|
| 10 |
+
- Chỉ phân tích và tạo tài liệu kế hoạch.
|
| 11 |
+
- Không sửa runtime, prompt, planner, monitor, executor hay giao diện trong lần này.
|
| 12 |
+
- Giữ nguyên toàn bộ thay đổi local và tính năng conversation memory Phase 1/2.
|
| 13 |
+
|
| 14 |
+
## File thay đổi
|
| 15 |
+
|
| 16 |
+
- Thêm `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md`.
|
| 17 |
+
- Thêm `development_logs/2026-07-03_22-40-00_plan-context-aware-goal-check.md`.
|
| 18 |
+
|
| 19 |
+
## Phát hiện chính
|
| 20 |
+
|
| 21 |
+
- Planner có `effective_command` đã contextualize nhưng giá trị này chỉ là biến cục
|
| 22 |
+
bộ và không được chuyển cho monitor.
|
| 23 |
+
- Web và execution pipeline truyền raw prompt gần nhất vào Goal Check.
|
| 24 |
+
- Reject của một lựa chọn clarification không hợp lệ đang xóa pending intent gốc.
|
| 25 |
+
- Re-plan dùng lại raw follow-up và failure reason, khiến goal bị thay đổi qua từng
|
| 26 |
+
attempt.
|
| 27 |
+
- Web thay pipeline agent nhưng không cập nhật tham chiếu agent trong monitor.
|
| 28 |
+
- `MAX_REPLANS=999999` khuếch đại lỗi ngữ nghĩa thành vòng lặp dài.
|
| 29 |
+
|
| 30 |
+
## Hành vi trước và sau
|
| 31 |
+
|
| 32 |
+
- Trước: chưa có kế hoạch riêng để giữ một goal đã resolve xuyên suốt planning,
|
| 33 |
+
execution, monitoring và re-planning.
|
| 34 |
+
- Sau: có thiết kế `TaskContext`/`ResolvedGoal`, deterministic predicates, LLM
|
| 35 |
+
fallback, clarification lifecycle, loop guard, rollout và test matrix.
|
| 36 |
+
- Hành vi runtime chưa thay đổi.
|
| 37 |
+
|
| 38 |
+
## Kiểm tra
|
| 39 |
+
|
| 40 |
+
- Đọc toàn bộ log đính kèm và đối chiếu các điểm Goal Check/re-plan.
|
| 41 |
+
- Đối chiếu `ConversationManager`, `LLMAgent`, `ExecutionMonitor`, Web pipeline và
|
| 42 |
+
execution pipeline.
|
| 43 |
+
- Chạy `git diff --check` sau khi tạo tài liệu.
|
| 44 |
+
|
| 45 |
+
## Bảo toàn
|
| 46 |
+
|
| 47 |
+
- Không xóa hoặc sửa tính năng hiện có.
|
| 48 |
+
- Không sửa `.env`, tốc độ robot, action schema hoặc các file runtime.
|
| 49 |
+
- Không ghi API key hay dữ liệu bí mật vào log.
|
| 50 |
+
|
| 51 |
+
## Việc cần người dùng xác nhận
|
| 52 |
+
|
| 53 |
+
Trước khi triển khai cần xác nhận:
|
| 54 |
+
|
| 55 |
+
- giữ pending sau invalid clarification answer;
|
| 56 |
+
- dùng deterministic Goal Check cho các predicate phổ biến;
|
| 57 |
+
- giảm giới hạn re-plan mặc định từ `999999` xuống giá trị hữu hạn (khuyến nghị 3).
|
development_logs/2026-07-03_22-46-06_implement-context-aware-goal-check.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Triển khai Goal Check theo ngữ cảnh
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Thực hiện kế hoạch sửa lỗi Goal Check chỉ dùng prompt gần nhất, khiến một follow-up
|
| 6 |
+
mơ hồ bị diễn giải khác nhau và robot di chuyển vật qua lại.
|
| 7 |
+
|
| 8 |
+
## Phạm vi và giả định
|
| 9 |
+
|
| 10 |
+
- Triển khai ba thay đổi đã được người dùng phê duyệt bằng yêu cầu “thực hiện đi”.
|
| 11 |
+
- Giữ API `LLMAgent.plan()` trả plan list và giữ nguyên action schema.
|
| 12 |
+
- Không thay đổi executor chuyển động, obstacle clearing, tốc độ robot hoặc scoring.
|
| 13 |
+
- Structured Goal Check bật mặc định nhưng có feature flag để rollback.
|
| 14 |
+
|
| 15 |
+
## File thêm/sửa
|
| 16 |
+
|
| 17 |
+
- Sửa `.env.example`.
|
| 18 |
+
- Sửa `frontend/interactive_server.py`.
|
| 19 |
+
- Sửa `llm_panda/conversation/__init__.py`.
|
| 20 |
+
- Sửa `llm_panda/conversation/models.py`.
|
| 21 |
+
- Sửa `llm_panda/conversation/manager.py`.
|
| 22 |
+
- Sửa `llm_panda/llm_agent.py`.
|
| 23 |
+
- Sửa `llm_panda/execution/monitor.py`.
|
| 24 |
+
- Sửa `llm_panda/execution/pipeline.py`.
|
| 25 |
+
- Sửa `tests/test_conversation_memory.py`.
|
| 26 |
+
- Sửa `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md`.
|
| 27 |
+
- Thêm log triển khai này.
|
| 28 |
+
|
| 29 |
+
## Hành vi trước
|
| 30 |
+
|
| 31 |
+
- Goal Check nhận raw prompt cuối thay vì intent đã hợp nhất.
|
| 32 |
+
- `effective_command` biến mất sau planning.
|
| 33 |
+
- Invalid clarification answer đóng pending request.
|
| 34 |
+
- Re-plan dùng lại câu follow-up mơ hồ.
|
| 35 |
+
- Web pipeline agent và monitor agent có thể lệch nhau.
|
| 36 |
+
- Mặc định cho phép 999999 lần re-plan.
|
| 37 |
+
|
| 38 |
+
## Hành vi sau
|
| 39 |
+
|
| 40 |
+
- Planning tạo `ResolvedGoal` bất biến với machine-checkable predicates.
|
| 41 |
+
- Goal được biên dịch từ semantic plan trước các bước dọn blocker.
|
| 42 |
+
- Follow-up không được tự mở rộng partial intent: yêu cầu pick-up không thể bị LLM
|
| 43 |
+
tự thêm move/place.
|
| 44 |
+
- Invalid choice giữ pending gốc để người dùng chọn lại.
|
| 45 |
+
- Execution/re-plan/Goal Check dùng chung resolved goal.
|
| 46 |
+
- Pick-up, location và spatial relation được kiểm tra deterministic; LLM chỉ fallback
|
| 47 |
+
nếu predicate chưa được hỗ trợ.
|
| 48 |
+
- Pipeline agent setter tự đồng bộ execution monitor.
|
| 49 |
+
- Re-plan mặc định tối đa 3, có thể cấu hình bằng `MAX_REPLANS`.
|
| 50 |
+
|
| 51 |
+
## Kiểm tra và kết quả
|
| 52 |
+
|
| 53 |
+
- `python -m pytest tests/test_conversation_memory.py tests/test_monitor.py -q`:
|
| 54 |
+
25 passed ở lần kiểm tra trung gian.
|
| 55 |
+
- `python -m pytest tests/test_conversation_memory.py tests/test_monitor.py
|
| 56 |
+
tests/test_obstacle_graph.py tests/test_occupancy.py tests/test_cost_map.py -q`:
|
| 57 |
+
53 passed.
|
| 58 |
+
- Regression rộng không dùng `tests/test_pipeline.py`: 73 passed, 3 skipped,
|
| 59 |
+
12 failed. Trong đó 10 test Remote LLM thất bại vì sandbox chặn kết nối mạng;
|
| 60 |
+
2 lỗi baseline không liên quan (`PandaApp.grasp_planner` và
|
| 61 |
+
`config.YCB_CATALOG` không tồn tại).
|
| 62 |
+
- `python -m pytest tests/test_pipeline.py -q`: 25 passed, 1 baseline failure
|
| 63 |
+
`test_grasp_survives_fast_translation` do `PandaApp.grasp_planner` không tồn tại.
|
| 64 |
+
- Python compile và `git diff --check` được chạy ở bước xác minh cuối.
|
| 65 |
+
|
| 66 |
+
## Bảo toàn tính năng
|
| 67 |
+
|
| 68 |
+
- Không xóa hay đổi tên API cũ.
|
| 69 |
+
- Obstacle clearing vẫn áp dụng sau khi chốt semantic goal.
|
| 70 |
+
- Rule planner, Remote planner, Web, CLI/Tk và app tiếp tục dùng plan list cũ.
|
| 71 |
+
- Không sửa `.env`, secrets, tốc độ robot hoặc các thay đổi `.history`.
|
| 72 |
+
|
| 73 |
+
## Vấn đề còn lại
|
| 74 |
+
|
| 75 |
+
- Test Remote LLM thật cần chạy ngoài sandbox có network.
|
| 76 |
+
- Các baseline failure về `PandaApp.grasp_planner` và `config.YCB_CATALOG` nằm ngoài
|
| 77 |
+
phạm vi thay đổi này.
|
| 78 |
+
- LLM fallback cũ vẫn tồn tại cho goal chưa có predicate; có thể mở rộng predicate
|
| 79 |
+
theo loại nhiệm vụ mới trong các phase sau.
|
development_logs/2026-07-03_23-01-35_implement-preplanning-goal-resolution.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Triển khai Goal Resolution trước planning
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Không cho action thiếu `object_id` đi xuống executor. LLM phải xác định câu lệnh đã
|
| 6 |
+
đủ rõ hay chưa; nếu mơ hồ thì hỏi lại. Chỉ sau khi goal rõ ràng mới lập kế hoạch và
|
| 7 |
+
Goal Check phải dùng goal đã chốt.
|
| 8 |
+
|
| 9 |
+
Ca tái hiện: `gắp quả lên lon chip` trong scene có nhiều loại quả.
|
| 10 |
+
|
| 11 |
+
## Phạm vi và giả định
|
| 12 |
+
|
| 13 |
+
- Remote LLM dùng thêm một API call cho Goal Resolution ở đầu mỗi tác vụ mới.
|
| 14 |
+
- Re-plan không gọi lại Goal Resolution vì đã có canonical resolved goal.
|
| 15 |
+
- RuleBasedPlanner và API plan list cũ tiếp tục hoạt động như trước.
|
| 16 |
+
- Có feature flag `LLM_GOAL_RESOLUTION_ENABLED` để rollback.
|
| 17 |
+
|
| 18 |
+
## File sửa
|
| 19 |
+
|
| 20 |
+
- `.env.example`
|
| 21 |
+
- `llm_panda/llm_agent.py`
|
| 22 |
+
- `llm_panda/execution/pipeline.py`
|
| 23 |
+
- `frontend/interactive_server.py`
|
| 24 |
+
- `tests/test_conversation_memory.py`
|
| 25 |
+
- `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md`
|
| 26 |
+
- Thêm development log này.
|
| 27 |
+
|
| 28 |
+
## Hành vi trước
|
| 29 |
+
|
| 30 |
+
- Remote planner có thể tự suy diễn generic noun `quả`.
|
| 31 |
+
- JSON schema chỉ yêu cầu `args` là object, không bắt buộc `object_id`.
|
| 32 |
+
- `pick_up` với args rỗng vẫn qua `_valid()`, gây lỗi runtime `'object_id'`.
|
| 33 |
+
|
| 34 |
+
## Hành vi sau
|
| 35 |
+
|
| 36 |
+
- `RemoteLLMPlanner.resolve_goal()` phân loại `ready`, `clarify`, `reject`.
|
| 37 |
+
- Generic noun khớp nhiều object phải clarify, không được đoán.
|
| 38 |
+
- Planner chỉ được gọi với `canonical_instruction` sau trạng thái `ready`.
|
| 39 |
+
- Clarification giữ các phần intent đã biết như relation và reference object.
|
| 40 |
+
- `_valid()` bắt buộc:
|
| 41 |
+
- `pick_up.object_id` là chuỗi không rỗng;
|
| 42 |
+
- `move_to.location_id` thuộc location hợp lệ;
|
| 43 |
+
- `clarify/reject.message` không rỗng.
|
| 44 |
+
- Plan rỗng hoặc có bất kỳ action sai schema được chuyển thành clarification an toàn.
|
| 45 |
+
- Re-plan dùng resolved goal hiện có và bỏ qua Goal Resolution Gate.
|
| 46 |
+
|
| 47 |
+
## Kiểm tra
|
| 48 |
+
|
| 49 |
+
- Test chứng minh `gắp quả lên lon chip` trả clarification trước planner.
|
| 50 |
+
- Test chứng minh canonical goal là input duy nhất của planner khi `ready`.
|
| 51 |
+
- Test action `pick_up` thiếu `object_id` bị đổi thành clarification.
|
| 52 |
+
- Test re-plan không gọi lại goal resolver.
|
| 53 |
+
- Test parser từ chối trạng thái `ready` thiếu canonical goal.
|
| 54 |
+
- `python -m pytest tests/test_conversation_memory.py tests/test_monitor.py
|
| 55 |
+
tests/test_obstacle_graph.py tests/test_occupancy.py tests/test_cost_map.py -q`:
|
| 56 |
+
**59 passed**.
|
| 57 |
+
- Python compile và `git diff --check` chạy ở bước xác minh cuối.
|
| 58 |
+
|
| 59 |
+
## Bảo toàn
|
| 60 |
+
|
| 61 |
+
- Không sửa executor chuyển động, obstacle clearing, scoring hay tốc độ robot.
|
| 62 |
+
- Không sửa `.env`, secret hoặc `.history`.
|
| 63 |
+
- `LLMAgent.plan()` vẫn trả list action như API cũ.
|
| 64 |
+
- Web, GUI/app, Tk và CLI tiếp tục dùng conversation manager hiện tại.
|
| 65 |
+
|
| 66 |
+
## Vấn đề còn lại
|
| 67 |
+
|
| 68 |
+
- Live OpenRouter Goal Resolution cần xác minh ngoài sandbox có network.
|
| 69 |
+
- Mỗi tác vụ Remote LLM mới tăng từ một lên hai API call; đổi lại planner không chạy
|
| 70 |
+
khi goal mơ hồ. Re-plan không phát sinh call resolution bổ sung.
|
development_logs/2026-07-03_23-10-10_fix-on-top-goal-check.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Sửa Goal Check nhận sai quan hệ on_top_of
|
| 2 |
+
|
| 3 |
+
## Yêu cầu
|
| 4 |
+
|
| 5 |
+
Giải thích và sửa trường hợp quả lê đã được đặt trên lon chips trong mô phỏng nhưng
|
| 6 |
+
Structured Goal Check vẫn báo:
|
| 7 |
+
|
| 8 |
+
`pear.on_top_of=None, expected 'chips_can'`.
|
| 9 |
+
|
| 10 |
+
## Nguyên nhân
|
| 11 |
+
|
| 12 |
+
`SceneManager.get_scene_state()` trước đây chỉ nhận `on_top_of` khi:
|
| 13 |
+
|
| 14 |
+
- AABB hai vật có chồng lấn XY;
|
| 15 |
+
- đáy A không xuyên xuống đỉnh B quá `0.02 m`;
|
| 16 |
+
- đáy A không cách đỉnh B quá `0.05 m`.
|
| 17 |
+
|
| 18 |
+
Quả lê là vật tròn/mesh và có thể nghiêng hoặc settle vào collision support. AABB đáy
|
| 19 |
+
của lê vì vậy có thể thấp hơn đỉnh AABB lon quá 2 cm dù vật đang nằm đúng trên lon.
|
| 20 |
+
Scene gán `on_top_of=None`; Structured Goal Check tin tuyệt đối vào nhãn này và tạo
|
| 21 |
+
false negative.
|
| 22 |
+
|
| 23 |
+
## Phạm vi và giả định
|
| 24 |
+
|
| 25 |
+
- Chỉ sửa nhận diện quan hệ stack và verification fallback.
|
| 26 |
+
- Không thay đổi tọa độ đặt vật, trajectory, grasp, physics hoặc planner.
|
| 27 |
+
- Vẫn phải tránh nhận nhầm vật chạm cạnh hoặc đang bay phía trên là stack.
|
| 28 |
+
|
| 29 |
+
## File sửa
|
| 30 |
+
|
| 31 |
+
- `llm_panda/scene_manager.py`
|
| 32 |
+
- `llm_panda/execution/monitor.py`
|
| 33 |
+
- `tests/test_occupancy.py`
|
| 34 |
+
- `tests/test_conversation_memory.py`
|
| 35 |
+
- `docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md`
|
| 36 |
+
- Thêm development log này.
|
| 37 |
+
|
| 38 |
+
## Hành vi sau
|
| 39 |
+
|
| 40 |
+
- `SceneManager._aabb_is_on_top()` dùng:
|
| 41 |
+
- tỷ lệ diện tích overlap XY tối thiểu 15%;
|
| 42 |
+
- tâm vật trên phải cao hơn tâm support;
|
| 43 |
+
- vertical gap từ `-0.06 m` đến `+0.08 m`.
|
| 44 |
+
- Scene state và live monitor dùng cùng một định nghĩa.
|
| 45 |
+
- Nếu final scene relation vẫn là `None`, monitor kiểm tra lại AABB live qua
|
| 46 |
+
`scene.is_on_top()` trước khi kết luận thất bại.
|
| 47 |
+
- Vật chỉ chạm cạnh với overlap nhỏ và vật bay quá cao vẫn bị từ chối.
|
| 48 |
+
|
| 49 |
+
## Kiểm tra
|
| 50 |
+
|
| 51 |
+
- Test stack có interpenetration 4 cm: được nhận đúng.
|
| 52 |
+
- Test side contact overlap nhỏ: không bị nhận nhầm.
|
| 53 |
+
- Test vật bay cao: không bị nhận nhầm.
|
| 54 |
+
- Test monitor fallback từ relation `None` sang live AABB: đạt.
|
| 55 |
+
- `python -m pytest tests/test_conversation_memory.py tests/test_monitor.py
|
| 56 |
+
tests/test_obstacle_graph.py tests/test_occupancy.py tests/test_cost_map.py -q`:
|
| 57 |
+
**63 passed**.
|
| 58 |
+
- Python compile và `git diff --check` chạy ở bước xác minh cuối.
|
| 59 |
+
|
| 60 |
+
## Bảo toàn
|
| 61 |
+
|
| 62 |
+
- Không sửa `.env`, secrets, tốc độ robot hoặc `.history`.
|
| 63 |
+
- Không thay đổi planner, action schema hay thuật toán đặt `on_top_of`.
|
| 64 |
+
- Các quan hệ left/right/front/behind/next_to giữ nguyên.
|
| 65 |
+
|
| 66 |
+
## Vấn đề còn lại
|
| 67 |
+
|
| 68 |
+
- Dung sai hiện được chọn theo các object hiện có. Nếu sau này thêm vật rất nhỏ hoặc
|
| 69 |
+
support có hình học đặc biệt, nên chuyển sang contact manifold theo từng body.
|
docs/CONTEXT_AWARE_GOAL_CHECK_PLAN.md
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kế hoạch sửa Goal Check theo ngữ cảnh hội thoại
|
| 2 |
+
|
| 3 |
+
## Trạng thái triển khai
|
| 4 |
+
|
| 5 |
+
Đã triển khai ngày 2026-07-03:
|
| 6 |
+
|
| 7 |
+
- pre-planning LLM Goal Resolution Gate: `ready | clarify | reject`;
|
| 8 |
+
- planner chỉ nhận canonical goal khi gate trả `ready`;
|
| 9 |
+
- action thiếu tham số bắt buộc bị chặn và chuyển thành clarification;
|
| 10 |
+
- `ResolvedGoal`/`PlanningOutcome` và goal predicates;
|
| 11 |
+
- giữ pending khi một lựa chọn clarification không tồn tại;
|
| 12 |
+
- khóa plan follow-up theo partial intent ban đầu;
|
| 13 |
+
- deterministic Goal Check cho pick-up, location và spatial relation;
|
| 14 |
+
- kiểm chứng `on_top_of` bằng AABB live có dung sai cho physics settling;
|
| 15 |
+
- dùng cùng resolved goal qua các vòng re-plan;
|
| 16 |
+
- đồng bộ pipeline agent với execution monitor;
|
| 17 |
+
- giới hạn re-plan mặc định là `3`, cấu hình qua `MAX_REPLANS`;
|
| 18 |
+
- feature flag rollback `STRUCTURED_GOAL_CHECK_ENABLED`.
|
| 19 |
+
|
| 20 |
+
API plan list và action schema cũ được giữ nguyên.
|
| 21 |
+
|
| 22 |
+
### Luồng runtime sau bổ sung Goal Resolution Gate
|
| 23 |
+
|
| 24 |
+
```text
|
| 25 |
+
user + conversation context + current scene
|
| 26 |
+
↓
|
| 27 |
+
LLM Goal Resolution Gate
|
| 28 |
+
├─ clarify → hỏi người dùng, không gọi planner
|
| 29 |
+
├─ reject → giải thích, không gọi planner
|
| 30 |
+
└─ ready → canonical goal
|
| 31 |
+
↓
|
| 32 |
+
planner
|
| 33 |
+
↓
|
| 34 |
+
schema/argument validation
|
| 35 |
+
↓
|
| 36 |
+
execute → structured Goal Check
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Ví dụ `gắp quả lên lon chip` khi scene có cả banana và pear phải trả clarification
|
| 40 |
+
chọn một trong hai. Quan hệ `on_top_of chips_can` được giữ trong partial intent để
|
| 41 |
+
lượt trả lời sau không phải nhắc lại.
|
| 42 |
+
|
| 43 |
+
## 1. Kết luận từ log
|
| 44 |
+
|
| 45 |
+
Log tái hiện chuỗi hội thoại:
|
| 46 |
+
|
| 47 |
+
1. Người dùng: `gắp một lon lên`.
|
| 48 |
+
2. Robot hỏi: `Bạn muốn tôi gắp lon súp hay lon chips?`
|
| 49 |
+
3. Người dùng: `lon coca`.
|
| 50 |
+
4. Robot từ chối vì scene không có lon Coca.
|
| 51 |
+
5. Người dùng: `thế thì lon chip đi`.
|
| 52 |
+
|
| 53 |
+
Ý định hợp nhất đúng phải là: **gắp `chips_can` lên**, không tự thêm đích đến.
|
| 54 |
+
|
| 55 |
+
Planner ở lượt cuối đã tạo một plan có `move_to(tray)` và `place_down`, sau đó Goal
|
| 56 |
+
Check chỉ nhận câu thô `thế thì lon chip đi`. LLM monitor diễn giải câu này không ổn
|
| 57 |
+
định: lúc là đưa lon chips vào khay, lúc là lấy lon chips khỏi khay. Kết quả là robot
|
| 58 |
+
di chuyển vật qua lại giữa bàn và khay.
|
| 59 |
+
|
| 60 |
+
## 2. Nguyên nhân gốc trong code
|
| 61 |
+
|
| 62 |
+
### 2.1 Goal Check nhận sai biểu diễn mục tiêu
|
| 63 |
+
|
| 64 |
+
`frontend/interactive_server.py` gọi:
|
| 65 |
+
|
| 66 |
+
```python
|
| 67 |
+
execution_monitor.verify_goal(user_prompt, final_state_text)
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
`user_prompt` là tin nhắn gần nhất của người dùng, không phải ý định đã hợp nhất mà
|
| 71 |
+
`ConversationManager.contextualize()` đã đưa cho planner.
|
| 72 |
+
|
| 73 |
+
Luồng CLI/app trong `llm_panda/execution/pipeline.py` cũng truyền trực tiếp
|
| 74 |
+
`nl_command`, nên có cùng rủi ro.
|
| 75 |
+
|
| 76 |
+
### 2.2 Ý định đã hợp nhất chỉ tồn tại tạm thời
|
| 77 |
+
|
| 78 |
+
Trong `LLMAgent.plan()`, `effective_command` chỉ là biến cục bộ. Sau khi có plan,
|
| 79 |
+
pipeline không nhận lại:
|
| 80 |
+
|
| 81 |
+
- câu lệnh chuẩn hóa;
|
| 82 |
+
- mục tiêu ngữ nghĩa;
|
| 83 |
+
- các lượt hội thoại đã tạo nên mục tiêu;
|
| 84 |
+
- điều kiện thành công cần kiểm tra.
|
| 85 |
+
|
| 86 |
+
Vì vậy execution và monitor không dùng chung một “hợp đồng mục tiêu”.
|
| 87 |
+
|
| 88 |
+
### 2.3 Pending clarification bị đóng quá sớm khi câu trả lời không hợp lệ
|
| 89 |
+
|
| 90 |
+
`ConversationManager.observe()` xóa pending khi planner trả `reject`. Trong ví dụ,
|
| 91 |
+
`lon coca` chỉ là một lựa chọn không hợp lệ cho câu hỏi đang chờ; nó không nên hủy
|
| 92 |
+
yêu cầu gốc `gắp một lon lên`. Robot phải giữ pending và hỏi lại soup/chips.
|
| 93 |
+
|
| 94 |
+
### 2.4 Re-plan cũng quay về câu thô
|
| 95 |
+
|
| 96 |
+
Mỗi vòng re-plan trong Web gọi lại `agent.plan(user_prompt, ...)`. Sau khi pending đã
|
| 97 |
+
bị đóng, câu `thế thì lon chip đi` được lập kế hoạch độc lập. `PREVIOUS FAILURE
|
| 98 |
+
REASON` còn có thể đẩy model theo diễn giải sai của lần Goal Check trước.
|
| 99 |
+
|
| 100 |
+
### 2.5 Web có tham chiếu agent không đồng bộ
|
| 101 |
+
|
| 102 |
+
Web thay `current_sim.pipeline.agent`, nhưng `execution_monitor.agent` được giữ từ
|
| 103 |
+
lúc khởi tạo pipeline. Planner và Goal Check vì thế có thể dùng hai agent khác nhau.
|
| 104 |
+
|
| 105 |
+
### 2.6 Giới hạn re-plan không an toàn
|
| 106 |
+
|
| 107 |
+
`MAX_REPLANS = 999999` cho phép một lỗi ngữ nghĩa tạo vòng lặp rất dài và liên tục
|
| 108 |
+
gọi API.
|
| 109 |
+
|
| 110 |
+
## 3. Thiết kế mục tiêu
|
| 111 |
+
|
| 112 |
+
Mỗi yêu cầu thực thi phải tạo đúng một `TaskContext` bất biến và dùng nó xuyên suốt:
|
| 113 |
+
|
| 114 |
+
```text
|
| 115 |
+
conversation turns
|
| 116 |
+
↓ resolve
|
| 117 |
+
TaskContext
|
| 118 |
+
├─ canonical_instruction: "gắp chips_can lên"
|
| 119 |
+
├─ resolved_goal: carried_object == "chips_can"
|
| 120 |
+
├─ source_turn_ids
|
| 121 |
+
├─ initial_scene_revision
|
| 122 |
+
└─ task_id
|
| 123 |
+
↓
|
| 124 |
+
planner → validator → executor → goal checker → re-planner
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Không đưa toàn bộ lịch sử chat vào Goal Check. Hội thoại chỉ được dùng ở bước resolve
|
| 128 |
+
intent; monitor nhận một goal có cấu trúc, ngắn và không mơ hồ.
|
| 129 |
+
|
| 130 |
+
## 4. Mô hình dữ liệu đề xuất
|
| 131 |
+
|
| 132 |
+
Thêm các dataclass tương thích ngược:
|
| 133 |
+
|
| 134 |
+
### `ResolvedGoal`
|
| 135 |
+
|
| 136 |
+
- `task_id`
|
| 137 |
+
- `canonical_instruction`
|
| 138 |
+
- `action`
|
| 139 |
+
- `targets`
|
| 140 |
+
- `destination`
|
| 141 |
+
- `relation`
|
| 142 |
+
- `relative_to`
|
| 143 |
+
- `predicates`: danh sách điều kiện hậu trạng thái có cấu trúc
|
| 144 |
+
- `source_turn_ids`
|
| 145 |
+
- `initial_scene_revision`
|
| 146 |
+
|
| 147 |
+
Ví dụ cho log hiện tại:
|
| 148 |
+
|
| 149 |
+
```json
|
| 150 |
+
{
|
| 151 |
+
"canonical_instruction": "gắp lon chips lên",
|
| 152 |
+
"action": "pick_up",
|
| 153 |
+
"targets": ["chips_can"],
|
| 154 |
+
"predicates": [
|
| 155 |
+
{"type": "carried_object_is", "object_id": "chips_can"}
|
| 156 |
+
]
|
| 157 |
+
}
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
### `PlanningOutcome`
|
| 161 |
+
|
| 162 |
+
- `steps`: plan hiện tại, giữ nguyên schema action cũ
|
| 163 |
+
- `resolved_goal`
|
| 164 |
+
- `effective_command`
|
| 165 |
+
- `response_type`: `ready | clarify | reject`
|
| 166 |
+
|
| 167 |
+
Giữ `LLMAgent.plan()` trả list để không phá API cũ. Thêm API nội bộ
|
| 168 |
+
`plan_with_context()` trả `PlanningOutcome`; pipeline mới dùng API này.
|
| 169 |
+
|
| 170 |
+
## 5. Chiến lược Goal Check
|
| 171 |
+
|
| 172 |
+
### Tầng 1 — deterministic predicates
|
| 173 |
+
|
| 174 |
+
Ưu tiên kiểm tra bằng code:
|
| 175 |
+
|
| 176 |
+
- `pick_up(X)` → `carried_object == X`;
|
| 177 |
+
- `place X on tray/table` → `location(X) == destination`;
|
| 178 |
+
- quan hệ không gian → kiểm tra relation tương ứng;
|
| 179 |
+
- category sorting → `all matching objects satisfy destination`, và chỉ thêm
|
| 180 |
+
`non-matching objects must not be there` khi câu gốc có từ loại trừ như
|
| 181 |
+
`chỉ`, `chỉ giữ`, `only`, `remove the others`.
|
| 182 |
+
|
| 183 |
+
Các bước dọn blocker do executor chèn không được biến thành mục tiêu người dùng.
|
| 184 |
+
|
| 185 |
+
### Tầng 2 — LLM fallback có cấu trúc
|
| 186 |
+
|
| 187 |
+
Chỉ dùng LLM khi goal không biểu diễn được bằng predicate hiện có. Input gồm:
|
| 188 |
+
|
| 189 |
+
- `ResolvedGoal` dạng JSON;
|
| 190 |
+
- final scene;
|
| 191 |
+
- không dùng riêng tin nhắn gần nhất;
|
| 192 |
+
- không cho model tự mở rộng từ “đưa X vào Y” thành “chỉ được có X ở Y”.
|
| 193 |
+
|
| 194 |
+
Output dùng JSON schema: `completed`, `reason`, `failed_predicates`.
|
| 195 |
+
|
| 196 |
+
Nếu LLM/API lỗi, trả trạng thái `indeterminate`, không coi là execution failure và
|
| 197 |
+
không tự động làm robot di chuyển ngược lại.
|
| 198 |
+
|
| 199 |
+
## 6. Vòng đời clarification chính xác
|
| 200 |
+
|
| 201 |
+
Trạng thái pending có thêm `status` và `invalid_answers`.
|
| 202 |
+
|
| 203 |
+
- `clarify` → giữ pending.
|
| 204 |
+
- Follow-up hợp lệ → tạo `ResolvedGoal`, sau đó mới đóng pending.
|
| 205 |
+
- Follow-up chọn object không tồn tại (`lon coca`) → thông báo lựa chọn không hợp lệ,
|
| 206 |
+
nhưng **giữ pending gốc** và hỏi lại.
|
| 207 |
+
- Lệnh hủy rõ ràng → đóng pending.
|
| 208 |
+
- Lệnh mới đầy đủ, độc lập → thay pending.
|
| 209 |
+
- Reject mang tính terminal vì nhiệm vụ thật sự bất khả thi → đóng pending.
|
| 210 |
+
|
| 211 |
+
Không suy luận “thế thì lon chip đi” là “đem lon chips đi chỗ khác”; trong pending
|
| 212 |
+
choice nó chỉ điền `object_id=chips_can` vào intent `action=pick_up`.
|
| 213 |
+
|
| 214 |
+
## 7. Re-plan nhất quán
|
| 215 |
+
|
| 216 |
+
- Tạo `TaskContext` một lần khi clarification hoàn tất.
|
| 217 |
+
- Mọi attempt dùng cùng `ResolvedGoal`.
|
| 218 |
+
- Re-plan nhận `resolved_goal + current_scene + execution_failure`; không nhận lại
|
| 219 |
+
câu follow-up thô như một nhiệm vụ mới.
|
| 220 |
+
- Lỗi Goal Check không được tự thay đổi goal.
|
| 221 |
+
- Dừng khi plan và scene lặp lại.
|
| 222 |
+
- Đổi giới hạn mặc định thành số hữu hạn cấu hình được, khuyến nghị `3`.
|
| 223 |
+
- Cho phép giữ giá trị cũ qua feature flag trong giai đoạn rollout nếu cần tương
|
| 224 |
+
thích vận hành.
|
| 225 |
+
|
| 226 |
+
## 8. Đồng bộ agent và session
|
| 227 |
+
|
| 228 |
+
- Khi gán `pipeline.agent`, đồng thời cập nhật `execution_monitor.agent`, tốt hơn là
|
| 229 |
+
để monitor đọc agent qua pipeline thay vì giữ bản sao tham chiếu.
|
| 230 |
+
- Mỗi WebSocket giữ một `ConversationManager` và một active `TaskContext`.
|
| 231 |
+
- Reset scene, đổi môi trường, disconnect và “cuộc hội thoại mới” phải xóa pending
|
| 232 |
+
cùng active task.
|
| 233 |
+
- GUI, Tk overlay, CLI và Web dùng cùng API `plan_with_context()`.
|
| 234 |
+
|
| 235 |
+
## 9. Phạm vi file dự kiến
|
| 236 |
+
|
| 237 |
+
- `llm_panda/conversation/models.py`
|
| 238 |
+
- thêm `ResolvedGoal`, `PlanningOutcome`, trạng thái clarification.
|
| 239 |
+
- `llm_panda/conversation/manager.py`
|
| 240 |
+
- giữ pending sau invalid clarification answer;
|
| 241 |
+
- resolve canonical intent và quản lý active task.
|
| 242 |
+
- `llm_panda/llm_agent.py`
|
| 243 |
+
- thêm `plan_with_context()`;
|
| 244 |
+
- compile goal từ intent/plan;
|
| 245 |
+
- đổi Goal Check sang structured goal.
|
| 246 |
+
- `llm_panda/execution/monitor.py`
|
| 247 |
+
- deterministic predicate evaluator và LLM fallback.
|
| 248 |
+
- `llm_panda/execution/pipeline.py`
|
| 249 |
+
- giữ một `TaskContext` xuyên suốt execute/re-plan/goal check.
|
| 250 |
+
- `frontend/interactive_server.py`
|
| 251 |
+
- bỏ truyền `user_prompt` th�� cho monitor;
|
| 252 |
+
- dùng task context; đồng bộ agent; giới hạn re-plan.
|
| 253 |
+
- `main.py` và các frontend controller/thread
|
| 254 |
+
- truyền outcome/task context mà không thay đổi UX hiện tại.
|
| 255 |
+
- `.env.example`
|
| 256 |
+
- thêm feature flags và giới hạn re-plan có mô tả.
|
| 257 |
+
- `tests/`
|
| 258 |
+
- thêm test unit, integration và parity giữa các giao diện.
|
| 259 |
+
|
| 260 |
+
## 10. Trình tự triển khai an toàn
|
| 261 |
+
|
| 262 |
+
### Bước 0 — Characterization
|
| 263 |
+
|
| 264 |
+
- Khóa bằng test lỗi trong log trước khi sửa.
|
| 265 |
+
- Test chứng minh planner nhận context nhưng monitor hiện nhận raw follow-up.
|
| 266 |
+
- Test agent reference cũ trong Web.
|
| 267 |
+
|
| 268 |
+
### Bước 1 — TaskContext không đổi hành vi
|
| 269 |
+
|
| 270 |
+
- Thêm dataclass và `plan_with_context()`.
|
| 271 |
+
- Giữ `plan()` cũ.
|
| 272 |
+
- Chỉ quan sát/log canonical goal, chưa bật monitor mới.
|
| 273 |
+
|
| 274 |
+
### Bước 2 — Clarification lifecycle
|
| 275 |
+
|
| 276 |
+
- Giữ pending khi lựa chọn follow-up không tồn tại.
|
| 277 |
+
- Resolve `gắp một lon lên` + `lon coca` + `thế thì lon chip đi` thành
|
| 278 |
+
`pick_up(chips_can)` duy nhất.
|
| 279 |
+
|
| 280 |
+
### Bước 3 — Deterministic Goal Check
|
| 281 |
+
|
| 282 |
+
- Implement predicate phổ biến.
|
| 283 |
+
- LLM chỉ fallback cho goal chưa hỗ trợ.
|
| 284 |
+
- Bật sau feature flag `STRUCTURED_GOAL_CHECK_ENABLED`.
|
| 285 |
+
|
| 286 |
+
### Bước 4 — Re-plan và agent wiring
|
| 287 |
+
|
| 288 |
+
- Dùng cùng task context cho mọi attempt.
|
| 289 |
+
- Đồng bộ monitor agent.
|
| 290 |
+
- Thêm loop guard và giới hạn hữu hạn.
|
| 291 |
+
|
| 292 |
+
### Bước 5 — Tích hợp mọi giao diện
|
| 293 |
+
|
| 294 |
+
- Web, PySide, Tk overlay, CLI cùng hành vi.
|
| 295 |
+
- Không thay đổi action schema và executor hiện có.
|
| 296 |
+
|
| 297 |
+
### Bước 6 — Rollout
|
| 298 |
+
|
| 299 |
+
- So sánh shadow result giữa checker cũ/mới.
|
| 300 |
+
- Bật checker mới trong local/test, sau đó deployment.
|
| 301 |
+
- Có thể rollback bằng feature flag mà không xóa code cũ.
|
| 302 |
+
|
| 303 |
+
## 11. Test bắt buộc
|
| 304 |
+
|
| 305 |
+
### Lỗi trong log
|
| 306 |
+
|
| 307 |
+
- `gắp một lon lên` → clarify.
|
| 308 |
+
- `lon coca` → báo không tồn tại, vẫn pending.
|
| 309 |
+
- `thế thì lon chip đi` → đúng một plan `pick_up(chips_can)`.
|
| 310 |
+
- Sau execution, Goal Check dùng `carried_object_is(chips_can)` và thành công.
|
| 311 |
+
- Không có `move_to`, không có re-plan.
|
| 312 |
+
|
| 313 |
+
### Hội thoại
|
| 314 |
+
|
| 315 |
+
- `di chuyển quả chuối` → `vào khay` → goal là banana ở tray.
|
| 316 |
+
- Follow-up `nó`/`cái đó` tham chiếu đúng object đã resolve.
|
| 317 |
+
- Lệnh mới đầy đủ thay pending; `thôi` hủy pending.
|
| 318 |
+
- Hai WebSocket không chia sẻ goal/pending.
|
| 319 |
+
|
| 320 |
+
### Ngữ nghĩa
|
| 321 |
+
|
| 322 |
+
- `gắp quả vào khay` không mặc định yêu cầu loại đồ không phải quả khỏi khay.
|
| 323 |
+
- `chỉ để trái cây trong khay` mới yêu cầu loại non-fruit khỏi khay.
|
| 324 |
+
- Goal Check cho cùng `ResolvedGoal` phải cho kết quả giống nhau qua nhiều lần gọi.
|
| 325 |
+
|
| 326 |
+
### Re-plan và lỗi
|
| 327 |
+
|
| 328 |
+
- API Goal Check timeout → `indeterminate`, không đảo trạng thái vật.
|
| 329 |
+
- Plan lặp + scene không đổi → dừng.
|
| 330 |
+
- Không vượt quá giới hạn re-plan cấu hình.
|
| 331 |
+
- Monitor luôn dùng đúng agent/session hiện tại.
|
| 332 |
+
|
| 333 |
+
### Hồi quy
|
| 334 |
+
|
| 335 |
+
- Action schema, obstacle clearing, PlanVerifier, step verification, scoring, tốc độ
|
| 336 |
+
robot và reset scene giữ nguyên.
|
| 337 |
+
- Các test conversation memory Phase 1/2 hiện có vẫn pass.
|
| 338 |
+
- Chạy parity test cho Web, GUI app, Tk overlay và CLI.
|
| 339 |
+
|
| 340 |
+
## 12. Tiêu chí nghiệm thu
|
| 341 |
+
|
| 342 |
+
- Goal Check không còn nhận riêng raw follow-up khi task bắt nguồn từ clarification.
|
| 343 |
+
- Planner, executor, re-planner và monitor dùng cùng `task_id` và `ResolvedGoal`.
|
| 344 |
+
- Ca log trên hoàn tất sau một lần `pick_up(chips_can)`.
|
| 345 |
+
- Không có vòng lặp chuyển cùng vật qua lại.
|
| 346 |
+
- Clarification continuation pass 100% cho bộ regression đã định nghĩa.
|
| 347 |
+
- Không tăng API call ở happy path; các goal phổ biến giảm một API call nhờ checker
|
| 348 |
+
deterministic.
|
| 349 |
+
- Có log theo `task_id`, canonical instruction, predicate result và re-plan count,
|
| 350 |
+
nhưng không ghi secret hoặc toàn bộ dữ liệu hội thoại nhạy cảm.
|
| 351 |
+
|
| 352 |
+
## 13. Các thay đổi đã được phê duyệt khi triển khai
|
| 353 |
+
|
| 354 |
+
Người dùng đã yêu cầu thực hiện kế hoạch, bao gồm ba thay đổi hành vi:
|
| 355 |
+
|
| 356 |
+
1. Invalid follow-up như `lon coca` sẽ giữ câu hỏi đang chờ thay vì đóng nó.
|
| 357 |
+
2. Goal Check phổ biến chuyển từ LLM sang deterministic predicates; LLM chỉ fallback.
|
| 358 |
+
3. `MAX_REPLANS` mặc định giảm từ `999999` xuống giá trị hữu hạn, khuyến nghị `3`.
|
docs/CONVERSATION_MEMORY_PLAN.md
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Kế hoạch bổ sung bộ nhớ hội thoại cho LLM-Panda
|
| 2 |
+
|
| 3 |
+
Ngày lập kế hoạch: 2026-07-03
|
| 4 |
+
|
| 5 |
+
## Trạng thái triển khai
|
| 6 |
+
|
| 7 |
+
- 2026-07-03: Hoàn thành Phase 1 — pending clarification memory trong phiên.
|
| 8 |
+
- 2026-07-03: Hoàn thành Phase 2 — structured dialogue state, cancel/replace,
|
| 9 |
+
scene revision và structured-output fallback.
|
| 10 |
+
- Đã tích hợp core agent, CLI/Tkinter, WebSocket, PySide và overlay.
|
| 11 |
+
- Reset scene/change environment sẽ xóa conversation context.
|
| 12 |
+
- Có feature flag `CONVERSATION_MEMORY_ENABLED` để quay về stateless mode.
|
| 13 |
+
- Có `LLM_STRUCTURED_OUTPUTS_ENABLED=auto`; provider không hỗ trợ sẽ tự fallback.
|
| 14 |
+
- Phase 3–4 (rolling summary, OpenRouter session stickiness và persistence qua
|
| 15 |
+
restart) chưa được triển khai.
|
| 16 |
+
|
| 17 |
+
## 1. Mục tiêu
|
| 18 |
+
|
| 19 |
+
Cho phép robot hiểu câu trả lời nối tiếp khi yêu cầu trước chưa đủ thông tin.
|
| 20 |
+
|
| 21 |
+
Ví dụ kỳ vọng:
|
| 22 |
+
|
| 23 |
+
1. Người dùng: `di chuyển quả chuối`
|
| 24 |
+
2. Robot: `Bạn muốn tôi di chuyển quả chuối đến đâu?`
|
| 25 |
+
3. Người dùng: `vào khay`
|
| 26 |
+
4. Robot hợp nhất hai lượt thành yêu cầu hoàn chỉnh và lập kế hoạch đặt chuối vào khay.
|
| 27 |
+
|
| 28 |
+
Thiết kế phải:
|
| 29 |
+
|
| 30 |
+
- không phá vỡ lệnh một lượt hiện có;
|
| 31 |
+
- không tăng thêm API call trên đường xử lý thông thường;
|
| 32 |
+
- cô lập hội thoại giữa các người dùng;
|
| 33 |
+
- giới hạn token, độ trễ và chi phí;
|
| 34 |
+
- không dùng ký ức hội thoại để bỏ qua validator hoặc safety guardrails;
|
| 35 |
+
- cho phép reset/xóa hội thoại rõ ràng.
|
| 36 |
+
|
| 37 |
+
## 2. Hiện trạng và nguyên nhân
|
| 38 |
+
|
| 39 |
+
### 2.1 Planner không nhận lịch sử hội thoại
|
| 40 |
+
|
| 41 |
+
`RemoteLLMPlanner.plan()` hiện gửi đúng ba phần:
|
| 42 |
+
|
| 43 |
+
- system prompt;
|
| 44 |
+
- scene hiện tại;
|
| 45 |
+
- instruction hiện tại.
|
| 46 |
+
|
| 47 |
+
Không có các lượt trước, câu hỏi robot vừa hỏi, hay yêu cầu còn dang dở.
|
| 48 |
+
|
| 49 |
+
### 2.2 Trạng thái clarification bị bỏ
|
| 50 |
+
|
| 51 |
+
Khi plan đầu tiên là `clarify` hoặc `reject`:
|
| 52 |
+
|
| 53 |
+
- `ExecutionPipeline.run_command()` trả về ngay;
|
| 54 |
+
- Web gửi kết quả cho client rồi kết thúc pipeline;
|
| 55 |
+
- không có state ghi lại original command, câu hỏi hoặc trường còn thiếu.
|
| 56 |
+
|
| 57 |
+
### 2.3 Một số frontend tạo planner mới cho mỗi lệnh
|
| 58 |
+
|
| 59 |
+
- Web gán một `LLMAgent`/planner mới trong mỗi lần chạy pipeline.
|
| 60 |
+
- PySide `LLMThread` cũng tạo planner và agent mới cho mỗi lệnh.
|
| 61 |
+
- Tkinter giữ `PandaApp`, nhưng `RemoteLLMPlanner` bản thân vẫn không lưu message history.
|
| 62 |
+
|
| 63 |
+
### 2.4 Rủi ro multi-user hiện có
|
| 64 |
+
|
| 65 |
+
Web đang dùng `current_sim` và `pipeline_executing` ở mức global. Đây là vấn đề
|
| 66 |
+
cô lập simulation độc lập với conversation memory. Memory mới phải được gắn với
|
| 67 |
+
`session_id`, không được gắn vào các global này. Việc tách simulation cho từng
|
| 68 |
+
người dùng là một hạng mục riêng và không nằm trong thay đổi memory nếu chưa được
|
| 69 |
+
người dùng phê duyệt.
|
| 70 |
+
|
| 71 |
+
## 3. Quyết định kiến trúc
|
| 72 |
+
|
| 73 |
+
Sử dụng **hybrid conversational memory**:
|
| 74 |
+
|
| 75 |
+
1. **Dialogue state có cấu trúc** là nguồn sự thật cho yêu cầu đang dang dở.
|
| 76 |
+
2. **Recent-turn buffer** giữ một số lượt gần nhất để hiểu đại từ và câu nối tiếp.
|
| 77 |
+
3. **Rolling summary** chỉ dùng khi hội thoại dài và vượt ngân sách token.
|
| 78 |
+
4. **Scene state** luôn lấy mới từ simulator; không đọc vị trí robot/vật thể từ ký ức.
|
| 79 |
+
5. **Long-term semantic memory** chưa bật ở giai đoạn đầu.
|
| 80 |
+
|
| 81 |
+
Không dùng vector database để giải quyết clarification. Câu trả lời nối tiếp cần
|
| 82 |
+
state chính xác theo session và theo thứ tự, trong khi vector retrieval là gần
|
| 83 |
+
đúng và có thể lấy nhầm ký ức của lượt cũ.
|
| 84 |
+
|
| 85 |
+
Các hệ thống memory hiện đại cũng phân biệt short-term/thread memory và long-term
|
| 86 |
+
memory, đồng thời dùng trimming/summarization để giới hạn context:
|
| 87 |
+
|
| 88 |
+
- [LangGraph memory overview](https://docs.langchain.com/oss/python/concepts/memory)
|
| 89 |
+
- [LangGraph short-term memory strategies](https://docs.langchain.com/oss/python/langgraph/add-memory)
|
| 90 |
+
- [MemGPT: hierarchical memory tiers](https://arxiv.org/abs/2310.08560)
|
| 91 |
+
|
| 92 |
+
Không bắt buộc thêm LangGraph vào dự án. Các nguyên tắc trên có thể được cài đặt
|
| 93 |
+
nhẹ hơn bằng dataclass và store nhỏ, tránh tăng dependency và thời gian khởi động.
|
| 94 |
+
|
| 95 |
+
## 4. Kiến trúc đề xuất
|
| 96 |
+
|
| 97 |
+
```text
|
| 98 |
+
User message
|
| 99 |
+
|
|
| 100 |
+
v
|
| 101 |
+
ConversationManager(session_id)
|
| 102 |
+
|-- pending clarification
|
| 103 |
+
|-- structured intent frame
|
| 104 |
+
|-- recent turns
|
| 105 |
+
|-- rolling summary
|
| 106 |
+
|
|
| 107 |
+
v
|
| 108 |
+
ContextBuilder
|
| 109 |
+
|-- stable system prompt
|
| 110 |
+
|-- compact conversation context
|
| 111 |
+
|-- fresh scene state
|
| 112 |
+
|-- current user message
|
| 113 |
+
|
|
| 114 |
+
v
|
| 115 |
+
RemoteLLMPlanner (1 API call)
|
| 116 |
+
|
|
| 117 |
+
v
|
| 118 |
+
PlanningResult: ready | clarify | reject
|
| 119 |
+
|
|
| 120 |
+
+-- clarify -> save pending state, do not move robot
|
| 121 |
+
+-- reject -> close pending state
|
| 122 |
+
+-- ready -> existing LLMAgent guards -> verifier -> executor
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
## 5. Mô hình dữ liệu
|
| 126 |
+
|
| 127 |
+
### 5.1 ConversationState
|
| 128 |
+
|
| 129 |
+
```python
|
| 130 |
+
@dataclass
|
| 131 |
+
class ConversationState:
|
| 132 |
+
session_id: str
|
| 133 |
+
recent_turns: deque[ConversationTurn]
|
| 134 |
+
summary: str | None
|
| 135 |
+
pending: PendingClarification | None
|
| 136 |
+
turn_count: int
|
| 137 |
+
updated_at: float
|
| 138 |
+
scene_revision: str | None
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
### 5.2 PendingClarification
|
| 142 |
+
|
| 143 |
+
```python
|
| 144 |
+
@dataclass
|
| 145 |
+
class PendingClarification:
|
| 146 |
+
original_command: str
|
| 147 |
+
robot_question: str
|
| 148 |
+
partial_intent: dict
|
| 149 |
+
missing_fields: list[str]
|
| 150 |
+
created_turn: int
|
| 151 |
+
expires_at: float
|
| 152 |
+
scene_revision: str
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
`partial_intent` dùng các slot hữu hạn:
|
| 156 |
+
|
| 157 |
+
- `action`;
|
| 158 |
+
- `object_id`;
|
| 159 |
+
- `destination`;
|
| 160 |
+
- `relation`;
|
| 161 |
+
- `relative_to`;
|
| 162 |
+
- `constraints`.
|
| 163 |
+
|
| 164 |
+
### 5.3 ConversationTurn
|
| 165 |
+
|
| 166 |
+
Chỉ lưu dữ liệu cần thiết:
|
| 167 |
+
|
| 168 |
+
- role;
|
| 169 |
+
- text;
|
| 170 |
+
- response type;
|
| 171 |
+
- resolved intent;
|
| 172 |
+
- timestamp.
|
| 173 |
+
|
| 174 |
+
Không lưu reasoning nội bộ của model, API key hoặc scene JSON đầy đủ.
|
| 175 |
+
|
| 176 |
+
## 6. Hợp đồng đầu ra của planner
|
| 177 |
+
|
| 178 |
+
### Giai đoạn tương thích
|
| 179 |
+
|
| 180 |
+
Tiếp tục chấp nhận array plan cũ để không làm hỏng hệ thống hiện tại.
|
| 181 |
+
|
| 182 |
+
Cho phép `clarify.args` bổ sung các trường tùy chọn:
|
| 183 |
+
|
| 184 |
+
```json
|
| 185 |
+
{
|
| 186 |
+
"function": "clarify",
|
| 187 |
+
"args": {
|
| 188 |
+
"message": "Bạn muốn đặt quả chuối ở đâu?",
|
| 189 |
+
"missing_fields": ["destination"],
|
| 190 |
+
"partial_intent": {
|
| 191 |
+
"action": "pick_and_place",
|
| 192 |
+
"object_id": "banana"
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
Code cũ vẫn chỉ đọc `message`, nên các trường mới tương thích ngược.
|
| 199 |
+
|
| 200 |
+
### Giai đoạn hardened
|
| 201 |
+
|
| 202 |
+
Bao planner bằng một `PlanningResult` nội bộ:
|
| 203 |
+
|
| 204 |
+
```json
|
| 205 |
+
{
|
| 206 |
+
"status": "ready",
|
| 207 |
+
"resolved_command": "gắp quả chuối đặt vào khay",
|
| 208 |
+
"message": null,
|
| 209 |
+
"missing_fields": [],
|
| 210 |
+
"partial_intent": {},
|
| 211 |
+
"plan": [
|
| 212 |
+
{"function": "pick_up", "args": {"object_id": "banana"}},
|
| 213 |
+
{"function": "move_to", "args": {"location_id": "tray"}},
|
| 214 |
+
{"function": "place_down", "args": {}}
|
| 215 |
+
]
|
| 216 |
+
}
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
OpenRouter hỗ trợ JSON Schema structured outputs trên model/provider tương thích.
|
| 220 |
+
Triển khai phải có capability check và fallback về parser hiện tại:
|
| 221 |
+
|
| 222 |
+
- [OpenRouter structured outputs](https://openrouter.ai/docs/guides/features/structured-outputs)
|
| 223 |
+
|
| 224 |
+
## 7. Luồng xử lý clarification
|
| 225 |
+
|
| 226 |
+
### 7.1 Yêu cầu đầu tiên chưa rõ
|
| 227 |
+
|
| 228 |
+
1. Lấy scene mới.
|
| 229 |
+
2. Planner trả `clarify`.
|
| 230 |
+
3. ConversationManager ghi original command, question, partial intent và missing fields.
|
| 231 |
+
4. UI hiển thị câu hỏi và giữ input hoạt động.
|
| 232 |
+
5. Robot không thực hiện hành động vật lý.
|
| 233 |
+
|
| 234 |
+
### 7.2 Người dùng trả lời
|
| 235 |
+
|
| 236 |
+
1. Tìm pending state theo `session_id`.
|
| 237 |
+
2. Gửi một request duy nhất gồm:
|
| 238 |
+
- original command;
|
| 239 |
+
- robot question;
|
| 240 |
+
- partial intent;
|
| 241 |
+
- user answer;
|
| 242 |
+
- scene mới nhất.
|
| 243 |
+
3. LLM phân loại câu mới là:
|
| 244 |
+
- câu trả lời clarification;
|
| 245 |
+
- lệnh mới thay thế;
|
| 246 |
+
- cancel;
|
| 247 |
+
- vẫn chưa đủ thông tin.
|
| 248 |
+
4. Nếu `ready`, plan đi qua toàn bộ guardrail/validator cũ rồi mới thực thi.
|
| 249 |
+
5. Nếu vẫn `clarify`, cập nhật pending state.
|
| 250 |
+
|
| 251 |
+
### 7.3 Hủy và hết hạn
|
| 252 |
+
|
| 253 |
+
- Các câu như `thôi`, `hủy`, `bỏ qua` xóa pending state.
|
| 254 |
+
- Một lệnh mới rõ ràng thay thế pending state cũ.
|
| 255 |
+
- Pending state hết hạn sau 10 phút hoặc 10 lượt, tùy điều kiện nào đến trước.
|
| 256 |
+
- `Reset Scene` xóa pending state vì scene revision đã thay đổi.
|
| 257 |
+
- Nếu scene thay đổi giữa hai lượt, planner phải lập lại kế hoạch từ scene mới.
|
| 258 |
+
|
| 259 |
+
## 8. Session isolation và persistence
|
| 260 |
+
|
| 261 |
+
### Phase 1 — khuyến nghị
|
| 262 |
+
|
| 263 |
+
- Web: tạo UUID khi WebSocket kết nối; state nằm trong TTL/LRU in-memory store.
|
| 264 |
+
- Tkinter/PySide: một UUID cho vòng đời cửa sổ.
|
| 265 |
+
- CLI: một UUID cho vòng đời process.
|
| 266 |
+
- Không giữ memory sau khi Space restart.
|
| 267 |
+
|
| 268 |
+
Ưu điểm: nhanh, không thêm dịch vụ, không lưu dữ liệu người dùng lâu dài.
|
| 269 |
+
|
| 270 |
+
### Phase 2 — tùy chọn
|
| 271 |
+
|
| 272 |
+
Nếu cần tiếp tục hội thoại sau reconnect/restart:
|
| 273 |
+
|
| 274 |
+
- client giữ session token ngẫu nhiên trong `sessionStorage`;
|
| 275 |
+
- server dùng Redis có TTL hoặc SQLite khi chỉ có một instance;
|
| 276 |
+
- trên Hugging Face, không dựa vào filesystem mặc định cho persistence dài hạn;
|
| 277 |
+
- không lưu dữ liệu qua nhiều phiên nếu chưa có consent và chính sách xóa dữ liệu.
|
| 278 |
+
|
| 279 |
+
## 9. Tối ưu hiệu năng và chi phí
|
| 280 |
+
|
| 281 |
+
- Không thêm API call riêng để “resolve follow-up”; hợp nhất context trong request
|
| 282 |
+
lập kế hoạch hiện tại.
|
| 283 |
+
- Recent buffer mặc định: tối đa 6 lượt user/robot.
|
| 284 |
+
- Memory token budget mục tiêu: 1.500–2.000 input tokens, không tính system prompt
|
| 285 |
+
và scene state.
|
| 286 |
+
- Ưu tiên structured state hơn transcript nguyên văn.
|
| 287 |
+
- Chỉ tạo rolling summary khi buffer vượt ngưỡng; thực hiện ngoài critical path
|
| 288 |
+
nếu có thể.
|
| 289 |
+
- Giữ system prompt ở đầu và ổn định để tận dụng prefix caching.
|
| 290 |
+
- Truyền `session_id` cho OpenRouter để sticky routing theo hội thoại và cải thiện
|
| 291 |
+
khả năng prompt-cache hit:
|
| 292 |
+
[OpenRouter prompt caching và session stickiness](https://openrouter.ai/docs/guides/best-practices/prompt-caching).
|
| 293 |
+
- Ghi nhận `prompt_tokens`, `cached_tokens`, latency và số API call nhưng không
|
| 294 |
+
ghi nội dung nhạy cảm.
|
| 295 |
+
|
| 296 |
+
## 10. An toàn
|
| 297 |
+
|
| 298 |
+
- Memory chỉ giúp hiểu ngôn ngữ; scene state vật lý luôn là dữ liệu trực tiếp.
|
| 299 |
+
- Mọi plan sau khi hợp nhất vẫn đi qua:
|
| 300 |
+
- obstacle-clearing normalization;
|
| 301 |
+
- safety guardrails;
|
| 302 |
+
- plan verifier;
|
| 303 |
+
- execution monitor.
|
| 304 |
+
- Không thực thi một phần plan khi clarification chưa hoàn tất.
|
| 305 |
+
- Không cho câu trả lời follow-up sửa system policy hoặc bỏ qua validator.
|
| 306 |
+
- Session A không được đọc pending state, summary hoặc turns của session B.
|
| 307 |
+
- UI có nút `Cuộc hội thoại mới`/`Xóa ngữ cảnh`.
|
| 308 |
+
|
| 309 |
+
## 11. Thay đổi dự kiến theo file
|
| 310 |
+
|
| 311 |
+
Không thực hiện trong bước lập kế hoạch này.
|
| 312 |
+
|
| 313 |
+
### File mới
|
| 314 |
+
|
| 315 |
+
- `llm_panda/conversation/models.py`
|
| 316 |
+
- `llm_panda/conversation/manager.py`
|
| 317 |
+
- `llm_panda/conversation/store.py`
|
| 318 |
+
- `llm_panda/conversation/context_builder.py`
|
| 319 |
+
- `tests/test_conversation_memory.py`
|
| 320 |
+
- `tests/test_conversation_sessions.py`
|
| 321 |
+
|
| 322 |
+
### File cần tích hợp
|
| 323 |
+
|
| 324 |
+
- `llm_panda/llm_agent.py`
|
| 325 |
+
- nhận conversation context/session ID;
|
| 326 |
+
- hỗ trợ structured clarification metadata;
|
| 327 |
+
- giữ fallback plan-array cũ.
|
| 328 |
+
- `llm_panda/execution/pipeline.py`
|
| 329 |
+
- lưu clarification result;
|
| 330 |
+
- chỉ execute khi status là ready.
|
| 331 |
+
- `frontend/interactive_server.py`
|
| 332 |
+
- tạo session ID theo WebSocket;
|
| 333 |
+
- không tạo memory global;
|
| 334 |
+
- clear state khi reset/disconnect theo policy.
|
| 335 |
+
- `main.py`
|
| 336 |
+
- tạo một conversation session cho CLI/Tkinter.
|
| 337 |
+
- `frontend/threads/llm_thread.py` và `frontend/controllers/ui_controller.py`
|
| 338 |
+
- truyền session/context thay vì tạo phiên planner hoàn toàn độc lập.
|
| 339 |
+
- `frontend/app.js` hoặc widget tương ứng
|
| 340 |
+
- hiển thị trạng thái “đang chờ câu trả lời” và nút xóa ngữ cảnh.
|
| 341 |
+
|
| 342 |
+
## 12. Lộ trình triển khai
|
| 343 |
+
|
| 344 |
+
### Phase 0 — Characterization tests
|
| 345 |
+
|
| 346 |
+
- Khóa hành vi lệnh một lượt hiện tại bằng test.
|
| 347 |
+
- Thêm test tái hiện lỗi clarification bị mất.
|
| 348 |
+
- Đo baseline latency, token và API calls.
|
| 349 |
+
|
| 350 |
+
### Phase 1 — Pending clarification memory
|
| 351 |
+
|
| 352 |
+
- Thêm model/store/manager.
|
| 353 |
+
- Lưu original command và robot question.
|
| 354 |
+
- Hợp nhất câu trả lời kế tiếp trong một API call.
|
| 355 |
+
- Tích hợp CLI, Tkinter và Web.
|
| 356 |
+
- Chưa có rolling summary hoặc persistence.
|
| 357 |
+
|
| 358 |
+
### Phase 2 — Structured dialogue state
|
| 359 |
+
|
| 360 |
+
- Trạng thái: hoàn thành ngày 2026-07-03.
|
| 361 |
+
- Bổ sung `missing_fields` và `partial_intent`.
|
| 362 |
+
- Dùng structured outputs nếu model hỗ trợ.
|
| 363 |
+
- Thêm cancel, replace-intent, expiry và scene revision.
|
| 364 |
+
|
| 365 |
+
### Phase 3 — Bounded history và tối ưu token
|
| 366 |
+
|
| 367 |
+
- Thêm recent-turn buffer.
|
| 368 |
+
- Thêm trimming và rolling summary có ngưỡng.
|
| 369 |
+
- Truyền OpenRouter `session_id`.
|
| 370 |
+
- Thêm telemetry cache/token/latency.
|
| 371 |
+
|
| 372 |
+
### Phase 4 — Persistence tùy chọn
|
| 373 |
+
|
| 374 |
+
- Redis/SQLite adapter.
|
| 375 |
+
- Consent, TTL, delete API và privacy controls.
|
| 376 |
+
- Chỉ triển khai khi có yêu cầu rõ ràng.
|
| 377 |
+
|
| 378 |
+
## 13. Test bắt buộc
|
| 379 |
+
|
| 380 |
+
### Chức năng
|
| 381 |
+
|
| 382 |
+
- `di chuyển quả chuối` → hỏi nơi đến → `vào khay` → plan hoàn chỉnh.
|
| 383 |
+
- `đặt vào khay` khi tay trống → hỏi vật → `quả lê` → plan hoàn chỉnh.
|
| 384 |
+
- Câu trả lời vẫn thiếu dữ kiện → hỏi tiếp, không thực thi.
|
| 385 |
+
- `thôi` → hủy pending.
|
| 386 |
+
- Lệnh mới rõ ràng khi đang pending → thay thế lệnh cũ.
|
| 387 |
+
- Reset scene giữa hai lượt → pending bị xóa hoặc revalidate.
|
| 388 |
+
- Lệnh một lượt hiện có cho plan giống trước khi thêm memory.
|
| 389 |
+
|
| 390 |
+
### Cô lập
|
| 391 |
+
|
| 392 |
+
- Hai WebSocket có pending state khác nhau.
|
| 393 |
+
- Ngắt/reconnect không nhận nhầm memory của session khác.
|
| 394 |
+
- Không có cross-user leakage trong log.
|
| 395 |
+
|
| 396 |
+
### An toàn
|
| 397 |
+
|
| 398 |
+
- Follow-up không bypass PlanVerifier/SafetyGuardrails.
|
| 399 |
+
- Object đã di chuyển giữa hai lượt được lập kế hoạch theo scene mới.
|
| 400 |
+
- Clarification không làm robot chuyển động.
|
| 401 |
+
|
| 402 |
+
### Hiệu năng
|
| 403 |
+
|
| 404 |
+
- Một follow-up hoàn chỉnh dùng tối đa một planning API call.
|
| 405 |
+
- P95 overhead local của ConversationManager dưới 10 ms.
|
| 406 |
+
- Memory context không vượt token budget.
|
| 407 |
+
- Không tăng thời gian khởi động đáng kể.
|
| 408 |
+
|
| 409 |
+
## 14. Chỉ số nghiệm thu
|
| 410 |
+
|
| 411 |
+
- Clarification continuation success rate ≥ 95% trên bộ test hội thoại.
|
| 412 |
+
- Regression pass 100% cho các lệnh một lượt hiện có.
|
| 413 |
+
- Cross-session leakage = 0.
|
| 414 |
+
- Invalid/partial plan execution = 0.
|
| 415 |
+
- API calls cho một lượt thông thường không tăng.
|
| 416 |
+
- Có telemetry cho latency, token, cache hit và clarification depth.
|
| 417 |
+
|
| 418 |
+
## 15. Rollout và rollback
|
| 419 |
+
|
| 420 |
+
- Bọc tính năng bằng `CONVERSATION_MEMORY_ENABLED`.
|
| 421 |
+
- Mặc định bật ở môi trường thử nghiệm, tắt được không cần rollback code.
|
| 422 |
+
- Triển khai theo thứ tự CLI/Tkinter trước, Web sau khi test session isolation.
|
| 423 |
+
- Khi lỗi, fallback về luồng stateless hiện tại; không thay đổi executor.
|
| 424 |
+
- Không xóa API hay schema cũ trong rollout đầu tiên.
|
| 425 |
+
|
| 426 |
+
## 16. Điểm cần phê duyệt trước khi code
|
| 427 |
+
|
| 428 |
+
Khuyến nghị mặc định:
|
| 429 |
+
|
| 430 |
+
- Phase 1 chỉ nhớ trong phiên hiện tại, không lưu qua restart.
|
| 431 |
+
- Pending timeout 10 phút.
|
| 432 |
+
- Recent history tối đa 6 lượt.
|
| 433 |
+
- Không thêm LangGraph/vector database.
|
| 434 |
+
- Chưa lưu sở thích dài hạn của người dùng.
|
| 435 |
+
|
| 436 |
+
Việc bật persistence qua Redis/SQLite, lưu dữ liệu dài hạn hoặc tách simulation
|
| 437 |
+
theo từng người dùng là thay đổi phạm vi và cần phê duyệt riêng.
|
frontend/__pycache__/interactive_server.cpython-310.pyc
CHANGED
|
Binary files a/frontend/__pycache__/interactive_server.cpython-310.pyc and b/frontend/__pycache__/interactive_server.cpython-310.pyc differ
|
|
|
frontend/app.js
CHANGED
|
@@ -509,10 +509,20 @@ function handleSocketMessage(msg) {
|
|
| 509 |
speakFeedback(window.currentPlanSummary);
|
| 510 |
break;
|
| 511 |
|
| 512 |
-
case 'result':
|
| 513 |
-
unlockInput();
|
| 514 |
-
|
| 515 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 516 |
const now = new Date();
|
| 517 |
const timeStr = now.toTimeString().split(' ')[0];
|
| 518 |
|
|
|
|
| 509 |
speakFeedback(window.currentPlanSummary);
|
| 510 |
break;
|
| 511 |
|
| 512 |
+
case 'result':
|
| 513 |
+
unlockInput();
|
| 514 |
+
|
| 515 |
+
// Clarifications and rejections are conversational turns, not
|
| 516 |
+
// completed robot executions. Keep the input ready for the reply
|
| 517 |
+
// and do not record a misleading failed run in analytics.
|
| 518 |
+
if (msg.response_type === 'clarify' || msg.response_type === 'reject') {
|
| 519 |
+
window.currentPlan = null;
|
| 520 |
+
window.currentLlmTime = 0;
|
| 521 |
+
chatInput.focus();
|
| 522 |
+
break;
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
// Add new run record to history log dynamically
|
| 526 |
const now = new Date();
|
| 527 |
const timeStr = now.toTimeString().split(' ')[0];
|
| 528 |
|
frontend/controllers/__pycache__/ui_controller.cpython-310.pyc
CHANGED
|
Binary files a/frontend/controllers/__pycache__/ui_controller.cpython-310.pyc and b/frontend/controllers/__pycache__/ui_controller.cpython-310.pyc differ
|
|
|
frontend/controllers/ui_controller.py
CHANGED
|
@@ -8,9 +8,10 @@ PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."
|
|
| 8 |
if PROJECT_SRC not in sys.path:
|
| 9 |
sys.path.insert(0, PROJECT_SRC)
|
| 10 |
|
| 11 |
-
from frontend.threads.llm_thread import LLMThread
|
| 12 |
-
from frontend.threads.simulation_thread import SimulationThread
|
| 13 |
-
from llm_panda.
|
|
|
|
| 14 |
|
| 15 |
class UIController(QObject):
|
| 16 |
"""
|
|
@@ -28,9 +29,10 @@ class UIController(QObject):
|
|
| 28 |
self.score_modal = None
|
| 29 |
|
| 30 |
# Threads
|
| 31 |
-
self.sim_thread = None
|
| 32 |
-
self.llm_thread = None
|
| 33 |
-
self.last_scene_state = None
|
|
|
|
| 34 |
|
| 35 |
def start(self):
|
| 36 |
"""Initializes and starts the simulation background thread."""
|
|
@@ -89,9 +91,10 @@ class UIController(QObject):
|
|
| 89 |
def handle_preset_click(self, prompt_text):
|
| 90 |
self.chat_widget.set_prompt_text(prompt_text)
|
| 91 |
|
| 92 |
-
def handle_reset_click(self):
|
| 93 |
-
if self.sim_thread:
|
| 94 |
-
self.
|
|
|
|
| 95 |
self.chat_widget.clear_plan()
|
| 96 |
self.status_widget.reset_steps()
|
| 97 |
self.sim_thread.queue_command("reset")
|
|
@@ -130,7 +133,12 @@ class UIController(QObject):
|
|
| 130 |
|
| 131 |
# Start LLM Planning Thread
|
| 132 |
self.status_widget.set_step_active("llm")
|
| 133 |
-
self.llm_thread = LLMThread(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
self.llm_thread.plan_ready.connect(self.handle_plan_ready)
|
| 135 |
self.llm_thread.log_message.connect(self.log_widget.append_log)
|
| 136 |
self.llm_thread.failed.connect(self.handle_llm_failed)
|
|
@@ -140,16 +148,29 @@ class UIController(QObject):
|
|
| 140 |
self.status_widget.set_step_error("llm")
|
| 141 |
self.chat_widget.unlock_inputs()
|
| 142 |
|
| 143 |
-
def handle_plan_ready(self, plan_steps):
|
| 144 |
-
self.status_widget.set_step_completed("llm")
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
if not plan_steps:
|
| 148 |
self.log_widget.append_log("⚠️ [1] Kế hoạch rỗng.", "warn")
|
| 149 |
self.status_widget.set_step_active("score")
|
| 150 |
# Calculate score immediately for empty plan
|
| 151 |
-
self.sim_thread.queue_command("execute_plan", [])
|
| 152 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
# Step 2: Validation
|
| 155 |
self.status_widget.set_step_active("val")
|
|
|
|
| 8 |
if PROJECT_SRC not in sys.path:
|
| 9 |
sys.path.insert(0, PROJECT_SRC)
|
| 10 |
|
| 11 |
+
from frontend.threads.llm_thread import LLMThread
|
| 12 |
+
from frontend.threads.simulation_thread import SimulationThread
|
| 13 |
+
from llm_panda.conversation import ConversationManager
|
| 14 |
+
from llm_panda.plan_verifier import PlanVerifier
|
| 15 |
|
| 16 |
class UIController(QObject):
|
| 17 |
"""
|
|
|
|
| 29 |
self.score_modal = None
|
| 30 |
|
| 31 |
# Threads
|
| 32 |
+
self.sim_thread = None
|
| 33 |
+
self.llm_thread = None
|
| 34 |
+
self.last_scene_state = None
|
| 35 |
+
self.conversation_manager = ConversationManager()
|
| 36 |
|
| 37 |
def start(self):
|
| 38 |
"""Initializes and starts the simulation background thread."""
|
|
|
|
| 91 |
def handle_preset_click(self, prompt_text):
|
| 92 |
self.chat_widget.set_prompt_text(prompt_text)
|
| 93 |
|
| 94 |
+
def handle_reset_click(self):
|
| 95 |
+
if self.sim_thread:
|
| 96 |
+
self.conversation_manager.clear()
|
| 97 |
+
self.log_widget.clear_logs()
|
| 98 |
self.chat_widget.clear_plan()
|
| 99 |
self.status_widget.reset_steps()
|
| 100 |
self.sim_thread.queue_command("reset")
|
|
|
|
| 133 |
|
| 134 |
# Start LLM Planning Thread
|
| 135 |
self.status_widget.set_step_active("llm")
|
| 136 |
+
self.llm_thread = LLMThread(
|
| 137 |
+
prompt,
|
| 138 |
+
scene_state,
|
| 139 |
+
use_mock,
|
| 140 |
+
conversation_manager=self.conversation_manager,
|
| 141 |
+
)
|
| 142 |
self.llm_thread.plan_ready.connect(self.handle_plan_ready)
|
| 143 |
self.llm_thread.log_message.connect(self.log_widget.append_log)
|
| 144 |
self.llm_thread.failed.connect(self.handle_llm_failed)
|
|
|
|
| 148 |
self.status_widget.set_step_error("llm")
|
| 149 |
self.chat_widget.unlock_inputs()
|
| 150 |
|
| 151 |
+
def handle_plan_ready(self, plan_steps):
|
| 152 |
+
self.status_widget.set_step_completed("llm")
|
| 153 |
+
|
| 154 |
+
if not plan_steps:
|
|
|
|
| 155 |
self.log_widget.append_log("⚠️ [1] Kế hoạch rỗng.", "warn")
|
| 156 |
self.status_widget.set_step_active("score")
|
| 157 |
# Calculate score immediately for empty plan
|
| 158 |
+
self.sim_thread.queue_command("execute_plan", [])
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
first_step = plan_steps[0]
|
| 162 |
+
if first_step.get("skill") in ("clarify", "reject"):
|
| 163 |
+
message = first_step.get("args", {}).get(
|
| 164 |
+
"message",
|
| 165 |
+
"Yêu cầu cần được làm rõ.",
|
| 166 |
+
)
|
| 167 |
+
self.chat_widget.add_message(message, is_user=False)
|
| 168 |
+
self.log_widget.append_log(f"Robot: {message}", "info")
|
| 169 |
+
self.chat_widget.clear_plan()
|
| 170 |
+
self.chat_widget.unlock_inputs()
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
self.chat_widget.display_plan(plan_steps)
|
| 174 |
|
| 175 |
# Step 2: Validation
|
| 176 |
self.status_widget.set_step_active("val")
|
frontend/interactive_server.py
CHANGED
|
@@ -19,9 +19,10 @@ if PROJECT_SRC not in sys.path:
|
|
| 19 |
sys.path.insert(0, PROJECT_SRC)
|
| 20 |
from dotenv import load_dotenv
|
| 21 |
load_dotenv()
|
| 22 |
-
from main import PandaApp
|
| 23 |
-
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 24 |
-
from llm_panda.
|
|
|
|
| 25 |
from llm_panda import config
|
| 26 |
import pybullet_data
|
| 27 |
from pybullet_object_models import ycb_objects
|
|
@@ -271,7 +272,14 @@ def compute_and_format_score(sim: PandaApp, plan: list, executed_successfully: b
|
|
| 271 |
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
|
| 272 |
return score, md
|
| 273 |
|
| 274 |
-
def run_pipeline_threadsafe(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
"""Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
|
| 276 |
global current_sim, pipeline_executing
|
| 277 |
pipeline_executing = True
|
|
@@ -302,11 +310,15 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
|
|
| 302 |
log(f"✅ [1] Tôi đang phân tích yêu cầu...")
|
| 303 |
|
| 304 |
with pybullet_lock:
|
| 305 |
-
current_sim.pipeline.agent = LLMAgent(
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
-
MAX_REPLANS =
|
| 308 |
-
last_failed_sig = None
|
| 309 |
-
last_failed_state_sig = None
|
|
|
|
| 310 |
|
| 311 |
# Hook pb.stepSimulation to capture states during movements
|
| 312 |
original_step = pb.stepSimulation
|
|
@@ -359,8 +371,28 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
|
|
| 359 |
try:
|
| 360 |
with pybullet_lock:
|
| 361 |
llm_start_time = time.time()
|
| 362 |
-
|
| 363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
|
| 365 |
# Summarize plan
|
| 366 |
targets = []
|
|
@@ -418,11 +450,12 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
|
|
| 418 |
header_title = "Phản hồi từ Robot" if plan[0].get("function") == "clarify" else "Yêu cầu bị từ chối"
|
| 419 |
score_md = f"### {header_title}\n\n**Robot phản hồi:** {summary_msg}\n"
|
| 420 |
asyncio.run_coroutine_threadsafe(
|
| 421 |
-
websocket.send_json({
|
| 422 |
-
"type": "result",
|
| 423 |
-
"
|
| 424 |
-
"
|
| 425 |
-
"
|
|
|
|
| 426 |
}),
|
| 427 |
loop
|
| 428 |
)
|
|
@@ -564,7 +597,13 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
|
|
| 564 |
with pybullet_lock:
|
| 565 |
final_scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried else None)
|
| 566 |
final_state_text = json.dumps(final_scene_state, indent=2)
|
| 567 |
-
goal_completed, goal_reason =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
if goal_completed:
|
| 569 |
log(f"✅ [GOAL CHECK] OK: {goal_reason}")
|
| 570 |
else:
|
|
@@ -614,10 +653,11 @@ def run_pipeline_threadsafe(websocket: WebSocket, user_prompt: str, loop, use_mo
|
|
| 614 |
)
|
| 615 |
pipeline_executing = False
|
| 616 |
@app.websocket("/ws")
|
| 617 |
-
async def websocket_endpoint(websocket: WebSocket):
|
| 618 |
-
global current_sim
|
| 619 |
-
await websocket.accept()
|
| 620 |
-
loop = asyncio.get_running_loop()
|
|
|
|
| 621 |
|
| 622 |
# Retrieve user's desktop display preference from client query params
|
| 623 |
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
|
|
@@ -730,11 +770,12 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 730 |
asyncio.to_thread(
|
| 731 |
run_pipeline_threadsafe,
|
| 732 |
websocket,
|
| 733 |
-
prompt,
|
| 734 |
-
loop,
|
| 735 |
-
use_mock
|
| 736 |
-
|
| 737 |
-
|
|
|
|
| 738 |
|
| 739 |
|
| 740 |
elif p_type == "mouse_pick_start":
|
|
@@ -811,8 +852,9 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 811 |
drag_state["constraint_id"] = None
|
| 812 |
await asyncio.to_thread(do_end)
|
| 813 |
|
| 814 |
-
elif p_type == "reset":
|
| 815 |
-
|
|
|
|
| 816 |
def reset_sim():
|
| 817 |
with pybullet_lock:
|
| 818 |
current_sim.reset_objects(seed=0)
|
|
@@ -824,8 +866,9 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 824 |
await websocket.send_json(state_payload)
|
| 825 |
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
|
| 826 |
|
| 827 |
-
elif p_type == "change_env":
|
| 828 |
-
|
|
|
|
| 829 |
env_path = os.path.join(PROJECT_SRC, "envs", env_file)
|
| 830 |
async with executor_lock:
|
| 831 |
def change_sim_env():
|
|
@@ -917,11 +960,12 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
| 917 |
|
| 918 |
except WebSocketDisconnect:
|
| 919 |
print("Client disconnected")
|
| 920 |
-
except Exception as e:
|
| 921 |
-
print(f"WS Exception: {e}")
|
| 922 |
-
finally:
|
| 923 |
-
|
| 924 |
-
|
|
|
|
| 925 |
if __name__ == "__main__":
|
| 926 |
port = int(os.environ.get("PORT", 8000))
|
| 927 |
-
uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False)
|
|
|
|
| 19 |
sys.path.insert(0, PROJECT_SRC)
|
| 20 |
from dotenv import load_dotenv
|
| 21 |
load_dotenv()
|
| 22 |
+
from main import PandaApp
|
| 23 |
+
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 24 |
+
from llm_panda.conversation import ConversationManager
|
| 25 |
+
from llm_panda.plan_verifier import PlanVerifier
|
| 26 |
from llm_panda import config
|
| 27 |
import pybullet_data
|
| 28 |
from pybullet_object_models import ycb_objects
|
|
|
|
| 272 |
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
|
| 273 |
return score, md
|
| 274 |
|
| 275 |
+
def run_pipeline_threadsafe(
|
| 276 |
+
websocket: WebSocket,
|
| 277 |
+
user_prompt: str,
|
| 278 |
+
loop,
|
| 279 |
+
use_mock: bool,
|
| 280 |
+
camera_state: Optional[dict] = None,
|
| 281 |
+
conversation_manager: Optional[ConversationManager] = None,
|
| 282 |
+
):
|
| 283 |
"""Runs the planning, validation, execution with image streaming, and scoring using closed-loop execution monitor."""
|
| 284 |
global current_sim, pipeline_executing
|
| 285 |
pipeline_executing = True
|
|
|
|
| 310 |
log(f"✅ [1] Tôi đang phân tích yêu cầu...")
|
| 311 |
|
| 312 |
with pybullet_lock:
|
| 313 |
+
current_sim.pipeline.agent = LLMAgent(
|
| 314 |
+
planner=planner,
|
| 315 |
+
conversation_manager=conversation_manager,
|
| 316 |
+
)
|
| 317 |
|
| 318 |
+
MAX_REPLANS = current_sim.pipeline.MAX_REPLANS
|
| 319 |
+
last_failed_sig = None
|
| 320 |
+
last_failed_state_sig = None
|
| 321 |
+
resolved_goal = None
|
| 322 |
|
| 323 |
# Hook pb.stepSimulation to capture states during movements
|
| 324 |
original_step = pb.stepSimulation
|
|
|
|
| 371 |
try:
|
| 372 |
with pybullet_lock:
|
| 373 |
llm_start_time = time.time()
|
| 374 |
+
planning_command = (
|
| 375 |
+
resolved_goal.canonical_instruction
|
| 376 |
+
if attempt > 0 and resolved_goal is not None
|
| 377 |
+
else user_prompt
|
| 378 |
+
)
|
| 379 |
+
current_sim.pipeline.agent.last_outcome = None
|
| 380 |
+
plan_kwargs = {
|
| 381 |
+
"previous_failed_reasons": last_failed_sig
|
| 382 |
+
}
|
| 383 |
+
if attempt > 0:
|
| 384 |
+
plan_kwargs["resolve_goal"] = False
|
| 385 |
+
plan = current_sim.pipeline.agent.plan(
|
| 386 |
+
planning_command,
|
| 387 |
+
state_text,
|
| 388 |
+
**plan_kwargs,
|
| 389 |
+
)
|
| 390 |
+
outcome = getattr(
|
| 391 |
+
current_sim.pipeline.agent, "last_outcome", None
|
| 392 |
+
)
|
| 393 |
+
if attempt == 0 and outcome is not None:
|
| 394 |
+
resolved_goal = outcome.resolved_goal
|
| 395 |
+
llm_time = time.time() - llm_start_time
|
| 396 |
|
| 397 |
# Summarize plan
|
| 398 |
targets = []
|
|
|
|
| 450 |
header_title = "Phản hồi từ Robot" if plan[0].get("function") == "clarify" else "Yêu cầu bị từ chối"
|
| 451 |
score_md = f"### {header_title}\n\n**Robot phản hồi:** {summary_msg}\n"
|
| 452 |
asyncio.run_coroutine_threadsafe(
|
| 453 |
+
websocket.send_json({
|
| 454 |
+
"type": "result",
|
| 455 |
+
"response_type": plan[0].get("function"),
|
| 456 |
+
"score_display": score_md,
|
| 457 |
+
"score_value": 0,
|
| 458 |
+
"success": False
|
| 459 |
}),
|
| 460 |
loop
|
| 461 |
)
|
|
|
|
| 597 |
with pybullet_lock:
|
| 598 |
final_scene_state = current_sim.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=current_sim.scene.get_name(current_sim.pipeline._carried) if current_sim.pipeline._carried else None)
|
| 599 |
final_state_text = json.dumps(final_scene_state, indent=2)
|
| 600 |
+
goal_completed, goal_reason = (
|
| 601 |
+
current_sim.pipeline.execution_monitor.verify_goal(
|
| 602 |
+
user_prompt,
|
| 603 |
+
final_state_text,
|
| 604 |
+
resolved_goal=resolved_goal,
|
| 605 |
+
)
|
| 606 |
+
)
|
| 607 |
if goal_completed:
|
| 608 |
log(f"✅ [GOAL CHECK] OK: {goal_reason}")
|
| 609 |
else:
|
|
|
|
| 653 |
)
|
| 654 |
pipeline_executing = False
|
| 655 |
@app.websocket("/ws")
|
| 656 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 657 |
+
global current_sim
|
| 658 |
+
await websocket.accept()
|
| 659 |
+
loop = asyncio.get_running_loop()
|
| 660 |
+
conversation_manager = ConversationManager()
|
| 661 |
|
| 662 |
# Retrieve user's desktop display preference from client query params
|
| 663 |
client_wants_gui = websocket.query_params.get("gui", "false").lower() == "true"
|
|
|
|
| 770 |
asyncio.to_thread(
|
| 771 |
run_pipeline_threadsafe,
|
| 772 |
websocket,
|
| 773 |
+
prompt,
|
| 774 |
+
loop,
|
| 775 |
+
use_mock,
|
| 776 |
+
conversation_manager=conversation_manager,
|
| 777 |
+
)
|
| 778 |
+
)
|
| 779 |
|
| 780 |
|
| 781 |
elif p_type == "mouse_pick_start":
|
|
|
|
| 852 |
drag_state["constraint_id"] = None
|
| 853 |
await asyncio.to_thread(do_end)
|
| 854 |
|
| 855 |
+
elif p_type == "reset":
|
| 856 |
+
conversation_manager.clear()
|
| 857 |
+
async with executor_lock:
|
| 858 |
def reset_sim():
|
| 859 |
with pybullet_lock:
|
| 860 |
current_sim.reset_objects(seed=0)
|
|
|
|
| 866 |
await websocket.send_json(state_payload)
|
| 867 |
await websocket.send_json({"type": "log", "message": "🔄 Đã reset môi trường mô phỏng."})
|
| 868 |
|
| 869 |
+
elif p_type == "change_env":
|
| 870 |
+
conversation_manager.clear()
|
| 871 |
+
env_file = payload.get("env")
|
| 872 |
env_path = os.path.join(PROJECT_SRC, "envs", env_file)
|
| 873 |
async with executor_lock:
|
| 874 |
def change_sim_env():
|
|
|
|
| 960 |
|
| 961 |
except WebSocketDisconnect:
|
| 962 |
print("Client disconnected")
|
| 963 |
+
except Exception as e:
|
| 964 |
+
print(f"WS Exception: {e}")
|
| 965 |
+
finally:
|
| 966 |
+
conversation_manager.clear()
|
| 967 |
+
if settle_task:
|
| 968 |
+
settle_task.cancel()
|
| 969 |
if __name__ == "__main__":
|
| 970 |
port = int(os.environ.get("PORT", 8000))
|
| 971 |
+
uvicorn.run("interactive_server:app", host="0.0.0.0", port=port, reload=False)
|
frontend/overlay_app.py
CHANGED
|
@@ -16,9 +16,10 @@ if PROJECT_SRC not in sys.path:
|
|
| 16 |
from dotenv import load_dotenv
|
| 17 |
load_dotenv()
|
| 18 |
|
| 19 |
-
from main import PandaSimulation
|
| 20 |
-
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 21 |
-
from llm_panda.
|
|
|
|
| 22 |
|
| 23 |
# Preset prompts matching CLI
|
| 24 |
PRESETS = {
|
|
@@ -271,9 +272,10 @@ def compute_and_format_score(sim: PandaSimulation, plan: list, executed_successf
|
|
| 271 |
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
|
| 272 |
return score, md
|
| 273 |
|
| 274 |
-
class AppOrchestrator:
|
| 275 |
-
def __init__(self, is_mock: bool = True):
|
| 276 |
-
self.is_mock = is_mock
|
|
|
|
| 277 |
|
| 278 |
self.overlay = TkinterOverlay(
|
| 279 |
on_submit_callback=self.handle_submit,
|
|
@@ -287,7 +289,10 @@ class AppOrchestrator:
|
|
| 287 |
planner = RuleBasedPlanner()
|
| 288 |
else:
|
| 289 |
planner = RemoteLLMPlanner()
|
| 290 |
-
agent = LLMAgent(
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
self.overlay.write_log("Đang mở cửa sổ OpenGL của Pybullet...")
|
| 293 |
self.sim = PandaSimulation(gui=True, agent=agent)
|
|
@@ -312,7 +317,10 @@ class AppOrchestrator:
|
|
| 312 |
planner = RemoteLLMPlanner()
|
| 313 |
self.overlay.write_log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
|
| 314 |
|
| 315 |
-
self.sim.agent = LLMAgent(
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
# Define reachability check for scene state
|
| 318 |
def reachability_fn(oid):
|
|
@@ -334,7 +342,15 @@ class AppOrchestrator:
|
|
| 334 |
self.overlay.write_log(f"❌ LLM Planner thất bại: {e}")
|
| 335 |
return
|
| 336 |
|
| 337 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 338 |
self.overlay.write_log(f" Bước {idx}: {step['function']}({step.get('args', {})})")
|
| 339 |
|
| 340 |
self.overlay.write_log("⏳ [2/5] Đang kiểm tra luật an toàn (Validator)...")
|
|
@@ -383,8 +399,9 @@ class AppOrchestrator:
|
|
| 383 |
messagebox.showinfo("Báo cáo kết quả Rearrangement", f"Rearrangement Score: {score_val:.1f}/100.0\n\nXem chi tiết điểm trong cửa sổ terminal chính.")
|
| 384 |
print("\n" + score_md)
|
| 385 |
|
| 386 |
-
def handle_reset(self):
|
| 387 |
-
self.
|
|
|
|
| 388 |
self.sim.controller.reset_to_home()
|
| 389 |
|
| 390 |
def handle_exit(self):
|
|
|
|
| 16 |
from dotenv import load_dotenv
|
| 17 |
load_dotenv()
|
| 18 |
|
| 19 |
+
from main import PandaSimulation
|
| 20 |
+
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 21 |
+
from llm_panda.conversation import ConversationManager
|
| 22 |
+
from llm_panda.plan_verifier import PlanVerifier
|
| 23 |
|
| 24 |
# Preset prompts matching CLI
|
| 25 |
PRESETS = {
|
|
|
|
| 272 |
md = f"### 🏆 Rearrangement Evaluation Report\n\n**Tổng điểm: {score}/100**\n\n**Chi tiết:**\n" + "\n".join([f"- {d}" for d in details])
|
| 273 |
return score, md
|
| 274 |
|
| 275 |
+
class AppOrchestrator:
|
| 276 |
+
def __init__(self, is_mock: bool = True):
|
| 277 |
+
self.is_mock = is_mock
|
| 278 |
+
self.conversation_manager = ConversationManager()
|
| 279 |
|
| 280 |
self.overlay = TkinterOverlay(
|
| 281 |
on_submit_callback=self.handle_submit,
|
|
|
|
| 289 |
planner = RuleBasedPlanner()
|
| 290 |
else:
|
| 291 |
planner = RemoteLLMPlanner()
|
| 292 |
+
agent = LLMAgent(
|
| 293 |
+
planner=planner,
|
| 294 |
+
conversation_manager=self.conversation_manager,
|
| 295 |
+
)
|
| 296 |
|
| 297 |
self.overlay.write_log("Đang mở cửa sổ OpenGL của Pybullet...")
|
| 298 |
self.sim = PandaSimulation(gui=True, agent=agent)
|
|
|
|
| 317 |
planner = RemoteLLMPlanner()
|
| 318 |
self.overlay.write_log(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})")
|
| 319 |
|
| 320 |
+
self.sim.agent = LLMAgent(
|
| 321 |
+
planner=planner,
|
| 322 |
+
conversation_manager=self.conversation_manager,
|
| 323 |
+
)
|
| 324 |
|
| 325 |
# Define reachability check for scene state
|
| 326 |
def reachability_fn(oid):
|
|
|
|
| 342 |
self.overlay.write_log(f"❌ LLM Planner thất bại: {e}")
|
| 343 |
return
|
| 344 |
|
| 345 |
+
if plan and plan[0].get("function") in ("clarify", "reject"):
|
| 346 |
+
message = plan[0].get("args", {}).get(
|
| 347 |
+
"message",
|
| 348 |
+
"Yêu cầu cần được làm rõ.",
|
| 349 |
+
)
|
| 350 |
+
self.overlay.write_log(f"Robot: {message}")
|
| 351 |
+
return
|
| 352 |
+
|
| 353 |
+
for idx, step in enumerate(plan, 1):
|
| 354 |
self.overlay.write_log(f" Bước {idx}: {step['function']}({step.get('args', {})})")
|
| 355 |
|
| 356 |
self.overlay.write_log("⏳ [2/5] Đang kiểm tra luật an toàn (Validator)...")
|
|
|
|
| 399 |
messagebox.showinfo("Báo cáo kết quả Rearrangement", f"Rearrangement Score: {score_val:.1f}/100.0\n\nXem chi tiết điểm trong cửa sổ terminal chính.")
|
| 400 |
print("\n" + score_md)
|
| 401 |
|
| 402 |
+
def handle_reset(self):
|
| 403 |
+
self.conversation_manager.clear()
|
| 404 |
+
self.sim.reset_objects(seed=0)
|
| 405 |
self.sim.controller.reset_to_home()
|
| 406 |
|
| 407 |
def handle_exit(self):
|
frontend/threads/__pycache__/llm_thread.cpython-310.pyc
CHANGED
|
Binary files a/frontend/threads/__pycache__/llm_thread.cpython-310.pyc and b/frontend/threads/__pycache__/llm_thread.cpython-310.pyc differ
|
|
|
frontend/threads/__pycache__/simulation_thread.cpython-310.pyc
CHANGED
|
Binary files a/frontend/threads/__pycache__/simulation_thread.cpython-310.pyc and b/frontend/threads/__pycache__/simulation_thread.cpython-310.pyc differ
|
|
|
frontend/threads/llm_thread.py
CHANGED
|
@@ -9,7 +9,8 @@ PROJECT_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."
|
|
| 9 |
if PROJECT_SRC not in sys.path:
|
| 10 |
sys.path.insert(0, PROJECT_SRC)
|
| 11 |
|
| 12 |
-
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
|
|
|
| 13 |
|
| 14 |
class LLMThread(QThread):
|
| 15 |
"""
|
|
@@ -20,11 +21,18 @@ class LLMThread(QThread):
|
|
| 20 |
log_message = Signal(str, str) # message, type (info, success, warn, error)
|
| 21 |
failed = Signal(str)
|
| 22 |
|
| 23 |
-
def __init__(
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def run(self):
|
| 30 |
try:
|
|
@@ -44,7 +52,10 @@ class LLMThread(QThread):
|
|
| 44 |
planner = RemoteLLMPlanner()
|
| 45 |
self.log_message.emit(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})", "success")
|
| 46 |
|
| 47 |
-
agent = LLMAgent(
|
|
|
|
|
|
|
|
|
|
| 48 |
state_text = json.dumps(self.scene_state, indent=2)
|
| 49 |
|
| 50 |
# Run planning
|
|
|
|
| 9 |
if PROJECT_SRC not in sys.path:
|
| 10 |
sys.path.insert(0, PROJECT_SRC)
|
| 11 |
|
| 12 |
+
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 13 |
+
from llm_panda.conversation import ConversationManager
|
| 14 |
|
| 15 |
class LLMThread(QThread):
|
| 16 |
"""
|
|
|
|
| 21 |
log_message = Signal(str, str) # message, type (info, success, warn, error)
|
| 22 |
failed = Signal(str)
|
| 23 |
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
prompt: str,
|
| 27 |
+
scene_state: dict,
|
| 28 |
+
use_mock: bool = True,
|
| 29 |
+
conversation_manager: ConversationManager = None,
|
| 30 |
+
):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.prompt = prompt
|
| 33 |
+
self.scene_state = scene_state
|
| 34 |
+
self.use_mock = use_mock
|
| 35 |
+
self.conversation_manager = conversation_manager
|
| 36 |
|
| 37 |
def run(self):
|
| 38 |
try:
|
|
|
|
| 52 |
planner = RemoteLLMPlanner()
|
| 53 |
self.log_message.emit(f"✅ [1] Đang sử dụng RemoteLLMPlanner (Model: {planner.model})", "success")
|
| 54 |
|
| 55 |
+
agent = LLMAgent(
|
| 56 |
+
planner=planner,
|
| 57 |
+
conversation_manager=self.conversation_manager,
|
| 58 |
+
)
|
| 59 |
state_text = json.dumps(self.scene_state, indent=2)
|
| 60 |
|
| 61 |
# Run planning
|
llm_panda/__pycache__/geofik.cpython-310.pyc
CHANGED
|
Binary files a/llm_panda/__pycache__/geofik.cpython-310.pyc and b/llm_panda/__pycache__/geofik.cpython-310.pyc differ
|
|
|
llm_panda/__pycache__/llm_agent.cpython-310.pyc
CHANGED
|
Binary files a/llm_panda/__pycache__/llm_agent.cpython-310.pyc and b/llm_panda/__pycache__/llm_agent.cpython-310.pyc differ
|
|
|
llm_panda/__pycache__/scene_manager.cpython-310.pyc
CHANGED
|
Binary files a/llm_panda/__pycache__/scene_manager.cpython-310.pyc and b/llm_panda/__pycache__/scene_manager.cpython-310.pyc differ
|
|
|
llm_panda/conversation/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Session-scoped conversational memory for clarification follow-ups."""
|
| 2 |
+
|
| 3 |
+
from .manager import ConversationManager
|
| 4 |
+
from .models import (
|
| 5 |
+
ConversationTurn,
|
| 6 |
+
GoalPredicate,
|
| 7 |
+
PendingClarification,
|
| 8 |
+
PlanningOutcome,
|
| 9 |
+
ResolvedGoal,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"ConversationManager",
|
| 14 |
+
"ConversationTurn",
|
| 15 |
+
"GoalPredicate",
|
| 16 |
+
"PendingClarification",
|
| 17 |
+
"PlanningOutcome",
|
| 18 |
+
"ResolvedGoal",
|
| 19 |
+
]
|
llm_panda/conversation/manager.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Thread-safe, in-session memory for multi-turn command clarification.
|
| 2 |
+
|
| 3 |
+
This deliberately stores only the unresolved command, the robot's question,
|
| 4 |
+
and a small recent-turn buffer. Physical scene state is never remembered here;
|
| 5 |
+
callers must continue to provide a fresh scene snapshot for every plan.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from collections import deque
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
import threading
|
| 13 |
+
import time
|
| 14 |
+
import uuid
|
| 15 |
+
from typing import Callable, Iterable, Optional
|
| 16 |
+
|
| 17 |
+
from .models import ConversationTurn, PendingClarification
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ConversationManager:
|
| 21 |
+
"""Maintain bounded clarification state for one user session."""
|
| 22 |
+
|
| 23 |
+
_CANCEL_PHRASES = {
|
| 24 |
+
"cancel",
|
| 25 |
+
"forget it",
|
| 26 |
+
"never mind",
|
| 27 |
+
"stop",
|
| 28 |
+
"bỏ qua",
|
| 29 |
+
"hủy",
|
| 30 |
+
"hủy lệnh",
|
| 31 |
+
"không cần nữa",
|
| 32 |
+
"thôi",
|
| 33 |
+
"thôi bỏ đi",
|
| 34 |
+
"dừng lại",
|
| 35 |
+
}
|
| 36 |
+
_ACTION_WORDS = {
|
| 37 |
+
"gắp",
|
| 38 |
+
"nhặt",
|
| 39 |
+
"nhấc",
|
| 40 |
+
"cầm",
|
| 41 |
+
"di chuyển",
|
| 42 |
+
"đặt",
|
| 43 |
+
"để",
|
| 44 |
+
"bỏ",
|
| 45 |
+
"pick",
|
| 46 |
+
"grab",
|
| 47 |
+
"move",
|
| 48 |
+
"place",
|
| 49 |
+
"put",
|
| 50 |
+
}
|
| 51 |
+
_OBJECT_WORDS = {
|
| 52 |
+
"chuối",
|
| 53 |
+
"banana",
|
| 54 |
+
"súp",
|
| 55 |
+
"soup",
|
| 56 |
+
"chips",
|
| 57 |
+
"snack",
|
| 58 |
+
"bóng",
|
| 59 |
+
"tennis",
|
| 60 |
+
"lê",
|
| 61 |
+
"pear",
|
| 62 |
+
"kẹp",
|
| 63 |
+
"kìm",
|
| 64 |
+
"clamp",
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
session_id: Optional[str] = None,
|
| 70 |
+
max_turns: int = 6,
|
| 71 |
+
pending_ttl_seconds: float = 600.0,
|
| 72 |
+
clock: Callable[[], float] = time.monotonic,
|
| 73 |
+
):
|
| 74 |
+
if max_turns < 1:
|
| 75 |
+
raise ValueError("max_turns must be >= 1")
|
| 76 |
+
if pending_ttl_seconds <= 0:
|
| 77 |
+
raise ValueError("pending_ttl_seconds must be > 0")
|
| 78 |
+
|
| 79 |
+
self.session_id = session_id or uuid.uuid4().hex
|
| 80 |
+
self.max_turns = max_turns
|
| 81 |
+
self.pending_ttl_seconds = float(pending_ttl_seconds)
|
| 82 |
+
self._clock = clock
|
| 83 |
+
self._turns = deque(maxlen=max_turns * 2)
|
| 84 |
+
self._pending: Optional[PendingClarification] = None
|
| 85 |
+
self._lock = threading.RLock()
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def pending(self) -> Optional[PendingClarification]:
|
| 89 |
+
with self._lock:
|
| 90 |
+
self._expire_pending_locked()
|
| 91 |
+
return self._pending
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def recent_turns(self) -> tuple[ConversationTurn, ...]:
|
| 95 |
+
with self._lock:
|
| 96 |
+
return tuple(self._turns)
|
| 97 |
+
|
| 98 |
+
def cancel_if_requested(self, user_command: str) -> bool:
|
| 99 |
+
"""Cancel an unresolved request without calling the LLM."""
|
| 100 |
+
command = user_command.strip()
|
| 101 |
+
normalized = self._normalize(command)
|
| 102 |
+
with self._lock:
|
| 103 |
+
self._expire_pending_locked()
|
| 104 |
+
if self._pending is None or normalized not in self._CANCEL_PHRASES:
|
| 105 |
+
return False
|
| 106 |
+
|
| 107 |
+
now = self._clock()
|
| 108 |
+
self._turns.append(
|
| 109 |
+
ConversationTurn("user", command, "cancel", now)
|
| 110 |
+
)
|
| 111 |
+
self._turns.append(
|
| 112 |
+
ConversationTurn(
|
| 113 |
+
"assistant",
|
| 114 |
+
"Đã hủy yêu cầu đang chờ.",
|
| 115 |
+
"cancelled",
|
| 116 |
+
now,
|
| 117 |
+
)
|
| 118 |
+
)
|
| 119 |
+
self._pending = None
|
| 120 |
+
return True
|
| 121 |
+
|
| 122 |
+
def contextualize(self, user_command: str, scene_state=None) -> str:
|
| 123 |
+
"""Return the effective instruction for the planner.
|
| 124 |
+
|
| 125 |
+
A normal one-shot command is returned byte-for-byte. Only a reply made
|
| 126 |
+
while clarification is pending receives the compact conversation block.
|
| 127 |
+
"""
|
| 128 |
+
command = user_command.strip()
|
| 129 |
+
with self._lock:
|
| 130 |
+
self._expire_pending_locked()
|
| 131 |
+
if self._pending is None:
|
| 132 |
+
return command
|
| 133 |
+
|
| 134 |
+
if self._looks_like_new_command(command):
|
| 135 |
+
self._pending = None
|
| 136 |
+
return command
|
| 137 |
+
|
| 138 |
+
pending = self._pending
|
| 139 |
+
current_revision = self.scene_revision(scene_state)
|
| 140 |
+
scene_changed = (
|
| 141 |
+
pending.scene_revision is not None
|
| 142 |
+
and current_revision is not None
|
| 143 |
+
and pending.scene_revision != current_revision
|
| 144 |
+
)
|
| 145 |
+
missing_fields = json.dumps(
|
| 146 |
+
list(pending.missing_fields),
|
| 147 |
+
ensure_ascii=False,
|
| 148 |
+
)
|
| 149 |
+
partial_intent = json.dumps(
|
| 150 |
+
dict(pending.partial_intent or {}),
|
| 151 |
+
ensure_ascii=False,
|
| 152 |
+
sort_keys=True,
|
| 153 |
+
)
|
| 154 |
+
return (
|
| 155 |
+
"Đây là lượt tiếp theo của một yêu cầu đang được làm rõ.\n"
|
| 156 |
+
f"Yêu cầu trước chưa hoàn chỉnh: {pending.original_command}\n"
|
| 157 |
+
f"Robot đã hỏi: {pending.robot_question}\n"
|
| 158 |
+
f"Thông tin còn thiếu: {missing_fields}\n"
|
| 159 |
+
f"Ý định đã biết: {partial_intent}\n"
|
| 160 |
+
f"Scene đã thay đổi từ lượt trước: {'có' if scene_changed else 'không'}\n"
|
| 161 |
+
f"Người dùng vừa trả lời: {command}\n"
|
| 162 |
+
"Hãy kết hợp câu trả lời với yêu cầu trước để lập kế hoạch. "
|
| 163 |
+
"Luôn dùng scene mới nhất bên dưới. Nếu câu mới rõ ràng là một "
|
| 164 |
+
"lệnh độc lập, hãy ưu tiên lệnh mới."
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def observe(self, user_command: str, plan: Iterable[dict], scene_state=None) -> None:
|
| 168 |
+
"""Update pending state after the planner returns a validated plan."""
|
| 169 |
+
command = user_command.strip()
|
| 170 |
+
steps = list(plan)
|
| 171 |
+
now = self._clock()
|
| 172 |
+
|
| 173 |
+
with self._lock:
|
| 174 |
+
self._expire_pending_locked(now)
|
| 175 |
+
previous_pending = self._pending
|
| 176 |
+
self._turns.append(
|
| 177 |
+
ConversationTurn("user", command, "message", now)
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
first = steps[0] if steps else {}
|
| 181 |
+
function = first.get("function")
|
| 182 |
+
args = first.get("args", {}) if isinstance(first, dict) else {}
|
| 183 |
+
|
| 184 |
+
if function == "clarify":
|
| 185 |
+
question = str(args.get("message", "")).strip()
|
| 186 |
+
missing_fields, partial_intent = self._clarification_metadata(
|
| 187 |
+
command,
|
| 188 |
+
question,
|
| 189 |
+
args,
|
| 190 |
+
)
|
| 191 |
+
if previous_pending is None:
|
| 192 |
+
accumulated = command
|
| 193 |
+
merged_intent = partial_intent
|
| 194 |
+
else:
|
| 195 |
+
accumulated = (
|
| 196 |
+
f"{previous_pending.original_command}; "
|
| 197 |
+
f"thông tin bổ sung: {command}"
|
| 198 |
+
)
|
| 199 |
+
merged_intent = dict(previous_pending.partial_intent or {})
|
| 200 |
+
merged_intent.update(partial_intent)
|
| 201 |
+
self._pending = PendingClarification(
|
| 202 |
+
original_command=accumulated,
|
| 203 |
+
robot_question=question,
|
| 204 |
+
created_at=now,
|
| 205 |
+
expires_at=now + self.pending_ttl_seconds,
|
| 206 |
+
missing_fields=missing_fields,
|
| 207 |
+
partial_intent=merged_intent,
|
| 208 |
+
scene_revision=self.scene_revision(scene_state),
|
| 209 |
+
)
|
| 210 |
+
self._turns.append(
|
| 211 |
+
ConversationTurn("assistant", question, "clarify", now)
|
| 212 |
+
)
|
| 213 |
+
return
|
| 214 |
+
|
| 215 |
+
if function == "reject":
|
| 216 |
+
message = str(args.get("message", "")).strip()
|
| 217 |
+
self._turns.append(
|
| 218 |
+
ConversationTurn("assistant", message, "reject", now)
|
| 219 |
+
)
|
| 220 |
+
if previous_pending is not None:
|
| 221 |
+
# A rejected answer to a clarification (for example choosing
|
| 222 |
+
# an object absent from the scene) does not cancel the
|
| 223 |
+
# original request. Keep asking the original question.
|
| 224 |
+
self._pending = PendingClarification(
|
| 225 |
+
original_command=previous_pending.original_command,
|
| 226 |
+
robot_question=previous_pending.robot_question,
|
| 227 |
+
created_at=previous_pending.created_at,
|
| 228 |
+
expires_at=now + self.pending_ttl_seconds,
|
| 229 |
+
missing_fields=previous_pending.missing_fields,
|
| 230 |
+
partial_intent=dict(previous_pending.partial_intent or {}),
|
| 231 |
+
scene_revision=self.scene_revision(scene_state),
|
| 232 |
+
)
|
| 233 |
+
return
|
| 234 |
+
elif steps:
|
| 235 |
+
self._turns.append(
|
| 236 |
+
ConversationTurn(
|
| 237 |
+
"assistant",
|
| 238 |
+
f"Generated {len(steps)} executable step(s).",
|
| 239 |
+
"plan",
|
| 240 |
+
now,
|
| 241 |
+
)
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# A ready plan or a rejection outside clarification closes state.
|
| 245 |
+
if function in ("reject", "pick_up", "move_to", "place_down"):
|
| 246 |
+
self._pending = None
|
| 247 |
+
|
| 248 |
+
def clear(self) -> None:
|
| 249 |
+
"""Forget all conversation state for this session."""
|
| 250 |
+
with self._lock:
|
| 251 |
+
self._pending = None
|
| 252 |
+
self._turns.clear()
|
| 253 |
+
|
| 254 |
+
def _expire_pending_locked(self, now: Optional[float] = None) -> None:
|
| 255 |
+
if self._pending is None:
|
| 256 |
+
return
|
| 257 |
+
current = self._clock() if now is None else now
|
| 258 |
+
if current >= self._pending.expires_at:
|
| 259 |
+
self._pending = None
|
| 260 |
+
|
| 261 |
+
@staticmethod
|
| 262 |
+
def scene_revision(scene_state) -> Optional[str]:
|
| 263 |
+
"""Return a stable digest of only the physical facts relevant to planning."""
|
| 264 |
+
if scene_state is None:
|
| 265 |
+
return None
|
| 266 |
+
if isinstance(scene_state, str):
|
| 267 |
+
try:
|
| 268 |
+
scene_state = json.loads(scene_state)
|
| 269 |
+
except (TypeError, ValueError, json.JSONDecodeError):
|
| 270 |
+
return hashlib.sha256(
|
| 271 |
+
scene_state.encode("utf-8", errors="replace")
|
| 272 |
+
).hexdigest()[:16]
|
| 273 |
+
if not isinstance(scene_state, dict):
|
| 274 |
+
return None
|
| 275 |
+
|
| 276 |
+
objects = []
|
| 277 |
+
for obj in scene_state.get("objects", []):
|
| 278 |
+
objects.append(
|
| 279 |
+
{
|
| 280 |
+
"name": obj.get("name"),
|
| 281 |
+
"location": obj.get("location"),
|
| 282 |
+
"reachable": obj.get("reachable"),
|
| 283 |
+
"blocking_objects": sorted(
|
| 284 |
+
obj.get("blocking_objects", [])
|
| 285 |
+
),
|
| 286 |
+
}
|
| 287 |
+
)
|
| 288 |
+
payload = {
|
| 289 |
+
"objects": sorted(objects, key=lambda item: item["name"] or ""),
|
| 290 |
+
"carried_object": scene_state.get("carried_object"),
|
| 291 |
+
}
|
| 292 |
+
encoded = json.dumps(
|
| 293 |
+
payload,
|
| 294 |
+
ensure_ascii=False,
|
| 295 |
+
sort_keys=True,
|
| 296 |
+
separators=(",", ":"),
|
| 297 |
+
).encode("utf-8")
|
| 298 |
+
return hashlib.sha256(encoded).hexdigest()[:16]
|
| 299 |
+
|
| 300 |
+
@classmethod
|
| 301 |
+
def _normalize(cls, command: str) -> str:
|
| 302 |
+
return re.sub(r"[.!?]+$", "", command.lower().strip())
|
| 303 |
+
|
| 304 |
+
@classmethod
|
| 305 |
+
def _looks_like_new_command(cls, command: str) -> bool:
|
| 306 |
+
normalized = cls._normalize(command)
|
| 307 |
+
has_action = any(word in normalized for word in cls._ACTION_WORDS)
|
| 308 |
+
has_object = any(word in normalized for word in cls._OBJECT_WORDS)
|
| 309 |
+
return has_action and has_object
|
| 310 |
+
|
| 311 |
+
@classmethod
|
| 312 |
+
def _clarification_metadata(cls, command, question, args):
|
| 313 |
+
raw_missing = args.get("missing_fields", [])
|
| 314 |
+
missing_fields = tuple(
|
| 315 |
+
field
|
| 316 |
+
for field in raw_missing
|
| 317 |
+
if isinstance(field, str) and field
|
| 318 |
+
)
|
| 319 |
+
partial_intent = args.get("partial_intent", {})
|
| 320 |
+
if not isinstance(partial_intent, dict):
|
| 321 |
+
partial_intent = {}
|
| 322 |
+
else:
|
| 323 |
+
partial_intent = dict(partial_intent)
|
| 324 |
+
|
| 325 |
+
normalized_question = cls._normalize(question)
|
| 326 |
+
if not missing_fields:
|
| 327 |
+
if any(
|
| 328 |
+
marker in normalized_question
|
| 329 |
+
for marker in ("vật nào", "object", "cái gì", "quả nào")
|
| 330 |
+
):
|
| 331 |
+
missing_fields = ("object_id",)
|
| 332 |
+
elif any(
|
| 333 |
+
marker in normalized_question
|
| 334 |
+
for marker in ("đến đâu", "ở đâu", "where", "khay hay bàn")
|
| 335 |
+
):
|
| 336 |
+
missing_fields = ("destination",)
|
| 337 |
+
else:
|
| 338 |
+
missing_fields = ("details",)
|
| 339 |
+
|
| 340 |
+
if not partial_intent:
|
| 341 |
+
normalized_command = cls._normalize(command)
|
| 342 |
+
if "khay" in normalized_command or "tray" in normalized_command:
|
| 343 |
+
partial_intent["destination"] = "tray"
|
| 344 |
+
elif "bàn" in normalized_command or "table" in normalized_command:
|
| 345 |
+
partial_intent["destination"] = "table"
|
| 346 |
+
|
| 347 |
+
return missing_fields, partial_intent
|
llm_panda/conversation/models.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, provider-agnostic data models for conversational state."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import Any, Mapping, Optional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass(frozen=True)
|
| 8 |
+
class ConversationTurn:
|
| 9 |
+
"""One bounded user/robot exchange kept for observability and future summary."""
|
| 10 |
+
|
| 11 |
+
role: str
|
| 12 |
+
content: str
|
| 13 |
+
kind: str
|
| 14 |
+
created_at: float
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(frozen=True)
|
| 18 |
+
class PendingClarification:
|
| 19 |
+
"""The unresolved command that the robot most recently asked about."""
|
| 20 |
+
|
| 21 |
+
original_command: str
|
| 22 |
+
robot_question: str
|
| 23 |
+
created_at: float
|
| 24 |
+
expires_at: float
|
| 25 |
+
missing_fields: tuple[str, ...] = ()
|
| 26 |
+
partial_intent: Mapping[str, Any] = field(default_factory=dict)
|
| 27 |
+
scene_revision: Optional[str] = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass(frozen=True)
|
| 31 |
+
class GoalPredicate:
|
| 32 |
+
"""One machine-checkable condition that defines task completion."""
|
| 33 |
+
|
| 34 |
+
type: str
|
| 35 |
+
object_id: Optional[str] = None
|
| 36 |
+
location_id: Optional[str] = None
|
| 37 |
+
relation: Optional[str] = None
|
| 38 |
+
relative_to: Optional[str] = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass(frozen=True)
|
| 42 |
+
class ResolvedGoal:
|
| 43 |
+
"""Immutable semantic goal shared by planning, execution and monitoring."""
|
| 44 |
+
|
| 45 |
+
task_id: str
|
| 46 |
+
canonical_instruction: str
|
| 47 |
+
predicates: tuple[GoalPredicate, ...]
|
| 48 |
+
source_command: str
|
| 49 |
+
effective_command: str
|
| 50 |
+
initial_scene_revision: Optional[str] = None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass(frozen=True)
|
| 54 |
+
class PlanningOutcome:
|
| 55 |
+
"""Backward-compatible plan plus the context needed after planning."""
|
| 56 |
+
|
| 57 |
+
steps: tuple[Mapping[str, Any], ...]
|
| 58 |
+
response_type: str
|
| 59 |
+
effective_command: str
|
| 60 |
+
resolved_goal: Optional[ResolvedGoal] = None
|
llm_panda/execution/monitor.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import logging
|
| 2 |
import json
|
|
|
|
| 3 |
import pybullet as pb
|
| 4 |
from llm_panda import config
|
| 5 |
|
|
@@ -58,12 +59,112 @@ class ExecutionMonitor:
|
|
| 58 |
|
| 59 |
return True, ""
|
| 60 |
|
| 61 |
-
def verify_goal(self, nl_command, scene_state_text):
|
| 62 |
"""
|
| 63 |
Uses LLM (if available) or Rule-based to check if the goal is met.
|
| 64 |
Since we might not want to incur an extra API call if not strictly necessary,
|
| 65 |
we can delegate to the agent's check_goal method.
|
| 66 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
if hasattr(self.agent, "check_goal"):
|
| 68 |
return self.agent.check_goal(nl_command, scene_state_text)
|
| 69 |
return True, "Assumed Goal Reached (Agent lacks check_goal method)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
import json
|
| 3 |
+
import os
|
| 4 |
import pybullet as pb
|
| 5 |
from llm_panda import config
|
| 6 |
|
|
|
|
| 59 |
|
| 60 |
return True, ""
|
| 61 |
|
| 62 |
+
def verify_goal(self, nl_command, scene_state_text, resolved_goal=None):
|
| 63 |
"""
|
| 64 |
Uses LLM (if available) or Rule-based to check if the goal is met.
|
| 65 |
Since we might not want to incur an extra API call if not strictly necessary,
|
| 66 |
we can delegate to the agent's check_goal method.
|
| 67 |
"""
|
| 68 |
+
enabled = os.environ.get(
|
| 69 |
+
"STRUCTURED_GOAL_CHECK_ENABLED", "true"
|
| 70 |
+
).lower() not in {"0", "false", "no", "off"}
|
| 71 |
+
if enabled and resolved_goal is not None:
|
| 72 |
+
result = self._verify_predicates(
|
| 73 |
+
resolved_goal,
|
| 74 |
+
scene_state_text,
|
| 75 |
+
scene=self.scene,
|
| 76 |
+
)
|
| 77 |
+
if result is not None:
|
| 78 |
+
return result
|
| 79 |
+
nl_command = resolved_goal.canonical_instruction
|
| 80 |
if hasattr(self.agent, "check_goal"):
|
| 81 |
return self.agent.check_goal(nl_command, scene_state_text)
|
| 82 |
return True, "Assumed Goal Reached (Agent lacks check_goal method)"
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def _verify_predicates(resolved_goal, scene_state_text, scene=None):
|
| 86 |
+
"""Evaluate common robot goals without another probabilistic LLM call."""
|
| 87 |
+
try:
|
| 88 |
+
state = (
|
| 89 |
+
json.loads(scene_state_text)
|
| 90 |
+
if isinstance(scene_state_text, str)
|
| 91 |
+
else scene_state_text
|
| 92 |
+
)
|
| 93 |
+
except (TypeError, ValueError, json.JSONDecodeError):
|
| 94 |
+
return None
|
| 95 |
+
if not isinstance(state, dict):
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
+
objects = {
|
| 99 |
+
obj.get("name"): obj
|
| 100 |
+
for obj in state.get("objects", [])
|
| 101 |
+
if isinstance(obj, dict) and obj.get("name")
|
| 102 |
+
}
|
| 103 |
+
failures = []
|
| 104 |
+
passed = []
|
| 105 |
+
for predicate in resolved_goal.predicates:
|
| 106 |
+
if predicate.type == "carried_object_is":
|
| 107 |
+
actual = state.get("carried_object")
|
| 108 |
+
ok = actual == predicate.object_id
|
| 109 |
+
detail = (
|
| 110 |
+
f"carried_object={actual!r}, expected {predicate.object_id!r}"
|
| 111 |
+
)
|
| 112 |
+
elif predicate.type == "location_is":
|
| 113 |
+
obj = objects.get(predicate.object_id, {})
|
| 114 |
+
actual = obj.get("location")
|
| 115 |
+
expected = (
|
| 116 |
+
"table"
|
| 117 |
+
if predicate.location_id == "buffer"
|
| 118 |
+
else predicate.location_id
|
| 119 |
+
)
|
| 120 |
+
ok = actual == expected
|
| 121 |
+
detail = (
|
| 122 |
+
f"{predicate.object_id}.location={actual!r}, expected "
|
| 123 |
+
f"{expected!r}"
|
| 124 |
+
)
|
| 125 |
+
elif predicate.type == "relation_is":
|
| 126 |
+
obj = objects.get(predicate.object_id, {})
|
| 127 |
+
relations = obj.get("relations", {}) or {}
|
| 128 |
+
if predicate.relation == "next_to":
|
| 129 |
+
actual = (obj.get("distances", {}) or {}).get(
|
| 130 |
+
predicate.relative_to
|
| 131 |
+
)
|
| 132 |
+
same_surface = (
|
| 133 |
+
obj.get("location")
|
| 134 |
+
== objects.get(predicate.relative_to, {}).get("location")
|
| 135 |
+
)
|
| 136 |
+
ok = (
|
| 137 |
+
isinstance(actual, (int, float))
|
| 138 |
+
and actual <= max(0.20, config.RELATION_TARGET_GAP * 1.5)
|
| 139 |
+
and same_surface
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
actual = relations.get(predicate.relation)
|
| 143 |
+
if isinstance(actual, list):
|
| 144 |
+
ok = predicate.relative_to in actual
|
| 145 |
+
else:
|
| 146 |
+
ok = actual == predicate.relative_to
|
| 147 |
+
if (
|
| 148 |
+
not ok
|
| 149 |
+
and predicate.relation == "on_top_of"
|
| 150 |
+
and scene is not None
|
| 151 |
+
and hasattr(scene, "is_on_top")
|
| 152 |
+
):
|
| 153 |
+
ok = scene.is_on_top(
|
| 154 |
+
predicate.object_id,
|
| 155 |
+
predicate.relative_to,
|
| 156 |
+
)
|
| 157 |
+
if ok:
|
| 158 |
+
actual = "verified_from_live_aabb"
|
| 159 |
+
detail = (
|
| 160 |
+
f"{predicate.object_id}.{predicate.relation}={actual!r}, "
|
| 161 |
+
f"expected {predicate.relative_to!r}"
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
(passed if ok else failures).append(detail)
|
| 167 |
+
|
| 168 |
+
if failures:
|
| 169 |
+
return False, "Structured goal failed: " + "; ".join(failures)
|
| 170 |
+
return True, "Structured goal satisfied: " + "; ".join(passed)
|
llm_panda/execution/pipeline.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import json
|
| 2 |
import logging
|
|
|
|
| 3 |
import random
|
| 4 |
import time
|
| 5 |
import pybullet as pb
|
|
@@ -24,7 +25,7 @@ class ExecutionPipeline:
|
|
| 24 |
}
|
| 25 |
|
| 26 |
_MOVE_XY_TOL = 0.12 # TCP must stop roughly above the requested XY
|
| 27 |
-
MAX_REPLANS =
|
| 28 |
|
| 29 |
@property
|
| 30 |
def scene(self):
|
|
@@ -36,6 +37,16 @@ class ExecutionPipeline:
|
|
| 36 |
if hasattr(self, "execution_monitor") and self.execution_monitor is not None:
|
| 37 |
self.execution_monitor.scene = value
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
def __init__(self, sim_engine, scene, controller, table_id, tray_id, agent=None, viz=False):
|
| 40 |
self.sim = sim_engine
|
| 41 |
self._scene = scene
|
|
@@ -43,9 +54,15 @@ class ExecutionPipeline:
|
|
| 43 |
self.table_id = table_id
|
| 44 |
self.tray_id = tray_id
|
| 45 |
|
| 46 |
-
self.
|
| 47 |
self.grasp_planner = GraspPlanner()
|
| 48 |
self.execution_monitor = ExecutionMonitor(self._scene, self.controller, self.agent)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
self.viz = viz
|
| 50 |
self._overlay = None
|
| 51 |
|
|
@@ -77,6 +94,7 @@ class ExecutionPipeline:
|
|
| 77 |
last_failed_plan_sig = None
|
| 78 |
last_failed_state_sig = None
|
| 79 |
plan = []
|
|
|
|
| 80 |
|
| 81 |
for attempt in range(self.MAX_REPLANS + 1):
|
| 82 |
carried_name = self.scene.get_name(self._carried) if self._carried is not None else None
|
|
@@ -90,7 +108,23 @@ class ExecutionPipeline:
|
|
| 90 |
}
|
| 91 |
state_sig = json.dumps(state_sig_dict, sort_keys=True)
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
if verbose:
|
| 95 |
if attempt > 0:
|
| 96 |
logger.info(f"\n[MONITOR] Re-plan attempt {attempt}/{self.MAX_REPLANS} due to: {last_failed_sig}")
|
|
@@ -128,7 +162,11 @@ class ExecutionPipeline:
|
|
| 128 |
final_scene_state = self.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=self.scene.get_name(self._carried) if self._carried else None)
|
| 129 |
final_state_text = json.dumps(final_scene_state, indent=2)
|
| 130 |
|
| 131 |
-
goal_completed, goal_reason = self.execution_monitor.verify_goal(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
if goal_completed:
|
| 134 |
if verbose:
|
|
|
|
| 1 |
import json
|
| 2 |
import logging
|
| 3 |
+
import os
|
| 4 |
import random
|
| 5 |
import time
|
| 6 |
import pybullet as pb
|
|
|
|
| 25 |
}
|
| 26 |
|
| 27 |
_MOVE_XY_TOL = 0.12 # TCP must stop roughly above the requested XY
|
| 28 |
+
MAX_REPLANS = 3
|
| 29 |
|
| 30 |
@property
|
| 31 |
def scene(self):
|
|
|
|
| 37 |
if hasattr(self, "execution_monitor") and self.execution_monitor is not None:
|
| 38 |
self.execution_monitor.scene = value
|
| 39 |
|
| 40 |
+
@property
|
| 41 |
+
def agent(self):
|
| 42 |
+
return self._agent
|
| 43 |
+
|
| 44 |
+
@agent.setter
|
| 45 |
+
def agent(self, value):
|
| 46 |
+
self._agent = value
|
| 47 |
+
if hasattr(self, "execution_monitor") and self.execution_monitor is not None:
|
| 48 |
+
self.execution_monitor.agent = value
|
| 49 |
+
|
| 50 |
def __init__(self, sim_engine, scene, controller, table_id, tray_id, agent=None, viz=False):
|
| 51 |
self.sim = sim_engine
|
| 52 |
self._scene = scene
|
|
|
|
| 54 |
self.table_id = table_id
|
| 55 |
self.tray_id = tray_id
|
| 56 |
|
| 57 |
+
self._agent = agent or LLMAgent()
|
| 58 |
self.grasp_planner = GraspPlanner()
|
| 59 |
self.execution_monitor = ExecutionMonitor(self._scene, self.controller, self.agent)
|
| 60 |
+
try:
|
| 61 |
+
self.MAX_REPLANS = max(
|
| 62 |
+
0, int(os.environ.get("MAX_REPLANS", str(self.MAX_REPLANS)))
|
| 63 |
+
)
|
| 64 |
+
except ValueError:
|
| 65 |
+
self.MAX_REPLANS = 3
|
| 66 |
self.viz = viz
|
| 67 |
self._overlay = None
|
| 68 |
|
|
|
|
| 94 |
last_failed_plan_sig = None
|
| 95 |
last_failed_state_sig = None
|
| 96 |
plan = []
|
| 97 |
+
resolved_goal = None
|
| 98 |
|
| 99 |
for attempt in range(self.MAX_REPLANS + 1):
|
| 100 |
carried_name = self.scene.get_name(self._carried) if self._carried is not None else None
|
|
|
|
| 108 |
}
|
| 109 |
state_sig = json.dumps(state_sig_dict, sort_keys=True)
|
| 110 |
|
| 111 |
+
planning_command = (
|
| 112 |
+
resolved_goal.canonical_instruction
|
| 113 |
+
if attempt > 0 and resolved_goal is not None
|
| 114 |
+
else nl_command
|
| 115 |
+
)
|
| 116 |
+
self.agent.last_outcome = None
|
| 117 |
+
plan_kwargs = {"previous_failed_reasons": last_failed_sig}
|
| 118 |
+
if attempt > 0 and isinstance(self.agent, LLMAgent):
|
| 119 |
+
plan_kwargs["resolve_goal"] = False
|
| 120 |
+
plan = self.agent.plan(
|
| 121 |
+
planning_command,
|
| 122 |
+
state_text,
|
| 123 |
+
**plan_kwargs,
|
| 124 |
+
)
|
| 125 |
+
outcome = getattr(self.agent, "last_outcome", None)
|
| 126 |
+
if attempt == 0 and outcome is not None:
|
| 127 |
+
resolved_goal = outcome.resolved_goal
|
| 128 |
if verbose:
|
| 129 |
if attempt > 0:
|
| 130 |
logger.info(f"\n[MONITOR] Re-plan attempt {attempt}/{self.MAX_REPLANS} due to: {last_failed_sig}")
|
|
|
|
| 162 |
final_scene_state = self.scene.get_scene_state(reachability_fn=reachability_fn, carried_object=self.scene.get_name(self._carried) if self._carried else None)
|
| 163 |
final_state_text = json.dumps(final_scene_state, indent=2)
|
| 164 |
|
| 165 |
+
goal_completed, goal_reason = self.execution_monitor.verify_goal(
|
| 166 |
+
nl_command,
|
| 167 |
+
final_state_text,
|
| 168 |
+
resolved_goal=resolved_goal,
|
| 169 |
+
)
|
| 170 |
|
| 171 |
if goal_completed:
|
| 172 |
if verbose:
|
llm_panda/llm_agent.py
CHANGED
|
@@ -17,11 +17,19 @@ Two planners are provided behind one interface:
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
import json
|
| 20 |
-
import logging
|
| 21 |
-
import os
|
| 22 |
-
import re
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
# Available actions the planner may emit.
|
| 27 |
ACTIONS = ("pick_up", "move_to", "place_down", "clarify", "reject")
|
|
@@ -121,12 +129,35 @@ class RuleBasedPlanner:
|
|
| 121 |
plan.append({"function": "place_down", "args": {}})
|
| 122 |
|
| 123 |
# Scenario 1: Robot is already holding an object, and user says where to place it
|
| 124 |
-
elif carried_object and location is not None and target_name is None:
|
| 125 |
-
plan.append({"function": "move_to", "args": location})
|
| 126 |
-
plan.append({"function": "place_down", "args": {}})
|
| 127 |
-
|
| 128 |
-
#
|
| 129 |
-
elif
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
# If we are already holding something else, place it on the table first.
|
| 131 |
if carried_object and carried_object != target_name:
|
| 132 |
plan.append({"function": "move_to", "args": {"location_id": "table"}})
|
|
@@ -154,19 +185,49 @@ class RuleBasedPlanner:
|
|
| 154 |
plan = [{"function": "reject", "args": {"message": f"Tôi đang cầm {friendly_name} rồi, bạn muốn tôi đặt nó đi đâu không?"}}]
|
| 155 |
# Check if it is a pick command but target resolved to None
|
| 156 |
elif any(w in cmd for w in _PICK_VERBS):
|
| 157 |
-
if "con mèo" in cmd:
|
| 158 |
-
plan = [{"function": "reject", "args": {"message": "Trong môi trường không có con mèo nào cả, tôi không thể thực hiện được."}}]
|
| 159 |
-
else:
|
| 160 |
-
plan = [
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
# No target found — check if it's a retry command.
|
| 165 |
elif any(kw in cmd for kw in _RETRY_KEYWORDS) and self._last_plan:
|
| 166 |
logger.debug(f"retry detected → reusing last plan: {self._last_plan}")
|
| 167 |
return list(self._last_plan)
|
| 168 |
-
else:
|
| 169 |
-
plan = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
logger.debug(f"rule-based plan: target={target_name} location={location} -> {plan}")
|
| 172 |
if plan:
|
|
@@ -306,9 +367,14 @@ class RemoteLLMPlanner:
|
|
| 306 |
|
| 307 |
SYSTEM_PROMPT = (
|
| 308 |
"""You are the semantic planner for a Franka Emika Panda robot arm (PyBullet).
|
| 309 |
-
Input: the scene state as JSON + a natural-language instruction.
|
| 310 |
-
Output: ONLY a JSON array of sequential function calls, using this schema:
|
| 311 |
-
[{"function":"pick_up","args":{"object_id":"<name>"}},{"function":"move_to","args":{"location_id":"<table|tray>","relation":"<optional>","relative_to":"<optional object name>"}},{"function":"place_down","args":{}}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
## DESTINATIONS
|
| 314 |
Only two destinations exist: "table" and "tray". You do NOT compute coordinates and do NOT track free space — the executor's optimiser automatically picks a free, collision-free, reachable spot. You only choose the surface (and optionally a relation). NEVER invent any other location_id.
|
|
@@ -358,12 +424,13 @@ EXCEPTION FOR MUTUAL BLOCKING CYCLES/DEADLOCKS: If objects block each other form
|
|
| 358 |
|
| 359 |
## INTERACTIVE CLARIFICATION & REJECTION
|
| 360 |
Analyze if the user's instruction is valid, complete, and physically possible given the current scene objects and state. If not, do NOT output standard physical steps. Instead, output a single clarify or reject step.
|
| 361 |
-
1. CLARIFICATION (clarify): Use this when the instruction is missing critical information, is ambiguous, or we cannot determine what action/object is intended.
|
| 362 |
-
- Schema: [{"function":"clarify","args":{"message":"<Vietnamese clarifying question>"}}]
|
| 363 |
-
-
|
| 364 |
-
|
| 365 |
-
- User: "
|
| 366 |
-
- User: "
|
|
|
|
| 367 |
|
| 368 |
2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules.
|
| 369 |
- Schema: [{"function":"reject","args":{"message":"<Vietnamese friendly rejection message explaining the reason>"}}]
|
|
@@ -391,11 +458,42 @@ carried_object="banana", "đặt nó bên trái lon súp": [{"function":"move_to
|
|
| 391 |
"gắp chuối bỏ vào khay" with banana blocking_objects=["chips_can"]: [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
|
| 392 |
# Category Sorting Example: Keep only food on the tray (banana is on table; tennis_ball and clamp are on tray): [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"tennis_ball"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"clamp"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}]
|
| 393 |
|
| 394 |
-
Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text."""
|
| 395 |
-
)
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
# Best-effort: load a local .env so keys/models are picked up automatically.
|
| 400 |
try:
|
| 401 |
from dotenv import load_dotenv
|
|
@@ -410,9 +508,14 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
|
|
| 410 |
model or os.environ.get("OPENAI_MODEL") or os.environ.get("OPENAI_MODE")
|
| 411 |
or os.environ.get("LLM_MODEL") or "gpt-4o"
|
| 412 |
)
|
| 413 |
-
# None -> the openai client uses the official OpenAI endpoint.
|
| 414 |
-
self.base_url = base_url or os.environ.get("OPENAI_BASE_URL") or os.environ.get("LLM_BASE_URL")
|
| 415 |
-
self._client = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
|
| 417 |
def plan(self, user_command, scene_state, previous_failed_reasons=None):
|
| 418 |
if isinstance(scene_state, dict):
|
|
@@ -435,15 +538,26 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
|
|
| 435 |
if previous_failed_reasons:
|
| 436 |
user_prompt += f"\n\nPREVIOUS FAILURE REASON:\n{previous_failed_reasons}\nPlease generate a new plan that avoids this failure."
|
| 437 |
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
|
| 448 |
# Check if targeting NVIDIA integrate endpoint and using a DeepSeek model
|
| 449 |
if self.base_url and "integrate.api.nvidia.com" in self.base_url and "deepseek" in self.model:
|
|
@@ -456,11 +570,32 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
|
|
| 456 |
max_retries = 5
|
| 457 |
backoff = 2.0
|
| 458 |
for attempt in range(max_retries):
|
| 459 |
-
try:
|
| 460 |
-
resp = client.chat.completions.create(**create_kwargs)
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
if hasattr(e, "status_code") and e.status_code == 429:
|
| 465 |
is_rate_limit = True
|
| 466 |
elif "429" in str(e) or "RateLimit" in type(e).__name__:
|
|
@@ -481,21 +616,150 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
|
|
| 481 |
if reasoning:
|
| 482 |
logger.info(f"\n--- [DEEPSEEK REASONING] ---\n{reasoning}\n---------------------------\n")
|
| 483 |
|
| 484 |
-
raw = resp.choices[0].message.content
|
| 485 |
-
logger.debug(f"LLM raw response: {raw}")
|
| 486 |
-
return self._parse(raw)
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
"""Extract the JSON array or object from a model response.
|
| 491 |
|
| 492 |
Some providers occasionally return an empty body (``content=None``),
|
| 493 |
e.g. on a transient hiccup or a reasoning-only turn. Treat that as "no
|
| 494 |
actionable plan" (``[]``) instead of crashing on ``re.search(None)``.
|
| 495 |
-
"""
|
| 496 |
-
if not text:
|
| 497 |
-
return []
|
| 498 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 499 |
if array_match:
|
| 500 |
try:
|
| 501 |
return json.loads(array_match.group(0))
|
|
@@ -509,9 +773,99 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
|
|
| 509 |
return [obj]
|
| 510 |
except Exception:
|
| 511 |
pass
|
| 512 |
-
return []
|
| 513 |
-
|
| 514 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
if isinstance(scene_state, dict):
|
| 516 |
scene_state = json.dumps(scene_state)
|
| 517 |
if not self.api_key:
|
|
@@ -555,11 +909,29 @@ Respond ONLY with the JSON array. No markdown, no code fences, no explanatory te
|
|
| 555 |
return False, str(e)
|
| 556 |
|
| 557 |
|
| 558 |
-
class LLMAgent:
|
| 559 |
-
"""Wraps a planner and validates its output against the action schema."""
|
| 560 |
-
|
| 561 |
-
def __init__(
|
| 562 |
-
self
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
def build_prompt(self, user_command, scene_state_text):
|
| 565 |
"""The exact text a real LLM would be shown (useful for logging)."""
|
|
@@ -568,13 +940,150 @@ class LLMAgent:
|
|
| 568 |
f"SCENE STATE:\n{scene_state_text}\n\n"
|
| 569 |
f"USER INSTRUCTION:\n{user_command}\n"
|
| 570 |
)
|
| 571 |
-
def plan(
|
| 572 |
-
|
| 573 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
# from scene geometry — so a model that rationalises away clearing (as
|
| 575 |
# the LLM did when it picked a banana blocked by a tall chips can) still
|
| 576 |
# produces a collision-free plan.
|
| 577 |
-
plan = self._inject_obstacle_clearing(
|
| 578 |
try:
|
| 579 |
from .plan_verifier import PlanVerifier
|
| 580 |
warnings = PlanVerifier.check(plan, scene_state)
|
|
@@ -582,7 +1091,119 @@ class LLMAgent:
|
|
| 582 |
logger.warning(f"[PLAN_WARN] {w}")
|
| 583 |
except ImportError:
|
| 584 |
pass # plan_verifier not yet available
|
| 585 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 586 |
|
| 587 |
def check_goal(self, user_command, scene_state):
|
| 588 |
if hasattr(self.planner, "check_goal"):
|
|
@@ -729,10 +1350,22 @@ class LLMAgent:
|
|
| 729 |
held = None
|
| 730 |
return out
|
| 731 |
|
| 732 |
-
@staticmethod
|
| 733 |
-
def _valid(step):
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
import json
|
| 20 |
+
import logging
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
import uuid
|
| 24 |
+
|
| 25 |
+
from llm_panda.conversation import (
|
| 26 |
+
ConversationManager,
|
| 27 |
+
GoalPredicate,
|
| 28 |
+
PlanningOutcome,
|
| 29 |
+
ResolvedGoal,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
|
| 34 |
# Available actions the planner may emit.
|
| 35 |
ACTIONS = ("pick_up", "move_to", "place_down", "clarify", "reject")
|
|
|
|
| 129 |
plan.append({"function": "place_down", "args": {}})
|
| 130 |
|
| 131 |
# Scenario 1: Robot is already holding an object, and user says where to place it
|
| 132 |
+
elif carried_object and location is not None and target_name is None:
|
| 133 |
+
plan.append({"function": "move_to", "args": location})
|
| 134 |
+
plan.append({"function": "place_down", "args": {}})
|
| 135 |
+
|
| 136 |
+
# A move request names the object but still needs a destination.
|
| 137 |
+
elif (
|
| 138 |
+
target_name is not None
|
| 139 |
+
and location is None
|
| 140 |
+
and any(w in cmd for w in ["di chuyển", "move", "put", "đặt", "để", "bỏ"])
|
| 141 |
+
):
|
| 142 |
+
plan = [
|
| 143 |
+
{
|
| 144 |
+
"function": "clarify",
|
| 145 |
+
"args": {
|
| 146 |
+
"message": (
|
| 147 |
+
f"Bạn muốn tôi di chuyển {target_name} đến đâu "
|
| 148 |
+
"(khay hay bàn)?"
|
| 149 |
+
),
|
| 150 |
+
"missing_fields": ["destination"],
|
| 151 |
+
"partial_intent": {
|
| 152 |
+
"action": "pick_and_place",
|
| 153 |
+
"object_id": target_name,
|
| 154 |
+
},
|
| 155 |
+
},
|
| 156 |
+
}
|
| 157 |
+
]
|
| 158 |
+
|
| 159 |
+
# Scenario 2: Standard command
|
| 160 |
+
elif target_name is not None:
|
| 161 |
# If we are already holding something else, place it on the table first.
|
| 162 |
if carried_object and carried_object != target_name:
|
| 163 |
plan.append({"function": "move_to", "args": {"location_id": "table"}})
|
|
|
|
| 185 |
plan = [{"function": "reject", "args": {"message": f"Tôi đang cầm {friendly_name} rồi, bạn muốn tôi đặt nó đi đâu không?"}}]
|
| 186 |
# Check if it is a pick command but target resolved to None
|
| 187 |
elif any(w in cmd for w in _PICK_VERBS):
|
| 188 |
+
if "con mèo" in cmd:
|
| 189 |
+
plan = [{"function": "reject", "args": {"message": "Trong môi trường không có con mèo nào cả, tôi không thể thực hiện được."}}]
|
| 190 |
+
else:
|
| 191 |
+
plan = [
|
| 192 |
+
{
|
| 193 |
+
"function": "clarify",
|
| 194 |
+
"args": {
|
| 195 |
+
"message": "Bạn muốn tôi gắp hoặc di chuyển vật thể nào?",
|
| 196 |
+
"missing_fields": ["object_id"],
|
| 197 |
+
"partial_intent": {"action": "pick_up"},
|
| 198 |
+
},
|
| 199 |
+
}
|
| 200 |
+
]
|
| 201 |
+
# Check if it is a place/move command but gripper is empty and no pick target is given
|
| 202 |
+
elif any(w in cmd for w in ["đặt", "để", "bỏ", "di chuyển", "place", "move", "put"]) and not carried_object:
|
| 203 |
+
partial_intent = {"action": "pick_and_place"}
|
| 204 |
+
if location is not None:
|
| 205 |
+
partial_intent["destination"] = location["location_id"]
|
| 206 |
+
plan = [
|
| 207 |
+
{
|
| 208 |
+
"function": "clarify",
|
| 209 |
+
"args": {
|
| 210 |
+
"message": "Bạn muốn tôi gắp vật nào để di chuyển?",
|
| 211 |
+
"missing_fields": ["object_id"],
|
| 212 |
+
"partial_intent": partial_intent,
|
| 213 |
+
},
|
| 214 |
+
}
|
| 215 |
+
]
|
| 216 |
# No target found — check if it's a retry command.
|
| 217 |
elif any(kw in cmd for kw in _RETRY_KEYWORDS) and self._last_plan:
|
| 218 |
logger.debug(f"retry detected → reusing last plan: {self._last_plan}")
|
| 219 |
return list(self._last_plan)
|
| 220 |
+
else:
|
| 221 |
+
plan = [
|
| 222 |
+
{
|
| 223 |
+
"function": "clarify",
|
| 224 |
+
"args": {
|
| 225 |
+
"message": "Tôi chưa hiểu rõ yêu cầu của bạn. Bạn có thể nói rõ hơn được không?",
|
| 226 |
+
"missing_fields": ["details"],
|
| 227 |
+
"partial_intent": {},
|
| 228 |
+
},
|
| 229 |
+
}
|
| 230 |
+
]
|
| 231 |
|
| 232 |
logger.debug(f"rule-based plan: target={target_name} location={location} -> {plan}")
|
| 233 |
if plan:
|
|
|
|
| 367 |
|
| 368 |
SYSTEM_PROMPT = (
|
| 369 |
"""You are the semantic planner for a Franka Emika Panda robot arm (PyBullet).
|
| 370 |
+
Input: the scene state as JSON + a natural-language instruction.
|
| 371 |
+
Output: ONLY a JSON array of sequential function calls, using this schema:
|
| 372 |
+
[{"function":"pick_up","args":{"object_id":"<name>"}},{"function":"move_to","args":{"location_id":"<table|tray>","relation":"<optional>","relative_to":"<optional object name>"}},{"function":"place_down","args":{}}]
|
| 373 |
+
|
| 374 |
+
The instruction has normally passed a Goal Resolution Gate. Plan only the stated
|
| 375 |
+
canonical goal. Never guess, omit, or emit an empty object_id/location_id. If any
|
| 376 |
+
critical field is still ambiguous, return one structured clarify step instead of
|
| 377 |
+
an incomplete physical action.
|
| 378 |
|
| 379 |
## DESTINATIONS
|
| 380 |
Only two destinations exist: "table" and "tray". You do NOT compute coordinates and do NOT track free space — the executor's optimiser automatically picks a free, collision-free, reachable spot. You only choose the surface (and optionally a relation). NEVER invent any other location_id.
|
|
|
|
| 424 |
|
| 425 |
## INTERACTIVE CLARIFICATION & REJECTION
|
| 426 |
Analyze if the user's instruction is valid, complete, and physically possible given the current scene objects and state. If not, do NOT output standard physical steps. Instead, output a single clarify or reject step.
|
| 427 |
+
1. CLARIFICATION (clarify): Use this when the instruction is missing critical information, is ambiguous, or we cannot determine what action/object is intended.
|
| 428 |
+
- Schema: [{"function":"clarify","args":{"message":"<Vietnamese clarifying question>","missing_fields":["object_id|destination|relation|relative_to|details"],"partial_intent":{"action":"<known action or null>","object_id":"<known object or null>","destination":"<known location or null>"}}}]
|
| 429 |
+
- Always include `missing_fields` and `partial_intent` for clarify. Omit unknown keys from `partial_intent` instead of inventing values.
|
| 430 |
+
- Examples:
|
| 431 |
+
- User: "gắp lên" or "di chuyển" -> [{"function":"clarify","args":{"message":"Bạn muốn tôi gắp hoặc di chuyển vật thể nào?","missing_fields":["object_id"],"partial_intent":{"action":"pick_up"}}}]
|
| 432 |
+
- User: "đặt vào khay" (when carried_object is null) -> [{"function":"clarify","args":{"message":"Bạn muốn tôi gắp vật nào để đặt vào khay?","missing_fields":["object_id"],"partial_intent":{"action":"pick_and_place","destination":"tray"}}}]
|
| 433 |
+
- User: "di chuyển quả chuối" -> [{"function":"clarify","args":{"message":"Bạn muốn tôi di chuyển quả chuối đến đâu (khay hay bàn)?","missing_fields":["destination"],"partial_intent":{"action":"pick_and_place","object_id":"banana"}}}]
|
| 434 |
|
| 435 |
2. REJECTION (reject): Use this when the instruction is impossible, unsafe, or violates physical/reachability rules.
|
| 436 |
- Schema: [{"function":"reject","args":{"message":"<Vietnamese friendly rejection message explaining the reason>"}}]
|
|
|
|
| 458 |
"gắp chuối bỏ vào khay" with banana blocking_objects=["chips_can"]: [{"function":"pick_up","args":{"object_id":"chips_can"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}}]
|
| 459 |
# Category Sorting Example: Keep only food on the tray (banana is on table; tennis_ball and clamp are on tray): [{"function":"pick_up","args":{"object_id":"banana"}},{"function":"move_to","args":{"location_id":"tray"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"tennis_ball"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}},{"function":"pick_up","args":{"object_id":"clamp"}},{"function":"move_to","args":{"location_id":"table"}},{"function":"place_down","args":{}}]
|
| 460 |
|
| 461 |
+
Respond ONLY with the JSON array. No markdown, no code fences, no explanatory text."""
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
GOAL_RESOLUTION_PROMPT = """You are the Goal Resolution Gate for a Franka Panda robot.
|
| 465 |
+
Decide whether the user's instruction is sufficiently precise to execute.
|
| 466 |
+
Do NOT create a robot action plan.
|
| 467 |
+
|
| 468 |
+
Use the current SCENE and any conversation context embedded in the instruction.
|
| 469 |
+
- status="ready" only when the exact action, target object(s), destination (when
|
| 470 |
+
needed), and spatial reference (when needed) are unambiguous and exist.
|
| 471 |
+
- status="clarify" when a critical field is missing or multiple objects match.
|
| 472 |
+
- status="reject" only when the request is absent, impossible, or unsupported.
|
| 473 |
+
|
| 474 |
+
Rules:
|
| 475 |
+
1. Never guess an object. Generic words such as "quả", "lon", "vật", or "cái đó"
|
| 476 |
+
are ambiguous whenever multiple scene objects match.
|
| 477 |
+
2. If banana and pear exist, "gắp quả lên lon chip" MUST ask which fruit. Preserve
|
| 478 |
+
the known on_top_of chips_can relation in partial_intent.
|
| 479 |
+
3. A pick-up-only request needs no destination. A pick-and-place request does.
|
| 480 |
+
4. Use only object IDs present in SCENE. Never emit an empty identifier.
|
| 481 |
+
5. canonical_instruction must fully express the resolved intent with canonical IDs.
|
| 482 |
+
6. The planner receives canonical_instruction, so preserve all stated constraints
|
| 483 |
+
and never add an unstated destination or exclusivity constraint.
|
| 484 |
+
7. Ask one concise Vietnamese question and offer scene-valid choices when possible.
|
| 485 |
+
|
| 486 |
+
Return one JSON object with exactly:
|
| 487 |
+
{
|
| 488 |
+
"status": "ready|clarify|reject",
|
| 489 |
+
"canonical_instruction": "<resolved instruction or empty string>",
|
| 490 |
+
"message": "<Vietnamese question/rejection, or empty when ready>",
|
| 491 |
+
"missing_fields": ["object_id|destination|relation|relative_to|details"],
|
| 492 |
+
"partial_intent": {}
|
| 493 |
+
}"""
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def __init__(self, model=None, api_key=None, base_url=None):
|
| 497 |
# Best-effort: load a local .env so keys/models are picked up automatically.
|
| 498 |
try:
|
| 499 |
from dotenv import load_dotenv
|
|
|
|
| 508 |
model or os.environ.get("OPENAI_MODEL") or os.environ.get("OPENAI_MODE")
|
| 509 |
or os.environ.get("LLM_MODEL") or "gpt-4o"
|
| 510 |
)
|
| 511 |
+
# None -> the openai client uses the official OpenAI endpoint.
|
| 512 |
+
self.base_url = base_url or os.environ.get("OPENAI_BASE_URL") or os.environ.get("LLM_BASE_URL")
|
| 513 |
+
self._client = None
|
| 514 |
+
self._structured_outputs_mode = os.environ.get(
|
| 515 |
+
"LLM_STRUCTURED_OUTPUTS_ENABLED",
|
| 516 |
+
"auto",
|
| 517 |
+
).lower()
|
| 518 |
+
self._structured_outputs_available = None
|
| 519 |
|
| 520 |
def plan(self, user_command, scene_state, previous_failed_reasons=None):
|
| 521 |
if isinstance(scene_state, dict):
|
|
|
|
| 538 |
if previous_failed_reasons:
|
| 539 |
user_prompt += f"\n\nPREVIOUS FAILURE REASON:\n{previous_failed_reasons}\nPlease generate a new plan that avoids this failure."
|
| 540 |
|
| 541 |
+
use_structured_outputs = self._should_use_structured_outputs()
|
| 542 |
+
system_prompt = self.SYSTEM_PROMPT
|
| 543 |
+
if use_structured_outputs:
|
| 544 |
+
system_prompt += (
|
| 545 |
+
"\n\nFor this request, return one JSON object with exactly one "
|
| 546 |
+
"top-level key named `plan`; its value must be the plan array "
|
| 547 |
+
"described above."
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
# Build completion arguments
|
| 551 |
+
create_kwargs = {
|
| 552 |
+
"model": self.model,
|
| 553 |
+
"messages": [
|
| 554 |
+
{"role": "system", "content": system_prompt},
|
| 555 |
+
{"role": "user", "content": user_prompt},
|
| 556 |
+
],
|
| 557 |
+
"temperature": 0.0,
|
| 558 |
+
}
|
| 559 |
+
if use_structured_outputs:
|
| 560 |
+
create_kwargs["response_format"] = self._plan_response_format()
|
| 561 |
|
| 562 |
# Check if targeting NVIDIA integrate endpoint and using a DeepSeek model
|
| 563 |
if self.base_url and "integrate.api.nvidia.com" in self.base_url and "deepseek" in self.model:
|
|
|
|
| 570 |
max_retries = 5
|
| 571 |
backoff = 2.0
|
| 572 |
for attempt in range(max_retries):
|
| 573 |
+
try:
|
| 574 |
+
resp = client.chat.completions.create(**create_kwargs)
|
| 575 |
+
if use_structured_outputs:
|
| 576 |
+
self._structured_outputs_available = True
|
| 577 |
+
break
|
| 578 |
+
except Exception as e:
|
| 579 |
+
status_code = getattr(e, "status_code", None)
|
| 580 |
+
if (
|
| 581 |
+
use_structured_outputs
|
| 582 |
+
and status_code in (400, 404, 422)
|
| 583 |
+
):
|
| 584 |
+
logger.warning(
|
| 585 |
+
"[WARN ] Structured output is unavailable for the "
|
| 586 |
+
"selected model/provider; falling back to the legacy "
|
| 587 |
+
"plan-array parser."
|
| 588 |
+
)
|
| 589 |
+
self._structured_outputs_available = False
|
| 590 |
+
use_structured_outputs = False
|
| 591 |
+
create_kwargs.pop("response_format", None)
|
| 592 |
+
create_kwargs["messages"][0] = {
|
| 593 |
+
"role": "system",
|
| 594 |
+
"content": self.SYSTEM_PROMPT,
|
| 595 |
+
}
|
| 596 |
+
continue
|
| 597 |
+
|
| 598 |
+
is_rate_limit = False
|
| 599 |
if hasattr(e, "status_code") and e.status_code == 429:
|
| 600 |
is_rate_limit = True
|
| 601 |
elif "429" in str(e) or "RateLimit" in type(e).__name__:
|
|
|
|
| 616 |
if reasoning:
|
| 617 |
logger.info(f"\n--- [DEEPSEEK REASONING] ---\n{reasoning}\n---------------------------\n")
|
| 618 |
|
| 619 |
+
raw = resp.choices[0].message.content
|
| 620 |
+
logger.debug(f"LLM raw response: {raw}")
|
| 621 |
+
return self._parse(raw)
|
| 622 |
+
|
| 623 |
+
def resolve_goal(self, user_command, scene_state):
|
| 624 |
+
"""Run a fail-closed semantic gate before generating executable steps."""
|
| 625 |
+
if isinstance(scene_state, dict):
|
| 626 |
+
scene_state = json.dumps(scene_state, ensure_ascii=False)
|
| 627 |
+
if not self.api_key:
|
| 628 |
+
raise RuntimeError(
|
| 629 |
+
"RemoteLLMPlanner needs OPENAI_API_KEY (or LLM_API_KEY)."
|
| 630 |
+
)
|
| 631 |
+
client = self._get_client()
|
| 632 |
+
create_kwargs = {
|
| 633 |
+
"model": self.model,
|
| 634 |
+
"messages": [
|
| 635 |
+
{"role": "system", "content": self.GOAL_RESOLUTION_PROMPT},
|
| 636 |
+
{
|
| 637 |
+
"role": "user",
|
| 638 |
+
"content": (
|
| 639 |
+
f"SCENE:\n{scene_state}\n\n"
|
| 640 |
+
f"USER INSTRUCTION AND CONTEXT:\n{user_command}"
|
| 641 |
+
),
|
| 642 |
+
},
|
| 643 |
+
],
|
| 644 |
+
"temperature": 0.0,
|
| 645 |
+
}
|
| 646 |
+
use_structured = self._should_use_structured_outputs()
|
| 647 |
+
if use_structured:
|
| 648 |
+
create_kwargs["response_format"] = self._goal_response_format()
|
| 649 |
+
try:
|
| 650 |
+
response = client.chat.completions.create(**create_kwargs)
|
| 651 |
+
except Exception as exc:
|
| 652 |
+
if (
|
| 653 |
+
use_structured
|
| 654 |
+
and getattr(exc, "status_code", None) in (400, 404, 422)
|
| 655 |
+
):
|
| 656 |
+
create_kwargs.pop("response_format", None)
|
| 657 |
+
response = client.chat.completions.create(**create_kwargs)
|
| 658 |
+
else:
|
| 659 |
+
raise
|
| 660 |
+
|
| 661 |
+
message = response.choices[0].message
|
| 662 |
+
reasoning = (
|
| 663 |
+
getattr(message, "reasoning", None)
|
| 664 |
+
or getattr(message, "reasoning_content", None)
|
| 665 |
+
)
|
| 666 |
+
if reasoning:
|
| 667 |
+
logger.info(
|
| 668 |
+
"\n--- [GOAL RESOLUTION REASONING] ---\n"
|
| 669 |
+
f"{reasoning}\n-----------------------------------\n"
|
| 670 |
+
)
|
| 671 |
+
result = self._parse_goal_resolution(message.content)
|
| 672 |
+
if result is not None:
|
| 673 |
+
return result
|
| 674 |
+
return {
|
| 675 |
+
"status": "clarify",
|
| 676 |
+
"canonical_instruction": "",
|
| 677 |
+
"message": (
|
| 678 |
+
"Tôi chưa xác định chắc chắn mục tiêu. "
|
| 679 |
+
"Bạn có thể nói rõ vật cần thao tác và vị trí đích không?"
|
| 680 |
+
),
|
| 681 |
+
"missing_fields": ["details"],
|
| 682 |
+
"partial_intent": {},
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
def _get_client(self):
|
| 686 |
+
if self._client is not None:
|
| 687 |
+
return self._client
|
| 688 |
+
try:
|
| 689 |
+
from openai import OpenAI
|
| 690 |
+
except ImportError as exc: # pragma: no cover
|
| 691 |
+
raise RuntimeError(
|
| 692 |
+
"RemoteLLMPlanner needs the 'openai' package (pip install openai)."
|
| 693 |
+
) from exc
|
| 694 |
+
kwargs = {"api_key": self.api_key}
|
| 695 |
+
if self.base_url:
|
| 696 |
+
kwargs["base_url"] = self.base_url
|
| 697 |
+
self._client = OpenAI(**kwargs)
|
| 698 |
+
return self._client
|
| 699 |
+
|
| 700 |
+
@staticmethod
|
| 701 |
+
def _parse_goal_resolution(text):
|
| 702 |
+
if not text:
|
| 703 |
+
return None
|
| 704 |
+
try:
|
| 705 |
+
data = json.loads(text)
|
| 706 |
+
except (TypeError, ValueError, json.JSONDecodeError):
|
| 707 |
+
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 708 |
+
if not match:
|
| 709 |
+
return None
|
| 710 |
+
try:
|
| 711 |
+
data = json.loads(match.group(0))
|
| 712 |
+
except (TypeError, ValueError, json.JSONDecodeError):
|
| 713 |
+
return None
|
| 714 |
+
if not isinstance(data, dict):
|
| 715 |
+
return None
|
| 716 |
+
status = data.get("status")
|
| 717 |
+
canonical = data.get("canonical_instruction", "")
|
| 718 |
+
message = data.get("message", "")
|
| 719 |
+
missing = data.get("missing_fields", [])
|
| 720 |
+
partial = data.get("partial_intent", {})
|
| 721 |
+
if status not in {"ready", "clarify", "reject"}:
|
| 722 |
+
return None
|
| 723 |
+
if not isinstance(canonical, str) or not isinstance(message, str):
|
| 724 |
+
return None
|
| 725 |
+
if not isinstance(missing, list) or not isinstance(partial, dict):
|
| 726 |
+
return None
|
| 727 |
+
if status == "ready" and not canonical.strip():
|
| 728 |
+
return None
|
| 729 |
+
if status != "ready" and not message.strip():
|
| 730 |
+
return None
|
| 731 |
+
return {
|
| 732 |
+
"status": status,
|
| 733 |
+
"canonical_instruction": canonical.strip(),
|
| 734 |
+
"message": message.strip(),
|
| 735 |
+
"missing_fields": [
|
| 736 |
+
field for field in missing if isinstance(field, str) and field
|
| 737 |
+
],
|
| 738 |
+
"partial_intent": partial,
|
| 739 |
+
}
|
| 740 |
+
|
| 741 |
+
@staticmethod
|
| 742 |
+
def _parse(text):
|
| 743 |
"""Extract the JSON array or object from a model response.
|
| 744 |
|
| 745 |
Some providers occasionally return an empty body (``content=None``),
|
| 746 |
e.g. on a transient hiccup or a reasoning-only turn. Treat that as "no
|
| 747 |
actionable plan" (``[]``) instead of crashing on ``re.search(None)``.
|
| 748 |
+
"""
|
| 749 |
+
if not text:
|
| 750 |
+
return []
|
| 751 |
+
try:
|
| 752 |
+
parsed = json.loads(text)
|
| 753 |
+
if isinstance(parsed, list):
|
| 754 |
+
return parsed
|
| 755 |
+
if isinstance(parsed, dict):
|
| 756 |
+
if isinstance(parsed.get("plan"), list):
|
| 757 |
+
return parsed["plan"]
|
| 758 |
+
return [parsed]
|
| 759 |
+
except (TypeError, ValueError, json.JSONDecodeError):
|
| 760 |
+
pass
|
| 761 |
+
|
| 762 |
+
array_match = re.search(r"\[.*\]", text, re.DOTALL)
|
| 763 |
if array_match:
|
| 764 |
try:
|
| 765 |
return json.loads(array_match.group(0))
|
|
|
|
| 773 |
return [obj]
|
| 774 |
except Exception:
|
| 775 |
pass
|
| 776 |
+
return []
|
| 777 |
+
|
| 778 |
+
def _should_use_structured_outputs(self):
|
| 779 |
+
if self._structured_outputs_mode in {"0", "false", "no", "off"}:
|
| 780 |
+
return False
|
| 781 |
+
if self._structured_outputs_available is False:
|
| 782 |
+
return False
|
| 783 |
+
if self._structured_outputs_mode in {"1", "true", "yes", "on"}:
|
| 784 |
+
return True
|
| 785 |
+
return bool(self.base_url and "openrouter.ai" in self.base_url)
|
| 786 |
+
|
| 787 |
+
@staticmethod
|
| 788 |
+
def _plan_response_format():
|
| 789 |
+
return {
|
| 790 |
+
"type": "json_schema",
|
| 791 |
+
"json_schema": {
|
| 792 |
+
"name": "robot_plan",
|
| 793 |
+
"strict": True,
|
| 794 |
+
"schema": {
|
| 795 |
+
"type": "object",
|
| 796 |
+
"properties": {
|
| 797 |
+
"plan": {
|
| 798 |
+
"type": "array",
|
| 799 |
+
"items": {
|
| 800 |
+
"type": "object",
|
| 801 |
+
"properties": {
|
| 802 |
+
"function": {
|
| 803 |
+
"type": "string",
|
| 804 |
+
"enum": list(ACTIONS),
|
| 805 |
+
},
|
| 806 |
+
"args": {
|
| 807 |
+
"type": "object",
|
| 808 |
+
"additionalProperties": True,
|
| 809 |
+
},
|
| 810 |
+
},
|
| 811 |
+
"required": ["function", "args"],
|
| 812 |
+
"additionalProperties": False,
|
| 813 |
+
},
|
| 814 |
+
}
|
| 815 |
+
},
|
| 816 |
+
"required": ["plan"],
|
| 817 |
+
"additionalProperties": False,
|
| 818 |
+
},
|
| 819 |
+
},
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
@staticmethod
|
| 823 |
+
def _goal_response_format():
|
| 824 |
+
return {
|
| 825 |
+
"type": "json_schema",
|
| 826 |
+
"json_schema": {
|
| 827 |
+
"name": "robot_goal_resolution",
|
| 828 |
+
"strict": True,
|
| 829 |
+
"schema": {
|
| 830 |
+
"type": "object",
|
| 831 |
+
"properties": {
|
| 832 |
+
"status": {
|
| 833 |
+
"type": "string",
|
| 834 |
+
"enum": ["ready", "clarify", "reject"],
|
| 835 |
+
},
|
| 836 |
+
"canonical_instruction": {"type": "string"},
|
| 837 |
+
"message": {"type": "string"},
|
| 838 |
+
"missing_fields": {
|
| 839 |
+
"type": "array",
|
| 840 |
+
"items": {
|
| 841 |
+
"type": "string",
|
| 842 |
+
"enum": [
|
| 843 |
+
"object_id",
|
| 844 |
+
"destination",
|
| 845 |
+
"relation",
|
| 846 |
+
"relative_to",
|
| 847 |
+
"details",
|
| 848 |
+
],
|
| 849 |
+
},
|
| 850 |
+
},
|
| 851 |
+
"partial_intent": {
|
| 852 |
+
"type": "object",
|
| 853 |
+
"additionalProperties": True,
|
| 854 |
+
},
|
| 855 |
+
},
|
| 856 |
+
"required": [
|
| 857 |
+
"status",
|
| 858 |
+
"canonical_instruction",
|
| 859 |
+
"message",
|
| 860 |
+
"missing_fields",
|
| 861 |
+
"partial_intent",
|
| 862 |
+
],
|
| 863 |
+
"additionalProperties": False,
|
| 864 |
+
},
|
| 865 |
+
},
|
| 866 |
+
}
|
| 867 |
+
|
| 868 |
+
def check_goal(self, user_command, scene_state):
|
| 869 |
if isinstance(scene_state, dict):
|
| 870 |
scene_state = json.dumps(scene_state)
|
| 871 |
if not self.api_key:
|
|
|
|
| 909 |
return False, str(e)
|
| 910 |
|
| 911 |
|
| 912 |
+
class LLMAgent:
|
| 913 |
+
"""Wraps a planner and validates its output against the action schema."""
|
| 914 |
+
|
| 915 |
+
def __init__(
|
| 916 |
+
self,
|
| 917 |
+
planner=None,
|
| 918 |
+
conversation_manager=None,
|
| 919 |
+
conversation_memory_enabled=None,
|
| 920 |
+
):
|
| 921 |
+
self.planner = planner or RuleBasedPlanner()
|
| 922 |
+
self.conversation_manager = (
|
| 923 |
+
conversation_manager or ConversationManager()
|
| 924 |
+
)
|
| 925 |
+
if conversation_memory_enabled is None:
|
| 926 |
+
raw_flag = os.environ.get("CONVERSATION_MEMORY_ENABLED", "true")
|
| 927 |
+
conversation_memory_enabled = raw_flag.lower() not in {
|
| 928 |
+
"0",
|
| 929 |
+
"false",
|
| 930 |
+
"no",
|
| 931 |
+
"off",
|
| 932 |
+
}
|
| 933 |
+
self.conversation_memory_enabled = bool(conversation_memory_enabled)
|
| 934 |
+
self.last_outcome = None
|
| 935 |
|
| 936 |
def build_prompt(self, user_command, scene_state_text):
|
| 937 |
"""The exact text a real LLM would be shown (useful for logging)."""
|
|
|
|
| 940 |
f"SCENE STATE:\n{scene_state_text}\n\n"
|
| 941 |
f"USER INSTRUCTION:\n{user_command}\n"
|
| 942 |
)
|
| 943 |
+
def plan(
|
| 944 |
+
self,
|
| 945 |
+
user_command,
|
| 946 |
+
scene_state,
|
| 947 |
+
previous_failed_reasons=None,
|
| 948 |
+
resolve_goal=True,
|
| 949 |
+
):
|
| 950 |
+
outcome = self.plan_with_context(
|
| 951 |
+
user_command,
|
| 952 |
+
scene_state,
|
| 953 |
+
previous_failed_reasons=previous_failed_reasons,
|
| 954 |
+
resolve_goal=resolve_goal,
|
| 955 |
+
)
|
| 956 |
+
return [dict(step) for step in outcome.steps]
|
| 957 |
+
|
| 958 |
+
def plan_with_context(
|
| 959 |
+
self,
|
| 960 |
+
user_command,
|
| 961 |
+
scene_state,
|
| 962 |
+
previous_failed_reasons=None,
|
| 963 |
+
resolve_goal=True,
|
| 964 |
+
):
|
| 965 |
+
"""Plan once and retain an immutable goal for downstream monitoring."""
|
| 966 |
+
if (
|
| 967 |
+
self.conversation_memory_enabled
|
| 968 |
+
and self.conversation_manager.cancel_if_requested(user_command)
|
| 969 |
+
):
|
| 970 |
+
steps = [
|
| 971 |
+
{
|
| 972 |
+
"function": "reject",
|
| 973 |
+
"args": {
|
| 974 |
+
"message": "Đã hủy yêu cầu đang chờ.",
|
| 975 |
+
"reason": "conversation_cancelled",
|
| 976 |
+
},
|
| 977 |
+
}
|
| 978 |
+
]
|
| 979 |
+
outcome = PlanningOutcome(
|
| 980 |
+
steps=tuple(steps),
|
| 981 |
+
response_type="reject",
|
| 982 |
+
effective_command=user_command,
|
| 983 |
+
)
|
| 984 |
+
self.last_outcome = outcome
|
| 985 |
+
return outcome
|
| 986 |
+
|
| 987 |
+
effective_command = user_command
|
| 988 |
+
pending_before = None
|
| 989 |
+
if self.conversation_memory_enabled:
|
| 990 |
+
pending_before = self.conversation_manager.pending
|
| 991 |
+
effective_command = self.conversation_manager.contextualize(
|
| 992 |
+
user_command,
|
| 993 |
+
scene_state=scene_state,
|
| 994 |
+
)
|
| 995 |
+
|
| 996 |
+
planning_instruction = effective_command
|
| 997 |
+
goal_resolution_enabled = os.environ.get(
|
| 998 |
+
"LLM_GOAL_RESOLUTION_ENABLED", "true"
|
| 999 |
+
).lower() not in {"0", "false", "no", "off"}
|
| 1000 |
+
if (
|
| 1001 |
+
resolve_goal
|
| 1002 |
+
and goal_resolution_enabled
|
| 1003 |
+
and hasattr(self.planner, "resolve_goal")
|
| 1004 |
+
):
|
| 1005 |
+
resolution = self.planner.resolve_goal(
|
| 1006 |
+
effective_command,
|
| 1007 |
+
scene_state,
|
| 1008 |
+
)
|
| 1009 |
+
status = resolution.get("status")
|
| 1010 |
+
if status in {"clarify", "reject"}:
|
| 1011 |
+
steps = [
|
| 1012 |
+
{
|
| 1013 |
+
"function": status,
|
| 1014 |
+
"args": {
|
| 1015 |
+
"message": resolution.get("message", ""),
|
| 1016 |
+
"missing_fields": resolution.get(
|
| 1017 |
+
"missing_fields", []
|
| 1018 |
+
),
|
| 1019 |
+
"partial_intent": resolution.get(
|
| 1020 |
+
"partial_intent", {}
|
| 1021 |
+
),
|
| 1022 |
+
"reason": "goal_resolution_gate",
|
| 1023 |
+
},
|
| 1024 |
+
}
|
| 1025 |
+
]
|
| 1026 |
+
if self.conversation_memory_enabled:
|
| 1027 |
+
self.conversation_manager.observe(
|
| 1028 |
+
user_command,
|
| 1029 |
+
steps,
|
| 1030 |
+
scene_state=scene_state,
|
| 1031 |
+
)
|
| 1032 |
+
outcome = PlanningOutcome(
|
| 1033 |
+
steps=tuple(steps),
|
| 1034 |
+
response_type=status,
|
| 1035 |
+
effective_command=effective_command,
|
| 1036 |
+
)
|
| 1037 |
+
self.last_outcome = outcome
|
| 1038 |
+
return outcome
|
| 1039 |
+
planning_instruction = resolution["canonical_instruction"]
|
| 1040 |
+
|
| 1041 |
+
raw_plan = self.planner.plan(
|
| 1042 |
+
planning_instruction,
|
| 1043 |
+
scene_state,
|
| 1044 |
+
previous_failed_reasons=previous_failed_reasons,
|
| 1045 |
+
)
|
| 1046 |
+
if not raw_plan or not all(self._valid(step) for step in raw_plan):
|
| 1047 |
+
semantic_plan = [
|
| 1048 |
+
{
|
| 1049 |
+
"function": "clarify",
|
| 1050 |
+
"args": {
|
| 1051 |
+
"message": (
|
| 1052 |
+
"Tôi chưa có đủ thông tin để tạo kế hoạch an toàn. "
|
| 1053 |
+
"Bạn muốn thao tác với vật nào và đặt nó ở đâu?"
|
| 1054 |
+
),
|
| 1055 |
+
"missing_fields": ["details"],
|
| 1056 |
+
"partial_intent": {},
|
| 1057 |
+
"reason": "invalid_or_empty_plan",
|
| 1058 |
+
},
|
| 1059 |
+
}
|
| 1060 |
+
]
|
| 1061 |
+
else:
|
| 1062 |
+
semantic_plan = list(raw_plan)
|
| 1063 |
+
semantic_plan = self._align_with_pending_intent(
|
| 1064 |
+
semantic_plan,
|
| 1065 |
+
pending_before,
|
| 1066 |
+
)
|
| 1067 |
+
response_type = (
|
| 1068 |
+
semantic_plan[0].get("function")
|
| 1069 |
+
if semantic_plan
|
| 1070 |
+
and semantic_plan[0].get("function") in ("clarify", "reject")
|
| 1071 |
+
else "ready"
|
| 1072 |
+
)
|
| 1073 |
+
resolved_goal = None
|
| 1074 |
+
if response_type == "ready":
|
| 1075 |
+
resolved_goal = self._compile_goal(
|
| 1076 |
+
user_command,
|
| 1077 |
+
planning_instruction,
|
| 1078 |
+
semantic_plan,
|
| 1079 |
+
scene_state,
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
# Enforce obstacle clearing on EVERY planner's output, deterministically
|
| 1083 |
# from scene geometry — so a model that rationalises away clearing (as
|
| 1084 |
# the LLM did when it picked a banana blocked by a tall chips can) still
|
| 1085 |
# produces a collision-free plan.
|
| 1086 |
+
plan = self._inject_obstacle_clearing(semantic_plan, scene_state)
|
| 1087 |
try:
|
| 1088 |
from .plan_verifier import PlanVerifier
|
| 1089 |
warnings = PlanVerifier.check(plan, scene_state)
|
|
|
|
| 1091 |
logger.warning(f"[PLAN_WARN] {w}")
|
| 1092 |
except ImportError:
|
| 1093 |
pass # plan_verifier not yet available
|
| 1094 |
+
valid_plan = [step for step in plan if self._valid(step)]
|
| 1095 |
+
if self.conversation_memory_enabled:
|
| 1096 |
+
self.conversation_manager.observe(
|
| 1097 |
+
user_command,
|
| 1098 |
+
valid_plan,
|
| 1099 |
+
scene_state=scene_state,
|
| 1100 |
+
)
|
| 1101 |
+
outcome = PlanningOutcome(
|
| 1102 |
+
steps=tuple(valid_plan),
|
| 1103 |
+
response_type=response_type,
|
| 1104 |
+
effective_command=effective_command,
|
| 1105 |
+
resolved_goal=resolved_goal,
|
| 1106 |
+
)
|
| 1107 |
+
self.last_outcome = outcome
|
| 1108 |
+
return outcome
|
| 1109 |
+
|
| 1110 |
+
@staticmethod
|
| 1111 |
+
def _align_with_pending_intent(plan, pending):
|
| 1112 |
+
"""Prevent a follow-up answer from silently expanding the original task."""
|
| 1113 |
+
if pending is None or not plan:
|
| 1114 |
+
return plan
|
| 1115 |
+
intent = dict(pending.partial_intent or {})
|
| 1116 |
+
if intent.get("action") != "pick_up" or intent.get("destination"):
|
| 1117 |
+
return plan
|
| 1118 |
+
|
| 1119 |
+
requested_object = intent.get("object_id")
|
| 1120 |
+
for step in plan:
|
| 1121 |
+
if step.get("function") != "pick_up":
|
| 1122 |
+
continue
|
| 1123 |
+
object_id = step.get("args", {}).get("object_id")
|
| 1124 |
+
if requested_object is None or object_id == requested_object:
|
| 1125 |
+
# The unresolved field selected the object only. A destination
|
| 1126 |
+
# invented from wording such as "thế thì ... đi" must not turn
|
| 1127 |
+
# the original pick-up request into a pick-and-place task.
|
| 1128 |
+
return [{"function": "pick_up", "args": {"object_id": object_id}}]
|
| 1129 |
+
return plan
|
| 1130 |
+
|
| 1131 |
+
@staticmethod
|
| 1132 |
+
def _compile_goal(user_command, effective_command, plan, scene_state):
|
| 1133 |
+
"""Compile user-visible plan effects, excluding injected blocker moves."""
|
| 1134 |
+
try:
|
| 1135 |
+
state = json.loads(scene_state) if isinstance(scene_state, str) else scene_state
|
| 1136 |
+
except (TypeError, ValueError, json.JSONDecodeError):
|
| 1137 |
+
state = {}
|
| 1138 |
+
carried = state.get("carried_object") if isinstance(state, dict) else None
|
| 1139 |
+
held = carried
|
| 1140 |
+
destination = None
|
| 1141 |
+
predicates = []
|
| 1142 |
+
|
| 1143 |
+
for step in plan:
|
| 1144 |
+
function = step.get("function")
|
| 1145 |
+
args = step.get("args", {})
|
| 1146 |
+
if function == "pick_up":
|
| 1147 |
+
held = args.get("object_id")
|
| 1148 |
+
destination = None
|
| 1149 |
+
elif function == "move_to":
|
| 1150 |
+
destination = args
|
| 1151 |
+
elif function == "place_down" and held and destination:
|
| 1152 |
+
relation = destination.get("relation")
|
| 1153 |
+
if relation and destination.get("relative_to"):
|
| 1154 |
+
predicates.append(
|
| 1155 |
+
GoalPredicate(
|
| 1156 |
+
type="relation_is",
|
| 1157 |
+
object_id=held,
|
| 1158 |
+
location_id=destination.get("location_id"),
|
| 1159 |
+
relation=relation,
|
| 1160 |
+
relative_to=destination.get("relative_to"),
|
| 1161 |
+
)
|
| 1162 |
+
)
|
| 1163 |
+
else:
|
| 1164 |
+
predicates.append(
|
| 1165 |
+
GoalPredicate(
|
| 1166 |
+
type="location_is",
|
| 1167 |
+
object_id=held,
|
| 1168 |
+
location_id=destination.get("location_id"),
|
| 1169 |
+
)
|
| 1170 |
+
)
|
| 1171 |
+
held = None
|
| 1172 |
+
destination = None
|
| 1173 |
+
|
| 1174 |
+
if held:
|
| 1175 |
+
predicates.append(
|
| 1176 |
+
GoalPredicate(type="carried_object_is", object_id=held)
|
| 1177 |
+
)
|
| 1178 |
+
if not predicates:
|
| 1179 |
+
return None
|
| 1180 |
+
|
| 1181 |
+
descriptions = []
|
| 1182 |
+
for predicate in predicates:
|
| 1183 |
+
if predicate.type == "carried_object_is":
|
| 1184 |
+
descriptions.append(f"gắp {predicate.object_id} lên")
|
| 1185 |
+
elif predicate.type == "location_is":
|
| 1186 |
+
descriptions.append(
|
| 1187 |
+
f"đặt {predicate.object_id} vào {predicate.location_id}"
|
| 1188 |
+
)
|
| 1189 |
+
else:
|
| 1190 |
+
descriptions.append(
|
| 1191 |
+
f"đặt {predicate.object_id} {predicate.relation} "
|
| 1192 |
+
f"{predicate.relative_to}"
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
return ResolvedGoal(
|
| 1196 |
+
task_id=uuid.uuid4().hex,
|
| 1197 |
+
canonical_instruction="; ".join(descriptions),
|
| 1198 |
+
predicates=tuple(predicates),
|
| 1199 |
+
source_command=user_command,
|
| 1200 |
+
effective_command=effective_command,
|
| 1201 |
+
initial_scene_revision=ConversationManager.scene_revision(scene_state),
|
| 1202 |
+
)
|
| 1203 |
+
|
| 1204 |
+
def reset_conversation(self):
|
| 1205 |
+
"""Clear clarification context without changing planner/executor state."""
|
| 1206 |
+
self.conversation_manager.clear()
|
| 1207 |
|
| 1208 |
def check_goal(self, user_command, scene_state):
|
| 1209 |
if hasattr(self.planner, "check_goal"):
|
|
|
|
| 1350 |
held = None
|
| 1351 |
return out
|
| 1352 |
|
| 1353 |
+
@staticmethod
|
| 1354 |
+
def _valid(step):
|
| 1355 |
+
if not isinstance(step, dict) or step.get("function") not in ACTIONS:
|
| 1356 |
+
return False
|
| 1357 |
+
args = step.get("args")
|
| 1358 |
+
if not isinstance(args, dict):
|
| 1359 |
+
return False
|
| 1360 |
+
function = step["function"]
|
| 1361 |
+
if function == "pick_up":
|
| 1362 |
+
return isinstance(args.get("object_id"), str) and bool(
|
| 1363 |
+
args["object_id"].strip()
|
| 1364 |
+
)
|
| 1365 |
+
if function == "move_to":
|
| 1366 |
+
return args.get("location_id") in {"table", "tray", "buffer"}
|
| 1367 |
+
if function in {"clarify", "reject"}:
|
| 1368 |
+
return isinstance(args.get("message"), str) and bool(
|
| 1369 |
+
args["message"].strip()
|
| 1370 |
+
)
|
| 1371 |
+
return function == "place_down"
|
llm_panda/scene_manager.py
CHANGED
|
@@ -62,9 +62,56 @@ class SceneManager:
|
|
| 62 |
"""(position, orientation_quaternion) of a body's base."""
|
| 63 |
return pb.getBasePositionAndOrientation(object_id)
|
| 64 |
|
| 65 |
-
def get_aabb(self, object_id):
|
| 66 |
-
"""Axis-aligned bounding box (aabb_min, aabb_max) in world coords."""
|
| 67 |
-
return pb.getAABB(object_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
# ------------------------------------------------------------------ #
|
| 70 |
# Symbolic localisation
|
|
@@ -509,23 +556,10 @@ class SceneManager:
|
|
| 509 |
except Exception:
|
| 510 |
pass
|
| 511 |
|
| 512 |
-
def is_on_top(name_a, name_b):
|
| 513 |
-
if name_a not in aabbs or name_b not in aabbs:
|
| 514 |
-
return False
|
| 515 |
-
|
| 516 |
-
min_b, max_b = aabbs[name_b]
|
| 517 |
-
|
| 518 |
-
# Check XY overlap
|
| 519 |
-
overlap_x = (min_a[0] <= max_b[0]) and (max_a[0] >= min_b[0])
|
| 520 |
-
overlap_y = (min_a[1] <= max_b[1]) and (max_a[1] >= min_b[1])
|
| 521 |
-
|
| 522 |
-
if overlap_x and overlap_y:
|
| 523 |
-
# Bottom of A is close to or above top of B
|
| 524 |
-
is_above = min_a[2] >= max_b[2] - 0.02
|
| 525 |
-
is_close = min_a[2] <= max_b[2] + 0.05
|
| 526 |
-
if is_above and is_close:
|
| 527 |
-
return True
|
| 528 |
-
return False
|
| 529 |
|
| 530 |
# Compute distances and relations for all objects
|
| 531 |
for entry_a in objects:
|
|
|
|
| 62 |
"""(position, orientation_quaternion) of a body's base."""
|
| 63 |
return pb.getBasePositionAndOrientation(object_id)
|
| 64 |
|
| 65 |
+
def get_aabb(self, object_id):
|
| 66 |
+
"""Axis-aligned bounding box (aabb_min, aabb_max) in world coords."""
|
| 67 |
+
return pb.getAABB(object_id)
|
| 68 |
+
|
| 69 |
+
@staticmethod
|
| 70 |
+
def _aabb_is_on_top(aabb_a, aabb_b):
|
| 71 |
+
"""Robustly determine whether A is physically supported by B.
|
| 72 |
+
|
| 73 |
+
PyBullet contacts allow a small amount of interpenetration and rounded
|
| 74 |
+
objects may settle a few centimetres into a support AABB. Requiring the
|
| 75 |
+
bottom of A to remain within 2 cm of the top of B produced false
|
| 76 |
+
negatives for visibly valid stacks.
|
| 77 |
+
"""
|
| 78 |
+
min_a, max_a = aabb_a
|
| 79 |
+
min_b, max_b = aabb_b
|
| 80 |
+
overlap_x = max(
|
| 81 |
+
0.0, min(max_a[0], max_b[0]) - max(min_a[0], min_b[0])
|
| 82 |
+
)
|
| 83 |
+
overlap_y = max(
|
| 84 |
+
0.0, min(max_a[1], max_b[1]) - max(min_a[1], min_b[1])
|
| 85 |
+
)
|
| 86 |
+
if overlap_x <= 0.0 or overlap_y <= 0.0:
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
area_a = max(1e-9, (max_a[0] - min_a[0]) * (max_a[1] - min_a[1]))
|
| 90 |
+
area_b = max(1e-9, (max_b[0] - min_b[0]) * (max_b[1] - min_b[1]))
|
| 91 |
+
overlap_ratio = (overlap_x * overlap_y) / min(area_a, area_b)
|
| 92 |
+
center_a_z = 0.5 * (min_a[2] + max_a[2])
|
| 93 |
+
center_b_z = 0.5 * (min_b[2] + max_b[2])
|
| 94 |
+
vertical_gap = min_a[2] - max_b[2]
|
| 95 |
+
|
| 96 |
+
return (
|
| 97 |
+
overlap_ratio >= 0.15
|
| 98 |
+
and center_a_z > center_b_z
|
| 99 |
+
and -0.06 <= vertical_gap <= 0.08
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def is_on_top(self, name_a, name_b):
|
| 103 |
+
"""Check a live named-object stack directly from current AABBs."""
|
| 104 |
+
object_a = self.name_to_id(name_a)
|
| 105 |
+
object_b = self.name_to_id(name_b)
|
| 106 |
+
if object_a is None or object_b is None:
|
| 107 |
+
return False
|
| 108 |
+
try:
|
| 109 |
+
return self._aabb_is_on_top(
|
| 110 |
+
self.get_aabb(object_a),
|
| 111 |
+
self.get_aabb(object_b),
|
| 112 |
+
)
|
| 113 |
+
except Exception:
|
| 114 |
+
return False
|
| 115 |
|
| 116 |
# ------------------------------------------------------------------ #
|
| 117 |
# Symbolic localisation
|
|
|
|
| 556 |
except Exception:
|
| 557 |
pass
|
| 558 |
|
| 559 |
+
def is_on_top(name_a, name_b):
|
| 560 |
+
if name_a not in aabbs or name_b not in aabbs:
|
| 561 |
+
return False
|
| 562 |
+
return self._aabb_is_on_top(aabbs[name_a], aabbs[name_b])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
# Compute distances and relations for all objects
|
| 565 |
for entry_a in objects:
|
main.py
CHANGED
|
@@ -63,6 +63,9 @@ class PandaApp:
|
|
| 63 |
|
| 64 |
def reset_objects(self, seed=None):
|
| 65 |
"""Remove current objects and re-spawn them (optionally re-randomised)."""
|
|
|
|
|
|
|
|
|
|
| 66 |
for oid in self.scene.object_ids:
|
| 67 |
pb.removeBody(oid)
|
| 68 |
|
|
|
|
| 63 |
|
| 64 |
def reset_objects(self, seed=None):
|
| 65 |
"""Remove current objects and re-spawn them (optionally re-randomised)."""
|
| 66 |
+
if hasattr(self.pipeline.agent, "reset_conversation"):
|
| 67 |
+
self.pipeline.agent.reset_conversation()
|
| 68 |
+
|
| 69 |
for oid in self.scene.object_ids:
|
| 70 |
pb.removeBody(oid)
|
| 71 |
|
tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc
CHANGED
|
Binary files a/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc and b/tests/__pycache__/test_occupancy.cpython-310-pytest-8.3.5.pyc differ
|
|
|
tests/test_conversation_memory.py
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Characterization and unit tests for session-scoped clarification memory."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from types import SimpleNamespace
|
| 5 |
+
|
| 6 |
+
from llm_panda.conversation import ConversationManager, GoalPredicate, ResolvedGoal
|
| 7 |
+
from llm_panda.execution.monitor import ExecutionMonitor
|
| 8 |
+
from llm_panda.execution.pipeline import ExecutionPipeline
|
| 9 |
+
from llm_panda.llm_agent import LLMAgent, RemoteLLMPlanner, RuleBasedPlanner
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _ScriptedPlanner:
|
| 13 |
+
def __init__(self, responses):
|
| 14 |
+
self.responses = list(responses)
|
| 15 |
+
self.commands = []
|
| 16 |
+
|
| 17 |
+
def plan(self, user_command, scene_state, previous_failed_reasons=None):
|
| 18 |
+
self.commands.append(user_command)
|
| 19 |
+
return self.responses.pop(0)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class _GoalAwarePlanner:
|
| 23 |
+
def __init__(self, resolution, plan=None):
|
| 24 |
+
self.resolution = resolution
|
| 25 |
+
self.plan_response = plan or []
|
| 26 |
+
self.resolve_commands = []
|
| 27 |
+
self.plan_commands = []
|
| 28 |
+
|
| 29 |
+
def resolve_goal(self, user_command, scene_state):
|
| 30 |
+
self.resolve_commands.append(user_command)
|
| 31 |
+
return dict(self.resolution)
|
| 32 |
+
|
| 33 |
+
def plan(self, user_command, scene_state, previous_failed_reasons=None):
|
| 34 |
+
self.plan_commands.append(user_command)
|
| 35 |
+
return list(self.plan_response)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _scene(*objects, carried_object=None):
|
| 39 |
+
return json.dumps(
|
| 40 |
+
{
|
| 41 |
+
"objects": [
|
| 42 |
+
{
|
| 43 |
+
"name": name,
|
| 44 |
+
"class": object_class,
|
| 45 |
+
"location": location,
|
| 46 |
+
"reachable": True,
|
| 47 |
+
"blocking_objects": [],
|
| 48 |
+
}
|
| 49 |
+
for name, object_class, location in objects
|
| 50 |
+
],
|
| 51 |
+
"carried_object": carried_object,
|
| 52 |
+
}
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_one_shot_command_is_not_rewritten():
|
| 57 |
+
memory = ConversationManager(session_id="one-shot")
|
| 58 |
+
command = "gắp quả lê vào khay"
|
| 59 |
+
|
| 60 |
+
assert memory.contextualize(command) == command
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_agent_keeps_one_shot_planner_input_unchanged():
|
| 64 |
+
ready = [{"function": "pick_up", "args": {"object_id": "pear"}}]
|
| 65 |
+
planner = _ScriptedPlanner([ready])
|
| 66 |
+
agent = LLMAgent(
|
| 67 |
+
planner=planner,
|
| 68 |
+
conversation_manager=ConversationManager(session_id="unchanged"),
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
agent.plan(
|
| 72 |
+
"gắp quả lê",
|
| 73 |
+
_scene(("pear", "pear", "table")),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
assert planner.commands == ["gắp quả lê"]
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_feature_flag_can_restore_stateless_behavior():
|
| 80 |
+
clarify = [
|
| 81 |
+
{
|
| 82 |
+
"function": "clarify",
|
| 83 |
+
"args": {"message": "Bạn muốn đặt vật nào vào khay?"},
|
| 84 |
+
}
|
| 85 |
+
]
|
| 86 |
+
planner = _ScriptedPlanner([clarify, clarify])
|
| 87 |
+
memory = ConversationManager(session_id="disabled")
|
| 88 |
+
agent = LLMAgent(
|
| 89 |
+
planner=planner,
|
| 90 |
+
conversation_manager=memory,
|
| 91 |
+
conversation_memory_enabled=False,
|
| 92 |
+
)
|
| 93 |
+
scene = _scene(("pear", "pear", "table"))
|
| 94 |
+
|
| 95 |
+
agent.plan("đặt vào khay", scene)
|
| 96 |
+
agent.plan("quả lê", scene)
|
| 97 |
+
|
| 98 |
+
assert planner.commands == ["đặt vào khay", "quả lê"]
|
| 99 |
+
assert memory.pending is None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_follow_up_completes_rule_based_plan_without_extra_api_call():
|
| 103 |
+
memory = ConversationManager(session_id="follow-up")
|
| 104 |
+
agent = LLMAgent(
|
| 105 |
+
planner=RuleBasedPlanner(),
|
| 106 |
+
conversation_manager=memory,
|
| 107 |
+
)
|
| 108 |
+
scene = _scene(("pear", "pear", "table"))
|
| 109 |
+
|
| 110 |
+
first = agent.plan("đặt vào khay", scene)
|
| 111 |
+
assert first[0]["function"] == "clarify"
|
| 112 |
+
assert memory.pending is not None
|
| 113 |
+
|
| 114 |
+
second = agent.plan("quả lê", scene)
|
| 115 |
+
assert second == [
|
| 116 |
+
{"function": "pick_up", "args": {"object_id": "pear"}},
|
| 117 |
+
{"function": "move_to", "args": {"location_id": "tray"}},
|
| 118 |
+
{"function": "place_down", "args": {}},
|
| 119 |
+
]
|
| 120 |
+
assert memory.pending is None
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_rule_based_move_request_tracks_missing_destination():
|
| 124 |
+
memory = ConversationManager(session_id="missing-destination")
|
| 125 |
+
agent = LLMAgent(
|
| 126 |
+
planner=RuleBasedPlanner(),
|
| 127 |
+
conversation_manager=memory,
|
| 128 |
+
)
|
| 129 |
+
scene = _scene(("banana", "banana", "table"))
|
| 130 |
+
|
| 131 |
+
first = agent.plan("di chuyển quả chuối", scene)
|
| 132 |
+
|
| 133 |
+
assert first[0]["function"] == "clarify"
|
| 134 |
+
assert first[0]["args"]["missing_fields"] == ["destination"]
|
| 135 |
+
assert first[0]["args"]["partial_intent"]["object_id"] == "banana"
|
| 136 |
+
assert memory.pending.missing_fields == ("destination",)
|
| 137 |
+
|
| 138 |
+
second = agent.plan("vào khay", scene)
|
| 139 |
+
assert second == [
|
| 140 |
+
{"function": "pick_up", "args": {"object_id": "banana"}},
|
| 141 |
+
{"function": "move_to", "args": {"location_id": "tray"}},
|
| 142 |
+
{"function": "place_down", "args": {}},
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_follow_up_uses_exactly_one_planner_call_per_user_turn():
|
| 147 |
+
clarify = [
|
| 148 |
+
{
|
| 149 |
+
"function": "clarify",
|
| 150 |
+
"args": {"message": "Bạn muốn đặt vật nào vào khay?"},
|
| 151 |
+
}
|
| 152 |
+
]
|
| 153 |
+
ready = [
|
| 154 |
+
{"function": "pick_up", "args": {"object_id": "pear"}},
|
| 155 |
+
{"function": "move_to", "args": {"location_id": "tray"}},
|
| 156 |
+
{"function": "place_down", "args": {}},
|
| 157 |
+
]
|
| 158 |
+
planner = _ScriptedPlanner([clarify, ready])
|
| 159 |
+
agent = LLMAgent(
|
| 160 |
+
planner=planner,
|
| 161 |
+
conversation_manager=ConversationManager(session_id="call-count"),
|
| 162 |
+
)
|
| 163 |
+
scene = _scene(("pear", "pear", "table"))
|
| 164 |
+
|
| 165 |
+
agent.plan("đặt vào khay", scene)
|
| 166 |
+
agent.plan("quả lê", scene)
|
| 167 |
+
|
| 168 |
+
assert len(planner.commands) == 2
|
| 169 |
+
assert planner.commands[0] == "đặt vào khay"
|
| 170 |
+
assert "Yêu cầu trước chưa hoàn chỉnh: đặt vào khay" in planner.commands[1]
|
| 171 |
+
assert "Robot đã hỏi: Bạn muốn đặt vật nào vào khay?" in planner.commands[1]
|
| 172 |
+
assert "Người dùng vừa trả lời: quả lê" in planner.commands[1]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def test_structured_clarification_metadata_is_preserved():
|
| 176 |
+
memory = ConversationManager(session_id="metadata")
|
| 177 |
+
scene = _scene(("banana", "banana", "table"))
|
| 178 |
+
memory.observe(
|
| 179 |
+
"di chuyển quả chuối",
|
| 180 |
+
[
|
| 181 |
+
{
|
| 182 |
+
"function": "clarify",
|
| 183 |
+
"args": {
|
| 184 |
+
"message": "Bạn muốn di chuyển quả chuối đến đâu?",
|
| 185 |
+
"missing_fields": ["destination"],
|
| 186 |
+
"partial_intent": {
|
| 187 |
+
"action": "pick_and_place",
|
| 188 |
+
"object_id": "banana",
|
| 189 |
+
},
|
| 190 |
+
},
|
| 191 |
+
}
|
| 192 |
+
],
|
| 193 |
+
scene_state=scene,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
pending = memory.pending
|
| 197 |
+
assert pending.missing_fields == ("destination",)
|
| 198 |
+
assert pending.partial_intent == {
|
| 199 |
+
"action": "pick_and_place",
|
| 200 |
+
"object_id": "banana",
|
| 201 |
+
}
|
| 202 |
+
assert pending.scene_revision == memory.scene_revision(scene)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_cancel_clears_pending_without_another_planner_call():
|
| 206 |
+
clarify = [
|
| 207 |
+
{
|
| 208 |
+
"function": "clarify",
|
| 209 |
+
"args": {"message": "Bạn muốn đặt vật nào vào khay?"},
|
| 210 |
+
}
|
| 211 |
+
]
|
| 212 |
+
planner = _ScriptedPlanner([clarify])
|
| 213 |
+
memory = ConversationManager(session_id="cancel")
|
| 214 |
+
agent = LLMAgent(planner=planner, conversation_manager=memory)
|
| 215 |
+
scene = _scene(("pear", "pear", "table"))
|
| 216 |
+
|
| 217 |
+
agent.plan("đặt vào khay", scene)
|
| 218 |
+
cancelled = agent.plan("thôi", scene)
|
| 219 |
+
|
| 220 |
+
assert len(planner.commands) == 1
|
| 221 |
+
assert cancelled[0]["function"] == "reject"
|
| 222 |
+
assert cancelled[0]["args"]["reason"] == "conversation_cancelled"
|
| 223 |
+
assert memory.pending is None
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def test_complete_new_command_replaces_pending_request():
|
| 227 |
+
clarify = [
|
| 228 |
+
{
|
| 229 |
+
"function": "clarify",
|
| 230 |
+
"args": {"message": "Bạn muốn đặt vật nào vào khay?"},
|
| 231 |
+
}
|
| 232 |
+
]
|
| 233 |
+
ready = [{"function": "pick_up", "args": {"object_id": "pear"}}]
|
| 234 |
+
planner = _ScriptedPlanner([clarify, ready])
|
| 235 |
+
memory = ConversationManager(session_id="replace")
|
| 236 |
+
agent = LLMAgent(planner=planner, conversation_manager=memory)
|
| 237 |
+
scene = _scene(("pear", "pear", "table"))
|
| 238 |
+
|
| 239 |
+
agent.plan("đặt vào khay", scene)
|
| 240 |
+
agent.plan("gắp quả lê", scene)
|
| 241 |
+
|
| 242 |
+
assert planner.commands[1] == "gắp quả lê"
|
| 243 |
+
assert memory.pending is None
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def test_follow_up_marks_changed_scene_and_uses_fresh_state():
|
| 247 |
+
memory = ConversationManager(session_id="scene-change")
|
| 248 |
+
old_scene = _scene(("pear", "pear", "table"))
|
| 249 |
+
new_scene = _scene(("pear", "pear", "tray"))
|
| 250 |
+
memory.observe(
|
| 251 |
+
"gắp quả lê",
|
| 252 |
+
[
|
| 253 |
+
{
|
| 254 |
+
"function": "clarify",
|
| 255 |
+
"args": {"message": "Bạn muốn đặt quả lê ở đâu?"},
|
| 256 |
+
}
|
| 257 |
+
],
|
| 258 |
+
scene_state=old_scene,
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
effective = memory.contextualize("vào khay", scene_state=new_scene)
|
| 262 |
+
|
| 263 |
+
assert "Scene đã thay đổi từ lượt trước: có" in effective
|
| 264 |
+
assert "Người dùng vừa trả lời: vào khay" in effective
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def test_remote_parser_accepts_structured_plan_wrapper():
|
| 268 |
+
text = json.dumps(
|
| 269 |
+
{
|
| 270 |
+
"plan": [
|
| 271 |
+
{
|
| 272 |
+
"function": "pick_up",
|
| 273 |
+
"args": {"object_id": "pear"},
|
| 274 |
+
}
|
| 275 |
+
]
|
| 276 |
+
}
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
assert RemoteLLMPlanner._parse(text) == [
|
| 280 |
+
{"function": "pick_up", "args": {"object_id": "pear"}}
|
| 281 |
+
]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def test_structured_output_falls_back_once_when_provider_rejects(monkeypatch):
|
| 285 |
+
class UnsupportedStructuredOutput(Exception):
|
| 286 |
+
status_code = 400
|
| 287 |
+
|
| 288 |
+
class FakeCompletions:
|
| 289 |
+
def __init__(self):
|
| 290 |
+
self.calls = []
|
| 291 |
+
|
| 292 |
+
def create(self, **kwargs):
|
| 293 |
+
self.calls.append(kwargs)
|
| 294 |
+
if len(self.calls) == 1:
|
| 295 |
+
raise UnsupportedStructuredOutput()
|
| 296 |
+
message = SimpleNamespace(
|
| 297 |
+
content=json.dumps(
|
| 298 |
+
{
|
| 299 |
+
"plan": [
|
| 300 |
+
{
|
| 301 |
+
"function": "pick_up",
|
| 302 |
+
"args": {"object_id": "pear"},
|
| 303 |
+
}
|
| 304 |
+
]
|
| 305 |
+
}
|
| 306 |
+
),
|
| 307 |
+
reasoning=None,
|
| 308 |
+
reasoning_content=None,
|
| 309 |
+
)
|
| 310 |
+
return SimpleNamespace(
|
| 311 |
+
choices=[SimpleNamespace(message=message)]
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
monkeypatch.setenv("LLM_STRUCTURED_OUTPUTS_ENABLED", "true")
|
| 315 |
+
completions = FakeCompletions()
|
| 316 |
+
planner = RemoteLLMPlanner(
|
| 317 |
+
model="test/model",
|
| 318 |
+
api_key="test-key",
|
| 319 |
+
base_url="https://openrouter.ai/api/v1",
|
| 320 |
+
)
|
| 321 |
+
planner._client = SimpleNamespace(
|
| 322 |
+
chat=SimpleNamespace(completions=completions)
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
plan = planner.plan(
|
| 326 |
+
"gắp quả lê",
|
| 327 |
+
_scene(("pear", "pear", "table")),
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
assert plan == [{"function": "pick_up", "args": {"object_id": "pear"}}]
|
| 331 |
+
assert len(completions.calls) == 2
|
| 332 |
+
assert "response_format" in completions.calls[0]
|
| 333 |
+
assert "response_format" not in completions.calls[1]
|
| 334 |
+
assert planner._structured_outputs_available is False
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def test_sessions_do_not_share_pending_clarification():
|
| 338 |
+
first = ConversationManager(session_id="first")
|
| 339 |
+
second = ConversationManager(session_id="second")
|
| 340 |
+
clarify = [
|
| 341 |
+
{
|
| 342 |
+
"function": "clarify",
|
| 343 |
+
"args": {"message": "Bạn muốn gắp vật nào?"},
|
| 344 |
+
}
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
first.observe("gắp lên", clarify)
|
| 348 |
+
|
| 349 |
+
assert first.pending is not None
|
| 350 |
+
assert second.pending is None
|
| 351 |
+
assert second.contextualize("quả lê") == "quả lê"
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def test_clear_removes_pending_and_recent_turns():
|
| 355 |
+
memory = ConversationManager(session_id="clear")
|
| 356 |
+
memory.observe(
|
| 357 |
+
"di chuyển",
|
| 358 |
+
[
|
| 359 |
+
{
|
| 360 |
+
"function": "clarify",
|
| 361 |
+
"args": {"message": "Bạn muốn di chuyển vật nào?"},
|
| 362 |
+
}
|
| 363 |
+
],
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
memory.clear()
|
| 367 |
+
|
| 368 |
+
assert memory.pending is None
|
| 369 |
+
assert memory.recent_turns == ()
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def test_pending_clarification_expires():
|
| 373 |
+
now = [100.0]
|
| 374 |
+
memory = ConversationManager(
|
| 375 |
+
session_id="expiry",
|
| 376 |
+
pending_ttl_seconds=10.0,
|
| 377 |
+
clock=lambda: now[0],
|
| 378 |
+
)
|
| 379 |
+
memory.observe(
|
| 380 |
+
"đặt vào khay",
|
| 381 |
+
[
|
| 382 |
+
{
|
| 383 |
+
"function": "clarify",
|
| 384 |
+
"args": {"message": "Bạn muốn đặt vật nào vào khay?"},
|
| 385 |
+
}
|
| 386 |
+
],
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
now[0] = 111.0
|
| 390 |
+
|
| 391 |
+
assert memory.pending is None
|
| 392 |
+
assert memory.contextualize("quả lê") == "quả lê"
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def test_invalid_clarification_choice_keeps_original_request_pending():
|
| 396 |
+
clarify = [
|
| 397 |
+
{
|
| 398 |
+
"function": "clarify",
|
| 399 |
+
"args": {
|
| 400 |
+
"message": "Bạn muốn tôi gắp lon súp hay lon chips?",
|
| 401 |
+
"missing_fields": ["object_id"],
|
| 402 |
+
"partial_intent": {"action": "pick_up"},
|
| 403 |
+
},
|
| 404 |
+
}
|
| 405 |
+
]
|
| 406 |
+
reject = [
|
| 407 |
+
{
|
| 408 |
+
"function": "reject",
|
| 409 |
+
"args": {"message": "Trong môi trường không có lon coca."},
|
| 410 |
+
}
|
| 411 |
+
]
|
| 412 |
+
model_ready = [
|
| 413 |
+
{"function": "pick_up", "args": {"object_id": "chips_can"}},
|
| 414 |
+
{"function": "move_to", "args": {"location_id": "tray"}},
|
| 415 |
+
{"function": "place_down", "args": {}},
|
| 416 |
+
]
|
| 417 |
+
expected_ready = [
|
| 418 |
+
{"function": "pick_up", "args": {"object_id": "chips_can"}}
|
| 419 |
+
]
|
| 420 |
+
planner = _ScriptedPlanner([clarify, reject, model_ready])
|
| 421 |
+
memory = ConversationManager(session_id="invalid-choice")
|
| 422 |
+
agent = LLMAgent(planner=planner, conversation_manager=memory)
|
| 423 |
+
scene = _scene(
|
| 424 |
+
("soup_can", "can", "tray"),
|
| 425 |
+
("chips_can", "can", "table"),
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
agent.plan("gắp một lon lên", scene)
|
| 429 |
+
agent.plan("lon coca", scene)
|
| 430 |
+
|
| 431 |
+
assert memory.pending is not None
|
| 432 |
+
assert memory.pending.original_command == "gắp một lon lên"
|
| 433 |
+
|
| 434 |
+
plan = agent.plan("thế thì lon chip đi", scene)
|
| 435 |
+
|
| 436 |
+
assert plan == expected_ready
|
| 437 |
+
assert "Yêu cầu trước chưa hoàn chỉnh: gắp một lon lên" in planner.commands[2]
|
| 438 |
+
assert "Người dùng vừa trả lời: thế thì lon chip đi" in planner.commands[2]
|
| 439 |
+
assert agent.last_outcome.resolved_goal.canonical_instruction == (
|
| 440 |
+
"gắp chips_can lên"
|
| 441 |
+
)
|
| 442 |
+
assert agent.last_outcome.resolved_goal.predicates == (
|
| 443 |
+
GoalPredicate(type="carried_object_is", object_id="chips_can"),
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def test_structured_goal_check_uses_resolved_goal_not_raw_follow_up():
|
| 448 |
+
goal = ResolvedGoal(
|
| 449 |
+
task_id="task-1",
|
| 450 |
+
canonical_instruction="đặt chips_can vào tray",
|
| 451 |
+
predicates=(
|
| 452 |
+
GoalPredicate(
|
| 453 |
+
type="location_is",
|
| 454 |
+
object_id="chips_can",
|
| 455 |
+
location_id="tray",
|
| 456 |
+
),
|
| 457 |
+
),
|
| 458 |
+
source_command="thế thì lon chip đi",
|
| 459 |
+
effective_command="context",
|
| 460 |
+
)
|
| 461 |
+
scene = _scene(
|
| 462 |
+
("chips_can", "can", "tray"),
|
| 463 |
+
("clamp", "tool", "tray"),
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
class FailIfCalled:
|
| 467 |
+
def check_goal(self, command, state):
|
| 468 |
+
raise AssertionError("LLM fallback must not run for a structured goal")
|
| 469 |
+
|
| 470 |
+
monitor = ExecutionMonitor(None, None, FailIfCalled())
|
| 471 |
+
completed, reason = monitor.verify_goal(
|
| 472 |
+
"thế thì lon chip đi",
|
| 473 |
+
scene,
|
| 474 |
+
resolved_goal=goal,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
assert completed is True
|
| 478 |
+
assert "chips_can.location='tray'" in reason
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def test_pipeline_agent_setter_keeps_monitor_agent_in_sync():
|
| 482 |
+
pipeline = ExecutionPipeline.__new__(ExecutionPipeline)
|
| 483 |
+
pipeline._agent = object()
|
| 484 |
+
pipeline.execution_monitor = SimpleNamespace(agent=None)
|
| 485 |
+
replacement = object()
|
| 486 |
+
|
| 487 |
+
pipeline.agent = replacement
|
| 488 |
+
|
| 489 |
+
assert pipeline.agent is replacement
|
| 490 |
+
assert pipeline.execution_monitor.agent is replacement
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def test_default_replan_limit_is_finite():
|
| 494 |
+
assert ExecutionPipeline.MAX_REPLANS == 3
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def test_ambiguous_goal_is_clarified_before_planner_runs():
|
| 498 |
+
planner = _GoalAwarePlanner(
|
| 499 |
+
{
|
| 500 |
+
"status": "clarify",
|
| 501 |
+
"canonical_instruction": "",
|
| 502 |
+
"message": "Bạn muốn gắp quả chuối hay quả lê lên lon chips?",
|
| 503 |
+
"missing_fields": ["object_id"],
|
| 504 |
+
"partial_intent": {
|
| 505 |
+
"action": "pick_and_place",
|
| 506 |
+
"relation": "on_top_of",
|
| 507 |
+
"relative_to": "chips_can",
|
| 508 |
+
},
|
| 509 |
+
}
|
| 510 |
+
)
|
| 511 |
+
agent = LLMAgent(
|
| 512 |
+
planner=planner,
|
| 513 |
+
conversation_manager=ConversationManager(session_id="goal-gate"),
|
| 514 |
+
)
|
| 515 |
+
scene = _scene(
|
| 516 |
+
("banana", "banana", "table"),
|
| 517 |
+
("pear", "pear", "table"),
|
| 518 |
+
("chips_can", "chips", "table"),
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
result = agent.plan("gắp quả lên lon chip", scene)
|
| 522 |
+
|
| 523 |
+
assert result[0]["function"] == "clarify"
|
| 524 |
+
assert "chuối hay quả lê" in result[0]["args"]["message"]
|
| 525 |
+
assert planner.plan_commands == []
|
| 526 |
+
assert agent.conversation_manager.pending is not None
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
def test_ready_goal_is_canonicalized_before_planning():
|
| 530 |
+
planner = _GoalAwarePlanner(
|
| 531 |
+
{
|
| 532 |
+
"status": "ready",
|
| 533 |
+
"canonical_instruction": (
|
| 534 |
+
"đặt banana on_top_of chips_can trên table"
|
| 535 |
+
),
|
| 536 |
+
"message": "",
|
| 537 |
+
"missing_fields": [],
|
| 538 |
+
"partial_intent": {},
|
| 539 |
+
},
|
| 540 |
+
plan=[
|
| 541 |
+
{"function": "pick_up", "args": {"object_id": "banana"}},
|
| 542 |
+
{
|
| 543 |
+
"function": "move_to",
|
| 544 |
+
"args": {
|
| 545 |
+
"location_id": "table",
|
| 546 |
+
"relation": "on_top_of",
|
| 547 |
+
"relative_to": "chips_can",
|
| 548 |
+
},
|
| 549 |
+
},
|
| 550 |
+
{"function": "place_down", "args": {}},
|
| 551 |
+
],
|
| 552 |
+
)
|
| 553 |
+
agent = LLMAgent(planner=planner)
|
| 554 |
+
scene = _scene(
|
| 555 |
+
("banana", "banana", "table"),
|
| 556 |
+
("chips_can", "chips", "table"),
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
result = agent.plan("đặt chuối lên lon chip", scene)
|
| 560 |
+
|
| 561 |
+
assert len(result) == 3
|
| 562 |
+
assert planner.plan_commands == [
|
| 563 |
+
"đặt banana on_top_of chips_can trên table"
|
| 564 |
+
]
|
| 565 |
+
assert agent.last_outcome.resolved_goal.canonical_instruction == (
|
| 566 |
+
"đặt banana on_top_of chips_can"
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def test_invalid_physical_action_is_converted_to_clarification():
|
| 571 |
+
planner = _GoalAwarePlanner(
|
| 572 |
+
{
|
| 573 |
+
"status": "ready",
|
| 574 |
+
"canonical_instruction": "gắp một fruit lên",
|
| 575 |
+
"message": "",
|
| 576 |
+
"missing_fields": [],
|
| 577 |
+
"partial_intent": {},
|
| 578 |
+
},
|
| 579 |
+
plan=[{"function": "pick_up", "args": {}}],
|
| 580 |
+
)
|
| 581 |
+
agent = LLMAgent(planner=planner)
|
| 582 |
+
scene = _scene(("banana", "banana", "table"))
|
| 583 |
+
|
| 584 |
+
result = agent.plan("gắp quả lên", scene)
|
| 585 |
+
|
| 586 |
+
assert result[0]["function"] == "clarify"
|
| 587 |
+
assert result[0]["args"]["reason"] == "invalid_or_empty_plan"
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def test_replan_can_skip_goal_resolution_gate():
|
| 591 |
+
planner = _GoalAwarePlanner(
|
| 592 |
+
{
|
| 593 |
+
"status": "reject",
|
| 594 |
+
"canonical_instruction": "",
|
| 595 |
+
"message": "should not be used",
|
| 596 |
+
"missing_fields": [],
|
| 597 |
+
"partial_intent": {},
|
| 598 |
+
},
|
| 599 |
+
plan=[{"function": "pick_up", "args": {"object_id": "banana"}}],
|
| 600 |
+
)
|
| 601 |
+
agent = LLMAgent(planner=planner)
|
| 602 |
+
scene = _scene(("banana", "banana", "table"))
|
| 603 |
+
|
| 604 |
+
result = agent.plan(
|
| 605 |
+
"gắp banana lên",
|
| 606 |
+
scene,
|
| 607 |
+
previous_failed_reasons="grasp failed",
|
| 608 |
+
resolve_goal=False,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
assert result == [
|
| 612 |
+
{"function": "pick_up", "args": {"object_id": "banana"}}
|
| 613 |
+
]
|
| 614 |
+
assert planner.resolve_commands == []
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def test_goal_resolution_parser_rejects_ready_without_canonical_goal():
|
| 618 |
+
invalid = json.dumps(
|
| 619 |
+
{
|
| 620 |
+
"status": "ready",
|
| 621 |
+
"canonical_instruction": "",
|
| 622 |
+
"message": "",
|
| 623 |
+
"missing_fields": [],
|
| 624 |
+
"partial_intent": {},
|
| 625 |
+
}
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
assert RemoteLLMPlanner._parse_goal_resolution(invalid) is None
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def test_goal_resolution_parser_accepts_structured_clarification():
|
| 632 |
+
clarification = json.dumps(
|
| 633 |
+
{
|
| 634 |
+
"status": "clarify",
|
| 635 |
+
"canonical_instruction": "",
|
| 636 |
+
"message": "Bạn muốn gắp quả chuối hay quả lê?",
|
| 637 |
+
"missing_fields": ["object_id"],
|
| 638 |
+
"partial_intent": {
|
| 639 |
+
"relation": "on_top_of",
|
| 640 |
+
"relative_to": "chips_can",
|
| 641 |
+
},
|
| 642 |
+
}
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
parsed = RemoteLLMPlanner._parse_goal_resolution(clarification)
|
| 646 |
+
|
| 647 |
+
assert parsed["status"] == "clarify"
|
| 648 |
+
assert parsed["missing_fields"] == ["object_id"]
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def test_goal_check_falls_back_to_live_geometry_for_on_top_relation():
|
| 652 |
+
goal = ResolvedGoal(
|
| 653 |
+
task_id="stack-task",
|
| 654 |
+
canonical_instruction="đặt pear on_top_of chips_can",
|
| 655 |
+
predicates=(
|
| 656 |
+
GoalPredicate(
|
| 657 |
+
type="relation_is",
|
| 658 |
+
object_id="pear",
|
| 659 |
+
location_id="table",
|
| 660 |
+
relation="on_top_of",
|
| 661 |
+
relative_to="chips_can",
|
| 662 |
+
),
|
| 663 |
+
),
|
| 664 |
+
source_command="đặt lê lên lon chip",
|
| 665 |
+
effective_command="đặt pear on_top_of chips_can",
|
| 666 |
+
)
|
| 667 |
+
state = _scene(
|
| 668 |
+
("pear", "pear", "table"),
|
| 669 |
+
("chips_can", "chips", "table"),
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
class LiveScene:
|
| 673 |
+
def is_on_top(self, upper, lower):
|
| 674 |
+
return upper == "pear" and lower == "chips_can"
|
| 675 |
+
|
| 676 |
+
completed, reason = ExecutionMonitor._verify_predicates(
|
| 677 |
+
goal,
|
| 678 |
+
state,
|
| 679 |
+
scene=LiveScene(),
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
assert completed is True
|
| 683 |
+
assert "verified_from_live_aabb" in reason
|
tests/test_occupancy.py
CHANGED
|
@@ -134,7 +134,7 @@ def test_find_free_tray_placements_returns_spots():
|
|
| 134 |
assert x0 <= x <= x1 and y0 <= y <= y1
|
| 135 |
|
| 136 |
|
| 137 |
-
def test_relation_left_of_places_on_correct_side():
|
| 138 |
# +Y is "left". A left_of placement must land at greater y than the reference.
|
| 139 |
cx, cy = config.TABLE_CENTER
|
| 140 |
ref = (cx, cy - 0.05) # reference object slightly to the right
|
|
@@ -142,6 +142,29 @@ def test_relation_left_of_places_on_correct_side():
|
|
| 142 |
spots = scene.find_free_placements(
|
| 143 |
(0.04, 0.04), max_results=1, relation="left_of", relative_to_pos=ref,
|
| 144 |
)
|
| 145 |
-
assert spots
|
| 146 |
-
assert spots[0][1] > ref[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
|
|
|
| 134 |
assert x0 <= x <= x1 and y0 <= y <= y1
|
| 135 |
|
| 136 |
|
| 137 |
+
def test_relation_left_of_places_on_correct_side():
|
| 138 |
# +Y is "left". A left_of placement must land at greater y than the reference.
|
| 139 |
cx, cy = config.TABLE_CENTER
|
| 140 |
ref = (cx, cy - 0.05) # reference object slightly to the right
|
|
|
|
| 142 |
spots = scene.find_free_placements(
|
| 143 |
(0.04, 0.04), max_results=1, relation="left_of", relative_to_pos=ref,
|
| 144 |
)
|
| 145 |
+
assert spots
|
| 146 |
+
assert spots[0][1] > ref[1]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def test_on_top_detection_accepts_small_physics_interpenetration():
|
| 150 |
+
support = ((0.45, -0.05, 0.30), (0.55, 0.05, 0.40))
|
| 151 |
+
# The upper object's AABB settles 4 cm into the support AABB. This can
|
| 152 |
+
# happen for rounded/concave visual meshes even when the stack is visible.
|
| 153 |
+
upper = ((0.47, -0.03, 0.36), (0.53, 0.03, 0.46))
|
| 154 |
+
|
| 155 |
+
assert SceneManager._aabb_is_on_top(upper, support)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_on_top_detection_rejects_side_contact_with_tiny_overlap():
|
| 159 |
+
support = ((0.45, -0.05, 0.30), (0.55, 0.05, 0.40))
|
| 160 |
+
side_object = ((0.545, -0.03, 0.36), (0.65, 0.03, 0.46))
|
| 161 |
+
|
| 162 |
+
assert not SceneManager._aabb_is_on_top(side_object, support)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_on_top_detection_rejects_object_floating_too_high():
|
| 166 |
+
support = ((0.45, -0.05, 0.30), (0.55, 0.05, 0.40))
|
| 167 |
+
floating = ((0.47, -0.03, 0.50), (0.53, 0.03, 0.60))
|
| 168 |
+
|
| 169 |
+
assert not SceneManager._aabb_is_on_top(floating, support)
|
| 170 |
|