File size: 9,190 Bytes
7fafb5b
 
 
 
112cf1c
7fafb5b
 
1305c82
 
 
 
 
c361e3e
7fafb5b
 
 
 
ae7e237
4db3f4c
b037b02
7fafb5b
d20078d
7fafb5b
1305c82
 
 
7fafb5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d20078d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fafb5b
ae7e237
7fafb5b
 
 
d20078d
7fafb5b
 
 
 
 
 
 
 
ae7e237
 
 
7fafb5b
d8e61fc
ae7e237
d8e61fc
ae7e237
4db3f4c
cdeed69
d8e61fc
cdeed69
 
 
c119621
 
cdeed69
ae7e237
4db3f4c
 
 
 
7fafb5b
 
d20078d
 
 
 
 
8c87437
 
 
d20078d
7fafb5b
4db3f4c
8200f63
 
 
 
 
 
 
d20078d
7fafb5b
 
b037b02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d20078d
 
 
7fafb5b
 
 
 
 
 
 
 
 
 
 
 
d20078d
 
 
7fafb5b
 
1305c82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fe5352
 
 
ae7e237
 
d20078d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fafb5b
 
d20078d
 
 
112cf1c
 
7fafb5b
 
 
ae7e237
 
 
 
2fe5352
 
 
ae7e237
 
2fe5352
ae7e237
 
7fafb5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a0172
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333

# api_server.py

import requests
from fastapi import FastAPI, Request
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi import BackgroundTasks

from core.conversation_manager import ConversationState
from core.conversation_engine import handle_turn

from core.agent_orchestrator import run_agents
from core.input_classifier import is_meaningful_input
from core.memory_store import save_state, load_state # session persistence handling
from core.conversation_manager import from_dict # to have the retrieved conversation in DICT/JSON converted to ConversationState Object
from core.command_parser import parse_command

from agents.epistemic_agent import epistemic_response

from core.epistemic.profile_manager import update_global_profile
from core.epistemic.epistemic_cross import cross_session_analysis

# CREATE APP FIRST
app = FastAPI()

# THEN MOUNT STATIC
app.mount("/static", StaticFiles(directory="web"), name="static")

# sessions = {}

# ---- CORS FIX ----
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # allow any origin
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class ChatRequest(BaseModel):
    session_id: str
    message: str


@app.get("/", response_class=HTMLResponse)
def serve_ui():
    return FileResponse("web/index.html")

#@app.get("/")
#def root():
#    return {"status": "CGJI01 API running"}

#@app.post("/analyze")
#def analyze(req: Request):
#    results = run_agents(req.text)
#    return results


@app.post("/analyze")
def analyze(req: Request):

    if not is_meaningful_input(req.text):
        return {
            "status": "ok",
            "message": "Input does not appear to require deep psychological analysis.",
            "input": req.text
        }

    results = run_agents(req.text)

    return {"result": results}
    
"""

sessions = {}

    

@app.post("/chat")

async def chat(req: Request):

    data = await req.json()

    session_id = data["session_id"]

    message = data["message"]



    if session_id not in sessions:

        sessions[session_id] = ConversationState()



    state = sessions[session_id]



    output = handle_turn(state, message)



    if output["type"] == "end":

        del sessions[session_id]  # Clean up session when finished



    return output

"""    

# HANDLE AGENT SWITCH - FUNCTION
def handle_agent_switch(state, agent_name):

    output = run_specific_agent(agent_name, state.initial_query)

    # Ensure output is a dict
    if not isinstance(output, dict):
        output = {
            "type": "error",
            "content": "Agent returned invalid response"
        }
    
    print("🧠 AGENT SWITCH OUTPUT:", output)
    
    # Inject agent identity
    output["agent"] = agent_name

    return output



#def handle_agent_switch(state, agent_name):

    # 🔥 TEMP: route through existing system
#    print(f"⚠️ Switching to {agent_name}, but using handle_turn for now")

#    return handle_turn(state, state.initial_query)

def run_epistemic_witness(state, session_id):
    try:
        # Extract full histories
        client_history = [
            msg["text"] for msg in state.agent_histories.get("jung", [])
            if msg["role"] == "client"
        ]

        jung_history = [
            msg["text"] for msg in state.agent_histories.get("jung", [])
            if msg["role"] == "agent"
        ]

        # Run epistemic analysis
        analysis = epistemic_response(client_history, jung_history)

        # Store inside state
        if not hasattr(state, "witness_logs"):
            state.witness_logs = {}

        state.witness_logs["epistemic"] = analysis

        print("🧠 EPISTEMIC UPDATED")

    except Exception as e:
        print("❌ Epistemic error:", e)


