Update api_helper.py
Browse files- api_helper.py +16 -5
api_helper.py
CHANGED
|
@@ -6,23 +6,34 @@ API_KEY = "s3cr3t_k3y" # Replace with your actual API key
|
|
| 6 |
|
| 7 |
def call_api(message):
|
| 8 |
"""
|
| 9 |
-
Calls the backend API with the user's input.
|
| 10 |
|
| 11 |
Args:
|
| 12 |
message (str): User's message.
|
| 13 |
|
| 14 |
Returns:
|
| 15 |
-
str:
|
| 16 |
"""
|
| 17 |
headers = {
|
| 18 |
"Authorization": f"Bearer {API_KEY}",
|
| 19 |
"Content-Type": "application/json",
|
| 20 |
}
|
| 21 |
payload = {"input": message}
|
|
|
|
| 22 |
try:
|
| 23 |
-
|
|
|
|
| 24 |
response.raise_for_status()
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
except requests.exceptions.RequestException as e:
|
| 28 |
return f"Error: {str(e)}"
|
|
|
|
| 6 |
|
| 7 |
def call_api(message):
|
| 8 |
"""
|
| 9 |
+
Calls the backend API with the user's input using streaming.
|
| 10 |
|
| 11 |
Args:
|
| 12 |
message (str): User's message.
|
| 13 |
|
| 14 |
Returns:
|
| 15 |
+
str: Streamed response from the backend API or an error message.
|
| 16 |
"""
|
| 17 |
headers = {
|
| 18 |
"Authorization": f"Bearer {API_KEY}",
|
| 19 |
"Content-Type": "application/json",
|
| 20 |
}
|
| 21 |
payload = {"input": message}
|
| 22 |
+
|
| 23 |
try:
|
| 24 |
+
# Send request with streaming enabled
|
| 25 |
+
response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True)
|
| 26 |
response.raise_for_status()
|
| 27 |
+
|
| 28 |
+
# Stream and aggregate the response
|
| 29 |
+
bot_response = ""
|
| 30 |
+
for chunk in response.iter_lines():
|
| 31 |
+
if chunk: # Ensure the chunk is not empty
|
| 32 |
+
try:
|
| 33 |
+
data = json.loads(chunk.decode("utf-8"))
|
| 34 |
+
bot_response += data.get("response", "")
|
| 35 |
+
except json.JSONDecodeError:
|
| 36 |
+
bot_response += "\nError decoding response chunk."
|
| 37 |
+
return bot_response
|
| 38 |
except requests.exceptions.RequestException as e:
|
| 39 |
return f"Error: {str(e)}"
|