PHPackages                             cognesy/instructor-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. cognesy/instructor-php

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

cognesy/instructor-php
======================

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

v2.2.0(2mo ago)310107.9k↑44.6%24[2 issues](https://github.com/cognesy/instructor-php/issues)1MITPHPPHP ^8.3|^8.4|^8.5CI passing

Since Feb 27Pushed 2mo ago7 watchersCompare

[ Source](https://github.com/cognesy/instructor-php)[ Packagist](https://packagist.org/packages/cognesy/instructor-php)[ RSS](/packages/cognesy-instructor-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (94)Versions (196)Used By (1)

About This Monorepo
===================

[](#about-this-monorepo)

This monorepo contains a set of dev-friendly, framework agnostic components offering 3 main capabilities:

- **Instructor for PHP** - structured data extraction in PHP - powered by LLMs, designed for simplicity, transparency, and control; supports custom LLM output processors (not just JSON),
- **Polyglot for PHP** - unified LLM API - write code once, deploy with any LLM provider: OpenAI chat completions API, OpenAI responses API, Anthropic, Gemini, Ollama, etc.; you can write own LLM drivers,
- **Agent SDK for PHP** - lightweight but powerful agent SDK, supports custom tools, lifecycle hooks, subagents, context management, custom stop / continuation criteria, observability via events, packaged capabilities, agent templates, session management, and more.

Read More
---------

[](#read-more)

- Official website
- Docs website (Mintlify)
- Docs (Github Pages)

Overview of Capabilities
------------------------

[](#overview-of-capabilities)

The library offers a set of small, focused building blocks.

### Structured output

[](#structured-output)

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/](packages/instructor/docs/)

### Unified inference

[](#unified-inference)

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/](packages/polyglot/docs/)

### Embeddings

[](#embeddings)

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/](packages/polyglot/docs/)

### Agents SDK

[](#agents-sdk)

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/](packages/agents/docs/)

### Code agent bridges

[](#code-agent-bridges)

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/](packages/agent-ctrl/docs/)

What is Instructor?
-------------------

[](#what-is-instructor)

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](https://jxnl.github.io/instructor/) library for Python created by [Jason Liu](https://twitter.com/jxnlco).

[![image](docs/images/concept.png)](docs/images/concept.png)

Here's a simple CLI demo app using Instructor to extract structured data from text:

[![image](docs/images/extraction.gif)](docs/images/extraction.gif)

How Instructor Enhances Your Workflow
-------------------------------------

[](#how-instructor-enhances-your-workflow)

Instructor introduces three key enhancements compared to direct API usage.

### Response Model

[](#response-model)

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.

### Validation

[](#validation)

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.

### Max Retries

[](#max-retries)

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.

### Support for LLM Providers

[](#support-for-llm-providers)

Instructor offers out-of-the-box support for the following LLM providers:

- A21 / Mamba
- Anthropic
- Azure OpenAI
- Cerebras
- Cohere (v2 OpenAI compatible)
- Deepseek
- Fireworks
- Google Gemini (native and OpenAI compatible)
- Groq
- HuggingFace
- Inception
- Minimaxi
- Mistral
- Moonshot / Kimi
- Ollama (on localhost)
- OpenAI
- OpenRouter
- Perplexity
- Sambanova
- xAI / Grok

For usage examples, check Hub section or `examples` directory in the code repository.

Usage
-----

[](#usage)

### Installation

[](#installation)

You can install Instructor via Composer:

```
composer require cognesy/instructor-php
```

### Basic Example

[](#basic-example)

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.

```
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
// }
```

> **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.

### Validation

[](#validation-1)

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](https://symfony.com/doc/current/validation.html#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
```

### Max Retries

[](#max-retries-1)

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.

```
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
```

### Output Modes

[](#output-modes)

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 Schema
- `OutputMode::Tools` - use tool calling API to get LLM follow provided schema
- `OutputMode::MdJson` - use prompting to generate structured output; fallback for the models that do not support JSON generation or tool calling

Additionally, you can use `OutputMode::Text` to get LLM to generate text output without any structured data extraction.

- `OutputMode::Text` - generate text output
- `OutputMode::Unrestricted` - generate unrestricted output based on inputs provided by the user (with no enforcement of specific output format)

Unified LLM API
---------------

[](#unified-llm-api)

Instructor ecosystem uses [Polyglot](https://github.com/cognesy/instructor-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.

### Example (using sync API)

[](#example-using-sync-api)

```
use Cognesy\Polyglot\Inference\Inference;

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

echo $answer;
```

### Example (using streaming API)

[](#example-using-streaming-api)

```
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->contentDelta;
}
```

### Example (customize LLM connection)

[](#example-customize-llm-connection)

```
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-chat',
]))
    ->withMessages([['role' => 'user', 'content' => 'What is the capital of France']])
    ->withOptions(['max_tokens' => 64])
    ->get();

echo $answer;
```

Documentation
-------------

[](#documentation)

Check out the [documentation website](https://docs.instructorphp.com/) for more details and examples of how to use Instructor for PHP.

Feature Highlights
------------------

[](#feature-highlights)

### Core features

[](#core-features)

- Get structured responses from LLMs without writing boilerplate code
- Validation of returned data
- Automated retries in case of errors when LLM responds with invalid data
- Integrate LLM support into your existing PHP code with minimal friction - no framework, no extensive code changes
- Framework agnostic - use it with Laravel, Symfony, your custom framework, or - with no framework at all

### Various extraction modes

[](#various-extraction-modes)

- Supports multiple extraction modes through `Cognesy\Instructor\Enums\OutputMode`
- `OutputMode::Json` - use response\_format to get LLM follow provided JSON Schema
- `OutputMode::JsonSchema` - use strict JSON Schema mode to get LLM follow provided JSON Schema
- `OutputMode::Tools` - use tool calling API to get LLM follow provided JSON Schema
- `OutputMode::MdJson` - extract via prompting LLM to nudge it to generate provided JSON Schema

### Flexible inputs

[](#flexible-inputs)

- Process various types of input data: text, series of chat messages or images using the same, simple API
- 'Structured-to-structured' processing - provide object or array as an input and get object with the results of inference back
- Demonstrate examples to improve the quality of inference

### Customization

[](#customization)

- Define response data model the way you want: type-hinted classes, JSON Schema arrays, or dynamic data shapes with `Structure` class
- Customize prompts and retry prompts
- Use attributes or PHP DocBlocks to provide additional instructions for LLM
- Customize response model processing by providing your own implementation of schema, deserialization, validation and transformation interfaces

### Sync and streaming support

[](#sync-and-streaming-support)

- Supports both synchronous or streaming responses
- Get partial updates &amp; stream completed sequence items

### Observability

[](#observability)

- Get detailed insight into internal processing via events
- Debug mode to see the details of LLM API requests and responses

### Support for multiple LLMs / API providers

[](#support-for-multiple-llms--api-providers)

- Easily switch between LLM providers
- Support for most popular LLM APIs (incl. OpenAI, Gemini, Anthropic, Cohere, Azure, Groq, Mistral, Fireworks AI, Together AI)
- OpenRouter support - access to 100+ language models
- Use local models with Ollama

### Other capabilities

[](#other-capabilities)

- Developer friendly LLM context caching for reduced costs and faster inference (for Anthropic models)
- Developer friendly data extraction from images (for OpenAI, Anthropic and Gemini models)
- Generate vector embeddings using APIs of multiple supported LLM providers

### Documentation and examples

[](#documentation-and-examples)

- Learn more from growing documentation and 100+ cookbooks

Instructor in Other Languages
-----------------------------

[](#instructor-in-other-languages)

Check out implementations in other languages below:

- [Python](https://useinstructor.com) (original)
- [Javascript](https://js.useinstructor.com/) (port)
- [Elixir](https://hexdocs.pm/instructor/Instructor.html) (port)
- [Ruby](https://ruby.useinstructor.com/) (port)

If you want to port Instructor to another language, please reach out to us on [Twitter](https://twitter.com/jxnlco) we'd love to help you get started!

Instructor Packages
-------------------

[](#instructor-packages)

This repository is a monorepo containing all Instructor's components (required and optional). It hosts all that you need to work with LLMs via Instructor.

Individual components are also distributed as standalone packages that can be used independently.

[![image](docs/images/instructor-packages.svg)](docs/images/instructor-packages.svg)

Links to read-only repositories of the standalone package distributions:

- [instructor-addons](https://github.com/cognesy/instructor-addons) - extra capabilities and common LLM-related problem solutions
- [instructor-aux](https://github.com/cognesy/instructor-aux) - external tools and integrations, e.g. used by Instructor examples
- [instructor-config](https://github.com/cognesy/instructor-config) - configuration management for Instructor
- [instructor-evals](https://github.com/cognesy/instructor-evals) - LLM output evaluation tools
- [instructor-events](https://github.com/cognesy/instructor-events) - events and event listeners for Instructor
- [instructor-http-client](https://github.com/cognesy/instructor-http-client) - easily switch between underlying HTTP client libraries (out-of-the-box support for Guzzle, Symfony, Laravel)
- [instructor-http-pool](https://github.com/cognesy/instructor-http-pool) - concurrent HTTP request execution for fan-out workloads
- [instructor-hub](https://github.com/cognesy/instructor-hub) - CLI tool for browsing and running Instructor examples
- [instructor-messages](https://github.com/cognesy/instructor-messages) - chat message sequence handling for Instructor
- [instructor-polyglot](https://github.com/cognesy/instructor-polyglot) - use single API for inference and embeddings across most of LLM providers, easily switch between them (e.g., develop on Ollama, switch to Groq in production)
- [instructor-schema](https://github.com/cognesy/instructor-schema) - object schema handling for Instructor
- [instructor-setup](https://github.com/cognesy/instructor-setup) - CLI tool for publishing Instructor config files in your app
- [instructor-struct](https://github.com/cognesy/instructor-struct) - get dev friendly structured outputs from LLMs
- [instructor-tell](https://github.com/cognesy/instructor-tell) - CLI tool for executing LLM prompts in your terminal
- [instructor-templates](https://github.com/cognesy/instructor-templates) - text and chat template tools used by Instructor, support Twig, Blade and ArrowPipe formats
- [instructor-utils](https://github.com/cognesy/instructor-utils) - common utility classes used by Instructor packages

> NOTE: If you are just starting to use Instructor, I recommend using the `instructor-php` package. It contains all the required components and is the easiest way to get started with the library.

License
-------

[](#license)

This project is licensed under the terms of the MIT License.

Support
-------

[](#support)

If you have any questions or need help, please reach out to me on [Twitter](https://twitter.com/ddebowczyk) or [GitHub](https://github.com/cognesy/instructor-php/issues).

Contributing
------------

[](#contributing)

If you want to help, check out some of the issues. All contributions are welcome - code improvements, documentation, bug reports, blog posts / articles, or new cookbooks and application examples.

Contributors
------------

[](#contributors)

[ ![Contributors](https://camo.githubusercontent.com/ee61e4237b386fd7bb2b1a19f8bc2bd21471ab2d913fd36d2eba725271e49d72/68747470733a2f2f636f6e747269622e726f636b732f696d6167653f7265706f3d636f676e6573792f696e7374727563746f722d706870)](https://github.com/cognesy/instructor-php/graphs/contributors)

###  Health Score

65

—

FairBetter than 99% of packages

Maintenance88

Actively maintained with recent releases

Popularity52

Moderate usage in the ecosystem

Community25

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 98.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Recently: every ~14 days

Total

192

Last Release

61d ago

Major Versions

v0.17.11 → v1.0-rc12025-06-11

v1.22.0 → v2.0.02026-03-13

PHP version history (3 changes)v0.0.3PHP ^8.2

v1.5.0PHP ^8.2|^8.3|^8.4

v1.19.0PHP ^8.3|^8.4|^8.5

### Community

Maintainers

![](https://www.gravatar.com/avatar/d11593cece5bb65ba5eea704a91e1dda72362e86f8fe0e99295f291ba7628cac?d=identicon)[ddebowczyk](/maintainers/ddebowczyk)

---

Top Contributors

[![ddebowczyk](https://avatars.githubusercontent.com/u/184133?v=4)](https://github.com/ddebowczyk "ddebowczyk (1264 commits)")[![slider23](https://avatars.githubusercontent.com/u/142277?v=4)](https://github.com/slider23 "slider23 (9 commits)")[![gewa24](https://avatars.githubusercontent.com/u/37919620?v=4)](https://github.com/gewa24 "gewa24 (3 commits)")[![garyblankenship](https://avatars.githubusercontent.com/u/163649?v=4)](https://github.com/garyblankenship "garyblankenship (2 commits)")[![Toflar](https://avatars.githubusercontent.com/u/481937?v=4)](https://github.com/Toflar "Toflar (2 commits)")[![jackwh](https://avatars.githubusercontent.com/u/627533?v=4)](https://github.com/jackwh "jackwh (1 commits)")[![adrienbrault](https://avatars.githubusercontent.com/u/611271?v=4)](https://github.com/adrienbrault "adrienbrault (1 commits)")[![mfadul24](https://avatars.githubusercontent.com/u/86224001?v=4)](https://github.com/mfadul24 "mfadul24 (1 commits)")[![raftx24](https://avatars.githubusercontent.com/u/10864136?v=4)](https://github.com/raftx24 "raftx24 (1 commits)")

---

Tags

agentsaiai-agentsgenaillmphpautomationinferenceaiopenaiGeminiclaudellmanthropicdeepseekollamadata processingdata extractionlanguage modelsgenaicoherestructured outputsemantic processing

###  Code Quality

TestsPest

Static AnalysisPHPStan, Psalm

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/cognesy-instructor-php/health.svg)

```
[![Health](https://phpackages.com/badges/cognesy-instructor-php/health.svg)](https://phpackages.com/packages/cognesy-instructor-php)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[symfony/ai-platform

PHP library for interacting with AI platform provider.

51927.7k136](/packages/symfony-ai-platform)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
