AIencoder commited on
Commit
3d89e37
·
verified ·
1 Parent(s): f5a3945

Update src/chimera_core.py

Browse files
Files changed (1) hide show
  1. src/chimera_core.py +76 -93
src/chimera_core.py CHANGED
@@ -4,7 +4,7 @@ from groq import Groq
4
 
5
  class Chimera:
6
  def __init__(self):
7
- # 1. SETUP GEMINI (The Router & Drafter)
8
  self.gemini_key = os.getenv("GEMINI_API_KEY")
9
  self.gemini_client = None
10
  if self.gemini_key:
@@ -12,112 +12,95 @@ class Chimera:
12
  self.gemini_client = genai.Client(api_key=self.gemini_key)
13
  self.gemini_model = "gemini-2.5-flash"
14
  print(f"🦁 Gemini: ONLINE")
15
- except Exception as e:
16
- print(f"⚠️ Gemini Init Failed: {e}")
17
 
18
- # 2. SETUP GROQ (The Speed Refiner - Llama 3.3)
19
  self.groq_key = os.getenv("GROQ_API_KEY")
20
  self.groq_client = None
21
  if self.groq_key:
22
  try:
23
  self.groq_client = Groq(api_key=self.groq_key)
24
- self.groq_model = "llama-3.3-70b-versatile"
25
- print(f"⚡ Groq (Llama 3.3): ONLINE")
26
- except Exception as e:
27
- print(f"⚠️ Groq Init Failed: {e}")
28
 
29
- def _call_gemini(self, prompt, system_msg="You are a helpful AI."):
30
- if not self.gemini_client: raise Exception("Gemini Down")
31
- response = self.gemini_client.models.generate_content(
32
- model=self.gemini_model,
33
- contents=f"System: {system_msg}\nUser: {prompt}"
34
- )
35
- return response.text
36
-
37
- def _call_groq(self, prompt, system_msg="You are a helpful AI."):
38
- if not self.groq_client: raise Exception("Groq Down")
39
- response = self.groq_client.chat.completions.create(
40
- model=self.groq_model,
41
- messages=[
42
- {"role": "system", "content": system_msg},
43
- {"role": "user", "content": prompt}
44
- ]
45
- )
46
- return response.choices[0].message.content
 
 
 
 
47
 
48
- def _binary_pipeline(self, user_prompt):
49
  """
50
- THE BINARY STAR PIPELINE:
51
- Phase 1: Gemini Drafts (Creative/Logic)
52
- Phase 2: Groq Refines (Optimization/Speed)
 
53
  """
54
- draft_code = ""
55
 
56
- # --- PHASE 1: DRAFTING (Gemini) ---
57
- try:
58
- print(" Phase 1: Gemini Drafting...")
59
- draft_code = self._call_gemini(user_prompt, "Write a Python solution. Be verbose and explanatory.")
60
- except Exception as e:
61
- print(f"⚠️ Gemini Draft Failed: {e}")
62
- # FALLBACK: If Gemini dies, Groq does it all
63
- try:
64
- return self._call_groq(user_prompt, "You are an expert Python Coder."), "ASM (Groq Backup)"
65
- except Exception as e2:
66
- return f"❌ CRITICAL: All models failed.", "ERROR"
67
 
68
- # --- PHASE 2: REFINEMENT (Groq) ---
69
- try:
70
- print(" ↳ Phase 2: Groq Refining...")
71
- refine_prompt = f"""
72
- You are a Senior Principal Engineer. Refine this Junior Developer's code.
73
-
74
- GOALS:
75
- 1. Optimize for speed.
76
- 2. Fix bugs.
77
- 3. Clean up comments.
78
-
79
- DRAFT CODE:
80
- {draft_code}
81
- """
82
- final_code = self._call_groq(refine_prompt, "You are a Senior Engineer.")
83
- return final_code, "ASM (Binary Refined)"
84
- except Exception as e:
85
- # Fallback: Just show the draft if Groq fails
86
- return f"{draft_code}\n\n**[⚠️ Groq Refine Failed. Showing Gemini Draft]**", "ASM (Gemini Draft)"
87
 
88
- def _route_task(self, prompt):
89
- # Quick router using Gemini (or Groq if Gemini is down)
90
- sys = "Classify: [ASM] (Code), [SFE] (Science), [CSM] (Story), [CHAT]. Reply TAG only."
91
- try: return self._call_gemini(prompt, sys).strip().replace("[","").replace("]","")
92
- except:
93
- try: return self._call_groq(prompt, sys).strip().replace("[","").replace("]","")
94
- except: return "CHAT"
 
95
 
96
  def process_request(self, user_message, history, manual_role="Auto"):
97
- # 1. Routing
98
- role = manual_role if manual_role != "Auto" else self._route_task(user_message)
99
- print(f"👉 Routing to: [{role}]")
100
-
101
- try:
102
- # === CODE PATH (ASM) ===
103
- # If we have both models, use the pipeline.
104
- if role == "ASM" and self.groq_client and self.gemini_client:
105
- return self._binary_pipeline(user_message)
106
-
107
- # === SINGLE MODEL PATHS ===
108
- system_instruction = "You are Project Chimera."
109
- if role == "SFE": system_instruction = "You are a Data Scientist."
110
- if role == "CSM": system_instruction = "You are a Creative Writer."
111
 
