PHP code example of binnash / typesafe-sdk

1. Go to this page and download the library: Download binnash/typesafe-sdk 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/ */

    

binnash / typesafe-sdk example snippets


use Binnash\Typesafe\TypeSafe;

$client = TypeSafe::client('your-api-key');

use Binnash\Typesafe\Support\Question;
use Binnash\Typesafe\TypeSafe;

$client = TypeSafe::client('your-api-key');

$result = $client->systemOne(
    state: [
        'subject' => 'Charged twice this month',
        'body' => 'I see two charges of $49 on my card. Please fix this ASAP.',
    ],
    questions: [
        'is_billing' => Question::noul('Is this ticket about billing?'),
        'tone' => Question::choice("What is the customer's tone?", [
            'calm' => null,
            'frustrated' => null,
            'angry' => null,
        ]),
        'urgency' => Question::score('How urgent is this ticket?', ['can wait', 'this week', 'today']),
    ],
);

$result->answers->is_billing->noul;               // 0.94
$result->answers->tone->choice;                   // "frustrated"
$result->answers->urgency->score;                 // 1.6, may land between levels
$result->usage->inputTokens;                      // 312
$result->requestId;                               // "req_..." for support and tracing

use Binnash\Typesafe\Support\Question;

use Binnash\Typesafe\Support\Question;

Question::noul('Does this convey urgency?');

Question::noul('Does this convey urgency?', [
    'true' => 'Explicitly time-sensitive',
    'false' => 'No urgency expressed',
]);

$answer = $result->answers->is_urgent;
$answer->noul;            // 0.92
$answer->isYes();         // true, using the default 0.5 threshold
$answer->isYes(0.9);      // true, using your own threshold

use Binnash\Typesafe\Support\Question;

Question::choice('Which team should handle this?', [
    'billing' => 'Payments, invoicing, refunds',
    'technical' => 'Bugs, outages, integrations',
    'sales' => null, // null when the label needs no extra detail
]);

$answer = $result->answers->department;
$answer->choice;                            // "technical"
$answer->confidence;                        // 0.82
$answer->probabilities;                     // ['billing' => 0.08, 'technical' => 0.85, 'sales' => 0.07]
$answer->probabilityOf('technical');        // 0.85

use Binnash\Typesafe\Support\Question;

Question::score('How frustrated is the customer?', ['Calm', 'Frustrated', 'Very angry']);

$answer = $result->answers->frustration;
$answer->score;                             // 1.6 — between "Frustrated" and "Very angry"
$answer->legend;                            // [0 => 'Calm', 1 => 'Frustrated', 2 => 'Very angry']
$answer->levelDescription(2);               // "Very angry"
$answer->probabilityOf(1);                  // 0.3
$answer->confidence;                        // 0.78

use Binnash\Typesafe\Support\Question;

Question::noul('Is the customer reporting a duplicate charge?', [
    'true' => [
        'meaning' => 'the same amount charged more than once',
        'examples' => ['billed twice'],
    ],
]);

Question::choice('Are these the same incident?', [
    'same' => ['match_on' => 'actors, action, location, occurrence time'],
    'different' => ['distinguish_by' => 'occurrence time or distinguishing numbers'],
]);

$answers = $result->answers;

$answers->tone;               // ChoiceResponse|null
$answers['tone'];             // ChoiceResponse|null
$answers->has('tone');        // true
$answers->get('tone');        // throws when the answer is missing
$answers->names();            // ['is_billing', 'tone', 'urgency']
$answers->all();              // every answer as an array

$answers->noul('is_billing'); // NoulResponse, throws on a type mismatch
$answers->choice('tone');     // ChoiceResponse
$answers->score('urgency');   // ScoreResponse

use Binnash\Typesafe\Config\ClientConfig;
use Binnash\Typesafe\Retry\RetryPolicy;
use Binnash\Typesafe\TypeSafeClient;

