執行時上下文讓中介軟體能夠存取當前執行環境與請求的資訊。 這使得像是每會話設定、使用者專屬行為,以及基於執行時條件的動態中介軟體行為等模式。
在 C# 中,執行時上下文通常是傳遞 AgentRunOptions 或自訂會話狀態。 中介軟體可以存取會話屬性並執行選項,以在執行時做出決策。
小提示
請參閱 Agent 與 Run Scope 頁面,了解中介軟體範圍如何影響執行時上下文存取。
Python 執行時上下文分為三個公開表面:
-
session=談話、州和歷史。 -
function_invocation_kwargs=這些值只有工具或函式中介軟體才會看到。 -
client_kwargs=用於聊天用戶端專用資料或用戶端中介軟體設定。
使用最小且能符合資料的表面。 這樣可以讓工具輸入明確,避免客戶端的元資料洩漏到工具執行中。
小提示
將 視為function_invocation_kwargs舊有任意公鑰**kwargs傳遞模式agent.run()get_response()的替代方案。
選擇合適的執行時桶
| 應用案例 | API 曲面 | 存取自 |
|---|---|---|
| 分享對話狀態、服務會話 ID 或歷史 | session= |
ctx.session、AgentContext.session |
| 傳遞執行時值,只有工具或函式中介軟體需要 | function_invocation_kwargs= |
FunctionInvocationContext.kwargs |
| 傳遞用戶端專屬的執行時值或用戶端中介軟體設定 | client_kwargs= |
自訂 get_response(..., client_kwargs=...) 實作 |
傳遞僅工具執行時的值
from typing import Annotated
from agent_framework import FunctionInvocationContext, tool
from agent_framework.openai import OpenAIResponsesClient
@tool(approval_mode="never_require")
def send_email(
address: Annotated[str, "Recipient email address."],
ctx: FunctionInvocationContext,
) -> str:
user_id = ctx.kwargs["user_id"]
tenant = ctx.kwargs.get("tenant", "default")
return f"Queued email for {address} from {user_id} ({tenant})"
agent = OpenAIResponsesClient().as_agent(
name="Notifier",
instructions="Send email updates.",
tools=[send_email],
)
response = await agent.run(
"Email the launch update to finance@example.com",
function_invocation_kwargs={
"user_id": "user-123",
"tenant": "contoso",
},
)
print(response.text)
在工具內使用 ctx.kwargs ,而不是在可呼叫工具上宣告blanket **kwargs 。 舊 **kwargs 有工具仍能維持相容性,但在 GA 前會被移除。
任何標註為 的 FunctionInvocationContext 參數,無論其名稱為何,都被視為注入的執行時上下文參數,且不會暴露在模型所呈現的 JSON 架構中。 如果你提供明確的結構/輸入模型,一個未註解的 ctx 普通參數也會被識別為注入的上下文參數。
如果值是長壽命工具狀態或相依關係,而非每次呼叫的資料,請將其保留在工具類別實例中,而非透過 function_invocation_kwargs傳遞。 關於該模式,請參見 「建立一個多功能工具類別」。
功能中介軟體接收相同的上下文
函式中介軟體使用工具接收的物件 FunctionInvocationContext 相同。 這表示中介軟體可以檢查 context.arguments、 context.kwargs、 context.session和 context.result。
from collections.abc import Awaitable, Callable
from agent_framework import FunctionInvocationContext
from agent_framework.openai import OpenAIResponsesClient
async def enrich_tool_runtime_context(
context: FunctionInvocationContext,
call_next: Callable[[], Awaitable[None]],
) -> None:
context.kwargs.setdefault("tenant", "contoso")
context.kwargs.setdefault("request_source", "middleware")
await call_next()
agent = OpenAIResponsesClient().as_agent(
name="Notifier",
instructions="Send email updates.",
tools=[send_email],
middleware=[enrich_tool_runtime_context],
)
中介軟體合約使用 call_next() 時沒有參數。 在呼叫前先變異 context.kwargs ,所選工具會透過注入 FunctionInvocationContext的 來看到這些值。
session=用於共享執行時狀態
from typing import Annotated
from agent_framework import FunctionInvocationContext, tool
from agent_framework.openai import OpenAIResponsesClient
@tool(approval_mode="never_require")
def remember_topic(
topic: Annotated[str, "Topic to remember."],
ctx: FunctionInvocationContext,
) -> str:
if ctx.session is None:
return "No session available."
ctx.session.state["topic"] = topic
return f"Stored {topic!r} in session state."
agent = OpenAIResponsesClient().as_agent(
name="MemoryAgent",
instructions="Remember important topics.",
tools=[remember_topic],
)
session = agent.create_session()
await agent.run("Remember that the budget review is on Friday.", session=session)
print(session.state["topic"])
明確傳遞 session 並session=從 讀取。ctx.session 會話存取不再需要經過執行時 kwarg。
與委託代理共享會話狀態
當代理被透過 作為工具 as_tool()揭露時,執行時函數 kwarg 已經流經 ctx.kwargs。 只有當次代理應該與來電AgentSession者共享時才加入propagate_session=True。
from agent_framework import FunctionInvocationContext, tool
from agent_framework.openai import OpenAIResponsesClient
@tool(description="Store findings for later steps.")
def store_findings(findings: str, ctx: FunctionInvocationContext) -> None:
if ctx.session is not None:
ctx.session.state["findings"] = findings
client = OpenAIResponsesClient()
research_agent = client.as_agent(
name="ResearchAgent",
instructions="Research the topic and store findings.",
tools=[store_findings],
)
research_tool = research_agent.as_tool(
name="research",
description="Research a topic and store findings.",
arg_name="query",
propagate_session=True,
)
當 propagate_session=True時,被委託的代理人看到的狀態與呼叫者相同 ctx.session 。 讓它 False 在自己的會話中孤立子代理。
自訂聊天客戶端與代理
如果你實作自訂公開 run() 或 get_response() 方法,請在簽名中加入明確的執行時桶。
from collections.abc import Mapping, Sequence
from typing import Any
from agent_framework import ChatOptions, Message
async def get_response(
self,
messages: Sequence[Message],
*,
options: ChatOptions[Any] | None = None,
function_invocation_kwargs: Mapping[str, Any] | None = None,
client_kwargs: Mapping[str, Any] | None = None,
**kwargs: Any,
):
...
用於 function_invocation_kwargs 工具呼叫流程及 client_kwargs 用戶端特定行為。 直接將客戶端專屬值透過公開 **kwargs 傳遞只是相容性路徑,應視為已棄用。 同樣地,將新工具定義為 **kwargs 僅遷移相容性——透過注入的上下文物件來消耗執行時資料。