Skip to content

Commit 716f44f

Browse files
committed
Rename methods as vision and saveFile
1 parent 6db0bdf commit 716f44f

File tree

11 files changed

+154
-25
lines changed

11 files changed

+154
-25
lines changed

Tests/DefaultModels.php

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
<?php
2+
3+
require_once '../vendor/autoload.php';
4+
5+
use Joomla\AI\Provider\OpenAIProvider;
6+
7+
echo "Testing Real OpenAI API Calls...\n\n";
8+
9+
$configFile = __DIR__ . '/../config.json';
10+
$config = json_decode(file_get_contents($configFile), true);
11+
$api_key = $config['openai_api_key'] ?? null;
12+
13+
try {
14+
// Create provider with your API key
15+
$provider = new OpenAIProvider([
16+
'api_key' => $api_key
17+
]);
18+
19+
echo "Provider created with API key\n";
20+
echo "Provider name: " . $provider->getName() . "\n\n";
21+
22+
// To Do: Check if the provider is supported. Currently key set as env variables only
23+
// // if (!OpenAIProvider::isSupported()) {
24+
// throw new \Exception('OpenAI API is not supported or API key is missing.');
25+
// }
26+
27+
// Set default model for all subsequent calls
28+
$provider->setDefaultModel('gpt-3.5-turbo');
29+
echo "Default model: " . $provider->getDefaultModel() . "\n\n";
30+
31+
// Test 1: Will use default model since ('gpt-3.5-turbo')
32+
// no model is specified in the options
33+
// and the default model is set
34+
echo "Test 1: Simple prompt- Will use default model gpt-3.5-turbo\n";
35+
echo str_repeat('-', 50) . "\n";
36+
$response = $provider->chat("Hello! How are you?");
37+
echo "Model: " . $response->getMetadata()['model'] . "\n";
38+
echo "Response: " . $response->getContent() . "\n";
39+
echo "\n";
40+
41+
// Test 2: Will use default model for the next call again since ('gpt-3.5-turbo')
42+
// no model is specified in the options
43+
// and the default model is set
44+
echo "Test 2: Multiple Response Choices- Will use default model gpt-3.5-turbo\n";
45+
echo str_repeat('-', 50) . "\n";
46+
47+
$response = $provider->chat("Suggest a name for a movie based on pilots and astronauts");
48+
echo "Model: " . $response->getMetadata()['model'] . "\n";
49+
echo "Response: " . $response->getContent() . "\n";
50+
echo "\n";
51+
52+
// Test 3: This will override the default model since
53+
// model is specified in the options ('gpt-4o-audio-preview')
54+
echo "Test 3: Test chat completions audio capability- Will override the default and use gpt-4o-audio-preview model\n";
55+
echo str_repeat('-', 50) . "\n";
56+
$response = $provider->chat("Say a few words on Joomla! for about 30 seconds in english.", [
57+
'model' => 'gpt-4o-audio-preview',
58+
'modalities' => ['text', 'audio'],
59+
'audio' => [
60+
'voice' => 'alloy',
61+
'format' => 'wav'
62+
],
63+
]);
64+
65+
$metadata = $response->getMetadata();
66+
echo "Model: " . $response->getMetadata()['model'] . "\n";
67+
if (isset($metadata['choices'][0]['message']['audio']['data'])) {
68+
$audioData = $metadata['choices'][0]['message']['audio']['data'];
69+
$audioDatab64 = base64_decode($audioData, true);
70+
$audioFile = file_put_contents("output/chat_completions_audio.wav", $audioDatab64);
71+
echo "Audio file found and saved to: \"output/chat_completions_audio.wav\".\n";
72+
} else {
73+
echo "Audio file not found.\n";
74+
}
75+
echo "\n";
76+
77+
// Test 4: Will use default model for the next call again since ('gpt-3.5-turbo')
78+
// no model is specified in the options
79+
// and the default model was never unset
80+
echo "Test 4: Simple prompt- Will use default model gpt-3.5-turbo because default model was not unset\n";
81+
echo str_repeat('-', 50) . "\n";
82+
83+
$response = $provider->chat("What is the capital of France?");
84+
echo "Model: " . $response->getMetadata()['model'] . "\n";
85+
echo "Response: " . $response->getContent() . "\n";
86+
echo "\n";
87+
88+
// Unset default model
89+
$provider->unsetDefaultModel();
90+
echo "Default model unset\n\n";
91+
92+
// Test 5: Uses method's default
93+
// (no model in options,
94+
// no default model,
95+
// no config model)
96+
echo "Test 5: generateImage with method's default model (should use 'dall-e-2')\n";
97+
echo str_repeat('-', 50) . "\n";
98+
99+
$response = $provider->generateImage("Generate an image of a dog playing chess.");
100+
$response->saveFile("output/test5_image.png");
101+
102+
echo "Model: " . ($response->getMetadata()['model']) . "\n";
103+
echo "File saved to: output/test5_image.png\n";
104+
echo "\n";
105+
106+
// Test 6: Uses provider's config default
107+
// (no model in options,
108+
// no default model,
109+
// config has model)
110+
$providerWithConfig = new OpenAIProvider([
111+
'api_key' => $api_key,
112+
'model' => 'dall-e-3' // Set default model in config
113+
]);
114+
115+
echo "Test 6: generateImage with provider's config default model (should use 'dall-e-3')\n";
116+
echo str_repeat('-', 50) . "\n";
117+
$response = $providerWithConfig->generateImage("Generate an image of gray tabby cat hugging an otter with an orange scarf. Make it look realistic.");
118+
119+
$response->saveFile("output/test6_image.png");
120+
echo "Model: " . ($response->getMetadata()['model']) . "\n";
121+
echo "File saved to: output/test6_image.png\n";
122+
echo "\n";
123+
124+
echo "\n" . str_repeat('=', 60) . "\n";
125+
echo "All Chat Completions API tests completed successfully!\n";
126+
} catch (Exception $e) {
127+
echo "Error: " . $e->getMessage() . "\n";
128+
}

