Using ChatGPT as Your Programming Assistant

A large language model is basically a machine that can understand and generate text. Depends on how it is trained, sometimes the model can generate something other than text. ChatGPT is such a large language model. It can generate programming code if you prompt it correctly. In this post, you will learn how to make ChatGPT to generate a program for you. Specifically, you will learn

  • How to make ChatGPT to bootstrap your programming project
  • How to use ChatGPT as your programming helper

Get started and apply ChatGPT with my book Maximizing Productivity with ChatGPT. It provides real-world use cases and prompt examples designed to get you using ChatGPT quickly.


Let’s get started.

Using ChatGPT as Your Programming Assistant
Picture generated by the author using Stable Diffusion. Some rights reserved.

Overview

This post is divided into two parts; they are:

  • Start a Programming Project
  • Understanding Code and Generating Function Snippets

Start a Programming Project

Let’s consider a simple project: You want to set up a REST API server that can help you take a “screen capture” of an entire web page of a provided URL. Optionally, the REST API can accept an additional optional parameter of an email address. In that case, the screen capture is not returned but emailed out.

This is a project that involves multiple components. You need something that can act like a REST API server that listens to HTTP requests and responds accordingly. You also need something to fetch a URL and take a screenshot like a normal web browser. There is also a logic in it that depends on whether an email address is provided; the output can be an image file returned, or an email with an attachment is sent out.

If you are unfamiliar with how to create a REST API server or don’t know the tools available, you can ask ChatGPT for help. Simply put down all the detail in your prompt and ask:

I need to create a REST API server that accepts a URL as input, captures the web page screenshot into JPEG format and returns it as output. Optionally, the user may provide an email address as an additional input. In that case, the screenshot should be emailed out instead of returned. Can you help me with this program?

With this, ChatGPT produces the following suggestion:

Certainly! I can help you with that. To create a REST API server that captures web page screenshots and handles optional email functionality, you can use Node.js along with a few additional packages. Here’s an outline of the steps you can follow:

1. Set up a new Node.js project and initialize it using npm:

2. Install the necessary packages. You’ll need express for the API server, puppeteer for capturing screenshots, and nodemailer for sending emails:

3. Create an index.js file and set up the basic server using Express:

4. Inside the /screenshot route, use Puppeteer to capture the web page screenshot and handle the response accordingly:

5. To handle sending emails with the screenshot attachment, add the following code inside the if (email) block:

Make sure to replace 'your-email-service-provider', 'your-email@example.com', and 'your-email-password' with your actual email service provider’s details.

6. Finally, start the server:

Now, when you make a GET request to http://localhost:3000/screenshot?url={URL}, the server will capture a screenshot of the provided URL. If an email address is also provided as email={EMAIL}, the server will send the screenshot as an email attachment instead of returning it directly.

Remember to handle errors and add any necessary error checking or validation based on your requirements.

That’s it! You now have a basic REST API server that captures web page screenshots and optionally sends them via email. Feel free to enhance it further according to your needs.

This is a very detailed result that tells you how to finish this programming task. The response covered all the requirements, but you should notice that when you didn’t specify explicitly in the prompt, ChatGPT will make some design decisions for you, such as what programming language to use.

It is not easy to think for all the details at the first run, but the nature of ChatGPT allows you to provide follow up prompt to revise the answer, such as:

For the above problem, I want to use Python and FastAPI as the web framework and Selenium for the web browser. Can you rewrite this?

The response from ChatGPT now becomes:

Certainly! Here’s a revised version of the solution using Python, FastAPI as the web framework, and Selenium for the web browser automation.

1. Install the necessary packages. You’ll need fastapi, uvicorn for running the server, selenium, and webdriver_manager for managing the web driver:

2. Create a new file called main.py and import the required modules:

3. Define a request model to handle the input data:

4. Create a route to capture the web page screenshot:

5. Start the server using Uvicorn:

Now, when you make a GET request to http://localhost:8000/screenshot?url={URL}, the server will capture a screenshot of the provided URL. If an email address is also provided as email={EMAIL}, you can handle sending the email with the screenshot attachment using the email field in the request.

Remember to handle errors and add any necessary error checking or validation based on your requirements.

Note: This solution assumes you have Chrome installed on your machine. If you’re using a different browser, you’ll need to adjust the webdriver accordingly.

That’s it! You now have a REST API server using Python, FastAPI, and Selenium to capture web page screenshots and handle optional email functionality.

You can see that, you didn’t provide any unnecessary detail in your follow-up prompt except referencing to “the above problem” but ChatGPT can accurately “translated” the Node.js implementation into Python and using the libraries you specified.

It is a fantastic result, although you may still need to polish the code. One example is that the browser screen size is certainly affecting how a web page is rendered, but the size was hard-coded in the above since you didn’t specify that it should be adjustable in your prompt. Another potential reason to polish the generated code is to catch other coding style issues or add defensive measures against security concerns.

In summary, as in the other use case, the more detail you put in the prompt with sufficient clarity is the key to a useful response. In the case of a programming task, it is crucial to lay out the details of

  • What is the objective
  • What is the input and output format
  • What are the tools the program should use
  • What are the different situations that the program may encounter and how should these situations be handled

Understanding Code and Generating Function Snippets

Sometimes, it is not a large program that you want to write but a smaller function. You can ask ChatGPT to generate a function for you using a prompt similar to the above, except you need to specify the output format, such as a function or a class.

