Skip to content
Magento6 min read

Introducing the Magento AI SDK

I've built a free, open-source AI SDK for Magento 2, inspired by the Laravel AI SDK. Write an agent as a PHP class, give it tools, and read the answer as typed fields.

Every Magento module I've added AI to has needed the same plumbing. An HTTP client for the provider. A loop that runs the tools the model asks for. Code to pull JSON out of a reply and hope it is valid. Retries when the API is busy. And some way to test it all without spending tokens.

Laravel solved this with its AI SDK. You write an agent as a class, prompt it, and get a response back. Tools, structured output, failover and testing fakes are all built in. I liked it enough that I've ported the same ideas to Magento 2 and Mage-OS. It's free, it's MIT-licensed and the code is on GitHub.

Install it

bash
composer require upturnstudio/module-ai
bin/magento module:enable UpturnStudio_Ai
bin/magento setup:upgrade

Then paste an Anthropic API key under Stores > Configuration > UpturnStudio > AI. It's stored encrypted. To check it works, make one real request from the command line:

bash
bin/magento upturn:ai:prompt "Say hello" --provider=anthropic

Your first agent

An agent is a PHP class with instructions. This one writes product copy and returns it as fields, not a block of text:

php
use UpturnStudio\Ai\Api\AgentInterface;
use UpturnStudio\Ai\Api\HasStructuredOutputInterface;
use UpturnStudio\Ai\Promptable;
use UpturnStudio\Ai\Schema\JsonSchema;

class ProductCopywriter implements AgentInterface, HasStructuredOutputInterface
{
    use Promptable;

    public function instructions(): string
    {
        return 'You write product copy for an online store. Plain, specific, no hype.';
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'meta_title' => $schema->string()->required(),
            'meta_description' => $schema->string()->required(),
        ];
    }
}

Prompt it and read the answer like an array:

php
$copy = (new ProductCopywriter)->prompt($product->getName());

$product->setMetaTitle($copy['meta_title']);
$product->setMetaDescription($copy['meta_description']);

If you've used the Laravel AI SDK, this will look familiar. The main difference is the Interface suffix: AgentInterface instead of Agent, HasStructuredOutputInterface instead of HasStructuredOutput. That's the Magento convention.

Give it tools

A tool lets the model call your own code. Here's one that looks up an order:

php
use UpturnStudio\Ai\Api\ToolInterface;
use UpturnStudio\Ai\Schema\JsonSchema;
use UpturnStudio\Ai\Tools\ToolRequest;

class LookupOrder implements ToolInterface
{
    public function description(): string
    {
        return 'Look up an order by its increment ID.';
    }

    public function handle(ToolRequest $request): string
    {
        $arguments = $request->validate();

        return json_encode($this->orders->summary($arguments['increment_id']));
    }

    public function schema(JsonSchema $schema): array
    {
        return ['increment_id' => $schema->string()->required()];
    }
}

Return it from an agent's tools() method and ask a question. The model decides to call LookupOrder, the SDK runs it, sends the result back and returns the final answer. The arguments are checked against the tool's schema first, and if they're wrong the error goes back to the model to fix.

php
$reply = SupportAgent::make()->prompt('Where is order 000000042?');

make() creates the agent through Magento's ObjectManager, so constructor dependencies such as a repository are injected as usual.

Fail over between providers

Pass a list of providers and the next one is used when the first is rate limited, overloaded, out of credit or unreachable. You can also build a provider at runtime, which is handy when each merchant brings their own key:

php
use UpturnStudio\Ai\Ai;

$response = (new ProductCopywriter)->prompt($brief, provider: [
    Ai::build(['driver' => 'anthropic', 'key' => $merchantKey]),
    Ai::build(['driver' => 'anthropic', 'key' => $storeKey]),
]);

An invalid key or a bad request doesn't fail over, because the next provider would fail the same way.

Test it without an API key

This is the part I wanted most. Fake an agent, run your code, then assert what it was asked. No provider, no ObjectManager and no tokens:

php
protected function tearDown(): void
{
    Ai::reset();
}

public function testCopyIsWritten(): void
{
    ProductCopywriter::fake([
        ['meta_title' => 'Waxed Field Jacket', 'meta_description' => 'A waxed cotton jacket.'],
    ]);

    $this->service->writeCopy($product);

    ProductCopywriter::assertPromptedTimes(1);
}

The method names are the same as Laravel's: fake(), assertPrompted(), assertNotPrompted(), assertPromptedTimes() and assertNeverPrompted().

How it differs from Laravel

I kept the shape of the Laravel API and changed what had to fit Magento:

  • Interfaces have an Interface suffix, so AgentInterface rather than Agent.
  • Ai is a static locator, not a facade. If you prefer constructor injection, depend on AiManagerInterface and AgentRunnerInterface instead.
  • Events are Magento events, such as upturn_ai_agent_prompted, so you listen with an observer.
  • Configuration lives in the admin, di.xml and env.php rather than config/ai.php.
  • Tool arguments are validated against the tool's own schema. There are no Laravel validation rule strings.

What it doesn't do yet

It's a work in progress, and I'd rather say so up front.

  • Anthropic is the only provider so far. OpenAI, Gemini and OpenAI-compatible providers such as Ollama are next.
  • Streaming, conversation memory, tool approval, queueing, files, images and audio aren't built yet.
  • It's a library for developers. On its own it adds a config section and a test command, nothing on the storefront.

The repository has a progress file that tracks every section of the Laravel AI SDK docs against the module, so you can see exactly what's done.

References

  • Laravel AI SDK documentation: laravel.com/docs/ai-sdk
  • Laravel AI: laravel.com/ai
  • Laravel AI SDK source: github.com/laravel/ai
  • Magento AI SDK source: github.com/brideo/magento-ai
  • Magento AI SDK module page: upturnstudio.com.au/modules/magento-ai

The short version

  • The Magento AI SDK is a free, MIT-licensed port of the Laravel AI SDK for Magento 2 and Mage-OS.
  • Agents are PHP classes. Tools call your own code, and structured output comes back as typed fields.
  • Providers fail over when one is busy, and fakes let you test without an API key.
  • Anthropic works today, with more providers on the way.

Grab it from the modules page or GitHub. If you're adding AI to a Magento store and want a hand, get in touch.

MagentoAILaravelOpen sourceModules
Work with me

Got a project like this?

Tell me what’s slow, broken or stuck. You’ll get a straight answer within one working day.

Keep reading · Next in the blogRollcall: a menu bar app for keeping track of Claude Code sessionsAI4 min read

More in Magento

All posts →