$config = new ClientConfig(
    apiKey: 'your-api-key',
    baseURL: 'https://api.typesafe.ai',
    defaultModel: 'jev-latest',
    timeout: 10.0,                       // seconds, per attempt
    retryPolicy: new RetryPolicy(maxRetries: 2),
    logger: $psr3Logger,                 // optional PSR-3 logger
    logLevel: 'warn',                    // debug | info | warn | error | off
    defaultHeaders: ['X-Team' => 'support'],
    httpClient: $psr18Client,            // optional overrides; discovered otherwise
    requestFactory: $psr17RequestFactory,
    streamFactory: $psr17StreamFactory,
);

$client = new TypeSafeClient($config);

use Binnash\Typesafe\Support\Question;

$result = $client->systemOne(
    state: $ticket,
    questions: ['tone' => Question::choice('Tone?', ['calm' => null, 'upset' => null])],
    model: 'jev-1.13.0',                                  // pin a version
    options: [
        'headers' => ['X-Trace' => $request->id()],
        'timeout' => 30.0,
        'retry' => ['maxRetries' => 0],                   // or a RetryPolicy instance
    ],
    extra: ['future_option' => null],                     // forwarded, never overriding state/model/questions
);

$response = $client->systemOneWithResponse($state, $questions);

$response->status;                 // 200
$response->requestId;              // "req_..."
$response->header('retry-after');  // null when absent
$response->data;                   // raw response body

use Binnash\Typesafe\Retry\RetryPolicy;

$policy = new RetryPolicy(maxRetries: 4, backoffInitialMs: 250);

$client = TypeSafe::client('key', ['retryPolicy' => $policy]);
$limited = $policy->with(maxRetries: 0);           // a copy with one setting changed

$client->models->list(['retry' => ['maxRetries' => 0]]);   // per call

use Binnash\Typesafe\Exceptions\ApiException;
use Binnash\Typesafe\Exceptions\RateLimitException;

try {
    $client->models->list();
} catch (RateLimitException $e) {
    $e->retryAfterMs;                    // 2500, when the server asked for a delay
} catch (ApiException $e) {
    $e->status;                          // 422
    $e->requestId;                       // "req_..."
    $e->getMessage();                    // '422 questions.q.score.criteria.0: Input should be a valid string'
    $e->body;                            // the decoded response body
}

use Binnash\Typesafe\Config\ClientConfig;
use Binnash\Typesafe\TypeSafeClient;

$client = new TypeSafeClient(new ClientConfig(
    apiKey: 'your-api-key',
    logger: $logger,  // any PSR-3 logger, such as Monolog
    logLevel: 'info', // debug | info | warn | error | off
));

foreach ($client->models->list() as $model) {
    echo $model->name, ' ', $model->releaseDate, PHP_EOL;
    $model->description;
}

$response = $client->models->listWithResponse();
$response->requestId;
$response->data;                       // the raw { "models": [...] } payload

use Binnash\Typesafe\Laravel\Facades\TypeSafe;
use Binnash\Typesafe\Support\Question;

$result = TypeSafe::systemOne(
    state: $ticket,
    questions: [
        'is_billing' => Question::noul('Is this ticket about billing?'),
        'urgency' => Question::score('How urgent is this?', ['can wait', 'this week', 'today']),
    ],
);

$result->answers->is_billing->noul;

$models = TypeSafe::models()->list();

use Binnash\Typesafe\Support\Question;
use Binnash\Typesafe\TypeSafeClient;

final class TriageTicket
{
    public function __construct(private readonly TypeSafeClient $typeSafe) {}

    public function handle(Ticket $ticket): void
    {
        $result = $this->typeSafe->systemOne(
            state: ['subject' => $ticket->subject, 'body' => $ticket->body],
            questions: ['urgency' => Question::score('How urgent?', ['can wait', 'this week', 'today'])],
            options: ['retry' => ['maxRetries' => 0]], // per call, for queue jobs with their own retries
        );

        $ticket->update(['urgency' => $result->answers->urgency->score]);
    }
}

use Psr\Http\Client\ClientInterface;

$this->app->instance(ClientInterface::class, $fakeClient);
sh
php artisan vendor:publish --tag=typesafe-config