Prometech Computer Sciences Corp
commited on
Update prettybird_brain.py
Browse files- prettybird_brain.py +234 -109
prettybird_brain.py
CHANGED
|
@@ -1,117 +1,242 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import json
|
| 3 |
import re
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
from
|
| 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 |
try:
|
| 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 |
score = 0.0
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
score += 0.5
|
|
|
|
| 67 |
return score
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
PrettyBird Skull Engine
|
| 6 |
+
- GGUF = mathematical optimization brain (skull)
|
| 7 |
+
- Bodies = interchangeable (text/image/audio/video/3D adapters)
|
| 8 |
+
- Single-file, backend-clean, optimizer-compatible
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
import json
|
| 12 |
import re
|
| 13 |
+
import ast
|
| 14 |
+
import numpy as np
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 17 |
+
|
| 18 |
+
from llama_cpp import Llama
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ============================================================
|
| 22 |
+
# 1) SYSTEM PROMPT (FINAL – kilitli)
|
| 23 |
+
# ============================================================
|
| 24 |
+
SYSTEM_PROMPT = """You are a controlled reasoning core operating as a mathematical optimization brain.
|
| 25 |
+
|
| 26 |
+
You are NOT an autonomous agent.
|
| 27 |
+
You operate under an external Python-based optimization and behavior orchestration system (BCE).
|
| 28 |
+
|
| 29 |
+
Hard rules:
|
| 30 |
+
- Output MUST be valid JSON.
|
| 31 |
+
- Output MUST contain ONLY JSON.
|
| 32 |
+
- Do NOT reveal chain-of-thought.
|
| 33 |
+
- Use double quotes only.
|
| 34 |
+
- Keep structure deterministic across revisions.
|
| 35 |
+
|
| 36 |
+
If information is missing, list it in "needs".
|
| 37 |
+
|
| 38 |
+
JSON CONTRACT:
|
| 39 |
+
{
|
| 40 |
+
"version": "1.0",
|
| 41 |
+
"task": "",
|
| 42 |
+
"assumptions": [],
|
| 43 |
+
"needs": [],
|
| 44 |
+
"candidates": [
|
| 45 |
+
{
|
| 46 |
+
"id": "c1",
|
| 47 |
+
"solution": {},
|
| 48 |
+
"constraints": [
|
| 49 |
+
{"name": "", "status": "pass|fail|unknown", "note": ""}
|
| 50 |
+
],
|
| 51 |
+
"objective_estimate": {"primary": 0.0, "notes": ""},
|
| 52 |
+
"rationale_summary": ""
|
| 53 |
+
}
|
| 54 |
+
],
|
| 55 |
+
"revision_instructions": "If controller feedback arrives, edit only referenced fields and preserve all others exactly."
|
| 56 |
+
}
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# ============================================================
|
| 61 |
+
# 2) Güvenli mini-tool (opsiyonel, math destek)
|
| 62 |
+
# ============================================================
|
| 63 |
+
_ALLOWED_AST = {
|
| 64 |
+
ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
|
| 65 |
+
ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.Mod,
|
| 66 |
+
ast.USub, ast.UAdd,
|
| 67 |
+
}
|
| 68 |
|
| 69 |
+
def safe_calc(expr: str) -> Optional[float]:
|
| 70 |
+
if not re.fullmatch(r"[0-9\.\s\+\-\*\/\(\)]+", expr):
|
| 71 |
+
return None
|
| 72 |
+
try:
|
| 73 |
+
tree = ast.parse(expr, mode="eval")
|
| 74 |
+
for n in ast.walk(tree):
|
| 75 |
+
if type(n) not in _ALLOWED_AST:
|
| 76 |
+
return None
|
| 77 |
+
return float(eval(compile(tree, "<calc>", "eval"), {"__builtins__": {}}))
|
| 78 |
+
except Exception:
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ============================================================
|
| 83 |
+
# 3) Skull (GGUF Math Brain)
|
| 84 |
+
# ============================================================
|
| 85 |
+
@dataclass
|
| 86 |
+
class Skull:
|
| 87 |
+
gguf_path: str
|
| 88 |
+
n_ctx: int = 8192
|
| 89 |
+
n_gpu_layers: int = 0
|
| 90 |
+
chat_format: str = "chatml"
|
| 91 |
+
verbose: bool = False
|
| 92 |
+
|
| 93 |
+
def __post_init__(self):
|
| 94 |
+
self.llm = Llama(
|
| 95 |
+
model_path=self.gguf_path,
|
| 96 |
+
n_ctx=self.n_ctx,
|
| 97 |
+
n_gpu_layers=self.n_gpu_layers,
|
| 98 |
+
chat_format=self.chat_format,
|
| 99 |
+
verbose=self.verbose,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def _parse_json(self, text: str) -> Dict[str, Any]:
|
| 103 |
+
t = text.strip()
|
| 104 |
try:
|
| 105 |
+
return json.loads(t)
|
| 106 |
+
except json.JSONDecodeError:
|
| 107 |
+
s, e = t.find("{"), t.rfind("}")
|
| 108 |
+
if s != -1 and e != -1 and e > s:
|
| 109 |
+
return json.loads(t[s:e+1])
|
| 110 |
+
raise
|
| 111 |
+
|
| 112 |
+
def think(
|
| 113 |
+
self,
|
| 114 |
+
observation: Dict[str, Any],
|
| 115 |
+
temperature: float = 0.2,
|
| 116 |
+
top_p: float = 0.9,
|
| 117 |
+
max_tokens: int = 512,
|
| 118 |
+
) -> Dict[str, Any]:
|
| 119 |
+
|
| 120 |
+
messages = [
|
| 121 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 122 |
+
{"role": "user", "content": json.dumps(observation, ensure_ascii=False)},
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
resp = self.llm.create_chat_completion(
|
| 126 |
+
messages=messages,
|
| 127 |
+
temperature=temperature,
|
| 128 |
+
top_p=top_p,
|
| 129 |
+
max_tokens=max_tokens,
|
| 130 |
+
response_format={"type": "json_object"},
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
content = resp["choices"][0]["message"]["content"]
|
| 134 |
+
return self._parse_json(content)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# ============================================================
|
| 138 |
+
# 4) Objective + Constraint (C)
|
| 139 |
+
# ============================================================
|
| 140 |
+
class ObjectiveEngine:
|
| 141 |
+
"""
|
| 142 |
+
GGUF çıktısını tekrar değerlendiren deterministik katman.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def score(self, result: Dict[str, Any]) -> float:
|
| 146 |
score = 0.0
|
| 147 |
+
|
| 148 |
+
# valid JSON already guaranteed
|
| 149 |
+
cands = result.get("candidates", [])
|
| 150 |
+
if not cands:
|
| 151 |
+
return -1e9
|
| 152 |
+
|
| 153 |
+
c = cands[0]
|
| 154 |
+
|
| 155 |
+
# constraint satisfaction
|
| 156 |
+
for con in c.get("constraints", []):
|
| 157 |
+
if con.get("status") == "pass":
|
| 158 |
+
score += 1.0
|
| 159 |
+
elif con.get("status") == "fail":
|
| 160 |
+
score -= 2.0
|
| 161 |
+
|
| 162 |
+
# model's own estimate
|
| 163 |
+
oe = c.get("objective_estimate", {})
|
| 164 |
+
if isinstance(oe.get("primary"), (int, float)):
|
| 165 |
+
score += float(oe["primary"])
|
| 166 |
+
|
| 167 |
+
# small structure bonus
|
| 168 |
+
if isinstance(c.get("solution"), dict):
|
| 169 |
score += 0.5
|
| 170 |
+
|
| 171 |
return score
|
| 172 |
|
| 173 |
+
|
| 174 |
+
# ============================================================
|
| 175 |
+
# 5) Body (örnek: text body)
|
| 176 |
+
# ============================================================
|
| 177 |
+
class TextBody:
|
| 178 |
+
def observe(self, text: str) -> Dict[str, Any]:
|
| 179 |
+
# İleride image/audio/video/3D body'ler aynı fonksiyonu sağlar
|
| 180 |
+
return {
|
| 181 |
+
"task": "optimization_request",
|
| 182 |
+
"body": "text",
|
| 183 |
+
"input": text,
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# ============================================================
|
| 188 |
+
# 6) Orchestrator (brain loop)
|
| 189 |
+
# ============================================================
|
| 190 |
+
class BrainSystem:
|
| 191 |
+
def __init__(self, skull: Skull, body: Any):
|
| 192 |
+
self.skull = skull
|
| 193 |
+
self.body = body
|
| 194 |
+
self.objective = ObjectiveEngine()
|
| 195 |
+
|
| 196 |
+
def run(self, raw_input: Any, rounds: int = 2) -> Dict[str, Any]:
|
| 197 |
+
obs = self.body.observe(raw_input)
|
| 198 |
+
|
| 199 |
+
best = None
|
| 200 |
+
best_score = -1e18
|
| 201 |
+
|
| 202 |
+
for r in range(rounds):
|
| 203 |
+
result = self.skull.think(obs)
|
| 204 |
+
score = self.objective.score(result)
|
| 205 |
+
|
| 206 |
+
if score > best_score:
|
| 207 |
+
best = result
|
| 208 |
+
best_score = score
|
| 209 |
+
|
| 210 |
+
# revise loop (hafif)
|
| 211 |
+
if result.get("needs"):
|
| 212 |
+
obs["_feedback"] = {
|
| 213 |
+
"issue": "missing_data",
|
| 214 |
+
"needs": result["needs"],
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
return {
|
| 218 |
+
"best_score": best_score,
|
| 219 |
+
"decision": best,
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# ============================================================
|
| 224 |
+
# 7) Demo
|
| 225 |
+
# ============================================================
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
skull = Skull(
|
| 228 |
+
gguf_path="prettybird_bce_basic_brain_mini_q4_k_m.gguf",
|
| 229 |
+
n_ctx=8192,
|
| 230 |
+
n_gpu_layers=0,
|
| 231 |
+
chat_format="chatml",
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
body = TextBody()
|
| 235 |
+
brain = BrainSystem(skull, body)
|
| 236 |
+
|
| 237 |
+
output = brain.run(
|
| 238 |
+
"5 işi 2 makineye ata ve makespan minimize et. Süreler: [3,5,2,6,4].",
|
| 239 |
+
rounds=2,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
print(json.dumps(output, ensure_ascii=False, indent=2))
|