您通过从服务器端调用模型的 API 来将 AI 构建到应用程序中,并将其输出视为不可信的输入。对于 Claude,这意味着从您的后端(WordPress 插件使用 PHP)调用 Messages API,并将 API 密钥保留在服务器上 — 决不在客户端 JavaScript 中使用,因为任何人都可能在那里盗取它。
服务器端调用
关键规则:。浏览器与端点通信;端点与 Claude 通信。
您通过从服务器端调用模型的 API 来将 AI 构建到应用程序中,并将其输出视为不可信的输入。对于 Claude,这意味着从您的后端(WordPress 插件使用 PHP)调用 Messages API,并将 API 密钥保留在服务器上 — 决不在客户端 JavaScript 中使用,因为任何人都可能在那里盗取它。
关键规则:。浏览器与端点通信;端点与 Claude 通信。
<?php
// In a WordPress plugin: run this in PHP (server-side), never expose the key to JS.
$resp = wp_remote_post( 'https://api.anthropic.com/v1/messages', [
'headers' => [
'x-api-key' => getenv( 'ANTHROPIC_API_KEY' ), // from env/secret store, not code
'anthropic-version' => '2023-06-01',
'content-type' => 'application/json',
],
'timeout' => 30,
'body' => wp_json_encode( [
'model' => 'claude-sonnet-4-5', // pick a current model id
'max_tokens' => 1024, // cap output → controls cost
'messages' => [
[ 'role' => 'user', 'content' => $user_prompt ],
],
] ),
] );
if ( is_wp_error( $resp ) ) { /* handle network/timeout errors, maybe retry */ }
$data = json_decode( wp_remote_retrieve_body( $resp ), true );
$text = $data['content'][0]['text'] ?? ''; // validate before trusting/displaying it
- TOOL USE / FUNCTION CALLING → let the model call your functions (search, DB lookup)
- STREAMING → stream tokens for a responsive UI on long answers
- PROMPT CACHING → cache a large static system prompt → cheaper, faster
- STRUCTURED OUTPUT → ask for JSON, then parse + schema-validate it
- ERRORS & RATE LIMITS → handle 429/5xx with backoff + retry; show a fallback
- COST → cap max_tokens, log token usage, set per-user limits
在使用模型输出之前,总是验证模型输出:永远不要将其作为代码运行、不要在没有转义的情况下呈现它,或者不要在没有检查的情况下将其写入您的数据库。该模型是一个强大但容易出错的文本生成器,而不是可信的来源。
在真实产品中交付 AI 的大部分工作主要是围绕调用的乏味但关键的工程,而不是调用本身。将密钥保留在服务器端可以防止被盗和账单飙升;处理错误、速率限制和成本可以让功能保持可靠和经济;在采取行动之前验证输出可以防止模型的错误或注入的指令成为安全漏洞。正确地做好这些,Messages API 就成为一个可靠的构建块;跳过它们,一个令人印象深刻的演示就会变成泄露的密钥、一张令人惊讶的账单,或一个被利用的漏洞。