I was working using my Openai's API key in Visual studio 2022 as setting the key as an environment variable after making a .env file and it was working perfectly. Somehow I needed to work on Google Colab. How do I do it? Should I use the Secrets option or should I import that .env file in my Colab notebook? In both ways please explain it to me.
I added my .env file to the drive and mounted my drive to Colab notebook and using the os library and dotenv library set my key but it gives None. When I used the Secrets option, I get error that your key should be set as an environment variable in OPENAI_API_KEY. Below I am giving both codes when I used os library and when I used Secrets.Using OS library:
import openaiimport osfrom dotenv import load_dotenvload_dotenv()openai.api_key = os.getenv("OPENAI_API_KEY")from openai import OpenAIclient = OpenAI()def chat(order, prompt, model = "gpt-3.5-turbo"): actor = "You are trained to analyze and " + order +" .If you are unsure you can say `not sure`." response = client.chat.completions.create( messages=[ {"role": "system", "content": actor}, {"role": "user", "content": prompt} ], model=model, max_tokens=1, n=1, stop=None, temperature=1 ) response_text = response.choices[0].message print(response_text)
Using Secrets:
import openaifrom google.colab import userdataapi_key = userdata.get("OPENAI_API_KEY")openai.api_key = api_keyfrom openai import OpenAIclient = OpenAI()def get_completion(order, prompt, model = "gpt-3.5-turbo"): actor = "You are trained to analyze and " + order +" .If you are unsure you can say `not sure` or recommend the user to summarize manually." response = client.chat.completions.create( messages=[ {"role": "system", "content": actor}, {"role": "user", "content": prompt} ], model=model, max_tokens = 150, n=1, stop=None, temperature = 1 ) response_text = response.choices[0].message