forked from WordPress/php-ai-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.php
More file actions
executable file
·191 lines (166 loc) · 5.7 KB
/
cli.php
File metadata and controls
executable file
·191 lines (166 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<?php
/**
* CLI script for interacting with the AI client.
*
* This script allows users to send prompts to the AI and receive responses.
* It supports named arguments for provider and model selection.
*
* Usage:
* GOOGLE_API_KEY=123456 php cli.php 'Your prompt here' --providerId=google --modelId=gemini-2.5-flash
* OPENAI_API_KEY=123456 php cli.php 'Your prompt here' --providerId=openai
* GOOGLE_API_KEY=123456 OPENAI_API_KEY=123456 php cli.php 'Your prompt here'
*/
declare(strict_types=1);
use WordPress\AiClient\AiClient;
use WordPress\AiClient\Providers\Http\Exception\ResponseException;
use WordPress\AiClient\Providers\Models\DTO\ModelConfig;
require_once __DIR__ . '/vendor/autoload.php';
/**
* Prints the output to stdout.
*
* @param string $output The output to print.
*/
function printOutput(string $output): void
{
echo $output . PHP_EOL;
}
/**
* Logs an informational message to stderr.
*
* @param string $message The message to log.
*/
function logInfo(string $message): void
{
fwrite(STDERR, '[INFO] ' . $message . PHP_EOL);
}
/**
* Logs a warning message to stderr.
*
* @param string $message The message to log.
*/
function logWarning(string $message): void
{
fwrite(STDERR, '[WARNING] ' . $message . PHP_EOL);
}
/**
* Logs an error message to stderr and terminates the script.
*
* @param string $message The message to log.
* @param int $exit_code The exit code to use.
*/
function logError(string $message, int $exit_code = 1): void
{
fwrite(STDERR, '[ERROR] ' . $message . PHP_EOL);
exit($exit_code);
}
// --- Argument parsing ---
$positional_args = [];
$named_args = [];
for ($i = 1; $i < $argc; $i++) {
$arg = $argv[$i];
if (str_starts_with($arg, '--')) {
$parts = explode('=', substr($arg, 2), 2);
$key = $parts[0];
$value = $parts[1] ?? true;
if (empty($key)) {
logWarning("Ignoring invalid named argument: {$arg}");
continue;
}
$named_args[$key] = $value;
} else {
$positional_args[] = $arg;
}
}
// --- Input validation ---
if (empty($positional_args[0])) {
logError('Missing required positional argument "prompt input".');
}
// Prompt input. Allow complex input as a JSON string.
$promptInput = $positional_args[0];
if (str_starts_with($promptInput, '{') || str_starts_with($promptInput, '[')) {
$decodedInput = json_decode($promptInput, true);
if ($decodedInput) {
$promptInput = $decodedInput;
}
}
// Provider ID, model ID, and output format.
$providerId = $named_args['providerId'] ?? null;
$modelId = $named_args['modelId'] ?? null;
$outputFormat = $named_args['outputFormat'] ?? 'message-text';
// Any model configuration options.
$schema = ModelConfig::getJsonSchema()['properties'];
$model_config_data = [];
foreach ($named_args as $key => $value) {
if (!isset($schema[$key])) {
continue;
}
$property_schema = $schema[$key];
$type = $property_schema['type'] ?? null;
$processed_value = $value;
if ($type === 'array' || $type === 'object') {
$decoded = json_decode((string) $value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
logWarning("Invalid JSON for argument --{$key}: " . json_last_error_msg());
continue;
}
$processed_value = $decoded;
} elseif ($type === 'integer') {
$processed_value = (int) $value;
} elseif ($type === 'number') {
$processed_value = (float) $value;
} elseif ($type === 'boolean') {
$processed_value = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if (null === $processed_value) {
logWarning("Invalid boolean for argument --{$key}: {$value}");
continue;
}
}
$model_config_data[$key] = $processed_value;
}
// --- Main logic ---
try {
$modelConfig = ModelConfig::fromArray($model_config_data);
$promptBuilder = AiClient::prompt($promptInput);
$promptBuilder = $promptBuilder->usingModelConfig($modelConfig);
if ($providerId && $modelId) {
$providerClassName = AiClient::defaultRegistry()->getProviderClassName($providerId);
$promptBuilder = $promptBuilder->usingModel($providerClassName::model($modelId));
} elseif ($providerId) {
$promptBuilder = $promptBuilder->usingProvider($providerId);
}
} catch (InvalidArgumentException $e) {
logError('Invalid arguments while trying to set up prompt builder: ' . $e->getMessage());
} catch (ResponseException $e) {
logError('Request failed while trying to set up prompt builder: ' . $e->getMessage());
}
try {
if ($outputFormat === 'image-json' || $outputFormat === 'image-base64') {
$result = $promptBuilder->generateImageResult();
} else {
$result = $promptBuilder->generateTextResult();
}
} catch (InvalidArgumentException $e) {
logError('Invalid arguments while trying to generate text result: ' . $e->getMessage());
} catch (ResponseException $e) {
logError('Request failed while trying to generate text result: ' . $e->getMessage());
}
logInfo("Using provider ID: \"{$result->getProviderMetadata()->getId()}\"");
logInfo("Using model ID: \"{$result->getModelMetadata()->getId()}\"");
switch ($outputFormat) {
case 'result-json':
$output = json_encode($result, JSON_PRETTY_PRINT);
break;
case 'candidates-json':
$output = json_encode($result->getCandidates(), JSON_PRETTY_PRINT);
break;
case 'image-json':
$output = json_encode($result->toFile(), JSON_PRETTY_PRINT);
break;
case 'image-base64':
$output = $result->toFile()->getBase64Data();
break;
case 'message-text':
default:
$output = $result->toText();
}
printOutput($output);