Spaces:
Runtime error
Runtime error
Create agent_system.py
Browse files- agent_system.py +147 -0
agent_system.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import TypedDict, Annotated, List
|
| 3 |
+
import operator
|
| 4 |
+
|
| 5 |
+
from langchain_core.messages import BaseMessage, HumanMessage
|
| 6 |
+
from langchain_huggingface import HuggingFaceEmbeddings, ChatHuggingFace
|
| 7 |
+
from langchain_community.vectorstores import FAISS
|
| 8 |
+
from langchain.tools.retriever import create_retriever_tool
|
| 9 |
+
from langgraph.graph import StateGraph, END
|
| 10 |
+
from langgraph.prebuilt import ToolExecutor
|
| 11 |
+
|
| 12 |
+
# --- Configuration ---
|
| 13 |
+
SAVE_PATH = "/data/faiss_index"
|
| 14 |
+
EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
| 15 |
+
# Recommended to use a powerful model for agentic tasks
|
| 16 |
+
LLM_REPO_ID = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
| 17 |
+
|
| 18 |
+
# --- Agent State Definition ---
|
| 19 |
+
class AgentState(TypedDict):
|
| 20 |
+
"""Defines the state of the agent graph, tracking messages."""
|
| 21 |
+
messages: Annotated, operator.add]
|
| 22 |
+
|
| 23 |
+
# --- Knowledge Base and Tools Setup ---
|
| 24 |
+
def create_agent_system():
|
| 25 |
+
"""
|
| 26 |
+
Initializes the entire agent system, including the knowledge base retriever,
|
| 27 |
+
specialized tools, and the LangGraph-based agent executor.
|
| 28 |
+
"""
|
| 29 |
+
print("Initializing Agent System...")
|
| 30 |
+
|
| 31 |
+
# 1. Load the Knowledge Base
|
| 32 |
+
if not os.path.exists(SAVE_PATH):
|
| 33 |
+
raise FileNotFoundError(
|
| 34 |
+
f"FAISS index not found at {SAVE_PATH}. "
|
| 35 |
+
"Please run knowledge_base.py first to create it."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
|
| 39 |
+
vector_store = FAISS.load_local(SAVE_PATH, embeddings, allow_dangerous_deserialization=True)
|
| 40 |
+
retriever = vector_store.as_retriever(search_kwargs={'k': 3})
|
| 41 |
+
|
| 42 |
+
# 2. Create Specialized Retriever Tools for each Agent
|
| 43 |
+
# The tool descriptions are crucial as they guide the Orchestrator agent.
|
| 44 |
+
academic_tool = create_retriever_tool(
|
| 45 |
+
retriever,
|
| 46 |
+
"academic_retriever",
|
| 47 |
+
"Searches for information about academics, including curriculum, study materials, timetables, RGPV links, exam papers, and Moodle/e-Library info."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
administrative_tool = create_retriever_tool(
|
| 51 |
+
retriever,
|
| 52 |
+
"administrative_retriever",
|
| 53 |
+
"Searches for information about college administration, including fees, scholarships, admissions, rules, regulations, and grievance policies."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
campus_services_tool = create_retriever_tool(
|
| 57 |
+
retriever,
|
| 58 |
+
"campus_services_retriever",
|
| 59 |
+
"Searches for information about campus services like library hours, bus routes, lab availability, sports facilities, and special academies (Cisco, AWS)."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
student_life_tool = create_retriever_tool(
|
| 63 |
+
retriever,
|
| 64 |
+
"student_life_retriever",
|
| 65 |
+
"Searches for information about student life, including upcoming events, clubs, cultural festivals, and how to submit complaints or raise issues."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
tools = [academic_tool, administrative_tool, campus_services_tool, student_life_tool]
|
| 69 |
+
tool_executor = ToolExecutor(tools)
|
| 70 |
+
|
| 71 |
+
# 3. Initialize the LLM
|
| 72 |
+
# This requires the HUGGINGFACEHUB_API_TOKEN to be set as a secret in the Space.
|
| 73 |
+
llm = ChatHuggingFace(
|
| 74 |
+
repo_id=LLM_REPO_ID,
|
| 75 |
+
task="text-generation",
|
| 76 |
+
model_kwargs={
|
| 77 |
+
"max_new_tokens": 1024,
|
| 78 |
+
"temperature": 0.1,
|
| 79 |
+
"repetition_penalty": 1.03,
|
| 80 |
+
},
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Bind the tools to the LLM so it knows how to call them
|
| 84 |
+
llm_with_tools = llm.bind_tools(tools)
|
| 85 |
+
|
| 86 |
+
# 4. Define the LangGraph Nodes
|
| 87 |
+
def agent_node(state):
|
| 88 |
+
"""The primary node that invokes the LLM to decide the next action."""
|
| 89 |
+
response = llm_with_tools.invoke(state["messages"])
|
| 90 |
+
return {"messages": [response]}
|
| 91 |
+
|
| 92 |
+
def tool_node(state):
|
| 93 |
+
"""Executes the tool called by the agent and returns the result."""
|
| 94 |
+
tool_calls = state["messages"][-1].tool_calls
|
| 95 |
+
tool_messages = tool_executor.batch(tool_calls)
|
| 96 |
+
return {"messages": tool_messages}
|
| 97 |
+
|
| 98 |
+
def should_continue(state):
|
| 99 |
+
"""Conditional edge logic: decides whether to continue or end."""
|
| 100 |
+
if state["messages"][-1].tool_calls:
|
| 101 |
+
return "continue"
|
| 102 |
+
return "end"
|
| 103 |
+
|
| 104 |
+
# 5. Build the Graph
|
| 105 |
+
workflow = StateGraph(AgentState)
|
| 106 |
+
workflow.add_node("agent", agent_node)
|
| 107 |
+
workflow.add_node("tools", tool_node)
|
| 108 |
+
|
| 109 |
+
workflow.set_entry_point("agent")
|
| 110 |
+
|
| 111 |
+
workflow.add_conditional_edges(
|
| 112 |
+
"agent",
|
| 113 |
+
should_continue,
|
| 114 |
+
{"continue": "tools", "end": END}
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
workflow.add_edge("tools", "agent")
|
| 118 |
+
|
| 119 |
+
# 6. Compile the graph into a runnable app
|
| 120 |
+
agent_executor = workflow.compile()
|
| 121 |
+
print("Agent System Initialized Successfully.")
|
| 122 |
+
return agent_executor
|
| 123 |
+
|
| 124 |
+
def run_query(agent_executor, query, user_info):
|
| 125 |
+
"""
|
| 126 |
+
Runs a query through the agent system, providing user context.
|
| 127 |
+
"""
|
| 128 |
+
# Prepend a system message with user context for better personalization
|
| 129 |
+
system_message = (
|
| 130 |
+
"You are the 'GGITS Digital Campus Assistant,' a helpful, professional, and reliable AI assistant. "
|
| 131 |
+
f"You are currently assisting a '{user_info['role']}' named {user_info['email']}. "
|
| 132 |
+
"Use the available tools to find the most relevant and accurate information from the college's knowledge base. "
|
| 133 |
+
"If you cannot find an answer, state that the information is not available in your current knowledge base."
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
messages = [
|
| 137 |
+
HumanMessage(content=system_message),
|
| 138 |
+
HumanMessage(content=query)
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
# The `stream` method provides real-time output as the agent works
|
| 142 |
+
final_response = None
|
| 143 |
+
for chunk in agent_executor.stream({"messages": messages}):
|
| 144 |
+
if "messages" in chunk:
|
| 145 |
+
final_response = chunk["messages"][-1]
|
| 146 |
+
|
| 147 |
+
return final_response.content if final_response else "I'm sorry, I couldn't process your request."
|