Retrieval Augmented Generation with Claude 3.5 Sonnet

Featured Imgs 23

In my previous article I presented results comparing Anthropic Claude 3.5 Sonnet and OpenAI GPT-4o models for zero-shot text classification. The results showed that the Claude 3.5 Sonnet significantly outperformed GPT-4o.

These results motivated me to develop a simple retrieval augmented generation system with LangChain that enables the Claude 3.5 Sonnet model to answer questions pertaining to custom documents.

By the end of this article, you will know how to develop a chatbot that uses the Claude 3.5 Sonnet LLM to answer questions on custom documents.

So, let's begin without ado.

Installing and Importing Required Libraries

The following script installs the libraries required to run scripts in this article.

!pip install -U langchain
!pip install -U langchain-anthropic
!pip install langchain-openai
!pip install pypdf
!pip install faiss-cpu

Subsequently, the script below imports the required libraries into your Python application.


from langchain_anthropic import ChatAnthropic

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.chains import create_retrieval_chain
from langchain_core.documents import Document
from langchain.chains import create_history_aware_retriever
from langchain_core.prompts import MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage
import os

Generating Default Response with Claude 3.5 Sonnet

Let's first generate a default response using Claude 3.5 Sonnet LLM in LangChain.

You will need an anthropic API key which you can get here.

Next, create an object of the ChatAnthropic class and pass the anthropic API key, the model ID, and the temperature value to its constructor. The temperature specifies how creative a model should be while generating responses. Higher temperature values allow models to be more creative.

Finally, pass the prompt to the invoke() method of the ChatAnthropic object to generate the model response.

anthropic_api_key = os.environ.get('ANTHROPIC_API_KEY')

llm = ChatAnthropic(model="claude-3-5-sonnet-20240620",
                     anthropic_api_key = anthropic_api_key,
                     temperature = 0.3)

result = llm.invoke("Write a funny poem for an ice cream shop on a beach.")
print(result.content)

Output:

image1.png

The LangChain ChatPromptTemplate class allows you to create a chatbot. The from_messages() method indicates that the conversation should be executed in message format. In this setup, you must specify the value for the user attribute, while the system attribute is optional.

You can use the StrOutputParser class to parse the model response in string format, as shown in the script below:


prompt = ChatPromptTemplate.from_messages([
    ("system", '{assistant}'),
    ("user", "{input}")
])

output_parser = StrOutputParser()

chain = prompt | llm | output_parser

result = chain.invoke(
    {"assistant": "You are a comedian",
     "input": "Write a funny poem for a music store on a beach."}
)
print(result)

Output:

image2.png

RAG with Claude 3.5 Sonnet

Now you know how to call the Claude 3.5 Sonnet LLM in LangChain. In this section, we will augment the Claude 3.5 Sonnet model's knowledge, making it capable of answering questions related to the documents it had not seen during training.

Step 1: Loading and Splitting Documents

We start by loading and splitting the document using PyPDFLoader. In this case, we load "The English Constitution" by Walter Bagehot from a URL.

The following script's load_and_split() method ensures the document is parsed correctly and divided into manageable sections.


loader = PyPDFLoader("https://web.archive.org/web/20170809122528id_/http://global-settlement.org/pub/The%20English%20Constitution%20-%20by%20Walter%20Bagehot.pdf")
docs = loader.load_and_split()
Step 2: Creating Embeddings

Next, we create embeddings for the text using OpenAI API's OpenAIEmbeddings class. We then split the text into smaller chunks with RecursiveCharacterTextSplitter and created a FAISS vector store using the split documents and their embeddings. This step transforms the text into a format suitable for retrieval and similarity search.


openai_key = os.environ.get('OPENAI_API_KEY')

embeddings = OpenAIEmbeddings(openai_api_key = openai_key)

text_splitter = RecursiveCharacterTextSplitter()
documents = text_splitter.split_documents(docs)
vector = FAISS.from_documents(documents, embeddings)
Step 3: Crafting the Prompt Template

The next step is to define a prompt template using the ChatPromptTemplate class. The template instructs the model to answer questions based solely on the provided context, ensuring accurate and relevant responses. The create_stuff_documents_chain function links this template with the language model, forming a document chain that will be used for generating responses.


prompt = ChatPromptTemplate.from_template("""Answer the following question based only on the provided context:

Question: {input}

Context: {context}
"""
)

document_chain = create_stuff_documents_chain(llm, prompt)
Step 4: Setting Up the Retriever

We convert the vector store into a retriever object with vector.as_retriever() method. The retriever, combined with the document chain, forms a retrieval_chain. This setup enables the system to fetch relevant document sections based on the user's query and use them as context for generating answers.


retriever = vector.as_retriever()
retrieval_chain = create_retrieval_chain(retriever, document_chain)
Step 5: Generating Responses

Finally, we define the generate_response() function that takes a query as input, invokes the retrieval chain, and prints the answer.


def generate_response(query):
    response = retrieval_chain.invoke({"input": query})
    print(response["answer"])

To demonstrate the system in action, we run a few example queries as shown below:

Query1:


query = "What is the total number of members of the house of commons?"
generate_response(query)

Output:

image3.png

Query2:


query = "What is the difference between the house of lords and house of commons? How members are elected for both?"
generate_response(query)

Output:

image4.png

Query3:


query = "How many players participate in a football game?"
generate_response(query)

Output:

image5.png

You can see that the model correctly replied to queries related to custom document and refused to generate response to questions that are not related to the document.

Conclusion

The retrieval augmented generation (RAG) technique has revolutionized the development of customized chatbots for various data sources. In this article, we demonstrated how to build a chatbot using the Claude 3.5 Sonnet model to answer questions based on previously unseen documents. This method can be applied to create chatbots capable of querying diverse data types such as PDFs, websites, text documents, and beyond.

I encourage you to leverage Claude 3.5 Sonnet to develop your custom chatbots, explore its powerful capabilities, and share your experience and feedback in the comments section.

Tales Of An Eternal Summer (July 2024 Wallpapers Edition)

Fotolia Subscription Monthly 4685447 Xl Stock

For many of us, July is the epitome of summer. The time for spending every free minute outside to enjoy the sun and those seemingly endless summer days, be it in a nearby park, by a lake, or on a trip exploring new places. So why not bring a bit of that summer joy to your desktop, too?

For this month’s wallpapers post, artists and designers from across the globe once again tickled their creativity to capture the July feeling in a collection of desktop wallpapers. They all come in versions with and without a calendar for July 2024 and can be downloaded for free — as it has been a Smashing tradition for more than 13 years already. A huge thank-you to everyone who submitted their artworks this month — this post wouldn’t exist without you!

As a little bonus goodie, we also compiled a selection of July favorites from our wallpapers archives at the end of this post. So maybe you’ll discover one of your almost-forgotten favorites in here, too? Have a fantastic July, no matter what your plans are!

  • You can click on every image to see a larger preview,
  • We respect and carefully consider the ideas and motivation behind each and every artist’s work. This is why we give all artists the full freedom to explore their creativity and express emotions and experience through their works. This is also why the themes of the wallpapers weren’t anyhow influenced by us but rather designed from scratch by the artists themselves.
  • Submit a wallpaper!
    Did you know that you could get featured in our next wallpapers post, too? We are always looking for creative talent.

Diving Among Corals

“The long-awaited vacation is coming closer. After working all year, we find ourselves with months that, although we don’t stop completely, are lived differently. We enjoy the days and nights more, and if we can, the beach will keep us company. Therefore, we’ll spend this month in Australia, enjoying the coral reefs and diving without limits.” — Designed by Veronica Valenzuela from Spain.

Level Up

“Join gamers worldwide on National Video Game Day to honor the rich history and vibrant culture of gaming. Enjoy exclusive discounts on top titles, participate in exciting online tournaments, and dive into special events featuring your favorite games. Whether you're a casual player or a dedicated enthusiast, there’s something for everyone to celebrate on this epic day!” — Designed by PopArt Studio from Serbia.

Bigfoot And The Little Girl

“This heartwarming moment captures an unlikely friendship of a gentle Bigfoot and an adorable little girl set against the backdrop of a magical and serene evening in nature.” — Designed by Reethu M from London.

Good Night

Designed by Ricardo Gimenes from Sweden.

Floral Elegance Of July

“The inspiration came from the lush gardens and floral landscapes that thrive in the height of summer. I wanted to bring the elegance and tranquility of these blooming flowers into a calendar that people can enjoy throughout the month of July.” — Designed by Hyfa K from India.

No More Hugs

Designed by Ricardo Gimenes from Sweden.

Olympics Stadium

