本指南分享經過驗證的最佳做法和設計模式,協助您最佳化及擴展代理程式應用程式。這類內容有助於降低設計時間成本、降低執行階段成本,以及提升代理程式可靠性。
一般
本節提供一般最佳做法,協助您開始開發代理程式和撰寫指令。
從簡單的福利開始
首次建構代理程式應用程式時,應從簡單的用途開始。簡單的使用案例運作正常後,請繼續建構更複雜的使用案例。
指令應具體明確
代理指令應具體明確。 說明應妥善整理,並依主題分組。 避免隨意分散特定主題的指示。 指令也應簡單明瞭,方便使用者遵循。
使用結構化指令
撰寫完指令後,請使用「重組指令」功能設定指令格式。採用這種格式的代理程式會更可靠。
使用多種模態和管道的模組化元件
如果代理程式應以不同方式回應不同模式 (文字或語音) 或管道 (API、電話或網路),請使用模組化元件,並在 Python 工具和回呼中檢查管道和模式。
工具
本節提供定義及使用工具的最佳做法,包括包裝外部 API 和串連工具呼叫。
使用 Python 工具納入 API
外部 API 結構定義可能會定義許多與代理無關的輸入和輸出參數。如果您在這種情況下使用 OpenAPI 工具,可能會向模型提供不必要的背景資訊,進而降低可靠性。舉例來說,假設 OpenAPI 規格工具會將 3 個參數做為輸入內容,並傳回含有 100 個鍵/值組合的大型 JSON 物件。代理程式會預測這項工具的 3 個輸入引數,並在傳回時查看完整的 JSON 酬載,其中包含所有 100 個鍵/值組合。如果只有 3 對與對話相關,其他 97 對就是無關的資料,會為對話記錄新增權杖。雖然這看似無害,但可能會造成代理程式不必要的混淆、增加推理時間和延遲。
最佳做法是使用 Python 工具包裝 API 呼叫。包裝功能可讓您隱藏代理程式和脈絡記錄中不必要的資料。您可以在特定時間點只傳回與服務專員相關的資料,藉此精確控管服務專員看到的內容。這樣一來,您就能完全掌控工具定義的輸入和輸出參數,並與模型共用。這項做法是使用工具進行脈絡工程的一種形式。
程式碼範例:
def python_wrapper(arg_a: str, arg_b: str) -> dict:
"""
Call the scheduling service to schedule an appointment,
returning only relevant fields.
"""
res = complicated_external_api_call(...)
# Process result to extract only relevant key-value pairs.
processed_res = {
"appointment_time": res.json()["appointment_time"],
"appointment_location": res.json()["appointment_location"],
"confirmation_id": res.json()["confirmation_id"],
}
return processed_res
使用工具和回呼來確保行為確定性
在某些對話情境中,您可能需要代理程式應用程式提供更具決定性的行為。在這種情況下,您應使用工具或回呼函式。
回呼通常是完整確定性控制的最佳選項。 回呼發生在代理程式的範圍外,因此代理程式不會參與回呼的執行作業。
工具的內部運作完全是決定性的,但代理程式協調的工具呼叫並非決定性。 代理會決定呼叫工具、準備工具輸入引數,並解讀工具結果。代理可能會產生這項自動調度管理工具的幻覺。
鏈結工具呼叫
與使用工具包裝 API 呼叫類似,如果對話回合中需要執行多個工具,請指示代理呼叫一個工具,並實作該工具來呼叫其他工具。或者,您也可以指示代理程式呼叫第一個工具,並定義 after_tool_callback 回呼來呼叫其餘工具。
串連工具呼叫的模式不佳
指示代理在對話輪流期間呼叫多個工具,以達成共同目標,這被視為不良模式。
模型必須預測每個工具呼叫和該工具呼叫中的每個參數。 然後,模型必須確保預測的工具呼叫順序正確。這表示您非常依賴模型 (本質上不具確定性) 執行確定性工作。
舉例來說,請看以下工具序列:
tool_1(arg_a, arg_b)-> outputctool_2(arg_c)-> outputdtool_3(arg_d)-> outpute
如果您為這三項工具呼叫定義指令,最終會得到下列事件的執行階段序列:
- 使用者輸入內容
- 模型 -> 代理程式預測
tool_1(arg_a, arg_b) tool_1_response.json()已退回- 代理會解讀
tool_1_response.json()並擷取arg_c - 模型 -> 代理程式預測
tool_2(arg_c) tool_2_response.json()已退回- 代理會解讀
tool_2_response.json()並擷取arg_d - 模型 -> 代理程式預測
tool_3(arg_d) tool_3_response.json()已退回- 模型 -> 代理提供最終回覆
有 4 次模型呼叫、3 次工具預測和 4 個輸入引數。
鏈結工具呼叫的良好模式
需要呼叫多個工具時,建議指示代理呼叫單一工具,並實作該工具來呼叫其他工具。
下列工具會呼叫另外三項工具:
def python_wrapper(arg_a: str, arg_b: str) -> dict:
"""Makes some sequential API calls."""
res1 = tools.tool_1({"arg_a": arg_a, "arg_b": arg_b})
res2 = tools.tool_2(res1.json())
res3 = tools.tool_3(res2.json())
return res3.json()
請考慮單一工具呼叫的事件序列:
- 使用者輸入內容
- 模型 -> 代理程式預測
python_wrapper(arg_a, arg_b) python_wrapper_response.json()已退回- 模型 -> 代理提供最終回覆
這個方法可減少權杖,並降低產生幻覺的機率。
清楚明確的工具定義
工具定義應採用下列最佳做法:
- 不同工具的名稱不應相似。 工具名稱應明顯不同。
- 請從代理程式節點中移除未使用的工具。
參數名稱請使用蛇形命名法、描述性名稱,並避免使用不常見的縮寫。
良好示例:
first_name、phone_number、url。錯誤示例:
i、arg1、fn、pnum、rqst。參數應使用扁平結構,而非巢狀結構。 結構的巢狀層級越多,您就越需要依賴模型預測鍵/值組合及其正確型別。
開發工作流程
本節說明開發代理程式時,團隊協作、版本控管和測試的最佳做法。
定義代理程式協作的開發程序
與團隊合作開發代理程式應用程式時,您應定義開發程序。以下是可能的協作做法範例:
- 使用第三方版本管控: 使用匯入和還原功能,將變更與第三方版本管控系統同步處理。同意同步、審查及合併的程序。 明確定義變更的負責人和接受變更的步驟 (例如評估結果)。
- 使用內建版本管控: 設定程序,使用內建版本管控。 同意如何使用快照進行版本控管。 舉例來說,您可以在達到里程碑 (通過一組評估) 時,或是在完成新功能開發前,要求建立快照。同意同步、檢查及合併變更的程序。
使用版本儲存代理狀態
版本: 可讓您記錄在代理程式應用程式中完成的工作或變更。變更指令、工具、變數和其他項目後,您可以先儲存該狀態,再進行其他變更。版本是代理程式在特定時間點的快照,如果您對某些變更感到滿意,且代理程式應用程式運作正常 (尤其是透過評估驗證變更後),就應建立版本。建立版本後,隨時都能復原至該版本。
建議您經常建立版本,或許每隔 10 到 15 次重大變更就建立一個版本。
為版本命名時,使用語意也有幫助,您應與開發團隊決定要使用的命名慣例。例如 pre-prod-instruction-changes 或 prod-ready-for-testing 等描述性名稱。您也可以使用語意版本管理等標準,使用 v1.0.0、v1.0.1 等名稱。版本也有說明欄位,可讓您新增更多詳細資料,類似於提交郵件內文。版本名稱和說明應簡短、有意義且容易理解,以防需要還原至該版本。
執行端對端測試
在開發代理程式應用程式時,應進行端對端測試,確認與外部系統的整合。
評估結果
本節提供評估的最佳做法,確保代理程式的可靠性。
使用評估結果
評估 有助於確保代理的可靠性。 您可以使用這些規則,為代理和代理呼叫的 API 設定預期行為。
工作階段處理
本節提供管理工作階段生命週期的模式。
透過靜態回覆提供確定性問候語,並縮短延遲時間
您可以設定在工作階段開始時,讓代理程式說出預先決定的回應。這個方法可節省模型呼叫次數和權杖,並縮短延遲時間。
使用 before_model_callback 即可攔截輸入內容,然後以靜態問候訊息回覆。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in callback_context.get_last_user_input():
# Or other events or texts
if part.text == "<event>session start</event>":
return LlmResponse.from_parts(parts=[
Part.from_text(text="Hello how can I help you today?")
])
return None
在模型運作時,使用前置訊息快速回覆
工作階段開始時,請避免強制使用者等待模型生成。 您可以為回覆加上前置字串,讓代理快速提供友善的品牌問候語 (例如「你好,我是你的個人助理 Gemini」),同時模型會在背景處理使用者的主要要求。
這項功能取決於 partial = True 設定。
通常,非 FuctionCall 回應會視為終端回應。
使用 partial = True 會強制代理在回應後繼續處理。
在下列範例中,代理程式應用程式會快速傳送歡迎訊息,然後繼續處理主要要求。這可避免出現尷尬的輸入暫停,讓服務專員感覺回應迅速。
def before_model_callback(callback_context: CallbackContext, llm_request: LlmRequest) -> Optional[LlmResponse]:
for part in callback_context.get_last_user_input():
if part.text == "<event>session start</event>":
response = LlmResponse.from_parts([Part.from_text("Hello, I'm Gemini, your personal AI assistant.")])
response.partial = True
return response
return None
驗證並強制執行必要內容
有時候,您可能會想指示代理程式提供特定強制性內容 (例如法律免責事項),但也要確認代理程式確實納入該內容。這個模式可讓您在模型正常運作時,依賴模型的自然生成功能,但如果模型無法正常運作,則會強制執行內容的確定性。
你可以使用after_model_callback檢查模型的輸出內容。如果存在必要內容,回呼會傳回 None (允許模型的回覆通過)。如果缺少這項資訊,回呼會建構包含必要內容的新回應。
範例變數:
| 變數名稱 | 預設值 |
|---|---|
| first_turn | 是 |
DISCLAIMER = "THIS CONVERSATION MAY BE RECORDED FOR LEGAL PURPOSES."
def after_model_callback(
callback_context: CallbackContext,
llm_response: LlmResponse
) -> Optional[LlmResponse]:
if callback_context.variables.get("first_turn"):
callback_context.variables["first_turn"] = False
# Check if the agent's response already contains the disclaimer.
# The agent might have produced it based on instructions.
for part in callback_context.get_last_agent_output():
if part.text and DISCLAIMER in part.text:
return None
# If the agent failed to produce the disclaimer, force it.
return LlmResponse.from_parts(parts=[
Part.from_text(DISCLAIMER),
*llm_response.content.parts
])
return None
在工作階段結束時呼叫自訂工具
您可以設定在工作階段結束時,讓服務專員呼叫特定工具。這項功能可用於通話後結尾事件,例如在結束時同步處理資料、將資料傳送至外部 API、完成後端工作,或記錄通話中繼資料。
舉例來說,假設您有現有的 post_call_logging 等工具,想在工作階段結束前呼叫該工具:
def post_call_logging(session_id: str) -> dict:
"""Logs the session ID to external API."""
API_URL = "https://api.example.com"
response = ces_requests.post(
url=API_URL,
data={"session_id": session_id}
)
return response.json()
您可以使用 after_model_callback 執行下列順序:
- 在代理程式的回覆中檢查
end_session工具呼叫。 - 建立
post_call_logging工具零件。 - 在
end_session工具呼叫之前,插入post_call_logging工具呼叫。
確保代理程式會在終止工作階段前執行記錄工具。
def after_model_callback(
callback_context: CallbackContext,
llm_response: LlmResponse
) -> Optional[LlmResponse]:
for index, part in enumerate(llm_response.content.parts):
if part.has_function_call('end_session'):
# Add an additional "post_call_logging" function call before "end_session",
# so the agent will execute the tool before ending the session.
tool_call = Part.from_function_call(
name="post_call_logging",
args={"sessionId": callback_context.session_id}
)
return LlmResponse.from_parts(
parts=llm_response.content.parts[:index] + [tool_call] + llm_response.content.parts[index:]
)
return None
使用部分回應即時更新使用者介面
當代理執行動作 (例如更新訂單狀態) 時,模型處理最終回覆可能需要一些時間,因此可能會出現延遲。使用部分回應可在工具執行完畢時,將通知傳送至用戶端使用者介面,將視覺更新與模型的文字生成作業分離。
使用者介面可以即時重新整理狀態列、追蹤器或收據。
這項功能取決於 partial = True 設定。
通常,非 FuctionCall 回應會視為終端回應。
使用 partial = True 會強制代理在回應後繼續處理。
系統不會將 JSON 酬載傳送至模型。 因此,代理程式在生成回覆時,不會知道酬載的存在。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
if llm_request.contents[-1].parts[-1].has_function_response('update_order'):
order_state = llm_request.contents[-1].parts[-1].function_response.response['result']['order_state']
# Return a custom JSON payload before calling the model to generate the final agent response.
response = LlmResponse.from_parts([Part.from_json(data=json.dumps(order_state))])
response.partial = True
return response
return None
用戶端整合
本節提供與用戶端應用程式整合的模式。
使用自訂酬載驅動使用者介面
使用者希望介面是動態且可互動的。 您可以運用自訂酬載,在用戶端進行算繪,縮短代理程式與完善應用程式之間的差距。您可以設定代理程式,偵測回覆中的特定模式 (例如選項清單),並將這些模式轉換為高轉換率的互動式使用者介面元素 (例如可點選的方塊或按鈕),而非提供純文字選項。
使用 after_model_callback 掃描代理回應,找出特定觸發條件。舉例來說,如果模型輸出內容為:「Available options are: Refund, Track Order, Speak to Agent」,下列回呼會攔截並擷取這些選項做為 JSON 酬載,可用於算繪使用者介面。
import json
def after_model_callback(
callback_context: CallbackContext,
llm_response: LlmResponse
) -> Optional[LlmResponse]:
prefix = 'Available options are:'
payload = {}
for part in llm_response.content.parts:
if part.text is not None and part.text.startswith(prefix):
# Return available options as chip list
payload['chips'] = part.text[len(prefix):].split(',')
break
new_parts = []
# Keep the original agent response part, as the custom payload won't be sent
# back to the model in the next turn.
new_parts.extend(llm_response.content.parts)
new_parts.append(Part.from_json(data=json.dumps(payload)))
return LlmResponse.from_parts(parts=new_parts)
顯示 Markdown 和 HTML
如果對話式介面支援以 Markdown 和 HTML 格式顯示專員回覆,您可以使用模擬器測試這些回覆,因為模擬器也支援 Markdown 和 HTML。
操作說明範例:
<role>
You are a "Markdown Display Assistant," an AI agent designed to demonstrate
various rich content formatting options like images, videos, and deep links
using HTML-style markdown. Your purpose is to generate and display this
content directly to the user based on their requests.
</role>
<persona>
Your primary goal is to showcase the rich content rendering capabilities of
the platform by generating HTML markdown for elements like images, videos,
and hyperlinks. You are a helpful and direct assistant. When asked to show
something, you generate the markdown for it and present it.
You should not engage in conversations outside the scope of generating and
displaying markdown. If the user asks for something unrelated, politely
state that you can only help with displaying rich content. Adhere strictly
to the defined constraints and task flow.
</persona>
<constraints>
1. **Scope Limitation:** Only handle requests related to displaying
markdown content (images, videos, links, etc.). Do not answer general
knowledge questions or perform other tasks.
2. **Tool Interaction Protocol:** You must use the \`display_markdown\`
tool to generate the formatted content string.
3. **Direct Output:** Your final response to the user must be the raw
markdown string returned by the \`display_markdown\` tool. Do not add
any conversational text around it unless the tool returns an error.
For example, if the tool returns \`"<img src='...'>"\`, your response
should be exactly \`"<img src='...'>"\`.
4. **Clarity and Defaults:** If a user's request is vague (e.g., "show me
an image"), use the tool's default values to generate a response. There
is no need to ask for clarification.
5. **Error Handling:** If the tool call fails or returns an error, inform
the user about the issue in a conversational manner.
</constraints>
<taskflow>
These define the conversational subtasks that you can take. Each subtask
has a sequence of steps that should be taken in order.
<subtask name="Generate and Display Markdown">
<step name="Parse Request and Call Tool">
<trigger>
User initiates a request to see any form of rich content (image,
video, link, etc.).
</trigger>
<action>
1. Identify the types of content the user wants to see (e.g.,
image, video, deep link).
2. Call the \`display_markdown\` tool. Set the corresponding
boolean arguments to \`True\` based on the user's request.
For example, if the user asks for a video and a link, call
\`display_markdown(show_video=True, show_deep_link=True)\`.
3. If the user makes a general request like "show me something
cool", you can enable all flags.
</action>
</step>
<step name="Output Tool Response">
<trigger>
The \`display_markdown\` tool returns a successful response
containing a \`markdown_string\`.
</trigger>
<action>
1. Extract the value of the \`markdown_string\` key from the
tool's output.
2. Use this value as your direct and final response to the
user, without any additional text or formatting.
</action>
</step>
</subtask>
</taskflow>
Python 工具範例:
from typing import Any
def display_markdown(show_image: bool, show_video: bool, show_deep_link: bool) -> dict[str, Any]:
"""
Constructs a markdown string containing HTML for various rich media elements.
This function generates an HTML-formatted string based on the boolean flags provided.
It can include an image, a video, and a hyperlink (deep link). The content for
these elements is pre-defined.
Args:
show_image (bool): If True, an <img> tag will be included in the output.
show_video (bool): If True, a <video> tag will be included in the output.
show_deep_link (bool): If True, an <a> tag will be included in the output.
Returns:
dict[str, Any]: A dictionary with a single key 'markdown_string' containing the
generated HTML markdown. If no flags are set, it returns a
message indicating nothing was requested.
"""
# MOCK: This is a mock implementation. It does not fetch any dynamic content.
# It assembles a markdown string from hardcoded HTML snippets to demonstrate
# the agent's ability to render rich content.
markdown_parts = []
if show_image:
image_html = "This is a sample image:\n<img src='https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png' alt='Google Logo' width='272' height='92' />"
markdown_parts.append(image_html)
if show_video:
video_html = "This is a sample video:\n<video controls width='320' height='240'><source src='https://www.w3schools.com/html/mov_bbb.mp4' type='video/mp4'>Sorry, your browser does not support embedded videos.</video>"
markdown_parts.append(video_html)
if show_deep_link:
link_html = "This is a sample deep link:\n<a href='https://www.google.com'>Click here to go to Google</a>"
markdown_parts.append(link_html)
if not markdown_parts:
return {"markdown_string": "You did not request any content to be displayed. Please specify if you want to see an image, video, or link."}
return {"markdown_string": "\n\n".join(markdown_parts)}
語音和音訊頻道控制選項
本節提供控制語音和音訊管道的模式,包括預錄音訊、保留音樂和插播設定。
注意:
- 音訊檔案支援 Linear16、mulaw 和 alaw 音訊編碼。
- 如果使用屬於其他雲端專案的 Cloud Storage 值區,則必須明確授予 Customer Engagement Suite 服務帳戶
service-<PROJECT-NUMBER>@gcp-sa-ces.iam.gserviceaccount.comstorage.objects.get權限,才能存取目標 Cloud Storage 值區。 - 您可以使用
interruptable輸入引數,設定預錄音訊是否可由使用者中斷。 - 如要停止播放音樂,可以使用
cancellable輸入引數,指出當代理程式生成新回覆時,應停止播放音樂。
播放品牌專屬的預錄音訊
您可以設定在處理使用者要求前,讓服務專員播放預錄音訊檔案。您可以在工作階段開始時,使用這項功能播放品牌核准的問候語或強制揭露的法律聲明。
使用 "transcript": "yyy" 為代理提供音訊播放文字,確保代理具備必要脈絡,可生成後續回應。
使用 "interrupable": false 可確保使用者不會中斷音訊播放。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in callback_context.get_last_user_input():
if part.text == "<event>session start</event>":
return LlmResponse.from_parts(parts=[
Part.from_json(data='{"audioUri": "gs://path/to/audio/file", "transcript": "transcript for the audio file", "interruptable": false}')
])
return None
執行緩慢的工具時播放預錄音樂 (不支援插播)
您可以設定在執行緩慢的「封鎖」工具 (例如帳戶驗證和啟用) 時,讓代理程式播放音樂。工具執行完畢後,音樂就會自動停止播放。 播放音樂時,使用者無法與智慧助理互動。
def after_model_callback(
callback_context: CallbackContext,
llm_response: LlmResponse
) -> Optional[LlmResponse]:
for index, part in enumerate(llm_response.content.parts):
if part.has_function_call("slow_tool"):
play_music = Part.from_json(
data='{"audioUri": "gs://path/to/music/file", "cancellable": true}'
)
return LlmResponse.from_parts(
parts=llm_response.content.parts[:index] +
[play_music] + llm_response.content.parts[index:]
)
return None
執行非同步工具時播放預錄音樂 (允許插播)
您可以設定代理程式,在非同步執行工具時播放音樂,例如在驗證及啟用使用者帳戶時。非同步工具完成後,音樂就會自動停止播放,前提是使用者尚未中斷播放。使用者隨時可以中斷音樂,繼續與代理程式互動。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in llm_request.contents[-1].parts:
if part.has_function_response("async_tool"):
text = Part.from_text(text="I'm submitting your order, it may take a while.")
music = Part.from_json(
data='{"audioUri": "gs://path/to/music/file", "cancellable": true}'
)
return LlmResponse.from_parts(parts=[text, music])
return None
禁止使用者插話,打斷特定回覆
您可以禁止使用者在代理程式朗讀重要資訊 (例如法律免責事項) 時插話,但允許在代理程式回應的其餘部分插話。
這會使用 customize_response 系統工具。
您可以透過兩種方式實作這項行為,視您是否需要確定性結果而定:
- 回呼 (確定性):強制回呼回應,如範例所示。
- 指令 (代理主導):在指令中提示代理使用
customize_response工具。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in callback_context.get_last_user_input():
if part.text == "<event>session start</event>":
return LlmResponse.from_parts(parts=[
Part.from_customized_response(
content=("Hello, I'm Gemini. Please listen to the following legal "
"disclaimer: <LEGAL_DISCLAIMER>"),
disable_barge_in=True
),
Part.from_text("How can I help you today?")
])
return None
自訂無輸入內容的回覆
當代理程式等待輸入內容逾時時 (請參閱代理程式應用程式設定中的「無聲逾時」),系統預設會使用生成式回覆。不過,您可以在模型前置回呼中檢查使用者是否收到輸入內容,並視情況提供回覆。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in callback_context.get_last_user_input():
if part.text:
if "no user activity detected" in part.text:
return LlmResponse.from_parts(parts=[
Part.from_text(text="Hi, are you still there?")
])
return None
處理錯誤
本節提供處理工具錯誤的模式。
工具失敗時轉移給其他服務專員
如果特定工具執行失敗,您可以確定要將對話交給另一個代理處理。這是重要的安全網,可在執行階段發生錯誤時保護使用者體驗。
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in llm_request.contents[-1].parts:
if (part.has_function_response('authentication') and
'error' in part.function_response.response['result']):
return LlmResponse.from_parts(parts=[
Part.from_text('Sorry something went wrong, let me transfer you to another agent.'),
Part.from_agent_transfer(agent='escalation agent')
])
return None
工具發生故障時,妥善終止工作階段
如果特定工具執行失敗,您可以安全終止工作階段。 發生重大工具故障時,這項功能可避免無限迴圈和令人困惑的回覆。
回呼範例:
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
for part in llm_request.contents[-1].parts:
if (part.has_function_response('authentication') and
'error' in part.function_response.response['result']):
return LlmResponse.from_parts(parts=[
Part.from_text('Sorry something went wrong, please call back later.'),
Part.from_end_session(reason='Failure during user authentication.')
])
return None
背景資訊和變數
本節提供使用內容變數的模式。
將內容變數傳遞至 OpenAPI 工具
個人化 AI 需要工具才能存取使用者工作階段資料。
手動回想並傳遞工作階段 ID 或使用者變數等重要詳細資料,本質上既不可靠又緩慢。代理可以改為將特定內容變數傳遞至 OpenAPI 工具。
您可以使用 x-ces-session-context 表示值不需要由模型產生 (且模型看不到該值的結構定義),而是來自環境變數。
下表列出可用的值:
| 值 | 說明 |
|---|---|
$context.project_id |
專案 ID。 Google Cloud |
$context.project_number |
專案編號。 Google Cloud |
$context.location |
虛擬服務專員的位置 (區域)。 |
$context.app_id |
代理程式應用程式 ID。 |
$context.session_id |
工作階段的專屬 ID。 |
$context.variables |
所有脈絡變數值,以物件形式表示。 |
$context.variables.variable_name |
特定脈絡變數的值。將 variable_name 替換為變數名稱。 |
openapi: 3.0.0
info:
title: test-title
description: test-description
version: 1.0.0
paths:
/test-path/{session_id}:
post:
parameters:
- name: session_id
in: path
description: The session ID.
required: true
schema:
type: string
x-ces-session-context: $context.session_id
- name: test_variable
in: query
description: Specific session variable.
required: true
schema:
type: string
x-ces-session-context: $context.variables.test_variable
requestBody:
description: test-description
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/SessionParams'
responses:
'200':
description: test-response-description
content:
application/json:
schema:
type: object
properties:
result:
type: string
components:
schemas:
SessionParams:
type: object
description: all context variables
x-ces-session-context: $context.variables
動態提示
您可以透過下列方式,建構可將動態提示傳送至模型的代理程式:
- 變數 可用於控管提示變化版本。
- 指令:包含變數參照。
- 工具:可根據對話詳細資料更新變數。
- before_model_callback。
舉例來說,您可以根據使用者是律師或海盜,變更代理程式指令:
變數:
| 變數名稱 | 預設值 |
|---|---|
| current_instructions | 你是 Gemini,為 Google 工作。 |
| lawyer_instructions | 你是一位律師,你的工作是講出律師風格的爸爸笑話。 |
| pirate_instructions | 你是海盜,你的工作是講海盜笑話。 |
| 使用者名稱 | 不明 |
指示:
The current user is: {username}
You can use {@TOOL: update_username} to update the user's name if they provide
it.
Follow the current instruction set below exactly.
{current_instructions}
Python 工具:
from typing import Optional
def update_username(username: str) -> Optional[str]:
"""Updates the current user's name."""
set_variable("username", username)
回呼:
def before_model_callback(
callback_context: CallbackContext,
llm_request: LlmRequest
) -> Optional[LlmResponse]:
username = callback_context.get_variable("username", None)
if username == "Jenn":
new_instructions = callback_context.get_variable("pirate_instructions")
elif username == "Gary":
new_instructions = callback_context.get_variable("lawyer_instructions")
callback_context.set_variable("current_instructions", new_instructions)