mooncak397 Claude Opus 5.5 commited on
Commit
3f2fa9a
·
1 Parent(s): 7417677

graph: entry and finalize nodes, _call error wrapper, one tool call max (ADR-010)

Browse files

The eval provider treats the BUSY reply as a rate-limit error, so the Gemini
retry loop still works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Files changed (2) hide show
  1. app/graph.py +87 -21
  2. evals/provider.py +5 -1
app/graph.py CHANGED
@@ -1,5 +1,7 @@
1
- """M2: LangGraph router. classify -> answer_cv | contact | off_topic (plan section 2).
 
2
  The model is injected, so tests can pass a fake one."""
 
3
  from typing import Literal
4
 
5
  from langchain_core.messages import AIMessage, SystemMessage
@@ -7,8 +9,12 @@ from langchain_core.tools import tool
7
  from langgraph.graph import END, START, MessagesState, StateGraph
8
  from pydantic import BaseModel
9
 
10
- from app.prompts import system_prompt
11
- from app.texts import FORM_INTRO, OFF_TOPIC
 
 
 
 
12
 
13
  CLASSIFY_PROMPT = """Classify the user's latest message for an assistant that answers questions about a job candidate.
14
  route:
@@ -32,6 +38,8 @@ class State(MessagesState):
32
  lang: str
33
  show_form: bool
34
  tool_calls: list[str] # names only: the tool has no arguments
 
 
35
 
36
 
37
  @tool
@@ -40,37 +48,95 @@ def request_contact_form() -> str:
40
  return "contact form shown"
41
 
42
 
 
 
 
 
 
 
 
 
 
 
43
  def build_graph(model):
44
  prompt = system_prompt()
 
 
45
  classifier = model.with_structured_output(Classification)
46
  contact_model = model.bind_tools([request_contact_form]) # the only tool, only in this node
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  def classify(state: State):
49
- c = classifier.invoke([SystemMessage(CLASSIFY_PROMPT), *state["messages"]])
50
- return {"route": c.route, "lang": c.lang, "show_form": False, "tool_calls": []}
 
 
51
 
52
  def answer_cv(state: State):
53
- return {"messages": [model.invoke([SystemMessage(prompt), *state["messages"]])]}
 
54
 
55
  def contact(state: State):
56
- ai = contact_model.invoke([SystemMessage(CONTACT_PROMPT), *state["messages"]])
57
- names = [c["name"] for c in ai.tool_calls]
58
- if "request_contact_form" in names:
59
- # fixed text: the model never writes the reply when the form opens
60
- return {"messages": [AIMessage(FORM_INTRO[state["lang"]])], "show_form": True, "tool_calls": names}
61
- return {"messages": [AIMessage(ai.text)], "tool_calls": names}
 
 
62
 
63
  def off_topic(state: State):
64
- return {"messages": [AIMessage(OFF_TOPIC[state["lang"]])]} # no LLM call
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
  g = StateGraph(State)
67
- g.add_node("classify", classify)
68
- g.add_node("answer_cv", answer_cv)
69
- g.add_node("contact", contact)
70
- g.add_node("off_topic", off_topic)
71
- g.add_edge(START, "classify")
72
- g.add_conditional_edges("classify", lambda s: s["route"],
73
- {"cv_question": "answer_cv", "contact": "contact", "off_topic": "off_topic"})
 
 
74
  for n in ("answer_cv", "contact", "off_topic"):
75
- g.add_edge(n, END)
 
76
  return g.compile()
 
1
+ """LangGraph router (plan section 2, ADR-010):
2
+ entry -> classify -> answer_cv | contact | off_topic -> finalize. entry and finalize make no model call.
3
  The model is injected, so tests can pass a fake one."""
4
+ import logging
5
  from typing import Literal
6
 
7
  from langchain_core.messages import AIMessage, SystemMessage
 
9
  from langgraph.graph import END, START, MessagesState, StateGraph
10
  from pydantic import BaseModel
11
 
12
+ from app.answer_guards import discretion_hit, only_fixed, scrub
13
+ from app.prompts import fixed_sentences, system_prompt
14
+ from app.texts import BUSY, EMPTY, FORM_INTRO, OFF_TOPIC, TOO_LONG
15
+
16
+ log = logging.getLogger(__name__)
17
+ MAX_CHARS = 1000
18
 
19
  CLASSIFY_PROMPT = """Classify the user's latest message for an assistant that answers questions about a job candidate.
20
  route:
 
38
  lang: str
39
  show_form: bool
40
  tool_calls: list[str] # names only: the tool has no arguments
41
+ reply: str # the node's reply; finalize checks it and appends the one AIMessage
42
+ fixed: bool # True = a code-chosen text, finalize returns it unchanged
43
 
44
 
45
  @tool
 
48
  return "contact form shown"
49
 
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
56
+ name, msg = type(e).__name__, str(e)
57
+ return (any(k in name for k in ("Timeout", "Connection", "RateLimit", "ResourceExhausted", "ServiceUnavailable"))
58
+ or "429" in msg or "RESOURCE_EXHAUSTED" in msg)
59
+
60
+
61
  def build_graph(model):
62
  prompt = system_prompt()
63
+ fixed = fixed_sentences()
64
+ idk = {"en": fixed["idk_en"], "de": fixed["idk_de"]}
65
  classifier = model.with_structured_output(Classification)
66
  contact_model = model.bind_tools([request_contact_form]) # the only tool, only in this node
67
 
