helene-rousset commited on
Commit
3c1a783
·
verified ·
1 Parent(s): 0470bd6

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +61 -16
agent.py CHANGED
@@ -11,6 +11,8 @@ import json
11
  import io
12
  import contextlib
13
  import os
 
 
14
 
15
  OPENAI = os.getenv("OPENAI")
16
 
@@ -74,32 +76,75 @@ If the question specifies a format, please return it in the specified format. Do
74
  state['messages'] = state['messages'] + [llm.invoke([sys_msg])]
75
  return state
76
 
77
-
78
  def python_interpreter(state: AgentState):
 
 
79
  question_id = state['task_id']
80
  url = f"https://agents-course-unit4-scoring.hf.space/files/{question_id}"
81
-
82
- # Step 1: Fetch Python code as bytes and decode
83
  response = requests.get(url)
84
  python_code = response.content.decode("utf-8")
85
- # print(python_code)
86
-
87
- # Step 2: Capture stdout
88
- stdout = io.StringIO()
89
- with contextlib.redirect_stdout(stdout):
90
- try:
91
- exec(python_code) # Use empty dict for isolated global context
92
- except Exception as e:
93
- output = f"Error during execution: {e}"
 
 
 
 
 
 
 
 
 
94
  else:
95
- output = stdout.getvalue().strip()
96
- print("Code output : ", output)
97
- # Step 3: Save output as message
 
 
 
 
98
  state['messages'] = state['messages'] + [
99
- AIMessage(content=f"The output of the python code is : {output}")
100
  ]
 
101
  return state
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  def image_interpreter(state: AgentState):
104
  print("image interpreter")
105
  """Answers a question about an image. Provide raw image bytes and a question."""
 
11
  import io
12
  import contextlib
13
  import os
14
+ import subprocess
15
+ import tempfile
16
 
17
  OPENAI = os.getenv("OPENAI")
18
 
 
76
  state['messages'] = state['messages'] + [llm.invoke([sys_msg])]
77
  return state
78
 
79
+
80
  def python_interpreter(state: AgentState):
81
+ print("python interpreter")
82
+
83
  question_id = state['task_id']
84
  url = f"https://agents-course-unit4-scoring.hf.space/files/{question_id}"
85
+
86
+ # Step 1: Download the code
87
  response = requests.get(url)
88
  python_code = response.content.decode("utf-8")
89
+
90
+ print("Running user code with subprocess...")
91
+
92
+ # Step 2: Write code to temp file
93
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as tmp_file:
94
+ tmp_file.write(python_code)
95
+ tmp_file_path = tmp_file.name
96
+
97
+ try:
98
+ # Step 3: Run using subprocess (set timeout if needed)
99
+ result = subprocess.run(
100
+ ["python3", tmp_file_path],
101
+ capture_output=True,
102
+ text=True,
103
+ timeout=30 # seconds
104
+ )
105
+ if result.returncode != 0:
106
+ output = f"⚠️ Error:\n{result.stderr.strip()}"
107
  else:
108
+ output = result.stdout.strip() or "Code ran but produced no output."
109
+ except subprocess.TimeoutExpired:
110
+ output = "Execution timed out."
111
+ except Exception as e:
112
+ output = f"Unexpected error: {e}"
113
+
114
+ # Step 4: Update agent state
115
  state['messages'] = state['messages'] + [
116
+ AIMessage(content=f"The output of the Python code is:\n```\n{output}\n```")
117
  ]
118
+
119
  return state
120
 
121
+
122
+
123
+ # def python_interpreter(state: AgentState):
124
+ # question_id = state['task_id']
125
+ # url = f"https://agents-course-unit4-scoring.hf.space/files/{question_id}"
126
+
127
+ # # Step 1: Fetch Python code as bytes and decode
128
+ # response = requests.get(url)
129
+ # python_code = response.content.decode("utf-8")
130
+ # # print(python_code)
131
+
132
+ # # Step 2: Capture stdout
133
+ # stdout = io.StringIO()
134
+ # with contextlib.redirect_stdout(stdout):
135
+ # try:
136
+ # exec(python_code) # Use empty dict for isolated global context
137
+ # except Exception as e:
138
+ # output = f"Error during execution: {e}"
139
+ # else:
140
+ # output = stdout.getvalue().strip()
141
+ # print("Code output : ", output)
142
+ # # Step 3: Save output as message
143
+ # state['messages'] = state['messages'] + [
144
+ # AIMessage(content=f"The output of the python code is : {output}")
145
+ # ]
146
+ # return state
147
+
148
  def image_interpreter(state: AgentState):
149
  print("image interpreter")
150
  """Answers a question about an image. Provide raw image bytes and a question."""