使用適用於 PHP 的 SDK 的 Amazon Bedrock 執行時期範例 - AWS SDK 程式碼範例

AWS文件開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。

使用適用於 PHP 的 SDK 的 Amazon Bedrock 執行時期範例

下列程式碼範例示範如何搭配使用 適用於 PHP 的 AWS SDK 和 Amazon Bedrock 執行時期執行動作,以及實作常見案例。

案例是向您展示如何呼叫服務中的多個函數或與其他 AWS 服務組合來完成特定任務的程式碼範例。

每個範例均包含完整原始碼的連結,您可在連結中找到如何設定和執行內容中程式碼的相關指示。

案例

下列程式碼範例示範如何在 Amazon Bedrock 上準備並傳送提示至各種大型語言模型 (LLM)

SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在 Amazon Bedrock 上調用多個 LLM。

namespace BedrockRuntime; class GettingStartedWithBedrockRuntime { protected BedrockRuntimeService $bedrockRuntimeService; public function runExample() { echo "\n"; echo "---------------------------------------------------------------------\n"; echo "Welcome to the Amazon Bedrock Runtime getting started demo using PHP!\n"; echo "---------------------------------------------------------------------\n"; $bedrockRuntimeService = new BedrockRuntimeService(); $prompt = 'In one paragraph, who are you?'; echo "\nPrompt: " . $prompt; echo "\n\nAnthropic Claude:\n"; echo $bedrockRuntimeService->invokeClaude($prompt); echo "\n---------------------------------------------------------------------\n"; $image_prompt = 'stylized picture of a cute old steampunk robot'; echo "\nImage prompt: " . $image_prompt; echo "\n\nStability.ai Stable Diffusion XL:\n"; $diffusionSeed = rand(0, 4294967295); $style_preset = 'photographic'; $base64 = $bedrockRuntimeService->invokeStableDiffusion($image_prompt, $diffusionSeed, $style_preset); $image_path = $this->saveImage($base64, 'stability.stable-diffusion-xl'); echo "The generated image has been saved to $image_path"; echo "\n\nAmazon Titan Image Generation:\n"; $titanSeed = rand(0, 2147483647); $base64 = $bedrockRuntimeService->invokeTitanImage($image_prompt, $titanSeed); $image_path = $this->saveImage($base64, 'amazon.titan-image-generator-v1'); echo "The generated image has been saved to $image_path"; } private function saveImage($base64_image_data, $model_id): string { $output_dir = "output"; if (!file_exists($output_dir)) { mkdir($output_dir); } $i = 1; while (file_exists("$output_dir/$model_id" . '_' . "$i.png")) { $i++; } $image_data = base64_decode($base64_image_data); $file_path = "$output_dir/$model_id" . '_' . "$i.png"; $file = fopen($file_path, 'wb'); fwrite($file, $image_data); fclose($file); return $file_path; } }

Amazon Nova

下列程式碼範例示範如何使用 Bedrock 的 Converse API,將文字訊息傳送至 Amazon Nova。

SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

使用 Bedrock 的 Converse API,將文字訊息傳送至 Amazon Nova。

// Use the Conversation API to send a text message to Amazon Nova. use Aws\BedrockRuntime\BedrockRuntimeClient; use Aws\Exception\AwsException; use RuntimeException; class Converse { public function converse(): string { // Create a Bedrock Runtime client in the AWS Region you want to use. $client = new BedrockRuntimeClient([ 'region' => 'us-east-1', 'profile' => 'default' ]); // Set the model ID, e.g., Amazon Nova Lite. $modelId = 'amazon.nova-lite-v1:0'; // Start a conversation with the user message. $userMessage = "Describe the purpose of a 'hello world' program in one line."; $conversation = [ [ "role" => "user", "content" => [["text" => $userMessage]] ] ]; try { // Send the message to the model, using a basic inference configuration. $response = $client->converse([ 'modelId' => $modelId, 'messages' => $conversation, 'inferenceConfig' => [ 'maxTokens' => 512, 'temperature' => 0.5 ] ]); // Extract and return the response text. $responseText = $response['output']['message']['content'][0]['text']; return $responseText; } catch (AwsException $e) { echo "ERROR: Can't invoke {$modelId}. Reason: {$e->getAwsErrorMessage()}"; throw new RuntimeException("Failed to invoke model: " . $e->getAwsErrorMessage(), 0, $e); } } } $demo = new Converse(); echo $demo->converse();
  • 如需 API 詳細資訊,請參閱《適用於 PHP 的 AWS SDK API 參考》中的 Converse

Amazon Titan Image Generator

下列程式碼範例示範如何在 Amazon Bedrock 上調用 Amazon Titan Image 來產生映像。

SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

使用 Amazon Titan 圖像生成器建立影像。

public function invokeTitanImage(string $prompt, int $seed) { // The different model providers have individual request and response formats. // For the format, ranges, and default values for Titan Image models refer to: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html $base64_image_data = ""; try { $modelId = 'amazon.titan-image-generator-v1'; $request = json_encode([ 'taskType' => 'TEXT_IMAGE', 'textToImageParams' => [ 'text' => $prompt ], 'imageGenerationConfig' => [ 'numberOfImages' => 1, 'quality' => 'standard', 'cfgScale' => 8.0, 'height' => 512, 'width' => 512, 'seed' => $seed ] ]); $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => $request, 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $base64_image_data = $response_body->images[0]; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $base64_image_data; }
  • 如需 API 詳細資訊,請參閱《適用於 PHP 的 AWS SDK API 參考》中的 InvokeModel

Anthropic Claude

下列程式碼範例示範如何使用調用模型 API,將文字訊息傳送至 Anthropic Claude。

SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

調用 Anthropic Claude 2 基礎模型以產生文字。

public function invokeClaude($prompt) { // The different model providers have individual request and response formats. // For the format, ranges, and default values for Anthropic Claude, refer to: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html $completion = ""; try { $modelId = 'anthropic.claude-3-haiku-20240307-v1:0'; // Claude requires you to enclose the prompt as follows: $body = [ 'anthropic_version' => 'bedrock-2023-05-31', 'max_tokens' => 512, 'temperature' => 0.5, 'messages' => [[ 'role' => 'user', 'content' => $prompt ]] ]; $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => json_encode($body), 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $completion = $response_body->content[0]->text; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $completion; }
  • 如需 API 詳細資訊,請參閱《適用於 PHP 的 AWS SDK API 參考》中的 InvokeModel

Stable Diffusion

下列程式碼範例示範如何在 Amazon Bedrock 上調用 Stability.ai Stable Diffusion XL 以產生映像。

SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

使用 Stable Diffusion 建立映像。

public function invokeStableDiffusion(string $prompt, int $seed, string $style_preset) { // The different model providers have individual request and response formats. // For the format, ranges, and available style_presets of Stable Diffusion models refer to: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-stability-diffusion.html $base64_image_data = ""; try { $modelId = 'stability.stable-diffusion-xl-v1'; $body = [ 'text_prompts' => [ ['text' => $prompt] ], 'seed' => $seed, 'cfg_scale' => 10, 'steps' => 30 ]; if ($style_preset) { $body['style_preset'] = $style_preset; } $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => json_encode($body), 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $base64_image_data = $response_body->artifacts[0]->base64; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $base64_image_data; }
  • 如需 API 詳細資訊,請參閱《適用於 PHP 的 AWS SDK API 參考》中的 InvokeModel