From 27082c02d58c459205864496dbc6cbc83bfee01f Mon Sep 17 00:00:00 2001 From: Daniel Plank Date: Thu, 5 Nov 2026 22:55:52 +0100 Subject: [PATCH] Deterministic tools: PTO calculator and support ticketing Refs #4 --- app/tools/__init__.py | 0 app/tools/calculator.py | 62 ++++++++++++++++++++++++++ app/tools/ticketing.py | 96 +++++++++++++++++++++++++++++++++++++++++ tests/__init__.py | 0 tests/conftest.py | 62 ++++++++++++++++++++++++++ tests/test_tools.py | 55 +++++++++++++++++++++++ 6 files changed, 275 insertions(+) create mode 100644 app/tools/__init__.py create mode 100644 app/tools/calculator.py create mode 100644 app/tools/ticketing.py create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_tools.py diff --git a/app/tools/__init__.py b/app/tools/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/tools/calculator.py b/app/tools/calculator.py new file mode 100644 index 0000000..5f5f5e5 --- /dev/null +++ b/app/tools/calculator.py @@ -0,0 +1,62 @@ +"""Deterministic PTO (leave balance) calculator tool. + +This is intentionally plain Python (no LLM call) wrapped as a LangChain tool: the agent +extracts structured arguments from the user's message with an LLM, but the arithmetic itself +is deterministic and auditable, which matters for an HR-facing calculation. + +Accrual rule, mirrored from app/data/policies/pto_policy.md: + - 1.75 days accrued per full calendar month of employment (21 days/year) + - max carryover of 5 days is ignored here (single-year, from-hire-date balance); a + production version would need full year-boundary bookkeeping. +""" +from __future__ import annotations + +from datetime import date + +from langchain_core.tools import tool + +ACCRUAL_DAYS_PER_MONTH = 1.75 + + +def _months_employed(hire_date: date, as_of: date) -> int: + if as_of < hire_date: + return 0 + months = (as_of.year - hire_date.year) * 12 + (as_of.month - hire_date.month) + if as_of.day < hire_date.day: + months -= 1 + return max(months, 0) + + +def compute_leave_balance(hire_date: str, days_taken: float, as_of_date: str | None = None) -> dict: + """Compute accrued and remaining PTO balance. + + Args: + hire_date: ISO date string (YYYY-MM-DD) the employee was hired. + days_taken: Number of PTO days already used this year. + as_of_date: ISO date string to calculate the balance as of; defaults to today. + """ + hire = date.fromisoformat(hire_date) + as_of = date.fromisoformat(as_of_date) if as_of_date else date.today() + + months = _months_employed(hire, as_of) + accrued = round(months * ACCRUAL_DAYS_PER_MONTH, 2) + remaining = round(accrued - float(days_taken), 2) + + return { + "hire_date": hire.isoformat(), + "as_of_date": as_of.isoformat(), + "months_employed": months, + "accrued_days": accrued, + "days_taken": float(days_taken), + "remaining_days": remaining, + } + + +@tool +def leave_balance_calculator(hire_date: str, days_taken: float, as_of_date: str | None = None) -> dict: + """Calculate an employee's remaining PTO balance from hire date and days already taken. + + hire_date and as_of_date must be ISO format strings (YYYY-MM-DD). as_of_date defaults to + today if omitted. + """ + return compute_leave_balance(hire_date, days_taken, as_of_date) diff --git a/app/tools/ticketing.py b/app/tools/ticketing.py new file mode 100644 index 0000000..c4e863f --- /dev/null +++ b/app/tools/ticketing.py @@ -0,0 +1,96 @@ +"""Mock support-ticket system. + +A real side-effecting (non-retrieval) tool: it writes a row to a local SQLite database and +returns a ticket id, simulating a corporate ticketing system (e.g. ServiceNow/Jira Service +Desk) that the agent can autonomously open on the user's behalf, or as a self-triggered +escalation when the RAG subgraph cannot confidently answer a policy question. +""" +from __future__ import annotations + +import sqlite3 +import uuid +from contextlib import contextmanager +from datetime import datetime, timezone + +from langchain_core.tools import tool + +from app.config import TICKETS_DB_PATH + +VALID_PRIORITIES = {"low", "normal", "high"} + + +@contextmanager +def _connect(): + TICKETS_DB_PATH.parent.mkdir(parents=True, exist_ok=True) + conn = sqlite3.connect(TICKETS_DB_PATH) + try: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS tickets ( + ticket_id TEXT PRIMARY KEY, + category TEXT NOT NULL, + summary TEXT NOT NULL, + user_query TEXT, + priority TEXT NOT NULL, + status TEXT NOT NULL, + created_at TEXT NOT NULL + ) + """ + ) + yield conn + conn.commit() + finally: + conn.close() + + +def create_ticket_record( + category: str, summary: str, user_query: str = "", priority: str = "normal" +) -> dict: + priority = priority if priority in VALID_PRIORITIES else "normal" + ticket_id = f"TCK-{uuid.uuid4().hex[:8].upper()}" + created_at = datetime.now(timezone.utc).isoformat() + + with _connect() as conn: + conn.execute( + "INSERT INTO tickets (ticket_id, category, summary, user_query, priority, status, created_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", + (ticket_id, category, summary, user_query, priority, "open", created_at), + ) + + return { + "ticket_id": ticket_id, + "category": category, + "summary": summary, + "priority": priority, + "status": "open", + "created_at": created_at, + } + + +def get_ticket(ticket_id: str) -> dict | None: + with _connect() as conn: + row = conn.execute( + "SELECT ticket_id, category, summary, user_query, priority, status, created_at " + "FROM tickets WHERE ticket_id = ?", + (ticket_id,), + ).fetchone() + if row is None: + return None + keys = ["ticket_id", "category", "summary", "user_query", "priority", "status", "created_at"] + return dict(zip(keys, row)) + + +@tool +def create_support_ticket( + category: str, summary: str, user_query: str = "", priority: str = "normal" +) -> dict: + """Open a support ticket in the corporate ticketing system. + + category: a short machine-readable category, e.g. 'it_access_request', + 'hr_leave_request', 'hr_conduct_concern', 'finance_expense_dispute', + 'legal_data_subject_request', 'it_security_incident', 'it_equipment_request', + 'travel_safety_approval'. + summary: a one or two sentence human-readable description of the request. + priority: one of 'low', 'normal', 'high'. + """ + return create_ticket_record(category, summary, user_query, priority) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..6f6c049 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,62 @@ +"""Shared test fixtures. + +No Ollama instance is available in CI/this sandbox, so graph-wiring tests inject a small +scripted stub instead of a real chat model. It only needs to support `.invoke(prompt) -> +object with `.content`, which is all `app/llm.py` and the graph nodes rely on - so it is a +faithful stand-in for exercising routing/state logic independent of actual answer quality. +Embedding-based retrieval (`tests/test_rag_subgraph.py`) still uses the real local +sentence-transformers model and a real FAISS index, since that part needs no Ollama. +""" +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +class ScriptedLLM: + """Returns responses from a fixed list, one per `.invoke()` call, repeating the last.""" + + def __init__(self, responses: list[str]): + self.responses = list(responses) + self.calls: list[str] = [] + self._i = 0 + + def invoke(self, prompt: str): + self.calls.append(prompt) + if self._i < len(self.responses): + text = self.responses[self._i] + else: + text = self.responses[-1] if self.responses else "{}" + self._i += 1 + return SimpleNamespace(content=text) + + +@pytest.fixture +def scripted_llm(): + return ScriptedLLM + + +@pytest.fixture +def tickets_db(tmp_path, monkeypatch): + db_path = tmp_path / "tickets.db" + monkeypatch.setattr("app.tools.ticketing.TICKETS_DB_PATH", db_path) + return db_path + + +@pytest.fixture(scope="session") +def tiny_store(tmp_path_factory): + """A tiny, real FAISS index (real embeddings) over two sample policy docs.""" + from app.rag.vectorstore import load_or_build_index + + docs_dir = tmp_path_factory.mktemp("docs") + (docs_dir / "pto.md").write_text( + "# PTO Policy\n\n## Accrual\nEmployees accrue 1.75 days of PTO per month.\n", + encoding="utf-8", + ) + (docs_dir / "travel.md").write_text( + "# Travel Policy\n\n## Booking\nBook flights through the corporate travel portal.\n", + encoding="utf-8", + ) + index_dir = tmp_path_factory.mktemp("index") + return load_or_build_index(docs_dir=docs_dir, index_dir=index_dir) diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 0000000..62534cb --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,55 @@ +from app.tools.calculator import compute_leave_balance +from app.tools.ticketing import create_ticket_record, get_ticket + + +def test_leave_balance_basic_accrual(): + result = compute_leave_balance(hire_date="2024-01-15", days_taken=3, as_of_date="2024-07-15") + assert result["months_employed"] == 6 + assert result["accrued_days"] == 10.5 + assert result["remaining_days"] == 7.5 + + +def test_leave_balance_partial_month_not_counted(): + # Hired on the 15th, "as of" the 10th of a later month: that partial month doesn't count. + result = compute_leave_balance(hire_date="2024-01-15", days_taken=0, as_of_date="2024-03-10") + assert result["months_employed"] == 1 + assert result["accrued_days"] == 1.75 + + +def test_leave_balance_before_hire_date_is_zero(): + result = compute_leave_balance(hire_date="2024-06-01", days_taken=0, as_of_date="2024-01-01") + assert result["months_employed"] == 0 + assert result["accrued_days"] == 0.0 + assert result["remaining_days"] == 0.0 + + +def test_leave_balance_defaults_as_of_to_today(): + result = compute_leave_balance(hire_date="2020-01-01", days_taken=1) + assert result["months_employed"] > 0 + + +def test_create_and_fetch_ticket(tickets_db): + ticket = create_ticket_record( + category="it_access_request", + summary="Need VPN access as a contractor", + user_query="How do I get VPN access?", + priority="high", + ) + assert ticket["ticket_id"].startswith("TCK-") + assert ticket["status"] == "open" + + fetched = get_ticket(ticket["ticket_id"]) + assert fetched is not None + assert fetched["category"] == "it_access_request" + assert fetched["priority"] == "high" + + +def test_create_ticket_invalid_priority_defaults_to_normal(tickets_db): + ticket = create_ticket_record(category="hr_leave_request", summary="x", priority="urgent!!") + assert ticket["priority"] == "normal" + + +def test_tickets_are_independent_rows(tickets_db): + t1 = create_ticket_record(category="hr_leave_request", summary="a") + t2 = create_ticket_record(category="hr_leave_request", summary="b") + assert t1["ticket_id"] != t2["ticket_id"]