generated from streamlit/blank-app-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
365 lines (302 loc) · 12.9 KB
/
streamlit_app.py
File metadata and controls
365 lines (302 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# app.py
import json
import streamlit as st
from agents import (
generate_learning_path,
LearnerProfile,
call_resource_agent,
call_curriculum_agent,
evaluate_learning_path,
refine_learning_path,
)
st.set_page_config(
page_title="Solara Skill Builder",
layout="wide",
)
st.title("Solara Skill Builder")
st.caption("Multi-agent AI that generates personalized learning paths for digital careers.")
# ------------- SIDEBAR: ABOUT / DEBUG -------------
with st.sidebar:
st.header("About")
st.write(
"This app uses a multi-agent system:\n"
"- Planner Agent\n"
"- Resource Researcher Agent\n"
"- Curriculum Synthesizer Agent\n"
"- Evaluation Module\n\n"
"Backend is in agents.py (Gemini-powered)."
)
show_raw = st.checkbox("Show raw JSON output", value=False)
show_agent_debug = st.checkbox(
"Show agent-level debug (plan/resources/path/eval)",
value=False,
)
# ------------- MAIN FORM: LEARNER PROFILE -------------
with st.form("learning_path_form"):
col1, col2 = st.columns(2)
with col1:
goal_role = st.text_input(
"Target role",
placeholder="e.g., Junior Data Analyst, Help Desk Technician",
)
timeframe_months = st.number_input(
"Timeframe (months)",
min_value=1,
max_value=60,
value=9,
step=1,
)
hours_per_week = st.number_input(
"Hours available per week",
min_value=1,
max_value=60,
value=7,
step=1,
)
with col2:
prior_experience = st.text_area(
"Prior experience / background",
placeholder="e.g., basic Excel, no programming, strong customer service skills",
height=140,
)
extra_constraints = st.text_area(
"Constraints or preferences (optional)",
placeholder="e.g., prefers video content; avoid paid courses; needs accessibility-friendly material",
height=150,
)
# Two buttons side by side inside the form
btn_col1, btn_col2 = st.columns(2)
with btn_col1:
submitted = st.form_submit_button("Generate Learning Path",
help="Create a personalized learning path based on the provided profile.",
width=200,
)
with btn_col2:
clear_requested = st.form_submit_button("Clear Learning Path",
help="Wipe the current learning path and start over.",
width=200,
)
# ------------- SESSION STATE INIT -------------
if "learning_result" not in st.session_state:
st.session_state.learning_result = None
if "last_error" not in st.session_state:
st.session_state.last_error = None
if "learner_profile" not in st.session_state:
st.session_state.learner_profile = None
# ------------- RUN PIPELINE ON FIRST GENERATE / CLEAR -------------
if "learning_result" not in st.session_state:
st.session_state.learning_result = None
if "last_error" not in st.session_state:
st.session_state.last_error = None
if "learner_profile" not in st.session_state:
st.session_state.learner_profile = None
# Clear button: wipe everything and skip generation
if "clear_requested" in locals() and clear_requested:
st.session_state.learning_result = None
st.session_state.last_error = None
st.session_state.learner_profile = None
st.info("Learning path and evaluation have been cleared.")
elif submitted:
if not goal_role:
st.warning("Please specify a target role before generating a learning path.")
else:
learner_profile: LearnerProfile = {
"goal_role": goal_role,
"timeframe_months": int(timeframe_months),
"hours_per_week": int(hours_per_week),
"prior_experience": prior_experience.strip(),
"constraints": extra_constraints.strip(),
}
try:
with st.spinner("Running multi-agent pipeline (planner → resources → curriculum → evaluation)..."):
result = generate_learning_path(learner_profile)
st.session_state.learning_result = result
st.session_state.learner_profile = learner_profile
st.session_state.last_error = None
except Exception as e:
st.session_state.learning_result = None
st.session_state.last_error = str(e)
# ------------- ERROR DISPLAY -------------
if st.session_state.last_error:
st.error("An error occurred while generating the learning path.")
with st.expander("Show error details"):
st.code(st.session_state.last_error, language="text")
# ------------- DISPLAY RESULTS -------------
result = st.session_state.learning_result
if result:
plan = result.get("plan", {})
resources = result.get("resources", [])
learning_path = result.get("learning_path", {})
evaluation = result.get("evaluation", {})
# ---- Overview ----
st.subheader("Generated Learning Path")
st.markdown("### Overview")
st.write(learning_path.get("summary", "No summary provided by the agent."))
cols = st.columns(3)
cols[0].metric(
"Estimated Total Hours",
str(learning_path.get("total_estimated_hours", "N/A")),
)
cols[1].metric(
"Schedule Type",
learning_path.get("schedule_type", "N/A"),
)
cols[2].metric(
"Modules",
str(len(learning_path.get("modules", []))),
)
# ---- Modules / Weeks ----
st.markdown("### Modules / Weeks")
modules = learning_path.get("modules", [])
if not modules:
st.info("No modules found in the learning path output.")
else:
for i, module in enumerate(modules, start=1):
title = module.get("title", f"Module {i}")
with st.expander(f"{i}. {title}", expanded=(i == 1)):
st.markdown(f"**Objective:** {module.get('objective', 'N/A')}")
st.markdown(f"**Estimated hours:** {module.get('estimated_hours', 'N/A')}")
competencies = module.get("competencies_covered", [])
if competencies:
st.markdown("**Competencies covered:** " + ", ".join(competencies))
# Resources
mod_resources = module.get("resources", [])
if mod_resources:
st.markdown("**Resources:**")
for res in mod_resources:
res_title = res.get("title", "Resource")
url = res.get("url", "")
r_type = res.get("type", "resource")
if url:
st.markdown(f"- [{res_title}]({url}) ({r_type})")
else:
st.markdown(f"- {res_title} ({r_type})")
else:
st.markdown("_No resources listed for this module._")
# Tasks
tasks = module.get("tasks", [])
if tasks:
st.markdown("**Practice Tasks:**")
for task in tasks:
st.markdown(f"- {task}")
else:
st.markdown("_No practice tasks listed for this module._")
# ---- Notes ----
notes = learning_path.get("notes", [])
if notes:
st.markdown("### Path Notes")
for n in notes:
st.markdown(f"- {n}")
# ---- Evaluation ----
st.subheader("Evaluation")
if evaluation:
main_score = evaluation.get("final_score", None)
cols = st.columns(6)
if main_score is not None:
cols[0].metric("Final Score", f"{main_score:.2f}")
else:
cols[0].metric("Final Score", "N/A")
cols[1].metric("Coverage", f"{evaluation.get('coverage', 0):.2f}")
cols[2].metric("Sequencing", f"{evaluation.get('sequencing', 0):.2f}")
cols[3].metric("Difficulty", f"{evaluation.get('difficulty_alignment', 0):.2f}")
cols[4].metric("Practicality", f"{evaluation.get('practicality', 0):.2f}")
cols[5].metric("Resource Quality", f"{evaluation.get('resource_quality', 0):.2f}")
st.markdown("### Evaluator Comments")
comments = evaluation.get("comments", {})
if comments:
for key, text in comments.items():
st.markdown(f"**{key.replace('_', ' ').title()}:** {text}")
else:
st.write("No comments provided by evaluator.")
else:
st.info("No evaluation data returned.")
# ---- Regenerate Resources & Path (KEEP PLAN) ----
# disable button if we don't have a plan + learner_profile in session
regen_disabled = (
st.session_state.learning_result is None
or not plan
or st.session_state.learner_profile is None
)
regen_clicked = st.button(
"Regenerate resources and path (keep plan)",
disabled=regen_disabled,
help="Run again using the same competency plan." if not regen_disabled else
"Generate a learning path first before regenerating.",
)
if regen_clicked:
# at this point we KNOW plan and learner_profile exist,
# because the button can't be clicked when disabled
with st.spinner("Regenerating resources, learning path, and evaluation (planner kept)..."):
learner_profile = st.session_state.learner_profile
# 1) Re-run Resource Agent with existing plan
new_resources = call_resource_agent(plan, learner_profile)
# 2) Re-run Curriculum Agent
new_draft_path = call_curriculum_agent(plan, new_resources, learner_profile)
# 3) Re-run Evaluation
new_eval = evaluate_learning_path(learner_profile, new_draft_path)
# ---- Apply the same bad-URL penalty logic ----
invalid_links = 0
total_links = 0
for group in new_resources:
for item in group.get("items", []):
if "valid_url" in item:
total_links += 1
if not item["valid_url"]:
invalid_links += 1
if total_links > 0 and invalid_links > 0:
invalid_ratio = invalid_links / total_links
penalty = min(0.4, invalid_ratio) # max -0.4 on resource_quality
half_penalty = penalty / 2.0 # smaller hit on final_score
rq = new_eval.get("resource_quality", 1.0)
fs = new_eval.get("final_score", 1.0)
new_eval["resource_quality"] = max(0.0, rq - penalty)
new_eval["final_score"] = max(0.0, fs - half_penalty)
comments = new_eval.get("comments") or {}
existing = comments.get("resource_quality", "")
extra_note = f"{invalid_links} invalid or malformed URLs detected out of {total_links}."
if existing:
comments["resource_quality"] = existing.rstrip(".") + f" ({extra_note})"
else:
comments["resource_quality"] = extra_note
new_eval["comments"] = comments
# 4) Optional refinement, same rule as in agents.generate_learning_path
final_path = new_draft_path
if new_eval.get("final_score", 1.0) < 0.8:
final_path = refine_learning_path(learner_profile, new_draft_path, new_eval)
new_result = {
"plan": plan, # keep the same plan
"resources": new_resources,
"learning_path": final_path,
"evaluation": new_eval,
}
# Update session + local variable so UI immediately reflects changes
st.session_state.learning_result = new_result
result = new_result
resources = new_resources
learning_path = final_path
evaluation = new_eval
st.success("Resources, learning path, and evaluation regenerated using the existing plan.")
# ---- Agent-level debug (per-agent outputs) ----
if show_agent_debug:
st.subheader("4. Agent-level Debug")
with st.expander("Planner Agent Output (plan)", expanded=False):
st.code(json.dumps(plan, indent=2), language="json")
with st.expander("Resource Researcher Output (resources)", expanded=False):
st.code(json.dumps(resources, indent=2), language="json")
with st.expander("Curriculum Synthesizer Output (learning_path)", expanded=False):
st.code(json.dumps(learning_path, indent=2), language="json")
with st.expander("Evaluator Output (evaluation)", expanded=False):
st.code(json.dumps(evaluation, indent=2), language="json")
# ---- Raw JSON (overall result) ----
if show_raw:
st.subheader("Raw Combined JSON Output")
st.write("Use this to debug or for exporting into notebooks / reports.")
st.code(json.dumps(result, indent=2), language="json")
st.download_button(
"Download result as JSON",
data=json.dumps(result, indent=2),
file_name="solara_skill_builder_result.json",
mime="application/json",
)
else:
st.info("Fill in the learner profile above and click 'Generate Learning Path' to get started.")