In this digital age, the demand for fresh, relevant content is ever-growing. Businesses, bloggers, and digital marketers are constantly seeking innovative tools to streamline content creation.

Enter the Blog Post Generator, an AI-powered tool that uses the latest advancements in AI to automate and personalize blog writing.

This article explores how this application, powered by Streamlit and Mistral AI, transforms ideas into structured, engaging blog posts.

Here is the application in action:

0:00
/0:38

Blog Post Generator

You can also see a live version of this application with payment integration at: https://blog-post-generator.developer-service.io/

You can also follow along this article in a video format:

YouTube Video


What is Streamlit?

Streamlit is an innovative open-source Python library that simplifies the process of creating and deploying web applications, particularly those focused on data science and machine learning.

It enables developers to quickly convert Python scripts into interactive, visually appealing web apps without requiring extensive knowledge of web development technologies such as HTML, CSS, or JavaScript.

Core Features:

  • Rapid Development: One of Streamlit’s standout features is its "app as a script" philosophy. Developers can write simple Python scripts and, with minimal adjustments, turn them into web apps. This is particularly useful for data scientists who want to showcase their findings or test hypotheses without spending time on web development.
  • Interactivity Made Simple: Streamlit includes widgets such as sliders, buttons, and checkboxes that can be added with single lines of code, allowing for interactive features that can control data input or adjust what is displayed on the screen.
  • Automatic Updates: The library is designed to automatically rerun the app script from top to bottom whenever the user interacts with a widget. This means that the state of the application is always up-to-date with the latest interactions, simplifying the state management usually required in traditional web applications.

Benefits:

  • Ease of Use: Streamlit’s straightforward syntax and abstraction of complex front-end technologies make it accessible to users who might be experts in data analysis but novices in web development.
  • Community and Support: Since its launch, Streamlit has developed a vibrant community of users ranging from professional data scientists to hobbyists, all contributing to a growing library of resources, shared apps, and support forums.
  • Integration Capabilities: It seamlessly integrates with other Python libraries commonly used in data science, such as NumPy, Pandas, and Matplotlib, and can connect to databases and APIs to fetch real-time data for visualizations.

Streamlit transforms the way data-driven applications are developed by making the process faster, more efficient, and accessible to a broader audience.


What is MistralAI?

MistralAI is a state-of-the-art AI platform known for its robust capabilities in natural language processing (NLP) and machine learning.

It specializes in providing AI solutions that enable developers to integrate advanced natural language understanding and generation into their applications.

Core Technologies:

  • Advanced Language Models: MistralAI utilizes cutting-edge language models that are trained on diverse and extensive datasets. These models can understand context, generate human-like text, and perform various NLP tasks such as summarization, translation, and sentiment analysis.
  • Custom Model Training: Beyond using pre-trained models, MistralAI offers capabilities for users to train custom models tailored to specific business needs or datasets. This flexibility allows for highly specialized applications of NLP technology.
  • Scalable Infrastructure: The platform is designed to handle high volumes of requests simultaneously, ensuring that AI integrations can scale with the needs of any business, from startups to large enterprises.

Benefits:

  • Enhanced Content Generation: With MistralAI, developers can automate content creation processes, generating everything from simple text responses to entire articles or reports that are coherent and contextually relevant.
  • Seamless Integration: MistralAI provides APIs that are easy to integrate with existing systems, allowing businesses to add sophisticated language processing capabilities without significant restructuring.
  • Cost-Effective NLP Solutions: By offering both pre-trained and customizable models, MistralAI provides cost-effective solutions that reduce the need for extensive in-house NLP expertise and infrastructure.

MistralAI is democratizing access to advanced NLP technologies, allowing businesses of all sizes to leverage the power of AI in their operations.


Ship your startup in days, not weeks

Building the Application

The Blog Post Generator application is composed of two main scripts that manage its functionality: blog_generator.py and main.py.

First, let's handle the installation of the necessary requirements:

pip install streamlit python-decouple mistralai

To use MistralAI API, you will need an API key. You can get one here.

Then you can place that key in the .env file:

