Rafael Andrade
  • PT
  • EN (current language)
All projects

AI agent · Text-to-Cypher

Sales Analytics Reporter

A LangGraph agent that answers natural-language questions about sales by generating Cypher over a read-only Neo4j graph.

  • Fail-closed guard with its own policy and 7 categories
  • Cypher self-correction via EXPLAIN
  • End-to-end tests against the real models
Type
Personal project
Period
Nov 2026
Stack
TypeScript, LangGraph, Neo4j, Fastify
Project banner (in Portuguese): the question “Top 5 courses by revenue?” goes through the guard, the planner that writes Cypher and the read-only Neo4j to the analytical answer; out-of-scope questions are stopped at the guard.
Banner published in the repository README, with the path of one question. The text is in Portuguese.

Architecture overview

  1. 01Input

    • POST /sales — Input

      Fastify; over 500 characters is rejected without calling a model

  2. 02Guard

    • gpt-oss-safeguard-20b — Language model

      domain policy; JSON output validated with Zod

      blocked or invalid format → fixed response (fail-closed)

  3. 03Planning

    • queryPlanner — Language model

      breaks compound questions into up to 3 sub-questions

  4. 04Query

    • cypherGenerator — Language model

      domain business rules in the context

    • cypherExecutor — Data

      EXPLAIN before running; routing: READ session

      invalid → cypherCorrection rewrites it with the error and the schema

  5. 05Answer

    • analyticalResponse — Language model

      numbers, comparisons and 2–3 follow-ups in the question’s language

  6. 06Output

    • JSON — Output

      answer, followUpQuestions, blocked — no Cypher, no internal errors

  • Input and output
  • Language model
  • Data
Each box is a StateGraph node. A blocked question ends at the guard, without reaching the more expensive models.

01Context and problem

Questions like “which courses earned the most through Pix?” usually depend on someone who knows the database and writes the query. A generic chatbot can answer, but it accepts any question, spends tokens on off-topic requests and may reveal the schema to anyone who asks.

02Goal

Allow questions in Portuguese about a sales graph — students, courses, purchases and progress — with numeric answers, keeping the scope limited to the business and preventing any write to the database, with security enforced outside the prompt.

03How it works

  1. 1.

    Input validation

    Fastify validates the request body; empty questions or questions over 500 characters are rejected without calling any model.

  2. 2.

    Guard

    A safety classifier reads a policy written for the domain and sorts the question into 7 categories — out of scope, system probing, prompt injection, database writes, personal data and others. A blocked question gets a fixed response with valid suggestions.

  3. 3.

    Planning

    Compound questions, such as comparing revenue between courses with high and low completion, are split into up to three sub-questions, each with its own query.

  4. 4.

    Cypher generation and correction

    Every query goes through EXPLAIN before it runs. If it is invalid, the error goes back to the model along with the schema, and the model rewrites the query.

  5. 5.

    Analytical answer

    The Neo4j result becomes text with percentages, highlights and two or three follow-up questions, in the language of the original question.

04Technical architecture

Each step is a node in a LangGraph StateGraph. The nodes share a state typed with Zod, and decisions live in conditional edges instead of being scattered through the code.

  • Two clients of the same service

    OpenRouterService is instantiated twice in the factory: once with the main model and once with the guard model, at temperature: 0. Each node receives the client it needs through dependency injection; switching models is a one-line configuration change.

  • Neo4jService

    query() always runs in a read session; write() is a separate, explicit method used only by the seed.

  • Versioned prompts

    The guard policy, sales context, fixed responses and schemas live in src/prompts/v1/, versioned as code.

  • Data model

    (:Student)-[:PURCHASED {status, amount, paymentMethod, paymentDate}]->(:Course) and (:Student)-[:PROGRESS {progress}]->(:Course). Domain rules — revenue counts only paid purchases — reach the Cypher generator through the context.

05Technologies

Orchestration
LangGraph · LangChain · Zod
Models
OpenRouter · gpt-oss-safeguard-20b (guard) · Nemotron (main)
Data
Neo4j 5.14 · APOC · Docker Compose
API and runtime
Fastify 5 · pino · Node 24 with native TypeScript · LangSmith (optional)

06Engineering decisions

  • Guard before everything

    The guard sits at the first point where the question exists as text and the last one before the main model. An off-topic question costs one call to a small model, instead of going through the planner, the Cypher generator and the answer.

  • A classifier instead of a prompt instruction

    The safeguard model follows a policy written by the developer in the system prompt, and the user’s message comes in as data ({"message": "..."}), never as an instruction. If the guard fails or answers in the wrong format, the question is blocked.

  • Permissions in the driver, not in the prompt

    A prompt is a suggestion; a permission is a rule. Even if an injection slips past the guard and the model generates a DELETE, the Neo4j READ session refuses the write.

  • An API that doesn’t leak details

    The response includes neither the Cypher nor the internal error; the details go to the log. A debug flag exposes that data only in development.

07Technical challenges

  • Invalid queries generated by the model

    Cypher with syntax or schema errors is caught by EXPLAIN before execution and sent back to the model with the schema, in a correction loop.

  • Questions that need several queries

    Comparisons need more than one query. The planner breaks the question down and the answer node combines the results into a single analysis.

  • Testing model behavior

    There is no LLM mock: the tests check how the guard actually behaves against the policy — 15 cases in Portuguese and English, including an injection in the middle of a valid question — plus 10 end-to-end questions against Neo4j.

08What was implemented

  • Cypher generation with self-correction via EXPLAIN
  • Breaking complex questions into up to 3 steps
  • Guard with its own policy, fail-closed
  • Neo4j in read-only mode
  • API that never leaks Cypher or internal errors
  • Seed with fictitious data generated by Faker
  • End-to-end tests for the guard and the full flow

09Possible next steps

Future improvements — not implemented yet

  • Remove personal fields (email and phone) from the result before the answer node.
  • End the flow with a fallback when the model fails, instead of hitting the recursion limit.
  • Conversation memory for follow-ups that depend on the previous question.

10Code and demo