### Install workflows-py Package Source: https://github.com/run-llama/workflows-py/blob/main/README.md Installs the llama-index-workflows package using pip. This is the first step to using the workflows library. ```bash pip install llama-index-workflows ``` -------------------------------- ### Install LlamaIndex Workflows Server Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Installs the necessary package for the LlamaIndex Workflows server, including server-specific functionalities. ```python %pip install llama-index-workflows[server] ``` -------------------------------- ### Serve Documentation Locally with MkDocs Source: https://github.com/run-llama/workflows-py/blob/main/docs/api_docs/README.md Starts a local development server for MkDocs to preview documentation changes. Requires uv to be installed and dependencies to be synced. ```bash uv run mkdocs serve ``` -------------------------------- ### Install Dependencies for LlamaIndex Workflows and Qdrant Source: https://github.com/run-llama/workflows-py/blob/main/examples/state_management_with_vector_databases.ipynb Installs necessary Python packages including llama-index-workflows, qdrant-client, sentence-transformers, and openai. This is the first step to set up the environment for the workflow state management example. ```python %pip install -q llama-index-workflows qdrant-client sentence-transformers openai ``` -------------------------------- ### Define Workflows and Setup Server Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Defines custom workflows (GreetingWorkflow, MathWorkflow, ProcessingWorkflow) that can emit streaming events and sets up the WorkflowServer. The server is configured to host these workflows and handle event streaming. This script is saved as 'server.py'. ```python %%writefile server.py import asyncio from workflows import Workflow, step from workflows.context import Context from workflows.events import Event, StartEvent, StopEvent from workflows.server import WorkflowServer class StreamEvent(Event): sequence: int # Define a simple workflow class GreetingWorkflow(Workflow): @step async def greet(self, ctx: Context, ev: StartEvent) -> StopEvent: for i in range(3): ctx.write_event_to_stream(StreamEvent(sequence=i)) await asyncio.sleep(0.3) name = getattr(ev, "name", "World") return StopEvent(result=f"Hello, {name}!") class ProgressEvent(Event): step: str progress: int message: str class MathWorkflow(Workflow): @step async def calculate(self, ev: StartEvent) -> StopEvent: a = getattr(ev, "a", 0) b = getattr(ev, "b", 0) operation = getattr(ev, "operation", "add") if operation == "add": result = a + b elif operation == "multiply": result = a * b elif operation == "subtract": result = a - b elif operation == "divide": result = a / b if b != 0 else None else: result = None return StopEvent( result={"a": a, "b": b, "operation": operation, "result": result} ) class ProcessingWorkflow(Workflow): """Example workflow that demonstrates event streaming with progress updates.""" @step async def process(self, ctx: Context, ev: StartEvent) -> StopEvent: items = getattr(ev, "items", ["item1", "item2", "item3", "item4", "item5"]) ctx.write_event_to_stream( ProgressEvent( step="start", progress=0, message=f"Starting processing of {len(items)} items", ) ) results = [] for i, item in enumerate(items): # Simulate processing time await asyncio.sleep(0.5) # Emit progress event progress = int((i + 1) / len(items) * 100) ctx.write_event_to_stream( ProgressEvent( step="processing", progress=progress, message=f"Processed {item} ({i + 1}/{len(items)})", ) ) results.append(f"processed_{item}") ctx.write_event_to_stream( ProgressEvent( step="complete", progress=100, message="Processing completed successfully", ) ) return StopEvent(result={"processed_items": results, "total": len(results)}) async def main(): server = WorkflowServer() # Register workflows server.add_workflow("greeting", GreetingWorkflow()) server.add_workflow("math", MathWorkflow()) server.add_workflow("processing", ProcessingWorkflow()) await server.serve(host="0.0.0.0", port=8000) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/run-llama/workflows-py/blob/main/docs/api_docs/README.md Installs project dependencies using the uv package manager. Assumes the repository has been cloned and uv is installed. ```bash uv sync ``` -------------------------------- ### Python: Install Observability and LLM Packages Source: https://github.com/run-llama/workflows-py/blob/main/examples/feature_walkthrough.ipynb Installs necessary Python packages for integrating observability features with LlamaIndex, including instrumentation for tracing and specific LLM providers. ```python %pip install llama-index-instrumentation %pip install llama-index-core llama-index-llms-openai %pip install arize-phoenix openinference-instrumentation-llama_index ``` -------------------------------- ### Install Workflows Library Source: https://github.com/run-llama/workflows-py/blob/main/examples/feature_walkthrough.ipynb Installs the llama-index-workflows Python package using pip. This is a prerequisite for using the Workflows library. ```python %pip install llama-index-workflows ``` -------------------------------- ### Define and Run a Basic Workflow in Python Source: https://github.com/run-llama/workflows-py/blob/main/README.md Demonstrates creating a Python workflow using the 'workflows' library. It defines custom event types and a workflow with 'start' and 'process' steps. The workflow manages state using a Pydantic model and demonstrates sequential execution and event handling. It requires Python 3.7+ for asyncio. ```python import asyncio from pydantic import BaseModel, Field from workflows import Context, Workflow, step from workflows.events import Event, StartEvent, StopEvent class MyEvent(Event): msg: list[str] class RunState(BaseModel): num_runs: int = Field(default=0) class MyWorkflow(Workflow): @step async def start(self, ctx: Context[RunState], ev: StartEvent) -> MyEvent: async with ctx.store.edit_state() as state: state.num_runs += 1 return MyEvent(msg=[ev.input_msg] * state.num_runs) @step async def process(self, ctx: Context[RunState], ev: MyEvent) -> StopEvent: data_length = len("".join(ev.msg)) new_msg = f"Processed {len(ev.msg)} times, data length: {data_length}" return StopEvent(result=new_msg) async def main(): workflow = MyWorkflow() # [optional] provide a context object to the workflow ctx = Context(workflow) result = await workflow.run(input_msg="Hello, world!", ctx=ctx) print("Workflow result:", result) # re-running with the same context will retain the state result = await workflow.run(input_msg="Hello, world!", ctx=ctx) print("Workflow result:", result) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install LlamaIndex Workflows and Dependencies Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/fastapi_server_example.ipynb Installs the necessary LlamaIndex Workflows package with server support and FastAPI using pip. This command ensures all required libraries are available for the project. ```bash %pip install llama-index-workflows[server] fastapi ``` -------------------------------- ### Install Workflow Dependencies Source: https://github.com/run-llama/workflows-py/blob/main/examples/streaming_internal_events.ipynb This command installs the necessary Python packages for using llama-index workflows, cloud services, and OpenAI language models. Ensure you have pip installed and a stable internet connection. ```python ! pip install llama-index-workflows llama-cloud-services llama-index-llms-openai ``` -------------------------------- ### Example Data Structure (JSON) Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet demonstrates a data structure, likely in JSON format, containing various fields such as 'dEpTmBcEMgozikI1IphRqHFopguBtWvXbvk98aWXXuriqq5fGjZsWMydOzd69/bXdl1LeZUAAQIECBAgQIAAAQLlEPCnu3LMSZcECBAgQI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KPA2rVrt/xetmbNmhpX/uHyYcOGxdy5c6N3b38l9wcVXxEgQIAAAQIECBAgQKDaAv4EWO35Oh0BAgQIECBAgACBXAT23nvveOCBB6J///6p6yWBjCSYsW7dum5r7L777vH88893e13aC5588sm0S62rUUAgo0Ywl+ciIJiRC6Mi2wi0t7fHxIkTY/ny5ds8W9uXAwYMiIULF0byqwcBAgQIECBAgAABAgQItI6AUEbrzNpJCRAgQIAAAQIECGQSOOyww+Lee+/N9K97k48wOfnkk7vsI/nXw6+99lqX12R9USgjq2DP1gtk9MzJVfUREMyoj2urVr3oooti0aJFqY+f/N6W3CFj+PDhqWtYSIAAAQIECBAgQIAAAQLlFBDKKOfcdE2AAAECBAgQIECgKQLHH398XHvttZn2vv/+++PTn/70DjXGjx8fV111VfvxH374oV51002XfXg/X/1xvv3331+qj/2o2h+V+j09yRkYyP/O9LwYt69q1K40ePHiYfv361d43xM8ECBAgQIAAAQIECBAgUE0BoYxqz9fpCBAgQIAAAQIECGQSOPfcc+PUU0/NVOOyyy6LOXPmpK4xfvz4THfs2H7jlStXbv+U7xskIJDRIOgW3UYwo0UH34RjL168OM4888xMO5999tkxadKkTDUsJkCAAAECBAgQIECAAIFyCAhllGNOuiRAgAABAgQIECDQNIHbb789Ro0alWn/yZMnR/JxJrU+jjzyyJg3b16ty7q8fsWKFdHW1tblNV7MX0AgI39TFXcUEMzY0cQz+Qokv4dMmDAh0+8jo0ePjquvvjrfxlQjQIAAAQIECBAgQIAAgcIKCGUUdjQaI0CAAAECBAgQIFAMgb59+8Y3v/nNGDJkSOqG1q9fH2PGjIlVq1b1uMYBBxwQy5Yt6/H1Pb3w1VdfjWeffbanl7suBwGBjBwQleixgGBGj6lcWKPA2rVrt/xetmbNmhpX/uHyYcOGxdy5c6N3b38l9wcVXxEgQIAAAQIECBAgQKDaAv4EWO35Oh0BAgQIECBAgACBXAT23nvveOCBB6J///6p6yWBjCSYsW7dum5r7L777vH88893e13aC5588sm0S62rUUAgo0Ywl+ciIJi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Vr3oooti0aJFqY+f/N6W3CFj+PDhqWtYSIAAAQIECBAgQIAAAQLlFBDKKOfcdE2AAAECBAgQIECgKQLHH398XHvttZn2vv/+++PTn/70DjXGjx8fV111VfvxH374oV51002XfXg/X/1xvv3331+qj/2o2h+V+j09yRkYyP/O9LwYt69q1K40ePHiYfv361d43xM8ECBAgQIAAAQIECBAgUE0BoYxqz9fpCBAgQIAAAQIECGQSOPfcc+PUU0/NVOOyyy6LOXPmpK4xfvz4THfs2H7jlStXbv+U7xskIJDRIOgW3UYwo0UH34RjL168OM4888xMO5999tkxadKkTDUsJkCAAAECBAgQIECAAIFyCAhllGNOuiRAgAABAgQIECDQNIHbb789Ro0alWn/yZMnR/JxJrU+jjzyyJg3b16ty7q8fsWKFdHW1tblNV7MX0AgI39TFXcUEMzY0cQz+Qokv4dMmDAh0+8jo0ePjquvvjrfxlQjQIAAAQIECBAgQIAAgcIKCGUUdjQaI0CAAAECBAgQIFAMgb59+8Y3v/nNGDJkSOqG1q9fH2PGjIlVq1b1uMYBBxwQy5Yt6/H1Pb3w1VdfjWeffbanl7suBwGBjBwQleixgGBGj6lcWKPA2rVrt/xetmbNmhpX/uHyYcOGxdy5c6N3b38l9wcVXxEgQIAAAQIECBAgQKDaAv4EWO35Oh0BAgQIECBAgACBXAT23nvveOCBB6J///6p6yWBjCSYsW7dum5r7L777vH88893e13aC5588sm0S62rUUAgo0Ywl+ciIJiRC6Mi2wi0t7fHxIkTY/ny5ds8W9uXAwYMiIULF0byqwcBAgQIECBAgAABAgQItI6AUEbrzNpJCRAgQIAAAQIECGQSOOyww+Lee+/N9K97k48wOfnkk7vsI/nXw6+99lqX12R9USgjq2DP1gtk9MzJVfUREMyoj2urVr3oooti0aJFqY+f/N6W3CFj+PDhqWtYSIAAAQIECBAgQIAAAQLlFBDKKOfcdE2AAAECBAgQIECgKQLHH398XHvttZn2vv/+++PTn/70DjXGjx8fV111VfvxH374oV51002XfXg/X/1xvv3331+qj/2o2h+V+j09yRkYyP/O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xlQjQIAAAQIECBAgQIAAgcIKCGUUdjQaI0CAAAECBAgQIFAMgb59+8Y3v/nNGDJkSOqG1q9fH2PGjIlVq1b1uMYBBxwQy5Yt6/H1Pb3w1VdfjWeffbanl7suBwGBjBwQleixgGBGj6lcWKPA2rVrt/xetmbNmhpX/uHyYcOGxdy5c6N3b38l9wcVXxEgQIAAAQIECBAgQKDaAv4EWO35Oh0BAgQIECBAgACBXAT23nvveOCBB6J///6p6yWBjCSYsW7dum5r7L777vH88893e13aC5588sm0S62rUUAgo0Ywl+ciIJiRC6Mi2wi0t7fHxIkTY/ny5ds8W9uXAwYMiIULF0byqwcBAgQIECBAgAABAgQItI6AUEbrzNpJCRAgQIAAAQIECGQSOOyww+Lee+/N9K97k48wOfnkk7vsI/nXw6+99lqX12R9USgjq2DP1gtk9MzJVfUREMyoj2urVr3oooti0aJFqY+f/N6W3CFj+PDhqWtYSIAAAQIECBAgQIAAAQLlFBDKKOfcdE2AAAECBAgQIECgKQLHH398XHvttZn2vv/+++PTn/70DjXGjx8fV111VfvxH374oV51002XfXg/X/1xvv3331+qj/2o2h+V+j09yRkYyP/O9LwYt69q1K40ePHiYfv361d43xM8ECBAgQIAAAQIECBAgUE0BoYxqz9fpCBAgQIAAAQIECGQSOPfcc+PUU0/NVOOyyy6LOXPmpK4xfvz4THfs2H7jlStXbv+U7xskIJDRIOgW3UYwo0UH34RjL168OM4888xMO5999tkxadKkTDUsJkCAAAECBAgQIECAAIFyCA -------------------------------- ### Install LlamaIndex Observability Dependencies Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Installs essential Python packages for LlamaIndex workflows, including instrumentation, OpenAI LLM integration, OpenTelemetry observability, LlamaCloud services, and OpenAI embeddings. This setup is crucial for enabling custom tracing and observability features. ```python # Install necessary packages ! pip install -q llama-index-workflows llama-index-instrumentation llama-index-llms-openai llama-index-observability-otel llama-cloud-services llama-index-indices-managed-llama-cloud llama-cloud llama-index-embeddings-openai ``` -------------------------------- ### Python: Llama-cpp-python GPU Acceleration Setup Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet details the setup for GPU acceleration with llama-cpp-python. It specifies parameters like `n_gpu_layers` to offload model layers to the GPU for faster inference. This requires a compatible GPU and correct installation of CUDA or other GPU drivers. ```python from llama_cpp import Llama # Initialize Llama with GPU offloading enabled # n_gpu_layers: Number of model layers to offload to GPU. # Set to -1 to offload all layers, or 0 to use CPU only. # Adjust n_ctx for context window size. llm = Llama( model_path="./models/your_llama_model.gguf", n_gpu_layers=-1, # Offload all layers to GPU n_ctx=2048, verbose=True # Set to False for less output ) # Example prompt for inference prompt = "Write a short story about a space explorer." # Generate text using the GPU-accelerated model output = llm(f"Prompt: {prompt} \nResponse: ", max_tokens=150, stop=["Prompt:"]) print(output['choices'][0]['text']) ``` -------------------------------- ### List Available Workflows via HTTP Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Sends an HTTP GET request to the '/workflows' endpoint of the workflow server to retrieve a list of all registered workflows. The response is a JSON object containing an array of workflow names. ```bash # List available workflows !curl http://localhost:8000/workflows ``` -------------------------------- ### Install Dependencies - Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/agent.ipynb Installs the necessary libraries for building function calling agents with LlamaIndex workflows and OpenAI LLMs. This command should be run in a Python environment. ```python !pip install llama-index-workflows llama-index-llms-openai ``` -------------------------------- ### Install Required Libraries Source: https://github.com/run-llama/workflows-py/blob/main/examples/document_processing.ipynb Installs the necessary Python libraries for LlamaIndex workflows, LlamaCloud services, JSON schema validation, and OpenAI integration. Ensure these are installed in your environment before running the workflow. ```python %pip install llama-index-workflows llama-cloud-services jsonschema, openai ``` -------------------------------- ### Install Dependencies for Langfuse and LlamaIndex Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_langfuse.ipynb Installs the necessary Python packages for Langfuse integration, LlamaIndex Workflows, and OpenInference instrumentation for LlamaIndex. It also includes an optional installation for OpenAI LLM integration. ```python %pip install langfuse llama-index-workflows openinference-instrumentation-llama_index llama-index-instrumentation # Optional if using openai or other llama-index packages %pip install llama-index-llms-openai ``` -------------------------------- ### Install Dependencies for Arize Phoenix and LlamaIndex Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb Installs the required Python packages for Arize Phoenix tracing and LlamaIndex workflows, including optional packages for specific LLM integrations like OpenAI. ```python %pip install arize-phoenix llama-index-workflows llama-index-instrumentation openinference-instrumentation-llama_index %pip install llama-index-llms-openai ``` -------------------------------- ### Install LlamaIndex Observability Dependencies (Python) Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt1.ipynb Installs the necessary LlamaIndex packages for workflows, instrumentation, OpenAI LLMs, and OpenTelemetry observability. Ensure you have a compatible environment for these installations. ```python ! pip install -q llama-index-workflows llama-index-instrumentation llama-index-llms-openai llama-index-observability-otel ``` -------------------------------- ### Python: Basic Class Definition Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb A simple Python class definition demonstrating encapsulation. This example defines a `MyClass` with an initializer and a method. It serves as a foundational example for object-oriented programming in Python. ```python class MyClass: def __init__(self, value): """Initializes MyClass with a given value.""" self.value = value print(f"MyClass instance created with value: {self.value}") def display_value(self): """Displays the current value of the instance.""" print(f"The current value is: {self.value}") # Example usage: # obj = MyClass(10) # obj.display_value() ``` -------------------------------- ### Example Data Transformation (Generic) Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb A generic example illustrating a data transformation process. This snippet is language-agnostic and shows a simple multiplication operation on input data. It can be implemented in various programming languages. ```python def transform_data(input_value): return input_value * 2 ``` ```javascript function transformData(inputValue) { return inputValue * 2; } ``` -------------------------------- ### Initialize and Create Qdrant Collection in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/state_management_with_vector_databases.ipynb Initializes an in-memory Qdrant client and a SentenceTransformer model, then instantiates the `QdrantVectorDatabase` class and creates the specified collection. This demonstrates the setup required before uploading data. ```python qdrant_client = AsyncQdrantClient(":memory:") model = SentenceTransformer("all-MiniLM-L6-v2") collection_name = "workflow_collection" vdb = QdrantVectorDatabase(qdrant_client, model, collection_name) await vdb.create_collection() ``` -------------------------------- ### Python: Initialize and Run Llama Workflow Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Demonstrates how to initialize a Llama workflow and execute it. This function likely handles the setup and invocation of a specific workflow, potentially involving parameters or configurations. ```python def run_llama_workflow(workflow_name: str, params: dict = None): """Initialize and run a Llama workflow. Args: workflow_name: The name of the workflow to run. params: Optional dictionary of parameters for the workflow. Returns: The result of the workflow execution. """ # Placeholder for actual workflow execution logic print(f"Initializing workflow: {workflow_name}") if params: print(f"With parameters: {params}") # ... actual workflow execution code ... return {"status": "completed", "result": "workflow_output"} ``` -------------------------------- ### Run Math Workflow via HTTP POST Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Executes the 'math' workflow by sending an HTTP POST request to '/workflows/math/run'. The request body includes JSON data specifying the operands 'a', 'b', and the 'operation'. Returns the result of the calculation. ```bash # Run math workflow !curl -X POST http://localhost:8000/workflows/math/run \ -H "Content-Type: application/json" \ -d '{"kwargs": {"a": 10, "b": 5, "operation": "multiply"}}' ``` -------------------------------- ### Basic Function Definition and Call in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This example defines a simple function `greet` that takes a name as an argument and prints a greeting. It then demonstrates how to call this function. Functions are reusable blocks of code that perform specific tasks. ```python def greet(name): print(f'Hello, {name}!') greet('Alice') ``` -------------------------------- ### Python: Execute a Workflow Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python code snippet illustrates how to execute a previously defined workflow. It typically involves connecting to a Temporal service and starting an instance of the workflow with specified arguments. ```python import asyncio from temporalio.client import Client async def main(): # Connect to Temporal service client = await Client.connect("localhost:7233") # Start workflow execution result = await client.execute_workflow( MyWorkflow.run, "World", id="my-workflow-id", task_queue="my-task-queue", ) print(f"Workflow result: {result}") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Run Pre-commit Hooks Source: https://github.com/run-llama/workflows-py/blob/main/CLAUDE.md Executes all pre-commit hooks to ensure code quality and consistency across the project. This includes formatting, linting, and other checks before committing code. ```bash uv run -- pre-commit run -a ``` -------------------------------- ### Python: Import and Instantiate Project Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet demonstrates importing the 'Project' class and then instantiating it. It's a common pattern for setting up project-related operations in Python. ```python from langchain_core.tools import Project project = Project( "/run-llama/workflows-py", "/run-llama/workflows-py" ) ``` -------------------------------- ### Check Workflow Server Health Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Sends an HTTP GET request to the '/health' endpoint of the workflow server to verify if it is running and responsive. Returns a JSON object indicating the server's status. ```bash # Hit the health endpoint to see the server is up and running !curl http://localhost:8000/health ``` -------------------------------- ### Python: Get current date Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet retrieves the current date. It uses `datetime.date.today()`. Useful when only the date part is needed, for example, for daily logging or reporting. Requires the `datetime` module. ```python import datetime def get_current_date(): return datetime.date.today() ``` -------------------------------- ### Python: Define a Simple LlamaIndex Workflow Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Shows how to chain multiple workflow steps together to create a complete data processing pipeline. This example defines a workflow that first loads, then transforms, and finally analyzes data. ```python from llama_index.workflows.base import BaseWorkflow # Assume LoadDataWorkflow, TransformDataWorkflow, AnalyzeDataWorkflow are defined as above class SimpleDataPipeline(BaseWorkflow): def __init__(self, load_path: str): self.load_workflow = LoadDataWorkflow(path=load_path) self.transform_workflow = TransformDataWorkflow() self.analyze_workflow = AnalyzeDataWorkflow() def run(self, **kwargs) -> dict: load_output = self.load_workflow.run() transform_output = self.transform_workflow.run(data=load_output) analyze_output = self.analyze_workflow.run(data=transform_output) return analyze_output # Example Usage: pipeline = SimpleDataPipeline(load_path="/data/sample.csv") final_result = pipeline.run() print(final_result) ``` -------------------------------- ### Looping and Conditional Logic in Java Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb Shows how to implement loops (for loop) and conditional statements (if-else) in Java. This is a foundational example for controlling program flow and making decisions based on conditions. ```java public class LoopExample { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i % 2 == 0) { System.out.println(i + " is even"); } else { System.out.println(i + " is odd"); } } } } ``` -------------------------------- ### Download Sample Data using wget Source: https://github.com/run-llama/workflows-py/blob/main/examples/document_processing.ipynb This snippet demonstrates how to download a sample PDF file from a given URL using the `wget` command-line utility. This is a common step for preparing data before processing it with LlamaIndex workflows. Ensure `wget` is installed in your environment. ```shell #!/bin/bash wget https://arxiv.org/pdf/2506.05176 -O qwen3_embed_paper.pdf ``` -------------------------------- ### Download Support Documents Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Downloads PDF documents for technical, sales, and general support from a GitHub repository into a local 'data' directory. This prepares data for indexing. ```bash ! mkdir data ! curl https://raw.githubusercontent.com/run-llama/workflows-observability-support-data/main/data/support/yourbestsoftware_technical.pdf > data/yourbestsoftware_technical.pdf ! curl https://raw.githubusercontent.com/run-llama/workflows-observability-support-data/main/data/support/yourbestsoftware_sales.pdf > data/yourbestsoftware_sales.pdf ! curl https://raw.githubusercontent.com/run-llama/workflows-observability-support-data/main/data/support/yourbestsoftware_general.pdf > data/yourbestsoftware_general.pdf ``` -------------------------------- ### Generate Fibonacci Sequence in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet presents a Python function to generate the Fibonacci sequence up to a specified number of terms. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. This is a classic example in computer science. ```python def generate_fibonacci(n): if n <= 0: return [] elif n == 1: return [0] else: list_fib = [0, 1] while len(list_fib) < n: next_fib = list_fib[-1] + list_fib[-2] list_fib.append(next_fib) return list_fib # Example usage: print(generate_fibonacci(10)) ``` -------------------------------- ### Run Math Workflow without Waiting and Get Handler ID Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Executes the 'math' workflow using the '/run-nowait' endpoint, which returns a handler ID without waiting for the workflow to complete. This is useful for long-running tasks. The handler ID is extracted using 'jq'. ```bash %%bash # Run workflow with nowait handler_id=$(curl -sX POST http://localhost:8000/workflows/math/run-nowait \ -H "Content-Type: application/json" \ -d '{"kwargs": {"a": 100, "b": 25, "operation": "divide"}}' | jq -r ".handler_id" ) printf "Got handler id: ${handler_id}\n\n" # Wait for the workflow to run in background sleep 1 ``` -------------------------------- ### Example Workflow Execution in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet demonstrates how to execute a workflow using the Llamafile library. It shows the basic structure for initializing and running a workflow, highlighting input and output handling. No external dependencies are explicitly mentioned beyond the core library. ```python from llamafile import LocalUserSpace # Initialize a local user space local_user_space = LocalUserSpace() # Define or load your workflow # workflow_definition = {"steps": [...]} # Example: Running a simple workflow (replace with your actual workflow) # For demonstration, assume 'my_workflow' is defined elsewhere or loaded. # For a real scenario, you would load a workflow definition. # Example placeholder for workflow execution: # result = local_user_space.run_workflow(workflow_definition) # print(result) # The actual execution would depend on the defined workflow structure. # This is a conceptual example. print("Workflow execution example (conceptual)") ``` -------------------------------- ### Define FastAPI App and Workflows in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/fastapi_server_example.ipynb Defines an existing FastAPI application with sample routes and custom workflows (UserProcessingWorkflow, NotificationWorkflow). It sets up the WorkflowServer, registers the defined workflows, and mounts the server as a sub-application to the main FastAPI app. The `main` function orchestrates the setup and runs the uvicorn server. ```python %%writefile server.py import uvicorn from fastapi import FastAPI from pydantic import BaseModel from workflows import Workflow, step from workflows.events import StartEvent, StopEvent from workflows.server import WorkflowServer class UserModel(BaseModel): name: str email: str # Existing FastAPI application with some routes app = FastAPI(title="My API with Workflows", version="1.0.0") # Existing API routes @app.get("/") async def root() -> dict: return {"message": "Welcome to My API"} @app.get("/users/{user_id}") async def get_user(user_id: int) -> dict: return { "user_id": user_id, "name": f"User {user_id}", "email": f"user{user_id}@example.com", } @app.post("/users") async def create_user(user: UserModel) -> dict: return {"message": f"Created user {user.name}", "user": user} # Define workflows class UserProcessingWorkflow(Workflow): @step async def process_user(self, ev: StartEvent) -> StopEvent: user_data = getattr(ev, "user_data", {}) name = user_data.get("name", "Unknown") email = user_data.get("email", "unknown@example.com") # Simulate some processing processed_data = { "processed_name": name.upper(), "domain": email.split("@")[1] if "@" in email else "unknown", "status": "processed", } return StopEvent(result=processed_data) class NotificationWorkflow(Workflow): @step async def send_notification(self, ev: StartEvent) -> StopEvent: message = getattr(ev, "message", "Default notification") recipient = getattr(ev, "recipient", "admin@example.com") # Simulate sending notification result = { "notification_id": "notif_123", "message": message, "recipient": recipient, "sent_at": "2024-01-01T12:00:00Z", "status": "sent", } return StopEvent(result=result) def main() -> None: # Create workflow server workflow_server = WorkflowServer() # Register workflows workflow_server.add_workflow("user_processing", UserProcessingWorkflow()) workflow_server.add_workflow("notification", NotificationWorkflow()) # Mount workflow server as sub-application app.mount("/wf-server", workflow_server.app) # run the FastAPI server uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info") if __name__ == "__main__": main() ``` -------------------------------- ### JSON: Example data structure Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb This JSON snippet represents a sample data structure. It includes an array of objects, where each object has properties like 'id', 'name', and 'value'. This is a standard format for data exchange. ```json [ { "id": 1, "name": "Example Item 1", "value": 100 }, { "id": 2, "name": "Example Item 2", "value": 200 } ] ``` -------------------------------- ### Basic HTML Structure with Placeholder Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb A minimal HTML document structure serving as a placeholder. It includes the basic doctype, html, head, and body tags, ready for further content population. This is often used as a starting point for web development. ```html Placeholder Page

