Skip to content

Commit ab2037b

Browse files
committed
Add documentation overing overview, getting started guide, and comprehensive provider-specific guides
1 parent fdad96a commit ab2037b

File tree

7 files changed

+1223
-1
lines changed

7 files changed

+1223
-1
lines changed

README.md

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# The Joomla! AI Package
2+
3+
## Installation via Composer
4+
5+
Add `"joomla/ai": "~4.0"` to the require block in your composer.json and then run `composer install`.
6+
7+
```json
8+
{
9+
"require": {
10+
"joomla/ai": "~4.0"
11+
}
12+
}
13+
```
14+
15+
Alternatively, you can simply run the following from the command line:
16+
17+
```sh
18+
composer require joomla/ai "~4.0"
19+
```
20+
21+
If you want to include the test sources and docs, use
22+
23+
```sh
24+
composer require --prefer-source joomla/ai "~4.0"
25+
```
26+
27+
## Using the AI Framework
28+
The AI Framework provides a straightforward, provider-agnostic interface for working with three main AI providers: OpenAI, Anthropic and Ollama. Instead of writing separate code for each provider’s SDK, developers write once and simply switch providers by changing configuration.
29+
30+
You can find the official provider APIs documentation here:
31+
- OpenAI API: https://platform.openai.com/docs/api-reference
32+
- Anthropic API: https://docs.anthropic.com/claude/docs
33+
- Ollama API: https://github.com/ollama/ollama/blob/main/docs/api.md
34+
35+
The AI framework is built upon the Http package which provides an easy way to consume URLs and web services in a transport independent way. Joomla\Http currently supports streams, sockets and cURL. The framework centralizes HTTP handling in the Abstract Provider. Providers encapsulate:
36+
- Base URLs, headers, and auth (API keys/tokens)
37+
- Request building (JSON/multipart)
38+
- Response normalization and error mapping into framework exceptions
39+
40+
## Instantiating a Provider
41+
42+
Each provider is instantiated with its configuration (API key, defaults such as model or base URL). You can override these defaults per call when needed.
43+
44+
### OpenAI:
45+
```php
46+
use Joomla\AI\Provider\OpenAIProvider;
47+
48+
$openai = new OpenAIProvider([
49+
'api_key' => getenv('OPENAI_API_KEY'),
50+
// Optional defaults:
51+
// 'model' => 'gpt-4o',
52+
// 'base_url' => 'https://api.openai.com/v1',
53+
]);
54+
```
55+
56+
### Anthropic:
57+
```php
58+
use Joomla\AI\Provider\AnthropicProvider;
59+
60+
$anthropic = new AnthropicProvider([
61+
'api_key' => getenv('ANTHROPIC_API_KEY'),
62+
// 'model' => 'claude-3-5-sonnet',
63+
]);
64+
```
65+
66+
### Ollama (local):
67+
```php
68+
use Joomla\AI\Provider\OllamaProvider;
69+
70+
$ollama = new OllamaProvider([
71+
// 'base_url' => 'http://localhost:11434',
72+
// 'model' => 'llama3',
73+
]);
74+
```
75+
76+
## Supported Methods
77+
78+
| Provider | Methods |
79+
| --- | --- |
80+
| OpenAI | `chat`, `vision`, `generateImage`, `createImageVariation`, `editImage`, `speech`, `transcribe`, `translate`, `createEmbeddings`, `moderate`, `isContentFlagged`|
81+
| Anthropic | `chat`, `vision`, `getModel`|
82+
| Ollama | `chat`, `generate`, `pullModel`, `copyModel`, `deleteModel`, `checkModelExists`, `getRunningModels`|
83+
84+
Not all providers implement every capability. The framework exposes capabilities via interfaces (e.g. ChatInterface, ImageInterface). Developers can use what each provider supports.
85+
86+
## Making your first request
87+
All providers implement a shared set of capability interfaces (e.g., Chat, Images, Audio). Invoke these methods directly, passing per-call options to override defaults.
88+
89+
```php
90+
// Chat example (OpenAI)
91+
$response = $openai->chat("Write a haiku about Joomla.", [
92+
'model' => 'gpt-4o-mini', // overrides constructor default if set
93+
]);
94+
echo $response->getContent(); // primary content (e.g. text)
95+
$meta = $response->getMetadata(); // metadata content (e.g. model, usage)
96+
```
97+
98+
## Error handling
99+
Provider HTTP errors are mapped to framework exceptions (e.g. auth, rate limit, invalid arguments). Catch and handle them as needed.
100+
```php
101+
try {
102+
$response = $openai->chat("Hello!");
103+
} catch (\Throwable $e) {
104+
// Log and surface a friendly message
105+
}
106+
```
107+
108+
## Documentation
109+
110+
- **[Overview](guides/overview.md)**
111+
Architecture & goals
112+
113+
- **[Getting Started](guides/index.md)**
114+
Install, configure, first provider
115+
116+
- **[Guides](guides/)**
117+
Task-specific guides (Chat, Images, Audio, etc.)
118+
119+
---

