Commit ·
0907ef1
1
Parent(s): a437ec2
Add comprehensive logging to integration script
Browse files- Added logging to file and console with timestamps
- Added detailed logging for each question and answer
- Captured agent tool usage and steps in logs
- Added log display to UI mode
- Enhanced headless mode with log file reporting
- direct_integration.py +132 -19
direct_integration.py
CHANGED
|
@@ -4,13 +4,26 @@ Integration script that connects our DirectAgent to the app.py submission system
|
|
| 4 |
"""
|
| 5 |
import os
|
| 6 |
import json
|
|
|
|
| 7 |
import requests
|
| 8 |
import tempfile
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
import gradio as gr
|
| 11 |
from direct_agent_fixed import DirectAgent
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
| 16 |
|
|
@@ -77,21 +90,68 @@ def run_agent_on_questions(questions):
|
|
| 77 |
for i, question in enumerate(questions):
|
| 78 |
task_id = question["task_id"]
|
| 79 |
question_text = question["question"]
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
# Check if there's a file URL
|
| 83 |
file_context = None
|
| 84 |
if "file_url" in question and question["file_url"]:
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
| 86 |
if "error" not in file_info:
|
| 87 |
file_context = file_info
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
# Run the agent on the question
|
| 91 |
try:
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
|
|
|
| 95 |
answers.append({
|
| 96 |
"task_id": task_id,
|
| 97 |
"submitted_answer": answer
|
|
@@ -101,11 +161,12 @@ def run_agent_on_questions(questions):
|
|
| 101 |
if file_context and "file_path" in file_context:
|
| 102 |
try:
|
| 103 |
os.unlink(file_context["file_path"])
|
| 104 |
-
|
| 105 |
-
|
|
|
|
| 106 |
|
| 107 |
except Exception as e:
|
| 108 |
-
|
| 109 |
# Still add the error message as the answer
|
| 110 |
answers.append({
|
| 111 |
"task_id": task_id,
|
|
@@ -123,35 +184,56 @@ def submit_answers(answers):
|
|
| 123 |
"answers": answers
|
| 124 |
}
|
| 125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
response = requests.post(SUBMIT_URL, json=submission)
|
| 127 |
response.raise_for_status()
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
except Exception as e:
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
|
| 132 |
def run_full_evaluation():
|
| 133 |
"""Run the full evaluation process: fetch questions, run agent, submit answers."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
# 1. Fetch questions
|
| 135 |
-
|
| 136 |
questions = fetch_questions()
|
| 137 |
|
| 138 |
if isinstance(questions, dict) and "error" in questions:
|
|
|
|
| 139 |
return questions["error"]
|
| 140 |
|
| 141 |
-
|
| 142 |
|
| 143 |
# 2. Run agent on questions
|
| 144 |
-
|
| 145 |
answers = run_agent_on_questions(questions)
|
|
|
|
| 146 |
|
| 147 |
# 3. Submit answers
|
| 148 |
-
|
| 149 |
submission_response = submit_answers(answers)
|
| 150 |
|
| 151 |
if "error" in submission_response:
|
|
|
|
| 152 |
return submission_response["error"]
|
| 153 |
|
| 154 |
# 4. Return result
|
|
|
|
|
|
|
|
|
|
| 155 |
return submission_response
|
| 156 |
|
| 157 |
def create_interface():
|
|
@@ -169,26 +251,47 @@ def create_interface():
|
|
| 169 |
|
| 170 |
with gr.Row():
|
| 171 |
results = gr.JSON(label="Results")
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
def update_env_and_run(username, code_link):
|
| 174 |
global USERNAME, CODE_LINK
|
| 175 |
USERNAME = username
|
| 176 |
CODE_LINK = code_link
|
| 177 |
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
def run_evaluation():
|
| 181 |
result = run_full_evaluation()
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
run_button.click(
|
| 185 |
fn=update_env_and_run,
|
| 186 |
inputs=[username_input, code_link_input],
|
| 187 |
-
outputs=[status, results]
|
| 188 |
).then(
|
| 189 |
fn=run_evaluation,
|
| 190 |
inputs=None,
|
| 191 |
-
outputs=[status, results]
|
| 192 |
)
|
| 193 |
|
| 194 |
return interface
|
|
@@ -199,11 +302,21 @@ if __name__ == "__main__":
|
|
| 199 |
|
| 200 |
if len(sys.argv) > 1 and sys.argv[1] == "--headless":
|
| 201 |
# Run in headless mode (just run the evaluation)
|
| 202 |
-
|
| 203 |
result = run_full_evaluation()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
print("\nFinal result:")
|
| 205 |
print(json.dumps(result, indent=2))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
else:
|
| 207 |
# Run with the UI
|
|
|
|
| 208 |
interface = create_interface()
|
| 209 |
interface.launch(share=False)
|
|
|
|
| 4 |
"""
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
+
import logging
|
| 8 |
import requests
|
| 9 |
import tempfile
|
| 10 |
+
from datetime import datetime
|
| 11 |
from pathlib import Path
|
| 12 |
import gradio as gr
|
| 13 |
from direct_agent_fixed import DirectAgent
|
| 14 |
from dotenv import load_dotenv
|
| 15 |
|
| 16 |
+
# Set up logging
|
| 17 |
+
logging.basicConfig(
|
| 18 |
+
level=logging.INFO,
|
| 19 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 20 |
+
handlers=[
|
| 21 |
+
logging.StreamHandler(), # Log to console
|
| 22 |
+
logging.FileHandler(f"agent_run_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log") # Log to file
|
| 23 |
+
]
|
| 24 |
+
)
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
# Load environment variables
|
| 28 |
load_dotenv()
|
| 29 |
|
|
|
|
| 90 |
for i, question in enumerate(questions):
|
| 91 |
task_id = question["task_id"]
|
| 92 |
question_text = question["question"]
|
| 93 |
+
|
| 94 |
+
# Create a separator line for better logging visibility
|
| 95 |
+
separator = "=" * 80
|
| 96 |
+
logger.info(f"\n{separator}")
|
| 97 |
+
logger.info(f"QUESTION {i+1}/{len(questions)} (Task ID: {task_id})")
|
| 98 |
+
logger.info(separator)
|
| 99 |
+
|
| 100 |
+
# Log the full question text
|
| 101 |
+
logger.info(f"QUESTION TEXT:\n{question_text}")
|
| 102 |
+
logger.info(separator)
|
| 103 |
|
| 104 |
# Check if there's a file URL
|
| 105 |
file_context = None
|
| 106 |
if "file_url" in question and question["file_url"]:
|
| 107 |
+
file_url = question["file_url"]
|
| 108 |
+
logger.info(f"File attachment detected: {file_url}")
|
| 109 |
+
|
| 110 |
+
file_info = download_file(file_url, task_id)
|
| 111 |
if "error" not in file_info:
|
| 112 |
file_context = file_info
|
| 113 |
+
logger.info(f"Downloaded file: {file_info['file_name']} to {file_info['file_path']}")
|
| 114 |
+
else:
|
| 115 |
+
logger.error(f"Error downloading file: {file_info.get('error')}")
|
| 116 |
+
|
| 117 |
+
# Create a wrapper for the agent to capture logs
|
| 118 |
+
class LoggingAgent:
|
| 119 |
+
def __init__(self, agent):
|
| 120 |
+
self.agent = agent
|
| 121 |
+
|
| 122 |
+
def __call__(self, question, context=None):
|
| 123 |
+
# Create a custom handler to capture the agent's output
|
| 124 |
+
class AgentOutputHandler:
|
| 125 |
+
def write(self, message):
|
| 126 |
+
if message.strip(): # Only log non-empty lines
|
| 127 |
+
logger.debug(message.strip())
|
| 128 |
+
|
| 129 |
+
# Set up a custom handler to capture standard output
|
| 130 |
+
import sys
|
| 131 |
+
original_stdout = sys.stdout
|
| 132 |
+
sys.stdout = AgentOutputHandler()
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
# Call the actual agent
|
| 136 |
+
result = self.agent(question, context)
|
| 137 |
+
return result
|
| 138 |
+
finally:
|
| 139 |
+
# Restore standard output
|
| 140 |
+
sys.stdout = original_stdout
|
| 141 |
+
|
| 142 |
+
# Create the logging agent
|
| 143 |
+
logging_agent = LoggingAgent(agent)
|
| 144 |
|
| 145 |
# Run the agent on the question
|
| 146 |
try:
|
| 147 |
+
logger.info("Starting agent execution...")
|
| 148 |
+
answer = logging_agent(question_text, context=file_context)
|
| 149 |
+
|
| 150 |
+
# Log the answer
|
| 151 |
+
answer_preview = answer[:200] + "..." if len(answer) > 200 else answer
|
| 152 |
+
logger.info(f"{separator}\nANSWER:\n{answer_preview}\n{separator}")
|
| 153 |
|
| 154 |
+
# Store the answer
|
| 155 |
answers.append({
|
| 156 |
"task_id": task_id,
|
| 157 |
"submitted_answer": answer
|
|
|
|
| 161 |
if file_context and "file_path" in file_context:
|
| 162 |
try:
|
| 163 |
os.unlink(file_context["file_path"])
|
| 164 |
+
logger.debug(f"Deleted temporary file: {file_context['file_path']}")
|
| 165 |
+
except Exception as e:
|
| 166 |
+
logger.warning(f"Error deleting temporary file: {str(e)}")
|
| 167 |
|
| 168 |
except Exception as e:
|
| 169 |
+
logger.error(f"Error running agent on question {task_id}: {str(e)}")
|
| 170 |
# Still add the error message as the answer
|
| 171 |
answers.append({
|
| 172 |
"task_id": task_id,
|
|
|
|
| 184 |
"answers": answers
|
| 185 |
}
|
| 186 |
|
| 187 |
+
logger.info(f"Submitting answers for {len(answers)} questions...")
|
| 188 |
+
logger.info(f"Username: {USERNAME}")
|
| 189 |
+
logger.info(f"Code link: {CODE_LINK}")
|
| 190 |
+
|
| 191 |
response = requests.post(SUBMIT_URL, json=submission)
|
| 192 |
response.raise_for_status()
|
| 193 |
+
result = response.json()
|
| 194 |
+
|
| 195 |
+
logger.info(f"Submission successful!")
|
| 196 |
+
logger.info(f"Response: {json.dumps(result, indent=2)}")
|
| 197 |
+
|
| 198 |
+
return result
|
| 199 |
except Exception as e:
|
| 200 |
+
error_msg = f"Error submitting answers: {str(e)}"
|
| 201 |
+
logger.error(error_msg)
|
| 202 |
+
return {"error": error_msg}
|
| 203 |
|
| 204 |
def run_full_evaluation():
|
| 205 |
"""Run the full evaluation process: fetch questions, run agent, submit answers."""
|
| 206 |
+
logger.info("=" * 80)
|
| 207 |
+
logger.info("STARTING FULL EVALUATION")
|
| 208 |
+
logger.info("=" * 80)
|
| 209 |
+
|
| 210 |
# 1. Fetch questions
|
| 211 |
+
logger.info("Fetching questions from API...")
|
| 212 |
questions = fetch_questions()
|
| 213 |
|
| 214 |
if isinstance(questions, dict) and "error" in questions:
|
| 215 |
+
logger.error(f"Error fetching questions: {questions['error']}")
|
| 216 |
return questions["error"]
|
| 217 |
|
| 218 |
+
logger.info(f"Received {len(questions)} questions from API")
|
| 219 |
|
| 220 |
# 2. Run agent on questions
|
| 221 |
+
logger.info("\nRunning agent on all questions...")
|
| 222 |
answers = run_agent_on_questions(questions)
|
| 223 |
+
logger.info(f"Agent processing complete for all {len(answers)} questions")
|
| 224 |
|
| 225 |
# 3. Submit answers
|
| 226 |
+
logger.info("\nSubmitting answers to evaluation API...")
|
| 227 |
submission_response = submit_answers(answers)
|
| 228 |
|
| 229 |
if "error" in submission_response:
|
| 230 |
+
logger.error(f"Submission error: {submission_response['error']}")
|
| 231 |
return submission_response["error"]
|
| 232 |
|
| 233 |
# 4. Return result
|
| 234 |
+
logger.info("=" * 80)
|
| 235 |
+
logger.info("EVALUATION COMPLETE")
|
| 236 |
+
logger.info("=" * 80)
|
| 237 |
return submission_response
|
| 238 |
|
| 239 |
def create_interface():
|
|
|
|
| 251 |
|
| 252 |
with gr.Row():
|
| 253 |
results = gr.JSON(label="Results")
|
| 254 |
+
|
| 255 |
+
with gr.Row():
|
| 256 |
+
log_output = gr.Textbox(label="Log Output", lines=20)
|
| 257 |
|
| 258 |
def update_env_and_run(username, code_link):
|
| 259 |
global USERNAME, CODE_LINK
|
| 260 |
USERNAME = username
|
| 261 |
CODE_LINK = code_link
|
| 262 |
|
| 263 |
+
logger.info(f"Updated username to: {username}")
|
| 264 |
+
logger.info(f"Updated code link to: {code_link}")
|
| 265 |
+
|
| 266 |
+
return "Running evaluation...", None, "Starting evaluation... Check console for detailed logs."
|
| 267 |
|
| 268 |
def run_evaluation():
|
| 269 |
result = run_full_evaluation()
|
| 270 |
+
|
| 271 |
+
# Get the log file content for display
|
| 272 |
+
log_content = ""
|
| 273 |
+
try:
|
| 274 |
+
log_files = sorted([f for f in os.listdir('.') if f.startswith('agent_run_') and f.endswith('.log')])
|
| 275 |
+
if log_files:
|
| 276 |
+
with open(log_files[-1], 'r') as f:
|
| 277 |
+
log_content = f.read()
|
| 278 |
+
# Truncate if too long
|
| 279 |
+
if len(log_content) > 10000:
|
| 280 |
+
log_content = log_content[-10000:]
|
| 281 |
+
log_content = "... (log truncated) ...\n\n" + log_content
|
| 282 |
+
except Exception as e:
|
| 283 |
+
log_content = f"Error reading log file: {str(e)}"
|
| 284 |
+
|
| 285 |
+
return "Evaluation complete", result, log_content
|
| 286 |
|
| 287 |
run_button.click(
|
| 288 |
fn=update_env_and_run,
|
| 289 |
inputs=[username_input, code_link_input],
|
| 290 |
+
outputs=[status, results, log_output]
|
| 291 |
).then(
|
| 292 |
fn=run_evaluation,
|
| 293 |
inputs=None,
|
| 294 |
+
outputs=[status, results, log_output]
|
| 295 |
)
|
| 296 |
|
| 297 |
return interface
|
|
|
|
| 302 |
|
| 303 |
if len(sys.argv) > 1 and sys.argv[1] == "--headless":
|
| 304 |
# Run in headless mode (just run the evaluation)
|
| 305 |
+
logger.info("Running in headless mode")
|
| 306 |
result = run_full_evaluation()
|
| 307 |
+
logger.info("\nFinal result:")
|
| 308 |
+
logger.info(json.dumps(result, indent=2))
|
| 309 |
+
|
| 310 |
+
# Also print to console for convenience
|
| 311 |
print("\nFinal result:")
|
| 312 |
print(json.dumps(result, indent=2))
|
| 313 |
+
|
| 314 |
+
# Print log file location
|
| 315 |
+
log_files = sorted([f for f in os.listdir('.') if f.startswith('agent_run_') and f.endswith('.log')])
|
| 316 |
+
if log_files:
|
| 317 |
+
print(f"\nDetailed logs saved to: {log_files[-1]}")
|
| 318 |
else:
|
| 319 |
# Run with the UI
|
| 320 |
+
logger.info("Starting with UI mode")
|
| 321 |
interface = create_interface()
|
| 322 |
interface.launch(share=False)
|