-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
67 lines (50 loc) · 1.58 KB
/
Copy pathmain.py
File metadata and controls
67 lines (50 loc) · 1.58 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
import json
import os
from typing import Dict
import requests
import chain
import config
def handler(event, context):
print(f"event is {event}")
body = json.loads(event["body"])
validate_response = validate_inputs(body)
if validate_response:
return validate_response
prompt = body['prompt']
session_id = body["session_id"]
print(f"prompt is {prompt}")
print(f"session_id is {session_id}")
response, session_id = chain.run(
api_key=get_api_key(),
session_id=session_id,
prompt=prompt
)
return build_response({
"response": response,
"session_id": session_id
})
def validate_inputs(body: Dict):
for input_name in ['prompt', 'session_id']:
if input_name not in body:
return build_response({
"status": "error",
"message": f"{input_name} missing in payload"
})
return ""
def build_response(body: Dict):
return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps(body)
}
def get_api_key():
"""Fetches the api keys saved in Secrets Manager"""
headers = {"X-Aws-Parameters-Secrets-Token": os.environ.get('AWS_SESSION_TOKEN')}
secrets_extension_endpoint = "http://localhost:2773" + \
"/secretsmanager/get?secretId=" + \
config.config.API_KEYS_SECRET_NAME
r = requests.get(secrets_extension_endpoint, headers=headers)
secret = json.loads(json.loads(r.text)["SecretString"])
return secret["openai-api-key"]