iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0
生成式 AI

Gemini 多模態大型語言模型大小事系列 第 13

Gemini 多模態大型語言模型大小事 Day13 - 函數呼叫配置

  • 分享至 

  • xImage
  •  

前言

    程式環境都會用colab 來執行程式,如果要在其他環境執行,請自行修改哦

colab 事前準備:設定專案和 API 金鑰
載入gemini

#pip install -q -U google-generativeai
import google.generativeai as genai

API 金鑰

from google.colab import userdata
API_KEY=userdata.get('GOOGLE_API_KEY')

#genai.configure(api_key="YOUR_API_KEY")

# Configure the client library by providing your API key.
genai.configure(api_key=API_KEY)

函數呼叫配置

指定 afunction_calling_config可讓您控制 Gemini API 在tools指定後的行為。例如,您可以選擇僅允許自由文字輸出(停用函數呼叫)、強制它從 中提供的函數子集中進行選擇tools,或讓它自動執行。

使用工具建立模型

使用 3 個函數來控制一個簡單的假設照明系統。使用這些函數需要按特定順序呼叫它們。例如,您必須先開啟燈光系統,然後才能變更顏色。

雖然您可以將它們直接傳遞給模型並讓它嘗試正確呼叫它們,但指定 可以function_calling_config讓您精確控制模型可用的函數。

def enable_lights():
    """Turn on the lighting system."""
    print("LIGHTBOT: 燈已啟用。")


def set_light_color(rgb_hex: str):
    """Set the light color. Lights must be enabled for this to work."""
    print(f"LIGHTBOT: 燈設定為 {rgb_hex}.")


def stop_lights():
    """Stop flashing lights."""
    print("LIGHTBOT: 燈已關閉。")


light_controls = [enable_lights, set_light_color, stop_lights]
instruction = "您是一個有用的照明系統機器人。您可以開啟和關閉燈光,也可以設定顏色。不要執行任何其他任務。"

model = genai.GenerativeModel(
    "models/gemini-1.5-pro", tools=light_controls, system_instruction=instruction
)

chat = model.start_chat()

function_calling_config建立一個用於設定的輔助函數tool_config。

from google.generativeai.types import content_types
from collections.abc import Iterable


def tool_config_from_mode(mode: str, fns: Iterable[str] = ()):
    """Create a tool config with the specified function calling mode."""
    return content_types.to_tool_config(
        {"function_calling_config": {"mode": mode, "allowed_function_names": fns}}
    )

純文字模式:NONE

如果您為模型提供了工具,但不想在目前會話中使用這些工具,則指定NONE為模式。NONE告訴模型不要進行任何函數調用,並且表現得就像沒有提供任何函數調用一樣。

tool_config = tool_config_from_mode("none")

response = chat.send_message(
    "你好,燈光機器人,你能做什麼?", tool_config=tool_config
)
print(response.text)

回答:
我可以開燈和關燈,還可以設定顏色。 我還能做些什麼嗎?

自動模式:AUTO

要讓模型決定是否以文字方式回應或呼叫特定函數,您可以指定AUTO為 mode。

tool_config = tool_config_from_mode("auto")

response = chat.send_message("點亮這個地方!", tool_config=tool_config)
print(response.parts[0])
chat.rewind();  # 您實際上並未呼叫該函數,因此請將其從歷史記錄中刪除。

回答:

function_call {
  name: "enable_lights"
  args {
  }
}

函數呼叫方式:ANY

將模式設定為ANY將強制模型進行函數呼叫。透過設置allowed_function_names,模型將僅從這些函數中進行選擇。如果未設置,則 中的所有函數都是tools函數呼叫的候選函數。

available_fns = ["set_light_color", "stop_lights"]

tool_config = tool_config_from_mode("any", available_fns)

response = chat.send_message("把這個地方變成紫色!", tool_config=tool_config)
print(response.parts[0])

回答:

function_call {
  name: "set_light_color"
  args {
    fields {
      key: "rgb_hex"
      value {
        string_value: "7F00FF"
      }
    }
  }
}

自動函數調用

tool_config啟用自動函數呼叫時也有效。

available_fns = ["enable_lights"]
tool_config = tool_config_from_mode("any", available_fns)

auto_chat = model.start_chat(enable_automatic_function_calling=True)
auto_chat.send_message("這裡太黑了...", tool_config=tool_config)

回答:

LIGHTBOT: 燈已啟用。
response:
GenerateContentResponse(
    done=True,
    iterator=None,
    result=protos.GenerateContentResponse({
      "candidates": [
        {
          "content": {
            "parts": [
              {
                "text": "\u6211\u5df2\u70ba\u60a8\u958b\u71c8\u3002"
              }
            ],
            "role": "model"
          },
          "finish_reason": "STOP",
          "index": 0,
          "safety_ratings": [
            {
              "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
              "probability": "NEGLIGIBLE"
            },
            {
              "category": "HARM_CATEGORY_HATE_SPEECH",
              "probability": "NEGLIGIBLE"
            },
            {
              "category": "HARM_CATEGORY_HARASSMENT",
              "probability": "NEGLIGIBLE"
            },
            {
              "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
              "probability": "NEGLIGIBLE"
            }
          ]
        }
      ],
      "usage_metadata": {
        "prompt_token_count": 163,
        "candidates_token_count": 7,
        "total_token_count": 170
      }
    }),
)

上一篇
Gemini 多模態大型語言模型大小事 Day12 - Gemini API 函式呼叫簡介
下一篇
Gemini 多模態大型語言模型大小事 Day14 - 平行函式呼叫
系列文
Gemini 多模態大型語言模型大小事18
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言