API InvokeAgent — отправка изображений агенту AWS BEDROCKPython

Программы на Python
Anonymous
API InvokeAgent — отправка изображений агенту AWS BEDROCK

Сообщение Anonymous »

Есть ли способ отправить файлы изображений в виде ссылки на репозиторий base64 или s3 агенту BedRock с помощью API InvokeAgent?
Я заметил, что в синтаксисе у нас есть эта часть:

Код: Выделить всё

response = client.invoke_agent(
agentAliasId='string',
agentId='string',
enableTrace=True|False,
endSession=True|False,
inputText='string',
memoryId='string',
sessionId='string',
sessionState={
'files': [
{
'name': 'string',
'source': {
'byteContent': {
'data': b'bytes',
'mediaType': 'string'
},
's3Location': {
'uri': 'string'
},
'sourceType': 'S3'|'BYTE_CONTENT'
},
'useCase': 'CODE_INTERPRETER'|'CHAT'
},
],

К сожалению, я не нашел никаких документов или примеров по заполнению этих частей.
Я пробовал передать изображение в формате Base64 р>

Код: Выделить всё

 'files': [
{
'name': 'uploaded_picture',
'source': {
'byteContent': {
'data': b'{base64}',
'mediaType': 'image/jpeg'
},

'sourceType': 'BYTE_CONTENT'
},
'useCase': 'CHAT'
},
],
Но Бедрок вернул мне ошибку:

Код: Выделить всё

EventStreamError: An error occurred (validationException) when calling the InvokeAgent operation: The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.
Hi There.
Есть ли способ отправить файлы изображений в виде ссылки на репозиторий base64 или s3 агенту BedRock с помощью API InvokeAgent?
Я заметил, что в синтаксисе у нас есть эта часть:

Код: Выделить всё

response = client.invoke_agent(
agentAliasId='string',
agentId='string',
enableTrace=True|False,
endSession=True|False,
inputText='string',
memoryId='string',
sessionId='string',
sessionState={
'files': [
{
'name': 'string',
'source': {
'byteContent': {
'data': b'bytes',
'mediaType': 'string'
},
's3Location': {
'uri': 'string'
},
'sourceType': 'S3'|'BYTE_CONTENT'
},
'useCase': 'CODE_INTERPRETER'|'CHAT'
},
],

К сожалению, я не нашел никаких документов или примеров по заполнению этих частей.
Я пробовал передать изображение в формате Base64 р>

Код: Выделить всё

 'files': [
{
'name': 'uploaded_picture',
'source': {
'byteContent': {
'data': b'{base64}',
'mediaType': 'image/jpeg'
},

'sourceType': 'BYTE_CONTENT'
},
'useCase': 'CHAT'
},
],

Но Бедрок вернул мне ошибку:

Код: Выделить всё

EventStreamError: An error occurred (validationException) when calling the InvokeAgent operation: The overridden prompt that you provided is incorrectly formatted. Check the format for errors, such as invalid JSON, and retry your request.

Та же ошибка возникает в пользовательском интерфейсе Bedrock.
введите здесь описание изображения

Вот полный код Python:

Код: Выделить всё

import boto3

# Initialize the boto3 client
agents_runtime_client = boto3.client('bedrock-agent-runtime', region_name='sa-east-1')

def invoke_agent(agent_id, agent_alias_id, session_id, prompt, image_path = None):

try:

image_data = None
if image_path:
with open(image_path, "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode('utf-8')

# 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 = agents_runtime_client.invoke_agent(
agentId=agent_id,
agentAliasId=agent_alias_id,
sessionId=session_id,
inputText=input_text,
sessionState={
'files': [
{
'name': 'picture',
'source': {
'byteContent': {
'data': image_data,
'mediaType': 'image/jpeg'
},
'sourceType': 'BYTE_CONTENT'
},
'useCase': 'CHAT'
}
]
}
)

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

# Define the chat parameters
agent_alias_id = "XXXXX"
agent_id = "XXXXX"
session_id = str(uuid.uuid4())
input_text = "Hello"
Я пробовал читать документацию и использовать предоставленные параметры.
Я ожидаю, что смогу отправлять изображения для интерпретации агенту.

Подробнее здесь: https://stackoverflow.com/questions/790 ... rock-agent

Вернуться в «Python»