本文將說明如何透過 Google Cloud 控制台和 Vertex AI API,註冊及使用 Google 提供的程式碼解譯器擴充功能。這個擴充功能可讓您產生及執行 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
事前準備
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vertex AI API.
前往 Google Cloud 控制台的「Vertex AI Extensions」頁面。
按一下「建立擴充功能」。
在「建立新的擴充功能」對話方塊中,執行下列操作:
- 擴充功能名稱:輸入擴充功能的名稱,例如「code_interpreter_extension」。
- 說明: (選填) 輸入擴充功能說明,例如「程式碼解譯器擴充功能」。
- 擴充功能類型:選取
Code interpreter
。
在隨即顯示的「OpenAPI Spec file」(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
。
- API 名稱:
(選用) 在「執行階段設定」部分中,提供輸入值區和輸出值區。
- 輸入值區是擴充功能用來讀取輸入檔案的 Cloud Storage 值區,包括
gs://
前置字串,例如gs://sample-bucket-name
。如果指定,您必須將這個值區的roles/storage.objectViewer
角色指派給 Vertex 擴充功能自訂程式碼服務代理服務帳戶。 - 輸出值區是擴充功能用來寫入輸出檔案的 Cloud Storage 值區,包括
gs://
前置字串,例如gs://sample-bucket-name
。如果指定,您必須將這個值區的roles/storage.objectUser
角色指派給 Vertex 擴充功能自訂程式碼服務代理服務帳戶。
- 輸入值區是擴充功能用來讀取輸入檔案的 Cloud Storage 值區,包括
按一下「建立擴充功能」。
前往 Google Cloud 控制台的「Vertex AI Extensions」頁面。
按一下「程式碼解讀器」擴充功能名稱,開啟「擴充功能詳細資料」頁面。
在「輸入訊息」方塊中輸入查詢,然後查看回覆。展開「擴充功能回覆」部分,即可查看擴充功能生成及執行的程式碼,瞭解結果的產生方式。
以下範例顯示查詢結果,其中計算使用者輸入的數字清單平均值。
- PROJECT_ID:您的 Google Cloud 專案 ID。
- REGION:Compute Engine 區域。
- DISPLAY_NAME:向使用者顯示的名稱擴充功能,例如「my_code_interpreter_extension」。
- DESCRIPTION:(選用) 向使用者顯示的擴充功能說明,例如「程式碼解譯器擴充功能」。
- SERVICE_ACCOUNT:(選用) Code Interpreter 擴充功能會使用 GOOGLE_SERVICE_ACCOUNT_AUTH,如範例要求內文所示。如未指定服務帳戶,擴充功能會使用預設的 Vertex AI Extension 服務代理服務帳戶。
如果您指定其他服務帳戶,請在指定服務帳戶中,將
iam.serviceAccounts.getAccessToken
權限授予 Vertex AI Extension 服務代理服務帳戶。 - INPUT_BUCKET:(選用) 擴充功能將用來讀取輸入檔案的 Cloud Storage 值區,包括
gs://
前置字元,例如gs://sample-bucket-name
。如果指定,您必須將這個值區的roles/storage.objectViewer
角色指派給 Vertex Extension Custom Code Service Agent 服務帳戶。 - OUTPUT_BUCKET:(選用) 擴充功能用來寫入輸出檔案的 Cloud Storage 值區,包括
gs://
前置字元,例如gs://sample-bucket-name
。如果指定,您必須將這個值區的roles/storage.objectUser
角色指派給 Vertex Extension Custom Code Service Agent 服務帳戶。 - 簡單查詢:找出數字清單中的最大值。
- 查詢內嵌資料:要查詢的資料會提供在要求主體中。
- 使用檔案資料查詢:列印檔案資料。
- 查詢 Cloud Storage 資料:讀取 Cloud Storage 資料。
- PROJECT_ID:您的 Google Cloud 專案 ID。
- REGION:Compute Engine 區域。
- EXTENSION_ID:程式碼解譯器擴充功能的 ID,列於 Google Cloud 控制台的「擴充功能詳細資料」中。
- PROJECT_ID:您的 Google Cloud 專案 ID。
- REGION:Compute Engine 區域。
- EXTENSION_ID:程式碼解譯器擴充功能的 ID,列於 Google Cloud 控制台的「擴充功能詳細資料」中。
- PROJECT_ID:您的 Google Cloud 專案 ID。
- REGION:Compute Engine 區域。
- EXTENSION_ID:程式碼解譯器擴充功能的 ID,列於 Google Cloud 控制台的「擴充功能詳細資料」中。
- FILE_NAME:要求主體中的 CSV 檔案資料會寫入工作目錄中的這個檔案。
- BASE64_ENCODED_FILE_BYTES:要求主體中的檔案位元組必須採用 base64 編碼。
- PROJECT_ID:您的 Google Cloud 專案 ID。
- REGION:Compute Engine 區域。
- EXTENSION_ID:程式碼解譯器擴充功能的 ID,列於 Google Cloud 控制台的「擴充功能詳細資料」中。
- BUCKET_NAME:包含要列印的 CSV 檔案的 Cloud Storage 值區。您必須在註冊程式碼解譯器擴充功能時指定這個輸入值。
- FILE_NAME:要列印的 CSV 檔案資料 (位於 BUCKET_NAME 中)。
註冊、查詢及執行 Code Interpreter 擴充功能
以下各節說明如何使用 Google Cloud 控制台和 Vertex AI API 註冊 Code Interpreter 擴充功能。註冊擴充功能後,您可以使用 Google Cloud 控制台查詢擴充功能,或使用 Vertex AI API 執行擴充功能。
控制台
註冊擴充功能
請按照下列步驟,使用 Google Cloud 控制台註冊 Code Interpreter 擴充功能。
(選用) 查詢擴充功能
您可以使用 Google Cloud 控制台試用 Code Interpreter 擴充功能。請按照下列步驟,使用自然語言提示呼叫擴充功能。
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
執行擴充功能
您可以向 Vertex AI API 提交 execute
作業,根據自然語言查詢生成及執行 Python 程式碼。
查詢範例:
簡單查詢
使用任何要求資料之前,請先替換以下項目:
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
內嵌資料
使用任何要求資料之前,請先替換以下項目:
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
列印檔案
使用任何要求資料之前,請先替換以下項目:
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 讀取
使用任何要求資料之前,請先替換以下項目:
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