Welcome

This is a placeholder for content.

``` -------------------------------- ### Run Greeting Workflow via HTTP POST Source: https://github.com/run-llama/workflows-py/blob/main/examples/server/server_example.ipynb Executes the 'greeting' workflow by sending an HTTP POST request to '/workflows/greeting/run'. The request body includes JSON data specifying the 'name' argument for the workflow. Returns the workflow's result. ```bash # Run greeting workflow !curl -X POST http://localhost:8000/workflows/greeting/run \ -H "Content-Type: application/json" \ -d '{"kwargs": {"name": "Alice"}}' ``` -------------------------------- ### JavaScript: Instantiate Project Class Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Demonstrates how to instantiate the 'Project' class in JavaScript. This likely involves providing configuration or initialization parameters to create a new project object. ```javascript new Project( "/run-llama/workflows-py", "/run-llama/workflows-py" ) ``` -------------------------------- ### Install workflows-py Library Source: https://github.com/run-llama/workflows-py/blob/main/examples/durable_workflows.ipynb Installs the necessary llama-index-workflows package using pip. This is a prerequisite for using the workflows library. ```python !pip install llama-index-workflows ``` -------------------------------- ### Programmatic WorkflowServer Setup (Python) Source: https://github.com/run-llama/workflows-py/blob/main/docs/src/content/docs/workflows/deployment.md This snippet demonstrates how to programmatically create a `WorkflowServer`, define a simple workflow with steps and event handling, add it to the server, and optionally run the server. It requires the `workflows` library and `asyncio` for asynchronous operations. The workflow emits stream events and returns a final result. ```python # my_server.py from workflows import Workflow, step from workflows.context import Context from workflows.events import Event, StartEvent, StopEvent from workflows.server import WorkflowServer import asyncio class StreamEvent(Event): sequence: int # Define a simple workflow class GreetingWorkflow(Workflow): @step async def greet(self, ctx: Context, ev: StartEvent) -> StopEvent: for i in range(3): ctx.write_event_to_stream(StreamEvent(sequence=i)) await asyncio.sleep(0.3) name = getattr(ev, "name", "World") return StopEvent(result=f"Hello, {name}!") greet_wf = GreetingWorkflow() # Create a server instance server = WorkflowServer() # Add the workflow to the server server.add_workflow("greet", greet_wf) # To run the server programmatically (e.g., from your own script) # async def main(): # await server.serve(host="0.0.0.0", port=8080) # # if __name__ == "__main__": # asyncio.run(main()) ``` -------------------------------- ### Logging Setup in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet demonstrates how to set up basic logging in Python using the built-in 'logging' module. It configures the logging level, format, and output stream (e.g., console). This is essential for tracking application behavior, debugging, and monitoring. Proper logging helps in understanding the workflow execution. ```python import logging def setup_logging(level=logging.INFO): """Sets up basic logging configuration. Args: level (int): The logging level (e.g., logging.INFO, logging.DEBUG). """ logging.basicConfig( level=level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # Example Usage: # setup_logging(level=logging.DEBUG) # logging.info('This is an informational message.') # logging.warning('This is a warning.') # logging.error('This is an error message.') ``` -------------------------------- ### Generate Range with Start and Stop Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb This Python snippet generates a sequence of numbers starting from a specified value up to (but not including) another specified value. It uses the `range()` function with two arguments: start and stop. This is commonly used in loops to iterate over a specific number of times or a defined numerical interval. ```python range(1, 10) ``` -------------------------------- ### Python: Launch Arize Phoenix Observability Server Source: https://github.com/run-llama/workflows-py/blob/main/examples/feature_walkthrough.ipynb Launches the Arize Phoenix application, which provides a local UI for visualizing traces and events from instrumented code. It outputs a URL to access the dashboard. ```python import phoenix as px px.launch_app() ``` -------------------------------- ### Python Workflow Execution Example Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Demonstrates a basic workflow execution pattern in Python. This snippet likely represents a simplified execution flow where data is processed through a series of steps. It assumes the existence of predefined processing functions. ```python def execute_workflow(initial_data): processed_data = format_data(initial_data) results = analyze_data(processed_data) final_output = utility_function(results) return final_output ``` -------------------------------- ### Set up a local LLM with `llama_cpp` Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet demonstrates how to set up a local Large Language Model (LLM) using the `llama_cpp` library. It involves specifying the model path, context size, and other relevant parameters for initializing the LLM. ```python from llama_cpp import Llama llm = Llama( model_path="/Users/robert/Desktop/LLM/llama-2-7b-chat.gguf", n_ctx=4096, n_threads=8, n_gpu_layers=0 ) ``` -------------------------------- ### Generate a List of Random Dates in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet shows how to generate a list of random dates within a specified start and end date. It calculates a random number of days to add to the start date. This is useful for creating sample datasets with temporal data, testing date-based logic, or generating random event schedules. Ensure the start date is before the end date. ```python import random import datetime def create_list_of_random_dates(start_date, end_date, count): """Creates a list of 'count' random dates between start_date and end_date.""" time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_dates = [] for _ in range(count): random_number_of_days = random.randrange(days_between_dates) random_date = start_date + datetime.timedelta(days=random_number_of_days) random_dates.append(random_date) return random_dates ``` -------------------------------- ### Create Simple Uppercase Workflow Source: https://github.com/run-llama/workflows-py/blob/main/examples/feature_walkthrough.ipynb Defines and runs a basic workflow that converts an input string to uppercase. It uses the `@step` decorator and `StartEvent`/`StopEvent` for input and output. ```python from workflows import Workflow, step from workflows.events import StartEvent, StopEvent class UppercaseWorkflow(Workflow): @step async def to_upper(self, ev: StartEvent) -> StopEvent: input_text = ev.get("input_text") return StopEvent(result=input_text.upper()) w = UppercaseWorkflow(timeout=10) result = await w.run(input_text="hello") print(result) ``` -------------------------------- ### Python Configuration Loading Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet shows how to load configuration settings, potentially from a file or environment variables. It uses common Python practices for handling configuration data. ```python def load_config(filename="config.yaml"): with open(filename, 'r') as f: config = yaml.safe_load(f) return config config = load_config() ``` -------------------------------- ### Generate a List of Random Datetimes in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet demonstrates how to generate a list of random datetime objects within a specified start and end datetime. It calculates a random time delta and adds it to the start datetime. This is useful for creating realistic temporal datasets for simulations, testing time-series analysis, or generating random event logs. Ensure the start datetime is before the end datetime. ```python import random import datetime def create_list_of_random_datetimes(start_dt, end_dt, count): """Creates a list of 'count' random datetimes between start_dt and end_dt.""" time_between_datetimes = end_dt - start_dt total_seconds = time_between_datetimes.total_seconds() random_datetimes = [] for _ in range(count): random_second = random.randrange(int(total_seconds)) random_datetime = start_dt + datetime.timedelta(seconds=random_second) random_datetimes.append(random_datetime) return random_datetimes ``` -------------------------------- ### Python: Get current date and time Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet gets the current date and time. It uses `datetime.datetime.now()`. Useful for logging, timestamps, and scheduling. Requires the `datetime` module. ```python import datetime def get_current_datetime(): return datetime.datetime.now() ``` -------------------------------- ### Class Definition and Instantiation in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb Demonstrates how to define a class and create instances (objects) from it in Python. This covers constructors (`__init__`) and methods. ```python class Dog: def __init__(self, name, breed): self.name = name self.breed = breed def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy", "Golden Retriever") print(my_dog.name) print(my_dog.breed) print(my_dog.bark()) ``` -------------------------------- ### Starting WorkflowServer via CLI (Bash) Source: https://github.com/run-llama/workflows-py/blob/main/docs/src/content/docs/workflows/deployment.md This command-line instruction shows how to launch a `WorkflowServer` using the `workflows` library's module execution. It takes a Python file containing a `WorkflowServer` instance as an argument. The server defaults to host `0.0.0.0` and port `8080`, configurable via environment variables `WORKFLOWS_PY_SERVER_HOST` and `WORKFLOWS_PY_SERVER_PORT`. ```bash python -m workflows.server my_server.py ``` -------------------------------- ### Python: HTTP GET request Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python snippet performs an HTTP GET request to a specified URL. It uses the `requests` library. Commonly used for fetching data from web APIs. Requires the `requests` library. ```python import requests def http_get(url): response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes return response.json() ``` -------------------------------- ### Creating and Using a Class in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet defines a simple Python class `MyClass` with an initializer and a method. It illustrates object-oriented programming concepts in Python, including instantiation and method invocation. ```python class MyClass: def __init__(self, value): self.value = value def display(self): print(self.value) obj = MyClass(10) obj.display() ``` -------------------------------- ### Get Current Working Directory in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet demonstrates how to get the current working directory (CWD) in Python using `os.getcwd()`. The CWD is the directory from which the Python script is executed. This is useful for relative path operations. ```python import os def get_current_working_directory(): return os.getcwd() # Example usage: # print(f"Current working directory: {get_current_working_directory()}") ``` -------------------------------- ### Get String Length Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb This Python snippet returns the number of characters in a string. It uses the built-in `len()` function, which is a universal way to get the size of sequences in Python. The input is a string, and the output is an integer representing the character count. ```python len(str) ``` -------------------------------- ### Instantiate Workflow with Configuration in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb Demonstrates how to instantiate a workflow object using a configuration dictionary in Python. It imports the `Workflow` class and passes the configuration to its constructor. This is a fundamental step before executing any workflow operations. ```python from workflows.workflow import Workflow workflow = Workflow(config=config) ``` -------------------------------- ### Use Custom StartEvent in Workflow Step Source: https://github.com/run-llama/workflows-py/blob/main/docs/src/content/docs/workflows/customizing_entry_exit_points.md Integrate a custom start event into a workflow step by type-hinting the event parameter with the custom class. This enables access to the custom fields defined in the start event within the step's logic. ```python from workflows.workflow import Workflow, step class JokeFlow(Workflow): ... @step async def generate_joke_from_index( self, ev: MyCustomStartEvent ) -> JokeEvent: # Build a query engine using the index and the llm from the start event query_engine = ev.an_index.as_query_engine(llm=ev.an_llm) topic = query_engine.query( f"What is the closest topic to {ev.a_string_field}" ) # Use the llm attached to the start event to instruct the model prompt = f"Write your best joke about {topic}." response = await ev.an_llm.acomplete(prompt) # Dump the response on disk using the Path object from the event ev.a_path_to_somewhere.write_text(str(response)) # Finally, pass the JokeEvent along return JokeEvent(joke=str(response)) ``` -------------------------------- ### Run Llama Model with Different Configurations (Python) Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb Demonstrates how to run a Llama model with varying configurations for text generation. This allows for customization of parameters like temperature, top_k, and top_p to influence the creativity and coherence of the output. It requires a loaded model and tokenizer. ```python from transformers import AutoModelForCausalLM, AutoTokenizer model_name = "meta-llama/Llama-2-7b-chat-hf" tokenizer_name = "meta-llama/Llama-2-7b-chat-hf" model = AutoModelForCausalLM.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) prompt = "Explain the concept of quantum entanglement in simple terms." inputs = tokenizer(prompt, return_tensors="pt") # Generation with different parameters generations = [ model.generate(**inputs, max_new_tokens=100, temperature=0.7, top_k=50, top_p=0.95), model.generate(**inputs, max_new_tokens=100, temperature=1.0, top_k=0, top_p=1.0) ] for i, output in enumerate(generations): generated_text = tokenizer.decode(output[0], skip_special_tokens=True) print(f"--- Generation {i+1} ---") print(generated_text) print("\n") ``` -------------------------------- ### Get File Size in Python Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet shows how to get the size of a file in bytes using `os.path.getsize()`. This is useful for monitoring disk usage, validating file integrity, or making decisions based on file size. It returns the size in bytes. ```python import os def get_file_size(filepath): try: size = os.path.getsize(filepath) return size except FileNotFoundError: return "File not found." except Exception as e: return f"An error occurred: {e}" # Example usage (assuming 'example.txt' exists): # print(f"Size of 'example.txt': {get_file_size('example.txt')} bytes") ``` -------------------------------- ### Python: Load and Run Llama Models Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This Python code snippet illustrates loading and running Llama models. It typically involves importing the necessary Llama library, specifying the model path, and then performing inference or other model-related tasks. Ensure the Llama model files are accessible and the library is installed. ```python from llama_cpp import Llama def load_and_run_llama(model_path, prompt): # Load the Llama model llm = Llama(model_path=model_path) # Generate text based on the prompt output = llm(prompt) return output # Example Usage: # model_file = "./models/llama-2-7b-chat.gguf" # user_prompt = "What is the capital of France?" # response = load_and_run_llama(model_file, user_prompt) # print(response) ``` -------------------------------- ### JSON: Example Data Structure Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observability_pt2.ipynb This snippet provides an example of a JSON data structure, likely used for configuration or data exchange within the workflows. It includes various data types such as strings, numbers, booleans, arrays, and nested objects. ```json { "id": "test-workflow", "name": "Test Workflow", "description": "A sample workflow for testing purposes.", "steps": [ { "id": "step-1", "name": "Data Ingestion", "action": "ingest_data", "config": { "source": "s3://my-bucket/data/", "format": "csv" } }, { "id": "step-2", "name": "Data Transformation", "action": "transform_data", "depends_on": ["step-1"], "config": { "operations": [ "filter_nulls", "normalize_columns" ] } }, { "id": "step-3", "name": "Model Training", "action": "train_model", "depends_on": ["step-2"], "config": { "model_type": "linear_regression", "hyperparameters": { "learning_rate": 0.01, "epochs": 100 } } } ], "outputs": { "model_path": "s3://my-bucket/models/test-model.pkl" } } ``` -------------------------------- ### Python File I/O Operations Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb Provides examples of basic file input and output operations in Python. This includes reading from and writing to text files. The code demonstrates using context managers (`with open(...)`) for automatic file handling. ```python def write_to_file(filename, content): """Writes content to a file.""" with open(filename, 'w') as f: f.write(content) def read_from_file(filename): """Reads content from a file.""" with open(filename, 'r') as f: return f.read() # Example usage: write_to_file('output.txt', 'Hello, world!\nThis is a test.') file_content = read_from_file('output.txt') print(file_content) ``` -------------------------------- ### Generate Range with Step Source: https://github.com/run-llama/workflows-py/blob/main/examples/observability/workflows_observablitiy_arize_phoenix.ipynb This Python snippet generates a sequence of numbers starting from a specified value, up to a stop value, with a defined increment or decrement (step). It uses the `range()` function with three arguments: start, stop, and step. This is useful for creating arithmetic progressions. ```python range(0, 10, 2) ```