PHP code example of bynn / decisionnode

1. Go to this page and download the library: Download bynn/decisionnode library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bynn / decisionnode example snippets


use Bynn\DecisionNode\DecisionNode;
use function Bynn\DecisionNode\{truth, choice, score};

$dn = new DecisionNode(); // reads DECISIONNODE_API_KEY

$d = $dn->decide(
    state: ['ticket' => 'I was charged twice and nobody has replied for 3 days.'],
    questions: [
        'route' => choice('Where should this go?', ['billing' => 'money', 'bug' => 'broken', 'account' => 'login']),
        'urgency' => score('How urgent is this?', ['routine', 'today', 'urgent', 'critical']),
        'escalate' => truth('Escalate to a human now?'),
    ],
);

$d['route']->choice;          // "billing"
$d['route']->probabilities;   // ["billing" => 0.87, "bug" => 0.08, "account" => 0.05]
$d['urgency']->score;         // 2.31
$d['escalate']->truth;        // 0.94

use function Bynn\DecisionNode\number;

$d = $dn->decide('Three cars and a van are parked outside.', ['vehicles' => number('How many vehicles?', 0, 20)]);
$d['vehicles']->number;          // 4
$d['vehicles']->expected;        // 4.08
$d['vehicles']->probabilities;   // [3 => 0.06, 4 => 0.87, 5 => 0.07]

$dn->decide('Paid 740 SEK at Nordic Rail.', [
    'currency' => ['type' => 'choice', 'instructions' => 'Which currency?', 'criteria' => ['SEK' => null, 'EUR' => null]],
]);

use Bynn\DecisionNode\Image;
use function Bynn\DecisionNode\{box, point, truth};

$d = $dn->decide(
    images: [Image::fromUrl('belt', 'https://files.example.com/line-3/cam-2/0917.jpg')],
    questions: [
        'pick' => point('Point to the yellow package closest to the robot arm.'),
        'damage' => box('Draw a box around the damaged package.', image: 'belt'),
        'any_damage' => truth('Is any package on the belt damaged?'),
    ],
);

$d['pick']->x;              // 812
$d['pick']->y;              // 455
$d['pick']->present;        // 0.97
$d['damage']->x1;           // 300 (and y1, x2, y2)
$d['damage']->confidence;   // 0.88
$d['any_damage']->truth;    // 0.93

$answer = $dn->check('Refund me now or I cancel.', 'Is the customer asking for a refund?');
$answer->truth; // 0.97

$results = $dn->decideMany([
    ['state' => $ticketA, 'questions' => ['spam' => truth('Is this spam?')]],
    ['state' => $ticketB, 'questions' => ['spam' => truth('Is this spam?')]],
]);
foreach ($results as $result) {
    if ($result instanceof \Bynn\DecisionNode\Exception\DecisionNodeError) {
        // this request failed; the others are unaffected
    }
}

$promise = $dn->decideAsync('...', ['q' => truth('...')]);
$decision = $promise->wait();

use Bynn\DecisionNode\Image;

$d = $dn->decide(
    state: ['claim' => ['total' => '740.00']],
    images: [Image::fromUrl('receipt', 'https://files.example.com/claims/4411/receipt.jpg')],
    questions: ['matches' => truth('Does the receipt show the claimed total?')],
);

Image::fromPath('receipt', __DIR__ . '/receipt.jpg');
Image::fromData('photo', $bytes);                 // media type read from the bytes
Image::fromData('scan', $bytes, 'image/png');      // a given media type must match the bytes
Image::fromBase64('scan', $base64);
Image::fromStream('scan', fopen('scan.webp', 'rb'));  // a resource or a PSR-7 stream
Image::fromUploadId('scan', 'upl_...');           // an upload made earlier, within its hour

$d = $dn->decide(
    state: 'Expense claim 4411: 740.00 EUR.',
    images: [
        Image::fromUrl('receipt', 'https://files.example.com/claims/4411/receipt.jpg'),
        Image::fromUrl('claim_photo', 'https://files.example.com/claims/4411/photo.jpg'),
    ],
    questions: ['matches' => truth('Does the total on `receipt` match the amount in the claim?')],
);

use Bynn\DecisionNode\{Video, VideoFrame};

$d = $dn->decide(
    state: 'Warehouse camera 4, loading dock, shift B.',
    videos: [
        Video::of('dock', [
            VideoFrame::fromPath(30.0, '/frames/dock-0001.jpg'),
            VideoFrame::fromPath(30.5, '/frames/dock-0002.jpg'),
            VideoFrame::fromData(31.0, $jpegBytes),
        ]),
    ],
    questions: ['fall' => truth('Does a person fall in the video?')],
);

