abanm commited on
Commit
95fdee2
·
verified ·
1 Parent(s): 2d4e21d

Update api_helper.py

Browse files
Files changed (1) hide show
  1. 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: 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
  try:
23
- response = requests.post(SPACE_URL, json=payload, headers=headers)
 
24
  response.raise_for_status()
25
- result = response.json()
26
- return result.get("output", "Error: No response from API.")
 
 
 
 
 
 
 
 
 
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)}"