Skip to content

Commit e8b4dfb

Browse files
emanuele-leviEmanuele Levi
andauthored
Java v2: Created InvokeFlow example for Amazon Bedrock Agents Runtime (#7038)
--------- Co-authored-by: Emanuele Levi <[email protected]>
1 parent 15f3c24 commit e8b4dfb

File tree

4 files changed

+290
-0
lines changed

4 files changed

+290
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Amazon Bedrock Agents Runtime code examples for the SDK for Java 2.x
2+
3+
## Overview
4+
5+
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.
6+
7+
<!--custom.overview.start-->
8+
<!--custom.overview.end-->
9+
10+
_Amazon Bedrock Agents Runtime offers you the ability to interact with your Amazon Bedrock Agents, Amazon Bedrock Knowledge Bases, and Amazon Bedrock Prompt Flows._
11+
12+
## ⚠ Important
13+
14+
* 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/).
15+
* Running the tests might result in charges to your AWS account.
16+
* 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).
17+
* 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).
18+
19+
<!--custom.important.start-->
20+
<!--custom.important.end-->
21+
22+
## Code examples
23+
24+
* [InvokeFlow](src/main/java/com/example/bedrockagents/runtime/InvokeFlow.java#L30)
25+
26+
### Prerequisites
27+
28+
For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav2` folder.
29+
30+
31+
<!--custom.prerequisites.start-->
32+
<!--custom.prerequisites.end-->
33+
34+
<!--custom.examples.start-->
35+
<!--custom.examples.end-->
36+
37+
## Run the examples
38+
39+
### Instructions
40+
41+
42+
<!--custom.instructions.start-->
43+
<!--custom.instructions.end-->
44+
45+
46+
47+
### Tests
48+
49+
⚠ Running tests might result in charges to your AWS account.
50+
51+
52+
To find instructions for running these tests, see the [README](../../README.md#Tests)
53+
in the `javav2` folder.
54+
55+
56+
57+
<!--custom.tests.start-->
58+
<!--custom.tests.end-->
59+
60+
## Additional resources
61+
62+
- [Amazon Bedrock Agents User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html)
63+
- [Amazon Bedrock Knowledge Bases User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html)
64+
- [Amazon Bedrock Propt Flow User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/flows.html)
65+
- [Amazon Bedrock Agents Runtime API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock_Runtime.html)
66+
- [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)
67+
68+
<!--custom.resources.start-->
69+
<!--custom.resources.end-->
70+
71+
---
72+
73+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
74+
75+
SPDX-License-Identifier: Apache-2.0
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
3+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.example.bedrockagents.runtime</groupId>
8+
<artifactId>bedrockagentsruntime</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<name>bedrockagentsruntime</name>
12+
13+
14+
<properties>
15+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16+
<java.version>17</java.version>
17+
<maven.compiler.target>${java.version}</maven.compiler.target>
18+
<maven.compiler.source>${java.version}</maven.compiler.source>
19+
</properties>
20+
21+
<build>
22+
<plugins>
23+
<plugin>
24+
<groupId>org.apache.maven.plugins</groupId>
25+
<artifactId>maven-compiler-plugin</artifactId>
26+
<version>3.8.1</version>
27+
<configuration>
28+
<source>${java.version}</source>
29+
<target>${java.version}</target>
30+
</configuration>
31+
</plugin>
32+
</plugins>
33+
</build>
34+
35+
<dependencyManagement>
36+
<dependencies>
37+
<dependency>
38+
<groupId>software.amazon.awssdk</groupId>
39+
<artifactId>bom</artifactId>
40+
<version>2.28.10</version>
41+
<type>pom</type>
42+
<scope>import</scope>
43+
</dependency>
44+
</dependencies>
45+
</dependencyManagement>
46+
47+
<dependencies>
48+
<dependency>
49+
<groupId>software.amazon.awssdk</groupId>
50+
<artifactId>bedrockruntime</artifactId>
51+
</dependency>
52+
<dependency>
53+
<groupId>software.amazon.awssdk</groupId>
54+
<artifactId>bedrockagentruntime</artifactId>
55+
</dependency>
56+
<dependency>
57+
<groupId>software.amazon.awssdk</groupId>
58+
<artifactId>sts</artifactId>
59+
</dependency>
60+
<dependency>
61+
<groupId>org.junit.jupiter</groupId>
62+
<artifactId>junit-jupiter-api</artifactId>
63+
<version>5.8.2</version>
64+
<scope>test</scope>
65+
</dependency>
66+
<dependency>
67+
<groupId>org.junit.vintage</groupId>
68+
<artifactId>junit-vintage-engine</artifactId>
69+
<version>5.8.2</version>
70+
<scope>test</scope>
71+
</dependency>
72+
</dependencies>
73+
</project>
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
package com.example.bedrockagents.runtime;
4+
5+
// snippet-start:[bedrock-agent.java2.InvokeFlow]
6+
import java.util.concurrent.CompletableFuture;
7+
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
8+
import software.amazon.awssdk.core.document.Document;
9+
import software.amazon.awssdk.regions.Region;
10+
import software.amazon.awssdk.services.bedrockagentruntime.BedrockAgentRuntimeAsyncClient;
11+
import software.amazon.awssdk.services.bedrockagentruntime.model.InvokeFlowRequest;
12+
import software.amazon.awssdk.services.bedrockagentruntime.model.InvokeFlowResponse;
13+
import software.amazon.awssdk.services.bedrockagentruntime.model.InvokeFlowResponseHandler;
14+
import software.amazon.awssdk.services.bedrockagentruntime.model.FlowInput;
15+
import software.amazon.awssdk.services.bedrockagentruntime.model.FlowInputContent;
16+
import software.amazon.awssdk.core.SdkBytes;
17+
import software.amazon.awssdk.core.async.SdkPublisher;
18+
19+
20+
/**
21+
* Before running this Java V2 code example, set up your development
22+
* environment, including your credentials.
23+
*
24+
* For more information, see the following documentation topic:
25+
*
26+
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
27+
*/
28+
29+
30+
public class InvokeFlow {
31+
32+
public static String invokeFlowString(String[] args) {
33+
final String usage = """
34+
35+
Usage:
36+
<flowId> <flowAliasId> <inputText>
37+
38+
Where:
39+
flowId - An instance id value that you can obtain from the AWS Management Console.\s
40+
flowAliasId - An instance id value that you can obtain from the AWS Management Console.\s
41+
inputText - A monitoring status (true|false)""";
42+
43+
44+
if (args.length != 3) {
45+
System.out.println(usage);
46+
System.exit(1);
47+
}
48+
49+
String flowId = args[0];
50+
String flowAliasId = args[1];
51+
String inputText = args[2];
52+
53+
//Create Agent Runtime Async Client
54+
BedrockAgentRuntimeAsyncClient AgentClient = BedrockAgentRuntimeAsyncClient.builder()
55+
.credentialsProvider(DefaultCredentialsProvider.create())
56+
.region(Region.US_EAST_1)
57+
.build();
58+
59+
60+
//Create input prompt
61+
Document doc = Document.fromString(inputText);
62+
FlowInputContent flowInputContent = FlowInputContent.builder().document(doc).build();
63+
FlowInput flowInput = FlowInput.builder().nodeName("FlowInputNode").nodeOutputName("document").content(flowInputContent).build();
64+
65+
//Create Invoke Flow Request
66+
InvokeFlowRequest invokeFlowRequest = InvokeFlowRequest.builder().flowAliasIdentifier(flowAliasId).flowIdentifier(flowId).inputs(flowInput).build();
67+
68+
//Build a string buffer to contain all events
69+
var completeResponseTextBuffer = new StringBuilder();
70+
71+
//Invoke the Invoke Flow endpoint
72+
CompletableFuture<Void> future = AgentClient.invokeFlow(invokeFlowRequest,
73+
new InvokeFlowResponseHandler() {
74+
@Override
75+
public void responseReceived(InvokeFlowResponse response) {
76+
System.out.println("Flow response received: " + response +"\n");
77+
completeResponseTextBuffer.append(response.toString());
78+
}
79+
80+
@Override
81+
@SuppressWarnings("unchecked")
82+
public void onEventStream(SdkPublisher publisher) {
83+
publisher.subscribe(event -> {
84+
if (event instanceof SdkBytes) {
85+
SdkBytes bytes = (SdkBytes) event;
86+
System.out.println("Message: " + bytes.asUtf8String()+"\n");
87+
completeResponseTextBuffer.append(bytes.asUtf8String());
88+
}
89+
else {
90+
System.out.println("Received event: " + event + "\n");
91+
completeResponseTextBuffer.append(event.toString());
92+
}
93+
});
94+
}
95+
96+
@Override
97+
public void exceptionOccurred(Throwable throwable) {
98+
System.err.println("Error occurred: " + throwable.getMessage());
99+
}
100+
101+
@Override
102+
public void complete() {
103+
System.out.println("Flow invocation completed");
104+
}
105+
});
106+
107+
future.join();
108+
// Return the complete response text.
109+
return completeResponseTextBuffer.toString();
110+
111+
}
112+
}
113+
// snippet-end:[bedrock-agent.java2.InvokeFlow]
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
package com.example.bedrockagents.runtime;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
import org.junit.jupiter.api.Test;
7+
import org.junit.jupiter.api.Order;
8+
import org.junit.jupiter.api.Tag;
9+
10+
import com.example.bedrockagents.runtime.InvokeFlow;
11+
12+
public class InvokeFlowTest {
13+
14+
// Fill in with the Prompt Flow Id and Alias.
15+
String flowId = "";
16+
String flowAliasId = "";
17+
String inputText = "Is putting pineapple on pizza a good idea?";
18+
String[] args = {flowId, flowAliasId, inputText};
19+
20+
@Test
21+
@Order(1)
22+
@Tag("IntegrationTest")
23+
void assertInvokeFlowAnswer() {
24+
String response = InvokeFlow.invokeFlowString(args);
25+
assertNotNull(response);
26+
assertFalse(response.isEmpty());
27+
System.out.println("Test 1 passed.");
28+
}
29+
}

0 commit comments

Comments
 (0)