Statistics
2
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-26

AuthorJeremy C. Morgan

This book empowers you to harness AI’s full potential and improve your coding. My goal is to help you save time by developing features faster and getting higher quality code as a result. The book covers practical uses of tools such as GitHub Copilot, Tabnine, Blackbox AI, and ChatGPT. You’ll see how these technologies can help you code faster, solve problems better, and cut down on repetitive tasks. You won’t just learn how to use these tools but also discover when and why to use them in your development process. Who should read this book This book is for Python developers who want to use generative AI tools in their work. But the techniques can be applied to many other languages as well. If you’re an experienced developer aiming to increase your productivity or a team lead exploring AI tools for your team, you’ll find helpful guidance and real-world examples. While some knowledge of Python is helpful, developers of all skill levels will learn how these tools can enhance their skills instead of replacing them.

Tags
No tags
ISBN: 1633437272
Publisher: Manning Publications
Publish Year: 2025
Language: 英文
Pages: 338
File Format: PDF
File Size: 8.0 MB
Support Statistics
¥.00 · 0times
Text Preview (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.

M A N N I N G Jeremy C. Morgan Examples in Python Coding with AI
Common Prompt Types and Their Best Uses Prompt types Zero shot Few shot Open ended Constraned Structured Simple queries Examples + query Creative tasks Limited scope Formatted output
Coding with AI
(This page has no text content)
MANN I NG Shelter ISland Jeremy C. Morgan Coding with AI Examples in Python
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com © 2025 Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid- free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. ∞ Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 ISBN 9781633437272 Printed in the United States of America The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Development editor: Doug Rudder Technical editor: Richard J. Vaughan Review editor: Dunja NikitoviÊ Production editor: Kathy Rossland Copy editor: Lana Todorovic-Arndt Proofreader: Keri Hales Typesetter: Tamara ŠveliÊ SabljiÊ Cover designer: Marija Tudor
I dedicate this book to my amazing family. Without them, this book would not have been possible.
vi brief contents Part 1 Getting started with AI-assisted coding .................1 1 ■ Introducing generative AI 3 2 ■ First steps with AI-assisted coding 27 Part 2 Building applications with AI assistance ..............55 3 ■ Design and discovery 57 4 ■ Coding the first version of our application 78 5 ■ Using Blackbox AI to generate base code 101 6 ■ Generating a software backend with Tabnine 149 Part 3 Advanced AI development techniques .................. 177 7 ■ Building user interfaces with ChatGPT 179 8 ■ Building effective tests with generative AI 210 9 ■ Prompt engineering 244 10 ■ Vibe coding with Cursor 285
vii contents preface xii acknowledgments xiv about this book xvi about the author xix about the cover illustration xx Part 1 Getting started with AI-assisted coding ..1 1 Introducing generative AI 3 1.1 Generative AI for coders 4 Code generation and autocompletion 4  ■  Bug detection and automated fixes 5  ■  Documentation generation 5 Code refactoring and optimization 5  ■  Test case generation and mock data creation 6 1.2 Developer tools landscape 6 Integrated developer tools 6  ■  Standalone tools 7 1.3 How does generative AI work? 8 1.4 What is an LLM, and why should I care? 10 1.5 Why do these tools sometimes get it wrong? 12 How LLMs differ from databases 13  ■  Training phase problems 13  ■  Misinterpreting context 14
viii contents 1.6 The potential of LLMs 15 1.7 Generative AI vs. code completion 15 Other types of generative AI 16  ■  Why coders care about generative AI 17 1.8 Project workflow with AI assistance 17 Ideation and planning 18  ■  Code generation and assistance 20 Code review and analysis 20  ■  Testing and debugging 22 Documentation and content generation 22 1.9 Choosing the right generative AI tools 22 Data quality and availability 22  ■  Integration with development workflows 23  ■  Quality assurance 23  ■  Keeping up with evolving tools 23  ■  Shift in focus 24 1.10 Don’t fear the rise of AI 24 1.11 Go forth and code! 25 2 First steps with AI-assisted coding 27 2.1 What is GitHub Copilot? 28 How GitHub Copilot works 28  ■  Interacting with GitHub Copilot 31 2.2 Common patterns 35 2.3 Context is everything 35 2.4 What is NLP? 36 2.5 A simple Python project 37 Preparing your development environment 39  ■  Creating the application 42  ■  Side quest: Testing the function speed 47 Part 2 Building applications with AI assistance ..55 3 Design and discovery 57 3.1 Getting to know ChatGPT 58 3.2 The problem 58 3.3 Creating the right prompt 59 3.4 Measuring the effect on the design process 60 3.5 A design document created with ChatGPT 61 3.6 Software design document: HAM radio license practice test application 63
ixcontents 3.7 Digging deeper 68 System overview (section 2) 68  ■  Technical stack (section 5) 70 3.8 Generating user stories for our project 72 Defining roles in prompts 73  ■  The output: User stories document 73  ■  Analyzing the output 75  ■  User stories document in detail 75 4 Coding the first version of our application 78 4.1 Stubbing: Building the skeleton of your application 79 A simple code example 80 4.2 Extracting requirements from the design 81 Step 1: Extract the requirements using ChatGPT 82 Step 2: Gathering requirements from Gemini 83 4.3 Setting up our development environment 86 4.4 Flask application structure 89 4.5 Stubbing out our application 91 4.6 Running our application 97 5 Using Blackbox AI to generate base code 101 5.1 Application development with generative AI tools 102 5.2 Setting up the development environment 103 5.3 Developing core features 103 Creating the database 103  ■  Connecting to our database 106 Calling our database from the frontend 113  ■  Refactoring our Questions class 119  ■  Modifying our entry point (App.py) 126 Pulling a set of questions 128  ■  Creating a test session in the database 133  ■  Creating code for the test session 136 Generating a question set 139  ■  Verifying our test session was created 146  ■  Conclusion 147 6 Generating a software backend with Tabnine 149 6.1 Creating a session and our first bug 150 6.2 Creating an index page 161 Persisting the session 166  ■  Refactoring session creation 169 Refactoring our question set method 171  ■  Creating an end session function that ends the test 174
x contents Part 3 Advanced AI development techniques ... 177 7 Building user interfaces with ChatGPT 179 7.1 Getting our strategy from our AI tools 180 ChatGPT Results 182  ■  Gemini Results 185 Blackbox AI results 188 7.2 Creating our templates 191 7.3 Describing the flow of our application 194 Creating an overall design 198  ■  Drafting HTML based on our wireframes 203  ■  The final UI for our application 207 8 Building effective tests with generative AI 210 8.1 Why use generative AI for testing? 211 8.2 What are unit tests? 212 8.3 The tools we’ll use for Python testing 212 Github Copilot 213  ■  Tabnine 213  ■  Blackbox AI 213 8.4 Writing unit tests with generative AI 213 unittest or pytest? 213  ■  Using Copilot for test generation 214 Using Tabnine for test generation 230  ■  Applying Blackbox AI for test generation 234  ■  Which tool should you use for testing? 242 9 Prompt engineering 244 9.1 Understanding prompt engineering 245 Why prompt engineering matters 248 9.2 Understanding the anatomy of a prompt 249 9.3 Crafting the ultimate prompt 254 Prompt engineering principles 255 9.4 Fundamental prompt types 257 Zero-shot prompting 257  ■  Few-shot prompting 258 Open-ended prompts 259  ■  Constrained prompts 260 Using iterative prompts 261  ■  Structured prompts 263 9.5 Advanced prompt types 265 Chain-of-thought prompting 265  ■  Recursive prompting 269 Context manipulation 272  ■  Instruction refinement 274 Output control 277  ■  Wrap up 279
xicontents 9.6 Prompt techniques for programmers 279 Examples 279 10 Vibe coding with Cursor 285 10.1 What is vibe coding? 286 10.2 What is Cursor, and why is it different? 287 The interface 287  ■  Project-wide context and customization 288 10.3 First concept 288 10.4 The initial prompt to build our game 289 10.5 Cursor basics 290 Giving feedback 291  ■  Adding context 292  ■  Selecting a mode 293  ■  Model selection 294  ■  MAX mode 295 10.6 Results from the first prompt 295 10.7 Running our game for the first time 296 10.8 Making changes to our game 298 index 309
xii preface I’ve been blessed to make a living doing something I’d do as a hobby. For decades, cod- ing has been my passion. When I started programming, learning was tough—hardcopy books, dogpile.com, and newsgroups were our lifelines. You had to really want it. My journey began with Perl, watching HTML come to life for the first time. Although tedious and frustrating, the results had me hooked. PHP changed everything, letting me build applications in days rather than months. The real high came from watching users’ eyes light up when their clunky spreadsheet workflow transformed into a sleek HTML form overnight. Back then, documentation was scarce, and Google was in its infancy. Without old head programmers helping us, we may never have finished anything. My code got the job done but was often ugly behind the scenes, something I’d be proud of on Monday and embarrassed about by Friday. I gravitated toward backend development—its deterministic nature felt more intu- itive. Like everyone else, I sought better ways to build code faster. Our team briefly adopted a rapid-application-development generator that promised miracles. It worked initially, cranking out features at warp speed. Then reality hit: when requirements changed, we spent twice as long untangling the generated mess. Less than a year later, we abandoned it. Lesson learned: Fast development is only fun if you never plan on maintaining it. Python was my next breakthrough—offering speed without sacrificing readability or maintainability. Later, C# provided similar efficiency gains. But I never matched the raw speed of that ill-fated PHP generator. Then generative AI crashed the party. With ChatGPT and GitHub Copilot, I tackled a C# side project. I watched AI spit out boilerplate and tests before my pizza cooled.
xiiipreface Work I’d blocked off for two weekends wrapped up before Sunday brunch. It felt like rediscovering that early PHP generator magic—only faster, with guardrails. Now the hype cycle is in full swing. Vibe coding promises amazing software from a few prompts. This is genuinely possible—but beware creating complex code nobody under- stands. It’s fine for a weekend project but not ideal for mission-critical applications. This book aims to use this silver bullet properly. AI can enhance productivity, but heavy reliance brings trouble. You’ll learn to manage expectations: AI can generate about 80% of an application, but the remaining 20% is up to you. You don’t need to be taught how to vibe code. Instead, you’ll learn how each tool works and when to use it effectively. Today’s tooling—cloud IDEs, auto-generated tests, and AI pair-programmers—means shipping faster with fewer tradeoffs than ever before. Whether you’re an old head like me who remembers the struggles or a beginner fac- ing different challenges, these tools will accelerate your journey. The best time to build was yesterday; the second-best time is right now.
xiv acknowledgments Although very fun to write, this book was a lot of work. I hope you’ll enjoy what we’ve put together here. There are quite a few folks I’d like to thank for helping me along the way. First, I would like to thank my wife Amber. You’ve always believed in me and gave up so much time with me to get this done. You also provided lots of helpful encour- agement, even if it was, “Go work on that book! Hurry up!” I love you and I’m eternally thankful. Also, thanks to my mother Robbin Fariss and father Rocky Morgan, and my stepfa- ther Russ Peckham and stepmother Tina Chambliss. They all raised me to believe in myself and not quit when times get tough. I never heard them say, “You can’t do that,” no matter what crazy ambition I had. They shaped me into who I am today. And thanks to  my four children Austin, Hayley, Rory, and Kendra, and  grandchildren Brynlee, Aubrie, Wittly, Aurora, Brantley, Cody, and Octavia. You are the folks who keep me grounded and motivated to keep going strong every day. You are my why and part of the reason I had to write this book.  At Manning, I’d like to thank my development editor Doug Rudder for all the patience and guidance throughout this process. I’ll never match your knowledge of writing, but I appreciate you lending it so often. And your way of delivering feedback is fantastic. I’d like to thank my acquisitions editor Michael Stephens for your guidance, knowledge, and tough conversations. Without your help, this book wouldn’t be nearly as good. In addition, thanks to the entire production team who helped shepherd this book into its final format. Thanks to the reviewers who have taken time to read my manuscript at various stages and help me with feedback: Tom Massey, Sean Collins, Xavier Morera, Lars Klint, Steve
xvacknowledgments Buchanan, Dave McCollough, Santosh Yadav, Danny Nunez, Steven Senkus, Renjith Ramachandran, and Roger Rizk. I’d also like to thank Roger for all the tips and tricks with Blackbox AI to make sure we got the most from it. I’d like to thank the team from Tabnine for all their help with questions and guidance. Also, thanks to Abir Qasem, Advait Patel, Anandaganesh Balakrishnan, Arik Leo- nidov, Asterios Raptis, Bin Hu, Christopher Forbes, Clifford Thurber, David Allen Blubaugh, David Goldfarb, Debasish Ghosh, Emre Sevinç, Estera Kot, Franklin Neves, Giampiero Granatella, Greg Grimes, Ian Walker, Ioannis Atsonios, Jacek Sokulski, Jason Nelson, Jesús Juárez, Jiri Pik, John Abela, Julien Pohie, Manohar Sai Jasti, Michael Bright, Mike Metzger, Nadeem Lalani, Nakul Pandey, Ninoslav Cerkez, Oliver Korten, Pasquale Zirpoli, Paul Soh, Piotr Jastrzebski, Ramani Natarajan, Rambabu Posa, Sam- uel Lawrence, Sanjana Kandi, Saurabh Aggarwal, Shiroshica Kulatilake, Simeon Leyz- erzon, Sriram Macharla, Steve Steiner, Thomas Jaensch, Tony Holdroyd, Vlad Bezden, Vladislav Bilay, Walter Alexander Mata López, and William Whitehead. Your sugges- tions helped make this a better book. Special thanks to technical editor Richard Vaughan. Richard is a highly experienced engineer, who is CTO at Purple Monkey Collective—a research focused startup deliver- ing machine learning and cloud guidance services. Finally, I’d like to thank my mother, Robbin Farris, for letting me use her work com- puter back in the 1980s and get hooked on tech. But most importantly, I am grateful she has always believed in me, telling me my entire life that anything is possible.
xvi about this book This book empowers you to harness AI’s full potential and improve your coding. My goal is to help you save time by developing features faster and getting higher quality code as a result. The book covers practical uses of tools such as GitHub Copilot, Tab- nine, Blackbox AI, and ChatGPT. You’ll see how these technologies can help you code faster, solve problems better, and cut down on repetitive tasks. You won’t just learn how to use these tools but also discover when and why to use them in your development process. Who should read this book This book is for Python developers who want to use generative AI tools in their work. But the techniques can be applied to many other languages as well. If you’re an expe- rienced developer aiming to increase your productivity or a team lead exploring AI tools for your team, you’ll find helpful guidance and real-world examples. While some knowledge of Python is helpful, developers of all skill levels will learn how these tools can enhance their skills instead of replacing them. How this book is organized: A road map The book consists of 10 chapters: ¡ Chapter 1 covers generative AI for coding. It explains how large language mod- els predict and create code. It also distinguishes between integrated tools, such as GitHub Copilot, and standalone tools, such as ChatGPT. These technologies boost developer productivity by automating routine tasks, letting developers focus more on problem-solving and design.
xviiabout this book ¡ Chapter 2 introduces AI-assisted coding with GitHub Copilot. It explains how Copilot works and shows different ways to use it, such as code completion, chat, and prompts. The chapter also includes a practical Python project that analyzes word frequency in text. This project shows developers how to integrate Copilot into their workflow effectively. ¡ Chapter 3 describes how to use ChatGPT for project design and discovery. It explains how to write effective prompts. These prompts help set AI roles, create detailed software design documents, and develop user stories. The focus is on a Python web application that offers randomized practice tests for HAM radio license exams. ¡ Chapter 4 demonstrates how to begin coding an application with AI assistance by extracting requirements from design documents using both ChatGPT and Gem- ini, setting up a Python virtual environment, creating a structured Flask appli- cation with AI-suggested file organization, and implementing code stubs that provide the skeleton of the application before adding functionality. ¡ Chapter 5 demonstrates how to build a functional Flask application for HAM radio practice tests using Blackbox AI, showing how to connect to an SQLite database, implement separation of concerns through refactoring, create data- base sessions to track test progress, generate random question sets, and build the core functionality, while highlighting when human intervention is necessary to improve AI-generated code. ¡ Chapter 6 focuses on building a question engine for the HAM radio practice test application, using Tabnine to troubleshoot bugs in session management, imple- ment persistent browser cookies to maintain user state across page refreshes, refactor code to properly handle question sets associated with specific sessions, and create a simple user interface that allows users to end test sessions and start new ones. ¡ Chapter 7 demonstrates how to create a user interface for the HAM radio prac- tice test application using AI tools such as ChatGPT, Google Gemini, and Black- box AI to generate design strategies, wireframes, flowcharts, and functional HTML/CSS code, transforming a basic application into one with a professional appearance, while following proper Flask templating practices. ¡ Chapter 8 explores how to use generative AI tools to create effective test suites for Python applications, comparing GitHub Copilot, Tabnine, and Blackbox AI for generating both unittest and pytest code, setting up in-memory databases for testing isolation, and demonstrating how each tool approaches the creation of test fixtures, assertions, and database interactions with varying degrees of context awareness. ¡ Chapter 9 explains prompt engineering techniques for working with generative AI tools, covering basic concepts like context, clear instructions, and examples. In addition, it explores advanced approaches such as chain of thought prompting,
xviii about this book recursive prompting, context manipulation, instruction refinement, and output control, before concluding with 30 specific prompt techniques tailored for soft- ware developers. ¡ Chapter 10 explores vibe coding, a fast-evolving approach to programming based on natural language prompts. It further demonstrates how to build a retro arcade-based game using this technique. I recommend reading the chapters in order, as each builds on concepts from previous chapters. However, experienced developers may choose to focus on specific chapters addressing their immediate needs. About the code This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/coding-with-ai. The complete code for the examples in the book is available for download from the Manning website at https://www.manning.com/books/coding-with-ai, and from GitHub at https://github .com/JeremyMorgan/HAM-Radio-Practice-Web. liveBook discussion forum Purchase of Coding with AI includes free access to liveBook, Manning’s online read- ing platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/ coding-with-ai/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dia- logue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.