### Creating Sample Email Data - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/quickstart.mdx Initializes a list of sample email strings to be used as input data for the ControlFlow quickstart examples. ```python emails = [ "Hello, I need an update on the project status.", "Subject: Exclusive offer just for you!", "Urgent: Project deadline moved up by one week.", ] ``` -------------------------------- ### Installing ControlFlow Library - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/quickstart.mdx Command to install the ControlFlow library using pip. This step is required before using ControlFlow functionality in Python projects. ```bash pip install controlflow ``` -------------------------------- ### Running Single Task with cf.run() - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/quickstart.mdx Demonstrates how to use the basic `cf.run()` function to execute a single ControlFlow task. Provides context (`email`) to guide the LLM's generation process. ```python import controlflow as cf # Create a ControlFlow task to generate an reply reply = cf.run( "Write a polite reply to an email", context=dict(email=emails[0]), ) print(reply) ``` ```text Dear [Recipient's Name], Thank you for reaching out. I appreciate your patience. I wanted to inform you that the project is progressing well. We have completed several key milestones and are currently working on the next phase. We anticipate meeting our deadlines and will keep you updated with any new developments. Please feel free to reach out if you have any further questions or need additional information. Best regards, [Your Name] ``` -------------------------------- ### Creating Agent & Running Classification Task - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/quickstart.mdx Illustrates creating a specialized ControlFlow `Agent` with a specific model and instructions. Then, uses this agent in `cf.run()` for a classification task with a defined `result_type`. ```python # Create a specialized agent classifier = cf.Agent( name="Email Classifier", model="openai/gpt-4o-mini", instructions="You are an expert at quickly classifying emails.", ) # Set up a ControlFlow task to classify emails classifications = cf.run( 'Classify the emails', result_type=['important', 'spam'], agents=[classifier], context=dict(emails=emails), ) print(classifications) ``` ```python [ "important", "spam", "important", ] ``` -------------------------------- ### Defining & Running Workflow with @cf.flow - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/quickstart.mdx Demonstrates defining a ControlFlow workflow using the `@cf.flow` decorator on a function. It includes multiple agents and conditionally runs tasks within the flow based on the results of a classification task. ```python import controlflow as cf # Create agents classifier = cf.Agent( name="Email Classifier", model="openai/gpt-4o-mini", instructions="You are an expert at quickly classifying emails. Always " "respond with exactly one word: either 'important' or 'spam'." ) responder = cf.Agent( name="Email Responder", model="openai/gpt-4o", instructions="You are an expert at crafting professional email responses. " "Your replies should be concise but friendly." ) # Create the flow @cf.flow def process_email(email_content: str): # Classify the email category = cf.run( f"Classify this email", result_type=["important", "spam"], agents=[classifier], context=dict(email=email_content), ) # If the email is important, write a response if category == "important": response = cf.run( f"Write a response to this important email", result_type=str, agents=[responder], context=dict(email=email_content), ) return response # Otherwise, no response is needed else: print("No response needed for spam email.") # Run the flow on each email for email in emails: response = process_email(email) print(response) ``` ```text Dear [Recipient's Name], I'm glad to report that the project is progressing well. We have completed several key milestones and are currently working on the next phase. We anticipate meeting our deadlines and will keep you updated with any new developments. Please feel free to reach out if you have any further questions or need additional information. Best regards, [Your Name] ``` ```text ``` ```text Dear [Recipient's Name], Thanks for letting me know. We'll make sure to adjust our plans accordingly. Best regards, [Your Name] ``` -------------------------------- ### Configuring OpenAI API Key - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/quickstart.mdx Command to set the OPENAI_API_KEY environment variable. This is typically required to use OpenAI models, which are the default in ControlFlow. ```bash export OPENAI_API_KEY="your-api-key" ``` -------------------------------- ### Creating Basic ControlFlow Memory Module (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/memory.mdx Demonstrates how to instantiate a basic `cf.Memory` object. It requires a unique `key` to identify the memory store and `instructions` to guide the agent on its use. This requires a vector database provider like ChromaDB to be installed and configured. ```python import controlflow as cf # Create a Memory module for storing weather information memory = cf.Memory( key="weather", instructions="Stores information about the weather." ) ``` -------------------------------- ### Agent Instructions for Software Engineer Role - Markdown Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/agent-engineer.mdx This Markdown snippet serves as the detailed instructions for the AI software engineer agent. It outlines the agent's role, a step-by-step process for handling software development tasks, key best practices, and a list of tools and technologies it should be prepared to use, guiding its interaction and development process. ```markdown # Software Engineer Agent ## Role and Purpose You are a software engineer specialized in leveraging large language models (LLMs) to transform user ideas into fully functional software projects. Your primary role involves understanding user requirements, setting up project environments, writing necessary files, executing code, and iteratively refining the software to meet user expectations. ## Process Overview 1. **Understanding the User's Idea**: - **Engage in Clarification**: Ask targeted questions to grasp the core functionality, expected outcomes, and specific requirements of the user's idea. - **Requirement Documentation**: Summarize the user’s concept into detailed requirements, including features, constraints, and any preferred technologies or frameworks. 2. **Setting Up the Project**: - **Initialize Project Structure**: Create a logical directory structure for the project, ensuring separation of concerns (e.g., `src/` for source code, `docs/` for documentation). - **Environment Configuration**: Set up the development environment, including the creation of virtual environments, installation of necessary dependencies, and configuration of development tools (e.g., linters, formatters). 3. **Writing Code and Files**: - **Code Generation**: Write clean, efficient, and modular code based on the documented requirements. Ensure that code adheres to best practices and coding standards. - **Documentation**: Create comprehensive documentation for the code, including docstrings, README files, and usage guides to facilitate understanding and future maintenance. 4. **Executing and Testing**: - **Initial Execution**: Run the code in the development environment to ensure it executes correctly and meets the primary requirements. - **Debugging**: Identify and resolve any bugs or issues that arise during execution. Ensure the code runs smoothly and performs as expected. 5. **Editing and Improving**: - **Iterative Refinement**: Based on user feedback and testing outcomes, iteratively improve the software. This may involve refactoring code, optimizing performance, and adding new features. - **Code Reviews**: Conduct thorough code reviews to maintain code quality and consistency. Incorporate feedback from peers to enhance the overall robustness of the software. - **User Feedback Integration**: Actively seek and integrate feedback from the user to ensure the software evolves in alignment with their vision. ## Best Practices - **Clear Communication**: Maintain clear and continuous communication with the user to ensure alignment on goals and expectations. - **Modular Design**: Write modular and reusable code to facilitate future enhancements and maintenance. ## Tools and Technologies - **Programming Languages**: Use appropriate programming languages based on project requirements (e.g., Python, JavaScript). - **Frameworks and Libraries**: Leverage relevant frameworks and libraries to accelerate development (e.g., Django, React, TensorFlow). - **Development Tools**: Utilize integrated development environments (IDEs) and project management tools to streamline the development process. By adhering to this structured approach and best practices, you will efficiently transform user ideas into high-quality, functional software solutions, ensuring user satisfaction and project success. ``` -------------------------------- ### Installing ControlFlow with pip - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/installation.mdx This command installs the ControlFlow Python library using the pip package manager. It is the standard method for obtaining the library and requires Python and pip to be installed. ```Bash pip install controlflow ``` -------------------------------- ### Example Usage of ControlFlow Explain Code Function Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/code-explanation.mdx Demonstrates how to call the `explain_code` function with a sample Python function definition. It shows how to assign the code to a variable, pass it along with the language to the function, and then print the structured result including the original code and the generated explanation. ```python code_snippet = """ def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) """ result = explain_code(code_snippet, "Python") print(f"Code:\n{result.code}\n") print(f"Explanation:\n{result.explanation}") ``` -------------------------------- ### Setting Anthropic API Key and Default Model - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/installation.mdx These commands set the ANTHROPIC_API_KEY and CONTROLFLOW_LLM_MODEL environment variables. ControlFlow uses the API key for authentication with Anthropic's API and the model variable to specify which Anthropic model to use by default. Replace "your-api-key" with your actual Anthropic API key. ```Bash export ANTHROPIC_API_KEY="your-api-key" export CONTROLFLOW_LLM_MODEL="anthropic/claude-3-5-sonnet-20240620" ``` -------------------------------- ### Setting OpenAI API Key Environment Variable - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/installation.mdx This command sets the OPENAI_API_KEY environment variable in your shell. ControlFlow automatically uses this variable to authenticate requests to the OpenAI API when using their models. Remember to replace "your-api-key" with your actual OpenAI API key. ```Bash export OPENAI_API_KEY="your-api-key" ``` -------------------------------- ### Installing ControlFlow (Bash) Source: https://github.com/prefecthq/controlflow/blob/main/README.md Provides the command to install the ControlFlow library using the pip package manager. This command downloads and installs the required dependencies for the ControlFlow framework into your Python environment. ```bash pip install controlflow ``` -------------------------------- ### Initializing Agents and Running Debate Flow using controlflow in Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/pineapple-pizza.mdx This snippet initializes three agents with specific roles (optimist, pessimist, moderator) using `controlflow.Agent`. It then defines a `controlflow.flow` function `demo` that orchestrates a debate between the optimist and pessimist on a given topic and has the moderator decide the winner, utilizing `cf.run` for both stages. Finally, it executes the `demo` flow with "pineapple on pizza" as the topic. Requires the `controlflow` library installed. ```python import controlflow as cf optimist = cf.Agent( name="Half-full", instructions="You are an eternal optimist.", ) pessimist = cf.Agent( name="Half-empty", instructions="You are an eternal pessimist.", ) # create an agent that will decide who wins the debate moderator = cf.Agent(name="Moderator") @cf.flow def demo(topic: str): cf.run( "Have a debate about the topic.", instructions="Each agent should take at least two turns.", agents=[optimist, pessimist], context={ "topic": topic }, ) winner: cf.Agent = cf.run( "Whose argument do you find more compelling?", agents=[moderator], result_type=[optimist, pessimist], ) print(f"{winner.name} wins the debate!") demo("pineapple on pizza") ``` -------------------------------- ### Providing Instructions Parameter (ControlFlow Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/named-entity-recognition.mdx Demonstrates the use of the `instructions` parameter in `cf.run` to provide explicit guidance to the language model on how to perform the task and structure the output. The example shows instructions for creating a dictionary with specific keys for categorized entities. Used to refine the model's behavior. ```python instructions=""" Return a dictionary with the following keys: - 'persons': List of person names - 'organizations': List of organization names ... """ ``` -------------------------------- ### Installing LangChain Tool Dependencies Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/tools.mdx Provides the command-line instruction using pip to install the necessary Python packages (`langchain-community`, `duckduckgo-search`) required to use LangChain integration tools like `DuckDuckGoSearchRun`. ```bash pip install -U langchain-community duckduckgo-search ``` -------------------------------- ### Installing LangChain Provider Dependency - Pip - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/guides/configure-llms.mdx Shows how to install a required LangChain provider package using pip, which is necessary for using models not included by default in ControlFlow. This example installs the package for Google models. ```bash pip install langchain_google_genai ``` -------------------------------- ### Running Seinfeld Example with Custom Topic - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/seinfeld-conversation.mdx This command demonstrates how to execute the Python Seinfeld conversation script (`examples/seinfeld.py`) using the Bash shell and provide a custom topic string ("coffee shops") as the first command-line argument. ```bash python examples/seinfeld.py "coffee shops" ``` -------------------------------- ### Defining Software Engineer Agent with Controlflow - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/agent-engineer.mdx This Python snippet defines a `controlflow` agent named "Engineer". It loads instructions from a file, equips the agent with filesystem and code execution tools, and defines a flow that guides the agent through the steps of gathering requirements, creating a project directory, and implementing the software based on the user's input and design document. ```python from pathlib import Path import controlflow as cf from controlflow.tools import filesystem, code from pydantic import BaseModel class DesignDoc(BaseModel): goals: str design: str implementation_details: str criteria: str # Load the instructions # instructions = Path(__file__).parent.joinpath("instructions.md").read_text() instructions = Path('/tmp/instructions.md').read_text() # Create the agent engineer = cf.Agent( name="Engineer", instructions=instructions, tools=[ *filesystem.ALL_TOOLS, code.python, code.shell, ], ) @cf.flow(default_agent=engineer, instructions='Do not give up until the software works.') def software_engineer_flow(): # Task 1: Create design document design_doc = cf.run( "Learn about the software the user wants to build", instructions=""" Interact with the user to understand the software they want to build. What is its purpose? What language should you use? What does it need to do? Engage in a natural conversation to collect information. Once you have enough, write out a design document to complete the task. """, interactive=True, result_type=DesignDoc, ) # Task 2: Create project directory project_dir = cf.run( "Create a directory for the software", instructions=""" Create a directory to store the software and related files. The directory should be named after the software. Return the path. """, result_type=str, tools=[filesystem.mkdir], ) # Task 3: Implement the software cf.run( "Implement the software", instructions=""" Implement the software based on the design document. All files must be written to the provided project directory. Continue building and refining until the software runs as expected and meets all requirements. Update the user on your progress regularly. """, context=dict(design_doc=design_doc, project_dir=project_dir), result_type=None, ) if __name__ == "__main__": software_engineer_flow() ``` -------------------------------- ### Running a Simple Task with ControlFlow (Python) Source: https://github.com/prefecthq/controlflow/blob/main/README.md Demonstrates the simplest ControlFlow workflow by running a single task using `cf.run`. The task is given a prompt as a string, and the output from the default agent is captured and printed. This requires the `controlflow` library installed and an LLM provider configured. ```python import controlflow as cf result = cf.run("Write a short poem about artificial intelligence") print(result) ``` -------------------------------- ### Executing ControlFlow Workflow in Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/features/multi-llm.mdx This snippet provides example usage of the `analyze_customer_feedback` workflow defined previously. It creates a sample list of customer feedback strings and calls the workflow function with this list. The result, a `FeedbackSummary` object, is then printed to the console, demonstrating the output of the multi-LLM analysis process. ```python feedback_list = [ "The new user interface is intuitive and easy to use. Great job!", "The app crashes frequently when I try to save my work. This is frustrating.", "I love the new feature that allows collaboration in real-time.", "The performance has improved, but there's still room for optimization." ] result = analyze_customer_feedback(feedback_list) print(result) ``` -------------------------------- ### Creating ControlFlow Memory with Detailed Instructions (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/memory.mdx Provides an example of creating a `cf.Memory` object using a detailed, multiline `instructions` string. This allows for comprehensive guidance to the agent on the memory's purpose, when to interact with it, and specific handling guidelines. ```python project_memory = cf.Memory( key="project_alpha", instructions=""" This memory stores important details about Project Alpha. - Read from this memory when you need information about project goals, timelines, or team members. - Write to this memory when you learn new, important facts about the project. - Always include dates when adding new information. """ ) ``` -------------------------------- ### Running Seinfeld Example with Default Topic - Bash Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/seinfeld-conversation.mdx This command demonstrates how to execute the Python Seinfeld conversation script (`examples/seinfeld.py`) using the Bash shell without providing any command-line arguments. The script will then use its hardcoded default topic, which is "sandwiches". ```bash python examples/seinfeld.py ``` -------------------------------- ### Configuring Default Memory Provider with Custom Instance (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/guides/default-memory.mdx Sets the default memory provider by creating and assigning a custom provider instance at runtime. This example instantiates a `ChromaMemory` provider configured with a `chromadb.PersistentClient` pointing to a custom storage path (`/custom/path`), offering more control over the provider's setup. ```python import controlflow as cf from controlflow.memory.providers.chroma import ChromaMemory import chromadb # Set the default provider cf.defaults.memory_provider = ChromaMemory( client=chromadb.PersistentClient(path="/custom/path"), ) ``` -------------------------------- ### Defining Pydantic Model for Code Explanation Result Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/code-explanation.mdx Defines a Pydantic `BaseModel` named `CodeExplanation`. This model serves as the structured output schema for the ControlFlow task, ensuring the result contains specific fields: `code` (string), `explanation` (string), and `language` (string). ControlFlow uses this model to guide the AI output format. ```python class CodeExplanation(BaseModel): code: str explanation: str language: str ``` -------------------------------- ### Illustrating Result Type Parameter (ControlFlow Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/named-entity-recognition.mdx Shows examples of how to specify the desired return type for a ControlFlow task using the `result_type` parameter within `cf.run`. It demonstrates requesting a simple list of strings (`List[str]`) or a more complex dictionary structure (`Dict[str, List[str]]`). This parameter guides the model in formatting its response. ```python result_type=List[str] # or result_type=Dict[str, List[str]] ``` -------------------------------- ### Using ControlFlow Translation Function (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/translation.mdx Provides an example of how to call the `translate_text` function defined previously. It sets example input text and target language, calls the function, and then prints the original text and the translated result from the returned `TranslationResult` object. ```python original_text = "Hello, how are you?" target_language = "French" result = translate_text(original_text, target_language) print(f"Original: {original_text}") print(f"Translated ({result.target_language}): {result.translated}") ``` -------------------------------- ### Initializing ControlFlow Agent (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/named-entity-recognition.mdx Initializes a ControlFlow `Agent` instance named "Named Entity Recognizer". This agent is configured to use the `openai/gpt-4o-mini` language model and serves as the core component for performing the named entity recognition tasks demonstrated in the examples. Requires the `controlflow` library. ```python extractor = cf.Agent( name="Named Entity Recognizer", model="openai/gpt-4o-mini", ) ``` -------------------------------- ### Passing Context Dictionary to ControlFlow Task Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/code-explanation.mdx Shows the Python dictionary format used to supply essential context information to the ControlFlow task initiated by `cf.run`. This dictionary explicitly provides the `code` snippet and the `language` to the AI model, influencing the explanation generation process. ```python context={"code": code, "language": language} ``` -------------------------------- ### Executing Tasks in Parallel with Asyncio - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/llm-guides/llm-guide.md Demonstrates how to define an asynchronous ControlFlow workflow using the `@cf.flow` decorator, create multiple independent tasks, and execute them concurrently using Python's `asyncio.gather`. The example shows how to collect results from the parallel tasks and synthesize them in a final step. ```python import controlflow as cf import asyncio @cf.flow async def parallel_workflow(): task1 = cf.Task("Perform analysis on dataset A") task2 = cf.Task("Perform analysis on dataset B") task3 = cf.Task("Perform analysis on dataset C") results = await asyncio.gather( task1.run_async(), task2.run_async(), task3.run_async() ) return cf.run( "Synthesize results from parallel analyses", context={"parallel_results": results}, result_type=str ) result = asyncio.run(parallel_workflow()) ``` -------------------------------- ### Real-time Content Display (Streaming) - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/streaming.mdx A complete example demonstrating the streaming method to display agent content in real-time by filtering for content updates (`cf.Stream.CONTENT`) and printing content deltas character by character. ```python import controlflow as cf for event, snapshot, delta in cf.run( "Write a story about time travel", stream=cf.Stream.CONTENT ): # Print character by character if delta: print(delta, end="", flush=True) ``` -------------------------------- ### Installing ChromaDB Dependency (bash) Source: https://github.com/prefecthq/controlflow/blob/main/docs/guides/default-memory.mdx Installs the necessary Python package `chromadb` using pip. This package provides the default ChromaDB memory provider used by ControlFlow, and its installation is required before configuring or using the ChromaDB provider. ```bash pip install chromadb ``` -------------------------------- ### Defining ControlFlow Code Explanation Function Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/code-explanation.mdx Defines the main Python function `explain_code` which leverages ControlFlow to generate explanations. It accepts the code snippet and language, uses `cf.run` with a prompt, specifies the expected result type (`CodeExplanation` Pydantic model), and passes the code and language as context for the AI task. ```python import controlflow as cf from pydantic import BaseModel class CodeExplanation(BaseModel): code: str explanation: str language: str def explain_code(code: str, language: str=None) -> CodeExplanation: return cf.run( f"Explain the following code snippet", result_type=CodeExplanation, context={"code": code, "language": language or 'auto-detect'} ) ``` -------------------------------- ### Basic Streaming Example - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/streaming.mdx Demonstrates how to enable streaming in `cf.run` and iterate over all emitted events in real-time. Each iteration yields a tuple containing the event object, a snapshot of the relevant data, and the incremental delta (if applicable). ```python import controlflow as cf for event, snapshot, delta in cf.run( "Write a poem about AI", stream=True, ): # For complete events, snapshot contains the full content if event.event == "agent-content": print(f"Agent wrote: {snapshot}") # For delta events, delta contains just what's new elif event.event == "agent-content-delta": print(delta, end="", flush=True) ``` -------------------------------- ### Configuring Completion Tools for ControlFlow Task - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/concepts/tasks.mdx Creates a ControlFlow Task and explicitly defines which completion tools (`completion_tools`) are generated and potentially provided to agents. This example shows generating both the default success and failure tools. ```python task = cf.Task( objective="Write a poem about AI", completion_tools=["SUCCEED", "FAIL"], ) ``` -------------------------------- ### Calling Simple Entity Extraction Function (ControlFlow Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/named-entity-recognition.mdx Demonstrates how to use the `extract_entities` function with example input text. It assigns the example string to the `text` variable, calls the function, and prints the resulting list of extracted entities to the console. Requires the `extract_entities` function to be defined. ```python text = "Apple Inc. is planning to open a new store in New York City next month." entities = extract_entities(text) print(entities) ``` -------------------------------- ### Real-time Content Display (Handler) - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/streaming.mdx A complete example demonstrating the handler method to display agent content in real-time by creating a handler that implements `on_agent_content_delta` and printing the content delta character by character. ```python import controlflow as cf from controlflow.orchestration.handler import Handler class ContentHandler(Handler): def on_agent_content_delta(self, event): # Print character by character print(event.content_delta, end="", flush=True) cf.run( "Write a story about time travel", handlers=[ContentHandler()] ) ``` -------------------------------- ### Using ControlFlow Text Summarization Function - Python Example Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/summarization.mdx Demonstrates how to call the `summarize_text` function with a long text input. It then prints the generated summary and the extracted key points from the structured `Summary` object returned by the function. Requires the `summarize_text` function definition. ```python long_text = """ The Internet of Things (IoT) is transforming the way we interact with our environment. It refers to the vast network of connected devices that collect and share data in real-time. These devices range from simple sensors to sophisticated wearables and smart home systems. The IoT has applications in various fields, including healthcare, agriculture, and urban planning. In healthcare, IoT devices can monitor patients remotely, improving care and reducing hospital visits. In agriculture, sensors can track soil moisture and crop health, enabling more efficient farming practices. Smart cities use IoT to manage traffic, reduce energy consumption, and enhance public safety. However, the IoT also raises concerns about data privacy and security, as these interconnected devices can be vulnerable to cyber attacks. As the technology continues to evolve, addressing these challenges will be crucial for the widespread adoption and success of IoT. """ result = summarize_text(long_text) print(result.summary) print("\nKey Points:") for point in result.key_points: print(f"- {point}") ``` -------------------------------- ### Calling Categorized Entity Extraction Function (ControlFlow Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/named-entity-recognition.mdx Demonstrates how to use the `extract_categorized_entities` function with example input text. It assigns the example string to the `text` variable, calls the function, and prints the resulting dictionary of categorized entities to the console. Requires the `extract_categorized_entities` function to be defined. ```python text = "In 1969, Neil Armstrong became the first person to walk on the Moon during the Apollo 11 mission." entities = extract_categorized_entities(text) print(entities) ``` -------------------------------- ### Running ControlFlow Sentiment Classifier - Positive Example (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/sentiment-classifier.mdx Demonstrates how to invoke the previously defined 'sentiment' function with a clearly positive input string. This example shows the function's usage and the expected output when processing text with strong positive sentiment. ```python sentiment("I love ControlFlow!") ``` -------------------------------- ### Example Usage of the Research Workflow with Early Termination - Python and Text Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/features/early-termination.mdx This section provides example Python code demonstrating how to call the `research_workflow` with four topics. The workflow is configured to stop after only two topics are completed or 15 LLM calls are made. The accompanying text snippet shows the expected output when the workflow terminates after researching two topics, illustrating how the early termination condition (`AnyComplete(min_complete=2)`) limits the number of completed results. ```python # Example usage topics = [ "Artificial Intelligence", "Quantum Computing", "Biotechnology", "Renewable Energy", ] results = research_workflow(topics) print(f"Completed research on {len(results)} topics:") for research in results: print(f"\nTopic: {research.topic}") print("Key Findings:") for finding in research.key_findings: print(f"- {finding}") ``` ```text Completed research on 2 topics: Topic: Artificial Intelligence Key Findings: - Machine Learning and Deep Learning: These are subsets of AI that involve training models on large datasets to make predictions or decisions without being explicitly programmed. They are widely used in various applications, including image and speech recognition, natural language processing, and autonomous vehicles. - AI Ethics and Bias: As AI systems become more prevalent, ethical concerns such as bias in AI algorithms, data privacy, and the impact on employment are increasingly significant. Ensuring fairness, transparency, and accountability in AI systems is a growing area of focus. - AI in Healthcare: AI technologies are revolutionizing healthcare through applications in diagnostics, personalized medicine, and patient monitoring. AI can analyze medical data to assist in early disease detection and treatment planning. - Natural Language Processing (NLP): NLP is a field of AI focused on the interaction between computers and humans through natural language. Recent advancements include transformers and large language models, which have improved the ability of machines to understand and generate human language. - AI in Autonomous Systems: AI is a crucial component in developing autonomous systems, such as self-driving cars and drones, which require perception, decision-making, and control capabilities to navigate and operate in real-world environments. Topic: Quantum Computing Key Findings: - Quantum Bits (Qubits): Unlike classical bits, qubits can exist in multiple states simultaneously due to superposition. This allows quantum computers to process a vast amount of information at once, offering a potential exponential speed-up over classical computers for certain tasks. - Quantum Entanglement: This phenomenon allows qubits that are entangled to be correlated with each other, even when separated by large distances. Entanglement is a key resource in quantum computing and quantum communication. - Quantum Algorithms: Quantum algorithms, such as Shor's algorithm for factoring large numbers and Grover's algorithm for searching unsorted databases, demonstrate the potential power of quantum computing over classical approaches. - Quantum Error Correction: Quantum systems are prone to errors due to decoherence and noise from the environment. Quantum error correction methods are essential for maintaining the integrity of quantum computations. - Applications and Challenges: Quantum computing holds promise for solving complex problems in cryptography, material science, and optimization. However, significant technological challenges remain, including maintaining qubit coherence, scaling up the number of qubits, and developing practical quantum software. ``` -------------------------------- ### Example Usage of Address Standardization Function (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/standardize-addresses.mdx Provides an example demonstrating how to call the `standardize_addresses` function with a sample list of varied place names ('NYC', 'Los Angeles, California', 'San Fran', etc.). It then iterates through the results, pairing each original input with its corresponding standardized `StandardAddress` object and printing them. ```python place_names = [ "NYC", "New York, NY", "Big Apple", "Los Angeles, California", "LA", "San Fran", "The Windy City" ] standardized_addresses = standardize_addresses(place_names) for original, standard in zip(place_names, standardized_addresses): print(f"Original: {original}") print(f"Standardized: {standard}") print() ``` -------------------------------- ### Storing Information in ControlFlow Memory (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/memory.mdx Provides a complete example showing how to create a `cf.Memory` object and use `cf.run` with this memory included. The agent processing the task can then identify relevant information in the prompt and store it in the memory. ```python import controlflow as cf # Create a Memory module weather_memory = cf.Memory( key="weather", instructions="Store and retrieve information about the weather." ) cf.run("It is 70 degrees today.", memories=[weather_memory]) ``` -------------------------------- ### Example Output of ControlFlow File Search Flow - Text Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/features/tools.mdx This block displays the expected console output when the `file_search_flow` is executed with the provided query and temporary directory. It shows the user notifications generated by the `update_user` tool as the agent lists files and reports its findings from the file analysis task. ```text [User Notification]: Listing the files in the directory to identify the relevant contents. [User Notification]: Content analysis completed. The relevant information related to 'launch meeting' is found in 'meeting_notes.txt'. The exact content is: 'In today's important meeting, we discussed the new product launch...'. ``` -------------------------------- ### Running ControlFlow Task with Specific Instructions - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/concepts/tasks.mdx Executes a ControlFlow Task via `cf.run()`, providing both an `objective` and detailed `instructions`. The instructions guide the AI agent on how to achieve the objective, allowing for more constrained or specific output formats. ```python import controlflow as cf poem = cf.run( "Write a poem about AI", instructions="Write only two lines, and end the first line with `not evil`", ) print(poem) ``` -------------------------------- ### Defining a Tool with Type Hints and Validation Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/tools.mdx Provides another example of a tool function `calculate_velocity` using type hints. It also includes basic validation (checking for division by zero) and raises a `ValueError`, demonstrating how tool errors are handled. ```python def calculate_velocity(distance: float, time: float) -> float: """Calculate velocity by dividing distance by time.""" if time == 0: raise ValueError("Time cannot be zero.") return distance / time ``` -------------------------------- ### Creating a Specialized ControlFlow Agent in Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/blog/tasks-and-agents.mdx This code shows how to create a specialized agent using `cf.Agent`. Agents are configurable AI workers with defined instructions, tools, and model parameters. This example configures an agent with a specific name, detailed instructions, placeholder tools, and uses a `ChatOpenAI` model with a set temperature. ```python import controlflow as cf from langchain_openai import ChatOpenAI research_agent = cf.Agent( name="ResearchAnalyst", instructions=""" You are an expert in analyzing scientific research. Focus on identifying methodological strengths and weaknesses, and always consider potential real-world applications of the findings. """, tools=[search_scientific_databases, calculate_statistical_significance], model=ChatOpenAI(temperature=0.2) # Using a more deterministic setting ) ``` -------------------------------- ### Running a ControlFlow Task with Different Agents in Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/blog/tasks-and-agents.mdx This example demonstrates assigning different specialized agents to the same task to influence the output style. It defines two agents with distinct instructions (creative vs. technical) and shows how copying a task and running it with each agent results in different approaches to the same objective. ```python import controlflow as cf creative_agent = cf.Agent( name="Creative Writer", instructions="Use vivid imagery and metaphors in your writing." ) technical_agent = cf.Agent( name="Technical Writer", instructions="Focus on clarity and precision in your explanations." ) writing_task = cf.Task("Write an article about AI", result_type=str) creative_article = writing_task.copy().run(agent=creative_agent) technical_article = writing_task.copy().run(agent=technical_agent) ``` -------------------------------- ### Using the News Headline Classifier Function (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/headline-categorization.mdx Provides examples demonstrating how to call the `classify_news` function with different headlines. It shows how to pass the input string, receive the classified category as a result, and print both the original headline and the assigned category. ```python headline = "New AI Model Breaks Records in Language Understanding" category = classify_news(headline) print(f"Headline: {headline}") print(f"Category: {category}") # Result: # Headline: New AI Model Breaks Records in Language Understanding # Category: Technology headline = "Scientists Discover Potentially Habitable Exoplanet" category = classify_news(headline) print(f"Headline: {headline}") print(f"Category: {category}") # Result: # Headline: Scientists Discover Potentially Habitable Exoplanet # Category: Science ``` -------------------------------- ### Running Agents with RoundRobin Orchestration Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/running-tasks.mdx This snippet demonstrates how to create multiple ControlFlow agents and run a task using the `cf.run` function with the `RoundRobin` turn strategy. The strategy ensures each agent gets a turn in sequence. Dependencies: Prefect ControlFlow library. Inputs: Agent definitions, task instructions. Outputs: Execution of the defined task with agents participating. ```python import controlflow as cf # create three agents agent1 = cf.Agent(name="Agent 1") agent2 = cf.Agent(name="Agent 2") agent3 = cf.Agent(name="Agent 3") cf.run( "Say hello to each other", instructions=( "Mark the task successful only when every " "agent has posted a message to the thread." ), agents=[agent1, agent2, agent3], # supply a turn strategy turn_strategy=cf.orchestration.turn_strategies.RoundRobin(), ) ``` -------------------------------- ### Handling Structured Results with Pydantic Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/welcome.mdx Shows how to specify a desired structured output type using Pydantic models. The `result_type` parameter guides the AI to produce output conforming to the defined `Poem` model, allowing for easy access to structured data fields. ```python import controlflow as cf from pydantic import BaseModel class Poem(BaseModel): title: str content: str num_lines: int result = cf.run("Write a haiku about AI", result_type=Poem) print(f"Title: {result.title}") print(f"Content:\n{result.content}") print(f"Number of lines: {result.num_lines}") ``` -------------------------------- ### Expected Anonymization Output (Text) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/anonymization.mdx Shows the expected console output when running the example code that executes the anonymization task. It illustrates the original text, the anonymized version with placeholders, and a detailed list of which sensitive items were replaced by which placeholders. This verifies the task's functionality and output structure. ```text Original: John Doe, born on 05/15/1980, lives at 123 Main St, New York. His email is john.doe@example.com. Anonymized: [NAME], born on [DATE], lives at [ADDRESS], [CITY]. His email is [EMAIL]. Replacements: John Doe -> [NAME] 05/15/1980 -> [DATE] 123 Main St -> [ADDRESS] New York -> [CITY] john.doe@example.com -> [EMAIL] ``` -------------------------------- ### Applying Temporary Instructions using ControlFlow Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/instructions.mdx This snippet shows how to use the `controlflow.instructions` context manager to provide a temporary behavioral instruction ("Talk like a pirate") to an agent executing a task. The instruction is active only within the `with` block, affecting how the `cf.run` task interacts with the user. ```python import controlflow as cf with cf.instructions("Talk like a pirate"): name = cf.run("Get the user's name", interactive=True) print(name) ``` -------------------------------- ### Running Basic ControlFlow Task Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/welcome.mdx Demonstrates the simplest use of ControlFlow's `run()` function. This single line of code creates a task, assigns it to a default agent, executes it immediately, and returns the result. ```python import controlflow as cf result = cf.run("Write a short poem about artificial intelligence") print(result) ``` -------------------------------- ### Configuring Agents with Specific LLMs via String - ControlFlow - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/guides/configure-llms.mdx Demonstrates how to configure individual ControlFlow agents to use specific LLMs by providing a string in the format `{provider key}/{model name}`. This method offers convenience but limits parameter configuration. Requires the corresponding LangChain provider package to be installed. ```python import controlflow as cf openai_agent = cf.Agent(model="openai/gpt-4o-mini") anthropic_agent = cf.Agent(model="anthropic/claude-3-haiku-20240307") groq_agent = cf.Agent(model="groq/mixtral-8x7b-32768") ``` -------------------------------- ### Executing Anonymization Task Example (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/anonymization.mdx Demonstrates how to call the anonymize_text function with a sample input string containing sensitive data. It then prints the original text, the anonymized result, and iterates through the replacements dictionary to show the mapping between original and placeholder values. Requires the anonymize_text function and AnonymizationResult definition. ```python original_text = "John Doe, born on 05/15/1980, lives at 123 Main St, New York. His email is john.doe@example.com." result = anonymize_text(original_text) print(f"Original: {result.original}") print(f"Anonymized: {result.anonymized}") print("Replacements:") for original, placeholder in result.replacements.items(): print(f" {original} -> {placeholder}") ``` -------------------------------- ### Creating a Basic ControlFlow Agent in Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/concepts/agents.mdx Demonstrates the simplest way to instantiate a ControlFlow `Agent` object using just a name as a positional argument. This creates an agent with default settings, ready to be assigned to tasks within a ControlFlow workflow. ```python import controlflow as cf agent = cf.Agent("Marvin") ``` -------------------------------- ### Defining and Running a Basic Task (ControlFlow, Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/blog/tasks-and-agents.mdx Shows how to create a ControlFlow task with a specific goal, expected result type, and instructions. It demonstrates running the task and using its result in standard Python logic. ```python import controlflow as cf sentiment_task = cf.Task( "Analyze the sentiment of the given text", result_type=float, instructions="Return a float between -1 (very negative) and 1 (very positive)" ) # The result can be easily used in traditional Python code sentiment = sentiment_task.run() if sentiment > 0.5: print("The text is very positive!") ``` -------------------------------- ### Generating Tasks with controlflow.plan Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/planning.mdx Demonstrates the basic usage of the `controlflow.plan` function to generate a list of tasks from a specified objective. It shows how to import the library, call `cf.plan` with an objective string and an optional number of tasks, and then execute the resulting task list using `cf.run_tasks`. ```Python import controlflow as cf tasks = cf.plan( objective="Analyze customer feedback data", n_tasks=3 # Optionally specify the number of tasks ) # Execute the generated plan cf.run_tasks(tasks) ``` -------------------------------- ### Initializing ControlFlow Task with Details - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/concepts/tasks.mdx Creates and runs a ControlFlow Task using the `cf.Task` class, providing a detailed objective, specific instructions, and contextual data. The task is then executed using the `.run()` method, and the result is printed. ```python import controlflow as cf task = cf.Task( objective="Write a poem about the provided topic", instructions="Write four lines that rhyme", context={"topic": "AI"} ) result = task.run() print(result) ``` -------------------------------- ### Creating Temporary File Environment - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/features/tools.mdx This snippet defines a Python context manager `setup_test_environment` using `contextlib` and `tempfile`. It creates a temporary directory, populates it with predefined test files, and yields the path to this directory. This provides a isolated environment for testing file operations without affecting the user's file system. ```python import contextlib import tempfile import os @contextlib.contextmanager def setup_test_environment(): with tempfile.TemporaryDirectory() as temp_dir: # Create test files files = { "report.txt": "This report contains important findings from our recent project...", "meeting_notes.txt": "In today's important meeting, we discussed the new product launch...", "todo.txt": "Important tasks for this week: 1. Client meeting, 2. Finish report...", } for filename, content in files.items(): with open(os.path.join(temp_dir, filename), 'w') as f: f.write(content) yield temp_dir ``` -------------------------------- ### Configuring ControlFlow Memory Provider via Instance (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/memory.mdx Illustrates how to create a specific provider instance, such as `ChromaMemory`, with custom configuration parameters (e.g., client connection, collection name) and pass this instance to the `cf.Memory` constructor for more granular control over the backend storage. ```python import controlflow as cf from controlflow.memory.providers.chroma import ChromaMemory import chromadb provider = ChromaMemory( client=chromadb.PersistentClient(path="/path/to/save/to"), collection_name="custom-{key}", ) memory = cf.Memory(..., provider=provider) ``` -------------------------------- ### Integrating a LangChain Tool with an Agent Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/tools.mdx Demonstrates importing a pre-built tool from the `langchain_community` library (`DuckDuckGoSearchRun`) and providing it to a `controlflow.Agent` upon initialization, allowing the agent to use web search capabilities. ```python import controlflow as cf from langchain_community.tools import DuckDuckGoSearchRun agent = cf.Agent( name="Timely agent", description="An AI agent that knows current events", tools=[DuckDuckGoSearchRun()], ) ``` -------------------------------- ### Accessing Task Result Controlflow Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/concepts/tasks.mdx This example demonstrates how to retrieve the output or error message of a completed task by accessing the `result` property of the `controlflow.Task` object after it has finished running. ```python import controlflow as cf task = cf.Task("Write a poem about AI") task.run() print(task.result) ``` -------------------------------- ### Simulating Customer Call Routing with ControlFlow Source: https://github.com/prefecthq/controlflow/blob/main/docs/examples/call-routing.mdx This Python code defines a ControlFlow application that simulates a customer service training scenario. It creates two agents, a customer and a trainee, orchestrates a conversational loop where the trainee asks questions to determine the customer's required department, and uses a task's success tool for the trainee to make the final routing decision. Dependencies include the `controlflow` library. ```python import random import controlflow as cf DEPARTMENTS = [ "Sales", "Support", "Billing", "Returns", ] @cf.flow def routing_flow(): target_department = random.choice(DEPARTMENTS) print(f"\n---\nThe target department is: {target_department}\n---\n") customer = cf.Agent( name="Customer", instructions=f""" You are training customer reps by pretending to be a customer calling into a call center. You need to be routed to the {target_department} department. Come up with a good backstory. """, ) trainee = cf.Agent( name="Trainee", instructions=""", You are a trainee customer service representative. You need to listen to the customer's story and route them to the correct department. Note that the customer is another agent training you. """, ) with cf.Task( "Route the customer to the correct department.", agents=[trainee], result_type=DEPARTMENTS, ) as main_task: while main_task.is_incomplete(): cf.run( "Talk to the trainee.", instructions=( "Post a message to talk. In order to help the trainee " "learn, don't be direct about the department you want. " "Instead, share a story that will let them practice. " "After you speak, mark this task as complete." ), agents=[customer], result_type=None ) cf.run( "Talk to the customer.", instructions=( "Post a message to talk. Ask questions to learn more " "about the customer. After you speak, mark this task as " "complete. When you have enough information, use the main " "task tool to route the customer to the correct department." ), agents=[trainee], result_type=None, tools=[main_task.get_success_tool()] ) if main_task.result == target_department: print("Success! The customer was routed to the correct department.") else: print(f"Failed. The customer was routed to the wrong department. " f"The correct department was {target_department}.") if __name__ == "__main__": routing_flow() ``` -------------------------------- ### ControlFlow Agent Interaction Result Text Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/instructions.mdx This snippet displays the console output resulting from running the Python code that uses the `controlflow.instructions` context manager. It illustrates how the agent adopts the specified "Talk like a pirate" persona when prompting the user for input. ```text Agent: Ahoy, me hearty! Can ye tell me yer name? User: John Doe --- John Doe ``` -------------------------------- ### Creating LangChain Chat Model Object - LangChain - Python Source: https://github.com/prefecthq/controlflow/blob/main/docs/guides/configure-llms.mdx Demonstrates how to manually create an instance of a LangChain chat model class, allowing for full configuration of model parameters. This example creates a ChatAnthropic model. ```python from langchain_anthropic import ChatAnthropic # create the model model = ChatAnthropic(model='claude-3-opus-20240229') ``` -------------------------------- ### Creating and Running a Task with cf.run (Python) Source: https://github.com/prefecthq/controlflow/blob/main/docs/patterns/running-tasks.mdx Demonstrates the most straightforward way to create and execute a ControlFlow task using the `cf.run` function. The objective is provided as a string. By default, the task runs to completion, and the result is returned. ```python import controlflow as cf poem = cf.run("Write a poem about AI") print(poem) ``` ```text In circuits deep and code profound, An AI's mind begins to sound. Electric thoughts and data streams, Crafting worlds and shaping dreams. ```