From the course: Building a Project with the ChatGPT API

Solution: Build a dialog using chat completion - ChatGPT Tutorial

From the course: Building a Project with the ChatGPT API

Solution: Build a dialog using chat completion

(upbeat techno music) - [Instructor] So, how did you do? Let's compare. Let's look at how I saw the challenge of building the foundation of a multi-turn conversation with an AI assistant. The first step is to install the necessary libraries. I've installed these libraries already, so I won't run this code again. Next, I imported the OS and OpenAI modules, or libraries. You're familiar with the OpenAI Python library. The OS module provides access to operating system dependent functionality. I'll use it to access the API key stored as an environment variable in an external dotenv file. Scroll down. On line one, here I am retrieving the OpenAI API key from the environment variable and storing it in OpenAI.API_key. This variable is used to authenticate to the API. Next, here in cell 16, I'm storing the name of the model I'm using in the model variable, which I'll use later. Let's scroll down. Notice cells 17 and 18. In the following few sections, you'll see that I've designed my code to be modular with reusable code defined in functions. The first function here in cell 17 is generate_prompt, which is used to set the context for the AI assistant. It helps us compose a tweet based on an AI-generated summary of a website. The next function here in cell 18 is called get_completion, which calls the ChatCompletions API, passes in the request, and gets a response back. You'll notice that this function takes one parameter called temperature. The value for temperature will default to zero if a value is not passed in. In this function, you'll see that I'm storing the completion response in the response variable. I'm passing in the model and prompt in the messages and temperature parameters. Next, here on line 10, I'm printing the content from the response. Scroll down, here on line 19, I'm calling the get_completion function and passing in zero for the temperature. I could have left this blank since the temperature will default to zero. I've executed this cell already, and the response is shown below. The assistant replies with, "Sure, I can help with that. Please provide me with the website you would like me to summarize." If you scroll down, I have a few examples that illustrate temperature, and this is just for extra credit. I encourage you to explore different temperature values on your own. And that's all there is to it. We now have the foundation for our application.

Contents