File size: 4,455 Bytes
7f45e54
69c848a
7f45e54
 
 
 
 
 
69c848a
7f45e54
69c848a
 
 
7f45e54
69c848a
 
7f45e54
69c848a
7f45e54
 
 
 
 
 
 
69c848a
 
 
7f45e54
69c848a
 
7f45e54
 
 
 
69c848a
 
 
7f45e54
 
 
 
 
 
69c848a
 
7f45e54
 
 
 
69c848a
 
 
 
 
 
7f45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69c848a
 
 
 
 
 
 
7f45e54
69c848a
7f45e54
69c848a
 
7f45e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69c848a
 
 
 
 
 
 
 
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

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")