RPay-build-recovery-agent
Health Warn
- No license — Repository has no license file
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 8 GitHub stars
Code Pass
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Pass
- Permissions — No dangerous permissions requested
No AI report is available for this listing yet.
Autonomous, relationship-aware B2B receivables recovery agent for Indian MSMEs. Replaces rigid calendar dunning with AI reasoning & a deterministic compliance envelope (MSMED Act & 43B(h)). Features Razorpay checkout, Promise-to-Pay tracking, dispute triage, human operator kill switch and 7 proven receivables recovery strategies.
PayUpPal
PayUpPal is a B2B receivables recovery agent for Indian small suppliers. For each debtor it decides whether to wait, reconcile a tax or bank-transfer gap, ask for payment, get a promise to pay, resolve a dispute, escalate under the MSMED Act, or hand off to a human.
This matters because calendar dunning (a nudge on day 7, firmer on day 15, a legal notice on day 30) sends the same escalation to everyone. A loyal buyer three days late gets it, a buyer who legitimately withheld TDS gets it, and so does a buyer who already paid by NEFT. In B2B, that can lose the supplier the next purchase order, and it sometimes asserts a statutory claim the supplier is not entitled to make.
Headline result. Seed 42 generates a seeded synthetic portfolio of 70 invoices across 20 debtors, with a ₹6.29 crore book. The table compares the agent's decision policy with a day 7/15/30 calendar baseline on the same accounts:
| Metric | Agent | Calendar baseline |
|---|---|---|
Debtors deliberately left alone (WAIT) |
10% (2/20) | 0% |
| Debtors routed to TDS / UTR reconciliation instead of a demand | 40% (8/20) | 0% |
| Statutory escalations sent | 0 | 20 |
| Outreach touches | 16 | 20 |
These figures come from the offline deterministic evaluator, not the live model (see Evaluation). The baseline escalates the whole book by construction, so the 0 vs 20 escalation count proves little alone. The 8-case adjudication matrix is the stronger comparison.
How the agent decides
The model never acts on its raw output. Every decision passes through four layers, and each boundary is enforced in code, not just requested in the prompt.
ledger (debtor + open invoices + supplier)
|
v
1. Policy envelope (app/envelope.py) deterministic: permitted strategies,
| excluded strategies with reasons
v
2. Strategist (app/strategist.py, app/llm.py) Gemini structured output against a Pydantic
| schema, then re-checked against the envelope
v
3. Message drafting (app/messages.py) statute-aware copy, anti-dark-pattern filter
|
v
4. Dispatch (app/pipeline.py, app/operator.py) kill switch checked per send; review-required
| decisions go to a human queue
v
debtor resolution page /r/{invoice_id}: pay (Razorpay) / promise a date / dispute
|
v
payment.captured webhook -> raw-byte HMAC check -> idempotent settlement -> chasing stops
1. Deterministic policy envelope. Before the model sees anything, evaluate_envelope works out which strategies are permitted and records a reason for each one it excludes. The rules:
- An opted-out debtor gets
WAITonly, with no channel. - An open dispute bars payment demands and escalation.
- A trading-category supplier cannot cite MSMED s.15/16.
- Invoices with TDS withheld or paid off-rail are routed to
RECONCILE. - High-value accounts are protected from escalation.
- A contact cooldown and an intensity cap apply.
- Money asks are barred while a promise to pay is open.
2. LLM strategist with schema-validated decisions. decide_for_debtor decides once per debtor, across all of that debtor's open invoices. The prompt is built from agent_view(debtor), which strips the hidden behaviour parameters the synthetic ledger uses as ground truth. The model returns a StrategistDecision with:
- strategy, channel, language and tone
- an ask in integer paise
- a deadline as a real
date - reasoning and a confidence score
rejected_actions: the alternatives it considered, and why it rejected each
The code then re-checks the decision:
- An excluded strategy is replaced by the safe fallback (
HUMAN_HANDOFF) and logged asenvelope.violation_intercepted. - An ask outside the pre-authorised band is clamped into
[min_ask, collectible]. - A stray field is dropped: an ask on a strategy that requests no money, a channel or deadline on a no-contact strategy, or a deadline already in the past.
Each correction is logged and sets review_required, which later steps cannot clear.
3. Message generation and anti-dark-pattern filter. Drafts are written in English or Hinglish. Copy is checked for prohibited coercive or false-legal phrasing. Statutory interest and due dates are computed in code (app/statute.py, app/messages.py); the model does not produce them.
4. Human review and kill switch. Review-required decisions wait in an operator queue. A master kill switch (/api/operator/kill-switch) blocks outbound dispatch, and the pipeline checks it before every send. Every step writes an append-only audit event (decision.made, envelope.*, strategist.*). Cooldowns and open promise windows are rebuilt from that log, so the log feeds later decisions as well as recording them.
Evaluation
python run_experiment.py --seed 42 # table
python run_experiment.py --seed 42 --output markdown
python run_experiment.py --seed 42 --output json --save runs/report.json
python run_experiment.py --seed 42 --live-llm # real Gemini decisions; needs GOOGLE_API_KEY
What it runs. app/ledger.py generates a seeded synthetic ledger, so the same seed always gives the same book. Seed 42 is pinned to fingerprint 7c1314468565fc3d, and drift fails the build. The ledger includes:
- TDS withholding
- off-rail UTR payments
- disputes
- partial settlements
- opted-out debtors
- a trading-category supplier
The agent and app/baseline.py each decide for every debtor with open invoices. The run writes to an isolated temporary audit log, so it never touches live state.
Offline mode is a stand-in for the model. Without --live-llm, the LLM call is replaced by _deterministic_mock_llm, a rule-based solver. It reads the same prompt sections the model gets: debtor profile, invoices, supplier and envelope. This keeps the run reproducible and free. Everything downstream is the real code path: the envelope, schema validation, post-checks and audit records. Live mode is not repeatable, because the model can choose differently on the same seed.
What it measures:
- the strategy distribution for the agent and for the baseline
- the
WAITrestraint share - the reconciliation routing share
- escalations the baseline sent and the agent did not
- outreach touches per ₹1 lakh of collectible balance
- portfolio totals: naive outstanding, and collectible net of TDS and off-rail payments
How failure is defined. The adjudication matrix has 8 archetypes:
- TDS deducted
- off-rail NEFT payment
- active dispute
- trader-ineligible supplier
- VIP relationship
- opted-out debtor
- reliable late payer
- complex mixed-state account
A case's verdict is credited only when all four conditions hold:
- The debtor has the target invoice state.
- The agent diverged from the baseline.
- The agent chose a strategy that the archetype is about.
- The case's mechanism check holds. This stops, for example, an opt-out
WAITfrom passing as reliable-payer restraint.
If any condition fails, the row reads N/A (case does not reproduce at this seed) and the authored verdict is withheld. test_experiment.py feeds deliberately mislabelled cases through this gate and checks that they are rejected. At seed 42 all 8 reproduce. Seven are agent wins, and the mixed-state account is deferred to human review.
Failure modes we found and fixed
The worst of these passed every test while the system was confidently wrong.
- A legal demand overstated by ₹95,253. MSMED s.16 compound interest was computed once, on the debtor's aggregate balance, against a single invoice's statutory clock. On a two-invoice probe that inflated the demand by ₹95,253. Interest is now summed per invoice, each from its own acceptance-derived due date, in exact Decimal paise.
- Falling back to
WAITdisguised an outage as restraint.WAITis this system's word for deliberate judgment. There are three failure paths: an unreachable model, unparseable output, and an intercepted policy violation. All three now go through one_safe_fallback, which returnsHUMAN_HANDOFF. Each path is logged under its own event (strategist.model_unavailable,strategist.parse_failed,envelope.violation_intercepted) with a confidence of 0.0 or 0.5, so a run can be filtered down to the decisions the model actually made. - Brittle structured output voided sound decisions. The prompt leaves
rejected_actionsfree-form, so it is the field most likely to come back wrong. It used to be validated with the rest of the decision, and one bad entry discarded a valid strategy, ask and reasoning. Each entry is now validated againstRejectedActionon its own. Bad entries are dropped and recorded asstrategist.rejection_discarded. - The failover chain missed the failure it was built for. The four-model Gemini chain caught
APIError, but a client-sidehttpx.ReadTimeoutis not anAPIError, and a demo hung. The chain now catcheshttpx.TimeoutExceptionandTransportErroras well, with one attempt per model underLLM_TIMEOUT_MS. - The test suite could have truncated the production audit log. The agent reads that log back for cooldowns and promise windows.
conftest.pynow clearsDATABASE_URLfor the whole session. Destructive store tests run only against a separateSTORE_TEST_DATABASE_URL.
bugs.md is the running adversarial-review ledger: 65 findings, 48 resolved and 17 open, none of them critical. The open items are written up as fully as the fixed ones, including a payment-claim race under Postgres READ COMMITTED.
Quickstart
Requires Python 3.12+ (the ruff target in pyproject.toml).
git clone https://github.com/uditdaftary/RPay-build-recovery-agent.git
cd RPay-build-recovery-agent
pip install -r requirements.txt
cp .env.example .env
app/config.py refuses to import unless RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET are set. The placeholder values in .env.example satisfy that check, so the commands below need no real keys and no network:
python -m pytest # durable-store checks skip without STORE_TEST_DATABASE_URL
python run_experiment.py --seed 42 # offline benchmark
python -m app.ledger --seed 42 --check # ledger self-check
python verify_all.py # tests, ruff, ledger fingerprint, benchmark, leak scan
To run the web app:
python -m uvicorn app.server:app --reload --port 8000
| Route | Purpose |
|---|---|
/ |
Landing page and live demo link |
/r/{invoice_id} |
Debtor resolution page: pay, promise or dispute |
/operator |
Review queue, kill switch, decision log, audit export (needs OPERATOR_API_KEY) |
/results |
Benchmark dashboard |
/health |
Health check |
Anything beyond the offline benchmark needs real configuration. Every variable is documented in .env.example.
| Variable | Needed for |
|---|---|
RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET |
Real checkout (Razorpay test mode) |
RAZORPAY_WEBHOOK_SECRET |
Verifying payment.captured webhooks |
GOOGLE_API_KEY, LLM_MODEL, LLM_FALLBACK_MODELS |
--live-llm and live strategist decisions |
OPERATOR_API_KEY |
Operator console. No default; unset returns 401 |
DATABASE_URL |
Postgres for the audit log, invoice state, kill switch and review queue. Unset, these use a local file and process memory |
SEND_MODE, RESEND_API_KEY, FROM_EMAIL, ALLOWED_RECIPIENT |
Live email. Every message is redirected to the one allowlisted address |
Repository layout
app/envelope.py policy envelope (stage 1)
app/strategist.py LLM strategist, schema, post-checks, safe fallback (stage 2)
app/llm.py Gemini client with model failover chain
app/messages.py message drafting and anti-dark-pattern filter (stage 3)
app/pipeline.py batch pipeline: decide, draft, kill-switch check, queue or dispatch
app/operator.py review queue, kill switch, audit export
app/statute.py MSMED s.15/16 interest and s.43B(h)
app/disputes.py dispute classification and statutory clock reset
app/baseline.py calendar dunning baseline
app/ledger.py seeded synthetic ledger generator and fingerprint
app/audit.py, store.py append-only audit log; optional Postgres persistence
app/server.py FastAPI routes, Razorpay webhook, resolution page
run_experiment.py agent vs baseline evaluation harness
verify_all.py five-gate verification script
test_*.py test suites
ARCHITECTURE.md detailed component notes
bugs.md defect ledger
Reviews (0)
Sign in to leave a review.
Leave a reviewNo results found