PHP code example of cognesy / instructor-php

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

    

cognesy / instructor-php example snippets


use Cognesy\Instructor\StructuredOutput;

final class Person {
    public string $name;
    public int $age;
}

$person = StructuredOutput::using('openai')
    ->with(messages: 'Jason is 28 years old.', responseModel: Person::class)
    ->get();

use Cognesy\Polyglot\Inference\Inference;

$text = Inference::using('openai')
    ->withMessages('Say hello in one sentence.')
    ->get();

use Cognesy\Messages\Messages;
use Cognesy\Polyglot\BatchInference\BatchInference;
use Cognesy\Polyglot\BatchInference\Collections\BatchItems;
use Cognesy\Polyglot\BatchInference\Data\BatchItem;
use Cognesy\Polyglot\Inference\Data\InferenceRequest;

$batches = BatchInference::using('mistral');
$job = $batches->submit(BatchItems::of(
    BatchItem::of('summary-1', new InferenceRequest(
        messages: Messages::fromString('Summarize this document.'),
    )),
));

$reference = $job->reference(); // persist $reference->toArray() to resume later
$job = $batches->retrieve($reference); // check status when needed

use Cognesy\Polyglot\Embeddings\Embeddings;

$vectors = Embeddings::using('openai')
    ->withInputs(['hello world'])
    ->vectors();

use Cognesy\Polyglot\Decision\Collections\Questions;
use Cognesy\Polyglot\Decision\Decision;
use Cognesy\Polyglot\Decision\Questions\Noul;

$answers = Decision::using('typesafe')
    ->with(
        input: 'I was charged twice. Please refund the duplicate.',
        questions: Questions::of(new Noul(
            id: 'refund_requested',
            instructions: 'Does the customer explicitly request a refund?',
        )),
    )
    ->get();

$refundProbability = $answers->noul('refund_requested')->probability();

use Cognesy\Retrieval\Retrieval;
use Cognesy\Retrieval\Query\VectorQuery;

$hits = Retrieval::fromStore($store)
    ->withQuery(new VectorQuery($queryVector, maxResults: 5))
    ->get();

use Cognesy\Agents\AgentLoop;
use Cognesy\Agents\Data\AgentState;

$result = AgentLoop::default()->execute(
    AgentState::empty()->withUserMessage('What is 2+2?')
);

use Cognesy\AgentCtrl\AgentCtrl;

$response = AgentCtrl::codex()->execute('Summarize this repository.');

use Cognesy\Instructor\StructuredOutput;

// Step 0: Create .env file in your project root:
// OPENAI_API_KEY=your_api_key

// Step 1: Define target data structure(s)
class Person {
    public string $name;
    public int $age;
}

// Step 2: Provide content to process
$text = "His name is Jason and he is 28 years old.";

// Step 3: Use Instructor to run LLM inference
$person = (new StructuredOutput)
    ->withResponseClass(Person::class)
    ->withMessages($text)
    ->get();

// Step 4: Work with structured response data
assert($person instanceof Person); // true
assert($person->name === 'Jason'); // true
assert($person->age === 28); // true

echo $person->name; // Jason
echo $person->age; // 28

var_dump($person);
// Person {
//     name: "Jason",
//     age: 28
// }    

use Cognesy\Instructor\StructuredOutput;
use Symfony\Component\Validator\Constraints as Assert;

class Person {
    public string $name;
    #[Assert\PositiveOrZero]
    public int $age;
}

$text = "His name is Jason, he is -28 years old.";
$person = (new StructuredOutput)
    ->withResponseClass(Person::class)
    ->with(
        messages: [['role' => 'user', 'content' => $text]],
    )
    ->get();

// if the resulting object does not validate, Instructor throws an exception

use Cognesy\Instructor\StructuredOutput;
use Cognesy\Instructor\StructuredOutputRuntime;
use Cognesy\Polyglot\Inference\LLMProvider;
use Symfony\Component\Validator\Constraints as Assert;

class Person {
    #[Assert\Length(min: 3)]
    public string $name;
    #[Assert\PositiveOrZero]
    public int $age;
}

$text = "His name is JX, aka Jason, he is -28 years old.";
$runtime = StructuredOutputRuntime::fromProvider(LLMProvider::new())
    ->withMaxRetries(3);

$person = (new StructuredOutput($runtime))
    ->with(
        messages: [['role' => 'user', 'content' => $text]],
        responseModel: Person::class,
    )
    ->get();

// if all LLM's attempts to self-correct the results fail, Instructor throws an exception

use Cognesy\Polyglot\Inference\Inference;

$message = Inference::using('openai') // specify LLM connection preset (defined in config)
    ->with(messages: 'What is capital of Germany')
    ->get();

echo $message->content()->toString();

use Cognesy\Polyglot\Inference\Inference;

$stream = Inference::using('anthropic') // specify LLM connection preset (defined in config)
    ->withMessages([['role' => 'user', 'content' => 'Describe capital of Brasil']])
    ->withOptions(['max_tokens' => 256])
    ->withStreaming()
    ->stream()
    ->deltas();

foreach ($stream as $delta) {
    echo $delta->messageChunks->textDelta();
}

use Cognesy\Polyglot\Inference\Config\LLMConfig;
use Cognesy\Polyglot\Inference\Inference;

$answer = Inference::fromConfig(LLMConfig::fromArray([
    'driver' => 'deepseek',
    'apiUrl' => 'https://api.deepseek.com',
    'endpoint' => '/chat/completions',
    'model' => 'deepseek-v4-flash',
]))
    ->withMessages([['role' => 'user', 'content' => 'What is the capital of France']])
    ->withOptions(['max_tokens' => 64])
    ->get();

echo $answer;
bash
composer