PHPackages                             codechap/ai - 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. [API Development](/categories/api)
4. /
5. codechap/ai

ActiveLibrary[API Development](/categories/api)

codechap/ai
===========

A generic PHP wrapper for integrating multiple AI services like OpenAI, Anthropic, and xAI.

1108PHP

Since Feb 9Pushed 3mo ago1 watchersCompare

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

READMEChangelogDependenciesVersions (2)Used By (0)

AI Service Integration Library
==============================

[](#ai-service-integration-library)

Overview
--------

[](#overview)

A PHP library that provides a unified interface for interacting with multiple AI services (OpenAI, Anthropic, Mistral, Groq, xAI). Simplifies integration and standardizes interactions across different AI providers while maintaining service-specific features.

Implementations
---------------

[](#implementations)

ServiceChatStreamingToolsVisionCachingPDFJSONLive SearchAnthropic✓✕✕✕✕✕✓✕Groq✓✕✕✓✕✕✓✕Mistral✓✕✕✕✕✕✓✕OpenAI✓✕✕✕✕✕✓✕xAI✓✕✓✓✕✕✓✓Google✓✕✕✕✕✕✓✕Requirements
------------

[](#requirements)

- PHP 8.2+
- Composer

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

[](#installation)

```
composer require codechap/ai
```

Basic Usage
-----------

[](#basic-usage)

### OpenAI

[](#openai)

```
use codechap\ai\Ai;
$openai = new ai('openai', $openaiKey);
print $openai
    ->set('temperature', 0)
    ->set('model', 'o3-mini-2025-01-31')
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('json', true)
    ->set('reasoningEffort', 'low')
    ->query("What is the capital of South Africa? Only return the three in a JSON response.")
    ->one()
    ;
```

### Mistral

[](#mistral)

```
use codechap\ai\Ai;
$mistral = new Ai('mistral', $mistralKey);
print $mistral
    ->set('temperature', 0)
    ->set('model', 'o3-mini-2025-01-31')
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('json', true)
    ->query("What is the capital of South Africa? Only return the three in a JSON response.")
    ->one()
    ;
```

### Groq (Most open source models)

[](#groq-most-open-source-models)

```
use codechap\ai\Ai;
$groq = new Ai('groq', $groqKey);
print $groq
    ->set('temperature', 0)
    ->set('model', 'deepseek-r1-distill-llama-70b')
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('stream', false)
    ->query("What is the capital of South Africa?")
    ->one()
    ;
print "\n\n";
```

### Anthropic (Claude)

[](#anthropic-claude)

```
use codechap\ai\Ai;
$anthropic = new Ai('anthropic', $anthropicKey);
print $anthropic
    ->set('temperature', 0)
    ->set('model', 'claude-3-5-sonnet-20241022')
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('stream', false)
    ->query("What is the capital of South Africa?")
    ->one()
    ;
```

### xAI (Grok)

[](#xai-grok)

```
use codechap\ai\Ai;
$xai = new Ai('xai', $xaiKey);
print $xai
    ->set('temperature', 0)
    ->set('model', 'grok-2-latest')
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('stream', false)
    ->query("What is the capital of South Africa?")
    ->one()
    ;
```

### Google (Gemini)

[](#google-gemini)

```
use codechap\ai\Ai;
$google = new Ai('google', $googleKey);
print = $google
    ->set('temperature', 0)
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('stream', false)
    ->set('json', true)
    ->query("What is the capital of South Africa? Only return the three in a JSON response.")
    ->all()
    ;
```

Vision Example
--------------

[](#vision-example)

```
$groq = new Ai('groq', $groqKey);
$result = $groq
    ->set('temperature', 0)
    ->set('model', 'meta-llama/llama-4-scout-17b-16e-instruct')
    ->set('systemPrompt', 'You are a helpful assistant from planet earth.')
    ->set('stream', false)
    ->set('json', false)
    ->query(
    [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'image_url',
                    'image_url' => [
                        'url' => 'https://upload.wikimedia.org/wikipedia/commons/f/f2/LPU-v1-die.jpg'
                    ]
                ],
                [
                    'type' => 'text',
                    'text' => 'What is this image about?'
                ]
            ]
        ]
    ])
    ->all()
    ;
print_r($result);
```

JSON Response Handling
----------------------

[](#json-response-handling)

Different AI services handle JSON responses in different ways:

### OpenAI

[](#openai-1)

- Uses native JSON response formatting via the `response_format` parameter
- Set `json: true` to automatically receive properly formatted JSON responses
- No additional processing needed

### Other Services (Anthropic, Mistral, Groq, xAI)

[](#other-services-anthropic-mistral-groq-xai)

- JSON responses are handled through post-processing
- Set `json: true` to enable JSON extraction and validation
- Uses the JsonExtractor helper to:
    - Extract JSON from raw responses
    - Handle JSON within markdown code blocks (`json ... `)
    - Validate JSON structure

Example usage:

```
// OpenAI (native JSON)
$ai->openai()
   ->set('json', true)
   ->query('Return user data')
   ->one();

// Other services (post-processed JSON)
$ai->anthropic() // or mistral(), groq(), xai()
   ->set('json', true)
   ->query('Return user data')
   ->one();
```

Scope
-----

[](#scope)

This library is focused on **text-based chat completions** across multiple AI providers.

FeatureStatusChat completions✓StreamingPlannedTool usePlannedVision✓JSON mode✓Live search✓CachingPlannedPDF inputPlannedImage generation✕Image generation is intentionally out of scope and will not be added here. It is better suited as a separate project (e.g., an MCP server) due to its fundamentally different request/response patterns.

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

[](#contributing)

- Todo

### Testing

[](#testing)

- PHPUnit test suite
- Automatic service discovery testing
- Error handling verification

### Contributing by adding a New Service

[](#contributing-by-adding-a-new-service)

To add a new AI service:

1. Create a new file in `src/Services/` following the naming convention
2. Implement the required methods:

    - `__construct(string $apiKey)`
    - `query(string $prompt): string`
3. The service will be automatically discovered and available through AIWrapper
4. Run `composer test` to verify your implementation

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance55

Moderate activity, may be stable

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity14

Early-stage or recently created project

 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.

### Community

Maintainers

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

---

Top Contributors

[![codeChap](https://avatars.githubusercontent.com/u/451621?v=4)](https://github.com/codeChap "codeChap (65 commits)")

### Embed Badge

![Health badge](/badges/codechap-ai/health.svg)

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

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M480](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M272](/packages/twilio-sdk)[facebook/php-business-sdk

PHP SDK for Facebook Business

90821.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

74513.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

265103.1M454](/packages/google-gax)[google/common-protos

Google API Common Protos for PHP

173103.7M50](/packages/google-common-protos)

PHPackages © 2026

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