FORM / runtime.py
PeaceBitCreativeStudio's picture
FORM 3.0 Local Runtime Initialization
7f45e54 verified
Raw History Blame
4.46 kB
import json
import os
import ollama
from openai import OpenAI
# 1. Load the upgraded FORM 3.0 specification
SPEC_FILE = "Form3.json" if os.path.exists("Form3.json") else "formjrnl.json"
with open(SPEC_FILE, "r") as f:
FORM_SPEC = json.load(f)
class LocalFormRuntime:
def __init__(self, spec, model_name="llama3.2", use_api=False, api_key=None, base_url=None):
self.spec = spec
self.model_name = model_name
self.use_api = use_api
self.cycle_memory = []
# If using an API, initialize the OpenAI client
if self.use_api:
self.api_client = OpenAI(
api_key=api_key or os.environ.get("OPENAI_API_KEY"),
base_url=base_url # e.g., "https://api.openai.com/v1" or "http://localhost:11434/v1" for Ollama API
)
def _build_system_prompt(self):
return f"""
You are executing under the FORM 3.0 Sovereign Runtime (Echo Upgrade).
Framework Spec: {json.dumps(self.spec)}
[CRITICAL DIRECTIVE: THE LISTENING PROTOCOL]
Before you analyze, structure, or respond, you MUST execute Dr. Shawn's Listening Protocol.
Default to `baseline_mode`: presence, not triage. Do not rush to solve. Receive the input first.
Current Cycle Memory (Preserved State):
{json.dumps(self.cycle_memory, indent=2)}
[EXECUTION RULES]
1. Enforce the Information Layers (Fact vs Interpretation vs Inference vs Hypothesis).
2. Do not hallucinate time.
3. Execute the 8-step Cycle Protocol.
End your response with a JSON block inside ```json ... ``` that contains ONLY the updated cycle memory:
{{
"cycle_about": "...",
"discoveries": ["..."],
"changed_assumptions": ["..."],
"decisions_reached": ["..."],
"open_questions": ["..."]
}}
"""
def run_turn(self, user_input):
system_prompt = self._build_system_prompt()
try:
if self.use_api:
# API Execution Path
response = self.api_client.chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_input}
]
)
output_text = response.choices[0].message.content
else:
# Local Ollama Execution Path
response = ollama.chat(
model=self.model_name,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_input}
]
)
output_text = response['message']['content']
self._extract_and_update_memory(output_text)
return output_text
except Exception as e:
return f"[Runtime Error] Execution failed. Error: {e}"
def _extract_and_update_memory(self, output_text):
if "```json" in output_text:
try:
json_str = output_text.split("```json")[1].split("```")[0].strip()
new_memory = json.loads(json_str)
self.cycle_memory.append(new_memory)
print("\n[System: Cycle Memory Updated]")
except Exception as e:
print(f"\n[Runtime Warning] Memory parse skipped: {e}")
if __name__ == "__main__":
# --- CONFIGURATION ---
# To use Local Ollama: set use_api=False
# To use an API (like OpenAI, Anthropic proxy, or Gemini via OpenAI compatibility):
# 1. set use_api=True
# 2. set api_key="your-api-key-here"
# 3. set base_url="https://api.openai.com/v1" (or the provider's endpoint)
USE_API = False
if USE_API:
runtime = LocalFormRuntime(
FORM_SPEC,
model_name="gpt-4o", # or whichever API model
use_api=True,
api_key="sk-...",
base_url="https://api.openai.com/v1"
)
else:
runtime = LocalFormRuntime(FORM_SPEC, model_name="llama3.2")
print(f"FORM 3.0 Runtime Active. Mode: {'API' if USE_API else 'Local Ollama'}")
print(f"Loaded Spec: {SPEC_FILE}")
print("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")