How To Send Request To ChatGPT And Get Response In Python

In this article, I will tell you how to create a chatbot using 3 python libraries step by step. One python library is OpenAI, the other library is revChatGPT, and the last library is chatgpt.

1. Prerequisites.

  1. Before you can use the python libraries to access ChatGPT, you should create an account on openai.com.
  2. You can use Google or Microsoft account to login, but you should get the access token after you login with those account.
  3. After you login, click the Personal item on the top right corner of the page.
  4. Then click the View API keys menu item in the drop-down menu list.
  5. You can create new secret key or see the created secret key in the API keys page.
  6. But you can not see the created API keys after you create them, so you should remember them or recreate one if you forget.

2. Use OpenAI Python API To Create A Chatbot.

  1. Run the command pip install openai to install the openai python library.
  2. After you successfully install openai in your OS, run the command pip show openai to confirm the installation.
    (MyPython) C:\Users\Zhao Song>pip show openai
    Name: openai
    Version: 0.26.5
    Summary: Python client library for the OpenAI API
    Home-page: https://github.com/openai/openai-python
    Author: OpenAI
    Author-email: support@openai.com
    License:
    Location: c:\users\zhao song\appdata\roaming\python\python39\site-packages
    Requires: aiohttp, requests, tqdm
    Required-by:
  3. Now you can import the openai python library in python code or interactive console.
    >>> import openai
  4. But before you can use it, you need to assign the openapi secret key to openai to identify your openai account.
    >>> openai.api_key = "sk-*********jO7"
  5. Otherwise, it will throw the error openai.error.AuthenticationError.
    openai.error.AuthenticationError: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions.
  6. Now you can call the openai python methods to make a chatbot like below.
    import openai
    
    openai.api_key = "sk-*************1jO7"
    
    #engine_str = "text-davinci-003"
    
    engine_str = "text-ada-001"
    
    question = "please write a story about a dog"
    
    response = openai.Completion.create(
    
        engine=engine_str,
    
        prompt=question,
    
        max_tokens=1024,
    
        n=1,
    
        stop=None,
    
        temperature=0.5
    
    
    )
    
    print(response["choices"][0]["text"])