“We have been waiting for it for many months: The Paris 2024 Olympics Games are coming in July! My drawing is a vision of the joyful activity of athletes in the stadium, with only colored tracks. I chose to use the colors of the Olympics rings. Let’s go to Paris or watch it on TV.” — Designed by Philippe Brouard from France.

Full Buck Moon

“July is the month of the full buck moon, named after the fact that many deer regrow their antlers around this time. It is also when the United States celebrate their Independence Day with fireworks and fun. I decided to combine these aspects into a magical encounter during the fourth of July. It takes place in a field of larkspur which is a flower associated with July.” — Designed by Quincy van Geffen from the Netherlands.

Celebrating World Chocolate Day

“World Chocolate Day, celebrated on July 7th, invites chocolate lovers worldwide to indulge in their favorite treat. Commemorating chocolate’s introduction to Europe, this day celebrates its global popularity. Enjoy dark, milk, or white chocolate, bake delicious desserts, and share the sweetness with loved ones.” — Designed by Reethu M from London.

Birdie July

Designed by Lívi Lénárt from Hungary.

Summer Cannonball

“Summer is coming in the northern hemisphere and what better way to enjoy it than with watermelons and cannonballs.” — Designed by Maria Keller from Mexico.

In Space

Designed by Lieke Dol from the Netherlands.

A Flamboyance Of Flamingos

“July in South Africa is dreary and wintery so we give all the southern hemisphere dwellers a bit of color for those gray days. And for the northern hemisphere dwellers a bit of pop for their summer!” — Designed by Wonderland Collective from South Africa.

Eternal Summer

“And once you let your imagination go, you find yourself surrounded by eternal summer, unexplored worlds, and all-pervading warmth, where there are no rules of physics and colors tint the sky under your feet.” — Designed by Ana Masnikosa from Belgrade, Serbia.

Day Turns To Night

Designed by Xenia Latii from Germany.

Tropical Lilies

“I enjoy creating tropical designs. They fuel my wanderlust and passion for the exotic, instantaneously transporting me to a tropical destination.” — Designed by Tamsin Raslan from the United States.

Road Trip In July

“July is the middle of summer, when most of us go on road trips, so I designed a calendar inspired by my love of traveling and summer holidays.” — Designed by Patricia Coroi from Romania.

The Ancient Device

Designed by Ricardo Gimenes from Sweden.

Taste Like Summer

“In times of clean eating and the world of superfoods there is one vegetable missing. An old, forgotten one. A flower actually. Rare and special. Once it had a royal reputation (I cheated a bit with the blue). The artichocke — this is my superhero in the garden! I am a food lover — you too? Enjoy it — dip it!” — Designed by Alexandra Tamgnoué from Germany.

Island River

“Make sure you have a refreshing source of ideas, plans and hopes this July. Especially if you are to escape from urban life for a while.” — Designed by Igor Izhik from Canada.

Cactus Hug

Designed by Ilaria Bagnasco from Italy.

Under The Enchanting Moonlight

“Two friends sat under the enchanting moonlight, enjoying the serene ambiance as they savoured their cups of tea. It was a rare and precious connection that transcended the ordinary, kindled by the magic of the moonlight. Eventually, as the night began to wane, they reluctantly stood, their empty cups in hand. They carried with them the memories and the tranquility of the moonlit tea session, knowing that they would return to this special place to create new memories in the future.” — Designed by Bhabna Basak from India.

DJ Little Bird

Designed by Ricardo Gimenes from Sweden.

Heated Mountains

“Warm summer weather inspired the color palette.” — Designed by Marijana Pivac from Croatia.

July Flavor

Designed by Natalia Szendzielorz from Poland.

Summer Heat

Designed by Xenia Latii from Berlin, Germany.

Mason Jar

“Make the days count this summer!” — Designed by Meghan Pascarella from the United States.

Summer Essentials

“A few essential items for the summertime weather at the beach, park, and everywhere in-between.” — Designed by Zach Vandehey from the United States.

Captain Amphicar

“My son and I are obsessed with the Amphicar right now, so why not have a little fun with it?” — Designed by 3 Bicycles Creative from the United States.

Hotdog

Designed by Ricardo Gimenes from Sweden.

Less Busy Work, More Fun!

Designed by ActiveCollab from the United States.

Sweet Summer

“In summer everything inspires me.” — Designed by Maria Karapaunova from Bulgaria.

Fire Camp

“What’s better than a starry summer night with an (unexpected) friend around a fire camp with some marshmallows? Happy July!” — Designed by Etienne Mansard from the UK.

Riding In The Drizzle

“Rain has come, showering the existence with new seeds of life. Everywhere life is blooming, as if they were asleep and the falling music of raindrops have awakened them. Feel the drops of rain. Feel this beautiful mystery of life. Listen to its music, melt into it.” — Designed by DMS Software from India.

An Intrusion Of Cockroaches

“Ever watched Joe’s Apartment when you were a kid? Well, that movie left a soft spot in my heart for the little critters. Don’t get me wrong: I won’t invite them over for dinner, but I won’t grab my flip flop and bring the wrath upon them when I see one running in the house. So there you have it… three roaches… bringing the smack down on that pesky human… ZZZZZZZAP!!” — Designed by Wonderland Collective from South Africa.

July Rocks!

Designed by Joana Moreira from Portugal.

Frogs In The Night

“July is coming and the nights are warmer. Frogs look at the moon while they talk about their day.” — Designed by Veronica Valenzuela from Spain.

Opengl, java background color rendering problem

Featured Imgs 23

Hello,

I have simple problem for professionalist (that i think ) but i asked all available AI about it and none was able to help and solve problem. so nothing is able to help me in this.

I have simple app that show 3 colored axes and camera that move around this scene by mouse click-hold . the problem is that after run appear first white backfround of frame for a second then its normal black background. i dont want this white at beginning.
can you tell me what in code change to get rid of this white flash at beginning ? I tried already plenty things.

This is the project code IntellJ, java , maven , with additional newest libraries lwjgl (lwjgl-release-3.31) and joml ( joml-1.10.61 ), this is whole code of 3d opengl - app 2 classes : Main and Camera , code is :

package org.example;

import org.joml.Matrix4f;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.MemoryStack;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Objects;

import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.system.MemoryUtil.NULL;

public class Main {

    private long window;
    private Camera camera;
    private float lastMouseX, lastMouseY;
    private boolean firstMouse = true;
    private boolean mousePressed = false;

    public void run() {
        init();
        loop();

        glfwFreeCallbacks(window);
        glfwDestroyWindow(window);

        glfwTerminate();
        Objects.requireNonNull(glfwSetErrorCallback(null)).free();
    }

    private void init() {
        GLFWErrorCallback.createPrint(System.err).set();

        if (!glfwInit()) {
            throw new IllegalStateException("Unable to initialize GLFW");
        }

        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
        glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
        // Request a double-buffered window
        glfwWindowHint(GLFW_DOUBLEBUFFER, GL_TRUE);

        window = glfwCreateWindow(800, 600, "3D Scene", NULL, NULL);
        if (window == NULL) {
            throw new RuntimeException("Failed to create the GLFW window");
        }

        glfwSetCursorPosCallback(window, (window, xpos, ypos) -> {
            if (firstMouse) {
                lastMouseX = (float) xpos;
                lastMouseY = (float) ypos;
                firstMouse = false;
            }

            if (mousePressed) {
                float dx = (float) xpos - lastMouseX;
                float dy = (float) ypos - lastMouseY;
                lastMouseX = (float) xpos;
                lastMouseY = (float) ypos;

                camera.rotate(dy * 0.1f, dx * 0.1f);
            }
        });

        glfwSetMouseButtonCallback(window, (window, button, action, mods) -> {
            if (button == GLFW_MOUSE_BUTTON_LEFT) {
                if (action == GLFW_PRESS) {
                    mousePressed = true;
                    firstMouse = true; // Reset firstMouse when the button is pressed
                } else if (action == GLFW_RELEASE) {
                    mousePressed = false;
                }
            }
        });

        glfwSetScrollCallback(window, (window, xoffset, yoffset) -> {
            camera.zoom((float) yoffset * -0.5f);
        });

        glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
            if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) {
                glfwSetWindowShouldClose(window, true);
            }
        });

        try (MemoryStack stack = stackPush()) {
            IntBuffer pWidth = stack.mallocInt(1);
            IntBuffer pHeight = stack.mallocInt(1);

            glfwGetWindowSize(window, pWidth, pHeight);

            GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());

            glfwSetWindowPos(
                    window,
                    (vidmode.width() - pWidth.get(0)) / 2,
                    (vidmode.height() - pHeight.get(0)) / 2
            );
        }

        glfwMakeContextCurrent(window);
        glfwSwapInterval(1);
        glfwShowWindow(window);

        GL.createCapabilities();

        glEnable(GL_DEPTH_TEST);

        // Set the projection matrix
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        float aspectRatio = 800.0f / 600.0f;
        glFrustum(-aspectRatio, aspectRatio, -1, 1, 1, 100);

        camera = new Camera(20, 30, 45);
    }

    private void loop() {
        // Set the clear color explicitly
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

        while (!glfwWindowShouldClose(window)) {
            // Clear the color and depth buffers
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            Matrix4f viewMatrix = camera.getViewMatrix();
            FloatBuffer fb = org.lwjgl.BufferUtils.createFloatBuffer(16);
            viewMatrix.get(fb);

            glMatrixMode(GL_MODELVIEW);
            glLoadMatrixf(fb);

            drawAxes();

            glfwSwapBuffers(window);
            glfwPollEvents();
        }
    }


    private void drawAxes() {
        glBegin(GL_LINES);

        // X axis in red
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(-20.0f, 0.0f, 0.0f);
        glVertex3f(20.0f, 0.0f, 0.0f);

        // Y axis in green
        glColor3f(0.0f, 1.0f, 0.0f);
        glVertex3f(0.0f, -20.0f, 0.0f);
        glVertex3f(0.0f, 20.0f, 0.0f);

        // Z axis in yellow
        glColor3f(1.0f, 1.0f, 0.0f);
        glVertex3f(0.0f, 0.0f, -20.0f);
        glVertex3f(0.0f, 0.0f, 20.0f);

        glEnd();
    }

    public static void main(String[] args) {
        new Main().run();
    }
}

