Unlock ChatGPT’s power with PHP: Your 1-hour journey to custom AI assistants

Pavel Buchnev
14 min readAug 27, 2024

--

In this article, we’re gonna show you how to create your very own AI assistant using PHP and the awesome ChatGPT API.

We’re gonna show you how to build an AI assistant that doesn’t just listen to you, but actually gets what you’re saying and can even guess what you might need next. It’s all thanks to some cool tech called LLM agents. Don’t worry if that sounds complicated — we’ll break it down for you!

Whether you’ve been coding for years or you’re just starting out, this guide’s got you covered. We’ll help you understand how to turn your regular old service into a super smart AI assistant that really understands you.

We’re going to walk you through a real-world example of building a smart home system. It’s a perfect way to show you just how powerful these LLM agents can be when tackling complex tasks. You’ll see firsthand how your AI assistant can manage everything from lights to temperature, making your home (or any system you design) truly intelligent. Cool, right?

Let’s dive in!

Hey there 👋! Imagine you’re a PHP developer working on something cool — your very own smart home system. What’s the big idea? You want your home to know exactly what you need when you walk in after a long day of coding.

Picture this: You’ve just finished a crazy day of typing away, fixing bugs, and sitting through boring meetings. All you want is to come home and chill. Wouldn’t it be awesome if your home could automatically make things comfy, turn on the lights, and play your favorite tunes? Sounds easy, right?

But here’s the thing — as a coder, you know it’s not that simple. There’s a lot of complicated stuff going on behind the scenes.

You need a system that can:

  • Understand what you say, just like a real person would
  • Figure out on its own which devices to use
  • Make smart choices based on what you tell it

For example, imagine if your home could:

  • Get it when you say, “I’m freezing!” and turn on the fireplace for you
  • Understand when you’re in a bad mood and play your favorite upbeat songs
  • Know that when you say “movie time,” it should dim the lights and turn on the TV

Chuck Norris doesn’t need LLM Agents; when he talks to his house, it listens, learns, and obeys — or else.

The Magic Behind Smart Homes: 🤖 LLM Agents

Let’s talk about the secret sauce that makes smart homes truly intelligent: LLM agents and their handy sidekicks, tools.

Tools: The Building Blocks of Smart Home Control

Think of tools as the special skills your smart home has. Each tool can do a specific job.

Here are some examples:

  • List Room Devices Tool: This can tell you all the smart gadgets in any room you ask about.
  • Device Details Tool: It can give you the lowdown on any specific device you’re curious about.
  • Control Device Tool: This is the handyman of the bunch. It can make devices do things, like turning them on or off, or changing their settings.
  • Room List Tool: Think of this as your home’s directory. It can tell you all the rooms in your smart home system.

These tools are like the hands and feet of your smart home system. They do the actual work of finding out what’s in your home and controlling your devices.

🧐 For example, if you want to know what’s in your living room, the List Room Devices Tool has got your back. Or if you need to turn off the kitchen light, the Control Device Tool is the one for the job.

Agents: The Brains of the Operation

Now, here’s where it gets really cool. LLM agents are like super-smart assistants that know how to use all these tools. An agent is a bundle of tools wrapped up with AI. Here’s what makes them awesome:

They understand human speech

You can talk to them like you would to a friend. This is huge! You don’t need to learn special commands or type in exact phrases. Just chat with your smart home like you’re talking to a buddy. Say something like, “Hey, it’s movie night!” and the agent gets it. It understands context, slang, and even picks up on the mood in your voice. If you’re tired and mumble, “Ugh, too bright,” it knows you want the lights dimmed.

They can think and make decisions

Based on what you say, they figure out which tools to use from their agent tool-set. This is where the magic happens. The agent doesn’t just follow a script — it thinks! When you make a request, the agent looks at all the tools it has (remember those we talked about earlier?) and decides which ones to use and in what order. If you say, “I’m cold,” it might decide to:

  1. Use the Get Room List tool to find what room you’re in
  2. Use the Get Device Details tool to check if there’s a heater or fireplace nearby
  3. Finally use the Control Device tool to turn up the heat

All this happens in seconds, and you don’t have to tell it each step!

They learn and remember: Over time, they get better at knowing what you like.

Your agent is always learning, and it’s got a special trick up its sleeve — the Memorizer tool.

Here’s how it works:

  1. Every time you interact with your smart home, the agent listens carefully.
  2. When you say something, the agent thinks, 🤔 “Is this important?” Using its AI smarts, it decides if what you’ve said is worth remembering for the long term.
  3. If it is important, the Memorizer tool springs into action. It takes that bit of info and adds it to the agent’s memory as a new instruction.

