Spaces:
Sleeping
Sleeping
Commit ·
c02b92b
1
Parent(s): cfc5e63
Add HF trace storage, admin controls, and Spaces deployment
Browse files- Upload traces as JSON to a HF dataset repo after each question
- Add Traces tab with session-scoped view (admin URL param for full history)
- Replace Gradio login with inline token field
- Decouple chat history from agent loop (display only)
- Add huggingface-hub dependency and requirements.txt for HF Spaces
- Add .claudeignore to exclude .env files
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Files changed (7)
- .claudeignoreAdded+3
- .env.example+5
- README.md+1
- app.py+212-87
- pyproject.toml+1
- requirements.txtAdded+269
- uv.lock+2
123.env.env.local.env.*.local10 unmodified lines1112131410 unmodified lines# Web app authenticationLH_ACCESS_TOKEN=your-secret-token# LH_MAX_SESSION_COST=0.5010 unmodified lines11121314151617181910 unmodified lines# Web app authenticationLH_ACCESS_TOKEN=your-secret-token# LH_ADMIN_TOKEN=your-admin-token# LH_MAX_SESSION_COST=0.50# Hugging Face trace storage (optional)# HF_TOKEN=your-hf-write-token# HF_TRACES_REPO=your-username/document-explorer-traces
6 unmodified lines7891011126 unmodified linessdk_version: "6.9.0"app_file: app.pypinned: false---# Document Explorer6 unmodified lines789101112136 unmodified linessdk_version: "6.9.0"app_file: app.pypinned: falsepython_version: "3.12"---# Document Explorer
8 unmodified lines910111213141516171819202122238 unmodified lines323334353637383940414224 unmodified lines6768697071727374757677787980818283848586878889909192939495968 unmodified lines10510610710810911011111211311411513 unmodified lines1291301311321331341356 unmodified lines1421431441451461471 unmodified line1491501511521531541551561571581 unmodified line1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322333 unmodified lines2372382392408 unmodified linesfrom __future__ import annotationsimport osimport tempfileimport timefrom dataclasses import asdictfrom pathlib import Pathimport gradio as grimport litellmfrom dotenv import load_dotenvfrom llm_harness.agent import run_agent_loopfrom llm_harness.prompt import build_system_prompt8 unmodified linesMODEL = os.environ.get("LH_MODEL", "")ACCESS_TOKEN = os.environ.get("LH_ACCESS_TOKEN", "")MAX_SESSION_COST = float(os.environ.get("LH_MAX_SESSION_COST", "0.50"))def authenticate(username: str, password: str) -> bool:return password == ACCESS_TOKENdef save_uploaded_files(files: list[str]) -> Path:24 unmodified linesdef chat(message: str,history: list[dict],files: list[str] | None,workspace_path: str,scratch_path: str,session_cost: float,):if not MODEL:yield ("Error: LH_MODEL not set.","",workspace_path,scratch_path,session_cost,)returnif session_cost >= MAX_SESSION_COST:yield (f"Session cost limit reached (${session_cost:.2f} / "f"${MAX_SESSION_COST:.2f}). Start a new session.","",workspace_path,scratch_path,session_cost,)return8 unmodified linesscratch_path = tempfile.mkdtemp(prefix="lh-scratch-")scratch_dir = Path(scratch_path)# Build messages from Gradio historysystem_prompt = build_system_prompt(base_prompt="", workspace=workspace)messages: list[Message] = [{"role": "system", "content": system_prompt}]messages.extend({"role": e["role"], "content": e["content"]} for e in history)messages.append({"role": "user", "content": message})# Run agent loop with E2B sandboxstart = time.monotonic()13 unmodified linesif isinstance(event, ToolCallEvent):tool_call_count += 1status = f"*Exploring documents ({tool_call_count} tool calls)...*"yield status, "", workspace_path, scratch_path, session_costelif isinstance(event, ToolResultEvent):continueelse:6 unmodified linesworkspace_path,scratch_path,session_cost,)return1 unmodified linetrace.wall_time_s = round(time.monotonic() - start, 2)answer = trace.answer or "(no answer)"stats = format_stats(trace)trace_html = render_trace({"question": message, "passed": True, "assertions": {}, "trace": asdict(trace)},max_chars=2000,)yield (f"{answer}\n\n---\n{stats}",1 unmodified lineworkspace_path,scratch_path,session_cost,)def build_app() -> gr.Blocks:with gr.Blocks(title="Document Explorer", theme=gr.themes.Soft()) as demo:gr.Markdown("# Document Explorer\n""Upload text or CSV files, then ask questions. ""The model explores your documents by writing and running Python code.")workspace_state = gr.State("")scratch_state = gr.State("")cost_state = gr.State(0.0)with gr.Accordion("Upload documents", open=True):file_upload = gr.File(label="Text, CSV, Markdown, or JSON files",file_count="multiple",file_types=[".txt", ".csv", ".md", ".json"],)chatbot = gr.Chatbot(height=500)msg = gr.Textbox(placeholder="Ask a question about your documents...",label="",show_label=False,)with gr.Accordion("Trace", open=False, visible=False) as trace_accordion:trace_display = gr.HTML("")def respond(message, history, files, workspace_path, scratch_path, session_cost):history = history or []history.append({"role": "user", "content": message})for response, trace_html, wp, sp, sc in chat(message, history[:-1], files, workspace_path, scratch_path, session_cost):history_with_response = [*history,{"role": "assistant", "content": response},]visible = gr.update(visible=bool(trace_html))yield history_with_response, "", trace_html, visible, wp, sp, scmsg.submit(respond,inputs=[msg,chatbot,file_upload,workspace_state,scratch_state,cost_state,],outputs=[chatbot,msg,trace_display,trace_accordion,workspace_state,scratch_state,cost_state,],)return demo3 unmodified linesprint("WARNING: LH_ACCESS_TOKEN not set — app is unprotected")app = build_app()app.launch(auth=authenticate if ACCESS_TOKEN else None)8 unmodified lines910111213141516171819202122232425268 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979824 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481498 unmodified lines15815916016116216316416516616716813 unmodified lines1821831841851861871886 unmodified lines1951961971981992002011 unmodified line2032042052062072082092102111 unmodified line2132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583 unmodified lines3623633643658 unmodified linesfrom __future__ import annotationsimport jsonimport osimport tempfileimport timefrom dataclasses import asdictfrom datetime import datetime, timezonefrom pathlib import Pathimport gradio as grimport litellmfrom dotenv import load_dotenvfrom huggingface_hub import HfApifrom llm_harness.agent import run_agent_loopfrom llm_harness.prompt import build_system_prompt8 unmodified linesMODEL = os.environ.get("LH_MODEL", "")ACCESS_TOKEN = os.environ.get("LH_ACCESS_TOKEN", "")ADMIN_TOKEN = os.environ.get("LH_ADMIN_TOKEN", "")MAX_SESSION_COST = float(os.environ.get("LH_MAX_SESSION_COST", "0.50"))HF_TRACES_REPO = os.environ.get("HF_TRACES_REPO", "")HF_TOKEN = os.environ.get("HF_TOKEN", "")hf_api = HfApi(token=HF_TOKEN) if HF_TOKEN else Nonedef _slugify(text: str, max_len: int = 50) -> str:slug = text.lower().replace(" ", "-")slug = "".join(c for c in slug if c.isalnum() or c == "-")return slug[:max_len].rstrip("-")def upload_trace(result: dict) -> str | None:if not hf_api or not HF_TRACES_REPO:return Nonetimestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")question_slug = _slugify(result.get("question", ""))filename = f"{timestamp}_{question_slug}.json" if question_slug else f"{timestamp}.json"content = json.dumps(result, indent=2, default=str).encode()try:hf_api.upload_file(path_or_fileobj=content,path_in_repo=filename,repo_id=HF_TRACES_REPO,repo_type="dataset",)return filenameexcept Exception as exc:print(f"WARNING: trace upload failed: {exc}")return Nonedef list_traces() -> list[str]:if not hf_api or not HF_TRACES_REPO:return []try:files = hf_api.list_repo_files(HF_TRACES_REPO, repo_type="dataset")traces = sorted([f for f in files if f.endswith(".json")],reverse=True,)return tracesexcept Exception:return []def fetch_trace(filename: str) -> dict | None:if not hf_api or not HF_TRACES_REPO or not filename:return Nonetry:path = hf_api.hf_hub_download(HF_TRACES_REPO, filename, repo_type="dataset")return json.loads(Path(path).read_text())except Exception:return Nonedef save_uploaded_files(files: list[str]) -> Path:24 unmodified linesdef chat(message: str,files: list[str] | None,workspace_path: str,scratch_path: str,session_cost: float,token: str = "",):empty = ("", "", workspace_path, scratch_path, session_cost, None)if ACCESS_TOKEN and token != ACCESS_TOKEN:yield ("Invalid access token.", *empty[1:])returnif not MODEL:yield ("Error: LH_MODEL not set.", *empty[1:])returnif session_cost >= MAX_SESSION_COST:yield (f"Session cost limit reached (${session_cost:.2f} / "f"${MAX_SESSION_COST:.2f}). Start a new session.",*empty[1:],)return8 unmodified linesscratch_path = tempfile.mkdtemp(prefix="lh-scratch-")scratch_dir = Path(scratch_path)system_prompt = build_system_prompt(base_prompt="", workspace=workspace)messages: list[Message] = [{"role": "system", "content": system_prompt},{"role": "user", "content": message},]# Run agent loop with E2B sandboxstart = time.monotonic()13 unmodified linesif isinstance(event, ToolCallEvent):tool_call_count += 1status = f"*Exploring documents ({tool_call_count} tool calls)...*"yield status, "", workspace_path, scratch_path, session_cost, Noneelif isinstance(event, ToolResultEvent):continueelse:6 unmodified linesworkspace_path,scratch_path,session_cost,None,)return1 unmodified linetrace.wall_time_s = round(time.monotonic() - start, 2)answer = trace.answer or "(no answer)"stats = format_stats(trace)result = {"question": message, "passed": True, "assertions": {}, "trace": asdict(trace)}trace_filename = upload_trace(result)trace_html = render_trace(result, max_chars=2000)yield (f"{answer}\n\n---\n{stats}",1 unmodified lineworkspace_path,scratch_path,session_cost,trace_filename,)def build_app() -> gr.Blocks:with gr.Blocks(title="Document Explorer", theme=gr.themes.Soft()) as demo:gr.Markdown("# Document Explorer")with gr.Tabs():with gr.Tab("Chat"):gr.Markdown("Upload text or CSV files, then ask questions. ""The model explores your documents by writing and running Python code.")workspace_state = gr.State("")scratch_state = gr.State("")cost_state = gr.State(0.0)session_traces_state = gr.State([]) # filenames uploaded this sessionwith gr.Row():token_input = gr.Textbox(placeholder="Access token",label="Access Token",type="password",scale=1,)with gr.Accordion("Upload documents", open=True):file_upload = gr.File(label="Text, CSV, Markdown, or JSON files",file_count="multiple",file_types=[".txt", ".csv", ".md", ".json"],)chatbot = gr.Chatbot(height=500)msg = gr.Textbox(placeholder="Ask a question about your documents...",label="",show_label=False,)with gr.Accordion("Trace", open=False, visible=False) as trace_accordion:trace_display = gr.HTML("")def respond(message, history, files, workspace_path, scratch_path,session_cost, session_traces, token,):history = history or []history.append({"role": "user", "content": message})for response, trace_html, wp, sp, sc, trace_file in chat(message, files, workspace_path, scratch_path, session_cost, token):if trace_file:session_traces = [*session_traces, trace_file]history_with_response = [*history,{"role": "assistant", "content": response},]accordion = gr.Accordion(visible=bool(trace_html))yield (history_with_response, "", trace_html, accordion,wp, sp, sc, session_traces,)msg.submit(respond,inputs=[msg,chatbot,file_upload,workspace_state,scratch_state,cost_state,session_traces_state,token_input,],outputs=[chatbot,msg,trace_display,trace_accordion,workspace_state,scratch_state,cost_state,session_traces_state,],)with gr.Tab("Traces") as traces_tab:admin_state = gr.State(False)trace_dropdown = gr.Dropdown(choices=[],label="Select trace",)refresh_btn = gr.Button("Refresh")trace_viewer = gr.HTML("")def check_admin(request: gr.Request):token = request.query_params.get("admin", "")return ADMIN_TOKEN and token == ADMIN_TOKENdef show_trace(filename):result = fetch_trace(filename)if not result:return ""return render_trace(result, max_chars=5000)def refresh_traces(session_traces, is_admin):if is_admin:filenames = list_traces()else:filenames = sorted(session_traces, reverse=True)return gr.Dropdown(choices=filenames,value=filenames[0] if filenames else None,)demo.load(check_admin,outputs=[admin_state],)trace_dropdown.change(show_trace,inputs=[trace_dropdown],outputs=[trace_viewer],)refresh_btn.click(refresh_traces,inputs=[session_traces_state, admin_state],outputs=[trace_dropdown],)traces_tab.select(refresh_traces,inputs=[session_traces_state, admin_state],outputs=[trace_dropdown],)return demo3 unmodified linesprint("WARNING: LH_ACCESS_TOKEN not set — app is unprotected")app = build_app()app.launch()
10 unmodified lines11121314151610 unmodified lines"a-simple-llm-harness","e2b-code-interpreter>=2.5","gradio>=5.0","python-dotenv",]10 unmodified lines1112131415161710 unmodified lines"a-simple-llm-harness","e2b-code-interpreter>=2.5","gradio>=5.0","huggingface-hub","python-dotenv",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269# This file was autogenerated by uv via the following command:# uv export --format requirements-txt --no-hashesa-simple-llm-harness @ git+https://github.com/chuckfinca/a-simple-llm-harness.git@a67e2cc8dcf320d5df765c44fbee282ba1aa5331 # via document-exploreraiofiles==24.1.0 # via gradioaiohappyeyeballs==2.6.1 # via aiohttpaiohttp==3.13.3 # via litellmaiosignal==1.4.0 # via aiohttpannotated-doc==0.0.4 # via # fastapi # typerannotated-types==0.7.0 # via pydanticanyio==4.12.1 # via # gradio # httpx # openai # starletteattrs==26.1.0 # via # aiohttp # e2b # e2b-code-interpreter # jsonschema # referencingaudioop-lts==0.2.2 ; python_full_version >= '3.13' # via gradiobracex==2.6 # via wcmatchbrotli==1.2.0 # via gradiocertifi==2026.2.25 # via # httpcore # httpx # requestscharset-normalizer==3.4.6 # via requestsclick==8.3.1 # via # litellm # typer # uvicorncolorama==0.4.6 ; sys_platform == 'win32' # via # click # tqdmdistro==1.9.0 # via openaidockerfile-parse==2.0.1 # via e2be2b==2.15.3 # via e2b-code-interpretere2b-code-interpreter==2.5.0 # via document-explorerfastapi==0.135.2 # via gradiofastuuid==0.14.0 # via litellmffmpy==1.0.0 # via gradiofilelock==3.25.2 # via huggingface-hubfrozenlist==1.8.0 # via # aiohttp # aiosignalfsspec==2026.2.0 # via # gradio-client # huggingface-hubgradio==6.9.0 # via document-explorergradio-client==2.3.0 # via gradiogroovy==0.1.2 # via gradioh11==0.16.0 # via # httpcore # uvicornhf-xet==1.4.2 ; platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64' # via huggingface-hubhttpcore==1.0.9 # via # e2b # httpxhttpx==0.28.1 # via # e2b # e2b-code-interpreter # gradio # gradio-client # huggingface-hub # litellm # openai # safehttpxhuggingface-hub==1.7.2 # via # document-explorer # gradio # gradio-client # tokenizersidna==3.11 # via # anyio # httpx # requests # yarlimportlib-metadata==9.0.0 # via litellmjinja2==3.1.6 # via # gradio # litellmjiter==0.13.0 # via openaijsonschema==4.26.0 # via litellmjsonschema-specifications==2025.9.1 # via jsonschemalitellm==1.82.6 # via a-simple-llm-harnessmarkdown-it-py==4.0.0 # via richmarkupsafe==3.0.3 # via # gradio # jinja2mdurl==0.1.2 # via markdown-it-pymultidict==6.7.1 # via # aiohttp # yarlnumpy==2.4.3 # via # gradio # pandasopenai==2.29.0 # via litellmorjson==3.11.7 # via gradiopackaging==26.0 # via # e2b # gradio # gradio-client # huggingface-hubpandas==3.0.1 # via gradiopillow==12.1.1 # via gradiopropcache==0.4.1 # via # aiohttp # yarlprotobuf==7.34.1 # via e2bpydantic==2.12.5 # via # fastapi # gradio # litellm # openaipydantic-core==2.41.5 # via pydanticpydub==0.25.1 # via gradiopygments==2.19.2 # via richpython-dateutil==2.9.0.post0 # via # e2b # pandaspython-dotenv==1.2.2 # via # document-explorer # litellmpython-multipart==0.0.22 # via gradiopytz==2026.1.post1 # via gradiopyyaml==6.0.3 # via # gradio # huggingface-hubreferencing==0.37.0 # via # jsonschema # jsonschema-specificationsregex==2026.2.28 # via tiktokenrequests==2.32.5 # via tiktokenrich==14.3.3 # via # a-simple-llm-harness # e2b # typerrpds-py==0.30.0 # via # jsonschema # referencingsafehttpx==0.1.7 # via gradiosemantic-version==2.10.0 # via gradioshellingham==1.5.4 # via typersix==1.17.0 # via python-dateutilsniffio==1.3.1 # via openaistarlette==0.52.1 # via # fastapi # gradiotiktoken==0.12.0 # via litellmtokenizers==0.22.2 # via litellmtomlkit==0.13.3 # via gradiotqdm==4.67.3 # via # huggingface-hub # openaityper==0.24.1 # via # gradio # huggingface-hubtyping-extensions==4.15.0 # via # aiosignal # anyio # e2b # fastapi # gradio # gradio-client # huggingface-hub # openai # pydantic # pydantic-core # referencing # starlette # typing-inspectiontyping-inspection==0.4.2 # via # fastapi # pydantictzdata==2025.3 ; sys_platform == 'emscripten' or sys_platform == 'win32' # via pandasurllib3==2.6.3 # via requestsuvicorn==0.42.0 # via gradiowcmatch==10.1 # via e2byarl==1.23.0 # via aiohttpzipp==3.23.0 # via importlib-metadata409 unmodified lines4104114124134144152 unmodified lines418419420421422423409 unmodified lines{ name = "a-simple-llm-harness" },{ name = "e2b-code-interpreter" },{ name = "gradio" },{ name = "python-dotenv" },]2 unmodified lines{ name = "a-simple-llm-harness", git = "https://github.com/chuckfinca/a-simple-llm-harness.git" },{ name = "e2b-code-interpreter", specifier = ">=2.5" },{ name = "gradio", specifier = ">=5.0" },{ name = "python-dotenv" },]409 unmodified lines4104114124134144154162 unmodified lines419420421422423424425409 unmodified lines{ name = "a-simple-llm-harness" },{ name = "e2b-code-interpreter" },{ name = "gradio" },{ name = "huggingface-hub" },{ name = "python-dotenv" },]2 unmodified lines{ name = "a-simple-llm-harness", git = "https://github.com/chuckfinca/a-simple-llm-harness.git" },{ name = "e2b-code-interpreter", specifier = ">=2.5" },{ name = "gradio", specifier = ">=5.0" },{ name = "huggingface-hub" },{ name = "python-dotenv" },]
.claudeignoreAdded+3
.env.example+5
README.md+1
app.py+212-87
pyproject.toml+1
requirements.txtAdded+269
uv.lock+2