and Camera code :

package org.example;
import org.joml.Matrix4f;
import org.joml.Vector3f;

public class Camera {

private Vector3f position;
private float pitch;
private float yaw;
private float distance;

public Camera(float distance, float pitch, float yaw) {
    this.position = new Vector3f(0, 0, 0);
    this.pitch = pitch;
    this.yaw = yaw;
    this.distance = distance;
}

public Matrix4f getViewMatrix() {
    Matrix4f viewMatrix = new Matrix4f();
    viewMatrix.identity();

    // Calculate the camera position based on spherical coordinates
    float x = (float) (distance * Math.sin(Math.toRadians(pitch)) * Math.cos(Math.toRadians(yaw)));
    float y = (float) (distance * Math.cos(Math.toRadians(pitch)));
    float z = (float) (distance * Math.sin(Math.toRadians(pitch)) * Math.sin(Math.toRadians(yaw)));

    position.set(x, y, z);

    viewMatrix.lookAt(position, new Vector3f(0, 0, 0), new Vector3f(0, 1, 0));
    return viewMatrix;
}

public void rotate(float pitchDelta, float yawDelta) {
    this.pitch += pitchDelta;
    this.yaw += yawDelta;
}

public void zoom(float distanceDelta) {
    this.distance += distanceDelta;
    if (this.distance < 1.0f) {
        this.distance = 1.0f; // Prevent camera from getting too close
    }
}

public Vector3f getPosition() {
    return position;
}

public float getPitch() {
    return pitch;
}

public float getYaw() {
    return yaw;
}

public float getDistance() {
    return distance;
}


}

and pom.xml file is :

4.0.0
<groupId>org.example</groupId>
<artifactId>3dscene</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
</properties>

<dependencies>
    <!-- LWJGL dependencies -->
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl-glfw</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl-opengl</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl-stb</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl</artifactId>
        <version>3.3.1</version>
        <classifier>natives-windows</classifier>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl-glfw</artifactId>
        <version>3.3.1</version>
        <classifier>natives-windows</classifier>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl-opengl</artifactId>
        <version>3.3.1</version>
        <classifier>natives-windows</classifier>
    </dependency>
    <dependency>
        <groupId>org.lwjgl</groupId>
        <artifactId>lwjgl-stb</artifactId>
        <version>3.3.1</version>
        <classifier>natives-windows</classifier>
    </dependency>

    <!-- JOML dependency -->
    <dependency>
        <groupId>org.joml</groupId>
        <artifactId>joml</artifactId>
        <version>1.10.5</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>sonatype</id>
        <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
    </repository>
</repositories>

Comparing GPT-4o vs Claude 3.5 Sonnet for Zero Shot Text Classification

Featured Imgs 23

On June 20, 2024, Anthropic released the Claude 3.5 sonnet large language model. Claude claims it to be the state-of-the-art model for many natural language processing tasks, surpassing the OpenAI GPT-4o model.

My first test for comparing two large language models is their zero-shot text classification ability. In this article, I will compare the Antropic Claude 3.5 sonnet with the OpenAI GPT-4o model for zero-shot tweet sentiment classification.

So, let's begin without ado.

Importing and Installing Required Libraries

The following script installs the Anthropic and OpenAI libraries to access the corresponding APIs.


!pip install anthropic
!pip install openai

The script below imports the required libraries into your Python application.


import os
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import anthropic
from openai import OpenAI

Importing and Preprocessing the Dataset

We will use the Twitter US Airline Sentiment dataset to perform zero-shot classification. You can download the dataset from Kaggle.

The following script imports the dataset into a Pandas DataFrame.

## Dataset download link
## https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment?select=Tweets.csv

dataset = pd.read_csv(r"D:\Datasets\tweets.csv")
print(dataset.shape)
dataset.head()

Output:

image1.png

Tweet sentiment falls into three categories: neutral, positive, and negative. For comparison, we will filter 100 tweets. The neutral, positive, and negative categories will contain 34, 33, and 33 tweets, respectively.

# Remove rows where 'airline_sentiment' or 'text' are NaN
dataset = dataset.dropna(subset=['airline_sentiment', 'text'])

# Remove rows where 'airline_sentiment' or 'text' are empty strings
dataset = dataset[(dataset['airline_sentiment'].str.strip() != '') & (dataset['text'].str.strip() != '')]

# Filter the DataFrame for each sentiment
neutral_df = dataset[dataset['airline_sentiment'] == 'neutral']
positive_df = dataset[dataset['airline_sentiment'] == 'positive']
negative_df = dataset[dataset['airline_sentiment'] == 'negative']

# Randomly sample records from each sentiment
neutral_sample = neutral_df.sample(n=34)
positive_sample = positive_df.sample(n=33)
negative_sample = negative_df.sample(n=33)

# Concatenate the samples into one DataFrame
dataset = pd.concat([neutral_sample, positive_sample, negative_sample])

# Reset index if needed
dataset.reset_index(drop=True, inplace=True)

# print value counts
print(dataset["airline_sentiment"].value_counts())

Output:

image2.png

Zero Shot Text Classification with GPT-4o

We will first perform zero-shot text classification with GPT-4o. Remember to get your OpenAI API key before executing the following script.

The script below defines a function find_sentiment() that accepts the client and model parameters. The client corresponds to the client, i.e., anthropic or OpenAI, while the model corresponds to Claude 3.5 Sonnet or GPT-4o.

The find_sentiment() function iterates through all the tweets from the filtered dataset and predicts sentiment for each tweet. The predicted sentiments are then compared with the actual sentiment values to determine the model's accuracy.


def find_sentiment(client, model):

    tweets_list = dataset["text"].tolist()


    all_sentiments = []

    i = 0
    exceptions = 0
    while i < len(tweets_list):

        try:
            tweet = tweets_list[i]
            content = """What is the sentiment expressed in the following tweet about an airline?
            Select sentiment value from positive, negative, or neutral. Return only the sentiment value in small letters.
            tweet: {}""".format(tweet)

            sentiment_value = client.chat.completions.create(
                                  model= model,
                                  temperature = 0,
                                  max_tokens = 10,
                                  messages=[
                                        {"role": "user", "content": content}
                                    ]
                                ).choices[0].message.content

            all_sentiments.append(sentiment_value)
            i = i + 1
            print(i, sentiment_value)

        except Exception as e:
            print("===================")
            print("Exception occurred:", e)
            exceptions += 1

    print("Total exception count:", exceptions)
    accuracy = accuracy_score(all_sentiments, dataset["airline_sentiment"])
    print("Accuracy:", accuracy)

Next, we create an OpenAI client and pass the client object along with the gpt-4o model to predict sentiments.


%%time
client = OpenAI(
    # This is the default and can be omitted
    api_key = os.environ.get('OPENAI_API_KEY'),
)
model = "gpt-4o"

find_sentiment(client, model)

Output:

image3.png

The above output shows that GPT-4o achieved an accuracy of 76%.

