Share E-Book

Coding with AI (MEAP) (Jeremy C. Morgan)(Z-Library)

Author

AI
Language English

Practical techniques to accelerate software development using generative AI. Let’s get real. You’d like to hand off a lot of tedious software development tasks to an assistant—and now you can! AI-powered coding tools like Copilot can accelerate research, design, code creation, testing, troubleshooting, documentation, refactoring and more. Coding with AI shows you how. Written for working developers, this book fast-tracks you to AI-powered productivity with bite-size projects, tested prompts, and techniques for getting the most out of AI. In Coding with AI you’ll learn how to: Incorporate AI tools into your development workflow Create pro-quality documentation and tests Debug and refactor software efficiently Create and organize reusable prompts Coding with AI takes you through several small Python projects with the help of AI tools, showing you exactly how to use AI to create and refine real software. This book skips the baby steps and goes straight to the techniques you’ll use on the job, every day. You’ll learn to sidestep AI inefficiencies like hallucination and identify the places where AI can save you the most time and effort.

Format PDF
Size 31.6 MB
8
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
Coding with Al Cxamples in Python Jeremy C. Morgan
Page 2
Coding with Al Examples in Python Jeremy C. Morgan MEAF
Page 3
Coding with AI 1. welcome 2. 1 Introduction to Generative AI 3. 2 First steps with Al-assisted coding 4. 3 Design and Discovery 5. 4 Coding the first version of our application 6. 5 Using BlackboxAI to Generate Base Code 7. 6 Generating a software backend with Tabnine 8. 7 Building user interfaces with ChatGPT 9. 8 Building Effective Tests with Generative AI 10. 9 Prompt Engineering 11. 10 Vibe Coding with Cursor
Page 4
welcome Thank you for purchasing the MEAP for Coding with AI. I’m very excited to share it with you. To get the most benefit from this book, you should have skills in software development, and familiarity with Python. It’s helpful to have participated in a software development project in the past. Even if you don’t know Python deeply, you can follow along in the project in this book. These principles can apply to many different languages. I’ve been a software developer and had various roles in development, engineering, and administering servers and the cloud for over twenty years now. The first time I used ChatGPT I felt the way most of us did, like it was some kind of magic and clearly is going to change the world. When I first saw “Generative AI tools for coding” I was immediately skeptical. It was the “code generation” part I had the hardest time with. I worked with IntelliSense for years, which I found incredibly useful. It’s not as much of a code generator as a code checker, and suggestion tool. I also worked with “code generators” over the years that were a waste of time. So immediately my mind went to the years of trying code generators that made bad code really fast. After using Tabnine (the first tool I tried) I quickly found out there’s a world of difference between these tools and the old “code generators” of the past. I’ve used three tools extensively for real software projects over the last year and half. GitHub Copilot, Tabnine, and BlackboxAI. I’ve learned some great tips and tricks and found how to integrate them into my workflow. First and foremost, I want these tools to speed up my workflow. I don’t want tools to write the whole application for me, with code I don’t understand. I don’t want a tool that locks me into complex design patterns. I just want something to augment my abilities, and enable me to build things faster, with fewer bugs. They’ve succeeded with that for me. I wouldn’t want to build a large application without them. In this book I focus on building an application and try to simulate a real
Page 5
development process like the one you use at work, or on an open-source project. I want to show how coding is just a small part of the process where these tools can help. I want this book to enable you to use these tools to supercharge your own work and take away the boring stuff like writing documentation and tests. I want to show how creative prompts can extract exactly what you’re looking for. I want you to be able to debug problems faster and move on to the “fun” stuff like building new features. This is a big turning point in software development, and I’m glad you’re taking this step to embrace these tools. With nearly 2 million developers using GitHub Copilot at the time of this writing, it’s safe to say these tools are gaining mainstream acceptance in the software development industry. The tools and techniques in this book will help you integrate these tools into your daily workflow, and help you become more productive, creative, and most importantly happier as a software developer. Thanks for joining me, let’s build some cool stuff together. Please leave comments in the LiveBook discussion forum and let me know your thoughts, questions, and ideas related to the book, anything that can be made more clear, more useful, or improved in any way! —Jeremy Morgan In this book welcome 1 Introduction to Generative AI 2 First steps with AI-assisted coding 3 Design and Discovery 4 Coding the first version of our application 5 Using BlackboxAI to Generate Base Code 6 Generating a software backend with Tabnine 7 Building user interfaces with ChatGPT 8 Building Effective Tests with Generative AI 9 Prompt Engineering 10 Vibe Coding with Cursor
Page 6
1 Introduction to Generative AI This chapter covers: h How generative AI transforms coding with context-aware help • The evolution of AI dev tools from IDE integration to standalone assistance • LLM fundamentals and code generation capabilitiesAI enhanced workflows from idea to deployment • Success factors for integrating AI into your development process Robots are not going to replace humans, they are going to make their jobs much more humane. Difficult, demeaning, demanding, dangerous, dull - these are the jobs robots will be taking. - Sabine Hauert, Co-founder of Robohub.org What if you could leverage your existing Python expertise alongside AI that understands your code context, anticipates patterns, and generates implementation details while you focus on architecture and design? That's the power of generative AI tools for experienced developers. When I first encountered these tools, I approached them with healthy skepticism. But after integrating them into real production projects over the past year, I've reduced implementation time by approximately 30% while improving code quality and test coverage. It’s likely you’ve already used ChatGPT or Claude for coding. You’ve likely seen GitHub Copilot suggestions pop up in your editor. Or maybe you're just curious about all the AI buzz. If you’re curious about how to leverage these tools to make yourself super productive, you're in the right place. This book is your practical guide to using AI tools to supercharge your coding - no AI expertise required. I'll show you exactly how to use these tools to:
Page 7
w Write code faster • Catch bugs earlier • Create better documentation • Create design diagrams (UML, flowcharts, etc) • Test your code more thoroughly The best part? You don't need a PhD in math, data science, or a background in AI to benefit. I've traveled this road extensively and discovered valuable tricks along the way. Consider this your field guide to these Generative AI coding tools- I'll help you navigate the potholes I've encountered. This book approaches generative AI from a developer's perspective, examining both programming-specific tools and general text generators that belong in your toolkit. We'll look at how these revolutionary tools work and how to leverage them efficiently. Coding will never be the same from now on. Through sharing my insights and experiences, I aim to cut through the hype and sales pitches to focus on what matters: making you a more productive Python developer. These techniques extend to many languages, empowering you to use AI as a tool for innovation, growth, and adding both fun and productivity to your daily work. This book is for: • Python coders who want to incorporate generative AI tools into their existing workflows to code faster and build better applications. • Developers who want to learn best practices for prompting, evaluating, and fine-tuning AI assistants. • Coders curious about paid tools such as GitHub CoPilot, ChatGPT Pro, Tabnine and others. It helps to get a preview before spending money on these tools. This book covers an overview of several popular tools. It includes step by step instructions on installing and using these tools to your advantage. You’ll also learn techniques for crafting effective prompts to get the best results from the tools.
Page 8
1.1 Generative AI for coders Generative AI can benefit you, the coder, in various ways, from code generation and bug detection to documentation and testing. Let’s take a look at the ways Generative AI can assist you in your day-to-day development work. 1.1.1 Code generation and autocompletion Autocompletion of code by software is nothing new. We've been using that for years. Smart autocompletion and code generation, however, are much newer concepts. Large language models can be trained to understand programming languages in depth and generate code snippets in a smart way. What do I mean by smart? They can utilize context and evaluate the code around it. They can generate code based on user inputs or requirements. By leveraging AI tools, developers can quickly prototype ideas or even generate entire applications. Many AI powered tools predict and suggest the next lines of code, as you type. This makes the development process much faster. Let's look at a simple example comparing traditional Python development with an AI-assisted approach: Traditional approach: You need to parse a CSV file, filter rows based on certain criteria, perform calculations, and output the results. You might: 1. Search for the Python CSV module documentation 2. Write boilerplate for file opening and error handling 3. Implement the parsing logic line by line 4. Debug edge cases manually AI-assisted approach: 1. You comment: "# Parse the CSV file at 'data.csv', filter rows where the 'status' column equals 'active', calculate the average of the 'value' column, and write results to 'output.csv'"
Page 9
2. The AI generates a complete implementation, including error handling 3. You review, adjust for specific requirements, and test it. 1.1.2 Bug detection and automated fixes Generative AI analyzes existing code to identify potential bugs, security vulnerabilities and performance issues. AI tools can evaluate context while generating suggestions for the code you're working on. Many of these tools learn as they go. Since they're based off trained models, those models are refined over time to get even better. They detect problems and suggest appropriate fixes, saving you heaps of time. 1.1.3 Documentation generation Writing documentation that is clear, concise, and accurate is crucial for a successful software project to thrive. Without good documentation your users, or other developers will suffer. The greatest software written can be useless without good documentation. But it can be boring to write. Generative AI helps with this by automatically generating human-like documentation for your software. It can provide well-structured and contextually relevant explanations for your code. Not only does it generate documentation for you, but it can help you understand your own code better. 1.1.4 Code refactoring and optimization It's always good to take a second or third look through your code to make sure there aren’t any errors and it is optimized. AI tools make this process much easier. These tools can analyze your code and make suggestions. They can identify redundant code, inefficient algorithms and more. By suggesting improvements, they make refactoring easier and more effective. 1.1.5 Test case generation and mock data creation I'm one of those strange developers who loves testing and building mocking tools. Creating good tests is imperative, and I've found that many of generative AI tools generate great tests and uncover things I haven't thought of. They can be used to generate test cases and create mock data for your
Page 10
application that meets your needs exactly. This improves your testing systems significantly. What generative AI tools am I talking about? Let’s take a look. 1.2 Developer tools landscape Generative AI is still new, yet AI developer tools are already making their mark on the industry. These tools utilize large language models to generate code, provide suggestions, and automate tasks. We’re going to look at two types of tools: Integrated Tooling: Tools that work within Visual Studio Code or other IDEs and function within them. Standalone Tools: Tools with their own interface, usually a website, that don’t interact with an IDE. 1.2.1 Integrated developer tools Generally, standalone tools are meant for many types of general text generation and chat. Think of ChatGPT or Gemini, which have a web interface and are meant for general help. Integrated tools are designed for software development. Integrated tools can often generate code specific to your problem within your code, using your code as context, which we’ll examine in this book. Standalone tools like ChatGPT are better for abstraction and design. The integrated tools we’ll work with in this book all leverage generative AI to help you as you’re writing code. They’ll help you become more productive and show you easier, better ways to write code. Your software can become more efficient, accurate, and performant with the use of these AI tools. Though each tool is different, many of them operate in a similar way. However, there are differences in the tools, and we’ll explore them in this book. By leveraging them properly you will become a better developer. GitHub Copilot
Page 11
GitHub is a well-known name in the developer ecosphere. Most developers today have at least some of their code on GitHub. Microsoft released GitHub CoPilot in October of 2021. It’s an AI-powered code completion tool developed by Microsoft and OpenAI. It uses the OpenAI Codex model. Copilot integrates with popular editors such as Visual Studio Code. It suggests code improvements, completions, comments, and even functions as you type. Copilot is context-aware and provides relevant suggestions in a variety of programming languages and frameworks. Tabnine Tabnine is another popular AI-powered code assistant. Tabnine utilizes GPT- 3 to provide context-aware code suggestions. It integrates with popular code editors such as Visual Studio Code and IntelliJ. It has a local version for offline use as well as a cloud-based version for faster, more accurate suggestions. It has a feature called “Deep Completion” which uses deep learning to provide more accurate suggestions. It is also contextually aware of your code as you write, and will attempt to auto suggest code in the “style” you write in. Blackbox AI Blackbox AI is an AI powered code assistant that works within Visual Studio Code and Jupyter Notebook. It is available for 20+ programming languages, including Python, JavaScript, TypeScript, Go, Ruby, and more. It is an integrated tool but also has a web interface and the ability to ask questions and interact with the backend model from your IDE. 1.2.2 Standalone tools In addition to integrated developer tools, there are several standalone tools and platforms that leverage generative AI for code generation and assistance. These tools operate outside of traditional integrated development environments (IDEs) and usually have a web interface. ChatGPT
Page 12
Surely, you've heard of ChatGPT by now. It's an awesome tool that can help software developers with developing software outlines, code generation, testing, documentation, and more. Its ability to understand and generate text specific to programming languages and frameworks is impressive. GPT4, the large language model used by ChatGPT at the time of this writing, is impressive. It uses a web interface for communication, you can enter a question and get an answer. Most importantly you can have a full discussion with ChatGPT, and it keeps “context” in the threads. There is also a CLI (command line interface) and a full API for ChatGPT, giving you many options for interacting with it, including the ability to build plugins. Google Gemini Google Gemini is similar to ChatGPT from an interface standpoint. You can ask questions and receive answers. It generates software outlines, code, etc., just like ChatGPT. Functionally they are very similar, however in my experience Gemini isn't quite as sophisticated at ChatGPT yet. It will get better and be a great contender. One advantage to Google Gemini is the potential to integrate with other Google Services in their ecosystem--which I can see being a great advantage in the future. Also, Google as a company has access to a lot of source code for training. This could help the model improve over time. Copilot Chat Copilot Chat has a similar interface to ChatGPT and Gemini. It uses several different models from OpenAI and Anthropic on the backend. There are some differences with Copilot Chat, however. Though it has a familiar web based question and answer format like the two mentioned, it's also integrated into Microsoft software. It's available on Desktop and Mobile also. Another difference is that the results focus more on simple requests than complex conversations. When you put in requests, it does a “search” which may perform differently than other text prediction functionality. It also has an
Page 13
“agent” mode so you can give it a list of tasks and it will go through and attempt to perform them step by step. 1.3 How does Generative AI work? Generative AI is a kind of statistical mimicry of the real world, where algorithms “learn” patterns and try to create things from them. If we replace the child with a generative AI model, we must “train” it to create a dog. We need to show it thousands of photos of dogs as examples. The patterns gathered from these pictures help the model learn more about dogs. What shape is a dog? How many legs does it have? What are the odds it has a tail? These are all possibilities with a probability attached to them. These parameters and many more would be used for the model. The tool can use this model to assemble what it thinks a dog will most likely look like. Similarly, when musicians learn to play an instrument, they aren’t just memorizing notes. They learn the patterns, rhythms, and structures of songs. They’ll listen to a particular song enough to “train” themselves on what it’s supposed to sound like. They’ll listen to so many songs that they grasp exactly what a song in general should sound like. Eventually they can play the songs others have written until they sound like the original. Then, of course, they move on to improvisation and creating songs of their own based on this training. Let’s add another layer to this analogy: feedback. Musicians seldom work in a vacuum. How do they know they’re playing the song correctly? By sharing it with others and looking for feedback. If the music teacher nods, they’re doing it right. If the audience applauds, the musician knows the song is successful. If they throw tomatoes, they know something has gone wrong and it needs to be fixed. This is the evaluation and feedback process that contributes to their ongoing “training”. Generative AI for coding is very similar. The model evaluates hundreds of thousands of lines of code or more. It parses the code and looks for patterns used to create working software. With enough training, they develop an idea (this is what software “looks like”) of what new, original code should be.
Page 14
First, training data is created by taking existing source code in many languages and feeding it into a model. This model is evaluated and has layers that look for specific things. One layer checks the type of syntax. Another checks for keywords and how they’re used. And so forth. The final layer determines “this is most likely to be correct and functional source code”. There is an enormous amount of machine learning algorithms that use the model to run through these layers and make determinations. Then, it produces output that is a prediction of what the new software should look like. The tool says, “based on what I know, this is the most statistically likely code you’re looking for”. Then, you the programmer, reach the evaluation point. If you give it a thumbs up, the feedback returns to the model (in many cases, not always) as a correct prediction. If you give it a thumbs down and reject it, that is also tracked. With this continuous feedback, the tool learns what good code should look like. Figure 1.1 illustrates the feedback loop between developer and AI that powers generative coding tools. Unlike traditional code completion, which operates on predefined rules, generative AI creates a continuous improvement cycle which includes five basic steps: 1. Developer input: You provide source code, comments, or natural language requirements 2. Context analysis: The model analyzes patterns in your existing code and requirements 3. Prediction: Based on training data and your specific context, the model generates probable code 4. Developer feedback: You accept, modify, or reject suggestions 5. Model adaptation: The system incorporates your feedback to improve future suggestions This cycle creates a powerful symbiotic relationship—the AI learns your coding patterns and preferences, while you gain implementation speed and exposure to new patterns and techniques that might not have been in your toolkit. Figure 1.1 Integrated tools use a sophisticated system to generate code. It starts with your prompt, and the assistant gathers up documentation, and source code to see if your answer can
Page 15
come from these sources. It makes a best guess at what you’re looking for and generates a response. Your acceptance of these responses helps train the assistant in the future (unless you’ve blocked feedback).
Page 16
(This page has no text content)
Page 17
This is a very high-level explanation of generative AI. It’s the science of predicting what is most likely to be a correct example of something new, based on the data it was trained on. There are features in the algorithms that make things probabilistic instead of deterministic. A deterministic system will always produce the same output given the same input—it follows fixed rules with no randomness or variation. For example, a traditional calculator always gives exactly 4 when you input 2+2. Generative AI models are not deterministic by design. You rarely get the same answer twice. This is intentionally done to create originality in the output. In other words, AI models strive to generate something new rather than regurgitate a copy of something already written. 1.4 What is an LLM, and why should I care? Generative AI for coding and language tools is based on the LLM concept. A large language model (LLM) is a type of neural network that processes and generates text in a human-like way. It does this by being trained on a massive dataset of text, which allows it to learn human language patterns, as we learned in the previous section. It lets LLMs translate, write, and answer questions with text. LLMs can contain natural language, source code, and more. An LLM is a deep learning architecture based on the Transformer model—a significant architectural advancement over previous RNNs (Recurrent Neural Network) and LSTMs (Long Term, Short Memory Network) for sequence processing. Transformers employ multiple layers of self-attention mechanisms that process entire sequences in parallel rather than sequentially, vastly improving training efficiency and enabling the scaling to billions of parameters. Imagine you have a smart system that reads sentences and tries to understand and generate text; this is what a Transformer does. It’s a powerful technology that underpins many advanced applications today, including chatbots, automatic translation, and content generation. Here are the steps a transformer goes through, from input data to results from your prompts.
Page 18
Starting with words: A Transformer begins by looking at your sentence word-by-word, turning each word into numbers that it can understand. Think of each word as getting its own special ID tag. Remembering word order: The Transformer doesn't just see words; it also pays attention to their positions. For example, in the sentence “Jane helps Joe,” it knows "Jane" comes first and "Joe" comes last. It tracks this position information so it can better understand the meaning of your sentence. Understanding context and meaning: Now, the Transformer examines how words relate to each other. It checks each word against all the other words in the sentence. Imagine each word asking every other word, “Hey, how relevant are you to me?” Words that are closely related have stronger relationships, helping the Transformer understand context. For example, in the sentence “The dog chased the cat,” the Transformer understands “dog” and “chased” have a strong connection. Repeating this analysis multiple times: The Transformer doesn't just do this once. It repeats this "checking relationships" step many times, each time learning something deeper about how words in the sentence connect. With each round, the system gains a clearer understanding of the sentence’s overall meaning. Producing the output: After understanding the sentence, the Transformer can now use its knowledge to do different tasks: t Translation: It can convert text from English to another language. • Text generation: It can predict what words might naturally come next. • Code Generation: (What we care about) it can predict the chunk of code that might come next. • Classification: It can recognize the overall meaning or sentiment behind a sentence. Figure 1.2 A transformer takes a sentence and analyzes word positions and relationships to try and extract meaning from the text it sees.
Page 19
(This page has no text content)
Page 20
Transformers excel at grasping relationships between words and concepts in sentences and documents. They greatly enhance tasks that were once challenging, such as natural language translation and understanding complex human questions. When applied to code, these models use attention mechanisms. This helps them assess the importance of various parts of the existing codebase when generating suggestions. Attention mechanisms act like a spotlight, helping AI focus on what matters. Picture yourself in a crowded room. You listen to one conversation while ignoring the noise around you. In coding, when an AI assistant suggests code, it doesn't see every line as equal. It uses attention to identify which parts are most relevant to its task. For instance, if you're writing a function to calculate taxes, the AI will focus more on your tax rate variables. It will pay less attention to unrelated code, like your login system. This way, it makes suggestions tailored to your project instead of generic ones. This ability to zero in on important code is why modern AI coding assistants can offer meaningful suggestions for your specific needs. It’s similar to how skilled developers know which code sections most affect a new implementation. Each transformer layer learns about various code patterns. This ranges from syntax validation to understanding the relationships among functions, classes, and modules. The LLM is trained on vast amounts of text from sources like books, articles, and websites. For example, GitHub Copilot learns from GitHub’s public code base. This allows it to understand the semantic structures of both human language and code. Once deployed, the LLM uses language patterns and context to create human-like text based on a prompt. It generates text and completes sentences to simulate conversation. For code tools, it aims to produce the most likely correct source code based on your input.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List