Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions javav2/example_code/bedrock-agents-runtime/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Amazon Bedrock Agents Runtime code examples for the SDK for Java 2.x

## Overview

Shows how to use the AWS SDK for Java 2.x to work with Amazon Bedrock Agents, Amazon Bedrock Knowledge Bases and Amazon Bedrock Prompt flows.

<!--custom.overview.start-->
<!--custom.overview.end-->

_Amazon Bedrock Agents Runtime offers you the ability to interact with your Amazon Bedrock Agents, Amazon Bedrock Knowledge Bases, and Amazon Bedrock Prompt Flows._

## ⚠ Important

* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/).
* Running the tests might result in charges to your AWS account.
* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege).
* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).

<!--custom.important.start-->
<!--custom.important.end-->

## Code examples

* [InvokeFlow](src/main/java/com/example/bedrockagents/runtime/InvokeFlow.java#L30)

### Prerequisites

For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav2` folder.


<!--custom.prerequisites.start-->
<!--custom.prerequisites.end-->

<!--custom.examples.start-->
<!--custom.examples.end-->

## Run the examples

### Instructions


<!--custom.instructions.start-->
<!--custom.instructions.end-->



### Tests

⚠ Running tests might result in charges to your AWS account.


To find instructions for running these tests, see the [README](../../README.md#Tests)
in the `javav2` folder.



<!--custom.tests.start-->
<!--custom.tests.end-->

## Additional resources

- [Amazon Bedrock Agents User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html)
- [Amazon Bedrock Knowledge Bases User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html)
- [Amazon Bedrock Propt Flow User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/flows.html)
- [Amazon Bedrock Agents Runtime API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock_Runtime.html)
- [SDK for Java 2.x Amazon Bedrock Agents Runtime reference](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/bedrockagentruntime/package-summary.html)

<!--custom.resources.start-->
<!--custom.resources.end-->

---

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
73 changes: 73 additions & 0 deletions javav2/example_code/bedrock-agents-runtime/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example.bedrockagents.runtime</groupId>
<artifactId>bedrockagentsruntime</artifactId>
<version>1.0-SNAPSHOT</version>

<name>bedrockagentsruntime</name>


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>17</java.version>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>2.28.10</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrockruntime</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrockagentruntime</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sts</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.bedrockagents.runtime;

// snippet-start:[bedrock-agent.java2.InvokeFlow]
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockagentruntime.BedrockAgentRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockagentruntime.model.InvokeFlowRequest;
import software.amazon.awssdk.services.bedrockagentruntime.model.InvokeFlowResponse;
import software.amazon.awssdk.services.bedrockagentruntime.model.InvokeFlowResponseHandler;
import software.amazon.awssdk.services.bedrockagentruntime.model.FlowInput;
import software.amazon.awssdk.services.bedrockagentruntime.model.FlowInputContent;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.async.SdkPublisher;


/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/


public class InvokeFlow {

public static String invokeFlowString(String[] args) {
final String usage = """

Usage:
<flowId> <flowAliasId> <inputText>

Where:
flowId - An instance id value that you can obtain from the AWS Management Console.\s
flowAliasId - An instance id value that you can obtain from the AWS Management Console.\s
inputText - A monitoring status (true|false)""";


if (args.length != 3) {
System.out.println(usage);
System.exit(1);
}

String flowId = args[0];
String flowAliasId = args[1];
String inputText = args[2];

//Create Agent Runtime Async Client
BedrockAgentRuntimeAsyncClient AgentClient = BedrockAgentRuntimeAsyncClient.builder()
.credentialsProvider(DefaultCredentialsProvider.create())
.region(Region.US_EAST_1)
.build();


//Create input prompt
Document doc = Document.fromString(inputText);
FlowInputContent flowInputContent = FlowInputContent.builder().document(doc).build();
FlowInput flowInput = FlowInput.builder().nodeName("FlowInputNode").nodeOutputName("document").content(flowInputContent).build();

//Create Invoke Flow Request
InvokeFlowRequest invokeFlowRequest = InvokeFlowRequest.builder().flowAliasIdentifier(flowAliasId).flowIdentifier(flowId).inputs(flowInput).build();

//Build a string buffer to contain all events
var completeResponseTextBuffer = new StringBuilder();

//Invoke the Invoke Flow endpoint
CompletableFuture<Void> future = AgentClient.invokeFlow(invokeFlowRequest,
new InvokeFlowResponseHandler() {
@Override
public void responseReceived(InvokeFlowResponse response) {
System.out.println("Flow response received: " + response +"\n");
completeResponseTextBuffer.append(response.toString());
}

@Override
@SuppressWarnings("unchecked")
public void onEventStream(SdkPublisher publisher) {
publisher.subscribe(event -> {
if (event instanceof SdkBytes) {
SdkBytes bytes = (SdkBytes) event;
System.out.println("Message: " + bytes.asUtf8String()+"\n");
completeResponseTextBuffer.append(bytes.asUtf8String());
}
else {
System.out.println("Received event: " + event + "\n");
completeResponseTextBuffer.append(event.toString());
}
});
}

@Override
public void exceptionOccurred(Throwable throwable) {
System.err.println("Error occurred: " + throwable.getMessage());
}

@Override
public void complete() {
System.out.println("Flow invocation completed");
}
});

future.join();
// Return the complete response text.
return completeResponseTextBuffer.toString();

}
}
// snippet-end:[bedrock-agent.java2.InvokeFlow]
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.bedrockagents.runtime;

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Tag;

import com.example.bedrockagents.runtime.InvokeFlow;

public class InvokeFlowTest {

// Fill in with the Prompt Flow Id and Alias.
String flowId = "";
String flowAliasId = "";
String inputText = "Is putting pineapple on pizza a good idea?";
String[] args = {flowId, flowAliasId, inputText};

@Test
@Order(1)
@Tag("IntegrationTest")
void assertInvokeFlowAnswer() {
String response = InvokeFlow.invokeFlowString(args);
assertNotNull(response);
assertFalse(response.isEmpty());
System.out.println("Test 1 passed.");
}
}
Loading