Python 執行階段參考資料

您可以在 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 如果事件作者是「user」,則為 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 == 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 方法的字串列舉。可能的值為:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • HEAD
  • OPTIONS

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,用於自訂行為的回覆 (例如停用插話、啟用 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)

全域變數

_session

您可以存取對話的目前管道和模態,方法與模組化元件類似。使用名為 _session 的預先定義變數,即可存取這些值。

Python 工具範例 (使用全域 context 變數):

def check_order_status(order_id: str) -> str:
  # Resolve modality and channel from the session state
  session_vars = context.variables.get('_session', {})
  modality = session_vars.get('modality', 'TEXT')
  channel = session_vars.get('channel', 'API')

  status = get_raw_order_status(order_id)  # Internal API lookup

  if modality == 'VOICE':
    # Keep response concise and remove markdown/links for natural TTS playback
    return "Your order has shipped and is estimated to arrive tomorrow."
  else:
    # Rich text with markdown links for Chat/Web interfaces
    return f"Your order shipped [Track it](https://shipper.com/{order_id})."

回呼範例 (使用 CallbackContext):

def before_agent_callback(callback_context: CallbackContext) -> None:
  session_vars = callback_context.get_variable('_session', {})
  modality = session_vars.get('modality', 'TEXT')
  channel = session_vars.get('channel', 'API')
  callback_context.set_variable('active_modality', modality)

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 物件可以互換。系統支援 state 物件,以便與 ADK 程式碼相容,但新程式碼應使用 variables 物件。