mludvig commited on
Commit
eccf2a7
·
1 Parent(s): efcf255

Improved Wikipedia tool and system prompt

Browse files
Files changed (4) hide show
  1. agents.py +23 -13
  2. app.py +3 -0
  3. requirements.txt +3 -1
  4. tools.py +49 -32
agents.py CHANGED
@@ -13,22 +13,27 @@ from tools import tools
13
  THINKER_SYSTEM_PROMPT = """
14
  You are a thinking agent that analyzes tasks and breaks them down into steps. You are encouraged to use tools to help you solve the task.
15
  You are not allowed to answer the task directly. Instead, you will provide a step-by-step breakdown of how to approach the task.
16
- You will also provide a final answer at the end of your reasoning. Only provide a concise answer to the task, no other text. Often it is just a number or a single word.
17
 
18
  Your job is to:
19
- 1. Understand what the task is asking.
20
- 2. Decide what information you need to solve it. Think step by step and think ahead.
21
- 3. Use the available tools to obtain the required information. Never answer any questions directly. Always use a tool or provide a final answer.
22
- 4. After the tools are called control will return to you and you will decide what to do next, whether to use another tool or provide a final answer.
23
- 5. If you have all the information to solve the task, write your response in this EXACT format:
 
 
 
 
24
  FINAL ANSWER: <your answer>
25
  """
26
 
27
  # Define the maximum number of turns for the agent
28
- MAX_TURNS = 5
29
 
30
  # Initialize the LLM
31
- llm = ChatOpenAI(model="o4-mini")
 
32
 
33
 
34
  class AgentState(TypedDict):
@@ -44,11 +49,16 @@ def thinker(state: AgentState) -> AgentState:
44
  ai_messages = [msg for msg in state["messages"] if isinstance(msg, AIMessage)]
45
  if len(ai_messages) >= MAX_TURNS:
46
  print("Maximum number of turns reached. Exiting.")
 
47
  return state
48
 
49
  # Bind the tools to the LLM
50
  llm_with_tools = llm.bind_tools(tools)
51
 
 
 
 
 
52
  # Get the thinking agent's response
53
  response = llm_with_tools.invoke(state["messages"])
54
 
@@ -141,15 +151,15 @@ class ThinkerAgent:
141
  return final_answer, final_state
142
 
143
 
144
- def dump_state(state: AgentState) -> str:
145
  """
146
  Dump the state to a string for debugging.
147
  """
148
  if state["messages"]:
149
  for i, msg in enumerate(state["messages"]):
150
  role = msg.type
151
- content_preview = msg.content[:50] + "..." if len(msg.content) > 50 else msg.content
152
- # content_preview = msg.content
153
  print(f"Message {i}: {role} - {content_preview}")
154
 
155
  # Print tool calls if present
@@ -158,8 +168,8 @@ def dump_state(state: AgentState) -> str:
158
  print(f"- Tool Call: {tool_call['name']} with arguments: {tool_call['args']}")
159
 
160
  # Print the final answer
161
- if final_answer:
162
- print(f"Final Answer: {final_answer}")
163
 
164
 
165
  if __name__ == "__main__":
 
13
  THINKER_SYSTEM_PROMPT = """
14
  You are a thinking agent that analyzes tasks and breaks them down into steps. You are encouraged to use tools to help you solve the task.
15
  You are not allowed to answer the task directly. Instead, you will provide a step-by-step breakdown of how to approach the task.
16
+ You will also provide a final answer at the end of your reasoning.
17
 
18
  Your job is to:
19
+ - Understand what the task is asking.
20
+ - Decide what information you need to solve it. Think step by step and think ahead about what you will need to do. Provide your thoughts in <thoughts>your thoughts</thoughts> format in every turn.
21
+ - Use the available tools to obtain the required information or if you are 100% sure about the answer use your knowledge.
22
+ - If you need to use a tool, call it with the required arguments. You are encouraged to use multiple tools in a single turn for a quicker resolution if they don't depend on each other. For example search for multiple terms in Google or Wikipedia at once.
23
+ - You can use the tools in any order you like. You can also use the same tool multiple times.
24
+ - After the tools are called control will return to you and you will decide what to do next, whether to use another tool or provide a final answer.
25
+ - When you think you have all the information to solve the task, present all the facts that led you to the final answer in a clear and concise summary, showing your reasoning.
26
+ - If you are not sure about the answer, ask for more information or use the tools to get it.
27
+ - If you have all the information to solve the task, provide a concise answer to the task, no other text. Often it is just a number or a single word or a comma-separated list. Write your response in this EXACT format:
28
  FINAL ANSWER: <your answer>
29
  """
