File size: 2,267 Bytes
af37a16 | 1 2 3 4 5 6 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 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 63 | """
Enterprise Knowledge Assistant - Multi-Agent Graph
Router -> Hybrid Retrieval -> Generation, orchestrated via LangGraph.
"""
from langgraph.graph import StateGraph, END
from typing import TypedDict
class AgentState(TypedDict):
query: str
domain: str
confidence: float
retrieved_chunks: list
answer: str
def build_agent_graph(router_model, tokenizer, label_encoder, embedding_model,
domain_indices, domain_chunks_map, index, all_chunks, groq_client,
classify_query_fn, retrieve_hybrid_fn, generate_with_groq_fn):
def router_node(state):
domain, confidence_or_probs = classify_query_fn(state['query'], router_model, tokenizer, label_encoder)
if hasattr(confidence_or_probs, 'shape') and confidence_or_probs.numel() > 1:
confidence = float(confidence_or_probs.max())
else:
confidence = float(confidence_or_probs)
print(f"[Router] Domain: {domain} (confidence: {confidence:.2f})")
return {**state, 'domain': domain, 'confidence': confidence}
def retrieval_node(state):
results = retrieve_hybrid_fn(
state['query'], state['domain'],
embedding_model, domain_indices, domain_chunks_map, index, all_chunks
)
return {**state, 'retrieved_chunks': results}
def generation_node(state):
context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}"
for dist, c in state['retrieved_chunks']])
prompt = f"""You are an enterprise knowledge assistant. Answer using ONLY the context below.
If the context doesn't fully answer the question, say what's missing honestly.
Context:
{context_text}
Question: {state['query']}
Answer:"""
answer = generate_with_groq_fn(prompt, groq_client)
return {**state, 'answer': answer}
graph = StateGraph(AgentState)
graph.add_node("router", router_node)
graph.add_node("retrieval", retrieval_node)
graph.add_node("generation", generation_node)
graph.set_entry_point("router")
graph.add_edge("router", "retrieval")
graph.add_edge("retrieval", "generation")
graph.add_edge("generation", END)
return graph.compile()
|