Frazer2810 commited on
Commit
97783bb
·
verified ·
1 Parent(s): 23e6356

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +36 -23
agent.py CHANGED
@@ -1,4 +1,4 @@
1
- """LangGraph Agent – Solo GPT-4.1 (OpenAI)"""
2
 
3
  import os
4
  from dotenv import load_dotenv
@@ -8,46 +8,58 @@ from langchain_openai import ChatOpenAI
8
  from langchain_core.messages import SystemMessage, HumanMessage
9
  from langchain_core.tools import tool
10
 
11
- # Tools loaders
12
  from langchain_community.tools.tavily_search import TavilySearchResults
13
  from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
14
 
15
  # ------------------------------------------------------------------ #
16
- # Inizializzazione ambiente #
17
  # ------------------------------------------------------------------ #
18
- load_dotenv() # carica OPENAI_KEY dai secrets dello Space
19
-
20
  OPENAI_KEY = os.getenv("OPENAI_KEY")
21
  if not OPENAI_KEY:
22
  raise ValueError("❌ OPENAI_KEY non impostata: aggiungila nei Secrets dello Space.")
23
 
24
  # ------------------------------------------------------------------ #
25
- # TOOL di esempio (aritmetica) #
26
  # ------------------------------------------------------------------ #
27
  @tool
28
- def multiply(a: int, b: int) -> int: return a * b
 
 
29
 
30
  @tool
31
- def add(a: int, b: int) -> int: return a + b
 
 
32
 
33
  @tool
34
- def subtract(a: int, b: int) -> int: return a - b
 
 
35
 
36
  @tool
37
  def divide(a: int, b: int) -> float:
 
 
 
 
 
38
  if b == 0:
39
  raise ValueError("Cannot divide by zero.")
40
  return a / b
41
 
42
  @tool
43
- def modulus(a: int, b: int) -> int: return a % b
 
 
44
 
45
  # ------------------------------------------------------------------ #
46
  # TOOL: Wikipedia #
47
  # ------------------------------------------------------------------ #
48
  @tool
49
  def wiki_search(query: str) -> str:
50
- """Search Wikipedia (max 2 docs) and return formatted result."""
51
  docs = WikipediaLoader(query=query, load_max_docs=2).load()
52
  return "\n\n---\n\n".join(
53
  f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page","")}"/>\n'
@@ -56,11 +68,11 @@ def wiki_search(query: str) -> str:
56
  )
57
 
58
  # ------------------------------------------------------------------ #
59
- # TOOL: Tavily #
60
  # ------------------------------------------------------------------ #
61
  @tool
62
  def web_search(query: str) -> str:
63
- """Search Tavily (max 3 docs) and return formatted result."""
64
  docs = TavilySearchResults(max_results=3).invoke(query=query)
