Spaces:
Sleeping
Sleeping
Upload agent.py
Browse files
agent.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import TypedDict, Annotated, Sequence
|
3 |
+
import operator
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
from langgraph.graph import StateGraph
|
6 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
7 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
8 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
9 |
+
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
10 |
+
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
|
11 |
+
from langchain.agents import Tool
|
12 |
+
from langchain_core.tools import tool
|
13 |
+
|
14 |
+
# Load environment variables
|
15 |
+
google_api_key = os.getenv("GOOGLE_API_KEY") or os.environ.get("GOOGLE_API_KEY")
|
16 |
+
if not google_api_key:
|
17 |
+
raise ValueError("Missing GOOGLE_API_KEY environment variable")
|
18 |
+
|
19 |
+
# --- System Prompt ---
|
20 |
+
with open("System_Prompt.txt", "r", encoding="utf-8") as f:
|
21 |
+
system_prompt = f.read()
|
22 |
+
sys_msg = SystemMessage(content=system_prompt)
|
23 |
+
|
24 |
+
# --- Tool Definitions ---
|
25 |
+
@tool
|
26 |
+
def multiply(a: int, b: int) -> int:
|
27 |
+
"""Multiply two integers together."""
|
28 |
+
return a * b
|
29 |
+
|
30 |
+
@tool
|
31 |
+
def add(a: int, b: int) -> int:
|
32 |
+
"""Add two integers together."""
|
33 |
+
return a + b
|
34 |
+
|
35 |
+
@tool
|
36 |
+
def subtract(a: int, b: int) -> int:
|
37 |
+
"""Subtract b from a."""
|
38 |
+
return a - b
|
39 |
+
|
40 |
+
@tool
|
41 |
+
def divide(a: int, b: int) -> float:
|
42 |
+
"""Divide a by b. Returns float. Raises error if b is zero."""
|
43 |
+
if b == 0:
|
44 |
+
raise ValueError("Cannot divide by zero.")
|
45 |
+
return a / b
|
46 |
+
|
47 |
+
@tool
|
48 |
+
def wiki_search(query: str) -> str:
|
49 |
+
"""Search Wikipedia and return up to 2 relevant documents."""
|
50 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
51 |
+
if not docs:
|
52 |
+
return "No Wikipedia results found."
|
53 |
+
return "\n\n".join([d.page_content[:1000] for d in docs])
|
54 |
+
|
55 |
+
# Tool inventory with proper categorization
|
56 |
+
tools = [
|
57 |
+
Tool(name="Math/Multiply", func=multiply, description="Multiplies two integers"),
|
58 |
+
Tool(name="Math/Add", func=add, description="Adds two integers"),
|
59 |
+
Tool(name="Math/Subtract", func=subtract, description="Subtracts two integers"),
|
60 |
+
Tool(name="Math/Divide", func=divide, description="Divides two numbers"),
|
61 |
+
Tool(name="Search/Wikipedia", func=wiki_search, description="Searches Wikipedia"),
|
62 |
+
Tool(
|
63 |
+
name="Search/Web",
|
64 |
+
func=DuckDuckGoSearchRun().run,
|
65 |
+
description="Searches the web using DuckDuckGo"
|
66 |
+
)
|
67 |
+
]
|
68 |
+
|
69 |
+
# --- Graph Definition ---
|
70 |
+
class AgentState(TypedDict):
|
71 |
+
"""State definition for the agent workflow"""
|
72 |
+
messages: Annotated[Sequence[BaseMessage], operator.add]
|
73 |
+
|
74 |
+
def build_graph():
|
75 |
+
"""Constructs and compiles the LangGraph workflow"""
|
76 |
+
|
77 |
+
# Initialize LLM with Gemini 2.0 Flash
|
78 |
+
llm = ChatGoogleGenerativeAI(
|
79 |
+
model="gemini-2.0-flash-exp",
|
80 |
+
temperature=0.3,
|
81 |
+
google_api_key=google_api_key
|
82 |
+
)
|
83 |
+
llm_with_tools = llm.bind_tools(tools)
|
84 |
+
|
85 |
+
# Node definitions
|
86 |
+
def agent_node(state: AgentState):
|
87 |
+
"""Main agent node that processes messages"""
|
88 |
+
response = llm_with_tools.invoke(state["messages"])
|
89 |
+
return {"messages": [response]}
|
90 |
+
|
91 |
+
# Graph construction
|
92 |
+
workflow = StateGraph(AgentState)
|
93 |
+
|
94 |
+
# Add nodes to the workflow
|
95 |
+
workflow.add_node("agent", agent_node)
|
96 |
+
workflow.add_node("tools", ToolNode(tools))
|
97 |
+
|
98 |
+
# Configure graph flow
|
99 |
+
workflow.set_entry_point("agent")
|
100 |
+
workflow.add_conditional_edges(
|
101 |
+
"agent",
|
102 |
+
tools_condition, # LangGraph's built-in tool detection
|
103 |
+
{"tools": "tools", "end": END}
|
104 |
+
)
|
105 |
+
workflow.add_edge("tools", "agent")
|
106 |
+
|
107 |
+
return workflow.compile()
|
108 |
+
|
109 |
+
# Initialize the agent graph
|
110 |
+
agent_graph = build_graph()
|