predictionio/predictionio
Apache PredictionIO is an open-source machine learning server for building predictive engines quickly. It integrates data collection, model training, and deployment, with support for event ingestion, scalable backends, and custom algorithms for recommendations and classification.
To integrate PredictionIO (now archived) into a Laravel application, follow these steps:
Install the PredictionIO Engine
docker run -d -p 8000:8000 predictionio/predictionio-engine:0.11.0
conf/engine.json (adjust appId, storageContext, etc.).Laravel HTTP Client Setup Install Guzzle for API calls:
composer require guzzlehttp/guzzle
First API Call (Event Tracking)
Create a helper class (app/Services/PredictionIOService.php):
use GuzzleHttp\Client;
class PredictionIOService {
protected $client;
public function __construct() {
$this->client = new Client([
'base_uri' => 'http://localhost:8000/ps/',
]);
}
public function trackEvent($userId, $event) {
$response = $this->client->post('events', [
'json' => [
'user' => $userId,
'event' => $event,
'properties' => ['timestamp' => now()->toDateTimeString()]
]
]);
return json_decode($response->getBody(), true);
}
}
Trigger an Event in a Controller
use App\Services\PredictionIOService;
class UserController extends Controller {
public function logAction(User $user) {
$predictionIO = new PredictionIOService();
$predictionIO->trackEvent($user->id, 'user:viewed:product');
}
}
Event Tracking
Log user actions (e.g., product:view, purchase) via the trackEvent method.
$predictionIO->trackEvent($userId, 'product:view', ['productId' => 123]);
Query Recommendations
Use the query endpoint to fetch recommendations:
public function getRecommendations($userId, $num = 5) {
$response = $this->client->post('query', [
'json' => [
'user' => $userId,
'num' => $num
]
]);
return json_decode($response->getBody(), true)['result']['itemScores'];
}
Batch Processing
For offline training, use the import endpoint to bulk-insert events:
public function importEvents(array $events) {
$response = $this->client->post('import', [
'json' => ['events' => $events]
]);
return $response->getStatusCode() === 200;
}
Queue Delayed Events Use Laravel Queues to defer event tracking (e.g., for analytics):
dispatch(new TrackPredictionIOEvent($userId, 'delayed:event'));
Cache Recommendations Cache API responses to reduce latency:
return Cache::remember("predio:recommendations:{$userId}", now()->addHours(1), function() use ($userId) {
return $this->getRecommendations($userId);
});
Model Binding Extend Laravel’s Eloquent models to auto-track events:
class Product extends Model {
public function save(array $options = []) {
event(new ProductViewed($this));
return parent::save($options);
}
}
Deprecated API
PredictionIO’s API is outdated (last release: 2016). Use ps/ prefix for endpoints (e.g., /ps/events).
/ps/ in the base URI.Event Schema Mismatch
Events must match the template defined in conf/event_schema.json. Invalid schemas return 400 Bad Request.
Engine Restarts
Changes to event_schema.json or models require engine restarts:
docker restart predictionio-engine
Rate Limiting
The engine may throttle requests. Monitor logs (logs/engine.out) for 429 Too Many Requests.
Check Engine Logs Access logs via Docker:
docker logs predictionio-engine
Look for errors like Invalid event schema.
Validate JSON Payloads
Use json_last_error() to debug malformed requests:
$data = ['user' => $userId, 'event' => $event];
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception("Invalid JSON: " . json_last_error_msg());
}
Custom Algorithms
Extend PredictionIO’s src/main/scala/engine (Scala) for custom recommenders. Rebuild the engine:
sbt assembly
Webhooks
Use Laravel’s HandleIncomingWebhook to process PredictionIO’s real-time updates (if configured).
Fallback Logic Implement a fallback for API failures:
try {
return $this->getRecommendations($userId);
} catch (\Exception $e) {
return Cache::get("fallback:recommendations:{$userId}", []);
}
Storage Backend
Defaults to H2 (in-memory). For production, switch to Postgres in conf/storage_context.json:
{
"name": "postgres",
"params": {
"host": "postgres-host",
"port": 5432,
"user": "user",
"password": "pass",
"database": "predictionio"
}
}
App ID Isolation
Use separate appIds for different environments (dev/staging/prod) in conf/engine.json.
How can I help you explore Laravel packages today?