AI models

AI models

In the fast-paced world of technology, artificial intelligence (AI) models are revolutionizing how applications function. Whether it’s generating human-like text, understanding semantics, or powering smart recommendations, AI is everywhere. For developers, however, integrating these models into projects can feel overwhelming. Each provider—think OpenAI, Anthropic Claude, or Google Gemini—comes with its own unique API, rules, and quirks. Learning these differences often pulls focus away from building the app itself.

What if there was a way to simplify this? Enter AI Access for PHP, an open-source PHP library crafted for developers. This tool offers a single, unified interface to connect with multiple AI providers effortlessly. Want to use OpenAI’s GPT-4 for text generation one day and switch to Claude’s Haiku for dialogue the next? This library makes it seamless, saving you time and frustration.

In this guide, we’ll dive deep into what AI Access for PHP offers—its features, benefits, and how to use it. Whether you’re a PHP beginner dipping your toes into AI or a seasoned coder looking to streamline your workflow, this article has something for you.


What is AI Access for PHP?

AI Access for PHP is a developer-friendly library that simplifies working with AI models. At its core, it provides a consistent API interface to interact with services from providers like OpenAI, Claude, and Gemini. Instead of juggling multiple SDKs or rewriting code for each provider, you get a single, reliable way to access them all. This cuts down the learning curve and lets you switch models with ease, keeping your focus on building great applications.

The library’s design revolves around three principles: consistency, flexibility, and practicality. Whether you’re adding a basic chatbot or tackling complex batch processing, AI Access for PHP is built to help.


Why Use AI Access for PHP? The Key Benefits

This isn’t just another API wrapper—it’s a thoughtfully designed tool with real advantages. Here’s why it stands out:

1. One Interface for All Models

Every AI provider has its own way of doing things, which often means writing custom code for each one. AI Access for PHP changes that with a unified set of methods. Whether you’re creating a chat, generating embeddings, or running batch tasks, the code stays nearly the same across providers. Learn it once, and you’re set.

2. Easy Model Switching

Need to swap models for cost, speed, or capability reasons? With this library, you can switch providers—like from OpenAI to Claude—by tweaking just one line of code. No need to overhaul your logic. This flexibility shines during testing or when optimizing your app.

3. More Time for What Matters

Dealing with AI APIs can get messy, with endless details to manage. AI Access for PHP wraps these complexities into simple PHP methods, so you don’t have to sweat the small stuff. Spend your energy on your app’s core features instead.

4. Built for Modern PHP

Running on PHP 8.1 and up, this library uses strict typing and modern features. This makes your code stronger, easier to maintain, and less prone to errors—perfect for projects that need to evolve over time.


Getting Started: A Quick Setup Guide

Ready to try it? Setting up AI Access for PHP is a breeze. Here’s how to get going.

Step 1: Install the Library

You’ll need Composer and PHP 8.1 or higher. Run this command in your terminal:

composer require ai-access/ai-access

That’s it—installation done!

Step 2: Set Up the Client

To use an AI model, you first create a client instance. Each provider has its own client class, but they all follow the same interface. Here’s an example:

$apiKey = trim(file_get_contents('path/to/key.txt'));

// OpenAI client
$client = new AIAccess\OpenAI\Client($apiKey);

// Claude client (uncomment to use)
// $client = new AIAccess\Claude\Client($apiKey);

// Gemini client (uncomment to use)
// $client = new AIAccess\Gemini\Client($apiKey);

Tip: For bigger projects, consider setting up the client in a dependency injection container instead of hardcoding it.


Basic Example: Build a Simple Chat

Once your client is ready, interacting with AI models is straightforward. Here’s how to generate text with Claude:

$model = 'claude-3-haiku-20240307'// Claude model

echo "Using model: " . $model . "\n";

$chat = $client->createChat($model);
$prompt = 'Write a short haiku about PHP.';
echo "User input: " . $prompt . "\n";

$response = $chat->sendMessage($prompt);

echo "Model response: " . $response->getText() . "\n";
echo "Finish reason: " . ($response->getFinishReason() ?? 'None') . "\n";
echo "Usage info: ";
print_r($response->getUsage());

Run this, and you might get: “PHP code flows smooth, Logic like a poem’s line, Simplicity breeds wisdom.” To switch to OpenAI? Just change the client and model name—no other tweaks needed.


Advanced Features: Level Up Your App

AI Access for PHP goes beyond basic prompts. Here are some powerful features to explore.

Multi-Turn Conversations

