您可以在 Python 工具和回呼中使用 Python 程式碼。本參考資料說明 Python 執行階段、匯入選項和類別、全域變數,以及可在程式碼中使用的函式。
Python 環境
Python 工具和回呼會在安全沙箱環境中執行。這個環境執行的是 Python 3.12。
匯入
您只能匯入下列模組:
類別
AsyncTools
用於非同步呼叫工具的別名類別。詳情請參閱async_tools全域變數。
Blob
內嵌位元組資料。
屬性:
| 屬性 | 說明 |
|---|---|
display_name: Optional[str] |
Blob 的顯示名稱。用於提供標籤或檔案名稱,以區分 Blob。 |
data: Optional[bytes] |
Base64 編碼位元組。 |
raw_data: Optional[bytes] |
原始解碼位元組。 |
mime_type: Optional[str] |
來源資料的 IANA 標準 MIME 類型。 |
方法:
| 方法 | 說明 |
|---|---|
transcript() -> Optional[str] |
如果有的話,會傳回 Blob 資料的快取轉錄稿。這項功能僅適用於音訊 Blob。 |
from_json(data: str) -> Blob |
從 JSON 字串建立 Blob 執行個體的類別方法,並將 mime_type 設為「application/json」。 |
範例:
# Create a blob from raw bytes
blob = Blob(mime_type='text/plain')
blob.raw_data = b'hello world'
# Create a blob from a JSON string
Blob.from_json(data='{"key": "value"}')
CallbackContext
回呼期間可用的工作階段資訊。
屬性:
| 屬性 | 說明 |
|---|---|
user_content: Optional[Content] |
使用者最近一次的輸入內容。 |
invocation_id: str |
特定回呼叫用的專屬 ID,有助於偵錯。 |
agent_name: str |
與目前回呼相關聯的代理程式顯示名稱。 |
session_id: str |
目前進行中工作階段的專屬工作階段 ID。 |
variables: dict[str, Any] |
字典,包含在設計階段定義或在執行階段插入的變數鍵/值組合。這是回呼執行時變數的目前狀態。 |
state: dict[str, Any] |
與 variables 屬性相同。 |
events: list[Event] |
工作階段事件。 |
方法:
| 方法 | 說明 |
|---|---|
get_variable(key: str, default: Any) -> Any |
從狀態取得變數。如果變數不存在,則傳回預設值。 |
set_variable(key: str, value: Any) -> None |
在狀態中設定變數。 |
remove_variable(key: str) -> None |
從狀態中移除變數。 |
get_last_user_input() -> list[Part] |
取得最後一組使用者事件中的所有部分。 |
get_last_agent_output() -> list[Part] |
取得代理程式事件最後一組的所有部分清單。 |
parts() -> list[Part] |
工作階段記錄中記錄的所有部分。 |
Content
使用者或服務專員的訊息內容。
屬性:
| 屬性 | 說明 |
|---|---|
parts: Optional[list[Part]] |
構成單一郵件的部分清單。每個部分可能都有不同的 IANA MIME 類型。 |
role: Optional[str] |
內容作者的角色。'user' 或 'agent'。 |
方法:
| 方法 | 說明 |
|---|---|
is_user() -> bool |
如果角色是 'user',則傳回 True。 |
is_model() -> bool |
如果角色是 'model',則傳回 True。 |
Event
代表工作階段中的事件。
屬性:
| 屬性 | 說明 |
|---|---|
id: str |
事件 ID。 |
invocation_id: str |
事件叫用 ID。 |
author: str |
「user」或代理程式名稱,表示誰出席了工作階段的活動。 |
timestamp: int |
事件時間戳記。 |
content: Content |
與此事件相關聯的內容。 |
actions: EventActions |
代理程式採取的動作。 |
long_running_tool_ids: set[str] |
長時間執行的函式呼叫 ID 集。 |
partial: bool |
True,表示 LLM 串流回應中的區塊不完整。 |
turn_complete: bool |
True,表示目前回合已完成。 |
error_code: str |
錯誤代碼。 |
error_message: str |
錯誤訊息。 |
interrupted: bool |
True (如果回合遭到中斷)。 |
branch: str |
事件的分支。 格式類似 agent_1.agent_2.agent_3,其中 agent_1 是 agent_2 的父項,而 agent_2 是 agent_3 的父項。如果多個子代理程式不應查看同儕代理程式的對話記錄,則會使用分支。 |
grounding_metadata: Any |
事件的基礎中繼資料。 |
方法:
| 方法 | 說明 |
|---|---|
is_user() -> bool |
True 如果活動的作者是「使用者」。 |
is_agent(agent_name: Optional[str] = None) -> bool |
True,如果活動的作者是代理人,如果提供 agent_name,系統會檢查作者是否與該特定代理程式相符。 |
has_error() -> bool |
True 如果事件有相關聯的錯誤代碼。 |
parts() -> list[Part] |
便利方法,可從事件的 content 取得 Part 物件清單。如果沒有內容或部分,則傳回空白清單。 |
EventActions
事件發生的動作。
屬性:
| 屬性 | 說明 |
|---|---|
skip_summarization: bool |
如果為 True,系統不會呼叫模型來摘要函式回應。僅適用於 function_response 事件。 |
state_delta: dict[str,Any] |
這個事件導致的變數變更。 |
artifact_delta: dict[str,Any] |
這項事件對構件所做的變更。索引鍵為檔案名稱,值為版本。 |
transfer_to_agent: str |
如果設定此屬性,系統會將事件轉移給指定的代理程式。 |
escalate: bool |
專員正在將案件提報給更高層級的專員。 |
requested_auth_configs: dict[str,dict[str,Any]] |
工具回覆要求驗證設定。 這個欄位只能由工具要求驗證憑證的工具回覆事件設定。 鍵:函式呼叫 ID。因為一個函式回應事件可能包含多個函式回應,對應多個函式呼叫。每次呼叫函式時,可能會要求不同的驗證設定。這個 ID 用於識別函式呼叫。 值:要求的驗證設定。 |
end_invocation: bool |
代理程式迴圈中斷。 |
ExternalResponse
表示來自 Python 環境外部的回應,例如工具呼叫或 HTTP 要求。
屬性:
| 屬性 | 說明 |
|---|---|
text: str |
以字串形式傳回的回應內文。 |
status_code: int |
HTTP 狀態碼。 |
reason: str |
擲回錯誤的原因。如果沒有錯誤,則為空白。 |
ok: bool |
如果 status_code 小於 400,則為 True,否則為 False。 |
方法:
| 方法 | 說明 |
|---|---|
json() -> Any |
剖析文字屬性 JSON 並傳回結果。如果剖析失敗,系統會擲回錯誤。 |
raise_for_status() |
如果回應不是 ok (ok == False),則會引發 StatusError。 |
FunctionCall
代表函式呼叫。
屬性:
| 屬性 | 說明 |
|---|---|
id: Optional[str] |
函式呼叫的專屬 ID。 |
args: Optional[dict[str,Any]] |
JSON 物件格式的函式參數和值。 |
name: Optional[str] |
函式名稱。 |
FunctionDeclaration
模型傳回的預測 FunctionCall,其中包含代表 FunctionDeclaration name 屬性的字串,以及參數和參數值。
屬性:
| 屬性 | 說明 |
|---|---|
name: Optional[str] |
函式名稱。 |
FunctionResponse
FunctionCall 的結果,其中包含代表 FunctionDeclaration name 屬性的字串,以及包含函式呼叫任何輸出的結構化 JSON 物件。做為模型的脈絡資訊。
屬性:
| 屬性 | 說明 |
|---|---|
id: Optional[str] |
對應函式呼叫的 ID。 |
name: Optional[str] |
函式名稱。 |
response: Optional[dict[str,Any]] |
JSON 物件格式的函式回應。使用「output」鍵指定函式輸出內容,並使用「error」鍵指定錯誤詳細資料 (如有)。如果未指定「output」和「error」鍵,系統會將整個「response」視為函式輸出內容。 |
GenerateContentConfig
選用模型設定參數。
屬性:
| 屬性 | 說明 |
|---|---|
system_instruction: Optional[Content] |
指示模型,引導模型提升成效。例如:「請盡可能簡潔地回答」或「請勿在回覆中使用技術用語」。 |
tools: Optional[list[ToolDeclaration]] |
模型可執行的可用工具清單。 |
excluded_tools: Optional[list[str]] |
模型會忽略的工具名稱清單。這會覆寫 tools。 |
方法:
| 方法 | 說明 |
|---|---|
hide_tool(tool_name: str) |
將 tool_name 新增至 excluded_tools 清單。 |
HttpMethod
代表 HTTP 方法的字串列舉。 可能的值為:
GETPOSTPUTDELETEPATCHHEADOPTIONS
LlmRequest
用於表示 LLM 要求的資料模型。
屬性:
| 屬性 | 說明 |
|---|---|
model: Optional[str] |
模型名稱 |
contents: List[Content] |
傳送至模型的內容清單。 |
config: Optional[GeneralContentConfig] |
模型設定參數。 |
LlmResponse
用於表示 LLM 回覆的資料模型。
屬性:
| 屬性 | 說明 |
|---|---|
content: Content |
模型回覆的第一個 Content。 |
partial: Optional[bool] |
指出內容是否代表不完整的模型回覆。發出部分回應後,代理程式會繼續處理。 |
方法:
| 方法 | 說明 |
|---|---|
from_parts(parts: list[Part]) -> LlmResponse |
類別方法,會從模型傳回 LlmResponse。 |
範例:
response = LlmResponse.from_parts(
parts=[
Part.from_text(text="hello world")
]
)
Part
包含媒體內容的資料型別。
應在 Part 中設定一個欄位,代表傳達的特定內容類型。在同一個 Part 執行個體中使用多個欄位視為無效。
屬性:
| 屬性 | 說明 |
|---|---|
function_call: Optional[FunctionCall] |
模型傳回的預測 FunctionCall,其中包含代表函式名稱的字串,以及包含參數及其值的結構化 JSON 物件。 |
function_response: Optional[FunctionResponse] |
FunctionCall 的結果輸出內容,包含代表函式名稱的字串,以及包含函式呼叫任何輸出內容的結構化 JSON 物件。做為模型的脈絡資訊。 |
text: Optional[str] |
訊息文字。 |
inline_data: Optional[Blob] |
內嵌位元組資料。 |
方法:
| 方法 | 說明 |
|---|---|
text_or_transcript() -> Optional[str] |
如果可用,則傳回文字;否則傳回內嵌資料的轉錄稿。 |
has_function_call(name) -> bool |
如果該部分包含特定函式呼叫,則傳回 True。 |
has_function_response(name) -> bool |
如果該部分包含特定函式回應,則傳回 True。 |
from_text(text: str) -> Part |
建立文字 Part 的類別方法。 |
from_function_call(name: str, args: dict[str, Any]) -> Part |
建立函式呼叫 Part 的類別方法。 |
from_function_response(name: str, response: dict[str, Any]) -> Part |
建立函式回應 Part 的類別方法。 |
from_inline_data(data: bytes, mime_type: str) -> Part |
建立內嵌資料 Part 的類別方法。 |
from_json(data: str) -> Part |
建立 JSON 內嵌資料 Part 的類別方法。 |
from_agent_transfer(agent: str) -> Part |
類別方法,用於建立 Part 以轉移給其他服務專員。 |
from_end_session(*, reason: str, escalated: bool = False) -> Part |
建立 Part 的類別方法,用於終止工作階段。 |
from_customized_response(*, content: str, disable_barge_in: bool = False, enable_dtmf: bool = False, dtmf_finish_digit = str: '#', dtmf_endpointing_timeout: int = 3) -> Part |
類別方法,可為具有自訂行為的回應建立 Part (例如停用 barege-in、啟用 DTMF 輸入等)。 |
範例:
text_part = ces_public.Part.from_text(text="Hello from the user!")
tool_part = ces_public.Part.from_function_call(
name="get_weather",
args={"location": "Mountain View"}
)
Requests
用於發出 HTTP 要求的別名類別。詳情請參閱 ces_requests 全域變數。
方法:
get(url, params=None, **kwargs)post(url, data=None, json=None, **kwargs)put(url, data=None, json=None, **kwargs)delete(url, **kwargs)patch(url, data=None, json=None, **kwargs)head(url, **kwargs)options(url, **kwargs)
StatusError
用於以狀態碼引發的錯誤。
屬性:
| 屬性 | 說明 |
|---|---|
status_code: int |
與這項錯誤相關聯的 HTTP 狀態碼。 |
reason: str |
擲回錯誤的原因。 |
Tool
代表具有名稱和說明的工具。
屬性:
| 屬性 | 說明 |
|---|---|
name: str |
工具名稱。 |
description: str |
說明工具的用途。 |
ToolContext
衍生自 CallbackContext。
執行工具時可用的工作階段資訊。
屬性:
| 屬性 | 說明 |
|---|---|
function_call_id: str |
目前執行的工具呼叫函式呼叫 ID。 |
Tools
用於同步呼叫工具的別名類別。 詳情請參閱工具全域變數。
ToolDeclaration
可向模型顯示的工具結構定義。
屬性:
| 屬性 | 說明 |
|---|---|
function_declarations: Optional[list[FunctionDeclaration]] |
工具支援的函式宣告清單。 |
函式
get_variable
這個函式會使用提供的鍵,從工作階段狀態擷取值。
這是 context.state.get(key) 或 context.variables.get(key) 的捷徑。
程式碼範例:
def get_a_value() -> int:
# Retrieve the value of 'my_key' from the state
my_value = get_variable('my_key')
return my_value + 5
remove_variable
這個函式會從工作階段狀態中移除鍵/值組合。
這是 del context.state[key] 的捷徑。
程式碼範例:
def remove_a_value() -> None:
# Delete 'my_key' from the state
remove_variable('my_key')
set_variable
這個函式會在工作階段狀態中,為指定鍵設定值。
如果該鍵已存在,系統會更新其值。這是 context.state[key] = value 的捷徑。
程式碼範例:
def set_a_value() -> None:
# Set the value of 'my_key' to 10
set_variable('my_key', 10)
全域變數
async_tools
AsyncTools 的例項,可讓您對工具進行非同步呼叫。
範例:
response_future = async_tools.<TOOL_DISPLAY_NAME>(<ARGS_AS_DICT>)
# ... misc work
response = response_future() # poll for response
# Check if the tool call was successful
try:
response.raise_for_status()
except StatusError:
print(f"Request failed with status {response.status_code}")
# Convert the response to json
data = response.json()
ces_requests
Requests 的執行個體。Requests 可讓您使用類似於熱門 Python 要求模組的語法發出 HTTP 呼叫。
範例:
# Make a GET request
response = ces_requests.get('https://api.example.com/data')
# Check if the request was successful
try:
response.raise_for_status()
except StatusError:
print(f"Request failed with status {response.status_code}")
# Convert the response to json
data = response.json()
tools
Tools 的執行個體,可讓您對工具進行同步呼叫。
範例:
response = tools.<TOOL_DISPLAY_NAME>(<ARGS_AS_DICT>)
# Check if the tool call was successful
try:
response.raise_for_status()
except StatusError:
print(f"Request failed with status {response.status_code}")
# Convert the response to json
data = response.json()
context
您可以在程式碼中存取 ADK 內容,用於讀取及寫入多種 ADK 內容資料。您可以在程式碼中使用名為 context 的全域變數。
context.state 和 context.variables 物件可以互換。
為與 ADK 程式碼相容,系統支援 state 物件,但新程式碼應使用 variables 物件。