Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cody prompting guide #367

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
196 changes: 196 additions & 0 deletions docs/cody/core-concepts/prompting-guide.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# Cody Prompting Guide

<p className="subtitle">These docs help you learn some of the best practices and tips for effective techniques to maximize your Cody experience.</p>

## Overarching Recommendation: Treat Cody Like a New Team Member

When collaborating with Sourcegraph Cody, it's helpful to approach it as if you were working with a new engineer who is unfamiliar with your project. Just as you would provide a new team member with detailed information and context about the codebase and the tasks at hand, you should do the same with Cody.

Always provide more specific information about a task to ensure Cody understands your requirements clearly. The more context and details you provide, the better Cody can assist you in generating relevant and accurate code.

Consider the following examples:

❌ Instead of a vague prompt like:

```
How can I filter products in JavaScript?
```

✅ Provide a more specific prompt with details:

```
I have an array of product objects in JavaScript, where each object has the following properties: id, name, category, and price. How can I write a function to filter the products by category?
```

By treating Cody as a new team member and providing detailed information, you'll establish a more effective collaboration and get better results.

Let's split these docs into two parts:

- **Preparation**: How you'll prepare your code for Cody
- **Prompting**: How you will create effective prompts for Cody

## Preparation

Before diving into prompting techniques, it's crucial to set the stage for a successful collaboration with Cody. Here are some key preparation steps:

### Choose descriptive variable names

Using clear and descriptive names for variables, functions, and classes is essential for making your code readable and understandable, not only for yourself but also for Cody. Avoid abbreviations or ambiguous names that may confuse your AI assistant.

✅ Good example:

```php
function calculateTotalPrice($items, $taxRate) {
// ...
}
```

❌ Bad example:

```php
function calc($i, $t) {
// ...
}
```

### Write clear comments and docstrings

In addition to variable names, comments and docstrings play a crucial role in guiding Cody's understanding of your code. Treat them as a way to communicate with Cody, just like you would with a new engineer. Explain complex logic, algorithms, or project-specific concepts to give Cody the necessary context.

✅ Good example:

```javascript
/**
* Calculate the shipping cost based on the order total.
* - For orders under $50, the shipping cost is $5.
* - For orders between $50 and $100, the shipping cost is $10.
* - For orders above $100, shipping is free.
*
* @param {number} orderTotal - The total amount of the order.
* @returns {number} The shipping cost, determined by the following rules:
*/
function calculateShippingCost(orderTotal) {
// Cody will autocomplete here
}
```

A bonus here is that Cody can generate these docstrings for you, so you don't have to write them manually. You can use the **Document Code** command to do this.

IMAGE HERE: cody-document-code.jpg

## Part 2: Prompting

Now that your code is well-prepared, it's time to focus on crafting effective prompts for Cody. Consider the following best practices:

### Provide Specific Information

When asking Cody for assistance, provide as much detail as possible. Include information about the problem, expected behavior, constraints, and any project-specific requirements.

Be sure to include comprehensive details about the problem, what you expect to happen, any limitations, and specific requirements related to your project.

❌ Bad example:

```
How do I calculate discounts based on loyalty points in Laravel?
```

✅ Good example:

```
I need to calculate discounts based on customer loyalty points.

- If the customer has loyalty points above 500, apply a 10% discount.
- If the customer has loyalty points between 200 and 500, apply a 5% discount.
- If the customer has loyalty points below 200, no discount is applied.

Create a function that takes the total amount and loyalty points as input and returns an object with the discount percentage and discount amount.
```

### Provide Specific Context

Providing detailed context is the most effective way to enhance Cody's assistance. Approach this as if you are explaining the situation to a new engineer.

You should:

- Reference important files and symbols
- Provide examples from other similar functions

To provide specific context from your codebase, you can use the `@-` mention feature to provide syntax. You can mention specific files, sections of code, and symbols to help Cody understand your code.

Here is an example of bringing in specific lines of code. The shortcut to do this is to highlight code and press `Opt+L` on Mac or `Ctrl+L` on Windows.

IMAGE HERE: cody-mention-snippet.jpg

Here is an example of `@-` mentioning a specific file:

IMAGE HERE: cody-mention-file.jpg

### Provide examples and test cases

Include examples and test cases when applicable to clarify your expectations. Demonstrate edge cases or handling of special conditions to guide Cody in generating robust code.

❌ Bad example:

```
I need to validate email addresses in JavaScript
```

✅ Good example:

```
Create a function to validate email addresses in JavaScript. Return true for valid email addresses and false for invalid ones. Here are some example test cases:

Valid:
- "[email protected]"
- "[email protected]"

Invalid:
- "john@example"
- "jane.doe@example."
- "invalid.email"

Please write the function
```

### Iterate and refine

Start with a general prompt and incrementally add more details based on Cody's responses. Take advantage of the fact that you can chat with Cody. Bring the back and forth conversation, especially if you didn't like Cody's first response. Review the generated code or suggestions, provide feedback, and refine your prompts to get the desired results.

Initial prompt:

```
I need to calculate the total price of an order. Help me write the function
```

Refined prompt:

```
Thanks. I forgot to mention:

- The function should take an array of order items as input
- We need to apply a 10% discount if the total price exceeds $100
- Final total should be rounded to two decimal places

Please update the function
```

### Leverage Cody's strengths

Utilize [Cody's capabilities](/cody/capabilities) for generating boilerplate code, common patterns, and repetitive tasks. Prompt it to assist with unit tests, documentation, and error handling to save time and ensure code quality.

✅ Good example:

```
Help me write tests for the `calculateAverageRating` function. Here are the test cases I have in mind:

- Empty ratings array should return 0
- Array with one rating should return that rating
- Array with multiple ratings should calculate the average correctly

Make sure the tests cover any edge cases or potential issues. Thanks!
```

You can also use the **Generate Tests** command to generate tests for your code.

It's recommended to try out these tips and make your experience better with Cody. If you have any questions regarding Cody, you can always [ask our community](https://community.sourcegraph.com), [Discord](https://discord.com/invite/s2qDtYGnAE), or [create a post on X](https://twitter.com/sourcegraphcody).

Loading