ChatGPT: Initial Experiments: Better Comments
THE CRAFT™️ EXPERIMENT :: WEEK 2 :: POST 3
< Previous Page | Page 4 of 5 | Next Page >
-
Please brainstorm some creative ways that comments can be adapted to A.I. Current programmers use comments to communicate with either themselves (reminders) or with other programmers. Since the CRAFT experiment involves communicating with A.I.s like you, we should consider new ways to adapt this to include the A.I. I would also like to go beyond just comments and add ways to communicate different types of communication (for example, is the comment a directive from me to the A.I.? Is it a question that requires an answer? Is it a question that does not require an answer but should be factored into the response? etc)
For reference as a starting point, here is some basic information on comments:
Programmers use comments in source code for a variety of important reasons. The most popular and widely accepted uses include:
Describing Intent and Purpose
• Explain why code exists or why it’s written in a particular way. Comments often clarify the intent behind a block of code, especially when the reasoning is not obvious from the code itself. This helps future maintainers understand the rationale for certain design decisions or unusual practices126.
• Describe the purpose of a file, class, function, or method. Prologue or header comments at the top of files, classes, or functions provide overviews, explain what the code is meant to do, and sometimes include metadata like author and date127.
Clarifying Complex or Non-Obvious Code
• Highlight complex algorithms or unusual practices. When code is particularly tricky, uses a workaround, or deviates from standard conventions (e.g., due to a library bug or performance reasons), comments are used to explain these choices13468.
• Detail how an algorithm works. Comments can include pseudocode or step-by-step explanations of algorithms, making it easier to review and maintain the code18.
Providing Context and Documentation
• Summarize what a function, class, or module does. These comments often include descriptions of parameters, return values, and exceptions, making code easier to use and integrate25.
• Reference external resources. Comments may link to documentation, specifications, or external references that influenced the implementation1.
Marking Tasks and Issues
• Use tags like TODO, FIXME, HACK, NOTE. These tags help developers quickly find areas needing further work, known issues, or non-ideal solutions that may need revisiting1.
Commenting Out Code
• Temporarily disable code. Programmers often comment out lines or blocks of code during debugging or experimentation to test changes without deleting code permanently16.
Storing Metadata
• Include author, date, version, and legal information. Some comments store metadata for tracking changes, authorship, or licensing1.
Integrating with Tools
• Support for documentation generators and configuration. Comments can be parsed by tools to generate API documentation or configure editors (e.g., Vim modelines)1.
Relieving Stress or Adding Humor
• Occasionally, programmers use comments to vent frustration, inject humor, or make notes about working conditions. While not always professional, these comments are sometimes found in codebases1.
Best Practices for Writing Comments in Code
1. Explain the "Why," Not the "What"
• Focus comments on why a particular approach, algorithm, or workaround was chosen, rather than restating what the code does. Well-written code should make the "what" clear; comments should provide the reasoning, context, or business logic behind it135678.
2. Avoid Redundancy
• Do not duplicate the code in your comments. Comments that simply restate the code add no value and can become misleading if the code changes but the comment does not1256.
3. Clarify Complex or Non-Obvious Code
• Use comments to explain complex logic, edge cases, or non-intuitive decisions. This helps others (and your future self) quickly grasp the intent behind intricate sections167.
4. Be Clear, Concise, and Precise
• Write comments in plain, easy-to-understand language. Avoid jargon, slang, or unnecessary detail. Keep comments brief and to the point—lengthy comments often signal that the code itself needs refactoring156.
5. Keep Comments Up to Date
• Regularly update or remove comments as code evolves. Outdated comments can be more harmful than no comments at all, leading to confusion and errors6.
6. Use Consistent Style and Placement
• Establish and follow a consistent commenting style across your team or project. Place comments near the code they describe (e.g., above functions, before complex logic), and use the same format for similar types of comments567.
7. Comment for Others, Not Just Yourself
• Write comments with the understanding that others will read your code. Avoid personal notes, jokes, or informal remarks; keep comments professional and relevant to the codebase7.
8. Document Classes, Methods, and Functions
• Provide brief summaries for classes, methods, and functions, describing their purpose, parameters, and return values when not obvious from the code or naming56.
9. Reference External Sources When Needed
• If your code is based on external documentation, standards, or online resources, include links or references in comments. This helps others understand the origin of certain implementations256.
10. Avoid Commenting Out Code and Excessive "TODOs"
Use version control systems to manage removed or experimental code instead of leaving large blocks commented out. Track tasks and incomplete features in issue trackers, not as lingering "TODO" comments in the code5.
RESPONSE FROM CHATGPT:
Below are some ideas for extending “comments” into a richer, multi‑dimensional channel for human→AI communication in the CRAFT framework. Instead of a one‑size‑fits‑all “# comment,” we can introduce distinct markers, tags or even mini‑languages so the AI knows exactly how to treat each line.
==========
Structured Comment Tags
•#!
Directive – AI should execute or obey.
Example:css
CopyEdit
#! Generate a 3‑point summary of the following section
•
#?
Question (answer expected) – AI must answer in its next response.bash
CopyEdit
#? What are the main risks of this approach?
•
#?*
Contextual question – AI should factor it in but not explicitly answer.arduino
CopyEdit
#?* Could users find this confusing?
•
#:
Fact or reference – AI treats this as background info.bash
CopyEdit
#: According to our metrics Q1 growth was 12%.
==========
2) Priority & Status Tags
• # TODO:
/ # FIXME:
/ # NOTE:
as usual, but AI can surface these as a task list or refactor hints.
• #!!!
Urgent – AI flags these and addresses them first.
==========
3) Personality / Tone Annotations
• #@persona: coach
– AI switches into “coach” mode.
• #@tone: playful
– AI adopts a lighter style.
==========
4) Configuration Blocks
Surround a small JSON or YAML‑like snippet in comments to tweak AI settings on the fly:
shell
CopyEdit
#> { #> "temperature": 0.3, #> "max_tokens": 500 #> }
AI parses and applies these parameters immediately.
==========
5) Question vs. Directive Blocks
Use fenced sections in comments:
python
CopyEdit
'''ai-directive Summarize this text in bullet points. ''' '''ai-question Does this fulfill our objective? '''
Each fence tells the AI exactly how to classify the content.
==========
6) Emoji‑Driven Cues
Pair a simple icon with comment tags for at‑a‑glance clarity:
• # 🚀 directive:
• # ❓ question:
• # 📋 context:
• # 🛠️ todo:
==========
7) Inline “Dev Tools” Commands
Borrow from doc‑generators—special @
tags in comments:
• @ask
(question)
• @do
(directive)
• @note
(context)
• @set
(config)
Example:
ruby
CopyEdit
# @ask What edge cases should we consider? # @do Generate unit‑test stubs for this function.
==========
8) Meta‑Comment Layers
Allow nesting of comment types:
ruby
CopyEdit
#! [directive] # • @do Validate input schema # • @ask Any missing parameters? #?* [context] # • This logic is experimental
==========
9) Visual Separators & Sections
Use long comment lines or ASCII art to delineate phases:
shell
CopyEdit
############################################ ### AI‑PREPROCESSING: Normalize all dates ### ############################################
==========
10) “No‑Op” Flags
A tag telling the AI to acknowledge but not act:
bash
CopyEdit
#NOP Ignore this for generation, but log it.
—
By giving comments semantic structure and distinct tags (directives, questions, context, config, priority), we turn passive notes into active, machine‑readable instructions that the AI can parse, prioritize, and act on—while still remaining lightweight and familiar to programmers.
You said:
Good, please revise suggestions to work with Python as the base language.
ChatGPT said:
Thought for 7 seconds
Here’s the same set of AI‑comment conventions, tuned to Python syntax and idioms:
==========
1) Python‑Style Comment Tags
python
CopyEdit
#! # Directive – AI should execute or obey #? # Question (answer expected) – AI must reply directly #?* # Contextual note – factor into response, no direct answer #: # Reference/fact – background info only #!!!# # Urgent – address these first
python
CopyEdit
#! Generate_summary(input_text) #? What edge cases should we handle? #?* Could users find this confusing? #: Last_release_date = "2025-04-01" #!!!# Fix performance bottleneck in preprocess()
==========
2) Decorators for Directives & Questions
Define lightweight decorators so you can annotate functions or blocks:
python
CopyEdit
from craft_tags import ai_directive, ai_question, ai_context @ai_directive def summarize_report(data): """Generate a 3‑point bullet summary.""" … @ai_question def check_risk_assumptions(): """What are the main risks here?""" … @ai_context def load_user_profile(): """# Context: user is on mobile, low bandwidth.""" …
==========
3) Docstring‑Embedded Prompts
Use function docstrings to carry AI prompts or questions:
python
CopyEdit
def process_data(data): """ AI-Directive: Summarize this dataset’s key metrics. AI-Question: What anomalies stand out? """ …
==========
4) In‑Code Config Blocks
Embed JSON/YAML‑style settings directly as Python literals. AI parses and applies them:
python
CopyEdit
AI_CONFIG = { "temperature": 0.2, "max_tokens": 300, "tone": "concise" }
==========
5) Triple‑Quoted Fences
Leverage Python’s triple‑quotes to section off prompts:
python
CopyEdit
"""ai-directive Generate bullet‑point recommendations based on sales_data. """ """ai-question Should we adjust pricing thresholds for Q3? """
==========
6) Emoji‑Enhanced Comments
Still use #
but add an emoji tag for quick visual parsing:
python
CopyEdit
# 🚀 directive: Optimize data pipeline for speed. # ❓ question: Are all data sources up‑to‑date? # 📋 context: Running this in CI with limited RAM.
==========
7) Inline “@” Tags in Comments
Borrow Python’s decorator look‑and‑feel with @
in comments:
python
CopyEdit
# @do Validate user input schema. # @ask What missing parameters exist? # @note This uses experimental API v2.
==========
8) Meta‑Comment Blocks
Combine multiple tags in a small section:
python
CopyEdit
#! [directive] # • @do Clean null values. # • @ask Should we aggregate by region? #?* [context] # • Data from last 6 months only.
==========
9) Section Separators
Use long comment lines to mark phases or stages:
python
CopyEdit
############################################ ### AI‑PREPROCESSING: Normalize timestamps ### ############################################
==========
10) No‑Op Flags for Logging
Tell the AI to acknowledge but not act—handy for auditing:
python
CopyEdit
# NOP: Log this user‑journey step without generating text.
All examples above use valid Python syntax and leverage its comment, decorator, and literal conventions—turning passive notes into active, machine‑readable instructions in your CRAFT Python base.
You said:
Great, thanks! Please provide 10 more ideas
ChatGPT said:
Here are 10 more Python‑centric comment patterns you can weave into CRAFT to drive richer AI behavior:
==========
11) Conversation State Tags
Use a simple key to tell the AI what “mode” it’s in or should switch to:
python
CopyEdit
# state: awaiting_user_feedback # state: summarizing_section
==========
12) Test/Validation Comments
Flag outputs for automated checking or unit‑test generation:
python
CopyEdit
# test: expect 3 items in summary_list # validate: all URLs start with "https://"
==========
13) YAML‑Style Metadata Blocks
Embed structured metadata the AI can parse without extra parsers:
python
CopyEdit
# --- ai-metadata # model: latest-gpt # retry: 2 # ---
==========
14) Logging‑Level Cues
Mimic logging calls so the AI logs or suppresses details appropriately:
python
CopyEdit
# DEBUG: loading user profile # INFO: generation complete # WARN: missing optional field “bio”
==========
15) Fallback / Graceful Degradation
Tell the AI what to do if its primary task fails:
python
CopyEdit
# fallback: if summary too long, give bullet‑point TL;DR # fallback: on error, apologize and ask for clarification
==========
16) Rate‑Limit & Resource Constraints
Signal token or time budgets for generation:
python
CopyEdit
# rate_limit: tokens_per_call=200 # budget: max_runtime=1.5s
==========
17) Persistent Memory Markers
Mark facts the AI should “remember” across turns:
python
CopyEdit
# remember: user_timezone = "America/Chicago" # remember: prefers_brief_responses = True
==========
18) Role‑Switch Comments
Temporarily adopt a specialist persona inline:
python
CopyEdit
# role: security_expert # role: ux_designer
==========
19) Output Format Specifiers
Instruct exactly how the AI should format its answer:
python
CopyEdit
# format: markdown_table # format: json_object # format: plain_bullets
==========
20) Interactive Prompt Placeholders
Leave “fill‑in” spots for the AI to replace dynamically:
python
CopyEdit
# placeholder: INSERT_CHART_HERE # placeholder: USER_NAME
With these, your Python scripts aren’t just code—they’re living, self‑documenting conversations that the AI can parse, act on, and even carry forward statefully.