Panggilan fungsi

Ringkasan

Model Bahasa Besar (LLM) sangat andal dalam memecahkan berbagai jenis masalah. Namun, konfigurasinya dibatasi oleh batasan berikut:

  • LLM dibekukan setelah pelatihan, sehingga pengetahuan yang ada dalamnya tidak diperbarui.
  • LLM tidak dapat membuat kueri atau mengubah data eksternal.

Panggilan fungsi dapat mengatasi kekurangan ini. Anda dapat menggunakan panggilan fungsi untuk menentukan fungsi kustom dan menyediakannya ke model AI generatif. Misalnya, Anda dapat menentukan fungsi get_weather yang menggunakan parameter lokasi dan menampilkan informasi tentang kondisi cuaca di lokasi tersebut.

Saat memproses prompt, model dapat memilih untuk mendelegasikan tugas pemrosesan data ke fungsi yang Anda identifikasi. Model ini tidak memanggil fungsi secara langsung. Sebagai gantinya, model ini memberikan output data terstruktur yang menyertakan fungsi yang akan dipanggil dan parameter value yang akan digunakan. Misalnya, untuk prompt What is the weather like in Boston?, model dapat mendelegasikan pemrosesan ke fungsi get_weather dan berikan nilai parameter lokasi Boston, MA.

Anda dapat menggunakan output terstruktur dari model untuk memanggil API eksternal. Sebagai Misalnya, Anda dapat terhubung ke API layanan cuaca, memberikan lokasi Boston, MA, dan menerima informasi tentang suhu, tutupan awan, dan angin conditions.

Anda kemudian dapat memberikan output API kembali ke model, sehingga model dapat menyelesaikan responsnya terhadap prompt. Untuk contoh cuaca, model dapat memberikan respons berikut: It is currently 38 degrees Fahrenheit in Boston, MA with partly cloudy skies.

Interaksi Panggilan Fungsi 

Model berikut memberikan dukungan untuk panggilan fungsi:

Model Versi Tahap peluncuran panggilan fungsi Dukungan untuk panggilan fungsi paralel Dukungan untuk panggilan fungsi paksa
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 berikut:

