arrow-left

All pages
gitbookPowered by GitBook
1 of 1

Loading...

5.2. Quickstart with GPT

hashtag
API Key

Create an account for OpenAIarrow-up-right and log in to your account.

Click your icon on the top-right corner and select "View API keys":

OpenAI account menu.

Click the "+ Create new secret key" button and copy the API key:

circle-info

Make sure to save this key in a local file. If you close the dialog without saving, you cannot retrieve the key again, in which case, you have to create a new one.

Create a file openai_api.txt under the directory and paste the API key to the file such that it contains only one line showing the key.

Add openai_api.txt to the file:

circle-info

Do not share this key with anyone or push it to any remote repository (including your private GitHub repository).

hashtag
Using GPT API

Open the terminal in PyCharm and install the OpenAI package:

Create a function called api_key() as follow:

  • #4: specifies the path of the file containing the OpenAI API key.

Retrieve a response by creating a module:

  • #1: the to use.

  • #2: the content to be sent to the GPT model.

  • #3

Print the type of the response and the response itself that is in the JSON format:

  • #1: the response type.

  • #2: the response in the JSON format.

Print only the content from the output:

: creates the chat completion model and retrieves the response.
  • #5: messages are stored in a list of dictionaries where each dictionary contains content from either the user or the system.

  • resourcesarrow-up-right
    .gitignorearrow-up-right
    ChatCompletitionarrow-up-right
    GPT modelarrow-up-right
    OpenAI API key generator.
    .idea/
    venv/
    /resources/openai_api.txt
    (venv) $ pip install openai
    import openai
    
    PATH_API_KEY = 'resources/openai_api.txt'
    openai.api_key_path = PATH_API_KEY
    model = 'gpt-3.5-turbo'
    content = 'Say something inspiring'
    response = openai.ChatCompletion.create(
        model=model,
        messages=[{'role': 'user', 'content': content}]
    )
    <class 'openai.openai_object.OpenAIObject'>
    {
      "choices": [
        {
          "finish_reason": "stop",
          "index": 0,
          "message": {
            "content": "\n\n\"Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle.\"",
            "role": "assistant"
          }
        }
      ],
      "created": 1678893623,
      "id": "chatcmpl-6uNDL6Qfh7MjxpLxH3NW7UPJXS3tN",
      "model": "gpt-3.5-turbo-0301",
      "object": "chat.completion",
      "usage": {
        "completion_tokens": 26,
        "prompt_tokens": 10,
        "total_tokens": 36
      }
    }
    output = response['choices'][0]['message']['content'].strip()
    print(output)
    "Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle."