-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass-anthropic-client.php
More file actions
246 lines (214 loc) · 6.24 KB
/
Copy pathclass-anthropic-client.php
File metadata and controls
246 lines (214 loc) · 6.24 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
/**
* Thin Anthropic API client for Hey Woo DIFM tier.
*
* Uses `wp_remote_post()` directly — no SDK dependency. The abstraction
* boundary is intentionally here: if WordPress ships a first-party AI client
* (`wp_ai_client_prompt`) in a future release, swapping to it is a
* one-file change.
*
* @package HeyWoo\Difm
*/
namespace HeyWoo\Difm;
defined( 'ABSPATH' ) || exit;
/**
* Anthropic Messages API client.
*
* PHP 7.4 compatible — no union types, no match, no enums.
*/
class AnthropicClient {
/**
* Anthropic API base URL.
*/
const API_BASE = 'https://api.anthropic.com/v1';
/**
* Anthropic API version header value.
*/
const API_VERSION = '2023-06-01';
/**
* Default model used for all Hey Woo DIFM calls.
*
* Override via the `hey_woo_difm_model` filter.
*/
const MODEL = 'claude-sonnet-4-5';
/**
* HTTP request timeout in seconds.
*
* AI inference calls can take up to ~20 seconds on a cold start;
* 90 s gives comfortable headroom even under high load.
*/
const REQUEST_TIMEOUT = 90;
/**
* Return the Anthropic API key in use.
*
* Priority:
* 1. `HEY_WOO_ANTHROPIC_KEY` PHP constant (key never touches the DB)
* 2. `hey_woo_anthropic_api_key` wp_options value
*
* @return string Empty string when no key is configured.
*/
public static function get_api_key() {
if ( defined( 'HEY_WOO_ANTHROPIC_KEY' ) ) {
return (string) HEY_WOO_ANTHROPIC_KEY;
}
return (string) get_option( 'hey_woo_anthropic_api_key', '' );
}
/**
* Whether an Anthropic API key is currently configured.
*
* @return bool
*/
public static function has_api_key() {
return '' !== self::get_api_key();
}
/**
* Call the Anthropic Messages API.
*
* @param array $messages Conversation messages, each a `['role' => 'user'|'assistant', 'content' => string]` pair.
* @param string $system System prompt (optional).
* @param array $tools Anthropic tool definitions (optional).
* @param int $max_tokens Maximum tokens to generate.
* @return array|\WP_Error Decoded response array, or WP_Error on failure.
*/
public function messages( array $messages, $system = '', array $tools = array(), $max_tokens = 4096 ) {
$api_key = self::get_api_key();
if ( '' === $api_key ) {
return new \WP_Error( 'no_api_key', __( 'No Anthropic API key is configured.', 'hey-woo' ) );
}
/**
* Filter the model used for Hey Woo DIFM inference calls.
*
* @since 0.2.0
*
* @param string $model Anthropic model identifier.
*/
$model = (string) apply_filters( 'hey_woo_difm_model', self::MODEL );
$body = array(
'model' => $model,
'max_tokens' => $max_tokens,
'messages' => $messages,
);
if ( '' !== $system ) {
$body['system'] = $system;
}
if ( ! empty( $tools ) ) {
$body['tools'] = $tools;
}
$response = wp_remote_post(
self::API_BASE . '/messages',
array(
'timeout' => self::REQUEST_TIMEOUT,
'headers' => array(
'x-api-key' => $api_key,
'anthropic-version' => self::API_VERSION,
'content-type' => 'application/json',
),
'body' => wp_json_encode( $body ),
)
);
if ( is_wp_error( $response ) ) {
return $response;
}
$status_code = (int) wp_remote_retrieve_response_code( $response );
$raw_body = wp_remote_retrieve_body( $response );
$decoded_body = json_decode( $raw_body, true );
if ( ! is_array( $decoded_body ) ) {
return new \WP_Error(
'invalid_response',
__( 'Anthropic returned an unexpected response format.', 'hey-woo' )
);
}
// Anthropic signals errors with {"type":"error"} even on 200 (rare) and
// always on 4xx/5xx.
if ( isset( $decoded_body['type'] ) && 'error' === $decoded_body['type'] ) {
$error_message = isset( $decoded_body['error']['message'] )
? (string) $decoded_body['error']['message']
: __( 'Unknown Anthropic error.', 'hey-woo' );
return new \WP_Error(
'anthropic_error',
$error_message,
array( 'status' => $status_code )
);
}
if ( $status_code < 200 || $status_code >= 300 ) {
return new \WP_Error(
'http_error',
sprintf(
/* translators: %d: HTTP status code */
__( 'Anthropic API returned HTTP %d.', 'hey-woo' ),
$status_code
),
array( 'status' => $status_code )
);
}
return $decoded_body;
}
/**
* Validate an API key with a minimal (max_tokens=1) API call.
*
* Does not persist the key. Returns true on success, WP_Error on failure.
*
* @param string $key Anthropic API key to validate.
* @return true|\WP_Error
*/
public static function validate_key( $key ) {
$key = (string) $key;
if ( '' === $key ) {
return new \WP_Error( 'empty_key', __( 'API key must not be empty.', 'hey-woo' ) );
}
$response = wp_remote_post(
self::API_BASE . '/messages',
array(
'timeout' => 15,
'headers' => array(
'x-api-key' => $key,
'anthropic-version' => self::API_VERSION,
'content-type' => 'application/json',
),
'body' => wp_json_encode(
array(
'model' => self::MODEL,
'max_tokens' => 1,
'messages' => array(
array(
'role' => 'user',
'content' => 'hi',
),
),
)
),
)
);
if ( is_wp_error( $response ) ) {
return $response;
}
$status_code = (int) wp_remote_retrieve_response_code( $response );
$raw_body = wp_remote_retrieve_body( $response );
$decoded_body = json_decode( $raw_body, true );
if ( 401 === $status_code ) {
return new \WP_Error(
'invalid_key',
__( 'Invalid API key — Anthropic returned 401.', 'hey-woo' )
);
}
if ( is_array( $decoded_body ) && isset( $decoded_body['type'] ) && 'error' === $decoded_body['type'] ) {
$error_message = isset( $decoded_body['error']['message'] )
? (string) $decoded_body['error']['message']
: __( 'Unknown Anthropic error.', 'hey-woo' );
return new \WP_Error( 'anthropic_error', $error_message );
}
// Any 2xx or the expected partial response (stop_reason=max_tokens) is
// treated as a valid key.
if ( $status_code >= 200 && $status_code < 300 ) {
return true;
}
return new \WP_Error(
'http_error',
sprintf(
/* translators: %d: HTTP status code */
__( 'Anthropic API returned HTTP %d.', 'hey-woo' ),
$status_code
)
);
}
}