yooke commited on
Commit
909afab
·
verified ·
1 Parent(s): f9faf38

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +23 -126
agent.py CHANGED
@@ -1,210 +1,107 @@
1
  import os
2
  from dotenv import load_dotenv
3
  from langgraph.graph import START, StateGraph, MessagesState
4
- from langgraph.prebuilt import tools_condition
5
- from langgraph.prebuilt import ToolNode
6
  from langchain_community.tools.tavily_search import TavilySearchResults
7
  from langchain_community.document_loaders import WikipediaLoader
8
- # Removed: from langchain_community.document_loaders import ArxivLoader
9
- from langchain_community.tools import DuckDuckGoSearchRun # Added DuckDuckGo import
10
  from langchain_core.messages import SystemMessage, HumanMessage
11
  from langchain_core.tools import tool
12
- # from langchain_openai import ChatOpenAI
13
  from langchain_deepseek import ChatDeepSeek
14
 
15
- # load_dotenv() # 假设你在 app.py 或其他地方加载了 .env
16
- # Ensure API keys are set
17
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
18
- TAVILY_API_KEY = os.getenv("TAVILY_API_KEY") # 需要在 Space Secrets 中添加 TAVILY_API_KEY
19
 
20
  if not DEEPSEEK_API_KEY:
21
  raise ValueError("DEEPSEEK_API_KEY not found in environment variables.")
22
- # Tavily is still included, so its key is needed if you want to use it.
23
- # If you ONLY want DuckDuckGo, you could remove Tavily and this check.
24
  if not TAVILY_API_KEY:
25
  print("Warning: TAVILY_API_KEY not found. Tavily search tool may not work.")
26
 
27
-
28
- # --- Removed math tools (multiply, add, subtract, divide, modulo) ---
29
-
30
-
31
- # Keep Wikipedia search
32
  @tool
33
  def wiki_search(query: str) -> str:
34
- "Using Wikipedia, search for a query and return up to 2 relevant results."
35
  try:
36
- search_docs = WikipediaLoader(query=query, load_max_docs=2, doc_content_chars_max=2000).load() # Limit content length
37
  if not search_docs:
38
- return "Wikipedia search found no relevant pages."
39
  formatted_search_docs = "\n\n---\n\n".join(
40
  [
41
  f'<Document source="Wikipedia - {doc.metadata.get("source", "")}" page="{doc.metadata.get("page", "")}">\n{doc.page_content}\n</Document>'
42
  for doc in search_docs
43
  ])
44
- return formatted_search_docs # Return string directly
45
  except Exception as e:
46
  return f"An error occurred during Wikipedia search: {e}"
47
 
48
-
49
- # --- Removed Arxiv search (arvix_search) ---
50
-
51
-
52
- # *** ADD TAVILY WEB SEARCH TOOL *** (Kept as requested implicitly by keeping web_search)
53
  @tool
54
  def web_search(query: str) -> str:
55
- """Search the web for a query using Tavily and return relevant snippets."""
56
  if not TAVILY_API_KEY:
57
- return "Tavily search is not available because TAVILY_API_KEY is not set."
58
  try:
59
- tavily = TavilySearchResults(max_results=5) # Get up to 5 results
60
  results = tavily.invoke(query)
61
  if not results:
62
- return "Web search (Tavily) found no relevant results."
63
- # Format Tavily results
64
  formatted_results = "\n\n---\n\n".join([
65
  f'<SearchResult source="{r["source"]}">\nTitle: {r["title"]}\nContent: {r["content"]}\n</SearchResult>'
66
  for r in results
67
  ])
68
- return formatted_results # Return string directly
69
  except Exception as e:
70
  return f"An error occurred during web search (Tavily): {e}"
71
 
72
- # *** ADD DUCKDUCKGO WEB SEARCH TOOL ***
73
- duckduckgo_search_tool_instance = DuckDuckGoSearchRun() # Instantiate the DuckDuckGo tool
74
 
75
  @tool
76
  def duckduckgo_search(query: str) -> str:
77
- """Search the web for a query using DuckDuckGo."""
78
  try:
79
- # The DuckDuckGoSearchRun tool directly returns a formatted string result
80
  results = duckduckgo_search_tool_instance.run(query)
81
  if not results:
82
- return "DuckDuckGo search found no relevant results."
83
- # DuckDuckGoSearchRun often returns results as a string ready to be used
84
  return results
85
  except Exception as e:
86
  return f"An error occurred during DuckDuckGo search: {e}"
87
 
88
-
89
- # load the system prompt from the file
90
- # Ensure this file exists and has the content from Step 2
91
  try:
92
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
93
  system_prompt = f.read()
94
  sys_msg = SystemMessage(content=system_prompt)
95
  except FileNotFoundError:
96
- print("Warning: system_prompt.txt not found. Using a default system message.")
97
- sys_msg = SystemMessage(content="You are a helpful AI assistant. You can use tools to find information.")
98
-
99
 