sessions = {}

@app.post("/chat")
def chat(req: ChatRequest, background_tasks: BackgroundTasks):

    print("🔥 CHAT ENDPOINT HIT")

    session_id = req.session_id
    message = req.message

    print("\n🧾 RAW REQUEST BODY:", req)

    #if session_id not in sessions:
    #    sessions[session_id] = ConversationState()

    if session_id not in sessions:
        saved_data = load_state(session_id) # when user sends a message after loading, backend restores full conversation automatically

        if saved_data:
            print("♻️ Restored session from disk")
            #sessions[session_id] = loaded

            print("🔍 SAVED DATA:", saved_data)  
            try:
                state = from_dict(saved_data)
            except Exception as e:
                print("❌ RESTORE FAILED:", e)
                state = ConversationState()

        else:
            #sessions[session_id] = ConversationState()
            state = ConversationState()

        sessions[session_id] = state

    state = sessions[session_id]

    # ✅ Ensure flag exists
    if not hasattr(state, "conversation_started"):
        state.conversation_started = False

    if not state.conversation_started:
        state.conversation_started = True

    # ✅ Store initial query
    if not state.initial_query and not message.startswith("__agent__:"):
        #state.initial_query = message
        if state.history:
            state.initial_query = next(
            (m["content"] for m in data.get("history", []) if m["role"] == "client"),
            ""
            ) # improve initial query restore
        else:
            state.initial_query = message

    print("\n📥 USER MESSAGE:", message)


    cmd, cleaned_message = parse_command(message)

    if cmd:
        if cmd["command"] == "general":
            state.mode = "general"
            state.role = "client"

        elif cmd["command"] == "analysis":
            state.mode = "analysis"

            if len(cmd["args"]) > 0:
                if cmd["args"][0] == "analyst":
                    state.role = "analyst"
                elif cmd["args"][0] == "client":
                    state.role = "client"

        message = cleaned_message



    # -----------------------------
    # AGENT SWITCH
    # -----------------------------
    if message.startswith("__agent__:"):
        selected_agent = message.split(":")[1]

        print("🧭 Switching to agent:", selected_agent)

        state.current_agent = selected_agent

        output = handle_agent_switch(state, selected_agent)

        print("\n📤 RESPONSE TO UI:", output)
        return output

    # -----------------------------
    # NORMAL FLOW (JUNG etc.)
    # -----------------------------
    output = handle_turn(state, message)

     
    # ---- (EXPERIMENTAL) LOW-LEVEL CROSS-SESSION EPISTEMIC INTELLIGENCE/ANALYSIS ----
    
    # -------------------------------
    # UPDATE GLOBAL PROFILE
    # -------------------------------
    state.session_id = session_id  # ensure attached
    session_record = update_global_profile(state)

    # -------------------------------
    # EPISTEMIC CROSS-SESSION
    # -------------------------------
    epistemic_text = cross_session_analysis(session_record)

    # attach to response
    output["witness_updates"] = {
        "epistemic": epistemic_text
    }
    # ---- (EXPERIMENTAL) LOW-LEVEL CROSS-SESSION EPISTEMIC INTELLIGENCE/ANALYSIS - End ----

    # -----------------------------------------
    # SAVE STATE AFTER EVERY TURN (PERSISTENCE)
    # -----------------------------------------
    save_state(session_id, state)

    # -----------------------------
    # 🧠 EPISTEMIC (BACKGROUND)
    # -----------------------------
    jung_history_len = len(state.agent_histories.get("jung", []))

    # ✅ Throttle → every 2 turns
    if jung_history_len % 2 == 0:
        background_tasks.add_task(run_epistemic_witness, state, session_id)

    # -----------------------------
    # 📦 ATTACH EPISTEMIC TO RESPONSE
    # -----------------------------
    if hasattr(state, "witness_logs"):
        output["witness_updates"] = state.witness_logs

    print("\n📤 RESPONSE TO UI:", output)

    # -----------------------------
    # CLEANUP
    # -----------------------------
    if output["type"] == "end":
        del sessions[session_id]

    return output

# ---- GET SESSION DATA, PAST CONVERSATION ---- 
@app.get("/session/{session_id}")
def get_session(session_id: str):

    data = load_state(session_id)

    if not data:
        return {"error": "Session not found"}

    return data



@app.get("/health")
def health_check():

    #import requests

    ollama_status = False

    try:
        requests.get("http://127.0.0.1:11434")
        ollama_status = True
    except:
        pass

    return {
        "api": "running",
        "ollama": "connected" if ollama_status else "not running",
        "agents": "ready"
    }