For example, let’s say you mention, “I always get cold feet when I’m working at my desk.” The agent might think, 🤓 “Aha! This is important!” The Memorizer tool then adds a note to the agent’s memory: 🧐 “When the user is in the home office, check if they need extra warmth for their feet.”

Now, here’s where it gets really cool:

  • The next time you’re in your home office, the agent might ask, “Would you like me to turn on the under-desk heater?
  • If you often say, “It’s too bright in here” in the evenings, the agent might start automatically dimming the lights at sunset.
  • When you come home on Fridays saying, “What a week!”, the agent might learn to start your relaxation routine without you even asking.

With the Memorizer tool, your smart home becomes more than just a bunch of connected gadgets. It becomes a living, learning system that gets to know you better every day. It picks up on your habits, preferences, and even your moods, making your home more comfortable and responsive to your needs over time.

The best part? You don’t have to fiddle with settings or program anything. Just live your life, chat with your home, and watch as it becomes more in tune with you. It’s like having a home that not only listens to you but truly understands and anticipates what you need.

Now that’s seriously smart!

From Dream to Reality: Creating Your Own Smart Home Agents

OK, I hear you thinking:

💀 “This all sounds amazing, but don’t I need super coding powers and years of work to create a smart home system like this?”

Well, here’s the exciting news — you don’t! Thanks to some seriously smart people and groundbreaking tech, creating your own smart home agents is way more doable than you might think.

We’re standing on the shoulders of giants here:

  1. The brilliant minds at OpenAI and Anthropic who created ChatGPT and Claude. These powerful AI models with tool-calling capabilities have opened up a whole new world of possibilities.
  2. The dedicated open-source community who’ve developed a ton of packages like openai-php/client. These folks have been working hard to make advanced AI more accessible to everyday PHP developers.
  3. The team behind the llm-agents-php/agents package, who’ve taken all this amazing tech and packaged it up in a way that’s super friendly for PHP developers.

🏗 It’s like we’ve been given a high-tech LEGO set. The really hard parts — creating the AI models, figuring out how to make them use tools — that’s already been done! 🤠

Now, we get to play with these cool building blocks and create our own unique smart home systems.

And the best part? You don’t need to be an AI genius or have a massive tech company’s resources. If you can code in PHP and know how to use any PHP framework, you’re ready to start building some seriously smart stuff!

Chuck Norris doesn’t use tools with his LLM agents; the tools use Chuck Norris.

Introducing Your New Best Friend 👨‍🌾

Alright, developers, get ready to meet your new coding buddy — the LLM Agents PHP package. This isn’t just another library; it’s your ticket to the world of AI-powered smart home control.

What is it?

The package https://github.com/llm-agents-php/agents is an open-source toolkit that lets you create and manage Language Model (LLM) based agents in your PHP applications. Think of it as your personal AI assistant factory.

What can it do?

  1. Build custom AI agents that understand natural language
  2. Create tools for your agents to use (like controlling smart home devices)
  3. Manage conversations and agent memory
  4. Integrate with powerful language models like GPT-4 or Claude3.5

Why should you care?

Imagine being able to code an AI assistant that can control your entire smart home, understand complex commands, and learn from interactions. That’s what this package enables you to do, without needing a PhD in machine learning.

How easy is it to use?

Super easy! If you can write PHP, you can create AI agents. The package handles all the complex AI stuff under the hood, leaving you free to focus on what your agents can do.

Building Your First Smart Home Agent: A Step-by-Step Guide 🚀

Let’s create a basic smart home agent that can control lights and temperature. We’ll go through this process step-by-step, using interfaces to represent our smart home integration.

Step 1: Set Up Your Project

First, make sure you have the package installed:

composer require llm-agents/agents

Step 2: Define Smart Home Interfaces

Here, we’re creating a blueprint for our smart home devices. Interfaces are used because they allow us to define a contract for what our devices should do, without worrying about the specific implementation. It means we can easily swap out different smart home systems as long as they implement these interfaces.

Let’s create interfaces to represent our smart home devices:

interface LightControlInterface
{
public function turnOn(string $roomName): bool;
public function turnOff(string $roomName): bool;
public function setBrightness(string $roomName, int $level): bool;
}

interface ThermostatInterface
{
public function getTemperature(string $roomName): float;
public function setTemperature(string $roomName, float $temperature): bool;
}

Step 3: Create Tools for Your Agent

