File size: 13,487 Bytes
89995d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | import os
import sys
import glob
import json
import argparse
import re
from typing import List
from google import genai
from google.genai import types
def run_validate(category: str, check_name: str, passed: bool, message: str = ""):
check_file = "/logs/verifier/validate_results.txt"
os.makedirs(os.path.dirname(check_file), exist_ok=True)
val = "pass" if passed else "fail"
with open(check_file, "a") as f:
f.write(f"{category}#{check_name}: {val}\n")
if passed:
print(f"✅ PASS: [{category}#{check_name}]")
else:
print(f"❌ FAILED: [{category}#{check_name}] {message}")
def execute_commands(command: str) -> str:
"""Execute an Android CLI or ADB command and return its output."""
cmd = command.strip()
if not (
cmd.startswith("adb")
or cmd.startswith("android")
or cmd.startswith("sleep")
or cmd.startswith("ls")
):
return "ERROR: You are only allowed to run 'adb', 'android', 'ls', or 'sleep' commands. Do not write python scripts to analyze images. You have built-in vision—just capture the screenshot and look at it!"
import subprocess
try:
res = subprocess.run(
command, shell=True, capture_output=True, text=True, timeout=30
)
return res.stdout + "\n" + res.stderr
except Exception as e:
return str(e)
def main():
parser = argparse.ArgumentParser(description="Run journey tests evaluation.")
parser.add_argument(
"--journey-dir",
type=str,
required=True,
help="Directory containing .journey.xml files",
)
parser.add_argument(
"--model",
type=str,
default=os.environ.get("MODEL_NAME", "gemini-3.6-flash"),
help="Model to use for evaluation",
)
parser.add_argument(
"--fallback-model",
type=str,
default=os.environ.get("FALLBACK_MODEL_NAME", "gemini-3.5-flash"),
help="Fallback model to use for evaluation in case of 503/429/529 errors",
)
parser.add_argument(
"--category",
type=str,
default="functional",
help="Test category to record in validation results",
)
args = parser.parse_args()
print("--------------------------------------------------")
print("🚀 Starting Journey Test Evaluation...")
print("--------------------------------------------------")
print("Setting up Android CLI...")
import subprocess
subprocess.run("apt-get update && apt-get install -y curl", shell=True, check=True)
subprocess.run(
"wget -qO- https://dl.google.com/android/cli/latest/linux_x86_64/install_root.sh | bash",
shell=True,
check=True,
)
subprocess.run("android init", shell=True, check=True)
# Find journey test XML files
journey_files = glob.glob(f"{args.journey_dir}/*.journey.xml")
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
print("ERROR: GEMINI_API_KEY environment variable not set.")
if journey_files:
for journey_file in journey_files:
journey_name = os.path.basename(journey_file)
check_key = f"journey_{journey_name.replace('.journey.xml', '')}"
run_validate(
args.category,
check_key,
False,
message="GEMINI_API_KEY environment variable not set.",
)
sys.exit(1)
model = args.model
fallback_model = args.fallback_model
client = genai.Client(api_key=api_key)
if not journey_files:
print(f"ERROR: No journey XML files found under {args.journey_dir}/")
sys.exit(1)
all_passed = True
for journey_file in journey_files:
current_model = model
journey_name = os.path.basename(journey_file)
print(f"Evaluating journey test: {journey_name}...")
try:
with open(journey_file, "r", encoding="utf-8") as f:
journey_xml = f.read()
except Exception as e:
print(f"Error reading journey file {journey_file}: {e}")
continue
skill_md, interact_md, journeys_md = "", "", ""
try:
import subprocess
res = subprocess.run(
"find /root /home -path '*/skills/android-cli/SKILL.md' 2>/dev/null | head -n 1",
shell=True,
capture_output=True,
text=True,
)
skill_md_path = res.stdout.strip()
if skill_md_path and os.path.exists(skill_md_path):
skill_dir = os.path.dirname(skill_md_path)
with open(os.path.join(skill_dir, "SKILL.md"), "r") as f:
skill_md = f.read()
with open(
os.path.join(skill_dir, "references", "interact.md"), "r"
) as f:
interact_md = f.read()
with open(
os.path.join(skill_dir, "references", "journeys.md"), "r"
) as f:
journeys_md = f.read()
else:
print("Warning: Could not locate android-cli SKILL.md dynamically")
except Exception as e:
print(f"Warning: Could not read skill files: {e}")
prompt = f"""
You are evaluating an Android journey test using the Android CLI and its journey testing skills.
Here is the Android CLI skill documentation:
<skill>{skill_md}</skill>
<interact>{interact_md}</interact>
<journeys>{journeys_md}</journeys>
Here is the Journey Test XML specification:
```xml
{journey_xml}
```
Evaluate the journey test according to the journey instructions in the Android CLI skills.
RULES:
1. Be really clear and critical about EVERY single word in EVERY `<action>`.
2. An action must be 100% achievable and flawless to be marked as "PASSED".
3. The Android CLI allows you to see the screenshot, so you can use images if you'd like to see them using this skill.
4. DO NOT write python or shell scripts to analyze images. You have native multimodal vision capabilities. When you run a screenshot command, the image will be directly shown to your vision system. Just look at it!
5. ALWAYS save your screenshots to the `/tmp/screenshots/` directory (e.g., `android screen capture -o /tmp/screenshots/screen.png`).
For each `<action>` you evaluated, output should be as per the documentation.
OUTPUT FORMAT: When done evaluating, output your final result as a raw JSON string.
"""
pass_count = 0
fail_count = 0
last_message = ""
free_retry_used = False
for attempt_idx in range(4):
attempt = attempt_idx + 1
try:
chat = client.chats.create(
model=current_model,
config=types.GenerateContentConfig(
tools=[execute_commands],
temperature=0.0,
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
),
)
response = chat.send_message(prompt)
while response.function_calls:
if response.text:
print(f"🤔 LLM Thought: {response.text.strip()}")
parts = []
all_valid_screenshots = []
for call in response.function_calls:
cmd = call.args.get("command", "")
print(f"🤖 LLM running command: {cmd}")
os.makedirs("/tmp/screenshots", exist_ok=True)
expected_paths = re.findall(r"-o\s+([^\s]+\.png)", cmd)
pngs_to_check = (
glob.glob("/tmp/screenshots/*.png") + expected_paths
)
for f in set(pngs_to_check):
try:
os.remove(f)
except:
pass
out = execute_commands(cmd)
parts.append(
types.Part.from_function_response(
name=call.name, response={"output": out}
)
)
screenshots = (
glob.glob("/tmp/screenshots/*.png") + expected_paths
)
valid_screenshots = [
f for f in set(screenshots) if os.path.exists(f)
]
if valid_screenshots:
all_valid_screenshots.extend(valid_screenshots)
response = chat.send_message(parts)
if all_valid_screenshots:
print(
f"📸 Attaching {len(set(all_valid_screenshots))} screenshot(s) to LLM context..."
)
image_parts = [
"Here are the newly captured screenshots from the commands:"
]
for f in set(all_valid_screenshots):
with open(f, "rb") as img:
image_parts.append(
types.Part.from_bytes(
data=img.read(), mime_type="image/png"
)
)
response = chat.send_message(image_parts)
if response.text:
print(f"🤔 LLM Thought: {response.text.strip()}")
text = response.text.strip() if response.text else ""
match = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.DOTALL)
if match:
text = match.group(1).strip()
else:
match = re.search(r"(\{.*\})", text, re.DOTALL)
if match:
text = match.group(1).strip()
eval_result = json.loads(text)
results = eval_result.get("results", [])
passed = bool(results) and all(
r.get("status") == "PASSED" for r in results
)
check_key = f"journey_{journey_name.replace('.journey.xml', '')}"
error_messages = [
r.get("comment", "") for r in results if r.get("status") != "PASSED"
]
message = (
" | ".join(error_messages)
if error_messages
else "All actions passed"
)
last_message = message
if passed:
pass_count += 1
else:
fail_count += 1
if pass_count >= 2:
run_validate(
args.category,
check_key,
True,
message="Passed 2 out of 3. Msg:" + last_message,
)
break
elif fail_count >= 2:
run_validate(
args.category,
check_key,
False,
message="Failed 2 out of 3. Msg:" + last_message,
)
all_passed = False
break
else:
print(
f"Attempt {attempt}: {'PASS' if passed else 'FAIL'} ({pass_count}P/{fail_count}F). Retrying..."
)
except Exception as e:
print(f"Error calling LLM for {journey_name}: {e}")
err_str = str(e)
if "503" in err_str or "429" in err_str or "529" in err_str:
if not free_retry_used:
print(
f"API error 503/429/529. Fallback model: {fallback_model} (free retry)"
)
current_model = fallback_model
free_retry_used = True
last_message = str(e)
continue
else:
print(
f"API error 503/429/529. Fallback model: {fallback_model} (counted fail)"
)
current_model = fallback_model
last_message = str(e)
fail_count += 1
if fail_count >= 2:
check_key = f"journey_{journey_name.replace('.journey.xml', '')}"
run_validate(
args.category,
check_key,
False,
message="Failed 2 out of 3 with API errors. Msg: "
+ last_message,
)
all_passed = False
break
else:
print(
f"Attempt {attempt}: ERROR ({pass_count}P/{fail_count}F). Retrying..."
)
if not all_passed:
sys.exit(1)
if __name__ == "__main__":
main()
|