$d['fall']->truth;
$d->usage->videoFrames;    // the frames the API read
$d->usage->videoSeconds;   // the seconds of video they cover
$d->warnings;              // for example, a video read at a lower rate than asked

VideoFrame::fromData(0.5, $bytes);                   // JPEG, PNG or WebP; the media type is read from the bytes
VideoFrame::fromBase64(0.5, $base64, 'image/jpeg');  // base64 text, sent as given, with its media type
VideoFrame::fromPath(0.5, '/frames/0002.jpg');       // read when the VideoFrame is made

Video::of('dock', $frames, fps: 4, start: 30, end: 60);

use Bynn\DecisionNode\{AgeReading, AiGeneratedReading, Image};

$d = $dn->decide(
    images: [
        Image::fromUrl('selfie', 'https://files.example.com/signup/88/selfie.jpg'),
        Image::fromUrl('listing', 'https://files.example.com/listings/4411/photo.jpg'),
    ],
    boosters: ['age', 'ai_generated'],
    questions: [
        'adult' => truth('Is the person in `selfie` an adult?'),
        'synthetic' => truth('Is `listing` AI-generated?'),
    ],
);

$d['adult']->truth;
foreach ($d->evidence['age']->results as $reading) {
    if ($reading instanceof AgeReading && $reading->faces > 0) {
        echo "{$reading->image}: about {$reading->ageYears} ({$reading->low} to {$reading->high})\n";
    }
}
foreach ($d->evidence['ai_generated']->results as $reading) {
    if ($reading instanceof AiGeneratedReading) {
        echo "{$reading->image}: {$reading->generated} by {$reading->method}\n";
    }
}
$d->usage->boosterTokens;  // the readings' share of the input tokens
$d->usage->boosters;       // the booster calls billed

use Bynn\DecisionNode\Booster;

