前往 ai.google.dev 查看 | 在 Google Colab 中執行 | 在 GitHub 上查看原始碼 |
您可以提供內含函式說明的 Gemini 模型。模型可能會要求您呼叫函式並傳回結果,協助模型處理您的查詢。
設定
安裝 Python SDK
Gemini API 的 Python SDK 已納入 google-generativeai
套件中。使用 pip 安裝依附元件:
pip install -U -q google-generativeai
匯入套件
匯入必要的套件。
import pathlib
import textwrap
import time
import google.generativeai as genai
from IPython import display
from IPython.display import Markdown
def to_markdown(text):
text = text.replace('•', ' *')
return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))
設定 API 金鑰
您必須先取得 API 金鑰,才能使用 Gemini API。如果還沒有金鑰,請在 Google AI Studio 中按一下即可建立。
在 Colab 中,請在左側面板的「🔑?」下方,將密鑰新增至密鑰管理工具。輸入名稱 API_KEY
。
取得 API 金鑰後,請傳遞至 SDK。操作方式有以下兩種:
- 將金鑰放入
GOOGLE_API_KEY
環境變數中 (SDK 會自動從該處取得金鑰)。 - 將金鑰傳送至
genai.configure(api_key=...)
try:
# Used to securely store your API key
from google.colab import userdata
# Or use `os.getenv('API_KEY')` to fetch an environment variable.
GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')
except ImportError:
import os
GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
genai.configure(api_key=GOOGLE_API_KEY)
函式基本概念
您可以在建立 genai.GenerativeModel
時,將函式清單傳遞至 tools
引數。
def multiply(a:float, b:float):
"""returns a * b."""
return a*b
model = genai.GenerativeModel(model_name='gemini-1.0-pro',
tools=[multiply])
model
genai.GenerativeModel( model_name='models/gemini-1.0-pro', generation_config={}, safety_settings={}, tools=<google.generativeai.types.content_types.FunctionLibrary object at 0x10e73fe90>, )
建議你透過即時通訊介面使用函式呼叫。主要原因是 FunctionCalls
能完美融入即時通訊的多輪結構。
chat = model.start_chat(enable_automatic_function_calling=True)
啟用自動函式呼叫功能後,如果模型要求,chat.send_message
會自動呼叫您的函式。
似乎只會傳回含有正確答案的文字回應:
response = chat.send_message('I have 57 cats, each owns 44 mittens, how many mittens is that in total?')
response.text
'The total number of mittens is 2508.'
57*44
2508
您可以在 ChatSession.history
中查看事件順序:
- 你已傳送問題。
- 模型利用
glm.FunctionCall
回覆。 genai.ChatSession
會在本機執行函式,並將模型傳回glm.FunctionResponse
。- 模型在答案中使用了函式輸出內容。
for content in chat.history:
part = content.parts[0]
print(content.role, "->", type(part).to_dict(part))
print('-'*80)
user -> {'text': 'I have 57 cats, each owns 44 mittens, how many mittens is that in total?'} -------------------------------------------------------------------------------- model -> {'function_call': {'name': 'multiply', 'args': {'a': 57.0, 'b': 44.0} } } -------------------------------------------------------------------------------- user -> {'function_response': {'name': 'multiply', 'response': {'result': 2508.0} } } -------------------------------------------------------------------------------- model -> {'text': 'The total number of mittens is 2508.'} --------------------------------------------------------------------------------
一般來說,狀態圖表如下:
模型可以在傳回文字回應前,透過多個函式呼叫回應,而函式呼叫位於文字回應之前。
雖然系統會自動處理上述所有操作,但如果您需要進一步掌控,你可以:
- 保留預設的
enable_automatic_function_calling=False
,並自行處理glm.FunctionCall
回應。 - 或者,您也可以透過
GenerativeModel.generate_content
管理即時通訊記錄。
[選用] 低層級存取權
在所有情況下,從 Python 函式自動擷取結構定義的功能並無法運作。舉例來說,在描述巢狀字典物件的欄位時,系統不會處理這些欄位,但 API 支援這項功能。此 API 可描述任何下降類型:
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType]
google.ai.generativelanguage
用戶端程式庫提供低層級類型的存取權,可讓您完全掌控。
import google.ai.generativelanguage as glm
首先仔細查看模型的 _tools
屬性,瞭解模型如何描述您傳送至模型的函式:
def multiply(a:float, b:float):
"""returns a * b."""
return a*b
model = genai.GenerativeModel(model_name='gemini-1.0-pro',
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" } }]
這會傳回要傳送至 API 的 glm.Tool
物件清單。如果對列印格式不熟悉,那是因為這些是 Google protobuf 類別。每個 glm.Tool
(在本例中為 1) 都包含 glm.FunctionDeclarations
清單,用於描述函式及其引數。
以下為使用 glm
類別編寫的相同乘數函式的宣告。
請注意,這些類別只會描述 API 的功能,並不包括其實作。因此,使用此方法並不能與自動函式呼叫搭配運作,但函式不一定需要實作。
calculator = glm.Tool(
function_declarations=[
glm.FunctionDeclaration(
name='multiply',
description="Returns the product of two numbers.",
parameters=glm.Schema(
type=glm.Type.OBJECT,
properties={
'a':glm.Schema(type=glm.Type.NUMBER),
'b':glm.Schema(type=glm.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']} }]}
glm.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" } }
無論採用何種方式,您都可以將 glm.Tool
的表示法或工具清單傳遞至
model = genai.GenerativeModel('gemini-pro', tools=calculator)
chat = model.start_chat()
response = chat.send_message(
f"What's 234551 X 325552 ?",
)
就像在模型傳回叫用計算機 multiply
函式的 glm.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(
glm.Content(
parts=[glm.Part(
function_response = glm.FunctionResponse(
name='multiply',
response={'result': result}))]))
摘要
SDK 支援基本函式呼叫。請記得,使用即時通訊模式能更輕鬆地管理,因為這是自然的往返架構。您必須負責實際呼叫函式,並將結果傳回模型,以便產生文字回應。