# orchestrator.py
from typing import TypedDict, Optional, Literal, Any, Dict, List
from collections import Counter
import json
import re
from langgraph.graph import StateGraph, START, END
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate
from langchain.schema import SystemMessage, HumanMessage
from langchain_databricks import ChatDatabricks # Llama served via Databricks
from langchain.chains import RetrievalQA
# ---------------------------------------
# LLMs and RAG (initialize once at app startup)
# ---------------------------------------
# Llama for intent + guard (small, fast)
llm_intent = ChatDatabricks(
endpoint="llama-intent-endpoint", # Databricks Model Serving endpoint name
max_tokens=128,
temperature=0.0,
)
# Llama (or DBRX) for analysis / RAG
llm_main = ChatDatabricks(
endpoint="llama-70b-instruct", # or dbrx-instruct, etc.
max_tokens=800,
temperature=0.2,
)
# Your retriever (Databricks Vector Search or other)
# Example: rag_chain = RetrievalQA.from_chain_type(llm=llm_main, retriever=retriever, chain_type="stuff")
rag_chain: RetrievalQA = ... # prebuilt elsewhere and imported
# Helper: fetch docs given query + filters (wrap your vector search)
def retrieve_docs(query: str, filters: Dict[str, Any], k: int = 50) -> List[Document]:
# Implement using your Databricks Vector Search retriever with metadata filters
# e.g., retriever.get_relevant_documents(query, filters={"medicine_name": ..., "geography": ...})
return [] # TODO: replace with your retrieval
# Helper: fetch docs for filters only (no query)
def retrieve_docs_by_filter(filters: Dict[str, Any], k: int = 200) -> List[Document]:
# Implement a filtered retrieval via vector search or Delta query fallback
return [] # TODO: replace with your retrieval
# ---------------------------------------
# Graph State
# ---------------------------------------
class GraphState(TypedDict, total=False):
query: str
filters: Dict[str, Any]
intent: Literal["summarization", "topic_mining", "aspect_sentiment", "sentiment_scores", "general", "reject"]
aspect: Optional[str]
output: Dict[str, Any]
# ---------------------------------------
# Node: Intent Classifier (Llama)
# ---------------------------------------
def classify_intent(state: GraphState) -> GraphState:
query = state["query"]
system = """You are an intent classifier for KOL oncology review analysis.
Allowed intents:
- summarization (user asks to summarize reviews)
- topic_mining (user asks for topics/themes)
- aspect_sentiment (user asks sentiment about a specific aspect, e.g., efficacy, safety, tolerability, dosing, QoL, biomarkers, resistance)
- sentiment_scores (user asks for numeric sentiment metrics or distributions)
- other (anything else)
If aspect_sentiment, extract the aspect (a short lowercase noun phrase).
Return strict JSON with keys: intent (string), aspect (string|null)."""
human = f"Query: {query}\nReturn JSON only."
resp = llm_intent.invoke([SystemMessage(content=system), HumanMessage(content=human)])
text = resp.content.strip()
# Robust JSON parse
intent = "general"
aspect = None
try:
data = json.loads(text)
intent_raw = str(data.get("intent", "")).lower().strip()
aspect_val = data.get("aspect")
if intent_raw in {"summarization", "topic_mining", "aspect_sentiment", "sentiment_scores"}:
intent = intent_raw
else:
intent = "general"
if intent == "aspect_sentiment" and isinstance(aspect_val, str) and aspect_val:
aspect = aspect_val.strip().lower()
except Exception:
# Fallback heuristics if JSON fails
q = query.lower()
if any(w in q for w in ["summarize", "summary", "overview", "synthesize", "recap"]):
intent = "summarization"
elif any(w in q for w in ["topic", "themes", "key topics", "main themes"]):
intent = "topic_mining"
elif re.search(r"(sentiment|opinion).*(efficacy|safety|tolerability|toxicity|qol|quality of life|biomarker|biomarkers|resistance|dosing|schedule|cost|convenience)", q):
intent = "aspect_sentiment"
m = re.search(r"(efficacy|safety|tolerability|toxicity|qol|quality of life|biomarker[s]?|resistance|dosing|schedule|cost|convenience)", q)
aspect = m.group(1) if m else None
elif any(w in q for w in ["sentiment score", "average score", "score trend", "distribution", "polarity"]):
intent = "sentiment_scores"
else:
intent = "general"
return {"intent": intent, "aspect": aspect}
# ---------------------------------------
# Node: Medical Guard (Llama)
# ---------------------------------------
def medical_guard(state: GraphState) -> GraphState:
query = state["query"]
system = """Classify whether the user's query is medical/clinical/oncology-related.
Answer strictly with 'yes' or 'no' (lowercase)."""
human = f"Query: {query}"
resp = llm_intent.invoke([SystemMessage(content=system), HumanMessage(content=human)])
answer = resp.content.strip().lower()
if answer == "yes":
return {} # allowed, continue
else:
return {
"intent": "reject",
"output": {
"intent": "reject",
"error": "Only medical/oncology-related queries are supported for general Q&A.",
},
}
# ---------------------------------------
# Node: Summarization
# ---------------------------------------
def node_summarization(state: GraphState) -> GraphState:
filters = state.get("filters", {})
docs = retrieve_docs_by_filter(filters, k=200) # filtered corpus
text_chunks = "\n\n".join(d.page_content[:1000] for d in docs[:20]) # cap to keep prompt small
prompt = ChatPromptTemplate.from_messages([
("system", "You are an oncology KOL review analyst. Summarize clinical perspectives with evidence."),
("human", "Summarize the following KOL review excerpts with focus on efficacy, safety, patient selection, and practice impact.\n\n{ctx}\n\nReturn a concise, structured summary with bullets and cite short quotes where useful.")
])
msg = prompt.format_messages(ctx=text_chunks)
resp = llm_main.invoke(msg)
return {
"output": {
"intent": "summarization",
"summary": resp.content.strip(),
"n_reviews_used": len(docs),
}
}
# ---------------------------------------
# Node: Topic Mining (use metadata + optional LLM grouping)
# ---------------------------------------
def node_topic_mining(state: GraphState) -> GraphState:
filters = state.get("filters", {})
docs = retrieve_docs_by_filter(filters, k=500)
# Aggregate from precomputed key topics in metadata
topics: Counter = Counter()
for d in docs:
raw = d.metadata.get("key_topics", "") or ""
for t in [x.strip().lower() for x in raw.split(",") if x.strip()]:
topics[t] += 1
# Optional LLM consolidation for synonyms
top_items = topics.most_common(20)
topic_list = [t for t, _ in top_items]
counts = {t: c for t, c in top_items}
return {
"output": {
"intent": "topic_mining",
"topics": topic_list,
"topic_counts": counts,
"n_reviews_used": len(docs),
}
}
# ---------------------------------------
# Node: ABSA (Aspect-Based Sentiment)
# ---------------------------------------
def node_absa(state: GraphState) -> GraphState:
aspect = (state.get("aspect") or "").lower().strip()
filters = state.get("filters", {})
# Retrieve docs that likely discuss the aspect
query = f"{aspect} in oncology KOL reviews"
docs = retrieve_docs(query, filters, k=200)
# Aggregate precomputed sentiment from metadata
labels = Counter()
scores: List[float] = []
evidences: List[str] = []
for d in docs:
lbl = (d.metadata.get("sentiment_label") or "").lower()
sc = d.metadata.get("sentiment_score")
if lbl in {"positive", "negative", "neutral"}:
labels[lbl] += 1
if isinstance(sc, (int, float)):
scores.append(float(sc))
# keep a few short quotes
if len(evidences) < 6:
snippet = d.page_content.strip().replace("\n", " ")
evidences.append(snippet[:220])
avg = sum(scores) / len(scores) if scores else None
# Short LLM synthesis over top snippets
ctx = "\n- ".join(evidences[:8])
prompt = ChatPromptTemplate.from_messages([
("system", "You analyze KOL opinions with aspect-based sentiment for oncology medicines."),
("human", f"Aspect: {aspect}\nUsing the snippets below, summarize sentiment (what is praised/criticized) and clinical takeaways.\n- {ctx}")
])
resp = llm_main.invoke(prompt.format_messages())
return {
"output": {
"intent": "aspect_sentiment",
"aspect": aspect or None,
"sentiment": {
"positive": labels.get("positive", 0),
"negative": labels.get("negative", 0),
"neutral": labels.get("neutral", 0),
"avg_score": round(avg, 3) if avg is not None else None,
"n_reviews_used": len(docs),
},
"analysis": resp.content.strip(),
"evidence_snippets": evidences,
}
}
# ---------------------------------------
# Node: Sentiment Scores (aggregates)
# ---------------------------------------
def node_sentiment_scores(state: GraphState) -> GraphState:
filters = state.get("filters", {})
docs = retrieve_docs_by_filter(filters, k=1000)
labels = Counter()
scores: List[float] = []
geo = Counter()
variant = Counter()
for d in docs:
lbl = (d.metadata.get("sentiment_label") or "").lower()
if lbl in {"positive", "negative", "neutral"}:
labels[lbl] += 1
sc = d.metadata.get("sentiment_score")
if isinstance(sc, (int, float)):
scores.append(float(sc))
if d.metadata.get("geography"):
geo[d.metadata["geography"]] += 1
if d.metadata.get("medicine_variant"):
variant[d.metadata["medicine_variant"]] += 1
avg = sum(scores) / len(scores) if scores else None
return {
"output": {
"intent": "sentiment_scores",
"summary": {
"counts": dict(labels),
"avg_score": round(avg, 3) if avg is not None else None,
"n_reviews_used": len(docs),
},
"by_geography": dict(geo.most_common(10)),
"by_variant": dict(variant.most_common(10)),
}
}
# ---------------------------------------
# Node: General RAG (medical Q&A)
# ---------------------------------------
def node_general_rag(state: GraphState) -> GraphState:
query = state["query"]
answer = rag_chain.run(query)
return {
"output": {
"intent": "general",
"answer": answer,
}
}
# ---------------------------------------
# Build the LangGraph
# ---------------------------------------
def route_intent(state: GraphState) -> str:
intent = state.get("intent", "general")
if intent in {"summarization", "topic_mining", "aspect_sentiment", "sentiment_scores"}:
return intent
return "medical_guard" # not a listed intent → check medical before Q&A
def route_after_guard(state: GraphState) -> str:
# If guard set intent to reject, end; otherwise go to general RAG
if state.get("intent") == "reject":
return "end"
return "general_rag"
def build_graph():
graph = StateGraph(GraphState)
graph.add_node("classify_intent", classify_intent)
graph.add_node("medical_guard", medical_guard)
graph.add_node("summarization", node_summarization)
graph.add_node("topic_mining", node_topic_mining)
graph.add_node("aspect_sentiment", node_absa)
graph.add_node("sentiment_scores", node_sentiment_scores)
graph.add_node("general_rag", node_general_rag)
graph.add_edge(START, "classify_intent")
graph.add_conditional_edges("classify_intent", route_intent, {
"summarization": "summarization",
"topic_mining": "topic_mining",
"aspect_sentiment": "aspect_sentiment",
"sentiment_scores": "sentiment_scores",
"medical_guard": "medical_guard",
})
graph.add_conditional_edges("medical_guard", route_after_guard, {
"general_rag": "general_rag",
"end": END
})
# All terminal analysis nodes end the graph
for node in ["summarization", "topic_mining", "aspect_sentiment", "sentiment_scores", "general_rag"]:
graph.add_edge(node, END)
return graph.compile()
compiled_graph = build_graph()