100
- # Updated tools list: Removed math and Arxiv, Added DuckDuckGo
101
  tools = [
102
  wiki_search,
103
- web_search, # Tavily search
104
- duckduckgo_search, # DuckDuckGo search
105
  ]
106
 
107
-
108
  def build_graph():
109
  llm = ChatDeepSeek(
110
  model="deepseek-chat",
111
- temperature=0, # Keep low for factual answers
112
  max_tokens=None,
113
  timeout=None,
114
  max_retries=2,
115
  api_key=DEEPSEEK_API_KEY,
116
  base_url="https://api.deepseek.com"
117
  )
118
- # Bind the updated tools list to the LLM
119
  llm_with_tools = llm.bind_tools(tools)
120
 
121
  def assistant(state: MessagesState):
122
- """Assistant node: invoke LLM with tools."""
123
- print("---Calling Assistant---") # Added print for debugging
124
- # Include the system message at the beginning of the conversation
125
  messages_for_llm = [sys_msg] + state["messages"]
126
  result = llm_with_tools.invoke(messages_for_llm)
127
- print(f"---Assistant Response: {result}") # Added print for debugging
128
  return {"messages": [result]}
129
 
130
  builder = StateGraph(MessagesState)
131
  builder.add_node("assistant", assistant)
132
- # The ToolNode needs the list of functions, not just the names
133
  builder.add_node("tools", ToolNode(tools))
134
 
135
  builder.add_edge(START, "assistant")
136
-
137
- # The tools_condition checks if the last message from "assistant" is a tool call.
138
- # If yes, it transitions to "tools".
139
- # If no, the graph implicitly ends. This is how the agent stops.
140
- builder.add_conditional_edges(
141
- "assistant",
142
- tools_condition,
143
- # If tool_condition is false (no tool calls detected), the default is None,
144
- # which implicitly ends the graph execution for that path.
145
- # We don't need to explicitly define other paths here for a simple graph.
146
- )
147
-
148
- # After a tool is executed, the result is added to the state, and the control
149
- # goes back to the assistant to process the tool result and decide the next step.
150
  builder.add_edge("tools", "assistant")
151
 
152
- # You can optionally increase the recursion limit if your graph is expected to be complex,
153
- # but it's better to fix the LLM's logic via the prompt first.
154
- # return builder.compile(recursion_limit=50) # Example of increasing limit
155
- return builder.compile()
156
-
157
-
158
- if __name__ == "__main__":
159
- # Example Usage (for local testing)
160
- # To run this part, make sure you have DEEPSEEK_API_KEY set.
161
- # TAVILY_API_KEY is needed for the web_search tool. DuckDuckGo usually works without a key.
162
- # If running locally, you'd typically use `load_dotenv()` here or in app.py
163
-
164
- print("Note: Ensure DEEPSEEK_API_KEY is set.")
165
- print("Note: TAVILY_API_KEY is required for the 'web_search' tool (Tavily). DuckDuckGo usually works without a key.")
166
-
167
- # Test questions covering different tool needs
168
- # Removed purely math questions and Arxiv questions.
169
- # Added questions that might benefit from multiple search tools.
170
- questions_for_testing = [
171
- "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)?", # Web Search (Tavily or DDG)
172
- "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2023? Use Wikipedia first if possible.", # Wikipedia or Web Search
173
- "What country had the least number of athletes at the 1928 Summer Olympics? Find this information using web search.", # Web Search (Tavily or DDG)
174
- "Tell me about the Voyager 1 probe. Use Wikipedia.", # Wikipedia
175
- "What is the current population of Tokyo?", # Web Search (Tavily or DDG)
176
- "Give me a brief overview of the concept of 'LangGraph'.", # Web Search (Tavily or DDG)
177
- ".rewsna eht sa \"tfel\" drow ehT etirw ,ecnetnes siht dnatsrednu uoy fI", # Text manipulation (no tool needed)
178
- ]
179
-
180
-
181
- graph = build_graph()
182
-
183
- # Optional: Draw graph
184
- # try:
185
- # png_data = graph.get_graph().draw_mermaid_png()
186
- # with open("graph.png", "wb") as f:
187
- # f.write(png_data)
188
- # print("Graph visualization saved to graph.png")
189
- # except Exception as e:
190
- # print(f"Could not draw graph: {e}. Make sure 'pygraphviz' and graphviz system libraries are installed.")
191
-
192
-
193
- print("\n--- Running single question tests ---")
194
- for i, question in enumerate(questions_for_testing):
195
- print(f"\n--- Testing Question {i+1}: {question}")
196
- try:
197
- # LangGraph returns the final state after execution completes or hits recursion limit
198
- # Need to start with the system message and the first human message
199
- # The assistant node prepends the system message internally now.
200
- final_state = graph.invoke({"messages": [HumanMessage(content=question)]})
201
- print("\n--- Final State Messages ---")
202
- # Print messages more readably
203
- for m in final_state["messages"]:
204
- print(f"{m.__class__.__name__}: {m.content}")
205
- print("-" * 30)
206
- except Exception as e:
207
- print(f"--- Error running graph for this question: {e}")
208
- import traceback
209
- traceback.print_exc() # Print full traceback for debugging
210
- print("-" * 30)
 
