philincloud commited on
Commit
1b3bfe1
·
verified ·
1 Parent(s): 1861c18

Update langgraph_agent.py

Browse files
Files changed (1) hide show
  1. langgraph_agent.py +71 -14
langgraph_agent.py CHANGED
@@ -1,4 +1,9 @@
1
  import os
 
 
 
 
 
2
  from langgraph.graph import START, StateGraph, MessagesState
3
  from langgraph.prebuilt import tools_condition, ToolNode
4
  from langchain_openai import ChatOpenAI
@@ -36,7 +41,6 @@ def modulus(a: int, b: int) -> int:
36
  """Return the remainder of dividing first integer by second."""
37
  return a % b
38
 
39
-
40
  @tool
41
  def wiki_search(query: str) -> dict:
42
  """Search Wikipedia for a query and return up to 2 documents."""
@@ -54,16 +58,19 @@ def wiki_search(query: str) -> dict:
54
  print(f"Error in wiki_search tool: {e}")
55
  return {"wiki_results": f"Error occurred while searching Wikipedia for '{query}'. Details: {str(e)}"}
56
 
57
-
58
  @tool
59
  def web_search(query: str) -> dict:
60
  """Perform a web search (via Tavily) and return up to 3 results."""
61
- docs = TavilySearchResults(max_results=3).invoke(query=query)
62
- formatted = "\n\n---\n\n".join(
63
- f'<Document source="{d.metadata["source"]}"/>\n{d.page_content}'
64
- for d in docs
65
- )
66
- return {"web_results": formatted}
 
 
 
 
67
 
68
  @tool
69
  def arvix_search(query: str) -> dict:
@@ -75,6 +82,55 @@ def arvix_search(query: str) -> dict:
75
  )
76
  return {"arvix_results": formatted}
77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  API_KEY = os.getenv("GEMINI_API_KEY")
79
  HF_SPACE_TOKEN = os.getenv("HF_SPACE_TOKEN")
80
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
@@ -83,6 +139,8 @@ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
83
  tools = [
84
  multiply, add, subtract, divide, modulus,
85
  wiki_search, web_search, arvix_search,
 
 
86
  ]
87
 
88
 
@@ -99,10 +157,9 @@ def build_graph(provider: str = "gemini"):
99
  temperature=1.0,
100
  max_retries=2,
101
  api_key=GEMINI_API_KEY,
102
- max_tokens=5000
103
  )
104
 
105
-
106
  elif provider == "huggingface":
