Skip to content

Commit

Permalink
[DO NOT MERGE] Official megabranch of "Copilot Chat Cookbook" with ne…
Browse files Browse the repository at this point in the history
…w map topic structure (#53046)

Co-authored-by: hubwriter <hubwriter@github.com>
Co-authored-by: Ben Ahmady <32935794+subatoi@users.noreply.github.com>
Co-authored-by: Tiago Pascoal <tspascoal@github.com>
Co-authored-by: Christopher Harrison <geektrainer@github.com>
Co-authored-by: Sophie <29382425+sophietheking@users.noreply.github.com>
Co-authored-by: Sunbrye Ly <56200261+sunbrye@users.noreply.github.com>
Co-authored-by: sunbrye <sunbrye@github.com>
Co-authored-by: Hector Alfaro <hectorsector@github.com>
Co-authored-by: Siara <108543037+SiaraMist@users.noreply.github.com>
  • Loading branch information
10 people authored Nov 22, 2024
1 parent 286327d commit 262ab79
Show file tree
Hide file tree
Showing 34 changed files with 1,999 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
title: Debugging invalid JSON
shortTitle: Debug invalid JSON
intro: '{% data variables.product.prodname_copilot_chat_short %} can identify and resolve syntax errors or structural issues in JSON data.'
versions:
feature: copilot
category:
- 'Debugging code'
complexity:
- Intermediate
octicon: bug
topics:
- Copilot
---

When working with JSON data, you may encounter issues such as trailing commas, mismatched braces, or incorrect data types that make the JSON invalid. {% data variables.product.prodname_copilot_chat %} can help you debug and fix these errors by suggesting corrections to fix invalid JSON.

## Example scenario

Consider a scenario where an application consumes JSON data from an API, but the response fails to parse due to invalid formatting. You receive the error message:

```bash
Error: Parse error
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
```

Below is the JSON data that caused the error:

```json
{
"location": "San Francisco",
"current_weather": {
"temperature": 18,
"unit": "Celsius",
"conditions": "Cloudy
},
"forecast": {
"day": "Monday",
"high": 22,
"low": 15,
"precipitation": 10
}
}
```

## Example prompt

```Why is my JSON object invalid and how can I fix it?```

## Example response

{% data reusables.copilot.example-prompts.response-is-an-example %}

{% data variables.product.prodname_copilot_short %} might suggest that your JSON is invalid because it is missing a closing quote for the `conditions` value. Here is the corrected JSON:

```json
{
"location": "San Francisco",
"current_weather": {
"temperature": 18,
"unit": "Celsius",
"conditions": "Cloudy"
},
"forecast": {
"day": "Monday",
"high": 22,
"low": 15,
"precipitation": 10
}
}
```

In this example response, {% data variables.product.prodname_copilot_short %}'s suggestions include fixing the closing quote for the `conditions` value, which resolves the JSON parsing error.

## Further reading

{% data reusables.copilot.example-prompts.further-reading-items %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
---
title: Handling API rate limits
shortTitle: Handle API rate limits
intro: '{% data variables.product.prodname_copilot_chat_short %} can help handle API rate limits by suggesting code that detects implements retry logic.'
versions:
feature: copilot
category:
- 'Debugging code'
complexity:
- Intermediate
octicon: bug
topics:
- Copilot
---

When making requests to APIs, it's common to encounter rate limits that restrict the number of calls you can make within a certain time frame. {% data variables.product.prodname_copilot_chat %} can help you handle these limits by suggesting code to detect rate limit responses and automatically retry requests after a delay.

## Example scenario

The following Python code fetches weather data from an external API. If the API has rate limits, requests may fail when limits are exceeded, and your app may need a way to handle these responses gracefully by implementing retry logic.

```python
from flask import Flask, request
import requests

app = Flask(__name__)

WEATHER_API_URL = "https://api.example.com/weather"

@app.route('/get_weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
# Simulate an API request to the external weather service
response = requests.get(WEATHER_API_URL, params={"city": city})
weather_data = response.json()

return weather_data
```

## Example prompt

`How can I handle API rate limits within get_weather().`

## Example response

{% data reusables.copilot.example-prompts.response-is-an-example %}

{% data variables.product.prodname_copilot_short %} might suggest code that implements a retry mechanism with exponential backoff to limit the frequency of retry attempts.

For example:

```python
import requests
from flask import Flask, request
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

app = Flask(__name__)

WEATHER_API_URL = "https://api.example.com/weather"

def requests_retry_session(
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None,
):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session

@app.route('/get_weather', methods=['GET'])
def get_weather():
city = request.args.get('city')
try:
response = requests_retry_session().get(WEATHER_API_URL, params={"city": city})
response.raise_for_status()
weather_data = response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}, 500

return weather_data
```

In this example, {% data variables.product.prodname_copilot_short %}'s suggestions include setting up a retry session that allows the code to automatically retry requests if they fail due to specific status codes (500, 502, 504). The `backoff_factor` gradually increases the delay between retries, helping avoid exceeding the API's rate limit further.

## Further reading

{% data reusables.copilot.example-prompts.further-reading-items %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
title: Debugging errors
intro: 'Discover ways that you can use {% data variables.product.prodname_copilot %} to debug errors during development.'
versions:
feature: copilot
topics:
- Copilot
children:
- /debugging-invalid-json
- /handling-api-rate-limits
---
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
---
title: 'Documenting legacy code'
shortTitle: Document legacy code
intro: '{% data variables.product.prodname_copilot_chat_short %} can help with documenting legacy code.'
versions:
feature: copilot
category:
- 'Documenting code'
complexity:
- Simple
octicon: book
topics:
- Copilot
---
Working with legacy code can be challenging for developers, especially when the code is complex or not well-documented. In such cases, it can be helpful to use Copilot Chat to explain unclear or complex code to other developers or to document it for future reference.

## Example scenario

The block of COBOL below connects to a database and inserts a record. The code lacks documentation, which makes it difficult to understand what it does and how it works.

```text
IDENTIFICATION DIVISION.
PROGRAM-ID. INSERT-RECORD.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-STATUS-FLAGS.
05 WS-DB-STATUS PIC X(2).
88 WS-SUCCESS VALUE "00".
05 WS-SQLCODE PIC S9(9) COMP.
05 WS-ERROR-MSG PIC X(50).
LINKAGE SECTION.
01 LS-PARAMETERS.
05 LS-PERSON-RECORD.
10 PERSON-ID PIC 9(6).
10 PERSON-NAME PIC X(50).
10 PERSON-AGE PIC 9(3).
05 LS-RESULT PIC X.
88 SUCCESS VALUE 'T'.
88 FAILED VALUE 'F'.
PROCEDURE DIVISION USING LS-PARAMETERS.
PERFORM INSERT-AND-VALIDATE
GOBACK
.
INSERT-AND-VALIDATE.
EXEC SQL
INSERT INTO persons (id, name, age)
VALUES (:PERSON-ID, :PERSON-NAME, :PERSON-AGE)
END-EXEC
IF SQLCODE = 0
EXEC SQL COMMIT END-EXEC
SET SUCCESS TO TRUE
ELSE
EXEC SQL ROLLBACK END-EXEC
SET FAILED TO TRUE
STRING "DB Error: " SQLCODE
DELIMITED BY SIZE
INTO WS-ERROR-MSG
DISPLAY WS-ERROR-MSG
END-IF
.
```

## Example prompt

We can use a simple prompt to ask {% data variables.product.prodname_copilot_chat_short %} to document the code.

`Document this code`

> [!NOTE] If you want the documentation generated in another format like Markdown, you can specify the desired output format in the prompt. For example: `Document this code in Markdown`.
## Example response

{% data reusables.copilot.example-prompts.response-is-an-example %}

Copilot will provide a text overview of the code block, and an updated version with comments explaining the logic and purpose of each section.

For example:

```text
*****************************************************************
* Program: INSERT-RECORD
* Purpose: Inserts a person record into the database with
* transaction management and error handling
*****************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. INSERT-RECORD.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
* Status flags and error handling variables
01 WS-STATUS-FLAGS.
05 WS-DB-STATUS PIC X(2). *> Database status
88 WS-SUCCESS VALUE "00". *> Success flag
05 WS-SQLCODE PIC S9(9) COMP. *> SQL return code
05 WS-ERROR-MSG PIC X(50). *> Error message
LINKAGE SECTION.
* Input/Output parameters
01 LS-PARAMETERS.
05 LS-PERSON-RECORD.
10 PERSON-ID PIC 9(6). *> Person ID
10 PERSON-NAME PIC X(50). *> Person name
10 PERSON-AGE PIC 9(3). *> Person age
05 LS-RESULT PIC X. *> Operation result
88 SUCCESS VALUE 'T'. *> Success flag
88 FAILED VALUE 'F'. *> Failure flag
PROCEDURE DIVISION USING LS-PARAMETERS.
PERFORM INSERT-AND-VALIDATE
GOBACK
.
*****************************************************************
* Handles database insertion with transaction management
*****************************************************************
INSERT-AND-VALIDATE.
EXEC SQL
INSERT INTO persons (id, name, age)
VALUES (:PERSON-ID, :PERSON-NAME, :PERSON-AGE)
END-EXEC
IF SQLCODE = 0
EXEC SQL COMMIT END-EXEC *> Commit if successful
SET SUCCESS TO TRUE
ELSE
EXEC SQL ROLLBACK END-EXEC *> Rollback if failed
SET FAILED TO TRUE
STRING "DB Error: " SQLCODE
DELIMITED BY SIZE
INTO WS-ERROR-MSG
DISPLAY WS-ERROR-MSG
END-IF
.
```

## Further reading

{% data reusables.copilot.example-prompts.further-reading-items %}
Loading

0 comments on commit 262ab79

Please sign in to comment.