PHPackages                             hudhaifas/silverstripe-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. hudhaifas/silverstripe-ai

ActiveSilverstripe-vendormodule[Utility &amp; Helpers](/categories/utility)

hudhaifas/silverstripe-ai
=========================

Context-aware AI agent for SilverStripe 5 — NeuronAI integration, Human-in-the-Loop, usage tracking, and multi-provider support

v1.1.0(4mo ago)121[1 issues](https://github.com/hudhaifas/silverstripe-ai/issues)BSD-3-ClausePHPPHP &gt;=8.1

Since Feb 22Pushed 4mo agoCompare

[ Source](https://github.com/hudhaifas/silverstripe-ai)[ Packagist](https://packagist.org/packages/hudhaifas/silverstripe-ai)[ Docs](https://github.com/hudhaifas/silverstripe-ai)[ RSS](/packages/hudhaifas-silverstripe-ai/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (2)Versions (4)Used By (0)

silverstripe-ai
===============

[](#silverstripe-ai)

AI-powered features for SilverStripe 5: a context-aware chatbot agent and a human-in-the-loop content generation system.

```
composer require hudhaifas/silverstripe-ai
```

---

What you get out of the box
---------------------------

[](#what-you-get-out-of-the-box)

- **Agent Widget** — a chat sidebar that knows which DataObject the user is viewing, can call tools to read or write data, and asks for confirmation before making changes
- **Content Widget** — generate AI content for any DataObject field with mandatory user review before saving
- **REST API** — endpoints under `/api/ai/agent` and `/api/ai/content`
- **Human-in-the-Loop (HITL)** — write tools and content generation pause for user approval
- **Zero-dependency storage** — conversation history and workflow state use SilverStripe's built-in cache; swap to Redis with one YAML line
- **Multi-provider** — OpenAI and Anthropic (with prompt caching for up to 90% cost reduction)
- **Credit system** — free monthly credits + purchasable credits per member, with automatic model tier selection
- **Usage logging** — every request logged with token counts, cost, and cache metrics

---

How it works
------------

[](#how-it-works)

### Agent Widget

[](#agent-widget)

```
Browser → POST /api/ai/agent/chat
            ↓
       AgentController
            ↓
       AgentService  ←→  MemberAIExtension (credit check + model selection)
            ↓
       AgentFactory  →  YourCustomAgent (extends DataObjectAgent)
            ↓
       NeuronAI  ←→  OpenAI / Anthropic
            ↓
       [tool called that writes data]
            ↓
       WorkflowInterrupt → returns resumeToken to browser
            ↓
       User approves/rejects in UI
            ↓
       POST /api/ai/agent/resume → tool executes → LLM responds

```

### Content Widget

[](#content-widget)

```
Browser → POST /api/ai/content/generate
            ↓
       ContentController
            ↓
       ContentService  ←→  MemberAIExtension (credit check + model selection)
            ↓
       ContentWorkflow
            ↓
       AgentRunnerNode → GenerateContentAgent → LLM
            ↓                     ↓
            ↓         YourContentExtension (prompt + input data)
            ↓
       ReviewContentNode → WorkflowInterrupt (HITL)
            ↓
       User approves/edits/rejects in UI
            ↓
       POST /api/ai/content/resume
            ↓
       PersistContentNode → entity.saveContent()
                                   ↓
                      YourContentExtension (save logic)

```

---

Quick start
-----------

[](#quick-start)

### 1. Install

[](#1-install)

```
composer require hudhaifas/silverstripe-ai
vendor/bin/sake dev/build flush=1
```

Set your API keys in `.env`:

```
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
```

### 2. Configure default models in the CMS

[](#2-configure-default-models-in-the-cms)

Go to Settings → AI and pick a free-tier model (e.g. `gpt-4o-mini`) and a paid-tier model (e.g. `claude-sonnet-4-5`). Models are seeded automatically on `dev/build`.

---

What's auto-configured
----------------------

[](#whats-auto-configured)

The module auto-applies these via YAML — no manual setup required:

ComponentAuto-applied toPurpose`MemberAIExtension``Member`Credit management, model selection, usage tracking`SiteConfigAIExtension``SiteConfig`Default model configuration in Settings → AIAPI routes`/api/ai/agent/*`, `/api/ai/content/*`REST endpointsCache backends`ChatHistoryInterface`, `PersistenceInterface`Conversation history + HITL stateYou only need to create your custom agents, tools, and content extensions.

---

Agent Widget
------------

[](#agent-widget-1)

[![Agent Widget](docs/images/agent-widget.png)](docs/images/agent-widget.png)

### 1. Create your agent

[](#1-create-your-agent)

```
use Hudhaifas\AI\Agent\DataObjectAgent;
use NeuronAI\Agent\Middleware\ToolApproval;
use NeuronAI\Agent\Nodes\ToolNode;

class ProductAgent extends DataObjectAgent
{
    // Cached by Anthropic for 5 min — put stable rules and tool descriptions here.
    // For OpenAI this is just the first part of the system prompt.
    protected function getStaticInstructions(): string
    {
        return 'You are a helpful assistant for managing products.
                Use the available tools to read and update product data.
                Always confirm with the user before making changes.';
    }

    // Injected fresh on every request — current entity state, date, session info.
    // Not cached, so keep it concise.
    protected function getDynamicContext(): string
    {
        $product = $this->contextEntity; // the DataObject passed from the controller
        return "Current product: {$product->Title} (ID: {$product->ID})\n"
             . "Price: {$product->Price}\n"
             . "Stock: {$product->Stock}";
    }

    // All tools the LLM can call. Read-only tools run immediately;
    // write tools are gated by ToolApproval in middleware() below.
    public function tools(): array
    {
        return [
            new GetProductDetailsTool(),   // read — runs freely
            new UpdateProductPriceTool(),  // write — requires user approval
            new DeleteProductTool(),       // write — requires user approval
        ];
    }

    // ToolApproval intercepts the listed tools before execution and returns
    // a resume_token to the frontend. The agent pauses until the user
    // approves or rejects via POST /api/ai/agent/resume.
    protected function middleware(): array
    {
        return [
            ToolNode::class => [
                new ToolApproval(tools: [
                    UpdateProductPriceTool::class,
                    DeleteProductTool::class,
                ]),
            ],
        ];
    }
}
```

### 2. Register the mapping

[](#2-register-the-mapping)

```
# _config/agent.yml
Hudhaifas\AI\Factory\AgentFactory:
  agent_mappings:
    MyApp\Model\Product: 'MyApp\Agent\ProductAgent'
```

### 3. Add the widget to your page

[](#3-add-the-widget-to-your-page)

```
# _config/extensions.yml
MyApp\Controller\ProductPageController:
  extensions:
    - Hudhaifas\AI\Extension\AgentRequirementsExtension
```

Include `$AgentWidget` in your template and the JS/CSS loads automatically.

**Template example:**

```

    $Title
    $Description
