-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.py
More file actions
133 lines (109 loc) · 4.03 KB
/
Copy pathlambda.py
File metadata and controls
133 lines (109 loc) · 4.03 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import boto3
import json
import logging
import random
import os
from datetime import datetime, timezone
from botocore.exceptions import ClientError
from botocore.config import Config
logger = logging.getLogger()
logger.setLevel(logging.INFO)
BUCKET_NAME = "myths-agent-aws-dev-challenge"
AWS_REGION = "eu-north-1"
MODEL_ID = "amazon.nova-lite-v1:0"
FALLBACK_MODEL_ID = "amazon.nova-micro-v1:0"
MANIFEST_KEY = "manifest.json"
_boto3_config = Config(region_name=AWS_REGION, retries={"max_attempts": 3, "mode": "adaptive"})
bedrock_rt = boto3.client("bedrock-runtime", config=_boto3_config)
s3 = boto3.client("s3", config=_boto3_config)
with open(os.path.join(os.path.dirname(__file__), "content_library.json")) as f:
LIBRARY = json.load(f)
def pick_random_pair():
myth = random.choice(LIBRARY["myths"])
trivia = random.choice(LIBRARY["tech_trivia"])
return myth, trivia
def build_prompt(myth, trivia):
return (
"You are a witty technical storyteller who writes short parables for software "
"engineers. Blend the mythological story below with the computer-science concept "
"below into a single, coherent, whimsical fable of 100-300 words. End with a short "
"'Moral for Engineers' takeaway (1-2 sentences). Do not explain that you are "
"combining two topics -- just tell the story.\n\n"
f"MYTH: {myth['title']} -- {myth['summary']}\n\n"
f"TECH CONCEPT: {trivia['title']} -- {trivia['detail']}\n"
)
def generate_story(myth, trivia):
prompt = build_prompt(myth=myth, trivia=trivia)
try:
return invoke_nova(prompt=prompt, model_id=MODEL_ID)
except ClientError as err:
code = err.response.get("Error", {}).get("Code", "")
logger.warning(f"Main Model failed {code}; falling to fallback model {FALLBACK_MODEL_ID}")
if code in ("ThrottlingException", "ModelTimeoutException", "ServiceUnavailableException", "InternalServerException"):
return invoke_nova(prompt, FALLBACK_MODEL_ID)
raise
def invoke_nova(prompt, model_id):
response = bedrock_rt.converse(
modelId=model_id,
messages=[
{
"role": "user",
"content": [
{"text": prompt}
]
}
],
inferenceConfig={
"maxTokens": 800,
"temperature": 0.9,
"topP": 0.9
}
)
return response["output"]["message"]["content"][0]["text"]
def update_manifest(entry):
try:
existing_obj = s3.get_object(Bucket=BUCKET_NAME, Key=MANIFEST_KEY)
manifest = json.loads(existing_obj["Body"].read())
except s3.exceptions.NoSuchKey:
manifest = []
manifest.append(entry)
s3.put_object(
Bucket=BUCKET_NAME,
Key=MANIFEST_KEY,
Body=json.dumps(manifest, indent=2).encode("utf-8"),
ContentType="application/json"
)
logger.info("manifest.json updated (%d total entries)", len(manifest))
def save_artifact(myth, trivia, story_text):
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
key = f"compendium/{today}-{myth['id']}-{trivia['id']}.md"
body = (
f"# {today}: {myth['title']} meets {trivia['title']}\n\n"
f"*Myth:* {myth['summary']}\n\n"
f"*Tech concept:* {trivia['detail']}\n\n---\n\n{story_text}\n"
)
s3.put_object(
Bucket=BUCKET_NAME, Key=key, Body=body.encode("utf-8"),
ContentType="text/markdown; charset=utf-8"
)
update_manifest({
"date": today,
"key": key,
"myth": myth["title"],
"trivia": trivia["title"]
})
return key
def handler(event, context):
myth, trivia = pick_random_pair()
logger.info("Pairing selected: %s + %s", myth["id"], trivia["id"])
story_text = generate_story(myth, trivia)
key = save_artifact(myth, trivia, story_text)
return {
"statusCode": 200,
"body": json.dumps({
"message": "Artifact generated",
"s3_key": key,
"myth": myth["id"],
"trivia": trivia["id"]
})
}