Kasus penggunaanContoh deskripsiContoh link
Mengekstrak entity dari cerita natural language Ekstrak daftar karakter, hubungan, hal, dan tempat dari sebuah cerita. Ekstraksi data terstruktur menggunakan panggilan fungsi [Vertex AI SDK untuk notebook Python]
Mengkueri dan memahami database SQL menggunakan natural language Minta model untuk mengonversi pertanyaan seperti What percentage of orders are returned? ke dalam kueri SQL dan membuat fungsi yang mengirimkan kueri ini ke BigQuery. Membangun Aplikasi Eksplorasi Data BigQuery yang didukung AI menggunakan Panggilan Fungsi di Gemini [Postingan blog]
Bantu pelanggan berinteraksi dengan bisnis Buat fungsi yang terhubung ke bisnis API, yang memungkinkan model memberikan jawaban akurat untuk kueri seperti Do you have the Pixel 8 Pro in stock? atau Is there a store in Mountain View, CA that I can visit to try it out? Panggilan Fungsi dengan Vertex AI Gemini API & Python SDK [Vertex AI SDK untuk notebook Python]
Contoh REST
Contoh chat Vertex AI SDK untuk Python
Membangun aplikasi AI generatif dengan terhubung ke API publik Melakukan konversi antarmata uang. Buat fungsi yang terhubung ke aplikasi pertukaran mata uang, sehingga model dapat memberikan jawaban akurat untuk kueri seperti What's the exchange rate for euros to dollars today? Cara Berinteraksi dengan API Menggunakan Panggilan Fungsi di Gemini [Codelab]
Dapatkan info cuaca untuk lokasi tertentu. Buat fungsi yang terhubung ke API layanan meteorologi, sehingga model dapat memberikan jawaban akurat untuk kueri seperti What's the weather like in Paris? Panggilan Fungsi dengan Vertex AI Gemini API & Python SDK [Vertex AI SDK untuk notebook Python]
Panggilan fungsi: Framework native untuk menghubungkan Gemini ke sistem, data, dan API eksternal [Postingan blog]
Contoh teks Vertex AI SDK untuk Python dan Node.js
Contoh chat Node.js, Java, dan Go
Konversi alamat menjadi koordinat lintang dan bujur. Buat fungsi yang mengonversi data lokasi terstruktur menjadi koordinat lintang dan bujur. Minta model untuk mengidentifikasi alamat jalan, kota, negara bagian/provinsi, dan kode pos dalam kueri seperti I want to get the lat/lon coordinates for the following address: 1600 Amphitheatre Pkwy, Mountain View, CA 94043, US. Panggilan Fungsi dengan Vertex AI Gemini API & Python SDK [Vertex AI SDK untuk notebook Python]
Menafsirkan perintah suara Membuat fungsi yang sesuai dengan tugas di dalam kendaraan. Misalnya, Anda dapat membuat fungsi yang menyalakan radio atau mengaktifkan penyejuk udara. Kirim file audio dari perintah suara pengguna ke model, dan minta model untuk mengonversi audio menjadi teks dan mengidentifikasi fungsi yang ingin dipanggil pengguna.  
Mengotomatiskan alur kerja berdasarkan pemicu lingkungan Membuat fungsi untuk mewakili proses yang dapat diotomatiskan. Berikan data dari sensor lingkungan kepada model dan minta model untuk mengurai dan memproses data guna menentukan apakah satu atau beberapa alur kerja harus diaktifkan. Misalnya, suatu model dapat memproses data suhu di gudang dan memilih untuk mengaktifkan fungsi sprinkler.  
Mengotomatiskan penetapan tiket dukungan Berikan tiket dukungan, log, dan aturan kontekstual kepada model. Minta model untuk memproses semua informasi ini untuk menentukan kepada siapa tiket tersebut harus ditetapkan. Panggil fungsi untuk menetapkan tiket kepada orang yang disarankan oleh model.  
Mengambil informasi dari pusat informasi Membuat fungsi yang mengambil artikel akademik tentang subjek tertentu dan meringkasnya. Memungkinkan model untuk menjawab pertanyaan tentang mata pelajaran akademik dan memberikan kutipan untuk jawabannya.  

Membuat aplikasi panggilan fungsi

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

  1. Lakukan inisialisasi model.
  2. Menentukan perintah pengguna.
  3. Menentukan dan menjelaskan serangkaian fungsi yang tersedia menggunakan deklarasi fungsi.
  4. Kirimkan perintah pengguna dan deklarasi fungsi ke model.
  5. Panggil fungsi menggunakan output data terstruktur dari model.
  6. Berikan output fungsi ke model.

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

Anda dapat menggunakan panggilan fungsi untuk menghasilkan satu respons teks atau untuk mendukung sesi obrolan. Respons teks {i>ad hoc <i}berguna untuk tugas bisnis tertentu, termasuk pembuatan kode. Sesi chat berguna dalam percakapan berformat bebas skenario, di mana pengguna cenderung mengajukan pertanyaan lanjutan.

Jika menggunakan panggilan fungsi untuk menghasilkan satu respons, Anda harus menyediakan model dengan konteks penuh dari interaksi. Di sisi lain, jika Anda menggunakan panggilan fungsi dalam konteks sesi {i>chat<i}, sesi menyimpan konteks tambahan untuk Anda dan menyertakannya di setiap permintaan model. Dalam kedua kasus tersebut, Vertex AI menyimpan histori interaksi di sisi klien.

Panduan ini menunjukkan cara menggunakan panggilan fungsi untuk membuat satu panggilan respons teks. Untuk melihat contoh menyeluruh, lihat Contoh teks. Untuk mempelajari cara menggunakan panggilan fungsi guna mendukung sesi chat, lihat Contoh chat.

Melakukan inisialisasi model