Indeed you can also do the other way round, namely, provide a code to ChatGPT and ask it to explain in English. It is sometimes useful, especially to decipher other people’s code. Let’s consider the following example:

Please explain what the following code is doing:

This prompt is very simple: There is only one keyword, “explain”. But pay attention to how you provide the code to ChatGPT: The use of backticks follows the Markdown’s code fence syntax to quote the program. This helps identify which is your instruction and which is not.

While this is not a very long program, ChatGPT explained the code with great verbosity. It also identifies the intent at a high level, namely, it is to calculate the determinant of a matrix. The following is the response:

The code you provided is a recursive implementation of calculating the determinant of a square matrix using the Laplace expansion.

Here’s a step-by-step breakdown of what the code does:

  1. The function det takes two parameters: a pointer to a 2D array (float** a) representing the matrix and the size of the matrix (float k).
  2. It declares some variables: s for sign, ret for the determinant value, and **b as a temporary matrix.
  3. It checks if k is equal to 1. If so, it means we have reached the base case of a 1×1 matrix, and the function returns the single value in the matrix, which is the determinant.
  4. If k is greater than 1, it proceeds with the calculation.
  5. It dynamically allocates memory for the temporary matrix b with size kxk.
  6. It initializes ret to 0.
  7. It enters a loop that iterates over each column of the first row of the matrix a.
  8. Inside the loop, it resets the indices m and n to 0.
  9. It enters a nested loop that iterates over each element of the matrix a.
  10. Inside the nested loop, it sets the element in the temporary matrix b at position m,n to 0.
  11. It checks if the current element is not in the first row (i != 0) and not in the current column (j != c).
  12. If the element is not in the first row or the current column, it copies the value from matrix a to the temporary matrix b at position m,n.
  13. It updates the indices m and n based on the position of the next element in b.
  14. After the nested loop, it calculates the determinant of the submatrix b by recursively calling the det function with the temporary matrix b and size k - 1.
  15. It multiplies the determinant of the submatrix by the sign s (alternating sign).
  16. It multiplies the sign s by -1 to switch the sign for the next iteration.
  17. It adds the product of the sign, the element in the first row (a[0][c]), and the determinant of the submatrix to the running sum ret.
  18. The loop continues to the next column.
  19. After the loop, it frees the memory allocated for each row of the temporary matrix b.
  20. It frees the memory allocated for the temporary matrix b.
  21. Finally, it returns the calculated determinant value ret.

In summary, the code recursively calculates the determinant of a square matrix by performing a Laplace expansion along the first row. It uses a temporary matrix to store the submatrices obtained by excluding the first row and the selected column. The recursion continues until it reaches the base case of a 1×1 matrix.

Follow-up to improve the code

This code is not easy to understand at first glance. There may be a way to make it easier to read. Indeed, ChatGPT can do a good job in this case, with just a very simple follow-up prompt:

Can you rewrite this code for clarity and add comments?

The keywords here are “for clarity” and “add comments”. ChatGPT provides the following in response:

Certainly! Here’s a revised version of the code with comments explaining each step:

I’ve added comments above each significant section of the code to explain what it does. This should make the code more readable and easier to understand.

This version is undoubtedly easier to read.

Besides, you can ask for more. Such as ask to catch bugs or potential security issues in the code. Let’s ask ChatGPT to produce some unit test code:

Can you give me a few unit test cases to ensure this function works well?

Not require any further explanation, the following is the response:

Certainly! Here are a few unit test cases to verify the correctness of the determinant function:

Test Case 1: 2×2 Matrix

Test Case 2: 3×3 Matrix

Test Case 3: 4×4 Matrix

These test cases cover matrices of different sizes (2×2, 3×3, and 4×4) and include positive, negative, and zero determinant values. By comparing the calculated determinant values with the expected outputs, you can verify if the determinant function is working correctly.

But it is quite obvious, the unit test code missed a corner case: The 1×1 matrix. This reveals that ChatGPT is not always perfect. You should only use it as your assistant not replacement. You should always verify the result.

Summary

In this post, you saw how ChatGPT can help you with programming. Not only can it generate code as part of its response to your question, but also it can figure out the intention of a code that you provided. Specifically, you have learned that:

  • You can use ChatGPT to generate the initial code for your software project, or generate test code for a function
  • You can ask ChatGPT to explain the code to you
  • You can make use of ChatGPT to refactor and clean up code

Maximize Your Productivity with ChatGPT!

Maximizing Productivity with ChatGPT

Let Generative AI Help You Work Smarter

...by leveraging the power of advanced AI from ChatGPT, Google Bard, and many other tools online

Discover how in my new Ebook:
Maximizing Productivity with ChatGPT

It provides great tips with examples of all kinds to make you the boss of AI robots
for brainstorming, editing, expert helper, translator, and much more...

Make AI work for you with my latest book


See What's Inside

3 Responses to Using ChatGPT as Your Programming Assistant

  1. Avatar
    Vincent June 26, 2023 at 12:24 am #

    Send a full pdf learning materials for the chatGPT please

    • Avatar
      James Carmichael June 26, 2023 at 8:33 am #

      Thank you for your suggestion! If you sign up for our newsletter, we will keep you informed of new content related to ChatGPT.

  2. Avatar
    Johan Widén June 26, 2023 at 5:21 pm #

    For a very streamlined way to analyze source code using llm, see https://simonwillison.net/2023/Jun/18/symbex/

Leave a Reply