Sgridda commited on
Commit
b2dcace
·
1 Parent(s): be491ce

Improve error handling and response parsing for HF API

Browse files
Files changed (1) hide show
  1. main.py +28 -14
main.py CHANGED
@@ -86,20 +86,34 @@ Feedback: This code could be improved by"""
86
  }
87
  }
88
 
89
- response = requests.post(
90
- f"https://api-inference.huggingface.co/models/{HF_MODEL_NAME}",
91
- headers=headers,
92
- json=payload
93
- )
94
-
95
- if response.status_code != 200:
96
- raise RuntimeError(f"Hugging Face API error: {response.status_code} {response.text}")
97
-
98
- response_data = response.json()
99
- if isinstance(response_data, list) and len(response_data) > 0:
100
- response_text = response_data[0].get("generated_text", "").strip()
101
- else:
102
- response_text = "Unable to generate a meaningful review."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
  # Clean up the response
105
  response_text = response_text.strip()
 
86
  }
87
  }
88
 
89
+ try:
90
+ response = requests.post(
91
+ f"https://api-inference.huggingface.co/models/{HF_MODEL_NAME}",
92
+ headers=headers,
93
+ json=payload,
94
+ timeout=30
95
+ )
96
+
97
+ if response.status_code != 200:
98
+ print(f"HF API Error: {response.status_code} - {response.text}")
99
+ return "Consider adding proper documentation and error handling."
100
+
101
+ response_data = response.json()
102
+ print(f"HF API Response: {response_data}")
103
+
104
+ if isinstance(response_data, list) and len(response_data) > 0:
105
+ generated_text = response_data[0].get("generated_text", "")
106
+ # Extract only the new generated part (after our prompt)
107
+ if generated_text.startswith(prompt):
108
+ response_text = generated_text[len(prompt):].strip()
109
+ else:
110
+ response_text = generated_text.strip()
111
+ else:
112
+ response_text = "Unable to generate a meaningful review."
113
+
114
+ except Exception as e:
115
+ print(f"HF API Exception: {e}")
116
+ return "Consider adding proper documentation and error handling."
117
 
118
  # Clean up the response
119
  response_text = response_text.strip()