> AI agents: For documentation discovery and navigation, see [llms.txt](/llms.txt).

# Best practices for using AI in VS Code

This article covers good practices for using AI in Visual Studio Code. Start with a bounded task, provide relevant context, and verify the result. The first sections cover that workflow. [Go further with configuration and optimization](#go-further-when-you-need-to) when you have a recurring need.

<div class="docs-action" data-show-in-doc="false" data-show-in-sidebar="true" title="How AI works in VS Code">
Learn about the agent loop, context window, tools, and other core concepts.

* [Read about core concepts](/docs/agents/concepts/agents.md)

</div>

## Pick the right tool for the task

AI in VS Code offers several interaction modes. Choosing the right one for the task at hand saves time and produces better results.

| Tool | Best for | Example |
|------|----------|---------|
| [Inline suggestions](/docs/editing/ai-powered-suggestions.md) | Staying in the flow while writing code | Inline suggestions, variable names, boilerplate |
| [Inline chat](/docs/chat/inline-chat.md) | Targeted, in-place edits without switching context | Refactoring a function, adding error handling |
| [Agents](/docs/agents/overview.md) | Single-file or multi-file tasks that benefit from tool calls, workspace search, terminal checks, or iteration | Implementing a feature, fixing a failing test, updating project configuration |
| [Plan](/docs/agents/run/planning.md) | Structured planning before implementation | Designing an architecture or migration strategy |
| [Smart actions](/docs/editing/copilot-smart-actions.md) | Built-in, specialized one-step tasks | Generating commit messages, fixing errors, renaming symbols |

## Apply the workflow to your project

When you're ready to use an agent in your own project, start with one bounded task in a project you know:

1. Open a trusted project. Commit or stash unrelated work so that you can distinguish the agent's edits from your own changes.

1. Choose a small task and define an observable result. If the approach is unclear, ask questions in chat or use the [Plan role](/docs/agents/run/planning.md) before implementation.

1. Provide the relevant files, errors, constraints, and existing test commands. For example:

    ```prompt
    Add empty-state text to the results view. Limit changes to the existing
    view and its tests. Follow the current component patterns, run the
    existing tests for this area, and summarize the behavior you verified.
    ```

1. In the [Chat view](/docs/agents/run/chat-view.md), select **Copilot** from the **Session Target** UI control, select the **Agent** role, and keep **Manual permissions** for an interactive first task.

    Keep the other session defaults for your first task. When you need a different setup, change one option at a time so that you can identify its effect.

1. Review each approval request. When the agent finishes, inspect every changed file and run the relevant tests yourself.

1. Commit only the intended changes. If the result is wrong, [choose a recovery action](/docs/agents/guides/get-agent-back-on-track.md#choose-a-recovery-action), such as providing focused feedback or restoring a checkpoint.

Stopping a request doesn't undo completed actions. Checkpoints restore affected workspace files and chat history, but they don't reverse completed terminal commands, deployments, or changes to external services. Use Git and the external service's recovery controls for those effects.

For step-by-step guides in an existing project, [explore a codebase](/docs/agents/guides/explore-a-codebase.md), [add a feature](/docs/agents/guides/add-a-feature.md), or [refactor without changing behavior](/docs/agents/guides/refactor-safely.md).

## Write effective prompts

The quality of AI responses depends on the clarity and specificity of your prompt. Writing requests with a clear goal, constraints, and relevant context is often called *prompt engineering*. These techniques help you get better results.

* **Be specific about inputs, outputs, and constraints.** State the programming language, frameworks, and libraries you want to use. Describe expected behavior or include example input and output.

    ```prompt
    Write a TypeScript function that validates email addresses.
    Return true for valid addresses, false otherwise. Don't use regex.
    Example: validateEmail("user@example.com") returns true
    Example: validateEmail("invalid") returns false
    ```

* **Break down complex tasks.** Instead of asking for an entire feature at once, decompose it into smaller, well-scoped steps. This approach produces more reliable results and makes it easier to catch problems early.

* **Include expected output for verification.** Provide test cases, expected results, or acceptance criteria so the AI can verify its own work. This step is one of the highest-leverage things you can do.

    ```prompt
    Implement a rate limiter using the token bucket algorithm.
    Write unit tests that verify: 10 requests/second allowed,
    11th request rejected, bucket refills after 1 second.
    Run the tests after implementing.
    ```

* **Avoid vague prompts.** A prompt that omits the goal, target scope, or verification check forces the AI to guess. State what needs to change, where to look, and how to confirm the result.

    | Task | Vague prompt | Actionable prompt |
    |------|--------------|-------------------|
    | Edit the current file | "Fix this file." | "In `#auth.ts`, return `401` when the token is expired instead of throwing an unhandled error. Keep existing error messages unchanged and run the auth unit tests." |
    | Debug a failure | "Why is this broken?" | "Investigate this stack trace from `npm test` without editing files yet. Identify the root cause in `#checkout.ts`, then propose a fix." |
    | Update configuration or UI | "Improve the layout." | "In `#header.css`, prevent the navigation links from wrapping below 768px while keeping the search input aligned right. Verify at mobile and desktop widths." |
    | Explore the codebase | "How does this work?" | "Explain how background jobs are queued and retried in this repository. Cite the entry points and configuration files without editing code." |

* **Iterate with follow-up prompts.** Refine responses by adding constraints or corrections in follow-up messages rather than rewriting the entire prompt.

* **Course-correct early.** If the AI is heading in the wrong direction, [steer it](/docs/chat/chat-overview.md#send-messages-while-a-request-is-running) while the request is running by opening the **Send** dropdown and selecting **Steer with Message** or **Stop and Send**. If an agent stops responding, select **Stop** and check whether a terminal command or approval prompt is waiting for your input.

    For help deciding whether to steer, restore changes, or start fresh, see [Get an agent back on track](/docs/agents/guides/get-agent-back-on-track.md).

* **Tell the AI to ask clarifying questions.** If a task is ambiguous, instruct the AI to ask you questions before proceeding. This leads to more accurate results than guessing at requirements.

Adapt the [prompt examples](/docs/agents/guides/prompt-examples.md) for your task, including the multi-turn examples for refining a result. For a video introduction, watch [Core principles of prompt engineering with GitHub Copilot](https://www.youtube.com/watch?v=hh1nOX14TyY).

## Provide the right context

The AI responds more accurately when it has relevant context. Use these techniques to point the AI at the right information:

* The AI automatically performs code search to gather relevant context. When your prompt is ambiguous, you can guide the AI by referencing specific files, folders, or symbols in your prompt with `#<file>`, `#<folder>`, or `#<symbol>`.

* To pull information from web pages or GitHub repositories, use `#fetch` to provide the AI with up-to-date information beyond your codebase or use tools from MCP servers like GitHub MCP.

* Reference VS Code environment context such as source control changes, terminal output, or test failures to help the AI understand the current state of your project and provide more relevant responses.

* Add images or screenshots to let the AI analyze visual content.

* Use the [integrated browser](/docs/debugtest/integrated-browser.md) to preview your app and manually add page elements, screenshots, or console logs as context.

* Give agents [browser tools](/docs/agents/run/browser-tools.md) to exercise user flows, inspect the result, fix problems, and verify their changes autonomously.

For more information, see [adding context to chat prompts](/docs/chat/copilot-chat-context.md) and [configuring tools](/docs/agents/run/tools.md).

### Keep sessions focused

Reusing one long session across unrelated tasks fills the context window with stale files and earlier decisions, which degrades response quality and increases token usage.

* **Stay in the current session** while iterating on the same task, refining an implementation, or fixing follow-up test failures.
* **Run `/compact`** when you want to stay on the same task after long exploration, repeated command output, or superseded approaches. You can tell the agent what to retain, for example `/compact keep the API contract and test commands`.
* **Start a fresh chat** when switching to an unrelated task or after completing a milestone. Select **New Chat**, or enter `/clear` in the Chat view to archive the current chat and open a new one in a single step. In the Agents window, select **New Session** and mark finished sessions as **Done**.

None of these actions revert saved file edits. For detailed options including forks, side chats, and nested sessions, see [Manage agent sessions](/docs/agents/run/sessions/manage-sessions.md#start-a-new-or-related-conversation).

## Plan first, then implement

For complex changes that span multiple files, separate planning from implementation. This approach prevents the AI from solving the wrong problem and avoids spending [AI credits](/docs/agents/concepts/language-models.md#ai-credits-and-model-costs) on code that needs to be thrown away.

1. **Explore.** Use **Ask** to read the relevant code and understand how it works before making changes.
1. **Plan.** Enter `/plan` to use the [Plan agent](/docs/agents/run/planning.md) and create a structured implementation plan. Review and refine the plan before executing.
1. **Implement.** Use the plan's handoff action to start implementing in **Agent**, or switch to **Agent** manually. Include tests or expected outputs so the agent can verify its work.
1. **Review.** [Inspect the diff and validation results](/docs/agents/run/review-code-edits.md) before committing. If the result doesn't match the plan, request a focused revision.

## Review and verify AI output

AI-generated code can contain bugs, security issues, or subtle logic errors. Always treat AI output as a starting point that needs review.

* **Review before integrating.** Read through generated code before you commit or merge the changes. Pay attention to edge cases, error handling, and assumptions the AI might have made.

* **Run tests after AI changes.** Include test cases in your prompt so the AI can verify its own work. If the AI doesn't run tests automatically, run them yourself before moving on.

* **Use checkpoints to rewind file edits and chat.** If the agent goes off track, hover over an earlier request in chat and select **Restore Checkpoint** to restore affected workspace files and chat history. Learn more about [checkpoints](/docs/agents/run/review-code-edits.md#restore-a-checkpoint). Checkpoints don't reverse completed commands or changes to external services.

* **Recover from unresponsive turns.** If an agent stops responding, select **Stop** to cancel the turn, check whether a terminal command or approval prompt is waiting for input, and verify your sign-in if an authorization error appears.

* **Check for security issues.** Review AI-generated code for common vulnerabilities such as injection flaws, hardcoded secrets, or missing input validation. Avoid pasting credentials or sensitive data into prompts.

For more information, see [GitHub Copilot security](/docs/agents/run/security.md) and the [GitHub Copilot Trust Center](https://copilot.github.trust.page/faq).

## Go further when you need to

You don't need these options to complete a first task. Use them when a specific problem or recurring workflow calls for more control:

| When you need to | Where to go |
|------------------|-------------|
| Balance quality, speed, and cost across models | Start with **Auto**, or follow [Compare and choose models](/docs/agents/guides/choose-a-model.md) and [Compare model results](/docs/agents/run/compare-models.md). Adjust [thinking effort](/docs/agent-customization/language-models.md#configure-thinking-effort-and-context-size) only when a task needs deeper analysis. |
| Switch agent harnesses or execution environments | Keep the Copilot harness by default, or compare [agent harnesses](/docs/agents/run/agent-harnesses.md#requirements-and-setup). Use [remote sessions](/docs/agents/run/remote-agent-sessions.md) or [cloud sessions](/docs/agents/run/cloud-sandbox-sessions.md) `feature(cloud-sessions)` when tools shouldn't run locally. |
| Stop repeating project rules or team workflows | Open the [Agent Customizations editor](/docs/agent-customization/overview.md#agent-customizations-editor) (**Chat: Open Customizations**) and create one starter item, such as a workspace instruction for your test command or coding convention, or an agent skill for a repeatable task. Follow [Adapt agents to your project](/docs/agents/guides/customize-copilot-guide.md) to verify one change at a time. |
| Keep long or parallel conversations organized | Start a fresh chat when you switch tasks or when repeated corrections create conflicting context. [Compact context](/docs/agents/run/sessions/manage-sessions.md#compact-conversation-context) with `/compact` when you want to stay on the same task with a shorter history, [fork a session](/docs/agents/run/sessions/manage-sessions.md#fork-a-chat-session) to explore alternatives, delegate investigations to [subagents](/docs/agents/run/subagents.md#subagents-by-harness), or [run parallel tasks in separate worktrees](/docs/agents/guides/delegate-two-tasks.md). |
| Reduce unexpected AI credit consumption | Both Copilot Free and paid individual plans (Copilot Pro, Copilot Pro+, and Copilot Max) have monthly allowances. Keep **Auto** selected and follow [Optimize AI credit usage](/docs/agents/guides/optimize-usage.md) to scope tasks, trim context, and compare model costs. Use the [Cache Explorer](/docs/agents/agent-troubleshooting/cache-explorer.md) if session metrics show low prompt-cache reuse. |

### Work with large codebases

Start with a bounded behavior or component instead of asking the agent to understand the entire repository. [Workspace context](/docs/agents/reference/workspace-context.md) explains how search and indexing help locate relevant code.

For monorepos or projects with multiple services, use [multi-root workspaces](/docs/editing/workspaces/multi-root-workspaces.md) to scope the workspace, and record non-obvious module boundaries in [project instructions](/docs/agent-customization/custom-instructions.md). [Exclude generated and noisy files from search](/docs/agents/reference/workspace-context.md#improve-agent-search-with-exclusion-settings) to keep searches focused.

## Next steps

* [Find a guide for your next project task](/docs/agents/guides/overview.md#work-on-a-project).
* [Choose a recovery action when an agent gets off track](/docs/agents/guides/get-agent-back-on-track.md#choose-a-recovery-action).
