cognesy/instructor-php

Unified LLM API, structured data outputs with LLMs, and agent SDK - in PHP

What it solves

Instructor for PHP eliminates the need to manually parse messy LLM outputs (like JSON or raw text) by turning them into typed, validated PHP data objects. It reduces the brittleness of LLM integrations by providing a structured way to extract information and ensuring the data meets specific validation rules before it is used in an application.

How it works

The library uses a "response model" (a plain PHP class with type-hints) to define the desired data structure. It leverages LLM capabilities—such as native JSON generation, JSON Schema, or tool calling—to force the model to follow that schema. If the output fails validation (using Symfony validation), Instructor can automatically retry the request, providing the LLM with the error details so the model can self-correct its response.

Who it’s for

PHP developers who want to integrate LLMs into their applications without writing extensive boilerplate for parsing, validation, and error handling, and those who need to switch between different LLM providers (like OpenAI, Anthropic, or Ollama) using a unified API.

Highlights

  • Structured Extraction: Converts LLM responses directly into PHP classes.
  • Automated Retries: Self-corrects invalid responses by feeding validation errors back to the LLM.
  • Unified Inference: Through the Polyglot component, it provides a single API for 20+ LLM providers.
  • Multi-Mode Output: Supports various extraction methods including JSON, JSON Schema, Tool calling, and Markdown-JSON.
  • Framework Agnostic: Works standalone or with first-party integrations for Laravel and Symfony.
  • Agent SDK: Includes a lightweight SDK for building tool-using agents with state management and lifecycle hooks.