Teach you how to use Python to call ChatGPT-3.5-API

A few days ago, OpenAI opened the api interface of two new models, gpt-3.5-turbo and gpt-3.5-turbo-0301, which are specially designed for chatting.

ChatGPT is powered by gpt-3.5-turbo, OpenAI’s most advanced language model.

From the above sentence, we can know that the official website of chat.openai.com is a service provided by the gpt-3.5-turbo model, and now the official release of the call interface of this model allows ordinary developers like us to directly Use this model that has attracted hundreds of millions of users in your own applications/services.

Next, I will introduce how to use Python to quickly play with gpt-3.5-turbo.

Run first, then understand

First of all, you need to have an openai account. I won’t say much about how to register. There are many online tutorials, and they are very detailed. If you have any questions, you can add me on WeChat:

Visit the following page, log in to the openai account, and create an api key.

# api keys create page
https://platform.openai.com/account/api-keys

The next step is very simple. Install openai’s official Python SDK. What you need to pay attention to here is to install the latest version of openai. The official recommended version is 0.27.0.

pip install openai==0.27.0

Directly upload the request code:

import openai
import json

# At present, you need to set up a proxy to access the api
os.environ["HTTP_PROXY"] = "Own proxy address"
os.environ["HTTPS_PROXY"] = "Own proxy address"


def get_api_key():
    # You can implement it according to your actual situation
    # Take me as an example, I have an openai_key file in json format
    '''
    {"api": "your api keys"}
    '''
    openai_key_file = '../envs/openai_key'
    with open(openai_key_file, 'r', encoding='utf-8') as f:
        openai_key = json. loads(f. read())
    return openai_key['api']

openai.api_key = get_api_key()

q = "Implemented with python: prompt to manually input 3 different 3-digit intervals, calculate the intersection of these 3 intervals after the input is completed, and output the result interval"
rsp = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
        {<!-- -->"role": "system", "content": "A senior algorithm engineer with 10 years of experience in Python development"},
        {<!-- -->"role": "user", "content": q}
    ]
)

Code Analysis:

  • The get_api_key() function is a method written by me to read api keys from a file. I store it in an openai_key file in json format. You can change it to your own method, or even write it directly into the code (although not recommended, but really the easiest).
  • q is the requested question
  • rsp is the result returned after sending the request
  • Parameters in openai.ChatCompletion.create
  • model is the name of the model used, which is a string, and the latest model can be directly set to gpt-3.5-turbo
  • messages is the text content of the request. It is a list. Each element type in the list is a dictionary. The specific meaning is as follows:

  • The content returned by the program running, we can see from the response content, the response content is a json string,

We can obtain relevant information directly through the following methods:


return message content

rsp.get("choices")[0]["message"]["content"]

Role

rsp.get("choices")[0]["message"]["role"]

Question + answer total length

rsp.get("usage")["total_tokens"]

Other information can also be obtained through similar methods.

  • Test ChatGPT to answer the code running status. It can be seen that there is no problem with the code logic and operation, and the comments are in place.

Achieving multiple rounds of dialogue

How to achieve multiple rounds of dialogue?

The message passed in the gpt-3.5-turbo model call method openai.ChatCompletion.create is a list, and each element in the list is a dictionary, including roles and content. We only need to store each round of dialogue, and then each time Ask questions and bring previous questions and answers.

Rendering

  • It can be seen that I first asked “1 + 1 = how many”, and then asked “why is this”, ChatGPT will recognize the new question as “why 1 + 1 = 2” based on the previous question.
  • Continue to ask what are the daffodil numbers later, and then ask “how to write a python program to identify these numbers”, ChatGPT will also recognize the new question as “how to write a python program to identify these daffodil numbers” based on the previous question, and Give corresponding answers.
  • Implementation code
import openai
import json
import os

os.environ["HTTP_PROXY"] = "http://127.0.0.1:7890"
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:7890"

# get api
def get_api_key():
    # You can implement it according to your actual situation
    # Take me as an example, I have an openai_key file in json format
    '''
    {"api": "your api keys"}
    '''
    openai_key_file = '../envs/openai_key'
    with open(openai_key_file, 'r', encoding='utf-8') as f:
        openai_key = json. loads(f. read())
    return openai_key['api']
openai.api_key = get_api_key()



