1. Go to this page and download the library: Download tigusigalpa/monica-api-php 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/ */
tigusigalpa / monica-api-php example snippets
igusigalpa\MonicaApi\MonicaClient;
use Tigusigalpa\MonicaApi\Exceptions\MonicaApiException;
use Tigusigalpa\MonicaApi\Exceptions\InvalidModelException;
// Initialize the client with GPT-5 (latest flagship model)
$client = new MonicaClient('your-monica-api-key', 'gpt-5');
try {
// Simple chat completion
$response = $client->chat('Hello! How are you today?');
echo $response->getContent();
} catch (MonicaApiException $e) {
echo "API Error: " . $e->getMessage();
} catch (InvalidModelException $e) {
echo "Invalid Model: " . $e->getMessage();
}
use Tigusigalpa\MonicaApi\MonicaClient;
// Use GPT-5 for the most advanced AI capabilities
$client = new MonicaClient('your-api-key', 'gpt-5');
$response = $client->chat('Explain quantum computing in simple terms');
echo $response->getContent();
$response = $client->chat('Write a creative story', [
'system' => 'You are a creative storyteller',
'temperature' => 0.8,
'max_tokens' => 500,
'top_p' => 0.9
]);
use Tigusigalpa\MonicaApi\Models\ChatMessage;
$messages = [
ChatMessage::system('You are a helpful programming assistant'),
ChatMessage::user('How do I create a PHP class?'),
ChatMessage::assistant('To create a PHP class, use the `class` keyword...'),
ChatMessage::user('Can you show me an example?')
];
$response = $client->chatWithMessages($messages, [
'temperature' => 0.3,
'max_tokens' => 1000
]);
// Quick questions
$response = $client->chat('What is the capital of France?');
// Simple tasks with system context
$response = $client->chat('Translate this to Spanish: Hello world', [
'system' => 'You are a professional translator',
'temperature' => 0.3
]);
// Testing and prototyping
$response = $client->chat('Explain quantum physics in simple terms');
// Multiple messages with different roles
$messages = [
ChatMessage::system('You are a helpful coding assistant'),
ChatMessage::user('How do I create a REST API in PHP?'),
ChatMessage::assistant('To create a REST API in PHP, you can use...'),
ChatMessage::user('Can you show me a complete example?')
];
$response = $client->chatWithMessages($messages);
// Image analysis (4,...']]
]
];
$message = ChatMessage::fromArray($messageData);
$response = $client->chatWithMessages([$message]);
// Before: Using chat()
$response = $client->chat('Hello, how are you?', [
'system' => 'You are a friendly assistant'
]);
// After: Using chatWithMessages()
$messages = [
ChatMessage::system('You are a friendly assistant'),
ChatMessage::user('Hello, how are you?')
];
$response = $client->chatWithMessages($messages);
use Tigusigalpa\MonicaApi\MonicaClient;
use Tigusigalpa\MonicaApi\Models\ChatMessage;
// GPT-5 provides the most advanced image analysis capabilities
$client = new MonicaClient('your-api-key', 'gpt-5');
// Create a message with image from file
$message = ChatMessage::userWithImage(
'What do you see in this image?',
'path/to/your/image.jpg'
);
// Alternative: Add image to existing message
$message = ChatMessage::user('Analyze this image for me');
$message->addImageFromFile('path/to/your/image.jpg', 'high'); // detail level: low, high, auto
$response = $client->chatWithMessages([$message]);
echo $response->getContent();
// Create message with image from URL
$message = ChatMessage::userWithImage(
'Describe what you see in this photo',
'https://example.com/image.jpg'
);
$response = $client->chatWithMessages([$message]);
echo $response->getContent();
// Upload multiple images at once
$imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'path/to/local/image3.png'
];
$message = ChatMessage::userWithImages(
'Compare these images and tell me the differences',
$imageUrls
);
$response = $client->chatWithMessages([$message]);
echo $response->getContent();
// Upload image from base64 data
$base64ImageData = base64_encode(file_get_contents('image.jpg'));
$message = ChatMessage::user('What breed is this dog?');
$message->addImageFromBase64($base64ImageData, 'image/jpeg', 'high');
$response = $client->chatWithMessages([$message]);
echo $response->getContent();
use Tigusigalpa\MonicaApi\Models\ChatMessage;
$messages = [
ChatMessage::system('You are an expert art critic and historian.'),
ChatMessage::userWithImage(
'Please analyze this painting in detail',
'path/to/painting.jpg'
)
];
$response = $client->chatWithMessages($messages, [
'temperature' => 0.7,
'max_tokens' => 1500
]);
echo "Art Analysis: " . $response->getContent();
// Continue the conversation with follow-up questions
$messages[] = ChatMessage::assistant($response->getContent());
$messages[] = ChatMessage::user('What art movement does this belong to?');
$followUp = $client->chatWithMessages($messages);
echo "Art Movement: " . $followUp->getContent();
// Control image processing detail level
$message = ChatMessage::user('Examine this image closely');
$message->addImageFromFile('detailed_image.jpg', 'high'); // More detailed analysis
// or
$message->addImageFromFile('simple_image.jpg', 'low'); // Faster, less detailed
// Check if message has images
if ($message->hasImages()) {
echo "Message contains " . count($message->getImages()) . " images";
}
// Get image information
$images = $message->getImages();
foreach ($images as $image) {
echo "Image URL: " . $image['image_url']['url'] . "\n";
echo "Detail level: " . $image['image_url']['detail'] . "\n";
}
// Create a simple text message from array
$messageData = [
'role' => 'user',
'content' => 'Hello, how are you today?'
];
$message = ChatMessage::fromArray($messageData);
$response = $client->chatWithMessages([$message]);
// Create a complex multimodal message with text and images
$messageData = [
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => 'Please solve this equation step by step:'
],
[
'type' => 'image_url',
'image_url' => [
'url' => 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA...',
'detail' => 'high'
]
],
[
'type' => 'text',
'text' => 'Show all intermediate steps in your solution.'
],
[
'type' => 'image_url',
'image_url' => [
'url' => 'https://example.com/reference-image.png',
'detail' => 'auto'
]
]
]
];
$message = ChatMessage::fromArray($messageData);
$response = $client->chatWithMessages([$message]);
echo $response->getContent();
// Create multiple messages from array data
$conversationData = [
[
'role' => 'system',
'content' => 'You are a helpful math tutor.'
],
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => 'Help me understand this problem:'
],
[
'type' => 'image_url',
'image_url' => [
'url' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...',
'detail' => 'high'
]
]
]
]
];
// Convert array data to ChatMessage objects
$messages = array_map(function($messageData) {
return ChatMessage::fromArray($messageData);
}, $conversationData);
$response = $client->chatWithMessages($messages);
echo $response->getContent();
/**
* Convert an array of message data to ChatMessage objects
*/
function createMessagesFromArray(array $messagesData): array
{
return array_map(function($messageData) {
return ChatMessage::fromArray($messageData);
}, $messagesData);
}
// Usage
$messagesData = [
['role' => 'system', 'content' => 'You are an expert assistant.'],
['role' => 'user', 'content' => 'What is the capital of France?'],
['role' => 'assistant', 'content' => 'The capital of France is Paris.'],
['role' => 'user', 'content' => 'Tell me more about it.']
];
$messages = createMessagesFromArray($messagesData);
$response = $client->chatWithMessages($messages);
use Tigusigalpa\MonicaApi\MonicaClient;
$client = new MonicaClient('your-api-key', 'gpt-5');
// Generate a single image with FLUX
$response = $client->generateImageSimple(
'flux_dev',
'A beautiful sunset over mountains, digital art style',
[
'size' => '1024x1024',
'steps' => 25,
'guidance' => 3.5,
'seed' => 42
]
);
echo "Generated image URL: " . $response->getFirstImageUrl();
// Save the image
$response->saveFirstImage('sunset.png');
use Tigusigalpa\MonicaApi\Models\ImageGeneration;
// Create detailed image generation request
$imageGen = new ImageGeneration('sd3_5', 'A majestic dragon flying over a medieval castle');
$imageGen->setNegativePrompt('blurry, low quality, distorted')
->setSize('1024x1024')
->setSteps(30)
->setCfgScale(7.5)
->setSeed(123);
$response = $client->generateImage($imageGen);
// Work with multiple images
foreach ($response->getImageUrls() as $index => $url) {
echo "Image " . ($index + 1) . ": {$url}\n";
}
// Save all images to directory
$savedFiles = $response->saveAllImages('./images/', 'dragon_', 'png');
$response = $client->generateImageSimple(
'dall-e-3',
'A cute robot playing with colorful balloons in a park',
[
'size' => '1024x1024',
'quality' => 'hd',
'style' => 'vivid'
]
);
$imageGen = new ImageGeneration('V_2', 'Logo design for "TECH STARTUP" with modern typography');
$imageGen->setAspectRatio('ASPECT_16_9')
->setMagicPromptOption('AUTO')
->setStyleType('AUTO');
$response = $client->generateImage($imageGen);
// Check if a model is supported
if ($client->isModelSupported('gpt-5')) {
$client->setModel('gpt-5');
}
// Get all supported models
$models = MonicaClient::getSupportedModels();
foreach ($models as $provider => $providerModels) {
echo "Provider: $provider\n";
foreach ($providerModels as $modelId => $modelName) {
echo " - $modelId: $modelName\n";
}
}
// Get models by specific provider
$openaiModels = MonicaClient::getModelsByProvider('OpenAI');
try {
$response = $client->chat('Hello world');
} catch (InvalidModelException $e) {
// Handle invalid model errors
echo "Model error: " . $e->getUserFriendlyMessage();
// Get suggestions for similar models
$suggestions = $e->getSuggestions();
if (!empty($suggestions)) {
echo "Did you mean: " . implode(', ', $suggestions);
}
} catch (MonicaApiException $e) {
// Handle API errors
if ($e->isAuthenticationError()) {
echo "Please check your API key";
} elseif ($e->isRateLimitError()) {
echo "Rate limit exceeded, please wait";
} elseif ($e->isQuotaError()) {
echo "API quota exceeded";
} else {
echo "API Error: " . $e->getUserFriendlyMessage();
}
}
$response = $client->chat('Tell me a joke');
// Get response content
echo $response->getContent();
// Get usage statistics
echo "Tokens used: " . $response->getTotalTokens() . "\n";
echo "Prompt tokens: " . $response->getPromptTokens() . "\n";
echo "Completion tokens: " . $response->getCompletionTokens() . "\n";
// Check completion status
if ($response->isComplete()) {
echo "Response completed normally";
} elseif ($response->wasTruncated()) {
echo "Response was truncated due to length limit";
} elseif ($response->wasFiltered()) {
echo "Response was filtered due to content policy";
}
// Get response as ChatMessage object
$message = $response->getFirstChoiceAsMessage();
if ($message) {
echo $message->getRole() . ": " . $message->getContent();
}
$response = $client->chat('Write a poem about nature', [
'system' => 'You are a poetic AI that writes beautiful verses',
'temperature' => 0.7,
'max_tokens' => 300,
'top_p' => 0.9,
'frequency_penalty' => 0.1,
'presence_penalty' => 0.1
]);
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Tigusigalpa\MonicaApi\MonicaClient;
class MonicaServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(MonicaClient::class, function ($app) {
return new MonicaClient(
config('services.monica.api_key'),
config('services.monica.default_model', 'gpt-5')
);
});
}
}