Spaces:
Sleeping
Sleeping
Download agent.py from xstard/research-agent: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/xstard/research-agent/resolve/main/agent.py
- Command line
-
hf download hf://spaces/xstard/research-agent/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/xstard/research-agent/resolve/main/agent.py
13.2 kB
| """A bounded tool loop. Only the application assigns source IDs and builds links.""" | |
| import html | |
| import re | |
| import unicodedata | |
| from urllib.parse import quote | |
| from web_tools import WebError, passages | |
| MAX_SEARCHES = 3 | |
| MAX_READS = 6 | |
| def literal(value): | |
| value = re.sub(r"https?://\S+|www\.\S+", "", str(value), flags=re.I) | |
| return re.sub(r"([\\\x60*_[\]{}()#!|>~])", r"\\\1", html.escape(" ".join(value.split()))) | |
| def source_link(source, label): | |
| url = quote(source["url"], safe=":/?#[]@!$&'*+,;=%-._~") | |
| return f"[{label}](<{url}>)" | |
| def fingerprints(body): | |
| words = re.findall(r"\w+", body.casefold()) | |
| return {tuple(words[i:i+5]) for i in range(max(1, len(words)-4))} | |
| def card_publisher(url): | |
| match = re.fullmatch(r"https://huggingface\.co/([\w.-]+)/[\w.-]+(?:/blob/[a-f0-9]{40}/README\.md)?/?", url) | |
| return match[1].casefold() if match else "" | |
| def numbers_supported(statement, text, title=""): | |
| def values(value): | |
| return {s.replace(",", ".") for s in re.findall(r"\d+(?:[.,]\d+)*", value)} | |
| percentages = {s.replace(",", ".") for s in re.findall(r"(\d+(?:[.,]\d+)*)\s*[%%]", statement)} | |
| return percentages <= values(text) and values(statement) <= values(text + " " + title) | |
| def quoted_passage(entry, parts): | |
| def normalize(text): | |
| return " ".join(unicodedata.normalize("NFKC", text).casefold().split()) | |
| quote = entry.get("quote") | |
| if not isinstance(quote, str) or not quote.strip(): | |
| return "" | |
| needle = normalize(quote) | |
| index = entry.get("passage") | |
| preferred = parts[index-1:index] if isinstance(index, int) and 1 <= index <= len(parts) else [] | |
| for part in [*preferred, *parts]: | |
| body = normalize(part) | |
| if len(needle) >= min(12, len(body)) and needle in body: | |
| return part | |
| return "" | |
| def missing_targets(targets, notes): | |
| available = " ".join(n["claim"] + " " + n["quote"] + " " + n["title"] for n in notes).casefold() | |
| return [name for name in targets if name.casefold() not in available] | |
| def render_report(topic, notes, sources, answer, reason): | |
| lines = [f"# {literal(topic)}"] | |
| by_id = {n["id"]: n for n in notes} | |
| by_source = {s["id"]: s for s in sources} | |
| used = {} | |
| def cited(item, comparison=False): | |
| if not isinstance(item, dict) or not isinstance(item.get("text"), str): | |
| return "" | |
| if not re.search(r"[А-ЩЬЮЯҐЄІЇа-щьюяґєії]", item["text"]): | |
| return "" | |
| ids = item.get("evidence") | |
| if not isinstance(ids, list) or not ids or any(not isinstance(i, str) or i not in by_id for i in ids): | |
| return "" | |
| if not numbers_supported(item["text"], " ".join(by_id[i]["excerpt"] for i in ids), | |
| " ".join(by_id[i]["title"] for i in ids)): | |
| return "" | |
| sids = list(dict.fromkeys(by_id[i]["source"] for i in ids)) | |
| if comparison and len({by_source[s]["origin"] for s in sids} - {"unknown"}) < 2: | |
| return "" | |
| labels = [] | |
| for sid in sids: | |
| number = used.setdefault(sid, len(used) + 1) | |
| labels.append(source_link(by_source[sid], f"[{number}]")) | |
| return literal(item["text"]) + " " + " ".join(labels) | |
| def cited_list(key, comparison=False): | |
| items = answer.get(key, []) | |
| if not isinstance(items, list): | |
| return [] | |
| return [line for item in items if (line := cited(item, comparison))] | |
| fallback = [] | |
| for n in notes: | |
| text = n["claim"] if re.search(r"[А-ЩЬЮЯҐЄІЇа-щьюяґєії]", n["claim"]) else "Оригінальний фрагмент наведено в журналі." | |
| item = {"text": text, "evidence": [n["id"]]} | |
| if not any(x["text"] == text and by_id[x["evidence"][0]]["source"] == n["source"] for x in fallback): | |
| fallback.append(item) | |
| summary = cited(answer.get("summary")) or cited(fallback[0]) | |
| findings = cited_list("findings") or [cited(item) for item in fallback] | |
| comparisons = cited_list("comparison", True) | |
| lines.extend(["## Коротка відповідь", summary, "## Основні висновки", | |
| "\n".join(f"- {line}" for line in findings), "## Порівняння джерел"]) | |
| if comparisons: | |
| lines.extend(comparisons) | |
| elif len({s["origin"] for s in sources} - {"unknown"}) < 2: | |
| lines.append("Незалежного підтвердження бракує.") | |
| else: | |
| lines.append("Автоматичне зіставлення не дало перевіреного спільного висновку.") | |
| lines.extend(cited(item) for item in fallback if by_id[item["evidence"][0]]["source"] not in used) | |
| lines.extend(["## Обмеження", reason]) | |
| limits = answer.get("limitations") | |
| if isinstance(limits, str) and re.search(r"[А-ЩЬЮЯҐЄІЇа-щьюяґєії]", limits): | |
| lines.append(literal(limits)) | |
| lines.append("## Джерела") | |
| lines.append("\n".join(f"{number}. {source_link(by_source[sid], literal(by_source[sid]['title']))}" | |
| for sid, number in used.items())) | |
| return "\n\n".join(lines) | |
| def investigate(topic, model, web, progress=lambda message: None): | |
| topic = (topic or "").strip() | |
| if not topic: | |
| return "Введіть тему або дослідницьке питання.", "" | |
| if len(topic) > 1000: | |
| return "Скоротіть тему до 1000 символів.", "" | |
| hits, sources, notes, trace, queries = {}, [], [], [], [] | |
| attempted, seen_urls, signatures = set(), set(), [] | |
| questions = [] | |
| named_pairs = re.findall(r"\b([A-Z][A-Za-z0-9+.-]*)\s+(?:та|і|й|чи|vs\.?|and)\s+([A-Z][A-Za-z0-9+.-]*)", topic) | |
| targets = list(dict.fromkeys(name.rstrip(".") for pair in named_pairs for name in pair)) | |
| reason = "Досягнуто меж доступного пошуку й читання." | |
| def log(message): | |
| trace.append(message) | |
| progress(message) | |
| invalid = 0 | |
| while len(attempted) < MAX_READS: | |
| pending = {k: v for k, v in hits.items() if k not in attempted and v.url not in seen_urls} | |
| known_teams = {s["publisher"] for s in sources if s["publisher"]} | |
| if known_teams: | |
| different = {k: v for k, v in pending.items() if card_publisher(v.url) not in known_teams} | |
| if different: | |
| pending = different | |
| missing = missing_targets(targets, notes) | |
| directly_relevant = {k: v for k, v in pending.items() if any(name.casefold() in v.title.casefold() for name in missing)} | |
| if directly_relevant: | |
| pending = directly_relevant | |
| choices = [f"read_page:{k}" for k in pending] | |
| if len(queries) < MAX_SEARCHES and (not invalid or not choices): | |
| choices.append("search_web") | |
| independent = len({s["origin"] for s in sources} - {"unknown"}) | |
| if not choices: | |
| break | |
| if independent >= 2 and not missing: | |
| choices.append("finish") | |
| state = {"topic": topic, "questions": questions, "queries": list(queries), "needs_evidence_for": missing, | |
| "results": [{"id": k, "title": v.title, "url": v.url, "snippet": v.snippet} for k, v in pending.items()], | |
| "read_sources": [{"title": s["title"], "url": s["url"]} for s in sources], | |
| "evidence": [n["claim"] for n in notes], "recent": trace[-2:]} | |
| try: | |
| decision = model.decide(state, choices) | |
| except (ValueError, RuntimeError): | |
| reason = "Помилка моделі під час вибору наступної дії. Наведено доступні свідчення." | |
| log(reason) | |
| break | |
| action = decision.get("action", "") | |
| if not questions: | |
| questions = [q.strip() for q in decision.get("questions", []) if isinstance(q, str) and q.strip()][:3] | |
| if questions: | |
| log("Питання дослідження • " + " / ".join(questions)) | |
| query = str(decision.get("query", "")).strip()[:350] | |
| if action not in choices or (action == "search_web" and (not query or query.casefold() in {q.casefold() for q in queries})): | |
| invalid += 1 | |
| log("Повторний запит або недоступна дія. Потрібен інший результат чи новий запит.") | |
| if invalid >= 2: | |
| reason = "Модель не запропонувала подальшої допустимої дії." | |
| break | |
| continue | |
| invalid = 0 | |
| if action == "finish": | |
| reason = "Модель вирішила, що зібраних матеріалів достатньо для підсумку." | |
| log("Модель завершила пошук.") | |
| break | |
| if action == "search_web": | |
| queries.append(query) | |
| log(f"search_web({query})") | |
| try: | |
| results = web.search_web(query) | |
| known = {v.url for v in hits.values()} | |
| for hit in results: | |
| if hit.url not in known: | |
| hits[len(hits)+1] = hit | |
| known.add(hit.url) | |
| log(f"Результатів пошуку: {len(results)}.") | |
| except WebError as error: | |
| log(str(error)) | |
| continue | |
| index = int(action.split(":")[1]) | |
| hit = hits[index] | |
| attempted.add(index) | |
| log(f"read_page({hit.url})") | |
| try: | |
| page = web.read_page(hit.url) | |
| except WebError as error: | |
| log(str(error)) | |
| continue | |
| if page.url in seen_urls: | |
| log("Цю сторінку вже прочитано.") | |
| continue | |
| seen_urls.add(page.url) | |
| signature = fingerprints(page.text) | |
| if any(len(signature & other) / max(1, len(signature | other)) >= 0.8 for other in signatures): | |
| log("Повтор уже прочитаного тексту.") | |
| continue | |
| parts = passages(page.text, " ".join([topic, *questions, *queries])) | |
| origins = [{"id": s["id"], "title": s["title"], "url": s["url"]} for s in sources] | |
| try: | |
| extracted = model.extract(topic, page, parts, origins) | |
| except (ValueError, RuntimeError): | |
| log("Моделі не вдалося опрацювати фрагменти цієї сторінки.") | |
| continue | |
| sid = len(sources) + 1 | |
| found = [] | |
| for entry in extracted.get("notes", [])[:3]: | |
| excerpt, claim = quoted_passage(entry, parts), entry.get("claim") | |
| if (excerpt and isinstance(claim, str) and claim.strip() and numbers_supported(claim, entry["quote"], page.title) | |
| and not any(n["claim"].casefold() == claim.strip().casefold() for n in found)): | |
| found.append({"id": f"E{len(notes)+len(found)+1}", "source": sid, "claim": claim.strip(), | |
| "excerpt": excerpt, "quote": entry["quote"]}) | |
| if not found: | |
| log("Релевантного фрагмента не знайдено.") | |
| continue | |
| signatures.append(signature) | |
| origin = extracted.get("origin") | |
| if origin == "new": | |
| group = sid | |
| else: | |
| group = next((s["origin"] for s in sources if str(s["id"]) == str(origin)), "unknown") | |
| publisher = card_publisher(page.url) | |
| if publisher in known_teams: | |
| group = next(s["origin"] for s in sources if s["publisher"] == publisher) | |
| sources.append({"id": sid, "url": page.url, "title": page.title, "origin": group, "publisher": publisher}) | |
| for note in found: | |
| note.update(origin=group, title=page.title) | |
| notes.extend(found) | |
| log("Збережено свідчень: " + str(len(found)) + ". " + found[0]["claim"]) | |
| counts = f"Виконано пошуків: {len(queries)} з {MAX_SEARCHES}. Відкриттів: {len(attempted)} з {MAX_READS}." | |
| if still_missing := missing_targets(targets, notes): | |
| reason += " Бракує підтверджених матеріалів про " + ", ".join(map(literal, still_missing)) + "." | |
| log(counts) | |
| if not notes: | |
| return (f"# {literal(topic)}\n\nНе вдалося зібрати перевірені свідчення для відповіді. " | |
| f"{reason} {counts} Подробиці спроб наведено в журналі.", "\n\n".join(trace)) | |
| log("Формування звіту та перевірка посилань…") | |
| independent = len({s["origin"] for s in sources} - {"unknown"}) | |
| answer = model.synthesize(topic, notes, independent) | |
| for n in notes: | |
| source = sources[n["source"]-1] | |
| trace.append(f"{n['id']} • {n['claim']}\n{source['title']} — {source['url']}\n«{n['quote']}»") | |
| return render_report(topic, notes, sources, answer, f"{reason} {counts}"), "\n\n".join(trace) | |