Berikut adalah contoh cara melakukan inisialisasi model:

Python

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")

Menentukan perintah pengguna

Berikut adalah contoh {i>prompt<i} pengguna: "Bagaimana cuaca di Jakarta?"

Berikut adalah contoh cara menentukan dialog pengguna:

Python

# 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?"),
    ],
)

Untuk mengetahui praktik terbaik terkait perintah pengguna, lihat Praktik terbaik - Perintah pengguna.

Menentukan dan menjelaskan serangkaian fungsi yang tersedia

Aplikasi harus mendeklarasikan sekumpulan fungsi yang dapat digunakan model untuk akan memproses prompt tersebut. Setiap deklarasi fungsi harus menyertakan nama fungsi dan parameter fungsi. Sebaiknya Anda juga menyertakan deskripsi fungsi di setiap deklarasi fungsi.

Jumlah maksimum deklarasi fungsi yang dapat diberikan dengan permintaan adalah 128.

Nama fungsi

Aplikasi dan model menggunakan nama fungsi untuk mengidentifikasi fungsi.

Untuk praktik terbaik yang terkait dengan 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. Hal berikut atribut didukung: type, nullable, required, format, description, properties, items, enum. Atribut berikut tidak didukung: default, optional, maximum, oneOf.

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

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

Deskripsi fungsi

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

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

Contoh deklarasi fungsi

Python: deklarasi sederhana

Berikut adalah contoh deklarasi fungsi sederhana di Python:

function_name = "get_current_weather"
get_current_weather_func = FunctionDeclaration(
    name=function_name,
    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."}},
    },
)

Python: array item

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"],
  },
)

Mengirimkan perintah dan deklarasi fungsi ke model

Saat pengguna memberikan prompt, aplikasi harus menyediakan model dengan perintah pengguna dan deklarasi fungsi. Untuk mengonfigurasi cara model memberikan hasil, aplikasi dapat menyediakan model dengan konfigurasi pembuatan. Untuk mengonfigurasi cara model menggunakan deklarasi fungsi, aplikasi dapat menyediakan model dengan konfigurasi alat. Fungsi tidak mendukung input multimodal.

Konfigurasi pembuatan

Model ini dapat membuat hasil yang berbeda untuk parameter value yang berbeda. Tujuan temperatur akan mengontrol tingkat keacakan dalam generasi ini. Suhu yang lebih rendah cocok untuk fungsi yang memerlukan parameter deterministik sedangkan suhu yang lebih tinggi baik untuk fungsi dengan parameter yang menerima parameter value materi iklan yang lebih beragam. Suhu 0 determenistik. Dalam hal ini, sebagian besar respons untuk perintah tertentu determenistik, tetapi masih dapat dilakukan dalam jumlah kecil. Untuk mempelajari selengkapnya, lihat Gemini API.

Untuk menetapkan parameter ini, kirimkan konfigurasi pembuatan (generation_config) beserta prompt dan deklarasi fungsi. Anda dapat memperbarui Parameter temperature selama percakapan chat menggunakan Vertex AI API dan generation_config yang diupdate. Misalnya pengaturan Parameter temperature, lihat Cara mengirimkan perintah dan deklarasi fungsi.

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

Konfigurasi alat

Anda dapat menempatkan beberapa batasan pada cara model harus menggunakan fungsi tersebut yang Anda sediakan. Misalnya, alih-alih mengizinkan model untuk memilih antara respons natural language dan panggilan fungsi, Anda dapat memaksanya untuk hanya memprediksi panggilan fungsi ("panggilan fungsi paksa"). Anda juga dapat memilih untuk memberikan dengan serangkaian deklarasi fungsi lengkap, tetapi membatasi responsnya subset dari fungsi-fungsi tersebut.

Untuk menempatkan batasan ini, kirimkan konfigurasi alat (tool_config) bersama dengan prompt dan deklarasi fungsi. Dalam konfigurasi, Anda bisa menentukan salah satu mode berikut:

