File size: 7,511 Bytes
c9803a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
// Apex Class: ProxyLiteService.cls
public class ProxyLiteService {

    @AuraEnabled(cacheable=false) 
    public static String runProxyLiteTask(String userTask, String targetUrl) {
        // Updated endpoint to use port 7860 based on the user's configuration
        String hugginFaceEndpoint = 'https://ttomy-proxy-lite-demo-v2.hf.space/run_proxy_task';
        
        HttpRequest request = new HttpRequest();
        request.setEndpoint(hugginFaceEndpoint);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');
        
        // Set the timeout for the HTTP callout (max 120 seconds)
        request.setTimeout(120000);
        
        // Create request body with both task and URL
        Map<String, String> requestBodyMap = new Map<String, String>();
        requestBodyMap.put('task', userTask);
        requestBodyMap.put('url', targetUrl);
        
        String jsonBody = JSON.serialize(requestBodyMap);
        request.setBody(jsonBody);

        Http http = new Http();
        HTTPResponse response = null;

        try {
            response = http.send(request);

            if (response.getStatusCode() == 200) {
                // Parse the response to handle the new structured format
                Map<String, Object> responseMap = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                
                // Check if the response has the expected structure
                if (responseMap.containsKey('status')) {
                    String status = (String) responseMap.get('status');
                    
                    if (status == 'success') {
                        // Return the entire structured response for processing in LWC
                        return JSON.serialize(responseMap);
                    } else {
                        // Handle error response from the API
                        String errorMessage = (String) responseMap.get('message');
                        String errorType = (String) responseMap.get('error_type');
                        
                        // Create structured error response
                        Map<String, Object> errorResponse = new Map<String, Object>();
                        errorResponse.put('status', 'error');
                        errorResponse.put('message', errorMessage);
                        errorResponse.put('error_type', errorType);
                        errorResponse.put('data', responseMap.get('data'));
                        
                        return JSON.serialize(errorResponse);
                    }
                } else {
                    // Legacy response format - try to extract 'output' field
                    String output = (String) responseMap.get('output');
                    if (output != null) {
                        // Wrap legacy response in new format
                        Map<String, Object> legacyResponse = new Map<String, Object>();
                        legacyResponse.put('status', 'success');
                        legacyResponse.put('task_result', output);
                        return JSON.serialize(legacyResponse);
                    } else {
                        throw new AuraHandledException('Unexpected response format from Proxy Lite API');
                    }
                }
            } else {
                // Handle HTTP error responses
                System.debug('HTTP Callout Error: ' + response.getStatusCode() + ' - ' + response.getStatus());
                System.debug('Response Body: ' + response.getBody());
                
                // Try to parse error response
                try {
                    Map<String, Object> errorResponse = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                    if (errorResponse.containsKey('message')) {
                        return JSON.serialize(errorResponse);
                    }
                } catch (Exception parseError) {
                    // If parsing fails, create a structured error response
                    Map<String, Object> errorResponse = new Map<String, Object>();
                    errorResponse.put('status', 'error');
                    errorResponse.put('message', 'HTTP Error: ' + response.getStatusCode() + ' ' + response.getStatus());
                    errorResponse.put('error_type', 'http_error');
                    
                    Map<String, Object> errorData = new Map<String, Object>();
                    errorData.put('status_code', response.getStatusCode());
                    errorData.put('response_body', response.getBody());
                    errorData.put('suggested_action', 'Check the Proxy Lite service status and try again');
                    
                    errorResponse.put('data', errorData);
                    return JSON.serialize(errorResponse);
                }
                
                throw new AuraHandledException('Error calling Proxy Lite API: ' + response.getStatusCode() + ' ' + response.getStatus());
            }
        } catch (System.CalloutException e) {
            System.debug('Callout Exception: ' + e.getMessage());
            
            // Create structured error response for callout exceptions
            Map<String, Object> errorResponse = new Map<String, Object>();
            errorResponse.put('status', 'error');
            errorResponse.put('error_type', 'callout_exception');
            
            Map<String, Object> errorData = new Map<String, Object>();
            errorData.put('exception_message', e.getMessage());
            
            // Provide specific error messages for different types of callout exceptions
            if (e.getMessage().contains('Read timed out')) {
                errorResponse.put('message', 'Request timed out. The automation task took too long to complete.');
                errorData.put('suggested_action', 'Try simplifying the task or check the Proxy Lite service performance');
            } else if (e.getMessage().contains('Connection refused')) {
                errorResponse.put('message', 'Unable to connect to the Proxy Lite service');
                errorData.put('suggested_action', 'Check if the Proxy Lite service is running and accessible');
            } else {
                errorResponse.put('message', 'Network or API connection error: ' + e.getMessage());
                errorData.put('suggested_action', 'Check your network connection and try again');
            }
            
            errorResponse.put('data', errorData);
            return JSON.serialize(errorResponse);
            
        } catch (Exception e) {
            System.debug('General Exception: ' + e.getMessage());
            
            // Create structured error response for general exceptions
            Map<String, Object> errorResponse = new Map<String, Object>();
            errorResponse.put('status', 'error');
            errorResponse.put('message', 'An unexpected error occurred: ' + e.getMessage());
            errorResponse.put('error_type', 'general_exception');
            
            Map<String, Object> errorData = new Map<String, Object>();
            errorData.put('exception_message', e.getMessage());
            errorData.put('suggested_action', 'Please try again or contact system administrator');
            
            errorResponse.put('data', errorData);
            return JSON.serialize(errorResponse);
        }
    }
}