Need a chatbot that remembers past messages? The library handles conversation history for you:

use AIAccess\Role;

$chat = $client->createChat($model);

$chat->addMessage('What is the capital of France?', Role::User);
$chat->addMessage('The capital of France is Paris.', Role::Model);
$chat->addMessage('What is a famous landmark there?', Role::User);

echo "Current message count: " . count($chat->getMessages()) . "\n";

$response = $chat->sendMessage();

echo "Model response: " . $response->getText() . "\n";

echo "Full conversation history (" . count($chat->getMessages()) . " messages):\n";
foreach ($chat->getMessages() as $message) {
    echo "[" . $message->getRole()->name . "]: " . $message->getText() . "\n";
}

Output might be: “A famous landmark in Paris is the Eiffel Tower.” The library keeps the context intact.

Custom System Instructions

Want the model to act a certain way? Set a system instruction:

$chat->setSystemInstruction('You are a humorous assistant who answers in a witty tone.');

Now, responses might sound like: “Oh, the Eiffel Tower? Been standing there forever and still hasn’t asked for a break!”

Fine-Tune Model Behavior

Adjust settings like temperature to control output randomness:

$chat->setOptions(temperature: 0.1); // Low randomness, stable responses

Check the docs for provider-specific options.


Batch Processing: Tackle Big Tasks Efficiently

For large-scale jobs—like generating tons of text or translations—batch processing is a game-changer. It’s supported for OpenAI and Claude, with lower costs but longer wait times (minutes to 24 hours).

How It Works

  1. Create a Batch: Use Client::createBatch().
  2. Add Tasks: Set up chats with unique customIds.
  3. Submit: Call Batch::submit().
  4. Monitor: Check status with scheduled tasks.
  5. Get Results: Fetch the output when done.

Sample Code

use AIAccess\Role;

$batch = $client->createBatch();

$chat1 = $batch->createChat($model, 'greeting-1');
$chat1->setSystemInstruction('Respond briefly and friendly.');
$chat1->addMessage('Hi!', Role::User);

$chat2 = $batch->createChat($model, 'translate-fr');
$chat2->setSystemInstruction('Translate the user message to French.');
$chat2->addMessage('Hello, world', Role::User);

$batchResponse = $batch->submit();

$batchId = $batchResponse->getId();
echo "Batch job submitted with ID: " . $batchId . "\n";

Retrieve Results

use AIAccess\BatchStatus;

$currentBatch = $client->retrieveBatch($batchId);
$status = $currentBatch->getStatus();

if ($status === BatchStatus::Completed) {
    $outputMessages = $currentBatch->getOutputMessages();
    foreach ($outputMessages as $customId => $message) {
        echo "Result for task '$customId':\n";
        echo $message->getText() . "\n";
    }
}

Embeddings: Unlock Text Intelligence

Embeddings turn text into numerical vectors—great for semantic search or recommendations. The library supports this for OpenAI and Gemini.

Example

$embeddingModel = 'embedding-001';

$textsToEmbed = [
    'The quick brown fox jumps over the lazy dog.',
    'PHP is a popular general-purpose scripting language.',
    'Paris is the capital of France.',
];

$results = $client->calculateEmbeddings(
    model: $embeddingModel,
    input: $textsToEmbed
);

foreach ($results as $index => $embedding) {
    $vector = $embedding->getVector();
    echo "Embedding vector for text " . ($index + 1) . ": \"" . $textsToEmbed[$index] . "\"\n";
    echo "Dimensions: " . count($vector) . "\n";
}

Use these vectors to compare text meanings and power smarter features.


Error Handling: Keep Your Code Solid

Things go wrong—networks fail, APIs glitch. AI Access for PHP has you covered:

try {
    $response = $chat->sendMessage('Tell me a story about a brave toaster.');
    echo "Model response: " . $response->getText() . "\n";
} catch (AIAccess\ApiException $e) {
    echo "API error: " . $e->getMessage() . "\n";
} catch (AIAccess\NetworkException $e) {
    echo "Network error: " . $e->getMessage() . "\n";
}

This keeps your app running smoothly.


Wrap-Up: Simplify AI with PHP

AI Access for PHP is a must-have for developers who want to tap into AI without the hassle. Its unified interface, easy model switching, and robust features—like chats, batch processing, and embeddings—make it a time-saver. Whether you’re building a small tool or a complex system, this library boosts efficiency and scalability.

Ready to make your PHP apps smarter? Check out the AI Access for PHP GitHub repository and get started. Your next project might just stand out thanks to this powerful tool!