Mode Deskripsi
AUTO Perilaku model default. Model 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.
TIDAK ADA Model tidak boleh memprediksi panggilan fungsi. Perilaku ini setara dengan permintaan model tanpa deklarasi fungsi terkait.

Mode ANY konfigurasi alat ("panggilan fungsi paksa") adalah 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 perintah dan fungsinya deklarasi ke model, dan membatasi model agar hanya memprediksi Panggilan fungsi get_current_weather.

Python

# Define a tool that includes the function declaration 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 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 membutuhkan output dari fungsi tertentu, yang diterima aplikasi dari model 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?". 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 dapat mengusulkan beberapa panggilan fungsi paralel. Panggilan fungsi paralel adalah fitur Pratinjau. Ini didukung oleh Gemini 1.5 Pro dan Gemini 1.5 Flash jaringan. Untuk mempelajari lebih lanjut, lihat Contoh panggilan fungsi paralel.

Memanggil API eksternal

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

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

Python

# 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.

Memberikan output fungsi ke model

Setelah aplikasi menerima respons dari API eksternal, aplikasi harus memberikan respons ini ke model. Berikut adalah contoh bagaimana Anda kita bisa melakukannya dengan Python:

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 telah mengusulkan beberapa panggilan fungsi paralel, aplikasi harus mengirimkan semua respons ke model. Panggilan fungsi paralel adalah Pratinjau. Ini didukung oleh Gemini 1.5 Pro dan Gemini 1.5 Flash jaringan. Untuk mempelajari lebih lanjut, lihat Contoh panggilan fungsi paralel.

Model gemini-1.0-pro-001 dan gemini-1.0-pro-002 dapat menentukan bahwa {i>output<i} dari fungsi lain diperlukan untuk merespons {i>prompt<i}. Dalam kasus ini, respons yang diterima aplikasi dari model berisi elemen nama fungsi dan satu set nilai parameter lainnya.

Jika model menentukan bahwa respons API cukup untuk merespons perintah pengguna, tindakan itu akan membuat respons natural language dan mengembalikannya ke aplikasi. Dalam hal ini, aplikasi harus meneruskan respons kembali ke . Berikut adalah contoh respons:

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.

Contoh teks

Anda dapat menggunakan panggilan fungsi untuk menghasilkan satu respons teks. Teks ad hoc berguna untuk tugas bisnis tertentu, termasuk pembuatan kode.

Jika menggunakan panggilan fungsi untuk menghasilkan satu respons, Anda harus menyediakan model dengan konteks penuh dari interaksi. Penyimpanan Vertex AI riwayat interaksi di sisi klien.

Python

