Skip to main content

Writing Custom Instructions Files

1. Creating a copilot-instructions.md File

Custom instructions files in AI-assisted development allow you to define specific behaviors, preferences, and context for your AI copilot. These files are typically named copilot-instructions.md and are placed in your project root or a designated configuration directory.

File Name Description Location
copilot-instructions.md Defines custom instructions for AI copilot behavior Project root or .copilot/ directory

Example: Basic copilot-instructions.md

# AI Copilot Instructions

## Coding Style
- Use camelCase for variable names.
- Prefer functional programming where appropriate.

## Project Context
This project is a React application using TypeScript and Tailwind CSS.
Note: The AI copilot reads the instructions file to understand project-specific context and coding preferences.
Warning: Ensure that the instructions file is not committed to version control if it contains sensitive project information.

2. Structuring Instruction File Sections

Section Type Description Structure Usage
system Defines the AI's role and behavior { "role": "system", "content": "You are a helpful assistant..." } Set context and personality for the AI
user Represents user input or queries { "role": "user", "content": "Explain quantum computing" } Provide instructions or questions to the AI
assistant Represents AI responses or outputs { "role": "assistant", "content": "Quantum computing uses..." } Store or simulate AI-generated responses

Example: Basic Instruction File Structure

{
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user",
      "content": "Explain quantum computing"
    },
    {
      "role": "assistant",
      "content": "Quantum computing uses quantum bits (qubits)..."
    }
  ]
}
Note: The order of messages matters for context and response generation.

3. Writing Coding Style Guidelines

Guideline Description Example
Naming Conventions Defines naming standards for variables, functions, and classes camelCase for variables and functions; PascalCase for classes
Code Formatting Specifies indentation, spacing, and line length limits Use 4 spaces for indentation; limit lines to 80 characters
Documentation Style Guidelines for inline comments and docstrings Use /** */ for JSDoc-style documentation
Error Handling Standards for catching and logging errors Always handle try/catch blocks with meaningful error messages

Example: Naming Convention

// Good
const userName = 'John';
function calculateTotal() { ... }

// Avoid
const user_name = 'John';
function calculate_total() { ... }

Example: Code Formatting

// Good
const processUser = (user) => {
  const result = user.name.length > 0 ? 'Valid' : 'Invalid';
  return result;
};

// Avoid
const processUser=(user)=>{const result=user.name.length>0?'Valid':'Invalid';return result;}
Note: Consistent style improves code readability and maintainability across teams.
Warning: Inconsistent style guidelines can lead to confusion and reduce team productivity.

4. Writing Project Context Guidelines

Guideline Description Best Practice
Project Overview Summarize the project's purpose, scope, and main objectives. Include high-level goals and key features to set context for the AI.
Technical Stack List the primary technologies, frameworks, and tools used in the project. Specify versions or major dependencies to ensure compatibility.
Code Style & Conventions Define naming conventions, formatting rules, and code structure expectations. Include examples or references to style guides (e.g., Airbnb JS Style Guide).
Constraints & Limitations Highlight any constraints such as performance, security, or compliance requirements. Specify limits like max file size, runtime duration, or data privacy rules.
Examples & Patterns Provide examples of how specific patterns or components should be implemented. Include code snippets or architecture diagrams to guide implementation.

Example: Project Overview

# Project: AI Code Assistant
## Overview
This project is a tool that helps developers write code faster by providing intelligent suggestions and auto-completions. It integrates with popular IDEs and supports multiple programming languages.

Example: Technical Stack

{
  "language": "JavaScript",
  "framework": "React",
  "buildTool": "Webpack",
  "testingLibrary": "Jest",
  "styling": "CSS Modules"
}
Note: Ensure that all guidelines are updated regularly to reflect changes in project scope or technology stack.

5. Writing Testing Requirements

Requirement Type Description Example
Test Coverage Specifies the percentage or scope of code to be tested 90% of business logic
Test Environment Defines the environment where tests should run CI/CD pipeline with Node.js 18+
Test Assertion Defines what must be validated in each test Response status code is 200

Example: Test Requirement Configuration

testRequirements:
  coverage: "90%"
  environment: "CI/CD pipeline with Node.js 18+"
  assertions:
    - "Response status code is 200"
    - "User data is returned correctly"
Note: Ensure test requirements align with the AI model's understanding of the application's behavior.

6. Avoiding Instruction Conflicts

