Search code examples
pythonopenai-api

Openai trouble with api key definition


I've been trying to make use of langchain openai but i just cant seem to get it to work.

I tried the openai quickstart test:


from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
  ]
)

print(completion.choices[0].message)

But it would give the error:


 line 98, in __init__
    raise OpenAIError(
openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

But after setting the api key like so:

import openai
import os

os.environ["OPENAI_API_KEY"] = "myapikey"

client = openai.OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
  ]
)

print(completion.choices[0].messages)

It would present me with a massive wall of errors:

    File "C:\Users\jasha\Desktop\code\python\gpt\gpt0\gpt0.py", line 9, in <module>enter code here
        completion = client.chat.completions.create(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_utils\_utils.py", line 271, in wrapper
        return func(*args, **kwargs)
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\resources\chat\completions.py", line 659, in create
        return self._post(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 1180, in post
        return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 869, in request
        return self._request(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 945, in _request
        return self._retry_request(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 993, in _retry_request
        return self._request(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 945, in _request
        return self._retry_request(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 993, in _retry_request
        return self._request(
      File "C:\Users\jasha\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_base_client.py", line 960, in _request
        raise self._make_status_error_from_response(err.response) from None
    openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}

Solution

  • First you need to create a ".env" file at your project folder like this

    # Once you add your API key below, make sure to not share it with anyone! The API key should remain private.
    OPENAI_API_KEY=abc123
    

    Then on your code initialization, it reads by default that environment variable:

    from openai import OpenAI

    client = OpenAI()
    # defaults to getting the key using os.environ.get("OPENAI_API_KEY")
    # if you saved the key under a different environment variable name, you can do something like:
    # client = OpenAI(
    #   api_key=os.environ.get("CUSTOM_ENV_NAME"),
    # )
    

    Also make sure you have the library properly installed. Alternatively, you can pass the api key directly but that is not recommended as it exposes it in the code.

    !pip install --upgrade pip
    from openai import OpenAI
    client = OpenAI(api_key='yourapikey')
    
    completion = client.chat.completions.create(
      model="gpt-3.5-turbo",
      messages=[
        {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
        {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
      ]
    )
    
    print(completion.choices[0].message)
    

    After you posted your error log, I finally understood. It says you have no credits on your account. You need a valid key, or buy credits on your account. Check your account usage here.

      raise self._make_status_error_from_response(err.response) from None
        openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}
    

    Source