3. Use Python Library revChatGPT To Create A Chatbot.

  1. Open a terminal and run the command pip install revChatGPT to install the library.
    (MyPython) C:\Users\Zhao Song>pip install revChatGPT
    Defaulting to user installation because normal site-packages is not writeable
    Collecting revChatGPT
      Downloading revChatGPT-2.3.14-py3-none-any.whl (28 kB)
    Requirement already satisfied: requests in c:\users\zhao song\appdata\roaming\python\python39\site-packages (from revChatGPT) (2.28.2)
    Collecting asyncio
      Downloading asyncio-3.4.3-py3-none-any.whl (101 kB)
         ---------------------------------------- 101.8/101.8 kB 34.5 kB/s eta 0:00:00
    Collecting httpx
      Downloading httpx-0.23.3-py3-none-any.whl (71 kB)
         ---------------------------------------- 71.5/71.5 kB 18.2 kB/s eta 0:00:00
    Collecting OpenAIAuth==0.3.2
      Downloading OpenAIAuth-0.3.2-py3-none-any.whl (4.3 kB)
    Collecting httpcore<0.17.0,>=0.15.0
      Downloading httpcore-0.16.3-py3-none-any.whl (69 kB)
         ---------------------------------------- 69.6/69.6 kB 23.1 kB/s eta 0:00:00
    Collecting rfc3986[idna2008]<2,>=1.3
      Downloading rfc3986-1.5.0-py2.py3-none-any.whl (31 kB)
    Requirement already satisfied: certifi in c:\programdata\anaconda3\envs\mypython\lib\site-packages (from httpx->revChatGPT) (2022.6.15)
    Collecting sniffio
      Downloading sniffio-1.3.0-py3-none-any.whl (10 kB)
    Requirement already satisfied: idna<4,>=2.5 in c:\users\zhao song\appdata\roaming\python\python39\site-packages (from requests->revChatGPT) (3.4)
    Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\zhao song\appdata\roaming\python\python39\site-packages (from requests->revChatGPT) (3.0.1)
    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\zhao song\appdata\roaming\python\python39\site-packages (from requests->revChatGPT) (1.26.12)
    Collecting anyio<5.0,>=3.0
      Downloading anyio-3.6.2-py3-none-any.whl (80 kB)
         ---------------------------------------- 80.6/80.6 kB 20.2 kB/s eta 0:00:00
    Collecting h11<0.15,>=0.13
      Downloading h11-0.14.0-py3-none-any.whl (58 kB)
         ---------------------------------------- 58.3/58.3 kB 27.4 kB/s eta 0:00:00
    Installing collected packages: rfc3986, asyncio, sniffio, h11, OpenAIAuth, anyio, httpcore, httpx, revChatGPT
      WARNING: The script httpx.exe is installed in 'C:\Users\Zhao Song\AppData\Roaming\Python\Python39\Scripts' which is not on PATH.
      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
    Successfully installed OpenAIAuth-0.3.2 anyio-3.6.2 asyncio-3.4.3 h11-0.14.0 httpcore-0.16.3 httpx-0.23.3 revChatGPT-2.3.14 rfc3986-1.5.0 sniffio-1.3.0
  2. Run the command pip show revChatGPT in the terminal to show the library detailed install information.
    (MyPython) C:\Users\Zhao Song>pip show revChatGPT
    Name: revChatGPT
    Version: 2.3.14
    Summary: ChatGPT is a reverse engineering of OpenAI's ChatGPT API
    Home-page: https://github.com/acheong08/ChatGPT
    Author: Antonio Cheong
    Author-email: acheong@student.dalat.org
    License: GNU General Public License v2.0
    Location: c:\users\zhao song\appdata\roaming\python\python39\site-packages
    Requires: asyncio, httpx, OpenAIAuth, requests
    Required-by:
  3. Then you can run the below python source code to use the above python library to send text to ChatGPT and get response.
    # import the ChatBot library.
    from revChatGPT.V1 import Chatbot
    
    # config the chatbot with the provided configuration data.
    chatbot = Chatbot(config={
    
      #"email": "happyzhaosong@gmail.com",
      #"password": "JBTuan))*632"
      "access_token": "fsdsfs(************)"
    })
    
    print("Chatbot: ")
    
    prev_text = ""
    
    for data in chatbot.ask(
        "Hello world",
    ):
        message = data["message"][len(prev_text) :]
        print(message, end="", flush=True)
        prev_text = data["message"]
    print()

4. Use Python Library chatgpt To Create A Chatbot.

4.1 How To Install Python chatgpt Library.

  1. To use the chatgpt library, you will first need to install the library using pip install chatgpt.
  2. Open a terminal and run the command pip install chatgpt then it will download and install the chatgpt library into your python environment like below.
    (MyPython) C:\Users\Zhao Song>pip install chatgpt
    Defaulting to user installation because normal site-packages is not writeable
    Collecting chatgpt
      Downloading chatgpt-2.2212.0-py3-none-any.whl (24 kB)
    Collecting tls-client
      Downloading tls_client-0.1.8-py3-none-any.whl (34.9 MB)
         ---------------------------------------- 34.9/34.9 MB 100.5 kB/s eta 0:00:00
    Collecting rich
      Downloading rich-13.3.1-py3-none-any.whl (239 kB)
         ---------------------------------------- 239.0/239.0 kB 152.5 kB/s eta 0:00:00
    Collecting pygments<3.0.0,>=2.14.0
      Downloading Pygments-2.14.0-py3-none-any.whl (1.1 MB)
         ---------------------------------------- 1.1/1.1 MB 113.0 kB/s eta 0:00:00
    Collecting markdown-it-py<3.0.0,>=2.1.0
      Downloading markdown_it_py-2.2.0-py3-none-any.whl (84 kB)
         ---------------------------------------- 84.5/84.5 kB 131.8 kB/s eta 0:00:00
    Collecting mdurl~=0.1
      Downloading mdurl-0.1.2-py3-none-any.whl (10.0 kB)
    Installing collected packages: tls-client, pygments, mdurl, markdown-it-py, rich, chatgpt
      WARNING: The script pygmentize.exe is installed in 'C:\Users\Zhao Song\AppData\Roaming\Python\Python39\Scripts' which is not on PATH.
      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
      WARNING: The script markdown-it.exe is installed in 'C:\Users\Zhao Song\AppData\Roaming\Python\Python39\Scripts' which is not on PATH.
      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
      WARNING: The script chatgpt.exe is installed in 'C:\Users\Zhao Song\AppData\Roaming\Python\Python39\Scripts' which is not on PATH.
      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
    Successfully installed chatgpt-2.2212.0 markdown-it-py-2.2.0 mdurl-0.1.2 pygments-2.14.0 rich-13.3.1 tls-client-0.1.8
  3. After the installation is complete, you can begin using the library.