Tools are the bridge between your agent’s understanding and the actual control of devices. Each tool encapsulates a specific functionality (like controlling lights or managing temperature). The execute method in each tool is where the magic happens - it's where we translate the agent's high-level commands into specific actions for our smart home devices.

Let’s create tools that our agent can use to control these devices:

use LLM\Agents\Tool\Tool;
use LLM\Agents\Tool\ToolLanguage;

final class LightControlTool extends Tool
{
public function __construct(
private LightControlInterface $lightControl
) {
parent::__construct(
name: 'light_control',
inputSchema: LightControlInput::class,
description: 'Control lights in a room'
);
}

public function getLanguage(): ToolLanguage
{
return ToolLanguage::PHP;
}

public function execute(object $input): string
{
$result = match ($input->action) {
'on' => $this->lightControl->turnOn($input->room),
'off' => $this->lightControl->turnOff($input->room),
'brightness' => $this->lightControl->setBrightness($input->room, $input->level),
default => false,
};

return json_encode(['success' => $result]);
}
}
use LLM\Agents\Tool\Tool;
use LLM\Agents\Tool\ToolLanguage;

final class ThermostatTool extends Tool
{
public function __construct(
private ThermostatInterface $thermostat
)
{
parent::__construct(
name: 'thermostat_control',
inputSchema: ThermostatInput::class,
description: 'Control temperature in a room'
);
}

public function getLanguage(): ToolLanguage
{
return ToolLanguage::PHP;
}

public function execute(object $input): string
{
if ($input->action === 'get') {
$temp = $this->thermostat->getTemperature($input->room);
return json_encode(['temperature' => $temp]);
} elseif ($input->action === 'set') {
$result = $this->thermostat->setTemperature($input->room, $input->temperature);
return json_encode(['success' => $result]);
}
return json_encode(['error' => 'Invalid action']);
}
}

Step 4: Define Input Schemas for Tools