Contoh ini menunjukkan skenario teks dengan satu fungsi dan satu fungsi . Class tersebut menggunakan class GenerativeModel dan metodenya. Untuk selengkapnya informasi tentang penggunaan Vertex AI SDK untuk Python dengan multimodal Gemini melihat 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 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("gemini-1.5-flash-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)

C#

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

C#

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

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


using Google.Cloud.AIPlatform.V1;
using System;
using System.Threading.Tasks;
using Type = Google.Cloud.AIPlatform.V1.Type;
using Value = Google.Protobuf.WellKnownTypes.Value;

public class FunctionCalling
{
    public async Task<string> GenerateFunctionCall(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.5-flash-001")
    {
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        // Define the user's prompt in a Content object that we can reuse in
        // model calls
        var userPromptContent = new Content
        {
            Role = "USER",
            Parts =
            {
                new Part { Text = "What is the weather like in Boston?" }
            }
        };

        // Specify a function declaration and parameters for an API request
        var functionName = "get_current_weather";
        var getCurrentWeatherFunc = new FunctionDeclaration
        {
            Name = functionName,
            Description = "Get the current weather in a given location",
            Parameters = new OpenApiSchema
            {
                Type = Type.Object,
                Properties =
                {
                    ["location"] = new()
                    {
                        Type = Type.String,
                        Description = "Get the current weather in a given location"
                    },
                    ["unit"] = new()
                    {
                        Type = Type.String,
                        Description = "The unit of measurement for the temperature",
                        Enum = {"celsius", "fahrenheit"}
                    }
                },
                Required = { "location" }
            }
        };

        // Send the prompt and instruct the model to generate content using the tool that you just created
        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0f
            },
            Contents =
            {
                userPromptContent
            },
            Tools =
            {
                new Tool
                {
                    FunctionDeclarations = { getCurrentWeatherFunc }
                }
            }
        };

        GenerateContentResponse response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        var functionCall = response.Candidates[0].Content.Parts[0].FunctionCall;
        Console.WriteLine(functionCall);

        string apiResponse = "";

        // Check the function name that the model responded with, and make an API call to an external system
        if (functionCall.Name == functionName)
        {
            // Extract the arguments to use in your API call
            string locationCity = functionCall.Args.Fields["location"].StringValue;

            // Here you can use your preferred method to make an API request to
            // fetch the current weather

            // In this example, we'll use synthetic data to simulate a response
            // payload from an external API
            apiResponse = @"{ ""location"": ""Boston, MA"",
                    ""temperature"": 38, ""description"": ""Partly Cloudy""}";
        }

        // Return the API response to Gemini so it can generate a model response or request another function call
        generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            Contents =
            {
                userPromptContent, // User prompt
                response.Candidates[0].Content, // Function call response,
                new Content
                {
                    Parts =
                    {
                        new Part
                        {
                            FunctionResponse = new()
                            {
                                Name = functionName,
                                Response = new()
                                {
                                    Fields =
                                    {
                                        { "content", new Value { StringValue = apiResponse } }
                                    }
                                }
                            }
                        }
                    }
                }
            },
            Tools =
            {
                new Tool
                {
                    FunctionDeclarations = { getCurrentWeatherFunc }
                }
            }
        };

        response = await predictionServiceClient.GenerateContentAsync(generateContentRequest);

        string responseText = response.Candidates[0].Content.Parts[0].Text;
        Console.WriteLine(responseText);

        return responseText;
    }
}

Node.js

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

Node.js

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

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

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

