Amazon Bedrock Runtime examples using SDK for PHP - Amazon SDK for PHP
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Amazon Bedrock Runtime examples using SDK for PHP

The following code examples show you how to perform actions and implement common scenarios by using the Amazon SDK for PHP with Amazon Bedrock Runtime.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

AI21 Labs Jurassic-2

The following code example shows how to send a text message to AI21 Labs Jurassic-2, using the Invoke Model API.

SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Use the Invoke Model API to send a text message.

public function invokeJurassic2($prompt) { # The different model providers have individual request and response formats. # For the format, ranges, and default values for AI21 Labs Jurassic-2, refer to: # https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-jurassic2.html $completion = ""; try { $modelId = 'ai21.j2-mid-v1'; $body = [ 'prompt' => $prompt, 'temperature' => 0.5, 'maxTokens' => 200, ]; $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => json_encode($body), 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $completion = $response_body->completions[0]->data->text; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $completion; }
  • For API details, see InvokeModel in Amazon SDK for PHP API Reference.

Amazon Titan Image Generator

The following code example shows how to invoke Amazon Titan Image on Amazon Bedrock to generate an image.

SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Create an image with the Amazon Titan Image Generator.

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; }
  • For API details, see InvokeModel in Amazon SDK for PHP API Reference.

Anthropic Claude

The following code example shows how to send a text message to Anthropic Claude, using the Invoke Model API.

SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Invoke the Anthropic Claude 2 foundation model to generate text.

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-v2'; # Claude requires you to enclose the prompt as follows: $prompt = "\n\nHuman: {$prompt}\n\nAssistant:"; $body = [ 'prompt' => $prompt, 'max_tokens_to_sample' => 200, 'temperature' => 0.5, 'stop_sequences' => ["\n\nHuman:"], ]; $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => json_encode($body), 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $completion = $response_body->completion; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $completion; }
  • For API details, see InvokeModel in Amazon SDK for PHP API Reference.

Meta Llama

The following code example shows how to send a text message to Meta Llama 2, using the Invoke Model API.

SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Use the Invoke Model API to send a text message.

public function invokeLlama2($prompt) { # The different model providers have individual request and response formats. # For the format, ranges, and default values for Meta Llama 2 Chat, refer to: # https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html $completion = ""; try { $modelId = 'meta.llama2-13b-chat-v1'; $body = [ 'prompt' => $prompt, 'temperature' => 0.5, 'max_gen_len' => 512, ]; $result = $this->bedrockRuntimeClient->invokeModel([ 'contentType' => 'application/json', 'body' => json_encode($body), 'modelId' => $modelId, ]); $response_body = json_decode($result['body']); $completion = $response_body->generation; } catch (Exception $e) { echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n"; } return $completion; }
  • For API details, see InvokeModel in Amazon SDK for PHP API Reference.

Scenarios

The following code example shows how to prepare and send a prompt to a variety of large-language models (LLMs) on Amazon Bedrock

SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Invoke multiple LLMs on Amazon Bedrock.

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"; $clientArgs = [ 'region' => 'us-east-1', 'version' => 'latest', 'profile' => 'default', ]; $bedrockRuntimeService = new BedrockRuntimeService($clientArgs); $prompt = 'In one paragraph, who are you?'; echo "\nPrompt: " . $prompt; echo "\n\nAnthropic Claude:"; echo $bedrockRuntimeService->invokeClaude($prompt); echo "\n\nAI21 Labs Jurassic-2: "; echo $bedrockRuntimeService->invokeJurassic2($prompt); echo "\n\nMeta Llama 2 Chat: "; echo $bedrockRuntimeService->invokeLlama2($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 images have 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 images have 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; } }

Stable Diffusion

The following code example shows how to invoke Stability.ai Stable Diffusion XL on Amazon Bedrock to generate an image.

SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

Create an image with 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'; $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; }
  • For API details, see InvokeModel in Amazon SDK for PHP API Reference.