Vertex AI Extensions 淘汰後,現有工作流程必須遷移至 Gemini Enterprise Agent Platform (Agent Platform)。本指南說明三種核心擴充功能類別的遷移路徑:
程式碼解譯器擴充功能
遷移至:Agent Platform 程式碼執行沙箱
替代方案:Gemini API CodeExecution 工具
程式碼解譯器擴充功能應遷移至 Agent Platform 程式碼執行沙箱。這項代管服務提供安全、隔離且具狀態的沙箱環境,專門用於執行不受信任的 AI 生成程式碼。非常適合用於程式輔助執行、財務計算和資料科學工作流程。
或者,您也可以使用 google-genai SDK 中的內建 code_execution 工具,讓 Gemini 模型在生成過程中自動編寫及執行程式碼。
遷移範例
Vertex AI 擴充功能:
from vertexai.preview import extensions
extension = extensions.Extension.from_hub("code_interpreter")
response = extension.execute(
operation_id="generate_and_execute_code",
operation_params={"code": "import math\nprint(math.sqrt(15376))"}
)
Agent Platform Code Execution Sandbox:
方法 1:使用 Agent Development Kit (ADK)
from google.adk.code_executors.agent_engine_sandbox_code_executor import (
AgentEngineSandboxCodeExecutor,
)
from vertexai.preview.reasoning_engines import Agent
root_agent = Agent(
model="gemini-2.0-flash-001",
name="agent_engine_code_execution_agent",
instruction=base_system_instruction()
+ """
You need to assist the user with their queries by looking at the data and the
context in the conversation. Your final answer should summarize the code and
code execution relevant to the user query.
Include all pieces of data required to answer the question, such as a table
from code execution results. If the query can be answered directly without
writing code, generate the textual response directly. Take care not to manually
run commands like `pip install`. When plotting trends, sort data by the x-axis.
""",
code_executor=AgentEngineSandboxCodeExecutor(
sandbox_resource_name=None,
agent_engine_resource_name=None,
),
)
選項 2:使用 GenAI 用戶端 SDK
from google import genai
# Initialize Gemini model
model = genai.Client().models
# Ask Gemini to generate code for a calculation
prompt = """
Write Python code to calculate the mean and standard deviation of these numbers:
[23, 45, 67, 89, 12, 34, 56]
Return only the Python code, no explanations.
"""
response = model.generate_content(
model="gemini-2.5-flash",
contents=prompt
)
generated_code = response.text.replace("```python", "").replace("```", "").strip()
# Execute the generated code in Agent Engine Sandbox using new pattern
exec_response = client.agent_engines.sandboxes.execute_code(
name=sandbox_resource_name,
input_data={"code": generated_code},
)
# Parse response with new file handling logic
for output in exec_response.outputs:
if output.mime_type == "application/json" and output.metadata is None:
result = json.loads(output.data.decode("utf-8"))
if result.get("msg_out"):
print(result.get("msg_out"))
if result.get("msg_err"):
print(f"Error occurred: {result.get('msg_err')}")
選項 3:定義為動態手動工具
import json
import re
from google.genai.types import FunctionDeclaration, Tool
def execute_python_code(code: str) -> str:
"""Execute Python code in a secure sandbox.
Args:
code: Python code to execute
Returns:
The output from code execution
"""
# Extract code block if wrapped in markdown
code_match = re.search(r"```python\n(.*?)\n```", code, re.DOTALL)
code_to_execute = code_match.group(1) if code_match else code
# Execute in sandbox
response = client.agent_engines.sandboxes.execute_code(
name=sandbox_resource_name, input_data={"code": code_to_execute}
)
# Parse response using new pattern
for output in response.outputs:
if output.mime_type == "application/json" and output.metadata is None:
result = json.loads(output.data.decode("utf-8"))
if result.get("msg_err"):
return f"Error: {result.get('msg_err')}"
return result.get("msg_out", "Code executed successfully")
return "Code executed (no output)"
# Create a tool from the function
code_tool = Tool(
function_declarations=[FunctionDeclaration.from_func(execute_python_code)]
)
Google 搜尋擴充功能
遷移至:以 Google 搜尋強化事實基礎
改用以 Google 搜尋建立基準。這項功能可讓模型根據可信的搜尋索引和最新公開資訊生成回覆,提高回覆內容的準確度。
遷移範例
Vertex AI 擴充功能:
from vertexai.preview import extensions
extension = extensions.Extension.from_hub("google_search")
response = extension.execute(
operation_id="search",
operation_params={"query": "What is the next total solar eclipse in the US?"}
)
使用 Google GenAI SDK,以 Google 搜尋強化事實基礎:
from google import genai
from google.genai.types import GenerateContentConfig, GoogleSearch, Tool
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.1-flash",
contents="When is the next total solar eclipse in the United States?",
config=GenerateContentConfig(
tools=[Tool(google_search=GoogleSearch())],
temperature=0.0,
),
)
print(response.text)
自訂擴充欄位
遷移至:函式呼叫 (工具使用)
將您透過 OpenAPI 規格設定的自訂擴充功能,遷移至函式呼叫。函式呼叫功能可讓您在來源檔案中定義外部平台 API,並將介面抽象化轉送至模型。
遷移範例
Vertex AI 擴充功能:
from vertexai.preview import extensions
extension = extensions.Extension.create(
manifest={
"name": "my_custom_api",
"apiSpec": {"openApiYaml": "..."}
}
)
使用 Google GenAI SDK 進行工具使用:
from google import genai
from google.genai.types import GenerateContentConfig
def get_order_status(order_id: str) -> str:
"""Returns the current status of a customer order.
Args:
order_id: The unique identifier of the order.
"""
statuses = {"123": "Shipped", "456": "Processing"}
return statuses.get(order_id, "Order not found")
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.0-pro",
contents="Can you check the status of my order 123?",
config=GenerateContentConfig(
tools=[get_order_status],
),
)
print(response.text)