zerocool commited on
Commit
b127970
·
verified ·
1 Parent(s): 0e57142

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -73
app.py CHANGED
@@ -1,11 +1,10 @@
1
- # app.py (on Hugging Face Spaces)
2
  import gradio as gr
3
  import httpx
4
  import asyncio
5
  import json
6
 
7
- # Replace with your Modal API endpoint URL
8
- MODAL_API_ENDPOINT = "https://blastingneurons--collective-hive-backend-orchestrate-hive-api.modal.run"
9
 
10
  # Helper function to format chat history for Gradio's 'messages' type
11
  def format_chat_history_for_gradio(log_entries: list[dict]) -> list[dict]:
@@ -16,85 +15,51 @@ def format_chat_history_for_gradio(log_entries: list[dict]) -> list[dict]:
16
  formatted_messages.append({"role": role, "content": content})
17
  return formatted_messages
18
 
19
- async def call_modal_backend(problem_input: str, complexity: int):
20
- full_chat_history = []
21
-
22
- current_status = "Connecting to Hive..."
23
- current_solution = ""
24
- current_confidence = ""
25
- current_minority_opinions = ""
26
-
27
  yield (
28
- current_status,
29
  format_chat_history_for_gradio([]),
30
- current_solution,
31
- current_confidence,
32
- current_minority_opinions
33
  )
34
 
35
  try:
36
- async with httpx.AsyncClient(timeout=600.0) as client:
37
- async with client.stream("POST", MODAL_API_ENDPOINT, json={"problem": problem_input, "complexity": complexity}) as response:
38
- response.raise_for_status()
39
-
40
- buffer = ""
41
- async for chunk in response.aiter_bytes():
42
- buffer += chunk.decode('utf-8')
43
- while "\n" in buffer:
44
- line, buffer = buffer.split("\n", 1)
45
- if not line.strip(): continue
46
- try:
47
- data = json.loads(line)
48
- event_type = data.get("event")
49
-
50
- if event_type == "status_update":
51
- current_status = data["data"]
52
- elif event_type == "chat_update":
53
- full_chat_history.append(data["data"])
54
- current_status = "In Progress..."
55
- elif event_type == "final_solution":
56
- current_status = "Solution Complete!"
57
- current_solution = data["solution"]
58
- current_confidence = data["confidence"]
59
- current_minority_opinions = data["minority_opinions"]
60
- yield (
61
- current_status,
62
- format_chat_history_for_gradio(full_chat_history + [{"role": "System", "content": "Final solution synthesized."}]),
63
- current_solution,
64
- current_confidence,
65
- current_minority_opinions
66
- )
67
- return
68
-
69
- yield (
70
- current_status,
71
- format_chat_history_for_gradio(full_chat_history),
72
- current_solution,
73
- current_confidence,
74
- current_minority_opinions
75
- )
76
-
77
- except json.JSONDecodeError as e:
78
- print(f"JSON Decode Error: {e} in line: {line}")
79
- current_status = f"Error decoding: {e}"
80
- yield (current_status, format_chat_history_for_gradio(full_chat_history), current_solution, current_confidence, current_minority_opinions)
81
- except Exception as e:
82
- print(f"Error processing event: {e}, Data: {data}")
83
- current_status = f"An internal error occurred: {e}"
84
- yield (current_status, format_chat_history_for_gradio(full_chat_history), current_solution, current_confidence, current_minority_opinions)
85
- return
86
 
87
  except httpx.HTTPStatusError as e:
88
- current_status = f"HTTP Error from Modal backend: {e.response.status_code}"
89
- print(current_status)
 
90
  except httpx.RequestError as e:
91
- current_status = f"Request Error: Could not connect to Modal backend: {e}"
92
- print(current_status)
 
93
  except Exception as e:
94
- current_status = f"An unexpected error occurred during API call: {e}"
95
- print(current_status)
 
96
 
97
- yield (current_status, format_chat_history_for_gradio(full_chat_history), current_solution, current_confidence, current_minority_opinions)
 
98
 
99
 
100
  with gr.Blocks() as demo:
@@ -124,7 +89,7 @@ with gr.Blocks() as demo:
124
  minority_output = gr.Textbox(label="Minority Opinions", lines=3, interactive=False)
125
 
126
  initiate_btn.click(
127
- call_modal_backend,
128
  inputs=[problem_input, complexity_slider],
129
  outputs=[
130
  status_output,
 
 
1
  import gradio as gr
2
  import httpx
3
  import asyncio
4
  import json
5
 
6
+ # Replace with your NEW Modal API endpoint URL (for the non-streaming backend)
7
+ MODAL_API_ENDPOINT = "https://blastingneurons--collective-hive-backend-sync-orchestrat-ee7dd9.modal.run"
8
 
9
  # Helper function to format chat history for Gradio's 'messages' type
10
  def format_chat_history_for_gradio(log_entries: list[dict]) -> list[dict]:
 
15
  formatted_messages.append({"role": role, "content": content})
16
  return formatted_messages
17
 
18
+ async def call_modal_backend_sync(problem_input: str, complexity: int):
19
+ # Initial yield to clear previous state and show connecting message
 
 
 
 
 
 
20
  yield (
21
+ "Connecting to Hive...",
22
  format_chat_history_for_gradio([]),
23
+ "", "", ""
 
 
24
  )
25
 
26
  try:
27
+ async with httpx.AsyncClient(timeout=600.0) as client: # Longer timeout for the full process
28
+ response = await client.post(MODAL_API_ENDPOINT, json={"problem": problem_input, "complexity": complexity})
29
+ response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
30
+
31
+ response_data = response.json() # Parse the full JSON response
32
+
33
+ final_status = response_data.get("status", "Unknown Status")
34
+ final_chat_history = response_data.get("chat_history", [])
35
+ final_solution = response_data.get("solution", "No solution provided.")
36
+ final_confidence = response_data.get("confidence", "0.0%")
37
+ final_minority_opinions = response_data.get("minority_opinions", "None")
38
+
39
+ yield (
40
+ final_status,
41
+ format_chat_history_for_gradio(final_chat_history),
42
+ final_solution,
43
+ final_confidence,
44
+ final_minority_opinions
45
+ )
46
+ return # Done processing
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  except httpx.HTTPStatusError as e:
49
+ error_message = f"HTTP Error from Modal backend: {e.response.status_code} - {e.response.text}"
50
+ print(error_message)
51
+ yield (error_message, format_chat_history_for_gradio([]), "", "", "")
52
  except httpx.RequestError as e:
53
+ error_message = f"Request Error: Could not connect to Modal backend: {e}"
54
+ print(error_message)
55
+ yield (error_message, format_chat_history_for_gradio([]), "", "", "")
56
  except Exception as e:
57
+ error_message = f"An unexpected error occurred during API call: {e}"
58
+ print(error_message)
59
+ yield (error_message, format_chat_history_for_gradio([]), "", "", "")
60
 
61
+ # Fallback yield in case of unexpected termination before return
62
+ yield ("An unexpected error occurred and processing stopped.", format_chat_history_for_gradio([]), "", "", "")
63
 
64
 
65
  with gr.Blocks() as demo:
 
89
  minority_output = gr.Textbox(label="Minority Opinions", lines=3, interactive=False)
90
 
91
  initiate_btn.click(
92
+ call_modal_backend_sync, # Changed function name
93
  inputs=[problem_input, complexity_slider],
94
  outputs=[
95
  status_output,