API Panggilan Fungsi

Panggilan fungsi meningkatkan kemampuan LLM untuk memberikan jawaban yang relevan dan kontekstual.

Anda dapat memberikan fungsi kustom ke model AI generatif dengan Function Calling API. Model tidak langsung memanggil fungsi ini, tetapi menghasilkan output data terstruktur yang menentukan nama fungsi dan argumen yang disarankan. Output ini memungkinkan panggilan API eksternal atau sistem informasi seperti database, sistem pengelolaan hubungan pelanggan, dan repositori dokumen. Output API yang dihasilkan dapat digunakan oleh LLM untuk meningkatkan kualitas respons.

Model yang Didukung:

  • Gemini 1.0 Pro
    • gemini-1.0-pro
    • gemini-1.0-pro-001
    • gemini-1.0-pro-002
  • Gemini 1.5 Pro
    • gemini-1.5-pro-preview-0409

Batasan:

  • Jumlah maksimum fungsi yang dapat disediakan adalah 64.
  • FunctionCallingConfig masih dalam Pratinjau dan hanya tersedia untuk "gemini-1.5-pro-preview-0409".

Sintaksis

  • ID_PROJECT = PROJECT_ID
  • WILAYAH = REGION
  • MODEL_ID = MODEL_ID

curl

http://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      ...
    }],
    "tools": [{
      "function_declarations": [
        {
          ...
        }
      ]
    }]
  }'

Python

gemini_model = GenerativeModel(
    MODEL_ID,
    generation_config=generation_config,
    tools=[
        Tool(
            function_declarations=[
                FunctionDeclaration(
                    ...
                )
            ]
        )
    ],
)

Daftar parameter

FunctionDeclaration

Representasi terstruktur dari deklarasi fungsi seperti yang ditentukan oleh spesifikasi OpenAPI 3.0 yang mewakili fungsi yang dapat dihasilkan input JSON-nya oleh model.

Parameter

name

string

Nama fungsi yang akan dipanggil.

description

Opsional: string

Deskripsi dan tujuan fungsi.

parameters

Opsional: Schema

Menjelaskan parameter ke fungsi ini dalam format Objek Skema JSON OpenAPI: Spesifikasi OpenAPI 3.0

response

Opsional: Schema

Menjelaskan output dari fungsi ini dalam format Skema JSON.

FunctionCallingConfig [Pratinjau]

Ini adalah konfigurasi tambahan untuk menggunakan fitur panggilan fungsi yang hanya tersedia untuk "gemini-1.5-pro-preview-0409"

Parameter

mode

Opsional: enum/string[]

  • AUTO: Perilaku model default, model memutuskan untuk memprediksi panggilan fungsi atau respons natural language.
  • NONE: Model tidak akan memprediksi panggilan fungsi apa pun. Perilaku model sama seperti saat tidak meneruskan deklarasi fungsi apa pun.
  • ANY: Model dibatasi untuk selalu memprediksi panggilan fungsi tunggal.

Jika allowed_function_names ditetapkan, panggilan fungsi yang diprediksi dibatasi ke allowed_function_names mana pun. Secara default, panggilan fungsi yang diprediksi akan berasal dari function_declarations yang disediakan.

allowed_function_names

Opsional: string[]

Nama fungsi yang akan dipanggil. Hanya disetel saat mode adalah ANY. Nama fungsi harus cocok dengan [FunctionDeclaration.name]. Dengan mode yang disetel ke ANY, model akan memprediksi panggilan fungsi dari kumpulan nama fungsi yang disediakan.

Skema

Skema digunakan untuk menentukan format data input dan output dalam panggilan fungsi. Representasi terstruktur dari deklarasi fungsi seperti yang ditetapkan oleh spesifikasi OpenAPI 3.0 Schema.

Parameter
jenis

string

Enum. Jenis data. Harus berupa salah satu dari:

  • STRING
  • INTEGER
  • BOOLEAN
  • NUMBER
  • ARRAY
  • OBJECT
description

Opsional: string

Deskripsi data.

enum

Opsional: string[]

Nilai elemen Type.STRING yang mungkin dengan format enum.

items

Opsional: Schema[]

Skema elemen Type.ARRAY

properties

Opsional: Schema

Skema properti Type.OBJECT

required

Opsional: string[]

Properti wajib Type.OBJECT.

