|
| 1 | +"""Fan-out/fan-in with LLM summarization aggregation. |
| 2 | +
|
| 3 | +Same 3 expert branches as workflow_fan_out_fan_in_edges.py, but instead |
| 4 | +of a hand-coded template, a summarizer Agent synthesizes all branch |
| 5 | +outputs into a concise executive brief. |
| 6 | +
|
| 7 | +Aggregation technique: LLM synthesis (Agent as post-processor). |
| 8 | +
|
| 9 | +Run: |
| 10 | + uv run examples/workflow_aggregator_llm_summary.py |
| 11 | + uv run examples/workflow_aggregator_llm_summary.py --devui (opens DevUI at http://localhost:8101) |
| 12 | +""" |
| 13 | + |
| 14 | +import asyncio |
| 15 | +import os |
| 16 | +import sys |
| 17 | + |
| 18 | +from agent_framework import Agent, AgentExecutorResponse, Executor, WorkflowBuilder, WorkflowContext, handler |
| 19 | +from agent_framework.openai import OpenAIChatClient |
| 20 | +from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider |
| 21 | +from dotenv import load_dotenv |
| 22 | + |
| 23 | +load_dotenv(override=True) |
| 24 | +API_HOST = os.getenv("API_HOST", "github") |
| 25 | + |
| 26 | +# Configure the chat client based on the API host |
| 27 | +async_credential = None |
| 28 | +if API_HOST == "azure": |
| 29 | + async_credential = DefaultAzureCredential() |
| 30 | + token_provider = get_bearer_token_provider(async_credential, "https://cognitiveservices.azure.com/.default") |
| 31 | + client = OpenAIChatClient( |
| 32 | + base_url=f"{os.environ['AZURE_OPENAI_ENDPOINT']}/openai/v1/", |
| 33 | + api_key=token_provider, |
| 34 | + model_id=os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"], |
| 35 | + ) |
| 36 | +elif API_HOST == "github": |
| 37 | + client = OpenAIChatClient( |
| 38 | + base_url="https://models.github.ai/inference", |
| 39 | + api_key=os.environ["GITHUB_TOKEN"], |
| 40 | + model_id=os.getenv("GITHUB_MODEL", "openai/gpt-5-mini"), |
| 41 | + ) |
| 42 | +else: |
| 43 | + client = OpenAIChatClient( |
| 44 | + api_key=os.environ["OPENAI_API_KEY"], model_id=os.environ.get("OPENAI_MODEL", "gpt-5-mini") |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +class DispatchPrompt(Executor): |
| 49 | + """Emit the same prompt downstream so fan-out edges can broadcast it.""" |
| 50 | + |
| 51 | + @handler |
| 52 | + async def dispatch(self, prompt: str, ctx: WorkflowContext[str]) -> None: |
| 53 | + await ctx.send_message(prompt) |
| 54 | + |
| 55 | + |
| 56 | +class FormatBranchResults(Executor): |
| 57 | + """Fan-in collector that formats branch outputs into a single prompt.""" |
| 58 | + |
| 59 | + @handler |
| 60 | + async def format( |
| 61 | + self, |
| 62 | + results: list[AgentExecutorResponse], |
| 63 | + ctx: WorkflowContext[str], |
| 64 | + ) -> None: |
| 65 | + """Combine expert outputs into labeled sections for the summarizer.""" |
| 66 | + sections = [] |
| 67 | + for result in results: |
| 68 | + sections.append(f"[{result.executor_id}]\n{result.agent_response.text}") |
| 69 | + await ctx.send_message("\n\n---\n\n".join(sections)) |
| 70 | + |
| 71 | + |
| 72 | +dispatcher = DispatchPrompt(id="dispatcher") |
| 73 | + |
| 74 | +researcher = Agent( |
| 75 | + client=client, |
| 76 | + name="Researcher", |
| 77 | + instructions=( |
| 78 | + "You are an expert market researcher. " |
| 79 | + "Given the prompt, provide concise factual insights, opportunities, and risks. " |
| 80 | + "Use short bullet points." |
| 81 | + ), |
| 82 | +) |
| 83 | + |
| 84 | +marketer = Agent( |
| 85 | + client=client, |
| 86 | + name="Marketer", |
| 87 | + instructions=( |
| 88 | + "You are a marketing strategist. " |
| 89 | + "Given the prompt, propose clear value proposition and audience messaging. " |
| 90 | + "Use short bullet points." |
| 91 | + ), |
| 92 | +) |
| 93 | + |
| 94 | +legal = Agent( |
| 95 | + client=client, |
| 96 | + name="Legal", |
| 97 | + instructions=( |
| 98 | + "You are a legal and compliance reviewer. " |
| 99 | + "Given the prompt, list constraints, disclaimers, and policy concerns. " |
| 100 | + "Use short bullet points." |
| 101 | + ), |
| 102 | +) |
| 103 | + |
| 104 | +formatter = FormatBranchResults(id="formatter") |
| 105 | + |
| 106 | +# The summarizer Agent is the final node — it receives the formatted expert |
| 107 | +# outputs and synthesizes them into a concise executive brief. |
| 108 | +summarizer = Agent( |
| 109 | + client=client, |
| 110 | + name="Summarizer", |
| 111 | + instructions=( |
| 112 | + "You receive analysis from three domain experts (researcher, marketer, legal). " |
| 113 | + "Synthesize their combined insights into a concise 3-sentence executive brief " |
| 114 | + "that a CEO could read in 30 seconds. Do not repeat the raw analysis." |
| 115 | + ), |
| 116 | +) |
| 117 | + |
| 118 | +workflow = ( |
| 119 | + WorkflowBuilder( |
| 120 | + name="FanOutFanInLLMSummary", |
| 121 | + description="Fan-out/fan-in with LLM summarization aggregation.", |
| 122 | + start_executor=dispatcher, |
| 123 | + output_executors=[summarizer], |
| 124 | + ) |
| 125 | + .add_fan_out_edges(dispatcher, [researcher, marketer, legal]) |
| 126 | + .add_fan_in_edges([researcher, marketer, legal], formatter) |
| 127 | + .add_edge(formatter, summarizer) |
| 128 | + .build() |
| 129 | +) |
| 130 | + |
| 131 | + |
| 132 | +async def main() -> None: |
| 133 | + """Run the sample and print the LLM-synthesized brief.""" |
| 134 | + prompt = "We are launching a budget-friendly electric bike for urban commuters." |
| 135 | + print(f"Prompt: {prompt}\n") |
| 136 | + |
| 137 | + events = await workflow.run(prompt) |
| 138 | + for output in events.get_outputs(): |
| 139 | + print("=== Executive Brief (LLM-synthesized) ===") |
| 140 | + print(output) |
| 141 | + |
| 142 | + if async_credential: |
| 143 | + await async_credential.close() |
| 144 | + |
| 145 | + |
| 146 | +if __name__ == "__main__": |
| 147 | + if "--devui" in sys.argv: |
| 148 | + from agent_framework.devui import serve |
| 149 | + |
| 150 | + serve(entities=[workflow], port=8101, auto_open=True) |
| 151 | + else: |
| 152 | + asyncio.run(main()) |
0 commit comments