Chapter 5: Using Blackbox AI to generate base code
The chapter introduces AI-assisted application development as a collaboration in which AI speeds up coding while the developer supplies judgment and direction.
After this chapter you will be able to
- Human and AI coding partnership. Explain how the author divides coding work between generative AI and the developer: AI supplies suggestions, scaffolding, and boilerplate, while the developer provides context, direction, corrections, and architectural judgment.
- AI-led initial coding. Explain that the beta application will use Blackbox AI as the lead programmer to generate most of the initial code, as a demonstration of the tool's capabilities rather than a generally recommended approach.
- Developer review and selection. Explain that, even in this AI-led experiment, the developer remains the final reviewer and would normally accept some suggestions and reject others.
- Application development toolchain. Describe the author's setup for building the application, including the editor, Python, SQLite browser, and AI coding extensions.
- Publicly available exam questions. Explain why the app can use an existing database of technician exam questions: HAM radio test questions and answers are publicly available, unlike those for tech certifications.
- Questions database creation. Describe how to create a SQLite database in DB Browser, import the downloaded questions CSV as a table named questions, and save and inspect the imported data.
- Unique question IDs. Explain why the ID column is marked PK and U after importing the questions table.
- Specific database connection prompts. Explain why the initial comment produced an unhelpful suggestion and how naming SQLite and the database file improved the prompt.
- Iterative chat request refinement. Describe why the author switched to Blackbox chat for a larger code request and how follow-up prompts narrowed the result to a direct SQLite connection in the existing class.
- Database-to-page data flow. Trace how question records move from the database query through a Flask view to the index template. Explain why the database function must return its results rather than print them.
- Flask template error resolution. Distinguish the missing render_template import from the later template-location error, and describe how the author resolved each.
- Single-purpose database connection. Justify the planned refactoring of connect_to_database() so it only connects and passes back a cursor, rather than also querying and displaying data.
- MVP scope for Questions. Explain why the author removes database updates and data validation from the Questions class at this stage while retaining the functionality needed to deliver questions.
- Separate database connection responsibility. Justify moving connection handling out of Questions and into a reusable DatabaseConnection class, even though the AI’s suggested code answered the request.
- SQLite context manager lifecycle. Trace what the DatabaseConnection context manager does when entering and leaving a with block.
- Root route database flow. Trace what happens when the root page is requested: the route handler connects to the SQLite database, fetches questions through the Questions class, and passes the data to the template.
- Unique question set selection. Explain how the proposed function builds a test question set and what it does when too few questions are available.
- IDs instead of full records. Explain why the application changes its question query to return IDs rather than full records, and how those IDs will be used.
- Test Session State Requirements. Explain what the database must track while a student takes a 35-question practice test.
- Three Table Test Design. Describe the roles of the sessions, question_sets, and existing questions tables, including how a question set connects a session to questions in the main pool.
- New session record requirements. State what the author asks Blackbox AI to provide when creating a session record: a unique session_id incremented from the last ID and initial values of zero for questions_correct and questions_incorrect.
- Existing database connection reuse. Explain why the author revises Blackbox AI’s first Session class and what change they ask for.
- Session invocation and question set. Describe how the author asks Blackbox AI to create a session from APP.py, and explain why that alone does not complete session creation.
- Session-linked question set. Trace how creating a test session leads to selecting 35 random questions and recording their IDs with the session ID in the question_sets table. Describe how the detailed Blackbox AI prompt requests this refactoring.
- Generated code integration fixes. Explain why the pasted code needed changes to its imports, Questions instantiation, and database setup. Describe the section's preference for injecting the database pathname and reusing the existing cursor rather than specifying the pathname or creating connections in multiple places.
- Test session database verification. Explain how the sessions and question_sets tables are checked to verify the initial test-session setup, and what those checks do not yet establish.
- Human and AI partnership. Explain how AI-generated code and human judgment worked together: Blackbox AI accelerated the initial implementation, while the developer refined the architecture, added code, and overrode suggestions when beneficial.
What it builds on
- Stubbing out our application (chapter 4) · The application skeleton developed earlier provides context for continuing the project.
- Flask application structure (chapter 4) · The application structure whose template location is corrected here.
Section by section
Introduction
The chapter introduces AI-assisted application development as a collaboration in which AI speeds up coding while the developer supplies judgment and direction.
- Human and AI coding partnership: Explain how the author divides coding work between generative AI and the developer: AI supplies suggestions, scaffolding, and boilerplate, while the developer provides context, direction, corrections, and architectural judgment.
Why it matters: This partnership lets you benefit from faster coding without surrendering responsibility for whether the code fits your application.
Key terms: scaffolding, boilerplate code, separation of concerns, human judgment
5.1 Application development with generative AI tools
The section frames an experiment in generating most of a beta application's initial code with Blackbox AI while keeping the developer responsible for reviewing it.
- AI-led initial coding: Explain that the beta application will use Blackbox AI as the lead programmer to generate most of the initial code, as a demonstration of the tool's capabilities rather than a generally recommended approach.
Why it matters: This explains why the chapter relies more heavily on generated code than the author normally recommends. - Developer review and selection: Explain that, even in this AI-led experiment, the developer remains the final reviewer and would normally accept some suggestions and reject others.
Why it matters: It keeps the chapter's aggressive use of AI distinct from handing responsibility for the code to the tool. - Choice of coding tool: State that readers following the project do not need to buy all three named tools; the author says the same techniques can be used with any one of them or with a different preferred tool.
Why it matters: A reader can follow the project without paying for every tool mentioned.
Key terms: Blackbox AI, lead programmer, smart assistant, initial code, suggestions, final reviewer, IDE, GitHub Copilot, Tabnine
5.2 Setting up the development environment
The section identifies the author's development setup and explains why readers can follow along on Windows, Linux, or Mac.
- Application development toolchain: Describe the author's setup for building the application, including the editor, Python, SQLite browser, and AI coding extensions.
Why it matters: This identifies the tools used in the application work that follows. - Cross-platform setup choice: Explain why readers can follow along on Linux or Mac instead of Windows and why the author chose DB Browser for SQLite.
Why it matters: Readers need not reproduce the author's Windows setup to follow the instructions.
Key terms: Visual Studio Code, Python, DB Browser for SQLite, GitHub Copilot Extension, Blackbox.AI Extension, Tabnine Pro Extension, cross-platform, SQLite browser, Windows 11, Linux
5.3 Developing core features
This section introduces the question dataset that will supply the HAM radio practice test app.
- Publicly available exam questions: Explain why the app can use an existing database of technician exam questions: HAM radio test questions and answers are publicly available, unlike those for tech certifications.
Why it matters: This explains where the app’s practice questions can come from.
Key terms: HAM radio test, technician exam, database of questions
5.3.1 Creating the database
This subsection shows how to create a SQLite questions database from a CSV file and make each question ID a unique primary key.
- Questions database creation: Describe how to create a SQLite database in DB Browser, import the downloaded questions CSV as a table named questions, and save and inspect the imported data.
Why it matters: These steps turn the supplied question data into the database the application will use. - Unique question IDs: Explain why the ID column is marked PK and U after importing the questions table.
Why it matters: A unique primary key gives each question a dependable identifier for later database work.
Key terms: DB Browser for SQLite, CSV, questions, Write changes, ID, PK, U, primary key
5.3.2 Connecting to our database
The section uses Blackbox AI to turn a stubbed database-connection method into a more suitable suggestion by adding context and refining the request in chat.
- Specific database connection prompts: Explain why the initial comment produced an unhelpful suggestion and how naming SQLite and the database file improved the prompt.
Why it matters: Specific context helps a coding assistant suggest code for the database you actually have. - Iterative chat request refinement: Describe why the author switched to Blackbox chat for a larger code request and how follow-up prompts narrowed the result to a direct SQLite connection in the existing class.
Why it matters: A useful AI suggestion may still need follow-up instructions to fit your project’s choices and the method’s intended role.
Key terms: Blackbox, comment, prompt, SQLite, data/questions.db, Blackbox AI chat, SQLAlchemy, sqlite3, Questions class, connect_to_database
5.3.3 Calling our database from the frontend
This section uses Blackbox AI suggestions to display database records on a Flask page, resolves two integration errors, and explains why the database method should later be narrowed to one responsibility.
- Database-to-page data flow: Trace how question records move from the database query through a Flask view to the index template. Explain why the database function must return its results rather than print them.
Why it matters: Seeing records on the page verifies the connection, query, and display path together. - Adapting generated example code: Explain why the Blackbox AI example could not be pasted in unchanged and how the author adapted it to the application’s actual class and method.
Why it matters: AI-generated examples are useful only when their assumptions match the code being built. - Flask template error resolution: Distinguish the missing render_template import from the later template-location error, and describe how the author resolved each.
Why it matters: Separating an import error from a file-location error makes the failed page render easier to diagnose. - Single-purpose database connection: Justify the planned refactoring of connect_to_database() so it only connects and passes back a cursor, rather than also querying and displaying data.
Why it matters: A focused connection method can support later database actions without accumulating unrelated responsibilities.
Key terms: questions, connect_to_database(), Flask, Jinja2, template, Blackbox AI, get_data(), render_template, Jinja, templates
5.3.4 Refactoring our Questions class
The section refactors AI-generated code for an MVP by narrowing the Questions class’s responsibilities and moving reusable SQLite connection handling into a context manager.
- MVP scope for Questions: Explain why the author removes database updates and data validation from the Questions class at this stage while retaining the functionality needed to deliver questions.
Why it matters: An AI-generated design can include useful features that still do not belong in the current version. - Contextual Blackbox code requests: Describe how the author gives Blackbox relevant code context when asking for connection error handling, and explain how a more specific prompt improves the request.
Why it matters: Providing the actual code and desired behavior makes an AI suggestion more relevant to the task. - Separate database connection responsibility: Justify moving connection handling out of Questions and into a reusable DatabaseConnection class, even though the AI’s suggested code answered the request.
Why it matters: Code that answers a prompt can still need a design change to fit the application. - SQLite context manager lifecycle: Trace what the DatabaseConnection context manager does when entering and leaving a with block.
Why it matters: The with block gives callers a cursor while centralizing connection setup and cleanup.
Key terms: minimum viable product (MVP), Questions class, fetch_questions(), Blackbox chat, Include Code in Active File, cursor object, separation of concerns, DatabaseConnection, context manager, with statement
5.3.5 Modifying our entry point (App.py)
This section updates the Flask entry point to fetch questions through the refactored database classes and display them at the application’s root page.
- Root route database flow: Trace what happens when the root page is requested: the route handler connects to the SQLite database, fetches questions through the Questions class, and passes the data to the template.
Why it matters: This is how the application gets database questions onto its web page. - Flask entry point setup: Describe how App.py sets up the root route and starts the Flask application when run directly.
Why it matters: The entry-point setup determines which function handles the home page and when the server starts. - Refactoring visible result: Explain why the updated entry point can show the same page while improving the application’s internal structure.
Why it matters: The unchanged display shows that the refactoring improved the code without changing what users currently see.
Key terms: index(), DatabaseConnection, cursor, Questions class, fetch_data, data, App.py, Flask, @app.route(), root path
5.3.6 Pulling a set of questions
The section uses Blackbox AI to select 35 unique, roughly randomized question IDs, then narrows the database query to return only the IDs the application needs.
- Unique question set selection: Explain how the proposed function builds a test question set and what it does when too few questions are available.
Why it matters: A test session needs 35 distinct questions rather than a dump of every question or repeated selections. - IDs instead of full records: Explain why the application changes its question query to return IDs rather than full records, and how those IDs will be used.
Why it matters: Keeping an ID-only set supports a test session without fetching full question records before they are needed. - Review of AI-generated SQL: Describe why AI-generated SQL needs review and name the query practices highlighted in this section.
Why it matters: A working AI suggestion still needs a developer to check whether its SQL fits the application’s data and usage.
Key terms: question_set, set, question ids, get_question_set, IDs, full record, get_all_questions(), get_question_set(), SELECT *, AI-generated SQL
5.3.7 Creating a test session in the database
This section defines the database structure needed to track a practice-test session and shows how to create its new tables in DB Browser for SQLite.
- Test Session State Requirements: Explain what the database must track while a student takes a 35-question practice test.
Why it matters: These requirements explain why the practice test needs more than a way to pull random questions. - Three Table Test Design: Describe the roles of the sessions, question_sets, and existing questions tables, including how a question set connects a session to questions in the main pool.
Why it matters: The three-table design separates a particular test attempt from the pool of available questions. - SQLite Table Creation Steps: Describe how the section creates and saves the sessions and question_sets tables in DB Browser for SQLite, including their primary keys.
Why it matters: Creating the tables and writing the changes makes the proposed structure available for the test-session code.
Key terms: test session, state, 35 questions, correct answer, sessions, question_sets, questions, session_id, question_id, main question pool
5.3.8 Creating code for the test session
The section uses Blackbox AI to draft session-creation code, adapt it to the application’s database connection, and call it from APP.py while noting that a session also needs a question set.
- New session record requirements: State what the author asks Blackbox AI to provide when creating a session record: a unique session_id incremented from the last ID and initial values of zero for questions_correct and questions_incorrect.
Why it matters: These are the initial values the generated session-creation code is meant to produce. - Existing database connection reuse: Explain why the author revises Blackbox AI’s first Session class and what change they ask for.
Why it matters: The generated code needs to fit the application’s existing structure rather than duplicate it. - Session invocation and question set: Describe how the author asks Blackbox AI to create a session from APP.py, and explain why that alone does not complete session creation.
Why it matters: Calling the Session class is only part of creating the test session described by the application design.
Key terms: session_id, questions_correct, questions_incorrect, Session class, DatabaseConnection, session.py, APP.py, question set, session
5.3.9 Generating a question set
The section uses Blackbox AI to generate a session-linked question set, then refactors and checks the generated code.
- Session-linked question set: Trace how creating a test session leads to selecting 35 random questions and recording their IDs with the session ID in the question_sets table. Describe how the detailed Blackbox AI prompt requests this refactoring.
Why it matters: The session association identifies which questions belong to a particular test. - Generated code integration fixes: Explain why the pasted code needed changes to its imports, Questions instantiation, and database setup. Describe the section's preference for injecting the database pathname and reusing the existing cursor rather than specifying the pathname or creating connections in multiple places.
Why it matters: Generated code still needs to fit the application's classes and database configuration. - Initial question-set checks: Describe what the successful application load, browser list of question IDs, and console output show, and why the author still calls for further verification.
Why it matters: Seeing expected output is an initial check, not proof that the full implementation succeeded.
Key terms: create_session(), create_question_set, get_question_set(), question_sets, session_id, Questions, Session, database pathname, self.cursor, DatabaseConnection
5.3.10 Verifying our test session was created
The section checks database records to confirm that a first test session and its question set were created, while noting that the application is not yet complete.
- Test session database verification: Explain how the sessions and question_sets tables are checked to verify the initial test-session setup, and what those checks do not yet establish.
Why it matters: Checking both tables distinguishes a successfully created session and question set from a fully working test application.
Key terms: sessions table, question_sets table, session_id, 35 questions
5.3.11 Conclusion
This conclusion recaps the application foundation built with Blackbox AI and explains why human judgment remained essential.
- Human and AI partnership: Explain how AI-generated code and human judgment worked together: Blackbox AI accelerated the initial implementation, while the developer refined the architecture, added code, and overrode suggestions when beneficial.
Why it matters: The example treats AI as a development partner, not a substitute for developer judgment. - Application foundation and limits: Describe what the application can do at this point and why the author still calls it a foundation rather than a usable finished application.
Why it matters: It distinguishes a working application foundation from a complete user-ready application.
Key terms: Blackbox AI, human judgment, maintainability, separation of concerns, database schema, test sessions, random question sets, test state
5.4 Summary
Where this is used later
- Using Copilot for test generation (chapter 8) · The application’s database.
- Creating a session and our first bug (chapter 6) · The application creates test sessions in the database.
- (chapter intro) (chapter 6) · The application has a generated question set to associate with a test session.
- Refactoring session creation (chapter 6) · Further refactoring continues the practice of improving the application rather than simply accepting generated code.
Concepts explained in this chapter
- Blackbox AIBlackbox AI is an AI-powered software development assistant that provides code generation, code assistance, and related programming support.
- code generationCode generation is the automated production of source code from natural-language instructions, existing code, or other structured input.
- separation of concernsSeparation of concerns is a design principle that assigns distinct responsibilities to separate software components so they do not overlap unnecessarily.
- cursorA database cursor is an object that executes database statements and accesses their results through an established connection.
- question setA question set is a grouped collection of questions assembled for a particular assessment or practice activity.
- context managerA context manager is an object protocol that performs setup on entering a managed block and cleanup when the block exits.
- SQLiteSQLite is a lightweight embedded relational database engine that stores a database in a local file.
- sessionA session is a recorded instance of a student's practice test that tracks its questions, answers, and result counts.
- database connectionA database connection is an active communication link through which software accesses a database and submits operations.
- render_templaterender_template is a Flask function that renders a named template with supplied context data and returns the resulting response content.
- contextContext is the surrounding conversation history, instructions, assumptions, and other information that determines the meaning and intent of an input.
- refactoringCode refactoring is the restructuring of existing source code to improve its internal organization without changing its externally observable behavior.
- promptA prompt is natural-language input that instructs a generative artificial-intelligence system what response or result to produce.
- sqlite3The Python standard-library module that provides an interface to SQLite databases.
- JinjaJinja2 is a Python templating engine that renders text or HTML from templates containing expressions and control directives.
- setA set is an unordered collection data structure that stores unique elements and supports efficient membership operations.
- FlaskFlask is a lightweight Python web framework for building web applications and HTTP services.
- databaseA database is a system that stores organized information and retrieves records matching explicit queries.
- boilerplate codeBoilerplate code is repetitive, standard code required for common implementation tasks but contributing little distinctive application behavior.
- generative modelingArtificial intelligence that produces new content, such as text, source code, documentation, or tests, from learned patterns and input instructions.
- scaffoldApplication scaffolding is the automated generation of a basic application structure, including starter code, files, and directories.
- GitHub CopilotCopilot Chat is a conversational generative AI tool that answers questions and assists with software-related tasks across web, desktop, and mobile interfaces.
- PythonPython is a general-purpose, dynamically typed programming language commonly used for application development, automation, and data science.
- TabnineTabnine is an AI-powered programming assistant that provides context-aware code suggestions in supported code editors.
- context managementContext management is the deliberate organization of codebase information and prompts so an AI system receives relevant context for producing useful outputs.
- parameterized queryA parameterized query is a database query whose values are supplied separately from the query structure to reduce injection risk and improve safe query execution.
- ai suggestionAn AI suggestion is a software-development recommendation or proposed code generated by an artificial intelligence system.
- unique constraintA unique constraint is a database rule requiring values in a column or column group to be distinct across records.
- prompt engineeringPrompt engineering is the systematic design and refinement of instructions and context provided to an AI system to elicit desired outputs.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
