<ph type="x-smartling-placeholder">
関数呼び出しを使用すると、構造化データの出力を 説明します。その後、これらの出力を使用して他の API を呼び出し、 レスポンス データをモデルに送ります。つまり関数呼び出しは 生成モデルを外部システムに接続して、生成されたコンテンツが に最新の正確な情報が含まれています。
Gemini モデルに関数の説明を提供できます。これらは アプリケーションの言語で記述する関数(つまり、 Google Cloud Functions)。モデルから、関数を呼び出して値を返すよう求められる場合があります。 モデルがクエリを処理できるよう支援します。
まだご覧になっていない場合は、 関数呼び出しの概要で学習する できます。 また、 この機能を試すには Google Colab または、 Gemini API クックブック リポジトリ。
照明制御用の API の例
基本的な照明制御システムとアプリケーション プログラミング インターフェース(API)を使用していて、ユーザーがシンプルな テキスト リクエスト。関数呼び出し機能を使用してライティングを解釈できる API 呼び出しに変換して照明を設定する API 呼び出しに変換し、 使用できます。この架空の照明制御システムを使用して、 明るさと色温度です parameters:
パラメータ | タイプ | 必須 / 省略可 | 説明 |
---|---|---|---|
brightness |
数値 | あり | 光レベル(0 ~ 100)。ゼロがオフで、100 が最大の明るさです。 |
colorTemperature |
文字列 | あり | 照明器具の色温度(daylight 、cool 、warm )。 |
わかりやすくするため、この架空の照明システムにはライトが 1 つしかないため、ユーザーは 客室や場所を指定する必要はありません。これが JSON リクエストの例です。 照明制御 API に送信して照明レベルを 50% に 昼光色温度を使うと次の式になります
{
"brightness": "50",
"colorTemperature": "daylight"
}
このチュートリアルでは、Gemini API の関数呼び出しを設定して、 ユーザーの照明リクエストを解釈し、API 設定にマッピングして 明るさと色温度の値に基づいて変化します
始める前に: プロジェクトと API キーを設定する
Gemini API を呼び出す前に、プロジェクトをセットアップして、 取得します。
API 関数を定義する
API リクエストを行う関数を作成します。この関数を定義する必要があります。 コード内で使用できますが、外部からサービスや API を呼び出すことはできます。 説明します。Gemini API は、この関数を直接呼び出しません。そのため、 この機能をアプリケーションで実行する方法とタイミングを制御できます。 できます。デモを目的として、このチュートリアルで定義するモック API 関数では、 リクエストされた照明の値を返すだけです。
def set_light_values(brightness, color_temp):
"""Set the brightness and color temperature of a room light. (mock API).
Args:
brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
Returns:
A dictionary containing the set brightness and color temperature.
"""
return {
"brightness": brightness,
"colorTemperature": color_temp
}
モデルによる関数呼び出しで使用する関数を作成すると、 関数とパラメータには、できるだけ詳しく記述する必要があります。 説明します。生成モデルはこの情報を使用して、 選択する関数と、その関数でパラメータの値を指定する方法 あります。
モデルの初期化時に関数を宣言する
モデルで関数呼び出しを使用する場合は、
指定する必要があります。関数を宣言するには、Terraform で
モデルの tools
パラメータ:
model = genai.GenerativeModel(model_name='gemini-1.5-flash',
tools=[set_light_values])
関数呼び出しを生成する
関数宣言でモデルを初期化したら、プロンプトを使用して、
モデルを定義します。関数呼び出しを使用するには、
チャット プロンプト(sendMessage()
)。関数呼び出しのメリットは一般的に
プロンプトやレスポンスのコンテキストがあります。
chat = model.start_chat()
response = chat.send_message('Dim the lights so the room feels cozy and warm.')
response.text
Python SDK の
ChatSession
会話の履歴を処理することでチャット セッションの管理を簡素化する
できます。enable_automatic_function_calling
を使用して、SDK を
自動的に
# Create a chat session that automatically makes suggested function calls
chat = model.start_chat(enable_automatic_function_calling=True)
並列関数呼び出し
上記の基本的な関数呼び出しに加えて、1 回のターンで複数の関数を呼び出すこともできます。このセクションでは、並列関数呼び出しの使用方法の例を示します。
ツールを定義する。
def power_disco_ball(power: bool) -> bool:
"""Powers the spinning disco ball."""
print(f"Disco ball is {'spinning!' if power else 'stopped.'}")
return True
def start_music(energetic: bool, loud: bool, bpm: int) -> str:
"""Play some music matching the specified parameters.
Args:
energetic: Whether the music is energetic or not.
loud: Whether the music is loud or not.
bpm: The beats per minute of the music.
Returns: The name of the song being played.
"""
print(f"Starting music! {energetic=} {loud=}, {bpm=}")
return "Never gonna give you up."
def dim_lights(brightness: float) -> bool:
"""Dim the lights.
Args:
brightness: The brightness of the lights, 0.0 is off, 1.0 is full.
"""
print(f"Lights are now set to {brightness:.0%}")
return True
次に、指定したすべてのツールを使用できる命令を使用してモデルを呼び出します。
# Set the model up with tools.
house_fns = [power_disco_ball, start_music, dim_lights]
model = genai.GenerativeModel(model_name="gemini-1.5-flash", tools=house_fns)
# Call the API.
chat = model.start_chat()
response = chat.send_message("Turn this place into a party!")
# Print out each of the function calls requested from this single call.
for part in response.parts:
if fn := part.function_call:
args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
print(f"{fn.name}({args})")
power_disco_ball(power=True) start_music(energetic=True, loud=True, bpm=120.0) dim_lights(brightness=0.3)
出力される各結果には、モデルがリクエストした単一の関数呼び出しが反映されています。結果を送り返すには、回答をリクエストしたのと同じ順序で含めます。
# Simulate the responses from the specified tools.
responses = {
"power_disco_ball": True,
"start_music": "Never gonna give you up.",
"dim_lights": True,
}
# Build the response parts.
response_parts = [
genai.protos.Part(function_response=genai.protos.FunctionResponse(name=fn, response={"result": val}))
for fn, val in responses.items()
]
response = chat.send_message(response_parts)
print(response.text)
Let's get this party started! I've turned on the disco ball, started playing some upbeat music, and dimmed the lights. 🎶✨ Get ready to dance! 🕺💃
関数呼び出しのデータ型マッピング
Python 関数からの自動スキーマ抽出は、すべてのケースで機能するわけではありません。たとえば、ネストされた辞書オブジェクトのフィールドを記述するケースは処理されませんが、API はこれをサポートしています。API は、次のいずれかのタイプを記述できます。
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])
google.ai.generativelanguage クライアント ライブラリでは、下位レベルの型にアクセスして詳細に制御できます。
まず、モデルの _tools
属性の内部をご覧ください。モデルに渡した関数がどのように記述されているかを確認できます。
def multiply(a:float, b:float):
"""returns a * b."""
return a*b
model = genai.GenerativeModel(model_name='gemini-1.5-flash',
tools=[multiply])
model._tools.to_proto()
[function_declarations { name: "multiply" description: "returns a * b." parameters { type_: OBJECT properties { key: "b" value { type_: NUMBER } } properties { key: "a" value { type_: NUMBER } } required: "a" required: "b" } }]
これは、サーバーに送信されるであろう genai.protos.Tool
オブジェクトのリストを返します。
API印刷されたフォーマットに馴染みがないというのは、
使用します。各 genai.protos.Tool
(この場合は 1)には、
genai.protos.FunctionDeclarations
は、関数とその関数を記述します。
渡します。
こちらは、上記と同じ乗算関数の宣言で、
genai.protos
クラス。これらのクラスは、変数の
その実装は含まれていません。これを使用しても
使用できますが、関数にコードがなくても
説明します。
calculator = genai.protos.Tool(
function_declarations=[
genai.protos.FunctionDeclaration(
name='multiply',
description="Returns the product of two numbers.",
parameters=genai.protos.Schema(
type=genai.protos.Type.OBJECT,
properties={
'a':genai.protos.Schema(type=genai.protos.Type.NUMBER),
'b':genai.protos.Schema(type=genai.protos.Type.NUMBER)
},
required=['a','b']
)
)
])
同様に、これを JSON 互換オブジェクトとして記述できます。
calculator = {'function_declarations': [
{'name': 'multiply',
'description': 'Returns the product of two numbers.',
'parameters': {'type_': 'OBJECT',
'properties': {
'a': {'type_': 'NUMBER'},
'b': {'type_': 'NUMBER'} },
'required': ['a', 'b']} }]}
genai.protos.Tool(calculator)
function_declarations { name: "multiply" description: "Returns the product of two numbers." parameters { type_: OBJECT properties { key: "b" value { type_: NUMBER } } properties { key: "a" value { type_: NUMBER } } required: "a" required: "b" } }
どちらの場合も、genai.protos.Tool
またはツールのリストの表現を
model = genai.GenerativeModel('gemini-1.5-flash', tools=calculator)
chat = model.start_chat()
response = chat.send_message(
f"What's 234551 X 325552 ?",
)
前の例と同様に、モデルは計算機の multiply
関数を呼び出す genai.protos.FunctionCall
を返します。
response.candidates
[index: 0 content { parts { function_call { name: "multiply" args { fields { key: "b" value { number_value: 325552 } } fields { key: "a" value { number_value: 234551 } } } } } role: "model" } finish_reason: STOP ]
関数を自分で実行します。
fc = response.candidates[0].content.parts[0].function_call
assert fc.name == 'multiply'
result = fc.args['a'] * fc.args['b']
result
76358547152.0
結果をモデルに送信して会話を継続します。
response = chat.send_message(
genai.protos.Content(
parts=[genai.protos.Part(
function_response = genai.protos.FunctionResponse(
name='multiply',
response={'result': result}))]))