### Project Setup and Execution Commands Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-node/README.md Commands to initialize the environment, install dependencies, and execute the PocketFlow application. ```bash python -m venv venv source venv/bin/activate pip install -r requirements.txt python main.py ``` -------------------------------- ### Install Dependencies and Run Example in Bash Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-async-basic/README.md This Bash script demonstrates how to set up and run the PocketFlow async example. It first installs the necessary Python packages using pip and then executes the main Python script. Ensure requirements.txt is present. ```bash pip install -r requirements.txt python main.py ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-batch-node/README.md Installs the necessary Python packages listed in the requirements.txt file. This is a standard command for setting up Python projects. ```bash pip install -r requirements.txt ``` -------------------------------- ### Bash: Environment Setup and API Key Configuration Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-tool-embeddings/README.md These bash commands demonstrate the setup process for the project. It includes creating a virtual environment, activating it, installing dependencies from a requirements file, and configuring the OpenAI API key either via a .env file or as a system environment variable. ```bash # Create a virtual environment python -m venv venv # Activate the virtual environment source venv/bin/activate # On Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt # Set OpenAI API key (Option A: .env file) # OPENAI_API_KEY=your_api_key_here # Set OpenAI API key (Option B: system environment variable) # export OPENAI_API_KEY=your_api_key_here ``` -------------------------------- ### Setup and Execution Commands for PocketFlow Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-code-generator/README.md Commands to install project dependencies, configure the Anthropic API key, and execute the code generator for specific programming problems. ```bash pip install -r requirements.txt export ANTHROPIC_API_KEY="your-api-key-here" python utils/call_llm.py python main.py python main.py "Reverse a linked list. Given the head of a singly linked list, reverse the list and return the reversed list." ``` -------------------------------- ### Setup and Execution Commands for PocketFlow Translation Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-parallel-batch/README.md Commands to install project dependencies, configure the Anthropic API key, and execute the translation process. These steps are required to initialize the environment and run the parallel translation script. ```bash pip install -r requirements.txt export ANTHROPIC_API_KEY="your-api-key-here" python utils.py python main.py ``` -------------------------------- ### Running a PocketFlow Summarization Workflow Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-node/README.md Demonstrates how to initialize a shared data store and execute a PocketFlow workflow to generate a text summary. ```python shared = {"data": "Your text to summarize here..."} flow.run(shared) print("Summary:", shared["summary"]) ``` -------------------------------- ### Setup and Execution Commands for PocketFlow CLI Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-cli-hitl/README.md Standard shell commands to install project dependencies, configure the required Anthropic API key for LLM interaction, and execute the application. ```bash pip install -r requirements.txt export ANTHROPIC_API_KEY="your-anthropic-api-key-here" python utils/call_llm.py python main.py ``` -------------------------------- ### Verify API Key and Environment Setup Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-thinking/README.md Runs a utility script to verify that the API key and environment variables are correctly configured for API access. This is an optional step to ensure the setup is working before running the main application. ```python python utils.py ``` -------------------------------- ### Install Pocket Flow and Dependencies Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow_demo.ipynb Installs the necessary libraries for Pocket Flow, FAISS, and OpenAI integration using pip. ```python ! pip install pocketflow ! pip install faiss-cpu ! pip install openai ``` -------------------------------- ### Run PocketFlow Agent Skills CLI Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-agent-skills/README.md Instructions for setting up the environment and executing the PocketFlow agent with specific task prompts. Requires an OpenAI API key and the installation of project dependencies. ```bash pip install -r requirements.txt export OPENAI_API_KEY="your-key" python main.py --"Summarize this launch plan for a VP audience" python main.py --"Turn this into an implementation checklist" ``` -------------------------------- ### Get Approval AsyncNode in Python Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-async-basic/README.md This Python AsyncNode handles user confirmation asynchronously. It presents a recipe suggestion to the user and waits for their input (accept or reject) using an asynchronous input function. The output determines the next flow control action. ```python async def post_async(self, shared, prep_res, suggestion): # Async user input answer = await get_user_input( f"Accept {suggestion}? (y/n): " ) return "accept" if answer == "y" else "retry" ``` -------------------------------- ### AsyncParallelBatchFlow Example - Python Source: https://github.com/the-pocket/pocketflow/blob/main/docs/core_abstraction/parallel.md Illustrates the use of AsyncParallelBatchFlow for running sub-flows concurrently. The `prep_async` method provides parameters for each iteration of the sub-flow. This example shows how to parallelize the process of loading and summarizing multiple 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) ``` -------------------------------- ### Install System Audio Dependencies Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-voice-chat/README.md Installs the PortAudio development headers required by the sounddevice library on Linux systems. ```bash sudo apt-get update && sudo apt-get install -y portaudio19-dev ``` -------------------------------- ### Run PocketFlow BatchNode Example Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-batch-node/README.md Executes the main Python script for the PocketFlow BatchNode CSV processing example. This script orchestrates the chunking, processing, and aggregation of the sales data. ```bash python main.py ``` -------------------------------- ### Fetch Recipes AsyncNode in Python Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-async-basic/README.md This Python AsyncNode demonstrates fetching recipes asynchronously. It takes user input for an ingredient and then makes an asynchronous API call to retrieve recipes. Dependencies include an asynchronous HTTP client. ```python async def prep_async(self, shared): ingredient = input("Enter ingredient: ") return ingredient async def exec_async(self, ingredient): # Async API call recipes = await fetch_recipes(ingredient) return recipes ``` -------------------------------- ### Install Dependencies with Pipenv Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-google-calendar/README.md Installs project dependencies using Pipenv, a tool for managing Python dependencies and virtual environments. Ensure Pipenv is installed before running this command. ```bash pipenv install ``` -------------------------------- ### Install Pocketflow and Dependencies Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-agent/demo.ipynb Installs the pocketflow library along with essential dependencies like aiohttp, openai, and duckduckgo-search. Ensure you have pip installed and a Python environment ready. ```python ! pip install pocketflow>=0.0.1 ! pip install aiohttp>=3.8.0 ! pip install openai>=1.0.0 ! pip install duckduckgo-search>=7.5.2 ``` -------------------------------- ### Implement Node Lifecycle and Fallback Source: https://github.com/the-pocket/pocketflow/blob/main/docs/core_abstraction/node.md A complete example of a Node implementation including prep, exec, post, and exec_fallback methods to handle data processing and potential errors. ```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) return summary def exec_fallback(self, prep_res, exc): return "There was an error processing your request." def post(self, shared, prep_res, exec_res): shared["summary"] = exec_res summarize_node = SummarizeFile(max_retries=3) action_result = summarize_node.run(shared) ``` -------------------------------- ### Define and Execute a Basic Flow Sequence Source: https://github.com/the-pocket/pocketflow/blob/main/docs/core_abstraction/flow.md Demonstrates how to link two nodes using the default transition operator and execute the sequence starting from the first node. ```python node_a >> node_b flow = Flow(start=node_a) flow.run(shared) ``` -------------------------------- ### Advanced PocketFlow Tracer Configuration Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-tracing/README.md Shows how to create a custom `TracingConfig` object and initialize a `LangfuseTracer` for advanced control over PocketFlow tracing. This example demonstrates loading configuration from environment variables and enabling debug mode. ```python from tracing import TracingConfig, LangfuseTracer # Create custom configuration config = TracingConfig.from_env() config.debug = True ``` -------------------------------- ### Initializing and Running a Flow (Python) Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow_demo.ipynb Shows how to define a starting point for a PocketFlow graph using 'Flow(start=node_a)' and then execute the entire flow by calling the 'flow.run(shared)' method. This is the primary way to initiate the execution of your node graph. ```python Flow(start=node_a) flow.run(shared) ``` -------------------------------- ### Generate Text Embeddings using Python APIs Source: https://github.com/the-pocket/pocketflow/blob/main/docs/utility_function/embedding.md This collection of snippets demonstrates how to interface with various cloud-based and hosted embedding providers. Each example requires a valid API key or project configuration and returns a vector representation of the input text. ```python from openai import OpenAI client = OpenAI(api_key="YOUR_API_KEY") response = client.embeddings.create( model="text-embedding-ada-002", input=text ) # Extract the embedding vector from the response embedding = response.data[0].embedding embedding = np.array(embedding, dtype=np.float32) print(embedding) ``` ```python import openai openai.api_type = "azure" openai.api_base = "https://YOUR_RESOURCE_NAME.openai.azure.com" openai.api_version = "2023-03-15-preview" openai.api_key = "YOUR_AZURE_API_KEY" resp = openai.Embedding.create(engine="ada-embedding", input="Hello world") vec = resp["data"][0]["embedding"] print(vec) ``` ```python from vertexai.preview.language_models import TextEmbeddingModel import vertexai vertexai.init(project="YOUR_GCP_PROJECT_ID", location="us-central1") model = TextEmbeddingModel.from_pretrained("textembedding-gecko@001") emb = model.get_embeddings(["Hello world"]) print(emb[0]) ``` ```python import boto3, json client = boto3.client("bedrock-runtime", region_name="us-east-1") body = {"inputText": "Hello world"} resp = client.invoke_model(modelId="amazon.titan-embed-text-v2:0", contentType="application/json", body=json.dumps(body)) resp_body = json.loads(resp["body"].read()) vec = resp_body["embedding"] print(vec) ``` ```python import cohere co = cohere.Client("YOUR_API_KEY") resp = co.embed(texts=["Hello world"]) vec = resp.embeddings[0] print(vec) ``` ```python import requests API_URL = "https://api-inference.huggingface.co/models/sentence-transformers/all-MiniLM-L6-v2" HEADERS = {"Authorization": "Bearer YOUR_HF_TOKEN"} res = requests.post(API_URL, headers=HEADERS, json={"inputs": "Hello world"}) vec = res.json()[0] print(vec) ``` ```python import requests url = "https://api.jina.ai/v2/embed" headers = {"Authorization": "Bearer YOUR_JINA_TOKEN"} payload = {"data": ["Hello world"], "model": "jina-embeddings-v3"} res = requests.post(url, headers=headers, json=payload) vec = res.json()["data"][0]["embedding"] print(vec) ``` -------------------------------- ### Main Entry Point (Python) Source: https://github.com/the-pocket/pocketflow/blob/main/docs/guide.md The main Python script for the project, serving as the entry point. It imports the `create_qa_flow` function to set up and potentially run the defined workflow. ```python # main.py from flow import create_qa_flow # Example main function # Please replace this with your own main function ``` -------------------------------- ### Suggest Recipe AsyncNode in Python Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-async-basic/README.md This Python AsyncNode processes a list of recipes asynchronously to suggest the best one using an LLM. It takes recipes as input and makes an asynchronous call to an LLM API. Dependencies include an asynchronous LLM client. ```python async def exec_async(self, recipes): # Async LLM call suggestion = await call_llm_async( f"Choose best recipe from: {recipes}" ) return suggestion ``` -------------------------------- ### Install Langfuse Dependency Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-tracing/README.md Command to install the required Langfuse package for enabling observability features. ```bash pip install langfuse ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-google-calendar/README.md Clones the Pocket Google Calendar repository from a remote URL and navigates into the newly created project directory. This is the initial step for setting up the project locally. ```bash git clone [REPOSITORY_URL] cd pocket-google-calendar ``` -------------------------------- ### Initialize Langfuse Tracer Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-tracing/README.md Demonstrates how to manually instantiate the LangfuseTracer class for advanced tracing control within PocketFlow. ```python from pocketflow import LangfuseTracer tracer = LangfuseTracer(config) ``` -------------------------------- ### Project Dependencies (requirements.txt) Source: https://github.com/the-pocket/pocketflow/blob/main/docs/guide.md Lists the Python dependencies required for the Pocketflow project. These packages need to be installed for the project to run correctly. ```plaintext PyYAML pocketflow ``` -------------------------------- ### Define Complex Order Processing Pipelines Source: https://github.com/the-pocket/pocketflow/blob/main/docs/core_abstraction/flow.md Example of breaking down a large process into multiple sub-flows for inventory, payment, and shipping, demonstrating modular architecture. ```python validate_payment >> process_payment >> payment_confirmation payment_flow = Flow(start=validate_payment) check_stock >> reserve_items >> update_inventory inventory_flow = Flow(start=check_stock) create_label >> assign_carrier >> schedule_pickup shipping_flow = Flow(start=create_label) ``` -------------------------------- ### Process Question with Agent Flow (Python) Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-agent/demo.ipynb This Python function, `main`, serves as the entry point for the PocketFlow application. It retrieves a question either from command-line arguments or uses a default question. It then initializes an agent flow and runs it with the question, finally printing the generated answer. ```python import sys def main(): """Simple function to process a question.""" # Default question default_question = "Who won the Nobel Prize in Physics 2024?" # Get question from command line if provided with -- question = default_question for arg in sys.argv[1:]: if arg.startswith("--"): question = arg[2:] break # Create the agent flow agent_flow = create_agent_flow() # Process the question shared = {"question": question} print(f"🤔 Processing question: {question}") agent_flow.run(shared) print("\n🎯 Final Answer:") print(shared.get("answer", "No answer found")) main() ``` -------------------------------- ### Define and Execute a Node in PocketFlow Source: https://context7.com/the-pocket/pocketflow/llms.txt Demonstrates the Node lifecycle by implementing a text summarization task. It shows how to use prep() for data retrieval, exec() for LLM calls with retry logic, and post() for state updates. ```python from pocketflow import Node, Flow class SummarizeText(Node): def prep(self, shared): return shared["document"] def exec(self, prep_res): prompt = f"Summarize this text in 50 words: {prep_res}" return call_llm(prompt) def exec_fallback(self, prep_res, exc): return "Summary unavailable due to processing error." def post(self, shared, prep_res, exec_res): shared["summary"] = exec_res return "default" summarize_node = SummarizeText(max_retries=3, wait=10) shared = {"document": "Long text content here..."} summarize_node.run(shared) print(shared["summary"]) ``` -------------------------------- ### Two Sum Implementation Example Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-code-generator/README.md A sample Python implementation generated by the system for the Two Sum problem, utilizing a hash map for O(n) time complexity. ```python def run_code(nums, target): num_to_index = {} for i, num in enumerate(nums): complement = target - num if complement in num_to_index: return [num_to_index[complement], i] num_to_index[num] = i return [] ``` -------------------------------- ### PocketFlow Client Log: Request and Response Handling Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-a2a/README.md This client log demonstrates the interaction with the PocketFlow server. It shows the client connecting to the server, sending a JSON-RPC request to initiate a task, and receiving an HTTP 200 OK status followed by the JSON-RPC response indicating task completion. This illustrates the client's perspective of the communication. ```log Connecting to agent at: http://localhost:10003 Using Session ID: f3e12b8424c44241be881cd4bb8a269f Enter your question (:q or quit to exit) > Who won the Nobel Prize in Physics 2024? Sending task 46c3ce7b941a4fff9b8e3b644d6db5f4... 2025-04-12 17:20:57,643 - A2AClient - INFO - -> Sending Request (ID: d3f3fb93350d47d9a94ca12bb62b656b, Method: tasks/send): { "jsonrpc": "2.0", "id": "d3f3fb93350d47d9a94ca12bb62b656b", "method": "tasks/send", "params": { "id": "46c3ce7b941a4fff9b8e3b644d6db5f4", "sessionId": "f3e12b8424c44241be881cd4bb8a269f", "message": { "role": "user", "parts": [ { "type": "text", "text": "Who won the Nobel Prize in Physics 2024?" } ] }, "acceptedOutputModes": [ "text", "text/plain" ] } } 2025-04-12 17:21:03,835 - httpx - INFO - HTTP Request: POST http://localhost:10003 "HTTP/1.1 200 OK" 2025-04-12 17:21:03,836 - A2AClient - INFO - <- Received HTTP Status 200 for Request (ID: d3f3fb93350d47d9a94ca12bb62b656b) 2025-04-12 17:21:03,836 - A2AClient - INFO - <- Received Success Response (ID: d3f3fb93350d47d9a94ca12bb62b656b): { "jsonrpc": "2.0", "id": "d3f3fb93350d47d9a94ca12bb62b656b", "result": { "id": "46c3ce7b941a4fff9b8e3b644d6db5f4", "sessionId": "f3e12b8424c44241be881cd4bb8a269f", "status": { "state": "completed", "timestamp": "2025-04-12T17:21:03.834542" }, "artifacts": [ { "parts": [ { "type": "text", ``` -------------------------------- ### Params Example in Python Source: https://github.com/the-pocket/pocketflow/blob/main/docs/core_abstraction/communication.md Illustrates how to use immutable parameters for node-specific configurations. The SummarizeFile node accesses 'filename' from its params to fetch data and store results. 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 ``` -------------------------------- ### Run Visualization Script Source: https://github.com/the-pocket/pocketflow/blob/main/cookbook/pocketflow-visualization/README.md Command-line instructions to execute the visualization script within the project directory. ```bash # Navigate to the directory cd cookbook/pocketflow-minimal-flow2flow # Run the visualization script python visualize.py ```