Zero Shot Text Classification with Claude 3.5-Sonnet

Let's now predict the sentiment for the same set of tweets using the Claude 3.5 sonnet model. We define the find_sentiment_claude() function which is similar to the find_sentiment() function, but predicts sentiments using the Claude 3.5 sonnet model.


def find_sentiment_claude(client, model):

    tweets_list = dataset["text"].tolist()


    all_sentiments = []

    i = 0
    exceptions = 0
    while i < len(tweets_list):

        try:
            tweet = tweets_list[i]
            content = """What is the sentiment expressed in the following tweet about an airline?
            Select sentiment value from positive, negative, or neutral. Return only the sentiment value in small letters.
            tweet: {}""".format(tweet)

            sentiment_value = client.messages.create(
                                model= model,
                                max_tokens=10,
                                temperature=0.0,
                                messages=[
                                    {"role": "user", "content": content}
                                ]
                            ).content[0].text

            all_sentiments.append(sentiment_value)
            i = i + 1
            print(i, sentiment_value)

        except Exception as e:
            print("===================")
            print("Exception occurred:", e)
            exceptions += 1

    print("Total exception count:", exceptions)
    accuracy = accuracy_score(all_sentiments, dataset["airline_sentiment"])
    print("Accuracy:", accuracy)

The script below calls the find_sentiment_claude() function using the anthropic client and the claude-3-5-sonnet-20240620 (the id for the Claude 3.5 sonnet) model.


%%time
client = anthropic.Anthropic(
    # defaults to os.environ.get("ANTHROPIC_API_KEY")
    api_key = os.environ.get('ANTHROPIC_API_KEY')
)

model = "claude-3-5-sonnet-20240620"

find_sentiment_claude(client, model)

Output:

image4.png

The above output shows that the Claude 3.5 Sonnet model achieved an accuracy of 83%, which is significantly better than the GPT-4o model.

Final Verdict

Here is an overall comparison between the Claude Sonnet 3.5 and the GPT-4o model.

image5.png

Given the price, performance, and context window size, I prefer the Claude 3.5 Sonnet over other proprietary models such as GPT-4o.

Feel free to share your opinions. I would be very interested in any results you obtain using the two models.

Increase Your Revenue with Our New Woo Affiliate Program

Featured Imgs 23
We're re-launching the Woo Affiliate Program to help you generate new revenue by promoting the web's most trusted and popular WooCommerce solutions. Participating affiliates will be able to monetize their site's traffic by promoting 800+ products and services from the Woo Marketplace alongside the full range of Automattic's product suite, including WordPress.com hosting packages, domain registration, Jetpack, Sensei LMS, and more. 

How To Improve Your Microcopy: UX Writing Tips For Non-UX Writers

Category Image 073

Throughout my UX writing career, I’ve held many different roles: a UX writer in a team of UX writers, a solo UX writer replacing someone who left, the first and only UX writer at a company, and even a teacher at a UX writing course, where I reviewed more than 100 home assignments. And oh gosh, what I’ve seen.

Crafting microcopy is not everyone’s strong suit, and it doesn’t have to be. Still, if you’re a UX designer, product manager, analyst, or marketing content writer working in a small company, on an MVP, or on a new product, you might have to get by without a UX writer. So you have the extra workload of creating microcopy. Here are some basic rules that will help you create clear and concise copy and run a quick health check on your designs.

Ensure Your Interface Copy Is Role-playable
Why it’s important:
  • To create a friendly, conversational experience;
  • To work out a consistent interaction pattern.

When crafting microcopy, think of the interface as a dialog between your product and your user, where:

  • Titles, body text, tooltips, and so on are your “phrases.”
  • Button labels, input fields, toggles, menu items, and other elements that can be tapped or selected are the user’s “phrases.”

Ideally, you should be able to role-play your interface copy: a product asks the user to do something — the user does it; a product asks for information — the user types it in or selects an item from the menu; a product informs or warns the user about something — the user takes action.

For example, if your screen is devoted to an event and the CTA is for the user to register, you should opt for a button label like “Save my spot” rather than “Save your spot.” This way, when a user clicks the button, it’s as if they are pronouncing the phrase themselves, which resonates with their thoughts and intentions.

Be Especially Transparent And Clear When It Comes To Sensitive Topics
Why it’s important: To build trust and loyalty towards your product.

Some topics, such as personal data, health, or money, are extremely sensitive for people. If your product involves any limitations, peculiarities, or possible negative outcomes related to these sensitive topics, you should convey this information clearly and unequivocally. You will also need to collaborate with your UX/UI Designer closely to ensure you deliver this information in a timely manner and always make it visible without requiring the user to take additional actions (e.g., don’t hide it in tooltips that are only shown by tapping).

Here’s a case from my work experience. For quite some time, I’ve been checking homework assignments for a UX writing course. In this course, all the tasks have revolved around an imaginary app for dog owners. One of the tasks students worked on was creating a flow for booking a consultation with a dog trainer. The consultation had to be paid in advance. In fact, the money was blocked on the user’s bank card and charged three hours before the consultation. That way, a user could cancel the meeting for free no later than three hours before the start time. A majority of the students added this information as a tooltip on the checkout screen; if a user didn’t tap on it, they wouldn’t be warned about the possibility of losing money.

In a real-life situation, this would cause immense negativity from users: they may post about it on social media, and it will show the company in a bad light. Even if you occasionally resort to dark patterns, make sure you can afford any reputational risks.

So, when creating microcopy on sensitive topics:

  • Be transparent and honest about all the processes and conditions. For example, you’re a fintech service working with other service providers. Because of that, you have fees built into transactions but don’t know the exact amount. Explain to users how the fees are calculated, their approximate range (if possible), and where users can see more precise info.
  • Reassure users that you’ll be extremely careful with their data. Explain why you need their data, how you will use it, store and protect it from breaches, and so on.
  • If some restrictions or limitations are implied, provide options to remove them (if possible).

Ensure That The Button Label Accurately Reflects What Happens Next
Why it’s important:
  • To make your interface predictable, trustworthy, and reliable;
  • To prevent user frustration.

The button label should reflect the specific action that occurs when the user clicks or taps it.

It might seem valid to use a button label that reflects the user’s goal or target action, even if it actually happens a bit later. For example, if your product allows users to book accommodations for vacations or business trips, you might consider using a “Book now” button in the booking flow. However, if tapping it leads the user to an order screen where they need to select a room, fill out personal details, and so on, the accommodation is not booked immediately. So you might want to opt for “Show rooms,” “Select a rate,” or another button label that better reflects what happens next.

Moreover, labels like “Buy now” or “Book now” might seem too pushy and even off-putting (especially when it comes to pricey products involving a long decision-making process), causing users to abandon your website or app in favor of ones with buttons that create the impression they can browse peacefully for as long as they need. You might want to let your users “Explore,” “Learn more,” “Book a call,” or “Start a free trial” first.

As a product manager or someone with a marketing background, you might want to create catchy and fancy button labels to boost conversion rates. For instance, when working on an investment app, you might label a button for opening a brokerage account as “Become an investor.” While this might appeal to users’ egos, it can also come across as pretentious and cheap. Additionally, after opening an account, users may still need to do many things to actually become investors, which can be frustrating. Opt for a straightforward “Open an account” button instead.

In this regard, it’s better not to promise users things that we can’t guarantee or that aren’t entirely up to us. For example, in a flow that includes an OTP password, it’s better to opt for the “Send a code” button rather than “Get a code” since we can’t guarantee there won’t be any network outages or other issues preventing the user from receiving an SMS or a push notification.

Finally, avoid using generic “Yes” or “No” buttons as they do not clearly reflect what happens next. Users might misread the text above or fail to notice a negation, leading to unexpected outcomes. For example, when asking for a confirmation, such as “Are you sure you want to quit?” you might want to go with button labels like “Quit” and “Stay” rather than just “Yes” and “No.”

Tip: If you have difficulty coming up with a button label, this may be a sign that the screen is poorly organized or the flow lacks logic and coherence. For example, a user has to deal with too many different entities and types of tasks on one screen, so the action can’t be summarized with just one verb. Or perhaps a subsequent flow has a lot of variations, making it hard to describe the action a user should take. In such cases, you might want to make changes to the screen (say, break it down into several screens) or the flow (say, add a qualifying question or attribute earlier so that the flow would be less branching).
Make It Clear To The User Why They Need To Perform The Action
Why it’s important:
  • To create transparency and build trust;
  • To boost conversion rates.

An ideal interface is self-explanatory and needs no microcopy. However, sometimes, we need to convince users to do something for us, especially when it involves providing personal information or interacting with third-party products.

