File size: 4,426 Bytes
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
"""High-level task planner: natural-language instruction -> validated skill plan.

The LLM may only use skills from SKILLS; each step becomes a short language
instruction for the low-level VLA (GR00T N1.7 / SmolVLA), which is the format
those policies were trained on.
"""
from __future__ import annotations

import json
import re
from dataclasses import dataclass, field
from typing import Callable

# Skills the low-level policy has been fine-tuned on. Extend as datasets grow.
SKILLS: dict[str, str] = {
    "pick": "pick up {object}",
    "place": "place the {object} {location}",
    "push": "push the {object} {location}",
    "open": "open the {object}",
    "close": "close the {object}",
    "stack": "stack the {object} on the {location}",
    "home": "move the arm to the home position",
}

SYSTEM_PROMPT = """You are the task planner for a single robot arm.
Decompose the user's instruction into a short sequence of skills.
Allowed skills (use ONLY these): {skills}.
Each step needs "skill"; "object" and "location" when the skill uses them.
Only reference objects listed in the scene. If the task is impossible with
these skills or objects, return {{"steps": [], "infeasible_reason": "..."}}.
Respond with JSON only: {{"steps": [{{"skill": ..., "object": ..., "location": ...}}]}}"""


@dataclass
class Step:
    skill: str
    object: str | None = None
    location: str | None = None

    def instruction(self) -> str:
        tmpl = SKILLS[self.skill]
        return tmpl.format(object=self.object or "", location=self.location or "").strip()


@dataclass
class Plan:
    steps: list[Step] = field(default_factory=list)
    infeasible_reason: str | None = None
    provider: str | None = None


class PlanError(ValueError):
    pass


def _extract_json(text: str) -> dict:
    text = text.strip()
    fence = re.search(r"```(?:json)?\s*(.*?)```", text, re.S)
    if fence:
        text = fence.group(1)
    start, end = text.find("{"), text.rfind("}")
    if start < 0 or end < start:
        raise PlanError("no JSON object in LLM output")
    try:
        return json.loads(text[start : end + 1])
    except json.JSONDecodeError as e:
        raise PlanError(f"invalid JSON: {e}") from e


def parse_plan(text: str, scene_objects: list[str] | None = None, max_steps: int = 12) -> Plan:
    data = _extract_json(text)
    raw = data.get("steps")
    if not isinstance(raw, list):
        raise PlanError("'steps' must be a list")
    if len(raw) > max_steps:
        raise PlanError(f"plan too long ({len(raw)} > {max_steps})")
    known = {o.lower() for o in scene_objects} if scene_objects else None
    steps: list[Step] = []
    for i, s in enumerate(raw):
        if not isinstance(s, dict) or s.get("skill") not in SKILLS:
            raise PlanError(f"step {i}: unknown skill {s!r}")
        step = Step(s["skill"], s.get("object") or None, s.get("location") or None)
        if "{object}" in SKILLS[step.skill] and not step.object:
            raise PlanError(f"step {i}: skill '{step.skill}' needs an object")
        if known is not None and step.object and step.object.lower() not in known:
            raise PlanError(f"step {i}: object '{step.object}' not in scene")
        steps.append(step)
    return Plan(steps=steps, infeasible_reason=data.get("infeasible_reason"))


def plan(
    instruction: str,
    scene_objects: list[str],
    chat_fn: Callable[..., tuple[str, str]] | None = None,
    max_attempts: int = 3,
) -> Plan:
    """Ask the LLM for a plan; on validation failure, feed the error back and retry."""
    if chat_fn is None:
        from robotics.llm.providers import chat as chat_fn  # lazy: keeps tests offline
    messages = [
        {"role": "system", "content": SYSTEM_PROMPT.format(skills=", ".join(SKILLS))},
        {"role": "user", "content": f"Scene objects: {scene_objects}\nInstruction: {instruction}"},
    ]
    last_err: Exception | None = None
    for _ in range(max_attempts):
        text, provider = chat_fn(messages, json_mode=True)
        try:
            p = parse_plan(text, scene_objects)
            p.provider = provider
            return p
        except PlanError as e:
            last_err = e
            messages += [{"role": "assistant", "content": text},
                         {"role": "user", "content": f"Invalid plan: {e}. Return corrected JSON only."}]
    raise PlanError(f"no valid plan after {max_attempts} attempts: {last_err}")