PHP code example of valksor / typesafe-sdk-php

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

    

valksor / typesafe-sdk-php example snippets




declare(strict_types=1);

use TypeSafe\Choice;
use TypeSafe\Client;

$client = new Client();
$response = $client->systemOne(
    state: ['document' => 'I was charged twice. Please fix this ASAP.'],
    questions: [
        'category' => new Choice(
            instructions: 'What is this ticket about?',
            criteria: ['billing' => null, 'technical' => null, 'other' => null],
        ),
    ],
);

$category = $response->choice('category');
echo $category?->choice;



declare(strict_types=1);

use TypeSafe\Choice;
use TypeSafe\Client;
use TypeSafe\Noul;
use TypeSafe\ResponseModel;
use TypeSafe\SystemOneResponse;

final readonly class Triage implements ResponseModel
{
    public function __construct(
        public float $spam,
        public string $category,
    ) {}

    public static function fromSystemOne(SystemOneResponse $response): static
    {
        // Extract null-safely: an omitted or unknown answer returns null.
        $spam = $response->noul('spam')
            ?? throw new \UnexpectedValueException('missing answer "spam"');
        $category = $response->choice('category')
            ?? throw new \UnexpectedValueException('missing answer "category"');

        return new self(spam: $spam->noul, category: $category->choice);
    }
}

$client = new Client();
$triage = $client->systemOne(
    state: ['document' => 'I was charged twice.'],
    questions: [
        'spam' => new Noul('Is this spam?'),
        'category' => new Choice('What is this about?', ['billing' => null, 'other' => null]),
    ],
    responseModel: Triage::class,
);
echo $triage->category;

use TypeSafe\ApiError;
use TypeSafe\RateLimitError;

try {
    $response = $client->systemOne(state: $state, questions: $questions);
} catch (RateLimitError $e) {
    // back off and retry
} catch (ApiError $e) {
    error_log("api error {$e->statusCode} (request {$e->requestId}): {$e->getMessage()}");
}