Spaces:
Runtime error
Runtime error
Update agent.py
Browse files
agent.py
CHANGED
@@ -9,52 +9,54 @@ from langchain_core.messages import AnyMessage, HumanMessage
|
|
9 |
from langchain_groq import ChatGroq
|
10 |
from typing import TypedDict, Annotated
|
11 |
|
12 |
-
# Load
|
13 |
load_dotenv()
|
14 |
groq_api_key = os.getenv("GROQ_API_KEY")
|
15 |
serpapi_api_key = os.getenv("SERPAPI_API_KEY")
|
16 |
|
17 |
-
# ---
|
18 |
def calculator_tool_func(query: str):
|
19 |
try:
|
20 |
result = str(eval(query, {"__builtins__": {}}))
|
21 |
return result
|
22 |
except Exception:
|
23 |
-
return "
|
24 |
|
25 |
calculator_tool = Tool(
|
26 |
name="Calculator",
|
27 |
func=calculator_tool_func,
|
28 |
-
description="Performs
|
29 |
)
|
30 |
|
31 |
def weather_tool_func(location: str):
|
32 |
-
return f"
|
33 |
|
34 |
weather_tool = Tool(
|
35 |
name="Weather",
|
36 |
func=weather_tool_func,
|
37 |
-
description="Provides weather information for a given location."
|
38 |
)
|
39 |
|
40 |
serpapi = SerpAPIWrapper(serpapi_api_key=serpapi_api_key)
|
41 |
-
|
42 |
name="WebSearch",
|
43 |
func=serpapi.run,
|
44 |
-
description="Searches the web for recent information."
|
45 |
)
|
46 |
|
47 |
-
# ---
|
48 |
-
tools = [
|
49 |
llm = ChatGroq(model="deepseek-r1-distill-llama-70b", groq_api_key=groq_api_key)
|
50 |
llm_with_tools = llm.bind_tools(tools)
|
51 |
|
|
|
52 |
class AgentState(TypedDict):
|
53 |
messages: Annotated[list[AnyMessage], add_messages]
|
54 |
|
55 |
def assistant(state: AgentState):
|
56 |
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
57 |
|
|
|
58 |
builder = StateGraph(AgentState)
|
59 |
builder.add_node("assistant", assistant)
|
60 |
builder.add_node("tools", ToolNode(tools))
|
@@ -62,22 +64,26 @@ builder.add_edge(START, "assistant")
|
|
62 |
builder.add_conditional_edges("assistant", tools_condition)
|
63 |
builder.add_edge("tools", "assistant")
|
64 |
|
65 |
-
# 👇 compiled agent
|
66 |
ninu = builder.compile()
|
67 |
|
68 |
-
# ---
|
69 |
def run_ninu(query: str):
|
70 |
conversation = []
|
71 |
|
72 |
-
|
73 |
-
You are a
|
74 |
-
If you cannot answer, respond: FINAL ANSWER: I do not know.
|
75 |
"""
|
76 |
-
conversation.append(HumanMessage(content=
|
77 |
conversation.append(HumanMessage(content=query))
|
78 |
|
79 |
response = ninu.invoke({"messages": conversation})
|
80 |
for message in reversed(response["messages"]):
|
81 |
if isinstance(message.content, str) and "FINAL ANSWER:" in message.content:
|
82 |
return message.content.split("FINAL ANSWER:")[-1].strip()
|
83 |
-
return "
|
|
|
|
|
|
|
|
|
|
|
|
9 |
from langchain_groq import ChatGroq
|
10 |
from typing import TypedDict, Annotated
|
11 |
|
12 |
+
# Load environment variables
|
13 |
load_dotenv()
|
14 |
groq_api_key = os.getenv("GROQ_API_KEY")
|
15 |
serpapi_api_key = os.getenv("SERPAPI_API_KEY")
|
16 |
|
17 |
+
# --- Tool Definitions ---
|
18 |
def calculator_tool_func(query: str):
|
19 |
try:
|
20 |
result = str(eval(query, {"__builtins__": {}}))
|
21 |
return result
|
22 |
except Exception:
|
23 |
+
return "Could not calculate the input expression."
|
24 |
|
25 |
calculator_tool = Tool(
|
26 |
name="Calculator",
|
27 |
func=calculator_tool_func,
|
28 |
+
description="Performs basic arithmetic calculations."
|
29 |
)
|
30 |
|
31 |
def weather_tool_func(location: str):
|
32 |
+
return f"The weather in {location}: Sunny, 25°C."
|
33 |
|
34 |
weather_tool = Tool(
|
35 |
name="Weather",
|
36 |
func=weather_tool_func,
|
37 |
+
description="Provides mock weather information for a given location."
|
38 |
)
|
39 |
|
40 |
serpapi = SerpAPIWrapper(serpapi_api_key=serpapi_api_key)
|
41 |
+
web_search_tool = Tool(
|
42 |
name="WebSearch",
|
43 |
func=serpapi.run,
|
44 |
+
description="Searches the web for recent information using SerpAPI."
|
45 |
)
|
46 |
|
47 |
+
# --- Model and Tools Binding ---
|
48 |
+
tools = [web_search_tool, calculator_tool, weather_tool]
|
49 |
llm = ChatGroq(model="deepseek-r1-distill-llama-70b", groq_api_key=groq_api_key)
|
50 |
llm_with_tools = llm.bind_tools(tools)
|
51 |
|
52 |
+
# --- Agent State ---
|
53 |
class AgentState(TypedDict):
|
54 |
messages: Annotated[list[AnyMessage], add_messages]
|
55 |
|
56 |
def assistant(state: AgentState):
|
57 |
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
58 |
|
59 |
+
# --- Agent Graph ---
|
60 |
builder = StateGraph(AgentState)
|
61 |
builder.add_node("assistant", assistant)
|
62 |
builder.add_node("tools", ToolNode(tools))
|
|
|
64 |
builder.add_conditional_edges("assistant", tools_condition)
|
65 |
builder.add_edge("tools", "assistant")
|
66 |
|
67 |
+
# 👇 The compiled agent: use with .invoke({...})
|
68 |
ninu = builder.compile()
|
69 |
|
70 |
+
# --- Run Function ---
|
71 |
def run_ninu(query: str):
|
72 |
conversation = []
|
73 |
|
74 |
+
system_prompt = """
|
75 |
+
You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
|
|
76 |
"""
|
77 |
+
conversation.append(HumanMessage(content=system_prompt.strip()))
|
78 |
conversation.append(HumanMessage(content=query))
|
79 |
|
80 |
response = ninu.invoke({"messages": conversation})
|
81 |
for message in reversed(response["messages"]):
|
82 |
if isinstance(message.content, str) and "FINAL ANSWER:" in message.content:
|
83 |
return message.content.split("FINAL ANSWER:")[-1].strip()
|
84 |
+
return "FINAL ANSWER: No valid answer found."
|
85 |
+
|
86 |
+
# --- Example test ---
|
87 |
+
if __name__ == "__main__":
|
88 |
+
result = run_ninu("What is the capital of Japan?")
|
89 |
+
print("🧠 NINU replied:", result)
|