MISTRAL_API_KEY=<YOUR_MISTRAL_API_KEY>
MISTRAL_MODEL=open-mixtral-8x7b

As mentioned the application logic is contained in two files:

  • blog_generator.py: This script is the backbone of content generation, utilizing MistralAI's capabilities to create both structured outlines and detailed sections of blog posts.
  • main.py: This script sets up the user interface with Streamlit, providing a simple and intuitive front end for users. It allows users to choose a blog category, enter a subject, and initiate the generation process. The generated content can be reviewed directly on the web app and downloaded as a Markdown file, offering flexibility in how the content is used.

blog_generator.py

Let's start by creating the file blog_generator.py:

import json
from decouple import config
from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage


# Mistral API
MISTRAL_API_KEY = config("MISTRAL_API_KEY")
MISTRAL_MODEL = config("MISTRAL_MODEL")


def write_section(topic, header, sub_sections, text):
    try:
        SYSTEM_MESSAGE = f"""You are well trained ghost writer for writing articles about {topic}.
                            Your articles are informative, detailed, well organized 
                            and written in a way that is easy to understand by all ages."""
        sub_section_text = ''
        for sub_section in sub_sections:
            sub_section_text += f"{sub_section}\n\n"
        # Mistral chat
        mistral_client = MistralClient(api_key=MISTRAL_API_KEY)
        messages = [
            ChatMessage(role="system", content=SYSTEM_MESSAGE),
            ChatMessage(role="system", content=f"Previous sections:\n{text}"),
            ChatMessage(role="user", content=f"Write section {header} with sub sections:\n {sub_section_text}."
                                             f"Make sure to use proper markdown formatting")
        ]
        chat_response = mistral_client.chat(
            model=MISTRAL_MODEL,
            messages=messages,
        )
        content = chat_response.choices[0].message.content
        return content
    except Exception as e:
        print(e)
        return "", ""


def generate_outline(topic, subject):
    try:
        SYSTEM_MESSAGE = f"""You are well trained ghost writer for writing articles about {topic}.
                            Your articles are informative, detailed, well organized 
                            and written in a way that is easy to understand by all ages."""
        PROMPT = f"Write the article outline for an article about {subject}."
        # Mistral chat
        mistral_client = MistralClient(api_key=MISTRAL_API_KEY)
        messages = [
            ChatMessage(role="system", content=SYSTEM_MESSAGE),
            ChatMessage(role="user", content=f"{PROMPT}"
                                             "Make sure to reply with a JSON object with the following format:"
                                             """{
                                                "title": "Example Title",
                                                "sections": [
                                                    {
                                                        "header": "Header Example",
                                                        "sub-sections": [
                                                            {
                                                                "header": "Example Header"
                                                            }
                                                        ]
                                                    }
                                                ]
                                            }""")
        ]
        chat_response = mistral_client.chat(
            model=MISTRAL_MODEL,
            messages=messages,
        )
        json_response = json.loads(chat_response.choices[0].message.content)
        return json_response
    except Exception as e:
        print(e)
        return {}, ""

Here's a breakdown of the code:

  • The script imports necessary libraries such as json for handling JSON data, decouple for managing configuration variables, and MistralClient and ChatMessage from mistralai for interacting with the Mistral AI's API.
  • The MISTRAL_API_KEY and MISTRAL_MODEL variables are fetched from the environment using the decouple library. These are used to authenticate and specify the model for the Mistral AI's API.
  • write_section(topic, header, sub_sections, text): This function generates a section of an article based on the provided topic, header, sub_sections, and previous text. It communicates with the Mistral AI's API to generate the text for the new section.
  • generate_outline(topic, subject): This function generates an outline for an article based on the provided topic and subject. It communicates with the Mistral AI's API to generate the outline in a specific JSON format.

Both functions use a system message to set the context for the Mistral AI model, and they handle exceptions by printing the error and returning an empty string or dictionary. The Mistral AI's responses are parsed accordingly, either as plain text for sections or as JSON for outlines.

main.py

Now let's build the main.py file that contains the user interface and logic to generate the blog post: