Pyscript beginner issue - script crashes HA instance

Hello,
I am a total beginner at pyscript but have some python experience. I am trying to use the chatgpt api to get a random notification text to let me know that alarmo is armed.

Sadly calling the service causes my HA to crash completely

Here is my pyscript python file:

import functools

@service
async def chatgpt():
    import requests
    import json
    
    try:
        # Set up the API call
        url = "https://api.openai.com/v1/chat/completions"
        headers = {
            "authorization": "Bearer MY API KEY", 
            "content-type": "application/json"
        }
        data = {
            "model": "gpt-3.5-turbo", 
            "messages": [
                {
                    "role": "user", 
                    "content": "give me a funny 5 sentence text that alexa can say when I arm the house alarm for the night using home assistant"
                }
            ]
        }
        
        # Send the API request and parse the response
        post_func = functools.partial(requests.post, url, headers=headers, data=json.dumps(data))
        response = await hass.async_add_executor_job(post_func)
        response_data = json.loads(response.text)
        notify_text = response_data['choices'][0]['message']['content']
        
        # Send notification to Alexa
        service_data = {"message": notify_text}
        hass.services.call("notify", "alexa_media_echo_dot_4", service_data)
    except Exception as e:
        hass.log.error(f"Error in chatgpt service: {e}")

Any help would be very appreciated!
Thank you

1 Like