Upload 3 files
Browse filesFiles changed (2)
- app.py+14
- pipeline.py+107-1
689 unmodified lines690691692693694695696697698689 unmodified linestrace=[{k: v for k, v in t.items() if k != "error"} for t in retrieval["trace"]],portal_search_url=_portal_link(plan, q),follow_up_suggestions=_followups(plan, retrieval) if results else [],)@app.post("/feedback")def feedback(req: FeedbackRequest):rating = (req.feedback or req.rating or "")[:10]689 unmodified lines690691692693694695696697698699700701702703704705706707708709710711712689 unmodified linestrace=[{k: v for k, v in t.items() if k != "error"} for t in retrieval["trace"]],portal_search_url=_portal_link(plan, q),follow_up_suggestions=_followups(plan, retrieval) if results else [],sections=_section_cards(retrieval, min(len(results), top_k) + len(scopus_only)),)def _section_cards(retrieval: dict, start: int) -> list[dict]:"""Theses and experts of a combined question, numbered after the publications (as the answer cites them)."""out, n = [], startfor k in ("theses", "experts"):v = (retrieval.get("sections") or {}).get(k)if not v or not v.get("results"):continueout.append({"kind": k, "label": {"theses": "Theses", "experts": "KU experts"}[k], "found": v["found"],"results": [_public_result(o, i) for i, o in enumerate(v["results"], n + 1)]})n += len(v["results"])return out@app.post("/feedback")def feedback(req: FeedbackRequest):rating = (req.feedback or req.rating or "")[:10]
82 unmodified lines83848586878820 unmodified lines109110111112113114269 unmodified lines3843853863873883893903913921074 unmodified lines146714681469147014711472147314741475147614771478246 unmodified lines172517261727172817291730144 unmodified lines18751876187718781879188037 unmodified lines19181919192019211922192317 unmodified lines19411942194319441945194682 unmodified linesunit_name: str | None = Field(default=None, description="A KU college, department or research centre named in the ""question as the unit whose people or theses are wanted, exactly as written.")want_count: bool = Field(default=False, description="True if the user asks HOW MANY (a number).")clarify_question: str = Field(default="", description="ONLY when the message genuinely has two or more different ""readings that would give different answers and none is clearly most likely: one short question to the user. ""Otherwise empty.")20 unmodified linesPure's search box is a keyword index over titles, abstracts, keywords and author names — it does NOT understand natural language.Convert the user's message into a QueryPlan.Clarifying (rare):- Set clarify_question + clarify_options ONLY when the message has two or more readings that need DIFFERENT answersand none is clearly the most likely, e.g. "how many KU authors in 2026?" (people with publications in 2026, or the269 unmodified linesif re.search(r"\b(how many|number of|count of|total)\b", question, re.I):plan.want_count = True_detect_totals(plan, question)return apply_scope(plan, scope)# Words that never make a topic: a "how many" question made only of these (plus years and stop words)# is a question about ALL outputs, whatever the planner put in keyword_queries._GENERIC_COUNT_WORDS = set("""total totals overall all altogether how many much number numbers count counts output outputs1074 unmodified linesconcept = Noneif plan.intent in ("topic_search", "thesis_search", "expert_search", "project_search", "collab_search", "count"):concept = await _expand_with_concepts(pure, plan)result = await _route(pure, plan)if concept:result["trace"].insert(0, concept)return resultasync def _route(pure: PureClient, plan: QueryPlan) -> dict:if plan.intent == "project_search":r = await _retrieve_outputs(pure, plan.model_copy(update={"output_types": [], "open_access_only": False}),246 unmodified lines- Then group the most relevant records by theme or approach in 2-4 short paragraphs or "- " bullets, naming key KU authors and years.- If some records are only loosely related, say so and do not stretch them. If none really answer the question, say that plainlyand suggest a better search (different keywords, removing a year filter, or contacting Nikesh Narayanan, Research Librarian, nikesh.narayanan@ku.ac.ae).- Numbers: Khazna misses many KU papers, so whenever FACTS give a Scopus/SciVal figure (ku_in_scopus_not_yet_in_khazna,all_ku_publications, ku_wide_scopus_not_yet_in_khazna), state it next to the Khazna figure and say where each comes from.- FACTS kind author_without_profile: the person has no Khazna profile (probably left KU before Khazna started); the144 unmodified linesreturn (f"{who} {state}. I found **{facts['outputs_found']}** of their publications in Khazna as a KU author; "f"they are listed below.")return f"{who} {state}, and I found no Khazna publications listing them as a KU author."if k == "author_without_profile":n_k, n_s = facts.get("outputs_found", 0), facts.get("scopus_only", 0)parts = []37 unmodified linesreturn ""async def synthesize(question: str, plan: QueryPlan, retrieval: dict, history: list[dict], model: str, top_k: int) -> str:outs = retrieval["results"][:top_k]filters = []17 unmodified lines+ (f"\nFACTS (exact):\n{json.dumps(facts, ensure_ascii=False, indent=1)}\n" if facts else "")+ f"\nRECORDS (top {len(outs)} of {len(retrieval['results'])} after filtering):\n\n{_format_records(outs)}"+ (f"\n\nNOT YET IN KHAZNA (KU papers listed in Scopus only):\n\n{_format_records(extra, len(outs) + 1)}" if extra else ""))if not os.environ.get("OPENAI_API_KEY") and not (model == "claude" and os.environ.get("ANTHROPIC_API_KEY")):return facts_sentence(facts) or f"I found {len(retrieval['results'])} matching Khazna records. The top results are listed below."82 unmodified lines83848586878889909120 unmodified lines112113114115116117118119120121122269 unmodified lines3923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264271074 unmodified lines15021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548246 unmodified lines179517961797179817991800180118021803144 unmodified lines194819491950195119521953195419551956195719581959196019611962196319641965196637 unmodified lines200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202817 unmodified lines204620472048204920502051205282 unmodified linesunit_name: str | None = Field(default=None, description="A KU college, department or research centre named in the ""question as the unit whose people or theses are wanted, exactly as written.")want_count: bool = Field(default=False, description="True if the user asks HOW MANY (a number).")combine: list[Literal["publications", "theses", "experts"]] = Field(default_factory=list, description=("When ONE question asks for two or more KINDS of results on a topic (e.g. 'articles and theses and experts on ""X', 'papers and supervisors for X', 'everything KU has on X'): the kinds asked for. Otherwise empty."))clarify_question: str = Field(default="", description="ONLY when the message genuinely has two or more different ""readings that would give different answers and none is clearly most likely: one short question to the user. ""Otherwise empty.")20 unmodified linesPure's search box is a keyword index over titles, abstracts, keywords and author names — it does NOT understand natural language.Convert the user's message into a QueryPlan.Combined questions:- "List all works on water desalination including articles, theses and experts" => topic_search withcombine=["publications","theses","experts"]; "papers and PhD theses on X" => combine=["publications","theses"];"everything KU has on X" => all three. A question about ONE kind leaves combine empty.Clarifying (rare):- Set clarify_question + clarify_options ONLY when the message has two or more readings that need DIFFERENT answersand none is clearly the most likely, e.g. "how many KU authors in 2026?" (people with publications in 2026, or the269 unmodified linesif re.search(r"\b(how many|number of|count of|total)\b", question, re.I):plan.want_count = True_detect_totals(plan, question)_detect_combine(plan, question)if scope != "all": # a search area picked on purpose: one kind onlyplan.combine = []return apply_scope(plan, scope)_COMBINE_WORDS = {# "works" only as a noun ("all the works on X"), not "who works on X""publications": r"\b(articles?|papers?|publications?|outputs?|literature|books?|chapters?)\b|(?<!who )\bworks\b(?!\s+(on|in|at|with)\b)","theses": r"\b(thes[ie]s|dissertations?)\b",# researchers as a request ("which researchers", "researchers working on"), not as authors ("papers by researchers")"experts": r"\b(experts?|supervisors?|specialists?|who (works|researches|is working)|which researchers|"r"researchers (working|who|active))\b",}def _detect_combine(plan: QueryPlan, question: str) -> None:"""Questions asking for several kinds of results at once ('articles and theses and experts on X') are searchedfor each kind in parallel (Nikesh, 1 Dec 2026: such a question had returned publications only)."""if plan.intent not in ("topic_search", "thesis_search", "expert_search") or plan.author_name or plan.all_outputs:plan.combine = []returnlow = question.lower()kinds = {k for k, rx in _COMBINE_WORDS.items() if re.search(rx, low)}if re.search(r"\b(everything|all (the )?(works|research|records))\b", low) and plan.keyword_queries:kinds |= {"publications", "theses", "experts"} if re.search(r"\beverything\b", low) else {"publications", "theses"}kinds |= set(plan.combine or [])plan.combine = [k for k in ("publications", "theses", "experts") if k in kinds] if len(kinds) >= 2 else []# Words that never make a topic: a "how many" question made only of these (plus years and stop words)# is a question about ALL outputs, whatever the planner put in keyword_queries._GENERIC_COUNT_WORDS = set("""total totals overall all altogether how many much number numbers count counts output outputs1074 unmodified linesconcept = Noneif plan.intent in ("topic_search", "thesis_search", "expert_search", "project_search", "collab_search", "count"):concept = await _expand_with_concepts(pure, plan)result = await (_retrieve_combined(pure, plan) if len(plan.combine) >= 2 else _route(pure, plan))if concept:result["trace"].insert(0, concept)return resultCOMBINED_TOP = {"publications": 10, "theses": 6, "experts": 6}async def _retrieve_combined(pure: PureClient, plan: QueryPlan) -> dict:"""Publications, theses and/or experts on one topic, searched in parallel; each comes back as its own section.The publication section stays the main result list; theses and experts ride along in 'sections'."""base = {"combine": [], "want_count": True}jobs = {}if "publications" in plan.combine:jobs["publications"] = _route(pure, plan.model_copy(update={**base, "intent": "topic_search"}))if "theses" in plan.combine:jobs["theses"] = _retrieve_theses(pure, plan.model_copy(update={**base, "intent": "thesis_search", "output_types": []}))if "experts" in plan.combine:jobs["experts"] = _retrieve_experts(pure, plan.model_copy(update={**base, "intent": "expert_search"}))got = dict(zip(jobs, await asyncio.gather(*jobs.values(), return_exceptions=True)))sections, trace = {}, []for kind, r in got.items():if isinstance(r, Exception):print(f"[combined] {kind} failed: {r}")trace.append({"endpoint": f"combined/{kind}", "error": str(r)[:200], "hits": 0})continuetrace += [dict(t, section=kind) for t in r.get("trace", [])]sections[kind] = {"results": r.get("results", [])[:COMBINED_TOP[kind]], "found": len(r.get("results", [])),"total": r.get("total"), "facts": r.get("facts"), "scopus_only": r.get("scopus_only") or []}main = sections.get("publications") or {}pubs = got.get("publications") if not isinstance(got.get("publications"), Exception) else Nonereturn {"results": (pubs or {}).get("results", []), "unfiltered": (pubs or {}).get("unfiltered", 0),"total": (pubs or {}).get("total", 0), "person": None, "trace": trace,"scopus_only": main.get("scopus_only", []),"facts": {"kind": "combined", "topic": (plan.keyword_queries or [plan.broad_query or ""])[0],"sections": {k: {"shown": len(v["results"]), "found": v["found"], "facts": v["facts"]}for k, v in sections.items()}},"sections": {k: v for k, v in sections.items() if k != "publications"}}async def _route(pure: PureClient, plan: QueryPlan) -> dict:if plan.intent == "project_search":r = await _retrieve_outputs(pure, plan.model_copy(update={"output_types": [], "open_access_only": False}),246 unmodified lines- Then group the most relevant records by theme or approach in 2-4 short paragraphs or "- " bullets, naming key KU authors and years.- If some records are only loosely related, say so and do not stretch them. If none really answer the question, say that plainlyand suggest a better search (different keywords, removing a year filter, or contacting Nikesh Narayanan, Research Librarian, nikesh.narayanan@ku.ac.ae).- FACTS kind combined (the user asked for several kinds of results): answer in short parts, one per section given(Publications, Theses, Experts), each with its count from FACTS and 2-4 cited examples. Name experts ONLY from theKU EXPERTS SECTION, never from author lists of records (those include external co-authors and former staff).- Numbers: Khazna misses many KU papers, so whenever FACTS give a Scopus/SciVal figure (ku_in_scopus_not_yet_in_khazna,all_ku_publications, ku_wide_scopus_not_yet_in_khazna), state it next to the Khazna figure and say where each comes from.- FACTS kind author_without_profile: the person has no Khazna profile (probably left KU before Khazna started); the144 unmodified linesreturn (f"{who} {state}. I found **{facts['outputs_found']}** of their publications in Khazna as a KU author; "f"they are listed below.")return f"{who} {state}, and I found no Khazna publications listing them as a KU author."if k == "combined":parts = []for name in ("publications", "theses", "experts"):sec = (facts.get("sections") or {}).get(name)if not sec:continuesub = facts_sentence(sec.get("facts")) if sec.get("facts") else ""if name == "experts":sub = f"**{sec['shown']}** current KU researchers work most on this topic; their profiles are listed below."elif not sub:sub = f"{name.capitalize()}: **{sec['found']}** found; the most relevant are listed below."parts.append(sub)return " ".join(parts)if k == "author_without_profile":n_k, n_s = facts.get("outputs_found", 0), facts.get("scopus_only", 0)parts = []37 unmodified linesreturn ""def _sections_context(retrieval: dict, start: int) -> str:"""Theses and experts of a combined question, numbered after the publications so citations stay unique."""out, n = "", startsecs = retrieval.get("sections") or {}if secs.get("theses"):t = secs["theses"]out += f"\n\nTHESES SECTION ({len(t['results'])} shown of {t['found']} found):\n\n{_format_records(t['results'], n + 1)}"n += len(t["results"])if secs.get("experts"):e = secs["experts"]lines = []for i, p in enumerate(e["results"], n + 1):units = ", ".join(o.get("name", "") for o in (p.get("organisations") or [])[:2] if isinstance(o, dict))lines.append(f"[{i}] {p.get('name')} ({units}); {p.get('matching_outputs', 0)} matching KU publications, "f"{p.get('supervised_theses', 0)} supervised theses on the topic")out += "\n\nKU EXPERTS SECTION (current KU researchers ranked by their KU work on the topic):\n" + "\n".join(lines)return outasync def synthesize(question: str, plan: QueryPlan, retrieval: dict, history: list[dict], model: str, top_k: int) -> str:outs = retrieval["results"][:top_k]filters = []17 unmodified lines+ (f"\nFACTS (exact):\n{json.dumps(facts, ensure_ascii=False, indent=1)}\n" if facts else "")+ f"\nRECORDS (top {len(outs)} of {len(retrieval['results'])} after filtering):\n\n{_format_records(outs)}"+ (f"\n\nNOT YET IN KHAZNA (KU papers listed in Scopus only):\n\n{_format_records(extra, len(outs) + 1)}" if extra else "")+ _sections_context(retrieval, len(outs) + len(extra)))if not os.environ.get("OPENAI_API_KEY") and not (model == "claude" and os.environ.get("ANTHROPIC_API_KEY")):return facts_sentence(facts) or f"I found {len(retrieval['results'])} matching Khazna records. The top results are listed below."
app.py+14
pipeline.py+107-1