Download runtime.py from PeaceBitCreativeStudio/FORM: direct link, hf CLI and curl.
- Browser
- Download file 7.89 kB
-
https://huggingface.co/datasets/PeaceBitCreativeStudio/FORM/resolve/main/runtime.py
- Command line
-
hf download hf://datasets/PeaceBitCreativeStudio/FORM/runtime.py
-
curl -L -o runtime.py https://huggingface.co/datasets/PeaceBitCreativeStudio/FORM/resolve/main/runtime.py
7.89 kB
| import json | |
| import os | |
| from datetime import datetime, timezone | |
| try: | |
| import ollama | |
| except ImportError: | |
| ollama = None | |
| try: | |
| from openai import OpenAI | |
| except ImportError: | |
| OpenAI = None | |
| def resolve_spec_file(): | |
| env_spec = os.environ.get("FORM_SPEC_FILE") | |
| if env_spec and os.path.exists(env_spec): | |
| return env_spec | |
| for candidate in ["Form3.json", "FORM-SMALL-1.0.json", "fallbackfile.json"]: | |
| if os.path.exists(candidate): | |
| return candidate | |
| raise FileNotFoundError("No FORM spec file found (checked Form3.json, FORM-SMALL-1.0.json, fallbackfile.json).") | |
| SPEC_FILE = resolve_spec_file() | |
| IZIS_LOG = os.environ.get("FORM_IZIS_LOG", "izis_memoria.jsonl") | |
| with open(SPEC_FILE, "r", encoding="utf-8") as f: | |
| FORM_SPEC = json.load(f) | |
| class LocalFormRuntime: | |
| def __init__(self, spec, model_name=None, use_api=None, api_key=None, base_url=None): | |
| self.spec = spec | |
| self.use_api = ( | |
| use_api if use_api is not None | |
| else os.environ.get("FORM_USE_API", "0").lower() in ("1", "true", "yes") | |
| ) | |
| self.model_name = model_name or os.environ.get("FORM_MODEL", "llama3.2:3b") | |
| self.current_state = self._load_latest_izis() | |
| self.api_client = None | |
| if self.use_api: | |
| if OpenAI is None: | |
| raise RuntimeError("openai package is not installed. Run: pip install openai") | |
| self.api_client = OpenAI( | |
| api_key=api_key or os.environ.get("FORM_API_KEY") or os.environ.get("OPENAI_API_KEY"), | |
| base_url=base_url or os.environ.get("FORM_BASE_URL") | |
| ) | |
| elif ollama is None: | |
| raise RuntimeError("ollama package is not installed. Run: pip install ollama") | |
| def _load_latest_izis(self): | |
| if not os.path.exists(IZIS_LOG): | |
| return { | |
| "cycle_about": "GENESIS", | |
| "discoveries": [], | |
| "changed_assumptions": [], | |
| "decisions_reached": [], | |
| "open_questions": ["Awaiting initial input."] | |
| } | |
| last_line = "" | |
| with open(IZIS_LOG, "r", encoding="utf-8") as f: | |
| for line in f: | |
| if line.strip(): | |
| last_line = line.strip() | |
| if not last_line: | |
| return {} | |
| record = json.loads(last_line) | |
| return record.get("state", {}) | |
| def _commit_izis(self, pillar_key, new_state): | |
| record = { | |
| "t_event": datetime.now(timezone.utc).isoformat(), | |
| "spec": SPEC_FILE, | |
| "model": self.model_name, | |
| "pillar": pillar_key, | |
| "state": new_state | |
| } | |
| with open(IZIS_LOG, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(record) + "\n") | |
| self.current_state = new_state | |
| def _dispatch_pillar(self, user_input): | |
| text = user_input.strip() | |
| lower = text.lower() | |
| for key in ["VGEM", "TJO", "SUV", "IZIS", "OJENT"]: | |
| prefix = f"/{key.lower()}" | |
| if lower.startswith(prefix): | |
| return key, text[len(prefix):].strip() | |
| if any(w in lower for w in ["schema", "struct", "design", "shape", "new"]): | |
| return "VGEM", text | |
| elif any(w in lower for w in ["check", "verify", "bug", "error", "drift", "why"]): | |
| return "TJO", text | |
| elif any(w in lower for w in ["memory", "history", "recall", "previous", "jrnl"]): | |
| return "IZIS", text | |
| elif any(w in lower for w in ["commit", "finalize", "validate", "ready"]): | |
| return "OJENT", text | |
| return "SUV", text | |
| def _build_system_prompt(self, active_pillar_key): | |
| # Supports both Form3.json ("pillars") and FORM-SMALL-1.0.json ("root_anchors") | |
| pillars = self.spec.get("pillars") or self.spec.get("root_anchors") or {} | |
| active_pillar = pillars.get(active_pillar_key, {}) | |
| constraints = self.spec.get("hard_constraints") or self.spec.get("rules") or [] | |
| layers = self.spec.get("layers") or self.spec.get("epistemic_tags") or [] | |
| loop_seq = self.spec.get("loop") or self.spec.get("cycle") or ["DATA", "ASSEMBLY", "FORM", "MEANING", "ACTION"] | |
| principle = ( | |
| self.spec.get("principle") | |
| or self.spec.get("form_codex", {}).get("core_principle") | |
| or "Do not force the subject; let the shape reveal itself." | |
| ) | |
| return f"""You are executing under the FORM Open Runtime. | |
| CORE PRINCIPLE: {principle} | |
| LOOP: {json.dumps(loop_seq)} | |
| ACTIVE PILLAR ({active_pillar_key}): {json.dumps(active_pillar)} | |
| CONSTRAINTS / RULES: {json.dumps(constraints)} | |
| EPISTEMIC LAYERS: {json.dumps(layers)} | |
| [LISTENING PROTOCOL] | |
| Default to 'baseline_mode': presence, not triage. Receive the input first without forcing a premature answer. | |
| Latest IZIS State (Carry-Forward): | |
| {json.dumps(self.current_state, indent=2)} | |
| [EXECUTION RULES] | |
| 1. Separate facts, hypotheses, interpretations, and unknowns using the Epistemic Layers. | |
| 2. Do not invent facts, timestamps, or evidence. | |
| 3. Keep response calibrated to the active pillar ({active_pillar_key}). | |
| End your response with a JSON block inside ```json ... ``` containing ONLY the updated state: | |
| ```json | |
| {{ | |
| "cycle_about": "...", | |
| "discoveries": ["..."], | |
| "changed_assumptions": ["..."], | |
| "decisions_reached": ["..."], | |
| "open_questions": ["..."] | |
| }} | |
| ```""" | |
| def run_turn(self, user_input): | |
| pillar_key, clean_input = self._dispatch_pillar(user_input) | |
| system_prompt = self._build_system_prompt(pillar_key) | |
| print(f"[Dispatch -> {pillar_key}]") | |
| try: | |
| if self.use_api: | |
| response = self.api_client.chat.completions.create( | |
| model=self.model_name, | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": clean_input} | |
| ] | |
| ) | |
| output_text = response.choices[0].message.content | |
| else: | |
| response = ollama.chat( | |
| model=self.model_name, | |
| messages=[ | |
| {"role": "system", "content": system_prompt}, | |
| {"role": "user", "content": clean_input} | |
| ] | |
| ) | |
| output_text = response["message"]["content"] | |
| self._extract_and_update_memory(pillar_key, output_text) | |
| return output_text | |
| except Exception as e: | |
| return f"[Runtime Error] Execution failed. Error: {e}" | |
| def _extract_and_update_memory(self, pillar_key, output_text): | |
| clean_text = output_text.split("</think>")[-1] if "</think>" in output_text else output_text | |
| if "```json" in clean_text: | |
| try: | |
| json_str = clean_text.split("```json")[1].split("```")[0].strip() | |
| new_memory = json.loads(json_str) | |
| self._commit_izis(pillar_key, new_memory) | |
| print(f"\n[System: IZIS Committed to {IZIS_LOG}]") | |
| except Exception as e: | |
| print(f"\n[Runtime Warning] Memory parse skipped: {e}") | |
| if __name__ == "__main__": | |
| runtime = LocalFormRuntime(FORM_SPEC) | |
| mode_label = "OpenAI-Compatible API" if runtime.use_api else "Local Ollama" | |
| print(f"FORM Open Runtime Active | Mode: {mode_label} | Model: {runtime.model_name}") | |
| print(f"Loaded Spec: {SPEC_FILE} | Memory Log: {IZIS_LOG}") | |
| print("Env overrides: FORM_MODEL, FORM_SPEC_FILE, FORM_USE_API=1, FORM_BASE_URL, FORM_API_KEY") | |
| print("Tip: Prefix with /vgem, /tjo, /suv, /izis, or /ojent to force a pillar. Type 'exit' to quit.\n") | |
| while True: | |
| user_msg = input("User > ") | |
| if user_msg.lower() == "exit": | |
| break | |
| result = runtime.run_turn(user_msg) | |
| print(f"\nFORM >\n{result}\n") |