65
  return "\n\n---\n\n".join(
66
  f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page","")}"/>\n'
@@ -73,7 +85,7 @@ def web_search(query: str) -> str:
73
  # ------------------------------------------------------------------ #
74
  @tool
75
  def arxiv_search(query: str) -> str:
76
- """Search ArXiv (max 3 docs) and return formatted snippet."""
77
  docs = ArxivLoader(query=query, load_max_docs=3).load()
78
  return "\n\n---\n\n".join(
79
  f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page","")}"/>\n'
@@ -89,7 +101,7 @@ with open("system_prompt.txt", "r", encoding="utf-8") as f:
89
  sys_msg = SystemMessage(content=system_prompt)
90
 
91
  # ------------------------------------------------------------------ #
92
- # Lista tool #
93
  # ------------------------------------------------------------------ #
94
  tools = [
95
  multiply, add, subtract, divide, modulus,
@@ -97,10 +109,10 @@ tools = [
97
  ]
98
 
99
  # ------------------------------------------------------------------ #
100
- # Costruzione graph #
101
  # ------------------------------------------------------------------ #
102
  def build_graph():
103
- """Restituisce un graph LangGraph che usa solo GPT-4.1."""
104
  llm = ChatOpenAI(
105
  model_name="gpt-4.1",
106
  temperature=0,
@@ -110,10 +122,11 @@ def build_graph():
110
 
111
  # Nodes --------------------------------------------------------- #
112
  def prepend_system(state: MessagesState):
113
- """Prepend system prompt to conversation."""
114
  return {"messages": [sys_msg] + state["messages"]}
115
 
116
  def assistant(state: MessagesState):
 
117
  return {"messages": [llm_with_tools.invoke(state["messages"])]}
118
 
119
  # Graph --------------------------------------------------------- #
@@ -130,12 +143,12 @@ def build_graph():
130
  return builder.compile()
131
 
132
  # ------------------------------------------------------------------ #
133
- # Test rapido (facoltativo) #
134
  # ------------------------------------------------------------------ #
135
  if __name__ == "__main__":
136
  g = build_graph()
137
- q = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
138
- msgs = [HumanMessage(content=q)]
139
- res = g.invoke({"messages": msgs})
140
- for m in res["messages"]:
141
  m.pretty_print()
 
1
+ """LangGraph Agent – Solo GPT-4.1 (OpenAI) con docstring obbligatorie."""
2
 
3
  import os
4
  from dotenv import load_dotenv
 
8
  from langchain_core.messages import SystemMessage, HumanMessage
9
  from langchain_core.tools import tool
10
 
11
+ # Loader & search tools
12
  from langchain_community.tools.tavily_search import TavilySearchResults
13
  from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
14
 
15
  # ------------------------------------------------------------------ #
16
+ # Ambiente #
17
  # ------------------------------------------------------------------ #
18
+ load_dotenv() # carica OPENAI_KEY dallo Space
 
19
  OPENAI_KEY = os.getenv("OPENAI_KEY")
20
  if not OPENAI_KEY:
21
  raise ValueError("❌ OPENAI_KEY non impostata: aggiungila nei Secrets dello Space.")
22
 
23
  # ------------------------------------------------------------------ #
24
+ # TOOL: aritmetica #
25
  # ------------------------------------------------------------------ #
26
  @tool
27
+ def multiply(a: int, b: int) -> int:
28
+ """Multiply two integers and return the product."""
29
+ return a * b
30
 
31
  @tool
32
+ def add(a: int, b: int) -> int:
33
+ """Add two integers and return the sum."""
34
+ return a + b
35
 
36
  @tool
37
+ def subtract(a: int, b: int) -> int:
38
+ """Subtract the second integer from the first and return the difference."""
39
+ return a - b
40
 
41
  @tool
42
  def divide(a: int, b: int) -> float:
43
+ """Divide the first integer by the second and return the quotient.
44
+
45
+ Raises:
46
+ ValueError: If b is zero.
47
+ """
48
  if b == 0:
49
  raise ValueError("Cannot divide by zero.")
50
  return a / b
51
 
52
  @tool
53
+ def modulus(a: int, b: int) -> int:
54
+ """Return the remainder of the division of a by b."""
55
+ return a % b
56
 
57
  # ------------------------------------------------------------------ #
58
  # TOOL: Wikipedia #
59
  # ------------------------------------------------------------------ #
60
  @tool
61
  def wiki_search(query: str) -> str:
62
+ """Search Wikipedia (max 2 docs) and return formatted content."""
63
  docs = WikipediaLoader(query=query, load_max_docs=2).load()
64
  return "\n\n---\n\n".join(
65
  f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page","")}"/>\n'
 
68
  )
69
 
70
  # ------------------------------------------------------------------ #
71
+ # TOOL: Tavily web search #
72
  # ------------------------------------------------------------------ #
73
  @tool
74
  def web_search(query: str) -> str:
75
+ """Perform a web search using Tavily (max 3 docs) and return formatted content."""
76
  docs = TavilySearchResults(max_results=3).invoke(query=query)
77
  return "\n\n---\n\n".join(
78
  f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page","")}"/>\n'
 
85
  # ------------------------------------------------------------------ #
86
  @tool
87
  def arxiv_search(query: str) -> str:
88
+ """Search ArXiv (max 3 docs) and return the first 1000 chars of each paper."""
89
  docs = ArxivLoader(query=query, load_max_docs=3).load()
90
  return "\n\n---\n\n".join(
91
  f'<Document source="{d.metadata["source"]}" page="{d.metadata.get("page","")}"/>\n'
 
101
  sys_msg = SystemMessage(content=system_prompt)
102
 
103
  # ------------------------------------------------------------------ #
104
+ # Tool list #
105
  # ------------------------------------------------------------------ #
106
  tools = [
107
  multiply, add, subtract, divide, modulus,
 
109
  ]
110
 
111
  # ------------------------------------------------------------------ #
112
+ # Build LangGraph #
113
  # ------------------------------------------------------------------ #
114
  def build_graph():
115
+ """Return a LangGraph graph that uses only GPT-4.1 via OpenAI."""
116
  llm = ChatOpenAI(
117
  model_name="gpt-4.1",
118
  temperature=0,
 
122
 
123
  # Nodes --------------------------------------------------------- #
124
  def prepend_system(state: MessagesState):
125
+ """Prepend system prompt to the incoming messages."""
126
  return {"messages": [sys_msg] + state["messages"]}
127
 
128
  def assistant(state: MessagesState):
129
+ """Invoke the LLM (tool calling enabled)."""
130
  return {"messages": [llm_with_tools.invoke(state["messages"])]}
131
 
132
  # Graph --------------------------------------------------------- #
 
143
  return builder.compile()
144
 
145
  # ------------------------------------------------------------------ #
146
+ # Test rapido #
147
  # ------------------------------------------------------------------ #
148
  if __name__ == "__main__":
149
  g = build_graph()
150
+ query = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
151
+ msgs = [HumanMessage(content=query)]
152
+ result = g.invoke({"messages": msgs})
153
+ for m in result["messages"]:
154
  m.pretty_print()