程式碼解譯器擴充功能

本文將說明如何透過 Google Cloud 控制台和 Vertex AI API 註冊及使用 Google 提供的 Code Interpreter 擴充功能。這個擴充功能可讓您產生及執行 Python 程式碼,以便執行下列操作:

  • 分析、清理、轉換及重塑資料集
  • 透過圖表和圖形以視覺化方式呈現資料
  • 執行計算

程式碼解譯器擴充功能會使用 code_interpreter_tool,根據自然語言說明產生及執行 Python 程式碼。code_interpreter_tool 是在 OpenAPI 規範 code_interpreter.yaml 檔案中定義。

openapi: "3.0.0"
info:
  version: 1.0.0
  title: code_interpreter_tool
  description: >
    This tool supports the following operations based on user input:

    1. **Generates and Executes Code:** Accepts a user query in natural language, generates corresponding code, and executes it to produce results for the user query.


    Supported AuthTypes:

    - `GOOGLE_SERVICE_ACCOUNT_AUTH`: (Vertex AI Extension Service Agent is supported).
paths:
  /generate_and_execute:
    post:
      operationId: generate_and_execute
      description: >
        Get the results of a natural language query by generating and executing a code snippet.
        Example queries: "Find the max in [1, 2, 5]" or "Plot average sales by year (from data.csv)".
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
              - query
              properties:
                query:
                  type: string
                  description: >
                    Required. The Natural language query to get the results for.
                    The query string can optionally contain data to use for the code generated.
                    For example: "I have a list of numbers: [1, 2, 3, 4]. Find the largest number in the provided data."
                timeout:
                  type: number
                  description: >
                    Optional. Timeout in miliseconds for the code execution. Default value: 30000.
                files:
                  type: array
                  description: >
                    Optional. Input files to use when executing the generated code.
                    If specified, the file contents are expected be base64-encoded.
                    For example: [{"name": "data.csv", "contents": "aXRlbTEsaXRlbTI="}]
                  items:
                    $ref: "#/components/schemas/File"
                file_gcs_uris:
                  type: array
                  description: >
                    Optional. GCS URIs of input files to use when executing the generated code.
                    For example: ["gs://input-bucket/data.csv"]
                    This option is only applicable when `file_input_gcs_bucket` is specified in `Extension.CodeInterpreterRuntimeConfig`.
                  items:
                    type: string
      responses:
        '200':
          description: >
            The results of generating and executing code based on the natual language query.
            The result contains the generated code, and the STDOUT, STDERR, and output files from code execution.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/GenerationAndExecutionResult"
