Selecione suas preferências de cookies

Usamos cookies essenciais e ferramentas semelhantes que são necessárias para fornecer nosso site e serviços. Usamos cookies de desempenho para coletar estatísticas anônimas, para que possamos entender como os clientes usam nosso site e fazer as devidas melhorias. Cookies essenciais não podem ser desativados, mas você pode clicar em “Personalizar” ou “Recusar” para recusar cookies de desempenho.

Se você concordar, a AWS e terceiros aprovados também usarão cookies para fornecer recursos úteis do site, lembrar suas preferências e exibir conteúdo relevante, incluindo publicidade relevante. Para aceitar ou recusar todos os cookies não essenciais, clique em “Aceitar” ou “Recusar”. Para fazer escolhas mais detalhadas, clique em “Personalizar”.

Use InvokeAgent com um AWS SDK

Modo de foco
Use InvokeAgent com um AWS SDK - AWS Exemplos de código do SDK

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Os exemplos de código a seguir mostram como usar o InvokeAgent.

JavaScript
SDK para JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

import { BedrockAgentRuntimeClient, InvokeAgentCommand, } from "@aws-sdk/client-bedrock-agent-runtime"; /** * @typedef {Object} ResponseBody * @property {string} completion */ /** * Invokes a Bedrock agent to run an inference using the input * provided in the request body. * * @param {string} prompt - The prompt that you want the Agent to complete. * @param {string} sessionId - An arbitrary identifier for the session. */ export const invokeBedrockAgent = async (prompt, sessionId) => { const client = new BedrockAgentRuntimeClient({ region: "us-east-1" }); // const client = new BedrockAgentRuntimeClient({ // region: "us-east-1", // credentials: { // accessKeyId: "accessKeyId", // permission to invoke agent // secretAccessKey: "accessKeySecret", // }, // }); const agentId = "AJBHXXILZN"; const agentAliasId = "AVKP1ITZAA"; const command = new InvokeAgentCommand({ agentId, agentAliasId, sessionId, inputText: prompt, }); try { let completion = ""; const response = await client.send(command); if (response.completion === undefined) { throw new Error("Completion is undefined"); } for await (const chunkEvent of response.completion) { const chunk = chunkEvent.chunk; console.log(chunk); const decodedResponse = new TextDecoder("utf-8").decode(chunk.bytes); completion += decodedResponse; } return { sessionId: sessionId, completion }; } catch (err) { console.error(err); } }; // Call function if run directly import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { const result = await invokeBedrockAgent("I need help.", "123"); console.log(result); }
  • Para obter detalhes da API, consulte InvokeAgenta Referência AWS SDK para JavaScript da API.

Python
SDK para Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Invoque um agente.

def invoke_agent(self, agent_id, agent_alias_id, session_id, prompt): """ Sends a prompt for the agent to process and respond to. :param agent_id: The unique identifier of the agent to use. :param agent_alias_id: The alias of the agent to use. :param session_id: The unique identifier of the session. Use the same value across requests to continue the same conversation. :param prompt: The prompt that you want Claude to complete. :return: Inference response from the model. """ try: # Note: The execution time depends on the foundation model, complexity of the agent, # and the length of the prompt. In some cases, it can take up to a minute or more to # generate a response. response = self.agents_runtime_client.invoke_agent( agentId=agent_id, agentAliasId=agent_alias_id, sessionId=session_id, inputText=prompt, ) completion = "" for event in response.get("completion"): chunk = event["chunk"] completion = completion + chunk["bytes"].decode() except ClientError as e: logger.error(f"Couldn't invoke agent. {e}") raise return completion
  • Para obter detalhes da API, consulte a InvokeAgentReferência da API AWS SDK for Python (Boto3).

SAP ABAP
SDK para SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

DATA(lo_result) = lo_bdz->invokeagent( iv_agentid = iv_agentid iv_agentaliasid = iv_agentaliasid iv_enabletrace = abap_true iv_sessionid = CONV #( cl_system_uuid=>create_uuid_c26_static( ) ) iv_inputtext = |Let's play "rock, paper, scissors". I choose rock.| ). DATA(lo_stream) = lo_result->get_completion( ). TRY. " loop while there are still events in the stream WHILE lo_stream->/aws1/if_rt_stream_reader~data_available( ) = abap_true. DATA(lo_evt) = lo_stream->read( ). " each /AWS1/CL_BDZRESPONSESTREAM_EV event contains exactly one member " all others are INITIAL. For each event, process the non-initial " member if desired IF lo_evt->get_chunk( ) IS NOT INITIAL. " Process a Chunk event DATA(lv_xstr) = lo_evt->get_chunk( )->get_bytes( ). DATA(lv_answer) = /aws1/cl_rt_util=>xstring_to_string( lv_xstr ). " the answer says something like "I chose paper, so you lost" ELSEIF lo_evt->get_files( ) IS NOT INITIAL. " process a Files event if desired ELSEIF lo_evt->get_returncontrol( ) IS NOT INITIAL. " process a ReturnControl event if desired ELSEIF lo_evt->get_trace( ) IS NOT INITIAL. " process a Trace event if desired ENDIF. ENDWHILE. " the stream of events can possibly contain an exception " which will be raised to break the loop " catch /AWS1/CX_BDZACCESSDENIEDEX. " catch /AWS1/CX_BDZINTERNALSERVEREX. " catch /AWS1/CX_BDZMODELNOTREADYEX. " catch /AWS1/CX_BDZVALIDATIONEX. " catch /AWS1/CX_BDZTHROTTLINGEX. " catch /AWS1/CX_BDZDEPENDENCYFAILEDEX. " catch /AWS1/CX_BDZBADGATEWAYEX. " catch /AWS1/CX_BDZRESOURCENOTFOUNDEX. " catch /AWS1/CX_BDZSERVICEQUOTAEXCDEX. " catch /AWS1/CX_BDZCONFLICTEXCEPTION. ENDTRY.
  • Para obter detalhes da API, consulte a InvokeAgentreferência da API AWS SDK for SAP ABAP.

SDK para JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

import { BedrockAgentRuntimeClient, InvokeAgentCommand, } from "@aws-sdk/client-bedrock-agent-runtime"; /** * @typedef {Object} ResponseBody * @property {string} completion */ /** * Invokes a Bedrock agent to run an inference using the input * provided in the request body. * * @param {string} prompt - The prompt that you want the Agent to complete. * @param {string} sessionId - An arbitrary identifier for the session. */ export const invokeBedrockAgent = async (prompt, sessionId) => { const client = new BedrockAgentRuntimeClient({ region: "us-east-1" }); // const client = new BedrockAgentRuntimeClient({ // region: "us-east-1", // credentials: { // accessKeyId: "accessKeyId", // permission to invoke agent // secretAccessKey: "accessKeySecret", // }, // }); const agentId = "AJBHXXILZN"; const agentAliasId = "AVKP1ITZAA"; const command = new InvokeAgentCommand({ agentId, agentAliasId, sessionId, inputText: prompt, }); try { let completion = ""; const response = await client.send(command); if (response.completion === undefined) { throw new Error("Completion is undefined"); } for await (const chunkEvent of response.completion) { const chunk = chunkEvent.chunk; console.log(chunk); const decodedResponse = new TextDecoder("utf-8").decode(chunk.bytes); completion += decodedResponse; } return { sessionId: sessionId, completion }; } catch (err) { console.error(err); } }; // Call function if run directly import { fileURLToPath } from "node:url"; if (process.argv[1] === fileURLToPath(import.meta.url)) { const result = await invokeBedrockAgent("I need help.", "123"); console.log(result); }
  • Para obter detalhes da API, consulte InvokeAgenta Referência AWS SDK para JavaScript da API.

PrivacidadeTermos do sitePreferências de cookies
© 2025, Amazon Web Services, Inc. ou suas afiliadas. Todos os direitos reservados.