PHP code example of revolution / laravel-amazon-bedrock
1. Go to this page and download the library: Download revolution/laravel-amazon-bedrock library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
revolution / laravel-amazon-bedrock example snippets
namespace App\Ai\Agents;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
class BedrockAgent implements Agent
{
use Promptable;
public function instructions(): string
{
return 'You are an expert at software development.';
}
}
use App\Ai\Agents\BedrockAgent;
$response = (new BedrockAgent)->prompt('Tell me about Laravel');
echo $response->text;
use function Laravel\Ai\agent;
$response = agent(
instructions: 'You are an expert at software development.',
)->prompt('Tell me about Laravel');
echo $response->text;
use App\Ai\Agents\BedrockAgent;
Route::get('/stream', function () {
return (new BedrockAgent)->stream('Tell me about Laravel');
});
use Laravel\Ai\Streaming\Events\TextDelta;
use function Laravel\Ai\agent;
$stream = agent(
instructions: 'You are an expert at software development.',
)->stream('Tell me about Laravel');
foreach ($stream as $event) {
if ($event instanceof TextDelta) {
echo $event->delta;
}
}
use Laravel\Ai\Contracts\Tool;
use Laravel\Ai\Tools\Request;
use Illuminate\Contracts\JsonSchema\JsonSchema;
class GetWeather implements Tool
{
public function description(): string
{
return 'Get current weather for a city.';
}
public function schema(JsonSchema $schema): array
{
return [
'city' => $schema->string()->
use App\Ai\Agents\BedrockAgent;
use App\Ai\Tools\GetWeather;
use Laravel\Ai\Attributes\MaxSteps;
#[MaxSteps(5)]
class BedrockAgent implements Agent
{
use Promptable;
public function tools(): array
{
return [new GetWeather];
}
public function instructions(): string
{
return 'You are a helpful weather assistant.';
}
}
$response = (new BedrockAgent)->prompt('What is the weather in Tokyo?');
echo $response->text;
use function Laravel\Ai\agent;
$response = agent(
instructions: 'You are a helpful weather assistant.',
tools: [new GetWeather],
maxSteps: 5,
)->prompt('What is the weather in Tokyo?');
use Laravel\Ai\Files\Document;
use Laravel\Ai\Files\Image;
use function Laravel\Ai\agent;
// Attach an image from a local path
$response = agent(
instructions: 'You are a helpful assistant.',
)->prompt('Describe this image.', attachments: [
Image::fromPath('/path/to/photo.jpg'),
]);
// Attach a document from a URL
$response = agent(
instructions: 'You are a helpful assistant.',
)->prompt('Summarize this document.', attachments: [
Document::fromUrl('https://example.com/report.pdf'),
]);
// Attach a document from a string (with explicit format)
$response = agent(
instructions: 'You are a helpful assistant.',
)->prompt('Analyze this text.', attachments: [
Document::fromString($csvContent, 'text/csv')->as('data.csv'),
]);
namespace App\Ai\Agents;
use App\Models\ChatHistory;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Messages\Message;
use Laravel\Ai\Promptable;
class ChatAgent implements Agent, Conversational
{
use Promptable;
public function __construct(public int $userId) {}
public function instructions(): string
{
return 'You are a helpful assistant.';
}
public function messages(): iterable
{
return ChatHistory::where('user_id', $this->userId)
->latest()
->limit(20)
->get()
->reverse()
->map(fn ($m) => new Message($m->role, $m->content))
->all();
}
}
$response = (new ChatAgent(auth()->id()))->prompt('What did we discuss earlier?');
namespace App\Ai\Agents;
use Laravel\Ai\Concerns\RemembersConversations;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\Conversational;
use Laravel\Ai\Promptable;
class ChatAgent implements Agent, Conversational
{
use Promptable, RemembersConversations;
public function instructions(): string
{
return 'You are a helpful assistant.';
}
}
$response = (new ChatAgent)->forUser($user)->prompt('Hello!');
$conversationId = $response->conversationId;
$response = (new ChatAgent)
->continue($conversationId, as: $user)
->prompt('Tell me more about that.');
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;
class ExtractPerson implements Agent, HasStructuredOutput
{
use Promptable;
public function instructions(): string
{
return 'Extract person information from the given text.';
}
public function schema(JsonSchema $schema): array
{
return [
'name' => $schema->string()->description('The person\'s full name'),
'age' => $schema->integer()->description('The person\'s age'),
'occupation' => $schema->string()->description('The person\'s occupation'),
];
}
}
$response = (new ExtractPerson)->prompt('John is a 30-year-old software engineer.');
// Access structured data via array access
echo $response['name']; // "John"
echo $response['age']; // 30
echo $response['occupation']; // "software engineer"
use function Laravel\Ai\agent;
$response = agent(
instructions: 'Extract person information from the given text.',
schema: fn (JsonSchema $schema) => [
'name' => $schema->string()->description('The person\'s full name'),
'age' => $schema->integer()->description('The person\'s age'),
],
)->prompt('Alice is 25 years old.');
echo $response['name']; // "Alice"
echo $response['age']; // 25
use function Laravel\Ai\agent;
// Anthropic Claude (uses Converse API)
$response = agent(
instructions: 'You are an expert at software development.',
model: 'global.anthropic.claude-sonnet-4-6',
)->prompt('Tell me about Laravel.');
// Amazon Nova
$response = agent(
instructions: 'You are a helpful assistant.',
model: 'amazon.nova-pro-v1:0',
)->prompt('Tell me about AWS.');
// Meta Llama
$response = agent(
instructions: 'You are a helpful assistant.',
model: 'meta.llama3-1-70b-instruct-v1:0',
)->prompt('Explain quantum computing.');
// Mistral
$response = agent(
instructions: 'You are a helpful assistant.',
model: 'mistral.mistral-large-2402-v1:0',
)->prompt('Write a haiku about coding.');
// Cohere Command R+
$response = agent(
instructions: 'You are a helpful assistant.',
model: 'cohere.command-r-plus-v1:0',
)->prompt('Summarize this text.');
// DeepSeek R1
$response = agent(
instructions: 'You are a helpful assistant.',
model: 'deepseek.r1-v1:0',
)->prompt('Solve this math problem.');
namespace App\Ai\Agents;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasProviderOptions;
use Laravel\Ai\Enums\Lab;
use Laravel\Ai\Promptable;
class BedrockAgent implements Agent, HasProviderOptions
{
use Promptable;
public function instructions(): string
{
return 'You are an expert at software development.';
}
public function providerOptions(Lab|string $provider): array
{
return [
'top_p' => 0.9,
];
}
}
use Laravel\Ai\Attributes\MaxTokens;
use Laravel\Ai\Attributes\Temperature;
use Laravel\Ai\Attributes\Timeout;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Promptable;
#[MaxTokens(4096)]
#[Temperature(0.7)]
#[Timeout(120)]
class BedrockAgent implements Agent
{
use Promptable;
// ...
}
use Laravel\Ai\Image;
use Revolution\Amazon\Bedrock\Bedrock;
// Uses Stability AI Stable Image Core by default
$response = Image::of('A cute steampunk robot')->generate(provider: Bedrock::KEY);
// Get the first image
$image = $response->firstImage();
// Store image to disk
$response->store('images', 's3');
// Render as HTML <img> tag
echo $response->toHtml('Steampunk robot');
use Laravel\Ai\Files\Image as ImageFile;
use Revolution\Amazon\Bedrock\Bedrock;
$inputImage = ImageFile::fromPath('/path/to/photo.jpg');
// Inpaint — fill in or replace areas using a mask or alpha channel
$response = Image::of('Replace the background with a forest')
->attachments([$inputImage])
->generate(provider: Bedrock::KEY, model: 'stability.stable-image-inpaint-v1:0');
// Erase — remove unwanted elements from an image
$response = Image::of('')
->attachments([$inputImage])
->generate(provider: Bedrock::KEY, model: 'stability.stable-image-erase-object-v1:0');
// Remove background — isolate the subject
$response = Image::of('')
->attachments([$inputImage])
->generate(provider: Bedrock::KEY, model: 'stability.stable-image-remove-background-v1:0');
// Search and replace — replace an object described in the prompt
$response = Image::of('a cat')
->attachments([$inputImage])
->generate(provider: Bedrock::KEY, model: 'stability.stable-image-search-replace-v1:0');
// Style transfer — apply a style from the prompt
$response = Image::of('Oil painting style')
->attachments([$inputImage])
->generate(provider: Bedrock::KEY, model: 'stability.stable-style-transfer-v1:0');
// Nova Canvas (deprecated — available in us-east-1, ap-northeast-1, eu-west-1)
$response = Image::of('A sunset')
->size('3:2') // '1:1', '3:2', or '2:3'
->quality('high') // 'low', 'medium', or 'high' (Nova Canvas only)
->generate(provider: Bedrock::KEY, model: 'amazon.nova-canvas-v1:0');
use Laravel\Ai\Audio;
use Revolution\Amazon\Bedrock\Bedrock;
$response = Audio::of('I love coding with Laravel.')->generate(provider: Bedrock::KEY);
$rawContent = (string) $response;
$response = Audio::of('I love coding with Laravel.')
->female()
->generate(provider: 'bedrock');
$response = Audio::of('I love coding with Laravel.')
->male()
->generate(provider: Bedrock::KEY);
$response = Audio::of('I love coding with Laravel.')
->voice('Joanna')
->generate(provider: Bedrock::KEY);
$response = Audio::of('I love coding with Laravel.')->generate(provider: Bedrock::KEY);
$path = $response->store();
$path = $response->storeAs('audio.mp3');
// Available engines: generative (default), neural, long-form, standard
$response = Audio::of('I love coding with Laravel.')
->generate(provider: Bedrock::KEY, model: 'neural');
use Laravel\Ai\Embeddings;
use Revolution\Amazon\Bedrock\Bedrock;
$response = Embeddings::for(['Hello world', 'Foo bar'])->generate(provider: Bedrock::KEY);
// Access first embedding vector
$vector = $response->first();
// Iterate all embeddings
foreach ($response as $embedding) {
// $embedding is an array of float values
}
echo $response->tokens; // total token count
use Laravel\Ai\Reranking;
use Revolution\Amazon\Bedrock\Bedrock;
$response = Reranking::of([
'Laravel is a PHP web framework.',
'Python is a programming language.',
'Laravel provides elegant syntax for web development.',
])->rerank(query: 'What is Laravel?', provider: Bedrock::KEY);
// Get the top-ranked document
echo $response->first()->document; // "Laravel is a PHP web framework."
echo $response->first()->score; // 0.95
// Get all documents in reranked order
foreach ($response as $result) {
echo "{$result->index}: {$result->document} ({$result->score})\n";
}
// Limit the number of results
$response = Reranking::of([...])
->limit(2)
->rerank(query: 'What is Laravel?', provider: Bedrock::KEY);
use Laravel\Ai\AnonymousAgent;
use Laravel\Ai\Prompts\AgentPrompt;
use function Laravel\Ai\agent;
it('can generate text', function () {
AnonymousAgent::fake();
$response = agent(
instructions: 'You are an expert at software development.',
)->prompt('Tell me about Laravel');
AnonymousAgent::assertPrompted(function (AgentPrompt $prompt) {
return $prompt->contains('Laravel');
});
});
shell
php artisan make:agent BedrockAgent
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.