cognesy/instructor-php

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

What it solves

Instructor for PHP 消除了手动解析混乱的 LLM 输出(如 JSON 或原始文本)的需求,通过将其转换为具有类型和验证功能的 PHP 数据对象。它通过提供一种结构化的方式来提取信息,并确保数据在应用于应用程序之前符合特定的验证规则,从而降低了 LLM 集成的脆弱性。

How it works

该库使用“响应模型”(一个带有类型提示的纯 PHP 类)来定义所需的数据结构。它利用 LLM 的能力——例如原生 JSON 生成、JSON Schema 或工具调用(tool calling)——来强制模型遵循该架构。如果输出结果未通过验证(使用 Symfony validation),Instructor 可以自动重新尝试请求,并向 LLM 提供错误详情,从而使模型能够自我纠正其响应。

Who it’s for

想要在应用中集成 LLM,但不想为解析、验证和错误处理编写大量冗余代码的 PHP 开发人员,以及需要使用统一 API 在不同 LLM 提供商(如 OpenAI, Anthropic, 或 Ollama)之间进行切换的开发人员。

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: Through the Polyglot component, it provides a single API for 20+ LLM providers.
  • Agent SDK: Includes a lightweight SDK for building tool-using agents with state management and lifecycle hooks."},