GitHub Copilot is the latest tool developed by GitHub to automate code completion with the help of OpenAI.
Copilot generates intelligent code suggestions from context, such as docstrings, code comments, function names, and even file names. It then uses all this information to suggest snippets of code that the developer can easily accept by pressing the Tab key on the keyboard.
According to the Copilot website, it understands Python, JavaScript, TypeScript, Ruby, and Go, among dozens of other languages, because it is “trained on billions of lines of common code.” While it’s still in limited technical preview, those interested can sign up to join a waiting list to try it out.
In this article, we’ll explore Copilot’s main features, how to build a simple application using only Copilot, and its advantages and disadvantages.
Copilot’s main features
Copilot’s main feature is its auto-complete function. For example, when a feature description is entered, Copilot completes the entire feature before the user does. While this auto-complete feature is similar to other normal auto-complete features, Copilot is superior.
As the code continues to be written and more comments added, Copilot begins to understand the entire context of the code through its ARTIFICIAL intelligence capabilities. With context, it automatically completes comments in the middle of sentences.
For example, by adding a function, it generates the entire comment and a function; In this case, it figured out that the last function should be a multiplication function, as shown in the figure below.
Another cool feature of Copilot is the ability to see 10 full-page suggestions, rather than a single line, and select the code that best fits.
To do this, press ^ + Return on the Mac keyboard or Ctrl + Enter on Windows to open the suggestion list, as shown in the image below.
Can you build an application using only GitHub Copilot?
Taking advantage of Copilot’s capabilities, I wanted to challenge myself to build a small application using only Copilot. In this challenge, I wanted to create a simple random quote application that also shows the mood of the quote.
To do this, I need to follow some rules to see how much I can benefit from Copilot.
First, if I run into problems, I can’t search online, including using Stack Overflow or documents. This led me to see if it was possible to create working code solely on Copilot’s advice.
The second rule is that I can’t write any new code myself. However, I can write comments, variables, names, and function names to trigger Copilot’s suggestion. Similarly, I can make small edits to the suggested code.
Finally, I can trigger Copilot’s list of suggestions and accept one of them, because this is a built-in feature.
Setting up the project
I chose Next. Js and React to build this project because they are the tools I’m most familiar with and help me better evaluate Copilot’s performance.
Since React makes it easier for developers to build applications, I wanted to see how Copilot manages the React component.
For Next. Js, it provides a good starting point, I don’t have to spend a lot of time setting everything up, and it has built-in backend functionality that makes it not raise CORS errors when calling different API endpoints.
While next.js may seem too powerful for this small project, no additional dependencies need to be installed beforehand, and its integrated, easy-to-use API capabilities make it a good choice for this challenge.
Developing API endpoints
To start developing the API endpoint, I want a quote generator that returns random quotes on GET requests and a sentiment analysis endpoint. The sentiment analysis endpoint needs to receive a string as a query parameter and return an emotion.
Since I don’t know what format the return value is, I let Copilot write it and see what it returns.
/api/get_quote
GET
Request the endpoint
To create two endpoints using next.js, I created two files in the API folder: get_quote.js and get_sentiment. Next. Js creates these endpoints based on the filename. All that’s left is to define handlers in these files, and I let Copilot do that for me.
For the get_QUOTE endpoint, I wrote a comment and chose a good recommendation.
// get random quote from random API
Copy the code
Click on the comments, and Copilot responds with a list of different options for me to choose from.
My choice of advice is the following.
const getQuote = async () => {
const response = await fetch('https://quotes.rest/qod.json')
const quote = await response.json()
return quote.contents.quotes[0].quote
}
Copy the code
The suggestion worked. Almost all of the other suggestions I checked were bad or required an API key I didn’t have. This may be because Copilot is trained on GitHub’s open source code, and some endpoints may be out of date, which can be frustrating.
Also, this endpoint returns the quote for the day, which means that every time I call it, I will receive the same quote for the day, which is not what I expected. Instead, I want to receive a different random quote for each endpoint call.
For the second part of this endpoint, I need to create a handler for this endpoint that calls the functions Copilot has already generated. This handler is the function that Next. Js calls when the client requests the endpoint.
To do this, I declare the name of the function to see if Copilot suggests the correct implementation.
And Copilot gave me another surprise. Everything seemed right.
First, it calls the getQuote function and returns the quote received from the network service. It then saves the quote to a constant and returns the retrieved quote to the client’s JSON. The only thing I need to add is.status(200) to send the 200 status code to the client.
/api/get_sentiment
GET
Request the endpoint
For the get_sentiment feature, I chose Copilot’s suggestion and didn’t need to change anything.
I entered the following.
// determine if the text is positive or negative
Copy the code
Copilot then suggested the following code, which I used.
async function getSentiment(text) {
const response = await fetch(`http://text-processing.com/api/sentiment/`, {
method: "POST",
body: `text=${text}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
const json = await response.json()
return json.label
}
Copy the code
However, for the endpoint part, I had to add.status(200), similar to the get_quote endpoint.
Here’s what I provided to Copilot.
export default async function handler(req
Copy the code
Copilot then suggested the following and I chose it.
export default async function handler(req, res) {
const sentiment = await getSentiment(req.query.text)
res.json({ sentiment })
}
Copy the code
Copilot again managed to give us a working solution, suggesting the right handler, and calculating what the get_sentiment handler needs to return. This proposal looks similar to our previous proposal.
Let’s look at how Copilot handles the generation of the React component.
The React components
For the front end, I need several specified React components and a React controller component with buttons. The two specified components need to display text: one is quote text and the other is testimonials text.
Let’s take a look at how Copilot handles creating these React components.
QuoteTextBox
I’ll start with the QuoteTextBox component, which will display a simple quote; I added the comments below to see what Copilot would suggest.
// React component to show a quote inside a div
const
Copy the code
Copilot recommends a simple function component that I don’t need to modify at all.
const QuoteTextBox = (props) => {
const { quote } = props
return (
<div className="quote-text-box">
<p>{quote}</p>
</div>
)
}
export default QuoteTextBox
Copy the code
SentimentTextBox
To create the emotional text box, I added the following comments.
// React component to show sentiment text inside a div
const
Copy the code
For this text box, finding the right suggestion was a hassle, and I had to scroll through most of the suggestions until I found one that worked with my code.
const SentimentTextBox = (props) => {
// Get sentiment text from props
const sentimentText = props.sentimentText
// Return component
return (
<div className="sentiment-text-box">
{sentimentText}
</div>
)
}
// Export component
export default SentimentTextBox
Copy the code
It’s important to have a clear understanding of what to expect from Copilot, because it’s just a tool, and developers can’t just rely on the first suggestion it gives.
I still need to go back to this component and map the content returned by the API into readable text. For example, if the network service returns NEG, I need to map it as Negative.
A controller component with buttons
I also need a controller component to manage all the logic. The first two React components I created just received the data and rendered it on the screen, but the controller component needed to manage the API calls.
I first typed the following.
// React component that uses QuiteTextBox and SentimentTextBox and APIs to show quotes and sentiment with a button to generate new quotes.
const
Copy the code
Then Copilot came with this suggestion.
const QuoteGenerator = ({quote, sentiment, onClick}) => {
return (
<div>
<QuoteTextBox quote={quote} sentiment={sentiment} />
<button onClick={onClick}>Generate New Quote</button>
<SentimentTextBox sentiment={sentiment} />
</div>
)
}
export default QuoteGenerator
Copy the code
Copilot suggests controller components that seem basic; It lacks API calls and doesn’t use the right item SentimentTextBox. However, Copilot does provide the right structure, it just needs some tweaks to get it done.
Then, I just need to add functionality to the controller component. Instead of passing quote, sentiment, onClick, I asked Copilot to generate them. I also need Hooks to store sentiment and quote data from calling the API.
For Hooks, Copilot immediately knows what I need. To trigger the first Hook suggestion, I started typing a comment and Copilot suggested the correct Hook.
For the second Hook, however, I don’t even need to enter a comment. I accept the suggestion of the first Hook, move to the next line, and Copilot immediately suggests the second Hook.
While the endpoints are correct, I still need to make some changes to make them work. I had to be very specific about what I wanted, or Copilot started suggesting different web services.
I want it to just call the endpoint that has already been created. In addition, when I receive a quote, I need to specifically call the getSentiment endpoint and map the sentiment into human-readable text.
This is my final version, after making a few small changes on my side.
const QuoteGenerator = () => { // Hook to store text in state const [quoteText, setQuoteText] = React.useState('') const [sentimentText, setSentimentText] = React.useState('') // Function to get quotes from API /api/get-quote const getQuote = () => { fetch('/api/get-quote') .then(response => response.json()) .then(json => { setQuoteText(json.quote) getSentiment(json.quote) }) } // Function to get sentiment from API /api/get-sentiment\ const getSentiment = (text) => { fetch('/api/get-sentiment? text=' + text) .then(response => response.json()) .then(json => { setSentimentText(json.sentiment) }) } // Function to be called when user clicks on button to generate new quote const onClick = () => { getQuote() } const mapSentimentToText = { 'neg': 'Negative', 'pos': 'Positive', 'neutral': 'Neutral' } return ( <div> <QuoteTextBox quote={quoteText} /> <SentimentTextBox sentimentText={mapSentimentToText[sentimentText]} /> <button onClick={onClick}>Generate New Quote</button> </div> ) } export default QuoteGeneratorCopy the code
The final application
After experimenting with my simple quote generation application, I found that Copilot provided enough help to create a simple application.
I didn’t have high expectations and initially thought I would need to change a lot of code to make the application work.
However, Copilot surprised me. In some places the advice it gave me was nonsense, but in others it was so good THAT I couldn’t believe Copilot made it.
Advantages and disadvantages of Copilot
To summarize my experience with Copilot, I’ve compiled the pros and cons of using it so you can decide if Copilot is something you can use every day.
The advantages of the Copilot
The main advantage of using Copilot is that it provides auto-complete functionality for steroids. As an autocomplete tool, I believe it is the best on the market today; Nothing is as useful as Copilot.
Copilot also shows developers a variety of ways to solve different problems that may not be obvious. The 10 Suggested feature is great when a code snippet is needed and can often be used in place of Stack Overflow to improve efficiency.
All in all, Copilot is fun to use. For all the tech geeks out there, this is a new thing to play with that makes everyday work a lot more fun.
The disadvantage of Copilot
While its functionality provides greater efficiency, users must remember that it is a tool, not a substitute for human developers. Because Copilot isn’t all-purpose, users can’t rely on it to complete all of their code. Most of its recommendations need to be modified to suit specific needs.
Finally, I note that Copilot recommends using the React class for small components that are not logical, rather than functional components that use Hooks. Because it’s trained on code that’s publicly available on GitHub, Copilot may provide some devalued coding suggestions.
conclusion
GitHub Copilot is not something you can listen to your project and code for you. It won’t take the developer’s job. But it can make coding easier.
GitHub Copilot is good at small tasks; When you start asking it to handle more complex tasks, you tend to get some nonsense. Still, it’s a great tool for beginners and experienced developers alike.
The Post1 Week with GitHub Copilot: Building an application using only Copilot first appeared on The LogRocket blog.