การเรียกใช้ฟังก์ชันด้วย Gemini API

การเรียกใช้ฟังก์ชันช่วยให้คุณเชื่อมต่อโมเดลกับเครื่องมือและ API ภายนอกได้ แทนที่จะสร้างการตอบกลับเป็นข้อความ โมเดลจะกำหนดเวลาที่จะเรียกใช้ฟังก์ชันที่เฉพาะเจาะจงและระบุพารามิเตอร์ที่จำเป็นเพื่อดำเนินการต่างๆ ในโลกแห่งความเป็นจริง ซึ่งช่วยให้โมเดลทำหน้าที่เป็นสะพานเชื่อมระหว่างภาษาธรรมชาติกับข้อมูลและการดำเนินการต่างๆ ในโลกแห่งความเป็นจริง การเรียกใช้ฟังก์ชันมีกรณีการใช้งานหลัก 3 กรณีดังนี้

  • ดำเนินการ: โต้ตอบกับระบบภายนอกโดยใช้ API เช่น การกำหนดเวลาการนัดหมาย การสร้างใบแจ้งหนี้ การส่งอีเมล หรือการควบคุม อุปกรณ์สมาร์ทโฮม
  • เพิ่มพูนความรู้: เข้าถึงข้อมูลจากแหล่งที่มาภายนอก เช่น ฐานข้อมูล API และฐานความรู้
  • ขยายขีดความสามารถ: ใช้เครื่องมือภายนอกเพื่อทำการคำนวณและ ขยายข้อจำกัดของโมเดล เช่น การใช้เครื่องคิดเลขหรือการสร้าง แผนภูมิ

คุณสามารถดูตัวอย่างกรณีการใช้งานเหล่านี้ได้ด้านล่าง

กำหนดเวลาการประชุม

ตัวอย่างนี้แสดงวิธีกำหนดฟังก์ชันที่กำหนดเวลาการประชุมกับผู้เข้าร่วมในเวลาที่เฉพาะเจาะจง ซึ่งช่วยให้โมเดลแยกวิเคราะห์คำขอของผู้ใช้และแสดงอาร์กิวเมนต์ที่มีโครงสร้างเพื่อทริกเกอร์การดำเนินการในระบบภายนอกได้

Python

from google import genai

schedule_meeting_function = {
    "type": "function",
    "name": "schedule_meeting",
    "description": "Schedules a meeting with specified attendees at a given time and date.",
    "parameters": {
        "type": "object",
        "properties": {
            "attendees": {"type": "array", "items": {"type": "string"}},
            "date": {"type": "string", "description": "Date (e.g., '2024-07-29')"},
            "time": {"type": "string", "description": "Time (e.g., '15:00')"},
            "topic": {"type": "string", "description": "The meeting topic."},
        },
        "required": ["attendees", "date", "time", "topic"],
    },
}

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.6-flash",
    input="Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about Q3 planning.",
    tools=[{"type": "function", **schedule_meeting_function}],
)

for step in interaction.steps:
    if step.type == "function_call":
        print(f"Function to call: {step.name}")
        print(f"Arguments: {step.arguments}")

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const scheduleMeetingFunction = {
  type: 'function',
  name: 'schedule_meeting',
  description: 'Schedules a meeting with specified attendees at a given time and date.',
  parameters: {
    type: 'object',
    properties: {
      attendees: { type: 'array', items: { type: 'string' } },
      date: { type: 'string', description: 'Date (e.g., "2024-07-29")' },
      time: { type: 'string', description: 'Time (e.g., "15:00")' },
      topic: { type: 'string', description: 'The meeting topic.' },
    },
    required: ['attendees', 'date', 'time', 'topic'],
  },
};

const interaction = await client.interactions.create({
  model: 'gemini-3.6-flash'