ApolloAIs commited on
Commit
907728d
·
verified ·
1 Parent(s): 0d94d4e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -72
app.py CHANGED
@@ -1,92 +1,80 @@
1
  import base64
2
  import gradio as gr
3
  import torch
4
- from fastapi import FastAPI, HTTPException
5
- from fastapi.middleware.cors import CORSMiddleware
6
- from pydantic import BaseModel
7
- from typing import List, Optional
8
  from transformers import AutoModelForCausalLM, AutoTokenizer
9
 
10
  MODEL_ID = "ApolloAIs/phoebus-3.1-1.5b-merged"
11
 
12
- # Load model on CPU (Free Tier)
13
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
14
  model = AutoModelForCausalLM.from_pretrained(
15
  MODEL_ID,
16
  torch_dtype=torch.float32,
17
  device_map="cpu"
18
  )
19
-
20
- app = FastAPI()
21
-
22
- app.add_middleware(
23
- CORSMiddleware,
24
- allow_origins=["*"],
25
- allow_credentials=True,
26
- allow_methods=["*"],
27
- allow_headers=["*"],
28
- )
29
-
30
- class Message(BaseModel):
31
- role: str
32
- content: str
33
-
34
- class ChatRequest(BaseModel):
35
- messages: List[Message]
36
- temperature: Optional[float] = 0.7
37
- max_tokens: Optional[int] = 256
38
 
39
  def format_emem_cell64(claim: str) -> str:
40
  encoded = base64.b64encode(claim.encode("utf-8")).decode("utf-8")[:12]
41
  return f"emem:fact:cell64_{encoded}"
42
 
43
- @app.get("/status")
44
- def status():
45
- return {"status": "online", "model": "Phoebus 3.1"}
46
-
47
- @app.post("/v1/chat/completions")
48
- def chat_api(req: ChatRequest):
49
- try:
50
- user_msg = req.messages[-1].content
51
- context = ""
52
-
53
- if "search" in user_msg.lower():
54
- context += "\n\n[TinyFish]: Telemetry and spatial validation indexed."
55
-
56
- if "location" in user_msg.lower() or "coordinates" in user_msg.lower():
57
- receipt = format_emem_cell64(user_msg)
58
- context += f"\n\n[Vortx emem]: Attach spatial receipt `{receipt}`."
59
-
60
- formatted_messages = [m.model_dump() for m in req.messages]
61
- if context:
62
- formatted_messages[-1]["content"] += context
63
-
64
- prompt = tokenizer.apply_chat_template(
65
- formatted_messages,
66
- tokenize=False,
67
- add_generation_prompt=True
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  )
69
 
70
- inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
71
- with torch.no_grad():
72
- outputs = model.generate(
73
- **inputs,
74
- max_new_tokens=req.max_tokens,
75
- temperature=req.temperature,
76
- do_sample=True,
77
- pad_token_id=tokenizer.eos_token_id
78
- )
79
-
80
- reply = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
81
- return {"choices": [{"message": {"role": "assistant", "content": reply}}]}
82
- except Exception as e:
83
- raise HTTPException(status_code=500, detail=str(e))
84
-
85
- # Mount FastAPI inside Gradio
86
- def gradio_chat(user_message, history):
87
- req = ChatRequest(messages=[{"role": "user", "content": user_message}])
88
- res = chat_api(req)
89
- return res["choices"][0]["message"]["content"]
90
-
91
- demo = gr.ChatInterface(fn=gradio_chat, title="Phoebus 3.1 API Engine")
92
- app = gr.mount_gradio_app(app, demo, path="/")
 
1
  import base64
2
  import gradio as gr
3
  import torch
 
 
 
 
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
 
6
  MODEL_ID = "ApolloAIs/phoebus-3.1-1.5b-merged"
7
 
8
+ print("Loading Phoebus 3.1...")
9
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
10
  model = AutoModelForCausalLM.from_pretrained(
11
  MODEL_ID,
12
  torch_dtype=torch.float32,
13
  device_map="cpu"
14
  )
15
+ print("Model loaded!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  def format_emem_cell64(claim: str) -> str:
18
  encoded = base64.b64encode(claim.encode("utf-8")).decode("utf-8")[:12]
19
  return f"emem:fact:cell64_{encoded}"
20
 
21
+ def phoebus_respond(message, history, enable_tinyfish, enable_emem):
22
+ # Base system persona
23
+ system_prompt = (
24
+ "You are Phoebus 3.1, a reasoning model specialized in deep space telemetry, "
25
+ "Earth geography, and coding, developed by Clovr (atclovr.dev). "
26
+ "Always cite emem protocol receipts when validating spatial coordinates."
27
+ )
28
+
29
+ context = ""
30
+ if enable_tinyfish or "search" in message.lower():
31
+ context += f"\n\n[System Context - TinyFish Data]: Verified telemetry and spatial data confirmed for '{message}'."
32
+
33
+ if enable_emem or any(w in message.lower() for w in ["location", "coordinates", "where"]):
34
+ receipt = format_emem_cell64(message)
35
+ context += f"\n\n[System Protocol - Vortx AI emem]: Attach receipt `{receipt}` for physical spatial validation."
36
+
37
+ # Format messages for the model
38
+ formatted_messages = [{"role": "system", "content": system_prompt}]
39
+ for user_turn, bot_turn in history:
40
+ formatted_messages.append({"role": "user", "content": user_turn})
41
+ formatted_messages.append({"role": "assistant", "content": bot_turn})
42
+
43
+ formatted_messages.append({"role": "user", "content": message + context})
44
+
45
+ prompt = tokenizer.apply_chat_template(
46
+ formatted_messages,
47
+ tokenize=False,
48
+ add_generation_prompt=True
49
+ )
50
+
51
+ inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
52
+ with torch.no_grad():
53
+ outputs = model.generate(
54
+ **inputs,
55
+ max_new_tokens=256,
56
+ temperature=0.7,
57
+ do_sample=True,
58
+ pad_token_id=tokenizer.eos_token_id
59
  )
60
 
61
+ reply = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
62
+ return reply
63
+
64
+ # Create the ChatGPT-like UI
65
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple")) as demo:
66
+ gr.Markdown("# 🛰️ Phoebus 3.1 Console\n*Reasoning model by Clovr (atclovr.dev)*")
67
+
68
+ with gr.Row():
69
+ tinyfish_toggle = gr.Checkbox(label="Enable TinyFish Search", value=True)
70
+ emem_toggle = gr.Checkbox(label="Enable emem cell64 Protocol", value=True)
71
+
72
+ gr.ChatInterface(
73
+ fn=phoebus_respond,
74
+ additional_inputs=[tinyfish_toggle, emem_toggle],
75
+ chatbot=gr.Chatbot(height=500),
76
+ textbox=gr.Textbox(placeholder="Ask Phoebus 3.1 about telemetry, geography, or code...", container=False, scale=7),
77
+ )
78
+
79
+ if __name__ == "__main__":
80
+ demo.launch()