4.2 How To Invoke ChatGPT In Python Source Code.

  1. Now you can use the python chatgpt library to send request to the ChatGPT server and get response.
  2. You can run the below source code to invoke ChatGPT library to create a chat bot example.
    import sys
    
    import chatgpt
    
    from chatgpt import Conversation
    
    chatbot = chatgpt.Conversation()
    
    response = chatbot.chat("how to use chatgpt in python")
    
    print(response.json)
    
    

4.3 How to fix ModuleNotFoundError: No module named ‘requests’.

  1. When you run the above source code, if it shows the error message ModuleNotFoundError: No module named ‘requests’, that means the python requests module is not installed.
    >>> import chatgpt
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\Zhao Song\AppData\Roaming\Python\Python39\site-packages\chatgpt\__init__.py", line 4, in <module>
        from .chatgpt import *
      File "C:\Users\Zhao Song\AppData\Roaming\Python\Python39\site-packages\chatgpt\chatgpt.py", line 6, in <module>
        from requests import HTTPError
    ModuleNotFoundError: No module named 'requests'
  2. To fix this error, you can run the command pip install requests to install the requests library.
    (MyPython) C:\Users\Zhao Song>pip install requests
    Defaulting to user installation because normal site-packages is not writeable
    Collecting requests
      Using cached requests-2.28.2-py3-none-any.whl (62 kB)
    WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/idna/
    Collecting idna<4,>=2.5
      Downloading idna-3.4-py3-none-any.whl (61 kB)
         ---------------------------------------- 61.5/61.5 kB 466.3 kB/s eta 0:00:00
    Requirement already satisfied: certifi>=2017.4.17 in c:\programdata\anaconda3\envs\mypython\lib\site-packages (from requests) (2022.6.15)
    Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\users\zhao song\appdata\roaming\python\python39\site-packages (from requests) (1.26.12)
    Collecting charset-normalizer<4,>=2
      Downloading charset_normalizer-3.0.1-cp39-cp39-win_amd64.whl (96 kB)
         ---------------------------------------- 96.5/96.5 kB 305.7 kB/s eta 0:00:00
    Installing collected packages: charset-normalizer, idna, requests
      WARNING: The script normalizer.exe is installed in 'C:\Users\Zhao Song\AppData\Roaming\Python\Python39\Scripts' which is not on PATH.
      Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
    Successfully installed charset-normalizer-3.0.1 idna-3.4 requests-2.28.2

4.4 How to fix chatgpt.errors.ChatgptError: No access token. Please, provide an access_token or email and password through the constructor/config file.

  1. When you run the above example source code, you may encounter the chatgpt.errors.ChatgptError: No access token. Please, provide an access_token or email and password through the constructor/config file.
  2. To fix the chatgpt.errors.ChatgptError: No access token. Please, provide an access_token or email and password through the constructor/config file error, you need to provide an access token to ChatGPT.
  3. You can get an access token by registering an account at the official ChatGPT website.
  4. Once registered, you can generate an access token. This token needs to be added to the configuration file of the ChatGPT module.
  5. You can create a config.json file and input the below content in the file.

    {
        "email": "your-email-address",
        "password": "your-password"
        "access_token": "the-access-token"
    }
  6. And then create the chatbot conversation and pass in the above configure file path.
    chatbot = chatgpt.Conversation(config_path="./config.json")
  7. You can also pass in the access token to the Conversation class using the access_token parameter.
    chatbot = chatgpt.Conversation(access_token="your-chatgpt-access-token")

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.