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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Unity Agent CLI β Interactive game development agent.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python cli.py # Start interactive REPL (chat with LLM)
|
| 7 |
+
python cli.py generate # Generate a game from a preset
|
| 8 |
+
python cli.py list-tools # List all available tools
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import os
|
| 13 |
+
import json
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
import httpx
|
| 20 |
+
except ImportError:
|
| 21 |
+
os.system(f"{sys.executable} -m pip install httpx")
|
| 22 |
+
import httpx
|
| 23 |
+
|
| 24 |
+
from unity_agent.config import Settings
|
| 25 |
+
from unity_agent.transport.unity_transport import UnityTransport
|
| 26 |
+
from unity_agent.tools.base import _GLOBAL_REGISTRY, ToolResult
|
| 27 |
+
from unity_agent.orchestrator.prompts import SYSTEM_PROMPT
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class LLMClient:
|
| 31 |
+
"""Z.ai OpenAI-compatible LLM client."""
|
| 32 |
+
def __init__(self, api_key, model="glm-4.5-flash", base_url="https://open.bigmodel.cn/api/paas/v4"):
|
| 33 |
+
self.api_key = api_key
|
| 34 |
+
self.model = model
|
| 35 |
+
self.base_url = base_url
|
| 36 |
+
|
| 37 |
+
def chat(self, messages, temperature=0.2):
|
| 38 |
+
headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"}
|
| 39 |
+
payload = {"model": self.model, "messages": messages, "temperature": temperature, "max_tokens": 4096}
|
| 40 |
+
try:
|
| 41 |
+
resp = httpx.post(f"{self.base_url}/chat/completions", headers=headers, json=payload, timeout=120.0)
|
| 42 |
+
return resp.json()["choices"][0]["message"]["content"]
|
| 43 |
+
except Exception as e:
|
| 44 |
+
return f"[LLM Error: {e}]"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def parse_tool_call(text):
|
| 48 |
+
match = re.search(r'```tool_call\s*\n(.*?)```', text, re.DOTALL)
|
| 49 |
+
if match:
|
| 50 |
+
try: return json.loads(match.group(1).strip())
|
| 51 |
+
except: pass
|
| 52 |
+
match = re.search(r'\{[^{}]*"name"[^{}]*"arguments"[^{}]*\}', text, re.DOTALL)
|
| 53 |
+
if match:
|
| 54 |
+
try: return json.loads(match.group(0))
|
| 55 |
+
except: pass
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def build_tool_catalog():
|
| 60 |
+
lines = []
|
| 61 |
+
for name in _GLOBAL_REGISTRY.all_names():
|
| 62 |
+
tool_cls = _GLOBAL_REGISTRY.get(name)
|
| 63 |
+
schema = tool_cls.input_schema if hasattr(tool_cls, 'input_schema') else {}
|
| 64 |
+
params = ", ".join(schema.keys()) if schema else "none"
|
| 65 |
+
desc = (tool_cls.__doc__ or "").strip().split("\n")[0][:70]
|
| 66 |
+
lines.append(f" - {name}({params}): {desc}")
|
| 67 |
+
return "\n".join(lines)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def run_tool(tool_name, arguments, settings, transport):
|
| 71 |
+
tool_cls = _GLOBAL_REGISTRY.get(tool_name)
|
| 72 |
+
if tool_cls is None:
|
| 73 |
+
return ToolResult(success=False, message=f"Unknown tool: {tool_name}")
|
| 74 |
+
try:
|
| 75 |
+
tool = tool_cls(settings, transport)
|
| 76 |
+
return tool.run(**arguments)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return ToolResult(success=False, message=str(e))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def interactive_repl():
|
| 82 |
+
print("=" * 60)
|
| 83 |
+
print(" UNITY GAME AGENT β Interactive Mode")
|
| 84 |
+
print(" Chat with the AI to generate Unity games")
|
| 85 |
+
print("=" * 60)
|
| 86 |
+
|
| 87 |
+
settings = Settings()
|
| 88 |
+
settings.output_dir = os.path.abspath("./unity_projects")
|
| 89 |
+
os.makedirs(settings.output_dir, exist_ok=True)
|
| 90 |
+
transport = UnityTransport(settings)
|
| 91 |
+
|
| 92 |
+
# Get API key
|
| 93 |
+
api_key = os.environ.get("ZAI_API_KEY", "")
|
| 94 |
+
if not api_key:
|
| 95 |
+
env_path = os.path.join(os.getcwd(), ".env")
|
| 96 |
+
if os.path.exists(env_path):
|
| 97 |
+
with open(env_path) as f:
|
| 98 |
+
for line in f:
|
| 99 |
+
if line.startswith("ZAI_API_KEY="):
|
| 100 |
+
api_key = line.split("=", 1)[1].strip()
|
| 101 |
+
break
|
| 102 |
+
if not api_key:
|
| 103 |
+
print("\n No API key found. Get a free key at https://z.ai")
|
| 104 |
+
api_key = input(" Paste your ZAI API key: ").strip()
|
| 105 |
+
if not api_key:
|
| 106 |
+
print(" No key. Exiting."); return
|
| 107 |
+
|
| 108 |
+
model = os.environ.get("ZAI_MODEL", "glm-4.5-flash")
|
| 109 |
+
base_url = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/paas/v4")
|
| 110 |
+
llm = LLMClient(api_key, model, base_url)
|
| 111 |
+
|
| 112 |
+
catalog = build_tool_catalog()
|
| 113 |
+
full_system = SYSTEM_PROMPT + f"\n\n# AVAILABLE TOOLS\n{catalog}\n"
|
| 114 |
+
messages = [{"role": "system", "content": full_system}]
|
| 115 |
+
current_project = None
|
| 116 |
+
|
| 117 |
+
print(f"\n Model: {model}")
|
| 118 |
+
print(f" Output: {settings.output_dir}")
|
| 119 |
+
print(f" Tools: {len(_GLOBAL_REGISTRY.all_names())} registered")
|
| 120 |
+
print(f"\n Type a game idea, or /help for commands.")
|
| 121 |
+
print("=" * 60)
|
| 122 |
+
|
| 123 |
+
while True:
|
| 124 |
+
try:
|
| 125 |
+
user_input = input("\ngame> ").strip()
|
| 126 |
+
except (EOFError, KeyboardInterrupt):
|
| 127 |
+
print("\n\nGoodbye!"); break
|
| 128 |
+
if not user_input: continue
|
| 129 |
+
|
| 130 |
+
if user_input.startswith("/"):
|
| 131 |
+
cmd = user_input.lower().split()[0]
|
| 132 |
+
args = user_input[len(cmd):].strip()
|
| 133 |
+
if cmd in ("/exit", "/quit"): break
|
| 134 |
+
elif cmd == "/help":
|
| 135 |
+
print("\n /help β This help")
|
| 136 |
+
print(" /tools β List all tools")
|
| 137 |
+
print(" /generate p β Generate game from preset (open_world_city, fps_arena, minimal)")
|
| 138 |
+
print(" /open path β Set output directory")
|
| 139 |
+
print(" /scene β Show current project files")
|
| 140 |
+
print(" /clear β Reset conversation")
|
| 141 |
+
print(" /exit β Quit")
|
| 142 |
+
print("\n Or just type: 'Create a racing game with obstacles'")
|
| 143 |
+
elif cmd == "/tools":
|
| 144 |
+
for name in _GLOBAL_REGISTRY.all_names():
|
| 145 |
+
print(f" {name}")
|
| 146 |
+
elif cmd == "/generate":
|
| 147 |
+
if not args: print("Usage: /generate open_world_city"); continue
|
| 148 |
+
print(f"\nGenerating '{args}'...")
|
| 149 |
+
r = run_tool("generate_complete_game", {"game_name": f"Game_{args}", "game_type": args}, settings, transport)
|
| 150 |
+
print(f"{'β' if r.success else 'β'} {r.message[:200]}")
|
| 151 |
+
if r.success: current_project = settings.output_dir
|
| 152 |
+
elif cmd == "/open":
|
| 153 |
+
if args:
|
| 154 |
+
settings.output_dir = os.path.abspath(args)
|
| 155 |
+
os.makedirs(settings.output_dir, exist_ok=True)
|
| 156 |
+
transport = UnityTransport(settings)
|
| 157 |
+
print(f"Output: {settings.output_dir}")
|
| 158 |
+
elif cmd == "/scene":
|
| 159 |
+
if current_project:
|
| 160 |
+
for root, dirs, files in os.walk(current_project):
|
| 161 |
+
for f in sorted(files):
|
| 162 |
+
print(f" {os.path.relpath(os.path.join(root, f), current_project)}")
|
| 163 |
+
else: print("No project yet.")
|
| 164 |
+
elif cmd == "/clear":
|
| 165 |
+
messages = [{"role": "system", "content": full_system}]
|
| 166 |
+
print("Cleared.")
|
| 167 |
+
else: print(f"Unknown: {cmd}. /help for commands.")
|
| 168 |
+
continue
|
| 169 |
+
|
| 170 |
+
# Send to LLM
|
| 171 |
+
messages.append({"role": "user", "content": user_input})
|
| 172 |
+
print("\n thinking...", end="", flush=True)
|
| 173 |
+
response = llm.chat(messages)
|
| 174 |
+
print("\r" + " " * 20 + "\r", end="")
|
| 175 |
+
|
| 176 |
+
tool_call = parse_tool_call(response)
|
| 177 |
+
display = re.sub(r'```tool_call\s*\n.*?```', '', response, flags=re.DOTALL).strip() if tool_call else response
|
| 178 |
+
if display: print(f" Agent: {display}")
|
| 179 |
+
messages.append({"role": "assistant", "content": response})
|
| 180 |
+
|
| 181 |
+
if tool_call:
|
| 182 |
+
tn = tool_call.get("name", "")
|
| 183 |
+
ta = tool_call.get("arguments", {})
|
| 184 |
+
print(f"\n β {tn}({json.dumps(ta, default=str)[:150]})")
|
| 185 |
+
r = run_tool(tn, ta, settings, transport)
|
| 186 |
+
print(f" {'β' if r.success else 'β'} {r.message[:200]}")
|
| 187 |
+
messages.append({"role": "user", "content": f"Tool '{tn}' result: {r.message}"})
|
| 188 |
+
if tn in ("generate_complete_game", "setup_unity_project"):
|
| 189 |
+
current_project = settings.output_dir
|
| 190 |
+
print(f"\n Game ready: {current_project}")
|
| 191 |
+
print(f" Open in Unity Hub β Add β {current_project}")
|
| 192 |
+
|
| 193 |
+
if "TASK COMPLETE" in response.upper():
|
| 194 |
+
print("\n" + "=" * 60)
|
| 195 |
+
if current_project: print(f" Game: {current_project}")
|
| 196 |
+
print("=" * 60)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
interactive_repl()
|