You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I want to use boto3 to run the already created agents for amazon bedrock.
The source code I created consists of the following
def compose_args_for_Agents_for_amazon_bedrock(
messages: list[MessageModel],
instruction: str | None = None,
) ->dict:
"""Compose arguments for Anthropic client.
Ref: https://docs.anthropic.com/claude/reference/messages_post
"""
text=""
if instruction:
text = instruction
# NOTE: Only corresponds to the last instruction
print(messages)
if messages:
for content in messages[-1].content:
if content.content_type == "text":
text += content.body
request_data = {
'agentAliasId': '*******',
'agentId': '********',
'inputText': text,
'sessionId': str(uuid.uuid1())
}
return request_data
def get_bedrock_agents(region=BEDROCK_REGION):
s3_client = boto3.client("bedrock-agent-runtime",
config=Config(connect_timeout=timeout, read_timeout=timeout, retries={'max_attempts': 2}),
aws_access_key_id='**************',
aws_secret_access_key=r'******************',
aws_session_token=r'**********',
region_name=region
)
return s3_client
def _generate_bedrock(user_id: str, chat_input: ChatInput):
user_msg_id, conversation, bot = prepare_conversation(user_id, chat_input)
message_map = conversation.message_map
messages = trace_to_root(
node_id=chat_input.message.parent_message_id, message_map=message_map
)
messages.append(chat_input.message) # type: ignore
# Create payload to invoke Bedrock
args = compose_args_for_Agents_for_amazon_bedrock(
messages=messages,
instruction=(
message_map["instruction"].content[0].body
if "instruction" in message_map
else None
),
)
# 変更
# client = boto3.client('bedrock-agent-runtime')
# response = client.invoke_agent(kwd)
response = client_agents.invoke_agent(**args)
print(response)
# response_body = json.loads(response["body"].read())
# responseのデータを定義する
response_data = response['completion']
for event in response_data:
if 'chunk' in event:
_data = event['chunk']['bytes'].decode("utf-8")
_content = []
_content.append(ContentModel(content_type="text", body=_data, media_type=None))
# Issue id for new assistant message
assistant_msg_id = str(ULID())
# Append bedrock output to the existing conversation
message = MessageModel(
role="assistant",
content=_content,
model=chat_input.message.model,
children=[],
parent=user_msg_id,
create_time=get_current_time(),
)
conversation.message_map[assistant_msg_id] = message
# Append children to parent
conversation.message_map[user_msg_id].children.append(assistant_msg_id)
conversation.last_message_id = assistant_msg_id
# NOTE: Pricing is not supported
# Update total pricing
# input_tokens = response.usage.input_tokens
# output_tokens = response.usage.output_tokens
# logger.debug(f"Input tokens: {input_tokens}, Output tokens: {output_tokens}")
# price = calculate_price(chat_input.message.model, input_tokens, output_tokens)
# conversation.total_price += price
# Store updated conversation
store_conversation(user_id, conversation)
# Update bot last used time
if chat_input.bot_id:
logger.info("Bot id is provided. Updating bot last used time.")
# Update bot last used time
modify_bot_last_used_time(user_id, chat_input.bot_id)
output = ChatOutput(
conversation_id=conversation.id,
create_time=conversation.create_time,
message=MessageOutput(
role=message.role,
content=[
Content(
content_type=c.content_type,
body=c.body,
media_type=c.media_type,
)
for c in message.content
],
model=message.model,
children=message.children,
parent=message.parent,
),
bot_id=conversation.bot_id,
)
return output
_generate_bedrock(user_id, chat_input)
This code's
# Define the response data
response_data = response['completion'].
for event in response_data: if 'chunk' in event
if 'chunk' in event:.
_data = event['chunk']['bytes'].decode(“utf-8”)
When I try to process this part, I get the following error
{'ResponseMetadata': {'RequestId': '0', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Tue, 07 May 2024 11:58:09 GMT', 'content-type': 'application/json', 'transfer-encoding': 'chunked', 'connection': 'keep-alive', 'x-amzn-requestid': '***', 'x-amz-bedrock-agent-session-id': '********', 'x-amzn-bedrock-agent-content-type': 'application/json'}, 'RetryAttempts': 0}, 'contentType': 'application/json', 'sessionId': '**********e2', 'completion': <botocore.eventstream.EventStream object at 0x00000176F17FD090>}
ERROR:app.main - An error occurred (resourceNotFoundException) when calling the InvokeAgent operation: Failed to retrieve resource because it doesn't exist. Retry the request with a different resource identifier.
How can I resolve this error?
I am translating from Japanese to English, so I apologize if some parts are difficult to understand.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I want to use boto3 to run the already created agents for amazon bedrock.
The source code I created consists of the following
This code's
When I try to process this part, I get the following error
{'ResponseMetadata': {'RequestId': '0', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Tue, 07 May 2024 11:58:09 GMT', 'content-type': 'application/json', 'transfer-encoding': 'chunked', 'connection': 'keep-alive', 'x-amzn-requestid': '***', 'x-amz-bedrock-agent-session-id': '********', 'x-amzn-bedrock-agent-content-type': 'application/json'}, 'RetryAttempts': 0}, 'contentType': 'application/json', 'sessionId': '**********e2', 'completion': <botocore.eventstream.EventStream object at 0x00000176F17FD090>}
ERROR:app.main - An error occurred (resourceNotFoundException) when calling the InvokeAgent operation: Failed to retrieve resource because it doesn't exist. Retry the request with a different resource identifier.
How can I resolve this error?
I am translating from Japanese to English, so I apologize if some parts are difficult to understand.
Thank you in advance.
Beta Was this translation helpful? Give feedback.
All reactions