-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
67 lines (48 loc) · 1.83 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
64
65
66
67
import boto3
import botocore.config
import json
from datetime import datetime
def blog_generate_using_bedrock(blogtopic:str)-> str:
prompt=f"""<s>[INST]Human: Write a 100 words blog on the topic {blogtopic}
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="meta.llama2-13b-chat-v1")
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("Article saved to s3")
except Exception as e:
print("Error when saving the Article to s3")
def lambda_handler(event, context):
event=json.loads(event['body'])
blogtopic=event['blog_topic']
generate_blog=blog_generate_using_bedrock(blogtopic=blogtopic)
if generate_blog:
current_time=datetime.now().strftime('%H%M%S')
s3_key=f"article-output/{current_time}.txt"
s3_bucket='aws_bedrock_article'
save_blog_details_s3(s3_key,s3_bucket,generate_blog)
else:
print("No blog was generated")
return{
'statusCode':200,
'body':json.dumps('Article Generation is completed')
}