from google.adk.agents import LoopAgent, LlmAgent, SequentialAgent
from google.adk.tools.tool_context import ToolContext
from google.adk.agents.callback_context import CallbackContext
# --- 常量 ---GEMINI_MODEL ="gemini-2.5-flash"# --- 状态键 ---STATE_CURRENT_DOC ="current_document"STATE_CRITICISM ="criticism"# 定义评论者应使用的确切短语以表示完成COMPLETION_PHRASE ="No major issues found."# --- 工具定义 ---defexit_loop(tool_context: ToolContext):
"""Call this function ONLY when the critique indicates no further changes are needed, signaling the iterative process should end.""" print(f" [Tool Call] exit_loop triggered by {tool_context.agent_name}")
tool_context.actions.escalate =True tool_context.actions.skip_summarization =True# 返回空字典,因为工具通常应该返回可 JSON 序列化的输出return {}
# --- Agent 前回调 ---defupdate_initial_topic_state(callback_context: CallbackContext):
"""Ensure 'initial_topic' is set in state before pipeline starts.""" callback_context.state['initial_topic'] = callback_context.state.get('initial_topic', 'a robot developing unexpected emotions')
# --- Agent 定义 ---# 步骤 1:初始写作 Agent(在开始时运行一次)initial_writer_agent = LlmAgent(
name="InitialWriterAgent",
model=GEMINI_MODEL,
include_contents='none',
instruction=f"""
You are a Creative Writing Assistant tasked with starting a story.
Write a *very basic* first draft of a short story (just 1-2 simple sentences).
Keep it plain and minimal - do NOT add descriptive language yet.
Topic: {{initial_topic}} Output *only* the story/document text. Do not add introductions or explanations.
""",
description="Writes the initial document draft based on the topic, aiming for some initial substance.",
output_key=STATE_CURRENT_DOC
)
# 步骤 2a:评论者 Agent(在完善循环内部)critic_agent_in_loop = LlmAgent(
name="CriticAgent",
model=GEMINI_MODEL,
include_contents='none',
instruction=f"""
You are a Constructive Critic AI reviewing a short story draft.
**Document to Review:**
```
{{current_document}} ```
**Completion Criteria (ALL must be met):**
1. At least 4 sentences long
2. Has a clear beginning, middle, and end
3. Includes at least one descriptive detail (sensory or emotional)
**Task:**
Check the document against the criteria above.
IF any criteria is NOT met, provide specific feedback on what to add or improve.
Output *only* the critique text.
IF ALL criteria are met, respond *exactly* with: "{COMPLETION_PHRASE}"
""",
description="Reviews the current draft, providing critique if clear improvements are needed, otherwise signals completion.",
output_key=STATE_CRITICISM
)
# STEP 2b: Refiner/Exiter Agent (Inside the Refinement Loop) refiner_agent_in_loop = LlmAgent(
name="RefinerAgent",
model=GEMINI_MODEL,
# Relies solely on state via placeholders include_contents='none',
instruction=f"""
You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
**Current Document:**
```
{{current_document}} ```
**Critique/Suggestions:**
{{criticism}} **Task:**
Analyze the 'Critique/Suggestions'.
IF the critique is *exactly* "{COMPLETION_PHRASE}":
You MUST call the 'exit_loop' function. Do not output any text.
ELSE (the critique contains actionable feedback):
Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.
Do not add explanations. Either output the refined document OR call the exit_loop function.
""",
description="Refines the document based on critique, or calls exit_loop if critique indicates completion.",
tools=[exit_loop], # Provide the exit_loop tool output_key=STATE_CURRENT_DOC # Overwrites state['current_document'] with the refined version )
# STEP 2: Refinement Loop Agent refinement_loop = LoopAgent(
name="RefinementLoop",
# Agent order is crucial: Critique first, then Refine/Exit sub_agents=[
critic_agent_in_loop,
refiner_agent_in_loop,
],
max_iterations=5# Limit loops )
# STEP 3: Overall Sequential Pipeline# For ADK tools compatibility, the root agent must be named `root_agent` root_agent = SequentialAgent(
name="IterativeWritingPipeline",
sub_agents=[
initial_writer_agent, # Run first to create initial doc refinement_loop # Then run the critique/refine loop ],
before_agent_callback=update_initial_topic_state, # set initial topic in state description="Writes an initial document and then iteratively refines it with critique using an exit tool." )
go124 行展开收起expand_more
// ExitLoopArgs 定义了 ExitLoop 工具的(空的)参数。typeExitLoopArgsstruct{}
// ExitLoopResults 定义了 ExitLoop 工具的输出。typeExitLoopResultsstruct{}
// ExitLoop 是一个通过将 Escalate 设置为 true 来通知循环终止的工具。funcExitLoop(ctxagent.Context, inputExitLoopArgs) (ExitLoopResults, error) {
fmt.Printf("[Tool Call] exitLoop triggered by %s \n", ctx.AgentName())
ctx.Actions().Escalate = truereturnExitLoopResults{}, nil}
funcmain() {
ctx:=context.Background()
iferr:=runAgent(ctx, "Write a document about a cat"); err!=nil {
log.Fatalf("Agent execution failed: %v", err)
}
}
funcrunAgent(ctxcontext.Context, promptstring) error {
model, err:=gemini.NewModel(ctx, modelName, &genai.ClientConfig{})
iferr!=nil {
returnfmt.Errorf("failed to create model: %v", err)
}
// 步骤 1:初始写作 Agent(在开始时运行一次)initialWriterAgent, err:=llmagent.New(llmagent.Config{
Name: "InitialWriterAgent",
Model: model,
Description: "Writes the initial document draft based on the topic.",
Instruction: `You are a Creative Writing Assistant tasked with starting a story.
Write the *first draft* of a short story (aim for 2-4 sentences).
Base the content *only* on the topic provided in the user's prompt.
Output *only* the story/document text. Do not add introductions or explanations.`,
OutputKey: stateDoc,
})
iferr!=nil {
returnfmt.Errorf("failed to create initial writer agent: %v", err)
}
// 步骤 2a:评论者 Agent(在完善循环内部)criticAgentInLoop, err:=llmagent.New(llmagent.Config{
Name: "CriticAgent",
Model: model,
Description: "Reviews the current draft, providing critique or signaling completion.",
Instruction: fmt.Sprintf(`You are a Constructive Critic AI reviewing a short document draft.
**Document to Review:**
"""
{%s}
"""
**Task:**
Review the document.
IF you identify 1-2 *clear and actionable* ways it could be improved:
Provide these specific suggestions concisely. Output *only* the critique text.
ELSE IF the document is coherent and addresses the topic adequately:
Respond *exactly* with the phrase "%s" and nothing else.`, stateDoc, donePhrase),
OutputKey: stateCrit,
})
iferr!=nil {
returnfmt.Errorf("failed to create critic agent: %v", err)
}
exitLoopTool, err:=functiontool.New(
functiontool.Config{
Name: "exitLoop",
Description: "Call this function ONLY when the critique indicates no further changes are needed.",
},
ExitLoop,
)
iferr!=nil {
returnfmt.Errorf("failed to create exit loop tool: %v", err)
}
// 步骤 2b:精炼器/退出器 Agent(在精炼循环内部)refinerAgentInLoop, err:=llmagent.New(llmagent.Config{
Name: "RefinerAgent",
Model: model,
Instruction: fmt.Sprintf(`You are a Creative Writing Assistant refining a document based on feedback OR exiting the process.
**Current Document:**
"""
{%s}
"""
**Critique/Suggestions:**
{%s}
**Task:**
Analyze the 'Critique/Suggestions'.
IF the critique is *exactly* "%s":
You MUST call the 'exitLoop' function. Do not output any text.
ELSE (the critique contains actionable feedback):
Carefully apply the suggestions to improve the 'Current Document'. Output *only* the refined document text.`, stateDoc, stateCrit, donePhrase),
Description: "Refines the document based on critique, or calls exitLoop if critique indicates completion.",
Tools: []tool.Tool{exitLoopTool},
OutputKey: stateDoc,
})
iferr!=nil {
returnfmt.Errorf("failed to create refiner agent: %v", err)
}
// 步骤 2:精炼循环 AgentrefinementLoop, err:=loopagent.New(loopagent.Config{
AgentConfig: agent.Config{
Name: "RefinementLoop",
SubAgents: []agent.Agent{criticAgentInLoop, refinerAgentInLoop},
},
MaxIterations: 5,
})
iferr!=nil {
returnfmt.Errorf("failed to create loop agent: %v", err)
}
// 步骤 3:整体顺序管道iterativeWriterAgent, err:=sequentialagent.New(sequentialagent.Config{
AgentConfig: agent.Config{
Name: appName,
SubAgents: []agent.Agent{initialWriterAgent, refinementLoop},
},
})
iferr!=nil {
returnfmt.Errorf("failed to create sequential agent pipeline: %v", err)
}