Update api_helper.py
Browse files- api_helper.py +10 -7
api_helper.py
CHANGED
|
@@ -19,23 +19,26 @@ def call_api(message):
|
|
| 19 |
"Authorization": f"Bearer {API_KEY}",
|
| 20 |
"Content-Type": "application/json",
|
| 21 |
}
|
| 22 |
-
payload = {"prompt": message} #
|
| 23 |
|
| 24 |
try:
|
| 25 |
# Send request with streaming enabled
|
| 26 |
response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True)
|
| 27 |
response.raise_for_status()
|
| 28 |
|
| 29 |
-
#
|
| 30 |
bot_response = ""
|
| 31 |
-
for chunk in response.iter_lines():
|
| 32 |
-
if chunk: # Ensure the chunk is not empty
|
| 33 |
try:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
except json.JSONDecodeError:
|
| 37 |
bot_response += "\nError decoding response chunk."
|
| 38 |
-
|
|
|
|
| 39 |
except requests.exceptions.Timeout:
|
| 40 |
return "Error: The API call timed out."
|
| 41 |
except requests.exceptions.RequestException as e:
|
|
|
|
| 19 |
"Authorization": f"Bearer {API_KEY}",
|
| 20 |
"Content-Type": "application/json",
|
| 21 |
}
|
| 22 |
+
payload = {"prompt": message} # Match the API's expected input key
|
| 23 |
|
| 24 |
try:
|
| 25 |
# Send request with streaming enabled
|
| 26 |
response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True)
|
| 27 |
response.raise_for_status()
|
| 28 |
|
| 29 |
+
# Aggregate streamed response
|
| 30 |
bot_response = ""
|
| 31 |
+
for chunk in response.iter_lines(decode_unicode=True):
|
| 32 |
+
if chunk.strip(): # Ensure the chunk is not empty
|
| 33 |
try:
|
| 34 |
+
# Parse JSON chunk
|
| 35 |
+
data = json.loads(chunk)
|
| 36 |
+
if "response" in data:
|
| 37 |
+
bot_response += data["response"]
|
| 38 |
except json.JSONDecodeError:
|
| 39 |
bot_response += "\nError decoding response chunk."
|
| 40 |
+
|
| 41 |
+
return bot_response.strip() if bot_response else "Error: No response from API."
|
| 42 |
except requests.exceptions.Timeout:
|
| 43 |
return "Error: The API call timed out."
|
| 44 |
except requests.exceptions.RequestException as e:
|