教學課程:Agent Platform API (快捷模式)

快速模式下的 Gemini Enterprise Agent Platform 可讓您快速試用 Gemini Enterprise Agent Platform 提供的核心生成式 AI 功能。本教學課程將說明如何使用快速模式下的 Agent Platform API 執行下列工作:

  • 安裝並初始化 Google Gen AI SDK (快捷模式)。
  • 傳送要求至 Gemini for Google Cloud API,包括下列項目:

    • 非串流要求
    • 串流要求
    • 函式呼叫要求

事前準備

執行本頁面所述工作前,請先註冊使用快捷模式

安裝並初始化 Google Gen AI SDK (快捷模式)

Google Gen AI SDK 可讓您使用 Google 生成式 AI 模型和功能,建構 AI 輔助應用程式。在快捷模式下使用 Gemini Enterprise Agent Platform 時,請安裝並初始化 google-genai 套件,透過產生的 API 金鑰進行驗證。

安裝

如要安裝 Google Gen AI SDK 的快捷模式,請執行下列指令:

# Developer TODO: If you're using Colab, uncomment the following lines:
# from google.colab import auth
# auth.authenticate_user()

!pip install google-genai

!pip install --force-reinstall -qq "numpy<2.0"

如果您使用 Colab,請忽略任何依附元件衝突,並在安裝後重新啟動執行階段。

初始化

設定快捷模式的 API 金鑰和環境變數。如要瞭解如何取得 API 金鑰,請參閱「Gemini Enterprise Agent Platform 快捷模式總覽」。

from google import genai
from google.genai import types

# Developer TODO: Replace YOUR_API_KEY with your API key.
API_KEY = "YOUR_API_KEY"

client = genai.Client(
    vertexai=True, api_key=API_KEY
)

傳送要求至 Gemini for Google Cloud API

您可以將串流或非串流要求傳送至 Gemini for Google Cloud API。串流要求會在處理要求時,以區塊形式傳回回應。對人類使用者而言,串流回應可減少延遲的感覺。處理要求後,非串流要求會以一個區塊的形式傳回回應。

串流要求

如要傳送串流要求,請設定 stream=True,並以區塊形式列印回應。

from google import genai
from google.genai import types

def generate():
  client = genai.Client(vertexai=True, api_key=YOUR_API_KEY)

  config=types.GenerateContentConfig(
      temperature=0,
      top_p=0.95,
      top_k=20,
      candidate_count=1,
      seed=5,
      max_output_tokens=100,
      stop_sequences=["STOP!"],
      presence_penalty=0.0,
      frequency_penalty=0.0,
      safety_settings=[
          types.SafetySetting(
              category="HARM_CATEGORY_HATE_SPEECH",
              threshold="BLOCK_ONLY_HIGH",
          )
      ],
  )
  for chunk in client.models.generate_content_stream(
    model="gemini-2.5-flash-lite",
    contents="Explain bubble sort to me",
    config=config,
  ):
    print(chunk.text)

generate()

非串流要求

下列程式碼範例定義的函式會將非串流要求傳送至 gemini-2.5-flash-lite,並說明如何設定基本要求參數和安全性設定。

from google import genai
from google.genai import types

def generate():
  client = genai.Client(vertexai=True, api_key=YOUR_API_KEY)

  config=types.GenerateContentConfig(
      temperature=0,
      top_p=0.95,
      top_k=20,
      candidate_count=1,
      seed=5,
      max_output_tokens=100,
      stop_sequences=["STOP!"],
      presence_penalty=0.0,
      frequency_penalty=0.0,
      safety_settings=[
          types.SafetySetting(
              category="HARM_CATEGORY_HATE_SPEECH",
              threshold="BLOCK_ONLY_HIGH",
          )
      ],
  )
  response = client.models.generate_content(
    model="gemini-2.5-flash-lite",
    contents="Explain bubble sort to me",
    config=config,
  )
  print(response.text)

generate()

函式呼叫要求

下列程式碼範例會宣告函式並將其做為工具傳遞,然後在回覆中接收函式呼叫部分。從模型收到函式呼叫部分後,您可以叫用函式並取得回覆,然後將回覆傳遞至模型。


function_response_parts = [
    {
        'function_response': {
            'name': 'get_current_weather',
            'response': {
                'name': 'get_current_weather',
                'content': {'weather': 'super nice'},
            },
        },
    },
]
manual_function_calling_contents = [
    {'role': 'user', 'parts': [{'text': 'What is the weather in Boston?'}]},
    {
        'role': 'model',
        'parts': [{
            'function_call': {
                'name': 'get_current_weather',
                'args': {'location': 'Boston'},
            }
        }],
    },
    {'role': 'user', 'parts': function_response_parts},
]
function_declarations = [{
    'name': 'get_current_weather',
    'description': 'Get the current weather in a city',
    'parameters': {
        'type': 'OBJECT',
        'properties': {
            'location': {
                'type': 'STRING',
                'description': 'The location to get the weather for',
            },
            'unit': {
                'type': 'STRING',
                'enum': ['C', 'F'],
            },
        },
    },
}]

response = client.models.generate_content(
    model="gemini-2.0-flash-001",
    contents=manual_function_calling_contents,
    config=dict(tools=[{'function_declarations': function_declarations}]),
)
print(response.text)

清除所用資源

本教學課程不會建立任何 Google Cloud 資源,因此不需要清理任何資料,以免產生費用。

後續步驟