-
Notifications
You must be signed in to change notification settings - Fork 5.8k
JavaScriptv3: Bedrock agent runtime tool use scenario example #7355
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
cecca43
Commit working base version of code
brmur 09a810b
Commit working base version of code
brmur 6962d7f
Commit working base version of code
brmur d4f27c0
Commit working base version of code
brmur 254a38d
Commit working base version of code
brmur 6dbbf72
Commit working base version of code
brmur 9f0224d
Commit working base version of code
brmur f32bdea
Commit working base version of code
brmur e152fcb
Commit working base version of code
brmur 6612836
Commit working base version of code
brmur 1a5ebfc
Commit working base version of code
brmur bc71287
Commit working base version of code
brmur 97c0a0b
Commit working base version of code
brmur a26fbb2
Merge remote-tracking branch 'origin/bedrock_agent_example' into bedr…
brmur 14a598c
Commit working base version of code
brmur 267b789
Commit working base version of code
brmur e3ae618
Commit working base version of code
brmur b6249ef
Commit working base version of code
brmur b62ffdb
Commit working base version of code
brmur 06b2c98
Commit working base version of code
brmur b0fee1e
Commit working base version of code
brmur e9948e2
Commit working base version of code
brmur 7c32bbf
Merge branch 'main' into bedrock_agent_example
scmacdon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,4 +5,4 @@ pathspec==0.11.2 | |
PyYAML==6.0.1 | ||
requests==2.32.0 | ||
types-PyYAML==6.0.12.12 | ||
yamale==4.0.4 | ||
yamale==4.0.4 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
jinja2>=3.0.3 | ||
pyyaml>=5.3.1 | ||
typer==0.15.1 | ||
aws-doc-sdk-examples-tools @ git+https://github.com/awsdocs/aws-doc-sdk-examples-tools | ||
aws-doc-sdk-examples-tools @ git+https://github.com/awsdocs/aws-doc-sdk-examples-tools | ||
brmur marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,4 +29,4 @@ typer==0.15.1 | |
types-PyYAML==6.0.12.12 | ||
typing_extensions==4.12.2 | ||
urllib3==2.3.0 | ||
yamale==4.0.4 | ||
yamale==4.0.4 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
193 changes: 193 additions & 0 deletions
193
javascriptv3/example_code/bedrock-runtime/models/amazonNovaText/converse-with-tool.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,193 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
// snippet-start:[Bedrock.ConverseTool.javascriptv3.SendConverseRequest] | ||
|
||
// This example demonstrates how to send a conversation of messages to Amazon Nova using Bedrock's Converse API with a tool configuration. | ||
// It shows how to: | ||
// - 1. Set up the Amazon Bedrock runtime client | ||
// - 2. Define the parameters required enable Amazon Bedrock to use a tool when formulating its response (model ID, user input, system prompt, and the tool spec) | ||
// - 3. Send the request to Amazon Bedrock, and returns the response. | ||
// - 4. Add the tool response to the conversation, and send it back to Amazon Bedrock. | ||
// - 5. Publish the response. | ||
|
||
import { | ||
BedrockRuntimeClient, | ||
ConverseCommand, | ||
} from "@aws-sdk/client-bedrock-runtime"; | ||
|
||
// Step 1: Create the Amazon Bedrock runtime client | ||
|
||
// Credentials will be automatically loaded from the environment | ||
const bedRockRuntimeClient = new BedrockRuntimeClient({ | ||
region: "us-east-1", | ||
}); | ||
|
||
// Step 2. Define the parameters required enable Amazon Bedrock to use a tool when formulating its response. | ||
|
||
// The Bedrock Model ID. | ||
const modelId = "amazon.nova-lite-v1:0"; | ||
|
||
// The system prompt to help Amazon Bedrock craft it's response. | ||
const system_prompt = [ | ||
{ | ||
text: | ||
"You are a music expert that provides the most popular song played on a radio station, using only the\n" + | ||
"the top_song tool, which he call sign for the radio station for which you want the most popular song. " + | ||
"Example calls signs are WZPZ and WKRP. \n" + | ||
"- Only use the top_song tool. Never guess or make up information. \n" + | ||
"- If the tool errors, apologize, explain weather is unavailable, and suggest other options.\n" + | ||
"- Only respond to queries about the most popular song played on a radio station\n" + | ||
"Remind off-topic users of your purpose. \n" + | ||
"- Never claim to search online, access external data, or use tools besides the top_song tool.\n", | ||
}, | ||
]; | ||
// The user's question. | ||
const message = [ | ||
{ | ||
role: "user", | ||
content: [{ text: "What is the most popular song on WZPZ?" }], | ||
}, | ||
]; | ||
// The tool specification. In this case, it uses an example schema for | ||
// a tool that gets the most popular song played on a radio station. | ||
const tool_config = { | ||
tools: [ | ||
{ | ||
toolSpec: { | ||
name: "top_song", | ||
description: "Get the most popular song played on a radio station.", | ||
inputSchema: { | ||
json: { | ||
type: "object", | ||
properties: { | ||
sign: { | ||
type: "string", | ||
description: | ||
"The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP.", | ||
}, | ||
}, | ||
required: ["sign"], | ||
}, | ||
}, | ||
}, | ||
}, | ||
], | ||
}; | ||
|
||
// Helper function to return the song and artist from top_song tool. | ||
async function get_top_song(call_sign) { | ||
try { | ||
if (call_sign === "WZPZ") { | ||
const song = "Elemental Hotel"; | ||
const artist = "8 Storey Hike"; | ||
return { song, artist }; | ||
} | ||
} catch (error) { | ||
console.log(`${error.message}`); | ||
} | ||
} | ||
|
||
// 3. Send the request to Amazon Bedrock, and returns the response. | ||
export async function SendConversationtoBedrock( | ||
modelId, | ||
message, | ||
system_prompt, | ||
tool_config, | ||
) { | ||
try { | ||
const response = await bedRockRuntimeClient.send( | ||
new ConverseCommand({ | ||
modelId: modelId, | ||
messages: message, | ||
system: system_prompt, | ||
toolConfig: tool_config, | ||
}), | ||
); | ||
if (response.stopReason === "tool_use") { | ||
const toolResultFinal = []; | ||
try { | ||
const output_message = response.output.message; | ||
message.push(output_message); | ||
const toolRequests = output_message.content; | ||
const toolMessage = toolRequests[0].text; | ||
console.log(toolMessage.replace(/<[^>]+>/g, "")); | ||
for (const toolRequest of toolRequests) { | ||
if (Object.hasOwn(toolRequest, "toolUse")) { | ||
const toolUse = toolRequest.toolUse; | ||
const sign = toolUse.input.sign; | ||
const toolUseID = toolUse.toolUseId; | ||
console.log( | ||
`Requesting tool ${toolUse.name}, Tool use id ${toolUseID}`, | ||
); | ||
if (toolUse.name === "top_song") { | ||
const toolResult = []; | ||
try { | ||
const top_song = await get_top_song(toolUse.input.sign).then( | ||
(top_song) => top_song, | ||
); | ||
const toolResult = { | ||
toolResult: { | ||
toolUseId: toolUseID, | ||
content: [ | ||
{ | ||
json: { song: top_song.song, artist: top_song.artist }, | ||
}, | ||
], | ||
}, | ||
}; | ||
toolResultFinal.push(toolResult); | ||
} catch (err) { | ||
const toolResult = { | ||
toolUseId: toolUseID, | ||
content: [{ json: { text: err.message } }], | ||
status: "error", | ||
}; | ||
} | ||
} | ||
} | ||
} | ||
const toolResultMessage = { | ||
role: "user", | ||
content: toolResultFinal, | ||
}; | ||
// Step 4. Add the tool response to the conversation, and send it back to Amazon Bedrock. | ||
|
||
message.push(toolResultMessage); | ||
await SendConversationtoBedrock( | ||
modelId, | ||
message, | ||
system_prompt, | ||
tool_config, | ||
); | ||
} catch (caught) { | ||
console.error(`${caught.message}`); | ||
throw caught; | ||
} | ||
} | ||
|
||
// 4. Publish the response. | ||
if (response.stopReason === "end_turn") { | ||
const finalMessage = response.output.message.content[0].text; | ||
const messageToPrint = finalMessage.replace(/<[^>]+>/g); | ||
console.log(messageToPrint.replace(/<[^>]+>/g)); | ||
return messageToPrint; | ||
} | ||
} catch (caught) { | ||
if (caught.name === "ModelNotReady") { | ||
console.log( | ||
`${caught.name} - Model not ready, please wait and try again.`, | ||
); | ||
throw caught; | ||
} | ||
if (caught.name === "BedrockRuntimeException") { | ||
console.log( | ||
`${caught.name} - Error occurred while sending Converse request`, | ||
); | ||
throw caught; | ||
} | ||
} | ||
} | ||
await SendConversationtoBedrock(modelId, message, system_prompt, tool_config); | ||
|
||
// snippet-end:[Bedrock.ConverseTool.javascriptv3.SendConverseRequest] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
...criptv3/example_code/bedrock-runtime/scenarios/converse_tool_scenario/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# Amazon Bedrock Runtime Converse API with Tool for the SDK for JavaScript (v3) | ||
|
||
## Overview | ||
|
||
This example shows how to use AWS SDKs and the Amazon Bedrock Converse API to call a custom tool from a large language model (LLM) as part of a multistep conversation. The example creates a weather tool that leverages the Open-Meteo API to retrieve current weather information based on user input. | ||
|
||
## ⚠ 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). | ||
|
||
## Scenario | ||
|
||
This example illustrates a typical interaction between a generative AI model, an application, and connected tools or APIs to solve a problem or achieve a specific goal. The scenario follows these steps: | ||
|
||
1. Set up the system prompt and tool configuration. | ||
2. Specify the AI model to be used (e.g., Anthropic Claude 3 Sonnet). | ||
3. Create a client to interact with Amazon Bedrock. | ||
4. Prompt the user for their weather request. | ||
5. Send the user input including the conversation history to the model. | ||
6. The model processes the input and determines if a connected tool or API needs to be used. If this is the case, the model returns a tool use request with specific parameters needed to invoke the tool, and a unique tool use ID to correlate tool responses to the request. | ||
7. The scenario application invokes the tool to fetch weather data, and append the response and tool use ID to the conversation. | ||
8. The model uses the tool response to generate a final response. If additional tool requests are needed, the process is repeated. | ||
9. Once the final response is received and printed, the application returns to the prompt. | ||
|
||
### Prerequisites | ||
|
||
For prerequisites, see the [README](../../../../README.md#prerequisites) in the `javascriptv3` folder. | ||
|
||
## Run the example | ||
|
||
```bash | ||
node converse-tool-scenario.js | ||
``` | ||
## 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 `javascriptv3` folder. | ||
|
||
## Additional resources | ||
|
||
- [Documentation: The Amazon Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) | ||
- [Tutorials: A developer's guide to Bedrock's new Converse API](https://community.aws/content/2dtauBCeDa703x7fDS9Q30MJoBA/amazon-bedrock-converse-api-developer-guide) | ||
- [More examples: Amazon Bedrock code examples and scenarios in multiple programming languages](https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html) | ||
|
||
--- | ||
|
||
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
|
||
SPDX-License-Identifier: Apache-2.0 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.