You can use the following formula: “To [get this], do [this] + UI element to make it happen.” For example, “To get your results, provide your email,” followed by an input field.

It’s better to provide the reasoning (“to get your results”) first and then the instructions (“provide your email” ): this way, the guidance is more likely to stick in the user’s memory, smoothly leading to the action. If you reverse the order — giving the instructions first and then the reasoning — the user might forget what they need to do and will have to reread the beginning of the sentence, leading to a less smooth and slightly hectic experience.

Ensure The UI Element Copy Doesn’t Explain How To Interact With This Very Element
Why it’s important:
  • If you need to explain how to interact with a UI element, it may be a sign that the interface is not intuitive;
  • Risk omitting or not including more important, useful text.

Every now and then, I come across meaningless placeholders or excessive toggle copy that explains how to interact with the field or toggle. The most frequent example is the “Search” placeholder for a search field. Occasionally, I see button labels like “Press to continue.”

Mobile and web interfaces have been around for quite a while, and users understand how to interact with buttons, toggles, and fields. Therefore, explanations such as “click,” “tap,” “enter,” and so on seem excessive in most cases. Perhaps it’s only with a group of checkboxes that you might add something like “Select up to 5.”

You might want to add something more useful. For example, instead of a generic “Search” placeholder for a search field, use specific instances a user might type in. If you’re a fashion marketplace, try placeholders like “oversized hoodies,” “women’s shorts,” and so on. Keep in mind the specifics of your website or app: ensure the placeholder is neither too broad nor too specific, and if a user types something like you’ve provided, their search will be successful.

Stick To The Rule “1 Microcopy Item = 1 Idea”
Why it’s important:
  • Not to create extra cognitive load, confusion, or friction;
  • To ensure a smooth and simple experience.

Users have short attention spans, scan text instead of reading it thoroughly, and can’t process multiple ideas simultaneously. That’s why it’s crucial to break information down into easily digestible chunks instead of, for example, trying to squeeze all the restrictions into one tooltip.

The golden rule is to provide users only with the information they need at this particular stage to take a specific action or make a decision.

You’ll need to collaborate closely with your designer to ensure the information is distributed over the screen evenly and you don’t overload one design element with a lot of text.

Be Careful With Titles Like “Done,” “Almost There,” “Attention,” And So On
Why it’s important:
  • Not to annoy a user;
  • To be more straightforward and economical with users’ time;
  • Not to overuse their attention;
  • Not to provoke anxiety.

Titles, written in bold and larger font sizes, grab users’ attention. Sometimes, titles are the only text users actually read. Titles stick better in their memory, so they must be understandable as a standalone text.

Titles like “One more thing” or “Almost there” might work well if they align with a product’s tone of voice and the flows where they appear are cohesive and can hardly be interrupted. But keep in mind that users might get distracted.

Use this quick check: set your design aside for about 20 minutes, do something else, and then open only the screen for which you’re writing a title. Is what happens on this screen still understandable from the title? Do you easily recall what has or hasn’t happened, what you were doing, and what should be done next?

Don’t Fall Back On Abstract Examples
Why it’s important:
  • To make the interface more precise and useful;
  • To ease the navigation through the product for a user;
  • To reduce cognitive load.

Some products (e.g., any B2B or financial ones) involve many rules and restrictions that must be explained to the user. To make this more understandable, use real-life examples (with specific numbers, dates, and so on) rather than distilling abstract information into a hint, tooltip, or bottom sheet.

It’s better to provide explanations using real-life examples that users can relate to. Check with engineers if it’s possible to get specific data for each user and add variables and conditions to show every user the most relevant microcopy. For example, instead of saying, “Your deposit limit is $1,000 per calendar month,” you could say, “Until Jan 31, you can deposit $400 more.” This relieves the user of unnecessary work, such as figuring out the start date of the calendar month in their case and calculating the remaining amount.

Try To Avoid Negatives
Why it’s important:
  • Not to increase cognitive load;
  • To prevent friction.

As a rule of thumb, it’s recommended to avoid double negatives, such as “Do not unfollow.” However, I’d go further and advise avoiding single negatives as well. The issue is that to decipher such a message, a user has to perform an excessive logical operation: first eliminating the negation, then trying to understand the gist.

For example, when listing requirements for a username, saying “Don’t use special characters, spaces, or symbols” forces a user to speculate (“If this is not allowed, then the opposite is allowed, which must be…”). It can take additional time to figure out what falls under “special characters.” To simplify the task for the user, opt for something like “Use only numbers and letters.”

Moreover, a user can easily overlook the “not” part and misread the message.

Another aspect worth noting is that negation often seems like a restriction or prohibition, which nobody likes. In some cases, especially in finance, all those don’ts might be perceived with suspicion rather than as precaution.

Express Action With Verbs, Not Nouns
Why it’s important:
  • To avoid wordiness;
  • To make text easily digestible.

When describing an action, use a verb, not a noun. Nouns that convey the meaning of verbs make texts harder to read and give off a legalistic vibe.

Here are some sure signs you need to paraphrase your text for brevity and simplicity:

  • Forms of “be” as the main verbs;
  • Noun phrases with “make” (e.g., “make a payment/purchase/deposit”);
  • Nouns ending in -tion, -sion, -ment, -ance, -ency (e.g., cancellation);
  • Phrases with “of” (e.g., provision of services);
  • Phrases with “process” (e.g., withdrawal process).
Make Sure You Use Only One Term For Each Entity
Why it’s important: Not to create extra cognitive load, confusion, and anxiety.

Ensure you use the same term for the same object or action throughout the entire app. For example, instead of using “account” and “profile” interchangeably, choose one and stick to it to avoid confusing your users.

The more complicated and/or regulated your product is, the more vital it is to choose precise wording and ensure it aligns with legal terms, the wording users see in the help center, and communication with support agents.

Less “Oopsies” In Error Messages
Why it’s important:
  • Not to annoy a user;
  • To save space for more important information.

At first glance, “Oops” may seem sweet and informal (yet with an apologetic touch) and might be expected to decrease tension. However, in the case of repetitive or serious errors, the effect will be quite the opposite.

Use “Oops” and similar words only if you’re sure it suits your brand’s tone of voice and you can finesse it.

As a rule of thumb, good error messages explain what has happened or is happening, why (if we know the reason), and what the user should do. Additionally, include any sensitive information related to the process or flow where the error appears. For example, if an error occurs during the payment process, provide users with information concerning their money.

No Excessive Politeness
Why it’s important: Not to waste precious space on less critical information.

I’m not suggesting we remove every single “please” from the microcopy. However, when it comes to interfaces, our priority is to convey meaning clearly and concisely and explain to users what to do next and why. Often, if you start your microcopy with “please,” you won’t have enough space to convey the essence of your message. Users will appreciate clear guidelines to perform the desired action more than a polite message they struggle to follow.

Remove Tech Jargon
Why it’s important:
  • To make the interface understandable for a broad audience;
  • To avoid confusion and ensure a frictionless experience.

As tech specialists, we’re often subject to the curse of knowledge, and despite our efforts to prioritize users, tech jargon can sneak into our interface copy. Especially if our product targets a wider audience, users may not be tech-savvy enough to understand terms like “icon.”

To ensure your interface doesn’t overwhelm users with professional jargon, a quick and effective method is to show the interface to individuals outside your product group. If that’s not feasible, here’s how to identify jargon: it’s the terminology you use in daily meetings among yourselves or in Jira task titles (e.g., authorization, authentication, and so on), or abbreviations (e.g., OTP code, KYC process, AML rules, and so on).

Ensure That Empty State Messages Don’t Leave Users Frustrated
Why it’s important:
  • For onboarding and navigation;
  • To increase discoverability of particular features;
  • To promote or boost the use of the product;
  • To reduce cognitive load and anxiety about the next steps.

Quite often, a good empty state message is a self-destructing one, i.e. one that helps a user to get rid of this emptiness. An empty state message shouldn’t just state “there’s nothing here” — that’s obvious and therefore unnecessary. Instead, it should provide users with a way out, smoothly guiding them into using the product or a specific feature. A well-crafted empty message can even boost conversions.

Of course, there are exceptions, for example, in a reactive interface like a CRM system for a restaurant displaying the status of orders to workers. If there are no orders in progress and, therefore, no corresponding empty state message, you can’t nudge or motivate restaurant workers to create new orders themselves.

Place All Important Information At The Beginning
Why it’s important:
  • To keep the user focused;
  • Not to overload a user with info;
  • Avoid information loss due to fading or cropping.

As mentioned earlier, users have short attention spans and often don’t want to focus on the texts they read, especially microcopy. Therefore, ensure you place all necessary information at the beginning of your text. Omit lead-ins, introductory words, and so on. Save less vital details for later in the text.

