Panggilan fungsi

Ringkasan

Anda dapat menggunakan panggilan fungsi untuk menentukan fungsi kustom dan memberikannya ke model AI generatif. Saat memproses kueri, model dapat memilih untuk mendelegasikan tugas pemrosesan data tertentu ke fungsi tersebut. Metode ini tidak memanggil fungsi. Sebagai gantinya, model ini menyediakan output data terstruktur yang menyertakan nama fungsi yang dipilih dan argumen yang diusulkan oleh model untuk fungsi yang akan dipanggil. Anda dapat menggunakan output ini untuk memanggil API eksternal. Selanjutnya, Anda dapat memberikan output API kembali ke model, sehingga model dapat menyelesaikan jawabannya atas kueri tersebut. Ketika digunakan dengan cara ini, panggilan fungsi memungkinkan LLM mengakses informasi real-time dan berinteraksi dengan berbagai layanan, seperti database SQL, sistem pengelolaan hubungan pelanggan, dan repositori dokumen.

Diagram berikut mengilustrasikan cara kerja panggilan fungsi: Interaksi Panggilan Fungsi 

Untuk mempelajari kasus penggunaan panggilan fungsi, lihat Kasus penggunaan panggilan fungsi. Untuk mempelajari cara membuat aplikasi panggilan fungsi, lihat Membuat aplikasi panggilan fungsi. Untuk praktik terbaik, lihat Praktik terbaik.

Model Versi Fungsi memanggil tahap peluncuran Dukungan untuk panggilan fungsi paralel Dukungan untuk panggilan fungsi yang dipaksakan
Gemini 1.0 Pro gemini-1.0-pro-001 Ketersediaan Umum Tidak Tidak
Gemini 1.0 Pro gemini-1.0-pro-002 Ketersediaan Umum Tidak Tidak
Gemini 1.5 Flash gemini-1.5-flash-001 Ketersediaan Umum Ya Tidak
Gemini 1.5 Pro gemini-1.5-pro-001 Ketersediaan Umum Ya Ya

Kasus penggunaan panggilan fungsi

Anda dapat menggunakan panggilan fungsi untuk tugas-tugas berikut:

Membuat aplikasi panggilan fungsi

Agar pengguna dapat berinteraksi dengan model dan menggunakan panggilan fungsi, Anda harus membuat kode yang melakukan tugas berikut:

Anda dapat membuat aplikasi yang mengelola semua tugas ini. Aplikasi ini dapat berupa chatbot teks, agen suara, alur kerja otomatis, atau program lainnya.

Menentukan dan menjelaskan kumpulan fungsi yang tersedia

Aplikasi harus mendeklarasikan sekumpulan fungsi yang dapat digunakan model untuk memproses kueri. Setiap deklarasi fungsi harus menyertakan nama fungsi dan parameter fungsi. Sebaiknya sertakan juga deskripsi fungsi di setiap deklarasi fungsi.

Function name

Aplikasi dan model menggunakan nama fungsi untuk mengidentifikasi fungsi.

Untuk praktik terbaik terkait nama fungsi, lihat Praktik terbaik - Nama fungsi.

Parameter fungsi

Parameter fungsi harus disediakan dalam format yang kompatibel dengan skema OpenAPI.

Vertex AI menawarkan dukungan terbatas untuk skema OpenAPI. Atribut berikut didukung: type, nullable, required, format, description, properties, items, enum. Atribut berikut tidak didukung: default, optional, maximum, oneOf.

Saat Anda menggunakan curl, tentukan skema menggunakan JSON. Saat Anda menggunakan Vertex AI SDK untuk Python, tentukan skema menggunakan kamus Python.

Untuk praktik terbaik terkait parameter fungsi, lihat Praktik terbaik - Parameter fungsi.

Deskripsi fungsi

Model ini menggunakan deskripsi fungsi untuk memahami tujuan fungsi dan menentukan apakah fungsi tersebut berguna dalam memproses kueri pengguna.

Untuk praktik terbaik terkait deskripsi fungsi, lihat Praktik terbaik - Deskripsi fungsi.

Contoh deklarasi fungsi

Berikut adalah contoh deklarasi fungsi sederhana di Python:

get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "The city name of the location for which to get the weather."}},
    },
)

Berikut adalah contoh deklarasi fungsi dengan array item:

extract_sale_records_func = FunctionDeclaration(
   name="extract_sale_records",
   description="Extract sale records from a document.",
   parameters={
       "type": "object",
       "properties": {
           "records": {
               "type": "array",
               "description": "A list of sale records",
               "items": {
                   "description": "Data for a sale record",
                   "type": "object",
                   "properties": {
                "id": {"type": "integer", "description": "The unique id of the sale."},
                       "date": {"type": "string", "description": "Date of the sale, in the format of MMDDYY, e.g., 031023"},
                       "total_amount": {"type": "number", "description": "The total amount of the sale."},
                       "customer_name": {"type": "string", "description": "The name of the customer, including first name and last name."},
                       "customer_contact": {"type": "string", "description": "The phone number of the customer, e.g., 650-123-4567."},
                   },
                   "required": ["id", "date", "total_amount"],
               },
           },
       },
       "required": ["records"],
   },
)

