Spaces:
Sleeping

research-agent / test_agent.py
xstard's picture
Run the research agent with Gemini 3.1 Flash Lite via OpenRouter (#1)
11ead5f
Raw History Blame Contribute Delete
16.3 kB
import unittest
import httpx
from agent import investigate
from web_tools import Page, Hit, Web, WebError, parse_search, parse_page, passages, table_rows
class TestWeb:
def __init__(self, bodies):
self.bodies = bodies
self.searches = []
self.reads = []
def search_web(self, query):
self.searches.append(query)
return [Hit(f"Праця {i}", f"https://source{i}.org/paper", "Короткий опис")
for i in range(len(self.bodies))]
def read_page(self, url):
self.reads.append(url)
i = int(url.split("source")[1].split(".")[0])
if self.bodies[i] is None:
raise WebError("Сторінка недоступна")
return Page(f"Праця {i}", url, self.bodies[i])
class ScriptedModel:
def __init__(self, comparison, same_origin=False):
self.comparison = comparison
self.same_origin = same_origin
self.decisions = []
def decide(self, state, choices):
self.decisions.append(state)
if not state["queries"]:
return {"action": "search_web", "query": "лематизація української", "questions": ["Які метрики?"]}
reads = [c for c in choices if c.startswith("read_page:")]
if reads:
return {"action": reads[-1]}
if "finish" in choices:
return {"action": "finish"}
return {"action": "search_web", "query": f"інше джерело {len(state['queries'])}"}
def extract(self, topic, page, parts, origins):
return {"origin": origins[0]["id"] if origins and self.same_origin else "new",
"notes": [{"passage": 1, "quote": parts[0], "claim": parts[0]}]}
def synthesize(self, topic, notes, independent):
ids = [note["id"] for note in notes]
finding = {"text": "Вимірювання описано в дослідженнях.", "evidence": ids}
return {"summary": finding, "findings": [finding],
"comparison": [{"text": self.comparison, "evidence": ids}],
"limitations": "Потрібні дані про інші корпуси."}
class AgentTests(unittest.TestCase):
def study(self, bodies, comparison="Оцінки узгоджуються.", same_origin=False):
model = ScriptedModel(comparison, same_origin)
web = TestWeb(bodies)
report, trace = investigate("Які результати?", model, web)
return report, trace, web, model
def test_agreement_and_actual_model_actions(self):
report, trace, web, model = self.study(["Перша лабораторія отримала 92%.", "Друга група повідомляє 92%."])
self.assertIn("Оцінки узгоджуються.", report)
self.assertIn("https://source1.org/paper", report)
self.assertIn("https://source0.org/paper", report)
self.assertEqual(web.reads[0], "https://source1.org/paper")
self.assertEqual(len(web.searches), 1)
self.assertIn("Які метрики?", trace)
self.assertIn("92%", trace)
self.assertGreaterEqual(len(model.decisions), 4)
def test_contradiction_with_two_attributions(self):
report, _, _, _ = self.study(["Оцінка A становить 90%.", "Оцінка B становить 94%."],
"Оцінки різняться через умови експерименту.")
line = next(line for line in report.splitlines() if "різняться" in line)
self.assertIn("[1]", line)
self.assertIn("[2]", line)
def test_missing_sources_and_partial_evidence(self):
report, trace, web, _ = self.study([None, None])
self.assertIn("не вдалося", report.lower())
self.assertNotIn("](https:", report)
self.assertIn("Сторінка недоступна", trace)
self.assertEqual(len(web.searches), 3)
report, _, _, _ = self.study([None, "Факти з однієї праці."])
self.assertIn("Незалежного підтвердження бракує", report)
self.assertNotIn("https://source0.org", report)
def test_duplicate_and_attributed_reprint(self):
for bodies, shared in [(["Той самий текст."] * 2, False),
(["Передрук іншою мовою.", "Original study."], True)]:
report, _, _, _ = self.study(bodies, same_origin=shared)
self.assertIn("Незалежного підтвердження бракує", report)
def test_model_cards_from_one_team_do_not_establish_independent_confirmation(self):
web = TestWeb(["Перша оцінка.", "Оцінка іншого корпусу."])
original_read = web.read_page
def same_team(url):
p = original_read(url)
return Page(p.title, "https://huggingface.co/one-team/" + p.url.split("/")[2] + "/blob/" + "a"*40 + "/README.md", p.text)
web.read_page = same_team
report, _, = investigate("Тема", ScriptedModel("Порівняння результатів."), web)
self.assertIn("Незалежного підтвердження бракує", report)
def test_comparison_target_missing_from_evidence_keeps_search_open(self):
model = ScriptedModel("Порівняння.")
web = TestWeb(["Stanza досліджували дві команди.", "Перше оцінювання Stanza."])
report, trace = investigate("Як Stanza та UDPipe оцінюють леми?", model, web)
self.assertEqual(len(web.searches), 3)
self.assertIn("UDPipe", report.split("## Обмеження")[1])
self.assertNotIn("Модель завершила пошук.", trace)
def test_original_sources_for_both_named_systems_are_read_before_stopping(self):
web = TestWeb(["Оцінювання Stanza.", "Вимірювання UDPipe.", "Загальна новина."])
original_search = web.search_web
def search(query):
return [Hit(title, hit.url, hit.snippet) for title, hit in zip(
["Stanza evaluation", "UDPipe models", "News"], original_search(query))]
web.search_web = search
model = ScriptedModel("Дві системи.")
original_decide = model.decide
model.decide = lambda state, choices: {"action": "finish"} if "finish" in choices else original_decide(state, choices)
report, trace = investigate("Як Stanza та UDPipe оцінюють леми?", model, web)
self.assertEqual(set(web.reads), {"https://source0.org/paper", "https://source1.org/paper"})
self.assertIn("Модель завершила пошук.", trace)
self.assertIn("Дві системи.", report)
def test_foreign_evidence_stays_in_trace_and_report_remains_ukrainian(self):
model = ScriptedModel("")
model.synthesize = lambda *args: {}
report, trace = investigate("Тема", model, TestWeb(["An original English sentence.", "Another claim in English."]))
self.assertNotIn("original English sentence", report)
self.assertIn("original English sentence", trace)
self.assertIn("https://source0.org", report)
def test_read_budget_and_empty_topic(self):
_, _, web, _ = self.study([None] * 10)
self.assertEqual(len(web.reads), 6)
self.assertLessEqual(len(web.searches), 3)
web = TestWeb([])
report, _ = investigate(" ", None, web)
self.assertIn("Введіть", report)
self.assertFalse(web.searches)
def test_unknown_evidence_and_injected_link_never_reach_report(self):
model = ScriptedModel("")
bogus = {"text": "[вигадка](https://unread.example)", "evidence": ["E999"]}
model.synthesize = lambda *args: {"summary": bogus, "findings": [bogus],
"comparison": [], "limitations": ""}
report, _ = investigate("Тест", model, TestWeb(["Перевірений факт."]))
self.assertNotIn("unread.example", report)
self.assertIn("Перевірений факт", report)
def test_model_failure_preserves_previous_evidence(self):
for failure in ("read", "decide"):
with self.subTest(failure=failure):
model = ScriptedModel("")
original_extract, original_decide = model.extract, model.decide
def extract(topic, page, parts, origins):
if origins and failure == "read":
raise ValueError("truncated JSON")
return original_extract(topic, page, parts, origins)
def decide(state, choices):
if state["evidence"] and failure == "decide":
raise RuntimeError("context exhausted")
return original_decide(state, choices)
model.extract, model.decide = extract, decide
report, trace = investigate("Тема", model, TestWeb(["Інше джерело.", "Доступний факт."]))
self.assertIn("https://source1.org", report)
self.assertIn("Доступний факт", trace)
self.assertIn("модел", trace.lower())
def test_synthesis_receives_original_work_and_title(self):
model = ScriptedModel("Спільне джерело.", same_origin=True)
captured = []
model.synthesize = lambda topic, notes, independent: captured.extend(notes) or {}
investigate("Тема", model, TestWeb(["Передрук.", "Первинний результат."]))
self.assertEqual([n["origin"] for n in captured], [1, 1])
self.assertEqual(captured[0]["title"], "Праця 1")
def test_repeated_query_leaves_unread_results_to_choose(self):
model = ScriptedModel("Праці погоджуються.")
original = model.decide
def decide(state, choices):
if "finish" in choices:
return {"action": "finish"}
if state["queries"] and "search_web" in choices:
return {"action": "search_web", "query": state["queries"][0]}
return original(state, choices)
model.decide = decide
web = TestWeb(["Перший текст.", "Інший матеріал."])
report, _, = investigate("Тема", model, web)
self.assertEqual(len(web.reads), 2)
self.assertIn("Праці погоджуються.", report)
def test_report_drops_numbers_missing_from_cited_passage(self):
model = ScriptedModel("")
model.synthesize = lambda *args: {"summary": {"text": "Показник склав 99,8%.", "evidence": ["E1"]}}
report, _ = investigate("Тест", model, TestWeb(["На вибірці виміряно 90.2%."]))
self.assertNotIn("99,8", report)
self.assertIn("90.2", report)
def test_extraction_requires_a_verbatim_fragment_and_deduplicates(self):
model = ScriptedModel("")
good = {"passage": 1, "quote": "Порівнювали дві моделі", "claim": "Порівнювали дві моделі."}
model.extract = lambda *args: {"origin": "new", "notes": [good, good,
{"passage": 1, "quote": "Випадкові дані", "claim": "Неіснуюче свідчення."}]}
report, trace = investigate("Тема", model, TestWeb(["Порівнювали дві моделі на корпусі."]))
self.assertNotIn("Неіснуюче", trace)
self.assertIn("E1 •", trace)
self.assertNotIn("E2 •", trace)
self.assertIn("https://source0.org", report)
def test_dataset_version_can_come_from_title_but_a_percentage_cannot(self):
model = ScriptedModel("")
web = TestWeb([""])
web.read_page = lambda url: Page("Benchmark UD v2.17", url, "Lemmas: 98.17")
def extract(*args):
return {"origin": "new", "notes": [
{"passage": 1, "quote": "Lemmas: 98.17", "claim": "На UD v2.17 показник складає 98,17%."},
{"passage": 1, "quote": "Lemmas: 98.17", "claim": "Результат становить 2,17%."}]}
model.extract = extract
model.synthesize = lambda *args: {}
report, trace = investigate("Тема", model, web)
self.assertIn("98,17%", report)
self.assertNotIn("становить 2,17%", trace)
class WebTests(unittest.TestCase):
def test_current_model_card_uses_the_published_revision(self):
requests = []
sha = "a" * 40
def transport(req):
requests.append(str(req.url))
return httpx.Response(200, headers={"x-repo-commit": sha}, text="---\ntags: []\n---\n# Study\nCurrent result: 98.17.")
with httpx.Client(transport=httpx.MockTransport(transport)) as client:
page = Web(client).read_page("https://huggingface.co/institute/benchmark")
self.assertEqual(requests, ["https://huggingface.co/institute/benchmark/raw/main/README.md"])
self.assertIn(sha, page.url)
self.assertIn("98.17", page.text)
def test_real_protocol_formats(self):
text = "Title: One\nURL: https://one.org/a\nPublished: N/A\nHighlights:\nA snippet.\n\n---\n\nTitle: Two\nURL: https://two.org/\nHighlights:\nB."
hits = parse_search(text)
self.assertEqual(len(hits), 2)
self.assertEqual(hits[0].snippet, "A snippet.")
page = parse_page("# One\nURL: https://one.org/a\n\nThe body.", hits[0].url)
self.assertEqual(page.text, "The body.")
with self.assertRaises(WebError):
parse_page("Failed to fetch page", hits[0].url)
def test_long_table_keeps_matching_row(self):
body = "Intro\n| Language | Lemmas |\n" + "\n".join(
f"| example{i} | 10 |" for i in range(800)) + "\n| Ukrainian | 96.72 |"
selected = passages(body, "Ukrainian lemma evaluation")
self.assertTrue(any("Ukrainian | 96.72" in s for s in selected))
self.assertTrue(any("Lemmas" in s for s in selected))
def test_specific_language_row_survives_generic_methodology(self):
intro = "\n\n".join(f"Evaluation note {i}: language, lemmas, dataset, treebanks, benchmarks. " * 4
for i in range(14))
table = "| Language | Lemmas |\n" + "\n".join(f"| name{i} | 75 |" for i in range(150))
body = intro + "\n\n" + table + "\n| Ukrainian | 96.72 |"
selected = passages(body, "methodology evaluation language lemmas dataset treebanks benchmarks Ukrainian")
self.assertTrue(any("| Ukrainian | 96.72 |" in p for p in selected))
def test_distant_table_row_has_the_correct_metric_labels(self):
header = "| Language | Corpus | Lemmas | LAS |"
row = "| Ukrainian | IU | 96.72 | 85.87 |"
body = header + "\n| --- | --- | --- | --- |\n| Dutch | Alpino | 97.1 | 88.2 |\n" + row
self.assertEqual(table_rows(body, [row]), [{"Language": "Ukrainian", "Corpus": "IU",
"Lemmas": "96.72", "LAS": "85.87"}])
class PlannerTests(unittest.TestCase):
def test_truncated_first_plan_retries_with_simple_schema(self):
from unittest.mock import patch
from model import OpenRouterModel
with patch.dict("os.environ", {"OPENROUTER_API_KEY": "test-key"}):
model = OpenRouterModel(None)
attempts = []
def ask(instruction, data, schema, tokens):
attempts.append(schema)
if len(attempts) == 1:
raise ValueError("truncated")
return {"action": "search_web", "query": "Ukrainian lemmas", "questions": ["Які метрики?"]}
model._ask = ask
result = model.decide({"queries": []}, ["search_web"])
self.assertEqual(result["query"], "Ukrainian lemmas")
self.assertEqual(len(attempts), 2)
self.assertEqual(attempts[-1]["properties"]["questions"]["minItems"], 1)
if __name__ == "__main__":
unittest.main()