class ChatGPT:
    def __init__(self, user):
        self.user = user
        self.messages = [{<!-- -->"role": "system", "content": "A senior algorithm engineer with 10 years of experience in Python development"}]
        self.filename="./user_messages.json"

    def ask_gpt(self):
        # q = "Implemented with python: prompt to manually input 3 different 3-digit intervals, calculate the intersection of these 3 intervals after the input is completed, and output the result interval"
        rsp = openai.ChatCompletion.create(
          model="gpt-3.5-turbo",
          messages = self. messages
        )
        return rsp.get("choices")[0]["message"]["content"]


    def writeTojson(self):
        try:
            # Check if the file exists
            if not os.path.exists(self.filename):
                with open(self. filename, "w") as f:
                    # Create a file
                    pass
            # read
            with open(self. filename, 'r', encoding='utf-8') as f:
                content = f. read()
                msgs = json. loads(content) if len(content) > 0 else {<!-- -->}
            # append
            msgs.update({<!-- -->self.user : self.messages})
            # write
            with open(self. filename, 'w', encoding='utf-8') as f:
                json. dump(msgs, f)
        except Exception as e:
            print(f"Error code: {<!-- -->e}")
            

def main():
    user = input("Please enter user name: ")
    chat = ChatGPT(user)
    
    # loop
    while 1:
        # limit the number of conversations
        if len(chat. messages) >= 11:
            print("******************************")
            print("********Forcibly reset dialog**********")
            print("******************************")
            # write previous information
            chat. writeTojson()
            user = input("Please enter user name: ")
            chat = ChatGPT(user)
            
        # ask questions
        q = input(f"【{<!-- -->chat.user}】")
        
        # logical judgment
        if q == "0":
            print("********Exit program**********")
            # write previous information
            chat. writeTojson()
            break
        elif q == "1":
            print("****************************")
            print("********Reset dialog**********")
            print("****************************")
            # write previous information
            chat. writeTojson()
            user = input("Please enter user name: ")
            chat = ChatGPT(user)
            continue
            
        # question-answer-record
        chat.messages.append({<!-- -->"role": "user", "content": q})
        answer = chat. ask_gpt()
        print(f"【ChatGPT】{<!-- -->answer}")
        chat.messages.append({<!-- -->"role": "assistant", "content": answer})


if __name__ == '__main__':
    main()

Code Analysis:

  • The ChatGPT class contains three functions:
  • The __init__ initialization function initializes three instance variables, user, messages, and filename (the current user, message list, and file path for storing records).
  • The ask_gpt function sends all historical messages + latest questions of the current user to gpt-3.5-turbo and returns the response result.
  • The writeTojson function records the previous access data of the current user when ending/resetting the user.
  • The main function, the program entry function, the user enters the user name and enters the circular dialogue with ChatGPT, enters 0 to exit the program, enters 1 to reset the user, both exit and reset will match the current user’s previous access data records with the json file.
  • Since the maximum number of tokens for a single request of gpt-3.5-turbo is: 4096, the number of conversations is limited in the code.

Last

Well, that’s all for today’s content sharing. If you are also interested in Python technology, here is a Python full set of learning materials, including learning route, software, source code, Videos, interview questions, etc., are all organized by myself during my studies. It is not easy to organize, please like and share~

WeChat scans the CSDN official certification QR code below to get it

1. Learning routes in all directions of Python

The route of all directions in Python is to organize the commonly used technical points of Python to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you learn more comprehensively.

2. Python learning software

If a worker wants to do a good job, he must first sharpen his tools. The commonly used development software for learning Python is here!

3. Python introductory learning video

There are also many learning videos suitable for getting started with 0 basics. With these videos, you can easily get started with Python~

4. Python exercises

After each video lesson, there are corresponding practice questions, you can test the learning results haha!

5. Python actual combat case

Optical theory is useless. You have to learn to type codes along with it, and then you can apply what you have learned in practice. At this time, you can learn from some practical cases. This information is also included~

6. Python interview materials

After we have learned Python, we can go out and find a job with the skills! The following interview questions are all from top Internet companies such as Ali, Tencent, Byte, etc., and some Ali bosses have given authoritative answers. After reading this set of interview materials, I believe everyone can find a satisfactory job.


Friends who need it can WeChat scan the CSDN official certification QR code below to get it for free! !