-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
63 lines (48 loc) · 1.79 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import json
from datetime import datetime
import boto3
import botocore.config
def blog_generate_using_bedrock(blog_topic: str) -> str:
prompt = f"""<s>[INST]Human: Write a 200 words blog on the topic {blog_topic}
Assistant:[/INST]
"""
body = {
"prompt": prompt,
"max_gen_len": 512,
"temperature": 0.5,
"top_p": 0.9
}
try:
bedrock = boto3.client("bedrock-runtime", region_name="us-east-1",
config=botocore.config.Config(read_timeout=300, retries={'max_attempts': 3}))
response = bedrock.invoke_model(body=json.dumps(body), modelId="us.meta.llama3-1-70b-instruct-v1:0")
response_content = response.get('body').read()
response_data = json.loads(response_content)
print(response_data)
blog_details = response_data['generation']
return blog_details
except Exception as e:
print(f"Error generating the blog:{e}")
return ""
def save_blog_details_s3(s3_key, s3_bucket, generate_blog):
s3 = boto3.client('s3')
try:
s3.put_object(Bucket=s3_bucket, Key=s3_key, Body=generate_blog)
print("Saved to s3")
except Exception as e:
print("Error when saving to s3")
def lambda_handler(event, context):
event = json.loads(event['body'])
blog_topic = event['blog_topic']
generate_blog = blog_generate_using_bedrock(blog_topic=blog_topic)
if generate_blog:
current_time = datetime.now().strftime('%H%M%S')
s3_key = f"blog-output/{current_time}.txt"
s3_bucket = 'awsbedrockblogcreation'
save_blog_details_s3(s3_key, s3_bucket, generate_blog)
else:
print("No blog was generated")
return {
'statusCode': 200,
'body': json.dumps('Blog Generation is completed')
}