porla commited on
Commit
fde6ed4
·
1 Parent(s): 7c1ec21

Add functionality to load and execute Python files; refactor test script for output capture

Browse files
Files changed (3) hide show
  1. src/agent.py +2 -2
  2. src/tools.py +38 -5
  3. test.py +24 -3
src/agent.py CHANGED
@@ -105,8 +105,8 @@ if __name__ == "__main__":
105
  #question = """Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\""""
106
  # question = """Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order."""
107
  # question = """The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places."""
108
- question = """What country had the least number of athletes at the 1928 Summer Olympics? If there's a tie for a number of athletes, return the first in alphabetical order. Give the IOC country code as your answer."""
109
- task_id = "7bd855d8-463d-4ed5-93ca-5fe35145f733"
110
  system_prompt = SystemMessage(content=get_prompt())
111
  messages = react_graph.invoke({
112
  "messages": [
 
105
  #question = """Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\""""
106
  # question = """Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order."""
107
  # question = """The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places."""
108
+ question = """What is the final numeric output from the attached Python code?"""
109
+ task_id = "f918266a-b3e0-4914-865d-4faa564f1aef"
110
  system_prompt = SystemMessage(content=get_prompt())
111
  messages = react_graph.invoke({
112
  "messages": [
src/tools.py CHANGED
@@ -1,3 +1,9 @@
 
 
 
 
 
 
1
  from langchain_community.tools import WikipediaQueryRun
2
  from langchain_community.utilities import WikipediaAPIWrapper
3
  from langchain_community.tools import DuckDuckGoSearchRun
@@ -15,11 +21,8 @@ from youtube_transcript_api import YouTubeTranscriptApi
15
 
16
  from pandasai.llm.openai import OpenAI
17
  from llama_index.readers.pandas_ai import PandasAIReader
 
18
 
19
- import os
20
- import re
21
- import whisper
22
- import pandas as pd
23
 
24
  from .state import State
25
 
@@ -139,7 +142,36 @@ def route_question(state: State) -> str:
139
  return "question_reversed"
140
  else:
141
  return "question_not_reversed"
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  def get_avaiable_tools():
145
  """Returns a list of available tools."""
@@ -152,5 +184,6 @@ def get_avaiable_tools():
152
  web_search_tool,
153
  get_youtube_transcript,
154
  transcript_mp3_audio,
155
- load_and_analyze_excel_file
 
156
  ]
 
1
+ import os
2
+ import re
3
+ import whisper
4
+ import io
5
+
6
+ import pandas as pd
7
  from langchain_community.tools import WikipediaQueryRun
8
  from langchain_community.utilities import WikipediaAPIWrapper
9
  from langchain_community.tools import DuckDuckGoSearchRun
 
21
 
22
  from pandasai.llm.openai import OpenAI
23
  from llama_index.readers.pandas_ai import PandasAIReader
24
+ from contextlib import redirect_stdout, redirect_stderr
25
 
 
 
 
 
26
 
27
  from .state import State
28
 
 
142
  return "question_reversed"
143
  else:
144
  return "question_not_reversed"
145
+
146
+ @tool
147
+ def load_and_execute_python_file(task_id: str) -> str:
148
+ """
149
+ Reads a Python file, executes it, and prints the result.
150
+ """
151
+ file_path = f"{task_id}.py" # Assuming the file is named with the task_id
152
+ file_path = os.path.join('results', file_path)
153
+ try:
154
+ with open(file_path, 'r', encoding='utf-8') as f:
155
+ python_code = f.read()
156
+ except FileNotFoundError:
157
+ return f"Errore: file '{file_path}' non trovato."
158
 
159
+ stdout_buffer = io.StringIO()
160
+ stderr_buffer = io.StringIO()
161
+
162
+ # Redirige stdout e stderr per catturare tutto l'output
163
+ with redirect_stdout(stdout_buffer), redirect_stderr(stderr_buffer):
164
+ try:
165
+ exec(python_code, {"__name__": "__main__"})
166
+ except Exception as e:
167
+ # Qualsiasi eccezione viene catturata e mostrata nel buffer stderr
168
+ print(f"Errore durante l'esecuzione: {e}", file=stderr_buffer)
169
+
170
+ # Combina stdout e stderr
171
+ output = stdout_buffer.getvalue()
172
+ errors = stderr_buffer.getvalue()
173
+ return output + errors
174
+
175
 
176
  def get_avaiable_tools():
177
  """Returns a list of available tools."""
 
184
  web_search_tool,
185
  get_youtube_transcript,
186
  transcript_mp3_audio,
187
+ load_and_analyze_excel_file,
188
+ load_and_execute_python_file
189
  ]
test.py CHANGED
@@ -1,7 +1,28 @@
1
  from youtube_transcript_api import YouTubeTranscriptApi
2
  import pandas as pd
 
 
 
 
3
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  # def get_youtube_transcript(video_url: str) -> list:
6
  # """Fetches the transcript of a YouTube video."""
7
  # ytt_api = YouTubeTranscriptApi()
@@ -13,6 +34,6 @@ import pandas as pd
13
  # print(transcript)
14
 
15
  # Leggi un file xlsx con pandas
16
- file_path = 'results/7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx'
17
- df = pd.read_excel(file_path)
18
- print(df)
 
1
  from youtube_transcript_api import YouTubeTranscriptApi
2
  import pandas as pd
3
+ from langchain_experimental.utilities import PythonREPL
4
+ from langchain_core.tools import Tool
5
+ from contextlib import redirect_stdout
6
+ import io
7
 
8
 
9
+ python_repl = PythonREPL()
10
+ def read_python_file(file_path: str) -> str:
11
+ """Reads a Python file and returns its code as a string."""
12
+ with open(file_path, 'r', encoding='utf-8') as f:
13
+ return f.read()
14
+ python_str = read_python_file('results/f918266a-b3e0-4914-865d-4faa564f1aef.py')
15
+ # Prepara un buffer per catturare stdout
16
+ f = io.StringIO()
17
+ with redirect_stdout(f):
18
+ # Esegui il codice come se fosse in un file .py
19
+ exec(python_str, {"__name__": "__main__"})
20
+
21
+ # Ottieni tutto ciò che è stato stampato
22
+ output = f.getvalue()
23
+ print("=== OUTPUT ===")
24
+ print(output)
25
+
26
  # def get_youtube_transcript(video_url: str) -> list:
27
  # """Fetches the transcript of a YouTube video."""
28
  # ytt_api = YouTubeTranscriptApi()
 
34
  # print(transcript)
35
 
36
  # Leggi un file xlsx con pandas
37
+ # file_path = 'results/7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx'
38
+ # df = pd.read_excel(file_path)
39
+ # print(df)