Skip to content

Commit c332cac

Browse files
committed
Merge branch 'feature/chat-with-document' into 'develop'
Guardrails Protection See merge request genaiic-reusable-assets/engagement-artifacts/genaiic-idp-accelerator!310
2 parents 23c10ad + 13f3f8e commit c332cac

File tree

2 files changed

+38
-12
lines changed

2 files changed

+38
-12
lines changed

src/lambda/chat_with_document_resolver/index.py

Lines changed: 37 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,28 @@
99
import base64
1010
import hashlib
1111
import os
12+
import re
1213
from urllib.parse import urlparse
1314
from botocore.exceptions import ClientError
1415
from idp_common.bedrock.client import BedrockClient
1516

1617
# Set up logging
1718
logger = logging.getLogger()
1819
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
19-
# Get LOG_LEVEL from environment variable with INFO as default
2020

21+
def remove_text_between_brackets(text):
22+
# Find position of first opening bracket
23+
start = text.find('{')
24+
# Find position of last closing bracket
25+
end = text.rfind('}')
26+
27+
# If both brackets exist, remove text between them including brackets
28+
if start != -1 and end != -1:
29+
return text[:start] + text[end+1:]
30+
# If brackets not found, return original string
31+
return text
32+
33+
# Get LOG_LEVEL from environment variable with INFO as default
2134
def s3_object_exists(bucket, key):
2235
try:
2336
s3 = boto3.client('s3')
@@ -66,7 +79,7 @@ def get_full_text(bucket, key):
6679

6780
except Exception as e:
6881
logger.error(f"Error getting document pages: {str(e)}")
69-
raise
82+
raise Exception(f"Error getting document pages: {str(e)}")
7083

7184

7285
def get_summarization_model():
@@ -98,7 +111,6 @@ def handler(event, context):
98111

99112
try:
100113
# logger.info(f"Received event: {json.dumps(event)}")
101-
102114
objectKey = event['arguments']['s3Uri']
103115
prompt = event['arguments']['prompt']
104116
history = event['arguments']['history']
@@ -115,8 +127,6 @@ def handler(event, context):
115127

116128
output_bucket = os.environ['OUTPUT_BUCKET']
117129

118-
bedrock_runtime = boto3.client('bedrock-runtime', region_name=os.environ['AWS_REGION'])
119-
120130
if (len(objectKey)):
121131
fulltext_key = objectKey + '/summary/fulltext.txt'
122132
content_str = ""
@@ -140,7 +150,6 @@ def handler(event, context):
140150
logger.info(f"Output Bucket: {output_bucket}")
141151
logger.info(f"Full Text Key: {fulltext_key}")
142152

143-
client = BedrockClient()
144153
# Content with cachepoint tags
145154
content = [
146155
{
@@ -150,16 +159,32 @@ def handler(event, context):
150159
}
151160
]
152161

153-
model_response = client.invoke_model(
154-
model_id="us.amazon.nova-pro-v1:0",
162+
client = BedrockClient(
163+
region=os.environ['AWS_REGION'],
164+
max_retries=5,
165+
initial_backoff=1.5,
166+
max_backoff=300,
167+
metrics_enabled=True
168+
)
169+
170+
# Invoke a model
171+
response = client.invoke_model(
172+
model_id=selectedModelId,
155173
system_prompt="You are an assistant that's responsible for getting details from document text attached here based on questions from the user.\n\nIf you don't know the answer, just say that you don't know. Don't try to make up an answer.\n\nAdditionally, use the user and assistant responses in the following JSON object to see what's been asked and what the resposes were in the past.\n\n",
156174
content=content,
157175
temperature=0.0
158176
)
159177

160-
text = client.extract_text_from_response(model_response)
178+
text = client.extract_text_from_response(response)
179+
logger.info(f"Full response: {text}")
180+
181+
# right now, there is a JSON object before the full response when a guardrail is tripped
182+
# need to remove that JSON object first
183+
logger.info(f"New response: {remove_text_between_brackets(text).strip("\n")}")
184+
cleaned_up_text = remove_text_between_brackets(text).strip("\n")
185+
186+
chat_response = {"cr": {"content": [{"text": cleaned_up_text}]}}
161187

162-
chat_response = {"cr": {"content": [{"text": text}]}}
163188
return json.dumps(chat_response)
164189

165190
except ClientError as e:
@@ -175,7 +200,7 @@ def handler(event, context):
175200
raise Exception(error_message)
176201

177202
except Exception as e:
178-
logger.error(f"Unexpected error: {str(e)}")
179-
raise Exception(f"Unexpected error: {str(e)}")
203+
logger.error(f"{str(e)}")
204+
raise Exception(f"{str(e)}")
180205

181206
return response_data

template.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6107,6 +6107,7 @@ Resources:
61076107
OUTPUT_BUCKET: !Ref OutputBucket
61086108
CONFIGURATION_TABLE_NAME: !Ref ConfigurationTable
61096109
TRACKING_TABLE_NAME: !Ref TrackingTable
6110+
GUARDRAIL_ID_AND_VERSION: !If [HasGuardrailConfig, !Sub "${BedrockGuardrailId}:${BedrockGuardrailVersion}", ""]
61106111
LoggingConfig:
61116112
LogGroup: !Ref ChatWithDocumentResolverFunctionLogGroup
61126113
Policies:

0 commit comments

Comments
 (0)