mayursaptal/semantic-kernel-php

PHP implementation of Microsoft's Semantic Kernel framework for orchestrating LLMs, memory, and AI agents

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/mayursaptal/semantic-kernel-php

dev-main / 1.0.x-dev 2025-07-28 06:32 UTC

This package is auto-updated.

Last update: 2025-10-28 07:14:13 UTC


README

PHP Version License Composer

Build AI-powered applications in PHP - A complete framework for orchestrating Large Language Models, memory systems, and intelligent planning. Compatible with Microsoft's Semantic Kernel patterns.

✨ What can you build?

πŸ€– AI-Powered Applications

// Customer support bot with memory
$kernel = Kernel::createBuilder()
    ->withOpenAI($_ENV['OPENAI_API_KEY'])
    ->withVolatileMemory()
    ->build();

$response = $kernel->getChatService()->generateText(
    "Help customer with order {{order_id}}: {{question}}",
    new ContextVariables(['order_id' => '12345', 'question' => 'Where is my package?'])
);

πŸ“ Document Processing & Summarization

// Smart document summarizer
$summarizer = new SemanticFunction(
    'summarize',
    'Summarize this document in 3 bullet points: {{input}}',
    'Extracts key insights from documents'
);

$plugin = KernelPlugin::create('DocumentTools');
$plugin->addFunction($summarizer);
$kernel->importPlugin($plugin);

$result = $kernel->run('DocumentTools.summarize', new ContextVariables([
    'input' => $longDocument
]));

🧠 Intelligent Planning & Task Execution

// AI plans and executes complex tasks
$planner = new Planner($kernel);
$plan = $planner->createPlan('Create and send weekly sales report');

// AI automatically breaks down into steps:
// 1. Gather sales data β†’ 2. Analyze trends β†’ 3. Create report β†’ 4. Send email
$result = $planner->executePlan($plan, $context);

πŸš€ Quick Start

Installation

composer require mayursaptal/semantic-kernel-php

Basic Usage

<?php
require_once 'vendor/autoload.php';

use SemanticKernel\Kernel;
use SemanticKernel\ContextVariables;

// Create kernel with AI service
$kernel = Kernel::createBuilder()
    ->withOpenAI($_ENV['OPENAI_API_KEY'])
    ->withVolatileMemory()
    ->build();

// Generate AI response
$response = $kernel->getChatService()->generateText('Explain AI in simple terms');
echo $response;

πŸ€– Supported AI Services

Service Models Use Case
OpenAI GPT-3.5, GPT-4 General-purpose AI tasks
Azure OpenAI GPT-3.5, GPT-4 Enterprise applications
Google Gemini Gemini 1.5 Flash/Pro Multimodal AI (text + images)
Ollama Llama2, Mistral, etc. Local/private deployments

Switch AI Services Easily

// OpenAI
$kernel = Kernel::createBuilder()
    ->withOpenAI($_ENV['OPENAI_API_KEY'], 'gpt-4')
    ->build();

// Google Gemini
$kernel = Kernel::createBuilder()
    ->withGemini($_ENV['GOOGLE_API_KEY'], 'gemini-1.5-pro')
    ->build();

// Azure OpenAI
$kernel = Kernel::createBuilder()
    ->withAzureOpenAI($_ENV['AZURE_API_KEY'], $_ENV['AZURE_ENDPOINT'], $_ENV['DEPLOYMENT'])
    ->build();

// Local Ollama
$kernel = Kernel::createBuilder()
    ->withOllama('llama2', 'http://localhost:11434')
    ->build();

🧩 Core Features

πŸ“¦ Plugin System

Organize AI functions into reusable plugins:

$plugin = KernelPlugin::create('TextUtils');

// Add semantic functions (AI-powered)
$plugin->addFunction(new SemanticFunction(
    'translate',
    'Translate "{{text}}" from {{from}} to {{to}}',
    'Translates between languages'
));

// Add native functions (PHP code)
$plugin->addFunction(new NativeFunction(
    'word_count',
    fn($context) => str_word_count($context->get('text')),
    'Counts words in text'
));

$kernel->importPlugin($plugin);

// Use functions
$result = $kernel->run('TextUtils.translate', new ContextVariables([
    'text' => 'Hello world',
    'from' => 'English', 
    'to' => 'Spanish'
]));

πŸ’Ύ Memory & Context

AI remembers conversations and context:

// Store information
$kernel->getMemoryStore()->store('user_preferences', 'user_123', 'Prefers technical explanations');

// Retrieve context
$preferences = $kernel->getMemoryStore()->retrieve('user_preferences', 'user_123');

// Use in conversation
$response = $kernel->getChatService()->generateText(
    "Based on user preference: {{preference}}, explain APIs",
    new ContextVariables(['preference' => $preferences])
);

🎯 Advanced Function Control

Control how AI uses functions:

use SemanticKernel\AI\PromptExecutionSettings;

// AI automatically decides when to call functions
$autoSettings = PromptExecutionSettings::withAutoFunctionChoice();

// AI must call at least one function
$requiredSettings = PromptExecutionSettings::withRequiredFunctionChoice();

// Disable function calling
$noneSettings = PromptExecutionSettings::withNoFunctionCalling();

πŸ“‘ Event System

Monitor and observe AI operations:

$kernel->getEventDispatcher()->addListener('function.invoked', function($event) {
    echo "Function '{$event->getFunctionName()}' executed in {$event->getDuration()}ms\n";
});

πŸ“š Examples

Explore comprehensive examples in the /examples directory:

  • 01_basic_usage.php - Getting started with text generation
  • 02_ai_services.php - All supported AI services (OpenAI, Gemini, etc.)
  • 03_semantic_functions.php - Creating and using AI-powered functions
  • 04_memory_and_planning.php - Memory storage and intelligent planning
  • 05_advanced_features.php - Events, caching, monitoring
# Run examples
php examples/01_basic_usage.php
php examples/02_ai_services.php

πŸ”§ Environment Setup

Create a .env file with your API keys:

# OpenAI
OPENAI_API_KEY=sk-your-openai-key

# Google Gemini  
GOOGLE_API_KEY=your-google-api-key

# Azure OpenAI
AZURE_OPENAI_API_KEY=your-azure-key
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com
AZURE_OPENAI_DEPLOYMENT=your-deployment-name

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Application   β”‚    β”‚  Semantic Kernel β”‚    β”‚   AI Services   β”‚
β”‚                 │───▢│                  │───▢│                 β”‚
β”‚  - Chat Bots    β”‚    β”‚  - Orchestration β”‚    β”‚  - OpenAI       β”‚
β”‚  - Summarizers  β”‚    β”‚  - Planning      β”‚    β”‚  - Gemini       β”‚
β”‚  - Analyzers    β”‚    β”‚  - Memory        β”‚    β”‚  - Azure OpenAI β”‚
β”‚  - Workflows    β”‚    β”‚  - Events        β”‚    β”‚  - Ollama       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🌟 Key Benefits

  • πŸš€ Easy Integration - Add AI to existing PHP applications
  • πŸ”„ Service Agnostic - Switch between OpenAI, Gemini, Azure seamlessly
  • 🧠 Memory & Context - AI remembers conversation history
  • πŸ“¦ Modular Plugins - Reusable AI function libraries
  • 🎯 Planning System - AI breaks down complex tasks automatically
  • πŸ“Š Production Ready - Caching, rate limiting, monitoring, events
  • πŸ”§ Microsoft Compatible - Aligned with Microsoft's Semantic Kernel patterns

πŸ“– Documentation

🀝 Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines.

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

⭐ Star this repo if you find it useful! | πŸ“’ Share with the PHP community