Kirim kueri dan deklarasi fungsi ke model

Saat pengguna memberikan perintah, aplikasi harus menyediakan prompt pengguna dan deklarasi fungsi kepada model. Untuk mengonfigurasi cara model menghasilkan hasil, aplikasi dapat memberikan konfigurasi pembuatan kepada model. Untuk mengonfigurasi cara model menggunakan deklarasi fungsi, aplikasi dapat menyediakan konfigurasi alat pada model.

Perintah pengguna

Berikut adalah contoh perintah pengguna: "Bagaimana cuaca di Jakarta?"

Untuk praktik terbaik yang terkait dengan perintah pengguna, lihat Praktik terbaik - Dialog pengguna.

Konfigurasi pembuatan

Model dapat membuat hasil yang berbeda untuk nilai parameter yang berbeda. Parameter suhu mengontrol tingkat keacakan pada generasi ini. Suhu yang lebih rendah cocok untuk fungsi yang memerlukan parameter value deterministik, sedangkan suhu yang lebih tinggi cocok untuk fungsi dengan parameter yang menerima parameter value yang lebih beragam atau kreatif. Suhu 0 bersifat deterministik. Dalam hal ini, respons untuk permintaan tertentu sebagian besar deterministik, tetapi sedikit variasi masih dimungkinkan. Untuk mempelajari lebih lanjut, lihat Gemini API.

Untuk menetapkan parameter ini, kirim konfigurasi pembuatan (generation_config) beserta perintah dan deklarasi fungsi. Anda dapat mengupdate parameter temperature selama percakapan chat menggunakan Vertex AI API dan generation_config yang telah diupdate. Untuk contoh setelan parameter temperature, lihat Cara mengirimkan perintah dan deklarasi fungsi.

Untuk praktik terbaik yang terkait dengan konfigurasi pembuatan, lihat Praktik terbaik - Konfigurasi pembuatan.

Konfigurasi alat

Anda dapat menerapkan beberapa batasan terkait cara model menggunakan deklarasi fungsi yang Anda berikan. Misalnya, daripada mengizinkan model untuk memilih antara respons bahasa natural dan panggilan fungsi, Anda dapat memaksanya untuk hanya memprediksi panggilan fungsi ("panggilan fungsi paksa"). Anda juga dapat memilih untuk menyediakan model dengan kumpulan lengkap deklarasi fungsi, tetapi membatasi responsnya ke sebagian fungsi ini.

Untuk menerapkan batasan ini, kirimkan konfigurasi alat (tool_config) beserta prompt dan deklarasi fungsi. Dalam konfigurasi, Anda dapat menentukan salah satu mode berikut:

Mode Deskripsi
AUTO Perilaku model default. Model tersebut akan memutuskan apakah akan memprediksi panggilan fungsi atau respons natural language.
APA PUN Model hanya boleh memprediksi panggilan fungsi. Untuk membatasi model ke subset fungsi, tentukan nama fungsi yang diizinkan di allowed_function_names.
NONE Model tidak boleh memprediksi panggilan fungsi. Perilaku ini setara dengan permintaan model tanpa deklarasi fungsi terkait.

Mode ANY konfigurasi alat ("pemanggilan fungsi paksa") adalah fitur Pratinjau. Hal ini hanya didukung untuk model Gemini 1.5 Pro.

Untuk mempelajari lebih lanjut, lihat Function Calling API.

Cara mengirimkan perintah dan deklarasi fungsi

Berikut adalah contoh cara mengirimkan kueri dan deklarasi fungsi ke model, dan membatasi model agar hanya memprediksi panggilan fungsi get_current_weather.

# Initialize Vertex AI
from vertexai.preview.generative_models import ToolConfig

vertexai.init(project=project_id, location=location)

# Initialize Gemini model
model = GenerativeModel("Gemini 1.5 Pro")

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

# Define the user's prompt in a Content object that we can reuse in model calls
user_prompt_content = Content(
    role="user",
    parts=[
        Part.from_text(prompt),
    ],
)

# Send the prompt and instruct the model to generate content using the Tool object that you just created
response = model.generate_content(
    user_prompt_content,
    generation_config={"temperature": 0},
    tools=[weather_tool],
    tool_config=ToolConfig(
        function_calling_config=ToolConfig.FunctionCallingConfig(
            # ANY mode forces the model to predict a function call
            mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
            # Allowed functions to call when the mode is ANY. If empty, any one of
            # the provided functions are called.
            allowed_function_names=["get_current_weather"],
    ))
)
response_function_call_content = response.candidates[0].content