const functionResponseParts = [
  {
    functionResponse: {
      name: 'get_current_weather',
      response: {name: 'get_current_weather', content: {weather: 'super nice'}},
    },
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {role: 'user', parts: [{text: 'What is the weather in Boston?'}]},
      {
        role: 'model',
        parts: [
          {
            functionCall: {
              name: 'get_current_weather',
              args: {location: 'Boston'},
            },
          },
        ],
      },
      {role: 'user', parts: functionResponseParts},
    ],
    tools: functionDeclarations,
  };
  const streamingResp = await generativeModel.generateContentStream(request);
  for await (const item of streamingResp.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

REST

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

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

Permintaan model pertama

Permintaan harus menentukan dialog dalam parameter text. Contoh ini mendefinisikan pertanyaan berikut: "Bioskop mana di Jakarta yang menampilkan film Barbie?".

Permintaan juga harus menentukan alat (tools) dengan kumpulan fungsi deklarasi (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 menemukan waktu mulai untuk film yang diputar di bioskop tertentu.

Untuk mempelajari lebih lanjut parameter permintaan model, 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 pertanyaan "Bioskop mana di Jakarta yang menampilkan film Barbie?", modelnya mungkin 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 respons berikut:

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

Anda dapat menggunakan panggilan fungsi untuk mendukung sesi chat. Sesi chat sangat berguna dalam skenario percakapan bentuk bebas, di mana pengguna cenderung meminta tindak lanjut semua pertanyaan.

Jika Anda menggunakan panggilan fungsi dalam konteks sesi chat, sesi tersebut akan menyimpan konteks untuk Anda dan menyertakannya di setiap permintaan model. Vertex AI menyimpan histori interaksi di sisi klien.

Python

Contoh ini menunjukkan skenario chat dengan dua fungsi dan dua prompt berurutan. Class tersebut menggunakan class GenerativeModel dan metodenya. Sebagai 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 Instal Vertex AI SDK untuk Python. Untuk 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.5-flash-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 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.5-flash-001";

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

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

  // A request involving the interaction with an external tool
  public static String whatsTheWeatherLike(String projectId, String location,
                                           String modelName, String promptText)
      throws IOException {
    // Initialize client that will be used to send requests.
    // This client only needs to be created once, and can be reused for multiple requests.
    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 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.5-flash-001"
	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectID, location)
	if err != nil {
		return fmt.Errorf("unable to create client: %w", 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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %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.MarshalIndent: %w", err)
	}
	fmt.Fprintf(w, "Answer generated by the model:\n\t%s\n\n", string(jsondata))
	return nil
}

Node.js

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

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

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

const functionResponseParts = [
  {
    functionResponse: {
      name: 'get_current_weather',
      response: {name: 'get_current_weather', content: {weather: 'super nice'}},
    },
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingStreamChat(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  // Create a chat session and pass your function declarations
  const chat = generativeModel.startChat({
    tools: functionDeclarations,
  });

  const chatInput1 = 'What is the weather in Boston?';

  // This should include a functionCall response from the model
  const result1 = await chat.sendMessageStream(chatInput1);
  for await (const item of result1.stream) {
    console.log(item.candidates[0]);
  }
  await result1.response;

  // Send a follow up message with a FunctionResponse
  const result2 = await chat.sendMessageStream(functionResponseParts);
  for await (const item of result2.stream) {
    console.log(item.candidates[0]);
  }

  // This should include a text response from the model using the response content
  // provided above
  const response2 = await result2.response;
  console.log(response2.candidates[0].content.parts[0].text);
}

Contoh panggilan fungsi paralel

Untuk perintah seperti "Dapatkan detail cuaca di New Delhi dan San Francisco?", model dapat mengusulkan beberapa panggilan fungsi paralel. Panggilan fungsi paralel adalah fitur Pratinjau. Ini didukung oleh Gemini 1.5 Pro dan Gemini 1.5 Flash jaringan.

REST

Contoh ini menunjukkan skenario dengan satu fungsi get_current_weather. Perintah pengguna adalah "Dapatkan detail cuaca di New Delhi dan San Francisco?". Tujuan model ini mengusulkan dua panggilan fungsi get_current_weather paralel: satu dengan parameter New Delhi dan parameter lainnya dengan parameter San Francisco. Panggilan fungsi paralel adalah Pratinjau aplikasi baru. Ini didukung oleh Model Gemini 1.5 Pro dan Gemini 1.5 Flash.

Untuk mempelajari lebih lanjut parameter permintaan model, 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 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",
            ...
        }
    ]
    ...
}
]
  

Praktik terbaik

Nama fungsi

Jangan gunakan karakter titik (.), tanda hubung (-), atau spasi pada 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 disukai. 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 jenis yang sesuai untuk mengurangi halusinasi model. Sebagai misalnya, jika nilai parameter berasal dari himpunan terbatas, tambahkan kolom enum alih-alih menempatkan kumpulan nilai ke dalam deskripsi. Jika parameter nilainya 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 mendapatkan hasil terbaik, awali perintah pengguna dengan detail berikut:

  • 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-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 menginstruksikan model untuk memberikan hasil yang lebih meyakinkan dan mengurangi halusinasi.

Pemanggilan API

Jika model mengusulkan fungsi yang akan mengirim urutan, memperbarui database, atau memiliki konsekuensi yang signifikan, memvalidasi dengan pengguna sebelum mengeksekusinya.

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 (prompt) mengacu pada {i>prompt <i}pengguna untuk putaran percakapan saat ini, fungsi deklarasi untuk perubahan percakapan saat ini, dan histori percakapan. Riwayat percakapan mencakup kueri, fungsi panggilan, dan fungsi respons percakapan sebelumnya. Vertex AI memangkas histori percakapan menjadi 32.000 karakter.

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