> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# A Quick Look ChatGPT

> Overview of using ChatGPT and custom GPTs for programming tasks, debugging, scaffolding, code examples, model selection, Canvas editing, and best practices for safe, effective AI-assisted development

If you've ever spent hours debugging only to find the fix was simple, you already know how useful ChatGPT can be as a pair-programming companion. Paste an error, ask "How do I do X?", request documentation, scaffold an app, or get debugging help — ChatGPT works well for many programming tasks.

Specialized tools such as [GitHub Copilot](https://github.com/features/copilot), [Tabnine](https://www.tabnine.com), and [Blackbox AI](https://www.blackbox.ai) are often more tightly focused on development workflows and can be more productive when integrated into your IDE. Still, ChatGPT is an excellent place to start for broad guidance and rapid prototyping.

<Callout icon="lightbulb" color="#1CB2FE">
  Tip: Use ChatGPT for quick scaffolding, concept clarifications, and debugging heuristics. For repository-aware, inline suggestions, prefer IDE-integrated tools like Copilot or Tabnine.
</Callout>

## Interface overview

* The ChatGPT interface is intentionally minimal: conversation history on the left, the chat pane in the center, and controls to continue a conversation, upload files, or star important chats.
* For many typical programming questions, the general ChatGPT models provide accurate and usable answers quickly.

## Example: MySQL with Python

Below is a compact, corrected example that demonstrates connecting to MySQL, querying data, and ensuring proper resource cleanup. Note: `raise_for_status()` is for HTTP libraries — for database operations, catch `mysql.connector.Error` and make sure cursors and connections are closed in `finally`.

```python theme={null}
# python
import mysql.connector
from mysql.connector import Error

def connect_to_mysql(host, user, password, database):
    try:
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password,
            database=database
        )
        if connection.is_connected():
            print("Connected to MySQL")
            return connection
    except Error as e:
        print(f"Error connecting to MySQL: {e}")
        return None

def query_database(connection, query="SELECT * FROM your_table_name;"):
    cursor = None
    try:
        cursor = connection.cursor()
        cursor.execute(query)
        rows = cursor.fetchall()
        return rows
    except Error as e:
        print(f"Database query error: {e}")
        return None
    finally:
        if cursor:
            cursor.close()

def close_connection(connection):
    try:
        if connection and connection.is_connected():
            connection.close()
            print("MySQL connection is closed")
    except Error as e:
        print(f"Error closing connection: {e}")

# Example usage
if __name__ == "__main__":
    conn = connect_to_mysql("localhost", "user", "password", "database")
    if conn:
        rows = query_database(conn, "SELECT * FROM your_table_name;")
        if rows is not None:
            print(f"Fetched {len(rows)} rows")
        close_connection(conn)
```

## Choosing a model

Which model to use depends on your goals: cost, latency, and reasoning ability. The table below summarizes typical choices.

| Model | Use case | Notes |
| - | - | - |
| GPT-3.5 | Cost-sensitive tasks, straightforward code generation | Fast and economical for many basic programming tasks. |
| GPT-4o | General-purpose, stronger understanding | Good balance of accuracy and breadth. |
| GPT-4o with Canvas (beta) | Collaborative visual and text editing | Useful for editing visual artifacts and live updates. |
| o1-preview | Advanced reasoning and debugging | Helpful for step-by-step problem solving. |
| o1-mini | Low-latency scenarios | Faster with fewer parameters; tradeoff in depth of reasoning. |

Choose the model that matches your need for accuracy, speed, or advanced reasoning.

## Canvas: interactive editing and live updates

Canvas provides a visual, collaborative editing surface where the AI can modify and refine code or documents in real time. For example, ask Canvas to generate a boilerplate HTML page with styles and JavaScript, then request iterative changes.

A concise HTML boilerplate example with CSS and JavaScript:

```html theme={null}
<!-- html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Boilerplate Page</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
      color: #333;
      margin: 0;
      padding: 0;
    }
    header {
      background-color: #4CAF50;
      color: white;
      padding: 15px;
      text-align: center;
    }
    main {
      padding: 20px;
    }
    button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 10px 20px;
      cursor: pointer;
      font-size: 16px;
    }
    button:hover {
      background-color: #45a049;
    }

    /* Mobile friendly styles */
    @media (max-width: 600px) {
      header {
        font-size: 1.5em;
        padding: 10px;
      }
      main {
        padding: 10px;
      }
      button {
        padding: 8px 16px;
        font-size: 14px;
      }
    }
  </style>
</head>
<body>
  <header>
    <h1>Welcome to the Boilerplate Page</h1>
  </header>
  <main>
    <p>This is a simple HTML boilerplate with CSS and JavaScript.</p>
    <button id="actionButton">Click Me!</button>
    <p id="message"></p>
  </main>
  <script>
    const actionButton = document.getElementById("actionButton");
    const messageElement = document.getElementById("message");

    actionButton.addEventListener("click", () => {
      alert("Hello!");
      messageElement.textContent = "Button clicked! Hello, World!";
    });
  </script>
</body>
</html>
```

## Converting to TypeScript

Browsers do not run TypeScript directly — you must transpile TypeScript to JavaScript using the TypeScript compiler, Vite, Webpack, or another bundler/transpiler. Example fragment:

```typescript theme={null}
// typescript
const actionButton = document.getElementById("actionButton") as HTMLButtonElement | null;
const messageElement = document.getElementById("message") as HTMLParagraphElement | null;

if (actionButton && messageElement) {
  actionButton.addEventListener("click", () => {
    alert("Hello!");
    messageElement.textContent = "Button clicked! Hello, World!";
  });
}
```

## Limitations: context and workspace awareness

* Canvas edits only know the immediate content inside the canvas. They do not automatically inspect your entire codebase.
* IDE-integrated tools (e.g., [GitHub Copilot](https://github.com/features/copilot), [Tabnine](https://www.tabnine.com)) analyze your repository and local context to make suggestions tailored to project structure.
* Use ChatGPT for broad guidance, scaffolding, and common troubleshooting. For repository-aware changes, prefer tools that have access to your codebase.

## Custom GPTs

ChatGPT supports custom GPTs: specialized instruction sets, added knowledge, or combined skills. A "Code Copilot" style custom GPT can offer focused commands and shortcuts to help with coding tasks.

Example custom command signatures:

```TypeScript theme={null}
/help(any_question?: string)
/fix(any: string)
/quick_fix(any: string)
/explain(any: string)
```

These can be customized to provide quick fixes, detailed explanations, code reviews, or to read content from provided URLs. Note that the custom GPT UI may occasionally produce transient errors — regenerating the response often helps.

## HTTP with Python: quick and robust examples

Compact, corrected examples for common HTTP tasks using the [requests](https://docs.python-requests.org/en/latest/) library.

Simple GET:

```python theme={null}
# python
import requests

url = "https://api.example.com/data"
response = requests.get(url, timeout=5)
print("Response:", response.text)
```

GET with parameters and timeout:

```python theme={null}
# python
params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get(url, params=params, timeout=5)
response.raise_for_status()
print("JSON:", response.json())
```

POST with JSON payload and robust error handling:

```python theme={null}
# python
import logging
import requests
from typing import Optional, Any

logging.basicConfig(level=logging.INFO)

def send_post_request(url: str, payload: dict, timeout: int = 10) -> Optional[Any]:
    try:
        response = requests.post(url, json=payload, timeout=timeout)
        response.raise_for_status()  # Raises HTTPError for 4xx/5xx
        if response.status_code == 201:  # 201 Created
            logging.info("Data successfully created.")
        else:
            logging.info(f"Received status code: {response.status_code}")
        return response.json()
    except requests.exceptions.RequestException as e:
        logging.error(f"An error occurred: {e}")
        return None

if __name__ == "__main__":
    url = "https://api.example.com/data"
    payload = {"key1": "value1", "key2": "value2"}
    data = send_post_request(url, payload)
    if data:
        logging.info(f"Response data: {data}")
    else:
        logging.error("Failed to create data.")
```

File upload example:

```python theme={null}
# python
import requests

file_path = 'example.txt'
with open(file_path, 'rb') as f:
    files = {'file': f}
    response = requests.post("https://api.example.com/upload", files=files, timeout=10)
    response.raise_for_status()
    print("Upload response:", response.json())
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/saITvJxm5YlZa_WW/images/AI-Assisted-Development/Introduction-to-AI-Assisted-Development/A-Quick-Look-ChatGPT/dark-docs-requests-post-json-201.jpg?fit=max&auto=format&n=saITvJxm5YlZa_WW&q=85&s=3f5d8937f85b5cee9be360e53708814e" alt="A dark-mode screenshot of a documentation/chat interface showing a section titled &#x22;What Happens When You Run This Code?&#x22; with numbered steps about requests.post, JSON payloads, and HTTP status codes (including 201 Created). A message input field labeled &#x22;Message Code Copilot&#x22; and a cursor are visible at the bottom." width="1920" height="1080" data-path="images/AI-Assisted-Development/Introduction-to-AI-Assisted-Development/A-Quick-Look-ChatGPT/dark-docs-requests-post-json-201.jpg" />
</Frame>

## Best practices and caveats

* Do not blindly copy-paste generated code. Review and understand it before committing.
* Add proper error handling, input validation, and structured logging for production code.
* Always include timeouts for network calls to avoid hanging requests.
* Replace ad-hoc `print` statements with `logging` for larger applications.
* Validate response content before calling `.json()` — the server may not always return JSON.

<Callout icon="warning" color="#FF6B6B">
  Warning: Generated code can contain hard-coded values, magic numbers, and missing validations. Always audit for security, edge cases, and performance before deploying.
</Callout>

## Code review and custom evaluators

Custom GPTs can be trained with coding best practices (e.g., from books like [Code Complete](https://en.wikipedia.org/wiki/Code_Complete)) and common articles to provide structured code reviews. They can flag hard-coded values, missing exception handling, magic numbers, and recommend replacing prints with logging.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/saITvJxm5YlZa_WW/images/AI-Assisted-Development/Introduction-to-AI-Assisted-Development/A-Quick-Look-ChatGPT/code-monkey-review-issues-python-snippet.jpg?fit=max&auto=format&n=saITvJxm5YlZa_WW&q=85&s=5fe1792d91600c736e95c75999d1132a" alt="Screenshot of a dark-themed code-review/chat interface titled &#x22;Code Monkey&#x22; showing a numbered list of issues (error handling, hardcoded values, validation, magic number 201, print statements) and a &#x22;Suggested Improvements&#x22; section with a Python code snippet. The UI includes a message input box at the bottom." width="1920" height="1080" data-path="images/AI-Assisted-Development/Introduction-to-AI-Assisted-Development/A-Quick-Look-ChatGPT/code-monkey-review-issues-python-snippet.jpg" />
</Frame>

Example review feedback (summary)

* Strengths: Clean structure, readable code.
* Issues: Missing exception handling, hard-coded values, assumption that responses always contain JSON, use of `print` instead of logging, magic numbers like `201` used without context.
* Recommendations: Add `try`/`except`, use `response.raise_for_status()`, validate `Content-Type` before parsing JSON, replace `print` with `logging`, and parameterize expected status codes or document them.

## Wrap-up

This lesson provided a quick overview of using ChatGPT for programming:

* Use ChatGPT for quick samples, scaffolding, and troubleshooting.
* Canvas is useful for iterative visual and textual edits.
* Advanced reasoning models and custom GPTs can help with deeper debugging and code reviews.
* For repository-aware suggestions, prefer IDE-integrated tools (e.g., [GitHub Copilot](https://github.com/features/copilot), [Tabnine](https://www.tabnine.com)) that read your codebase.

Use these tools to accelerate development, but always review and test generated code before using it in production.

## Links and references

* [MySQL](https://www.mysql.com)
* [requests documentation](https://docs.python-requests.org/en/latest/)
* [GitHub Copilot](https://github.com/features/copilot)
* [Tabnine](https://www.tabnine.com)
* [Code Complete (Wikipedia)](https://en.wikipedia.org/wiki/Code_Complete)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/ai-assisted-development/module/d64636e3-1af6-4ab7-934f-5676c4266ac7/lesson/f1811de9-574a-4cb8-a4b1-ca141663269b" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.