AI 能否最终生成最佳实践代码?我认为可以。

86 阅读5分钟

几周前,我发布了一篇关于使用 Cursor 创建提示的最佳实践和专业提示的文章。这些提示的核心思想是尽可能多地为代码生成器提供上下文。

在 Cursor 中,可以通过两种主要方式实现这一点:

  1. 通过在代码生成器窗口中或通过 Cursor 设置直接提及文档或代码;
  2. 通常通过创建更具说明性的提示,例如 “始终使用.env 文件存储凭据”。

使用 Cursor 中的提及

在技术领域,尤其是在人工智能方面,有一件事是你会习惯的,那就是变化的速度非常快。

自从我写了那篇文章以来,发生了很多变化。像 Cursor 和 Windsurf 这样的工具引入了规则文件。规则文件以及了解哪些 LLM 最适合什么任务,是我使用提示和编码方式的一个游戏规则改变者。

你可以将规则文件视为一个可以指定项目中提示必须遵循的更长、更具说明性规则的地方。如果你习惯在编码中使用依赖文件,那么它有点像增强版的依赖文件。

与此同时,我们已经从生成式 AI 助手转向了协作式智能体 AI。

将这些结合起来,结果相当惊人!

这是一个例子。

假设我正在使用Cursor构建一系列数据应用程序,并使用Airbyte作为数据移动平台,使用 Streamlit 作为前端。我正在使用 Python 编写代码,并使用 Airbyte API 库。这是我的基本 “技术栈”。

我可以在项目文件夹根目录下的.cursorrules文件中定义这一点。

- name: "Import Required Libraries"
    action: "Always ensure the required libraries are imported at the top of the file."
    details:
      - "os: To load environment variables."
      - "dotenv: To load .env file for credentials."
      - "pandas: For mapping API results to DataFrame."
      - "airbyte_api_client: For interacting with Airbyte APIs."
      - "airbyte_api_client.api: Import API-specific modules."
      - "airbyte_api_client.configuration: To configure the API client."
      - "requests: For token management and refreshing the token."

我还可以进一步告诉 Cursor 我的一些编码偏好,例如我想要如何进行身份验证、存储敏感密钥以及如何处理数据。

- name: "Store Sensitive Information Securely"
    action: "All API keys, tokens, client IDs, and client secrets must be stored in a .env file."
    details:
      - ".env file example:"
        content: |
          AIRBYTE_API_URL=https://your-airbyte-instance.com
          AIRBYTE_CLIENT_ID=your_client_id
          AIRBYTE_CLIENT_SECRET=your_client_secret
      - "Load credentials using the python-dotenv library."
      - "Example code:"
        content: |
          from dotenv import load_dotenv
          import os
          load_dotenv()
          AIRBYTE_API_URL = os.getenv('AIRBYTE_API_URL')
          AIRBYTE_CLIENT_ID = os.getenv('AIRBYTE_CLIENT_ID')
          AIRBYTE_CLIENT_SECRET = os.getenv('AIRBYTE_CLIENT_SECRET')

  - name: "Authenticate Using Bearer Token"
    action: "Use client and secret keys to fetch a new bearer token before making API requests."
    details:
      - "Add token refresh logic in a reusable function."
      - "Example function to get a fresh token:"
        content: |
          import requests

          def get_access_token():
              """
              Fetch a new access token using client ID and secret.

              Returns:
                  str: Bearer token.
              """
              url = f"{AIRBYTE_API_URL}/oauth/token"
              payload = {
                  "client_id": AIRBYTE_CLIENT_ID,
                  "client_secret": AIRBYTE_CLIENT_SECRET,
                  "grant_type": "client_credentials"
              }
              response = requests.post(url, json=payload)
              response.raise_for_status()
              return response.json()["access_token"]

这就是真正有趣的地方。我希望我的代码易于维护且结构良好。早期的生成式 AI 助手在这方面确实遇到了困难。它们经常生成庞大的代码块,虽然可以运行,但相当丑陋。我希望我的规则能够告诉 Cursor 我希望我的代码如何编写。幸运的是,智能体 AI 可以使用推理来弄清楚如何创建结构良好的代码。在 Python 世界中,PEP 8提供了关于如何编写良好代码的最佳实践的样式指南。我现在可以告诉 Cursor 在编写代码时使用此指南!

- name: "Follow PEP8 Naming Conventions"
    action: "Ensure that variable, function, and class names adhere to PEP8 standards."
    details:
      - "Use snake_case for variable and function names."
      - "Use PascalCase for class names."
      - "Limit line length to 79 characters."
      - "Prefix all private variables and functions with an underscore."
       - "Use encapsulation for best practices"

现在,当我创建规则或生成代码时,我的函数整洁、易于阅读,并实践了良好的封装技术。这是我在编码时应该做的所有事情。

  - name: "Map Results to pandas DataFrame"
    action: "Always convert API response data to pandas DataFrame for further processing."
    details:
      - "Example function to convert API response to DataFrame:"
        content: |
          import pandas as pd

          def map_to_dataframe(data, columns=None):
              """
              Convert API response data to pandas DataFrame.

              Args:
                  data (list or dict): JSON response data.
                  columns (list, optional): List of column names to include.

              Returns:
                  pd.DataFrame: Data in tabular format.
              """
              df = pd.DataFrame(data)
              if columns:
                  df = df[columns]
              return df

PEP 8 还提供了关于代码文档、如何处理错误消息等的指南。我可以在我的.cursorrules文件中添加示例,以便在创建新代码时使用它们作为上下文。

- name: "Error Handling for API Requests"
    action: "Implement robust error handling for API calls."
    details:
      - "Use try-except blocks to handle common exceptions."
      - "Raise errors for debugging when necessary."
      - "Example:"
        content: |
          try:
              api_client = get_api_client()
              df = get_workspaces(api_client)
              print(df.head())
          except Exception as e:
              print(f"An error occurred: {e}")

综上所述,我目前用于 Python 开发的 Airbyte 的.cursorrules文件意味着我可以花更多时间思考提示要执行的任务,而不是如何构建实际提示以创建最佳实践代码。这为我省去了数小时的重构时间。

而且,由于我经常在 Python、React 和 Swift 之间切换,所以我已经开始为每种语言创建规则文件。这种方法允许我针对每种语言应用最佳实践,定义项目中的目录结构等。如果你想查看我的规则文件,我已经将它们添加到了一个 GitHub 存储库中。我一直在不断重构和添加更多内容。如果你想保持最新状态,请关注并点赞。