|
| 1 | +"""GraphAgent multi-agent research workflow example. |
| 2 | +
|
| 3 | +Demonstrates a coordinator → parallel researchers → merger → critic loop: |
| 4 | +
|
| 5 | + coordinator |
| 6 | + ↓ |
| 7 | + [researcher_a || researcher_b] (ParallelNodeGroup, WAIT_ALL) |
| 8 | + ↓ |
| 9 | + merger |
| 10 | + ↓ |
| 11 | + critic ──REVISE──→ merger |
| 12 | + │ |
| 13 | + APPROVED |
| 14 | + ↓ |
| 15 | + END |
| 16 | +
|
| 17 | +Why GraphAgent (not ParallelAgent/SequentialAgent)? |
| 18 | +- SequentialAgent: cannot run researcher_a and researcher_b concurrently. |
| 19 | +- ParallelAgent: parallelises but cannot add coordinator before or critic+loop after. |
| 20 | +- GraphAgent: combines sequential coordination, true parallel research, AND a |
| 21 | + conditional quality-review loop in one declarative graph. |
| 22 | +
|
| 23 | +Run (requires GOOGLE_API_KEY env var): |
| 24 | + python -m contributing.samples.graph_agent_multi_agent.agent |
| 25 | +""" |
| 26 | + |
| 27 | +import asyncio |
| 28 | +import os |
| 29 | + |
| 30 | +from google.adk.agents.graph import GraphAgent |
| 31 | +from google.adk.agents.graph import GraphState |
| 32 | +from google.adk.agents.graph import JoinStrategy |
| 33 | +from google.adk.agents.graph import ParallelNodeGroup |
| 34 | +from google.adk.agents.graph import StateReducer |
| 35 | +from google.adk.agents.llm_agent import LlmAgent |
| 36 | +from google.adk.runners import Runner |
| 37 | +from google.adk.sessions.in_memory_session_service import InMemorySessionService |
| 38 | +from google.genai import types |
| 39 | +from pydantic import BaseModel |
| 40 | + |
| 41 | +_MODEL = os.getenv("LLM_MODEL_NAME", "gemini-2.5-flash") |
| 42 | + |
| 43 | +# --------------------------------------------------------------------------- |
| 44 | +# Output Schemas |
| 45 | +# --------------------------------------------------------------------------- |
| 46 | + |
| 47 | + |
| 48 | +class ReviewResult(BaseModel): |
| 49 | + """Structured review output from critic agent.""" |
| 50 | + |
| 51 | + decision: str # "approve" or "revise" |
| 52 | + feedback: str # Review comments |
| 53 | + |
| 54 | + |
| 55 | +# --------------------------------------------------------------------------- |
| 56 | +# Agents |
| 57 | +# --------------------------------------------------------------------------- |
| 58 | + |
| 59 | +coordinator = LlmAgent( |
| 60 | + name="coordinator", |
| 61 | + model=_MODEL, |
| 62 | + instruction=( |
| 63 | + "You are a research coordinator. Given a research topic, split it into" |
| 64 | + " exactly two independent subtopics for parallel investigation. Output" |
| 65 | + " each subtopic on its own line prefixed with 'SUBTOPIC A:' and" |
| 66 | + " 'SUBTOPIC B:'." |
| 67 | + ), |
| 68 | + output_key="subtopics", |
| 69 | +) |
| 70 | + |
| 71 | +researcher_a = LlmAgent( |
| 72 | + name="researcher_a", |
| 73 | + model=_MODEL, |
| 74 | + instruction=( |
| 75 | + "You are a researcher specialising in the first subtopic. " |
| 76 | + "Write a concise research summary (3-5 sentences) with key findings." |
| 77 | + ), |
| 78 | + output_key="research_a", |
| 79 | +) |
| 80 | + |
| 81 | +researcher_b = LlmAgent( |
| 82 | + name="researcher_b", |
| 83 | + model=_MODEL, |
| 84 | + instruction=( |
| 85 | + "You are a researcher specialising in the second subtopic. " |
| 86 | + "Write a concise research summary (3-5 sentences) with key findings." |
| 87 | + ), |
| 88 | + output_key="research_b", |
| 89 | +) |
| 90 | + |
| 91 | +merger = LlmAgent( |
| 92 | + name="merger", |
| 93 | + model=_MODEL, |
| 94 | + instruction=( |
| 95 | + "You are a synthesis expert. Merge the two research summaries into a " |
| 96 | + "single coherent report. Highlight complementary insights." |
| 97 | + ), |
| 98 | + output_key="merged_report", |
| 99 | +) |
| 100 | + |
| 101 | +critic = LlmAgent( |
| 102 | + name="critic", |
| 103 | + model=_MODEL, |
| 104 | + instruction=( |
| 105 | + "You are a peer reviewer. Evaluate the merged report for clarity, " |
| 106 | + "completeness, and accuracy. " |
| 107 | + 'Return {"decision": "approve", "feedback": "..."} if good, ' |
| 108 | + 'or {"decision": "revise", "feedback": "explanation..."} if needs work.' |
| 109 | + ), |
| 110 | + output_schema=ReviewResult, # Structured output |
| 111 | + # output_key auto-defaults to "critic" (agent name) |
| 112 | +) |
| 113 | + |
| 114 | + |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | +# Routing predicates |
| 117 | +# --------------------------------------------------------------------------- |
| 118 | + |
| 119 | + |
| 120 | +def _needs_revision(state: GraphState) -> bool: |
| 121 | + """Check if critic requested revision using structured output.""" |
| 122 | + review = state.get_parsed("critic", ReviewResult) |
| 123 | + return review.decision.lower() == "revise" if review else False |
| 124 | + |
| 125 | + |
| 126 | +def _is_approved(state: GraphState) -> bool: |
| 127 | + """Check if critic approved using structured output.""" |
| 128 | + review = state.get_parsed("critic", ReviewResult) |
| 129 | + return review.decision.lower() == "approve" if review else False |
| 130 | + |
| 131 | + |
| 132 | +# --------------------------------------------------------------------------- |
| 133 | +# Graph |
| 134 | +# --------------------------------------------------------------------------- |
| 135 | + |
| 136 | + |
| 137 | +def build_multi_agent_graph() -> GraphAgent: |
| 138 | + graph = GraphAgent( |
| 139 | + name="research_graph", |
| 140 | + description=( |
| 141 | + "Multi-agent research with parallel execution and quality loop" |
| 142 | + ), |
| 143 | + max_iterations=20, |
| 144 | + ) |
| 145 | + |
| 146 | + graph.add_node("coordinator", agent=coordinator) |
| 147 | + |
| 148 | + graph.add_node( |
| 149 | + "researcher_a", |
| 150 | + agent=researcher_a, |
| 151 | + # Both researchers see the same coordinator output |
| 152 | + input_mapper=lambda s: s.data.get("subtopics", ""), |
| 153 | + reducer=StateReducer.OVERWRITE, |
| 154 | + ) |
| 155 | + graph.add_node( |
| 156 | + "researcher_b", |
| 157 | + agent=researcher_b, |
| 158 | + input_mapper=lambda s: s.data.get("subtopics", ""), |
| 159 | + reducer=StateReducer.OVERWRITE, |
| 160 | + ) |
| 161 | + |
| 162 | + graph.add_node( |
| 163 | + "merger", |
| 164 | + agent=merger, |
| 165 | + input_mapper=lambda s: ( |
| 166 | + f"Research A:\n{s.data.get('research_a', '')}\n\n" |
| 167 | + f"Research B:\n{s.data.get('research_b', '')}" |
| 168 | + ), |
| 169 | + reducer=StateReducer.OVERWRITE, |
| 170 | + ) |
| 171 | + graph.add_node("critic", agent=critic) |
| 172 | + |
| 173 | + # Register parallel group so branches execute concurrently |
| 174 | + graph.add_parallel_group( |
| 175 | + "researchers", |
| 176 | + ParallelNodeGroup( |
| 177 | + nodes=["researcher_a", "researcher_b"], |
| 178 | + join_strategy=JoinStrategy.WAIT_ALL, |
| 179 | + ), |
| 180 | + ) |
| 181 | + |
| 182 | + graph.set_start("coordinator") |
| 183 | + graph.add_edge("coordinator", "researcher_a") |
| 184 | + graph.add_edge("coordinator", "researcher_b") |
| 185 | + graph.add_edge("researcher_a", "merger") |
| 186 | + graph.add_edge("researcher_b", "merger") |
| 187 | + graph.add_edge("merger", "critic") |
| 188 | + |
| 189 | + # Quality loop: revise if not approved |
| 190 | + graph.add_edge("critic", "merger", condition=_needs_revision) |
| 191 | + |
| 192 | + graph.set_end("critic") |
| 193 | + |
| 194 | + return graph |
| 195 | + |
| 196 | + |
| 197 | +# --------------------------------------------------------------------------- |
| 198 | +# Main |
| 199 | +# --------------------------------------------------------------------------- |
| 200 | + |
| 201 | + |
| 202 | +async def main() -> None: |
| 203 | + session_service = InMemorySessionService() |
| 204 | + graph = build_multi_agent_graph() |
| 205 | + |
| 206 | + session = await session_service.create_session( |
| 207 | + app_name="research_graph", user_id="user1" |
| 208 | + ) |
| 209 | + |
| 210 | + topic = "The impact of large language models on software engineering" |
| 211 | + print(f"Research topic: {topic}\n") |
| 212 | + |
| 213 | + # Use Runner instead of manual invocation context |
| 214 | + runner = Runner( |
| 215 | + app_name="research_graph", |
| 216 | + agent=graph, |
| 217 | + session_service=session_service, |
| 218 | + auto_create_session=False, # Session already created above |
| 219 | + ) |
| 220 | + |
| 221 | + revision_count = 0 |
| 222 | + async for event in runner.run_async( |
| 223 | + user_id="user1", |
| 224 | + session_id=session.id, |
| 225 | + new_message=types.Content(parts=[types.Part(text=topic)]), |
| 226 | + ): |
| 227 | + if not event.content or not event.content.parts: |
| 228 | + continue |
| 229 | + author = event.author |
| 230 | + text = event.content.parts[0].text or "" |
| 231 | + if author == "coordinator": |
| 232 | + print("Coordinator assigned subtopics.") |
| 233 | + elif author in ("researcher_a", "researcher_b"): |
| 234 | + print(f" [{author}] research complete ({len(text)} chars)") |
| 235 | + elif author == "merger": |
| 236 | + revision_count += 1 |
| 237 | + print(f"Merger produced report (revision {revision_count}).") |
| 238 | + elif author == "critic": |
| 239 | + # Parse critic output from the event text (JSON string) |
| 240 | + try: |
| 241 | + review = ReviewResult.model_validate_json(text.strip()) |
| 242 | + decision = review.decision.upper() |
| 243 | + except Exception: |
| 244 | + decision = "UNKNOWN (parse error)" |
| 245 | + print(f"Critic verdict: {decision}") |
| 246 | + |
| 247 | + # Re-fetch fresh session state (create_session returns a deepcopy) |
| 248 | + fresh_session = await session_service.get_session( |
| 249 | + app_name="research_graph", user_id="user1", session_id=session.id |
| 250 | + ) |
| 251 | + final_data = (fresh_session or session).state.get("graph_data", {}) |
| 252 | + final_state = GraphState(data=final_data) |
| 253 | + |
| 254 | + print("\nFinal merged report:") |
| 255 | + print(final_state.get_str("merged_report", "(none)")[:500]) |
| 256 | + print("\nFinal review:") |
| 257 | + review = final_state.get_parsed("critic", ReviewResult) |
| 258 | + print(f"Decision: {review.decision if review else 'none'}") |
| 259 | + print(f"Feedback: {review.feedback[:200] if review else 'none'}") |
| 260 | + |
| 261 | + |
| 262 | +if __name__ == "__main__": |
| 263 | + asyncio.run(main()) |
0 commit comments