pocketflow 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 490463d8d52e70e815ca1a168f6898f63635598a974345986fe56d7455b5de3c
4
+ data.tar.gz: 4a1a7e3f49c36db3d280cc3ceb7851f291b542fbb1118a9caf458ec071622a64
5
+ SHA512:
6
+ metadata.gz: 6ad329a5dc7bac6d51ffc071823bc2f823d7627ba06bdb9d33bf2f87ad6740e03be97b5e957b0e2f23a886a27e7f569f39bfb97f619cfe0836fa0b4d90269963
7
+ data.tar.gz: 85df02a0643c70785e7f23943494ed6bd8905461206ed2c00ca910d3efae20cb93effd9bb91444a162c693c0d1cf3bf67471af8dd0a44740377f89f054e58d43
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,45 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Victor Duarte and Zachary Huang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ The MIT License (MIT)
26
+
27
+ Copyright (c) 2025 Jonathan Hoyt
28
+
29
+ Permission is hereby granted, free of charge, to any person obtaining a copy
30
+ of this software and associated documentation files (the "Software"), to deal
31
+ in the Software without restriction, including without limitation the rights
32
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33
+ copies of the Software, and to permit persons to whom the Software is
34
+ furnished to do so, subject to the following conditions:
35
+
36
+ The above copyright notice and this permission notice shall be included in
37
+ all copies or substantial portions of the Software.
38
+
39
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
42
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,253 @@
1
+ # PocketFlow Ruby
2
+
3
+ PocketFlow Ruby is a minimal, synchronous workflow library for Ruby 3.4+, **ported from the excellent [PocketFlow project](https://github.com/The-Pocket/PocketFlow)** by [The Pocket](https://www.thepocket.io/). This version draws inspiration primarily from the TypeScript implementation and reimagines it using idiomatic Ruby and plain-old Ruby objects. It aims to maintain API consistency across languages while being lightweight and extensible.
4
+
5
+ > [!NOTE]
6
+ > This library is a community-maintained port and is not affiliated with or officially supported by the original PocketFlow maintainers.
7
+
8
+ All "parallel" variants currently run sequentially, making it safe to adopt now and evolve toward concurrency later without breaking consumers.
9
+
10
+ ## Getting Started
11
+
12
+ Add PocketFlow to your `Gemfile`:
13
+
14
+ ```ruby
15
+ gem "pocketflow"
16
+ ```
17
+
18
+ Then install via Bundler:
19
+
20
+ ```bash
21
+ bundle install
22
+ ```
23
+
24
+ ## Core Abstractions
25
+
26
+ PocketFlow is built around a handful of simple, composable concepts:
27
+
28
+ - **BaseNode**: The fundamental unit of work, following a `prep → exec → post` lifecycle. Successor nodes are linked via actions.
29
+ - **Node**: Extends `BaseNode` with configurable retry and wait behavior around `exec` (via `max_retries` and `wait`).
30
+ - **BatchNode**: Processes an array of items sequentially, applying `exec` to each element.
31
+ - **ParallelBatchNode**: API-compatible with `BatchNode`; runs sequentially for now.
32
+ - **Flow**: Orchestrates a graph of linked nodes, starting from a root node and following action-based transitions.
33
+ - **BatchFlow**: Executes a flow once per parameter set returned by `prep`, useful for batch processing.
34
+ - **ParallelBatchFlow**: API-compatible with `BatchFlow`; runs sequentially for now.
35
+
36
+ ## Examples
37
+
38
+ ### Hello World
39
+
40
+ ```ruby
41
+ require "pocketflow"
42
+
43
+ class HelloNode < Pocketflow::Node
44
+ def exec(_)
45
+ puts "hello, world"
46
+ end
47
+ end
48
+
49
+ Pocketflow::Flow.new(HelloNode.new).run({})
50
+ ```
51
+
52
+ ```mermaid
53
+ flowchart LR
54
+ HelloNode[HelloNode] --> Flow[Flow]
55
+ ```
56
+
57
+ ### Question-Answer (QA) Pattern
58
+
59
+ ```ruby
60
+ require "pocketflow"
61
+
62
+ # Define the nodes
63
+ class GetQuestionNode < Pocketflow::Node
64
+ def initialize(question)
65
+ @question = question
66
+ super()
67
+ end
68
+ def exec(_)
69
+ @question
70
+ end
71
+ def post(shared, _prep, question)
72
+ shared[:question] = question
73
+ "default"
74
+ end
75
+ end
76
+
77
+ class AnswerNode < Pocketflow::Node
78
+ def prep(shared)
79
+ shared[:question] || ""
80
+ end
81
+ def exec(question)
82
+ # Simple QA logic / LLM call
83
+ if question.include?("PocketFlow")
84
+ "PocketFlow is a TypeScript library for building reliable AI pipelines."
85
+ else
86
+ "I don't know the answer to that question."
87
+ end
88
+ end
89
+ def post(shared, _prep, answer)
90
+ shared[:answer] = answer
91
+ nil
92
+ end
93
+ end
94
+
95
+ # Build and run the flow
96
+ flow = Pocketflow::Flow.new(
97
+ GetQuestionNode.new("What is PocketFlow?")
98
+ .next(AnswerNode.new)
99
+ )
100
+ shared = {}
101
+ flow.run(shared)
102
+ puts shared[:answer]
103
+ ```
104
+
105
+ ```mermaid
106
+ flowchart LR
107
+ GetQuestionNode[GetQuestionNode] --> AnswerNode[AnswerNode]
108
+ ```
109
+
110
+
111
+ ### Retrieval-Augmented Generation (RAG) Pattern
112
+
113
+ ```ruby
114
+ require "pocketflow"
115
+
116
+ # Offline indexing
117
+ offline_flow = Pocketflow::Flow.new(
118
+ ChunkDocs.new
119
+ .next(EmbedDocs.new)
120
+ .next(StoreIndex.new)
121
+ )
122
+ shared = { files: %w[doc1.txt doc2.txt] }
123
+ offline_flow.run(shared)
124
+
125
+ # Online query and answer
126
+ online_flow = Pocketflow::Flow.new(
127
+ EmbedQuery.new
128
+ .next(RetrieveDocs.new)
129
+ .next(GenerateAnswer.new)
130
+ )
131
+ shared[:question] = "What is the content about?"
132
+ online_flow.run(shared)
133
+ puts shared[:answer]
134
+
135
+ # Combined RAG pipeline
136
+ full_flow = Pocketflow::Flow.new(
137
+ ChunkDocs.new
138
+ .next(EmbedDocs.new)
139
+ .next(StoreIndex.new)
140
+ .next(EmbedQuery.new)
141
+ .next(RetrieveDocs.new)
142
+ .next(GenerateAnswer.new)
143
+ )
144
+ shared = { files: %w[doc1.txt doc2.txt], question: "What is the content about?" }
145
+ full_flow.run(shared)
146
+ puts shared[:answer]
147
+ ```
148
+
149
+ #### Offline Flow
150
+
151
+ ```mermaid
152
+ flowchart LR
153
+ ChunkDocs[ChunkDocs] --> EmbedDocs[EmbedDocs] --> StoreIndex[StoreIndex]
154
+ ```
155
+
156
+ #### Online Flow
157
+
158
+ ```mermaid
159
+ flowchart LR
160
+ EmbedQuery[EmbedQuery] --> RetrieveDocs[RetrieveDocs] --> GenerateAnswer[GenerateAnswer]
161
+ ```
162
+
163
+ ### MapReduce Pattern
164
+
165
+ ```ruby
166
+ require "pocketflow"
167
+
168
+ # Summarize multiple files
169
+ flow = Pocketflow::Flow.new(
170
+ SummarizeAllFiles.new
171
+ .on("summarized", CombineSummaries.new)
172
+ )
173
+ shared = { files: { 'file1.txt' => '...', 'file2.txt' => '...', 'file3.txt' => '...' } }
174
+ flow.run(shared)
175
+ puts shared[:all_files_summary]
176
+ ```
177
+
178
+ ```mermaid
179
+ flowchart LR
180
+ SummarizeAllFiles[SummarizeAllFiles] --> CombineSummaries[CombineSummaries]
181
+ ```
182
+
183
+ ```ruby
184
+ # Map and reduce text transformation
185
+ flow = Pocketflow::Flow.new(
186
+ MapChunks.new
187
+ .on("mapped", ReduceResults.new)
188
+ )
189
+ shared = { text_to_process: 'This is a sample text to process.' }
190
+ flow.run(shared)
191
+ puts shared[:final_result]
192
+ ```
193
+
194
+ ```mermaid
195
+ flowchart LR
196
+ MapChunks[MapChunks] --> ReduceResults[ReduceResults]
197
+ ```
198
+
199
+ ### Multi-Agent Pattern
200
+
201
+ ```ruby
202
+ require "pocketflow"
203
+
204
+ # Simple message listener loop
205
+ listener = ListenerAgent.new.on("continue", ListenerAgent.new)
206
+ flow = Pocketflow::Flow.new(listener)
207
+ shared = { messages: ["msg1", "msg2", "msg3"], processed_messages: [] }
208
+ flow.run(shared)
209
+ puts shared[:processed_messages]
210
+ ```
211
+
212
+ ```mermaid
213
+ flowchart LR
214
+ ListenerAgent[ListenerAgent] --> ListenerAgent[ListenerAgent]
215
+ ```
216
+
217
+ ```ruby
218
+ # Taboo-style hint and guess agents
219
+ hinter = Hinter.new.on("continue_hinter", Hinter.new)
220
+ guesser = Guesser.new.on("continue_guesser", Guesser.new)
221
+ hinter_flow = Pocketflow::Flow.new(hinter)
222
+ guesser_flow = Pocketflow::Flow.new(guesser)
223
+ shared = {
224
+ target_word: "popsicle",
225
+ forbidden_words: %w[ice cream frozen stick summer],
226
+ past_guesses: [],
227
+ hinter_queue: ["start_game"],
228
+ guesser_queue: [],
229
+ game_over: false,
230
+ max_rounds: 3,
231
+ current_round: 0
232
+ }
233
+ until shared[:game_over]
234
+ hinter_flow.run(shared)
235
+ guesser_flow.run(shared)
236
+
237
+ until shared[:game_over]
238
+ puts shared[:past_guesses]
239
+ ```
240
+
241
+ ```mermaid
242
+ flowchart LR
243
+ Hinter[Hinter] -->|continue_hinter| Hinter[Hinter]
244
+ Guesser[Guesser] -->|continue_guesser| Guesser[Guesser]
245
+ ```
246
+
247
+ ## Contributing
248
+
249
+ Contributions and feedback are welcome — please fork the repository and open a pull request.
250
+
251
+ ## License
252
+
253
+ This project is licensed under the MIT License - see the LICENSE.txt file for details.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ task default: %i[test]
data/lib/pocketflow.rb ADDED
@@ -0,0 +1,293 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Public: Pocketflow – A tiny, synchronous workflow library for Ruby 3.4+.
4
+ #
5
+ # The library mirrors sibling implementations in TypeScript, Python, Go and
6
+ # Java while embracing plain‑old Ruby objects and language idioms. All "parallel"
7
+ # variants share the same public surface as their concurrent cousins but run
8
+ # sequentially for now so that real parallelism can be introduced later without
9
+ # breaking consumers.
10
+ #
11
+ # Examples
12
+ #
13
+ # require_relative "pocketflow"
14
+ #
15
+ # class HelloNode < Pocketflow::Node
16
+ # def exec(*)
17
+ # puts "hello, world"
18
+ # end
19
+ # end
20
+ #
21
+ # Pocketflow::Flow.new(HelloNode.new).run({})
22
+ #
23
+ # Returns nothing.
24
+ module Pocketflow
25
+ VERSION = "1.0.0"
26
+
27
+ # Public: Default action name used when a node's +post+ does not specify one.
28
+ DEFAULT_ACTION = "default"
29
+
30
+ # Public: BaseNode is the minimal building block of a Pocketflow graph.
31
+ #
32
+ # A node's lifecycle is **prep → exec → post**. Override those hooks to
33
+ # perform work. Successor nodes are linked via {#next} or {#on}.
34
+ class BaseNode
35
+ # Public: Arbitrary parameters for the node.
36
+ attr_accessor :params
37
+
38
+ # Internal: Action → successor node mapping.
39
+ attr_reader :successors
40
+
41
+ # Public: Create a node.
42
+ #
43
+ # Returns the new BaseNode.
44
+ def initialize
45
+ @params = {}
46
+ @successors = {}
47
+ end
48
+
49
+ # Public: Replace the parameter hash.
50
+ #
51
+ # params - The Hash of parameters (may be nil).
52
+ #
53
+ # Returns the node itself.
54
+ def set_params(params)
55
+ @params = params || {}
56
+ self
57
+ end
58
+
59
+ # Public: Connect this node to another node for a given action.
60
+ #
61
+ # node - The BaseNode successor.
62
+ # action - The String action name (default: DEFAULT_ACTION).
63
+ #
64
+ # Returns the given node.
65
+ def next(node, action = DEFAULT_ACTION)
66
+ on(action, node)
67
+ node
68
+ end
69
+
70
+ alias >> next
71
+
72
+ # Public: Define (or overwrite) a successor for an action.
73
+ #
74
+ # action - The String action name.
75
+ # node - The BaseNode successor.
76
+ #
77
+ # Returns the node itself.
78
+ def on(action, node)
79
+ warn "Overwriting successor for action '#{action}'" if @successors.key?(action)
80
+ @successors[action] = node
81
+ self
82
+ end
83
+
84
+ # Public: Prepare for execution. Override in subclasses.
85
+ #
86
+ # shared - The shared context passed through the entire flow.
87
+ #
88
+ # Returns an arbitrary prep object.
89
+ def prep(shared) = nil
90
+
91
+ # Public: Perform the primary work. Override in subclasses.
92
+ #
93
+ # prep_res - The value returned by +prep+.
94
+ #
95
+ # Returns an arbitrary execution result.
96
+ def exec(prep_res) = nil
97
+
98
+ # Public: Process results and decide the next action. Override in subclasses.
99
+ #
100
+ # shared - The shared context.
101
+ # prep_res - The object returned by +prep+.
102
+ # exec_res - The object returned by +exec+.
103
+ #
104
+ # Returns the String action name or +nil+ / DEFAULT_ACTION.
105
+ def post(shared, prep_res, exec_res) = nil
106
+
107
+ # Internal: Wrapper around the node lifecycle.
108
+ #
109
+ # shared - The shared context.
110
+ #
111
+ # Returns the action String (or nil).
112
+ def run_internal(shared)
113
+ prep_res = prep(shared)
114
+ exec_res = exec_internal(prep_res)
115
+ post(shared, prep_res, exec_res)
116
+ end
117
+
118
+ # Internal: Wrapper around +exec+. Subclasses override to inject retry
119
+ # logic.
120
+ #
121
+ # prep_res - The object returned by +prep+.
122
+ #
123
+ # Returns whatever +exec+ returns.
124
+ def exec_internal(prep_res) = exec(prep_res)
125
+
126
+ # Public: Execute this node as a standalone unit.
127
+ #
128
+ # shared - The shared context.
129
+ #
130
+ # Returns the action String (or nil).
131
+ def run(shared)
132
+ warn "Node won't run successors. Use Flow." unless @successors.empty?
133
+ run_internal(shared)
134
+ end
135
+
136
+ # Internal: Retrieve the successor for an action.
137
+ #
138
+ # action - The String action name (default: DEFAULT_ACTION).
139
+ #
140
+ # Returns the BaseNode successor or nil.
141
+ def get_next_node(action = DEFAULT_ACTION)
142
+ action = DEFAULT_ACTION if action.nil? || action.empty?
143
+ next_node = @successors[action]
144
+ warn "Flow ends: '#{action}' not found in #{successors.keys}" if next_node.nil? && !@successors.empty?
145
+ next_node
146
+ end
147
+
148
+ # Internal: Shallow‑clone the node so that params/successors are isolated.
149
+ #
150
+ # Returns the cloned BaseNode.
151
+ def clone
152
+ # Use Object#clone to preserve singleton methods; shallow-copy params and successors
153
+ cloned = super
154
+ cloned.params = @params.dup
155
+ cloned.instance_variable_set(:@successors, @successors.dup)
156
+ cloned
157
+ end
158
+ end
159
+
160
+ # Public: Node adds retry/wait behaviour around BaseNode#exec.
161
+ class Node < BaseNode
162
+ attr_reader :max_retries, :wait, :current_retry
163
+
164
+ # Public: Build a Node.
165
+ #
166
+ # max_retries - The Integer attempts per execution (minimum 1).
167
+ # wait - The Numeric seconds between retries.
168
+ #
169
+ # Returns the new Node.
170
+ def initialize(max_retries: 1, wait: 0)
171
+ super()
172
+ @max_retries = [max_retries, 1].max
173
+ @wait = [wait, 0].max
174
+ @current_retry = 0
175
+ end
176
+
177
+ # Public: Called after all retries fail. Override to customise behaviour.
178
+ #
179
+ # prep_res - The object returned by +prep+.
180
+ # error - The Exception raised by the last attempt.
181
+ #
182
+ # Returns an execution result or raises.
183
+ def exec_fallback(prep_res, error)
184
+ raise error
185
+ end
186
+
187
+ # Internal: Retry wrapper around +exec+.
188
+ def exec_internal(prep_res)
189
+ @current_retry = 0
190
+ while @current_retry < @max_retries
191
+ begin
192
+ return exec(prep_res)
193
+ rescue StandardError => e
194
+ if @current_retry == @max_retries - 1
195
+ return exec_fallback(prep_res, e)
196
+ end
197
+ sleep @wait if @wait.positive?
198
+ ensure
199
+ @current_retry += 1
200
+ end
201
+ end
202
+ end
203
+ end
204
+
205
+ # Public: BatchNode executes Node#exec_internal once per item.
206
+ class BatchNode < Node
207
+ # Internal: Sequentially process an Array of items.
208
+ def exec_internal(items)
209
+ return [] unless items.is_a?(Array)
210
+ items.map { |item| super(item) }
211
+ end
212
+ end
213
+
214
+ # Public: ParallelBatchNode matches BatchNode's API; runs sequentially for now.
215
+ class ParallelBatchNode < Node
216
+ # Internal: Sequentially process an Array of items.
217
+ def exec_internal(items)
218
+ return [] unless items.is_a?(Array)
219
+ items.map { |item| super(item) }
220
+ end
221
+ end
222
+
223
+ # Public: Flow orchestrates the execution of a linked chain of nodes.
224
+ class Flow < BaseNode
225
+ attr_reader :start
226
+
227
+ # Public: Build a Flow.
228
+ #
229
+ # start - The BaseNode that begins the graph.
230
+ #
231
+ # Returns the new Flow.
232
+ def initialize(start)
233
+ super()
234
+ @start = start
235
+ end
236
+
237
+ # Internal: Execute the graph beginning at +@start+.
238
+ #
239
+ # shared - The shared context.
240
+ # params - A Hash of parameters to merge into each node (optional).
241
+ #
242
+ # Returns nothing.
243
+ def orchestrate_internal(shared, params = nil)
244
+ current = @start.clone
245
+ effective_params = params || @params
246
+
247
+ while current
248
+ current.set_params(effective_params)
249
+ action = current.run_internal(shared)
250
+ current = current.get_next_node(action)&.clone
251
+ end
252
+ end
253
+
254
+ # Internal: Flow's lifecycle wrapper.
255
+ def run_internal(shared)
256
+ prep_res = prep(shared)
257
+ orchestrate_internal(shared)
258
+ post(shared, prep_res, nil)
259
+ end
260
+
261
+ # Public: Flows cannot be executed via +exec+.
262
+ def exec(*)
263
+ raise "Flow can't exec directly."
264
+ end
265
+ end
266
+
267
+ # Public: BatchFlow runs its flow once for every parameter‑set yielded by +prep+.
268
+ class BatchFlow < Flow
269
+ # Internal: Run the batch flow.
270
+ def run_internal(shared)
271
+ batch_params = prep(shared) || []
272
+ batch_params.each do |bp|
273
+ orchestrate_internal(shared, @params.merge(bp.to_h))
274
+ end
275
+ post(shared, batch_params, nil)
276
+ end
277
+
278
+ # Public: Override to supply an Array of Hash‑like parameter sets.
279
+ def prep(shared) = []
280
+ end
281
+
282
+ # Public: ParallelBatchFlow mirrors BatchFlow; execution is sequential.
283
+ class ParallelBatchFlow < BatchFlow
284
+ # Internal: Run the batch flow sequentially.
285
+ def run_internal(shared)
286
+ batch_params = prep(shared) || []
287
+ batch_params.each do |bp|
288
+ orchestrate_internal(shared, @params.merge(bp.to_h))
289
+ end
290
+ post(shared, batch_params, nil)
291
+ end
292
+ end
293
+ end
metadata ADDED
@@ -0,0 +1,49 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pocketflow
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Jonathan Hoyt
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-05-05 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Pocket Flow: A minimalist LLM framework. Let Agents build Agents!'
13
+ email:
14
+ - jonmagic@gmail.com
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - CODE_OF_CONDUCT.md
20
+ - LICENSE.txt
21
+ - README.md
22
+ - Rakefile
23
+ - lib/pocketflow.rb
24
+ homepage: https://github.com/jonmagic/PocketFlow-Ruby
25
+ licenses:
26
+ - MIT
27
+ metadata:
28
+ homepage_uri: https://github.com/jonmagic/PocketFlow-Ruby
29
+ source_code_uri: https://github.com/jonmagic/PocketFlow-Ruby
30
+ changelog_uri: https://github.com/jonmagic/PocketFlow-Ruby
31
+ rdoc_options: []
32
+ require_paths:
33
+ - lib
34
+ required_ruby_version: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: 3.1.0
39
+ required_rubygems_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '0'
44
+ requirements: []
45
+ rubygems_version: 3.6.6
46
+ specification_version: 4
47
+ summary: pocketflow.rb is a Ruby port of the original Python version - a minimalist
48
+ LLM framework.
49
+ test_files: []