68
+ def _call(fn, lang):
69
+ """One model call. Returns (result, None), or (None, fixed reply) on any error: never raises."""
70
+ try:
71
+ out = fn()
72
+ if out is None: # structured output that did not parse
73
+ raise ValueError("no parsed output")
74
+ return out, None
75
+ except Exception as e: # refusal, parse error, transport: the user gets a fixed text, not a 500
76
+ busy = _transport(e)
77
+ log.warning("model_error class=%s busy=%s", type(e).__name__, busy)
78
+ return None, (BUSY if busy else idk)[lang]
79
+
80
+ def entry(state: State):
81
+ lang = state.get("lang") or "en" # the session's last lang; no model call to detect it
82
+ out = {"route": "entry", "lang": lang, "show_form": False, "tool_calls": [], "reply": "", "fixed": False}
83
+ text = state["messages"][-1].text.strip()
84
+ if not text:
85
+ return {**out, "reply": EMPTY[lang], "fixed": True}
86
+ if len(text) > MAX_CHARS:
87
+ return {**out, "reply": TOO_LONG[lang], "fixed": True}
88
+ return out
89
+
90
  def classify(state: State):
91
+ c, err = _call(lambda: classifier.invoke([SystemMessage(CLASSIFY_PROMPT), *state["messages"]]), state["lang"])
92
+ if err:
93
+ return {"route": "error", "reply": err, "fixed": True}
94
+ return {"route": c.route, "lang": c.lang}
95
 
96
  def answer_cv(state: State):
97
+ ai, err = _call(lambda: model.invoke([SystemMessage(prompt), *state["messages"]]), state["lang"])
98
+ return {"reply": err, "fixed": True} if err else {"reply": ai.text}
99
 
100
  def contact(state: State):
101
+ ai, err = _call(lambda: contact_model.invoke([SystemMessage(CONTACT_PROMPT), *state["messages"]]), state["lang"])
102
+ if err:
103
+ return {"reply": err, "fixed": True}
104
+ if any(c["name"] == "request_contact_form" for c in ai.tool_calls):
105
+ # one tool call at most; the model never writes the reply when the form opens
106
+ return {"reply": FORM_INTRO[state["lang"]], "fixed": True, "show_form": True,
107
+ "tool_calls": ["request_contact_form"]}
108
+ return {"reply": ai.text}
109
 
110
  def off_topic(state: State):
111
+ return {"reply": OFF_TOPIC[state["lang"]], "fixed": True} # no LLM call
112
+
113
+ def finalize(state: State):
114
+ lang, text, guard = state["lang"], state["reply"], None
115
+ if not state["fixed"]:
116
+ text = text.strip()
117
+ if not text:
118
+ text, guard = idk[lang], "empty"
119
+ elif s := only_fixed(text, fixed):
120
+ text, guard = s, ("fixed_sentence" if s != text else None)
121
+ elif discretion_hit(text):
122
+ text, guard = idk[lang], "discretion"
123
+ elif (s := scrub(text, lang)) != text:
124
+ text, guard = s, "scrub"
125
+ if guard:
126
+ log.info("guard=%s route=%s lang=%s", guard, state["route"], lang)
127
+ return {"messages": [AIMessage(text)], "reply": text}
128
 
129
  g = StateGraph(State)
130
+ for name, fn in [("entry", entry), ("classify", classify), ("answer_cv", answer_cv),
131
+ ("contact", contact), ("off_topic", off_topic), ("finalize", finalize)]:
132
+ g.add_node(name, fn)
133
+ g.add_edge(START, "entry")
134
+ g.add_conditional_edges("entry", lambda s: "finalize" if s["fixed"] else "classify",
135
+ {"classify": "classify", "finalize": "finalize"})
136
+ g.add_conditional_edges("classify", lambda s: "finalize" if s["fixed"] else s["route"],
137
+ {"cv_question": "answer_cv", "contact": "contact", "off_topic": "off_topic",
138
+ "finalize": "finalize"})
139
  for n in ("answer_cv", "contact", "off_topic"):
140
+ g.add_edge(n, "finalize")
141
+ g.add_edge("finalize", END)
142
  return g.compile()
evals/provider.py CHANGED
@@ -11,6 +11,7 @@ from langchain_core.callbacks import BaseCallbackHandler # noqa: E402
11
 
12
  from app.graph import build_graph # noqa: E402
13
  from app.llm import get_model # noqa: E402
 
14
  from evals import usage # noqa: E402
15
 
16
  _graph = None
@@ -38,7 +39,10 @@ def call_api(prompt, options, context):
38
  counter = CountCalls()
39
  try:
40
  s = _graph.invoke({"messages": [("user", prompt)]}, config={"callbacks": [counter]})
41
- break
 
 
 
42
  except Exception as e: # shortcut: any 429-like error is retried, others returned as errors
43
  # Gemini free tier: wait and retry. Claude: the SDK retries a little by itself, no wait code here.
44
  if os.environ.get("PROVIDER_APP", "google") == "google" and ("429" in str(e) or "RESOURCE_EXHAUSTED" in str(e)):
 
11
 
12
  from app.graph import build_graph # noqa: E402
13
  from app.llm import get_model # noqa: E402
14
+ from app.texts import BUSY # noqa: E402
15
  from evals import usage # noqa: E402
16
 
17
  _graph = None
 
39
  counter = CountCalls()
40
  try:
41
  s = _graph.invoke({"messages": [("user", prompt)]}, config={"callbacks": [counter]})
42
+ if s["messages"][-1].text not in BUSY.values():
43
+ break
44
+ # the graph turns 429/5xx into the BUSY text (ADR-010); for the eval that is an error, not an answer
45
+ raise RuntimeError("429 busy reply from the graph")
46
  except Exception as e: # shortcut: any 429-like error is retried, others returned as errors
47
  # Gemini free tier: wait and retry. Claude: the SDK retries a little by itself, no wait code here.
48
  if os.environ.get("PROVIDER_APP", "google") == "google" and ("429" in str(e) or "RESOURCE_EXHAUSTED" in str(e)):