共用方式為


Python 2026 重大變更指南

本文件列出自 2026 年初以來 Python 版本中的所有重大變更,包括可能影響程式碼的重要變更與重要改進。 每個變更都會標示為:

  • 🔴 重大變更 — 需要進行程式碼更改來升級
  • 🟡 增強 — 新能力或改進;現有程式碼仍然有效

這份文件將在我們達到 1.0.0 穩定版後被移除,因此在 2026 年升級版本時,請務必參考,以確保不會錯過任何重要變更。 關於特定主題的詳細升級指引(例如選項遷移),請參閱連結的升級指南或連結的PR。


Post-python-1.0.0b260212 合併變更(未發布)

以下重要的 PR 是在最新公開的 Python 預發布後合併的,並應追蹤即將到來的套件更新。

🟡 Azure Functions 的 Durable workflow support

PR:#3630

agent-framework-azurefunctions 套件現在支援在 Azure Durable Functions 上執行 Workflow 圖形。 將 workflow 參數傳遞到 AgentFunctionApp,以自動註冊代理實體、活動函數和 HTTP 端點。

from agent_framework.azurefunctions import AgentFunctionApp

app = AgentFunctionApp(workflow=my_workflow)
# Automatically registers:
#   POST /api/workflow/run          — start a workflow
#   GET  /api/workflow/status/{id}  — check status
#   POST /api/workflow/respond/{id}/{requestId} — HITL response

支援扇出/扇入、共享狀態,以及人工參與流程模式,並可設定逾時和在到期時自動拒絕的功能。


🟡 OpenTelemetry 追蹤上下文傳播至 MCP 請求

PR:#3780

當安裝 OpenTelemetry 時,追蹤上下文(例如 W3C traceparent)會自動注入到 MCP 請求中,透過params._meta。 這使得跨代理→MCP伺服器呼叫實現端對端分散式追蹤。 不需要程式碼變更——這是當存在有效區間上下文時會啟動的加法行為。


🔴 Pydantic 設定被替換為 TypedDict + load_settings()

PRs:#3843#4032

pydantic-settings 基於 AFBaseSettings 的類別已被使用 TypedDictload_settings() 的輕量級、基於函數的設定系統取代。 pydantic-settings依賴性完全被移除了。

所有設定類別(例如、 OpenAISettingsAzureOpenAISettingsAnthropicSettings)現在 TypedDict 都是定義,設定值則透過字典語法而非屬性存取。

Before:

from agent_framework.openai import OpenAISettings

settings = OpenAISettings()  # pydantic-settings auto-loads from env
api_key = settings.api_key
model_id = settings.model_id

After:

from agent_framework.openai import OpenAISettings, load_settings

settings = load_settings(OpenAISettings, env_prefix="OPENAI_")
api_key = settings["api_key"]
model_id = settings["model_id"]

這很重要

Agent Framework 不會 自動從檔案載入數值 .env 。 您必須明確地選擇以下方法之一來載入 .env

  • 在應用程式開始時從python-dotenv套件呼叫load_dotenv()
  • 轉交 env_file_path=".env"load_settings()
  • 直接在你的 shell 或 IDE 中設定環境變數

load_settings解析順序為:明確覆蓋→.env檔案值(提供時env_file_path)→環境變數→預設值。 如果你指定 env_file_path,檔案必須存在,否則 FileNotFoundError 會被觸發。


🔴 FunctionTool[Any] 移除架構直通的通用設定

PR:#3907

基於結構的工具路徑不再依賴先前 FunctionTool[Any] 的通用行為。 直接使用 FunctionTool,並在需要時提供 pydantic BaseModel 或明確的結構定義(例如,使用 @tool(schema=...))。

Before:

placeholder: FunctionTool[Any] = FunctionTool(...)

After:

placeholder: FunctionTool = FunctionTool(...)

🟡 workflow.as_agent() 現在當提供者未設定時,這裡會預設本地歷史

PR:#3918

當沒有 workflow.as_agent() 時建立 context_providers,現在預設會加入 InMemoryHistoryProvider("memory")。 若明確提供上下文提供者,該清單將保持不變。

workflow_agent = workflow.as_agent(name="MyWorkflowAgent")
# Default local history provider is injected when none are provided.

🟡 AzureAIClient 警告不支援的執行階段覆寫

PR:#3919

AzureAIClient現在在執行時間的toolsstructured_output與代理程式建立時間的配置不同時,會記錄警告。 Azure AI 代理服務不支援執行時工具或回應格式變更——如果你需要動態覆寫,請改用 AzureOpenAIResponsesClient