Ensure Title And Buttons Are Understandable Without Body Text
Why it’s important:
  • For clarity;
  • To overcome the serial position effect;
  • To make sure the interface, the flow, and the next steps are understandable for a user even if they scan the text instead of reading.

There’s a phenomenon called the serial position effect: people tend to remember information better if it’s at the beginning or end of a text or sentence, often overlooking the middle part. When it comes to UX/UI design, this effect is reinforced by the visual hierarchy, which includes the bigger font size of the title and the accentuated buttons. What’s more, the body text is often longer, which puts it at risk of being missed. Since users tend to scan rather than read, ensure your title and buttons make sense even without the body text.

Wrapping up

Trying to find the balance between providing a user with all the necessary explanations, warnings, and reasonings on one hand and keeping the UI intuitive and frictionless on the other hand is a tricky task.

You can facilitate the process of creating microcopy with the help of ChatGPT and AI-based Figma plugins such as Writer or Grammarly. But beware of the limitations these tools have as of now.

For instance, creating a prompt that includes all the necessary details and contexts can take longer than actually writing a title or a label on your own. Grammarly is a nice tool to check the text for typos and mistakes, but when it comes to microcopy, its suggestions might be a bit inaccurate or confusing: you might want to, say, omit articles for brevity or use elliptical sentences, and Grammarly will identify it as a mistake.

You’ll still need a human eye to evaluate the microcopy &mdahs; and I hope this checklist will come in handy.

Microcopy Checklist

General

✅ Microcopy is role-playable (titles, body text, tooltips, etc., are your “phrases”; button labels, input fields, toggles, menu items, etc. are the user’s “phrases”).

Information presentation & structure

✅ The user has the exact amount of information they need right now to perform an action — not less, not more.
✅ Important information is placed at the beginning of the text.
✅ It’s clear to the user why they need to perform the action.
✅ Everything related to sensitive topics is always visible and static and doesn’t require actions from a user (e.g., not hidden in tooltips).
✅ You provide a user with specific information rather than generic examples.
✅ 1 microcopy item = 1 idea.
✅ 1 entity = 1 term.
✅ Empty state messages provide users with guidelines on what to do (when possible and appropriate).

Style

✅ No tech jargon.
✅ No excessive politeness, esp. at the expense of meaning.
✅ Avoid or reduce the use of “not,” “un-,” and other negatives.
✅ Actions are expressed with verbs, not nouns.

Syntax

✅ UI element copy doesn’t explain how to interact with this very element.
✅ Button label accurately reflects what happens next.
✅ Fewer titles like “done,” “almost there,” and “attention.”
✅ “Oopsies” in error messages are not frequent and align well with the brand’s tone of voice.
✅ Title and buttons are understandable without body text.

With Rapid Tech Advancement, Beware the Pitfalls of Centralization

Featured Imgs 23

Technology has become a dominant force in how we interact and operate. Now more than ever, we need to be aware of the dangers of centralization including the risks of overdependency.

decentralize.jpg

What do Facebook and North Korea have in common? They're both heavily centralized systems. The dangers of over-centralization were highlighted just a few years ago when a single server failure at a Meta data center in California caused a global outage for Facebook, Instagram, WhatsApp, and other services. With corporate AI on the rise and ChatGPT poised to become an integral part of your iPhone, it's time to take a closer look at centralized systems and their inherent vulnerabilities.

So, buckle up for an excursion into the domain of system theory, where we will explore the fundamental differences between centralized and decentralized organization and uncover what makes centralized systems so vulnerable. Armed with this knowledge, we'll ponder whether concentrating AI development in the hands of a few corporate giants is a smart move or a recipe for waking up in a Philip K. Dick novel.

The System Theory of Centralization vs. Decentralization

System science aims to understand the function of different components within complex systems to enhance overall efficiency and reliability. My first encounter with this field was when blockchain technology emerged. Heres an excerpt from an article I wrote at that time, which should clarify the concept of centralization versus decentralization and why blockchain was a revolutionary concept for system scientists (although the latter is not the point of this article)

Try asking Google whether the earth is flat. The answer is clearly a simple no, but the search results will include plenty of dissenting opinions. This is because the Internet is decentralized in both its organization and logic. The fact that it is not subject to a central authority has many advantages, but also means that there is no one to vouch for any of the information it offers.

Most states are the polar opposite of this, they have a centralized logic and organization. They are subject to the control of an institution (i.e. the government) that vouches for content and prescribes procedures (e.g. through laws).

Then there are systems with centralized organization and decentralized logic. They are managed institutionally but allow for individual use. A Word file is a good example, as it can be processed on any computer outfitted with the same software. The workflows are predefined by the program, while the contents can be individually edited by each user.

This is the system theory that underlies our experience of everyday life. A fourth option a system that is logically centralized and organizationally decentralized, hence independent and yet reliable seemed improbable. Then along came blockchain.

Source: Goethe Institute

Many corporations today incorporate processes that are logically decentralized (e.g., independent decision-making within departments) yet they are organizationally centralized, making their components heavily interdependent. Such centralized corporate structures have advantages, including clear command chains and streamlined processes. However, their vulnerability and over-dependence by users pose significant risks.

The Dangers of Centralization

At the heart of the debate between centralization and decentralization lies the question of efficient resource management, with centralized systems often claiming greater efficiency. For instance, its more straightforward for everyone to line up at the school cafeteria and receive their lunch rather than everyone preparing their own meal individually. However, the academic debate on whether centralized or decentralized systems are more efficient remains unresolved and varies depending on the type of system in question. Its important to clarify that my focus on centralization here concerns globally available services controlled by a handful of large corporate entities. So, we're not discussing the logistics within a single school cafeteria, but rather a hypothetical global network of cafeterias relying on a singular distribution chain, where one point of failure could leave all kids without lunch.

This leads us to a fundamental issue that renders centralized systems highly vulnerable: if the central node is compromised or fails, the entire system collapsesa single point of failure can bring down the whole network. Consider the example of GPS. Whether you use Google Maps, Waze, or another navigation app, they all depend on GPS. If GPS were to fail due to a cyberattack or another unforeseen issue, youd better know how to read a map.

In addition to risks associated with single points of failure and overdependency, centralized systems have other significant drawbacks. They can stifle innovation, reduce operational flexibility, create bureaucratic inefficiencies, and limit responsiveness to individual needs. Furthermore, the concentration of power within centralized systems can make them not just vulnerable but also potentially dangerous. Economist Leopold Kohr, who fled the Nazi regime, devoted his life to arguing that overly large systems are the root of many societal evils. In his book The Breakdown of Nations (1957), he states:

there seems only one cause behind all forms of social misery: bigness. Oversimplified as this may seem, we shall find the idea more easily acceptable if we consider that bigness, or oversize, is really much more than just a social problem. It appears to be the one and only problem permeating all creation. Wherever something is wrong, something is too big.

He then builds an extensive argument that there are natural boundaries to growtha sentiment that was further elaborated on by The Limits of Growth some 15 years later, and is shared by many economists today. The solution, Kohr argues, is healthy decentralization. In respect to governance systems, that means a division into small states, resulting in a system where less power is divided into more hands, which could theoretically prevent atrocities like nuclear warfare and genocides that historically have been the hallmarks of large nations and empires.

Such dangers are still relevant today, and due to technological advances and the rise of global communication networks, the notion of threatening bigness has entered an entirely new domain. Today, a handful of tech giants control most of our communication, our personal data, what we see, what we hear, and where we go. Besides the Orwellian vibes, this concentration of power bears serious dependency risks. And with AI development being controlled and driven by the exact same data-oligarchs, wed better be careful all this rapid technological growth does not eventually backfire.

Just imagine if all Google services went down for a day. The implications would extend far beyond the inconvenience of using another search engine. Your browser data and passwords, your authentication apps, your calendars, everything you have stored in the cloudif all that disappeared, chaos would surely ensue in one form or another.

Decentralize!

Yes, humanity would most likely recover from such disruptions, but it is crucial to recognize that we are currently in the early stages of a great technological transformation, comparable to the Industrial Revolution. AI is rapidly evolving, improving, and increasingly blurring the boundaries between whats real and whats not. The biggest stakeholders are the usual suspects: Google/Alphabet, Meta, Apple, and Microsoftwith OpenAI morphing into the unexpected lovechild of the latter two. As technology advances and markets become monopolized, further centralization and concentration of power are almost inevitable.

