rakesh-dvg commited on
Commit
3b4f489
·
verified ·
1 Parent(s): 371909c

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +34 -83
agent.py CHANGED
@@ -25,7 +25,6 @@ print(f"SUPABASE_SERVICE_KEY: {SUPABASE_SERVICE_KEY[:10]}..." if SUPABASE_SERVIC
25
 
26
 
27
  def get_supabase_client():
28
- """Create and return a Supabase client from environment variables."""
29
  if not SUPABASE_URL or not SUPABASE_SERVICE_KEY:
30
  raise ValueError("Supabase environment variables are missing.")
31
  return create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
@@ -33,117 +32,46 @@ def get_supabase_client():
33
 
34
  @tool
35
  def multiply(a: int, b: int) -> int:
36
- """Multiply two integers and return the result.
37
-
38
- Args:
39
- a (int): First multiplier.
40
- b (int): Second multiplier.
41
-
42
- Returns:
43
- int: The product of a and b.
44
- """
45
  return a * b
46
 
47
-
48
  @tool
49
  def add(a: int, b: int) -> int:
50
- """Add two integers and return the sum.
51
-
52
- Args:
53
- a (int): First addend.
54
- b (int): Second addend.
55
-
56
- Returns:
57
- int: The sum of a and b.
58
- """
59
  return a + b
60
 
61
-
62
  @tool
63
  def subtract(a: int, b: int) -> int:
64
- """Subtract b from a and return the difference.
65
-
66
- Args:
67
- a (int): Minuend.
68
- b (int): Subtrahend.
69
-
70
- Returns:
71
- int: The difference a - b.
72
- """
73
  return a - b
74
 
75
-
76
  @tool
77
  def divide(a: int, b: int) -> float:
78
- """Divide a by b and return the quotient.
79
-
80
- Args:
81
- a (int): Dividend.
82
- b (int): Divisor.
83
-
84
- Raises:
85
- ValueError: If b is zero.
86
-
87
- Returns:
88
- float: The quotient of a divided by b.
89
- """
90
  if b == 0:
91
  raise ValueError("Cannot divide by zero.")
92
  return a / b
93
 
94
-
95
  @tool
96
  def modulus(a: int, b: int) -> int:
97
- """Return the remainder of dividing a by b.
98
-
99
- Args:
100
- a (int): Dividend.
101
- b (int): Divisor.
102
-
103
- Returns:
104
- int: The remainder of a divided by b.
105
- """
106
  return a % b
107
 
108
-
109
  @tool
110
  def wiki_search(query: str) -> str:
111
- """Search Wikipedia for the query and return the combined content of top 2 documents.
112
-
113
- Args:
114
- query (str): Search query string.
115
-
116
- Returns:
117
- str: Combined content of top 2 Wikipedia documents separated by "---".
118
- """
119
  docs = WikipediaLoader(query=query, load_max_docs=2).load()
120
  return "\n\n---\n\n".join([doc.page_content for doc in docs])
121
 
122
-
123
  @tool
124
  def web_search(query: str) -> str:
125
- """Search the web using TavilySearchResults and return combined content of top 3 results.
126
-
127
- Args:
128
- query (str): Search query string.
129
-
130
- Returns:
131
- str: Combined content of top 3 web search results separated by "---".
132
- """
133
  docs = TavilySearchResults(max_results=3).invoke(query=query)
134
  return "\n\n---\n\n".join([doc.page_content for doc in docs])
135
 
136
-
137
  @tool
138
  def arvix_search(query: str) -> str:
139
- """Search Arxiv for the query and return combined content (up to 1000 chars) of top 3 documents.
140
-
141
- Args:
142
- query (str): Search query string.
143
-
144
- Returns:
145
- str: Combined content snippet of top 3 Arxiv documents separated by "---".
146
- """
147
  docs = ArxivLoader(query=query, load_max_docs=3).load()
148
  return "\n\n---\n\n".join([doc.page_content[:1000] for doc in docs])
149
 
@@ -151,7 +79,11 @@ def arvix_search(query: str) -> str:
151
  tools = [multiply, add, subtract, divide, modulus, wiki_search, web_search, arvix_search]
152
 
153
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
154
- system_prompt = f.read()
 
 
 
 
155
 
156
  sys_msg = SystemMessage(content=system_prompt)
157
 
@@ -188,7 +120,26 @@ def build_graph(provider: str = "groq"):
188
  llm_with_tools = llm.bind_tools(tools)
189
 
190
  def assistant(state: MessagesState):
191
- return {"messages": [llm_with_tools.invoke(state["messages"])]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
 
193
  def retriever(state: MessagesState):
194
  similar = vector_store.similarity_search(state["messages"][0].content)
@@ -212,4 +163,4 @@ if __name__ == "__main__":
212
  question = "When was Aquinas added to Wikipedia page on double effect?"
213
  output = g.invoke({"messages": [HumanMessage(content=question)]})
214
  for msg in output["messages"]:
215
- msg.pretty_print()
 
25
 
26
 
27
  def get_supabase_client():
 
28
  if not SUPABASE_URL or not SUPABASE_SERVICE_KEY:
29
  raise ValueError("Supabase environment variables are missing.")
30
  return create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
 
32
 
33
  @tool
34
  def multiply(a: int, b: int) -> int:
35
+ """Multiply two integers."""
 
 
 
 
 
 
 
 
36
  return a * b
37
 
 
38
  @tool
39
  def add(a: int, b: int) -> int:
40
+ """Add two integers."""
 
 
 
 
 
 
 
 
41
  return a + b
42
 
 
43
  @tool
44
  def subtract(a: int, b: int) -> int:
45
+ """Subtract b from a."""
 
 
 
 
 
 
 
 
46
  return a - b
47
 
 
48
  @tool
49
  def divide(a: int, b: int) -> float:
50
+ """Divide a by b."""
 
 
 
 
 
 
 
 
 
 
 
51
  if b == 0:
52
  raise ValueError("Cannot divide by zero.")
53
  return a / b
54
 
 
55
  @tool
56
  def modulus(a: int, b: int) -> int:
57
+ """Modulo operation."""
 
 
 
 
 
 
 
 
58
  return a % b
59
 
 
60
  @tool
61
  def wiki_search(query: str) -> str:
62
+ """Search Wikipedia for the query and return top results."""
 
 
 
 
 
 
 
63
  docs = WikipediaLoader(query=query, load_max_docs=2).load()
64
  return "\n\n---\n\n".join([doc.page_content for doc in docs])
65
 
 
66
  @tool
67
  def web_search(query: str) -> str:
68
+ """Search the web and return top results."""
 
 
 
 
 
 
 
69
  docs = TavilySearchResults(max_results=3).invoke(query=query)
70
  return "\n\n---\n\n".join([doc.page_content for doc in docs])
71
 
 
72
  @tool
73
  def arvix_search(query: str) -> str:
74
+ """Search Arxiv for the query and return excerpts."""
 
 
 
 
 
 
 
75
  docs = ArxivLoader(query=query, load_max_docs=3).load()
76
  return "\n\n---\n\n".join([doc.page_content[:1000] for doc in docs])
77
 
 
79
  tools = [multiply, add, subtract, divide, modulus, wiki_search, web_search, arvix_search]
80
 
81
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
82
+ system_prompt = f.read().strip()
83
+
84
+ if not system_prompt:
85
+ print("Warning: system_prompt.txt is empty. Using default system prompt.")
86
+ system_prompt = "You are a helpful assistant."
87
 
88
  sys_msg = SystemMessage(content=system_prompt)
89
 
 
120
  llm_with_tools = llm.bind_tools(tools)
121
 
122
  def assistant(state: MessagesState):
123
+ try:
124
+ print("Assistant received messages:")
125
+ for m in state["messages"]:
126
+ print(f"- {m.__class__.__name__}: {m.content[:100]}")
127
+
128
+ result = llm_with_tools.invoke(state["messages"])
129
+ print("LLM output message:")
130
+ if hasattr(result, "content"):
131
+ print(result.content[:500])
132
+ else:
133
+ print(result)
134
+
135
+ if not result or not getattr(result, "content", None):
136
+ print("Warning: LLM returned empty result or no content.")
137
+ return {"messages": [HumanMessage(content="Sorry, I couldn't generate an answer.")]}
138
+
139
+ return {"messages": [result]}
140
+ except Exception as e:
141
+ print(f"Error invoking LLM: {e}")
142
+ return {"messages": [HumanMessage(content="Sorry, I encountered an error during processing.")]}
143
 
144
  def retriever(state: MessagesState):
145
  similar = vector_store.similarity_search(state["messages"][0].content)
 
163
  question = "When was Aquinas added to Wikipedia page on double effect?"
164
  output = g.invoke({"messages": [HumanMessage(content=question)]})
165
  for msg in output["messages"]:
166
+ print(f"\n[{msg.__class__.__name__}] {msg.content}\n")