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)}"