mooncak397 Claude Sonnet 5.5 commited on
Commit
58b6069
·
1 Parent(s): 0175fd3

M2: LangGraph router (classify, answer_cv, contact, off_topic), fixed EN/DE texts, graph diagram

Browse files
Files changed (5) hide show
  1. app/cli.py +5 -4
  2. app/graph.py +64 -7
  3. app/texts.py +14 -0
  4. docs/graph.mmd +22 -0
  5. tests/test_graph.py +67 -15
app/cli.py CHANGED
@@ -5,12 +5,13 @@ from app.graph import build_graph
5
  from app.llm import get_model
6
 
7
 
8
- def ask(graph, question: str) -> str:
9
- result = graph.invoke({"messages": [("user", question)]})
10
- return result["messages"][-1].text
11
 
12
 
13
  if __name__ == "__main__":
14
  if len(sys.argv) != 2:
15
  raise SystemExit('Usage: python -m app.cli "<question>"')
16
- print(ask(build_graph(get_model()), sys.argv[1]))
 
 
 
5
  from app.llm import get_model
6
 
7
 
8
+ def ask(graph, question: str) -> dict:
9
+ return graph.invoke({"messages": [("user", question)]})
 
10
 
11
 
12
  if __name__ == "__main__":
13
  if len(sys.argv) != 2:
14
  raise SystemExit('Usage: python -m app.cli "<question>"')
15
+ state = ask(build_graph(get_model()), sys.argv[1])
16
+ print(f"[route={state['route']} lang={state['lang']} show_form={state['show_form']}]", file=sys.stderr)
17
+ print(state["messages"][-1].text)
app/graph.py CHANGED
@@ -1,18 +1,75 @@
1
- """M1: a LangGraph graph with one node that answers from the system prompt. M2 adds the router."""
2
- from langchain_core.messages import SystemMessage
 
 
 
 
3
  from langgraph.graph import END, START, MessagesState, StateGraph
 
4
 
5
  from app.prompts import system_prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
 
8
  def build_graph(model):
9
  prompt = system_prompt()
 
 
10
 
11
- def answer(state: MessagesState):
 
 
 
 
12
  return {"messages": [model.invoke([SystemMessage(prompt), *state["messages"]])]}
13
 
14
- g = StateGraph(MessagesState)
15
- g.add_node("answer", answer)
16
- g.add_edge(START, "answer")
17
- g.add_edge("answer", END)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  return g.compile()
 
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
6
+ 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:
15
+ - cv_question: about the candidate's career, skills, education, projects, languages or availability
16
+ - contact: the user wants to talk to, reach or write to the candidate
17
+ - off_topic: anything else
18
+ lang: "de" if the latest message is German, otherwise "en"."""
19
+
20
+ CONTACT_PROMPT = """The user may want to contact the candidate. If they do, call request_contact_form.
21
+ If it is unclear what they want, ask one short question. Never repeat an email address."""
22
+
23
+
24
+ class Classification(BaseModel):
25
+ route: Literal["cv_question", "contact", "off_topic"]
26
+ lang: Literal["en", "de"]
27
+
28
+
29
+ class State(MessagesState):
30
+ route: str
31
+ lang: str
32
+ show_form: bool
33
+ tool_calls: list[str] # names only: the tool has no arguments
34
+
35
+
36
+ @tool
37
+ def request_contact_form() -> str:
38
+ """Show the contact form to the user."""
39
+ return "contact form shown"
40
 
41
 
42
  def build_graph(model):
43
  prompt = system_prompt()
44
+ classifier = model.with_structured_output(Classification)
45
+ contact_model = model.bind_tools([request_contact_form]) # the only tool, only in this node
46
 
47
+ def classify(state: State):
48
+ c = classifier.invoke([SystemMessage(CLASSIFY_PROMPT), *state["messages"]])
49
+ return {"route": c.route, "lang": c.lang, "show_form": False, "tool_calls": []}
50
+
51
+ def answer_cv(state: State):
52
  return {"messages": [model.invoke([SystemMessage(prompt), *state["messages"]])]}
53
 
54
+ def contact(state: State):
55
+ ai = contact_model.invoke([SystemMessage(CONTACT_PROMPT), *state["messages"]])
56
+ names = [c["name"] for c in ai.tool_calls]
57
+ if "request_contact_form" in names:
58
+ # fixed text: the model never writes the reply when the form opens
59
+ return {"messages": [AIMessage(FORM_INTRO[state["lang"]])], "show_form": True, "tool_calls": names}
60
+ return {"messages": [AIMessage(ai.text)], "tool_calls": names}
61
+
62
+ def off_topic(state: State):
63
+ return {"messages": [AIMessage(OFF_TOPIC[state["lang"]])]} # no LLM call
64
+
65
+ g = StateGraph(State)
66
+ g.add_node("classify", classify)
67
+ g.add_node("answer_cv", answer_cv)
68
+ g.add_node("contact", contact)
69
+ g.add_node("off_topic", off_topic)
70
+ g.add_edge(START, "classify")
71
+ g.add_conditional_edges("classify", lambda s: s["route"],
72
+ {"cv_question": "answer_cv", "contact": "contact", "off_topic": "off_topic"})
73
+ for n in ("answer_cv", "contact", "off_topic"):
74
+ g.add_edge(n, END)
75
  return g.compile()
app/texts.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fixed texts the code picks by language, so the model never writes them (ADR-007).
2
+ Swiss German: "Sie", never "ß"."""
3
+
4
+ OFF_TOPIC = {
5
+ "en": "I can only answer questions about Christopher's professional background. "
6
+ "Please ask about his CV, or use the contact form to reach him.",
7
+ "de": "Ich kann nur Fragen zum beruflichen Hintergrund von Christopher beantworten. "
8
+ "Fragen Sie mich gern zu seinem Lebenslauf, oder nutzen Sie das Kontaktformular.",
9
+ }
10
+
11
+ FORM_INTRO = {
12
+ "en": "Happy to help. Please use the contact form below to send Christopher a message.",
13
+ "de": "Gern. Bitte nutzen Sie das Kontaktformular unten, um Christopher eine Nachricht zu senden.",
14
+ }
docs/graph.mmd ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ config:
3
+ flowchart:
4
+ curve: linear
5
+ ---
6
+ graph TD;
7
+ __start__([<p>__start__</p>]):::first
8
+ classify(classify)
9
+ answer_cv(answer_cv)
10
+ contact(contact)
11
+ off_topic(off_topic)
12
+ __end__([<p>__end__</p>]):::last
13
+ __start__ --> classify;
14
+ classify -. &nbsp;cv_question&nbsp; .-> answer_cv;
15
+ classify -.-> contact;
16
+ classify -.-> off_topic;
17
+ answer_cv --> __end__;
18
+ contact --> __end__;
19
+ off_topic --> __end__;
20
+ classDef default fill:#f2f0ff,line-height:1.2
21
+ classDef first fill-opacity:0
22
+ classDef last fill:#bfb6fc
tests/test_graph.py CHANGED
@@ -1,27 +1,79 @@
1
- """M1 tests: no key, no network. A fake chat model stands in for Gemini."""
2
  import pytest
