Spaces:
Sleeping
Sleeping
Commit ·
a822dca
1
Parent(s): 1706cd9
model loading + fix preview + tracing + pptx skills
Browse filesFiles changed (12)
- .gitignore+2
- apps/gradio-space/src/gradio_space/app.py+5-3
- apps/gradio-space/src/gradio_space/model_loading.py+14-1
- apps/gradio-space/src/gradio_space/tabs/chat.py+1-1
- apps/gradio-space/src/gradio_space/tabs/education_pptx.py+31-9
- libs/agent/src/agent/preview.py+8-3
- libs/agent/src/agent/prompts.py+10-1
- libs/agent/src/agent/runner.py+77-17
- libs/agent/src/agent/tools/pptx.py+5
- libs/agent/src/agent/trace.py+3
- libs/agent/tests/test_runner.py+27
- uv.lock+17
8 unmodified lines910118 unmodified lines*.egg-info/dist/build/8 unmodified lines9101112138 unmodified lines*.egg-info/dist/build/outputs/traces
1 unmodified line234567831 unmodified lines404142434445464748495051521 unmodified lineimport gradio as grfrom gradio_space.tabs import build_chat_tab, build_education_pptx_tabfrom inference.config import get_app_config_app_config = get_app_config()31 unmodified linesreturn demodemo = build_demo()def main() -> None:demo.launch(server_name="0.0.0.0",server_port=int(os.environ.get("PORT", "7860")),)1 unmodified line234567891031 unmodified lines424344454647484950515253541 unmodified lineimport gradio as grfrom gradio_space.model_loading import preload_active_modelfrom gradio_space.tabs import build_chat_tab, build_education_pptx_tabfrom gradio_space.tabs.education_pptx import gradio_allowed_pathsfrom inference.config import get_app_config_app_config = get_app_config()31 unmodified linesreturn demodef main() -> None:preload_active_model()demo = build_demo()demo.launch(server_name="0.0.0.0",server_port=int(os.environ.get("PORT", "7860")),allowed_paths=gradio_allowed_paths(),)
68 unmodified lines6970717273747576777868 unmodified linesdevice_hint = runtime_device_hint(key)return (f"Preset `{key}` selected ({model.backend}, {device_hint}). ""Weights load on the first request.")def model_status(model_key: str) -> str:model = get_model_config(model_key)return f"**{model.label}**\n\n- Backend: `{model.backend}`\n- {warmup(model_key)}"68 unmodified lines697071727374757677787980818283848586878889909168 unmodified linesdevice_hint = runtime_device_hint(key)return (f"Preset `{key}` selected ({model.backend}, {device_hint}). ""Loading weights…")def preload_active_model() -> str:"""Load the active preset at startup so the first request is fast."""key = get_active_model_key()print(f"[startup] Loading model preset `{key}`…", flush=True)error = ensure_model_loaded(key)if error:print(f"[startup] {error}", flush=True)return errorstatus = warmup(key)print(f"[startup] {status}", flush=True)return statusdef model_status(model_key: str) -> str:model = get_model_config(model_key)return f"**{model.label}**\n\n- Backend: `{model.backend}`\n- {warmup(model_key)}"
123456import gradio as grfrom gradio_space.model_loading import chat, model_status, warmupfrom inference.config import get_app_config_app_config = get_app_config()123456import gradio as grfrom gradio_space.model_loading import chat, model_statusfrom inference.config import get_app_config_app_config = get_app_config()
123456789101112131415161718192021226 unmodified lines2930313233343536373 unmodified lines41424344454647484938 unmodified lines888990919293949541 unmodified lines137138139import gradio as grfrom agent.runner import AgentRunnerfrom gradio_space.model_loading import ensure_model_loaded, get_active_model_key, model_statusfrom inference.factory import get_backenddef generate_lesson_slides(topic: str,grade: str,slide_count: int,) -> tuple[str, str, list[tuple[str, str]], str | None, str | None, str | None, str, str]:model_key = get_active_model_key()load_error = ensure_model_loaded(model_key)if load_error:return load_error, "", [], None, None, None, load_error, load_errorif not topic.strip():message = "Please enter a lesson topic."return message, "", [], None, None, None, message, messagetry:runner = AgentRunner()6 unmodified lines)except Exception as exc: # noqa: BLE001 — show agent errors in UImessage = f"Agent error: {exc}"return message, "", [], None, None, None, message, messagegallery = [(path, f"Slide {i}") for i, path in enumerate(result.preview_images)]trace_summary = (f"Run `{result.trace.run_id}` · skill `{result.trace.skill}` · "f"model `{result.trace.model}`\n\n"3 unmodified linesresult.markdown_preview,result.html_preview,gallery,result.pptx_path,result.docx_path,result.html_export_path,trace_summary,result.trace.to_json(),)38 unmodified linesslide_gallery = gr.Gallery(label="Slide thumbnails",columns=2,height="auto",object_fit="contain",)with gr.Tab("Outline"):outline_preview = gr.Markdown(label="Outline (markdown)")41 unmodified linestrace_box,],)123456789101112131415161718192021222324252627282930313233343536376 unmodified lines4445464748495051523 unmodified lines56575859606162636438 unmodified lines10310410510610710810911011141 unmodified lines153154155156157158159160161from pathlib import Pathimport gradio as grfrom agent.runner import AgentRunnerfrom agent.tools.pptx import get_outputs_dirfrom gradio_space.model_loading import ensure_model_loaded, get_active_model_key, model_statusfrom inference.factory import get_backenddef _error_html(message: str) -> str:safe = (message.replace("&", "&").replace("<", "<").replace(">", ">"))return (f'<div style="padding:12px;border:1px solid #c44;border-radius:8px;'f'background:#fff5f5;color:#8a1f1f;">{safe}</div>')def generate_lesson_slides(topic: str,grade: str,slide_count: int,) -> tuple[str, str, list[str], str | None, str | None, str | None, str, str]:model_key = get_active_model_key()load_error = ensure_model_loaded(model_key)if load_error:return load_error, _error_html(load_error), [], None, None, None, load_error, load_errorif not topic.strip():message = "Please enter a lesson topic."return message, _error_html(message), [], None, None, None, message, messagetry:runner = AgentRunner()6 unmodified lines)except Exception as exc: # noqa: BLE001 — show agent errors in UImessage = f"Agent error: {exc}"return message, _error_html(message), [], None, None, None, message, messagegallery = [str(Path(p).resolve()) for p in result.preview_images]trace_summary = (f"Run `{result.trace.run_id}` · skill `{result.trace.skill}` · "f"model `{result.trace.model}`\n\n"3 unmodified linesresult.markdown_preview,result.html_preview,gallery,str(Path(result.pptx_path).resolve()),str(Path(result.docx_path).resolve()),str(Path(result.html_export_path).resolve()),trace_summary,result.trace.to_json(),)38 unmodified linesslide_gallery = gr.Gallery(label="Slide thumbnails",columns=2,height=420,object_fit="contain",preview=True,)with gr.Tab("Outline"):outline_preview = gr.Markdown(label="Outline (markdown)")41 unmodified linestrace_box,],)def gradio_allowed_paths() -> list[str]:"""Paths Gradio must be allowed to read for previews and downloads."""root = get_outputs_dir().resolve()return [str(root)]
214 unmodified lines215216217218219220221222223224225226214 unmodified linesy = marginif is_title:draw.text((margin, height // 2 - 80), _wrap_text(title, 28), fill=fg, font=title_font)if subtitle:draw.text((margin, height // 2 + 40), subtitle, fill=accent, font=small_font)else:draw.text((margin, y), _wrap_text(title, 32), fill=fg, font=title_font)y += 90for bullet in bullets:line = _wrap_text(f"• {bullet}", 48)for part in line.split("\n"):214 unmodified lines215216217218219220221222223224225226227228229230231214 unmodified linesy = marginif is_title:y_title = height // 2 - 80for part in _wrap_text(title, 28).split("\n"):draw.text((margin, y_title), part, fill=fg, font=title_font)y_title += 64if subtitle:draw.text((margin, height // 2 + 40), subtitle, fill=accent, font=small_font)else:for part in _wrap_text(title, 32).split("\n"):draw.text((margin, y), part, fill=fg, font=title_font)y += 52y += 20for bullet in bullets:line = _wrap_text(f"• {bullet}", 48)for part in line.split("\n"):
39 unmodified lines4041424344454647484939 unmodified lines)def education_outline_repair(invalid_output: str, error: str) -> str:return ("The previous response was invalid JSON or did not match the schema.\n"f"Validation error: {error}\n"f"Previous output:\n{invalid_output}\n\n""Return corrected JSON only, no explanation.")39 unmodified lines4041424344454647484950515253545556575839 unmodified lines)def education_outline_repair(invalid_output: str,error: str,*,expected_slides: int | None = None,) -> str:count_line = ""if expected_slides is not None:count_line = f"\nYou must include exactly {expected_slides} items in the slides array.\n"return ("The previous response was invalid JSON or did not match the schema.\n"f"Validation error: {error}\n"f"{count_line}"f"Previous output:\n{invalid_output}\n\n""Return corrected JSON only, no explanation.")
6 unmodified lines78910111213111 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571586 unmodified linesfrom inference.base import InferenceBackendfrom agent.models import EducationPptxInput, SlideOutlinefrom agent.preview import outline_to_html, render_slide_imagesfrom agent.prompts import (education_outline_repair,111 unmodified linestrace.log_llm(prompt_text, raw)try:return self._parse_outline(raw, req.slide_count)except (json.JSONDecodeError, ValueError) as first_error:repair_messages = messages + [{"role": "assistant", "content": raw},{"role": "user","content": education_outline_repair(raw, str(first_error)),},]repaired = backend.chat(repair_messages, max_tokens=2048, temperature=0.1)trace.log_llm(education_outline_repair(raw, str(first_error)), repaired)return self._parse_outline(repaired, req.slide_count)def _parse_outline(self, raw: str, expected_slides: int) -> SlideOutline:data = self._extract_json(raw)outline = SlideOutline.model_validate(data)if len(outline.slides) != expected_slides:if len(outline.slides) > expected_slides:outline = SlideOutline(title=outline.title,slides=outline.slides[:expected_slides],)else:raise ValueError(f"Expected {expected_slides} slides, got {len(outline.slides)}")return outline@staticmethoddef _extract_json(text: str) -> dict[str, Any]:cleaned = text.strip()6 unmodified lines78910111213111 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172186 unmodified linesfrom inference.base import InferenceBackendfrom agent.models import EducationPptxInput, SlideOutline, SlideSpecfrom agent.preview import outline_to_html, render_slide_imagesfrom agent.prompts import (education_outline_repair,111 unmodified linestrace.log_llm(prompt_text, raw)try:return self._parse_outline(raw, req.slide_count, trace)except (json.JSONDecodeError, ValueError) as first_error:repair_messages = messages + [{"role": "assistant", "content": raw},{"role": "user","content": education_outline_repair(raw, str(first_error), expected_slides=req.slide_count),},]repair_prompt = education_outline_repair(raw, str(first_error), expected_slides=req.slide_count)repaired = backend.chat(repair_messages, max_tokens=2048, temperature=0.1)trace.log_llm(repair_prompt, repaired)return self._parse_outline(repaired, req.slide_count, trace)def _parse_outline(self,raw: str,expected_slides: int,trace: TraceRecorder | None = None,) -> SlideOutline:data = self._sanitize_outline_data(self._extract_json(raw))outline = SlideOutline.model_validate(data)original_count = len(outline.slides)outline = self._normalize_slide_count(outline, expected_slides)if trace and original_count != expected_slides:trace.log_note("Adjusted slide count to match request",requested=expected_slides,model_returned=original_count,final=len(outline.slides),)return outline@staticmethoddef _sanitize_outline_data(data: dict[str, Any]) -> dict[str, Any]:title = str(data.get("title") or "Lesson").strip() or "Lesson"slides_in = data.get("slides") or []slides_out: list[dict[str, Any]] = []for index, slide in enumerate(slides_in):if not isinstance(slide, dict):continueslide_title = str(slide.get("title") or f"Slide {index + 1}").strip()bullets_raw = slide.get("bullets") or []if isinstance(bullets_raw, str):bullets_raw = [bullets_raw]bullets = [str(b).strip() for b in bullets_raw if str(b).strip()]if not bullets:bullets = ["Discuss this topic with the class"]slides_out.append({"title": slide_title or f"Slide {index + 1}","bullets": bullets,"speaker_note": str(slide.get("speaker_note") or ""),})if not slides_out:slides_out.append({"title": "Introduction","bullets": ["Overview of the topic", "Why it matters"],"speaker_note": "",})return {"title": title, "slides": slides_out}@staticmethoddef _normalize_slide_count(outline: SlideOutline, expected: int) -> SlideOutline:slides = list(outline.slides)if len(slides) > expected:slides = slides[:expected]while len(slides) < expected:number = len(slides) + 1slides.append(SlideSpec(title=f"More about {outline.title}",bullets=["Key idea to expand in class","Question for students",],speaker_note="Add details for this slide during the lesson.",))return SlideOutline(title=outline.title, slides=slides)@staticmethoddef _extract_json(text: str) -> dict[str, Any]:cleaned = text.strip()
9 unmodified lines1011121314159 unmodified linesfrom agent.models import SlideOutlinedef _outputs_dir() -> Path:import osimport tempfile9 unmodified lines10111213141516171819209 unmodified linesfrom agent.models import SlideOutlinedef get_outputs_dir() -> Path:"""Directory for generated artifacts (pptx, docx, preview images)."""return _outputs_dir()def _outputs_dir() -> Path:import osimport tempfile
31 unmodified lines32333435363731 unmodified lines})def log_tool(self, name: str, arguments: dict[str, Any], result: str) -> None:self.steps.append({31 unmodified lines32333435363738394031 unmodified lines})def log_note(self, message: str, **details: Any) -> None:self.steps.append({"type": "note", "message": message, **details})def log_tool(self, name: str, arguments: dict[str, Any], result: str) -> None:self.steps.append({
4 unmodified lines56789104 unmodified linesfrom agent.tools.pptx import create_pptxdef test_extract_json_from_fenced_block():raw = '```json\n{"title": "T", "slides": [{"title": "S", "bullets": ["a"]}]}\n```'data = AgentRunner._extract_json(raw)4 unmodified lines56789101112131415161718192021222324252627282930313233343536374 unmodified linesfrom agent.tools.pptx import create_pptxdef test_parse_outline_pads_when_model_returns_too_few():runner = AgentRunner()raw = ('{"title": "AI Agents", "slides": [''{"title": "Intro", "bullets": ["What is an agent?"]},''{"title": "Uses", "bullets": ["Automation"]}'"]}")outline = runner._parse_outline(raw, expected_slides=5)assert len(outline.slides) == 5assert outline.title == "AI Agents"def test_parse_outline_trims_when_model_returns_too_many():runner = AgentRunner()raw = ('{"title": "Topic", "slides": [''{"title": "A", "bullets": ["a"]},''{"title": "B", "bullets": ["b"]},''{"title": "C", "bullets": ["c"]},''{"title": "D", "bullets": ["d"]}'"]}")outline = runner._parse_outline(raw, expected_slides=3)assert len(outline.slides) == 3def test_extract_json_from_fenced_block():raw = '```json\n{"title": "T", "slides": [{"title": "S", "bullets": ["a"]}]}\n```'data = AgentRunner._extract_json(raw)
44 unmodified lines454647484950511 unmodified line535455565758591264 unmodified lines13241325132613271328132944 unmodified linessource = { editable = "libs/agent" }dependencies = [{ name = "inference" },{ name = "pydantic" },{ name = "python-pptx" },{ name = "pyyaml" },]1 unmodified line[package.metadata]requires-dist = [{ name = "inference", editable = "libs/inference" },{ name = "pydantic", specifier = ">=2.0.0" },{ name = "python-pptx", specifier = ">=1.0.0" },{ name = "pyyaml", specifier = ">=6.0.2" },]1264 unmodified lines{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },][[package]]name = "python-multipart"version = "0.0.32"44 unmodified lines4546474849505152531 unmodified line5556575859606162631264 unmodified lines132813291330133113321333133413351336133713381339134013411342134313441345134644 unmodified linessource = { editable = "libs/agent" }dependencies = [{ name = "inference" },{ name = "pillow" },{ name = "pydantic" },{ name = "python-docx" },{ name = "python-pptx" },{ name = "pyyaml" },]1 unmodified line[package.metadata]requires-dist = [{ name = "inference", editable = "libs/inference" },{ name = "pillow", specifier = ">=10.0.0" },{ name = "pydantic", specifier = ">=2.0.0" },{ name = "python-docx", specifier = ">=1.1.0" },{ name = "python-pptx", specifier = ">=1.0.0" },{ name = "pyyaml", specifier = ">=6.0.2" },]1264 unmodified lines{ url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },][[package]]name = "python-docx"version = "1.2.0"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "lxml" },{ name = "typing-extensions" },]sdist = { url = "https://files.pythonhosted.org/packages/a9/f7/eddfe33871520adab45aaa1a71f0402a2252050c14c7e3009446c8f4701c/python_docx-1.2.0.tar.gz", hash = "sha256:7bc9d7b7d8a69c9c02ca09216118c86552704edc23bac179283f2e38f86220ce", size = 5723256, upload-time = "2025-06-16T20:46:27.921Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/d0/00/1e03a4989fa5795da308cd774f05b704ace555a70f9bf9d3be057b680bcf/python_docx-1.2.0-py3-none-any.whl", hash = "sha256:3fd478f3250fbbbfd3b94fe1e985955737c145627498896a8a6bf81f4baf66c7", size = 252987, upload-time = "2025-06-16T20:46:22.506Z" },][[package]]name = "python-multipart"version = "0.0.32"
.gitignore+2
apps/gradio-space/src/gradio_space/app.py+5-3
apps/gradio-space/src/gradio_space/model_loading.py+14-1
apps/gradio-space/src/gradio_space/tabs/chat.py+1-1
apps/gradio-space/src/gradio_space/tabs/education_pptx.py+31-9
libs/agent/src/agent/preview.py+8-3
libs/agent/src/agent/prompts.py+10-1
libs/agent/src/agent/runner.py+77-17
libs/agent/src/agent/tools/pptx.py+5
libs/agent/src/agent/trace.py+3
libs/agent/tests/test_runner.py+27
uv.lock+17