PHPackages                             tourze/open-ai-contracts - 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. [PSR &amp; Standards](/categories/psr-standards)
4. /
5. tourze/open-ai-contracts

ActiveLibrary[PSR &amp; Standards](/categories/psr-standards)

tourze/open-ai-contracts
========================

OpenAI compatible API contracts and interfaces for PHP

1.0.1(6mo ago)0622MITPHPPHP ^8.2CI passing

Since Nov 5Pushed 4mo agoCompare

[ Source](https://github.com/tourze/open-ai-contracts)[ Packagist](https://packagist.org/packages/tourze/open-ai-contracts)[ RSS](/packages/tourze-open-ai-contracts/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (2)

OpenAI Contracts
================

[](#openai-contracts)

[English](README.md) | [中文](README.zh-CN.md)

[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)[![PHP Version](https://camo.githubusercontent.com/962aced9b09d89716dbebf186ff899754a096ff1068b6b7988675c2d9fab9331/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c75652e737667)](https://camo.githubusercontent.com/962aced9b09d89716dbebf186ff899754a096ff1068b6b7988675c2d9fab9331/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c75652e737667)[![Tests](https://camo.githubusercontent.com/645f6cb8e1906a40371adf07a2d8a0c05005d031a91500824418befce3309315/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d70617373696e672d677265656e2e737667)](https://camo.githubusercontent.com/645f6cb8e1906a40371adf07a2d8a0c05005d031a91500824418befce3309315/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d70617373696e672d677265656e2e737667)

OpenAI compatible API contracts and interfaces for PHP applications.

Installation
------------

[](#installation)

```
composer require tourze/open-ai-contracts
```

Features
--------

[](#features)

This package provides a comprehensive set of contracts and interfaces for building OpenAI-compatible API clients:

### Core Components

[](#core-components)

- **Client Interfaces**: Define standard methods for OpenAI API interactions
- **Request/Response Contracts**: Type-safe request and response structures
- **DTO Classes**: Data transfer objects for API communication
- **Enums**: Standardized enumerations for roles, model types, and finish reasons
- **Attributes**: Annotations for API compatibility and authentication
- **Exception Interfaces**: Structured error handling contracts

### Client Interface

[](#client-interface)

```
use Tourze\OpenAiContracts\Client\OpenAiCompatibleClientInterface;

interface OpenAiCompatibleClientInterface
{
    public function chatCompletion(ChatCompletionRequestInterface $request): ChatCompletionResponseInterface;
    public function listModels(): ModelListResponseInterface;
    public function getBalance(): BalanceResponseInterface;
    public function setApiKey(string $apiKey): void;
    public function getApiKey(): ?string;
    public function getName(): string;
    public function getBaseUrl(): string;
    public function isAvailable(): bool;
    public function getLastError(): ?string;
}
```

### Data Transfer Objects

[](#data-transfer-objects)

#### Chat Message

[](#chat-message)

```
use Tourze\OpenAiContracts\DTO\ChatMessage;
use Tourze\OpenAiContracts\Enum\Role;

$message = new ChatMessage(
    role: Role::USER,
    content: 'Hello, how are you?'
);

// Convert to array for API requests
$messageArray = $message->toArray();

// Create from API response
$message = ChatMessage::fromArray($responseData);
```

#### Usage Statistics

[](#usage-statistics)

```
use Tourze\OpenAiContracts\DTO\Usage;

$usage = new Usage(
    promptTokens: 100,
    completionTokens: 50,
    totalTokens: 150
);
```

### Enumerations

[](#enumerations)

#### Role Enum

[](#role-enum)

```
use Tourze\OpenAiContracts\Enum\Role;

Role::USER;       // 'user'
Role::ASSISTANT;  // 'assistant'
Role::SYSTEM;     // 'system'
Role::FUNCTION;   // 'function'
Role::TOOL;       // 'tool'
```

#### Model Type

[](#model-type)

```
use Tourze\OpenAiContracts\Enum\ModelType;

ModelType::CHAT_COMPLETION;  // 'chat.completion'
ModelType::TEXT_COMPLETION;  // 'text.completion'
ModelType::EMBEDDING;        // 'embedding'
// ... and more
```

### Attributes

[](#attributes)

Mark classes and methods as OpenAI compatible:

```
use Tourze\OpenAiContracts\Attribute\OpenAiCompatible;
use Tourze\OpenAiContracts\Attribute\OpenAiEndpoint;
use Tourze\OpenAiContracts\Attribute\RequiresAuthentication;
use Tourze\OpenAiContracts\Attribute\RateLimited;

#[OpenAiCompatible(version: 'v1')]
#[RequiresAuthentication]
class MyApiClient
{
    #[OpenAiEndpoint('/v1/chat/completions')]
    #[RateLimited(requests: 100, timeWindow: 60)]
    public function chatCompletion(): void
    {
        // Implementation
    }
}
```

### Exception Handling

[](#exception-handling)

```
use Tourze\OpenAiContracts\Exception\InvalidRequestException;
use Tourze\OpenAiContracts\Exception\OpenAiExceptionInterface;

try {
    // API call
} catch (InvalidRequestException $e) {
    // Handle invalid request
} catch (OpenAiExceptionInterface $e) {
    // Handle general OpenAI errors
}
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- tourze/enum-extra ^1.0

Quality
-------

[](#quality)

This package follows strict quality standards:

- **Static Analysis**: Uses PHPStan for comprehensive static analysis
- **Testing**: Full test coverage with PHPUnit
- **Code Style**: Follows PSR-12 coding standards
- **Type Safety**: Full type declarations and strict typing

Architecture
------------

[](#architecture)

### Request/Response Flow

[](#requestresponse-flow)

```
Client Request → DTO Validation → Interface Contract → API Response → DTO Response

```

### Package Structure

[](#package-structure)

```
src/
├── Attribute/          # PHP Attributes for API compatibility
├── Client/            # Client interfaces
├── DTO/               # Data Transfer Objects
├── Enum/              # Enumerations for constants
├── Exception/         # Exception interfaces
├── Request/           # Request interfaces
└── Response/          # Response interfaces

```

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

[](#contributing)

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests and static analysis
5. Commit your changes (`git commit -m 'Add some amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request

Development Setup
-----------------

[](#development-setup)

```
# Clone the repository
git clone https://github.com/tourze/php-monorepo.git
cd php-monorepo/packages/open-ai-contracts

# Install dependencies
composer install

# Run tests
composer test

# Run static analysis
composer analyse
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance72

Regular maintenance activity

Popularity8

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Total

2

Last Release

184d ago

### Community

Maintainers

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

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-open-ai-contracts/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-open-ai-contracts/health.svg)](https://phpackages.com/packages/tourze-open-ai-contracts)
```

###  Alternatives

[phpdocumentor/type-resolver

A PSR-5 based resolver of Class names, Types and Structural Element Names

9.2k719.5M166](/packages/phpdocumentor-type-resolver)[pimple/pimple

Pimple, a simple Dependency Injection Container

2.7k130.5M1.4k](/packages/pimple-pimple)[league/container

A fast and intuitive dependency injection container.

86387.8M343](/packages/league-container)[stella-maris/clock

A pre-release of the proposed PSR-20 Clock-Interface

7947.5M2](/packages/stella-maris-clock)[wptrt/wpthemereview

PHP\_CodeSniffer rules (sniffs) to verify theme compliance with the rules for theme hosting on wordpress.org

217736.5k29](/packages/wptrt-wpthemereview)[inpsyde/modularity

Modular PSR-11 implementation for WordPress plugins, themes or libraries.

54383.3k3](/packages/inpsyde-modularity)

PHPackages © 2026

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