Input schemas are crucial for ensuring that the data passed to our tools is in the correct format. They act as a contract between the agent and the tools, specifying exactly what information is needed to perform an action. The use of attributes (like #[Field]) allows us to provide additional metadata about each field, which can be used by the agent to better understand how to use these tools.

use Spiral\JsonSchemaGenerator\Attribute\Field;

class LightControlInput
{
public function __construct(
#[Field(title: 'Room', description: 'The room to control lights in')]
public string $room,
#[Field(title: 'Action', description: 'Action to perform (on, off, brightness)')]
public string $action,
#[Field(title: 'Brightness Level', description: 'Brightness level (0-100)')]
public ?int $level = null
) {}
}
use Spiral\JsonSchemaGenerator\Attribute\Field;

class ThermostatInput
{
public function __construct(
#[Field(title: 'Room', description: 'The room to control temperature in')]
public string $room,
#[Field(title: 'Action', description: 'Action to perform (get, set)')]
public string $action,
#[Field(title: 'Temperature', description: 'Temperature to set')]
public ?float $temperature = null
) {}
}

Step 5: Create Your Smart Home Agent

This is where we bring everything together. The agent is the brain of our smart home system. It’s configured with a specific purpose (controlling a smart home), given instructions on how to behave, and equipped with the tools it needs to perform actions. The metadata we add (like user preferences) helps the agent make more informed decisions.

Now, let’s put it all together and create our smart home agent:

use LLM\Agents\Agent\AgentAggregate;
use LLM\Agents\Agent\Agent;
use LLM\Agents\Solution\Model;
use LLM\Agents\Solution\ToolLink;
use LLM\Agents\Solution\MetadataType;
use LLM\Agents\Solution\SolutionMetadata;

class SmartHomeAgent extends AgentAggregate
{
public const NAME = 'smart_home_assistant';

public static function create(): self
{
$agent = new Agent(
key: self::NAME,
name: 'Smart Home Assistant',
description: 'This agent controls lights and temperature in your smart home.',
instruction: 'You are a smart home assistant. Help users control their lights and temperature. Use the provided tools to perform actions.'
);

$aggregate = new self($agent);

$aggregate->addMetadata(
new SolutionMetadata(
type: MetadataType::Memory,
key: 'user_preference',
content: 'The user prefers warm lighting in the evening.'
)
);

$model = new Model(model: 'gpt-4o-mini');
$aggregate->addAssociation($model);

$aggregate->addAssociation(new ToolLink(name: LightControlTool::NAME));
$aggregate->addAssociation(new ToolLink(name: ThermostatTool::NAME));

return $aggregate;
}
}

Step 6: Use Your Smart Home Agent

This final step shows how to actually use the agent we’ve created. We’re setting up a loop that allows for back-and-forth communication between the user, the agent, and the smart home devices. The agent interprets the user’s command, decides which tools to use, and then we execute those tools and feed the results back to the agent. This cycle continues until the agent has fully addressed the user’s request.

Finally, let’s see how we can use our new smart home agent:

use LLM\Agents\Agent\AgentExecutor;
use LLM\Agents\LLM\Prompt\Chat\Prompt;
use LLM\Agents\Tool\ToolExecutor;

$agentExecutor = new AgentExecutor(/* ... */);
$toolExecutor = new ToolExecutor(/* ... */);

$prompt = new Prompt([
Prompt\MessagePrompt::user("Turn on the lights in the living room and set the temperature to 72 degrees"),
]);

while (true) {
$execution = $agentExecutor->execute(SmartHomeAgent::NAME, $prompt);
$result = $execution->result;
$prompt = $execution->prompt;

if ($result instanceof ToolCalledResponse) {
foreach ($result->tools as $tool) {
$functionResult = $toolExecutor->execute($tool->name, $tool->arguments);
$prompt = $prompt->withAddedMessage(
new ToolCallResultMessage(
id: $tool->id,
content: [$functionResult],
)
);
}
continue;
}

if ($result instanceof ChatResponse) {
echo $result->content;
break;
}
}

And there you have it! You’ve just created a basic smart home agent that can control lights and temperature. This agent can understand natural language commands, use the appropriate tools to control your smart home devices, and respond to the user.

Remember, this is just the beginning. You can expand this agent by adding more tools, improving its understanding with more metadata, and integrating with real smart home devices. The possibilities are endless!

Sample Application with Pre-Built Agents 💊

If you’re excited about the potential of LLM Agents but not quite ready to dive into coding your own, we’ve got you covered! We’ve developed a sample application that lets you experiment with several pre-built agents right out of the box. This is a great way to get a feel for the capabilities of agents and spark ideas for your own projects.Available Agents

  1. Smart Home Control Assistant: Similar to our earlier example, this agent can manage various smart home devices across multiple rooms.
  2. Site Status Checker: This agent can check if websites are online, retrieve basic site information, and even provide troubleshooting tips if a site is down.
  3. Order Assistant: Perfect for e-commerce scenarios, this agent can help with order-related queries, check delivery statuses, and provide personalized customer support.
  4. Task Splitter: This agent excels at breaking down complex project descriptions into structured task lists with subtasks.
  5. Code Review Agent: For the developers out there, this agent can analyze code files, provide feedback, and suggest improvements.

CLI Interface

The sample application features a user-friendly Command Line Interface that makes interacting with these agents a breeze. Here’s a sneak peek at what you’ll see:

Start Chatting: Once installed, kick off your first chat session with a simple command:

php app.php chat
This screenshot shows the CLI interface of the sample application, specifically the list of available agents.

Choose one, and start interacting!

This screenshot displays the details of the Smart Home Control Assistant after it has been selected. It includes:

The interface then provides a command that the user can run in a separate terminal session to see the AI’s response:

php app.php chat:session 01919280-d5e1-7340-9f23-9cb00db8acb3 -v

Ok. Let’s try to set the fireplace in the living room to medium intensity

Just give it a shot, and you’ll like it!

Explore and Experiment

With this sample application, you can:

  • Test different types of queries with each agent
  • Observe how agents use their tools to accomplish tasks
  • Get inspired for your own agent designs

Give it a try, and see firsthand how LLM Agents can understand complex requests, make decisions, and provide intelligent responses!

How to Install and Run the Sample App

We’ve provided a detailed README in the project repository with step-by-step instructions.

Conclusion

The package opens up a world of possibilities for developers. It’s not just about turning lights on and off anymore; it’s about creating a home that understands context, learns from interactions, and anticipates needs.

But the implications go far beyond just smart homes. The same principles we’ve discussed can be applied to countless other domains — from customer service bots that genuinely understand customer needs, to code review assistants that can provide insightful feedback, to task management systems that can break down complex projects with human-like understanding.

The beauty of the package is that it makes this advanced technology accessible. You don’t need to be an AI expert or have the resources of a tech giant. If you can code in PHP, you can start building sophisticated AI agents today.

Machine learning algorithms ask Chuck Norris for advice.

Thx for reading to the end, clapping and and sharing with your friends! It means a lot for Open Source community! 🖖

--

--

Pavel Buchnev
Pavel Buchnev

Written by Pavel Buchnev

Senior PHP Developer | Contributor to Spiral Framework 🚀 | Enthusiast of RoadRunner & long-running applications | Creator of Buggregator