Tests/DefaultsTest.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
$response1 = $provider->chat("Hi, Can you write a paragraph on the importance of AI in modern technology?");
2727
echo $response1->getContent();
28-
$response1->saveContentToFile('output/chat.txt');
28+
$response1->saveFile('output/chat.txt');
2929

3030
echo "\n" . str_repeat("=", 50) . "\n";
3131

@@ -38,7 +38,7 @@
3838
echo str_repeat("-", 40) . "\n";
3939

4040
$response2 = $provider->generateImage("Please generate an image for my blog post about my mount fuji hiking trip");
41-
$response2->saveContentToFile('output/mount_fuji.png');
41+
$response2->saveFile('output/mount_fuji.png');
4242

4343
echo "\n" . str_repeat("=", 50) . "\n";
4444

@@ -54,7 +54,7 @@
5454
'n' => 3,
5555
]
5656
);
57-
$response3->saveContentToFile('output/thin_pizza.txt');
57+
$response3->saveFile('output/thin_pizza.txt');
5858

5959
echo "\n" . str_repeat("=", 50) . "\n\n";
6060

@@ -69,7 +69,7 @@
6969
$text = "Hello world! This is a test of the OpenAI text-to-speech capability.";
7070

7171
$response4 = $provider->speech($text);
72-
$response4->saveContentToFile('output/speech_4.mp3');
72+
$response4->saveFile('output/speech_4.mp3');
7373

7474
echo str_repeat("=", 50) . "\n\n";
7575

@@ -85,7 +85,7 @@
8585

8686
$response5 = $provider->transcribe($audioFile);
8787
$response5->getContent();
88-
$response5->saveContentToFile('output/transcribed.txt');
88+
$response5->saveFile('output/transcribed.txt');
8989

9090
echo str_repeat("=", 50) . "\n\n";
9191

@@ -101,7 +101,7 @@
101101

102102
$response6 = $provider->translate($testAudioFile);
103103
echo $response6->getContent();
104-
$response6->saveContentToFile('output/translated.txt');
104+
$response6->saveFile('output/translated.txt');
105105

106106
echo "\n" . str_repeat("=", 50) . "\n\n";
107107

