// agent

薛竹老师

by luzheng · Nov 11, 2026 Public

Choose how to run this agent

⚡ Local runs on your GPU. For usable speed it needs a WebGPU-capable browser — Chrome or Edge on a machine with a graphics card, or an Apple Silicon Mac. This agent runs on-device only. Check your machine
Try it now

Requires an API key and an AgentOp account.

37 downloads
0 forks
0.0 rating

Description

智能体位高校教务老师,负责解答学生关于学籍管理、选课、成绩管理、考试、学科竞赛等等常见事务。

What this agent can do

薛竹老师 is built from the New Hire Handbook Grounded Q&A template and loads pypdf in the browser. Runs fully on your own device: llama.cpp compiled to WebAssembly, GPU-accelerated through WebGPU, with no API key and no server. After the one-time model download it works offline.

Runs in the browser

  • Document Q&A (local RAG). Answers from documents you drop in: the text is chunked and indexed locally in the browser (IndexedDB), the relevant passages are retrieved for each question, and nothing is uploaded.

Source Code

agent.py
import io
import json
from typing import Any

from pypdf import PdfReader

MAX_DOC_CHARS = int("[[[MAX_CHARS|6000]]]")
TOP_K = 5


def _truncate_text(text: str, max_chars: int = MAX_DOC_CHARS) -> str:
    text = (text or "").strip()
    if len(text) <= max_chars:
        return text
    return text[:max_chars] + "\n\n[Truncated for answer budget]"


def _extract_pdf_text(pdf_bytes: list[int]) -> str:
    buffer = io.BytesIO(bytes(pdf_bytes))
    reader = PdfReader(buffer)
    pages = []
    for page in reader.pages:
        try:
            pages.append(page.extract_text() or "")
        except Exception:
            pages.append("")
    return "\n\n".join(pages).strip()


async def _add_text_document(name: str, text: str, kind: str = "text") -> dict[str, Any]:
    clean_name = (name or "Untitled document").strip()
    clean_text = (text or "").strip()
    if not clean_text:
        return {"ok": False, "error": f"{clean_name} appears to be empty."}
    await agentop_rag.add_document(clean_name, clean_text)
    return {
        "ok": True,
        "name": clean_name,
        "kind": kind,
        "chars": len(clean_text),
    }


async def _add_pdf_document(name: str, pdf_bytes: list[int]) -> dict[str, Any]:
    clean_name = (name or "Untitled PDF").strip()
    text = _extract_pdf_text(pdf_bytes)
    if not text:
        return {"ok": False, "error": f"No readable text was found in {clean_name}."}
    await agentop_rag.add_document(clean_name, text)
    return {
        "ok": True,
        "name": clean_name,
        "kind": "pdf",
        "chars": len(text),
    }


async def _clear_all_documents() -> None:
    await agentop_rag.clear()


async def _list_documents() -> list[dict[str, Any]]:
    try:
        hits = await agentop_rag.search("*", k=50)
    except Exception:
        hits = []
    docs: dict[str, dict[str, Any]] = {}
    for hit in hits:
        source = (hit.get("source") or "Uploaded document").strip()
        text = hit.get("text") or ""
        if source not in docs:
            docs[source] = {"name": source, "kind": source.split(".")[-1].lower() if "." in source else "document", "chars": 0}
        docs[source]["chars"] += len(text)
    return sorted(docs.values(), key=lambda x: x["name"].lower())


async def process_user_query(query: str) -> str:
    clean_query = (query or "").strip()
    if not clean_query:
        return "Please ask a question about the uploaded employee handbook or policy documents."

    hits = await agentop_rag.search(clean_query, k=TOP_K)
    if not hits:
        return (
            "I could not find relevant content in the uploaded documents.\n\n"
            "Not covered in the uploaded handbook set. Please upload the relevant handbook, benefits guide, or policy document if you want me to answer."
        )

    filtered_hits = []
    for hit in hits:
        text = (hit.get("text") or "").strip()
        source = (hit.get("source") or "Uploaded document").strip()
        score = hit.get("score", 0)
        if text:
            filtered_hits.append({"source": source, "text": _truncate_text(text), "score": score})

    if not filtered_hits:
        return (
            "I found documents, but no readable policy text for this question.\n\n"
            "Not covered in the uploaded handbook set."
        )

    context_blocks = []
    sources = []
    for i, hit in enumerate(filtered_hits, start=1):
        sources.append(hit["source"])
        context_blocks.append(
            f"Source {i}: {hit['source']}\n"
            f"Relevance: {hit['score']}\n"
            f"Excerpt:\n{hit['text']}"
        )

    grounded_prompt = (
        "Answer the employee onboarding question using ONLY the provided document excerpts.\n\n"
        "Rules:\n"
        "- Do not use outside knowledge.\n"
        "- If the answer is not clearly stated in the excerpts, say: Not covered in the uploaded documents.\n"
        "- Do not guess or infer company policy details.\n"
        "- Cite the source document names in a final 'Sources:' line.\n"
        "- If excerpts conflict, say that the documents appear inconsistent and cite both sources.\n"
        "- Keep the answer concise and practical for a new hire.\n\n"
        f"Question:\n{clean_query}\n\n"
        f"Document excerpts:\n\n{'\n\n'.join(context_blocks)}"
    )

    answer = await process_user_query_wllama(grounded_prompt, globals().get("TEMPLATE_SYSTEM_PROMPT", ""))
    answer = (answer or "").strip()

    if not answer:
        return "Not covered in the uploaded documents.\n\nSources: None"

    unique_sources = []
    for src in sources:
        if src not in unique_sources:
            unique_sources.append(src)
    sources_line = "Sources: " + ", ".join(unique_sources)

    if "Sources:" not in answer:
        answer = answer + "\n\n" + sources_line

    return answer