Jika model menentukan bahwa ia memerlukan output dari fungsi tertentu, respons yang diterima aplikasi dari model akan berisi nama fungsi dan nilai parameter yang harus digunakan untuk memanggil fungsi.

Berikut adalah contoh respons model terhadap perintah pengguna "What is the weather like in Boston?" (Bagaimana cuaca di Boston?). Model ini mengusulkan untuk memanggil fungsi get_current_weather dengan parameter Boston, MA.

candidates {
  content {
    role: "model"
    parts {
      function_call {
        name: "get_current_weather"
        args {
          fields {
            key: "location"
            value {
              string_value: "Boston, MA"
            }
          }
        }
      }
    }
  }
  ...
}

Untuk perintah seperti "Dapatkan detail cuaca di New Delhi dan San Francisco?", model tersebut dapat mengusulkan beberapa panggilan fungsi paralel. Panggilan fungsi paralel adalah fitur Pratinjau. Hal ini didukung oleh model Gemini 1.5 Pro dan Gemini 1.5 Flash. Untuk mempelajari lebih lanjut, lihat Contoh panggilan fungsi paralel.

Memanggil API eksternal

Jika aplikasi menerima nama fungsi dan parameter value dari model, aplikasi itu harus terhubung ke API eksternal dan memanggil fungsi.

Contoh berikut menggunakan data sintetis untuk menyimulasikan payload respons dari API eksternal:

# Check the function name that the model responded with, and make an API call to an external system
if (
    response.candidates[0].content.parts[0].function_call.name
    == "get_current_weather"
):
    # Extract the arguments to use in your API call
    location = (
        response.candidates[0].content.parts[0].function_call.args["location"]
    )

    # Here you can use your preferred method to make an API request to fetch the current weather, for example:
    # api_response = requests.post(weather_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = """{ "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy",
                    "icon": "partly-cloudy", "humidity": 65, "wind": { "speed": 10, "direction": "NW" } }"""

Untuk praktik terbaik terkait pemanggilan API, lihat Praktik terbaik - pemanggilan API.

Menyediakan output fungsi ke model

Setelah menerima respons dari API eksternal, aplikasi harus memberikan respons ini ke model. Berikut adalah contoh cara melakukannya menggunakan Python:

response = model.generate_content(
    [
        user_prompt_content,  # User prompt
        response_function_call_content,  # Function call response
        Content(
            parts=[
                Part.from_function_response(
                    name="get_current_weather",
                    response={
                        "content": api_response,  # Return the API response to Gemini
                    },
                )
            ],
        ),
    ],
    tools=[weather_tool],
)
# Get the model summary response
summary = response.candidates[0].content.parts[0].text

Jika model mengajukan beberapa panggilan fungsi paralel, aplikasi harus menyediakan semua respons kembali ke model. Panggilan fungsi paralel adalah fitur Pratinjau. Hal ini didukung oleh model Gemini 1.5 Pro dan Gemini 1.5 Flash. Untuk mempelajari lebih lanjut, lihat Contoh panggilan fungsi paralel.

Model gemini-1.0-pro-001 dan gemini-1.0-pro-002 dapat menentukan bahwa output fungsi lain diperlukan untuk menjawab kueri. Dalam hal ini, respons yang diterima aplikasi dari model berisi nama fungsi lain dan kumpulan parameter value lainnya.

Jika model menentukan bahwa respons API sudah memadai untuk menjawab kueri pengguna, model akan membuat respons natural language dan mengembalikannya ke aplikasi. Dalam hal ini, aplikasi harus meneruskan respons kembali ke pengguna. Berikut adalah contoh respons kueri: It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies. The humidity is 65% and the wind is blowing at 10 mph from the northwest.

Praktik terbaik

Function name

Jangan gunakan titik (.), tanda hubung (-), atau karakter spasi di nama fungsi. Sebagai gantinya, gunakan karakter garis bawah (_) atau karakter lainnya.

Parameter fungsi

Tulis deskripsi parameter yang jelas dan panjang, termasuk detail seperti format atau nilai yang Anda inginkan. Misalnya, untuk fungsi book_flight_ticket:

  • Berikut adalah contoh yang baik dari deskripsi parameter departure: Use the 3 char airport code to represent the airport. For example, SJC or SFO. Don't use the city name.
  • Berikut adalah contoh yang buruk dari deskripsi parameter departure: the departure airport

Jika memungkinkan, gunakan parameter dengan sistem hardcode untuk mengurangi halusinasi model. Misalnya, jika parameter value berasal dari set terbatas, tambahkan kolom enum, bukan memasukkan kumpulan nilai ke dalam deskripsi. Jika parameter value selalu berupa bilangan bulat, setel jenisnya ke integer, bukan number.

Deskripsi fungsi

Tulis deskripsi fungsi dengan jelas dan panjang. Misalnya, untuk fungsi book_flight_ticket:

  • Berikut adalah contoh deskripsi fungsi yang baik: book flight tickets after confirming users' specific requirements, such as time, departure, destination, party size and preferred airline
  • Berikut adalah contoh deskripsi fungsi yang buruk: book flight ticket

Perintah pengguna

Untuk hasil terbaik, tambahkan detail berikut ke kueri pengguna:

  • Konteks tambahan untuk model, misalnya, You are a flight API assistant to help with searching flights based on user preferences.
  • Detail atau petunjuk tentang cara dan waktu untuk menggunakan fungsi tersebut, misalnya, Don't make assumptions on the departure or destination airports. Always use a future date for the departure or destination time.
  • Petunjuk untuk mengajukan pertanyaan klarifikasi jika kueri pengguna bersifat ambigu, misalnya, Ask clarifying questions if not enough information is available.

Konfigurasi pembuatan

Untuk parameter suhu, gunakan 0 atau nilai rendah lainnya. Hal ini memerintahkan model untuk memberikan hasil yang lebih meyakinkan dan mengurangi halusinasi.

Pemanggilan API

Jika model mengusulkan pemanggilan fungsi yang akan mengirim pesanan, memperbarui database, atau memiliki konsekuensi yang signifikan, validasi panggilan fungsi tersebut dengan pengguna sebelum menjalankannya.

Harga

Harga untuk panggilan fungsi didasarkan pada jumlah karakter dalam input dan output teks. Untuk mempelajari lebih lanjut, lihat harga Vertex AI.

Di sini, input teks (perintah) mengacu pada kueri pengguna untuk percakapan saat ini, deklarasi fungsi untuk giliran percakapan saat ini, dan histori percakapan. Histori percakapan mencakup kueri, panggilan fungsi, dan respons fungsi dari percakapan sebelumnya. Vertex AI memangkas histori percakapan hingga 32.000 karakter.

Output teks (respons) mengacu pada panggilan fungsi dan respons teks untuk giliran percakapan saat ini.

Contoh panggilan fungsi

Anda dapat menggunakan panggilan fungsi untuk menghasilkan respons teks tunggal atau untuk mendukung sesi chat. Respons teks ad hoc berguna untuk tugas bisnis tertentu, termasuk pembuatan kode. Sesi chat berguna dalam skenario percakapan berbentuk bebas, di mana pengguna kemungkinan akan mengajukan pertanyaan lanjutan.

Jika menggunakan panggilan fungsi untuk menghasilkan satu respons, Anda harus memberikan konteks lengkap interaksi kepada model. Di sisi lain, jika Anda menggunakan panggilan fungsi dalam konteks sesi chat, sesi tersebut akan menyimpan konteksnya untuk Anda dan menyertakannya dalam setiap permintaan model. Dalam kedua kasus tersebut, Vertex AI menyimpan histori interaksi di sisi klien.

Untuk mempelajari cara menggunakan panggilan fungsi guna menghasilkan respons teks tunggal, lihat Contoh teks. Untuk mempelajari cara menggunakan panggilan fungsi guna mendukung sesi chat, lihat Contoh Chat. Untuk contoh yang menunjukkan panggilan fungsi paralel, lihat Contoh panggilan fungsi paralel.

Contoh teks

Python

Contoh ini menunjukkan skenario teks dengan satu fungsi dan satu perintah. Class ini menggunakan class GenerativeModel dan metodenya. Untuk mengetahui informasi selengkapnya tentang penggunaan Vertex AI SDK untuk Python dengan model multimodal Gemini, lihat Pengantar class multimodal di Vertex AI SDK untuk Python.

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Python API.

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

# Initialize Vertex AI
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-1.0-pro-001")

# Define the user's prompt in a Content object that we can reuse in model calls
user_prompt_content = Content(
    role="user",
    parts=[
        Part.from_text("What is the weather like in Boston?"),
    ],
)

# Specify a function declaration and parameters for an API request
function_name = "get_current_weather"
get_current_weather_func = FunctionDeclaration(
    name=function_name,
    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": "Location"}},
    },
)

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

# Send the prompt and instruct the model to generate content using the Tool that you just created
response = model.generate_content(
    user_prompt_content,
    generation_config=GenerationConfig(temperature=0),
    tools=[weather_tool],
)
function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == function_name:
    # Extract the arguments to use in your API call
    location = function_call.args["location"]  # noqa: F841

    # Here you can use your preferred method to make an API request to fetch the current weather, for example:
    # api_response = requests.post(weather_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = """{ "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy",
                    "icon": "partly-cloudy", "humidity": 65, "wind": { "speed": 10, "direction": "NW" } }"""

# Return the API response to Gemini so it can generate a model response or request another function call
response = model.generate_content(
    [
        user_prompt_content,  # User prompt
        response.candidates[0].content,  # Function call response
        Content(
            parts=[
                Part.from_function_response(
                    name=function_name,
                    response={
                        "content": api_response,  # Return the API response to Gemini
                    },
                ),
            ],
        ),
    ],
    tools=[weather_tool],
)

# Get the model response
print(response.text)

Node.js

Contoh ini menunjukkan skenario teks dengan satu fungsi dan satu perintah.

REST

Contoh ini menunjukkan skenario teks dengan tiga fungsi dan satu perintah.

Dalam contoh ini, Anda memanggil model AI generatif dua kali.

Permintaan model pertama

Permintaan tersebut harus menentukan kueri dalam parameter text. Contoh ini mendefinisikan kueri berikut: "Bioskop mana di Mountain View yang menampilkan film Barbie?".

Permintaan tersebut juga harus menentukan alat (tools) dengan kumpulan deklarasi fungsi (functionDeclarations). Deklarasi fungsi ini harus ditentukan dalam format yang kompatibel dengan skema OpenAPI. Contoh ini menentukan fungsi berikut:

  • find_movies menemukan judul film yang diputar di bioskop.
  • find_theatres menemukan bioskop berdasarkan lokasi.
  • get_showtimes mencari waktu mulai untuk film yang diputar di bioskop tertentu.

Untuk mempelajari parameter permintaan model lebih lanjut, lihat Gemini API.

Ganti my-project dengan nama project Google Cloud Anda.

Permintaan model pertama

PROJECT_ID=my-project
MODEL_ID=gemini-1.0-pro
API=streamGenerateContent
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"  https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:${API} -d '{
"contents": {
  "role": "user",
  "parts": {
    "text": "Which theaters in Mountain View show the Barbie movie?"
  }
},
"tools": [
  {
    "function_declarations": [
      {
        "name": "find_movies",
        "description": "find movie titles currently playing in theaters based on any description, genre, title words, etc.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
            },
            "description": {
              "type": "string",
              "description": "Any kind of description including category or genre, title words, attributes, etc."
            }
          },
          "required": [
            "description"
          ]
        }
      },
      {
        "name": "find_theaters",
        "description": "find theaters based on location and optionally movie title which are is currently playing in theaters",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
            },
            "movie": {
              "type": "string",
              "description": "Any movie title"
            }
          },
          "required": [
            "location"
          ]
        }
      },
      {
        "name": "get_showtimes",
        "description": "Find the start times for movies playing in a specific theater",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
            },
            "movie": {
              "type": "string",
              "description": "Any movie title"
            },
            "theater": {
              "type": "string",
              "description": "Name of the theater"
            },
            "date": {
              "type": "string",
              "description": "Date for requested showtime"
            }
          },
          "required": [
            "location",
            "movie",
            "theater",
            "date"
          ]
        }
      }
    ]
  }
]
}'
  

Untuk dialog "Bioskop mana di Jakarta yang menampilkan film Barbie?", model mungkin akan menampilkan fungsi find_theatres dengan parameter Barbie dan Mountain View, CA.

Respons terhadap permintaan model pertama

[{
"candidates": [
  {
    "content": {
      "parts": [
        {
          "functionCall": {
            "name": "find_theaters",
            "args": {
              "movie": "Barbie",
              "location": "Mountain View, CA"
            }
          }
        }
      ]
    },
    "finishReason": "STOP",
    "safetyRatings": [
      {
        "category": "HARM_CATEGORY_HARASSMENT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "probability": "NEGLIGIBLE"
      }
    ]
  }
],
"usageMetadata": {
  "promptTokenCount": 9,
  "totalTokenCount": 9
}
}]
  

Permintaan model kedua

Contoh ini menggunakan data sintetis, bukan memanggil API eksternal. Ada dua hasil, masing-masing dengan dua parameter (name dan address):

  1. name: AMC Mountain View 16, address: 2000 W El Camino Real, Mountain View, CA 94040
  2. name: Regal Edwards 14, address: 245 Castro St, Mountain View, CA 94040

Ganti my-project dengan nama project Google Cloud Anda.

Permintaan model kedua

PROJECT_ID=my-project
MODEL_ID=gemini-1.0-pro
API=streamGenerateContent
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"  https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:${API} -d '{
"contents": [{
  "role": "user",
  "parts": [{
    "text": "Which theaters in Mountain View show the Barbie movie?"
  }]
}, {
  "role": "model",
  "parts": [{
    "functionCall": {
      "name": "find_theaters",
      "args": {
        "location": "Mountain View, CA",
        "movie": "Barbie"
      }
    }
  }]
}, {
  "parts": [{
    "functionResponse": {
      "name": "find_theaters",
      "response": {
        "name": "find_theaters",
        "content": {
          "movie": "Barbie",
          "theaters": [{
            "name": "AMC Mountain View 16",
            "address": "2000 W El Camino Real, Mountain View, CA 94040"
          }, {
            "name": "Regal Edwards 14",
            "address": "245 Castro St, Mountain View, CA 94040"
          }]
        }
      }
    }
  }]
}],
"tools": [{
  "functionDeclarations": [{
    "name": "find_movies",
    "description": "find movie titles currently playing in theaters based on any description, genre, title words, etc.",
    "parameters": {
      "type": "OBJECT",
      "properties": {
        "location": {
          "type": "STRING",
          "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
        },
        "description": {
          "type": "STRING",
          "description": "Any kind of description including category or genre, title words, attributes, etc."
        }
      },
      "required": ["description"]
    }
  }, {
    "name": "find_theaters",
    "description": "find theaters based on location and optionally movie title which are is currently playing in theaters",
    "parameters": {
      "type": "OBJECT",
      "properties": {
        "location": {
          "type": "STRING",
          "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
        },
        "movie": {
          "type": "STRING",
          "description": "Any movie title"
        }
      },
      "required": ["location"]
    }
  }, {
    "name": "get_showtimes",
    "description": "Find the start times for movies playing in a specific theater",
    "parameters": {
      "type": "OBJECT",
      "properties": {
        "location": {
          "type": "STRING",
          "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
        },
        "movie": {
          "type": "STRING",
          "description": "Any movie title"
        },
        "theater": {
          "type": "STRING",
          "description": "Name of the theater"
        },
        "date": {
          "type": "STRING",
          "description": "Date for requested showtime"
        }
      },
      "required": ["location", "movie", "theater", "date"]
    }
  }]
}]
}'
  

Respons model mungkin mirip dengan berikut ini:

Respons terhadap permintaan model kedua

{
"candidates": [
  {
    "content": {
      "parts": [
        {
          "text": " OK. Barbie is showing in two theaters in Mountain View, CA: AMC Mountain View 16 and Regal Edwards 14."
        }
      ]
    }
  }
],
"usageMetadata": {
  "promptTokenCount": 9,
  "candidatesTokenCount": 27,
  "totalTokenCount": 36
}
}
  

Contoh chat

Python

Contoh ini menunjukkan skenario chat dengan dua fungsi dan dua perintah berurutan. Class ini menggunakan class GenerativeModel dan metodenya. Untuk mengetahui informasi selengkapnya tentang penggunaan Vertex AI SDK untuk Python dengan model multimodal, lihat Pengantar class multimodal di Vertex AI SDK untuk Python.

Untuk mempelajari cara menginstal atau mengupdate Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi Python API.

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

# Initialize Vertex AI
# project_id = "PROJECT_ID"
# TODO(developer): Update and un-comment below lines
vertexai.init(project=project_id, location="us-central1")

# Specify a function declaration and parameters for an API request
get_product_sku = "get_product_sku"
get_product_sku_func = FunctionDeclaration(
    name=get_product_sku,
    description="Get the SKU for a product",
    # 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_sku_func,
        get_store_location_func,
    ],
)

# Initialize Gemini model
model = GenerativeModel(
    model_name="gemini-1.0-pro-001",
    generation_config=GenerationConfig(temperature=0),
    tools=[retail_tool],
)

# Start a chat session
chat = model.start_chat()

# Send a prompt for the first conversation turn that should invoke the get_product_sku function
response = chat.send_message("Do you have the Pixel 8 Pro in stock?")

function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == get_product_sku:
    # Extract the arguments to use in your API call
    product_name = function_call.args["product_name"]  # noqa: F841

    # Here you can use your preferred method to make an API request to retrieve the product SKU, as in:
    # api_response = requests.post(product_api_url, data={"product_name": product_name})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = {"sku": "GA04834-US", "in_stock": "yes"}

# Return the API response to Gemini, so it can generate a model response or request another function call
response = chat.send_message(
    Part.from_function_response(
        name=get_product_sku,
        response={
            "content": api_response,
        },
    ),
)
# Extract the text from the model response
print(response.text)

# Send a prompt for the second conversation turn that should invoke the get_store_location function
response = chat.send_message(
    "Is there a store in Mountain View, CA that I can visit to try it out?"
)

function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == "get_store_location":
    # Extract the arguments to use in your API call
    location = function_call.args["location"]  # noqa: F841

    # Here you can use your preferred method to make an API request to retrieve store location closest to the user, as in:
    # api_response = requests.post(store_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = {"store": "2000 N Shoreline Blvd, Mountain View, CA 94043, US"}

# Return the API response to Gemini, so it can generate a model response or request another function call
response = chat.send_message(
    Part.from_function_response(
        name="get_store_location",
        response={
            "content": api_response,
        },
    ),
)

# Extract the text from the model response
print(response.text)

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.Content;
import com.google.cloud.vertexai.api.FunctionDeclaration;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.api.Schema;
import com.google.cloud.vertexai.api.Tool;
import com.google.cloud.vertexai.api.Type;
import com.google.cloud.vertexai.generativeai.ChatSession;
import com.google.cloud.vertexai.generativeai.ContentMaker;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.PartMaker;
import com.google.cloud.vertexai.generativeai.ResponseHandler;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;

public class FunctionCalling {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-google-cloud-project-id";
    String location = "us-central1";
    String modelName = "gemini-1.0-pro-002";

    String promptText = "What's the weather like in Paris?";

    whatsTheWeatherLike(projectId, location, modelName, promptText);
  }

  public static String whatsTheWeatherLike(String projectId, String location,
                                           String modelName, String promptText)
      throws IOException {

    try (VertexAI vertexAI = new VertexAI(projectId, location)) {

      FunctionDeclaration functionDeclaration = FunctionDeclaration.newBuilder()
          .setName("getCurrentWeather")
          .setDescription("Get the current weather in a given location")
          .setParameters(
              Schema.newBuilder()
                  .setType(Type.OBJECT)
                  .putProperties("location", Schema.newBuilder()
                      .setType(Type.STRING)
                      .setDescription("location")
                      .build()
                  )
                  .addRequired("location")
                  .build()
          )
          .build();

      System.out.println("Function declaration:");
      System.out.println(functionDeclaration);

      // Add the function to a "tool"
      Tool tool = Tool.newBuilder()
          .addFunctionDeclarations(functionDeclaration)
          .build();

      // Start a chat session from a model, with the use of the declared function.
      GenerativeModel model = new GenerativeModel(modelName, vertexAI)
          .withTools(Arrays.asList(tool));
      ChatSession chat = model.startChat();

      System.out.println(String.format("Ask the question: %s", promptText));
      GenerateContentResponse response = chat.sendMessage(promptText);

      // The model will most likely return a function call to the declared
      // function `getCurrentWeather` with "Paris" as the value for the
      // argument `location`.
      System.out.println("\nPrint response: ");
      System.out.println(ResponseHandler.getContent(response));

      // Provide an answer to the model so that it knows what the result
      // of a "function call" is.
      Content content =
          ContentMaker.fromMultiModalData(
              PartMaker.fromFunctionResponse(
                  "getCurrentWeather",
                  Collections.singletonMap("currentWeather", "sunny")));
      System.out.println("Provide the function response: ");
      System.out.println(content);
      response = chat.sendMessage(content);

      // See what the model replies now
      System.out.println("Print response: ");
      String finalAnswer = ResponseHandler.getText(response);
      System.out.println(finalAnswer);

      return finalAnswer;
    }
  }
}

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Go Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

// functionCallsChat opens a chat session and sends 4 messages to the model:
// - convert a first text question into a structured function call request
// - convert the first structured function call response into natural language
// - convert a second text question into a structured function call request
// - convert the second structured function call response into natural language
func functionCallsChat(w io.Writer, projectID, location, modelName string) error {
	// location := "us-central1"
	// modelName := "gemini-1.0-pro-002"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %v", err)
	}
	defer client.Close()

	model := client.GenerativeModel(modelName)

	// Build an OpenAPI schema, in memory
	paramsProduct := &genai.Schema{
		Type: genai.TypeObject,
		Properties: map[string]*genai.Schema{
			"productName": {
				Type:        genai.TypeString,
				Description: "Product name",
			},
		},
	}
	fundeclProductInfo := &genai.FunctionDeclaration{
		Name:        "getProductSku",
		Description: "Get the SKU for a product",
		Parameters:  paramsProduct,
	}
	paramsStore := &genai.Schema{
		Type: genai.TypeObject,
		Properties: map[string]*genai.Schema{
			"location": {
				Type:        genai.TypeString,
				Description: "Location",
			},
		},
	}
	fundeclStoreLocation := &genai.FunctionDeclaration{
		Name:        "getStoreLocation",
		Description: "Get the location of the closest store",
		Parameters:  paramsStore,
	}
	model.Tools = []*genai.Tool{
		{FunctionDeclarations: []*genai.FunctionDeclaration{
			fundeclProductInfo,
			fundeclStoreLocation,
		}},
	}
	model.SetTemperature(0.0)

	chat := model.StartChat()

	// Send a prompt for the first conversation turn that should invoke the getProductSku function
	prompt := "Do you have the Pixel 8 Pro in stock?"
	fmt.Fprintf(w, "Question: %s\n", prompt)
	resp, err := chat.SendMessage(ctx, genai.Text(prompt))
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has returned a function call to the declared function `getProductSku`
	// with a value for the argument `productName`.
	jsondata, err := json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call generated by the model:\n\t%s\n", string(jsondata))

	// Create a function call response, to simulate the result of a call to a
	// real service
	funresp := &genai.FunctionResponse{
		Name: "getProductSku",
		Response: map[string]any{
			"sku":      "GA04834-US",
			"in_stock": "yes",
		},
	}
	jsondata, err = json.MarshalIndent(funresp, "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call response sent to the model:\n\t%s\n\n", string(jsondata))

	// And provide the function call response to the model
	resp, err = chat.SendMessage(ctx, funresp)
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has taken the function call response as input, and has
	// reformulated the response to the user.
	jsondata, err = json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "Answer generated by the model:\n\t%s\n\n", string(jsondata))

	// Send a prompt for the second conversation turn that should invoke the getStoreLocation function
	prompt2 := "Is there a store in Mountain View, CA that I can visit to try it out?"
	fmt.Fprintf(w, "Question: %s\n", prompt)

	resp, err = chat.SendMessage(ctx, genai.Text(prompt2))
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has returned a function call to the declared function `getStoreLocation`
	// with a value for the argument `store`.
	jsondata, err = json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call generated by the model:\n\t%s\n", string(jsondata))

	// Create a function call response, to simulate the result of a call to a
	// real service
	funresp = &genai.FunctionResponse{
		Name: "getStoreLocation",
		Response: map[string]any{
			"store": "2000 N Shoreline Blvd, Mountain View, CA 94043, US",
		},
	}
	jsondata, err = json.MarshalIndent(funresp, "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "function call response sent to the model:\n\t%s\n\n", string(jsondata))

	// And provide the function call response to the model
	resp, err = chat.SendMessage(ctx, funresp)
	if err != nil {
		return err
	}
	if len(resp.Candidates) == 0 ||
		len(resp.Candidates[0].Content.Parts) == 0 {
		return errors.New("empty response from model")
	}

	// The model has taken the function call response as input, and has
	// reformulated the response to the user.
	jsondata, err = json.MarshalIndent(resp.Candidates[0].Content.Parts[0], "\t", "  ")
	if err != nil {
		return fmt.Errorf("json.Marshal: %w", err)
	}
	fmt.Fprintf(w, "Answer generated by the model:\n\t%s\n\n", string(jsondata))
	return nil
}

Contoh panggilan fungsi paralel

REST

Contoh ini menunjukkan skenario dengan satu fungsi get_current_weather. Dialog pengguna adalah "Dapatkan detail cuaca di New Delhi dan San Francisco?". Model ini menawarkan dua panggilan fungsi get_current_weather paralel: satu dengan parameter New Delhi dan satunya lagi dengan parameter San Francisco. Panggilan fungsi paralel adalah fitur Pratinjau. Hal ini didukung oleh model Gemini 1.5 Pro dan Gemini 1.5 Flash.

Untuk mempelajari parameter permintaan model lebih lanjut, lihat Gemini API.

candidates {
content {
  role: "model"
  parts: [
    {
      function_call {
        name: "get_current_weather"
        args {
          fields {
            key: "location"
            value {
              string_value: "New Delhi"
            }
          }
        }
      }
    },
    {
      function_call {
        name: "get_current_weather"
        args {
          fields {
            key: "location"
            value {
              string_value: "San Francisco"
            }
          }
        }
      }
    }
  ]
}
...
}

Perintah berikut menunjukkan cara memberikan output fungsi ke model. Ganti my-project dengan nama project Google Cloud Anda.

Permintaan model

PROJECT_ID=my-project
MODEL_ID=gemini-1.5-pro-001
VERSION="v1"
LOCATION="us-central1"
ENDPOINT=${LOCATION}-aiplatform.googleapis.com
API="generateContent"
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json"  https://${ENDPOINT}/${VERSION}/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:${API} -d '{
"contents": [
    {
        "role": "user",
        "parts": {
            "text": "What is difference in temperature in New Delhi and San Francisco?"
        }
    },
    {
        "role": "model",
        "parts": [
            {
                "functionCall": {
                    "name": "get_current_weather",
                    "args": {
                        "location": "New Delhi"
                    }
                }
            },
            {
                "functionCall": {
                    "name": "get_current_weather",
                    "args": {
                        "location": "San Francisco"
                    }
                }
            }
        ]
    },
    {
        "role": "user",
        "parts": [
            {
                "functionResponse": {
                    "name": "get_current_weather",
                    "response": {
                        "temperature": 30.5,
                        "unit": "C"
                    }
                }
            },
            {
                "functionResponse": {
                    "name": "get_current_weather",
                    "response": {
                        "temperature": 20,
                        "unit": "C"
                    }
                }
            }
        ]
    }
],
"tools": [
    {
        "function_declarations": [
            {
                "name": "get_current_weather",
                "description": "Get the current weather in a specific 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"
                    ]
                }
            }
        ]
    }
]
}'
  

Respons natural language yang dibuat oleh model ini mirip dengan berikut ini:

Respons model

[
{
    "candidates": [
        {
            "content": {
                "parts": [
                    {
                        "text": "The temperature in New Delhi is 30.5C and the temperature in San Francisco is 20C. The difference is 10.5C. \n"
                    }
                ]
            },
            "finishReason": "STOP",
            ...
        }
    ]
    ...
}
]