-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
352 lines (283 loc) · 11.9 KB
/
main.py
File metadata and controls
352 lines (283 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""openarmature demo: enrich a lunar-mission news article with three
independent analyses running concurrently.
**Use case:** Given a news article about a lunar mission, produce three
side-by-side outputs: a one-sentence summary, an overall sentiment label,
and a short list of topic tags. The three analyses don't depend on each
other, so dispatch them in parallel. Each analysis is its own subgraph
with its own state schema (the summary subgraph doesn't care about
sentiment, the topic extractor doesn't care about either); which is
exactly the shape parallel-branches is for.
Where fan-out (the fan-out-with-retry example) runs N copies of ONE subgraph against
different inputs, parallel-branches runs M heterogeneous subgraphs
against the same input. Different schemas, different middleware,
different topologies per branch; one dispatch.
**What's interesting in the implementation:**
- ``GraphBuilder.add_parallel_branches_node`` registers M
``BranchSpec``s under named keys (``summary``, ``sentiment``,
``topics`` here). Each spec carries its own compiled subgraph,
its own input/output projection, and optionally its own middleware.
- The branches have DIFFERENT state schemas. The summary subgraph's
state has a ``summary`` field; the sentiment subgraph's has a
``label`` field; the topics subgraph's has a ``tags`` list. Each is
scoped to its job. The projection mapping translates the parent's
``article`` into each branch's input field name.
- The sentiment branch wraps its subgraph in ``RetryMiddleware`` to
show per-branch middleware composition. The other two branches run
bare. Per-branch middleware is heterogeneous; branch A may have
retry + timing, branch B nothing, branch C something custom.
- Branch insertion order determines fan-in order: when two branches
contribute to the same parent field, the parent's reducer applies
them in the order the branches were declared in the ``branches``
mapping (not in completion order). The three branches here write
disjoint parent fields, so the order doesn't affect the result,
but the property holds and would matter if they overlapped.
- A ``branch_attribution_observer`` reads ``NodeEvent.branch_name``
on inner-node events. ``branch_name`` is populated only for
events INSIDE a branch's subgraph; outermost nodes (receive,
enrich, present) have ``branch_name=None``. This is the
per-event attribution that lets observability backends route
metrics / spans by branch.
**Configuration** (env vars; OpenAI defaults shown):
- ``LLM_BASE_URL`` defaults to ``https://api.openai.com``. **Host root only.**
- ``LLM_MODEL`` defaults to ``gpt-4o-mini``.
- ``LLM_API_KEY`` required (empty for local servers that don't authenticate).
Run with:
uv sync --group examples
cd examples/parallel-branches
LLM_API_KEY=sk-... uv run python main.py
"""
from __future__ import annotations
import asyncio
import os
import time
from collections.abc import Mapping
from typing import Annotated, Any
from pydantic import Field
from openarmature.graph import (
END,
BranchSpec,
CompiledGraph,
GraphBuilder,
NodeEvent,
ObserverEvent,
State,
append,
)
from openarmature.graph.middleware import (
RetryConfig,
RetryMiddleware,
deterministic_backoff,
)
from openarmature.llm import OpenAIProvider, SystemMessage, UserMessage
_provider_instance: OpenAIProvider | None = None
def _get_provider() -> OpenAIProvider:
global _provider_instance
if _provider_instance is None:
_provider_instance = OpenAIProvider(
base_url=os.environ.get("LLM_BASE_URL", "https://api.openai.com"),
model=os.environ.get("LLM_MODEL", "gpt-4o-mini"),
api_key=os.environ.get("LLM_API_KEY") or None,
)
return _provider_instance
async def _chat(system: str, user: str) -> str:
response = await _get_provider().complete(
[SystemMessage(content=system), UserMessage(content=user)],
)
return (response.message.content or "").strip()
# ---------------------------------------------------------------------------
# Sample article. A real app would pull this from a feed, a queue, an API.
# ---------------------------------------------------------------------------
ARTICLE = (
"NASA's Artemis II crew capsule Integrity splashed down in the Pacific "
"Ocean this evening, ending a ten-day flight that carried four "
"astronauts on a free-return trajectory around the Moon and back. The "
"flight was the first crewed mission beyond low Earth orbit since "
"Apollo 17 in 1972. Agency officials described the result as a "
"successful test of the Orion spacecraft's deep-space systems and "
"cautioned that the Artemis III surface-landing timeline remains "
"dependent on the on-ground refurbishment cadence and lander-system "
"milestones. Even so, the splashdown was greeted with relief by "
"partner space agencies and renewed calls in policy circles for "
"sustained federal funding of the lunar return program."
)
# ---------------------------------------------------------------------------
# State schemas
# ---------------------------------------------------------------------------
class ArticleState(State):
"""Outer: an article goes in, three enrichment fields come out."""
article: str = ""
summary: str = ""
sentiment: str = ""
topics: list[str] = Field(default_factory=list)
trace: Annotated[list[str], append] = Field(default_factory=list)
class SummaryState(State):
"""Summary branch: one-sentence rewrite of the article."""
text: str = ""
summary: str = ""
class SentimentState(State):
"""Sentiment branch: overall tone of the article."""
text: str = ""
label: str = ""
class TopicsState(State):
"""Topics branch: a short list of topic tags."""
text: str = ""
tags: list[str] = Field(default_factory=list)
# ---------------------------------------------------------------------------
# Branch subgraphs; each is one node, but each has its own scope.
# ---------------------------------------------------------------------------
async def write_summary(s: SummaryState) -> Mapping[str, Any]:
content = await _chat(
system=("Summarize the article in one tight sentence (~20 words). No preamble, no quoting."),
user=s.text,
)
return {"summary": content}
async def classify_sentiment(s: SentimentState) -> Mapping[str, Any]:
content = await _chat(
system=(
"Classify the overall sentiment of the article. Reply with ONE "
"word from this set: positive, negative, neutral, mixed. "
"Lowercase, no punctuation."
),
user=s.text,
)
label = content.strip().lower().strip(".")
return {"label": label}
async def extract_topics(s: TopicsState) -> Mapping[str, Any]:
content = await _chat(
system=(
"Extract three short topic tags for the article. Reply with "
"exactly three lines, one tag per line, no numbering or bullets. "
"Tags should be 1-3 words each."
),
user=s.text,
)
tags = [line.strip(" -*•\t") for line in content.splitlines() if line.strip()][:3]
return {"tags": tags}
def build_summary_subgraph() -> CompiledGraph[SummaryState]:
return (
GraphBuilder(SummaryState)
.add_node("write_summary", write_summary)
.add_edge("write_summary", END)
.set_entry("write_summary")
.compile()
)
def build_sentiment_subgraph() -> CompiledGraph[SentimentState]:
return (
GraphBuilder(SentimentState)
.add_node("classify_sentiment", classify_sentiment)
.add_edge("classify_sentiment", END)
.set_entry("classify_sentiment")
.compile()
)
def build_topics_subgraph() -> CompiledGraph[TopicsState]:
return (
GraphBuilder(TopicsState)
.add_node("extract_topics", extract_topics)
.add_edge("extract_topics", END)
.set_entry("extract_topics")
.compile()
)
# ---------------------------------------------------------------------------
# Outer graph
# ---------------------------------------------------------------------------
async def receive(s: ArticleState) -> Mapping[str, Any]:
del s
return {"trace": ["receive"]}
async def present(s: ArticleState) -> Mapping[str, Any]:
del s
return {"trace": ["present"]}
async def branch_attribution_observer(event: ObserverEvent) -> None:
"""Print which branch each inner-node event came from.
NodeEvent carries ``branch_name`` on events from nodes that
execute INSIDE a parallel-branches branch; it's the per-event
attribution that says "this came from branch X." Outermost-graph
nodes (receive, enrich, present) carry no branch_name. The
observer skips events with no branch attribution and prints
``(branch=…) node_name`` for the rest.
"""
if not isinstance(event, NodeEvent):
return
if event.branch_name is None or event.phase != "started":
return
print(f" [observer] (branch={event.branch_name}) inner node {event.node_name!r} started")
def build_graph() -> CompiledGraph[ArticleState]:
summary = build_summary_subgraph()
sentiment = build_sentiment_subgraph()
topics = build_topics_subgraph()
# Only the sentiment branch retries. Realistic in production: the
# classification call is short and cheap to retry, but you may not want
# the same policy on a longer summarize call (where a retry doubles
# cost) or on a topic-extract that has different transient profile.
sentiment_retry = RetryMiddleware(
RetryConfig(
max_attempts=3,
backoff=deterministic_backoff(0.2),
)
)
return (
GraphBuilder(ArticleState)
.add_node("receive", receive)
.add_parallel_branches_node(
"enrich",
branches={
"summary": BranchSpec(
subgraph=summary,
inputs={"text": "article"},
outputs={"summary": "summary"},
),
"sentiment": BranchSpec(
subgraph=sentiment,
inputs={"text": "article"},
outputs={"sentiment": "label"},
middleware=(sentiment_retry,),
),
"topics": BranchSpec(
subgraph=topics,
inputs={"text": "article"},
outputs={"topics": "tags"},
),
},
)
.add_node("present", present)
.add_edge("receive", "enrich")
.add_edge("enrich", "present")
.add_edge("present", END)
.set_entry("receive")
.compile()
)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
async def main() -> None:
graph = build_graph()
graph.attach_observer(branch_attribution_observer)
print("=" * 72)
print("Lunar-mission article enrichment; three independent analyses in parallel")
print("=" * 72)
print()
print(f"Article ({len(ARTICLE)} chars):")
print()
print(ARTICLE)
print()
wall_start = time.monotonic()
try:
final = await graph.invoke(ArticleState(article=ARTICLE))
wall_ms = (time.monotonic() - wall_start) * 1000.0
print("=" * 72)
print("Enrichment results")
print("=" * 72)
print()
print(f" summary: {final.summary}")
print(f" sentiment: {final.sentiment}")
print(f" topics: {final.topics}")
print()
print(f" wall-clock: {wall_ms:7.1f} ms")
print()
print("The three branches ran in parallel; wall-clock is closer to the")
print("slowest single branch than to the sum of all three.")
finally:
await graph.drain()
if _provider_instance is not None:
await _provider_instance.aclose()
if __name__ == "__main__":
asyncio.run(main())