components:
  schemas:
    File:
      description: >
        File used as inputs and outputs of code execution. The `contents` string should be base64-encoded bytes.
        For example: [{"name": "data.csv", "contents": "aXRlbTEsaXRlbTI="}]
      type: object
      properties:
        name:
          type: string
        contents:
          type: string
          format: byte
    GenerationAndExecutionResult:
      description: >
        The results of generating and executing code based on the natual language query.
      properties:
        generated_code:
          type: string
          description: >
            The generated code in markdown format.
            For example: "```python\nprint(\"Hello World\")\n```"
        execution_result:
          type: string
          description: >
            The code execution result string from STDOUT.
        execution_error:
          type: string
          description: >
            The code execution error string from STDERR.
        output_files:
          type: array
          description: >
            The output files generated from code execution.
            If present, the file contents are required be base64-encoded.
            For example: [{"name": "data.csv", "contents": "aXRlbTEsaXRlbTI="}]
          items:
            $ref: "#/components/schemas/File"
        output_gcs_uris:
          type: array
          description: >
            The output GCS URIs of files generated from code execution.
            For example: ["gs://output-bucket/subfolder/output.csv"]

            This field is only applicable when `file_output_gcs_bucket` is specified in `Extension.CodeInterpreterRuntimeConfig`.
          items:
            type: string

    

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

  8. 註冊、查詢及執行 Code Interpreter 擴充功能

    以下各節將說明如何使用 Google Cloud 控制台和 Vertex AI API 註冊 Code Interpreter 擴充功能。註冊擴充功能後,您可以使用 Google Cloud 控制台查詢擴充功能,也可以使用 Vertex AI API 執行擴充功能。

    控制台

    註冊擴充功能

    請按照下列步驟,使用 Google Cloud 主控台註冊程式碼解譯器擴充功能。

    1. 在 Google Cloud 控制台中,前往 Vertex AI 的「Extensions」頁面。

      前往 Vertex AI 擴充功能

    2. 按一下「建立擴充功能」

    3. 在「Create a new extension」對話方塊中,執行下列操作:

      • 擴充功能名稱:輸入擴充功能的名稱,例如「code_interpreter_extension」。
      • 說明: (選填) 輸入擴充功能說明,例如「程式碼轉譯器擴充功能」。
      • 額外資訊類型:選取 Code interpreter
    4. 在現在顯示的「OpenAPI 規格檔案」部分中,確認下列欄位已正確設定:

      • API 名稱: code_interpreter_tool
      • API 說明: Tool to generate and run valid Python code from a natural language description, or to run custom Python code...
      • 來源: Cloud Storage
      • OpenAPI 規格: vertex-extension-public/code_interpreter.yaml
      • 驗證: Google service account
    5. (選用) 在「執行階段設定」部分中,提供輸入值區和輸出值區。

    6. 按一下「建立擴充功能」

    (選用) 查詢擴充功能

    您可以使用 Google Cloud 主控台來嘗試使用 Code Interpreter 擴充功能。請按照下列步驟操作,使用自然語言提示喚醒擴充功能。

    1. 在 Google Cloud 控制台中,前往 Vertex AI 的「Extensions」頁面。

      前往 Vertex AI 擴充功能

    2. 按一下 Code Interpreter 擴充功能名稱,開啟「Extensions details」頁面。

      程式碼解譯器名稱。

    3. 在「輸入訊息」方塊中輸入查詢,然後查看回應。展開「Extension Response」部分,即可查看擴充功能產生並執行的程式碼,以產生結果。

      以下範例顯示查詢結果,該查詢計算了使用者輸入的數字清單平均值。

      平均值查詢。

    REST

    註冊擴充功能

    提交 Vertex AI API extensions.import 要求,以便註冊 Code Interpreter 擴充功能。

    使用任何要求資料之前,請先替換以下項目:

    HTTP 方法和網址:

    POST https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions:import

    JSON 要求主體:

    {
      "displayName":"DISPLAY_NAME",
      "description":"DESCRIPTION",
      "manifest":{
        "name":"code_interpreter_tool",
        "description":"A Google Code Interpreter tool",
        "apiSpec":{
          "openApiGcsUri":"gs://vertex-extension-public/code_interpreter.yaml"
        },
        "authConfig":{
          "authType":"GOOGLE_SERVICE_ACCOUNT_AUTH",
          "googleServiceAccountConfig":{
            "serviceAccount":"SERVICE_ACCOUNT"
          }
        }
      }
      "runtimeConfig": {
         "codeInterpreterRuntimeConfig": {
            "fileInputGcsBucket": "INPUT_BUCKET",
            "fileOutputGcsBucket": "OUTPUT_BUCKET"
         }
      }
    }
    
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions:import"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions:import" | Select-Object -Expand Content

    執行擴充功能

    您可以將 execute 作業提交至 Vertex AI API,根據自然語言查詢產生及執行 Python 程式碼。

    查詢範例:

    • 簡單查詢:找出數字清單中的最大值。
    • 查詢內嵌資料:在要求主體中提供要查詢的資料。
    • 使用檔案資料查詢:列印檔案資料。
    • 使用 Cloud Storage 資料查詢:讀取 Cloud Storage 資料。

    簡易查詢

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • REGIONCompute Engine 區域
    • EXTENSION_ID:程式碼轉譯器擴充功能的 ID,列於 Google Cloud 主控台的「Extension details」中。

    HTTP 方法和網址:

    POST https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute

    JSON 要求主體:

    {
      "operation_id":"generate_and_execute",
      "operation_params":{
        "query":"find the max value in the list: [1,2,3,4,-5]"
      }
    }
    
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute" | Select-Object -Expand Content

    內嵌資料

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • REGIONCompute Engine 區域
    • EXTENSION_ID:程式碼轉譯器擴充功能的 ID,列於 Google Cloud 主控台的「Extension details」中。

    HTTP 方法和網址:

    POST https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute

    JSON 要求主體:

    {
      "operation_id":"generate_and_execute",
      "operation_params":{
        "query":"Calculate the total values of each column(mobile_subscribers, percent_internet_users, total_internet_users, fixed_broadband_subscribers) from the below dataset.\n\n\ncountry_name        country_code        year        mobile_subscribers        percent_internet_users        total_internet_users        fixed_broadband_subscribers\nUnited States        US        2023        333.4        90.5        303.1        200.3\nChina        CN        2023        1.613        70.2        1131.4        512.2\nIndia        IN        2023        1.165        50.7        688.5        557.2\nJapan        JP        2023        124.3        88.2        109.5        114.8\nGermany        DE        2023        102.1        90.5        92.1        100\nUnited Kingdom        UK        2023        67.1        92.7        62.2        65\nFrance        FR        2023        66.7        89        63        69.7\nBrazil        BR        2023        213.5        68        144.1        69.4\nRussia        RU        2023        203.8        74.9        152.7        51.1"
      }
    }
    
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute" | Select-Object -Expand Content

    檔案沖印

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • REGIONCompute Engine 區域
    • EXTENSION_ID:程式碼轉譯器擴充功能的 ID,列於 Google Cloud 主控台的「Extension details」中。
    • FILE_NAME:要求主體中的 CSV 檔案資料會寫入工作目錄中的這個檔案。
    • BASE64_ENCODED_FILE_BYTES:要求主體中的檔案位元組必須採用 Base64 編碼。

    HTTP 方法和網址:

    POST https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute

    JSON 要求主體:

    {
      "operation_id":"generate_and_execute",
      "operation_params":{
        "query":"print the csv file",
        "files":[
          {
            "name":"FILE_NAME",
            "contents":"BASE64_ENCODED_FILE_BYTES"
          }
        ]
      }
    }
    
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute" | Select-Object -Expand Content

    Cloud Storage 讀取

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID: Google Cloud 專案的 ID。
    • REGIONCompute Engine 區域
    • EXTENSION_ID:程式碼轉譯器擴充功能的 ID,列於 Google Cloud 主控台的「Extension details」中。
    • BUCKET_NAME:包含要列印的 CSV 檔案的 Cloud Storage 值區。註冊程式碼解譯器擴充功能時,您必須指定這個輸入桶。
    • FILE_NAME:要列印的 BUCKET_NAME 中的 CSV 檔案資料。

    HTTP 方法和網址:

    POST https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute

    JSON 要求主體:

    {
      "operation_id":"generate_and_execute",
      "operation_params":{
        "query":"print the csv file",
        "file_gcs_uris": ["gs://BUCKET_NAME/FILE_NAME"]
      }
    }
    
    

    如要傳送要求,請選擇以下其中一個選項:

    curl

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute"

    PowerShell

    將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://REGION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/REGION/extensions/EXTENSION_ID:execute" | Select-Object -Expand Content