File size: 7,893 Bytes
69c848a 7f45e54 3d9122e 7f45e54 2007316 69c848a 3d9122e 69c848a 3d9122e 69c848a 2007316 69c848a 2007316 3d9122e 2007316 3d9122e 7f45e54 2007316 7f45e54 2007316 7f45e54 2007316 69c848a 3d9122e 2007316 3d9122e 2007316 3d9122e 2007316 3d9122e 2007316 3d9122e 2007316 69c848a 2007316 7f45e54 2007316 3d9122e 69c848a 7f45e54 2007316 3d9122e 7f45e54 3d9122e 69c848a 7f45e54 69c848a 3d9122e 69c848a 3d9122e 7f45e54 3d9122e 7f45e54 3d9122e 7f45e54 3d9122e 7f45e54 3d9122e 7f45e54 69c848a 3d9122e 2007316 3d9122e 69c848a 3d9122e 69c848a 3d9122e 69c848a 7f45e54 69c848a 3d9122e 69c848a 2007316 3d9122e 2007316 3d9122e 2007316 3d9122e 69c848a 3d9122e 69c848a 2007316 | 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 | 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") |