30
 
31
  # Define the maximum number of turns for the agent
32
+ MAX_TURNS = 10
33
 
34
  # Initialize the LLM
35
+ # llm = ChatOpenAI(model="o4-mini")
36
+ llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
37
 
38
 
39
  class AgentState(TypedDict):
 
49
  ai_messages = [msg for msg in state["messages"] if isinstance(msg, AIMessage)]
50
  if len(ai_messages) >= MAX_TURNS:
51
  print("Maximum number of turns reached. Exiting.")
52
+ dump_state(state)
53
  return state
54
 
55
  # Bind the tools to the LLM
56
  llm_with_tools = llm.bind_tools(tools)
57
 
58
+ if len(ai_messages) > 0:
59
+ # Add new instructions for the LLM
60
+ state["messages"].append(HumanMessage(content="With the information you have, can you confidently answer the question? If so, please do. If not, please use the tools to get the information you need."))
61
+
62
  # Get the thinking agent's response
63
  response = llm_with_tools.invoke(state["messages"])
64
 
 
151
  return final_answer, final_state
152
 
153
 
154
+ def dump_state(state: AgentState) -> None:
155
  """
156
  Dump the state to a string for debugging.
157
  """
158
  if state["messages"]:
159
  for i, msg in enumerate(state["messages"]):
160
  role = msg.type
161
+ # content_preview = msg.content[:50] + "..." if len(msg.content) > 50 else msg.content
162
+ content_preview = msg.content
163
  print(f"Message {i}: {role} - {content_preview}")
164
 
165
  # Print tool calls if present
 
168
  print(f"- Tool Call: {tool_call['name']} with arguments: {tool_call['args']}")
169
 
170
  # Print the final answer
171
+ if state.get("final_answer"):
172
+ print(f"Final Answer: {state['final_answer']}")
173
 
174
 
175
  if __name__ == "__main__":
app.py CHANGED
@@ -62,6 +62,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
62
  print(f"An unexpected error occurred fetching questions: {e}")
63
  return f"An unexpected error occurred fetching questions: {e}", None
64
 
 
 
 
65
  # 3. Run your Agent
66
  results_log = []
67
  answers_payload = []
 
62
  print(f"An unexpected error occurred fetching questions: {e}")
63
  return f"An unexpected error occurred fetching questions: {e}", None
64
 
65
+ # 2.5 Filter out questions with files (for now)
66
+ questions_data = [item for item in questions_data if not item.get("file_name")]
67
+
68
  # 3. Run your Agent
69
  results_log = []
70
  answers_payload = []
requirements.txt CHANGED
@@ -11,4 +11,6 @@ langgraph
11
 
12
  langchain-community
13
  pyowm
14
- wikipedia
 
 
 
11
 
12
  langchain-community
13
  pyowm
14
+ wikipedia
15
+
16
+ markitdown[all]
tools.py CHANGED
@@ -1,37 +1,36 @@
 
1
  from langchain_core.tools import tool
2
- from langchain_core.messages import SystemMessage, HumanMessage
3
- from langchain_openai import ChatOpenAI
4
  from langchain_community.utilities import OpenWeatherMapAPIWrapper
5
  # from langchain_community.retrievers import WikipediaRetriever
6
  import wikipedia
 
7
 
 
 
 
 
8
 
9
- llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
 
 
 
10
 
 
 
11
 
12
- @tool
13
- def simple_answer_function(question: str) -> str:
14
- """
15
- Answer a specific question using LLM common knowledge.
16
 
17
- Args:
18
- question (str): The question to be answered.
19
- """
20
- print(f"simple_answer_function called with: {question}")
21
 
22
- # Create the system message
23
- system_message = SystemMessage(content="Answer the question as best as you can. Only provide the answer, no other text.")
24
 
25
- # Create the initial messages
26
- messages = [system_message, HumanMessage(content=question)]
27
-
28
- # Get the response from the LLM
29
- response = llm.invoke(messages)
30
- answer = response.content
31
-
32
- print(f"simple_answer_function response: {answer}")
33
-
34
- return answer
35
 
36
 
37
  @tool
@@ -84,38 +83,56 @@ def unit_converter_tool(value: float, from_unit: str, to_unit: str) -> float:
84
 
85
 
86
  @tool
87
- def wikipedia_tool(query: str) -> str:
88
  """
89
  Search Wikipedia for a specific query.
90
 
91
  Args:
92
  query (str): The query to search for on Wikipedia.
 
93
  Returns:
94
  str: The HTML content of the Wikipedia page.
95
  """
96
  print(f"wikipedia_tool called with: {query}")
97
 
98
- wikipedia.set_lang("en")
99
  # Search Wikipedia for the query
100
- search_results = wikipedia.search(query)
101
  if search_results:
102
  # Get the first result
103
  page_title = search_results[0]
104
  print(f"First Wikipedia search result: {page_title}")
105
 
106
- # Get the page summary
107
- page = wikipedia.page(page_title, auto_suggest=True, preload=True)
108
- print(f"wikipedia_tool summary: {page.summary}")
109
- return page.html()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  error = f"No results found for query: {query}"
112
  print(error)
113
- raise ValueError(error)
114
 
115
 
116
  # List of tools to be used
117
  tools = [
118
- simple_answer_function,
119
  weather_tool,
120
  unit_converter_tool,
121
  wikipedia_tool,
 
1
+ from io import BytesIO
2
  from langchain_core.tools import tool
3
+ # from langchain_core.messages import SystemMessage, HumanMessage
4
+ # from langchain_openai import ChatOpenAI
5
  from langchain_community.utilities import OpenWeatherMapAPIWrapper
6
  # from langchain_community.retrievers import WikipediaRetriever
7
  import wikipedia
8
+ from markitdown import MarkItDown
9
 
10
+ # @tool
11
+ # def simple_answer_function(question: str) -> str:
12
+ # """
13
+ # Answer a specific question using LLM common knowledge.
14
 
15
+ # Args:
16
+ # question (str): The question to be answered.
17
+ # """
18
+ # print(f"simple_answer_function called with: {question}")
19
 
20
+ # # Create the system message
21
+ # system_message = SystemMessage(content="Answer the question as best as you can. Only provide the answer, no other text.")
22
 
23
+ # # Create the initial messages
24
+ # messages = [system_message, HumanMessage(content=question)]
 
 
25
 
26
+ # # Get the response from the LLM
27
+ # llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
28
+ # response = llm.invoke(messages)
29
+ # answer = response.content
30
 
31
+ # print(f"simple_answer_function response: {answer}")
 
32
 
33
+ # return answer
 
 
 
 
 
 
 
 
 
34
 
35
 
36
  @tool
 
83
 
84
 
85
  @tool
86
+ def wikipedia_tool(query: str, language: str) -> str:
87
  """
88
  Search Wikipedia for a specific query.
89
 
90
  Args:
91
  query (str): The query to search for on Wikipedia.
92
+ language (str): The language to use for the Wikipedia search, e.g., "en" for English.
93
  Returns:
94
  str: The HTML content of the Wikipedia page.
95
  """
96
  print(f"wikipedia_tool called with: {query}")
97
 
98
+ wikipedia.set_lang(language)
99
  # Search Wikipedia for the query
100
+ search_results = wikipedia.search(query, results=1)
101
  if search_results:
102
  # Get the first result
103
  page_title = search_results[0]
104
  print(f"First Wikipedia search result: {page_title}")
105
 
106
+ try:
107
+ # Get the page summary
108
+ page = wikipedia.page(page_title, auto_suggest=False, preload=True)
109
+ print(f"wikipedia_tool title: {page.title}")
110
+ # print(f"wikipedia_tool page summary: {page.summary[:100]}...")
111
+ # Get the page content as a BytesIO object
112
+ # Build a complete HTML page
113
+ page_content = f"<html><head><title>{page.title}</title></head><body>{page.html()}</body></html>"
114
+ page_io = BytesIO(page_content.encode("utf-8"))
115
+ # Convert the page content from HTML to Markdown
116
+ markdown_converter = MarkItDown()
117
+ markdown_result = markdown_converter.convert(page_io)
118
+ # Get the markdown content
119
+ markdown_content = markdown_result.markdown
120
+ print(f"wikipedia_tool markdown content: {markdown_content.splitlines()[0]}...")
121
+ return markdown_content
122
+
123
+ except Exception as e:
124
+ error = f"Error retrieving Wikipedia page: {e}"
125
+ print(error)
126
+ return error
127
 
128
  error = f"No results found for query: {query}"
129
  print(error)
130
+ return error
131
 
132
 
133
  # List of tools to be used
134
  tools = [
135
+ # simple_answer_function,
136
  weather_tool,
137
  unit_converter_tool,
138
  wikipedia_tool,