Unified LLM API, structured data outputs with LLMs, and agent SDK - in PHP
Unified LLM API, structured data outputs with LLMs, and agent SDK - in PHP
This monorepo contains a set of dev-friendly, framework agnostic components offering 3 main capabilities:
Framework integration packages:
packages/symfonyThe library offers a set of small, focused building blocks.
Purpose: turn messy model output into typed PHP data. Benefit: you stop hand-parsing JSON or text before using LLM results.
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();
Detailed docs: packages/instructor/docs/
Purpose: call different LLM providers through one API. Benefit: switch providers without rewriting request code.
use Cognesy\Polyglot\Inference\Inference;
$text = Inference::using('openai')
->withMessages('Say hello in one sentence.')
->get();
Detailed docs: packages/polyglot/docs/
Purpose: generate vectors through the same provider layer. Benefit: keep retrieval and inference in one stack.
use Cognesy\Polyglot\Embeddings\Embeddings;
$vectors = Embeddings::using('openai')
->withInputs(['hello world'])
->vectors();
Detailed docs: packages/polyglot/docs/
Purpose: build tool-using agents as a simple loop over state. Benefit: add tools and control flow without inventing your own agent runtime first.
use Cognesy\Agents\AgentLoop;
use Cognesy\Agents\Data\AgentState;
$result = AgentLoop::default()->execute(
AgentState::empty()->withUserMessage('What is 2+2?')
);
Detailed docs: packages/agents/docs/
Purpose: drive external coding agents like Codex, Claude Code, and OpenCode from PHP. Benefit: automate reviews, summaries, and coding workflows through one interface.
use Cognesy\AgentCtrl\AgentCtrl;
$response = AgentCtrl::codex()->execute('Summarize this repository.');
Detailed docs: packages/agent-ctrl/docs/
Purpose: install framework-native runtime wiring instead of assembling your own glue. Benefit: get a supported bundle or package surface for container bindings, events, observability, and testing.
Symfony docs highlights:
Instructor is a library that allows you to extract structured, validated data from multiple types of inputs: text, images or OpenAI style chat sequence arrays. It is powered by Large Language Models (LLMs).
Instructor simplifies LLM integration in PHP projects. It handles the complexity of extracting structured data from LLM outputs, so you can focus on building your application logic and iterate faster.
Instructor for PHP is inspired by the Instructor library for Python created by Jason Liu.
Here's a simple CLI demo app using Instructor to extract structured data from text:
Instructor introduces three key enhancements compared to direct API usage.
Specify a PHP class to extract data into via the 'magic' of LLM chat completion. And that's it.
Instructor reduces brittleness of the code extracting the information from textual data by leveraging structured LLM responses.
Instructor helps you write simpler, easier to understand code: you no longer have to define lengthy function call definitions or write code for assigning returned JSON into target data objects.
Response model generated by LLM can be automatically validated, following set of rules. Currently, Instructor supports only Symfony validation.
You can also provide a context object to use enhanced validator capabilities.
You can set the number of retry attempts for requests.
Instructor will repeat requests in case of validation or deserialization error up to the specified number of times, trying to get a valid response from LLM.
Instructor offers out-of-the-box support for the following LLM providers:
For usage examples, check Hub section or examples directory in the code repository.
You can install Instructor via Composer:
composer require cognesy/instructor-php
This is a simple example demonstrating how Instructor retrieves structured information from provided text (or chat message sequence).
Response model class is a plain PHP class with typehints specifying the types of fields of the object.
…
NOTE: Instructor supports classes / objects as response models. In case you want to extract simple types or enums, you need to wrap them in Scalar adapter - see section below: Extracting Scalar Values.
Instructor validates results of LLM response against validation rules specified in your data model.
For further details on available validation rules, check Symfony Validation constraints.
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
In case maxRetries parameter is provided and LLM response does not meet validation criteria, Instructor will make subsequent inference attempts until results meet the requirements or maxRetries is reached.
Instructor uses validation errors to inform LLM on the problems identified in the response, so that LLM can try self-correcting in the next attempt.
…
Instructor supports multiple output modes through Cognesy\Instructor\Enums\OutputMode to allow working with various models depending on their capabilities.
OutputMode::Json - generate structured output via LLM's native JSON generation OutputMode::JsonSchema - use LLM's strict JSON Schema mode to enforce JSON SchemaOutputMode::Tools - use tool calling API to get LLM follow provided schemaOutputMode::MdJson - use prompting to generate structured output; fallback for the models that do not support JSON generation or tool callingAdditionally, you can use OutputMode::Text to get LLM to generate text output without any structured data extraction.
OutputMode::Text - generate text outputOutputMode::Unrestricted - generate unrestricted output based on inputs provided by the user (with no enforcement of specific output format)Instructor ecosystem uses Polyglot as an unified inference API layer supporting 20+ LLM providers.
Polyglot takes care of translation of familiar OpenAI chat completion API conventions into LLM provider specific idioms / APIs, so you can easily switch between LLM providers without rewriting your LLM connectivity code.
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;
Check out the documentation website for more details and examples of how to use Instructor for PHP.
Cognesy\Instructor\Enums\OutputModeOutputMode::Json - use response_format to get LLM follow provided JSON SchemaOutputMode::JsonSchema - use strict JSON Schema mode to get LLM follow provided JSON SchemaOutputMode::Tools - use tool calling API to get LLM follow provided JSON SchemaOutputMode::MdJson - extract via prompting LLM to nudge it to generate provided JSON SchemaNo open issues yet, or sync has not completed.