nullable

Opsional: bool

Menunjukkan apakah nilainya mungkin null.

Contoh

  • ID_PROJECT = PROJECT_ID
  • WILAYAH = REGION
  • MODEL_ID = MODEL_ID

Kasus Penggunaan Dasar

Berikut adalah contoh cara mengirim kueri dan deklarasi fungsi ke model.

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  http://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "What is the weather in Boston?"
      }]
    }],
    "tools": [{
      "function_declarations": [
        {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
              }
            },
            "required": [
              "location"
            ]
          }
        }
      ]
    }]
  }'

Python

import vertexai
from vertexai.generative_models import (
    FunctionDeclaration,
    GenerativeModel,
    GenerationConfig,
    Part,
    Tool,
)

vertexai.init(project=PROJECT_ID, location=REGION)

# Specify a function declaration and parameters for an API request
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"}},
    },
)

# Define a tool that includes the above get_current_weather_func
weather_tool = Tool(
    function_declarations=[get_current_weather_func],
)

gemini_model = GenerativeModel(
    MODEL_ID, generation_config={"temperature": 0}, tools=[weather_tool]
)
model_response = gemini_model.generate_content("What is the weather in Boston?")

print(model_response)

Kasus Penggunaan Lanjutan

Contoh berikut menunjukkan cara meneruskan konfigurasi pembuatan dan konfigurasi alat ke model. Konfigurasi panggilan fungsi dapat digunakan untuk memastikan bahwa output model selalu berupa panggilan fungsi tertentu. Untuk mencapainya, tetapkan mode panggilan fungsi ke ANY dan tentukan nama fungsi yang diizinkan dalam parameter allowed_function_names. Jika allowed_function_names kosong, salah satu fungsi yang disediakan dapat ditampilkan.

  • MODEL_ID = gemini-1.5-pro-preview-0409

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  http://${REGION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "Do you have the White Pixel 8 Pro 128GB in stock in the US?"
      }]
    }],
    "tools": [{
      "function_declarations": [
        {
          "name": "get_product_sku",
          "description": "Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc",
          "parameters": {
            "type": "object",
            "properties": {
                "product_name": {"type": "string", "description": "Product name"}
            }
          }
        },
        {
          "name": "get_store_location",
          "description": "Get the location of the closest store",
          "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "Location"}},
          }
        }
      ]
    }],
    "tool_config": {
        "function_calling_config": {
            "mode":"ANY",
            "allowed_function_names": ["get_product_sku"]
       }
    },
    "generationConfig": {
      "temperature": 0.95,
      "topP": 1.0,
      "maxOutputTokens": 8192
    }
  }'

Python

import vertexai
from vertexai.generative_models import (
    FunctionDeclaration,
    GenerativeModel,
    GenerationConfig,
    Part,
    Tool,
    ToolConfig,
)

vertexai.init(project=PROJECT_ID, location=REGION)

# Specify a function declaration and parameters for an API request
get_product_info_func = FunctionDeclaration(
    name="get_product_sku",
    description="Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "product_name": {"type": "string", "description": "Product name"}
        },
    },
)

# Specify another function declaration and parameters for an API request
get_store_location_func = FunctionDeclaration(
    name="get_store_location",
    description="Get the location of the closest store",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "Location"}},
    },
)

# Define a tool that includes the above functions
retail_tool = Tool(
    function_declarations=[
        get_product_info_func,
        get_store_location_func,
    ],
)

# Define a tool config for the above functions
retail_tool_config = ToolConfig(
    function_calling_config=ToolConfig.FunctionCallingConfig(
        # ANY mode forces the model to predict a function call
        mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
        # List of functions that can be returned when the mode is ANY.
        # If the list is empty, any declared function can be returned.
        allowed_function_names=["get_product_sku"],
    )
)

generation_config = GenerationConfig(
    temperature=0.95, top_p=1.0, max_output_tokens=8192
)

gemini_model = GenerativeModel(
    MODEL_ID,
    generation_config=generation_config,
    tools=[retail_tool],
    tool_config=retail_tool_config,
)
model_response = gemini_model.generate_content(
    "Do you have the White Pixel 8 Pro 128GB in stock in the US?"
)

print(model_response)

Jelajahi lebih lanjut

Untuk dokumentasi mendetail, lihat berikut ini: