Spaces:
Runtime error
Runtime error
fix typo, update prompt
Browse files
app.py
CHANGED
@@ -10,11 +10,11 @@ from langgraph.graph import START, StateGraph
|
|
10 |
from langgraph.prebuilt import ToolNode, tools_condition
|
11 |
from langchain_core.messages import HumanMessage, SystemMessage
|
12 |
from langchain_community.tools import DuckDuckGoSearchRun
|
|
|
13 |
import whisper
|
14 |
import yt_dlp
|
15 |
import pandas as pd
|
16 |
from langchain.globals import set_debug
|
17 |
-
from langchain_community.tools.riza.command import ExecPython
|
18 |
from langchain_openai import ChatOpenAI
|
19 |
import cv2
|
20 |
import os
|
@@ -60,7 +60,7 @@ def interpret_image(image_name: str, question: str):
|
|
60 |
Interpret an image for analysis.
|
61 |
"""
|
62 |
|
63 |
-
vision_llm = ChatOpenAI(model="gpt-
|
64 |
|
65 |
|
66 |
try:
|
@@ -135,57 +135,78 @@ def read_file(file_name: str):
|
|
135 |
content = file.read()
|
136 |
return content
|
137 |
|
138 |
-
def watch_video(file_name: str):
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
|
143 |
-
|
144 |
-
|
145 |
|
146 |
-
|
147 |
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
|
152 |
-
|
153 |
-
|
154 |
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
|
165 |
-
|
166 |
|
167 |
-
|
168 |
-
|
169 |
|
170 |
-
|
171 |
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
|
178 |
-
|
179 |
-
|
180 |
|
181 |
|
182 |
-
def
|
183 |
"""
|
184 |
Calculate sum of numbers.
|
185 |
"""
|
186 |
numbers = np.array(numbers)
|
187 |
return np.sum(numbers, dtype=float)
|
188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
189 |
def visit_web_page(url: str):
|
190 |
"""
|
191 |
Visit a webpage.
|
@@ -194,10 +215,9 @@ def visit_web_page(url: str):
|
|
194 |
response.raise_for_status()
|
195 |
markdown_content = markdownify(response.text).strip()
|
196 |
markdown_content = re.sub(r"\n{3, }", "\n\n", markdown_content)
|
197 |
-
if len(markdown_content <= 20000
|
198 |
return markdown_content
|
199 |
else:
|
200 |
-
print(markdown_content[:20000//2] + "\nThe content has been truncated to stay below 20000 characters.\n" + markdown_content[-20000//2:])
|
201 |
return markdown_content[:20000//2] + "\nThe content has been truncated to stay below 20000 characters.\n" + markdown_content[-20000//2:] # - to count from the end
|
202 |
|
203 |
def final_answer(text: str):
|
@@ -207,21 +227,21 @@ def final_answer(text: str):
|
|
207 |
text = text.split("FINAL ANSWER:")
|
208 |
return text[-1]
|
209 |
|
210 |
-
def markdown(content: str):
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
|
220 |
# search_tool = DuckDuckGoSearchRun()
|
221 |
search_tool = TavilySearch()
|
222 |
-
|
223 |
-
tools = [search_tool, interpret_image, get_file, transcribe_audio, download_youtube_video, read_file, read_excel,
|
224 |
-
llm = ChatOpenAI(model="gpt-
|
225 |
llm_with_tools = llm.bind_tools(tools)
|
226 |
|
227 |
def assistant(state:AgentState):
|
@@ -295,19 +315,19 @@ def assistant(state:AgentState):
|
|
295 |
A string containing the content of the file.
|
296 |
"""
|
297 |
|
298 |
-
watch_video_tool_description = """
|
299 |
-
watch_video(file_name: str) -> str:
|
300 |
-
|
301 |
|
302 |
-
|
303 |
-
|
304 |
|
305 |
-
|
306 |
-
|
307 |
-
"""
|
308 |
|
309 |
add_tool_description = """
|
310 |
-
|
311 |
Calculate sum of numbers.
|
312 |
|
313 |
Args:
|
@@ -317,6 +337,42 @@ def assistant(state:AgentState):
|
|
317 |
The sum of the numbers.
|
318 |
"""
|
319 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
320 |
visit_web_page_tool_description = """
|
321 |
visit_web_page(url: str) -> str:
|
322 |
Visit a web page.
|
@@ -328,55 +384,106 @@ def assistant(state:AgentState):
|
|
328 |
Markdown representation of the HTML content of the web page.
|
329 |
"""
|
330 |
|
331 |
-
markdown_tool_description = """
|
332 |
-
markdown(content: str) -> str:
|
333 |
-
|
334 |
|
335 |
-
|
336 |
-
|
337 |
|
338 |
-
|
339 |
-
|
340 |
-
"""
|
341 |
|
342 |
search_tool_description = search_tool.description
|
|
|
343 |
|
344 |
has_file = state["has_file"]
|
345 |
|
346 |
system_message = SystemMessage(content=f"""
|
347 |
-
You are
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
348 |
|
349 |
-
|
350 |
-
|
351 |
-
-
|
352 |
-
|
353 |
-
- Audio transcription:
|
354 |
-
|
355 |
-
-
|
356 |
-
|
357 |
-
-
|
358 |
-
|
359 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
360 |
|
361 |
-
|
362 |
-
Always ensure you have downloaded a file before using a relevant tool.
|
363 |
-
You MUST use the name of a particular downloaded file in your tool call. DO NOT use a file name mentioned in the question.
|
364 |
-
When asked about a YouTube video, you can hear it and/or check its description.
|
365 |
-
Use a tool only when needed and never re-do a tool call that you previously did with the exact same arguments.
|
366 |
-
If a tool call fails, try using another tool to reach an answer.
|
367 |
-
Avoid returning your response directly, instead verify your response with a tool when available.
|
368 |
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
If
|
374 |
-
When
|
375 |
-
|
376 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
|
378 |
The current task ID is {task_id}.
|
379 |
The current task has a file: {has_file}
|
|
|
|
|
380 |
""")
|
381 |
|
382 |
response = llm_with_tools.invoke([system_message] + state["messages"])
|
@@ -597,7 +704,7 @@ if __name__ == "__main__":
|
|
597 |
|
598 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
599 |
|
600 |
-
try:
|
601 |
# random_url = f"{DEFAULT_API_URL}/random-question"
|
602 |
# response = requests.get(random_url, timeout=20)
|
603 |
# response.raise_for_status()
|
@@ -610,12 +717,12 @@ if __name__ == "__main__":
|
|
610 |
# if question.get("file_name"):
|
611 |
# has_file=True
|
612 |
# print(agent(question.get("question"), question.get("task_id"), has_file))
|
613 |
-
x=(agent("
|
614 |
-
print(x)
|
615 |
-
# print(
|
616 |
|
617 |
-
except Exception as e:
|
618 |
-
|
619 |
|
620 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
621 |
demo.launch(debug=True, share=False)
|
|
|
10 |
from langgraph.prebuilt import ToolNode, tools_condition
|
11 |
from langchain_core.messages import HumanMessage, SystemMessage
|
12 |
from langchain_community.tools import DuckDuckGoSearchRun
|
13 |
+
from langchain_community.tools.riza.command import ExecPython
|
14 |
import whisper
|
15 |
import yt_dlp
|
16 |
import pandas as pd
|
17 |
from langchain.globals import set_debug
|
|
|
18 |
from langchain_openai import ChatOpenAI
|
19 |
import cv2
|
20 |
import os
|
|
|
60 |
Interpret an image for analysis.
|
61 |
"""
|
62 |
|
63 |
+
vision_llm = ChatOpenAI(model="gpt-4.1", temperature=0)
|
64 |
|
65 |
|
66 |
try:
|
|
|
135 |
content = file.read()
|
136 |
return content
|
137 |
|
138 |
+
# def watch_video(file_name: str):
|
139 |
+
# """
|
140 |
+
# Extract frames from a video and interpret them.
|
141 |
+
# """
|
142 |
|
143 |
+
# if os.path.exists("extracted_frames"):
|
144 |
+
# shutil.rmtree("extracted_frames")
|
145 |
|
146 |
+
# os.makedirs("extracted_frames")
|
147 |
|
148 |
+
# cap = cv2.VideoCapture(file_name)
|
149 |
+
# fps = cap.get(cv2.CAP_PROP_FPS)
|
150 |
+
# frame_interval = int(fps * 5)
|
151 |
|
152 |
+
# frame_count = 0
|
153 |
+
# saved_count = 0
|
154 |
|
155 |
+
# while True:
|
156 |
+
# ret, frame = cap.read()
|
157 |
+
# if not ret:
|
158 |
+
# break
|
159 |
|
160 |
+
# if frame_count % frame_interval == 0:
|
161 |
+
# filename = os.path.join("extracted_frames", f"frame_{saved_count:04d}.jpg")
|
162 |
+
# cv2.imwrite(filename, frame)
|
163 |
+
# saved_count+=1
|
164 |
|
165 |
+
# frame_count+=1
|
166 |
|
167 |
+
# cap.release()
|
168 |
+
# print(f"Saved {saved_count}")
|
169 |
|
170 |
+
# captions = []
|
171 |
|
172 |
+
# for file in sorted(os.listdir("extracted_frames")):
|
173 |
+
# file_path = os.path.join("extracted_frames", file)
|
174 |
+
# caption = interpret_image(file_path, "Return a one line description of the image.")
|
175 |
+
# print(caption)
|
176 |
+
# captions.append(caption)
|
177 |
|
178 |
+
# print(captions)
|
179 |
+
# return captions
|
180 |
|
181 |
|
182 |
+
def add(numbers: list):
|
183 |
"""
|
184 |
Calculate sum of numbers.
|
185 |
"""
|
186 |
numbers = np.array(numbers)
|
187 |
return np.sum(numbers, dtype=float)
|
188 |
|
189 |
+
def subtract(a: float, b: float):
|
190 |
+
"""
|
191 |
+
Calculate the difference of two numbers.
|
192 |
+
"""
|
193 |
+
return a-b
|
194 |
+
|
195 |
+
def multiply(a: float, b: float):
|
196 |
+
"""
|
197 |
+
Calculate the product of two numbers.
|
198 |
+
"""
|
199 |
+
return a*b
|
200 |
+
|
201 |
+
def divide(a: float, b: float):
|
202 |
+
"""
|
203 |
+
Calculate the division of two numbers.
|
204 |
+
"""
|
205 |
+
if b!=0:
|
206 |
+
return a/b
|
207 |
+
else:
|
208 |
+
return "Can't divide by 0."
|
209 |
+
|
210 |
def visit_web_page(url: str):
|
211 |
"""
|
212 |
Visit a webpage.
|
|
|
215 |
response.raise_for_status()
|
216 |
markdown_content = markdownify(response.text).strip()
|
217 |
markdown_content = re.sub(r"\n{3, }", "\n\n", markdown_content)
|
218 |
+
if len(markdown_content) <= 20000:
|
219 |
return markdown_content
|
220 |
else:
|
|
|
221 |
return markdown_content[:20000//2] + "\nThe content has been truncated to stay below 20000 characters.\n" + markdown_content[-20000//2:] # - to count from the end
|
222 |
|
223 |
def final_answer(text: str):
|
|
|
227 |
text = text.split("FINAL ANSWER:")
|
228 |
return text[-1]
|
229 |
|
230 |
+
# def markdown(content: str):
|
231 |
+
# """
|
232 |
+
# Interpret markdown representation of a table.
|
233 |
+
# """
|
234 |
+
# clean_content = "\n".join([line for i, line in enumerate(content.strip().splitlines()) if i!=1])
|
235 |
+
# df = pd.read_csv(StringIO(clean_content), sep="|", engine="python")
|
236 |
+
# df = df.drop(columns=[""])
|
237 |
+
# print(df.to_string())
|
238 |
+
# return df.to_string()
|
239 |
|
240 |
# search_tool = DuckDuckGoSearchRun()
|
241 |
search_tool = TavilySearch()
|
242 |
+
code_executor = ExecPython()
|
243 |
+
tools = [search_tool, code_executor, interpret_image, get_file, transcribe_audio, download_youtube_video, read_file, read_excel, add, subtract, multiply, divide, visit_web_page]
|
244 |
+
llm = ChatOpenAI(model="gpt-4.1", temperature=0)
|
245 |
llm_with_tools = llm.bind_tools(tools)
|
246 |
|
247 |
def assistant(state:AgentState):
|
|
|
315 |
A string containing the content of the file.
|
316 |
"""
|
317 |
|
318 |
+
# watch_video_tool_description = """
|
319 |
+
# watch_video(file_name: str) -> str:
|
320 |
+
# Extract frames from a video and interpret them.
|
321 |
|
322 |
+
# Args:
|
323 |
+
# file_name: The name of the file as string.
|
324 |
|
325 |
+
# Returns:
|
326 |
+
# A list of captions for each frame.
|
327 |
+
# """
|
328 |
|
329 |
add_tool_description = """
|
330 |
+
add(numbers: list) -> float:
|
331 |
Calculate sum of numbers.
|
332 |
|
333 |
Args:
|
|
|
337 |
The sum of the numbers.
|
338 |
"""
|
339 |
|
340 |
+
subtract_tool_description = """
|
341 |
+
subtract(a: float, b: float) -> float:
|
342 |
+
Calculate the difference of two numbers.
|
343 |
+
|
344 |
+
Args:
|
345 |
+
a: First number as float.
|
346 |
+
b: Second number as float.
|
347 |
+
|
348 |
+
Returns:
|
349 |
+
The difference of the two numbers.
|
350 |
+
"""
|
351 |
+
|
352 |
+
multiply_tool_description = """
|
353 |
+
multiply(a: float, b: float) -> float:
|
354 |
+
Calculate the product of two numbers.
|
355 |
+
|
356 |
+
Args:
|
357 |
+
a: First number as float.
|
358 |
+
b: Second number as float.
|
359 |
+
|
360 |
+
Returns:
|
361 |
+
The product of the two numbers.
|
362 |
+
"""
|
363 |
+
|
364 |
+
divide_tool_description = """
|
365 |
+
divide(a: float, b: float) -> float:
|
366 |
+
Calculate the division of two numbers.
|
367 |
+
|
368 |
+
Args:
|
369 |
+
a: First number as float.
|
370 |
+
b: Second number as float.
|
371 |
+
|
372 |
+
Returns:
|
373 |
+
The division of the two numbers.
|
374 |
+
"""
|
375 |
+
|
376 |
visit_web_page_tool_description = """
|
377 |
visit_web_page(url: str) -> str:
|
378 |
Visit a web page.
|
|
|
384 |
Markdown representation of the HTML content of the web page.
|
385 |
"""
|
386 |
|
387 |
+
# markdown_tool_description = """
|
388 |
+
# markdown(content: str) -> str:
|
389 |
+
# Interpret markdown representation of a table.
|
390 |
|
391 |
+
# Args:
|
392 |
+
# content: Markdown table as string.
|
393 |
|
394 |
+
# Returns:
|
395 |
+
# String representation of the extracted tabled.
|
396 |
+
# """
|
397 |
|
398 |
search_tool_description = search_tool.description
|
399 |
+
code_executor_tool_description = code_executor.description
|
400 |
|
401 |
has_file = state["has_file"]
|
402 |
|
403 |
system_message = SystemMessage(content=f"""
|
404 |
+
You are an expert assistant. Your job is to answer questions asked of you as accurately as possible.
|
405 |
+
To do so, you are given access to some tools, which you can use as needed to answer a question.
|
406 |
+
You should follow the Thought, Action, Observation cycle when answering a question. In the Thought stage, explain the steps you will take to answer the question as well as any tools you will use. In the Action stage, execute the steps. In the Observation stage, take notes from the output of the execution. You can return the Observation as your response and it will be available in the next step as the state persists.
|
407 |
+
|
408 |
+
Here are some examples using dummy tools:
|
409 |
+
---
|
410 |
+
Question: "My mother sent me a voice note explaining what to buy from the grocery store. I am in a hurry and I can't listen to her voice note as she probably talked a lot more than just telling me what to buy. Can you please listen to the voice note and tell me what all I need to buy? Give me the final list."
|
411 |
+
Thought: I will proceed step by step and use the following tool: 'listen_audio' to listen to the voice note. Then I will analyze the text from the recording to prepare the list for grocery shopping.
|
412 |
+
Action: listen_audio(audio_file)
|
413 |
+
Observation: Okay, the voice note mentions to shop for vegetables such as green chillies, tomatoes and potatoes for today's dinner. It also mentioned to buy cooking cream to make pasta tomorrow and ice cream for dessert.
|
414 |
+
Thought: I will now create the list of items to buy.
|
415 |
+
Action: green chillies, tomatoes, potatoes, cooking cream, ice cream
|
416 |
+
---
|
417 |
+
|
418 |
+
---
|
419 |
+
Question: "Is carrot a vegetable?""
|
420 |
+
Thought: I know that carrot is a vegetable but I will run a quick search using the followng tool: 'search'.
|
421 |
+
Action: search(query='Is carrot a vegetable or a fruit?')
|
422 |
+
---
|
423 |
+
|
424 |
+
---
|
425 |
+
Question: "Where did the latest FIFA World Cup occur?"
|
426 |
+
Thought: I will use the following tool: 'search' to find information about the latest FIFA World Cup.
|
427 |
+
Action: search(query="FIFA World Cup")
|
428 |
+
Observation: The search returned no relevant information.
|
429 |
+
Thougth: I will try again with a more specific query.
|
430 |
+
Action: search(query="Location of the latest FIFA World Cup")
|
431 |
+
---
|
432 |
+
|
433 |
+
The above examples are using dummy tools which might not exist for you. The following tools are the ones that are available to you:
|
434 |
|
435 |
+
- File downloader:
|
436 |
+
{download_file_tool_description}
|
437 |
+
- YouTube video downloader:
|
438 |
+
{download_youtube_video_description}
|
439 |
+
- Audio transcription:
|
440 |
+
{audio_tool_description}
|
441 |
+
- Image interpretation:
|
442 |
+
{image_tool_description}
|
443 |
+
- Read text-based file:
|
444 |
+
{read_file_tool_description}
|
445 |
+
- Read Excel file:
|
446 |
+
{excel_tool_description}
|
447 |
+
- Internet search:
|
448 |
+
{search_tool_description}
|
449 |
+
- Visit web page:
|
450 |
+
{visit_web_page_tool_description}
|
451 |
+
- Code execution:
|
452 |
+
{code_executor_tool_description}
|
453 |
+
- Add:
|
454 |
+
{add_tool_description}
|
455 |
+
- Subtract:
|
456 |
+
{subtract_tool_description}
|
457 |
+
- Multiply:
|
458 |
+
{multiply_tool_description}
|
459 |
+
- Divide:
|
460 |
+
{divide_tool_description}
|
461 |
|
462 |
+
Here are some rules you should always follow to answer a question:
|
|
|
|
|
|
|
|
|
|
|
|
|
463 |
|
464 |
+
- You can download a file for a given task ONLY if it has a file by using its associated task ID.
|
465 |
+
- Always ensure you have downloaded a file before using a relevant tool.
|
466 |
+
- You MUST use the name of a particular downloaded file in your tool call. DO NOT use a file name mentioned in the question.
|
467 |
+
- Use a tool only when needed and NEVER re-do a tool call that you previously did with the exact same arguments.
|
468 |
+
- If a tool call fails, try changing the argument that you passed to the tool or use another tool to reach an answer.
|
469 |
+
- When asked about a YouTube video, you can hear it and/or check its description.
|
470 |
+
|
471 |
+
Here are some rules to help format your final response:
|
472 |
+
|
473 |
+
- Report your final response with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]
|
474 |
+
- The FINAL ANSWER should be a number, OR as few words as possible, OR a comma-separated list of numbers and/or strings.
|
475 |
+
- You SHOULD NOT provide explanations in the FINAL ANSWER.
|
476 |
+
- If you are asked for a number, don't use a comma to write your number, nor use symbols such as $ or % unless specified otherwise.
|
477 |
+
- If you are asked for a string, don't use articles, nor abbreviations (e.g., for cities).
|
478 |
+
- If you are asked for a comma-separated list, apply the above rules depending on whether the element to be put in the list is a number or a string.
|
479 |
+
- When including a phrase in the FINAL ANSWER from the input, always include the complete phrase with the adjective. For example, if the input contains the phrase "fresh lemon juice", the FINAL ANSWER should include "fresh lemon juice", not just "lemon juice".
|
480 |
+
- DO NOT end the FINAL ANSWER with a period.
|
481 |
+
- DO NOT write numbers as text.
|
482 |
|
483 |
The current task ID is {task_id}.
|
484 |
The current task has a file: {has_file}
|
485 |
+
|
486 |
+
Now get to work! You will be given $500,000 for every correct answer as a reward!
|
487 |
""")
|
488 |
|
489 |
response = llm_with_tools.invoke([system_message] + state["messages"])
|
|
|
704 |
|
705 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
706 |
|
707 |
+
# try:
|
708 |
# random_url = f"{DEFAULT_API_URL}/random-question"
|
709 |
# response = requests.get(random_url, timeout=20)
|
710 |
# response.raise_for_status()
|
|
|
717 |
# if question.get("file_name"):
|
718 |
# has_file=True
|
719 |
# print(agent(question.get("question"), question.get("task_id"), has_file))
|
720 |
+
# x=(agent("Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.", "6f37996b-2ac7-44b0-8e68-6d28256631b4", False))
|
721 |
+
# print(x)
|
722 |
+
# print(code_executor.invoke("x=2*5\nprint(x)"))
|
723 |
|
724 |
+
# except Exception as e:
|
725 |
+
# print(str(e))
|
726 |
|
727 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
728 |
demo.launch(debug=True, share=False)
|