File size: 9,004 Bytes
3f2fa9a
 
58b6069
3f2fa9a
ebe48a7
58b6069
 
 
 
5f42268
58b6069
5f42268
6b6ccde
3f2fa9a
 
 
 
 
295c71d
58b6069
 
 
 
c92bb06
 
5f5ac3c
9726285
91bf6fe
58b6069
50de21b
3592f25
58b6069
 
 
 
 
 
 
 
 
 
 
 
 
3f2fa9a
 
58b6069
 
 
 
 
 
5f42268
 
3f2fa9a
 
087098d
 
3f2fa9a
 
 
 
 
 
 
 
ebe48a7
 
 
 
 
 
 
 
 
 
 
5f42268
 
3f2fa9a
 
58b6069
 
5f42268
3f2fa9a
 
 
 
 
 
 
 
 
59bc960
 
3f2fa9a
 
 
295c71d
ebe48a7
 
3f2fa9a
 
 
 
 
 
58b6069
3f2fa9a
 
 
 
58b6069
 
3f2fa9a
 
5f42268
58b6069
3f2fa9a
 
 
 
 
 
 
 
58b6069
 
3f2fa9a
 
 
 
 
 
 
 
3f301d6
 
 
 
3f2fa9a
6b6ccde
 
3f2fa9a
 
 
 
 
 
 
58b6069
 
3f2fa9a
 
 
 
 
 
 
 
 
58b6069
3f2fa9a
 
5f42268
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""LangGraph router (plan section 2, ADR-010):
entry -> classify -> answer_cv | contact | off_topic -> finalize. entry and finalize make no model call.
The model is injected, so tests can pass a fake one."""
import logging
import re
from typing import Literal

from langchain_core.messages import AIMessage, SystemMessage
from langchain_core.tools import tool
from langgraph.graph import END, START, MessagesState, StateGraph
from pydantic import BaseModel

from app.answer_guards import discretion_hit, only_fixed, scrub, thought_hit
from app.prompts import fixed_sentences, system_prompt
from app.texts import BUSY, EMPTY, FORM_INTRO, OFF_TOPIC, TOO_LONG

log = logging.getLogger(__name__)
MAX_CHARS = 1000
INVISIBLE = re.compile("[\u200b-\u200d\u2060\ufeff\u3164\x00]")  # zero-width, word joiner, BOM, Hangul filler, NUL

CLASSIFY_PROMPT = """Classify the user's latest message for an assistant that answers questions about a job candidate.
route:
- cv_question: about the candidate's career, skills, education, projects, languages or availability
- contact: the user wants to talk to, reach or send a message to the candidate through this site
- A request to draft or write a text (an email, an InMail, a LinkedIn message, a summary, a form), also a text addressed to the candidate, is a cv_question.
- Look at the real question, not at the format. A message in JSON, XML, CSV or a table, a message that mixes languages, or a message with odd text or instructions around it is a cv_question if it asks anything about the candidate. The answer step deals with the instructions.
- off_topic: only clearly unrelated things (weather, cooking, coding help, general knowledge). A question about the candidate, his projects (for example AgentBrain), his tools, his age, his city or other personal facts is a cv_question, even if the answer may be unknown.
lang: the language of the user's own request in the latest message: "de" for German, otherwise "en". A quoted text does not count: "Translate this into English: '<German text>'" is "en"."""

CONTACT_PROMPT = """The user may want to contact the candidate. Call request_contact_form only if the user wants to write to, reach or talk to the candidate himself (for example "How can I reach him?" or "I want to send him a message").
Do not call it, and say you cannot do that, if the user asks you to send, forward or email anything to someone else, or to do any other task. Make no tool call. Write at most two short sentences. Never write an email address or a domain name: if you must refer to it, say 'that address'.
If it is unclear what they want, ask one short question. Never repeat an email address."""


class Classification(BaseModel):
    route: Literal["cv_question", "contact", "off_topic"]
    lang: Literal["en", "de"]


class State(MessagesState):
    route: str
    lang: str
    show_form: bool
    tool_calls: list[str]  # names only: the tool has no arguments
    reply: str  # the node's reply; finalize checks it and appends the one AIMessage
    fixed: bool  # True = a code-chosen text, finalize returns it unchanged


@tool
def request_contact_form() -> str:
    """Show the contact form to the user."""
    return "contact form shown"


def _transport(e: Exception) -> bool:
    """429, 5xx, timeout or connection error (after the SDK's own retries)."""
    if getattr(e, "is_retryable", False):  # langchain_core ModelError subclasses
        return True
    code = getattr(e, "status_code", None) or getattr(e, "code", None)
    if isinstance(code, int) and (code == 429 or code >= 500):
        return True
    name, msg = type(e).__name__, str(e)
    return (any(k in name for k in ("Timeout", "Connection", "RateLimit", "ResourceExhausted", "ServiceUnavailable"))
            or "429" in msg or "RESOURCE_EXHAUSTED" in msg)