107
  llm = ChatHuggingFace(
108
  llm=HuggingFaceEndpoint(
@@ -129,7 +186,7 @@ def build_graph(provider: str = "gemini"):
129
  return builder.compile()
130
 
131
  if __name__ == "__main__":
132
- graph = build_graph()
133
- msgs = graph.invoke({"messages":[ HumanMessage(content="What’s the capital of France?") ]})
134
- for m in msgs["messages"]:
135
- m.pretty_print()
 
1
  import os
2
+ import io
3
+ import contextlib
4
+ import pandas as pd # Added for Excel file handling
5
+ from typing import Dict, List, Union # Added for type hinting
6
+
7
  from langgraph.graph import START, StateGraph, MessagesState
8
  from langgraph.prebuilt import tools_condition, ToolNode
9
  from langchain_openai import ChatOpenAI
 
41
  """Return the remainder of dividing first integer by second."""
42
  return a % b
43
 
 
44
  @tool
45
  def wiki_search(query: str) -> dict:
46
  """Search Wikipedia for a query and return up to 2 documents."""
 
58
  print(f"Error in wiki_search tool: {e}")
59
  return {"wiki_results": f"Error occurred while searching Wikipedia for '{query}'. Details: {str(e)}"}
60
 
 
61
  @tool
62
  def web_search(query: str) -> dict:
63
  """Perform a web search (via Tavily) and return up to 3 results."""
64
+ try: # Added try-except block for robustness
65
+ docs = TavilySearchResults(max_results=3).invoke(query=query)
66
+ formatted = "\n\n---\n\n".join(
67
+ f'<Document source="{d.metadata["source"]}"/>\n{d.page_content}'
68
+ for d in docs
69
+ )
70
+ return {"web_results": formatted}
71
+ except Exception as e:
72
+ print(f"Error in web_search tool: {e}")
73
+ return {"web_results": f"Error occurred while searching the web for '{query}'. Details: {str(e)}"}
74
 
75
  @tool
76
  def arvix_search(query: str) -> dict:
 
82
  )
83
  return {"arvix_results": formatted}
84
 
85
+ @tool
86
+ def read_file_content(file_path: str) -> Dict[str, str]:
87
+ """
88
+ Reads the content of a file and returns it.
89
+ Supports text (.txt), Python (.py), and Excel (.xlsx) files.
90
+ For other file types, returns a message indicating limited support.
91
+ """
92
+ try:
93
+ _, file_extension = os.path.splitext(file_path)
94
+ content = ""
95
+ if file_extension.lower() in (".txt", ".py"):
96
+ with open(file_path, "r", encoding="utf-8") as f:
97
+ content = f.read()
98
+ elif file_extension.lower() == ".xlsx":
99
+ # Ensure pandas is installed for this.
100
+ df = pd.read_excel(file_path)
101
+ content = df.to_string() # Convert Excel to string representation
102
+ elif file_extension.lower() == ".mp3":
103
+ content = "Audio file provided. Unable to directly process audio. Consider using a transcription service if available."
104
+ elif file_extension.lower() == ".png":
105
+ content = "Image file provided. Unable to directly process images. Consider using an OCR or image analysis service if available."
106
+ else:
107
+ content = f"Unsupported file type: {file_extension}. Only .txt, .py, and .xlsx files are fully supported for reading content."
108
+ return {"file_content": content, "file_name": file_path}
109
+ except FileNotFoundError:
110
+ return {"file_error": f"File not found: {file_path}. Please ensure the file exists in the environment."}
111
+ except Exception as e:
112
+ return {"file_error": f"Error reading file {file_path}: {e}"}
113
+
114
+ @tool
115
+ def python_interpreter(code: str) -> Dict[str, str]:
116
+ """
117
+ Executes Python code and returns its standard output.
118
+ If there's an error during execution, it returns the error message.
119
+ """
120
+ old_stdout = io.StringIO()
121
+ # Redirect stdout to capture print statements
122
+ with contextlib.redirect_stdout(old_stdout):
123
+ try:
124
+ # Create a dictionary to hold the execution scope for exec
125
+ exec_globals = {}
126
+ exec_locals = {}
127
+ exec(code, exec_globals, exec_locals)
128
+ output = old_stdout.getvalue()
129
+ return {"execution_result": output.strip()}
130
+ except Exception as e:
131
+ return {"execution_error": str(e)}
132
+
133
+
134
  API_KEY = os.getenv("GEMINI_API_KEY")
135
  HF_SPACE_TOKEN = os.getenv("HF_SPACE_TOKEN")
136
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
 
139
  tools = [
140
  multiply, add, subtract, divide, modulus,
141
  wiki_search, web_search, arvix_search,
142
+ read_file_content, # Added new tool
143
+ python_interpreter, # Added new tool
144
  ]
145
 
146
 
 
157
  temperature=1.0,
158
  max_retries=2,
159
  api_key=GEMINI_API_KEY,
160
+ max_tokens=5000
161
  )
162
 
 
163
  elif provider == "huggingface":
164
  llm = ChatHuggingFace(
165
  llm=HuggingFaceEndpoint(
 
186
  return builder.compile()
187
 
188
  if __name__ == "__main__":
189
+ # This block is intentionally left empty as per user request to remove examples.
190
+ # Your agent will interact with the graph by invoking it with messages.
191
+ pass
192
+