So, what can we do about this? Admittedly, from an individual standpoint, there are no simple solutions. While smaller alternatives to all the major services exist, convenience often outweighs the effort required to diversifybecause it is simply easier to use one account for everything, get all services from one provider, and store all files in the same cloud. However, spreading awareness about the dangers of centralization is essential. It enables individuals to balance convenience against the risks of over-dependency and make informed decisions. Ultimately, it is up to each of us to ensure we do not become overly reliant on any single platform, tool, or corporationand to prevent systems from becoming too big.

How To Make A Strong Case For Accessibility

Fotolia Subscription Monthly 4685447 Xl Stock

Getting support for accessibility efforts isn’t easy. There are many accessibility myths, wrong assumptions, and expectations that make accessibility look like a complex, expensive, and time-consuming project. Let’s fix that!

Below are some practical techniques that have been working well for me to convince stakeholders to support and promote accessibility in small and large companies.

This article is part of our ongoing series on UX. You might want to take a look at Smart Interface Design Patterns 🍣 and the upcoming live UX training as well. Use code BIRDIE to save 15% off.

Launching Accessibility Efforts

A common way to address accessibility is to speak to stakeholders through the lens of corporate responsibility and ethical and legal implications. Personally, I’ve never been very successful with this strategy. People typically dismiss concerns that they can’t relate to, and as designers, we can’t build empathy with facts, charts, or legal concerns.

The problem is that people often don’t know how accessibility applies to them. There is a common assumption that accessibility is dull and boring and leads to “unexciting” and unattractive products. Unsurprisingly, businesses often neglect it as an irrelevant edge case.

So, I use another strategy. I start conversations about accessibility by visualizing it. I explain the different types of accessibility needs, ranging from permanent to temporary to situational — and I try to explain what exactly it actually means to our products. Mapping a more generic understanding of accessibility to the specifics of a product helps everyone explore accessibility from a point that they can relate to.

And then I launch a small effort — just a few usability sessions, to get a better understanding of where our customers struggle and where they might be blocked. If I can’t get access to customers, I try to proxy test via sales, customer success, or support. Nothing is more impactful than seeing real customers struggling in their real-life scenario with real products that a company is building.

From there, I move forward. I explain inclusive design, accessibility, neurodiversity, EAA, WCAG, ARIA. I bring people with disabilities into testing as we need a proper representation of our customer base. I ask for small commitments first, then ask for more. I reiterate over and over and over again that accessibility doesn’t have to be expensive or tedious if done early, but it can be very expensive when retrofitted or done late.

Throughout that entire journey, I try to anticipate objections about costs, timing, competition, slowdowns, dullness — and keep explaining how accessibility can reduce costs, increase revenue, grow user base, minimize risks, and improve our standing in new markets. For that, I use a few templates that I always keep nearby just in case an argument or doubts arise.

Useful Templates To Make A Strong Case For Accessibility

1. “But Accessibility Is An Edge Case!”

❌ “But accessibility is an edge case. Given the state of finances right now, unfortunately, we really can’t invest in it right now.”

🙅🏽♀️ “I respectfully disagree. 1 in 6 people around the world experience disabilities. In fact, our competitors [X, Y, Z] have launched accessibility efforts ([references]), and we seem to be lagging behind. Plus, it doesn’t have to be expensive. But it will be very expensive once we retrofit much later.”

2. “But There Is No Business Value In Accessibility!”

❌ “We know that accessibility is important, but at the moment, we need to focus on efforts that will directly benefit business.”

🙅🏼♂️ “I understand what you are saying, but actually, accessibility directly benefits business. Globally, the extended market is estimated at 2.3 billion people, who control an incremental $6.9 trillion in annual disposable income. Prioritizing accessibility very much aligns with your goal to increase leads, customer engagement, mitigate risk, and reduce costs.” (via Yichan Wang)

3. “But We Don’t Have Disabled Users!”

❌ “Why should we prioritize accessibility? Looking at our data, we don’t really have any disabled users at all. Seems like a waste of time and resources.”

🙅♀️ “Well, if a product is inaccessible, users with disabilities can’t and won’t be using it. But if we do make our product more accessible, we open the door for prospect users for years to come. Even small improvements can have a high impact. It doesn’t have to be expensive nor time-consuming.”

4. “Screen Readers Won’t Work With Our Complex System!”

❌ “Our application is very complex and used by expert users. Would it even work at all with screen readers?”

🙅🏻♀️ “It’s not about designing only for screen readers. Accessibility can be permanent, but it can also be temporary and situational — e.g., when you hold a baby in your arms or if you had an accident. Actually, it’s universally useful and beneficial for everyone.”

5. “We Can’t Win Market With Accessibility Features!”

❌ “To increase our market share, we need features that benefit everyone and improve our standing against competition. We can’t win the market with accessibility.”

🙅🏾♂️ “Modern products succeed not by designing more features, but by designing better features that improve customer’s efficiency, success rate, and satisfaction. And accessibility is one of these features. For example, voice control and auto-complete were developed for accessibility but are now widely used by everyone. In fact, the entire customer base benefits from accessibility features.”

6. “Our Customers Can’t Relate To Accessibility Needs”

❌ “Our research clearly shows that our customers are young and healthy, and they don't have accessibility needs. We have other priorities, and accessibility isn’t one of them.”

🙅♀️ “I respectfully disagree. People of all ages can have accessibility needs. In fact, accessibility features show your commitment to inclusivity, reaching out to every potential customer of any age, regardless of their abilities.

This not only resonates with a diverse audience but also positions your brand as socially responsible and empathetic. As you know, our young user base increasingly values corporate responsibility, and this can be a significant differentiator for us, helping to build a loyal customer base for years to come.” (via Yichan Wang)

7. “Let’s Add Accessibility Later”

❌ “At the moment, we need to focus on the core features of our product. We can always add accessibility later once the product is more stable.”

🙅🏼 “I understand concerns about timing and costs. However, it’s important to note that integrating accessibility from the start is far more cost-effective than retrofitting it later. If accessibility is considered after development is complete, we will face significant additional expenses for auditing accessibility, followed by potentially extensive work involving a redesign and redevelopment.

This process can be significantly more expensive than embedding accessibility from the beginning. Furthermore, delaying accessibility can expose your business to legal risks. With the increasing number of lawsuits for non-compliance with accessibility standards, the cost of legal repercussions could far exceed the expense of implementing accessibility now. The financially prudent move is to work on accessibility now.”

You can find more useful ready-to-use templates in Yichan Wang’s Designer’s Accessibility Advocacy Toolkit — a fantastic resource to keep nearby.

Building Accessibility Practices From Scratch

As mentioned above, nothing is more impactful than visualizing accessibility. However, it requires building accessibility research and accessibility practices from scratch, and it might feel like an impossible task, especially in large corporations. In “How We’ve Built Accessibility Research at Booking.com”, Maya Alvarado presents a fantastic case study on how to build accessibility practices and inclusive design into UX research from scratch.

Maya rightfully points out that automated accessibility testing alone isn’t reliable. Compliance means that a user can use your product, but it doesn’t mean that it’s a great user experience. With manual testing, we make sure that customers actually meet their goals and do so effectively.

Start by gathering colleagues and stakeholders interested in accessibility. Document what research was done already and where the gaps are. And then whenever possible, include 5–12 users with disabilities in accessibility testing.

Then, run a small accessibility initiative around key flows. Tap into critical touch points and research them. As you are making progress, extend to components, patterns, flows, and service design. And eventually, incorporate inclusive sampling into all research projects — at least 15% of usability testers should have a disability.

Companies often struggle to recruit testers with disabilities. One way to find participants is to reach out to local chapters, local training centers, non-profits, and public communities of users with disabilities in your country. Ask the admin’s permission to post your research announcement, and it won’t be rejected. If you test on site, add extra $25–$50 depending on disability transportation.

I absolutely love the idea of extending Microsoft's Inclusive Design Toolkit to meet specific user needs of a product. It adds a different dimension to disability considerations which might be less abstract and much easier to relate for the entire organization.

As Maya noted, inclusive design is about building a door that can be opened by anyone and lets everyone in. Accessibility isn’t a checklist — it’s a practice that goes beyond compliance. A practice that involves actual people with actual disabilities throughout all UX research activities.

Wrapping Up

To many people, accessibility is a big mystery box. They might have never seen a customer with disabilities using their product, and they don’t really understand what it involves and requires. But we can make accessibility relatable, approachable, and visible by bringing accessibility testing to our companies — even if it’s just a handful of tests with people with disabilities.

No manager really wants to deliberately ignore the needs of their paying customers — they just need to understand these needs first. Ask for small commitments, and get the ball rolling from there.

