ML Ecosystem in PHP

Learning examples

These examples will help you understand how you can use ML in PHP. They are not full-fledged applications, but they will help you understand the basics of working with ML in PHP.


Example with Neuron AI

Neuron AI is another way to work with LLMs from PHP. The snippet below creates an agent, sends a user message, and prints the returned response content.

 
<?php

namespace App\Neuron;

use 
NeuronAI\Agent\Agent;
use 
NeuronAI\Chat\Messages\UserMessage;
use 
NeuronAI\Providers\AIProviderInterface;
use 
NeuronAI\Providers\OpenAI\OpenAI;

/** @psalm-suppress PropertyNotSetInConstructor */
class MyAgent extends Agent {
    public function 
__construct() {
        
parent::__construct();
    }

    protected function 
provider(): AIProviderInterface {
        return new 
OpenAI(
            
key:  config('OPENAI_API_KEY'''),
            
modelconfig('OPENAI_API_MODEL'''),
            
parameters: [], // Add custom params (temperature, logprobs, etc)
            
strict_responsefalse// Strict structured output
        
);
    }
}

$message MyAgent::make()
    ->
chat(new UserMessage('Hi!'))
    ->
getMessage();


echo 
"Q1: Hi!\n";
echo 
'A: ' $message->getContent() . "\n\n";
echo 
"Q2: Explain who you are?\n";
echo 
'A: ' MyAgent::make()
    ->
chat(new UserMessage('Explain who you are?'))
    ->
getMessage()
    ->
getContent();
Result: Memory: 0.001 Mb Time running: < 0.001 sec.
Q1: Hi!
A: Hello! How can I assist you today?

Q2: Explain who you are?
A: Hello! I’m an AI assistant created using Neuron AI, which is a powerful agentic framework designed for the PHP ecosystem. My purpose is to help answer your questions, provide explanations, assist with coding tasks, and support you in various topics, especially related to PHP development. How can I assist you today?