[Python] How to access ChatGPT with openai key?

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to access openai chatgpt using python using the following code:

    import openai

    KEY = ...
    openai.api_key = KEY

    client = openai.OpenAI()

    response = client.responses.create(
    model="gpt-4.1",
    input="Write a one-sentence bedtime story about a unicorn."
    )

    print(response.output_text)


    However I get the error

    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


    The OpenAI documentation is totally useless as it does not show how to use the key, and asking ChatGPT itself I seem to get an incorrect answer on how to do that.

    So how can I fix this code?

    Continue reading...

Compartilhe esta Página