6 Prompting Principles for Improving Claude Code Output Quality =============================================================== Learn how to structure and communicate context, output contracts, exception handling, and validation criteria instead of simply asking Claude Code to generate code. It also provides prompt templates you can immediately apply to new agent development, feature additions, and bug fixes. - 1. Before starting the task, document the user context, problem to solve, success criteria, and technical constraints in a single document. - 2. Specify the deliverable's file structure, data format, permitted scope, and completion criteria in a concrete output contract. - 3. Define foreseeable exceptions, such as external API failures, empty results, duplicate data, and authentication errors, along with response policies. - 4. Divide the work into planning review, minimum viable implementation, automated testing, and feature expansion, and review the results at each stage. - 5. Instead of making vague rework requests, provide failure cases and measurable improvement goals, then validate against the final acceptance criteria. Coding agents such as Claude Code are not merely tools that generate snippets of code; they are working environments that can explore repositories, modify multiple files, and run tests and commands. Therefore, the quality of the result depends less on how plausible the wording sounds and more on how clearly the scope of work and validation methods are defined. A good prompt is not a lengthy explanation but an actionable work specification. It should communicate not only what to build, but also why it is needed, which conditions must be followed, how failures should be handled, and what must pass for the work to be considered complete. First Distinguish Between the Prompt and the Execution Environment Vibe coding is a collaborative approach in which intent is communicated in natural language and an AI agent handles the implementation. However, the fact that a request was made in natural language does not guarantee code accuracy or operational stability. The following elements work together in a Claude Code task. Element Role What to Confirm in the Prompt User request Communicates the goal and scope of changes Purpose, priorities, prohibitions Repository context Provides the existing structure and rules Framework, execution commands, related files CLAUDE.md Provides project instructions that are applied repeatedly Coding rules, testing methods, directory conventions Tool permissions Controls the permitted scope of file modifications and command execution Commands that may be run and tasks requiring prior confirmation External connections Provide access to APIs, databases, MCP servers, and more Authentication method, trust boundaries, failure policy Validation procedure Determines whether the result meets the requirements Tests, static analysis, manual checks Writing a good prompt alone does not solve every problem. For example, Claude Code can create scheduled-execution code, but running a task even while a computer is turned off requires a separate server, CI service, or operating system scheduler. Email delivery also cannot be completed without actual provider credentials and sending permissions. Principle 1. Explain the Background, Purpose, and Constraints First If you provide only the name of the desired result, such as Build me a news collection agent, the agent must guess the users, data sources, execution environment, and success criteria. Even for the same news collector, a business development manager, investor, and university newspaper editor will need different sources and classification criteria. Insufficient Request Build me an AI news collection agent. Improved Request I am a business development manager at an IT startup. Before starting work each day, I want to quickly review news in the AI, cloud, and fintech sectors that could affect business partnerships or product strategy. Goals: - Collect recent article candidates for each specified keyword. - Remove articles with the same URL and duplicates with similar titles. - Classify impact as high, medium, or low based on whether a product or partnership decision is required within 3 months. - Produce the results as a Korean email briefing. Constraints: - Preserve the current repository's Python version and package management approach. - Before adding a new library, explain its necessity and alternatives. - Do not record API keys or email passwords in code or logs. - Generate only a preview file before sending an actual email. First investigate the repository structure and how to run it, then propose an implementation plan. Do not guess unknown environment details; organize them into a list of questions. Good background information includes the following four items. User and usage context: Who will use it, when, and for what decision Goal: What problem must be solved, rather than simply what code must be written Constraints: Which technologies, security rules, cost limits, or time limits must be maintained Non-goals: Which features are explicitly excluded from this change Stating non-goals prevents the scope from expanding indefinitely. For example, defining that Scheduled execution and actual email delivery are excluded from this phase allows the collection and classification logic to be validated reliably first. Principle 2. Turn the Desired Output Format into an Output Contract Send it as a nicely formatted email can be interpreted differently by each person. Rather than showing only an example, define the required fields, allowed values, handling of missing data, and sort order together. Email subject: [News Briefing] {YYYY-MM-DD} Today's Top News Article format in the body: 1. {Title} Summary: {1–2 sentences in Korean} Impact: {High|Medium|Low} Reason for assessment: {1 sentence} Source: {Publisher name} Link: {Original article URL} Sorting rules: 1. Highest impact first 2. If impact is the same, most recent publication time first Statistics at the bottom: - Total number of articles - Number of articles by impact level - Keywords with no search results Constraints: - Do not invent figures or claims in the summary that are not in the original article. - If the date cannot be verified, do not estimate it; mark it as 'Unable to verify.' - Exclude items without links from the final briefing. If results must be passed between programs, it is helpful to request a JSON schema or type definition along with a human-readable example. { "title": "string", "summary": "string", "impact": "high | medium | low", "reason": "string", "source": "string", "url": "absolute URL", "published_at": "ISO 8601 string | null" } An output contract includes not only format but also meaning. If there are no assessment criteria defining what impact: high means, the JSON syntax may be correct while the classification results remain inconsistent. Principle 3. Specify Exceptional Situations and Recovery Policies The quality of production code is revealed more clearly in failure paths than in the normal path. A prompt should state foreseeable failures, whether retries are allowed, when the user should be notified, and which information must not be recorded. Exceptional Situation Example Recommended Policy No search results Skip the keyword and record it in the final statistics Temporary network error Retry only a limited number of times at set intervals Authentication failure Do not retry; stop immediately and provide instructions to check the configuration API rate limit Follow the response's waiting instructions and prohibit infinite retries Duplicate articles Remove them based on normalized URLs and title similarity Malformed data Preserve the original and isolate only the affected item Email delivery failure If it still fails after retries, send an alternative notification or record a failure status Partial success Report successful results separately from failed items You can request specific policies as follows. Treat network timeouts as retryable errors. Wait between retries, and if the maximum number is exceeded, mark only that source as failed. Stop immediately for authentication errors and invalid requests, because repeating them will not resolve the problem. For every error log, record the time, task stage, source, and error type, but do not record API keys, full email addresses, authentication headers, or full article bodies. Use process exit statuses to distinguish complete success, partial success, and complete failure. Values such as retry three times or wait 5 seconds are not universally correct. They must be determined within the project based on the external service's official limits, the urgency of the task, and the risk of duplicate execution. Tasks with side effects, such as payments or message delivery, may be processed more than once if automatically retried without an idempotency guarantee. Principle 4. Develop Incrementally in the Order of Plan, Minimum Implementation, and Validation Connecting multiple external services and automated execution all at once makes it difficult to isolate the cause of an error. Dividing the implementation into small validation units allows the inputs and outputs of each stage to be checked. Recommended Sequence Investigate the repository structure, related files, and execution commands. Have the agent present a plan and the files that will be affected before changing code. Implement collection using one keyword and fixed sample data. Test deduplication and impact classification separately. Validate the email with a local preview instead of actual delivery. Add actual provider integration and scheduled execution after the tests pass. The first request can be limited as follows. Perform only phase 1 for now. Investigate the repository and report the following: - The current application's entry point - Related modules and test files - The package management and test commands in use - Files that are likely to require changes - Questions that must be resolved before implementation Do not modify any files yet. After reviewing the plan, implement with a narrower scope of changes. Of the approved plan, implement only news collection and deduplication. Do not add classification, email delivery, or scheduled execution. Make it runnable with fixed test data, and summarize the modified files and test results at the end. If a planning-only mode is available in the Claude Code environment, it can be used during the exploration and design phases. However, a plausible plan does not mean the implementation is correct, so actual tests and code review must follow. Principle 5. Provide Feedback with Failure Cases and Numbers Feedback such as The result is not very good, Performance is slow, or The classification is wrong makes it difficult to determine how to revise the implementation. You must provide the current state, expected state, reproduction input, and the acceptable scope of change. Request to Revise Length The current email body is generated at approximately 3,000 characters. I want to reduce it to at most 500 characters so it can be read quickly on mobile. Limit each article summary to 1–2 sentences and retain the reason for assessment. Link the original URL to the title and remove the separate link line. Keep the statistics at the bottom. Request to Revise Classification Criteria Of the 10 test records, 8 were classified as 'high.' Classify long-term technology forecasts or general product introductions as 'low.' Classify an article as 'high' only when there is specific evidence that a decision on pricing, product roadmaps, regulatory response, or partnerships must change within 3 months. For the attached cases, A and B should be high, and C should be low. Revise the classification rules and add these cases as regression tests. Request to Improve Performance The average execution time for the same sample input is currently approximately 45 seconds. The target is at most 30 seconds in the same environment. First measure the time for each stage and show the bottleneck. Do not remove result accuracy or error handling. Compare the effects and risks of the improvement options, then apply the smallest change first. Performance figures can be compared only when the measurement environment and input data are the same. Do not conclude that performance has improved based on a single execution result; the measurement method, sample, and cache state must also be fixed. Principle 6. Use Prompt Templates for Each Type of Task New Agent Creation Template [Role and Context] I am a {profession/role} trying to solve {problem situation}. This result will be used by {user or downstream system}. [Goal] {Result to achieve and success criteria} [Execution Trigger] {Manual execution, event, scheduled time, etc.} [Input] - Data source: {file/API/database} - Required fields: {field list} - Authentication method: {environment variable or secret management method} [Processing Logic] 1. {Step 1} 2. {Step 2} 3. {Step 3} [Output Contract] {File format, schema, template, sorting and missing-data rules} [Exception Handling] {Empty results, timeouts, authentication errors, partial failure policy} [Constraints and Non-goals] - Technologies to preserve: {items} - Prohibitions: {items} - Features excluded from this task: {items} [Validation] - Tests that must pass: {items} - Items to include in the completion report: changed files, execution commands, test results, remaining risks First investigate the repository and present an implementation plan. Do not guess unknown information; ask questions. Existing Feature Addition Template Add {new feature} to the existing {agent or module name}. The new feature must run after {existing stage A} and before {existing stage B}. Detailed logic: - {Conditions and processing rules} - {Input/output format} - {Behavior on failure} Preservation requirements: - Do not change the existing public interfaces or configuration format. - Preserve all existing tests. - Do not modify unrelated files. First explain the scope of impact and regression risks, then add tests that preserve the existing behavior before implementing the feature. Bug Fix Template Reproduce the following error and fix its root cause. Full error message: {Error message and stack trace with secrets and personal information removed} Conditions: - Execution command: {command} - Input: {minimal reproduction input} - Environment: {operating system, runtime, relevant versions} - Point of occurrence: {which stage} Expected behavior: {Result that should appear under normal operation} Actual behavior: {Currently observed result} Request: 1. Reproduce the error first. 2. Explain the cause based on evidence. 3. Fix it within the smallest possible scope. 4. Add a regression test that prevents the same error. 5. Report the tests run and remaining risks. When pasting error messages, remove sensitive information such as API keys, session tokens, customer data, and internal addresses. Complete Example: News Briefing Agent Request The following example combines all six principles into a single request. I am a business development manager at a SaaS startup. I want to review only news about changes in the AI, cloud, and fintech markets that could alter product or partnership decisions within 3 months. Investigate the current repository and design a news briefing tool. In the first phase, implement only the functionality that reads sample JSON, removes duplicates, classifies impact, and creates an HTML preview file. Web search, actual email delivery, and scheduled execution are excluded from this phase. Input fields: - title, url, source, published_at, body Processing rules: - Treat records with the same normalized URL as duplicates. - Even if URLs differ, mark articles with similar titles as duplicate candidates. - Classify only articles requiring specific changes to pricing, regulatory response, product roadmaps, or partnership decisions within 3 months as 'high' impact. - If evidence is insufficient, do not guess a high rating. Output: - Display the title, 1–2 sentence summary, impact, reason for assessment, source, and URL. - Sort by highest impact first. - Display the total count, number of duplicates removed, and count by rating at the bottom. Exception handling: - Do not exclude items missing required fields; record them in a separate error list. - Do not estimate invalid dates; keep them as null. - Do not leave full article bodies or authentication information in logs. Validation: - Test normal input, empty input, duplicate URLs, invalid dates, and missing required fields. - If existing tests are present, they must all pass. Work sequence: 1. Investigate the repository structure and related files. 2. Present the files to be modified and the test plan. 3. Do not change code until I have reviewed the plan. 4. After approval, implement the minimum functionality and report the test results. This request does not ask for every required feature to be deployed to the production environment at once. Its scope is limited, and the meaning of the output, failure handling, and test cases are defined together, making the result easy to assess. Quality Criteria That Are Easy to Miss with Prompts Alone Many vibe coding guides focus on writing more detailed instructions. However, additional factors that determine actual quality are verifiability, change control, observability, and security boundaries. 1. Turn Acceptance Criteria into Tests Instead of saying Make it work well, provide paired inputs and expected outputs. Preserve important classification cases as regression tests to confirm that the results remain consistent after subsequent changes. 2. Do Not Use the Agent's Self-Assessment as Final Evidence An agent saying Completed is not the same as the tests passing. Have it report the commands run, test results, changed files, and unresolved risks, and have a person review the diff. 3. Minimize Permissions and Secrets Do not provide access to unnecessary directories, production databases, and deployment credentials all at once. Do not place API keys directly in prompts or repositories; use environment variables or an approved secret management system. Do not grant sensitive repository access to MCP servers or scripts of unknown origin. 4. Require Observable Code For automated tasks, retain information needed to identify the cause of failures, such as status by stage, structured errors, execution time, and number of records processed. Remove authentication information and personal information from logs. 5. Make Changes Reversible Do not mix unrelated refactoring and feature additions into the same change. Reviewing diffs in small units and recording them in version control makes it easier to isolate and revert incorrect changes. Claude Code Project Operation Tips Record recurring project rules briefly and specifically in CLAUDE.md. Provide build, test, and lint commands in a form that can actually be executed. Do not place secrets, one-off error logs, or lengthy reference documents in CLAUDE.md. Before large-scale changes, have the agent investigate related files and dependencies first. When adding a new package, review its necessity, license, and maintenance risks. Do not automatically approve dangerous deletion, deployment, or data modification commands. Before connecting an external API or MCP, confirm where the data will be transmitted. At completion, have the agent summarize changed files, execution commands, test results, and remaining limitations. Pre-Submission Checklist Are the user and usage context explained? Are goals and non-goals separated? Are existing technologies and prohibited changes specified? Are the input data and output format defined? Are the meanings of classification values and status values explained? Are there policies for empty results, authentication failures, timeouts, and partial failures? Are planning and implementation separated into stages? Are there tests for normal, boundary, and failure cases? Are secrets and personal information excluded from prompts and logs? Have you requested a diff and execution evidence for human review? The key to a good Claude Code prompt is not writing a long command. It is reducing what the agent must guess and enabling a third party to reproduce and assess whether the result is correct. FAQ Q. Are longer Claude Code prompts better? A. What matters more than length is whether the information needed for the task is included in a structured way. Be specific about the background, goals, constraints, output contract, exception handling, and completion criteria, while removing irrelevant explanations and duplicate instructions. Q. Can I ask it to create the entire program from the start? A. This may be possible for a small, standalone tool, but it is safer to develop tasks involving an external API, database, email, and scheduled execution in stages. Reviewing the repository investigation and plan first, then expanding in the order of minimum functionality, testing, and external integrations makes it easier to isolate the causes of failures. Q. Can I skip testing if I use Plan Mode? A. No. Plan Mode is useful for reviewing the structure and approach before making changes, but it does not prove that the actual code is correct. After implementation, you must separately perform automated tests, static analysis, review the changes, and carry out any necessary manual checks. Q. What should I include in CLAUDE.md? A. It is appropriate to include instructions that recur across multiple tasks, such as the project structure, coding conventions, build and test commands, and areas that must not be modified. It is best not to include API keys, passwords, personal information, descriptions of one-off tasks, or excessively long reference materials. Q. What information should I provide when requesting a bug fix? A. You should provide the error message and stack trace with sensitive information removed, the execution command, minimal reproduction input, the relevant environment, and the actual and expected behavior. It is also advisable to request an explanation of the cause, a minimal-scope fix, regression tests, and execution results. Q. Can I provide an API key to Claude Code in a prompt? A. As a rule, you should not directly include actual API keys in prompts or source code. Use approved environment variables or a secrets management system, and ensure that credentials are not exposed in logs or test results. Q. Do I have to specify the number of retries and the wait time in the prompt? A. For operational automation, it is important to distinguish between errors that can be retried and errors that require immediate termination. However, the specific number of retries and wait time should be determined after checking the external service's limits, the urgency of the task, and the risk of duplicate processing, and not every error should be retried unconditionally. Q. How can I tell whether the generated code is complete? A. Assess it against predefined acceptance criteria. Check whether tests for required functionality and edge cases pass, the commands that were run, the files that were changed, and whether performance or security constraints are met, and have a person review the code changes. Sources - Claude Code overview: https://docs.anthropic.com/en/docs/claude-code/overview - Claude Code: Best practices for agentic coding: https://www.anthropic.com/engineering/claude-code-best-practices - Anthropic Claude Code GitHub repository: https://github.com/anthropics/claude-code Images - Developer working at a desk with code and a workflow diagram on a large monitor: https://injoys.com/rails/active_storage/blobs/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MTExNTQsInB1ciI6ImJsb2JfaWQifX0=--9f2d2e2c8a61fc294a6019e4807ece297f36e85a/ai-4caeb237.webp - Laptop code editor connected to requirements, tables, errors, version control, and performance charts: https://injoys.com/rails/active_storage/blobs/proxy/eyJfcmFpbHMiOnsiZGF0YSI6MTExNjAsInB1ciI6ImJsb2JfaWQifX0=--285d7ecdc8209e07e0fc4eb68085cd8a304b9a81/ai-062b34c5.webp --- Category: Tutorial Source: https://injoys.com/en/articles/claude-code-prompt-six-principles-and-templates License: cc_by Translation-Status: reviewed