docs/getting-started.md

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,273 @@
1+
# Getting Started
2+
3+
This guide will help you install the AI Framework and make your first request in just a few minutes.
4+
5+
## Requirements
6+
7+
- PHP 8.3.0 or higher
8+
- Composer
9+
- API keys for the providers you want to use
10+
11+
## Installation
12+
13+
### Via Composer
14+
15+
Add the AI package to your project:
16+
17+
```json
18+
{
19+
"require": {
20+
"joomla/ai": "~4.0"
21+
}
22+
}
23+
```
24+
25+
Then run:
26+
```bash
27+
composer install
28+
```
29+
30+
Alternatively, install directly:
31+
```bash
32+
composer require joomla/ai "~4.0"
33+
```
34+
35+
For development with test sources:
36+
```bash
37+
composer require --prefer-source joomla/ai "~4.0"
38+
```
39+
40+
## Configuration
41+
42+
### API Keys
43+
44+
You will need API keys from the providers you want to use:
45+
46+
- **OpenAI**: Get your key at https://platform.openai.com/api-keys
47+
- **Anthropic**: Get your key at https://console.anthropic.com/
48+
- **Ollama**: Runs locally, no API key needed
49+
50+
### Storing API Keys
51+
52+
**It is recommended to store API keys in environment variables** for security reasons. Never commit API keys to version control.
53+
54+
**Windows (Command Prompt):**
55+
```cmd
56+
setx OPENAI_API_KEY "sk-your-openai-key-here"
57+
setx ANTHROPIC_API_KEY "sk-ant-your-anthropic-key-here"
58+
```
59+
60+
**Windows (PowerShell):**
61+
```powershell
62+
[Environment]::SetEnvironmentVariable("OPENAI_API_KEY", "sk-your-openai-key-here", "User")
63+
[Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-your-anthropic-key-here", "User")
64+
```
65+
66+
> **Note**: Restart your terminal or web server after setting environment variables to ensure they are loaded.
67+
68+
## Your First Request
69+
70+
### Basic Chat Example
71+
72+
```php
73+
<?php
74+
require_once 'vendor/autoload.php';
75+
76+
use Joomla\AI\Provider\OpenAIProvider;
77+
78+
// Create provider instance
79+
$openai = new OpenAIProvider([
80+
'api_key' => getenv('OPENAI_API_KEY')
81+
]);
82+
83+
// Make your first chat request
84+
$response = $openai->chat("Hello! Tell me about Joomla in one sentence.");
85+
86+
// Display the result
87+
echo "Response: " . $response->getContent() . "\n";
88+
echo "Model used: " . $response->getMetadata()['model'] . "\n";
89+
echo "Provider: " . $response->getProvider() . "\n";
90+
```
91+
92+
### Multi-Provider Example
93+
94+
```php
95+
<?php
96+
require_once 'vendor/autoload.php';
97+
98+
use Joomla\AI\Provider\OpenAIProvider;
99+
use Joomla\AI\Provider\AnthropicProvider;
100+
use Joomla\AI\Provider\OllamaProvider;
101+
102+
// Configure multiple providers
103+
$providers = [
104+
'openai' => new OpenAIProvider(['api_key' => getenv('OPENAI_API_KEY')]),
105+
'anthropic' => new AnthropicProvider(['api_key' => getenv('ANTHROPIC_API_KEY')]),
106+
'ollama' => new OllamaProvider() // Local server, no API key needed
107+
];
108+
109+
$question = "What is Joomla?";
110+
111+
foreach ($providers as $name => $provider) {
112+
try {
113+
$response = $provider->chat($question);
114+
echo "\n=== {$name} ===\n";
115+
echo $response->getContent() . "\n";
116+
} catch (Exception $e) {
117+
echo "{$name}: Error - " . $e->getMessage() . "\n";
118+
}
119+
}
120+
```
121+
122+
## Working with Different Capabilities
123+
124+
### Image Generation
125+
126+
```php
127+
use Joomla\AI\Provider\OpenAIProvider;
128+
129+
$openai = new OpenAIProvider(['api_key' => getenv('OPENAI_API_KEY')]);
130+
131+
// Generate an image
132+
$image = $openai->generateImage("A beautiful sunset over mountains", [
133+
'model' => 'dall-e-3',
134+
'size' => '1024x1024',
135+
'response_format' => 'b64_json'
136+
]);
137+
138+
// Save the image
139+
$image->saveFile('my_sunset.png');
140+
echo "Image saved as my_sunset.png\n";
141+
```
142+
143+
### Text-to-Speech
144+
145+
```php
146+
$audio = $openai->speech("Welcome to Joomla! This is a text-to-speech demo.", [
147+
'model' => 'tts-1',
148+
'voice' => 'alloy',
149+
'response_format' => 'mp3'
150+
]);
151+
152+
$audio->saveFile('welcome.mp3');
153+
echo "Audio saved as welcome.mp3\n";
154+
```
155+
156+
### Vision (Image Analysis)
157+
158+
```php
159+
$vision = $openai->vision(
160+
"What do you see in this image?",
161+
"https://example.com/your-image.jpg"
162+
);
163+
164+
echo "Vision analysis: " . $vision->getContent() . "\n";
165+
```
166+
167+
## Setting Default Models
168+
169+
Avoid repeating model names by setting defaults:
170+
171+
```php
172+
$openai = new OpenAIProvider(['api_key' => getenv('OPENAI_API_KEY')]);
173+
174+
// Set a default model for all chat requests
175+
$openai->setDefaultModel('gpt-4o-mini');
176+
177+
// These will use gpt-4o-mini
178+
$response1 = $openai->chat("Hello!");
179+
$response2 = $openai->chat("How are you?");
180+
181+
// Override the default for one request
182+
$response3 = $openai->chat("Complex task", ['model' => 'gpt-4o']);
183+
184+
// Back to default
185+
$response4 = $openai->chat("Simple task");
186+
187+
// Clear the default
188+
$openai->unsetDefaultModel();
189+
```
190+
191+
## Error Handling
192+
193+
The framework provides specific exceptions that are inherited from [`AIException`](../src/Exception/AIException.php):
194+
195+
```php
196+
use Joomla\AI\Exception\AuthenticationException;
197+
use Joomla\AI\Exception\RateLimitException;
198+
use Joomla\AI\Exception\QuotaExceededException;
199+
use Joomla\AI\Exception\InvalidArgumentException;
200+
use Joomla\AI\Exception\ProviderException;
201+
202+
try {
203+
$response = $openai->chat("Hello!");
204+
echo $response->getContent();
205+
} catch (AuthenticationException $e) {
206+
echo "Authentication failed: Check your API key\n";
207+
} catch (RateLimitException $e) {
208+
echo "Rate limited: Please wait before trying again\n";
209+
} catch (QuotaExceededException $e) {
210+
echo "Quota exceeded: Check your billing\n";
211+
} catch (InvalidArgumentException $e) {
212+
echo "Invalid input: " . $e->getMessage() . "\n";
213+
} catch (ProviderException $e) {
214+
echo "Provider error: " . $e->getMessage() . "\n";
215+
} catch (Exception $e) {
216+
echo "Unexpected error: " . $e->getMessage() . "\n";
217+
}
218+
```
219+
220+
## Local Development with Ollama
221+
222+
For local AI without API costs:
223+
224+
1. **Install Ollama**: Download from https://ollama.ai/
225+
2. **Pull a model**: `ollama pull llama3`
226+
3. **Use in your code**:
227+
228+
```php
229+
use Joomla\AI\Provider\OllamaProvider;
230+
231+
$ollama = new OllamaProvider();
232+
233+
$response = $ollama->chat("Hello!", ['model' => 'llama3']);
234+
echo $response->getContent();
235+
```
236+
237+
## Response Object
238+
239+
All methods return a unified [`Response`](../src/Response/Response.php) object:
240+
241+
```php
242+
$response = $provider->chat("Hello!");
243+
244+
// Primary content
245+
echo $response->getContent();
246+
247+
// Provider metadata (model, usage, etc.)
248+
$metadata = $response->getMetadata();
249+
print_r($metadata);
250+
251+
// Provider name
252+
echo $response->getProvider(); // "OpenAI", "Anthropic", or "Ollama"
253+
254+
// Save files (for images, audio)
255+
$response->saveFile('output.png');
256+
```
257+
258+
## Next Steps
259+
260+
Now that you have the basics working:
261+
262+
- **[Provider Guides](providers/)** - Provider-specific features and limitations
263+
264+
## Troubleshooting
265+
266+
**API Key Issues:**
267+
- Ensure environment variables are set correctly
268+
- Restart your terminal/web server after setting environment variables
269+
- Check that your API keys have sufficient credits/permissions
270+
271+
**Model Issues:**
272+
- Verify the model name is correct and available
273+
- Some models may require special access or billing setup

docs/index.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,5 @@
11
* [Overview](overview.md)
2+
* [Getting Started](getting-started.md)
3+
* [Open AI Provider](providers/openai.md)
4+
* [Anthropic Provider](providers/anthropic.md)
5+
* [Ollama](providers/ollama.md)

0 commit comments

Comments
 (0)