代理迴圈會重複呼叫代理,直到滿足完備條件。 它用於反覆優化、完成待辦事項、等待背景任務,或評估答案是否符合明確標準。
一定要綁定自主迴圈。 完備條件可能失敗,模型可能停滯,評估器則可能是機率的。
這很重要
代理迴圈是實驗性的。
手動設定循環播放
當你想要在不使用 Harness Agent 的其他預設設定下實作迴圈時,請使用直接組合 API。
匯入迴圈類型,並用 AIAgent包裹任何 LoopAgent 。 其預設最多呼叫次數為 10 次代理:
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
AIAgent baseAgent = chatClient.AsAIAgent();
AIAgent agent = new LoopAgent(
baseAgent,
new CompletionMarkerLoopEvaluator("DONE"),
new LoopAgentOptions { MaxIterations = 5 });
匯入 AgentLoopMiddleware,並將其加入一般的 Agent。 預設的代理程式最大執行次數為 10 次:
from agent_framework import Agent, AgentLoopMiddleware
def needs_more_work(*, last_result, **kwargs):
return "DONE" not in last_result.text
agent = Agent(
client=client,
middleware=[
AgentLoopMiddleware(
needs_more_work,
max_iterations=5,
)
],
)
謂詞可以是同步或非同步的。 返回 True 以繼續、 False 停止,或 (continue, feedback) 將回饋傳給下一個迭代。
Go 會透過 agent/harness/loop 提供有界限的重新叫用。 註冊 loop.New(loop.Config{...}) 於 agent.Config.Middlewares。 中介軟體執行代理,評估其回應,並可選擇性地將回饋傳送到另一個迭代中。
以下 Foundry 範例使用完成標記。 它需要 FOUNDRY_PROJECT_ENDPOINT、 FOUNDRY_MODEL,以及一個 Azure 憑證:
// Copyright (c) Microsoft. All rights reserved.
package main
import (
"context"
"github.com/microsoft/agent-framework-go/agent"
"github.com/microsoft/agent-framework-go/agent/harness/loop"
"github.com/microsoft/agent-framework-go/examples/internal/demo"
"github.com/microsoft/agent-framework-go/provider/foundryprovider"
)
var logger = demo.NewLogger(
"Loop Harness",
"This sample shows how the loop harness keeps re-invoking an agent until it "+
"signals completion with a marker, so the agent can work across several turns "+
"on its own before returning.",
"Model", demo.FoundryModel,
)
// completionMarker is the token the agent is asked to emit once the task is
// fully done; the loop stops as soon as it appears in a response.
const completionMarker = "TASK COMPLETE"
func main() {
token := demo.FoundryTokenCredential()
// Wrap the agent with the loop harness: after each iteration the
// completion-marker evaluator decides whether to run the agent again.
a := foundryprovider.NewAgent(
demo.FoundryProjectEndpoint,
token,
foundryprovider.ModelDeployment(demo.FoundryModel),
foundryprovider.AgentConfig{
Instructions: "You are a diligent assistant. Work on the request step by step across " +
"multiple turns. End your final message with the marker '" + completionMarker +
"' once, and only once, the request is fully complete.",
Config: agent.Config{
Name: "Worker",
Middlewares: []agent.Middleware{
// The loop re-invokes the agent (and everything below it,
// including the logger) until an evaluator stops the loop.
loop.New(loop.Config{
Evaluators: []loop.Evaluator{
loop.NewCompletionMarkerEvaluator(loop.CompletionMarkerConfig{Marker: completionMarker}),
},
}),
logger, // for logging each agent iteration
},
},
},
)
ctx := context.Background()
resp, err := a.RunText(ctx, "Draft a short checklist for planning a small birthday party, "+
"then review it once for anything missing, and finish.").Collect()
demo.Response(resp, err)
}
MaxIterations 為可選 *int 選項,預設為10。 請為您的工作設定明確的界限。 在多個評估者中,第一個要求再進行一次迭代的評估者會提供回饋;迴圈僅在所有評估者停止或迭代極限達到時才停止。
關於無需憑證的範例,請參見 腳本迴圈範例。 它展示了標記完成、自訂評估器以及迭代安全上限。
選擇完備條件
LoopAgent 接受一個評估器或一個有序集合:
| 評估員 | 持續期間 |
|---|---|
CompletionMarkerLoopEvaluator |
最新的回應沒有包含設定好的標記。 |
TodoCompletionLoopEvaluator |
已解決的 TodoProvider 仍有未完成的項目,可選擇性地在所選的代理程式模式中。 |
BackgroundTaskCompletionLoopEvaluator |
已解決的 BackgroundAgentsProvider 仍有正在執行中的任務。 |
AIJudgeLoopEvaluator |
另一個裁判用戶端表示,原始要求尚未完全獲得解答。 |
DelegateLoopEvaluator |
您的回呼函式會傳回 LoopEvaluation.Continue(...)。 |
當多個評估器被設定時,它們會依序執行。 第一個要求再進行一次迭代的評估者會提供回饋;只有當所有評估者都拒絕繼續時,這個循環才會停止。
使用AI法官
法官會收到原始請求及最新的代理人回覆。 若發現缺口,其分析即為下一次迭代的反饋:
var evaluator = new AIJudgeLoopEvaluator(
judgeClient,
new AIJudgeLoopEvaluatorOptions
{
Criteria =
[
"Answer every part of the request.",
"Support conclusions with evidence.",
],
});
AIAgent loopAgent = new LoopAgent(
agent,
evaluator,
new LoopAgentOptions { MaxIterations = 4 });
僅使用你信任的評判端點來處理原始請求和產生的回應。
控制上下文與輸出
預設情況下,LoopAgent 會重複使用同一個工作階段,並將勝出的評估器最近一次的回饋作為下一個輸入。
FreshContextPerIteration = true 則是根據原始要求加上彙整的意見反應記錄,重新建構每一次的執行,並重設或還原工作階段。
非串流執行預設會回傳彙總逐字稿。 設定 NonStreamingReturnsLastResponseOnly = true 只回傳最終回應。 串流一律會傳送每次反覆處理的結果,以及任何可見的代表他人發出的意見反應訊息。
謂詞會接收關鍵字引數,包括 iteration、last_result、messages、original_messages、session、agent、progress 以及 feedback。 協助程式 todos_remaining() 和 background_tasks_running() 提供內建的待辦事項與背景工作條件。 將它們與 todos_remaining_message 或 background_tasks_running_message 搭配,以產生有針對性的下一個輸入。
使用AI法官
AgentLoopMiddleware.with_judge 形成一個由法官主導的循環。 裁判迴圈預設為五次迭代:
from agent_framework import Agent, AgentLoopMiddleware
loop = AgentLoopMiddleware.with_judge(
judge_client,
criteria=[
"Answer every part of the request.",
"Support conclusions with evidence.",
],
max_iterations=4,
)
agent = Agent(
client=client,
middleware=[loop],
)
當需要更多工作時,法官的理由會回饋給代理人。 僅使用你信任的評判端點來處理原始請求和產生的回應。
控制上下文、進度與輸出
對於進階迴圈,直接構造 AgentLoopMiddleware :
-
record_feedback每次工作迭代後建立簡潔的進度條目。 -
progress會向回呼公開累積的項目。 -
inject_progress=True為下一階段的輸入增加進度。 -
fresh_context=True會從原始工作和進度記錄重新啟動,並將附加的工作階段還原為進入迴圈前的快照。 -
return_final_only=True僅回傳非串流運行的最後回應。
僅在可保證完成述詞會終止時,才傳遞 max_iterations=None。
當最新回應包含已設定的標記時,請使用 loop.NewCompletionMarkerEvaluator 以停止。 針對特定應用的補全,實作 loop.Evaluator 或使用 loop.EvaluatorFunc,返回 loop.Stop(), loop.Continue(feedback)或 loop.ContinueWithMessages(messages)。
FreshContextPerIteration 從原始輸入加上累積的回饋開始重新開始。
NonStreamingReturnsLastResponseOnly 將非串流結果限制為僅顯示最終迭代的結果。
Go 沒有包含 C# 範例中顯示的內建 AI 裁判評估器。 如果完成需要另一個模型或外部檢查,請自行提供評估員。
搭配 Harness Agent 使用迴圈功能
如果您也想要 Harness Agent 預先設定的歷程記錄、規劃、記憶、核准和可檢視性管線時,請使用 Harness Agent 設定。
設定 HarnessAgentOptions.LoopEvaluators。 該執行框架將 LoopAgent 套用為其最外層的代理程式裝飾項目:
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
var options = new HarnessAgentOptions
{
LoopEvaluators =
[
new CompletionMarkerLoopEvaluator("DONE"),
],
LoopAgentOptions = new LoopAgentOptions
{
MaxIterations = 5,
},
};
HarnessAgent agent = chatClient.AsHarnessAgent(options);
// Equivalent construction: new HarnessAgent(chatClient, options)
AgentSession session = await agent.CreateSessionAsync();
空的或 nullLoopEvaluators 集合會使這個執行框架變成單次使用。
核准與工作階段行為
LoopAgent 當迭代回傳待處理的工具核准請求時,會在評估完備條件前停止。 它會將請求回傳給呼叫者,而不是將請求隱藏在另一個自主迭代後面。 呼叫者透過正常 工具核准 流程提供批准回應後,客服人員即可繼續。
LoopAgent 它本身不會增加審核處理。 Harness Agent 將迴圈套用到 ToolApprovalAgent 外部,允許擱置的核准要求逸出迴圈。
在通話中重複使用該 AgentSession 內容以繼續對話。 迴圈反覆處理預設會共用該工作階段。 在支援時,透過 FreshContextPerIteration = trueLoopAgent ,可重置或還原呼叫者提供的會話狀態。 當序列化會話僅包含遠端對話識別碼時,服務擁有的對話儲存可以保留歷史紀錄。
供應 loop_should_continue 至 create_harness_agent; loop_max_iterations 預設為10:
from agent_framework import create_harness_agent
def needs_more_work(*, last_result, **kwargs):
return "DONE" not in last_result.text
agent = create_harness_agent(
client=client,
loop_should_continue=needs_more_work,
loop_max_iterations=5,
)
session = agent.create_session()
loop_next_message 自訂下一次輸入。 沒有 loop_should_continue時,工廠不會新增迴圈,也會忽略其他迴圈參數。
核准與工作階段行為
在某次反覆處理傳回擱置的工具核准要求時,AgentLoopMiddleware 會在評估其接續條件述詞之前停止。 它會將請求回傳給呼叫者,而不是將請求隱藏在另一個自主迭代後面。 呼叫者透過正常 工具核准 流程提供批准回應後,客服人員即可繼續。
AgentLoopMiddleware 本身不會新增 ToolApprovalMiddleware。 Harness Agent 會將迴圈置於其核可中介軟體之外,讓待核可的請求得以脫離該迴圈。 在工具自動核准啟用時,每次執行 Harness Agent 時建立並傳遞一個 AgentSession。
在通話中重複使用該 AgentSession 內容以繼續對話。 迴圈反覆處理預設會共用該工作階段。 使用 fresh_context=True 時,中介軟體會在每次反覆處理之間,將附加的工作階段還原為進入迴圈前的快照狀態。 當序列化會話僅包含遠端對話識別碼時,服務擁有的對話儲存可以保留歷史紀錄。
Go harness.AgentConfig 輔助工具預設不會新增迴圈。 將 loop.New(...) 包含在呼叫端的 agent.Config.Middlewares 中,藉此以有界限的重新叫用來包裝已設定的 Agent。
當迭代產生待處理工具核准請求時,迴圈會結束。 它不會自動核准工具。 在主機內處理請求,並在同一會話中回傳匹配的核准回應後再繼續。