Skip to content

Commit 1ee64db

Browse files
author
Pierre
committed
1 parent c83a8e2 commit 1ee64db

File tree

2 files changed

+211
-1
lines changed

2 files changed

+211
-1
lines changed

examples/workflows/README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,18 @@ The evaluator-optimizer pattern employs an iterative feedback loop. An initial o
4848

4949
For an implementation example, see [evaluator_optimizer.py](evaluator_optimizer.py).
5050

51+
## 6. Chain of Agents (Long Context Processing)
52+
The Chain of Agents pattern is designed for processing long documents or complex tasks that exceed the context window of a single model. In this pattern, multiple worker agents process different chunks of the input sequentially, passing their findings through the chain, while a manager agent synthesizes the final output.
53+
54+
**Example:**
55+
- Split a long document into manageable chunks
56+
- Worker agents process each chunk sequentially, building upon previous findings
57+
- A manager agent synthesizes all findings into a final, coherent response
58+
59+
For an implementation example, see [chain_of_agents.py](chain_of_agents.py).
60+
5161
---
5262

53-
These patterns were inspired by the workflow patterns described in the [Vercel AI SDK Documentation](https://sdk.vercel.ai/docs/foundations/agents#patterns-with-examples).
63+
These patterns were inspired by the workflow patterns described in the [Vercel AI SDK Documentation](https://sdk.vercel.ai/docs/foundations/agents#patterns-with-examples) and research from organizations like [Google Research](https://research.google/blog/chain-of-agents-large-language-models-collaborating-on-long-context-tasks/).
5464

5565
This README should serve as a high-level guide to understanding and using the different patterns available in our workflows.
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
"""
2+
This implementation is inspired by Google Research's Chain of Agents (CoA) framework:
3+
https://research.google/blog/chain-of-agents-large-language-models-collaborating-on-long-context-tasks/
4+
5+
CoA is a training-free, task-agnostic framework for handling long-context tasks through LLM collaboration.
6+
Instead of trying to fit everything into a single context window, it:
7+
1. Breaks input into manageable chunks
8+
2. Uses worker agents to process chunks sequentially, passing information forward
9+
3. Uses a manager agent to synthesize the final answer
10+
11+
Key benefits of this approach:
12+
- More efficient than full-context processing (O(nk) vs O(n²) complexity)
13+
- Better performance than RAG for complex reasoning tasks
14+
- Scales well with input length (performance improves with longer inputs)
15+
- No training required, works with any LLM
16+
"""
17+
18+
import workflowai
19+
from workflowai import Model
20+
from pydantic import BaseModel, Field
21+
import asyncio
22+
from typing import List
23+
24+
25+
class DocumentChunk(BaseModel):
26+
"""A chunk of text from a long document."""
27+
content: str = Field(description="The content of this document chunk.")
28+
29+
30+
class WorkerInput(BaseModel):
31+
"""Input for a worker agent processing a document chunk."""
32+
chunk: DocumentChunk = Field(description="The current chunk to process.")
33+
query: str = Field(description="The query or task to be answered.")
34+
previous_findings: str = Field(
35+
default="",
36+
description="Accumulated findings from previous workers."
37+
)
38+
39+
40+
class WorkerOutput(BaseModel):
41+
"""Output from a worker agent containing findings and evidence."""
42+
findings: str = Field(
43+
description="Key findings and information extracted from this chunk."
44+
)
45+
evidence: List[str] = Field(
46+
default_factory=list,
47+
description="Supporting evidence or quotes from the chunk."
48+
)
49+
message_for_next: str = Field(
50+
description="Message to pass to the next worker with relevant context."
51+
)
52+
53+
54+
class ManagerInput(BaseModel):
55+
"""Input for the manager agent to generate final response."""
56+
query: str = Field(description="The original query to answer.")
57+
accumulated_findings: str = Field(
58+
description="All findings accumulated through the worker chain."
59+
)
60+
61+
62+
class ManagerOutput(BaseModel):
63+
"""Final output from the manager agent."""
64+
answer: str = Field(description="The final answer to the query.")
65+
reasoning: str = Field(description="Explanation of how the answer was derived.")
66+
supporting_evidence: List[str] = Field(
67+
default_factory=list,
68+
description="Key evidence supporting the answer."
69+
)
70+
71+
72+
@workflowai.agent(id='document-worker', model=Model.GPT_4O_MINI_LATEST)
73+
async def worker_agent(input: WorkerInput) -> WorkerOutput:
74+
"""
75+
Process your assigned document chunk to:
76+
1. Extract relevant information related to the query
77+
2. Build upon findings from previous workers
78+
3. Pass important context to the next worker
79+
80+
Be concise but thorough in your analysis.
81+
Focus on information that could be relevant to the query.
82+
"""
83+
...
84+
85+
86+
@workflowai.agent(id='document-manager', model=Model.CLAUDE_3_5_SONNET_LATEST)
87+
async def manager_agent(input: ManagerInput) -> ManagerOutput:
88+
"""
89+
Synthesize all findings from the worker agents to:
90+
1. Generate a comprehensive answer to the query
91+
2. Provide clear reasoning for your answer
92+
3. Include supporting evidence from the document
93+
94+
Ensure your answer is well-supported by the accumulated findings.
95+
"""
96+
...
97+
98+
99+
async def process_long_document(
100+
document: str,
101+
query: str,
102+
chunk_size: int = 2000
103+
) -> ManagerOutput:
104+
"""
105+
Process a long document using Chain of Agents pattern:
106+
1. Split document into chunks
107+
2. Have worker agents process each chunk sequentially
108+
3. Pass findings through the chain
109+
4. Have manager agent synthesize final answer
110+
"""
111+
# Split document into chunks
112+
chunks = [
113+
document[i:i + chunk_size]
114+
for i in range(0, len(document), chunk_size)
115+
]
116+
117+
# Convert to DocumentChunk objects
118+
doc_chunks = [DocumentChunk(content=chunk) for chunk in chunks]
119+
120+
# Initialize accumulator for findings
121+
accumulated_findings = ""
122+
123+
# Process chunks sequentially through worker chain
124+
for chunk in doc_chunks:
125+
worker_input = WorkerInput(
126+
chunk=chunk,
127+
query=query,
128+
previous_findings=accumulated_findings
129+
)
130+
131+
# Get worker's output
132+
worker_output = await worker_agent(worker_input)
133+
134+
# Accumulate findings
135+
if accumulated_findings:
136+
accumulated_findings += "\n\n"
137+
accumulated_findings += f"Findings:\n{worker_output.findings}"
138+
139+
if worker_output.evidence:
140+
accumulated_findings += "\nEvidence:\n- "
141+
accumulated_findings += "\n- ".join(worker_output.evidence)
142+
143+
# Have manager synthesize final answer
144+
manager_input = ManagerInput(
145+
query=query,
146+
accumulated_findings=accumulated_findings
147+
)
148+
149+
return await manager_agent(manager_input)
150+
151+
152+
async def main():
153+
# Example long document
154+
document = """
155+
The Industrial Revolution was a period of major industrialization and innovation during the late 18th and early 19th centuries. It began in Britain and later spread to other parts of the world. This era marked a major turning point in human history, fundamentally changing economic and social organization. Steam power, mechanization, and new manufacturing processes revolutionized production methods. The introduction of new technologies and manufacturing techniques led to unprecedented increases in productivity and efficiency.
156+
157+
The development of new manufacturing processes led to significant changes in how goods were produced. The factory system replaced cottage industries, bringing workers into centralized locations. New iron production processes using coke instead of charcoal dramatically increased output. Textile manufacturing was transformed by inventions like the spinning jenny and power loom. These changes enabled mass production of goods at unprecedented scales. The mechanization of agriculture through innovations like the seed drill and threshing machine reduced the labor needed for farming while increasing food production.
158+
159+
Social and economic impacts were profound, affecting both urban and rural life. Cities grew rapidly as people moved from rural areas to work in factories. Working conditions were often harsh, with long hours, dangerous conditions, and child labor being common. A new middle class emerged, while traditional skilled craftsmen often struggled. Living conditions in industrial cities were frequently overcrowded and unsanitary, leading to disease outbreaks. The rise of labor movements and trade unions began in response to poor working conditions and low wages. Education systems were developed to provide workers with basic literacy and numeracy skills needed in the new industrial economy.
160+
161+
Environmental consequences became apparent as industrialization progressed. Coal burning led to severe air pollution in industrial cities, creating smog and respiratory problems. Rivers became contaminated with industrial waste and raw sewage. Deforestation increased as wood was needed for construction and fuel. The landscape was transformed by mines, factories, and expanding urban areas. These changes marked the beginning of large-scale human impact on the environment, leading to problems that would only be recognized and addressed much later.
162+
163+
Transportation and communication systems underwent revolutionary changes during this period. The development of railways, steam-powered ships, and improved road networks facilitated the movement of goods and people. The telegraph enabled rapid long-distance communication for the first time. These advances in transportation and communication helped create larger markets and more integrated economies.
164+
165+
The Industrial Revolution also had significant cultural and intellectual impacts. Scientific and technological progress led to increased faith in human capability and reason. The Enlightenment ideals of progress and rationality found practical expression in industrial innovations. New forms of urban culture emerged, while traditional rural ways of life declined. The period saw the rise of new philosophical and political movements, including socialism, in response to industrial conditions.
166+
167+
Public health and medicine saw both challenges and advances during this period. The concentration of population in cities led to serious health problems, including cholera epidemics and tuberculosis outbreaks. However, these challenges eventually spurred improvements in urban sanitation and medical knowledge. The development of public health systems and modern medical practices can be traced to this era.
168+
169+
The Industrial Revolution's impact on agriculture extended beyond mechanization. New farming techniques and crop rotation methods increased agricultural productivity. The application of scientific principles to farming led to improved livestock breeding and crop yields. These agricultural advances were necessary to feed growing urban populations and free up labor for industrial work.
170+
171+
The financial and business systems also evolved significantly. New forms of business organization, such as joint-stock companies, emerged to handle larger-scale industrial operations. Banking and credit systems expanded to provide capital for industrial growth. Insurance companies developed to manage the risks of industrial enterprises. These financial innovations helped fuel continued industrial expansion.
172+
173+
The role of women in society began to change during this period. While many women worked in factories under difficult conditions, the Industrial Revolution also created new opportunities for women's employment in sectors like textile manufacturing. Middle-class women often found themselves managing increasingly complex households. The seeds of women's rights movements were planted during this era.
174+
175+
The global impact of the Industrial Revolution was profound and long-lasting. As industrialization spread from Britain to other countries, it created new patterns of international trade and competition. Colonial empires expanded as industrial nations sought raw materials and markets. The technological and economic gaps between industrialized and non-industrialized regions grew, shaping global relationships that persist to the present day.
176+
177+
The Industrial Revolution's legacy continues to influence modern society. Many current environmental challenges, including climate change, can be traced to the industrial practices established during this period. Modern labor laws, education systems, and urban planning still reflect responses to Industrial Revolution conditions. Understanding this transformative period helps explain many aspects of contemporary life and the ongoing challenges we face.
178+
"""
179+
180+
query = "What were the major environmental impacts of the Industrial Revolution?"
181+
182+
result = await process_long_document(document, query)
183+
184+
print("\n=== Query ===")
185+
print(query)
186+
187+
print("\n=== Answer ===")
188+
print(result.answer)
189+
190+
print("\n=== Reasoning ===")
191+
print(result.reasoning)
192+
193+
if result.supporting_evidence:
194+
print("\n=== Supporting Evidence ===")
195+
for evidence in result.supporting_evidence:
196+
print(f"- {evidence}")
197+
198+
199+
if __name__ == "__main__":
200+
asyncio.run(main())

0 commit comments

Comments
 (0)