Conflict Type Description Resolution Strategy
Overlapping Instructions Multiple instructions that target the same code area or function Use priority tags to define order of execution
Contradictory Rules Instructions that directly oppose each other (e.g., "do this" vs "do not do this") Implement a conflict resolution engine that flags or auto-resolves contradictions
Ambiguous Scope Instructions that are unclear about which code elements they apply to Use explicit scope markers like function:myFunction or file:src/main.js

Example: Prioritizing Instructions

# Instruction 1 - High Priority
priority: 1
scope:
  file: "src/main.js"
  function: "processData"
action: "add logging"

# Instruction 2 - Low Priority
priority: 2
scope:
  file: "src/main.js"
  function: "processData"
action: "optimize performance"
Note: Priority levels are numeric, with lower numbers indicating higher priority.
Warning: Conflicts can lead to unpredictable behavior or runtime errors if not resolved.

7. Testing Instruction Effectiveness

Test Type Description Metrics Tools
Response Consistency Measure how consistently the AI responds to similar prompts Response similarity score, variance in outputs LLM-Test, AI-Tester
Accuracy Validation Validate that responses align with expected outcomes or facts Accuracy percentage, error rate Fact-Check, Truth-Verifier
Instruction Fidelity Check if the AI follows instruction format and content precisely Fidelity score, adherence to structure Instruction-Validator, Compliance-Checker

Example: Testing Consistency

const testPrompts = [
  "Explain the concept of AI in simple terms",
  "What is artificial intelligence?",
  "Define AI in one sentence"
];

const responses = testPrompts.map(prompt => {
  return aiModel.generate(prompt);
});

// Calculate consistency score
const consistencyScore = calculateConsistency(responses);
console.log("Consistency Score:", consistencyScore);
Note: Use a diverse set of prompts to ensure comprehensive testing.
Warning: Avoid using prompts that are too vague or subjective for accurate measurement.

Testing Strategy Summary

  • Use multiple prompt variations to test consistency
  • Validate factual accuracy with external sources
  • Measure adherence to instruction format

8. Versioning Instruction Files

Field Description Example
version Version of the instruction file schema "1.0"
instructions List of instruction objects [{...}]

Example: Basic Versioned Instruction File

{
  "version": "1.0",
  "instructions": [
    {
      "id": "ai-code-review",
      "description": "Review code for best practices",
      "action": "code-review"
    }
  ]
}
Note: Versioning ensures backward compatibility and allows for schema evolution over time.

9. Sharing Instructions Across Teams

Aspect Description Implementation
File Format Standardized format for sharing instructions .ai-instructions.json or .ai-instructions.yaml
Version Control Track changes and collaborate on instruction sets Git integration with .ai-instructions.json
Access Control Define who can view or edit instructions Role-based permissions (e.g., read, write)

Example: Sharing Instructions in a Team

{
  "name": "Team AI Instructions",
  "version": "1.0.0",
  "instructions": [
    {
      "id": "team-code-style",
      "description": "Enforce consistent code style across the team",
      "rules": [
        {
          "rule": "Use 2-space indentation",
          "type": "formatting"
        }
      ]
    }
  ],
  "access": {
    "read": ["team-members"],
    "write": ["team-leads"]
  }
}
Note: Instructions can be shared via version control systems like Git or internal documentation platforms.

Best Practices for Sharing Instructions

  • Use a standardized format like JSON or YAML to ensure compatibility.
  • Version your instruction files to track changes over time.
  • Implement access control to restrict who can modify shared instructions.

10. Combining Global and Local Instructions

Instruction Type Scope Usage Priority
global System-wide Applies to all projects and AI interactions High
local Project-specific Applies only within the project directory Medium

Example: Combining Global and Local Instructions

# Global instructions (e.g., ~/.ai-instructions.yaml)
rules:
  - type: global
    content: |
      Always follow the company's coding standards.
      Use consistent naming conventions across all projects.

# Local instructions (e.g., ./project/.ai-instructions.yaml)
rules:
  - type: local
    content: |
      For this project, use camelCase for all variables.
      Implement error handling with try/catch blocks.

How Instructions Are Merged

  • Global instructions are loaded first and applied to all AI interactions.
  • Local instructions override or supplement global rules within the project scope.
  • Rules are processed in order: global first, then local.
Note: Local instructions take precedence over global ones when there are conflicts.

Was this article helpful?