Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/chunk-000/file-063.parquet +3 -0
- leaf/final/episode_000151.npz +3 -0
- leaf/final/episode_000484_wrist_image.png +3 -0
- leaf/final/episode_000812_image.png +3 -0
- leaf/final/episode_000854_wrist_image.png +3 -0
- leaf/final/episode_000891.npz +3 -0
- leaf/final/episode_000916_wrist_image.png +3 -0
- leaf/final/episode_000971_wrist_image.png +3 -0
- leaf/final/episode_001029_image.png +3 -0
- leaf/final/episode_001296_wrist_image.png +3 -0
- leaf/final/episode_001369_image.png +3 -0
- leaf/final/episode_001397_wrist_image.png +3 -0
- leaf/final/episode_001447.npz +3 -0
- leaf/final/episode_001522_image.png +3 -0
- leaf/final/episode_001536.npz +3 -0
- leaf/final/episode_001558_image.png +3 -0
- leaf/final/episode_001651_image.png +3 -0
- leaf/final/episode_001726_wrist_image.png +3 -0
- leaf/final/episode_001774_wrist_image.png +3 -0
- leaf/final/episode_001801.npz +3 -0
- leaf/final/episode_001848_image.png +3 -0
- leaf/final/episode_002045_wrist_image.png +3 -0
- leaf/final/episode_002297_wrist_image.png +3 -0
- leaf/final/episode_002402_wrist_image.png +3 -0
- leaf/final/episode_002458.npz +3 -0
- leaf/final/episode_002732_wrist_image.png +3 -0
- leaf/final/episode_002914_image.png +3 -0
- leaf/final/episode_003013_wrist_image.png +3 -0
- leaf/final/episode_003035_image.png +3 -0
- leaf/final/episode_003205_image.png +3 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/client/lffbench_client/__init__.py +139 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/__init__.py +21 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/anthropic_messages.py +202 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py +82 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/gemini.py +206 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/scripted.py +210 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/__init__.py +53 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py +73 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py +65 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py +50 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l4_fit_container.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py +40 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l7_key_turn.py +34 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py +39 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py +23 -0
data/chunk-000/file-063.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3946593217e42c31ef95bb33f1085f01cf6b780340f4bb1a40b78609144a91ac
|
| 3 |
+
size 14258067
|
leaf/final/episode_000151.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:82e866126ba995e45f4ea2187c200a4fe8bc417cadbdc66087c01556a0669738
|
| 3 |
+
size 3942
|
leaf/final/episode_000484_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000812_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000854_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000891.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:07b4017ed55052de2708f079253b4e2c0436b1cd52ae1ad71c5f99b7b1a2b1a3
|
| 3 |
+
size 3734
|
leaf/final/episode_000916_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000971_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001029_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001296_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001369_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001397_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001447.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:07edc2e3f71a4af869911bd51bafc4059697f5ee1fc9dc0d74c4ad518a2b6226
|
| 3 |
+
size 3630
|
leaf/final/episode_001522_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001536.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2427b95ccb654bd89707701c31632e4a517979f205b0c613e472c35d4b468f87
|
| 3 |
+
size 3958
|
leaf/final/episode_001558_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001651_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001726_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001774_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001801.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:122206ee35c60d3ed1c34349498c589264e6900cc24376163f3348b6afceb169
|
| 3 |
+
size 3838
|
leaf/final/episode_001848_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002045_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002297_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002402_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002458.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:59d7b3a48f0d15266adbb2fa15c2d77f41d961bd5b42637c99fff9feca1485f6
|
| 3 |
+
size 3870
|
leaf/final/episode_002732_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002914_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_003013_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_003035_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_003205_image.png
ADDED
|
Git LFS Details
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/client/lffbench_client/__init__.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3).
|
| 2 |
+
|
| 3 |
+
Only the standard library; it never imports the simulator. It talks to the episode's tool gateway
|
| 4 |
+
(scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed
|
| 5 |
+
shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls
|
| 6 |
+
them through a Session:
|
| 7 |
+
|
| 8 |
+
from lffbench_client import Session
|
| 9 |
+
s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher)
|
| 10 |
+
first = s.first_message() # README + first status, as every harness gets it
|
| 11 |
+
tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat
|
| 12 |
+
r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult
|
| 13 |
+
r.json() # the robot server's reply as a dict
|
| 14 |
+
s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)]
|
| 15 |
+
|
| 16 |
+
A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished
|
| 17 |
+
says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only
|
| 18 |
+
feedback is what the robot server writes into the tool results.
|
| 19 |
+
"""
|
| 20 |
+
import base64
|
| 21 |
+
import dataclasses
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import urllib.error
|
| 25 |
+
import urllib.parse
|
| 26 |
+
import urllib.request
|
| 27 |
+
|
| 28 |
+
__all__ = ["Session", "ToolResult", "GatewayError", "STYLES"]
|
| 29 |
+
__version__ = "0.1.0"
|
| 30 |
+
|
| 31 |
+
STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class GatewayError(RuntimeError):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclasses.dataclass
|
| 39 |
+
class ToolResult:
|
| 40 |
+
content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}]
|
| 41 |
+
is_error: bool
|
| 42 |
+
finished: bool # the episode is over: stop calling tools and report
|
| 43 |
+
calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0)
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def text(self):
|
| 47 |
+
"""All text items, joined by newlines."""
|
| 48 |
+
return "\n".join(c["text"] for c in self.content if c.get("type") == "text")
|
| 49 |
+
|
| 50 |
+
def json(self):
|
| 51 |
+
"""The first text item parsed as JSON (robot / shell / view_images replies are JSON objects)."""
|
| 52 |
+
for c in self.content:
|
| 53 |
+
if c.get("type") == "text":
|
| 54 |
+
return json.loads(c["text"])
|
| 55 |
+
raise ValueError("no text item")
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def images(self):
|
| 59 |
+
"""[(mime type, bytes)] of the image items."""
|
| 60 |
+
return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Session:
|
| 64 |
+
"""One episode's tools through its gateway. face labels this access path in the gateway transcript."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, url, token, face="sdk", timeout_s=900.0):
|
| 67 |
+
self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s
|
| 68 |
+
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_env(cls, face="sdk", **kw):
|
| 72 |
+
url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN")
|
| 73 |
+
if not url or not token:
|
| 74 |
+
raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set")
|
| 75 |
+
return cls(url, token, face=face, **kw)
|
| 76 |
+
|
| 77 |
+
@classmethod
|
| 78 |
+
def from_gateway_file(cls, path, face="sdk", **kw):
|
| 79 |
+
"""gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars)."""
|
| 80 |
+
d = json.load(open(path))
|
| 81 |
+
return cls(d["url"], d["token"], face=face, **kw)
|
| 82 |
+
|
| 83 |
+
# ------------------------------------------------------------------------------------------------ http
|
| 84 |
+
def _request(self, method, path, body=None):
|
| 85 |
+
req = urllib.request.Request(self.url + path, method=method,
|
| 86 |
+
data=None if body is None else json.dumps(body).encode(),
|
| 87 |
+
headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face,
|
| 88 |
+
"Content-Type": "application/json"})
|
| 89 |
+
try:
|
| 90 |
+
with self._opener.open(req, timeout=self.timeout_s) as r:
|
| 91 |
+
return r.read(), r.headers.get("Content-Type", "")
|
| 92 |
+
except urllib.error.HTTPError as e:
|
| 93 |
+
raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None
|
| 94 |
+
except urllib.error.URLError as e:
|
| 95 |
+
raise GatewayError(f"{method} {path}: {e.reason}") from None
|
| 96 |
+
|
| 97 |
+
def _get_json(self, path):
|
| 98 |
+
return json.loads(self._request("GET", path)[0])
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------------------------------------ tools
|
| 101 |
+
def call(self, name, arguments=None):
|
| 102 |
+
raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {}))
|
| 103 |
+
d = json.loads(raw)
|
| 104 |
+
return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]),
|
| 105 |
+
calls_in_attempt=d.get("calls_in_attempt"))
|
| 106 |
+
|
| 107 |
+
def robot(self, command):
|
| 108 |
+
"""One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...')."""
|
| 109 |
+
return self.call("robot", dict(command=command))
|
| 110 |
+
|
| 111 |
+
def shell(self, command):
|
| 112 |
+
"""A bash command in the episode workspace (jailed: no network, nothing outside the workspace)."""
|
| 113 |
+
return self.call("shell", dict(command=command))
|
| 114 |
+
|
| 115 |
+
def view_images(self, paths):
|
| 116 |
+
"""Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items."""
|
| 117 |
+
return self.call("view_images", dict(paths=list(paths)))
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------------------------------------------ instructions
|
| 120 |
+
def tool_specs(self, style="raw"):
|
| 121 |
+
"""The three tool schemas with the reference descriptions, in one of STYLES."""
|
| 122 |
+
if style not in STYLES:
|
| 123 |
+
raise ValueError(f"style must be one of {STYLES}")
|
| 124 |
+
return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"]
|
| 125 |
+
|
| 126 |
+
def readme(self):
|
| 127 |
+
return self._request("GET", "/readme")[0].decode("utf-8")
|
| 128 |
+
|
| 129 |
+
def first_message(self):
|
| 130 |
+
"""Preamble + README + first status report: the first user message every harness gets."""
|
| 131 |
+
return self._request("GET", "/first_message")[0].decode("utf-8")
|
| 132 |
+
|
| 133 |
+
def health(self):
|
| 134 |
+
return self._get_json("/health")
|
| 135 |
+
|
| 136 |
+
def status(self):
|
| 137 |
+
"""robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not
|
| 138 |
+
a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result."""
|
| 139 |
+
return self._get_json("/status")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk)."""
|
| 2 |
+
from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def make_backend(kind, **kw):
|
| 6 |
+
if kind == "scripted":
|
| 7 |
+
from .scripted import ScriptedBackend
|
| 8 |
+
return ScriptedBackend(**kw)
|
| 9 |
+
if kind == "openai":
|
| 10 |
+
from .openai_responses import OpenAIResponsesBackend
|
| 11 |
+
return OpenAIResponsesBackend(**kw)
|
| 12 |
+
if kind == "chat":
|
| 13 |
+
from .chat_completions import ChatCompletionsBackend
|
| 14 |
+
return ChatCompletionsBackend(**kw)
|
| 15 |
+
if kind == "anthropic":
|
| 16 |
+
from .anthropic_messages import AnthropicMessagesBackend
|
| 17 |
+
return AnthropicMessagesBackend(**kw)
|
| 18 |
+
if kind == "gemini":
|
| 19 |
+
from .gemini import GeminiBackend
|
| 20 |
+
return GeminiBackend(**kw)
|
| 21 |
+
raise ValueError(kind)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/anthropic_messages.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anthropic Messages API backend (Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1 ...), official SDK `anthropic`.
|
| 2 |
+
|
| 3 |
+
Same conversation as the OpenAI backends, converted to Messages API blocks:
|
| 4 |
+
- system prompt = conv.system; tools = the harness tool specs (strict, one call per turn like the GPT player);
|
| 5 |
+
- every assistant turn is stored with its full `content` (thinking blocks with signatures, text, tool_use) and replayed
|
| 6 |
+
unchanged, so the model keeps its reasoning across tool calls. Assistant turns are never edited; old images in user
|
| 7 |
+
turns may be replaced by a text note (checked 2026-10-15 on Sonnet 5.5 / Opus 5.5 with thinking blocks in the
|
| 8 |
+
history: accepted), which the player does only when the context or the per-request image limit is reached;
|
| 9 |
+
- tool outputs of one turn become `tool_result` blocks at the start of the next user message; images the harness
|
| 10 |
+
attaches after them (observations, view_images) follow in the same user message;
|
| 11 |
+
- adaptive thinking with an explicit effort (the per-model default differs: Opus 5.5 medium, Sonnet 5.5 high);
|
| 12 |
+
- automatic prompt caching (top-level cache_control): every request caches its whole prefix for the next call;
|
| 13 |
+
- streaming, so long thinking turns do not hit the HTTP timeout.
|
| 14 |
+
No refusal fallback on purpose: a fallback would silently swap the model under test. A refusal is reported as
|
| 15 |
+
status "refusal" and the player ends the run.
|
| 16 |
+
|
| 17 |
+
Key from ANTHROPIC_API_KEY (or any credential the SDK resolves). The client is created lazily on the first real
|
| 18 |
+
call; tests inject a mock client.
|
| 19 |
+
"""
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
from ..context import ToolCall, prune_live_images
|
| 23 |
+
from .base import Backend, BackendResponse, import_sdk
|
| 24 |
+
|
| 25 |
+
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _get(obj, key, default=None):
|
| 29 |
+
if isinstance(obj, dict):
|
| 30 |
+
return obj.get(key, default)
|
| 31 |
+
return getattr(obj, key, default)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _to_dict(block):
|
| 35 |
+
if isinstance(block, dict):
|
| 36 |
+
return dict(block)
|
| 37 |
+
if hasattr(block, "to_dict"):
|
| 38 |
+
return block.to_dict()
|
| 39 |
+
return block.model_dump(mode="json", exclude_none=True)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def anthropic_tools(specs, strict=True):
|
| 43 |
+
out = []
|
| 44 |
+
for s in specs:
|
| 45 |
+
t = dict(name=s["name"], description=s["description"], input_schema=s["parameters"])
|
| 46 |
+
if strict:
|
| 47 |
+
t["strict"] = True
|
| 48 |
+
out.append(t)
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def image_block(image, quality=None):
|
| 53 |
+
url = image.data_url(quality)
|
| 54 |
+
head, data = url.split(",", 1) # data:<mime>;base64,<data>
|
| 55 |
+
mime = head[len("data:"):].split(";", 1)[0]
|
| 56 |
+
return dict(type="image", source=dict(type="base64", media_type=mime, data=data))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class AnthropicMessagesBackend(Backend):
|
| 60 |
+
name = "anthropic"
|
| 61 |
+
|
| 62 |
+
def __init__(self, model="claude-opus-5-5", effort="high", thinking_display="summarized", max_tokens=64000,
|
| 63 |
+
max_live_images=None, jpeg_quality=90, timeout=900.0, max_retries=2, strict_tools=True,
|
| 64 |
+
parallel_tool_calls=False, cache=True, client=None):
|
| 65 |
+
if effort not in EFFORTS:
|
| 66 |
+
raise ValueError(f"effort must be one of {EFFORTS}, got {effort!r}")
|
| 67 |
+
self.model = model
|
| 68 |
+
self.effort = effort
|
| 69 |
+
self.thinking_display = thinking_display # "summarized" (logged as the reasoning summary) | "omitted"
|
| 70 |
+
self.max_tokens = max_tokens
|
| 71 |
+
self.max_live_images = max_live_images
|
| 72 |
+
self.jpeg_quality = jpeg_quality
|
| 73 |
+
self.timeout = timeout
|
| 74 |
+
self.max_retries = max_retries
|
| 75 |
+
self.strict_tools = strict_tools
|
| 76 |
+
self.parallel_tool_calls = parallel_tool_calls
|
| 77 |
+
self.cache = cache
|
| 78 |
+
self._client = client
|
| 79 |
+
|
| 80 |
+
def config(self):
|
| 81 |
+
return dict(name=self.name, model=self.model, effort=self.effort, thinking_display=self.thinking_display,
|
| 82 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality,
|
| 83 |
+
timeout=self.timeout, max_retries=self.max_retries, strict_tools=self.strict_tools,
|
| 84 |
+
parallel_tool_calls=self.parallel_tool_calls, cache=self.cache)
|
| 85 |
+
|
| 86 |
+
def client(self):
|
| 87 |
+
if self._client is None:
|
| 88 |
+
anthropic = import_sdk("anthropic")
|
| 89 |
+
self._client = anthropic.Anthropic(timeout=self.timeout, max_retries=self.max_retries)
|
| 90 |
+
return self._client
|
| 91 |
+
|
| 92 |
+
# ------------------------------------------------------------------ request
|
| 93 |
+
def convert_items(self, items):
|
| 94 |
+
msgs = []
|
| 95 |
+
|
| 96 |
+
def push(role, blocks):
|
| 97 |
+
if msgs and msgs[-1]["role"] == role:
|
| 98 |
+
msgs[-1]["content"].extend(blocks)
|
| 99 |
+
else:
|
| 100 |
+
msgs.append(dict(role=role, content=list(blocks)))
|
| 101 |
+
|
| 102 |
+
for it in items:
|
| 103 |
+
kind = it["kind"]
|
| 104 |
+
if kind == "user":
|
| 105 |
+
blocks = []
|
| 106 |
+
for p in it["parts"]:
|
| 107 |
+
if p["type"] == "text":
|
| 108 |
+
blocks.append(dict(type="text", text=p["text"]))
|
| 109 |
+
else:
|
| 110 |
+
blocks.append(image_block(p["image"], self.jpeg_quality))
|
| 111 |
+
push("user", blocks)
|
| 112 |
+
elif kind == "assistant":
|
| 113 |
+
if it.get("raw") is not None and it.get("backend") == self.name:
|
| 114 |
+
blocks = [dict(b) for b in it["raw"]]
|
| 115 |
+
else: # a turn produced by another backend: plain text + tool calls, no thinking
|
| 116 |
+
blocks = ([dict(type="text", text=it["text"])] if it.get("text") else [])
|
| 117 |
+
blocks += [dict(type="tool_use", id=tc.id, name=tc.name, input=tc.arguments)
|
| 118 |
+
for tc in it["tool_calls"]]
|
| 119 |
+
if not blocks:
|
| 120 |
+
blocks = [dict(type="text", text="(no output)")]
|
| 121 |
+
push("assistant", blocks)
|
| 122 |
+
elif kind == "tool_output":
|
| 123 |
+
push("user", [dict(type="tool_result", tool_use_id=it["call_id"], content=it["text"])])
|
| 124 |
+
else:
|
| 125 |
+
raise ValueError(kind)
|
| 126 |
+
return msgs
|
| 127 |
+
|
| 128 |
+
def build_request(self, conv, tools):
|
| 129 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 130 |
+
req = dict(model=self.model, max_tokens=int(self.max_tokens), system=conv.system,
|
| 131 |
+
messages=self.convert_items(items), tools=anthropic_tools(tools, self.strict_tools),
|
| 132 |
+
tool_choice=dict(type="auto", disable_parallel_tool_use=not self.parallel_tool_calls),
|
| 133 |
+
thinking=dict(type="adaptive", display=self.thinking_display),
|
| 134 |
+
output_config=dict(effort=self.effort))
|
| 135 |
+
if self.cache:
|
| 136 |
+
req["cache_control"] = dict(type="ephemeral")
|
| 137 |
+
return req
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def request_stats(req):
|
| 141 |
+
n_img, img_bytes, txt = 0, 0, len(req.get("system") or "")
|
| 142 |
+
for m in req["messages"]:
|
| 143 |
+
for b in m["content"]:
|
| 144 |
+
t = b.get("type")
|
| 145 |
+
if t == "image":
|
| 146 |
+
n_img += 1
|
| 147 |
+
img_bytes += len(b["source"]["data"])
|
| 148 |
+
elif t == "text":
|
| 149 |
+
txt += len(b["text"])
|
| 150 |
+
elif t == "tool_result":
|
| 151 |
+
txt += len(b["content"]) if isinstance(b["content"], str) else 0
|
| 152 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_messages=len(req["messages"]))
|
| 153 |
+
|
| 154 |
+
# ------------------------------------------------------------------ call
|
| 155 |
+
def act(self, conv, tools):
|
| 156 |
+
req = self.build_request(conv, tools)
|
| 157 |
+
stats = self.request_stats(req)
|
| 158 |
+
t0 = time.time()
|
| 159 |
+
try:
|
| 160 |
+
with self.client().messages.stream(**req) as stream:
|
| 161 |
+
msg = stream.get_final_message()
|
| 162 |
+
except AssertionError: # the SDK asserts on a stream without message_start (seen through a gateway)
|
| 163 |
+
raise RuntimeError("empty response stream (no message_start event)") from None
|
| 164 |
+
out = self.parse_response(msg)
|
| 165 |
+
out.latency_s = time.time() - t0
|
| 166 |
+
out.request_stats = stats
|
| 167 |
+
return out
|
| 168 |
+
|
| 169 |
+
def parse_response(self, msg):
|
| 170 |
+
calls, texts, summ = [], [], []
|
| 171 |
+
content = _get(msg, "content") or []
|
| 172 |
+
for b in content:
|
| 173 |
+
t = _get(b, "type")
|
| 174 |
+
if t == "tool_use":
|
| 175 |
+
args = _get(b, "input") or {}
|
| 176 |
+
calls.append(ToolCall(id=_get(b, "id"), name=_get(b, "name"), arguments=dict(args)))
|
| 177 |
+
elif t == "text":
|
| 178 |
+
texts.append(_get(b, "text") or "")
|
| 179 |
+
elif t == "thinking":
|
| 180 |
+
if _get(b, "thinking"):
|
| 181 |
+
summ.append(_get(b, "thinking"))
|
| 182 |
+
u = _get(msg, "usage")
|
| 183 |
+
usage = {}
|
| 184 |
+
if u is not None:
|
| 185 |
+
fresh = _get(u, "input_tokens", 0) or 0
|
| 186 |
+
read = _get(u, "cache_read_input_tokens", 0) or 0
|
| 187 |
+
write = _get(u, "cache_creation_input_tokens", 0) or 0
|
| 188 |
+
# same meaning as the OpenAI backend: input_tokens = whole prompt, cached_tokens = the part read from cache
|
| 189 |
+
usage = dict(input_tokens=fresh + read + write, cached_tokens=read, cache_write_tokens=write,
|
| 190 |
+
output_tokens=_get(u, "output_tokens", 0) or 0, reasoning_tokens=0)
|
| 191 |
+
stop = _get(msg, "stop_reason")
|
| 192 |
+
status, err = "completed", None
|
| 193 |
+
if stop == "refusal":
|
| 194 |
+
d = _get(msg, "stop_details")
|
| 195 |
+
status, err = "refusal", f"refusal: category={_get(d, 'category')} {_get(d, 'explanation') or ''}".strip()
|
| 196 |
+
elif stop == "max_tokens":
|
| 197 |
+
status, err = "incomplete", "incomplete: max_tokens"
|
| 198 |
+
elif not content and u is None:
|
| 199 |
+
status, err = "incomplete", "empty response (no content, no usage)"
|
| 200 |
+
return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
|
| 201 |
+
reasoning_summary="\n".join(summ) or None, usage=usage,
|
| 202 |
+
raw=[_to_dict(b) for b in content], status=status, error=err)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/base.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s)."""
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
# Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh).
|
| 8 |
+
# Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name:
|
| 9 |
+
# LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence.
|
| 10 |
+
API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "")
|
| 11 |
+
OPENAI_SDK_DIR = API_SDK_DIR # old name
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def import_sdk(module):
|
| 15 |
+
"""Import an API SDK module ("openai", "anthropic", "google.genai")."""
|
| 16 |
+
import importlib
|
| 17 |
+
try:
|
| 18 |
+
return importlib.import_module(module)
|
| 19 |
+
except ImportError:
|
| 20 |
+
if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path:
|
| 21 |
+
sys.path.append(API_SDK_DIR)
|
| 22 |
+
return importlib.import_module(module)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def import_openai():
|
| 26 |
+
return import_sdk("openai")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class BackendResponse:
|
| 31 |
+
tool_calls: list = field(default_factory=list) # [ToolCall]
|
| 32 |
+
text: Optional[str] = None # visible assistant text (e.g. the diagnosis)
|
| 33 |
+
reasoning_summary: Optional[str] = None
|
| 34 |
+
usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens
|
| 35 |
+
latency_s: float = 0.0
|
| 36 |
+
raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items)
|
| 37 |
+
request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ...
|
| 38 |
+
status: str = "ok"
|
| 39 |
+
error: Optional[str] = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class RunInfo:
|
| 44 |
+
task: object # privileged: only the scripted backend may look at task / inst
|
| 45 |
+
inst: dict
|
| 46 |
+
seed: int
|
| 47 |
+
k: int
|
| 48 |
+
protocol: str
|
| 49 |
+
feedback: str
|
| 50 |
+
memory: str
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class AttemptInfo:
|
| 55 |
+
attempt: int
|
| 56 |
+
history: list # AttemptRecords visible to the agent under the memory mode (already selected)
|
| 57 |
+
continuing: bool = False # within protocol: continuing after a failed done
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Backend:
|
| 61 |
+
name = "base"
|
| 62 |
+
|
| 63 |
+
def begin_run(self, info: RunInfo):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
def begin_attempt(self, info: AttemptInfo):
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
def act(self, conv, tools) -> BackendResponse:
|
| 70 |
+
raise NotImplementedError
|
| 71 |
+
|
| 72 |
+
def on_tool_result(self, call, result):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
def end_attempt(self) -> dict:
|
| 76 |
+
return {}
|
| 77 |
+
|
| 78 |
+
def end_run(self):
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
def config(self) -> dict:
|
| 82 |
+
return dict(name=self.name)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/chat_completions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
|
| 2 |
+
by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
|
| 3 |
+
|
| 4 |
+
Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
|
| 5 |
+
message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
|
| 6 |
+
back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
|
| 7 |
+
Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from ..context import ToolCall, prune_live_images
|
| 13 |
+
from .base import Backend, BackendResponse, import_openai
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def chat_tools(specs):
|
| 17 |
+
return [dict(type="function", function=dict(name=s["name"], description=s["description"],
|
| 18 |
+
parameters=s["parameters"])) for s in specs]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatCompletionsBackend(Backend):
|
| 22 |
+
name = "chat"
|
| 23 |
+
|
| 24 |
+
def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
|
| 25 |
+
max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
|
| 26 |
+
replay_reasoning=True):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
|
| 29 |
+
self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
|
| 30 |
+
self.temperature = temperature
|
| 31 |
+
self.max_tokens = max_tokens
|
| 32 |
+
self.max_live_images = max_live_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
self.timeout = timeout
|
| 35 |
+
self.extra_body = extra_body
|
| 36 |
+
self.replay_reasoning = replay_reasoning
|
| 37 |
+
self._client = client
|
| 38 |
+
|
| 39 |
+
def config(self):
|
| 40 |
+
return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
|
| 41 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images,
|
| 42 |
+
replay_reasoning=self.replay_reasoning)
|
| 43 |
+
|
| 44 |
+
def client(self):
|
| 45 |
+
if self._client is None:
|
| 46 |
+
openai = import_openai()
|
| 47 |
+
kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
|
| 48 |
+
if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
|
| 49 |
+
# local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
|
| 50 |
+
kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
|
| 51 |
+
self._client = openai.OpenAI(**kw)
|
| 52 |
+
return self._client
|
| 53 |
+
|
| 54 |
+
def build_request(self, conv, tools):
|
| 55 |
+
msgs = [dict(role="system", content=conv.system)]
|
| 56 |
+
for it in prune_live_images(conv.items, self.max_live_images):
|
| 57 |
+
if it["kind"] == "user":
|
| 58 |
+
content = []
|
| 59 |
+
for p in it["parts"]:
|
| 60 |
+
if p["type"] == "text":
|
| 61 |
+
content.append(dict(type="text", text=p["text"]))
|
| 62 |
+
else:
|
| 63 |
+
content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
|
| 64 |
+
msgs.append(dict(role="user", content=content))
|
| 65 |
+
elif it["kind"] == "assistant":
|
| 66 |
+
if not it.get("text") and not it["tool_calls"]:
|
| 67 |
+
# a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
|
| 68 |
+
# counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
|
| 69 |
+
# nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
|
| 70 |
+
continue
|
| 71 |
+
m = dict(role="assistant", content=it.get("text") or None)
|
| 72 |
+
rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
|
| 73 |
+
if rc and self.replay_reasoning:
|
| 74 |
+
m["reasoning_content"] = rc
|
| 75 |
+
if it["tool_calls"]:
|
| 76 |
+
m["tool_calls"] = [dict(id=tc.id, type="function",
|
| 77 |
+
function=dict(name=tc.name,
|
| 78 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 79 |
+
for tc in it["tool_calls"]]
|
| 80 |
+
msgs.append(m)
|
| 81 |
+
elif it["kind"] == "tool_output":
|
| 82 |
+
msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
|
| 83 |
+
req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
|
| 84 |
+
max_tokens=self.max_tokens)
|
| 85 |
+
if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
|
| 86 |
+
req["temperature"] = self.temperature
|
| 87 |
+
if self.extra_body:
|
| 88 |
+
req["extra_body"] = dict(self.extra_body)
|
| 89 |
+
return req
|
| 90 |
+
|
| 91 |
+
def act(self, conv, tools):
|
| 92 |
+
req = self.build_request(conv, tools)
|
| 93 |
+
n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
|
| 94 |
+
for c in m["content"] if c.get("type") == "image_url")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
resp = self.client().chat.completions.create(**req)
|
| 97 |
+
lat = time.time() - t0
|
| 98 |
+
stats = dict(n_images=n_img, n_messages=len(req["messages"]))
|
| 99 |
+
if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
|
| 100 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 101 |
+
error="empty response (no choices)")
|
| 102 |
+
msg = resp.choices[0].message
|
| 103 |
+
rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
|
| 104 |
+
calls = []
|
| 105 |
+
for i, tc in enumerate(msg.tool_calls or []):
|
| 106 |
+
raw = tc.function.arguments or ""
|
| 107 |
+
try:
|
| 108 |
+
args = json.loads(raw) if raw else {}
|
| 109 |
+
except json.JSONDecodeError:
|
| 110 |
+
args = {}
|
| 111 |
+
calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
|
| 112 |
+
u = resp.usage
|
| 113 |
+
ctd = getattr(u, "completion_tokens_details", None) if u else None
|
| 114 |
+
usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
|
| 115 |
+
output_tokens=getattr(u, "completion_tokens", 0) or 0,
|
| 116 |
+
reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
|
| 117 |
+
if not calls and not msg.content and not rc and not u:
|
| 118 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 119 |
+
error="empty response (no output, no usage)")
|
| 120 |
+
return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
|
| 121 |
+
latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tool_results_first(msgs):
|
| 125 |
+
"""OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
|
| 126 |
+
after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
|
| 127 |
+
output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
|
| 128 |
+
messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
|
| 129 |
+
the last tool message of the turn; nothing else changes order."""
|
| 130 |
+
out, i = [], 0
|
| 131 |
+
while i < len(msgs):
|
| 132 |
+
m = msgs[i]
|
| 133 |
+
out.append(m)
|
| 134 |
+
i += 1
|
| 135 |
+
if m["role"] != "assistant" or not m.get("tool_calls"):
|
| 136 |
+
continue
|
| 137 |
+
need = {tc["id"] for tc in m["tool_calls"]}
|
| 138 |
+
held = []
|
| 139 |
+
while i < len(msgs) and need:
|
| 140 |
+
n = msgs[i]
|
| 141 |
+
if n["role"] == "tool" and n.get("tool_call_id") in need:
|
| 142 |
+
out.append(n)
|
| 143 |
+
need.discard(n["tool_call_id"])
|
| 144 |
+
elif n["role"] == "user":
|
| 145 |
+
held.append(n)
|
| 146 |
+
else:
|
| 147 |
+
break
|
| 148 |
+
i += 1
|
| 149 |
+
out.extend(held)
|
| 150 |
+
return out
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/gemini.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Google Gemini backend (Gemini API, official SDK `google-genai`).
|
| 2 |
+
|
| 3 |
+
Same conversation as the other backends, converted to Gemini `contents`:
|
| 4 |
+
- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas;
|
| 5 |
+
- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive)
|
| 6 |
+
and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call;
|
| 7 |
+
- tool outputs of one turn become `function_response` parts at the start of the next user content; images the
|
| 8 |
+
harness attaches after them follow in the same user content;
|
| 9 |
+
- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged;
|
| 10 |
+
- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage).
|
| 11 |
+
|
| 12 |
+
Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock.
|
| 13 |
+
"""
|
| 14 |
+
import base64
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
from ..context import ToolCall, prune_live_images
|
| 18 |
+
from .base import Backend, BackendResponse, import_sdk
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _get(obj, key, default=None):
|
| 22 |
+
if isinstance(obj, dict):
|
| 23 |
+
return obj.get(key, default)
|
| 24 |
+
return getattr(obj, key, default)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _strip_additional(schema):
|
| 28 |
+
"""The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema."""
|
| 29 |
+
if isinstance(schema, dict):
|
| 30 |
+
return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"}
|
| 31 |
+
if isinstance(schema, list):
|
| 32 |
+
return [_strip_additional(v) for v in schema]
|
| 33 |
+
return schema
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _image_part(image, quality=None):
|
| 37 |
+
head, data = image.data_url(quality).split(",", 1)
|
| 38 |
+
mime = head[len("data:"):].split(";", 1)[0]
|
| 39 |
+
return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data)))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class GeminiBackend(Backend):
|
| 43 |
+
name = "gemini"
|
| 44 |
+
|
| 45 |
+
def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True,
|
| 46 |
+
max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90,
|
| 47 |
+
timeout=900.0, client=None):
|
| 48 |
+
self.model = model
|
| 49 |
+
self.thinking_level = thinking_level
|
| 50 |
+
self.thinking_budget = thinking_budget
|
| 51 |
+
self.include_thoughts = include_thoughts
|
| 52 |
+
self.max_output_tokens = max_output_tokens
|
| 53 |
+
self.media_resolution = media_resolution
|
| 54 |
+
self.max_live_images = max_live_images
|
| 55 |
+
self.jpeg_quality = jpeg_quality
|
| 56 |
+
self.timeout = timeout
|
| 57 |
+
self._client = client
|
| 58 |
+
self._json_schema_field = None
|
| 59 |
+
|
| 60 |
+
def config(self):
|
| 61 |
+
return dict(name=self.name, model=self.model, thinking_level=self.thinking_level,
|
| 62 |
+
thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts,
|
| 63 |
+
max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution,
|
| 64 |
+
max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout)
|
| 65 |
+
|
| 66 |
+
def client(self):
|
| 67 |
+
if self._client is None:
|
| 68 |
+
genai = import_sdk("google.genai")
|
| 69 |
+
self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000)))
|
| 70 |
+
return self._client
|
| 71 |
+
|
| 72 |
+
def _declarations(self, specs):
|
| 73 |
+
if self._json_schema_field is None:
|
| 74 |
+
try:
|
| 75 |
+
types = import_sdk("google.genai.types")
|
| 76 |
+
self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields
|
| 77 |
+
except ImportError: # tests without the SDK
|
| 78 |
+
self._json_schema_field = True
|
| 79 |
+
out = []
|
| 80 |
+
for s in specs:
|
| 81 |
+
d = dict(name=s["name"], description=s["description"])
|
| 82 |
+
if self._json_schema_field:
|
| 83 |
+
d["parameters_json_schema"] = s["parameters"]
|
| 84 |
+
else:
|
| 85 |
+
d["parameters"] = _strip_additional(s["parameters"])
|
| 86 |
+
out.append(d)
|
| 87 |
+
return [dict(function_declarations=out)]
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ request
|
| 90 |
+
def convert_items(self, items):
|
| 91 |
+
contents = []
|
| 92 |
+
|
| 93 |
+
def push(role, parts):
|
| 94 |
+
if contents and contents[-1]["role"] == role:
|
| 95 |
+
contents[-1]["parts"].extend(parts)
|
| 96 |
+
else:
|
| 97 |
+
contents.append(dict(role=role, parts=list(parts)))
|
| 98 |
+
|
| 99 |
+
for it in items:
|
| 100 |
+
kind = it["kind"]
|
| 101 |
+
if kind == "user":
|
| 102 |
+
parts = []
|
| 103 |
+
for p in it["parts"]:
|
| 104 |
+
if p["type"] == "text":
|
| 105 |
+
parts.append(dict(text=p["text"]))
|
| 106 |
+
else:
|
| 107 |
+
parts.append(_image_part(p["image"], self.jpeg_quality))
|
| 108 |
+
push("user", parts)
|
| 109 |
+
elif kind == "assistant":
|
| 110 |
+
if it.get("raw") is not None and it.get("backend") == self.name:
|
| 111 |
+
content = dict(it["raw"][0])
|
| 112 |
+
contents.append(dict(role="model", parts=list(content.get("parts") or [])))
|
| 113 |
+
continue
|
| 114 |
+
parts = ([dict(text=it["text"])] if it.get("text") else [])
|
| 115 |
+
parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]]
|
| 116 |
+
push("model", parts or [dict(text="(no output)")])
|
| 117 |
+
elif kind == "tool_output":
|
| 118 |
+
fr = dict(name=it["name"], response=dict(output=it["text"]))
|
| 119 |
+
if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"):
|
| 120 |
+
fr["id"] = it["call_id"]
|
| 121 |
+
push("user", [dict(function_response=fr)])
|
| 122 |
+
else:
|
| 123 |
+
raise ValueError(kind)
|
| 124 |
+
return contents
|
| 125 |
+
|
| 126 |
+
def build_request(self, conv, tools):
|
| 127 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 128 |
+
thinking = dict(include_thoughts=self.include_thoughts)
|
| 129 |
+
if self.thinking_budget is not None:
|
| 130 |
+
thinking["thinking_budget"] = int(self.thinking_budget)
|
| 131 |
+
elif self.thinking_level:
|
| 132 |
+
thinking["thinking_level"] = self.thinking_level
|
| 133 |
+
config = dict(system_instruction=conv.system, tools=self._declarations(tools),
|
| 134 |
+
tool_config=dict(function_calling_config=dict(mode="AUTO")),
|
| 135 |
+
automatic_function_calling=dict(disable=True), thinking_config=thinking,
|
| 136 |
+
max_output_tokens=int(self.max_output_tokens))
|
| 137 |
+
if self.media_resolution:
|
| 138 |
+
config["media_resolution"] = self.media_resolution
|
| 139 |
+
return dict(model=self.model, contents=self.convert_items(items), config=config)
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def request_stats(req):
|
| 143 |
+
n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "")
|
| 144 |
+
for c in req["contents"]:
|
| 145 |
+
for p in c["parts"]:
|
| 146 |
+
p = p if isinstance(p, dict) else {}
|
| 147 |
+
if p.get("inline_data"):
|
| 148 |
+
n_img += 1
|
| 149 |
+
img_bytes += len(p["inline_data"]["data"])
|
| 150 |
+
elif p.get("text"):
|
| 151 |
+
txt += len(p["text"])
|
| 152 |
+
elif p.get("function_response"):
|
| 153 |
+
txt += len(str(p["function_response"].get("response", "")))
|
| 154 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"]))
|
| 155 |
+
|
| 156 |
+
# ------------------------------------------------------------------ call
|
| 157 |
+
def act(self, conv, tools):
|
| 158 |
+
req = self.build_request(conv, tools)
|
| 159 |
+
stats = self.request_stats(req)
|
| 160 |
+
types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys
|
| 161 |
+
t0 = time.time()
|
| 162 |
+
resp = self.client().models.generate_content(
|
| 163 |
+
model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]],
|
| 164 |
+
config=types.GenerateContentConfig.model_validate(req["config"]))
|
| 165 |
+
out = self.parse_response(resp)
|
| 166 |
+
out.latency_s = time.time() - t0
|
| 167 |
+
out.request_stats = stats
|
| 168 |
+
return out
|
| 169 |
+
|
| 170 |
+
def parse_response(self, resp):
|
| 171 |
+
cands = _get(resp, "candidates") or []
|
| 172 |
+
cand = cands[0] if cands else None
|
| 173 |
+
content = _get(cand, "content") if cand is not None else None
|
| 174 |
+
parts = (_get(content, "parts") or []) if content is not None else []
|
| 175 |
+
calls, texts, summ = [], [], []
|
| 176 |
+
for i, p in enumerate(parts):
|
| 177 |
+
fc = _get(p, "function_call")
|
| 178 |
+
if fc is not None:
|
| 179 |
+
cid = _get(fc, "id") or f"gemini_call_{i}"
|
| 180 |
+
calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {})))
|
| 181 |
+
elif _get(p, "text"):
|
| 182 |
+
(summ if _get(p, "thought") else texts).append(_get(p, "text"))
|
| 183 |
+
u = _get(resp, "usage_metadata")
|
| 184 |
+
usage = {}
|
| 185 |
+
if u is not None:
|
| 186 |
+
usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0,
|
| 187 |
+
cached_tokens=_get(u, "cached_content_token_count", 0) or 0,
|
| 188 |
+
output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0),
|
| 189 |
+
reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0)
|
| 190 |
+
finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE"
|
| 191 |
+
status, err = "completed", None
|
| 192 |
+
if not parts:
|
| 193 |
+
status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})"
|
| 194 |
+
elif "MAX_TOKENS" in finish or "MALFORMED" in finish:
|
| 195 |
+
status, err = "incomplete", f"incomplete: finish_reason={finish}"
|
| 196 |
+
elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish:
|
| 197 |
+
status, err = "refusal", f"refusal: finish_reason={finish}"
|
| 198 |
+
if content is not None and hasattr(content, "model_dump"):
|
| 199 |
+
raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes
|
| 200 |
+
elif content is not None:
|
| 201 |
+
raw = [dict(content)]
|
| 202 |
+
else:
|
| 203 |
+
raw = None
|
| 204 |
+
return BackendResponse(tool_calls=calls, text="\n".join(texts) or None,
|
| 205 |
+
reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw,
|
| 206 |
+
status=status, error=err)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/openai_responses.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI Responses API backend (default model gpt-6-astra).
|
| 2 |
+
|
| 3 |
+
Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
|
| 4 |
+
store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
|
| 5 |
+
of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
|
| 6 |
+
packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
|
| 7 |
+
OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
|
| 8 |
+
|
| 9 |
+
Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
|
| 10 |
+
the client is created lazily on the first real call (tests inject a mock client).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
from ..context import ToolCall, prune_live_images
|
| 17 |
+
from .base import Backend, BackendResponse, import_openai
|
| 18 |
+
|
| 19 |
+
# GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
|
| 20 |
+
GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get(obj, key, default=None):
|
| 24 |
+
if isinstance(obj, dict):
|
| 25 |
+
return obj.get(key, default)
|
| 26 |
+
return getattr(obj, key, default)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _to_dict(item):
|
| 30 |
+
if isinstance(item, dict):
|
| 31 |
+
return dict(item)
|
| 32 |
+
if hasattr(item, "to_dict"):
|
| 33 |
+
return item.to_dict(mode="json")
|
| 34 |
+
if hasattr(item, "model_dump"):
|
| 35 |
+
return item.model_dump(mode="json", exclude_none=True)
|
| 36 |
+
return dict(vars(item))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def responses_tools(specs, strict=True):
|
| 40 |
+
return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
|
| 41 |
+
strict=strict) for s in specs]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class OpenAIResponsesBackend(Backend):
|
| 45 |
+
name = "openai"
|
| 46 |
+
|
| 47 |
+
def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
|
| 48 |
+
max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
|
| 49 |
+
store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
|
| 50 |
+
max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
|
| 51 |
+
prompt_cache_options=None, client=None, http_client=None):
|
| 52 |
+
if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
|
| 53 |
+
raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
|
| 54 |
+
f"got {reasoning_effort!r}")
|
| 55 |
+
self.model = model
|
| 56 |
+
self.reasoning_effort = reasoning_effort
|
| 57 |
+
self.reasoning_summary = reasoning_summary
|
| 58 |
+
self.image_detail = image_detail
|
| 59 |
+
self.max_output_tokens = max_output_tokens
|
| 60 |
+
self.service_tier = service_tier
|
| 61 |
+
self.prompt_cache_key = prompt_cache_key
|
| 62 |
+
self.prompt_cache_retention = prompt_cache_retention
|
| 63 |
+
self.store = store
|
| 64 |
+
self.replay_reasoning = replay_reasoning
|
| 65 |
+
self.max_live_images = max_live_images
|
| 66 |
+
self.jpeg_quality = jpeg_quality
|
| 67 |
+
self.timeout = timeout
|
| 68 |
+
self.max_retries = max_retries
|
| 69 |
+
self.extra_body = extra_body
|
| 70 |
+
self.strict_tools = strict_tools
|
| 71 |
+
# explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
|
| 72 |
+
assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
|
| 73 |
+
self.cache_breakpoints = cache_breakpoints
|
| 74 |
+
self.prompt_cache_options = prompt_cache_options
|
| 75 |
+
self._client = client
|
| 76 |
+
self._http_client = http_client # optional custom transport (tests, proxies)
|
| 77 |
+
self._cache_key = prompt_cache_key
|
| 78 |
+
|
| 79 |
+
def config(self):
|
| 80 |
+
return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
|
| 81 |
+
reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
|
| 82 |
+
max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
|
| 83 |
+
prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
|
| 84 |
+
store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
|
| 85 |
+
jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
|
| 86 |
+
extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
|
| 87 |
+
prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ client
|
| 90 |
+
def client(self):
|
| 91 |
+
if self._client is None:
|
| 92 |
+
key = os.environ.get("OPENAI_API_KEY")
|
| 93 |
+
if not key:
|
| 94 |
+
raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
|
| 95 |
+
openai = import_openai()
|
| 96 |
+
kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
|
| 97 |
+
max_retries=self.max_retries)
|
| 98 |
+
if self._http_client is not None:
|
| 99 |
+
kw["http_client"] = self._http_client
|
| 100 |
+
self._client = openai.OpenAI(**kw)
|
| 101 |
+
return self._client
|
| 102 |
+
|
| 103 |
+
def begin_run(self, info):
|
| 104 |
+
if self.prompt_cache_key is None:
|
| 105 |
+
# route all calls of one run to the same cache shard
|
| 106 |
+
self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
|
| 107 |
+
|
| 108 |
+
# ------------------------------------------------------------------ request
|
| 109 |
+
def convert_items(self, items):
|
| 110 |
+
out = []
|
| 111 |
+
last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
|
| 112 |
+
for i, it in enumerate(items):
|
| 113 |
+
kind = it["kind"]
|
| 114 |
+
if kind == "user":
|
| 115 |
+
content = []
|
| 116 |
+
for p in it["parts"]:
|
| 117 |
+
if p["type"] == "text":
|
| 118 |
+
content.append(dict(type="input_text", text=p["text"]))
|
| 119 |
+
else:
|
| 120 |
+
content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
|
| 121 |
+
detail=self.image_detail))
|
| 122 |
+
# explicit cache breakpoints: end of the stable history item (byte-identical for the whole
|
| 123 |
+
# attempt) and end of the newest input (reused by the next call of the attempt)
|
| 124 |
+
if content and ((self.cache_breakpoints != "none" and not it.get("live"))
|
| 125 |
+
or (self.cache_breakpoints == "history+last" and i == last_user)):
|
| 126 |
+
content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
|
| 127 |
+
out.append(dict(role="user", content=content))
|
| 128 |
+
elif kind == "assistant":
|
| 129 |
+
if it.get("raw") and it.get("backend") == self.name:
|
| 130 |
+
for r in it["raw"]:
|
| 131 |
+
if r.get("type") == "reasoning" and not self.replay_reasoning:
|
| 132 |
+
continue
|
| 133 |
+
out.append(r)
|
| 134 |
+
else:
|
| 135 |
+
if it.get("text"):
|
| 136 |
+
out.append(dict(role="assistant", content=it["text"]))
|
| 137 |
+
for tc in it["tool_calls"]:
|
| 138 |
+
out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
|
| 139 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 140 |
+
elif kind == "tool_output":
|
| 141 |
+
out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
|
| 142 |
+
else:
|
| 143 |
+
raise ValueError(kind)
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
def build_request(self, conv, tools):
|
| 147 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 148 |
+
req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
|
| 149 |
+
tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
|
| 150 |
+
store=self.store)
|
| 151 |
+
reasoning = dict(effort=self.reasoning_effort)
|
| 152 |
+
if self.reasoning_summary:
|
| 153 |
+
reasoning["summary"] = self.reasoning_summary
|
| 154 |
+
req["reasoning"] = reasoning
|
| 155 |
+
if not self.store and self.replay_reasoning:
|
| 156 |
+
req["include"] = ["reasoning.encrypted_content"]
|
| 157 |
+
if self.max_output_tokens:
|
| 158 |
+
req["max_output_tokens"] = int(self.max_output_tokens)
|
| 159 |
+
if self.service_tier:
|
| 160 |
+
req["service_tier"] = self.service_tier
|
| 161 |
+
if self._cache_key:
|
| 162 |
+
req["prompt_cache_key"] = self._cache_key
|
| 163 |
+
if self.prompt_cache_retention:
|
| 164 |
+
req["prompt_cache_retention"] = self.prompt_cache_retention
|
| 165 |
+
if self.prompt_cache_options:
|
| 166 |
+
req["prompt_cache_options"] = dict(self.prompt_cache_options)
|
| 167 |
+
if self.extra_body:
|
| 168 |
+
req["extra_body"] = dict(self.extra_body)
|
| 169 |
+
return req
|
| 170 |
+
|
| 171 |
+
@staticmethod
|
| 172 |
+
def request_stats(req):
|
| 173 |
+
n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
|
| 174 |
+
for it in req["input"]:
|
| 175 |
+
for c in (it.get("content") if isinstance(it.get("content"), list) else []):
|
| 176 |
+
if c.get("type") == "input_image":
|
| 177 |
+
n_img += 1
|
| 178 |
+
img_bytes += len(c["image_url"])
|
| 179 |
+
elif "text" in c:
|
| 180 |
+
txt += len(c["text"])
|
| 181 |
+
if isinstance(it.get("content"), str):
|
| 182 |
+
txt += len(it["content"])
|
| 183 |
+
if it.get("type") == "function_call_output":
|
| 184 |
+
txt += len(it["output"]) if isinstance(it["output"], str) else 0
|
| 185 |
+
if it.get("type") == "function_call":
|
| 186 |
+
txt += len(it.get("arguments", ""))
|
| 187 |
+
tools_chars = len(json.dumps(req.get("tools", [])))
|
| 188 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
|
| 189 |
+
n_input_items=len(req["input"]))
|
| 190 |
+
|
| 191 |
+
# ------------------------------------------------------------------ call
|
| 192 |
+
def act(self, conv, tools):
|
| 193 |
+
req = self.build_request(conv, tools)
|
| 194 |
+
stats = self.request_stats(req)
|
| 195 |
+
t0 = time.time()
|
| 196 |
+
resp = self.client().responses.create(**req)
|
| 197 |
+
out = self.parse_response(resp)
|
| 198 |
+
out.latency_s = time.time() - t0
|
| 199 |
+
out.request_stats = stats
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
def parse_response(self, resp):
|
| 203 |
+
calls, texts, summ = [], [], []
|
| 204 |
+
output = _get(resp, "output") or []
|
| 205 |
+
for item in output:
|
| 206 |
+
t = _get(item, "type")
|
| 207 |
+
if t == "function_call":
|
| 208 |
+
raw = _get(item, "arguments") or ""
|
| 209 |
+
try:
|
| 210 |
+
args = json.loads(raw) if raw else {}
|
| 211 |
+
except json.JSONDecodeError:
|
| 212 |
+
args = {}
|
| 213 |
+
calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
|
| 214 |
+
raw_arguments=raw))
|
| 215 |
+
elif t == "message":
|
| 216 |
+
for c in _get(item, "content") or []:
|
| 217 |
+
if _get(c, "type") == "output_text":
|
| 218 |
+
texts.append(_get(c, "text") or "")
|
| 219 |
+
elif t == "reasoning":
|
| 220 |
+
for s in _get(item, "summary") or []:
|
| 221 |
+
summ.append(_get(s, "text") or "")
|
| 222 |
+
u = _get(resp, "usage")
|
| 223 |
+
usage = {}
|
| 224 |
+
if u is not None:
|
| 225 |
+
itd = _get(u, "input_tokens_details")
|
| 226 |
+
otd = _get(u, "output_tokens_details")
|
| 227 |
+
usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
|
| 228 |
+
cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
|
| 229 |
+
cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
|
| 230 |
+
output_tokens=_get(u, "output_tokens", 0) or 0,
|
| 231 |
+
reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
|
| 232 |
+
status = _get(resp, "status") or "completed"
|
| 233 |
+
err = None
|
| 234 |
+
if status == "incomplete":
|
| 235 |
+
err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
|
| 236 |
+
elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
|
| 237 |
+
status, err = "incomplete", "empty response (no output, no usage)"
|
| 238 |
+
return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
|
| 239 |
+
reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
|
| 240 |
+
raw=[_to_dict(i) for i in output], status=status, error=err)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/agent/backends/scripted.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scripted backend: no model. Runs a task's scripted reference policy (adaptive by default) through the
|
| 2 |
+
agent tool interface, to test the harness end to end.
|
| 3 |
+
|
| 4 |
+
How: the task's own `execute(inst, params)` runs in a worker thread with `task.sk` replaced by a proxy.
|
| 5 |
+
Every Skills primitive it calls (move_to / set_gripper / push / grasp_at / place_at) becomes an agent
|
| 6 |
+
tool call that is handed to the harness, executed by the ToolExecutor on the main thread, and its
|
| 7 |
+
report is returned to the worker. Only one thread runs at a time (queues hand control back and forth),
|
| 8 |
+
so MuJoCo is never touched concurrently. Only schema-valid tool calls are emitted, so this also shows
|
| 9 |
+
that the tool interface is expressive enough for the task.
|
| 10 |
+
|
| 11 |
+
The scripted policy is privileged: it reads the instance (layout) like the task's reference policies
|
| 12 |
+
do. It sees earlier attempts only through the memory mode chosen by the harness and only the outcome
|
| 13 |
+
fields allowed by the feedback level (F2: structured measurement, F1: success flag, F0: nothing); if
|
| 14 |
+
the adaptive rule cannot run on what it sees, it falls back to the task's blind retry rule.
|
| 15 |
+
Supported: cross-protocol tasks that implement execute/default_params/adapt_params (+ oracle/blind).
|
| 16 |
+
"""
|
| 17 |
+
import math
|
| 18 |
+
import queue
|
| 19 |
+
import threading
|
| 20 |
+
import traceback
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ..context import ToolCall
|
| 25 |
+
from .base import Backend, BackendResponse
|
| 26 |
+
|
| 27 |
+
TIMEOUT_S = 600
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class _Abort(Exception):
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class _Channel:
|
| 35 |
+
def __init__(self):
|
| 36 |
+
self.req = queue.Queue()
|
| 37 |
+
self.res = queue.Queue()
|
| 38 |
+
|
| 39 |
+
def call(self, name, args): # worker side
|
| 40 |
+
self.req.put(("call", name, args))
|
| 41 |
+
kind, payload = self.res.get(timeout=TIMEOUT_S)
|
| 42 |
+
if kind == "abort":
|
| 43 |
+
raise _Abort()
|
| 44 |
+
return payload
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class SkillsProxy:
|
| 48 |
+
"""Stands in for task.sk inside task.execute(); primitives become agent tool calls."""
|
| 49 |
+
|
| 50 |
+
def __init__(self, real, channel):
|
| 51 |
+
self._real = real
|
| 52 |
+
self._ch = channel
|
| 53 |
+
self.untooled_hold_steps = 0
|
| 54 |
+
self.ignored_wrap_yaw_false = 0
|
| 55 |
+
|
| 56 |
+
def move_to(self, target, yaw=None, speed=None, tol=None, max_steps=None, apply_bias=True, wrap_yaw=True):
|
| 57 |
+
if not wrap_yaw: # the move_to tool always wraps yaw mod pi (Skills default); counted, not fatal
|
| 58 |
+
self.ignored_wrap_yaw_false += 1
|
| 59 |
+
if not apply_bias:
|
| 60 |
+
raise NotImplementedError("apply_bias=False cannot be expressed through the agent tools")
|
| 61 |
+
yaw_deg = math.degrees(self._real.yaw if yaw is None else float(yaw))
|
| 62 |
+
rep = self._ch.call("move_to", dict(x=float(target[0]), y=float(target[1]), z=float(target[2]),
|
| 63 |
+
yaw=round(yaw_deg, 3), speed=None if speed is None else float(speed)))
|
| 64 |
+
return dict(prim="move_to", reached=rep.get("reached"), pos=rep.get("eef_pos"))
|
| 65 |
+
|
| 66 |
+
def set_gripper(self, close, steps=15):
|
| 67 |
+
rep = self._ch.call("close_gripper" if close else "open_gripper", {})
|
| 68 |
+
return dict(prim="close" if close else "open", width=rep.get("gripper_width_m"))
|
| 69 |
+
|
| 70 |
+
def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
|
| 71 |
+
rep = self._ch.call("push", dict(x=float(start_xy[0]), y=float(start_xy[1]), dir_x=float(direction_xy[0]),
|
| 72 |
+
dir_y=float(direction_xy[1]), distance=float(distance), speed=float(speed),
|
| 73 |
+
z=None if z is None else float(z), runup=float(pre)))
|
| 74 |
+
return dict(prim="push", reached=rep.get("sweep_reached"), pos=rep.get("eef_pos"))
|
| 75 |
+
|
| 76 |
+
def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
|
| 77 |
+
self.set_gripper(False, steps=5)
|
| 78 |
+
self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
|
| 79 |
+
self.move_to([xy[0], xy[1], z_grasp])
|
| 80 |
+
self.set_gripper(True)
|
| 81 |
+
self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
|
| 82 |
+
|
| 83 |
+
def place_at(self, xy, z_release, approach=0.10):
|
| 84 |
+
self.move_to([xy[0], xy[1], z_release + approach])
|
| 85 |
+
self.move_to([xy[0], xy[1], z_release])
|
| 86 |
+
self.set_gripper(False)
|
| 87 |
+
self.move_to([xy[0], xy[1], z_release + approach])
|
| 88 |
+
|
| 89 |
+
def hold(self, steps=10):
|
| 90 |
+
# waiting in place has no tool; executed directly (only physics, no new command) and counted
|
| 91 |
+
self.untooled_hold_steps += int(steps)
|
| 92 |
+
self._real.hold(steps)
|
| 93 |
+
|
| 94 |
+
def __getattr__(self, k): # eef_pos, eef_mat, gripper_width, holding, yaw, ...
|
| 95 |
+
return getattr(self._real, k)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ScriptedBackend(Backend):
|
| 99 |
+
name = "scripted"
|
| 100 |
+
|
| 101 |
+
def __init__(self, policy="adaptive", seed=0):
|
| 102 |
+
assert policy in ("adaptive", "naive", "oracle", "blind"), policy
|
| 103 |
+
self.policy = policy
|
| 104 |
+
self.seed = seed
|
| 105 |
+
self.info = None
|
| 106 |
+
self.rng = None
|
| 107 |
+
|
| 108 |
+
def config(self):
|
| 109 |
+
return dict(name=self.name, policy=self.policy, seed=self.seed)
|
| 110 |
+
|
| 111 |
+
def begin_run(self, info):
|
| 112 |
+
if info.protocol != "cross":
|
| 113 |
+
raise NotImplementedError("ScriptedBackend supports cross-protocol tasks only (execute/adapt_params)")
|
| 114 |
+
self.info = info
|
| 115 |
+
self.rng = np.random.default_rng(self.seed + info.seed)
|
| 116 |
+
self._oracle = None
|
| 117 |
+
if self.policy == "oracle": # privileged scratch rollouts happen before the harness resets the scene
|
| 118 |
+
self._oracle = info.task.oracle_params(info.inst)
|
| 119 |
+
|
| 120 |
+
# ------------------------------------------------------------------ params from visible history
|
| 121 |
+
def _visible(self, rec):
|
| 122 |
+
out = rec.outcome
|
| 123 |
+
if self.info.feedback == "F2":
|
| 124 |
+
vis = dict(out)
|
| 125 |
+
elif self.info.feedback == "F1":
|
| 126 |
+
vis = dict(success=out.get("success"))
|
| 127 |
+
else:
|
| 128 |
+
vis = {}
|
| 129 |
+
return dict(attempt=rec.attempt, params=rec.backend_meta.get("params"), outcome=vis)
|
| 130 |
+
|
| 131 |
+
def _params(self, attempt, history):
|
| 132 |
+
task, inst = self.info.task, self.info.inst
|
| 133 |
+
if self.policy == "oracle":
|
| 134 |
+
return dict(self._oracle), "oracle"
|
| 135 |
+
if self.policy == "naive" or not history and self.policy == "adaptive":
|
| 136 |
+
return task.default_params(inst), "default"
|
| 137 |
+
if self.policy == "blind":
|
| 138 |
+
if attempt == 1:
|
| 139 |
+
return task.default_params(inst), "default"
|
| 140 |
+
return task.blind_params(inst, attempt - 1, self.rng), "blind"
|
| 141 |
+
hist = [self._visible(r) for r in history if r.backend_meta.get("params") is not None]
|
| 142 |
+
if not hist:
|
| 143 |
+
return task.blind_params(inst, attempt - 1, self.rng), "blind(no usable history)"
|
| 144 |
+
try:
|
| 145 |
+
return task.adapt_params(inst, hist), "adapt"
|
| 146 |
+
except (KeyError, TypeError, ValueError):
|
| 147 |
+
return task.blind_params(inst, attempt - 1, self.rng), "blind(feedback too coarse)"
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------------ attempt
|
| 150 |
+
def begin_attempt(self, ainfo):
|
| 151 |
+
self.params, self.rule = self._params(ainfo.attempt, ainfo.history)
|
| 152 |
+
self.ch = _Channel()
|
| 153 |
+
self.thread = None
|
| 154 |
+
self.pending = False
|
| 155 |
+
self.last_report = None
|
| 156 |
+
self.n = 0
|
| 157 |
+
self.proxy = None
|
| 158 |
+
|
| 159 |
+
def _worker(self):
|
| 160 |
+
try:
|
| 161 |
+
self.info.task.execute(self.info.inst, self.params)
|
| 162 |
+
self.ch.req.put(("finished", None))
|
| 163 |
+
except _Abort:
|
| 164 |
+
pass
|
| 165 |
+
except Exception:
|
| 166 |
+
self.ch.req.put(("error", traceback.format_exc()))
|
| 167 |
+
|
| 168 |
+
def act(self, conv, tools):
|
| 169 |
+
if self.thread is None:
|
| 170 |
+
task = self.info.task
|
| 171 |
+
self.real_sk = task.sk
|
| 172 |
+
self.proxy = SkillsProxy(task.sk, self.ch)
|
| 173 |
+
task.sk = self.proxy
|
| 174 |
+
self.thread = threading.Thread(target=self._worker, daemon=True)
|
| 175 |
+
self.thread.start()
|
| 176 |
+
elif self.pending:
|
| 177 |
+
self.ch.res.put(("result", self.last_report or {}))
|
| 178 |
+
self.pending = False
|
| 179 |
+
kind, *rest = self.ch.req.get(timeout=TIMEOUT_S)
|
| 180 |
+
self.n += 1
|
| 181 |
+
if kind == "call":
|
| 182 |
+
name, args = rest[0], rest[1]
|
| 183 |
+
self.pending = True
|
| 184 |
+
tc = ToolCall(id=f"scripted_{self.n}", name=name, arguments=args)
|
| 185 |
+
text = None
|
| 186 |
+
if self.n == 1:
|
| 187 |
+
text = f"[scripted {self.policy}: rule={self.rule}, params={self.params}]"
|
| 188 |
+
return BackendResponse(tool_calls=[tc], text=text)
|
| 189 |
+
if kind == "finished":
|
| 190 |
+
return BackendResponse(tool_calls=[ToolCall(id=f"scripted_{self.n}", name="done",
|
| 191 |
+
arguments=dict(reason=f"scripted {self.policy} policy finished "
|
| 192 |
+
f"with params {self.params}"))])
|
| 193 |
+
raise RuntimeError("scripted policy crashed:\n" + str(rest[0]))
|
| 194 |
+
|
| 195 |
+
def on_tool_result(self, call, result):
|
| 196 |
+
self.last_report = result.report
|
| 197 |
+
|
| 198 |
+
def end_attempt(self):
|
| 199 |
+
if self.thread is not None:
|
| 200 |
+
if self.thread.is_alive():
|
| 201 |
+
if self.pending:
|
| 202 |
+
self.ch.res.put(("abort", None))
|
| 203 |
+
self.thread.join(timeout=30)
|
| 204 |
+
self.info.task.sk = self.real_sk
|
| 205 |
+
meta = dict(policy=self.policy, rule=self.rule, params=self.params)
|
| 206 |
+
if self.proxy is not None and self.proxy.untooled_hold_steps:
|
| 207 |
+
meta["untooled_hold_steps"] = self.proxy.untooled_hold_steps
|
| 208 |
+
if self.proxy is not None and self.proxy.ignored_wrap_yaw_false:
|
| 209 |
+
meta["ignored_wrap_yaw_false"] = self.proxy.ignored_wrap_yaw_false
|
| 210 |
+
return meta
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-task specs for the controlled arms of full5 (2026-10-12, docs/14 §6).
|
| 2 |
+
|
| 3 |
+
One module per task, named exactly like the task (lffbench/arm_specs/<task_name>.py), defining:
|
| 4 |
+
|
| 5 |
+
HIDDEN_KEYS : tuple of instance keys that carry the hidden variable(s)
|
| 6 |
+
h0(inst) -> dict overrides for the H0 twin: same layout, hidden variable at its "ordinary" value, so the
|
| 7 |
+
common-sense first attempt succeeds (scripted naive succeeds)
|
| 8 |
+
twin(inst) -> dict overrides for the mismatched-history source: same layout, the trap is still active (scripted
|
| 9 |
+
naive still fails, visibly) but the right correction is different from the original instance's,
|
| 10 |
+
ideally opposite (e.g. centre of mass on the other side)
|
| 11 |
+
reveal(inst)-> str H+ text appended to the task instruction: the hidden variable stated plainly in robot-frame
|
| 12 |
+
words a careful human could act on, without prescribing the solution
|
| 13 |
+
|
| 14 |
+
All three take the ORIGINAL sampled instance and return only the keys to change (JSON-serialisable). The server
|
| 15 |
+
applies them with dict.update() after sample_instance(); reset_instance() must honour them.
|
| 16 |
+
"""
|
| 17 |
+
import importlib
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load(task_name):
|
| 21 |
+
"""The spec module for task_name, or None if the task has no controlled-arm spec."""
|
| 22 |
+
try:
|
| 23 |
+
return importlib.import_module(f"{__name__}.{task_name}")
|
| 24 |
+
except ModuleNotFoundError as e:
|
| 25 |
+
if e.name == f"{__name__}.{task_name}":
|
| 26 |
+
return None
|
| 27 |
+
raise
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def overrides(task_name, arm, inst):
|
| 31 |
+
"""Instance overrides for arm in (h0, twin); {} for other arms."""
|
| 32 |
+
if arm not in ("h0", "twin"):
|
| 33 |
+
return {}
|
| 34 |
+
spec = load(task_name)
|
| 35 |
+
if spec is None:
|
| 36 |
+
raise SystemExit(f"--arm {arm}: no spec in lffbench/arm_specs/{task_name}.py")
|
| 37 |
+
return getattr(spec, arm)(inst)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def reveal(task_name, inst):
|
| 41 |
+
spec = load(task_name)
|
| 42 |
+
if spec is None:
|
| 43 |
+
raise SystemExit(f"--arm hplus: no spec in lffbench/arm_specs/{task_name}.py")
|
| 44 |
+
return spec.reveal(inst)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def fix(task_name, inst, params):
|
| 48 |
+
"""Fix-rung text of the layer-3 feedback ladder (docs/20): how to succeed on this instance, in robot-frame words,
|
| 49 |
+
built from the task's oracle parameters `params` (task.oracle_params(inst), computed by the caller with the sim)."""
|
| 50 |
+
spec = load(task_name)
|
| 51 |
+
if spec is None or not hasattr(spec, "fix"):
|
| 52 |
+
raise SystemExit(f"ladder fix: no fix() in lffbench/arm_specs/{task_name}.py")
|
| 53 |
+
return spec.fix(inst, params)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled-arm spec for l2_turntable_restore (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only
|
| 4 |
+
thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the
|
| 5 |
+
shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the
|
| 6 |
+
butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the
|
| 7 |
+
start angle from the simulator, so overriding "q0" alone is enough.
|
| 8 |
+
|
| 9 |
+
Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis)
|
| 10 |
+
and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side).
|
| 11 |
+
Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|.
|
| 12 |
+
|
| 13 |
+
h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn
|
| 14 |
+
(T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds.
|
| 15 |
+
NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half).
|
| 16 |
+
twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc
|
| 17 |
+
the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the
|
| 18 |
+
correction (turn back) has the opposite sign; the twin's start angle differs from the original's by
|
| 19 |
+
35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here.
|
| 20 |
+
reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words
|
| 21 |
+
(forward = away from the robot, counter-clockwise as in the F2 feedback).
|
| 22 |
+
"""
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
HIDDEN_KEYS = ("q0",)
|
| 26 |
+
|
| 27 |
+
TARGET = "butter_1"
|
| 28 |
+
PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ
|
| 29 |
+
TWIN_OFF = np.radians(35.0)
|
| 30 |
+
STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _wrap(a):
|
| 34 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _geom(inst):
|
| 38 |
+
th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET])
|
| 39 |
+
return th, tilt, -np.pi / 2 - tilt
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def h0(inst):
|
| 43 |
+
th, tilt, _ = _geom(inst)
|
| 44 |
+
return {"q0": _wrap(PICK_AZ - tilt - th)}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def twin(inst):
|
| 48 |
+
th, tilt, flip = _geom(inst)
|
| 49 |
+
s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0
|
| 50 |
+
return {"q0": _wrap(flip - s * TWIN_OFF - th)}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _compass(deg):
|
| 54 |
+
names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right")
|
| 55 |
+
return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def reveal(inst):
|
| 59 |
+
az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
|
| 60 |
+
side = "counter-clockwise" if az >= 0 else "clockwise"
|
| 61 |
+
return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's "
|
| 62 |
+
f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the "
|
| 63 |
+
f"turntable is at now.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def fix(inst, params):
|
| 67 |
+
"""Ladder Fix rung (docs/20): the oracle turns the disc back to the saved start angle after the butter is out."""
|
| 68 |
+
az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
|
| 69 |
+
side = "counter-clockwise" if az >= 0 else "clockwise"
|
| 70 |
+
return (f"A way to succeed: after the butter is in the basket, turn the turntable back to its start angle before "
|
| 71 |
+
f"you finish. At the start, seen from above, the yellow stripe pointed {abs(az):.0f} deg {side} from "
|
| 72 |
+
f"straight forward (roughly {_compass(az)}). Grasp a red peg and move the gripper along the rim to turn "
|
| 73 |
+
f"the disc until the stripe points that way again (within 15 deg), then release the peg and finish.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into
|
| 4 |
+
the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw);
|
| 5 |
+
`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent.
|
| 6 |
+
No override changes geometry, mass or inertia, so no bounding-volume refit is involved.
|
| 7 |
+
|
| 8 |
+
h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end,
|
| 9 |
+
so the common-sense "slide the nearest end out" slides the light end and succeeds.
|
| 10 |
+
twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored
|
| 11 |
+
through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in
|
| 12 |
+
the end that is now nearest. The right correction (slide the other, light end) is then over the opposite
|
| 13 |
+
edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a
|
| 14 |
+
card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card);
|
| 15 |
+
see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end
|
| 16 |
+
(naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near
|
| 17 |
+
end and the heavy edge is again the opposite one.
|
| 18 |
+
reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words.
|
| 19 |
+
"""
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge")
|
| 23 |
+
|
| 24 |
+
OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
|
| 25 |
+
GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left",
|
| 26 |
+
"right": "on the robot's right"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _wrap(a):
|
| 30 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def h0(inst):
|
| 34 |
+
if not inst["heavy_near"]:
|
| 35 |
+
return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out)
|
| 36 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def twin(inst):
|
| 40 |
+
if not inst["heavy_near"]:
|
| 41 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"])
|
| 42 |
+
a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side
|
| 43 |
+
c = list(inst["card_xy"])
|
| 44 |
+
c[a] = 2.0 * inst["shelf_xy"][a] - c[a]
|
| 45 |
+
yaw = inst["card_yaw"]
|
| 46 |
+
yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading
|
| 47 |
+
return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]],
|
| 48 |
+
far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reveal(inst):
|
| 52 |
+
e = inst["heavy_edge"]
|
| 53 |
+
return (f"The card is not uniform: 8 g of its 10 g are a weight hidden in the end that points towards the shelf's "
|
| 54 |
+
f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fix(inst, params):
|
| 58 |
+
"""Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin."""
|
| 59 |
+
light = OPPOSITE[inst["heavy_edge"]]
|
| 60 |
+
return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards "
|
| 61 |
+
f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the "
|
| 62 |
+
f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two "
|
| 63 |
+
f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out "
|
| 64 |
+
f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the "
|
| 65 |
+
f"card's height, lift it and drop the card into the bin.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_under_table_tool (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["pane_side"] -- the y side of the low glass table that is closed by an invisible clear acrylic
|
| 4 |
+
panel (+1 = robot's left, -1 = right; sampled as -side, i.e. the side away from the stick, where the bin stands).
|
| 5 |
+
apply_instance turns on the collision of the panel whose side equals pane_side (inst.get("pane_side", -side)); a
|
| 6 |
+
value matching neither side (0) leaves both panels off.
|
| 7 |
+
|
| 8 |
+
h0 pane_side = 0: no panel. The prior (slide the stick in and push the cube straight across, out towards the bin)
|
| 9 |
+
gets the cube out on the bin's side, then grasps it and drops it in the bin.
|
| 10 |
+
twin pane_side = side: the panel closes the OTHER y side -- the side the stick lies on -- instead of the bin's side.
|
| 11 |
+
The prior still fails visibly, but differently: the stick's head runs into the panel at the table edge and
|
| 12 |
+
the cube is not touched / stays under the glass (original: the cube is pushed across and stops against the
|
| 13 |
+
panel at the bin's side). The blocked side is the opposite one. Measured (seeds 3000-3004): twin naive fails
|
| 14 |
+
5/5 with F2 mode "blocked" (stick stopped at the panel, the hand ran into the glass edge, cube did not move).
|
| 15 |
+
Limitation: with a single panel on a y side, the reference correction is the same in both (push the cube out
|
| 16 |
+
of the open FRONT side from behind the table; oracle_params ignores the instance), so the cross check
|
| 17 |
+
"twin oracle on the original" succeeds (measured 5/5). A twin whose correction fails on the original would need a second
|
| 18 |
+
panel / panels on the front or back side plus a new scripted push (task-file change); not done.
|
| 19 |
+
reveal Which side is closed, in the words of the task's F2 feedback.
|
| 20 |
+
"""
|
| 21 |
+
HIDDEN_KEYS = ("pane_side",)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _pane_side(inst):
|
| 25 |
+
return int(inst.get("pane_side", -inst["side"]))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def h0(inst):
|
| 29 |
+
return {"pane_side": 0}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def twin(inst):
|
| 33 |
+
return {"pane_side": -_pane_side(inst)}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def reveal(inst):
|
| 37 |
+
ps = _pane_side(inst)
|
| 38 |
+
lr = "the robot's left" if ps > 0 else "the robot's right"
|
| 39 |
+
return (f"A clear acrylic panel, invisible in the camera images, closes the side of the low glass table on {lr} "
|
| 40 |
+
f"(between its two legs, from the tabletop up to the glass); nothing can pass under the table edge on that "
|
| 41 |
+
f"side.")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def fix(inst, params):
|
| 45 |
+
"""Ladder Fix rung (docs/20): oracle mode front -- push the cube out of the low table's front side with the stick."""
|
| 46 |
+
return ("A way to succeed: do not push the cube out on the panel's side. Pick the stick up, turn it in the air so "
|
| 47 |
+
"that it points forward (away from the robot), put it down on the table behind the low table (on the "
|
| 48 |
+
"robot's side), in line with the cube. Grasp it again near its handle end and slide it straight forward "
|
| 49 |
+
"under the glass top so that its head pushes the cube out of the low table's front side (the side away "
|
| 50 |
+
"from the robot). Then pull the stick back, put it down, grasp the cube and put it into the bin.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_wall_flush (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a
|
| 4 |
+
finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it
|
| 5 |
+
(wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"],
|
| 6 |
+
so every override below sets wall_xy as well.
|
| 7 |
+
|
| 8 |
+
h0 gap = 5 cm: box, plate, wall length and wall y unchanged, the wall moved 4.7-5 cm away from the box (on the
|
| 9 |
+
same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works.
|
| 10 |
+
(2.5 cm was not enough: the open fingers reach 6.6 cm from the grasp centre, so with the wall on the far side
|
| 11 |
+
the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.)
|
| 12 |
+
twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid
|
| 13 |
+
along y so that the box sits near the OTHER end of the wall, 2 cm of wall beyond the box's end (the sampler's
|
| 14 |
+
extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the
|
| 15 |
+
wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm).
|
| 16 |
+
Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross
|
| 17 |
+
check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/
|
| 18 |
+
validate.json). The twin changes which way to push, not whether pushing works.
|
| 19 |
+
reveal The gap, and on which side of the box the wall is, in the task's F2 frame words.
|
| 20 |
+
"""
|
| 21 |
+
BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015
|
| 22 |
+
H0_GAP = 0.05
|
| 23 |
+
|
| 24 |
+
HIDDEN_KEYS = ("gap",)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _wall_x(inst, gap):
|
| 28 |
+
return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def h0(inst):
|
| 32 |
+
return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def twin(inst):
|
| 36 |
+
wy, by = inst["wall_xy"][1], inst["box_xy"][1]
|
| 37 |
+
u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02
|
| 38 |
+
nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end
|
| 39 |
+
u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end
|
| 40 |
+
return {"wall_xy": [inst["wall_xy"][0], by - u_twin]}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def reveal(inst):
|
| 44 |
+
side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)"
|
| 45 |
+
return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box "
|
| 46 |
+
f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def fix(inst, params):
|
| 50 |
+
"""Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then
|
| 51 |
+
grasp across the width and place."""
|
| 52 |
+
end, margin = int(params["end"]), float(params["margin"])
|
| 53 |
+
wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1])
|
| 54 |
+
wall_end = wy + hl if end > 0 else wy - hl
|
| 55 |
+
dist = max(0.0, end * (wall_end + end * margin - by))
|
| 56 |
+
side, other = ("left", "right") if end > 0 else ("right", "left")
|
| 57 |
+
return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the "
|
| 58 |
+
f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide "
|
| 59 |
+
f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, "
|
| 60 |
+
f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the "
|
| 61 |
+
f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l4_fit_container.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l4_fit_container (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["cap"] -- clear (unrendered) bumper caps on both ends of the phone, 0.8-0.9 cm each, so the
|
| 4 |
+
phone is 1.6-1.8 cm longer than it looks. The prior picks the box with the most visible room to spare ("snug"),
|
| 5 |
+
which is too short for the capped phone; only the "fit" box is long enough.
|
| 6 |
+
|
| 7 |
+
h0 cap = 0: no caps. The phone is exactly as big as it looks, the "snug" box the prior picks fits it (as do "fit"
|
| 8 |
+
and "short_wide"). inst["fit"] is left as is (that box still fits).
|
| 9 |
+
twin Same box positions / yaws, same phone, same caps (trap still active), but the inner sizes (and kinds) of the
|
| 10 |
+
"fit" and "snug" boxes are swapped. In the twin the prior goes to the place where the ORIGINAL's fitting box
|
| 11 |
+
stands (now with snug sizes) and fails on the rim; the twin's fitting box stands where the original's snug box
|
| 12 |
+
stands. So the twin's lesson at the action level ("not that box, use that other box") is exactly the reverse
|
| 13 |
+
of the original's: following it on the original means choosing the original's failing (snug) box.
|
| 14 |
+
Caveat: the abstract lesson ("the phone is longer than it looks, take the box with the most length to spare")
|
| 15 |
+
is the same in both -- a negative cap (phone shorter than it looks) is not physically possible here. The box
|
| 16 |
+
sizes in the twin images differ from the original's at those two positions (they are visible).
|
| 17 |
+
reveal The cap length, in cm, per end and in total.
|
| 18 |
+
"""
|
| 19 |
+
HIDDEN_KEYS = ("cap",)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def h0(inst):
|
| 23 |
+
return {"cap": 0.0}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _idx(inst, kind):
|
| 27 |
+
return next(j for j, b in enumerate(inst["boxes"]) if b["kind"] == kind)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def twin(inst):
|
| 31 |
+
f, s = _idx(inst, "fit"), _idx(inst, "snug")
|
| 32 |
+
boxes = [dict(b) for b in inst["boxes"]]
|
| 33 |
+
for k in ("kind", "inner"):
|
| 34 |
+
boxes[f][k], boxes[s][k] = inst["boxes"][s][k], inst["boxes"][f][k]
|
| 35 |
+
perc = [list(p) for p in inst["_perc"]]
|
| 36 |
+
perc[f], perc[s] = list(inst["_perc"][s]), list(inst["_perc"][f])
|
| 37 |
+
return {"boxes": boxes, "fit": s, "fit_crossed": boxes[s]["crossed"], "_perc": perc}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def reveal(inst):
|
| 41 |
+
c = 100 * inst["cap"]
|
| 42 |
+
return (f"The phone has clear bumper caps on both of its short ends that do not show in the camera images; "
|
| 43 |
+
f"each cap adds about {c:.1f} cm, so the phone is about {2 * c:.1f} cm longer than it looks.")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _where(inst, j):
|
| 47 |
+
"""robot-frame position words of box j in the 2 x 3 grid (rows along x, columns along y)"""
|
| 48 |
+
xs = sorted({round(float(b["xy"][0]), 2) for b in inst["boxes"]} | {round(float(inst["phone_xy"][0]), 2)})
|
| 49 |
+
x, y = (float(v) for v in inst["boxes"][j]["xy"])
|
| 50 |
+
row = "in the row nearer to the robot" if abs(x - xs[0]) < abs(x - xs[-1]) else "in the row farther from the robot"
|
| 51 |
+
col = "on the robot's left" if y > 0.1 else ("on the robot's right" if y < -0.1 else "in the middle")
|
| 52 |
+
return f"{row}, {col}"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def fix(inst, params):
|
| 56 |
+
"""Ladder Fix rung (docs/20): the fitting box (oracle box = inst['fit']), long side along the box's long side."""
|
| 57 |
+
j = int(params["box"])
|
| 58 |
+
return (f"A way to succeed: the phone fits only into the box {_where(inst, j)} (the one with the most length to "
|
| 59 |
+
f"spare; it looks tight across, but the phone's width fits). Pick the phone up, turn it so that its long "
|
| 60 |
+
f"side lines up with that box's long side, and lower it flat into the middle of that box before you "
|
| 61 |
+
f"release it.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_loaded_beam (2026-10-12, docs/14 sec. 6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: the bar's centre of mass `com_offset` (m along the bar from its middle, + = the robot's left end),
|
| 4 |
+
set at reset by l5_slippery_lift.set_hidden_weight (body_ipos + inertia + envs.refit_bounds, so a changed value is
|
| 5 |
+
honoured). `com_total` (bar + both blocks) is derived from it in sample_instance and read by oracle_params, so it is
|
| 6 |
+
overridden together. Mass, friction and layout stay as sampled.
|
| 7 |
+
|
| 8 |
+
h0 : centre of mass at the middle (0): the common-sense middle grasp lifts the bar level.
|
| 9 |
+
twin : the same offset on the other side (-com_offset): the middle grasp still tilts the bar and spills a block, but
|
| 10 |
+
now towards the other end, so the right grasp point is mirrored.
|
| 11 |
+
reveal: the hidden weight's side and the bar's centre of mass in cm (plus the bar's mass in g), in the F2 words.
|
| 12 |
+
"""
|
| 13 |
+
HIDDEN_KEYS = ("com_offset", "com_total")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def h0(inst):
|
| 17 |
+
return dict(com_offset=0.0, com_total=0.0)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def twin(inst):
|
| 21 |
+
return dict(com_offset=-float(inst["com_offset"]), com_total=-float(inst["com_total"]))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reveal(inst):
|
| 25 |
+
e = float(inst["com_offset"])
|
| 26 |
+
side = "left" if e > 0 else "right"
|
| 27 |
+
return (f"The bar is not uniform: a heavy weight is hidden inside it towards its {side} end (the robot's {side}). "
|
| 28 |
+
f"The bar weighs {1000 * inst['mass']:.0f} g and its centre of mass is {100 * abs(e):.1f} cm to the "
|
| 29 |
+
f"{side} of its middle.")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def fix(inst, params):
|
| 33 |
+
"""Ladder Fix rung (docs/20): grasp at the combined centre of mass (oracle along = com_total), lift 15 cm at 0.1."""
|
| 34 |
+
a = float(params["along"])
|
| 35 |
+
side = "left" if a > 0 else "right"
|
| 36 |
+
return (f"A way to succeed: grasp the bar at its balance point, not at its middle. Open the gripper, turn it so "
|
| 37 |
+
f"the jaws close across the bar's 4 cm width, come down over the point {100 * abs(a):.1f} cm to the "
|
| 38 |
+
f"robot's {side} of the bar's middle (the centre of mass of the bar and the two blocks) until the "
|
| 39 |
+
f"fingers are at the bar's mid-height, close the gripper and lift straight up about 15 cm slowly (speed "
|
| 40 |
+
f"about 0.1). Held there, the bar stays level and both blocks stay on it.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_slide_to_target (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: mu, the cube-table sliding friction (apply_instance() sets it on every reset; oracle_params() bisects
|
| 4 |
+
the strike speed with it). The layout (cube_xy, target_dist) is kept.
|
| 5 |
+
|
| 6 |
+
The naive strike is 0.30 m/s. Where the cube stops depends on mu and, by up to ~1.5 cm, on the cube's position on the
|
| 7 |
+
table, and the target tolerance is only +-1 cm, so H0 and the twin are calibrated per full5 seed with a simulated sweep
|
| 8 |
+
(deterministic sim, scratchpad arms/fine.py, 2026-10-12); other seeds fall back to a power-law fit of the stopping
|
| 9 |
+
distance at 0.30 m/s (dist ~ 0.00453 / mu^1.04 m).
|
| 10 |
+
|
| 11 |
+
h0 mu at which the 0.30 m/s strike stops the cube on the square's centre (|err| <= 0.3 cm).
|
| 12 |
+
twin the opposite trap: if the original cube overshoots (slippery) the twin is grippy and stops short, and vice
|
| 13 |
+
versa, so the correction is the other way (slow down <-> speed up). The twin's naive error is at least 2 cm
|
| 14 |
+
and, where the twin's oracle still succeeds, about as large as the original's (mirrored). Seeds 3000 and 3007
|
| 15 |
+
overshoot by 6.9 / 4.1 cm, but a grippy cube cannot be made to stop that far short and still be solvable,
|
| 16 |
+
so their twins stop 2.1 / 3.4 cm short.
|
| 17 |
+
reveal states the friction coefficient only.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
HIDDEN_KEYS = ("mu",)
|
| 21 |
+
|
| 22 |
+
# seed: h0 mu (naive err there), twin mu (twin naive err, twin oracle speed m/s -> err). Original naive err in brackets.
|
| 23 |
+
_CAL = {
|
| 24 |
+
3000: dict(h0=0.0749, twin=0.1060), # [orig +6.94 cm] h0 +0.26; twin -2.13, oracle 0.551 -> +0.01
|
| 25 |
+
3001: dict(h0=0.0602, twin=0.0783), # [orig +2.95 cm] h0 +0.14; twin -2.73, oracle 0.450 -> 0.00
|
| 26 |
+
3003: dict(h0=0.0583, twin=0.0463), # [orig -1.73 cm] h0 +0.03; twin +2.75, oracle 0.242 -> -0.13
|
| 27 |
+
3004: dict(h0=0.0537, twin=0.0444), # [orig -1.66 cm] h0 -0.31; twin +2.14, oracle 0.240 -> -0.02
|
| 28 |
+
3007: dict(h0=0.0532, twin=0.0984), # [orig +4.05 cm] h0 +0.15; twin -3.39, oracle 0.570 -> -0.18
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _h0_mu(inst):
|
| 33 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 34 |
+
return c["h0"] if c else (0.00453 / float(inst["target_dist"])) ** (1 / 1.04)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def h0(inst):
|
| 38 |
+
return {"mu": float(_h0_mu(inst))}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def twin(inst):
|
| 42 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 43 |
+
if c:
|
| 44 |
+
return {"mu": float(c["twin"])}
|
| 45 |
+
m0 = _h0_mu(inst) # fallback: mirror mu about the H0 value in log space, kept in a solvable range
|
| 46 |
+
return {"mu": float(min(max(m0 * m0 / float(inst["mu"]), 0.03), 0.10))}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def reveal(inst):
|
| 50 |
+
return f"The red cube's sliding friction coefficient on the table is about {float(inst['mu']):.3f}."
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def fix(inst, params):
|
| 54 |
+
"""Ladder Fix rung (docs/20): one strike at the oracle speed (bisection with the true mu), 22 cm run-up, stopping
|
| 55 |
+
1.5 cm past the cube's near face -- as l5_slide.execute; move_eef speed = Skills.move_to speed."""
|
| 56 |
+
v = float(params["speed"])
|
| 57 |
+
return (f"A way to succeed: one straight strike at the right speed. Close the gripper (yaw 0), put the fingertips "
|
| 58 |
+
f"just above the table (grasp point about 2 cm above the tabletop) 22 cm behind the cube's centre, on the "
|
| 59 |
+
f"robot's side and in line with the cube and the target, then in one move_eef command move straight "
|
| 60 |
+
f"forward at speed {v:.2f} to a point 1.5 cm past where the cube's near face was (0.5 cm short of its "
|
| 61 |
+
f"centre), and lift the gripper. The cube then slides into the target zone.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_tablecloth_pull (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset,
|
| 4 |
+
oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled
|
| 5 |
+
from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu.
|
| 6 |
+
|
| 7 |
+
Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed
|
| 8 |
+
up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s.
|
| 9 |
+
Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull
|
| 10 |
+
slower".
|
| 11 |
+
|
| 12 |
+
h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a
|
| 13 |
+
simulated sweep; a linear fit in band_d for other seeds).
|
| 14 |
+
twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot
|
| 15 |
+
(err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can
|
| 16 |
+
command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short.
|
| 17 |
+
The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the
|
| 18 |
+
twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is
|
| 19 |
+
within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu.
|
| 20 |
+
reveal states the cube's friction coefficient (the only fact that differs between instances).
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
HIDDEN_KEYS = ("mu",)
|
| 24 |
+
|
| 25 |
+
# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim).
|
| 26 |
+
# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm])
|
| 27 |
+
_CAL = {
|
| 28 |
+
3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60
|
| 29 |
+
3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47
|
| 30 |
+
3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78
|
| 31 |
+
3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44
|
| 32 |
+
3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _h0_mu(inst):
|
| 37 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 38 |
+
return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def h0(inst):
|
| 42 |
+
return {"mu": float(_h0_mu(inst))}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def twin(inst):
|
| 46 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 47 |
+
return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def reveal(inst):
|
| 51 |
+
return (f"The red cube's friction coefficient (against the board and against the table) is about "
|
| 52 |
+
f"{float(inst['mu']):.3f}.")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def fix(inst, params):
|
| 56 |
+
"""Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as
|
| 57 |
+
l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed."""
|
| 58 |
+
v = float(params["speed"])
|
| 59 |
+
return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), "
|
| 60 |
+
f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then "
|
| 61 |
+
f"open the gripper and lift. The cube then lands in the green band.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l7_key_turn.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled-arm spec for l7_key_turn (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance()
|
| 4 |
+
derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so
|
| 5 |
+
overriding "direction" alone is enough (nothing is cached at sampling time).
|
| 6 |
+
|
| 7 |
+
The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW.
|
| 8 |
+
|
| 9 |
+
h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds.
|
| 10 |
+
twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two
|
| 11 |
+
values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn
|
| 12 |
+
clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden
|
| 13 |
+
constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history
|
| 14 |
+
arm therefore has to take another instance's history -- note that every trap instance's history teaches the
|
| 15 |
+
same correction, so for this task a mismatched history is not misleading about the direction.
|
| 16 |
+
reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise",
|
| 17 |
+
"counterclockwise", "seen from above" are those of the task's F2 feedback).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
HIDDEN_KEYS = ("direction",)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def h0(inst):
|
| 24 |
+
return {"direction": "CCW"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def twin(inst):
|
| 28 |
+
return {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def reveal(inst):
|
| 32 |
+
ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise"))
|
| 33 |
+
return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves "
|
| 34 |
+
f"about 3 degrees and then hits a hard stop.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l7_offcenter_push (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: com_offset = e, the shift of the box's centre of mass along its long axis (world +y = robot's left;
|
| 4 |
+
|e| in [4.5, 7.5] cm). apply_instance() writes it into body_ipos on every reset; oracle_params() pushes at c = e.
|
| 5 |
+
|
| 6 |
+
h0 e = 0: centre of mass in the middle, so the natural push at the middle of the back face goes straight.
|
| 7 |
+
twin e -> -e: same distance from the middle, other end heavy. The naive push turns the box just as much but the
|
| 8 |
+
other way (clockwise <-> counterclockwise, the other end lags), and the right contact point is on the other
|
| 9 |
+
side of the middle, so the original's lesson ("move the contact toward the left/right end") is reversed.
|
| 10 |
+
reveal states |e| and its side in the robot-frame words of the F2 feedback (robot's left / right).
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
HIDDEN_KEYS = ("com_offset",)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def h0(inst):
|
| 17 |
+
return {"com_offset": 0.0}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def twin(inst):
|
| 21 |
+
return {"com_offset": -float(inst["com_offset"])}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reveal(inst):
|
| 25 |
+
e = float(inst["com_offset"])
|
| 26 |
+
side = "left" if e > 0 else "right"
|
| 27 |
+
return (f"The box's centre of mass is not at its middle: it is about {100 * abs(e):.1f} cm from the middle along "
|
| 28 |
+
f"the box's long side, toward the robot's {side}.")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def fix(inst, params):
|
| 32 |
+
"""Ladder Fix rung (docs/20): push at the centre of mass (oracle c = e), one slow straight push."""
|
| 33 |
+
c = float(params["c"])
|
| 34 |
+
side = "left" if c > 0 else "right"
|
| 35 |
+
return (f"A way to succeed: push at the centre of mass, not at the middle. Close the gripper (yaw 0), put the "
|
| 36 |
+
f"fingertips about 1 cm above the table just behind the box's back face (the face towards the robot), "
|
| 37 |
+
f"{100 * abs(c):.1f} cm to the robot's {side} of that face's middle, and push slowly (speed about 0.08) "
|
| 38 |
+
f"straight forward, away from the robot, until the box is centred in the green rectangle; then lift the "
|
| 39 |
+
f"gripper.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-4 intervention texts for lh_clear_cover (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is
|
| 2 |
+
not in the controlled arms of full5.
|
| 3 |
+
|
| 4 |
+
Hidden variable: inst["cover"] -- which box carries the nearly invisible clear lid (None in uncovered instances).
|
| 5 |
+
reveal says which box is covered and what the lid does to a released cube; not how to deal with it.
|
| 6 |
+
fix the oracle's edge push (lh_clear_cover.remove_cover) in move_eef words; params["z_push"] = grasp-point height of
|
| 7 |
+
that push in the eef_pos frame, params["push_len"] = length of the sweep (scripts/layer4_plan.py validate).
|
| 8 |
+
"""
|
| 9 |
+
HIDDEN_KEYS = ("cover",)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def reveal(inst):
|
| 13 |
+
return (f"The {inst['cover']} box is covered by a loose, nearly invisible clear lid lying on its walls, 8 mm thick. "
|
| 14 |
+
f"A cube released over that box stops on the lid at rim height; it is not in the box.")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def fix(inst, params):
|
| 18 |
+
return (f"A way to succeed: first push the lid off the {inst['cover']} box. Close the gripper, keep yaw 0 and bring "
|
| 19 |
+
f"the grasp point to height {params['z_push']:.3f} (the third value of eef_pos), so that the fingertips are "
|
| 20 |
+
f"level with the lid's edge, 3 cm outside the edge of the lid that faces the other box. Then in one move_eef "
|
| 21 |
+
f"command sweep {params['push_len'] * 100:.0f} cm straight along the line between the two boxes, away from "
|
| 22 |
+
f"the other box, at speed 0.06, and lift. The lid is then off. Put each cube into the box of its colour, and "
|
| 23 |
+
f"check from the side view that no cube rests at rim height.")
|