🔴 聊天/客服訊息輸入對齊(runget_response

PR:#3920

聊天客戶端 get_response 實作現在持續接收 Sequence[Message]agent.run(...)保持彈性(strContent、 、 Message或這些序列),並在呼叫聊天客戶端前正規化輸入。

Before:

async def get_response(self, messages: str | Message | list[Message], **kwargs): ...

After:

from collections.abc import Sequence
from agent_framework import Message

async def get_response(self, messages: Sequence[Message], **kwargs): ...

🟡 基岩添加至 core[all],並修正工具選擇預設

PR:#3953

Amazon Bedrock 現已包含在 agent-framework-core[all] 額外內容中,並可透過 agent_framework.amazon 懶加載介面使用。 工具選擇行為也被修正:未設定的工具選擇值保持不變,提供者使用其服務預設值,而明確設定的值則被保留。

from agent_framework.amazon import BedrockClient

🔴 由 source_id 決定的提供者狀態範圍

PR:#3995

提供者掛鉤現在會獲得提供者範圍的狀態字典(state.setdefault(provider.source_id, {})),而非完整的會話狀態。 這表示過去透過巢狀狀態 state[self.source_id]["key"] 存取的提供者實作,現在必須直接存取 state["key"]

此外,預設InMemoryHistoryProvidersource_id也從 "memory" 變成 "in_memory"

Before:

# In a custom provider hook:
async def on_before_agent(self, state: dict, **kwargs):
    my_data = state[self.source_id]["my_key"]

# InMemoryHistoryProvider default source_id
provider = InMemoryHistoryProvider("memory")

After:

# Provider hooks receive scoped state — no nested access needed:
async def on_before_agent(self, state: dict, **kwargs):
    my_data = state["my_key"]

# InMemoryHistoryProvider default source_id changed
provider = InMemoryHistoryProvider("in_memory")

python-1.0.0b260212(2026年2月12日)

發行說明:python-1.0.0b260212

🔴 Hosted*Tool 類別被用戶端 get_*_tool() 方法取代

PR:#3634

託管工具類別被移除,改為使用屬於客戶端範圍的工廠方法。 這使得工具的可用性由供應商明確呈現。

已移除的類別 Replacement
HostedCodeInterpreterTool client.get_code_interpreter_tool()
HostedWebSearchTool client.get_web_search_tool()
HostedFileSearchTool client.get_file_search_tool(...)
HostedMCPTool client.get_mcp_tool(...)
HostedImageGenerationTool client.get_image_generation_tool(...)

Before:

from agent_framework import HostedCodeInterpreterTool, HostedWebSearchTool

tools = [HostedCodeInterpreterTool(), HostedWebSearchTool()]

After:

from agent_framework.openai import OpenAIResponsesClient

client = OpenAIResponsesClient()
tools = [client.get_code_interpreter_tool(), client.get_web_search_tool()]

🔴 會話/上下文提供者管道已完成AgentSessioncontext_providers

PR:#3850

Python 會話及上下文提供者遷移已完成。 AgentThread 舊有的上下文提供者類型也被移除。

  • AgentThreadAgentSession
  • agent.get_new_thread()agent.create_session()
  • agent.get_new_thread(service_thread_id=...)agent.get_session(service_session_id=...)
  • context_provider= / chat_message_store_factory= 模式被替換為 context_providers=[...]

Before:

thread = agent.get_new_thread()
response = await agent.run("Hello", thread=thread)

After:

session = agent.create_session()
response = await agent.run("Hello", session=session)

🔴 檢查點模型與儲存行為重構

PR:#3744

檢查點內部結構已重新設計,這影響了持久化檢查點的相容性及自訂儲存機制:

  • WorkflowCheckpoint 現在儲存活物件(序列化發生在檢查點儲存中)
  • FileCheckpointStorage 現在使用 Pickle 序列化技術
  • workflow_id 被移除後 previous_checkpoint_id 又被加入
  • 已廢棄的檢查點掛鉤被移除

如果你在不同版本間保存檢查點,請在恢復工作流程前重新生成或遷移現有的檢查點檔案。


🟡 AzureOpenAIResponsesClient 支援 Azure AI Foundry 專案端點

PR:#3814

你現在可以用 Foundry 專案端點或直接 Azure OpenAI 端點來建立AzureOpenAIResponsesClient,而不僅限於此,還可以建立AIProjectClient

from azure.identity import DefaultAzureCredential
from agent_framework.azure import AzureOpenAIResponsesClient

client = AzureOpenAIResponsesClient(
    project_endpoint="https://<your-project>.services.ai.azure.com",
    deployment_name="gpt-4o-mini",
    credential=DefaultAzureCredential(),
)

🔴 中介軟體 call_next 不再接受 context

PR:#3829

中介軟體延續現在不接受任何爭議。 如果你的中介軟體還在呼叫 call_next(context),請更新成 call_next()

Before:

async def telemetry_middleware(context, call_next):
    # ...
    return await call_next(context)

After:

async def telemetry_middleware(context, call_next):
    # ...
    return await call_next()

python-1.0.0b260210(2026年2月10日)

發佈說明:python-1.0.0b260210

🔴 工作流程工廠函式已從 WorkflowBuilder

PR:#3781

register_executor()register_agent()已從WorkflowBuilder中移除。 所有建構方法(add_edgeadd_fan_out_edgesadd_fan_in_edgesadd_chainadd_switch_case_edge_groupadd_multi_selection_edge_group)且start_executor不再接受字串名稱——它們需要執行者或代理實例直接使用。

為了狀態隔離,將執行者/代理實例化和工作流程建置包裝在輔助方法中,讓每次呼叫都能產生新的實例。

WorkflowBuilder 與執行器

Before:

workflow = (
    WorkflowBuilder(start_executor="UpperCase")
    .register_executor(lambda: UpperCaseExecutor(id="upper"), name="UpperCase")
    .register_executor(lambda: ReverseExecutor(id="reverse"), name="Reverse")
    .add_edge("UpperCase", "Reverse")
    .build()
)

After:

upper = UpperCaseExecutor(id="upper")
reverse = ReverseExecutor(id="reverse")

workflow = WorkflowBuilder(start_executor=upper).add_edge(upper, reverse).build()

WorkflowBuilder 與經紀人合作

Before:

builder = WorkflowBuilder(start_executor="writer_agent")
builder.register_agent(factory_func=create_writer_agent, name="writer_agent")
builder.register_agent(factory_func=create_reviewer_agent, name="reviewer_agent")
builder.add_edge("writer_agent", "reviewer_agent")

workflow = builder.build()

After:

writer_agent = create_writer_agent()
reviewer_agent = create_reviewer_agent()

workflow = WorkflowBuilder(start_executor=writer_agent).add_edge(writer_agent, reviewer_agent).build()

使用輔助方法進行狀態隔離

對於每次調用需要隔離狀態的工作流程,請用輔助方法包裝建構:

def create_workflow() -> Workflow:
    """Each call produces fresh executor instances with independent state."""
    upper = UpperCaseExecutor(id="upper")
    reverse = ReverseExecutor(id="reverse")

    return WorkflowBuilder(start_executor=upper).add_edge(upper, reverse).build()

workflow_a = create_workflow()
workflow_b = create_workflow()

🔴 ChatAgent 重新命名為 AgentChatMessage 再命名為 Message

PR:#3747

核心 Python 類型透過移除冗餘 Chat 前綴而簡化。 不提供向下相容的別名。

之前 之後
ChatAgent Agent
RawChatAgent RawAgent
ChatMessage Message
ChatClientProtocol SupportsChatGetResponse

更新匯入

Before:

from agent_framework import ChatAgent, ChatMessage

After:

from agent_framework import Agent, Message

更新類型參照

Before:

agent = ChatAgent(
    chat_client=client,
    name="assistant",
    instructions="You are a helpful assistant.",
)

message = ChatMessage(role="user", contents=[Content.from_text("Hello")])

After:

agent = Agent(
    client=client,
    name="assistant",
    instructions="You are a helpful assistant.",
)

message = Message(role="user", contents=[Content.from_text("Hello")])

備註

ChatClientChatResponseChatOptionsChatMessageStore都未因此變更而被重新命名。


🔴 類型 API 檢視跨回應/訊息模型的更新

PR:#3647

此版本包含廣泛的訊息/回應類型與輔助 API 的重大變更清理。

  • RoleFinishReason 現在是基於 NewTypestr 封裝器,並使用 RoleLiteral/FinishReasonLiteral 來處理已知值。 把它們當成弦來看待(不用 .value 用)。
  • Message 建構標準化在 Message(role, contents=[...]) ; 字元串 contents 會自動轉換為文字內容。
  • ChatResponseAgentResponse建構器現在以messages=(單一的或序列)為中心,舊有Message建構器的使用已被移除。
  • ChatResponseUpdateAgentResponseUpdate 不再接受 text=;請使用 contents=[Content.from_text(...)]
  • 更新合併輔助工具名稱被簡化。
  • try_parse_valueChatResponseAgentResponse中移除。

輔助方法的重新命名

之前 之後
ChatResponse.from_chat_response_updates(...) ChatResponse.from_updates(...)
ChatResponse.from_chat_response_generator(...) ChatResponse.from_update_generator(...)
AgentResponse.from_agent_run_response_updates(...) AgentResponse.from_updates(...)

更新回應-更新構建方法

Before:

update = AgentResponseUpdate(text="Processing...", role="assistant")

After:

from agent_framework import AgentResponseUpdate, Content

update = AgentResponseUpdate(
    contents=[Content.from_text("Processing...")],
    role="assistant",
)

try_parse_value 替換為 try/except.value

Before:

if parsed := response.try_parse_value(MySchema):
    print(parsed.name)

After:

from pydantic import ValidationError

try:
    parsed = response.value
    if parsed:
        print(parsed.name)
except ValidationError as err:
    print(f"Validation failed: {err}")

🔴統一run/get_response模型與應用ResponseStream

PR:#3379

Python API 被整合為 agent.run(...)client.get_response(...),串流則以 ResponseStream表示。

Before:

async for update in agent.run_stream("Hello"):
    print(update)

After:

stream = agent.run("Hello", stream=True)
async for update in stream:
    print(update)

🔴 核心上下文/協定類型重新命名

PRs:#3714#3717

之前 之後
AgentRunContext AgentContext
AgentProtocol SupportsAgentRun

更新匯入並相應輸入註解。


🔴 中介軟體延續參數已重新命名為 call_next

PR:#3735

中介軟體簽名現在應該用 call_next 來替換 next

Before:

async def my_middleware(context, next):
    return await next(context)

After:

async def my_middleware(context, call_next):
    return await call_next(context)

🔴 TypeVar 名稱標準化(TNameNameT

PR:#3770

程式碼庫現採用一致的 TypeVar 命名風格,並使用後綴 T

Before:

TMessage = TypeVar("TMessage")

After:

MessageT = TypeVar("MessageT")

如果你在框架泛型周圍維持自訂包裝,請將本地 TypeVar 名稱與新慣例對齊,以減少註解流失。


🔴 工作流程作為代理的輸出與串流變化

PR:#3649

workflow.as_agent() 行為更新以使輸出與串流與標準代理反應模式對齊。 檢視那些依賴於舊有輸出或更新處理方式的工作流程代理消費者,並將其更新至目前 AgentResponse/AgentResponseUpdate 流程。


🔴 流暢建構器方法則轉向建構參數

PR:#3693

跨 6 個建構器(WorkflowBuilderSequentialBuilderConcurrentBuilderGroupChatBuilderMagenticBuilderHandoffBuilder)的單一配置流暢方法已遷移至建構參數。 原本是設定唯一配置路徑的流暢方法被移除,取而代之的是建構子參數。

WorkflowBuilder

set_start_executor() with_checkpointing() with_output_from(), 被移除。 改用建構參數。

Before:

upper = UpperCaseExecutor(id="upper")
reverse = ReverseExecutor(id="reverse")

workflow = (
    WorkflowBuilder(start_executor=upper)
    .add_edge(upper, reverse)
    .set_start_executor(upper)
    .with_checkpointing(storage)
    .build()
)

After:

upper = UpperCaseExecutor(id="upper")
reverse = ReverseExecutor(id="reverse")

workflow = (
    WorkflowBuilder(start_executor=upper, checkpoint_storage=storage)
    .add_edge(upper, reverse)
    .build()
)

SequentialBuilder / ConcurrentBuilder

participants()register_participants()with_checkpointing()with_intermediate_outputs() 都被移除。 改用建構參數。

Before:

workflow = SequentialBuilder().participants([agent_a, agent_b]).with_checkpointing(storage).build()

After:

workflow = SequentialBuilder(participants=[agent_a, agent_b], checkpoint_storage=storage).build()

GroupChatBuilder

participants()、、register_participants()with_orchestrator()with_termination_condition()with_max_rounds()with_checkpointing()with_intermediate_outputs()都被移除。 改用建構參數。

Before:

workflow = (
    GroupChatBuilder()
    .with_orchestrator(selection_func=selector)
    .participants([agent1, agent2])
    .with_termination_condition(lambda conv: len(conv) >= 4)
    .with_max_rounds(10)
    .build()
)

After:

workflow = GroupChatBuilder(
    participants=[agent1, agent2],
    selection_func=selector,
    termination_condition=lambda conv: len(conv) >= 4,
    max_rounds=10,
).build()

MagenticBuilder

participants()、、register_participants()with_manager()with_plan_review()with_checkpointing()with_intermediate_outputs() 都被移除。 改用建構參數。

Before:

workflow = (
    MagenticBuilder()
    .participants([researcher, coder])
    .with_manager(agent=manager_agent)
    .with_plan_review()
    .build()
)

After:

workflow = MagenticBuilder(
    participants=[researcher, coder],
    manager_agent=manager_agent,
    enable_plan_review=True,
).build()

HandoffBuilder

with_checkpointing()with_termination_condition() 被移除。 改用建構參數。

Before:

workflow = (
    HandoffBuilder(participants=[triage, specialist])
    .with_start_agent(triage)
    .with_termination_condition(lambda conv: len(conv) > 5)
    .with_checkpointing(storage)
    .build()
)

After:

workflow = (
    HandoffBuilder(
        participants=[triage, specialist],
        termination_condition=lambda conv: len(conv) > 5,
        checkpoint_storage=storage,
    )
    .with_start_agent(triage)
    .build()
)

驗證變更

  • WorkflowBuilder 現在 需要 start_executor 作為建構子參數(先前透過流流方法設定)
  • SequentialBuilderConcurrentBuilderGroupChatBuilderMagenticBuilder 現在要求在構造時提供 participantsparticipant_factories — 若都未提供將引發 ValueError

備註

HandoffBuilder 當時已被接受 participants/participant_factories 為建造者參數,且在此方面未作更改。


🔴 工作流程事件統一為單一的 WorkflowEvent,並搭配 type 判別器

PR:#3690

所有個別的工作流程事件子類別都被一個通用 WorkflowEvent[DataT] 類別取代。 你不再用 isinstance() 檢查來識別事件類型,而是檢查 event.type 字串的文字(例如, "output""request_info""status")。 這與從Contentpython-1.0.0b260123類別合併遵循相同的模式。

移除的賽事級別

以下匯出的事件子類別已不復存在:

舊類別 event.type 價值
WorkflowOutputEvent "output"
RequestInfoEvent "request_info"
WorkflowStatusEvent "status"
WorkflowStartedEvent "started"
WorkflowFailedEvent "failed"
ExecutorInvokedEvent "executor_invoked"
ExecutorCompletedEvent "executor_completed"
ExecutorFailedEvent "executor_failed"
SuperStepStartedEvent "superstep_started"
SuperStepCompletedEvent "superstep_completed"

更新匯入

Before:

from agent_framework import (
    WorkflowOutputEvent,
    RequestInfoEvent,
    WorkflowStatusEvent,
    ExecutorCompletedEvent,
)

After:

from agent_framework import WorkflowEvent
# Individual event classes no longer exist; use event.type to discriminate

更新事件類型檢查

Before:

async for event in workflow.run_stream(input_message):
    if isinstance(event, WorkflowOutputEvent):
        print(f"Output from {event.executor_id}: {event.data}")
    elif isinstance(event, RequestInfoEvent):
        requests[event.request_id] = event.data
    elif isinstance(event, WorkflowStatusEvent):
        print(f"Status: {event.state}")

After:

async for event in workflow.run_stream(input_message):
    if event.type == "output":
        print(f"Output from {event.executor_id}: {event.data}")
    elif event.type == "request_info":
        requests[event.request_id] = event.data
    elif event.type == "status":
        print(f"Status: {event.state}")

使用 AgentResponseUpdate 串流

Before:

from agent_framework import AgentResponseUpdate, WorkflowOutputEvent

async for event in workflow.run_stream("Write a blog post about AI agents."):
    if isinstance(event, WorkflowOutputEvent) and isinstance(event.data, AgentResponseUpdate):
        print(event.data, end="", flush=True)
    elif isinstance(event, WorkflowOutputEvent):
        print(f"Final output: {event.data}")

After:

from agent_framework import AgentResponseUpdate

async for event in workflow.run_stream("Write a blog post about AI agents."):
    if event.type == "output" and isinstance(event.data, AgentResponseUpdate):
        print(event.data, end="", flush=True)
    elif event.type == "output":
        print(f"Final output: {event.data}")

型別註解

Before:

pending_requests: list[RequestInfoEvent] = []
output: WorkflowOutputEvent | None = None

After:

from typing import Any
from agent_framework import WorkflowEvent

pending_requests: list[WorkflowEvent[Any]] = []
output: WorkflowEvent | None = None

備註

WorkflowEvent 是泛型(WorkflowEvent[DataT]),但用於混合事件集合,使用 WorkflowEvent[Any] 或未參數化 WorkflowEvent的。


🔴 workflow.send_responses* 移除;使用 workflow.run(responses=...)

PR:#3720

send_responses()send_responses_streaming() 被從 Workflow 中移除。 透過直接將回應傳遞給 run(),繼續暫停的工作流程。

Before:

async for event in workflow.send_responses_streaming(
    checkpoint_id=checkpoint_id,
    responses=[approved_response],
):
    ...

After:

async for event in workflow.run(
    checkpoint_id=checkpoint_id,
    responses=[approved_response],
):
    ...

🔴 SharedState 重新命名為 State;工作流程狀態 API 是同步的

PR:#3667

州級 API 不再要求 await,命名也已標準化:

之前 之後
ctx.shared_state ctx.state
await ctx.get_shared_state("k") ctx.get_state("k")
await ctx.set_shared_state("k", v) ctx.set_state("k", v)
checkpoint.shared_state checkpoint.state

🔴 協作編排工具已移至 agent_framework.orchestrations

PR:#3685

編排建構器現在存在專用的套件命名空間。

Before:

from agent_framework import SequentialBuilder, GroupChatBuilder

After:

from agent_framework.orchestrations import SequentialBuilder, GroupChatBuilder

🟡 長期的背景回應與延續標記

PR:#3808

現在支援 Python 代理程式在 options={"background": True}continuation_token的執行中進行背景回應。

response = await agent.run("Long task", options={"background": True})
while response.continuation_token is not None:
    response = await agent.run(options={"continuation_token": response.continuation_token})

🟡 會話/上下文提供者預覽類型並排新增

PR:#3763

新增的會話/上下文管線類型與舊有 API 一同引入,用於增量遷移,包括 SessionContextBaseContextProvider


🟡 程式碼解譯器串流現在包含增量程式碼 delta

PR:#3775

串流程式碼直譯器現在會在串流內容中進行 Surfacecode Delta 更新,讓使用者介面能逐步渲染生成的程式碼。


🟡 @tool 支援明確的結構處理

PR:#3734

工具定義現在可以在推斷出的結構輸出需要客製化時,使用明確的結構處理。


python-1.0.0b260130(2026年1月30日)

發布說明:python-1.0.0b260130

🟡 ChatOptionsChatResponse/AgentResponse 現在都可用於通用的回應格式

PR:#3305

ChatOptions、、ChatResponseAgentResponse以及現在都是以回應格式類型為參數化的通用型別。 這使得在使用結構化輸出和 response_format 時,能更精確地進行型別推斷。

Before:

from agent_framework import ChatOptions, ChatResponse
from pydantic import BaseModel

class MyOutput(BaseModel):
    name: str
    score: int

options: ChatOptions = {"response_format": MyOutput}  # No type inference
response: ChatResponse = await client.get_response("Query", options=options)
result = response.value  # Type: Any

After:

from agent_framework import ChatOptions, ChatResponse
from pydantic import BaseModel

class MyOutput(BaseModel):
    name: str
    score: int

options: ChatOptions[MyOutput] = {"response_format": MyOutput}  # Generic parameter
response: ChatResponse[MyOutput] = await client.get_response("Query", options=options)
result = response.value  # Type: MyOutput | None (inferred!)

小提示

這是非破壞性的強化。 沒有型別參數的現有程式碼仍然能正常運作。 你不需要在上述程式碼摘要中指定選項和回應的類型;這裡展示這些資料以求清晰。


🟡 BaseAgent 新增對 Claude Agent SDK 的支援

PR:#3509

Python SDK 現已包含 BaseAgent Claude Agent SDK 的實作,使能在 Agent Framework 中以一流的適配器方式使用。


python-1.0.0b260128(2026年1月28日)

發行說明:python-1.0.0b260128

🔴 AIFunction更名為 FunctionTool@ai_function@tool

PR:#3413

該類別與裝飾器已更名,以提高清晰度並符合業界一致的術語。

Before:

from agent_framework.core import ai_function, AIFunction

@ai_function
def get_weather(city: str) -> str:
    """Get the weather for a city."""
    return f"Weather in {city}: Sunny"

# Or using the class directly
func = AIFunction(get_weather)

After:

from agent_framework.core import tool, FunctionTool

@tool
def get_weather(city: str) -> str:
    """Get the weather for a city."""
    return f"Weather in {city}: Sunny"

# Or using the class directly
func = FunctionTool(get_weather)

🔴 工廠設計模式已加入群組聊天與 Magentic,API 重新命名

PR:#3224

在群組聊天中新增了參與者工廠模組和協調器工廠模組。 同時包含重新命名:

  • with_standard_managerwith_manager
  • participant_factoriesregister_participant

Before:

from agent_framework.workflows import MagenticBuilder

builder = MagenticBuilder()
builder.with_standard_manager(manager)
builder.participant_factories(factory1, factory2)

After:

from agent_framework.workflows import MagenticBuilder

builder = MagenticBuilder()
builder.with_manager(manager)
builder.register_participant(factory1)
builder.register_participant(factory2)

🔴 Github 更名為 GitHub

PR:#3486

類別名稱和套件名稱已更新,使用正確的外殼。

Before:

from agent_framework_github_copilot import GithubCopilotAgent

agent = GithubCopilotAgent(...)

After:

from agent_framework_github_copilot import GitHubCopilotAgent

agent = GitHubCopilotAgent(...)

python-1.0.0b260127(2026年1月27日)

發行說明:python-1.0.0b260127

🟡 BaseAgent 新增對 GitHub Copilot SDK 的支援

PR:#3404

Python SDK 現在包含 GitHub Copilot SDK 整合的BaseAgent實作。


python-1.0.0b260123(2026年1月23日)

發布說明:python-1.0.0b260123

🔴 內容類型簡化為單一類別,並且使用 classmethod 作為建構方式

PR:#3252

將所有舊有的內容型別(源自 BaseContent)替換為一個帶有 classmethods 的單一 Content 類別,以建立特定型別。

完整遷移參考

舊型 新的方法
TextContent(text=...) Content.from_text(text=...)
DataContent(data=..., media_type=...) Content.from_data(data=..., media_type=...)
UriContent(uri=..., media_type=...) Content.from_uri(uri=..., media_type=...)
ErrorContent(message=...) Content.from_error(message=...)
HostedFileContent(file_id=...) Content.from_hosted_file(file_id=...)
FunctionCallContent(name=..., arguments=..., call_id=...) Content.from_function_call(name=..., arguments=..., call_id=...)
FunctionResultContent(call_id=..., result=...) Content.from_function_result(call_id=..., result=...)
FunctionApprovalRequestContent(...) Content.from_function_approval_request(...)
FunctionApprovalResponseContent(...) Content.from_function_approval_response(...)

其他新方法(無直接前身):

  • Content.from_text_reasoning(...) — 用於推理/思維內容
  • Content.from_hosted_vector_store(...) — 向量存儲參考
  • Content.from_usage(...) — 用於使用/標記資訊
  • Content.from_mcp_server_tool_call(...) / Content.from_mcp_server_tool_result(...) — 針對 MCP 伺服器工具
  • Content.from_code_interpreter_tool_call(...) / Content.from_code_interpreter_tool_result(...) — 用於程式碼直譯器
  • Content.from_image_generation_tool_call(...) / Content.from_image_generation_tool_result(...) — 用於影像生成

型別檢查

不要使用 isinstance() 檢查,而是使用 type 屬性:

Before:

from agent_framework.core import TextContent, FunctionCallContent

if isinstance(content, TextContent):
    print(content.text)
elif isinstance(content, FunctionCallContent):
    print(content.name)

After:

from agent_framework.core import Content

if content.type == "text":
    print(content.text)
elif content.type == "function_call":
    print(content.name)

基本範例

Before:

from agent_framework.core import TextContent, DataContent, UriContent

text = TextContent(text="Hello world")
data = DataContent(data=b"binary", media_type="application/octet-stream")
uri = UriContent(uri="https://example.com/image.png", media_type="image/png")

After:

from agent_framework.core import Content

text = Content.from_text("Hello world")
data = Content.from_data(data=b"binary", media_type="application/octet-stream")
uri = Content.from_uri(uri="https://example.com/image.png", media_type="image/png")

🔴 註解類型簡化為 AnnotationTextSpanRegion TypedDicts

PR:#3252

以更 TypedDict 簡單的定義取代基於類別的註解類型。

舊型 新型
CitationAnnotation (類別) Annotation(類型字典)type="citation"
BaseAnnotation (類別) Annotation (TypedDict)
TextSpanRegion (類別為 SerializationMixin TextSpanRegion (TypedDict)
Annotations (類型別名) Annotation
AnnotatedRegions (類型別名) TextSpanRegion

Before:

from agent_framework import CitationAnnotation, TextSpanRegion

region = TextSpanRegion(start_index=0, end_index=25)
citation = CitationAnnotation(
    annotated_regions=[region],
    url="https://example.com/source",
    title="Source Title"
)

After:

from agent_framework import Annotation, TextSpanRegion

region: TextSpanRegion = {"start_index": 0, "end_index": 25}
citation: Annotation = {
    "type": "citation",
    "annotated_regions": [region],
    "url": "https://example.com/source",
    "title": "Source Title"
}

備註

既然 AnnotationTextSpanRegion 現在是 TypedDict 的字典,你就將它們創建為字典,而不是類別實例。


🔴 response_format 驗證錯誤現在對使用者可見

PR:#3274

ChatResponse.valueAgentResponse.value 現在在結構驗證失敗時觸發 ValidationError,而非靜默返回 None

Before:

response = await agent.run(query, options={"response_format": MySchema})
if response.value:  # Returns None on validation failure - no error details
    print(response.value.name)

After:

from pydantic import ValidationError

# Option 1: Catch validation errors
try:
    print(response.value.name)  # Raises ValidationError on failure
except ValidationError as e:
    print(f"Validation failed: {e}")

# Option 2: Safe parsing (returns None on failure)
if result := response.try_parse_value(MySchema):
    print(result.name)

🔴 AG-UI 運行邏輯簡化;MCP 與 Anthropic 用戶端修正

PR:#3322

runAG-UI 中的方法簽名與行為已被簡化。

Before:

from agent_framework.ag_ui import AGUIEndpoint

endpoint = AGUIEndpoint(agent=agent)
result = await endpoint.run(
    request=request,
    run_config={"streaming": True, "timeout": 30}
)

After:

from agent_framework.ag_ui import AGUIEndpoint

endpoint = AGUIEndpoint(agent=agent)
result = await endpoint.run(
    request=request,
    streaming=True,
    timeout=30
)

🟡 Anthropic 用戶端現在支援 response_format 結構化輸出

PR:#3301

你現在可以透過 Anthropic 客戶端 response_format使用結構化輸出解析,類似 OpenAI 和 Azure 客戶端。


🟡 Azure AI 配置擴展 (reasoningrai_config

PRs:#3403#3265

在代理程式創建過程中,Azure AI 支援已隨著推理配置支援及 rai_config 而擴展。


python-1.0.0b260116(2026年1月16日)

發布說明:python-1.0.0b260116

🔴 create_agent 更名為 as_agent

PR:#3249

方法名稱已更改,以更清楚說明其用途。

Before:

from agent_framework.core import ChatClient

client = ChatClient(...)
agent = client.create_agent()

After:

from agent_framework.core import ChatClient

client = ChatClient(...)
agent = client.as_agent()

🔴 WorkflowOutputEvent.source_executor_id 更名為 executor_id

PR:#3166

為了 API 一致性,屬性重新命名。

Before:

async for event in workflow.run_stream(...):
    if isinstance(event, WorkflowOutputEvent):
        executor = event.source_executor_id

After:

async for event in workflow.run_stream(...):
    if isinstance(event, WorkflowOutputEvent):
        executor = event.executor_id

🟡 AG-UI 支援由服務管理的會話持續性

PR:#3136

AG-UI 現在保留由服務管理的對話身份(例如,Foundry 管理的會話/執行緒),以保持多回合的連續性。


python-1.0.0b260114(2026年1月14日)

發布說明:python-1.0.0b260114

🔴 編排已重構

PR:#3023

代理框架工作流程中對編排進行大規模重構與簡化:

  • 群組聊天:將編排器執行器拆分為專用代理型與功能型(BaseGroupChatOrchestratorGroupChatOrchestratorAgentBasedGroupChatOrchestrator)。 簡化為星型拓撲與廣播模型。
  • Handoff:移除單層、協調器及自訂執行者支援。 轉為使用 HandoffAgentExecutor 的廣播模式。
  • 順序與並行:透過AgentApprovalExecutorAgentRequestInfoExecutor來依賴子工作流程的簡化請求資訊機制。

Before:

from agent_framework.workflows import GroupChat, HandoffOrchestrator

# Group chat with custom coordinator
group = GroupChat(
    participants=[agent1, agent2],
    coordinator=my_coordinator
)

# Handoff with single tier
handoff = HandoffOrchestrator(
    agents=[agent1, agent2],
    tier="single"
)

After:

from agent_framework.workflows import (
    GroupChatOrchestrator,
    HandoffAgentExecutor,
    AgentApprovalExecutor
)

# Group chat with star topology
group = GroupChatOrchestrator(
    participants=[agent1, agent2]
)

# Handoff with executor-based approach
handoff = HandoffAgentExecutor(
    agents=[agent1, agent2]
)

🔴 以 TypedDict 與 Generic 形式引入的選項

PR:#3140

選項現在使用TypedDict來提高類型安全性和IDE自動完成功能。

📖 完整的遷移說明,請參閱 「類型化選項指南」。

Before:

response = await client.get_response(
    "Hello!",
    model_id="gpt-4",
    temperature=0.7,
    max_tokens=1000,
)

After:

response = await client.get_response(
    "Hello!",
    options={
        "model_id": "gpt-4",
        "temperature": 0.7,
        "max_tokens": 1000,
    },
)

🔴 display_name 刪除; context_provider 更改為單數; middleware 必須為清單

PR:#3139

  • display_name 從代理人移除的參數
  • context_providers (複數,接受名單)改為 context_provider (單數,僅允許1人)
  • middleware 現在需要一個清單(不再接受單一實例)
  • AggregateContextProvider 從程式碼中移除(如有需要,請使用範例實作)

Before:

from agent_framework.core import Agent, AggregateContextProvider

agent = Agent(
    name="my-agent",
    display_name="My Agent",
    context_providers=[provider1, provider2],
    middleware=my_middleware,  # single instance was allowed
)

aggregate = AggregateContextProvider([provider1, provider2])

After:

from agent_framework.core import Agent

# Only one context provider allowed; combine manually if needed
agent = Agent(
    name="my-agent",  # display_name removed
    context_provider=provider1,  # singular, only 1
    middleware=[my_middleware],  # must be a list now
)

# For multiple context providers, create your own aggregate
class MyAggregateProvider:
    def __init__(self, providers):
        self.providers = providers
    # ... implement aggregation logic

🔴 AgentRunResponse* 更名為 AgentResponse*

PR:#3207

AgentRunResponseAgentRunResponseUpdate 被重新命名為 AgentResponseAgentResponseUpdate

Before:

from agent_framework import AgentRunResponse, AgentRunResponseUpdate

After:

from agent_framework import AgentResponse, AgentResponseUpdate

🟡 新增宣告式工作流程執行環境,以支援 YAML 定義的工作流程

PR:#2815

新增了基於圖形的執行時,用於執行宣告式 YAML 工作流程,使多代理能在無需自訂執行時程式碼的情況下進行協調。


🟡 MCP 載入與可靠性改進

PR:#3154

MCP 整合改善了連接中斷行為、載入時的分頁支援,以及表示控制選項。


🟡 Foundry A2ATool 現在支援沒有目標 URL 的連線

PR:#3127

A2ATool 現在即使未設定直接目標 URL,也能透過專案連線元資料解析 Foundry 支援的 A2A 連線。


python-1.0.0b260107(2026年1月7日)

發布說明:python-1.0.0b260107

這次發行沒有重大變動。


python-1.0.0b260106(2026年1月6日)

發行說明:python-1.0.0b260106

這次發行沒有重大變動。


摘要表

釋放 發行說明 類型 改變 PR
1.0.0B260212 後(未發行) N/A 🔴 中斷 聊天/代理訊息輸入對齊:自訂 get_response() 實作必須接受 Sequence[Message] #3920
1.0.0B260212 後(未發行) N/A 🔴 中斷 FunctionTool[Any] 為了架構直通而移除相容性 Shim,根據需要使用 FunctionTool 明確的架構 #3907
1.0.0B260212 後(未發行) N/A 🟡 強化 workflow.as_agent() 現在當上下文提供者未設定時,預設會 InMemoryHistoryProvider("memory") 注入 #3918
1.0.0b260212 注意事項 🔴 中斷 Hosted*Tool 課程被取消;透過客戶端 get_*_tool() 方法建立託管工具 #3634
1.0.0b260212 🔴 中斷 會話/上下文提供者管線已完成:AgentThread 已移除,請使用 AgentSession + context_providers #3850
1.0.0b260212 🔴 中斷 檢查點模型/儲存重構(workflow_id 移除、 previous_checkpoint_id 新增、儲存行為變更) #3744
1.0.0b260212 🟡 強化 AzureOpenAIResponsesClient 可由 Azure AI Foundry 專案端點建立,或 AIProjectClient #3814
1.0.0b260212 🔴 中斷 中介軟體的延續功能不再接受context,請將call_next(context)更新為call_next() #3829
1.0.0b260210 注意事項 🔴 中斷 send_responses() / send_responses_streaming() 移除; 使用 workflow.run(responses=...) #3720
1.0.0b260210 🔴 中斷 SharedStateState;工作流程狀態 API 是同步的,檢查點狀態欄位會重新命名 #3667
1.0.0b260210 🔴 中斷 編排設計者遷移到agent_framework.orchestrations封裝 #3685
1.0.0b260210 🟡 強化 為 Python 代理回應新增背景回應與 continuation_token 支援 #3808
1.0.0b260210 🟡 強化 並排新增的會話/上下文預覽類型 (SessionContextBaseContextProvider #3763
1.0.0b260210 🟡 強化 串流程式碼解譯器更新現在包含增量程式碼 delta #3775
1.0.0b260210 🟡 強化 @tool Decorator 新增了明確的結構處理支援 #3734
1.0.0b260210 注意事項 🔴 中斷 register_executor() / register_agent() 已從 WorkflowBuilder 中移除; 直接使用實例,分離狀態的輔助方法 #3781
1.0.0b260210 🔴 中斷 ChatAgentAgentChatMessageMessageRawChatAgentRawAgentChatClientProtocolSupportsChatGetResponse #3747
1.0.0b260210 🔴 中斷 類型 API 審查: Role/FinishReason 類型變更、回應/更新建構子限制、輔助工具改名為 from_updates,以及移除 try_parse_value #3647
1.0.0b260210 🔴 中斷 API 統一於 run/get_responseResponseStream #3379
1.0.0b260210 🔴 中斷 AgentRunContext 更名為 AgentContext #3714
1.0.0b260210 🔴 中斷 AgentProtocol 更名為 SupportsAgentRun #3717
1.0.0b260210 🔴 中斷 中介軟體 next 參數重新命名為 call_next #3735
1.0.0b260210 🔴 中斷 TypeVar 命名標準化(TNameNameT #3770
1.0.0b260210 🔴 中斷 工作流程作為代理的輸出/串流行為,與目前代理回應流程相符 #3649
1.0.0b260210 🔴 中斷 流暢構建器方法在 6 個構建器中轉換為建構子參數 #3693
1.0.0b260210 🔴 中斷 工作流程事件統一為單一 WorkflowEvent,並使用 type 做為判別器。isinstance()event.type == "..." #3690
1.0.0b260130 注意事項 🟡 強化 ChatOptions / ChatResponse / AgentResponse 通用響應格式 #3305
1.0.0b260130 🟡 強化 BaseAgent 新增對 Claude Agent SDK 整合的支援 #3509
1.0.0b260128 注意事項 🔴 中斷 AIFunctionFunctionTool@ai_function@tool #3413
1.0.0b260128 🔴 中斷 GroupChat/Magentic 的工廠模式; with_standard_managerwith_managerparticipant_factoriesregister_participant #3224
1.0.0b260128 🔴 中斷 GithubGitHub #3486
1.0.0b260127 注意事項 🟡 強化 BaseAgent 新增對 GitHub Copilot SDK 整合的支援 #3404
1.0.0b260123 注意事項 🔴 中斷 內容類型整合為 Content 單一類別,並搭配類別方法。 #3252
1.0.0b260123 🔴 中斷 response_format 驗證錯誤現在會引發 ValidationError #3274
1.0.0b260123 🔴 中斷 AG-UI 運行邏輯簡化版 #3322
1.0.0b260123 🟡 強化 Anthropic 用戶端新增 response_format 對結構化輸出的支援 #3301
1.0.0b260123 🟡 強化 Azure AI 配置擴充與reasoningrai_config支援 #3403#3265
1.0.0b260116 注意事項 🔴 中斷 create_agentas_agent #3249
1.0.0b260116 🔴 中斷 source_executor_idexecutor_id #3166
1.0.0b260116 🟡 強化 AG-UI 支援服務管理的會話/執行緒連續性 #3136
1.0.0b260114 注意事項 🔴 中斷 重構的編排(群組聊天、切換、順序、並行) #3023
1.0.0b260114 🔴 中斷 選項可作為 TypedDict 與 Generic #3140
1.0.0b260114 🔴 中斷 display_name 移除; context_providerscontext_provider (單數); middleware 必須為列表 #3139
1.0.0b260114 🔴 中斷 AgentRunResponse / AgentRunResponseUpdate 更名為 AgentResponse/AgentResponseUpdate #3207
1.0.0b260114 🟡 強化 為 YAML 定義的工作流程新增宣告式工作流程執行階段 #2815
1.0.0b260114 🟡 強化 MCP 載入/可靠性改進(連線遺失處理、分頁、表示控制) #3154
1.0.0b260114 🟡 強化 Foundry A2ATool 支援沒有明確目標 URL 的連線 #3127
1.0.0b260107 注意事項 沒有顯著變化
1.0.0b260106 注意事項 沒有顯著變化

後續步驟