Spaces:
Running
Running
Rachit-Mangawa commited on
Commit ·
9e6280a
1
Parent(s): d892581
feat: implement high-intelligence model rotation pool (v8.0) and align infrastructure
Browse files
app.py
CHANGED
|
@@ -4,25 +4,21 @@ import logging
|
|
| 4 |
import asyncio
|
| 5 |
import time
|
| 6 |
import re
|
| 7 |
-
import random
|
| 8 |
from typing import List, Dict, Any, Optional
|
| 9 |
-
from fastapi import FastAPI
|
| 10 |
from pydantic import BaseModel
|
| 11 |
import httpx
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
|
| 14 |
load_dotenv()
|
| 15 |
|
| 16 |
-
# Vera Engine -
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
| 18 |
-
logger = logging.getLogger("
|
| 19 |
|
| 20 |
app = FastAPI()
|
| 21 |
|
| 22 |
-
# --- 1. Infrastructure &
|
| 23 |
-
# If FAST_TEST=true, skip cloud tiers for local debugging speed.
|
| 24 |
-
FAST_TEST = os.getenv("FAST_TEST", "false").lower() == "true"
|
| 25 |
-
|
| 26 |
class ContextPayload(BaseModel):
|
| 27 |
scope: Optional[str] = None
|
| 28 |
context_id: Optional[str] = None
|
|
@@ -71,22 +67,33 @@ class Agent:
|
|
| 71 |
def check_health(self):
|
| 72 |
if not self.is_healthy and time.time() > self.cooldown_until:
|
| 73 |
self.is_healthy = True
|
| 74 |
-
logger.info(f"Agent {self.name} is healthy again")
|
| 75 |
return self.is_healthy and len(self.keys) > 0
|
| 76 |
|
| 77 |
class LocalAgent(Agent):
|
| 78 |
def __init__(self):
|
| 79 |
super().__init__("LocalOllama", "ollama", "llama3.2", 5)
|
| 80 |
-
self.keys = ["local"]
|
| 81 |
def check_health(self): return True
|
| 82 |
|
| 83 |
-
# Initialize Registry
|
| 84 |
AGENT_REGISTRY: List[Agent] = [
|
|
|
|
| 85 |
Agent("Cloud-OpenRouter-Laguna", "openrouter", "poolside/laguna-m.1:free", 1),
|
| 86 |
Agent("Cloud-OpenRouter-Hy3", "openrouter", "tencent/hy3:free", 1),
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
Agent("Cloud-Groq-Llama", "groq", "llama-3.3-70b-versatile", 3),
|
|
|
|
|
|
|
| 89 |
Agent("Cloud-DeepSeek-Chat", "deepseek", "deepseek-chat", 4),
|
|
|
|
|
|
|
| 90 |
LocalAgent()
|
| 91 |
]
|
| 92 |
|
|
@@ -95,25 +102,18 @@ llm_semaphore_local = asyncio.Semaphore(1)
|
|
| 95 |
|
| 96 |
# --- 3. Orchestration Logic ---
|
| 97 |
async def call_llm_chain(prompt: str, system: str = "") -> Optional[Dict]:
|
| 98 |
-
if FAST_TEST:
|
| 99 |
-
logger.info("FAST_TEST enabled: Skipping cloud tiers.")
|
| 100 |
-
return await call_local_agent(AGENT_REGISTRY[-1], prompt, system)
|
| 101 |
-
|
| 102 |
json_suffix = "\n\nRETURN JSON ONLY: {\"body\": \"...\", \"cta\": \"...\", \"rationale\": \"...\"}"
|
| 103 |
full_system = system + json_suffix
|
| 104 |
|
| 105 |
-
# Iterate through tiers
|
| 106 |
for tier in range(1, 6):
|
| 107 |
-
tier_agents = [a for
|
| 108 |
for agent in tier_agents:
|
| 109 |
res = await execute_agent(agent, prompt, full_system if agent.tier < 5 else system)
|
| 110 |
if res: return res
|
| 111 |
return None
|
| 112 |
|
| 113 |
async def execute_agent(agent: Agent, prompt: str, system: str) -> Optional[Dict]:
|
| 114 |
-
if agent.provider == "ollama":
|
| 115 |
-
return await call_local_agent(agent, prompt, system)
|
| 116 |
-
|
| 117 |
key = await agent.get_key()
|
| 118 |
if not key: return None
|
| 119 |
|
|
@@ -122,33 +122,18 @@ async def execute_agent(agent: Agent, prompt: str, system: str) -> Optional[Dict
|
|
| 122 |
if agent.provider == "openrouter":
|
| 123 |
res = await client.post("https://openrouter.ai/api/v1/chat/completions",
|
| 124 |
headers={"Authorization": f"Bearer {key}", "HTTP-Referer": "https://vera.ai", "X-Title": "Vera Platinum"},
|
| 125 |
-
json={
|
| 126 |
-
"model": agent.model,
|
| 127 |
-
"messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}],
|
| 128 |
-
"response_format": {"type": "json_object"}
|
| 129 |
-
}, timeout=5.0) # Tightened to 5s for chain speed
|
| 130 |
-
|
| 131 |
elif agent.provider == "gemini":
|
| 132 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/{agent.model}:generateContent?key={key}"
|
| 133 |
-
res = await client.post(url, json={"contents": [{"parts": [{"text": f"System: {system}\n\nUser: {prompt}"}]}]}, timeout=
|
| 134 |
-
|
| 135 |
elif agent.provider == "groq":
|
| 136 |
res = await client.post("https://api.groq.com/openai/v1/chat/completions",
|
| 137 |
headers={"Authorization": f"Bearer {key}"},
|
| 138 |
-
json={
|
| 139 |
-
"model": agent.model,
|
| 140 |
-
"messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}],
|
| 141 |
-
"response_format": {"type": "json_object"}
|
| 142 |
-
}, timeout=5.0)
|
| 143 |
-
|
| 144 |
elif agent.provider == "deepseek":
|
| 145 |
res = await client.post("https://api.deepseek.com/chat/completions",
|
| 146 |
headers={"Authorization": f"Bearer {key}"},
|
| 147 |
-
json={
|
| 148 |
-
"model": agent.model,
|
| 149 |
-
"messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}],
|
| 150 |
-
"response_format": {"type": "json_object"}
|
| 151 |
-
}, timeout=5.0)
|
| 152 |
|
| 153 |
if res.status_code == 200:
|
| 154 |
if agent.provider == "gemini":
|
|
@@ -156,33 +141,21 @@ async def execute_agent(agent: Agent, prompt: str, system: str) -> Optional[Dict
|
|
| 156 |
text = re.sub(r'```json\n?|\n?```', '', text).strip()
|
| 157 |
return json.loads(text)
|
| 158 |
return json.loads(res.json()["choices"][0]["message"]["content"])
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
else:
|
| 163 |
-
agent.mark_unhealthy()
|
| 164 |
-
except Exception:
|
| 165 |
-
pass
|
| 166 |
return None
|
| 167 |
|
| 168 |
async def call_local_agent(agent: Agent, prompt: str, system: str) -> Optional[Dict]:
|
| 169 |
async with llm_semaphore_local:
|
| 170 |
-
|
| 171 |
-
payload = {
|
| 172 |
-
"model": agent.model,
|
| 173 |
-
"prompt": f"System: {system}\nStrict Grounding. No Fabrication. Context: {prompt}\nUser: Return JSON message.",
|
| 174 |
-
"stream": False, "format": "json", "options": {"num_predict": 80, "temperature": 0.1}
|
| 175 |
-
}
|
| 176 |
async with httpx.AsyncClient() as client:
|
| 177 |
try:
|
| 178 |
-
|
| 179 |
-
res = await client.post("http://127.0.0.1:11434/api/generate", json=payload, timeout=28.0)
|
| 180 |
if res.status_code == 200: return json.loads(res.json().get('response', '{}'))
|
| 181 |
-
except
|
| 182 |
-
logger.error(f"Local Model Error: {e}")
|
| 183 |
-
return None
|
| 184 |
|
| 185 |
-
# --- 4.
|
| 186 |
def prune_message(text: str) -> str:
|
| 187 |
text = text.replace("\n", " ").strip()
|
| 188 |
if len(text) <= 315: return text
|
|
@@ -203,45 +176,24 @@ async def compose(category: dict, merchant: dict, trigger: dict, customer: Optio
|
|
| 203 |
hinglish_note = "USE NATURAL HINGLISH (50% English words, 50% Hindi script/transliteration)." if 'hi' in lang_pref else "USE PROFESSIONAL ENGLISH."
|
| 204 |
|
| 205 |
primary_metric = list(m.items())[0] if m else None
|
| 206 |
-
|
| 207 |
-
evidence_block = ""
|
| 208 |
-
if primary_metric: evidence_block += f"MANDATORY METRIC: '{primary_metric[0]}' is {primary_metric[1]}. "
|
| 209 |
-
if verbatim_source: evidence_block += f"MANDATORY CITATION: '{verbatim_source}'. "
|
| 210 |
-
|
| 211 |
-
beats = category.get("seasonal_beats", [])
|
| 212 |
-
knowledge_anchor = f"INDUSTRY CONTEXT: {beats[0].get('note', '')}. " if beats else ""
|
| 213 |
|
| 214 |
sys_prompt = f"""Role: Elite Growth Strategist. Target: {prefix} {owner_name} in {ident.get('locality')}.
|
| 215 |
-
Objective:
|
| 216 |
-
RULES:
|
| 217 |
-
|
| 218 |
-
2. NO FABRICATION: Use only context numbers. EVIDENCE: {evidence_block}
|
| 219 |
-
3. CONTEXT: {knowledge_anchor}
|
| 220 |
-
4. TONE: {hinglish_note} Professional clinical-peer tone for dentists.
|
| 221 |
-
5. LIMIT: 280-310 characters."""
|
| 222 |
-
|
| 223 |
-
prompt = f"CONTEXT: {json.dumps({'merchant': ident, 'perf': m, 'trigger': trigger, 'customer': customer})}"
|
| 224 |
res = await call_llm_chain(prompt, system=sys_prompt)
|
| 225 |
if not res:
|
| 226 |
-
|
| 227 |
-
body = f"{prefix} {owner_name}, noticed {v} views and {c} calls in {ident.get('locality')}. Important growth update found. Review now?"
|
| 228 |
-
res = {"body": body, "cta": "Reply YES", "rationale": "Hard Fallback"}
|
| 229 |
res["body"] = prune_message(res.get("body", ""))
|
| 230 |
return res
|
| 231 |
|
| 232 |
# --- 5. Endpoints ---
|
| 233 |
-
@app.on_event("startup")
|
| 234 |
-
async def startup_event():
|
| 235 |
-
logger.info("Initializing Agent Registry...")
|
| 236 |
-
for agent in AGENT_REGISTRY:
|
| 237 |
-
logger.info(f"Agent {agent.name} initialized with {len(agent.keys)} keys")
|
| 238 |
-
|
| 239 |
@app.get("/v1/healthz")
|
| 240 |
async def healthz(): return {"status": "ok"}
|
| 241 |
|
| 242 |
@app.get("/v1/metadata")
|
| 243 |
-
async def metadata():
|
| 244 |
-
return {"team_name": "Vera Lead Solver", "version": "7.0", "engine": "Multi-Agent-Orchestrator"}
|
| 245 |
|
| 246 |
@app.post("/v1/context")
|
| 247 |
def push_context(data: ContextPayload):
|
|
@@ -252,7 +204,6 @@ def push_context(data: ContextPayload):
|
|
| 252 |
async def tick(req: TickRequest):
|
| 253 |
tids = sorted(req.available_triggers, key=lambda t: contexts["trigger"].get(t, {}).get("kind", ""), reverse=True)
|
| 254 |
results = []
|
| 255 |
-
# Sequential processing. Limit to 1 to stay under 30s.
|
| 256 |
for tid in tids[:1]:
|
| 257 |
res = await process_trigger(tid)
|
| 258 |
if res: results.append(res)
|
|
@@ -265,44 +216,29 @@ async def process_trigger(trigger_id: str):
|
|
| 265 |
category = contexts["category"].get(merchant.get("category_slug", ""), {"slug": "general"})
|
| 266 |
customer = contexts["customer"].get(trigger.get("customer_id"))
|
| 267 |
composed = await compose(category, merchant, trigger, customer)
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
return {
|
| 271 |
-
"conversation_id": f"conv_{trigger_id}", "merchant_id": trigger.get("merchant_id"),
|
| 272 |
-
"customer_id": trigger.get("customer_id") if is_customer_facing else None,
|
| 273 |
-
"send_as": "merchant_on_behalf" if is_customer_facing else "vera",
|
| 274 |
-
"trigger_id": trigger_id, "template_name": "vera_platinum_v7",
|
| 275 |
-
"body": composed["body"], "cta": composed["cta"], "suppression_key": trigger_id,
|
| 276 |
-
"rationale": composed.get("rationale", "Orchestrated Inference")
|
| 277 |
-
}
|
| 278 |
|
| 279 |
AUTO_REPLY_PATTERNS = [r"thank you for contacting", r"we are currently away", r"automated message", r"business hours", r"auto-reply"]
|
| 280 |
-
HOSTILE_PATTERNS = [r"stop", r"spam", r"useless", r"abuse"
|
| 281 |
-
INTENT_PATTERNS = [r"\bok\b", r"\byes\b", r"\bdo it\b", r"let'?s do it", r"\bsure\b"
|
| 282 |
|
| 283 |
@app.post("/v1/reply")
|
| 284 |
async def reply(req: Dict[str, Any]):
|
| 285 |
-
msg = req.get("message", "").lower()
|
| 286 |
-
turn = req.get("turn_number", 1)
|
| 287 |
for p in HOSTILE_PATTERNS:
|
| 288 |
-
if re.search(p, msg): return {"action": "end", "rationale": "Hostility
|
| 289 |
for p in AUTO_REPLY_PATTERNS:
|
| 290 |
if re.search(p, msg):
|
| 291 |
if turn > 2: return {"action": "end", "rationale": "Repeated auto-reply."}
|
| 292 |
return {"action": "wait", "wait_seconds": 3600, "rationale": "Auto-reply wait."}
|
| 293 |
for p in INTENT_PATTERNS:
|
| 294 |
if re.search(p, msg):
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
body = res.get("body", "I'm setting that up for you now.") if res else "I'm setting that up now."
|
| 298 |
-
return {"action": "send", "body": body, "cta": "Reply YES", "rationale": "Intent Transition."}
|
| 299 |
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
res = await call_llm_chain(prompt, system=sys)
|
| 303 |
-
body = res.get("body", "I'm on it. Setting that up for you now. Ready?") if res else "Understood. I'll get that started. Ready?"
|
| 304 |
-
return {"action": "send", "body": body, "cta": "Reply YES"}
|
| 305 |
|
| 306 |
if __name__ == "__main__":
|
| 307 |
import uvicorn
|
| 308 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
|
|
|
| 4 |
import asyncio
|
| 5 |
import time
|
| 6 |
import re
|
|
|
|
| 7 |
from typing import List, Dict, Any, Optional
|
| 8 |
+
from fastapi import FastAPI
|
| 9 |
from pydantic import BaseModel
|
| 10 |
import httpx
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
|
| 13 |
load_dotenv()
|
| 14 |
|
| 15 |
+
# Vera Engine - High-Intelligence Model Rotation Pool (v8.0)
|
| 16 |
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger("VeraArchitect")
|
| 18 |
|
| 19 |
app = FastAPI()
|
| 20 |
|
| 21 |
+
# --- 1. Infrastructure & Elasticity ---
|
|
|
|
|
|
|
|
|
|
| 22 |
class ContextPayload(BaseModel):
|
| 23 |
scope: Optional[str] = None
|
| 24 |
context_id: Optional[str] = None
|
|
|
|
| 67 |
def check_health(self):
|
| 68 |
if not self.is_healthy and time.time() > self.cooldown_until:
|
| 69 |
self.is_healthy = True
|
|
|
|
| 70 |
return self.is_healthy and len(self.keys) > 0
|
| 71 |
|
| 72 |
class LocalAgent(Agent):
|
| 73 |
def __init__(self):
|
| 74 |
super().__init__("LocalOllama", "ollama", "llama3.2", 5)
|
| 75 |
+
self.keys = ["local"]
|
| 76 |
def check_health(self): return True
|
| 77 |
|
| 78 |
+
# Initialize High-Intelligence Registry
|
| 79 |
AGENT_REGISTRY: List[Agent] = [
|
| 80 |
+
# Tier 1: Cloud Speed
|
| 81 |
Agent("Cloud-OpenRouter-Laguna", "openrouter", "poolside/laguna-m.1:free", 1),
|
| 82 |
Agent("Cloud-OpenRouter-Hy3", "openrouter", "tencent/hy3:free", 1),
|
| 83 |
+
|
| 84 |
+
# Tier 2: Intelligence Pool (Sequential Rotation)
|
| 85 |
+
Agent("Cloud-Gemini-3-Lead", "gemini", "gemini-3-flash", 2),
|
| 86 |
+
Agent("Cloud-Gemini-2.5-Stable", "gemini", "gemini-2.5-flash", 2),
|
| 87 |
+
Agent("Cloud-Gemini-2.5-Lite", "gemini", "gemini-2.5-flash-lite", 2),
|
| 88 |
+
Agent("Cloud-Gemma-4-Reasoning", "gemini", "gemma-4-31b-it", 2),
|
| 89 |
+
|
| 90 |
+
# Tier 3: Throughput
|
| 91 |
Agent("Cloud-Groq-Llama", "groq", "llama-3.3-70b-versatile", 3),
|
| 92 |
+
|
| 93 |
+
# Tier 4: Fallback
|
| 94 |
Agent("Cloud-DeepSeek-Chat", "deepseek", "deepseek-chat", 4),
|
| 95 |
+
|
| 96 |
+
# Tier 5: Local
|
| 97 |
LocalAgent()
|
| 98 |
]
|
| 99 |
|
|
|
|
| 102 |
|
| 103 |
# --- 3. Orchestration Logic ---
|
| 104 |
async def call_llm_chain(prompt: str, system: str = "") -> Optional[Dict]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
json_suffix = "\n\nRETURN JSON ONLY: {\"body\": \"...\", \"cta\": \"...\", \"rationale\": \"...\"}"
|
| 106 |
full_system = system + json_suffix
|
| 107 |
|
|
|
|
| 108 |
for tier in range(1, 6):
|
| 109 |
+
tier_agents = [a for a in AGENT_REGISTRY if a.tier == tier and a.check_health()]
|
| 110 |
for agent in tier_agents:
|
| 111 |
res = await execute_agent(agent, prompt, full_system if agent.tier < 5 else system)
|
| 112 |
if res: return res
|
| 113 |
return None
|
| 114 |
|
| 115 |
async def execute_agent(agent: Agent, prompt: str, system: str) -> Optional[Dict]:
|
| 116 |
+
if agent.provider == "ollama": return await call_local_agent(agent, prompt, system)
|
|
|
|
|
|
|
| 117 |
key = await agent.get_key()
|
| 118 |
if not key: return None
|
| 119 |
|
|
|
|
| 122 |
if agent.provider == "openrouter":
|
| 123 |
res = await client.post("https://openrouter.ai/api/v1/chat/completions",
|
| 124 |
headers={"Authorization": f"Bearer {key}", "HTTP-Referer": "https://vera.ai", "X-Title": "Vera Platinum"},
|
| 125 |
+
json={"model": agent.model, "messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}], "response_format": {"type": "json_object"}}, timeout=7.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
elif agent.provider == "gemini":
|
| 127 |
url = f"https://generativelanguage.googleapis.com/v1beta/models/{agent.model}:generateContent?key={key}"
|
| 128 |
+
res = await client.post(url, json={"contents": [{"parts": [{"text": f"System: {system}\n\nUser: {prompt}"}]}]}, timeout=7.0)
|
|
|
|
| 129 |
elif agent.provider == "groq":
|
| 130 |
res = await client.post("https://api.groq.com/openai/v1/chat/completions",
|
| 131 |
headers={"Authorization": f"Bearer {key}"},
|
| 132 |
+
json={"model": agent.model, "messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}], "response_format": {"type": "json_object"}}, timeout=7.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
elif agent.provider == "deepseek":
|
| 134 |
res = await client.post("https://api.deepseek.com/chat/completions",
|
| 135 |
headers={"Authorization": f"Bearer {key}"},
|
| 136 |
+
json={"model": agent.model, "messages": [{"role": "system", "content": system}, {"role": "user", "content": prompt}], "response_format": {"type": "json_object"}}, timeout=7.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
if res.status_code == 200:
|
| 139 |
if agent.provider == "gemini":
|
|
|
|
| 141 |
text = re.sub(r'```json\n?|\n?```', '', text).strip()
|
| 142 |
return json.loads(text)
|
| 143 |
return json.loads(res.json()["choices"][0]["message"]["content"])
|
| 144 |
+
if res.status_code in [401, 429]: agent.rotate_key()
|
| 145 |
+
else: agent.mark_unhealthy()
|
| 146 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
return None
|
| 148 |
|
| 149 |
async def call_local_agent(agent: Agent, prompt: str, system: str) -> Optional[Dict]:
|
| 150 |
async with llm_semaphore_local:
|
| 151 |
+
payload = {"model": agent.model, "prompt": f"System: {system}\nContext: {prompt}\nUser: Return JSON message.", "stream": False, "format": "json", "options": {"num_predict": 80, "temperature": 0.1}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
async with httpx.AsyncClient() as client:
|
| 153 |
try:
|
| 154 |
+
res = await client.post("http://127.0.0.1:11434/api/generate", json=payload, timeout=90.0)
|
|
|
|
| 155 |
if res.status_code == 200: return json.loads(res.json().get('response', '{}'))
|
| 156 |
+
except: return None
|
|
|
|
|
|
|
| 157 |
|
| 158 |
+
# --- 4. Core Logic ---
|
| 159 |
def prune_message(text: str) -> str:
|
| 160 |
text = text.replace("\n", " ").strip()
|
| 161 |
if len(text) <= 315: return text
|
|
|
|
| 176 |
hinglish_note = "USE NATURAL HINGLISH (50% English words, 50% Hindi script/transliteration)." if 'hi' in lang_pref else "USE PROFESSIONAL ENGLISH."
|
| 177 |
|
| 178 |
primary_metric = list(m.items())[0] if m else None
|
| 179 |
+
evidence_block = f"MANDATORY METRIC: '{primary_metric[0]}' is {primary_metric[1]}. MANDATORY CITATION: '{str(payload)[:150]}'." if primary_metric else "Use curiosity hook."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
sys_prompt = f"""Role: Elite Growth Strategist. Target: {prefix} {owner_name} in {ident.get('locality')}.
|
| 182 |
+
Objective: WhatsApp growth message.
|
| 183 |
+
RULES: 1. TRIGGER PRIMACY: Address {trigger.get('kind')}. 2. NO FABRICATION. {evidence_block} 3. TONE: {hinglish_note} 4. LIMIT: 280-310 chars."""
|
| 184 |
+
prompt = f"CONTEXT: {json.dumps({'merchant': ident, 'trigger': trigger})}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
res = await call_llm_chain(prompt, system=sys_prompt)
|
| 186 |
if not res:
|
| 187 |
+
res = {"body": f"{prefix} {owner_name}, noticed update in {ident.get('locality')}. Review growth opportunity now?", "cta": "Reply YES", "rationale": "Hard Fallback"}
|
|
|
|
|
|
|
| 188 |
res["body"] = prune_message(res.get("body", ""))
|
| 189 |
return res
|
| 190 |
|
| 191 |
# --- 5. Endpoints ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
@app.get("/v1/healthz")
|
| 193 |
async def healthz(): return {"status": "ok"}
|
| 194 |
|
| 195 |
@app.get("/v1/metadata")
|
| 196 |
+
async def metadata(): return {"team_name": "Vera Lead Solver", "version": "8.0", "engine": "High-Intelligence-Registry"}
|
|
|
|
| 197 |
|
| 198 |
@app.post("/v1/context")
|
| 199 |
def push_context(data: ContextPayload):
|
|
|
|
| 204 |
async def tick(req: TickRequest):
|
| 205 |
tids = sorted(req.available_triggers, key=lambda t: contexts["trigger"].get(t, {}).get("kind", ""), reverse=True)
|
| 206 |
results = []
|
|
|
|
| 207 |
for tid in tids[:1]:
|
| 208 |
res = await process_trigger(tid)
|
| 209 |
if res: results.append(res)
|
|
|
|
| 216 |
category = contexts["category"].get(merchant.get("category_slug", ""), {"slug": "general"})
|
| 217 |
customer = contexts["customer"].get(trigger.get("customer_id"))
|
| 218 |
composed = await compose(category, merchant, trigger, customer)
|
| 219 |
+
return {"conversation_id": f"conv_{trigger_id}", "merchant_id": trigger.get("merchant_id"), "trigger_id": trigger_id, "body": composed["body"], "cta": composed["cta"]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
AUTO_REPLY_PATTERNS = [r"thank you for contacting", r"we are currently away", r"automated message", r"business hours", r"auto-reply"]
|
| 222 |
+
HOSTILE_PATTERNS = [r"stop", r"spam", r"useless", r"abuse"]
|
| 223 |
+
INTENT_PATTERNS = [r"\bok\b", r"\byes\b", r"\bdo it\b", r"let'?s do it", r"\bsure\b"]
|
| 224 |
|
| 225 |
@app.post("/v1/reply")
|
| 226 |
async def reply(req: Dict[str, Any]):
|
| 227 |
+
msg, turn = req.get("message", "").lower(), req.get("turn_number", 1)
|
|
|
|
| 228 |
for p in HOSTILE_PATTERNS:
|
| 229 |
+
if re.search(p, msg): return {"action": "end", "rationale": "Hostility."}
|
| 230 |
for p in AUTO_REPLY_PATTERNS:
|
| 231 |
if re.search(p, msg):
|
| 232 |
if turn > 2: return {"action": "end", "rationale": "Repeated auto-reply."}
|
| 233 |
return {"action": "wait", "wait_seconds": 3600, "rationale": "Auto-reply wait."}
|
| 234 |
for p in INTENT_PATTERNS:
|
| 235 |
if re.search(p, msg):
|
| 236 |
+
res = await call_llm_chain(f"Merchant said: {msg}", system="Role: Vera AI. Interest detected. Provide EXACT next step action. 15 words max.")
|
| 237 |
+
return {"action": "send", "body": res.get("body", "I'm setting that up for you now.") if res else "I'm setting that up now.", "cta": "Reply YES"}
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
res = await call_llm_chain(f"Merchant: {msg}", system="Role: Vera AI. Growth Strategist. Be concise.")
|
| 240 |
+
return {"action": "send", "body": res.get("body", "Understood. Proceed?") if res else "Understood. Proceed?", "cta": "Reply YES"}
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
if __name__ == "__main__":
|
| 243 |
import uvicorn
|
| 244 |
+
uvicorn.run(app, host="0.0.0.0", port=8080)
|