1
  import os
2
  from dotenv import load_dotenv
3
  from langgraph.graph import START, StateGraph, MessagesState
4
+ from langgraph.prebuilt import tools_condition, ToolNode
 
5
  from langchain_community.tools.tavily_search import TavilySearchResults
6
  from langchain_community.document_loaders import WikipediaLoader
7
+ from langchain_community.tools import DuckDuckGoSearchRun
 
8
  from langchain_core.messages import SystemMessage, HumanMessage
9
  from langchain_core.tools import tool
 
10
  from langchain_deepseek import ChatDeepSeek
11
 
12
+ load_dotenv()
13
+
14
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
15
+ TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
16
 
17
  if not DEEPSEEK_API_KEY:
18
  raise ValueError("DEEPSEEK_API_KEY not found in environment variables.")
 
 
19
  if not TAVILY_API_KEY:
20
  print("Warning: TAVILY_API_KEY not found. Tavily search tool may not work.")
21
 
 
 
 
 
 
22
  @tool
23
  def wiki_search(query: str) -> str:
 
24
  try:
25
+ search_docs = WikipediaLoader(query=query, load_max_docs=2, doc_content_chars_max=2000).load()
26
  if not search_docs:
27
+ return "Wikipedia search found no relevant pages."
28
  formatted_search_docs = "\n\n---\n\n".join(
29
  [
30
  f'<Document source="Wikipedia - {doc.metadata.get("source", "")}" page="{doc.metadata.get("page", "")}">\n{doc.page_content}\n</Document>'
31
  for doc in search_docs
32
  ])
33
+ return formatted_search_docs
34
  except Exception as e:
35
  return f"An error occurred during Wikipedia search: {e}"
36
 
 
 
 
 
 
37
  @tool
38
  def web_search(query: str) -> str:
 
39
  if not TAVILY_API_KEY:
40
+ return "Tavily search is not available because TAVILY_API_KEY is not set."
41
  try:
42
+ tavily = TavilySearchResults(max_results=5)
43
  results = tavily.invoke(query)
44
  if not results:
45
+ return "Web search (Tavily) found no relevant results."
 
46
  formatted_results = "\n\n---\n\n".join([
47
  f'<SearchResult source="{r["source"]}">\nTitle: {r["title"]}\nContent: {r["content"]}\n</SearchResult>'
48
  for r in results
49
  ])
50
+ return formatted_results
51
  except Exception as e:
52
  return f"An error occurred during web search (Tavily): {e}"
53
 
54
+ duckduckgo_search_tool_instance = DuckDuckGoSearchRun()
 
55
 
56
  @tool
57
  def duckduckgo_search(query: str) -> str:
 
58
  try:
 
59
  results = duckduckgo_search_tool_instance.run(query)
60
  if not results:
61
+ return "DuckDuckGo search found no relevant results."
 
62
  return results
63
  except Exception as e:
64
  return f"An error occurred during DuckDuckGo search: {e}"
65
 
 
 
 
66
  try:
67
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
68
  system_prompt = f.read()
69
  sys_msg = SystemMessage(content=system_prompt)
70
  except FileNotFoundError:
71
+ print("Warning: system_prompt.txt not found. Using a default system message.")
72
+ sys_msg = SystemMessage(content="You are a helpful AI assistant.")
 
73
 
 
74
  tools = [
75
  wiki_search,
76
+ web_search,
77
+ duckduckgo_search,
78
  ]
79
 
 
80
  def build_graph():
81
  llm = ChatDeepSeek(
82
  model="deepseek-chat",
83
+ temperature=0,
84
  max_tokens=None,
85
  timeout=None,
86
  max_retries=2,
87
  api_key=DEEPSEEK_API_KEY,
88
  base_url="https://api.deepseek.com"
89
  )
 
90
  llm_with_tools = llm.bind_tools(tools)
91
 
92
  def assistant(state: MessagesState):
93
+ print("---Calling Assistant---")
 
 
94
  messages_for_llm = [sys_msg] + state["messages"]
95
  result = llm_with_tools.invoke(messages_for_llm)
96
+ print(f"---Assistant Response: {result}")
97
  return {"messages": [result]}
98
 
99
  builder = StateGraph(MessagesState)
100
  builder.add_node("assistant", assistant)
 
101
  builder.add_node("tools", ToolNode(tools))
102
 
103
  builder.add_edge(START, "assistant")
104
+ builder.add_conditional_edges("assistant", tools_condition)
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  builder.add_edge("tools", "assistant")
106
 
107
+ return builder.compile()