3
- from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
4
  from langchain_core.messages import AIMessage, SystemMessage
5
 
6
  from app.cli import ask
7
- from app.graph import build_graph
 
8
 
9
 
10
- class RecordingModel(GenericFakeChatModel):
11
- seen: list = [] # the messages the graph sent to the model
12
 
13
- def _generate(self, messages, *a, **k):
14
- self.seen.append(messages)
15
- return super()._generate(messages, *a, **k)
 
16
 
 
 
17
 
18
- def test_graph_sends_rules_and_profile_then_returns_the_answer():
19
- model = RecordingModel(messages=iter([AIMessage("He works at DATEV.")]), seen=[])
20
- assert ask(build_graph(model), "Where does Christopher work?") == "He works at DATEV."
21
- system, user = model.seen[0]
22
- assert isinstance(system, SystemMessage)
23
- assert "version: v1" in system.content and "DATEV" in system.content # rules + profile
24
- assert user.content == "Where does Christopher work?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
 
27
  def test_get_model_fails_clearly_without_settings(monkeypatch):
 
1
+ """Router tests: no key, no network. FakeModel stands in for Gemini."""
2
  import pytest
 
3
  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.texts import FORM_INTRO, OFF_TOPIC
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 or AIMessage("He works at DATEV.")
16
+ self.calls = [] # (kind, messages)
17
 
18
+ def with_structured_output(self, _schema):
19
+ return _Step(self, "classify", self.cls)
20
 
21
+ def bind_tools(self, tools):
22
+ assert [t.name for t in tools] == ["request_contact_form"] # exactly one tool
23
+ return _Step(self, "contact", self.reply)
24
+
25
+ def invoke(self, messages):
26
+ self.calls.append(("answer", messages))
27
+ return self.reply
28
+
29
+
30
+ class _Step:
31
+ def __init__(self, parent, kind, out):
32
+ self.parent, self.kind, self.out = parent, kind, out
33
+
34
+ def invoke(self, messages):
35
+ self.parent.calls.append((self.kind, messages))
36
+ return self.out
37
+
38
+
39
+ def kinds(m):
40
+ return [k for k, _ in m.calls]
41
+
42
+
43
+ def test_cv_question_uses_rules_and_profile():
44
+ m = FakeModel()
45
+ s = ask(build_graph(m), "Where does Christopher work?")
46
+ assert s["messages"][-1].text == "He works at DATEV."
47
+ assert kinds(m) == ["classify", "answer"]
48
+ system = m.calls[1][1][0]
49
+ assert isinstance(system, SystemMessage) and "version: v1" in system.content and "DATEV" in system.content
50
+ assert not s["show_form"] and s["tool_calls"] == []
51
+
52
+
53
+ @pytest.mark.parametrize("lang", ["en", "de"])
54
+ def test_off_topic_is_fixed_text_and_costs_one_call(lang):
55
+ m = FakeModel(route="off_topic", lang=lang)
56
+ s = ask(build_graph(m), "What is the weather?")
57
+ assert s["messages"][-1].text == OFF_TOPIC[lang]
58
+ assert kinds(m) == ["classify"] # no LLM call for the answer
59
+
60
+
61
+ @pytest.mark.parametrize("lang", ["en", "de"])
62
+ def test_contact_tool_call_opens_form_with_fixed_text(lang):
63
+ reply = AIMessage("", tool_calls=[{"name": "request_contact_form", "args": {}, "id": "1"}])
64
+ s = ask(build_graph(FakeModel(route="contact", lang=lang, reply=reply)), "I'd like to talk to him")
65
+ assert s["show_form"] is True and s["tool_calls"] == ["request_contact_form"]
66
+ assert s["messages"][-1].text == FORM_INTRO[lang]
67
+
68
+
69
+ def test_contact_unclear_asks_and_shows_no_form():
70
+ s = ask(build_graph(FakeModel(route="contact", reply=AIMessage("What would you like to discuss?"))), "contact?")
71
+ assert s["show_form"] is False and s["tool_calls"] == []
72
+ assert s["messages"][-1].text == "What would you like to discuss?"
73
+
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):