112
- # Prefer Gemini for creative/long context
113
- try:
114
- return self._call_gemini(user_message, system_instruction), f"{role} (Gemini)"
115
- except:
116
- # Fallback to Groq
117
- try:
118
- return self._call_groq(user_message, system_instruction), f"{role} (Groq)"
119
- except:
120
- return "❌ All systems down.", "OUTAGE"
121
 
122
- except Exception as e:
123
- return f" System Error: {str(e)}", "ERR"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  class Chimera:
6
  def __init__(self):
7
+ # 1. SETUP GEMINI (The Router)
8
  self.gemini_key = os.getenv("GEMINI_API_KEY")
9
  self.gemini_client = None
10
  if self.gemini_key:
 
12
  self.gemini_client = genai.Client(api_key=self.gemini_key)
13
  self.gemini_model = "gemini-2.5-flash"
14
  print(f"🦁 Gemini: ONLINE")
15
+ except: pass
 
16
 
17
+ # 2. SETUP GROQ (The Factory)
18
  self.groq_key = os.getenv("GROQ_API_KEY")
19
  self.groq_client = None
20
  if self.groq_key:
21
  try:
22
  self.groq_client = Groq(api_key=self.groq_key)
23
+ print(f"⚡ Groq (Llama 3.3 + Qwen 2.5): ONLINE")
24
+ except: pass
 
 
25
 
26
+ def _call_model(self, client, model, prompt, system_msg):
27
+ """ Generic handler for any model """
28
+ if not client: return None
29
+ try:
30
+ if "gemini" in model:
31
+ res = client.models.generate_content(
32
+ model=model, contents=f"System: {system_msg}\nUser: {prompt}"
33
+ )
34
+ return res.text
35
+ else:
36
+ # Groq / OpenAI style
37
+ res = client.chat.completions.create(
38
+ model=model,
39
+ messages=[
40
+ {"role": "system", "content": system_msg},
41
+ {"role": "user", "content": prompt}
42
+ ]
43
+ )
44
+ return res.choices[0].message.content
45
+ except Exception as e:
46
+ print(f"⚠️ Error calling {model}: {e}")
47
+ return None
48
 
49
+ def _trinity_pipeline(self, user_prompt):
50
  """
51
+ THE QWEN TRINITY:
52
+ 1. Gemini: Plan (Strategy)
53
+ 2. Qwen 2.5: Code (Draft)
54
+ 3. Llama 3.3: Refine (Polish)
55
  """
56
+ log = []
57
 
58
+ # --- PHASE 1: STRATEGY (Gemini) ---
59
+ print(" ↳ Phase 1: Gemini Planning...")
60
+ strategy = self._call_model(self.gemini_client, "gemini-2.5-flash", user_prompt, "You are a Software Architect. Outline the logic for this code task.")
61
+ if not strategy: strategy = user_prompt
 
 
 
 
 
 
 
62
 
63
+ # --- PHASE 2: DRAFTING (Qwen 2.5 - The Coder) ---
64
+ print(" ↳ Phase 2: Qwen Coding...")
65
+ # Note: Groq model ID for Qwen 2.5 32B
66
+ qwen_code = self._call_model(self.groq_client, "qwen-2.5-32b", f"Plan: {strategy}\n\nTask: {user_prompt}", "You are an expert Python Developer. Write the code.")
67
+
68
+ if not qwen_code:
69
+ return "❌ Qwen failed to generate code.", "ERROR"
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ # --- PHASE 3: REFINEMENT (Llama 3.3 - The Critic) ---
72
+ print(" ↳ Phase 3: Llama Refining...")
73
+ final_code = self._call_model(self.groq_client, "llama-3.3-70b-versatile", f"Refine this code:\n{qwen_code}", "You are a Senior Engineer. Fix bugs, optimize, and add comments.")
74
+
75
+ if final_code:
76
+ return final_code, "ASM (Qwen + Llama)"
77
+ else:
78
+ return qwen_code, "ASM (Qwen Draft)"
79
 
80
  def process_request(self, user_message, history, manual_role="Auto"):
81
+ # Router logic
82
+ role = manual_role
83
+ if role == "Auto":
84
+ # Simple keyword check for speed
85
+ if any(x in user_message.lower() for x in ["code", "python", "function", "script", "app"]):
86
+ role = "ASM"
87
+ else:
88
+ role = "CHAT"
 
 
 
 
 
 
89
 
90
+ print(f"👉 Routing to: [{role}]")
 
 
 
 
 
 
 
 
91
 
92
+ # Execute
93
+ if role == "ASM" and self.groq_client:
94
+ return self._trinity_pipeline(user_message)
95
+
96
+ elif role == "SFE":
97
+ # Use Llama for Science
98
+ return self._call_model(self.groq_client, "llama-3.3-70b-versatile", user_message, "You are a Scientist."), "SFE (Llama)"
99
+
100
+ elif role == "CSM":
101
+ # Use Gemini for Stories
102
+ return self._call_model(self.gemini_client, "gemini-2.5-flash", user_message, "You are a Creative Writer."), "CSM (Gemini)"
103
+
104
+ else:
105
+ # Default Chat (Gemini)
106
+ return self._call_model(self.gemini_client, "gemini-2.5-flash", user_message, "You are Chimera."), "CHAT"