Spaces:
Sleeping
Sleeping
Rajan Sharma
commited on
Update llm_router.py
Browse files- llm_router.py +57 -23
llm_router.py
CHANGED
|
@@ -1,23 +1,57 @@
|
|
| 1 |
-
import
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, List
|
| 2 |
+
import cohere
|
| 3 |
+
from settings import COHERE_API_KEY, COHERE_MODEL_PRIMARY, MODEL_SETTINGS
|
| 4 |
+
from local_llm import LocalLLM
|
| 5 |
+
|
| 6 |
+
_local = None
|
| 7 |
+
|
| 8 |
+
def _local_llm() -> LocalLLM:
|
| 9 |
+
global _local
|
| 10 |
+
if _local is None:
|
| 11 |
+
_local = LocalLLM()
|
| 12 |
+
return _local
|
| 13 |
+
|
| 14 |
+
def cohere_chat(prompt: str) -> Optional[str]:
|
| 15 |
+
if not COHERE_API_KEY:
|
| 16 |
+
return None
|
| 17 |
+
try:
|
| 18 |
+
cli = cohere.Client(api_key=COHERE_API_KEY)
|
| 19 |
+
resp = cli.chat(
|
| 20 |
+
model=COHERE_MODEL_PRIMARY,
|
| 21 |
+
message=prompt,
|
| 22 |
+
temperature=MODEL_SETTINGS["temperature"],
|
| 23 |
+
max_tokens=MODEL_SETTINGS["max_new_tokens"],
|
| 24 |
+
)
|
| 25 |
+
if hasattr(resp, "text") and resp.text: return resp.text
|
| 26 |
+
if hasattr(resp, "reply") and resp.reply: return resp.reply
|
| 27 |
+
if hasattr(resp, "generations") and resp.generations: return resp.generations[0].text
|
| 28 |
+
except Exception:
|
| 29 |
+
return None
|
| 30 |
+
return None
|
| 31 |
+
|
| 32 |
+
def open_fallback_chat(prompt: str) -> Optional[str]:
|
| 33 |
+
return _local_llm().chat(prompt)
|
| 34 |
+
|
| 35 |
+
def generate_narrative(scenario_text: str, structured_sections_md: str, rag_snippets: List[str]) -> str:
|
| 36 |
+
grounding = "\n\n".join([f"[RAG {i+1}]\n{t}" for i, t in enumerate(rag_snippets or [])])
|
| 37 |
+
prompt = f"""You are a Canadian healthcare operations copilot.
|
| 38 |
+
Follow the scenario's requested deliverables exactly. Use the structured computations provided (already calculated deterministically) and the RAG snippets for grounding.
|
| 39 |
+
|
| 40 |
+
# Scenario
|
| 41 |
+
{scenario_text}
|
| 42 |
+
|
| 43 |
+
# Deterministic Results (already computed)
|
| 44 |
+
{structured_sections_md}
|
| 45 |
+
|
| 46 |
+
# Grounding (Canadian sources, snippets)
|
| 47 |
+
{grounding}
|
| 48 |
+
|
| 49 |
+
Write a concise, decision-ready report tailored to provincial operations leaders.
|
| 50 |
+
Do not invent numbers. If data are missing, say so clearly.
|
| 51 |
+
"""
|
| 52 |
+
out = cohere_chat(prompt)
|
| 53 |
+
if out: return out
|
| 54 |
+
out = open_fallback_chat(prompt)
|
| 55 |
+
if out: return out
|
| 56 |
+
return "Unable to generate narrative at this time."
|
| 57 |
+
|