abanm commited on
Commit
199c60b
·
verified ·
1 Parent(s): ae39a63

Update api_helper.py

Browse files
Files changed (1) hide show
  1. 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} # Ensure the key matches API's expected input
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
- # Stream and aggregate the response
30
  bot_response = ""
31
- for chunk in response.iter_lines():
32
- if chunk: # Ensure the chunk is not empty
33
  try:
34
- data = json.loads(chunk.decode("utf-8"))
35
- bot_response += data.get("response", "")
 
 
36
  except json.JSONDecodeError:
37
  bot_response += "\nError decoding response chunk."
38
- return bot_response.strip() if bot_response else "Error: Empty response from API."
 
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: