Skip to content

Commit d9011ad

Browse files
authored
Merge pull request #25 from WordPress/enhance/documentation
Notably enhance documentation with additional code examples, including more complex ones
2 parents 9037ede + 3a75ad7 commit d9011ad

File tree

1 file changed

+175
-34
lines changed

1 file changed

+175
-34
lines changed

README.md

Lines changed: 175 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -13,85 +13,226 @@ Built on top of the [PHP AI Client](https://github.com/WordPress/php-ai-client),
1313
- **Automatic Credential Wiring**: Automatic wiring up of AI provider API credentials based on storage in a WordPress database option.
1414
- **PSR-compliant HTTP Client**: HTTP client implementation using the WordPress HTTP API, fully compatible with PSR standards.
1515

16-
## Installation and Configuration
17-
18-
1. Add this package to your WordPress plugin.
19-
```bash
20-
composer require wordpress/wp-ai-client
21-
```
22-
2. Initialize the package by hooking up the `WordPress\AI_Client\AI_Client::init()` method to the WordPress `init` action:
23-
```php
24-
add_action( 'init', array( \WordPress\AI_Client\AI_Client::class, 'init' ) );
25-
```
26-
3. With your plugin active, visit _Settings > AI Credentials_ in WP Admin to configure AI provider credentials.
27-
4. Get started prompting various AI models by using the `WordPress\AI_Client\AI_Client::prompt( )` method.
16+
## Installation
17+
18+
```bash
19+
composer require wordpress/wp-ai-client
20+
```
2821

2922
## Configuration
3023

31-
## Code examples
24+
### 1. Initialize the Client
25+
26+
You must initialize the client on the WordPress `init` hook. This sets up the HTTP client integration and registers the settings screen.
27+
28+
```php
29+
add_action( 'init', array( 'WordPress\AI_Client\AI_Client', 'init' ) );
30+
```
31+
32+
### 2. Configure API Credentials
33+
34+
Before making requests, you need to configure API keys for your desired providers (e.g. Anthropic, Google, OpenAI).
3235

33-
### Text generation using a specific model
36+
1. Go to **Settings > AI Credentials** in the WordPress Admin.
37+
2. Enter your API keys for the providers you intend to use.
38+
3. Save changes.
39+
40+
## Usage
41+
42+
The SDK provides a fluent `Prompt_Builder` interface to construct and execute AI requests.
43+
44+
### Text Generation
3445

3546
```php
3647
use WordPress\AI_Client\AI_Client;
3748

38-
$text = AI_Client::prompt( 'Write a 2-verse poem about PHP.' )
39-
->using_model( Google::model( 'gemini-2.5-flash' ) )
49+
$text = AI_Client::prompt( 'Write a haiku about WordPress.' )
4050
->generate_text();
51+
52+
echo wp_kses_post( $text );
4153
```
4254

43-
### Text generation using any compatible model from a specific provider
55+
### Image Generation
4456

4557
```php
4658
use WordPress\AI_Client\AI_Client;
4759

48-
$text = AI_Client::prompt( 'Write a 2-verse poem about PHP.' )
49-
->using_provider( 'openai' )
50-
->generate_text();
60+
$image_file = AI_Client::prompt( 'A futuristic WordPress logo in neon style' )
61+
->generate_image();
62+
63+
$data_uri = $image_file->getDataUri();
64+
65+
echo '<img src="' . esc_url( $data_uri ) . '" alt="A futuristic WordPress logo in neon style">';
5166
```
5267

53-
### Text generation using any compatible model
68+
### Advanced Usage
69+
70+
#### JSON Output and Temperature
5471

5572
```php
5673
use WordPress\AI_Client\AI_Client;
5774

58-
$text = AI_Client::prompt( 'Write a 2-verse poem about PHP.' )
75+
$schema = array(
76+
'type' => 'array',
77+
'items' => array(
78+
'type' => 'object',
79+
'properties' => array(
80+
'plugin_name' => array( 'type' => 'string' ),
81+
'category' => array( 'type' => 'string' ),
82+
),
83+
'required' => array( 'plugin_name', 'category' ),
84+
),
85+
);
86+
87+
$json = AI_Client::prompt( 'List 5 popular WordPress plugins with their primary category.' )
88+
->using_temperature( 0.2 ) // Lower temperature for more deterministic result.
89+
->as_json_response( $schema )
5990
->generate_text();
91+
92+
// Output will be a JSON string adhering to the schema.
93+
$data = json_decode( $json, true );
94+
```
95+
96+
#### Generating Multiple Image Candidates
97+
98+
```php
99+
use WordPress\AI_Client\AI_Client;
100+
101+
$images = AI_Client::prompt( 'Aerial shot of snowy plains, cinematic.' )
102+
->generate_images( 4 );
103+
104+
foreach ( $images as $image_file ) {
105+
echo '<img src="' . esc_url( $image_file->getDataUri() ) . '" alt="Aerial shot of snowy plains">';
106+
}
107+
```
108+
109+
#### Multimodal Output (Text & Image)
110+
111+
```php
112+
use WordPress\AI_Client\AI_Client;
113+
use WordPress\AiClient\Messages\Enums\ModalityEnum;
114+
115+
$result = AI_Client::prompt( 'Create a recipe for a chocolate cake and include photos for the steps.' )
116+
->as_output_modalities( ModalityEnum::text(), ModalityEnum::image() )
117+
->generate_result();
118+
119+
// Iterate through the message parts.
120+
foreach ( $result->toMessage()->getParts() as $part ) {
121+
if ( $part->isText() ) {
122+
echo wp_kses_post( $part->getText() );
123+
} elseif ( $part->isFile() && $part->getFile()->isImage() ) {
124+
echo '<img src="' . esc_url( $part->getFile()->getDataUri() ) . '" alt="">';
125+
}
126+
}
60127
```
61128

62-
### Text generation with additional parameters
129+
## Best Practices
130+
131+
### Automatic Model Selection
132+
133+
By default, the SDK automatically chooses a suitable model based on the prompt's requirements (e.g., text vs. image) and the configured providers on the site. This makes your plugin **provider-agnostic**, allowing it to work on any site regardless of which AI provider the admin has configured.
134+
135+
### Using Model Preferences
136+
137+
If you prefer specific models for better performance or capabilities, use `using_model_preference()`. The SDK will try to use the first available model from your list. If none are available (e.g., provider not configured), it falls back to automatic selection.
138+
139+
Pass preferences as an array of `[ provider_id, model_id ]` to ensure the correct provider is targeted.
63140

64141
```php
65142
use WordPress\AI_Client\AI_Client;
66143

67-
$text = AI_Client::prompt( 'Write a 2-verse poem about PHP.' )
68-
->using_system_instruction( 'You are a famous poet from the 17th century.' )
69-
->using_temperature( 0.8 )
144+
$summary = AI_Client::prompt( 'Summarize the history of the printing press.' )
145+
->using_temperature( 0.1 )
146+
->using_model_preference(
147+
array( 'anthropic', 'claude-sonnet-4-5' ),
148+
array( 'google', 'gemini-3-pro-preview' ),
149+
array( 'openai', 'gpt-5.1' )
150+
)
70151
->generate_text();
71152
```
72153

73-
### Text generation with multiple candidates using any compatible model
154+
### Using a Specific Model
155+
156+
Enforcing a single specific model using `using_model()` restricts your feature to sites that have that specific provider configured. For most scenarios, this is unnecessarily opinionated. Only use this approach if you really only want to offer the feature in combination with that model.
74157

75158
```php
76159
use WordPress\AI_Client\AI_Client;
160+
use WordPress\AiClient\ProviderImplementations\Anthropic\AnthropicProvider as Anthropic;
77161

78-
$texts = AI_Client::prompt( 'Write a 2-verse poem about PHP.' )
79-
->generate_texts( 4 );
162+
$text = AI_Client::prompt( 'Explain quantum computing in simple terms.' )
163+
->using_model( Anthropic::model( 'claude-sonnet-4-5' ) )
164+
->generate_text();
80165
```
81166

82-
### Image generation using any compatible model
167+
### Feature Detection
168+
169+
Before actually sending an AI prompt and getting a response, always check if the prompt is supported before execution.
170+
171+
This is always recommended, but especially crucial if you require the use of a specific model.
83172

84173
```php
85174
use WordPress\AI_Client\AI_Client;
86175

87-
$imageFile = AI_Client::prompt( 'Generate an illustration of the PHP elephant in the Caribbean sea.' )
88-
->generate_image();
176+
$prompt = AI_Client::prompt( 'Explain quantum computing in simple terms.' )
177+
->using_temperature( 0.2 );
178+
179+
if ( $prompt->is_supported_for_text_generation() ) {
180+
// Safe to generate.
181+
$text = $prompt->generate_text();
182+
} else {
183+
// Fallback: Hide feature or show setup instructions.
184+
}
89185
```
90186

91-
See the [`Prompt_Builder` class](https://github.com/WordPress/wp-ai-client/blob/trunk/includes/Builders/Prompt_Builder.php) and its public methods for all the ways you can configure the prompt.
187+
The above condition will only evaluate to `true` if the site has one or more providers configured with models that support text generation including a temperature configuration.
188+
189+
Generally, using `is_supported_for_text_generation()` (or `is_supported_for_image_generation()`, etc.) ensures you only expose AI features that can actually run on the current site configuration.
190+
191+
## Error Handling
192+
193+
The SDK offers two ways to handle errors.
194+
195+
### 1. Exception Based
196+
197+
`AI_Client::prompt()` throws exceptions on failure.
198+
199+
```php
200+
try {
201+
$text = AI_Client::prompt( 'Hello' )->generate_text();
202+
} catch ( \Exception $e ) {
203+
wp_die( $e->getMessage() );
204+
}
205+
206+
echo wp_kses_post( $text );
207+
```
208+
209+
### 2. `WP_Error` Based
210+
211+
`AI_Client::prompt_with_wp_error()` returns a `WP_Error` object on failure.
212+
213+
> **Note:** This error handling mechanism is experimental. We are gathering feedback to decide whether the SDK should primarily focus on exceptions or `WP_Error` objects.
214+
215+
```php
216+
$text = AI_Client::prompt_with_wp_error( 'Hello' )
217+
->generate_text();
218+
219+
if ( is_wp_error( $text ) ) {
220+
wp_die( $text->get_error_message() );
221+
}
222+
223+
echo wp_kses_post( $text );
224+
```
92225

93-
**More documentation is coming soon.**
226+
## Architecture
227+
228+
This library is a WordPress-specific wrapper around the [PHP AI Client](https://github.com/WordPress/php-ai-client).
229+
230+
* **`WordPress\AI_Client\AI_Client`**: The main entry point.
231+
* **`WordPress\AI_Client\Builders\Prompt_Builder`**: A fluent builder for constructing AI requests. It maps WordPress-style `snake_case` methods to the underlying SDK's `camelCase` methods.
232+
* **`WordPress\AI_Client\Builders\Prompt_Builder_With_WP_Error`**: A wrapper around `Prompt_Builder` that catches exceptions and returns `WP_Error` objects.
94233

95234
## Further reading
96235

236+
See the [`Prompt_Builder` class](https://github.com/WordPress/wp-ai-client/blob/trunk/includes/Builders/Prompt_Builder.php) and its public methods for all the ways you can configure the prompt.
237+
97238
See the [contributing documentation](./CONTRIBUTING.md) for more information on how to get involved.

0 commit comments

Comments
 (0)