# cognesy/instructor-php architecture

> Architecture diagram of the GitHub repository cognesy/instructor-php, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-04-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/cognesy/instructor-php
- Repository: https://github.com/cognesy/instructor-php

## Overview

##### Main Components / Modules
- “Instructor Core Engine” – The heart of the library that parses the input (which can be plain text, structured objects, or arrays), encodes the data model (using PHP type hints, docblocks, and optional Structure definitions), and then orchestrates the inference process.
- “Response Model & Data Transformation” – This comprises the classes and mechanisms (including Scalar adapters, Sequence wrappers, dynamic Structures, and custom response model contracts) that let the developer describe the expected output from the LLM, trigger deserialization, validation (via Symfony Validator) and transformation.
- “LLM Client / Driver” – A set of adapters and drivers that abstract the actual API calls to external LLM providers. Refer to the multiple providers (OpenAI, Anthropic, Azure, Ollama, etc.) and the configuration found in config/llm.php. This component manages HTTP requests (using Guzzle or Symfony client wrappers from the src-http folder) for sending and receiving LLM responses.
- “Addon Modules” – Such as the Chat, Evals, FunctionCall, ToolUse, and others in src-addons. They encapsulate specialized processing pipelines (for chat summaries, multi-turn conversation handling, evaluation and observation systems, etc.) that extend the core capabilities.
- “Configuration & Environment” – The configuration files (in /config, .env-dist, etc.) and bootstrap scripts (in bin, scripts directories) which initialize parameters such as API keys, default LLM connections, retry limits, and other options.
- “Observability / Event Logging” – This comprises the event wiring, dispatchers and wiretap functionalities that allow the system to emit internal events (request sent, response received, partial updates, etc.) for debugging and monitoring.
- “Testing and Examples” – Represented in the examples and tests directories. They’re important for understanding how the components are used and integrated in a real-world scenario.

##### Relationships and Data Flow
- The “User Application” or “Client Code” (which can be a CLI app, a web controller, etc.) calls the Instructor’s public API (methods such as respond(), request(), or get()). This input is then processed by the Instructor Core.
- The Instructor Core analyzes the response model (using reflection, docblock parsing, etc.) and encodes it into a JSON schema or instructional prompt.
- It then sends a request through the LLM Client component wherein the proper driver/client adapter (selected via configuration and the withConnection/withDriver methods) makes an HTTP call to an external LLM provider.
- The external provider sends back a response (either all-at-once or as a stream). The Instructor Core then sends the response to the deserialization pipeline.
- Within the pipeline the returned data is transformed into PHP object(s), validated (with Symfony Validation), and — if needed — triggers retries using feedback loops.
- Finally, the validated and possibly transformed output is passed back to the user. Meanwhile, event dispatchers (and optional wiretaps) log each major step for observability.

##### Architectural and Design Principles
- Modularity & Separation of Concerns: Each functional area, such as communication with external LLMs, data deserialization/validation, and event logging, is separated into its own module. Adapters are used to allow switching between providers without major code changes.
- Extensibility: The structure is designed to be extended (support for custom drivers, response models using both static PHP classes and dynamic “Structure” definitions).
- Resilience & Retry Logic: The design includes built-in mechanisms to validate responses and attempt retries if results do not pass validation.
- Observability & Debugging: Internal events are strongly emphasized so that issues during processing can be traced and debugged.

## Diagram (Mermaid)

```mermaid
flowchart TD
    UA["User Application / Client Code"]:::client
    CONFIG["Configuration & Environment"]:::config
    BS["Bootstrap Scripts (bin)"]:::config
    IC["Instructor Core Engine"]:::core
    LLM["LLM Client / Driver"]:::driver
    GA["Guzzle Adapter"]:::driver
    PA["Polyglot Adapter"]:::driver
    EXT["External LLM Provider"]:::external
    RM["Response Model & Data Transformation"]:::transformation
    OBS["Observability / Event Logging"]:::observability
    ADDON["Addon Modules"]:::addon
    TEST["Testing and Examples"]:::testing

    %% Vertical Pipeline Flow
    UA -->|"calls_API"| IC
    CONFIG -- "configures" --> IC
    CONFIG -- "initializes" --> LLM
    IC -->|"orchestrates"| LLM
    LLM -->|"uses"| GA
    LLM -->|"uses"| PA
    GA -->|"HTTP_call"| EXT
    PA -->|"HTTP_call"| EXT
    EXT -->|"returns_response"| LLM
    LLM -->|"relays_response"| IC
    IC -->|"deserializes_validates"| RM
    RM -->|"returns_output"| UA

    %% Auxiliary Connections
    IC ---|"integrates"| ADDON
    IC ---|"logs_events"| OBS
    RM ---|"logs_events"| OBS
    CONFIG -->|"boots"| BS
    UA ---|"triggers"| TEST

    %% Click Events
    click IC "https://github.com/cognesy/instructor-php/blob/main/src-instructor/Instructor.php"
    click RM "https://github.com/cognesy/instructor-php/blob/main/src-instructor/Features/Core/Data/ResponseModel.php"
    click LLM "https://github.com/cognesy/instructor-php/blob/main/config/llm.php"
    click GA "https://github.com/cognesy/instructor-php/blob/main/src-http/Drivers/GuzzleDriver.php"
    click PA "https://github.com/cognesy/instructor-php/tree/main/src-polyglot/LLM/Drivers"
    click ADDON "https://github.com/cognesy/instructor-php/tree/main/src-addons"
    click CONFIG "https://github.com/cognesy/instructor-php/tree/main/config"
    click BS "https://github.com/cognesy/instructor-php/tree/main/bin/instructor"
    click OBS "https://github.com/cognesy/instructor-php/tree/main/src-instructor/Events"
    click TEST "https://github.com/cognesy/instructor-php/tree/main/tests"

    %% Style Definitions
    classDef client fill:#cce5ff,stroke:#333,stroke-width:1px;
    classDef core fill:#d4edda,stroke:#333,stroke-width:1px;
    classDef driver fill:#fff3cd,stroke:#333,stroke-width:1px;
    classDef external fill:#f8d7da,stroke:#333,stroke-width:1px;
    classDef transformation fill:#d1ecf1,stroke:#333,stroke-width:1px;
    classDef config fill:#e2e3e5,stroke:#333,stroke-width:1px;
    classDef addon fill:#e6ccff,stroke:#333,stroke-width:1px;
    classDef observability fill:#fde2e2,stroke:#333,stroke-width:1px;
    classDef testing fill:#d1ffd1,stroke:#333,stroke-width:1px;
```
