### Online RAG Flow Execution Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Provides an example of how to run the `OnlineFlow`. It sets a user question in the shared context and executes the flow to get an answer. ```python # Suppose we already ran OfflineFlow and have: # shared["all_chunks"], shared["index"], etc. shared["question"] = "Why do people like cats?" OnlineFlow.run(shared) # final answer in shared["answer"] ``` -------------------------------- ### SummarizeFile Node Example - Python Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md A complete example of a Node subclass 'SummarizeFile' demonstrating prep, exec, exec_fallback, and post methods, including running the node and accessing results. ```Python class SummarizeFile(Node): def prep(self, shared): return shared["data"] def exec(self, prep_res): if not prep_res: return "Empty file content" prompt = f"Summarize this text in 10 words: {prep_res}" summary = call_llm(prompt) # might fail return summary def exec_fallback(self, prep_res, exc): # Provide a simple fallback instead of crashing return "There was an error processing your request." def post(self, shared, prep_res, exec_res): shared["summary"] = exec_res # Return "default" by not returning summarize_node = SummarizeFile(max_retries=3) # node.run() calls prep->exec->post # If exec() fails, it retries up to 3 times before calling exec_fallback() action_result = summarize_node.run(shared) print("Action returned:", action_result) # "default" print("Summary stored:", shared["summary"]) ``` -------------------------------- ### Online RAG Flow Execution Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Provides an example of how to run the `OnlineFlow`. It sets a user question in the shared context and executes the flow to get an answer. ```python # Suppose we already ran OfflineFlow and have: # shared["all_chunks"], shared["index"], etc. shared["question"] = "Why do people like cats?" OnlineFlow.run(shared) # final answer in shared["answer"] ``` -------------------------------- ### SummarizeFile Node Example - Python Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md A complete example of a Node subclass 'SummarizeFile' demonstrating prep, exec, exec_fallback, and post methods, including running the node and accessing results. ```Python class SummarizeFile(Node): def prep(self, shared): return shared["data"] def exec(self, prep_res): if not prep_res: return "Empty file content" prompt = f"Summarize this text in 10 words: {prep_res}" summary = call_llm(prompt) # might fail return summary def exec_fallback(self, prep_res, exc): # Provide a simple fallback instead of crashing return "There was an error processing your request." def post(self, shared, prep_res, exec_res): shared["summary"] = exec_res # Return "default" by not returning summarize_node = SummarizeFile(max_retries=3) # node.run() calls prep->exec->post # If exec() fails, it retries up to 3 times before calling exec_fallback() action_result = summarize_node.run(shared) print("Action returned:", action_result) # "default" print("Summary stored:", shared["summary"]) ``` -------------------------------- ### Agent Node Prompt for Dynamic Actions Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Provides an example prompt structure for an Agent node, defining CONTEXT, ACTION SPACE with descriptions and parameters, and the expected format for NEXT ACTION. This prompt guides the agent in deciding its next step. ```Python f""" ### CONTEXT Task: {task_description} Previous Actions: {previous_actions} Current State: {current_state} ### ACTION SPACE [1] search Description: Use web search to get results Parameters: - query (str): What to search for [2] answer Description: Conclude based on the results Parameters: - result (str): Final answer to provide ### NEXT ACTION Decide the next action based on the current context and available action space. Return your response in the following format: ```yaml thinking: | action: parameters: : ```""" ``` -------------------------------- ### Offline RAG Flow Execution Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Provides an example of how to run the `OfflineFlow`. It initializes the shared context with a list of files and then executes the flow. ```python shared = { "files": ["doc1.txt", "doc2.txt"], # any text files } OfflineFlow.run(shared) ``` -------------------------------- ### Offline RAG Flow Execution Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Provides an example of how to run the `OfflineFlow`. It initializes the shared context with a list of files and then executes the flow. ```python shared = { "files": ["doc1.txt", "doc2.txt"], # any text files } OfflineFlow.run(shared) ``` -------------------------------- ### Order Processing Pipeline Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md An example of a complex order processing pipeline using nested flows. It defines separate flows for payment, inventory, and shipping, and then connects these sub-flows sequentially to create a master order pipeline. ```Python # Payment processing sub-flow validate_payment >> process_payment >> payment_confirmation payment_flow = Flow(start=validate_payment) # Inventory sub-flow check_stock >> reserve_items >> update_inventory inventory_flow = Flow(start=check_stock) # Shipping sub-flow create_label >> assign_carrier >> schedule_pickup shipping_flow = Flow(start=create_label) # Connect the flows into a main order pipeline payment_flow >> inventory_flow >> shipping_flow # Create the master flow order_pipeline = Flow(start=payment_flow) ``` -------------------------------- ### Call Ollama LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates how to use the `ollama` library to interact with locally hosted LLMs. This example uses the `llama2` model and the `chat` function. ```Python from ollama import chat def call_llm(prompt): response = chat( model="llama2", messages=[{"role": "user", "content": prompt}] ) return response.message.content ``` -------------------------------- ### Python Shared Store Design Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md An example of a shared store design using a Python dictionary, demonstrating nested structures for user context and results. This serves as a data contract for nodes in a PocketFlow workflow. ```Python shared = { "user": { "id": "user123", "context": { # Another nested dict "weather": {"temp": 72, "condition": "sunny"}, "location": "San Francisco" } }, "results": {} # Empty dict to store outputs } ``` -------------------------------- ### Simple Sequence Flow Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates a minimal PocketFlow with two nodes in a sequence. The flow executes node_a, and if it returns the default action, it proceeds to node_b, after which the flow terminates. ```Python node_a >> node_b flow = Flow(start=node_a) flow.run(shared) ``` -------------------------------- ### Python Shared Store Design Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md An example of a shared store design using a Python dictionary, demonstrating nested structures for user context and results. This serves as a data contract for nodes in a PocketFlow workflow. ```Python shared = { "user": { "id": "user123", "context": { # Another nested dict "weather": {"temp": 72, "condition": "sunny"}, "location": "San Francisco" } }, "results": {} # Empty dict to store outputs } ``` -------------------------------- ### Call Ollama LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates how to use the Ollama Python client to interact with locally hosted LLMs. This example calls the 'llama2' model with a user prompt. ```Python from ollama import chat def call_llm(prompt): response = chat( model="llama2", messages=[{"role": "user", "content": prompt}] ) return response.message.content ``` -------------------------------- ### Python Async Node Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates the structure of an asynchronous Node in Pocket Flow, including methods for asynchronous preparation, execution, fallback execution, and post-execution steps. This is useful for I/O-bound tasks like fetching data or making async LLM calls. ```Python from pocketflow import AsyncNode class MyAsyncNode(AsyncNode): async def prep_async(self, shared): # Fetch data asynchronously pass async def exec_async(self, shared): # Perform async LLM call pass async def post_async(self, shared): # Await user feedback or coordinate agents pass async def exec_fallback_async(self, shared): # Fallback for async execution pass ``` -------------------------------- ### Enable Logging for LLM Calls Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Provides an example of how to integrate logging into an LLM call function. It logs the prompt before making the call and the response after receiving it, aiding in debugging and monitoring. ```Python import logging def call_llm(prompt): logging.info(f"Prompt: {prompt}") response = ... # Your implementation here logging.info(f"Response: {response}") return response ``` -------------------------------- ### Python Async Node Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates the structure of an asynchronous Node in Pocket Flow, including methods for asynchronous preparation, execution, fallback execution, and post-execution steps. This is useful for I/O-bound tasks like fetching data or making async LLM calls. ```Python from pocketflow import AsyncNode class MyAsyncNode(AsyncNode): async def prep_async(self, shared): # Fetch data asynchronously pass async def exec_async(self, shared): # Perform async LLM call pass async def post_async(self, shared): # Await user feedback or coordinate agents pass async def exec_fallback_async(self, shared): # Fallback for async execution pass ``` -------------------------------- ### Call Google Generative AI LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Provides an example of using Google's Generative AI models via the `google` library. It requires a Gemini API key and allows specifying the model for content generation. ```Python from google import genai def call_llm(prompt): client = genai.Client(api_key='GEMINI_API_KEY') response = client.models.generate_content( model='gemini-2.5-pro', contents=prompt ) return response.text ``` -------------------------------- ### Shared Store Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md A Python dictionary representing the shared data structure used within the PocketFlow nodes. It demonstrates a simple key-value pair for storing and retrieving data between nodes. ```Python shared = { "key": "value" } ``` -------------------------------- ### Python Shared Store Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates how to use a shared dictionary to pass data between nodes in a flow. The LoadData node writes content to shared['data'], and the Summarize node reads from it, processes it, and writes the summary to shared['summary']. ```python class LoadData(Node): def post(self, shared, prep_res, exec_res): # We write data to shared store shared["data"] = "Some text content" return None class Summarize(Node): def prep(self, shared): # We read data from shared store return shared["data"] def exec(self, prep_res): # Call LLM to summarize prompt = f"Summarize: {prep_res}" summary = call_llm(prompt) return summary def post(self, shared, prep_res, exec_res): # We write summary to shared store shared["summary"] = exec_res return "default" load_data = LoadData() summarize = Summarize() load_data >> summarize flow = Flow(start=load_data) shared = {} flow.run(shared) ``` -------------------------------- ### Basic Flow Nesting Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates how to nest one PocketFlow within another. A sub-flow, composed of node_a and node_b, is treated as a single node and connected to node_c in a parent flow. ```Python # Create a sub-flow node_a >> node_b subflow = Flow(start=node_a) # Connect it to another node subflow >> node_c # Create the parent flow parent_flow = Flow(start=subflow) ``` -------------------------------- ### Shared Store Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md A Python dictionary representing the shared data structure used within the PocketFlow nodes. It demonstrates a simple key-value pair for storing and retrieving data between nodes. ```Python shared = { "key": "value" } ``` -------------------------------- ### Node with Retry Logic - Python Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md An example of a Node subclass implementing the 'exec' method that includes retry logic, demonstrating how to access the current retry count. ```Python class RetryNode(Node): def exec(self, prep_res): print(f"Retry {self.cur_retry} times") raise Exception("Failed") ``` -------------------------------- ### Call Google Generative AI LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Provides an example of calling Google's Generative AI models (like Gemini) using the google-generativeai Python client. It requires a Gemini API key and specifies the model for content generation. ```Python from google import genai def call_llm(prompt): client = genai.Client(api_key='GEMINI_API_KEY') response = client.models.generate_content( model='gemini-2.5-pro', contents=prompt ) return response.text ``` -------------------------------- ### Python Shared Store Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates how to use a shared dictionary to pass data between nodes in a flow. The LoadData node writes content to shared['data'], and the Summarize node reads from it, processes it, and writes the summary to shared['summary']. ```python class LoadData(Node): def post(self, shared, prep_res, exec_res): # We write data to shared store shared["data"] = "Some text content" return None class Summarize(Node): def prep(self, shared): # We read data from shared store return shared["data"] def exec(self, prep_res): # Call LLM to summarize prompt = f"Summarize: {prep_res}" summary = call_llm(prompt) return summary def post(self, shared, prep_res, exec_res): # We write summary to shared store shared["summary"] = exec_res return "default" load_data = LoadData() summarize = Summarize() load_data >> summarize flow = Flow(start=load_data) shared = {} flow.run(shared) ``` -------------------------------- ### Node with Retry Logic - Python Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md An example of a Node subclass implementing the 'exec' method that includes retry logic, demonstrating how to access the current retry count. ```Python class RetryNode(Node): def exec(self, prep_res): print(f"Retry {self.cur_retry} times") raise Exception("Failed") ``` -------------------------------- ### Branching and Looping Flow Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Illustrates a PocketFlow for expense approval with branching and looping. The 'review' node can transition to 'payment', 'revise', or 'finish' based on its returned action. The 'revise' node loops back to 'review'. ```Python # Define the flow connections review - "approved" >> payment # If approved, process payment review - "needs_revision" >> revise # If needs changes, go to revision review - "rejected" >> finish # If rejected, finish the process revise >> review # After revision, go back for another review payment >> finish # After payment, finish the process flow = Flow(start=review) ``` -------------------------------- ### Python: Order Processing Pipeline Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md An example of composing multiple sub-flows into a master order processing pipeline. Separate flows are defined for payment processing, inventory management, and shipping. These sub-flows are then chained together sequentially to form the main 'order_pipeline'. ```python # Payment processing sub-flow validate_payment >> process_payment >> payment_confirmation payment_flow = Flow(start=validate_payment) # Inventory sub-flow check_stock >> reserve_items >> update_inventory inventory_flow = Flow(start=check_stock) # Shipping sub-flow create_label >> assign_carrier >> schedule_pickup shipping_flow = Flow(start=create_label) # Connect the flows into a main order pipeline payment_flow >> inventory_flow >> shipping_flow # Create the master flow order_pipeline = Flow(start=payment_flow) ``` -------------------------------- ### Python Params Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Illustrates how to use node-specific parameters for identifying tasks, such as filenames. The SummarizeFile node accesses its 'filename' parameter to fetch data and store results. It shows how Flow params can override node params. ```python # 1) Create a Node that uses params class SummarizeFile(Node): def prep(self, shared): # Access the node's param filename = self.params["filename"] return shared["data"].get(filename, "") def exec(self, prep_res): prompt = f"Summarize: {prep_res}" return call_llm(prompt) def post(self, shared, prep_res, exec_res): filename = self.params["filename"] shared["summary"][filename] = exec_res return "default" # 2) Set params node = SummarizeFile() # 3) Set Node params directly (for testing) node.set_params({"filename": "doc1.txt"}) node.run(shared) # 4) Create Flow flow = Flow(start=node) # 5) Set Flow params (overwrites node params) flow.set_params({"filename": "doc2.txt"}) flow.run(shared) # The node summarizes doc2, not doc1 ``` -------------------------------- ### Python Params Example Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Illustrates how to use node-specific parameters for identifying tasks, such as filenames. The SummarizeFile node accesses its 'filename' parameter to fetch data and store results. It shows how Flow params can override node params. ```python # 1) Create a Node that uses params class SummarizeFile(Node): def prep(self, shared): # Access the node's param filename = self.params["filename"] return shared["data"].get(filename, "") def exec(self, prep_res): prompt = f"Summarize: {prep_res}" return call_llm(prompt) def post(self, shared, prep_res, exec_res): filename = self.params["filename"] shared["summary"][filename] = exec_res return "default" # 2) Set params node = SummarizeFile() # 3) Set Node params directly (for testing) node.set_params({"filename": "doc1.txt"}) node.run(shared) # 4) Create Flow flow = Flow(start=node) # 5) Set Flow params (overwrites node params) flow.set_params({"filename": "doc2.txt"}) flow.run(shared) # The node summarizes doc2, not doc1 ``` -------------------------------- ### Python: Basic Flow Nesting Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates nesting a sub-flow within a parent flow. A 'subflow' is created with nodes 'node_a' and 'node_b'. This 'subflow' is then treated as a single node and connected to 'node_c'. The 'parent_flow' starts with the 'subflow'. ```python # Create a sub-flow node_a >> node_b subflow = Flow(start=node_a) # Connect it to another node subflow >> node_c # Create the parent flow parent_flow = Flow(start=subflow) ``` -------------------------------- ### Call LLM Utility Function Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md A Python function to interact with a Large Language Model (LLM) using the genai library. It takes a prompt as input and returns the LLM's response. It includes environment variable configuration for API keys and model selection, and a basic example of how to use it. ```Python from google import genai import os def call_llm(prompt: str) -> str: client = genai.Client( api_key=os.getenv("GEMINI_API_KEY", ""), ) model = os.getenv("GEMINI_MODEL", "gemini-2.5-flash") response = client.models.generate_content(model=model, contents=[prompt]) return response.text if __name__ == "__main__": test_prompt = "Hello, how are you?" # First call - should hit the API print("Making call...") response1 = call_llm(test_prompt, use_cache=False) print(f"Response: {response1}") ``` -------------------------------- ### Python: Basic Flow Definition Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Defines a simple sequential flow with two nodes, node_a and node_b. The flow starts at node_a and transitions to node_b if node_a returns the default action. The flow terminates after node_b if no further transitions are defined. ```python node_a >> node_b flow = Flow(start=node_a) flow.run(shared) ``` -------------------------------- ### Call LLM Utility Function Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md A Python function to interact with a Large Language Model (LLM) using the genai library. It takes a prompt as input and returns the LLM's response. It includes environment variable configuration for API keys and model selection, and a basic example of how to use it. ```Python from google import genai import os def call_llm(prompt: str) -> str: client = genai.Client( api_key=os.getenv("GEMINI_API_KEY", ""), ) model = os.getenv("GEMINI_MODEL", "gemini-2.5-flash") response = client.models.generate_content(model=model, contents=[prompt]) return response.text if __name__ == "__main__": test_prompt = "Hello, how are you?" # First call - should hit the API print("Making call...") response1 = call_llm(test_prompt, use_cache=False) print(f"Response: {response1}") ``` -------------------------------- ### Project Entry Point Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md The main Python script for the project, serving as the entry point. It imports and utilizes the `create_qa_flow` function to set up the application's workflow. ```Python # main.py from flow import create_qa_flow # Example main function # Please replace this with your own main function ``` -------------------------------- ### Project Entry Point Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md The main Python script for the project, serving as the entry point. It imports and utilizes the `create_qa_flow` function to set up the application's workflow. ```Python # main.py from flow import create_qa_flow # Example main function # Please replace this with your own main function ``` -------------------------------- ### Call OpenAI LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates how to make a basic call to an OpenAI language model using the OpenAI Python client. It requires an API key and specifies the model to use. Best practice suggests storing the API key in an environment variable. ```Python from openai import OpenAI def call_llm(prompt): client = OpenAI(api_key="YOUR_API_KEY_HERE") r = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": prompt}] ) return r.choices[0].message.content # Example usage call_llm("How are you?") ``` -------------------------------- ### Run Pipeline - Python Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates how to execute an entire pipeline using the 'run' method, passing shared data. This represents the top-level execution flow. ```Python order_pipeline.run(shared_data) ``` -------------------------------- ### Pipeline Execution Flow - Mermaid Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Visualizes the complete order pipeline using Mermaid syntax, showing the sequence of payment, inventory, and shipping flows. ```Mermaid flowchart LR subgraph order_pipeline[Order Pipeline] subgraph paymentFlow["Payment Flow"] A[Validate Payment] --> B[Process Payment] --> C[Payment Confirmation] end subgraph inventoryFlow["Inventory Flow"] D[Check Stock] --> E[Reserve Items] --> F[Update Inventory] end subgraph shippingFlow["Shipping Flow"] G[Create Label] --> H[Assign Carrier] --> I[Schedule Pickup] end paymentFlow --> inventoryFlow inventoryFlow --> shippingFlow end ``` -------------------------------- ### Call OpenAI LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates how to call the OpenAI API using the `openai` library. It requires an API key and specifies the model to use. Best practice suggests storing the API key in an environment variable. ```Python from openai import OpenAI def call_llm(prompt): client = OpenAI(api_key="YOUR_API_KEY_HERE") r = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": prompt}] ) return r.choices[0].message.content # Example usage call_llm("How are you?") ``` -------------------------------- ### Enhance LLM Call with Chat History Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Shows how to modify the LLM call function to accept and process chat history. This is useful for maintaining context in conversational AI applications. The example uses the OpenAI client. ```Python from openai import OpenAI def call_llm(messages): client = OpenAI(api_key="YOUR_API_KEY_HERE") r = client.chat.completions.create( model="gpt-4o", messages=messages ) return r.choices[0].message.content ``` -------------------------------- ### Summarize and Verify with AsyncNode Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates an asynchronous node that reads a document, summarizes it using an LLM, and waits for user approval before finalizing. It includes asynchronous file reading and LLM calls. ```python class SummarizeThenVerify(AsyncNode): async def prep_async(self, shared): # Example: read a file asynchronously doc_text = await read_file_async(shared["doc_path"]) return doc_text async def exec_async(self, prep_res): # Example: async LLM call summary = await call_llm_async(f"Summarize: {prep_res}") return summary async def post_async(self, shared, prep_res, exec_res): # Example: wait for user feedback decision = await gather_user_feedback(exec_res) if decision == "approve": shared["summary"] = exec_res return "approve" return "deny" summarize_node = SummarizeThenVerify() final_node = Finalize() # Define transitions summarize_node - "approve" >> final_node summarize_node - "deny" >> summarize_node # retry flow = AsyncFlow(start=summarize_node) async def main(): shared = {"doc_path": "document.txt"} await flow.run_async(shared) print("Final Summary:", shared.get("summary")) asyncio.run(main()) ``` -------------------------------- ### Pipeline Execution Flow - Mermaid Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Visualizes the complete order pipeline using Mermaid syntax, showing the sequence of payment, inventory, and shipping flows. ```Mermaid flowchart LR subgraph order_pipeline[Order Pipeline] subgraph paymentFlow["Payment Flow"] A[Validate Payment] --> B[Process Payment] --> C[Payment Confirmation] end subgraph inventoryFlow["Inventory Flow"] D[Check Stock] --> E[Reserve Items] --> F[Update Inventory] end subgraph shippingFlow["Shipping Flow"] G[Create Label] --> H[Assign Carrier] --> I[Schedule Pickup] end paymentFlow --> inventoryFlow inventoryFlow --> shippingFlow end ``` -------------------------------- ### Agent Node Prompt for Dynamic Actions Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Provides a structured prompt for an agent node to decide dynamic actions based on context, action space, and reasoning. It includes sections for context, available actions with parameters, and the expected output format for the next action. ```Python f""" ### CONTEXT Task: {task_description} Previous Actions: {previous_actions} Current State: {current_state} ### ACTION SPACE [1] search Description: Use web search to get results Parameters: - query (str): What to search for [2] answer Description: Conclude based on the results Parameters: - result (str): Final answer to provide ### NEXT ACTION Decide the next action based on the current context and available action space. Return your response in the following format: ```yaml thinking: | action: parameters: : ```""" ``` -------------------------------- ### AsyncParallelBatchNode for Parallel Summarization Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates how to implement an AsyncParallelBatchNode to process and summarize multiple texts concurrently. The `prep_async` method prepares the input texts, `exec_async` calls an LLM for summarization, and `post_async` aggregates the results. ```Python class ParallelSummaries(AsyncParallelBatchNode): async def prep_async(self, shared): # e.g., multiple texts return shared["texts"] async def exec_async(self, text): prompt = f"Summarize: {text}" return await call_llm_async(prompt) async def post_async(self, shared, prep_res, exec_res_list): shared["summary"] = "\n\n".join(exec_res_list) return "default" node = ParallelSummaries() flow = AsyncFlow(start=node) ``` -------------------------------- ### AsyncParallelBatchFlow for Concurrent File Summarization Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Illustrates the use of AsyncParallelBatchFlow to run a sub-flow concurrently for each file in a list. The `prep_async` method prepares parameters for each sub-flow execution, and the sub-flow itself handles loading and summarizing files. ```Python class SummarizeMultipleFiles(AsyncParallelBatchFlow): async def prep_async(self, shared): return [{"filename": f} for f in shared["files"]] sub_flow = AsyncFlow(start=LoadAndSummarizeFile()) parallel_flow = SummarizeMultipleFiles(start=sub_flow) await parallel_flow.run_async(shared) ``` -------------------------------- ### Run Pipeline - Python Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates how to execute an entire pipeline using the 'run' method, passing shared data. This represents the top-level execution flow. ```Python order_pipeline.run(shared_data) ``` -------------------------------- ### Summarize and Verify Async Node Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md An asynchronous node that first prepares by reading a document, then executes by summarizing the content using an LLM, and finally posts by gathering user feedback to approve or deny the summary. ```python class SummarizeThenVerify(AsyncNode): async def prep_async(self, shared): # Example: read a file asynchronously doc_text = await read_file_async(shared["doc_path"]) return doc_text async def exec_async(self, prep_res): # Example: async LLM call summary = await call_llm_async(f"Summarize: {prep_res}") return summary async def post_async(self, shared, prep_res, exec_res): # Example: wait for user feedback decision = await gather_user_feedback(exec_res) if decision == "approve": shared["summary"] = exec_res return "approve" return "deny" summarize_node = SummarizeThenVerify() final_node = Finalize() # Define transitions summarize_node - "approve" >> final_node summarize_node - "deny" >> summarize_node # retry flow = AsyncFlow(start=summarize_node) async def main(): shared = {"doc_path": "document.txt"} await flow.run_async(shared) print("Final Summary:", shared.get("summary")) asyncio.run(main()) ``` -------------------------------- ### Python Main Flow Execution Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md This Python code snippet shows the main execution logic for a Pocket Flow application. It initializes a shared dictionary, creates a QA flow, runs the flow with the shared data, and then prints the question and answer from the shared store. ```Python def main(): shared = { "question": None, # Will be populated by GetQuestionNode from user input "answer": None # Will be populated by AnswerNode } # Create the flow and run it qa_flow = create_qa_flow() qa_flow.run(shared) print(f"Question: {shared['question']}") print(f"Answer: {shared['answer']}") if __name__ == "__main__": main() ``` -------------------------------- ### List Python Dependencies Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Specifies the Python libraries required for the project to run, including PyYAML and pocketflow. ```Python PyYAML pocketflow ``` -------------------------------- ### Enable LLM Logging Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates how to integrate logging into the LLM calling function to track prompts and responses. This is helpful for debugging and monitoring LLM interactions. ```Python import logging def call_llm(prompt): logging.info(f"Prompt: {prompt}") response = ... # Your implementation here logging.info(f"Response: {response}") return response ``` -------------------------------- ### Mermaid Diagram for Flowchart Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Illustrates a basic flowchart structure using Mermaid syntax, showing sequential steps, conditional branching, and subgraphs. This is useful for visualizing the flow of an AI system or any process. ```mermaid flowchart LR start[Start] --> batch[Batch] batch --> check[Check] check -->|OK| process check -->|Error| fix[Fix] fix --> check subgraph process[Process] step1[Step 1] --> step2[Step 2] end process --> endNode[End] ``` -------------------------------- ### Call Azure OpenAI LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Illustrates how to connect to Azure OpenAI services using the `openai` library. This requires the Azure endpoint, an API key, and the specific deployment name for the model. ```Python from openai import AzureOpenAI def call_llm(prompt): client = AzureOpenAI( azure_endpoint="https://.openai.azure.com/", api_key="YOUR_API_KEY_HERE", api_version="2023-05-15" ) r = client.chat.completions.create( model="", messages=[{"role": "user", "content": prompt}] ) return r.choices[0].message.content ``` -------------------------------- ### Article Writing Workflow (Python) Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md This Python code defines a workflow for writing an article using a chain of Nodes: generating an outline, writing content based on the outline, and then reviewing and refining the draft. It demonstrates task decomposition for complex processes. ```Python class GenerateOutline(Node): def prep(self, shared): return shared["topic"] # type: ignore def exec(self, topic): return call_llm(f"Create a detailed outline for an article about {topic}") def post(self, shared, prep_res, exec_res): shared["outline"] = exec_res class WriteSection(Node): def prep(self, shared): return shared["outline"] # type: ignore def exec(self, outline): return call_llm(f"Write content based on this outline: {outline}") def post(self, shared, prep_res, exec_res): shared["draft"] = exec_res class ReviewAndRefine(Node): def prep(self, shared): return shared["draft"] # type: ignore def exec(self, draft): return call_llm(f"Review and improve this draft: {draft}") def post(self, shared, prep_res, exec_res): shared["final_article"] = exec_res # Connect nodes outline = GenerateOutline() write = WriteSection() review = ReviewAndRefine() outline >> write >> review # Create and run flow writing_flow = Flow(start=outline) shared = {"topic": "AI Safety"} writing_flow.run(shared) ``` -------------------------------- ### Create PocketFlow Question-Answering Flow Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Python code demonstrating how to create a question-answering flow using PocketFlow. It defines two nodes, `GetQuestionNode` and `AnswerNode`, and connects them sequentially to form the flow. ```Python # flow.py from pocketflow import Flow from nodes import GetQuestionNode, AnswerNode def create_qa_flow(): """Create and return a question-answering flow.""" # Create nodes get_question_node = GetQuestionNode() answer_node = AnswerNode() # Connect nodes in sequence get_question_node >> answer_node # Create flow starting with input node return Flow(start=get_question_node) ``` -------------------------------- ### Document Summarization with MapReduce Pattern Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Demonstrates the MapReduce design pattern for document summarization. It uses a BatchNode to summarize individual files and a regular Node to combine these summaries into a final output. Dependencies include 'BatchNode', 'Node', 'Flow', and 'call_llm'. ```Python class SummarizeAllFiles(BatchNode): def prep(self, shared): files_dict = shared["files"] # e.g. 10 files return list(files_dict.items()) # [("file1.txt", "aaa..."), ("file2.txt", "bbb..."), ...] # def exec(self, one_file): filename, file_content = one_file summary_text = call_llm(f"Summarize the following file:\n{file_content}") return (filename, summary_text) def post(self, shared, prep_res, exec_res_list): shared["file_summaries"] = dict(exec_res_list) class CombineSummaries(Node): def prep(self, shared): return shared["file_summaries"] def exec(self, file_summaries): # format as: "File1: summary\nFile2: summary...\n" text_list = [] for fname, summ in file_summaries.items(): text_list.append(f"{fname} summary:\n{summ}\n") big_text = "\n---".join(text_list) return call_llm(f"Combine these file summaries into one final summary:\n{big_text}") def post(self, shared, prep_res, final_summary): shared["all_files_summary"] = final_summary batch_node = SummarizeAllFiles() combine_node = CombineSummaries() batch_node >> combine_node flow = Flow(start=batch_node) shared = { "files": { "file1.txt": "Alice was beginning to get very tired of sitting by her sister...", "file2.txt": "Some other interesting text ...", # ... } } flow.run(shared) print("Individual Summaries:", shared["file_summaries"]) print("\nFinal Summary:\n", shared["all_files_summary"]) ``` -------------------------------- ### Mermaid Diagram for Flowchart Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Illustrates a basic flowchart structure using Mermaid syntax, showing sequential steps, conditional branching, and subgraphs. This is useful for visualizing the flow of an AI system or any process. ```mermaid flowchart LR start[Start] --> batch[Batch] batch --> check[Check] check -->|OK| process check -->|Error| fix[Fix] fix --> check subgraph process[Process] step1[Step 1] --> step2[Step 2] end process --> endNode[End] ``` -------------------------------- ### Python Main Flow Execution Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md This Python code snippet shows the main execution logic for a Pocket Flow application. It initializes a shared dictionary, creates a QA flow, runs the flow with the shared data, and then prints the question and answer from the shared store. ```Python def main(): shared = { "question": None, # Will be populated by GetQuestionNode from user input "answer": None # Will be populated by AnswerNode } # Create the flow and run it qa_flow = create_qa_flow() qa_flow.run(shared) print(f"Question: {shared['question']}") print(f"Answer: {shared['answer']}") if __name__ == "__main__": main() ``` -------------------------------- ### Document Summarization with MapReduce Pattern Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Demonstrates the MapReduce design pattern for document summarization. It uses a BatchNode to summarize individual files and a regular Node to combine these summaries into a final output. Dependencies include 'BatchNode', 'Node', 'Flow', and 'call_llm'. ```Python class SummarizeAllFiles(BatchNode): def prep(self, shared): files_dict = shared["files"] # e.g. 10 files return list(files_dict.items()) # [("file1.txt", "aaa..."), ("file2.txt", "bbb..."), ...] # def exec(self, one_file): filename, file_content = one_file summary_text = call_llm(f"Summarize the following file:\n{file_content}") return (filename, summary_text) def post(self, shared, prep_res, exec_res_list): shared["file_summaries"] = dict(exec_res_list) class CombineSummaries(Node): def prep(self, shared): return shared["file_summaries"] def exec(self, file_summaries): # format as: "File1: summary\nFile2: summary...\n" text_list = [] for fname, summ in file_summaries.items(): text_list.append(f"{fname} summary:\n{summ}\n") big_text = "\n---".join(text_list) return call_llm(f"Combine these file summaries into one final summary:\n{big_text}") def post(self, shared, prep_res, final_summary): shared["all_files_summary"] = final_summary batch_node = SummarizeAllFiles() combine_node = CombineSummaries() batch_node >> combine_node flow = Flow(start=batch_node) shared = { "files": { "file1.txt": "Alice was beginning to get very tired of sitting by her sister...", "file2.txt": "Some other interesting text ...", # ... } } flow.run(shared) print("Individual Summaries:", shared["file_summaries"]) print("\nFinal Summary:\n", shared["all_files_summary"]) ``` -------------------------------- ### List Python Dependencies Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Specifies the Python libraries required for the project to run, including PyYAML and pocketflow. ```Python PyYAML pocketflow ``` -------------------------------- ### Create PocketFlow Question-Answering Flow Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md Python code demonstrating how to create a question-answering flow using PocketFlow. It defines two nodes, `GetQuestionNode` and `AnswerNode`, and connects them sequentially to form the flow. ```Python # flow.py from pocketflow import Flow from nodes import GetQuestionNode, AnswerNode def create_qa_flow(): """Create and return a question-answering flow.""" # Create nodes get_question_node = GetQuestionNode() answer_node = AnswerNode() # Connect nodes in sequence get_question_node >> answer_node # Create flow starting with input node return Flow(start=get_question_node) ``` -------------------------------- ### Article Writing Workflow (Python) Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/CLAUDE.md This Python code defines a workflow for writing an article using a chain of Nodes: generating an outline, writing content based on the outline, and then reviewing and refining the draft. It demonstrates task decomposition for complex processes. ```Python class GenerateOutline(Node): def prep(self, shared): return shared["topic"] # type: ignore def exec(self, topic): return call_llm(f"Create a detailed outline for an article about {topic}") def post(self, shared, prep_res, exec_res): shared["outline"] = exec_res class WriteSection(Node): def prep(self, shared): return shared["outline"] # type: ignore def exec(self, outline): return call_llm(f"Write content based on this outline: {outline}") def post(self, shared, prep_res, exec_res): shared["draft"] = exec_res class ReviewAndRefine(Node): def prep(self, shared): return shared["draft"] # type: ignore def exec(self, draft): return call_llm(f"Review and improve this draft: {draft}") def post(self, shared, prep_res, exec_res): shared["final_article"] = exec_res # Connect nodes outline = GenerateOutline() write = WriteSection() review = ReviewAndRefine() outline >> write >> review # Create and run flow writing_flow = Flow(start=outline) shared = {"topic": "AI Safety"} writing_flow.run(shared) ``` -------------------------------- ### Run Individual Node vs. Run Flow Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Compares running a single node using `node.run(shared)` for isolated testing versus running an entire flow with `flow.run(shared)` for production execution. Running a single node does not follow transitions. ```Python # Run a single node (for testing) node.run(shared) # Run the entire flow (for production) flow.run(shared) ``` -------------------------------- ### Call Azure OpenAI LLM Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Illustrates how to connect to Azure OpenAI services using the OpenAI Python client. This requires the Azure endpoint, an API key, and the specific deployment name for the model. ```Python from openai import AzureOpenAI def call_llm(prompt): client = AzureOpenAI( azure_endpoint="https://.openai.azure.com/", api_key="YOUR_API_KEY_HERE", api_version="2023-05-15" ) r = client.chat.completions.create( model="", messages=[{"role": "user", "content": prompt}] ) return r.choices[0].message.content ``` -------------------------------- ### Define Basic Default Transition Source: https://github.com/the-pocket/pocketflow-template-python/blob/main/GEMINI.md Defines a transition where if a node's post() method returns the default action, the flow proceeds to the next specified node. ```Python node_a >> node_b ```