$boosters = ['age', new Booster('ai_generated', images: ['listing'], 

$d = $dn->decide(
    questions: ['pad_ahead' => truth('Is there a landing pad in front of the drone?')],
    images: [Image::fromUrl('front', 'https://files.example.com/drone/7/front.jpg')],
    boosters: [Booster::depth(8), Booster::segment('landing pad')],
);
foreach ($d->evidence['bynn_segment']->results as $r) {
    if ($r instanceof \Bynn\DecisionNode\SegmentReading) {
        foreach ($r->instances as $m) {
            echo $m['label'], ' ', $m['score'], ' ', implode(',', $m['centroid']), "\n";
        }
    }
}

$col = $dn->collections->create('Staff, Stockholm office');
$item = $dn->collections->enroll(
    $col->id,
    Image::fromUrl('badge', 'https://files.example.com/badges/emp-1042.jpg'),
    reference: 'emp-1042',
    label: 'Reception',
    metadata: ['site' => 'stockholm', 'floor' => 3],
);
$page = $dn->collections->listItems($col->id, referencePrefix: 'emp-');
$item = $dn->collections->updateItem($col->id, $item->id, label: null);

use Bynn\DecisionNode\Document;

$kb = $dn->collections->create('Claims policy', type: 'text', scopeKey: 'mission');

// Markdown (or plain text) held in memory is sent inline.
$rules = $dn->collections->addDocument(
    $kb->id,
    Document::fromText("# Receipts\n\nReject any claim over 500 SEK without a receipt."),
    title: 'Claims policy 2026',
    reference: 'policy-2026',
);

// A file from a path: uploaded, then converted to text.
$manual = $dn->collections->addDocument($kb->id, Document::fromPath('handbooks/claims-handbook.pdf'));

$manual = $dn->collections->waitUntilReady($kb->id, $manual->id);   // 'ready' or 'failed'

$dn->collections->addDocument($kb->id, Document::fromText('Never approve a claim for a vehicle marked as stolen.'),
    title: 'Stolen vehicles', pinned: true, pinRank: 0);

$dn->collections->addDocument($kb->id, Document::fromPath('missions/m-42-brief.md'), metadata: ['mission' => 'M-42']);

use Bynn\DecisionNode\{Booster, KnowledgeReading};

$d = $dn->decide(
    state: ['claim' => 'Windscreen, 620 SEK, no receipt attached.'],
    questions: ['approve' => truth('Approve this claim?')],
    boosters: [Booster::knowledge($kb->id, scope: 'M-42', })\n";
    }
}

$found = $dn->collections->search($kb->id, 'receipts for windscreen claims', scope: 'M-42', topK: 5);

$one = $dn->usage->key('key_7c2e9a41b0d34f6e8a5c1d2b3e4f5a60', granularity: 'day');   // the UTC month so far
echo $one->totals['cost']['usd'], PHP_EOL;

foreach ($dn->usage->all('2026-09-01T00:00:00Z', '2026-10-01T00:00:00Z', labels: ['customer' => 'acme']) as $item) {
    echo $item->key['name'], ' ', $item->totals['requests'], ' ', $item->totals['cost']['usd'], PHP_EOL;
}

$manage = new DecisionNode(apiKey: getenv('DECISIONNODE_MANAGE_KEY') ?: null);

$made = $manage->keys->create(
    'Kiosk 0412',
    deviceId: 'kiosk-0412',
    labels: ['store' => '118', 'fw' => '2.4'],
    limits: ['requests_per_second' => 5, 'tokens_per_second' => 20000],
    dailySpendCapUsd: 2.0,
    expiresAt: '2027-10-13T00:00:00Z',
    idempotencyKey: 'enroll-kiosk-0412',   // a retry returns the same key and secret
);
// hand $made->secret to the device once, over your own channel; never log it. Keep $made->key->id.

$page = $manage->keys->list(labels: ['store' => '118']);
$manage->keys->update($made->key->id, labels: ['store' => '119']);
$manage->keys->revoke($made->key->id);

$counted = $manage->keys->revokeByLabels(['fw' => '2.4'], dryRun: true);   // $counted->wouldRevoke
do {
    $done = $manage->keys->revokeByLabels(['fw' => '2.4']);
} while ($done->more);

$session = $dn->openSession(
    state: ['mission' => 'Survey the north field'],
    questions: [
        'mode' => choice('Which flight mode now?', ['continue' => 'keep flying', 'hold' => 'hover', 'land' => 'land now']),
        'abort' => truth('Should the mission be aborted now?'),
    ],
);
$session->connect();
$session->send(frame: ['battery' => 0.31, 'wind_mps' => 11.4]);

foreach ($session->replies() as $event) {
    if ($event instanceof \Bynn\DecisionNode\Reply) {
        $event->answers['abort']->truth;
    } elseif ($event instanceof \Bynn\DecisionNode\FrameError) {
        // this frame was not answered: $event->errorType, $event->retryAfterMs
    } else {
        // a SessionClosed: $event->closeCode, $event->reopen
    }
}
$session->end();

$closed = $dn->supervise(
    ['state' => ['mission' => 'Survey'], 'questions' => ['abort' => truth('Abort?')]],
    $telemetry,   // any iterable of send() arguments, such as ['frame' => [...]]
    function ($reply) { /* ... */ },
);

[$batch, $results] = $dn->runBatch([
    ['custom_id' => 'ticket-1', 'state' => 'I was charged twice.', 'questions' => ['refund' => truth('Is a refund asked for?')]],
    ['custom_id' => 'ticket-2', 'state' => 'The app crashes.', 'questions' => ['refund' => truth('Is a refund asked for?')]],
], pollInterval: 60);

foreach ($results as $line) {
    $line->customId;
    $line->decision?->answers['refund']->truth;   // a 200 line
    $line->error;                                 // any other line: the error decide() would have raised, as a value
}

use Bynn\DecisionNode\Exception\{DecisionNodeError, RateLimitError, ValidationError};

try {
    $d = $dn->decide($state, $questions);
} catch (ValidationError $e) {
    var_dump($e->entries);
} catch (RateLimitError $e) {
    sleep((int) ceil($e->retryAfter ?? 1));
} catch (DecisionNodeError $e) {
    error_log($e->getMessage() . ' ' . $e->requestId);
}

$dn->checkRequest('decide', ['state' => $state, 'questions' => $questions, 'images' => $images, 'videos' => $videos]);
$dn->checkRequest('openSession', ['questions' => $questions, 'window' => 16]);
$dn->checkRequest('batches.create', ['requests' => $requests]);   // also batches.add
$session->checkFrame(frame: $reading, questions: ['abort']);

$dn = new DecisionNode(timeout: 5.0, maxRetries: 4);

$dn = new DecisionNode(headers: ['x-decisionnode-safety-body' => 'true']);

$d = $dn->decide('...', ['q' => truth('...')]);
$d->safety;          // parsed from the x-decisionnode-safety header, as always
$d->raw['safety'];   // the same scores, from the body

$dn = new DecisionNode(
    apiKey: 'your-api-key',
    model: 'decisionnode-flash',
    headers: ['x-team' => 'billing'], // sent with every request
);

$dn = new DecisionNode(httpClient: new \GuzzleHttp\Client(['proxy' => 'http://proxy.example.com:3128']));