PHP code example of sabioweb / api-chatgpt

1. Go to this page and download the library: Download sabioweb/api-chatgpt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sabioweb / api-chatgpt example snippets


use SBAO\Factory\ServiceFactory;

$factory = new ServiceFactory('your-api-key-here');

// Using factory with default configuration
$ocrService = $factory->createOcrService();

// Extract from image file
$text = $ocrService->extractFromFile('/path/to/image.jpg');

// Extract from base64-encoded string
$base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRg...';
$text = $ocrService->extractFromBase64($base64Image);

// Using custom configuration
use SBAO\Ocr\OcrConfig;

$config = new OcrConfig(
    model: 'gpt-4-vision-preview',
    quality: 'high',
    maxTokens: 500
);
$ocrService = $factory->createOcrService($config);

// Using factory with default configuration
$mathService = $factory->createMathematicsService();

// Solve an equation
$solution = $mathService->solve('Solve for x: 2x + 5 = 15');

// Solve a word problem
$solution = $mathService->solve('If a train travels 120 km in 2 hours, what is its average speed?');

// Using custom configuration
use SBAO\Mathematics\MathematicsConfig;

$config = new MathematicsConfig(
    model: 'gpt-4',
    temperature: 0.3,
    maxTokens: 1000
);
$mathService = $factory->createMathematicsService($config);

// Using factory with default configuration
$programmingService = $factory->createProgrammingService();

// Generate code
$code = $programmingService->generateCode(
    'Create a PHP function to calculate factorial',
    'php'
);

// Analyze code
$analysis = $programmingService->analyzeCode(
    ' function test() { return $x; }',
    'php'
);

// Debug code
$debug = $programmingService->debugCode(
    ' function divide($a, $b) { return $a / $b; }',
    'Division by zero error',
    'php'
);

// Using custom configuration
use SBAO\Programming\ProgrammingConfig;

$config = new ProgrammingConfig(
    model: 'gpt-4',
    temperature: 0.2,
    maxTokens: 2000,
    defaultLanguage: 'php',
    codeStyle: 'PSR-12'
);
$programmingService = $factory->createProgrammingService($config);

// Using factory with default configuration
$chatBot = $factory->createChatBotService();

// Single message
$response = $chatBot->chat('Hello, how are you?');

// Multi-turn conversation (history is maintained automatically)
$response1 = $chatBot->chat('What is the capital of France?');
$response2 = $chatBot->chat('What is its population?');

// Get conversation history
$history = $chatBot->getHistory();

// Clear history
$chatBot->clearHistory();

// Using custom configuration
use SBAO\ChatBot\ChatBotConfig;

$config = new ChatBotConfig(
    model: 'gpt-4',
    temperature: 0.7,
    maxTokens: 1000,
    systemPrompt: 'You are a helpful assistant.',
    maxHistory: 20
);
$chatBot = $factory->createChatBotService($config);

// Using custom conversation history
$history = [
    ['role' => 'user', 'content' => 'Hello'],
    ['role' => 'assistant', 'content' => 'Hi there!'],
];
$response = $chatBot->chat('What is 2+2?', $history);

// Using factory with default configuration

// Speech-to-Text: Convert audio to text
$speechToText = $factory->createSpeechToTextService();

// Transcribe from audio file
$text = $speechToText->transcribeFromFile('/path/to/audio.mp3');

// Transcribe from base64-encoded audio
$base64Audio = 'data:audio/mp3;base64,UklGRiQAAABXQVZFZm10...';
$text = $speechToText->transcribeFromBase64($base64Audio, 'audio.mp3');

// Text-to-Speech: Convert text to audio
$textToSpeech = $factory->createTextToSpeechService();

// Synthesize text to audio (returns binary data)
$audioData = $textToSpeech->synthesize('Hello, world!', 'nova', 'mp3', 1.0);

// Synthesize and save to file
$textToSpeech->synthesizeToFile(
    'Hello, world!',
    '/path/to/output.mp3',
    'nova',  // voice: alloy, echo, fable, onyx, nova, shimmer
    'mp3',   // format: mp3, opus, aac, flac
    1.0      // speed: 0.25 to 4.0
);

// Using custom configuration
use SBAO\Speech\SpeechConfig;

// Speech-to-Text configuration
$sttConfig = new SpeechConfig(
    sttModel: 'whisper-1',
    sttLanguage: 'en',
    sttResponseFormat: 'json',
    sttTemperature: 0.0
);
$speechToText = $factory->createSpeechToTextService($sttConfig);

// Text-to-Speech configuration
$ttsConfig = new SpeechConfig(
    ttsModel: 'tts-1',
    ttsVoice: 'nova',
    ttsSpeed: 1.0,
    ttsFormat: 'mp3'
);
$textToSpeech = $factory->createTextToSpeechService($ttsConfig);

use SBAO\Exception\InvalidImageException;
use SBAO\Exception\InvalidAudioException;
use SBAO\Exception\InvalidInputException;
use SBAO\Exception\ApiException;
use SBAO\Exception\NetworkException;
use SBAO\Exception\AuthenticationException;
use SBAO\Exception\RateLimitException;

try {
    $text = $ocrService->extractFromFile('/path/to/image.jpg');
    // Or for Speech-to-Text:
    // $text = $speechToText->transcribeFromFile('/path/to/audio.mp3');
} catch (InvalidImageException $e) {
    // Handle invalid image
    echo "Invalid image: " . $e->getMessage();
} catch (InvalidAudioException $e) {
    // Handle invalid audio
    echo "Invalid audio: " . $e->getMessage();
} catch (AuthenticationException $e) {
    // Handle authentication error
    echo "Authentication failed: " . $e->getMessage();
} catch (RateLimitException $e) {
    // Handle rate limiting
    echo "Rate limit exceeded. Retry after: " . $e->getRetryAfter();
} catch (NetworkException $e) {
    // Handle network errors
    echo "Network error: " . $e->getMessage();
} catch (ApiException $e) {
    // Handle other API errors
    echo "API error: " . $e->getMessage();
}