Update app.py
Browse files
app.py
CHANGED
|
@@ -77,13 +77,9 @@ def update_model_dropdown(provider):
|
|
| 77 |
return gr.Dropdown(choices=OPENROUTER_MODELS, value=OPENROUTER_MODELS[0], label="Target Engine Architecture")
|
| 78 |
|
| 79 |
# --- Common LLM API Request Orchestrator ---
|
| 80 |
-
def call_llm(provider, api_key, model_choice, system_prompt,
|
| 81 |
messages = [{"role": "system", "content": system_prompt}]
|
| 82 |
-
|
| 83 |
-
if chat_history_format:
|
| 84 |
-
messages.extend(chat_history_format)
|
| 85 |
-
else:
|
| 86 |
-
messages.append({"role": "user", "content": user_message})
|
| 87 |
|
| 88 |
if provider == "Groq":
|
| 89 |
client = Groq(api_key=api_key)
|
|
@@ -101,8 +97,6 @@ def call_llm(provider, api_key, model_choice, system_prompt, user_message, chat_
|
|
| 101 |
|
| 102 |
elif provider == "OpenRouter":
|
| 103 |
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
| 104 |
-
|
| 105 |
-
# Maps user-facing selection directly to their OpenRouter global endpoints
|
| 106 |
openrouter_model_map = {
|
| 107 |
"nvidia/nemotron-3.5-content-safety:free": "nvidia/nemotron-3.5-content-safety:free",
|
| 108 |
"qwen/qwen3.7-plus": "qwen/qwen3.7-plus",
|
|
@@ -138,7 +132,8 @@ def execute_ai_query(provider, api_key, model_choice, user_question):
|
|
| 138 |
)
|
| 139 |
|
| 140 |
try:
|
| 141 |
-
|
|
|
|
| 142 |
sql_query = sql_query.replace("```sql", "").replace("```", "").replace("`", "").strip()
|
| 143 |
|
| 144 |
conn = sqlite3.connect(DB_NAME)
|
|
@@ -148,13 +143,21 @@ def execute_ai_query(provider, api_key, model_choice, user_question):
|
|
| 148 |
except Exception as e:
|
| 149 |
return None, f"❌ Execution Failed: {str(e)}"
|
| 150 |
|
| 151 |
-
# --- Tab 2:
|
| 152 |
-
def
|
| 153 |
-
if not api_key.strip():
|
| 154 |
-
chat_history.append({"role": "assistant", "content": "⚠️ Authentication missing. Please input your API Key on the left menu pane."})
|
| 155 |
-
return chat_history, ""
|
| 156 |
if not user_msg.strip():
|
| 157 |
return chat_history, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
system_prompt = (
|
| 160 |
"You are a helpful conversational assistant and workflow coordinator for the Strides Pharma AI operational framework.\n"
|
|
@@ -168,14 +171,13 @@ def conversation_and_commit_agent(chat_history, provider, api_key, model_choice,
|
|
| 168 |
"If some schema details are completely absent, converse politely with the client to verify those remaining parameters before adding the string tag marker."
|
| 169 |
)
|
| 170 |
|
|
|
|
| 171 |
formatted_history = []
|
| 172 |
for turn in chat_history:
|
| 173 |
formatted_history.append({"role": turn["role"], "content": turn["content"]})
|
| 174 |
-
formatted_history.append({"role": "user", "content": user_msg})
|
| 175 |
|
| 176 |
try:
|
| 177 |
-
raw_response = call_llm(provider, api_key, model_choice, system_prompt,
|
| 178 |
-
|
| 179 |
cleaned_response = raw_response
|
| 180 |
database_committed_alert = ""
|
| 181 |
|
|
@@ -196,20 +198,17 @@ def conversation_and_commit_agent(chat_history, provider, api_key, model_choice,
|
|
| 196 |
conn.commit()
|
| 197 |
conn.close()
|
| 198 |
|
| 199 |
-
database_committed_alert = f"\n\n⚙️ **[SYSTEM UPDATE]:** Successfully appended task '{data_payload.get('task_name')}' to the
|
| 200 |
except Exception as inner_err:
|
| 201 |
-
database_committed_alert = f"\n\n⚠️ **[SYSTEM NOTICE]:** Captured
|
| 202 |
|
| 203 |
final_display_text = cleaned_response + database_committed_alert
|
| 204 |
-
|
| 205 |
-
chat_history.append({"role": "user", "content": user_msg})
|
| 206 |
chat_history.append({"role": "assistant", "content": final_display_text})
|
| 207 |
-
return chat_history
|
| 208 |
|
| 209 |
except Exception as e:
|
| 210 |
-
chat_history.append({"role": "user", "content": user_msg})
|
| 211 |
chat_history.append({"role": "assistant", "content": f"❌ API Connection Failure: {str(e)}"})
|
| 212 |
-
return chat_history
|
| 213 |
|
| 214 |
# --- Interface Layout Configuration ---
|
| 215 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
@@ -222,40 +221,52 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 222 |
provider_select = gr.Dropdown(choices=["Groq", "OpenRouter"], value="Groq", label="API Gateway Provider")
|
| 223 |
token_input = gr.Textbox(label="User API Secret Key", type="password", placeholder="gsk_... or sk-or-...")
|
| 224 |
|
| 225 |
-
# This component gets updated dynamically by the event handler below
|
| 226 |
model_select = gr.Dropdown(
|
| 227 |
choices=GROQ_MODELS,
|
| 228 |
value=GROQ_MODELS[0],
|
| 229 |
label="Target Engine Architecture"
|
| 230 |
)
|
| 231 |
-
|
| 232 |
gr.Markdown("✨ **Global Platform Database State Schema:**\n- `phase` (Discovery, Data Prep, Modeling, Validation)\n- `task_name` (Structural workflow description string)\n- `owner` (Assigned personnel scientist name)\n- `timeline` (Expected operational delivery time frames)\n- `priority` (High, Medium, Low)")
|
| 233 |
|
| 234 |
with gr.Column(scale=2):
|
| 235 |
with gr.Tabs():
|
| 236 |
|
|
|
|
| 237 |
with gr.TabItem("🤖 Interactive Data Contributor Chatbot"):
|
| 238 |
gr.Markdown("### Conversational Contributor Agent")
|
| 239 |
-
gr.Markdown("Chat with this engine normally, or
|
| 240 |
|
| 241 |
chatbot_viewport = gr.Chatbot(type="messages", label="Operational History Workspace")
|
| 242 |
chat_input = gr.Textbox(placeholder="Say hello, or submit task details to log...", label="Your Message")
|
| 243 |
send_btn = gr.Button("Submit Message", variant="primary")
|
| 244 |
|
|
|
|
|
|
|
|
|
|
| 245 |
send_btn.click(
|
| 246 |
-
fn=
|
| 247 |
-
inputs=[chatbot_viewport,
|
| 248 |
outputs=[chatbot_viewport, chat_input]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
)
|
|
|
|
| 250 |
chat_input.submit(
|
| 251 |
-
fn=
|
| 252 |
-
inputs=[chatbot_viewport,
|
| 253 |
outputs=[chatbot_viewport, chat_input]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
)
|
| 255 |
|
|
|
|
| 256 |
with gr.TabItem("🔎 SQL Inquisitor Desk"):
|
| 257 |
gr.Markdown("### Natural Language SQL Query Engine")
|
| 258 |
-
query_input = gr.Textbox(label="Query
|
| 259 |
query_btn = gr.Button("Evaluate Infrastructure", variant="secondary")
|
| 260 |
|
| 261 |
sql_status_display = gr.Markdown()
|
|
@@ -267,8 +278,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 267 |
outputs=[output_data_table, sql_status_display]
|
| 268 |
)
|
| 269 |
|
| 270 |
-
#
|
| 271 |
-
# Whenever the provider dropdown changes, change the choices of the model select dropdown
|
| 272 |
provider_select.change(
|
| 273 |
fn=update_model_dropdown,
|
| 274 |
inputs=[provider_select],
|
|
|
|
| 77 |
return gr.Dropdown(choices=OPENROUTER_MODELS, value=OPENROUTER_MODELS[0], label="Target Engine Architecture")
|
| 78 |
|
| 79 |
# --- Common LLM API Request Orchestrator ---
|
| 80 |
+
def call_llm(provider, api_key, model_choice, system_prompt, history_messages):
|
| 81 |
messages = [{"role": "system", "content": system_prompt}]
|
| 82 |
+
messages.extend(history_messages)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
if provider == "Groq":
|
| 85 |
client = Groq(api_key=api_key)
|
|
|
|
| 97 |
|
| 98 |
elif provider == "OpenRouter":
|
| 99 |
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
|
|
|
|
|
|
| 100 |
openrouter_model_map = {
|
| 101 |
"nvidia/nemotron-3.5-content-safety:free": "nvidia/nemotron-3.5-content-safety:free",
|
| 102 |
"qwen/qwen3.7-plus": "qwen/qwen3.7-plus",
|
|
|
|
| 132 |
)
|
| 133 |
|
| 134 |
try:
|
| 135 |
+
query_as_history = [{"role": "user", "content": user_question}]
|
| 136 |
+
sql_query = call_llm(provider, api_key, model_choice, system_prompt, query_as_history)
|
| 137 |
sql_query = sql_query.replace("```sql", "").replace("```", "").replace("`", "").strip()
|
| 138 |
|
| 139 |
conn = sqlite3.connect(DB_NAME)
|
|
|
|
| 143 |
except Exception as e:
|
| 144 |
return None, f"❌ Execution Failed: {str(e)}"
|
| 145 |
|
| 146 |
+
# --- Tab 2: Decoupled Multi-Step Chatbot Logic ---
|
| 147 |
+
def append_user_message(chat_history, user_msg):
|
|
|
|
|
|
|
|
|
|
| 148 |
if not user_msg.strip():
|
| 149 |
return chat_history, ""
|
| 150 |
+
# Instantly pushes user text to client viewport layout canvas
|
| 151 |
+
chat_history.append({"role": "user", "content": user_msg})
|
| 152 |
+
return chat_history, ""
|
| 153 |
+
|
| 154 |
+
def generate_agent_response(chat_history, provider, api_key, model_choice):
|
| 155 |
+
if not chat_history:
|
| 156 |
+
return chat_history
|
| 157 |
+
|
| 158 |
+
if not api_key.strip():
|
| 159 |
+
chat_history.append({"role": "assistant", "content": "⚠️ Authentication missing. Please input your API Key on the left menu pane."})
|
| 160 |
+
return chat_history
|
| 161 |
|
| 162 |
system_prompt = (
|
| 163 |
"You are a helpful conversational assistant and workflow coordinator for the Strides Pharma AI operational framework.\n"
|
|
|
|
| 171 |
"If some schema details are completely absent, converse politely with the client to verify those remaining parameters before adding the string tag marker."
|
| 172 |
)
|
| 173 |
|
| 174 |
+
# Format pipeline matching exact schema constraints
|
| 175 |
formatted_history = []
|
| 176 |
for turn in chat_history:
|
| 177 |
formatted_history.append({"role": turn["role"], "content": turn["content"]})
|
|
|
|
| 178 |
|
| 179 |
try:
|
| 180 |
+
raw_response = call_llm(provider, api_key, model_choice, system_prompt, formatted_history)
|
|
|
|
| 181 |
cleaned_response = raw_response
|
| 182 |
database_committed_alert = ""
|
| 183 |
|
|
|
|
| 198 |
conn.commit()
|
| 199 |
conn.close()
|
| 200 |
|
| 201 |
+
database_committed_alert = f"\n\n⚙️ **[SYSTEM UPDATE]:** Successfully appended task '{data_payload.get('task_name')}' to the database structural master records."
|
| 202 |
except Exception as inner_err:
|
| 203 |
+
database_committed_alert = f"\n\n⚠️ **[SYSTEM NOTICE]:** Captured token parameters, but update aborted due to structural parsing errors: {str(inner_err)}"
|
| 204 |
|
| 205 |
final_display_text = cleaned_response + database_committed_alert
|
|
|
|
|
|
|
| 206 |
chat_history.append({"role": "assistant", "content": final_display_text})
|
| 207 |
+
return chat_history
|
| 208 |
|
| 209 |
except Exception as e:
|
|
|
|
| 210 |
chat_history.append({"role": "assistant", "content": f"❌ API Connection Failure: {str(e)}"})
|
| 211 |
+
return chat_history
|
| 212 |
|
| 213 |
# --- Interface Layout Configuration ---
|
| 214 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
|
|
| 221 |
provider_select = gr.Dropdown(choices=["Groq", "OpenRouter"], value="Groq", label="API Gateway Provider")
|
| 222 |
token_input = gr.Textbox(label="User API Secret Key", type="password", placeholder="gsk_... or sk-or-...")
|
| 223 |
|
|
|
|
| 224 |
model_select = gr.Dropdown(
|
| 225 |
choices=GROQ_MODELS,
|
| 226 |
value=GROQ_MODELS[0],
|
| 227 |
label="Target Engine Architecture"
|
| 228 |
)
|
|
|
|
| 229 |
gr.Markdown("✨ **Global Platform Database State Schema:**\n- `phase` (Discovery, Data Prep, Modeling, Validation)\n- `task_name` (Structural workflow description string)\n- `owner` (Assigned personnel scientist name)\n- `timeline` (Expected operational delivery time frames)\n- `priority` (High, Medium, Low)")
|
| 230 |
|
| 231 |
with gr.Column(scale=2):
|
| 232 |
with gr.Tabs():
|
| 233 |
|
| 234 |
+
# Tab 1: Decoupled Multi-Step Chatbot
|
| 235 |
with gr.TabItem("🤖 Interactive Data Contributor Chatbot"):
|
| 236 |
gr.Markdown("### Conversational Contributor Agent")
|
| 237 |
+
gr.Markdown("Chat with this engine normally, or log a brand-new task assignment milestone directly into the active SQLite infrastructure.")
|
| 238 |
|
| 239 |
chatbot_viewport = gr.Chatbot(type="messages", label="Operational History Workspace")
|
| 240 |
chat_input = gr.Textbox(placeholder="Say hello, or submit task details to log...", label="Your Message")
|
| 241 |
send_btn = gr.Button("Submit Message", variant="primary")
|
| 242 |
|
| 243 |
+
# Decoupled sequence logic prevents thread locking:
|
| 244 |
+
# Step A: Push user input to UI frame immediately & clear the input box
|
| 245 |
+
# Step B: Call backend API to obtain assistant response
|
| 246 |
send_btn.click(
|
| 247 |
+
fn=append_user_message,
|
| 248 |
+
inputs=[chatbot_viewport, chat_input],
|
| 249 |
outputs=[chatbot_viewport, chat_input]
|
| 250 |
+
).then(
|
| 251 |
+
fn=generate_agent_response,
|
| 252 |
+
inputs=[chatbot_viewport, provider_select, token_input, model_select],
|
| 253 |
+
outputs=[chatbot_viewport]
|
| 254 |
)
|
| 255 |
+
|
| 256 |
chat_input.submit(
|
| 257 |
+
fn=append_user_message,
|
| 258 |
+
inputs=[chatbot_viewport, chat_input],
|
| 259 |
outputs=[chatbot_viewport, chat_input]
|
| 260 |
+
).then(
|
| 261 |
+
fn=generate_agent_response,
|
| 262 |
+
inputs=[chatbot_viewport, provider_select, token_input, model_select],
|
| 263 |
+
outputs=[chatbot_viewport]
|
| 264 |
)
|
| 265 |
|
| 266 |
+
# Tab 2: Natural-Language-to-SQL Inquisitor
|
| 267 |
with gr.TabItem("🔎 SQL Inquisitor Desk"):
|
| 268 |
gr.Markdown("### Natural Language SQL Query Engine")
|
| 269 |
+
query_input = gr.Textbox(label="Query current database contents using conversational English:", placeholder="e.g., Show me all records sorted by priority status")
|
| 270 |
query_btn = gr.Button("Evaluate Infrastructure", variant="secondary")
|
| 271 |
|
| 272 |
sql_status_display = gr.Markdown()
|
|
|
|
| 278 |
outputs=[output_data_table, sql_status_display]
|
| 279 |
)
|
| 280 |
|
| 281 |
+
# Provider dropdown change handler
|
|
|
|
| 282 |
provider_select.change(
|
| 283 |
fn=update_model_dropdown,
|
| 284 |
inputs=[provider_select],
|