File size: 1,553 Bytes
98dab2a 298c165 ca1674f 298c165 95fdee2 298c165 95fdee2 298c165 199c60b 95fdee2 298c165 95fdee2 298c165 95fdee2 199c60b 95fdee2 199c60b 95fdee2 199c60b 95fdee2 f9e855f 69c7d43 298c165 f9e855f |
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 |
import requests
import json
# Constants
SPACE_URL = "https://abanm-dubs.hf.space/api/generate"
API_KEY = "s3cr3t_k3y" # Replace with your actual API key
def call_api(message):
"""
Calls the backend API with the user's input using streaming.
Args:
message (str): User's message.
Returns:
str: Streamed response from the backend API or an error message.
"""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json",
}
payload = {"prompt": message} # Match the API's expected input key
try:
# Send request with streaming enabled
response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True)
response.raise_for_status()
# Aggregate streamed response
bot_response = ""
for chunk in response.iter_lines(decode_unicode=True):
if chunk.strip(): # Ensure the chunk is not empty
try:
# Parse JSON chunk
data = json.loads(chunk)
if "response" in data:
bot_response += data["response"]
except json.JSONDecodeError:
bot_response += "\nError decoding response chunk."
return bot_response.strip() if bot_response else "Error: No response from API."
except requests.exceptions.Timeout:
return "Error: The API call timed out."
except requests.exceptions.RequestException as e:
return f"Error: {str(e)}" |