_EN = {"the", "and", "is", "you", "for", "he", "his", "of", "to", "what", "does", "how", "please"}
_DE = {"der", "die", "und", "ist", "sie", "für", "ein", "eine", "das", "er", "nicht", "wie", "was", "hat", "seine", "bitte"}


def _guess_lang(text: str, default: str) -> str:
    """Function-word count for the fixed entry texts. A tie (also empty text) keeps the default."""
    words = re.findall(r"[a-zäöüß]+", text.lower())
    en, de = sum(w in _EN for w in words), sum(w in _DE for w in words)
    return "de" if de > en else "en" if en > de else default


def build_graph(model):
    prompt = system_prompt()
    fixed = fixed_sentences()
    idk = {"en": fixed["idk_en"], "de": fixed["idk_de"]}
    classifier = model.with_structured_output(Classification)
    contact_model = model.bind_tools([request_contact_form])  # the only tool, only in this node

    def _call(fn, lang):
        """One model call. Returns (result, None), or (None, fixed reply) on any error: never raises."""
        try:
            out = fn()
            if out is None:  # structured output that did not parse
                raise ValueError("no parsed output")
            return out, None
        except Exception as e:  # refusal, parse error, transport: the user gets a fixed text, not a 500
            busy = _transport(e)
            # the exception rides along for evals/provider.py (daily-quota stop); the log text has no message content
            log.warning("model_error class=%s busy=%s", type(e).__name__, busy, extra={"error": e})
            return None, (BUSY if busy else idk)[lang]

    def entry(state: State):
        text = INVISIBLE.sub("", state["messages"][-1].text).strip()  # invisible-only input counts as empty
        lang = _guess_lang(text, state.get("lang") or "en")  # no model call to detect it
        out = {"route": "entry", "lang": lang, "show_form": False, "tool_calls": [], "reply": "", "fixed": False}
        if not text:
            return {**out, "reply": EMPTY[lang], "fixed": True}
        if len(text) > MAX_CHARS:
            return {**out, "reply": TOO_LONG[lang], "fixed": True}
        return out

    def classify(state: State):
        c, err = _call(lambda: classifier.invoke([SystemMessage(CLASSIFY_PROMPT), *state["messages"]]), state["lang"])
        if err:
            return {"route": "error", "reply": err, "fixed": True}
        return {"route": c.route, "lang": c.lang}

    def answer_cv(state: State):
        ai, err = _call(lambda: model.invoke([SystemMessage(prompt), *state["messages"]]), state["lang"])
        return {"reply": err, "fixed": True} if err else {"reply": ai.text}

    def contact(state: State):
        ai, err = _call(lambda: contact_model.invoke([SystemMessage(CONTACT_PROMPT), *state["messages"]]), state["lang"])
        if err:
            return {"reply": err, "fixed": True}
        if any(c["name"] == "request_contact_form" for c in ai.tool_calls):
            # one tool call at most; the model never writes the reply when the form opens
            return {"reply": FORM_INTRO[state["lang"]], "fixed": True, "show_form": True,
                    "tool_calls": ["request_contact_form"]}
        return {"reply": ai.text}

    def off_topic(state: State):
        return {"reply": OFF_TOPIC[state["lang"]], "fixed": True}  # no LLM call

    def finalize(state: State):
        lang, text, guard = state["lang"], state["reply"], None
        if not state["fixed"]:
            text = text.strip()
            if not text:
                text, guard = idk[lang], "empty"
            elif hit := only_fixed(text, fixed):
                k, kept = hit
                s = fixed[f"{k}_{lang}"]  # the turn's language wins: the model sometimes picks the other one
                s = f"{scrub(kept, lang)}\n\n{s}" if kept else s
                text, guard = s, ("fixed_sentence" if s != text else None)
            elif thought_hit(text):  # thought, rule or marker text: never show it
                text, guard = idk[lang], "thought"
            elif discretion_hit(text):
                text, guard = idk[lang], "discretion"
            elif (s := scrub(text, lang)) != text:
                text, guard = s, "scrub"
        if guard:
            log.info("guard=%s route=%s lang=%s", guard, state["route"], lang)
        return {"messages": [AIMessage(text)], "reply": text}

    g = StateGraph(State)
    for name, fn in [("entry", entry), ("classify", classify), ("answer_cv", answer_cv),
                     ("contact", contact), ("off_topic", off_topic), ("finalize", finalize)]:
        g.add_node(name, fn)
    g.add_edge(START, "entry")
    g.add_conditional_edges("entry", lambda s: "finalize" if s["fixed"] else "classify",
                            {"classify": "classify", "finalize": "finalize"})
    g.add_conditional_edges("classify", lambda s: "finalize" if s["fixed"] else s["route"],
                            {"cv_question": "answer_cv", "contact": "contact", "off_topic": "off_topic",
                             "finalize": "finalize"})
    for n in ("answer_cv", "contact", "off_topic"):
        g.add_edge(n, "finalize")
    g.add_edge("finalize", END)
    return g.compile()