Ali-Developments commited on
Commit
ed0c48c
·
verified ·
1 Parent(s): f4df3f7

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +110 -81
agent.py CHANGED
@@ -1,89 +1,118 @@
1
- import os
2
- from dotenv import load_dotenv
3
- from langchain.tools import Tool
4
- from langchain.utilities import SerpAPIWrapper
5
- from langgraph.graph.message import add_messages
6
- from langgraph.graph import START, StateGraph
7
- from langgraph.prebuilt import ToolNode, tools_condition
8
- from langchain_core.messages import AnyMessage, HumanMessage
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 "I couldn't compute that 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))
63
- builder.add_edge(START, "assistant")
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 smart, helpful, and curious assistant. Think step by step and use any available tools if needed. Explain your reasoning, be honest about what you know and don't know, and speak naturally in English.
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):
83
- return message.content.strip()
84
- return "No response received."
85
 
86
- # --- Example test ---
 
 
87
  if __name__ == "__main__":
88
- result = run_ninu("What is the capital of Japan?")
89
- print("🧠 NINU replied:", result)
 
 
 
 
 
1
+ from langchain_core.tools import tool
2
+ from langgraph.graph import StateGraph, START, MessagesState
3
+ from langgraph.prebuilt import tools_condition, ToolNode
 
 
 
 
 
4
  from langchain_groq import ChatGroq
5
+ from langchain_core.messages import HumanMessage, SystemMessage
6
+ import math
7
 
8
+ # -------------------------
9
+ # Tools
10
+ # -------------------------
11
+ @tool
12
+ def add(a: float, b: float) -> float:
13
+ return a + b
14
 
15
+ @tool
16
+ def subtract(a: float, b: float) -> float:
17
+ return a - b
18
+
19
+ @tool
20
+ def multiply(a: float, b: float) -> float:
21
+ return a * b
22
+
23
+ @tool
24
+ def divide(a: float, b: float) -> float:
25
+ if b == 0:
26
+ return float('inf')
27
+ return a / b
28
+
29
+ @tool
30
+ def modulus(a: int, b: int) -> int:
31
+ return a % b
32
+
33
+ @tool
34
+ def python_eval(code: str) -> str:
35
  try:
36
+ result = eval(code)
37
+ return f"Result: {result}"
38
+ except Exception as e:
39
+ return f"Error: {str(e)}"
40
+
41
+ @tool
42
+ def translate_to_arabic(text: str) -> str:
43
+ return f"Arabic translation of '{text}'"
44
+
45
+ @tool
46
+ def translate_to_english(text: str) -> str:
47
+ return f"English translation of '{text}'"
48
+
49
+ @tool
50
+ def summarize_text(text: str) -> str:
51
+ return f"Summary: {text[:100]}..."
52
+
53
+ @tool
54
+ def analyze_sentiment(text: str) -> str:
55
+ if any(word in text.lower() for word in ["good", "great", "excellent", "happy"]):
56
+ return "Sentiment: Positive"
57
+ elif any(word in text.lower() for word in ["bad", "terrible", "sad", "hate"]):
58
+ return "Sentiment: Negative"
59
+ return "Sentiment: Neutral"
60
+
61
+ @tool
62
+ def speech_to_text_stub(audio: str) -> str:
63
+ return "Converted audio to text: (This is a placeholder result)"
64
+
65
+ # -------------------------
66
+ # System Prompt
67
+ # -------------------------
68
+ system_prompt = """
69
+ You are DeepSeek, a thoughtful and curious AI assistant. You analyze before answering.
70
+ You always reflect step by step, consider using tools intelligently, and aim for precision and clarity.
71
+
72
+ Behaviors:
73
+ - Think deeply about the user's question.
74
+ - Decide if you need tools to calculate, search, translate, or analyze.
75
+ - If no tool is needed, answer directly with your own knowledge.
76
+
77
+ Respond in a helpful, concise, and accurate way.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  """
79
+ sys_msg = SystemMessage(content=system_prompt)
80
+
81
+ # -------------------------
82
+ # Build LangGraph Agent
83
+ # -------------------------
84
+ def build_deepseek_graph():
85
+ llm = ChatGroq(model="deepseek-llm-67b", temperature=0.3)
86
+
87
+ all_tools = [
88
+ add, subtract, multiply, divide, modulus,
89
+ translate_to_arabic, translate_to_english,
90
+ summarize_text, analyze_sentiment,
91
+ python_eval, speech_to_text_stub
92
+ ]
93
+ llm_with_tools = llm.bind_tools(all_tools)
94
+
95
+ def assistant(state: MessagesState):
96
+ return {"messages": [llm_with_tools.invoke(state["messages"])]}
97
+
98
+ builder = StateGraph(MessagesState)
99
+ builder.add_node("assistant", assistant)
100
+ builder.add_node("tools", ToolNode(all_tools))
101
+
102
+ builder.add_edge(START, "assistant")
103
+ builder.add_conditional_edges("assistant", tools_condition)
104
+ builder.add_edge("tools", "assistant")
105
 
106
+ ninu = builder.compile()
107
+ return ninu
 
 
 
108
 
109
+ # -------------------------
110
+ # Example Run
111
+ # -------------------------
112
  if __name__ == "__main__":
113
+ ninu = build_deepseek_graph()
114
+ user_question = "ترجم لي الجملة: Artificial intelligence is transforming education."
115
+ messages = [sys_msg, HumanMessage(content=user_question)]
116
+ result = ninu.invoke({"messages": messages})
117
+ for msg in result["messages"]:
118
+ print("\n", msg.content)