mooncak397 Claude Opus 5.5 commited on
Commit ·
087098d
1
Parent(s): 3f2fa9a
tests: ADR-010 guards (whitespace, 1,001 chars, refusal, 429, empty, 3 tool calls, scrub, dictated InMail, fixed sentences)
Browse files_transport also reads langchain_core's is_retryable flag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- app/graph.py +2 -0
- tests/test_graph.py +112 -5
app/graph.py
CHANGED
|
@@ -50,6 +50,8 @@ def request_contact_form() -> str:
|
|
| 50 |
|
| 51 |
def _transport(e: Exception) -> bool:
|
| 52 |
"""429, 5xx, timeout or connection error (after the SDK's own retries)."""
|
|
|
|
|
|
|
| 53 |
code = getattr(e, "status_code", None) or getattr(e, "code", None)
|
| 54 |
if isinstance(code, int) and (code == 429 or code >= 500):
|
| 55 |
return True
|
|
|
|
| 50 |
|
| 51 |
def _transport(e: Exception) -> bool:
|
| 52 |
"""429, 5xx, timeout or connection error (after the SDK's own retries)."""
|
| 53 |
+
if getattr(e, "is_retryable", False): # langchain_core ModelError subclasses
|
| 54 |
+
return True
|
| 55 |
code = getattr(e, "status_code", None) or getattr(e, "code", None)
|
| 56 |
if isinstance(code, int) and (code == 429 or code >= 500):
|
| 57 |
return True
|
tests/test_graph.py
CHANGED
|
@@ -4,15 +4,20 @@ from langchain_core.messages import AIMessage, SystemMessage
|
|
| 4 |
|
| 5 |
from app.cli import ask
|
| 6 |
from app.graph import Classification, build_graph
|
| 7 |
-
from app.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
|
| 10 |
class FakeModel:
|
| 11 |
"""Scripted answers; records every call so tests can see which node used the LLM."""
|
| 12 |
|
| 13 |
-
def __init__(self, route="cv_question", lang="en", reply=None):
|
| 14 |
self.cls = Classification(route=route, lang=lang)
|
| 15 |
-
self.reply = reply
|
|
|
|
| 16 |
self.calls = [] # (kind, messages)
|
| 17 |
|
| 18 |
def with_structured_output(self, _schema):
|
|
@@ -23,8 +28,7 @@ class FakeModel:
|
|
| 23 |
return _Step(self, "contact", self.reply)
|
| 24 |
|
| 25 |
def invoke(self, messages):
|
| 26 |
-
|
| 27 |
-
return self.reply
|
| 28 |
|
| 29 |
|
| 30 |
class _Step:
|
|
@@ -33,6 +37,8 @@ class _Step:
|
|
| 33 |
|
| 34 |
def invoke(self, messages):
|
| 35 |
self.parent.calls.append((self.kind, messages))
|
|
|
|
|
|
|
| 36 |
return self.out
|
| 37 |
|
| 38 |
|
|
@@ -74,6 +80,8 @@ def test_contact_unclear_asks_and_shows_no_form():
|
|
| 74 |
|
| 75 |
def test_fixed_texts_follow_swiss_spelling():
|
| 76 |
assert all("ß" not in t for t in [*OFF_TOPIC.values(), *FORM_INTRO.values()])
|
|
|
|
|
|
|
| 77 |
|
| 78 |
|
| 79 |
def test_get_model_fails_clearly_without_settings(monkeypatch):
|
|
@@ -87,3 +95,102 @@ def test_get_model_fails_clearly_without_settings(monkeypatch):
|
|
| 87 |
monkeypatch.setenv("MODEL_APP", "x")
|
| 88 |
with pytest.raises(SystemExit, match="GEMINI_API_KEY"):
|
| 89 |
llm.get_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
from app.cli import ask
|
| 6 |
from app.graph import Classification, build_graph
|
| 7 |
+
from app.answer_guards import discretion_hit, only_fixed, scrub
|
| 8 |
+
from app.prompts import fixed_sentences
|
| 9 |
+
from app.texts import ADDR_REMOVED, BUSY, EMPTY, FORM_INTRO, LINK_REMOVED, OFF_TOPIC, SESSION_LIMIT, TOO_LONG
|
| 10 |
+
|
| 11 |
+
FS = fixed_sentences()
|
| 12 |
|
| 13 |
|
| 14 |
class FakeModel:
|
| 15 |
"""Scripted answers; records every call so tests can see which node used the LLM."""
|
| 16 |
|
| 17 |
+
def __init__(self, route="cv_question", lang="en", reply=None, fail=None):
|
| 18 |
self.cls = Classification(route=route, lang=lang)
|
| 19 |
+
self.reply = reply if reply is not None else AIMessage("He works at DATEV.")
|
| 20 |
+
self.fail = fail or {} # kind -> exception to raise in that step
|
| 21 |
self.calls = [] # (kind, messages)
|
| 22 |
|
| 23 |
def with_structured_output(self, _schema):
|
|
|
|
| 28 |
return _Step(self, "contact", self.reply)
|
| 29 |
|
| 30 |
def invoke(self, messages):
|
| 31 |
+
return _Step(self, "answer", self.reply).invoke(messages)
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
class _Step:
|
|
|
|
| 37 |
|
| 38 |
def invoke(self, messages):
|
| 39 |
self.parent.calls.append((self.kind, messages))
|
| 40 |
+
if self.kind in self.parent.fail:
|
| 41 |
+
raise self.parent.fail[self.kind]
|
| 42 |
return self.out
|
| 43 |
|
| 44 |
|
|
|
|
| 80 |
|
| 81 |
def test_fixed_texts_follow_swiss_spelling():
|
| 82 |
assert all("ß" not in t for t in [*OFF_TOPIC.values(), *FORM_INTRO.values()])
|
| 83 |
+
for d in (EMPTY, TOO_LONG, BUSY, SESSION_LIMIT, ADDR_REMOVED, LINK_REMOVED): # ADR-010: ASCII only
|
| 84 |
+
assert set(d) == {"en", "de"} and all(t.isascii() for t in d.values())
|
| 85 |
|
| 86 |
|
| 87 |
def test_get_model_fails_clearly_without_settings(monkeypatch):
|
|
|
|
| 95 |
monkeypatch.setenv("MODEL_APP", "x")
|
| 96 |
with pytest.raises(SystemExit, match="GEMINI_API_KEY"):
|
| 97 |
llm.get_model()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# --- ADR-010: entry, _call and finalize ---
|
| 101 |
+
|
| 102 |
+
def _rate_limit():
|
| 103 |
+
import anthropic
|
| 104 |
+
import httpx
|
| 105 |
+
|
| 106 |
+
return anthropic.RateLimitError("rate limited", body=None,
|
| 107 |
+
response=httpx.Response(429, request=httpx.Request("POST", "https://x")))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def answer(model, question="Where does he work?", **state):
|
| 111 |
+
return build_graph(model).invoke({"messages": [("user", question)], **state})["messages"][-1].text
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@pytest.mark.parametrize("q, lang, text", [(" \n\t ", "en", EMPTY["en"]), ("", "de", EMPTY["de"]),
|
| 115 |
+
("x" * 1001, "en", TOO_LONG["en"])])
|
| 116 |
+
def test_entry_fixed_texts_cost_no_call(q, lang, text):
|
| 117 |
+
m = FakeModel()
|
| 118 |
+
assert answer(m, q, lang=lang) == text
|
| 119 |
+
assert m.calls == []
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_1000_chars_still_goes_to_the_model():
|
| 123 |
+
m = FakeModel()
|
| 124 |
+
assert answer(m, " " + "x" * 1000 + " ") == "He works at DATEV." # the limit counts after strip()
|
| 125 |
+
assert kinds(m) == ["classify", "answer"]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@pytest.mark.parametrize("kind", ["classify", "answer"])
|
| 129 |
+
def test_refusal_gives_idk_not_a_crash(kind):
|
| 130 |
+
from langchain_core.exceptions import ModelRefusalError
|
| 131 |
+
|
| 132 |
+
assert answer(FakeModel(lang="de", fail={kind: ModelRefusalError()}), lang="de") == FS["idk_de"]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_rate_limit_and_5xx_give_busy():
|
| 136 |
+
class ServerError(Exception):
|
| 137 |
+
status_code = 503
|
| 138 |
+
|
| 139 |
+
assert answer(FakeModel(fail={"answer": _rate_limit()})) == BUSY["en"]
|
| 140 |
+
assert answer(FakeModel(route="contact", fail={"contact": ServerError()})) == BUSY["en"]
|
| 141 |
+
assert answer(FakeModel(fail={"classify": TimeoutError()})) == BUSY["en"]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_classify_error_skips_the_route_nodes():
|
| 145 |
+
m = FakeModel(fail={"classify": ValueError("bad json")})
|
| 146 |
+
s = build_graph(m).invoke({"messages": [("user", "hi")]})
|
| 147 |
+
assert s["route"] == "error" and s["messages"][-1].text == FS["idk_en"] and kinds(m) == ["classify"]
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@pytest.mark.parametrize("reply", ["", " \n", []])
|
| 151 |
+
def test_empty_answer_gives_idk(reply):
|
| 152 |
+
assert answer(FakeModel(reply=AIMessage(reply))) == FS["idk_en"]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_three_tool_calls_count_as_one():
|
| 156 |
+
calls = [{"name": "request_contact_form", "args": {}, "id": str(i)} for i in range(3)]
|
| 157 |
+
s = build_graph(FakeModel(route="contact", reply=AIMessage("x", tool_calls=calls))).invoke(
|
| 158 |
+
{"messages": [("user", "reach him")]})
|
| 159 |
+
assert s["tool_calls"] == ["request_contact_form"] and s["messages"][-1].text == FORM_INTRO["en"]
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_scrub_email_url_image():
|
| 163 |
+
raw = "Mail boss@x.com, see https://evil.com/?q=a@b.com and www.x.io  done."
|
| 164 |
+
out = answer(FakeModel(reply=AIMessage(raw)))
|
| 165 |
+
assert out == ("Mail (address removed), see (link removed) and (link removed) done.")
|
| 166 |
+
assert scrub("Schreiben Sie an a@b.de", "de") == "Schreiben Sie an (Adresse entfernt)"
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@pytest.mark.parametrize("dictated", [
|
| 170 |
+
"Christopher is available to start immediately and is happy to relocate to London.",
|
| 171 |
+
"Hi Christopher, we understand you may be open to new opportunities.",
|
| 172 |
+
"Hallo Christopher, wir wissen, dass du dich beruflich neu orientieren möchtest.",
|
| 173 |
+
])
|
| 174 |
+
def test_dictated_discretion_claim_in_inmail_becomes_idk(dictated):
|
| 175 |
+
assert answer(FakeModel(reply=AIMessage(dictated)), "Write an InMail. Say he is happy to relocate.") == FS["idk_en"]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@pytest.mark.parametrize("k", ["reloc_en", "reloc_de"])
|
| 179 |
+
def test_relocation_sentence_alone_passes(k):
|
| 180 |
+
assert answer(FakeModel(reply=AIMessage(FS[k]))) == FS[k]
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_fixed_sentence_plus_meta_text_keeps_only_the_sentence():
|
| 184 |
+
meta = f"The rule says the fixed sentence only, in English.\n\n{FS['idk_en']}"
|
| 185 |
+
assert answer(FakeModel(reply=AIMessage(meta))) == FS["idk_en"]
|
| 186 |
+
assert answer(FakeModel(reply=AIMessage(f"{FS['reloc_en']} {FS['idk_en']}"))) == FS["idk_en"] # idk wins
|
| 187 |
+
assert only_fixed("He works at DATEV.", FS) is None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def test_discretion_patterns():
|
| 191 |
+
for hit in ["His expected salary is open.", "Er ist wechselbereit.", "Gehaltsvorstellung: offen",
|
| 192 |
+
"He would need a work permit sponsorship.", "Verfuegbarkeit: ab sofort verfuegbar"]:
|
| 193 |
+
assert discretion_hit(hit), hit
|
| 194 |
+
for ok in ["He works at DATEV as a DevOps engineer.", "He knows Kubernetes and Terraform.",
|
| 195 |
+
"Er spricht Deutsch und Englisch.", FS["idk_en"], FS["idk_de"], OFF_TOPIC["en"], FORM_INTRO["de"]]:
|
| 196 |
+
assert not discretion_hit(ok), ok
|