使用适用于 JavaScript (v3) 的软件开发工具包的 Amazon Bedrock 代理示例 - Amazon SDK for JavaScript
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

Amazon SDK for JavaScript V3 API 参考指南详细描述了 Amazon SDK for JavaScript 版本 3 (V3) 的所有 API 操作。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用适用于 JavaScript (v3) 的软件开发工具包的 Amazon Bedrock 代理示例

以下代码示例向您展示了如何使用带有 Amazon Bedrock 代理的 Amazon SDK for JavaScript (v3) 来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景 是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例显示了如何开始使用适用于 Amazon Bedrock 的代理。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { BedrockAgentClient, GetAgentCommand, paginateListAgents, } from "@aws-sdk/client-bedrock-agent"; /** * @typedef {Object} AgentSummary */ /** * A simple scenario to demonstrate basic setup and interaction with the Bedrock Agents Client. * * This function first initializes the Amazon Bedrock Agents client for a specific region. * It then retrieves a list of existing agents using the streamlined paginator approach. * For each agent found, it retrieves detailed information using a command object. * * Demonstrates: * - Use of the Bedrock Agents client to initialize and communicate with the AWS service. * - Listing resources in a paginated response pattern. * - Accessing an individual resource using a command object. * * @returns {Promise<void>} A promise that resolves when the function has completed execution. */ export const main = async () => { const region = "us-east-1"; console.log("=".repeat(68)); console.log(`Initializing Amazon Bedrock Agents client for ${region}...`); const client = new BedrockAgentClient({ region }); console.log(`Retrieving the list of existing agents...`); const paginatorConfig = { client }; const pages = paginateListAgents(paginatorConfig, {}); /** @type {AgentSummary[]} */ const agentSummaries = []; for await (const page of pages) { agentSummaries.push(...page.agentSummaries); } console.log(`Found ${agentSummaries.length} agents in ${region}.`); if (agentSummaries.length > 0) { for (const agentSummary of agentSummaries) { const agentId = agentSummary.agentId; console.log("=".repeat(68)); console.log(`Retrieving agent with ID: ${agentId}:`); console.log("-".repeat(68)); const command = new GetAgentCommand({ agentId }); const response = await client.send(command); const agent = response.agent; console.log(` Name: ${agent.agentName}`); console.log(` Status: ${agent.agentStatus}`); console.log(` ARN: ${agent.agentArn}`); console.log(` Foundation model: ${agent.foundationModel}`); } } console.log("=".repeat(68)); }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { await main(); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考中的以下主题。

主题

操作

以下代码示例演示了如何创建 Amazon Bedrock 代理。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

创建 代理

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { checkForPlaceholders } from "../lib/utils.js"; import { BedrockAgentClient, CreateAgentCommand, } from "@aws-sdk/client-bedrock-agent"; /** * Creates an Amazon Bedrock Agent. * * @param {string} agentName - A name for the agent that you create. * @param {string} foundationModel - The foundation model to be used by the agent you create. * @param {string} agentResourceRoleArn - The ARN of the IAM role with permissions required by the agent. * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<import("@aws-sdk/client-bedrock-agent").Agent>} An object containing details of the created agent. */ export const createAgent = async ( agentName, foundationModel, agentResourceRoleArn, region = "us-east-1", ) => { const client = new BedrockAgentClient({ region }); const command = new CreateAgentCommand({ agentName, foundationModel, agentResourceRoleArn, }); const response = await client.send(command); return response.agent; }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { // Replace the placeholders for agentName and accountId, and roleName with a unique name for the new agent, // the id of your AWS account, and the name of an existing execution role that the agent can use inside your account. // For foundationModel, specify the desired model. Ensure to remove the brackets '[]' before adding your data. // A string (max 100 chars) that can include letters, numbers, dashes '-', and underscores '_'. const agentName = "[your-bedrock-agent-name]"; // Your AWS account id. const accountId = "[123456789012]"; // The name of the agent's execution role. It must be prefixed by `AmazonBedrockExecutionRoleForAgents_`. const roleName = "[AmazonBedrockExecutionRoleForAgents_your-role-name]"; // The ARN for the agent's execution role. // Follow the ARN format: 'arn:aws:iam::account-id:role/role-name' const roleArn = `arn:aws:iam::${accountId}:role/${roleName}`; // Specify the model for the agent. Change if a different model is preferred. const foundationModel = "anthropic.claude-v2"; // Check for unresolved placeholders in agentName and roleArn. checkForPlaceholders([agentName, roleArn]); console.log(`Creating a new agent...`); const agent = await createAgent(agentName, foundationModel, roleArn); console.log(agent); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考CreateAgent中的。

以下代码示例演示了如何删除 Amazon Bedrock 代理。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

删除代理。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { checkForPlaceholders } from "../lib/utils.js"; import { BedrockAgentClient, DeleteAgentCommand, } from "@aws-sdk/client-bedrock-agent"; /** * Deletes an Amazon Bedrock Agent. * * @param {string} agentId - The unique identifier of the agent to delete. * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<import("@aws-sdk/client-bedrock-agent").DeleteAgentCommandOutput>} An object containing the agent id, the status, and some additional metadata. */ export const deleteAgent = (agentId, region = "us-east-1") => { const client = new BedrockAgentClient({ region }); const command = new DeleteAgentCommand({ agentId }); return client.send(command); }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { // Replace the placeholders for agentId with an existing agent's id. // Ensure to remove the brackets (`[]`) before adding your data. // The agentId must be an alphanumeric string with exactly 10 characters. const agentId = "[ABC123DE45]"; // Check for unresolved placeholders in agentId. checkForPlaceholders([agentId]); console.log(`Deleting agent with ID ${agentId}...`); const response = await deleteAgent(agentId); console.log(response); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考DeleteAgent中的。

以下代码示例演示了如何获取有关 Amazon Bedrock 代理的信息。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

获取代理。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { checkForPlaceholders } from "../lib/utils.js"; import { BedrockAgentClient, GetAgentCommand, } from "@aws-sdk/client-bedrock-agent"; /** * Retrieves the details of an Amazon Bedrock Agent. * * @param {string} agentId - The unique identifier of the agent. * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<import("@aws-sdk/client-bedrock-agent").Agent>} An object containing the agent details. */ export const getAgent = async (agentId, region = "us-east-1") => { const client = new BedrockAgentClient({ region }); const command = new GetAgentCommand({ agentId }); const response = await client.send(command); return response.agent; }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { // Replace the placeholders for agentId with an existing agent's id. // Ensure to remove the brackets '[]' before adding your data. // The agentId must be an alphanumeric string with exactly 10 characters. const agentId = "[ABC123DE45]"; // Check for unresolved placeholders in agentId. checkForPlaceholders([agentId]); console.log(`Retrieving agent with ID ${agentId}...`); const agent = await getAgent(agentId); console.log(agent); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考GetAgent中的。

以下代码示例演示了如何列出 Amazon Bedrock 代理的操作组。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出代理的操作组。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { checkForPlaceholders } from "../lib/utils.js"; import { BedrockAgentClient, ListAgentActionGroupsCommand, paginateListAgentActionGroups, } from "@aws-sdk/client-bedrock-agent"; /** * Retrieves a list of Action Groups of an agent utilizing the paginator function. * * This function leverages a paginator, which abstracts the complexity of pagination, providing * a straightforward way to handle paginated results inside a `for await...of` loop. * * @param {string} agentId - The unique identifier of the agent. * @param {string} agentVersion - The version of the agent. * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<ActionGroupSummary[]>} An array of action group summaries. */ export const listAgentActionGroupsWithPaginator = async ( agentId, agentVersion, region = "us-east-1", ) => { const client = new BedrockAgentClient({ region }); // Create a paginator configuration const paginatorConfig = { client, pageSize: 10, // optional, added for demonstration purposes }; const params = { agentId, agentVersion }; const pages = paginateListAgentActionGroups(paginatorConfig, params); // Paginate until there are no more results const actionGroupSummaries = []; for await (const page of pages) { actionGroupSummaries.push(...page.actionGroupSummaries); } return actionGroupSummaries; }; /** * Retrieves a list of Action Groups of an agent utilizing the ListAgentActionGroupsCommand. * * This function demonstrates the manual approach, sending a command to the client and processing the response. * Pagination must manually be managed. For a simplified approach that abstracts away pagination logic, see * the `listAgentActionGroupsWithPaginator()` example below. * * @param {string} agentId - The unique identifier of the agent. * @param {string} agentVersion - The version of the agent. * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<ActionGroupSummary[]>} An array of action group summaries. */ export const listAgentActionGroupsWithCommandObject = async ( agentId, agentVersion, region = "us-east-1", ) => { const client = new BedrockAgentClient({ region }); let nextToken; const actionGroupSummaries = []; do { const command = new ListAgentActionGroupsCommand({ agentId, agentVersion, nextToken, maxResults: 10, // optional, added for demonstration purposes }); /** @type {{actionGroupSummaries: ActionGroupSummary[], nextToken?: string}} */ const response = await client.send(command); for (const actionGroup of response.actionGroupSummaries || []) { actionGroupSummaries.push(actionGroup); } nextToken = response.nextToken; } while (nextToken); return actionGroupSummaries; }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { // Replace the placeholders for agentId and agentVersion with an existing agent's id and version. // Ensure to remove the brackets '[]' before adding your data. // The agentId must be an alphanumeric string with exactly 10 characters. const agentId = "[ABC123DE45]"; // A string either containing `DRAFT` or a number with 1-5 digits (e.g., '123' or 'DRAFT'). const agentVersion = "[DRAFT]"; // Check for unresolved placeholders in agentId and agentVersion. checkForPlaceholders([agentId, agentVersion]); console.log("=".repeat(68)); console.log( "Listing agent action groups using ListAgentActionGroupsCommand:", ); for (const actionGroup of await listAgentActionGroupsWithCommandObject( agentId, agentVersion, )) { console.log(actionGroup); } console.log("=".repeat(68)); console.log( "Listing agent action groups using the paginateListAgents function:", ); for (const actionGroup of await listAgentActionGroupsWithPaginator( agentId, agentVersion, )) { console.log(actionGroup); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考ListAgentActionGroups中的。

以下代码示例演示了如何列出属于某个账户的 Amazon Bedrock 代理。

适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

列出属于某个账户的代理。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { fileURLToPath } from "url"; import { BedrockAgentClient, ListAgentsCommand, paginateListAgents, } from "@aws-sdk/client-bedrock-agent"; /** * Retrieves a list of available Amazon Bedrock agents utilizing the paginator function. * * This function leverages a paginator, which abstracts the complexity of pagination, providing * a straightforward way to handle paginated results inside a `for await...of` loop. * * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<AgentSummary[]>} An array of agent summaries. */ export const listAgentsWithPaginator = async (region = "us-east-1") => { const client = new BedrockAgentClient({ region }); const paginatorConfig = { client, pageSize: 10, // optional, added for demonstration purposes }; const pages = paginateListAgents(paginatorConfig, {}); // Paginate until there are no more results const agentSummaries = []; for await (const page of pages) { agentSummaries.push(...page.agentSummaries); } return agentSummaries; }; /** * Retrieves a list of available Amazon Bedrock agents utilizing the ListAgentsCommand. * * This function demonstrates the manual approach, sending a command to the client and processing the response. * Pagination must manually be managed. For a simplified approach that abstracts away pagination logic, see * the `listAgentsWithPaginator()` example below. * * @param {string} [region='us-east-1'] - The AWS region in use. * @returns {Promise<AgentSummary[]>} An array of agent summaries. */ export const listAgentsWithCommandObject = async (region = "us-east-1") => { const client = new BedrockAgentClient({ region }); let nextToken; const agentSummaries = []; do { const command = new ListAgentsCommand({ nextToken, maxResults: 10, // optional, added for demonstration purposes }); /** @type {{agentSummaries: AgentSummary[], nextToken?: string}} */ const paginatedResponse = await client.send(command); agentSummaries.push(...(paginatedResponse.agentSummaries || [])); nextToken = paginatedResponse.nextToken; } while (nextToken); return agentSummaries; }; // Invoke main function if this file was run directly. if (process.argv[1] === fileURLToPath(import.meta.url)) { console.log("=".repeat(68)); console.log("Listing agents using ListAgentsCommand:"); for (const agent of await listAgentsWithCommandObject()) { console.log(agent); } console.log("=".repeat(68)); console.log("Listing agents using the paginateListAgents function:"); for (const agent of await listAgentsWithPaginator()) { console.log(agent); } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考ListAgents中的。