iTranslated by AI
Crafting Prompts for API Reference Generation (Dart/Flutter)
Recently, I released plough, an interactive network graph drawing library. The documentation for this library was almost entirely generated using Claude 3.5 Sonnet + MCP—nearly everything, including the README (except for its structure). I’m noting down the insights I gained from the prompt trial-and-error process.
Note that the documentation mentioned in this article primarily refers to the API references that can be generated with dart doc.
I've uploaded a somewhat generalized sample file to flutter-documentation-prompt. Feel free to check it out if you're interested.
AI Used
- Claude 3.5 Sonnet on the Claude Professional Plan
- Claude Desktop + MCP (Recommended, as it saves the hassle of copying and pasting)
Objective
The adjustments here are aimed at generating documentation with a structure and content similar to the official API references.
Prompt Format
I described it in XML, a format that is easy for Claude to understand. The XML tag names can be anything as long as they make sense; I even let the AI decide on the tag names.
Issues When No Content Instructions are Provided
If you let the AI read the implementation and generate documentation without specifying any content instructions, you naturally won't get the expected results. For example, in class comments, there was a tendency to output the following:
- Exaggerated summaries
- Property lists (which belong in the specific property definitions)
- Method lists (same as above)
- Usage and strangely long sample code (which isn't guaranteed to run)
- Potential exceptions (this is often useful)
- Implementation details (unnecessary unless the algorithm is critical)
- Performance considerations
- Cross-references (though often with incorrect syntax)
While the output might look comprehensive, it rarely contains truly useful information. It tends to result in excessive commentary based on specific implementation logic, often including over-explanations of internal constraints or optimizations.
What Instructions Should Be Provided
As I went through multiple rounds of trial and error with prompts, I began to see certain tendencies in the comments generated by the AI (Claude). Since these tendencies will likely become obsolete eventually, there's no need to obsess over the details, but I found that providing a summary of "what to write," "what not to write," "good examples," and "bad examples" made it easier to get comments with the expected content.
Providing examples is highly effective, but if the word count gets too high, it consumes context for loading the prompt and increases the likelihood that some instructions will be ignored, so it's best to keep them moderate.
Target Documentation
I am assuming a depth and structure similar to the official Dart/Flutter API references. This needs to be adjusted based on the project requirements and the target audience.
Documentation Levels
Documentation levels are categories for files and APIs. You can define the group contents according to your project's requirements, but the following items should cover basic use cases:
- Level name
- Description. Both the level name and description are considered during documentation generation.
- Target APIs. Broad text-based instructions like "data models" or "utilities" are sufficient.
- Depth. Instructions on what and to what extent things should be explained in detail.
- Inclusion of examples. Without instructions, there's a high probability that sample code will be output. For most APIs, this might be an excessive explanation, and since it's unclear if the code actually runs, adding them indiscriminately increases the maintenance burden.
Here is an example:
<documentation_levels>
<level name="core">
<description>Core level documentation requirements</description>
<targets>Data models, major view components, customizable classes</targets>
<depth>Relationships between related APIs, key considerations</depth>
<examples>Typical use cases</examples>
</level>
<level name="standard">
<description>Standard level documentation requirements</description>
<targets>APIs primarily for reference, classes that don't need customization</targets>
<depth>Concise overview</depth>
<examples>Not needed</examples>
</level>
</documentation_levels>
In this example, two levels are provided: core and standard. The core level handles data models, view-related APIs, and customizable classes, while the standard level handles APIs that are primarily for reference (rarely instantiated by users) or classes that don't require customization. Even without specifying specific target APIs, the AI can often determine the level by reading the implementation, but it's better to specify them if possible.
Themes
Instruct the AI on themes that should and should not be written. By specifying themes, you can filter for useful information.
In the sample, the following themes are specified:
- Required themes
- Widget constraints
- Relationships between APIs
- State management
- Excluded themes
- Performance and optimization
- Implementation details (output only if specifically instructed)
Example:
<themes>
<required_themes>
<theme>Widget constraints</theme>
<theme>API relationships</theme>
<theme>State management</theme>
</required_themes>
<excluded_themes>
<theme>Performance optimizations</theme>
<theme>Implementation details (unless specifically required)</theme>
</excluded_themes>
</themes>
Guidelines
Instruct the AI on various rules to follow when generating documentation. Guideline instructions are particularly important; without detailed instructions tailored to the output trends, content won't be placed in the proper location with the correct format.
The sample primarily specifies the following rules. Please refer to the file for details.
- Code other than comments
- Keep class declarations (
class), annotations, and modifiers. For some reason, these codes often disappeared when outputting class comments. - Do not edit existing code when updating comments. There were many instances where existing code was changed or deleted along with the comments.
- Keep class declarations (
- Linter
- Keep annotations (such as
ignore_for_file)
- Keep annotations (such as
- Classes
- Structure: "A single-line summary, concept, See also," etc.
- Avoid complex structures using sections
- Avoid descriptions regarding performance unless instructed
- Do not explain properties or methods within class documentation
- Constructors
- Always write documentation for public APIs. These are easily ignored if not instructed.
- Do not describe whether arguments are required or optional
- Good and bad examples. Providing only instructions was often insufficient, so examples are provided.
- Properties
- Primarily explain the purpose and usage
- Explain constraints and side effects
- Methods
- Structure
- Do not describe whether arguments are required or optional
- Explain behavior, side effects, and return values
- Good and bad examples
- Other rules
- Syntax for cross-references
- Describe potential exceptions that may occur
- Do not include descriptions of default values in comments
- Classes with
@freezedapplied
Templates
Specify the comment format and additional notes. Providing a concrete format makes it easier to follow the guidelines and stabilizes the accuracy of the output.
The following is an example of a class comment:
<template type="class">
<format>/// A class that represents {purpose}.
///
/// {Conceptual explanation of core functionality and behavior}
///
/// See also:
/// * [RelatedClass], for {related functionality}
</format>
<notes>
<note>Start with a clear single-sentence summary of the class purpose</note>
<note>Follow with conceptual explanation</note>
<note>Avoid listing properties or methods in class comments</note>
</notes>
</template>
Others
Below are some prompts that are helpful to include for a smoother workflow.
Simplification of Execution Steps
Specifying the processing targets in advance can save chat effort and tokens. This is particularly useful when using an AI like MCP that can directly access directories and files.
For this project, I mainly specified the following items:
- Target files and excluded files
- Target APIs and excluded APIs
- (For public packages) Whether to output comments for private APIs
Example of target and excluded files:
<target_files>
<include>
<pattern>lib/**/*.dart</pattern>
</include>
<exclude>
<pattern>**/*_test.dart</pattern>
<pattern>**/*.g.dart</pattern>
<pattern>**/*.freezed.dart</pattern>
</exclude>
</target_files>
This configuration excludes test code and code automatically generated by build tools.
API Overview
Preparing a prompt that summarizes the overview of the main APIs improves the quality of the documentation. Simply describing the following items concisely is enough:
- Overview
- Importance
- File path
When combined with MCP, the AI can efficiently refer to the source code.
Annotations for IDEs
If you let the AI edit the prompt files, it's a good idea to include annotations that disable automatic formatting or the addition of new lines by the IDE. If you have the prompt file open in your IDE while allowing MCP to access the file directly, edits may fail because of discrepancies between the file content and what the IDE's context holds.
I use IntelliJ IDEA and Writerside, so I disable formatting with the following annotation:
<?xml version="1.0" encoding="UTF-8"?>
<!-- @formatter:off -->
Version and Last Modified Date
Including the version and last modified date of the prompt—and recording them somewhere alongside the documentation's generation date—provides a useful indicator for when old documentation should be updated.
In the sample, I've embedded a "date + serial number" as the version. Here is an example:
<meta>
<version>2025_01_28_001</version>
<version_rules>
<format>YYYY_MM_DD_NNN</format>
<description>Version number format</description>
<rules>
<rule>Date (YYYY_MM_DD): Documentation rule update date</rule>
<rule>Number (NNN): Treated as a sequential number, continuing even when date changes</rule>
<rule>Example: After 2025_01_28_001 comes 2025_01_29_002, keeping sequence even when date changes</rule>
</rules>
<notes>
<note>Once assigned, version numbers should not be changed</note>
<note>When creating a new version, always use the latest number plus 1</note>
</notes>
</version_rules>
</meta>
Execution Sample
The following shows a document generated using a sample prompt based on the strategies discussed so far. I had Claude generate the implementation and comments for a text field that performs validation. The comments were generated in a single attempt with no manual adjustments.
import 'package:flutter/material.dart';
import '../../flutter_value_validators.dart';
import 'validated_form.dart';
import 'validatable_field.dart';
/// A text field that integrates with form validation.
///
/// This widget extends [TextField] with validation capabilities, allowing it to
/// participate in form-level validation through [ValidatedForm]. It supports
/// both manual and automatic validation modes.
///
/// See also:
/// * [ValidatedForm], which coordinates validation across multiple fields
/// * [StringValidator], which provides common string validation rules
class ValidatedTextField extends StatefulWidget {
/// Creates a validated text field.
const ValidatedTextField({
super.key,
required this.validator,
this.onChanged,
this.decoration,
this.controller,
this.errorBuilder,
this.autovalidate = false,
this.obscureText = false,
});
/// The validator used to validate the field's value.
final Validator<String> validator;
/// Called when the user changes the text in the field.
final ValueChanged<String>? onChanged;
/// The decoration to show around the text field.
final InputDecoration? decoration;
/// Controls the text being edited.
final TextEditingController? controller;
/// A builder that creates custom error displays.
final Widget Function(BuildContext context, ValidationError error)? errorBuilder;
/// Whether to validate the field whenever its value changes.
final bool autovalidate;
/// Whether to hide the text being edited.
final bool obscureText;
@override
State<ValidatedTextField> createState() => _ValidatedTextFieldState();
}
Thoughts
The difficulty in creating documentation lies in the fact that "what the developer wants to convey" and "what the user actually needs" do not always match. When generating with AI, "unintended information generated by the AI" is added to the equation. As I repeatedly generated and discarded content, I began to wonder, "Wait, is the AI the one outputting the appropriate comments...?" and felt drained by the constant reviewing.
However, since unintended information from AI can also serve as new hints, I personally feel it shouldn't just be a repetitive "gacha" process. With manual work, by the time you get around to writing documentation, you've often forgotten the implementation details, and the themes tend to become biased toward your own interests and concerns.
If you found this helpful, I'd appreciate it if you could give me a badge. It will go toward my coffee funds and motivation.
Discussion