Voice AI

Building a Durable Chargeback Adjudicator with Telnyx Decision Models and Edge Actors

When a patient disputes a medical charge, the billing team has a narrow window — often 7 to 30 days — to submit evidence or risk an automatic loss of funds. Miss the deadline, lose the money, face compliance scrutiny, erode patient trust. Most clinics handle this with spreadsheets, email threads, and calendar reminders. It works until it doesn't.

What if, instead, every chargeback became a self-managing case? Born the moment a webhook fires, it assembles evidence, calls a live Decision Model to rule, arms a deadline timer, and keeps an append-only audit ledger. When the patient replies with a photo of their delivered medication, the case re-wakes with the full prior transcript, re-runs the Decision Model, and updates the verdict. If the platform reboots mid-decision, the case survives — its state, its deadline, and its ledger all durable across restarts.

That's exactly what the chargeback-adjudication sample does. Built on Telnyx Edge Compute with the Agent SDK, it turns a race against the clock into a managed, auditable workflow.

What the App Does

The sample implements a single durable actor — DisputeCase — that represents one chargeback from birth to resolution. Here's the lifecycle:

  1. Birth: A POST /webhook/chargeback fires. The Edge Fetch handler looks up (or creates) a DisputeCase actor keyed by disputeId. The actor seeds evidence rows into SQL (orders, deliveries, contact logs), computes a regulatory deadline, and arms a decide:<disputeId> scheduled task.
  1. Adjudication: The decide() task handler assembles all evidence from SQL, calls the Telnyx Decision Models API, and applies a policy based on the result. The Decision Model returns three answers:

- answers.decision.choice — one of approve_rebate, request_evidence, or deny - answers.loseProb.score — probability of losing the dispute (0–1) - answers.fraud.noul — fraud likelihood (0–1)

  1. Policy Routing:

- If noul > 0.8, the case is routed to a human reviewer: inserted into a reviewQueue, the on-call reviewer is paged via SMS, and the customer is notified — never auto-rebated. - If choice = approve_rebate, the customer is SMS'd a refund confirmation and the case is marked decided. - If choice = request_evidence, the customer is SMS'd an evidence request and a respond:<disputeId> deadline timer is armed. - If choice = deny, the customer is SMS'd a denial notice and the case is marked decided.

  1. Deadline Enforcement: If the respond:<disputeId> timer fires and the case is still undecided, it auto-loses with a full audit trail.
  1. Re-evaluation: When the customer replies via POST /webhook/inbound-message, the actor re-wakes, assembles the new evidence (including any media URL), re-calls the Decision Model, and updates the verdict — all while preserving the full audit history.

How It Works

The Actor Model on Telnyx Edge

The DisputeCase actor is registered via the Agent SDK's actor system. Each dispute gets its own durable actor instance, self-provisioned on webhook:

const actorId = this.env.DISPUTES.idFromName(disputeId);
const stub = this.env.DISPUTES.get(actorId);
await stub.onChargeback(payload);

The actor's state — current status, deadline timestamp, decision history — is persisted automatically by the Edge runtime. Scheduled tasks (decide:<id>, respond:<id>) are exactly-once and survive restarts.

Calling Telnyx Decision Models

The judgeWithDecisionModel method calls POST /v2/ai/typesafe/v1/systemone with a JSON stringified state object and a questions array. Each question uses a criteria map or rubric to define the expected output shape:

const response = await fetch(
  "https://api.telnyx.com/v2/ai/typesafe/v1/systemone",
  {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${this.env.TELNYX_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      state: JSON.stringify(evidenceState),
      questions: [
        {
          key: "decision",
          criteria: {
            type: "choice",
            options: ["approve_rebate", "request_evidence", "deny"],
          },
        },
        {
          key: "loseProb",
          criteria: {
            type: "score",
            min: 0,
            max: 1,
          },
        },
        {
          key: "fraud",
          criteria: {
            type: "noul",
            min: 0,
            max: 1,
          },
        },
      ],
    }),
  }
);

const result = await response.json();
const choice = result.answers.decision.choice;
const loseProb = result.answers.loseProb.score;
const fraudScore = result.answers.fraud.noul;

The method includes retry-with-backoff for 429s and 502s, and throws immediately on 4xx errors (malformed request or auth failure).

The Append-Only Audit Ledger

Every state transition — birth, decision, policy application, deadline enforcement, re-evaluation — is appended to a SQL table:

CREATE TABLE IF NOT EXISTS audit (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  dispute_id TEXT NOT NULL,
  event TEXT NOT NULL,
  payload TEXT,
  timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

An examiner can replay the entire case history by querying SELECT * FROM audit WHERE dispute_id = ? ORDER BY id.

SMS Notifications via Telnyx Messaging

Customer notifications and evidence requests are sent through the Telnyx Messaging API:

if (this.env.DEMO_MODE === "true") {
  console.log(`[DEMO] SMS to ${customer}: ${text}`);
} else {
  await this.env.TELNYX.messages.send({
    from: this.env.TELNYX_PHONE_NUMBER,
    to: customer,
    text: text,
  });
}

Setup

# 1. Clone the repository
git clone https://github.com/team-telnyx/telnyx-code-examples.git
cd telnyx-code-examples/chargeback-adjudication

# 2. Install dependencies
npm install

# 3. Configure environment
cp .env.example .env
# Edit .env and set your TELNYX_API_KEY

# 4. Authenticate with Telnyx Edge
telnyx-edge auth api-key set <your_telnyx_api_key>

# 5. Run the smoke test
npx tsx smoke_test.ts

# 6. Deploy
telnyx-edge ship

Environment Variables

VariableRequiredDefaultDescription
TELNYX_API_KEYYes—Your Telnyx API key
RESPONSE_DEADLINE_DAYSNo7Fallback deadline in days
REVIEWER_ONCALL_E164No—Phone number to page on fraud holds
DEMO_MODENotrueWhen true, SMS is logged to console

Why This Matters

Chargeback adjudication is a textbook example of a workflow that demands both intelligence and durability. You need a live judge (Decision Models) to score evidence and rule on outcomes. You need durable actors (Agent SDK) to survive restarts and span days. You need reliable messaging (Messaging API) to communicate with customers. And you need an audit trail (SQL ledger) that stands up to compliance scrutiny.

Telnyx provides AI Communications Infrastructure — the durable, programmable foundation that lets applications reason about real-world events and act on them reliably. This sample shows how to compose those primitives into a system that never forgets a deadline, never loses evidence, and can re-evaluate a case when new information arrives days later.

The full source code is available at https://github.com/team-telnyx/telnyx-code-examples/tree/main/chargeback-adjudication.

Ready to build with low-latency voice AI?

Join developers building the future of real-time conversations