File size: 3,891 Bytes
c288490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/env python3
"""
Test script to run the agent on a single question.
"""
import os
import json
import requests
import tempfile
from pathlib import Path
import argparse
from direct_agent_fixed import DirectAgent
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

def download_file(url):
    """Download a file from a URL and save it to a temporary location."""
    try:
        response = requests.get(url)
        response.raise_for_status()
        
        # Create a temporary file with the right extension
        file_extension = Path(url).suffix.lower()
        
        # If no extension or weird extension, try to guess from content-type
        if not file_extension:
            content_type = response.headers.get('content-type', '')
            if 'excel' in content_type or 'spreadsheet' in content_type:
                file_extension = '.xlsx'
            elif 'csv' in content_type:
                file_extension = '.csv'
        
        # Create temporary file with correct extension
        with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:
            temp_file.write(response.content)
            temp_file_path = temp_file.name
        
        # Get the original filename from the URL
        filename = Path(url).name
        
        print(f"Downloaded file: {filename}")
        print(f"Saved to: {temp_file_path}")
        
        return {
            "file_path": temp_file_path,
            "file_name": filename
        }
    
    except Exception as e:
        print(f"Error downloading file: {str(e)}")
        return None

def test_question_with_file(question, file_url=None):
    """Test a question with an optional file attachment."""
    # Initialize agent
    agent = DirectAgent()
    
    # Download file if URL provided
    file_context = None
    if file_url:
        file_context = download_file(file_url)
    
    # Run the agent on the question
    print(f"\nQuestion: {question}")
    print("\nRunning agent...\n")
    
    answer = agent(question, context=file_context)
    
    print("\n" + "=" * 50)
    print("ANSWER:")
    print(answer)
    print("=" * 50)
    
    # Clean up temporary file
    if file_context and "file_path" in file_context:
        try:
            os.unlink(file_context["file_path"])
            print(f"Deleted temporary file: {file_context['file_path']}")
        except Exception as e:
            print(f"Error deleting temporary file: {str(e)}")
    
    return answer

def get_sample_questions():
    """Return a list of sample questions for testing."""
    return [
        {
            "id": 1,
            "question": "What is the capital of France?",
            "file_url": None
        },
        {
            "id": 2,
            "question": "What is 25 * 4 + 10?",
            "file_url": None
        },
        {
            "id": 3,
            "question": "What is the largest mammal on Earth?",
            "file_url": None
        }
    ]

def main():
    parser = argparse.ArgumentParser(description="Test the agent on a single question")
    parser.add_argument("--question", "-q", type=str, help="The question to test")
    parser.add_argument("--file", "-f", type=str, help="URL to a file attachment (optional)")
    parser.add_argument("--sample", "-s", type=int, help="Use a sample question (1, 2, or 3)")
    
    args = parser.parse_args()
    
    if args.sample:
        samples = get_sample_questions()
        if 1 <= args.sample <= len(samples):
            sample = samples[args.sample - 1]
            test_question_with_file(sample["question"], sample["file_url"])
        else:
            print(f"Sample number must be between 1 and {len(samples)}")
    elif args.question:
        test_question_with_file(args.question, args.file)
    else:
        parser.print_help()

if __name__ == "__main__":
    main()