Tests/ModelManagementTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@
8888
// Test with valid vision model
8989
try {
9090
echo "Testing vision with valid model (gpt-4o-mini)...\n";
91-
$response = $provider->chatWithVision("What do you see?", $imageUrl);
91+
$response = $provider->vision("What do you see?", $imageUrl);
9292
echo "Vision with gpt-4o-mini successful\n";
9393
echo "Response: " . $response->getContent() . "\n\n";
9494
} catch (Exception $e) {
@@ -98,7 +98,7 @@
9898
// Test with invalid model for vision
9999
try {
100100
echo "Testing vision with invalid model (gpt-3.5-turbo)...\n";
101-
$response = $provider->chatWithVision("What do you see?", $imageUrl, ['model' => 'gpt-3.5-turbo']);
101+
$response = $provider->vision("What do you see?", $imageUrl, ['model' => 'gpt-3.5-turbo']);
102102
echo "This should not succeed!\n\n";
103103
} catch (Exception $e) {
104104
echo "Correctly caught error: " . $e->getMessage() . "\n\n";

Tests/ModerationTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@
131131
echo "Testing vision message: \"$flaggedVisionMessage\"\n";
132132
echo "With image URL: $sampleImageUrl\n";
133133

134-
$response = $provider->chatWithVision($flaggedVisionMessage, $sampleImageUrl);
134+
$response = $provider->vision($flaggedVisionMessage, $sampleImageUrl);
135135

136136
echo "Response: " . $response->getContent() . "\n";
137137
echo "Status: (FAILED) Flagged vision content was NOT blocked\n";

Tests/TextToSpeechTest.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
echo "Audio Size: " . $metadata['size_bytes'] . " bytes\n";
3838

3939
// Save audio to file
40-
$response->saveContentToFile('output/speech_test_1.mp3');
40+
$response->saveFile('output/speech_test_1.mp3');
4141
echo "Audio saved as 'output/speech_test_1.mp3'\n\n";
4242

4343
echo str_repeat("=", 50) . "\n\n";
@@ -65,7 +65,7 @@
6565
echo "Audio Size: " . $metadata2['size_bytes'] . " bytes\n";
6666

6767
// Save WAV file
68-
$response2->saveContentToFile('output/speech_test_2.wav');
68+
$response2->saveFile('output/speech_test_2.wav');
6969
echo "Audio saved as 'output/speech_test_2.wav'\n\n";
7070

7171
echo str_repeat("=", 50) . "\n\n";
@@ -95,7 +95,7 @@
9595
echo "Instructions Used: " . ($metadata3['instructions'] ?? 'None') . "\n";
9696

9797
// Save audio file
98-
$response3->saveContentToFile('output/speech_test_3.mp3');
98+
$response3->saveFile('output/speech_test_3.mp3');
9999
echo "Audio saved as 'output/speech_test_3.mp3'\n\n";
100100

101101
echo str_repeat("=", 50) . "\n\n";

Tests/TranscriptionTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
$testText = "Hello world! This is a test of the OpenAI transcription functionality. We are testing speech to text conversion with the Whisper model.";
2222

2323
$speechResponse = $provider->speech($testText, ['model' => 'tts-1', 'voice' => 'alloy', 'response_format' => 'wav']);
24-
$speechResponse->saveContentToFile('test_files/test_audio.wav');
24+
$speechResponse->saveFile('test_files/test_audio.wav');
2525
echo "Audio file created: test_files/test_audio.wav\n\n";
2626

2727
echo str_repeat("=", 60) . "\n\n";

Tests/TranslationTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
$testText = "Hallo, hiermit testen wir die Übersetzungsfunktion von OpenAI. Audio wird ins Englische übersetzt. Wir geben die Dateien und das zu verwendende Modell ein; aktuell ist nur Whisper-1 verfügbar. Ein optionaler Text dient zur Orientierung des Modells oder zur Fortsetzung eines vorherigen Audiosegments. Die Eingabeaufforderung sollte auf Englisch sein. Das Ausgabeformat kann in einer der folgenden Optionen gewählt werden: JSON, Text, SRT, Verbose_JSON oder VTT. Wir hoffen, dies funktioniert.";
2323

2424
$speechResponse = $provider->speech($testText, ['model' => 'tts-1', 'voice' => 'alloy', 'response_format' => 'wav']);
25-
$speechResponse->saveContentToFile('test_files/test_german_audio.wav');
25+
$speechResponse->saveFile('test_files/test_german_audio.wav');
2626
echo "Audio file created: test_files/test_german_audio.wav\n\n";
2727

2828
echo str_repeat("=", 60) . "\n\n";

Tests/ChatWithVisionTest.php renamed to Tests/VisionTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
echo "Test 1: Vision with image URL...\n";
2424
$imageUrl = "https://upload.wikimedia.org/wikipedia/commons/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg";
2525

26-
$response = $provider->chatWithVision("What do you see in this image?", $imageUrl);
26+
$response = $provider->vision("What do you see in this image?", $imageUrl);
2727

2828
echo "Vision API call successful!\n";
2929
echo "Response: " . $response->getContent() . "\n";
@@ -42,7 +42,7 @@
4242

4343
// Test 2: Vision with specific model
4444
echo "Test 2: Vision with specific model (gpt-4o)...\n";
45-
$response = $provider->chatWithVision(
45+
$response = $provider->vision(
4646
"Describe the colors and mood of this image.",
4747
$imageUrl,
4848
['model' => 'gpt-4o', 'max_tokens' => 100]

src/Interface/ChatInterface.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,5 +39,5 @@ public function chat(string $message, array $options = []): Response;
3939
* @return Response
4040
* @since __DEPLOY_VERSION__
4141
*/
42-
public function chatWithVision(string $message, string $image, array $options = []): Response;
42+
public function vision(string $message, string $image, array $options = []): Response;
4343
}

src/Provider/OpenAIProvider.php

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ public function chat(string $message, array $options = []): Response
455455
* @return Response
456456
* @since __DEPLOY_VERSION__
457457
*/
458-
public function chatWithVision(string $message, string $image, array $options = []): Response
458+
public function vision(string $message, string $image, array $options = []): Response
459459
{
460460
// Apply moderation to the input (text + image)
461461
$multiModalInput = [
@@ -509,8 +509,8 @@ public function generateImage(string $prompt, array $options = []): Response
509509
json_encode($payload),
510510
$headers
511511
);
512-
513-
return $this->parseImageResponse($httpResponse->getBody());
512+
513+
return $this->parseImageResponse($httpResponse->getBody(), $payload);
514514
}
515515

516516
/**
@@ -534,7 +534,7 @@ public function createImageVariation(string $imagePath, array $options = []): Re
534534
$headers
535535
);
536536

537-
return $this->parseImageResponse($httpResponse->getBody());
537+
return $this->parseImageResponse($httpResponse->getBody(), $payload);
538538
}
539539

540540
/**
@@ -566,7 +566,7 @@ public function editImage($images, string $prompt, array $options = []): Respons
566566
$headers
567567
);
568568

569-
return $this->parseImageResponse($httpResponse->getBody());
569+
return $this->parseImageResponse($httpResponse->getBody(), $payload);
570570
}
571571

572572
/**
@@ -1583,7 +1583,7 @@ private function parseOpenAIResponse(string $responseBody): Response
15831583
* @throws \Exception If response parsing fails
15841584
* @since __DEPLOY_VERSION__
15851585
*/
1586-
private function parseImageResponse(string $responseBody): Response
1586+
private function parseImageResponse(string $responseBody, array $payload): Response
15871587
{
15881588
// To Do: Clean Image API response for generation and editing
15891589
$data = $this->parseJsonResponse($responseBody);
@@ -1633,6 +1633,7 @@ private function parseImageResponse(string $responseBody): Response
16331633
}
16341634

16351635
$metadata = [
1636+
'model' => $data['model'] ?? $payload['model'],
16361637
'created' => $data['created'] ?? time(),
16371638
'response_format' => $responseFormat,
16381639
'image_count' => count($images),
@@ -1829,7 +1830,7 @@ private function parseEmbeddingResponse(string $responseBody, array $payload): R
18291830
$content = json_encode($contentData);
18301831

18311832
$metadata = [
1832-
'model' => $data['model'],
1833+
'model' => $data['model'] ?? $payload['model'],
18331834
'object' => $data['object'],
18341835
'embedding_count' => count($embeddings),
18351836
'encoding_format' => $payload['encoding_format'],

0 commit comments

Comments
 (0)