Set up an accessibility roadmap with actions, timelines, roles and goals. Frankly, this strategy has been working for me much better than arguing about legal and moral obligations, which typically makes stakeholders defensive and reluctant to commit.

Fingers crossed! And a huge thank-you to everyone working on and improving accessibility in your day-to-day work, often without recognition and often fueled by your own enthusiasm and passion — thank you for your incredible work in pushing accessibility forward! 👏🏼👏🏽👏🏾

Useful Resources

Making A Case For Accessibility

Accessibility Testing

Meet Smart Interface Design Patterns

If you are interested in UX and design patterns, take a look at Smart Interface Design Patterns, our 10h-video course with 100s of practical examples from real-life projects — with a live UX training later this year. Everything from mega-dropdowns to complex enterprise tables — with 5 new segments added every year. Jump to a free preview. Use code BIRDIE to save 15% off.

Meet Smart Interface Design Patterns, our video course on interface design & UX.

100 design patterns & real-life examples.
10h-video course + live UX training. Free preview.

Elementor for WordPress: Build a Website with Ease (No Coding Required)

Featured Imgs 23

What are the primary qualities of Elementor that make it a popular choice for making WordPress sites without knowing how to code? You don’t have to know how to code to make a site with the help of Elementor for WordPress. You can introduce this module on your WordPress site. With Elementor, making a site is basically as simple as relocating components onto the homepage. This suggests that you can move things on your page, such as buttons, text boxes, and photographs, by tapping on them. Plus, Elementor comes with a tonne of pre-made templates. These templates offer pre-made designs that you may alter to suit your needs, giving you a head start. Colours, typefaces, and layouts can all be easily changed.

Even inexperienced clients can create proficient-looking sites because of its convenience. Whether you need to make an individual blog, a business site, or a web-based store, Elementor makes it simple and pleasant. Anyone, regardless of technical ability, may utilize Elementor to design a perfect site.

Hostinger and Elementor: The Perfect Website Duo” for your website requirements. Hostinger provides quick and dependable hosting, whereas Elementor delivers user-friendly design tools. Together, they enable you to develop great websites quickly and efficiently. Start your online journey with Hostinger and Elementor today.

Designing with Elementor: Drag-and-Drop Basics

With Elementor, creating a website can be simple and enjoyable. One well-liked plugin for WordPress is Elementor. With a drag-and-drop interface, you can easily design stunning webpages. It follows that no prior coding knowledge is required. Installing Elementor on your WordPress website is the first step. After installation, you can immediately begin creating. To edit a page, just select it and launch Elementor on it. The user interface is easy to use. A panel with different elements, including text fields, photos, and buttons, is located on the left side. Any of these components can be dragged to the main window of your website. Simply click and drag an element to the desired location on the page to utilize it.

You may then personalize it by clicking on it. A menu will display, with options for changing the text, colour, size, and other settings. You can view all of your changes in real time, making design very intuitive. Elementor likewise provides pre-designed layouts. In the event that you’re new to website creation, these layouts are an amazing place to begin. You can choose a layout and then customize it to address your issues. Elementor permits you to make proficient-looking sites rapidly and without any problem. It’s an incredible instrument for both new users and specialists. Anybody can make a site utilizing its simplified elements without having any technical knowledge. This makes Elementor an excellent solution for small business owners, bloggers, and anyone looking to design their own website.

Advanced Design – Tips and Tricks in Elementor

Elementor’s Advanced Design Tips and Tricks can significantly improve the look and feel of your website. With the help of the well-known WordPress plugin Elementor, you can visually design websites without knowing any coding.

  1. Learning how to apply custom CSS is one useful tip. Even though Elementor has a tonne of styling possibilities, there are situations when you might wish to create a unique look that isn’t possible with the default settings. Knowing the fundamentals of CSS will enable you to accurately alter elements to your preference.
  2. Investigating sophisticated layout strategies is an additional helpful tip. You may construct intricate and responsive layouts with Elementor’s capabilities, which include adjustable column widths, configurable spacing, and widget positioning settings. Acquiring information on these components will empower you to deliver unique and more imaginative designs.

Best Practices for “Building” search engine optimization (SEO-Friendly) Sites with “Elementor”

Using Elementor to build SEO-friendly websites means adhering to a number of best practices that guarantee your website will appear highly in search engine results. To begin with, select a design that is both versatile and responsive. This suggests that your site ought to work and look perfect on a wide range of devices, including tablets and cell phones. Consider website speed next. Pages that load quickly are essential for SEO and the user experience. To speed up loading times, use a reputable hosting company, optimize your pictures, and employ cache plugins. Make keyword research a top priority while developing content. To locate appropriate terms with high search traffic, use tools such as Google Keyword Planner. Naturally include these keywords in your content’s titles, subheadings, and body.

Organize your information using clear headers and subheadings. This not only helps consumers navigate your site, but it also allows search engines to better grasp the structure of your material. Optimize your meta tags, including the title and meta description. These tags display in search engine results and should appropriately represent the content on each page, including important keywords. Make sure your website has a clear, crawlable structure. Use Elementor’s design features to construct a logical hierarchy complete with menus, breadcrumbs, and internal links. Regularly update your material to keep it current and relevant. Search engines prefer websites that consistently publish fresh information, so consider including blog entries, news updates, and other important content.

Finally, use tools like Google Analytics to track and evaluate the performance of your website. To track down regions that need work, watch out for investigations like keyword ranks, bounce rates, and traffic sources. You might utilize Elementor to make a site that looks fabulous and performs well in web search rankings, which will expand the amount of organic traffic to your site by sticking to these prescribed procedures. 

Elevate Your Online Presence – Discovering the “Benefits” of Robust WordPress (Server Hosting)

Powerful WordPress server hosting” is required to run a successful website. It ensures that your site loads quickly and manages a large number of visitors efficiently. When you choose a strong hosting provider, such as one created particularly for WordPress, you will benefit from faster loading times, more consistent performance, and improved security measures. These hosting services frequently incorporate WordPress-specific features, such as one-click installations, automated updates, and specialized support from WordPress professionals. They employ high-performance servers that are optimized for WordPress, so your site can manage huge traffic without slowing down. Scalability is another benefit of high-performance WordPress hosting. As your website expands, you can simply change your hosting package to accommodate additional users and data.

Your website will always be quick and responsive because of its scalability, even as its popularity grows. Strong WordPress hosting places a high premium on security. In order to protect your website and its contents, providers frequently incorporate cutting-edge security features like virus scanning and automatic backups. You may relax knowing that your website is protected from online attacks due to this. Customer service is important to consider when selecting a hosting company. You usually have access to expert support staff when using powerful WordPress hosting, who can assist you with troubleshooting and performance optimization of your website. Therefore, for anyone who is serious about the functionality, speed, security, and scalability of their website, strong WordPress server hosting is a great option.

It’s designed to make administering a WordPress site simpler and more efficient, allowing you to concentrate on creating amazing content and expanding your online presence.

Conclusion

Elementor provides a complete toolkit for design, functionality, and SEO, enabling WordPress users to easily develop websites of a professional calibre. Elementor is the preferred option for web construction without coding because of its extensive features and user-friendly interface, regardless of the type of website you’re creating a personal blog, an E-commerce site, or a business page. Accept Elementor to open up countless opportunities and effortlessly improve your internet visibility.

Beyond just design, Elementor has strong features that increase usefulness without getting complicated, like widgets and integrations with well-known plugins. Because of its adaptability, users may easily add sophisticated components like galleries, forms, and sliders, improving both utility and appearance. Another noteworthy aspect of Elementor is its dedication to efficiency, with clean code and quick loading times both essential for good SEO. Elementor helps websites rank higher in search engine results by focusing on the user experience and speed, which efficiently drives organic traffic.

FAQs

Can I export/import Elementor designs?

Yes, Elementor allows you to export and import templates, sections, and even full websites, making it simple to reuse designs or migrate sites.

Does Elementor provide support and updates?

Yes, Elementor releases regular updates with bug fixes and new features, and they offer help through their documentation and community forums.

Is my website slowed down by Elementor?

Although Elementor is performance-optimized by design, utilizing an excessive number of large widgets or animations might slow down a website.

Can I use Elementor to make responsive websites?

Yes, Elementor makes it simple to create responsive websites that work well across all platforms.

With Elementor, what kinds of websites can I create?

With Elementor, you can make almost any sort of site, including blogs, internet business retail stores, portfolios, organization sites, and more.

Is there a template option in Elementor?

Yes, you may import and modify a library of pre-made templates for pages, sections, and entire websites that come with Elementor.

The post Elementor for WordPress: Build a Website with Ease (No Coding Required) appeared first on CSS Author.