Spaces:
Sleeping
Sleeping
Mahdiyar
commited on
Commit
Β·
c47b1e1
1
Parent(s):
5e3d8c8
Improvement
Browse files- app.py +59 -49
- matching_agent.py +2 -1
app.py
CHANGED
|
@@ -5,6 +5,7 @@ import logging
|
|
| 5 |
import sys
|
| 6 |
import os
|
| 7 |
import io
|
|
|
|
| 8 |
|
| 9 |
# Change from absolute imports to relative imports
|
| 10 |
from database import initialize_database, add_participant, get_participants_dataframe
|
|
@@ -50,8 +51,16 @@ initialize_database()
|
|
| 50 |
if not os.environ.get("OPENAI_API_KEY"):
|
| 51 |
raise ValueError("The OPENAI_API_KEY environment variable is not set. Please set it before running the app.")
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# --- Gradio UI Functions ---
|
| 57 |
|
|
@@ -84,14 +93,15 @@ def refresh_participants_list():
|
|
| 84 |
async def run_matching_process(organizer_criteria, progress=gr.Progress(track_tqdm=True)):
|
| 85 |
"""Async callback to run the team matching process, with live log streaming."""
|
| 86 |
# 1. Clear previous logs and show panel
|
|
|
|
| 87 |
log_stream.seek(0)
|
| 88 |
log_stream.truncate(0)
|
| 89 |
progress(0, desc="Initializing...")
|
| 90 |
-
yield
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
|
| 96 |
# 2. Get participants and perform initial checks
|
| 97 |
logger.info("Fetching participants...")
|
|
@@ -100,47 +110,51 @@ async def run_matching_process(organizer_criteria, progress=gr.Progress(track_tq
|
|
| 100 |
if len(participants_df) < 2:
|
| 101 |
warning_msg = "Matching process aborted: not enough participants."
|
| 102 |
logger.warning(warning_msg)
|
| 103 |
-
yield
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
return
|
| 109 |
|
| 110 |
logger.info(f"Running matching for {len(participants_df)} participants.")
|
| 111 |
progress(0.2, desc="π§ Agent is thinking...")
|
| 112 |
|
| 113 |
-
# 3. Create a
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
# --- Gradio App Definition ---
|
| 146 |
|
|
@@ -216,7 +230,7 @@ with gr.Blocks(theme=gr.themes.Default(
|
|
| 216 |
run_button.click(
|
| 217 |
fn=run_matching_process,
|
| 218 |
inputs=[organizer_criteria_in],
|
| 219 |
-
outputs=[
|
| 220 |
)
|
| 221 |
|
| 222 |
# --- Launching the App ---
|
|
@@ -228,8 +242,4 @@ if __name__ == "__main__":
|
|
| 228 |
except KeyboardInterrupt:
|
| 229 |
logger.info("Gradio app shutting down.")
|
| 230 |
finally:
|
| 231 |
-
|
| 232 |
-
logger.info("Closing agent resources...")
|
| 233 |
-
# We need to run the async close method
|
| 234 |
-
asyncio.run(agent.close())
|
| 235 |
-
logger.info("Cleanup complete.")
|
|
|
|
| 5 |
import sys
|
| 6 |
import os
|
| 7 |
import io
|
| 8 |
+
from contextlib import asynccontextmanager
|
| 9 |
|
| 10 |
# Change from absolute imports to relative imports
|
| 11 |
from database import initialize_database, add_participant, get_participants_dataframe
|
|
|
|
| 51 |
if not os.environ.get("OPENAI_API_KEY"):
|
| 52 |
raise ValueError("The OPENAI_API_KEY environment variable is not set. Please set it before running the app.")
|
| 53 |
|
| 54 |
+
# --- Session Management ---
|
| 55 |
+
@asynccontextmanager
|
| 56 |
+
async def agent_session():
|
| 57 |
+
"""Create and manage a session-specific agent."""
|
| 58 |
+
session_agent = create_matching_agent(log_manager=log_manager)
|
| 59 |
+
try:
|
| 60 |
+
yield session_agent
|
| 61 |
+
finally:
|
| 62 |
+
await session_agent.close()
|
| 63 |
+
logger.info("Session agent resources cleaned up")
|
| 64 |
|
| 65 |
# --- Gradio UI Functions ---
|
| 66 |
|
|
|
|
| 93 |
async def run_matching_process(organizer_criteria, progress=gr.Progress(track_tqdm=True)):
|
| 94 |
"""Async callback to run the team matching process, with live log streaming."""
|
| 95 |
# 1. Clear previous logs and show panel
|
| 96 |
+
|
| 97 |
log_stream.seek(0)
|
| 98 |
log_stream.truncate(0)
|
| 99 |
progress(0, desc="Initializing...")
|
| 100 |
+
yield [
|
| 101 |
+
gr.update(visible=True, open=True), # log_panel
|
| 102 |
+
"Starting matching process...\n", # log_output
|
| 103 |
+
"π Setting up the matching process..." # matching_results_out
|
| 104 |
+
]
|
| 105 |
|
| 106 |
# 2. Get participants and perform initial checks
|
| 107 |
logger.info("Fetching participants...")
|
|
|
|
| 110 |
if len(participants_df) < 2:
|
| 111 |
warning_msg = "Matching process aborted: not enough participants."
|
| 112 |
logger.warning(warning_msg)
|
| 113 |
+
yield [
|
| 114 |
+
gr.update(), # log_panel
|
| 115 |
+
log_stream.getvalue(), # log_output
|
| 116 |
+
"Cannot run matching with fewer than 2 participants." # matching_results_out
|
| 117 |
+
]
|
| 118 |
return
|
| 119 |
|
| 120 |
logger.info(f"Running matching for {len(participants_df)} participants.")
|
| 121 |
progress(0.2, desc="π§ Agent is thinking...")
|
| 122 |
|
| 123 |
+
# 3. Create a session-specific agent and run matching
|
| 124 |
+
async with agent_session() as session_agent:
|
| 125 |
+
logger.info("Created session-specific agent")
|
| 126 |
+
|
| 127 |
+
# Create a background task for the core matching logic
|
| 128 |
+
match_task = asyncio.create_task(
|
| 129 |
+
run_matching(session_agent, participants_df, organizer_criteria)
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# 4. Stream logs while the agent works
|
| 133 |
+
while not match_task.done():
|
| 134 |
+
await asyncio.sleep(0.5) # Poll for new logs every 0.5s
|
| 135 |
+
yield [
|
| 136 |
+
gr.update(), # log_panel
|
| 137 |
+
log_stream.getvalue(), # log_output
|
| 138 |
+
gr.update() # matching_results_out - No change to final output yet
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
# 5. Process the final result from the agent
|
| 142 |
+
try:
|
| 143 |
+
final_report = await match_task
|
| 144 |
+
logger.info("Matching process completed successfully.")
|
| 145 |
+
progress(1.0, desc="β
Done!")
|
| 146 |
+
yield [
|
| 147 |
+
gr.update(), # log_panel
|
| 148 |
+
log_stream.getvalue(), # log_output
|
| 149 |
+
final_report # matching_results_out
|
| 150 |
+
]
|
| 151 |
+
except Exception as e:
|
| 152 |
+
logger.error(f"An error occurred during the matching process: {e}", exc_info=True)
|
| 153 |
+
yield [
|
| 154 |
+
gr.update(), # log_panel
|
| 155 |
+
log_stream.getvalue(), # log_output
|
| 156 |
+
f"An error occurred: {e}" # matching_results_out
|
| 157 |
+
]
|
| 158 |
|
| 159 |
# --- Gradio App Definition ---
|
| 160 |
|
|
|
|
| 230 |
run_button.click(
|
| 231 |
fn=run_matching_process,
|
| 232 |
inputs=[organizer_criteria_in],
|
| 233 |
+
outputs=[log_panel, log_output, matching_results_out]
|
| 234 |
)
|
| 235 |
|
| 236 |
# --- Launching the App ---
|
|
|
|
| 242 |
except KeyboardInterrupt:
|
| 243 |
logger.info("Gradio app shutting down.")
|
| 244 |
finally:
|
| 245 |
+
logger.info("Shutdown complete.")
|
|
|
|
|
|
|
|
|
|
|
|
matching_agent.py
CHANGED
|
@@ -49,7 +49,7 @@ def create_matching_agent(log_manager=None) -> TinyCodeAgent:
|
|
| 49 |
api_key=os.environ.get("OPENAI_API_KEY"),
|
| 50 |
log_manager=log_manager,
|
| 51 |
pip_packages=["pandas", "numpy", "scikit-learn"],
|
| 52 |
-
|
| 53 |
local_execution=False, # Use remote Modal for security by default
|
| 54 |
)
|
| 55 |
|
|
@@ -94,6 +94,7 @@ async def run_matching(
|
|
| 94 |
task = organizer_prompt+'\n\n'
|
| 95 |
|
| 96 |
task += ("Form the teams based on the provided data and criteria."
|
|
|
|
| 97 |
f"\n<Organizer Criteria>\n{organizer_criteria}\n</Organizer Criteria>")
|
| 98 |
|
| 99 |
final_report = await agent.run(task, max_turns=15)
|
|
|
|
| 49 |
api_key=os.environ.get("OPENAI_API_KEY"),
|
| 50 |
log_manager=log_manager,
|
| 51 |
pip_packages=["pandas", "numpy", "scikit-learn"],
|
| 52 |
+
authorized_imports=["pandas", "numpy", "collections","itertools","requests"],
|
| 53 |
local_execution=False, # Use remote Modal for security by default
|
| 54 |
)
|
| 55 |
|
|
|
|
| 94 |
task = organizer_prompt+'\n\n'
|
| 95 |
|
| 96 |
task += ("Form the teams based on the provided data and criteria."
|
| 97 |
+
"\n Please go through all of them and give me details of all groups. "
|
| 98 |
f"\n<Organizer Criteria>\n{organizer_criteria}\n</Organizer Criteria>")
|
| 99 |
|
| 100 |
final_report = await agent.run(task, max_turns=15)
|