-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda.py
More file actions
38 lines (32 loc) · 1.08 KB
/
lambda.py
File metadata and controls
38 lines (32 loc) · 1.08 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
import json
import boto3
import logging
import os
from openai import OpenAI
# Configure logging
logging.basicConfig(level=logging.INFO)
def lambda_handler(event, context):
try:
# Get prompt from event
prompt = event['prompt']
# Diagnose API Key accessibility
api_key = <your-open-ai-key>> # First element of the list is the API key
if not api_key:
raise ValueError("OpenAI API key not found in environment variables.")
question = event['prompt']
client = OpenAI(api_key=api_key)
# Create chat
messages = [{"role": "user", "content": question}]
completion = client.chat.completions.create(model="gpt-4",messages=messages ,max_tokens=250)
response = completion.choices[0].message.content
return {
"statusCode": 200,
"body": json.dumps({"response": response})}
except Exception as e:
logging.error(f"Error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps({
'error': str(e)
})
}